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        let mut index_reads = IndexReads::default();
1571        for item in &items {
1572            let _handle = execute_work_item(
1573                item,
1574                &mut warm_cache,
1575                &mut warm_devices,
1576                &mut warm_layouts,
1577                &mut warm_syms,
1578                false,
1579                Some(&mut persistent),
1580                Some(&mut index_reads),
1581            )
1582            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1583        }
1584        // Flush all warm launches before capture (device idle; result stable).
1585        sync_active_cuda_devices(&warm_cache)?;
1586        index_reads.check()?;
1587
1588        let output = warm_cache.get(&target).cloned().ok_or_else(|| {
1589            Error::Msg(format!(
1590                "capture_decode: target {:?} not realized in warm run",
1591                target,
1592            ))
1593            .bt()
1594        })?;
1595        let output_layout = warm_layouts.get(&target).cloned().ok_or_else(|| {
1596            Error::Msg(format!("capture_decode: target {:?} has no layout", target)).bt()
1597        })?;
1598
1599        // Derive the CUDA device from the target's storage for capture_run.
1600        let device = {
1601            let guard = output.read().map_err(|_| poisoned("output storage"))?;
1602            match &guard.inner {
1603                BackendStorage::Cuda(c) => c.device().clone(),
1604                other => {
1605                    return Err(Error::Msg(format!(
1606                        "capture_decode: target {:?} is BackendStorage::{:?}, not Cuda",
1607                        target,
1608                        other.backend_id(),
1609                    ))
1610                    .bt());
1611                }
1612            }
1613        };
1614
1615        // ---- Pass 2: capture (reuse) — record the launch sequence ----------
1616        let mut reuse = PersistentOutputs::reuse(persistent.into_map());
1617        // Retain EVERY input buffer before `inputs` is consumed: the captured
1618        // graph bakes their device addresses, so they must outlive it even if
1619        // the caller doesn't independently hold them.
1620        let retained_inputs: Vec<Arc<RwLock<Storage>>> = inputs.values().cloned().collect();
1621        let mut cap_cache: StorageCache = inputs;
1622        let mut cap_layouts = seed_layouts;
1623        let mut cap_syms = SymEnv::new();
1624        let mut cap_devices = cuda_registry_of_inputs(&cap_cache);
1625        let mut inner_err: Option<Error> = None;
1626        let items_ref = &items;
1627        let graph_ref = &graph;
1628        let run = device.capture_run(|_stream| {
1629            // Inside the capture scope: NO device alloc, NO host sync. Each
1630            // kernel launches on device.stream() (now capturing) and writes
1631            // into its reused fixed buffer.
1632            for item in items_ref {
1633                match execute_work_item(
1634                    item,
1635                    &mut cap_cache,
1636                    &mut cap_devices,
1637                    &mut cap_layouts,
1638                    &mut cap_syms,
1639                    false,
1640                    Some(&mut reuse),
1641                    // A captured replay cannot sync, so its reads are not checked (GAP-415).
1642                    None,
1643                ) {
1644                    Ok(_handle) => {}
1645                    Err(e) => {
1646                        inner_err = Some(with_node_location(graph_ref, item.node_id, e));
1647                        break;
1648                    }
1649                }
1650            }
1651            Ok(())
1652        })?;
1653        if let Some(e) = inner_err {
1654            return Err(e);
1655        }
1656
1657        Ok(CapturedDecode {
1658            run,
1659            output,
1660            output_layout,
1661            retained_inputs,
1662            persistent: reuse.into_map(),
1663        })
1664    }
1665
1666    fn realize_inner(
1667        graph: Arc<RwLock<Graph>>,
1668        target: NodeId,
1669        inputs: StorageCache,
1670        order_source: OrderSource<'_>,
1671        sym_env: SymEnv,
1672    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1673        Self::realize_inner_with(
1674            graph,
1675            target,
1676            inputs,
1677            order_source,
1678            sym_env,
1679            DeviceRegistry::new(),
1680        )
1681    }
1682
1683    /// [`Self::realize_inner`] with the device handles the caller already holds.
1684    fn realize_inner_with(
1685        graph: Arc<RwLock<Graph>>,
1686        target: NodeId,
1687        inputs: StorageCache,
1688        order_source: OrderSource<'_>,
1689        sym_env: SymEnv,
1690        device_handles: DeviceRegistry,
1691    ) -> Result<(Arc<RwLock<Storage>>, Layout, SymEnv)> {
1692        // Auto-insert safety copies for in-place ops whose target
1693        // has additional readers in this realize set (residual-
1694        // connection cycle break). No-op when no destructive ops
1695        // are present.
1696        {
1697            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.safety_copies");
1698            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
1699            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1700            insert_safety_copies(&mut g, &effective_roots);
1701        }
1702
1703        // Execution plan + initial layouts for the input cache
1704        // entries, computed on the calling thread to keep the
1705        // compiler thread free of graph-locking responsibilities.
1706        // Side-effect roots (Op::Print, Op::Save, etc.) are merged
1707        // into the walk so their effects fire even when not
1708        // reachable from the user's `target`. `execution_plan`
1709        // integrates `derive_ordering`'s view-aware pinning so
1710        // destructive ops run AFTER non-destructive readers of
1711        // their targets.
1712        let (compiler_work, wait_set, mut layout_cache): (
1713            CompilerWork,
1714            WaitSet,
1715            HashMap<NodeId, Layout>,
1716        ) = {
1717            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.plan_order");
1718            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
1719            let effective_roots = extend_with_side_effect_roots(&g, &[target]);
1720            // PR-A3b-1: the OptimizedGraph path lowers via
1721            // `extract_runs`/`lower_run` (computed here, AFTER
1722            // `insert_safety_copies`, so the order covers freshly
1723            // inserted safety-copy nodes). The default path keeps the
1724            // pre-A3b-1 `execution_plan` walk. On a branchless graph the
1725            // two sequences are identical (A3a equivalence gate).
1726            //
1727            // PR-C1: a `Streaming` source is NOT flattened here — it is
1728            // handed to the compiler thread as a `CompilerWork::Streaming`
1729            // spec so the thread resolves each branch lazily at the
1730            // frontier (see `compiler_thread_body`).
1731            //
1732            // Step E A4b open question #4: the SAME pass also derives the
1733            // `WaitSet` from the materialized order ("event only where
1734            // waited" — see `compiler_work_and_wait_set_for`).
1735            let (work, wait_set) =
1736                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
1737            let mut layouts = HashMap::with_capacity(inputs.len());
1738            for &id in inputs.keys() {
1739                layouts.insert(id, g.layout(id));
1740            }
1741            (work, wait_set, layouts)
1742        };
1743
1744        let (tx, rx) = channel::<Result<WorkItem>>();
1745        let graph_for_compiler = Arc::clone(&graph);
1746
1747        // Compiler thread: read graph nodes, resolve kernels,
1748        // push WorkItems. On error, push the error and bail. PR-C1: for a
1749        // `Streaming` work spec the thread also resolves each branch's arm
1750        // at the frontier (the SAME VRAM-only selector the one-shot picker
1751        // uses) before compiling that arm's runs.
1752        let compiler = {
1753            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.spawn_compiler");
1754            thread::spawn(move || {
1755                let _t = crate::compiled::op_profile::PhaseTimer::start(
1756                    "compiler_thread (runs concurrently)",
1757                );
1758                compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
1759            })
1760        };
1761
1762        // Executor on this thread: consume WorkItems, gather
1763        // inputs from the cache, allocate outputs, call kernels,
1764        // populate the cache. After each destructive op
1765        // (Op::Release / Op::Move) evict the destroyed input from
1766        // the cache, unless it's the realize target.
1767        //
1768        // Phase 4.3: at each dispatch-chunk boundary (target_backend
1769        // change), check the live SystemTopology generation against
1770        // the plan's stamped generation. Mismatch surfaces
1771        // `Error::TopologyChanged`; the realize layer
1772        // (`pipelined_bridge`) catches it, rebuilds the plan against
1773        // the fresh topology, and retries.
1774        let plan_generation: Option<u64> = generation_for(&order_source);
1775        let mut current_chunk_backend: Option<BackendId> = None;
1776        let mut cache: StorageCache = inputs;
1777        let mut devices = device_handles;
1778        // Data-dependent dynamic-shapes: symbols BOUND BY PRODUCERS during
1779        // this pass (e.g. `Op::NonZeroIndices`'s runtime count). Distinct
1780        // from the compile-time `sym_env` (input-determined, moved into the
1781        // compiler thread): these become known only as ops execute. Returned
1782        // to the caller so a downstream pass can consume them.
1783        let mut produced_syms = SymEnv::new();
1784        // Step E A4b-1: per-node async-completion handles. Each producing node's
1785        // `execute_compiled` returns a `CompletionHandle` (CUDA → a recorded
1786        // `Event`; CPU/Vulkan → `Ready`) instead of being `wait`ed inline. We
1787        // store them here, wait the SOURCE producer's handle before a
1788        // cross-device copy (A4b-3, below), and drain whatever remains at
1789        // realize-end.
1790        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
1791        // Step E A4b-4: eagerly-submitted-but-not-yet-waited Vulkan batches. The
1792        // OVERLAP enabler — when we LEAVE a Vulkan chunk (or are about to block on
1793        // a CUDA copy) we `submit_pending` the open Vulkan batch so the iGPU runs
1794        // it while the executor records/dispatches the next (CUDA) chunk, instead
1795        // of letting it sit merely-recorded until realize-end (the A4b-2 behavior,
1796        // which never overlapped). Each submitted batch is tracked here and waited
1797        // at the in-flight-lifetime guard (before a Vulkan read / Vulkan-referenced
1798        // eviction / realize-end). `multi_backend` gates ALL eager submits so a
1799        // single-device realize never touches this path (byte-identical to A4b-2).
1800        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
1801        // ROADMAP row 158: the backlog this realize adds to the device queues; its `Drop` takes it back out on
1802        // the Ok path and when an error unwinds the walk.
1803        let mut backlog = crate::dispatch::BacklogLedger::new();
1804        // GAP-415: out-of-range CUDA index reads, checked before any result leaves this run.
1805        let mut index_reads = IndexReads::default();
1806        // Step E A4b-4: set true the first time the dispatch order transitions
1807        // between two DIFFERENT non-CPU... actually any two distinct backends — a
1808        // genuine backend switch. On a pure-CUDA or pure-Vulkan graph there is no
1809        // switch, so this stays false and the eager-submit / in-flight machinery is
1810        // unreachable (single-device byte-identical + throughput-neutral, §5).
1811        let mut multi_backend = false;
1812        let loop_total = crate::compiled::op_profile::PhaseTimer::start("realize.loop_total");
1813        loop {
1814            let t_wait =
1815                crate::compiled::op_profile::PhaseTimer::start("realize.wait_for_compiler");
1816            let Ok(item) = rx.recv() else {
1817                break;
1818            };
1819            drop(t_wait);
1820            let item = item?;
1821            // Chunk-boundary hook (target_backend change). Existing duty: the
1822            // `TopologyChanged` generation check. Step E A4b-4 adds two duties:
1823            // (1) detect a genuine backend switch → arm `multi_backend`; (2) when
1824            // LEAVING a Vulkan chunk on a multi-backend graph, eager-submit the
1825            // open Vulkan batch so the iGPU starts it concurrently with the chunk
1826            // we are about to dispatch (the overlap win).
1827            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
1828            {
1829                if let Some(plan_gen) = plan_generation {
1830                    let live = crate::dispatch::topology_generation();
1831                    if live != plan_gen {
1832                        return Err(Error::TopologyChanged {
1833                            plan_generation: plan_gen,
1834                            current_generation: live,
1835                        }
1836                        .bt());
1837                    }
1838                }
1839                let leaving = current_chunk_backend;
1840                if let Some(prev) = leaving
1841                    && prev != item.target_backend
1842                {
1843                    // A real backend switch occurred — this realize is
1844                    // genuinely multi-backend.
1845                    multi_backend = true;
1846                    // Leaving a Vulkan chunk → submit it NOW so it runs on the
1847                    // iGPU while we record/dispatch the next chunk. Whole-chunk
1848                    // granularity (the open batch IS the just-finished Vulkan
1849                    // chunk with all its intra-CB barriers) — UAF/race-safe per
1850                    // `eager_submit_all_vulkan`'s contract.
1851                    if prev == BackendId::Vulkan {
1852                        {
1853                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1854                                "realize.eager_submit_vulkan",
1855                            );
1856                            eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1857                        }
1858                    }
1859                }
1860                current_chunk_backend = Some(item.target_backend);
1861            }
1862            // Vulkan realizes run the async path (deferred eviction, size-based eager
1863            // submit) even on a single device: ordering between batches is structural
1864            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
1865            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
1866            {
1867                multi_backend = true;
1868            }
1869            // Same-device cross-chunk RAW/WAR safety between Vulkan batches (the old
1870            // "Invariant E": wait every in-flight Vulkan batch on the HOST before
1871            // recording a new Vulkan op) is now structural: the Vulkan recorder
1872            // starts every batch with a memory barrier whose first scope covers all
1873            // earlier submissions on the queue (`Recorder::record_inter_batch_barrier`),
1874            // so a later batch cannot read or overwrite what an earlier in-flight
1875            // one is still using. The host therefore keeps recording while the
1876            // GPU runs the batches already submitted; waits remain only where the
1877            // host needs a result (D2H reads), before freeing a buffer, and at
1878            // realize-end.
1879            // Step E A4b-3 + A4b-4: the cross-device residency boundary.
1880            if matches!(
1881                item.kind,
1882                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
1883            ) {
1884                // A4b-4: before we (possibly) block the host on the CUDA producer,
1885                // eager-submit any open Vulkan chunk so the iGPU runs it WHILE we
1886                // wait on CUDA (the §5.1 ordering — submit Vulkan *before* draining
1887                // CUDA). Cheap + safe; gated to multi-backend (no-op single-device).
1888                if multi_backend {
1889                    {
1890                        let _pt = crate::compiled::op_profile::PhaseTimer::start(
1891                            "realize.eager_submit_vulkan",
1892                        );
1893                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
1894                    }
1895                }
1896                if let Some(&producer) = item.inputs.first() {
1897                    // A4b-4: a VULKAN-source D2H must read COMPLETED data, and the
1898                    // Vulkan download path only flushes the OPEN batch (not our
1899                    // in-flight ones) — so wait the in-flight Vulkan batches here.
1900                    // For a CUDA/CPU source we do NOT wait Vulkan (the copy reads no
1901                    // Vulkan buffer); waiting it would needlessly serialize the
1902                    // independent Vulkan sub-DAG and kill the overlap. The Vulkan
1903                    // work that was eager-submitted at the chunk boundary keeps
1904                    // running concurrently until ITS result is the one being copied.
1905                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
1906                        {
1907                            let _pt = crate::compiled::op_profile::PhaseTimer::start(
1908                                "realize.drain_inflight_vulkan",
1909                            );
1910                            drain_inflight_vulkan(&mut inflight_vulkan)?;
1911                        }
1912                    }
1913                    // Step E A4b-3: FINER CUDA source-drain — wait ONLY the source
1914                    // producer's recorded event (not the whole source device), so
1915                    // the OTHER sub-DAG's independent in-flight CUDA work keeps
1916                    // running. No-op for a Vulkan/CPU producer (no CUDA handle).
1917                    wait_producer_handle(&mut handles, producer)?;
1918                    index_reads.check()?;
1919                }
1920            }
1921            let t_exec =
1922                crate::compiled::op_profile::PhaseTimer::start(work_item_kind_name(&item.kind));
1923            let handle = execute_work_item(
1924                &item,
1925                &mut cache,
1926                &mut devices,
1927                &mut layout_cache,
1928                &mut produced_syms,
1929                will_be_waited(&wait_set, item.node_id),
1930                // No persistent-output mode on the standard realize paths —
1931                // fresh alloc per node, byte-identical to pre-CapturedRun.
1932                None,
1933                Some(&mut index_reads),
1934            )
1935            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
1936            drop(t_exec);
1937            store_handle(&mut handles, item.node_id, handle);
1938            feed_backlog(&mut backlog, &cache, &item);
1939            if let Some(d_idx) = item.destructive_input
1940                && let Some(&destroyed) = item.inputs.get(d_idx)
1941                && destroyed != target
1942            {
1943                // Step E A2.1 (in-flight-batch DATA-BUFFER lifetime — the
1944                // UAF guard, now DEFERRED-DELETION instead of a drain). A
1945                // `SubmittedBatch` owns its CB/descriptors/transients but
1946                // NOT the DATA buffers it reads (those live here in the
1947                // cache); recycling a data buffer an in-flight/open CB still
1948                // reads is a use-after-free. PRE-A2.1 we host-blocked here —
1949                // `drain_inflight_vulkan` (wait every in-flight batch) +
1950                // `force_flush` (submit+wait the open batch) — which stalled
1951                // the iGPU work we were overlapping with CUDA at EVERY such
1952                // eviction. A2.1 instead RETAINS the evicted buffer until the
1953                // reader fences signal: it eager-submits the open batch (no
1954                // wait → it becomes a fenced in-flight batch) and moves a
1955                // refcount clone of the buffer into every in-flight batch, so
1956                // the buffer frees POST-fence on each batch's `Drop`
1957                // (follow-on #2) with NO host block. Conservative over all
1958                // batches (no cheap buffer→batch map — the same reason the old
1959                // drain waited all of them). CUDA eviction is stream-ordered-
1960                // safe via A3. Single-device (multi_backend == false) keeps the
1961                // pre-A2.1 blocking force_flush of the OPEN batch (the else
1962                // branch) — byte-identical + UAF-safe there; the deferred path is
1963                // unsafe single-device (no eager-submit/in-flight tracking, and the
1964                // cross-batch RAW guard at :832 doesn't run — see
1965                // force_flush_vulkan's doc).
1966                let _t =
1967                    crate::compiled::op_profile::PhaseTimer::start("realize.evict_destroyed_input");
1968                if multi_backend {
1969                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
1970                } else if let Some(d_arc) = cache.get(&destroyed) {
1971                    let _f = crate::compiled::op_profile::PhaseTimer::start(
1972                        "realize.evict_force_flush_vulkan",
1973                    );
1974                    force_flush_vulkan(d_arc)?;
1975                }
1976                cache.remove(&destroyed);
1977                layout_cache.remove(&destroyed);
1978                // Drop the evicted node's CUDA handle (if still present)
1979                // so the realize-end drain's empty-map assert stays
1980                // meaningful. The free itself is stream-ordered-safe (A3).
1981                handles.remove(&destroyed);
1982            }
1983        }
1984
1985        drop(loop_total);
1986        {
1987            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.join_compiler");
1988            compiler
1989                .join()
1990                .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
1991        }
1992
1993        // Step E A4b-1: drain every outstanding async handle before the result is
1994        // read / the cache drops (freeing intermediates). For CUDA this waits the
1995        // recorded events (one stream/device ⇒ waiting the latest drains all prior
1996        // stream work too; see `drain_handles`).
1997        let post_loop = crate::compiled::op_profile::PhaseTimer::start("realize.post_loop_drains");
1998        drain_handles(&mut handles)?;
1999        // Step E A4b open question #4 — "event only where waited": most CUDA
2000        // nodes in this realize never got an Event (elided per the `WaitSet`),
2001        // so `drain_handles` above only retired the (typically few) tracked
2002        // handles. This blanket per-device `cuStreamSynchronize` flushes the
2003        // elided work too — safe + sufficient because of single-stream-per-
2004        // device ordering (see `sync_active_cuda_devices`'s doc).
2005        sync_active_cuda_devices(&cache)?;
2006        index_reads.check()?;
2007        // Step E A4b-4: wait every eagerly-submitted (in-flight) Vulkan batch
2008        // before the cache drops, freeing the data buffers their CBs read. Empty
2009        // on a single-device realize (nothing was eager-submitted).
2010        {
2011            let _pt =
2012                crate::compiled::op_profile::PhaseTimer::start("realize.drain_inflight_vulkan");
2013            drain_inflight_vulkan(&mut inflight_vulkan)?;
2014        }
2015        // Step E A4b-2: drain all deferred Vulkan work before reading/returning
2016        // the result (and before the cache drops, freeing buffers). The A2
2017        // submit+wait is now SPLIT — `drain_vulkan_pending` submits the open
2018        // batch then waits it via a `VulkanCompletion` handle. Byte-identical to
2019        // A2 for pure-Vulkan (one submission at realize-end, just split).
2020        drain_vulkan_pending(&cache)?;
2021        debug_assert!(
2022            inflight_vulkan.is_empty(),
2023            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2024        );
2025
2026        drop(post_loop);
2027        let storage = cache.remove(&target).ok_or_else(|| {
2028            Error::Msg(format!(
2029                "PipelinedExecutor::realize: target slot {:?} not populated after execution",
2030                target
2031            ))
2032            .bt()
2033        })?;
2034        let layout = layout_cache.remove(&target).ok_or_else(|| {
2035            Error::Msg(format!(
2036                "PipelinedExecutor::realize: target layout {:?} not populated after execution",
2037                target
2038            ))
2039            .bt()
2040        })?;
2041        {
2042            let _t = crate::compiled::op_profile::PhaseTimer::start("realize.drop_cache");
2043            drop(cache);
2044            drop(handles);
2045            drop(layout_cache);
2046        }
2047        Ok((storage, layout, produced_syms))
2048    }
2049
2050    /// Realize multiple targets in one walk. Each target's transitive
2051    /// dependency set is collapsed into a single execution plan
2052    /// (via [`execution_plan`]); shared subgraphs are evaluated
2053    /// once. Returns a `Vec<(Storage, Layout)>` whose order matches
2054    /// `targets`.
2055    ///
2056    /// This is Phase A of Phase 7.6 step 9c — feature-parity with the
2057    /// legacy `GraphExecutor::realize_many_f32`. Multi-session
2058    /// migration target ([memory: project_phase_7_6_step_9c_parity_audit.md]).
2059    ///
2060    /// Pre-conditions: every reachable `Op::Const` must be in
2061    /// `inputs`; every reachable non-`Const` must have its
2062    /// `target_backend` set; the op + dtype must be registered in
2063    /// `global_bindings()`. Same as single-target [`Self::realize`].
2064    pub fn realize_many(
2065        graph: Arc<RwLock<Graph>>,
2066        targets: &[NodeId],
2067        inputs: StorageCache,
2068    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2069        Self::realize_many_inner(
2070            graph,
2071            targets,
2072            inputs,
2073            OrderSource::Default,
2074            SymEnv::default(),
2075        )
2076    }
2077
2078    /// [`Self::realize_many`] with the device handles the caller already holds (ROADMAP row 137, seam S3
2079    /// step 3b).
2080    pub fn realize_many_with_devices(
2081        graph: Arc<RwLock<Graph>>,
2082        targets: &[NodeId],
2083        inputs: StorageCache,
2084        devices: DeviceRegistry,
2085    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2086        Self::realize_many_inner_with(
2087            graph,
2088            targets,
2089            inputs,
2090            OrderSource::Default,
2091            SymEnv::default(),
2092            devices,
2093        )
2094    }
2095
2096    /// [`Self::realize_many_with_optimized_picking_env`] with the device handles the caller already holds.
2097    #[allow(clippy::too_many_arguments)]
2098    pub fn realize_many_with_optimized_picking_env_with_devices(
2099        graph: Arc<RwLock<Graph>>,
2100        targets: &[NodeId],
2101        inputs: StorageCache,
2102        optimized: &OptimizedGraph,
2103        selector: Option<Arc<dyn RuntimeSelector>>,
2104        lookup: Option<BackendRuntimeLookup>,
2105        sym_env: SymEnv,
2106        devices: DeviceRegistry,
2107    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2108        let order_source = match Self::streaming_pick_for(&graph, selector, lookup)? {
2109            Some(pick) => {
2110                return Self::realize_many_inner_with(
2111                    graph,
2112                    targets,
2113                    inputs,
2114                    OrderSource::Streaming {
2115                        optimized,
2116                        pick: &pick,
2117                    },
2118                    sym_env,
2119                    devices,
2120                );
2121            }
2122            None => OrderSource::Optimized {
2123                optimized,
2124                route: None,
2125            },
2126        };
2127        Self::realize_many_inner_with(graph, targets, inputs, order_source, sym_env, devices)
2128    }
2129
2130    /// Multi-target PR-A3b-1 entry — the `realize_many` sibling of
2131    /// [`Self::realize_with_optimized`]. Drives the executor from the
2132    /// `OptimizedGraph`'s run lowering via the binding-table-lookup
2133    /// path, with the optimize-time `generation` keying the
2134    /// `TopologyChanged` chunk-boundary check.
2135    pub fn realize_many_with_optimized(
2136        graph: Arc<RwLock<Graph>>,
2137        targets: &[NodeId],
2138        inputs: StorageCache,
2139        optimized: &OptimizedGraph,
2140    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2141        Self::realize_many_inner(
2142            graph,
2143            targets,
2144            inputs,
2145            OrderSource::Optimized {
2146                optimized,
2147                route: None,
2148            },
2149            SymEnv::default(),
2150        )
2151    }
2152
2153    /// Env-carrying sibling of [`Self::realize_many_with_optimized`] (Phase D
2154    /// symbolic extents). An empty env is byte-identical to it.
2155    pub fn realize_many_with_optimized_env(
2156        graph: Arc<RwLock<Graph>>,
2157        targets: &[NodeId],
2158        inputs: StorageCache,
2159        optimized: &OptimizedGraph,
2160        sym_env: SymEnv,
2161    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2162        Self::realize_many_inner(
2163            graph,
2164            targets,
2165            inputs,
2166            OrderSource::Optimized {
2167                optimized,
2168                route: None,
2169            },
2170            sym_env,
2171        )
2172    }
2173
2174    /// Multi-target PR-C1 entry — the `realize_many` sibling of
2175    /// [`Self::realize_with_optimized_route`]. Lowers each target's runs
2176    /// following the picker's chosen arms via
2177    /// [`fuel_graph::lower_picked_route`].
2178    pub fn realize_many_with_optimized_route(
2179        graph: Arc<RwLock<Graph>>,
2180        targets: &[NodeId],
2181        inputs: StorageCache,
2182        optimized: &OptimizedGraph,
2183        route: &PickedRoute,
2184    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2185        Self::realize_many_inner(
2186            graph,
2187            targets,
2188            inputs,
2189            OrderSource::Optimized {
2190                optimized,
2191                route: Some(route),
2192            },
2193            SymEnv::default(),
2194        )
2195    }
2196
2197    /// Env-carrying sibling of [`Self::realize_many_with_optimized_route`]
2198    /// (Phase D symbolic extents). An empty env is byte-identical to it.
2199    pub fn realize_many_with_optimized_route_env(
2200        graph: Arc<RwLock<Graph>>,
2201        targets: &[NodeId],
2202        inputs: StorageCache,
2203        optimized: &OptimizedGraph,
2204        route: &PickedRoute,
2205        sym_env: SymEnv,
2206    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2207        Self::realize_many_inner(
2208            graph,
2209            targets,
2210            inputs,
2211            OrderSource::Optimized {
2212                optimized,
2213                route: Some(route),
2214            },
2215            sym_env,
2216        )
2217    }
2218
2219    /// Multi-target sibling of [`Self::realize_with_optimized_picking_env`] —
2220    /// the executor resolves one arm per `Op::Branch` (cleanup Step C/D) over
2221    /// the effective targets. PR C1: a branched graph routes to the
2222    /// `OrderSource::Streaming` walk (lazy per-branch resolution at the
2223    /// frontier); branchless / no-selector falls to the untouched arm-0 path.
2224    pub fn realize_many_with_optimized_picking_env(
2225        graph: Arc<RwLock<Graph>>,
2226        targets: &[NodeId],
2227        inputs: StorageCache,
2228        optimized: &OptimizedGraph,
2229        selector: Option<Arc<dyn RuntimeSelector>>,
2230        lookup: Option<BackendRuntimeLookup>,
2231        sym_env: SymEnv,
2232    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2233        match Self::streaming_pick_for(&graph, selector, lookup)? {
2234            Some(pick) => Self::realize_many_inner(
2235                graph,
2236                targets,
2237                inputs,
2238                OrderSource::Streaming {
2239                    optimized,
2240                    pick: &pick,
2241                },
2242                sym_env,
2243            ),
2244            None => {
2245                Self::realize_many_with_optimized_env(graph, targets, inputs, optimized, sym_env)
2246            }
2247        }
2248    }
2249
2250    fn realize_many_inner(
2251        graph: Arc<RwLock<Graph>>,
2252        targets: &[NodeId],
2253        inputs: StorageCache,
2254        order_source: OrderSource<'_>,
2255        sym_env: SymEnv,
2256    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2257        Self::realize_many_inner_with(
2258            graph,
2259            targets,
2260            inputs,
2261            order_source,
2262            sym_env,
2263            DeviceRegistry::new(),
2264        )
2265    }
2266
2267    /// [`Self::realize_many_inner`] with the device handles the caller already holds.
2268    fn realize_many_inner_with(
2269        graph: Arc<RwLock<Graph>>,
2270        targets: &[NodeId],
2271        inputs: StorageCache,
2272        order_source: OrderSource<'_>,
2273        sym_env: SymEnv,
2274        device_handles: DeviceRegistry,
2275    ) -> Result<Vec<(Arc<RwLock<Storage>>, Layout)>> {
2276        if targets.is_empty() {
2277            return Ok(Vec::new());
2278        }
2279
2280        // Auto-insert safety copies for in-place ops whose target
2281        // has additional readers in this realize set (residual-
2282        // connection cycle break). No-op when no destructive ops
2283        // are present.
2284        {
2285            let mut g = graph.write().map_err(|_| poisoned("graph lock"))?;
2286            let effective_roots = extend_with_side_effect_roots(&g, targets);
2287            insert_safety_copies(&mut g, &effective_roots);
2288        }
2289
2290        // Execution plan covering every target's dependency set +
2291        // initial layouts for the input cache entries. Side-effect
2292        // roots merge in so their effects fire even when not
2293        // reachable from any target. `execution_plan` integrates
2294        // `derive_ordering`'s view-aware pinning so destructive ops
2295        // run AFTER non-destructive readers of their targets.
2296        let (compiler_work, wait_set, mut layout_cache): (
2297            CompilerWork,
2298            WaitSet,
2299            HashMap<NodeId, Layout>,
2300        ) = {
2301            let g = graph.read().map_err(|_| poisoned("graph lock"))?;
2302            let effective_roots = extend_with_side_effect_roots(&g, targets);
2303            // PR-A3b-1: derive from the OptimizedGraph's run lowering
2304            // when present (post-safety-copies); else the legacy
2305            // `execution_plan` walk. Identical on branchless graphs.
2306            //
2307            // PR-C1: a `Streaming` source is handed to the compiler thread
2308            // unflattened (resolves branches at the frontier).
2309            //
2310            // Step E A4b open question #4: also derives the `WaitSet`
2311            // ("event only where waited") from the same materialized order.
2312            let (work, wait_set) =
2313                compiler_work_and_wait_set_for(&g, &effective_roots, &order_source);
2314            let mut layouts = HashMap::with_capacity(inputs.len());
2315            for &id in inputs.keys() {
2316                layouts.insert(id, g.layout(id));
2317            }
2318            (work, wait_set, layouts)
2319        };
2320
2321        // Caller's target set — used to gate destructive-input
2322        // eviction so we don't drop a tensor the caller asked for.
2323        let target_set: std::collections::HashSet<NodeId> = targets.iter().copied().collect();
2324
2325        let (tx, rx) = channel::<Result<WorkItem>>();
2326        let graph_for_compiler = Arc::clone(&graph);
2327
2328        let compiler = thread::spawn(move || {
2329            compiler_thread_body(graph_for_compiler, compiler_work, sym_env, tx);
2330        });
2331
2332        // Phase 4.3: per-chunk SystemTopology generation check (see
2333        // realize_inner for the rationale). PR-A3b-1: the OptimizedGraph
2334        // path supplies its own optimize-time generation.
2335        let plan_generation: Option<u64> = generation_for(&order_source);
2336        let mut current_chunk_backend: Option<BackendId> = None;
2337        let mut cache: StorageCache = inputs;
2338        let mut devices = device_handles;
2339        // Data-dependent dynamic-shapes producer-bound symbols (see
2340        // `realize_inner`). `realize_many` does not expose them today; the
2341        // env is dropped at pass end (producers still publish, keeping the
2342        // seam uniform across both realize loops).
2343        let mut produced_syms = SymEnv::new();
2344        // Step E A4b-1/A4b-3: per-node async-completion handles (see realize_inner
2345        // for the full rationale). Map drained at realize-end; the cross-device
2346        // copy waits the SOURCE producer's handle (A4b-3).
2347        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
2348        // Step E A4b-4: eagerly-submitted in-flight Vulkan batches + the
2349        // multi-backend gate. See realize_inner for the full rationale — this is
2350        // the identical eager-submit / in-flight-lifetime machinery applied to the
2351        // multi-target walk. `multi_backend` arms on a genuine backend switch and
2352        // gates every eager submit, so a single-device realize_many is
2353        // byte-identical to A4b-2.
2354        let mut inflight_vulkan: Vec<InflightVulkan> = Vec::new();
2355        // ROADMAP row 158: the backlog this realize adds to the device queues; its `Drop` takes it back out on
2356        // the Ok path and when an error unwinds the walk.
2357        let mut backlog = crate::dispatch::BacklogLedger::new();
2358        // GAP-415: out-of-range CUDA index reads, checked before any result leaves this run.
2359        let mut index_reads = IndexReads::default();
2360        let mut multi_backend = false;
2361        for item in rx {
2362            let item = item?;
2363            // Chunk-boundary hook: TopologyChanged check + (A4b-4) backend-switch
2364            // detection + eager-submit-on-leaving-a-Vulkan-chunk.
2365            if !is_backend_neutral(&item.kind) && current_chunk_backend != Some(item.target_backend)
2366            {
2367                if let Some(plan_gen) = plan_generation {
2368                    let live = crate::dispatch::topology_generation();
2369                    if live != plan_gen {
2370                        return Err(Error::TopologyChanged {
2371                            plan_generation: plan_gen,
2372                            current_generation: live,
2373                        }
2374                        .bt());
2375                    }
2376                }
2377                let leaving = current_chunk_backend;
2378                if let Some(prev) = leaving
2379                    && prev != item.target_backend
2380                {
2381                    multi_backend = true;
2382                    if prev == BackendId::Vulkan {
2383                        eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2384                    }
2385                }
2386                current_chunk_backend = Some(item.target_backend);
2387            }
2388            // Vulkan realizes run the async path (deferred eviction, size-based eager
2389            // submit) even on a single device: ordering between batches is structural
2390            // (inter-batch barrier + epoch-gated buffer reuse), not a host wait.
2391            if item.target_backend == BackendId::Vulkan && matches!(item.kind, WorkItemKind::Kernel)
2392            {
2393                multi_backend = true;
2394            }
2395            // Inter-batch Vulkan ordering is structural (see realize_inner): no host
2396            // wait before recording a new Vulkan op.
2397            // Step E A4b-3 + A4b-4: cross-device residency boundary. See
2398            // realize_inner for the full rationale.
2399            if matches!(
2400                item.kind,
2401                WorkItemKind::Copy { .. } | WorkItemKind::Move { .. }
2402            ) {
2403                // A4b-4: submit any open Vulkan chunk so the iGPU runs while the
2404                // host (possibly) waits on the CUDA producer.
2405                if multi_backend {
2406                    eager_submit_all_vulkan(&cache, &mut inflight_vulkan)?;
2407                }
2408                if let Some(&producer) = item.inputs.first() {
2409                    // A4b-4: wait in-flight Vulkan ONLY for a Vulkan-source D2H
2410                    // (reads completed data; download flushes only the OPEN batch).
2411                    // A CUDA/CPU source does NOT wait Vulkan (preserves overlap).
2412                    if multi_backend && copy_source_is_vulkan(&cache, producer)? {
2413                        drain_inflight_vulkan(&mut inflight_vulkan)?;
2414                    }
2415                    // Step E A4b-3: finer CUDA source-drain — wait ONLY the producer.
2416                    wait_producer_handle(&mut handles, producer)?;
2417                    index_reads.check()?;
2418                }
2419            }
2420            let handle = execute_work_item(
2421                &item,
2422                &mut cache,
2423                &mut devices,
2424                &mut layout_cache,
2425                &mut produced_syms,
2426                will_be_waited(&wait_set, item.node_id),
2427                // No persistent-output mode on the standard realize paths —
2428                // fresh alloc per node, byte-identical to pre-CapturedRun.
2429                None,
2430                Some(&mut index_reads),
2431            )
2432            .map_err(|e| with_node_location(&graph, item.node_id, e))?;
2433            store_handle(&mut handles, item.node_id, handle);
2434            feed_backlog(&mut backlog, &cache, &item);
2435            if let Some(d_idx) = item.destructive_input
2436                && let Some(&destroyed) = item.inputs.get(d_idx)
2437                && !target_set.contains(&destroyed)
2438            {
2439                // Step E A2.1 (in-flight DATA-BUFFER lifetime — UAF guard,
2440                // now DEFERRED-DELETION instead of a drain): retain the
2441                // evicted buffer until the reader fences signal — eager-
2442                // submit the open batch (no wait) + move a refcount clone of
2443                // the buffer into every in-flight batch, freeing it post-
2444                // fence on each batch's `Drop` with NO host block. Replaces
2445                // the pre-A2.1 `drain_inflight_vulkan` + open-batch
2446                // `force_flush` (two host-blocking fence waits). See
2447                // `defer_evicted_vulkan_buffer` / realize_inner for the
2448                // UAF/leak argument. CUDA eviction is A3 stream-safe.
2449                // Single-device (multi_backend == false) keeps the pre-A2.1
2450                // blocking force_flush of the OPEN batch (the else branch) —
2451                // byte-identical + UAF-safe; the deferred path is unsafe there
2452                // (see force_flush_vulkan's doc).
2453                if multi_backend {
2454                    defer_evicted_vulkan_buffer(&cache, destroyed, &mut inflight_vulkan)?;
2455                } else if let Some(d_arc) = cache.get(&destroyed) {
2456                    force_flush_vulkan(d_arc)?;
2457                }
2458                cache.remove(&destroyed);
2459                layout_cache.remove(&destroyed);
2460                // CUDA eviction is stream-ordered-safe (A3); drop the
2461                // handle so the realize-end empty-map assert stays valid.
2462                handles.remove(&destroyed);
2463            }
2464        }
2465
2466        compiler
2467            .join()
2468            .map_err(|_| Error::Msg("compiler thread panicked".to_string()).bt())?;
2469
2470        // Step E A4b-1: drain every outstanding async handle (CUDA events) before
2471        // results are read / the cache drops.
2472        drain_handles(&mut handles)?;
2473        // Step E A4b open question #4: blanket per-device stream sync for the
2474        // elided nodes `drain_handles` never tracked — see `realize_inner`'s
2475        // identical comment / `sync_active_cuda_devices`'s doc for the argument.
2476        sync_active_cuda_devices(&cache)?;
2477        index_reads.check()?;
2478        // Step E A4b-4: wait every eagerly-submitted in-flight Vulkan batch before
2479        // the cache drops. Empty on a single-device realize.
2480        drain_inflight_vulkan(&mut inflight_vulkan)?;
2481        // Step E A4b-2: drain all deferred Vulkan work — submit the open batch
2482        // then wait it via a `VulkanCompletion` handle (the A2 submit+wait, split;
2483        // byte-identical for pure-Vulkan — one submission at realize-end).
2484        drain_vulkan_pending(&cache)?;
2485        debug_assert!(
2486            inflight_vulkan.is_empty(),
2487            "A4b-4: in-flight Vulkan batch list must be empty after realize-end drain",
2488        );
2489
2490        // Verify every target was realized + collect outputs in
2491        // target order. We don't `remove` from the cache because the
2492        // same NodeId can appear twice in `targets` (caller wants the
2493        // same storage twice) — clone the Arc instead.
2494        let mut out = Vec::with_capacity(targets.len());
2495        for &target in targets {
2496            let storage = cache.get(&target).cloned().ok_or_else(|| {
2497                Error::Msg(format!(
2498                    "PipelinedExecutor::realize_many: target {:?} not populated after execution",
2499                    target
2500                ))
2501                .bt()
2502            })?;
2503            let layout = layout_cache.get(&target).cloned().ok_or_else(|| {
2504                Error::Msg(format!(
2505                    "PipelinedExecutor::realize_many: target layout {:?} not populated after execution",
2506                    target
2507                ))
2508                .bt()
2509            })?;
2510            out.push((storage, layout));
2511        }
2512        Ok(out)
2513    }
2514}
2515
2516/// Resolve the executor's dispatch order from the configured
2517/// [`OrderSource`]. PR-A3b-1: `Optimized` lowers the in-place
2518/// "plan IS the graph" form via `extract_runs`/`lower_run`; `Default`
2519/// keeps the pre-A3b-1 `execution_plan` walk. Both produce the same
2520/// `NodeId` sequence on a branchless graph (A3a equivalence gate),
2521/// computed here AFTER safety-copy insertion so either path covers
2522/// any freshly inserted copies.
2523fn order_for(
2524    graph: &Graph,
2525    effective_roots: &[NodeId],
2526    order_source: &OrderSource<'_>,
2527) -> Vec<NodeId> {
2528    match order_source {
2529        OrderSource::Default => execution_plan(graph, effective_roots),
2530        // The streaming walk is driven in the compiler thread (it
2531        // interleaves arm resolution with compilation), so `order_for`
2532        // never flattens it on the production path. This arm exists only
2533        // for match totality / non-pipelined callers: it collects the SAME
2534        // lazily-resolved order eagerly (the streaming walk with the same
2535        // `resolve_branch` over the threaded selector), which equals the
2536        // one-shot `lower_picked_route(pick_route(..))` order.
2537        OrderSource::Streaming {
2538            optimized: _optimized,
2539            pick,
2540        } => {
2541            let bindings = global_bindings();
2542            fuel_graph::lower_picked_route_streaming(graph, effective_roots, |branch| {
2543                resolve_branch(graph, branch, &bindings, pick.selector.as_ref())
2544            })
2545        }
2546        OrderSource::Optimized { optimized, route } => {
2547            // Lower the runs over the *effective* roots (user targets +
2548            // any spliced/side-effect roots) so the order matches the
2549            // walk's reachable set rather than only the optimize-time
2550            // roots. On a branchless graph this is the same concatenated
2551            // `lower_run` sequence the OptimizedGraph reports.
2552            //
2553            // PR-C1: when the picker supplied a route, follow the chosen
2554            // arms (`lower_picked_route`); otherwise the arm-0 lowering
2555            // (`OptimizedGraph::dispatch_order`). An empty route is
2556            // byte-identical to arm-0, so the two paths agree whenever
2557            // the picker chose arm-0 everywhere (the no-pressure case).
2558            match route {
2559                Some(route) => fuel_graph::lower_picked_route(graph, effective_roots, route),
2560                None => {
2561                    // A transient view built solely to call `dispatch_order`;
2562                    // it does no planning, so it carries no placements. The
2563                    // real optimization's map lives on `optimized`.
2564                    let view = OptimizedGraph {
2565                        roots: effective_roots.to_vec(),
2566                        generation: optimized.generation,
2567                        placements: None,
2568                        eviction: None,
2569                    };
2570                    view.dispatch_order(graph)
2571                }
2572            }
2573        }
2574        // Resolved by `compiler_work_and_wait_set_for` before delegating
2575        // here (the whole point of `Cached` is to skip this computation
2576        // on a hit) — never reached. Kept exhaustive rather than wildcarded
2577        // so a future `OrderSource` variant can't silently fall through.
2578        OrderSource::Cached { .. } => {
2579            unreachable!("OrderSource::Cached is resolved before order_for is called")
2580        }
2581    }
2582}
2583
2584/// Step E A4b open question #4 — "event only where waited". The producer
2585/// [`NodeId`]s that some later `Op::Copy`/`Op::Move` node in `order` will
2586/// `wait_producer_handle` on (the executor's cross-device residency
2587/// boundary — see `wait_producer_handle`, whose `item.inputs.first()` read
2588/// this mirrors exactly). A CUDA node whose id is absent from the returned
2589/// set has NO mid-walk reader: same-device consumers are correct via stream
2590/// ordering alone (they never `wait`), and nothing touches its handle before
2591/// the realize-end drain, so [`crate::compiled::execute_compiled_with_wait_hint`]
2592/// can skip recording an `Event` for it entirely.
2593///
2594/// Requires a materialized `order` (works for [`OrderSource::Default`] /
2595/// [`OrderSource::Optimized`], whose [`CompilerWork::Order`] is a frozen
2596/// `Vec<NodeId>` computed up front) — see
2597/// [`compiler_work_and_wait_set_for`] for the [`OrderSource::Streaming`]
2598/// fallback.
2599fn build_wait_set(graph: &Graph, order: &[NodeId]) -> HashSet<NodeId> {
2600    let mut set = HashSet::new();
2601    for &id in order {
2602        let node = graph.node(id);
2603        if matches!(node.op, Op::Copy { .. } | Op::Move { .. })
2604            && let Some(&producer) = node.inputs.first()
2605        {
2606            set.insert(producer);
2607        }
2608    }
2609    set
2610}
2611
2612/// Step E A4b open question #4: the executor's per-realize wait-set.
2613/// `None` is the CONSERVATIVE fallback — every CUDA node still gets an Event
2614/// (today's pre-elision behavior, byte-identical). `Some(set)` restricts
2615/// event production to `set`'s members ([`build_wait_set`]'s output);
2616/// everything else gets `CompletionHandle::Ready` with no Event recorded.
2617type WaitSet = Option<HashSet<NodeId>>;
2618
2619/// Whether `node_id`'s completion handle must be individually observable
2620/// (i.e. `execute_compiled_with_wait_hint`'s `will_be_waited`). `None` (the
2621/// [`OrderSource::Streaming`] fallback — never elides) is always `true`.
2622#[inline]
2623fn will_be_waited(wait_set: &WaitSet, node_id: NodeId) -> bool {
2624    match wait_set {
2625        None => true,
2626        Some(set) => set.contains(&node_id),
2627    }
2628}
2629
2630/// Build the [`CompilerWork`] the compiler thread walks for the configured
2631/// [`OrderSource`], plus the [`WaitSet`] "event only where waited" (open
2632/// question #4) consults. The non-streaming sources flatten up front via
2633/// [`order_for`] (unchanged) and the SAME materialized order feeds
2634/// [`build_wait_set`], so the pre-scan and the dispatch order never
2635/// disagree. [`OrderSource::Streaming`] is handed to the compiler thread as
2636/// a [`CompilerWork::Streaming`] spec — NOT flattened here — so the thread
2637/// resolves branches lazily at the frontier (Step E Phase C, PR C1); the lazy
2638/// order can't be pre-scanned without eagerly resolving it (which would
2639/// defeat the point of streaming), so it falls back to the conservative
2640/// `WaitSet::None` — event every node, unchanged behavior. Holds the graph
2641/// read-lock only for the flattening branches; the streaming branch defers
2642/// the lock to the compiler thread.
2643fn compiler_work_and_wait_set_for(
2644    graph: &Graph,
2645    effective_roots: &[NodeId],
2646    order_source: &OrderSource<'_>,
2647) -> (CompilerWork, WaitSet) {
2648    match order_source {
2649        OrderSource::Streaming { pick, .. } => (
2650            CompilerWork::Streaming {
2651                roots: effective_roots.to_vec(),
2652                pick: (*pick).clone(),
2653            },
2654            None,
2655        ),
2656        OrderSource::Cached {
2657            optimized,
2658            order_cache,
2659        } => {
2660            let order = order_cache.get_or_init(|| {
2661                order_for(
2662                    graph,
2663                    effective_roots,
2664                    &OrderSource::Optimized {
2665                        optimized,
2666                        route: None,
2667                    },
2668                )
2669            });
2670            let wait_set = build_wait_set(graph, order);
2671            (CompilerWork::Order(order.clone()), Some(wait_set))
2672        }
2673        other => {
2674            let order = order_for(graph, effective_roots, other);
2675            let wait_set = build_wait_set(graph, &order);
2676            (CompilerWork::Order(order), Some(wait_set))
2677        }
2678    }
2679}
2680
2681/// The topology generation that keys the executor's `TopologyChanged`
2682/// chunk-boundary check. Uses the `OptimizedGraph`'s optimize-time
2683/// generation (PR-A3b-1 path). `None` ⇒ no check (the plain
2684/// `realize`/`realize_many` entries).
2685fn generation_for(order_source: &OrderSource<'_>) -> Option<u64> {
2686    match order_source {
2687        OrderSource::Optimized { optimized, .. } => Some(optimized.generation),
2688        OrderSource::Streaming { optimized, .. } => Some(optimized.generation),
2689        OrderSource::Cached { optimized, .. } => Some(optimized.generation),
2690        OrderSource::Default => None,
2691    }
2692}
2693
2694/// What the compiler thread walks: either a pre-flattened dispatch
2695/// `Order` (the `Default` / `Optimized` paths — unchanged), or a
2696/// `Streaming` spec the thread resolves branch-by-branch at the frontier
2697/// (Step E Phase C, PR C1).
2698enum CompilerWork {
2699    /// A frozen topological order (computed up front by `order_for`). The
2700    /// compiler thread compiles each node and sends it in turn.
2701    Order(Vec<NodeId>),
2702    /// The streaming run-walk: the compiler thread drives
2703    /// [`fuel_graph::walk_picked_route_streaming`] over `roots`, resolving
2704    /// each `Op::Branch` lazily via [`resolve_branch`] as the frontier
2705    /// reaches its arm-entry, and compiling + sending only the chosen
2706    /// arm's runs. `roots` are the effective roots (same set `order_for`
2707    /// lowers over). Byte-identical to `Order(lower_picked_route(
2708    /// pick_route(..)))` in C1 (same VRAM-only selector).
2709    Streaming {
2710        roots: Vec<NodeId>,
2711        pick: StreamingPick,
2712    },
2713}
2714
2715/// Compiler thread body. Holds the graph read-lock + a thread-local
2716/// layout cache and emits `WorkItem`s in topological order. For
2717/// [`CompilerWork::Order`] it walks the frozen order; for
2718/// [`CompilerWork::Streaming`] it resolves each branch at the frontier and
2719/// emits only the chosen arm's runs (Step E Phase C, PR C1). Sends
2720/// `Err(...)` and stops on the first failure.
2721fn compiler_thread_body(
2722    graph: Arc<RwLock<Graph>>,
2723    work: CompilerWork,
2724    sym_env: SymEnv,
2725    tx: Sender<Result<WorkItem>>,
2726) {
2727    let bindings = global_bindings();
2728
2729    let g = match graph.read() {
2730        Ok(g) => g,
2731        Err(_) => {
2732            let _ = tx.send(Err(poisoned("graph lock in compiler")));
2733            return;
2734        }
2735    };
2736
2737    // Compiler-thread-local layout cache. Populated as compile_one
2738    // walks topologically; downstream nodes look up their inputs'
2739    // layouts here (rather than from the graph side-table) to honor
2740    // the strided layouts emitted by metadata-only view ops earlier
2741    // in the same realize call.
2742    let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
2743    // `compile_one` for one node + send; returns `false` to stop the walk
2744    // (channel closed or compile error). Shared by both work modes so the
2745    // streamed and frozen-order paths compile identically.
2746    // Arm exits of live branches. The reconverge node reads ARM 0's exit (the runnability invariant),
2747    // so when the picker chooses an arm k >= 1 its exit is the value the reconverge must see: right
2748    // after compiling that exit, alias arm 0's exit id to it (a zero-copy `ViewOf`). Non-chosen arms
2749    // are never compiled, so an exit that is compiled here is the chosen one.
2750    let alias_exits: HashMap<NodeId, NodeId> = {
2751        let mut m = HashMap::new();
2752        for i in 0..g.len() {
2753            let id = NodeId(i);
2754            if matches!(g.node(id).op, Op::Branch { .. }) {
2755                let arms = &g.node(id).inputs;
2756                for &exit in arms.iter().skip(1) {
2757                    m.insert(exit, arms[0]);
2758                }
2759            }
2760        }
2761        m
2762    };
2763    // Diagnostic (`FUEL_PRINT_BRANCH_COUNT`): every node the compiler thread sends, in order, so a failed
2764    // realize can be read against the order it was fed.
2765    let print_order = std::env::var_os("FUEL_PRINT_BRANCH_COUNT").is_some();
2766    let compile_and_send = |id: NodeId, layout_cache: &mut HashMap<NodeId, Layout>| -> bool {
2767        if print_order {
2768            let n = g.node(id);
2769            eprintln!(
2770                "fuel: send Node#{} {} inputs={:?} backend={:?} placement={:?}",
2771                id.0,
2772                format!("{:?}", n.op).chars().take(40).collect::<String>(),
2773                n.inputs.iter().map(|i| i.0).collect::<Vec<_>>(),
2774                g.target_backend(id),
2775                g.placement(id),
2776            );
2777        }
2778        let item = compile_one(&g, id, layout_cache, &bindings, &sym_env);
2779        let stop_on_err = item.is_err();
2780        if tx.send(item).is_err() {
2781            return false;
2782        }
2783        if stop_on_err {
2784            return false;
2785        }
2786        if let Some(&arm0_exit) = alias_exits.get(&id)
2787            && tx
2788                .send(Ok(arm_exit_alias_item(&g, arm0_exit, id, layout_cache)))
2789                .is_err()
2790        {
2791            return false;
2792        }
2793        true
2794    };
2795
2796    match work {
2797        CompilerWork::Order(order) => {
2798            for id in order {
2799                if !compile_and_send(id, &mut layout_cache) {
2800                    return;
2801                }
2802            }
2803        }
2804        CompilerWork::Streaming { roots, pick } => {
2805            // Resolve each branch lazily at its arm-entry. C1 built the
2806            // streaming frontier; C2 made `pick.selector` load-aware (the
2807            // production `ChainedSelector` now reads each arm's live device
2808            // load — `pending_work_count / slot_capacity` via the
2809            // `BackendStreams` seam — as a key leg under the VRAM guard),
2810            // so this resolution reads live device load at THIS moment: the
2811            // executor has been submitting/draining (and updating the B1
2812            // counter) while the compiler ran ahead. Emit only the chosen
2813            // arm's runs, compiling + sending each node as the walk reaches
2814            // it — genuine streaming (resolution interleaved with
2815            // dispatch), not a pre-flattened order.
2816            let mut stopped = false;
2817            fuel_graph::walk_picked_route_streaming(
2818                &g,
2819                &roots,
2820                |branch| resolve_branch(&g, branch, &bindings, pick.selector.as_ref()),
2821                |members| {
2822                    if stopped {
2823                        return;
2824                    }
2825                    for &id in members {
2826                        if !compile_and_send(id, &mut layout_cache) {
2827                            stopped = true;
2828                            return;
2829                        }
2830                    }
2831                },
2832            );
2833        }
2834    }
2835}
2836
2837/// The work item that makes arm 0's exit id carry the value of the chosen arm's exit: a zero-copy
2838/// `ViewOf` (the executor clones the source's storage into `alias_id`'s cache slot). Emitted right
2839/// after the chosen exit, before the reconverge node that reads `alias_id`. The two exits agree on
2840/// shape and dtype by the branch's cast-to-uniform rule, so the layout is the source's.
2841fn arm_exit_alias_item(
2842    graph: &Graph,
2843    alias_id: NodeId,
2844    source: NodeId,
2845    layout_cache: &mut HashMap<NodeId, Layout>,
2846) -> WorkItem {
2847    let node = graph.node(alias_id);
2848    let layout = layout_cache
2849        .get(&source)
2850        .cloned()
2851        .unwrap_or_else(|| Layout::contiguous(graph.node(source).shape.clone()));
2852    layout_cache.insert(alias_id, layout.clone());
2853    WorkItem {
2854        node_id: alias_id,
2855        inputs: vec![source],
2856        elem_count: node.shape.elem_count(),
2857        dtype: node.dtype,
2858        target_backend: graph
2859            .target_backend(source)
2860            .or_else(|| graph.target_backend(alias_id))
2861            .unwrap_or(BackendId::Cpu),
2862        kind: WorkItemKind::ViewOf { input: source },
2863        compiled: None,
2864        output_layout: layout,
2865        destructive_input: None,
2866        output_bundle: None,
2867    }
2868}
2869
2870/// Resolve the [`CompiledNode`] for a kernel-bearing graph node via
2871/// the first-registered [`compile_node`] binding-table lookup.
2872///
2873/// `op_params` always comes from the executor's
2874/// `op_to_op_params(graph, node, id, layout_cache, sym_env)` — the live
2875/// OpParams shape (reduce dims, conv geometry, the per-pass
2876/// `SymEnv`-resolved `WriteSlice` offset, etc.) derives from the graph
2877/// node + its resolved input layouts at execute time.
2878fn resolve_compiled(
2879    graph: &Graph,
2880    node: &fuel_graph::Node,
2881    op_kind: OpKind,
2882    dtypes: &[DType],
2883    target_backend: BackendId,
2884    op_params: OpParams,
2885    bindings: &KernelBindingTable,
2886) -> Result<CompiledNode> {
2887    let mut compiled = compile_node(op_kind, dtypes, target_backend, op_params, bindings)?;
2888    // ROADMAP row 158: price the launch ONCE here so the executor's per-op feed of the device backlog is a
2889    // field read, not a cost-model query (see `compiled::estimate_static_ns`).
2890    if target_backend != BackendId::Cpu {
2891        let shapes: Vec<fuel_ir::Shape> = node
2892            .inputs
2893            .iter()
2894            .map(|&i| graph.node(i).shape.clone())
2895            .collect();
2896        compiled.est_ns = crate::compiled::estimate_static_ns(
2897            op_kind,
2898            dtypes,
2899            &shapes,
2900            target_backend,
2901            &compiled.op_params,
2902            bindings,
2903        );
2904    }
2905    Ok(compiled)
2906}
2907
2908/// Resolve one node into a `WorkItem` and update `layout_cache`
2909/// with the node's output layout. Three op shapes:
2910///
2911/// - `Op::Const` — adopts the entry from the input cache; layout is
2912///   read from the graph's side-table (or its contiguous fallback).
2913///
2914/// - Metadata-only view op — output layout is read from the graph's
2915///   side-table (populated by `Graph::push` at construction time);
2916///   the executor adopts the input's Storage Arc (no allocation, no
2917///   kernel).
2918///
2919/// - Computational op — output layout is `Layout::contiguous(node.shape)`
2920///   because today's kernels write contiguous output. The compiler
2921///   resolves the kernel ref and emits a Kernel work item.
2922fn compile_one(
2923    graph: &Graph,
2924    id: NodeId,
2925    layout_cache: &mut HashMap<NodeId, Layout>,
2926    bindings: &KernelBindingTable,
2927    sym_env: &SymEnv,
2928) -> Result<WorkItem> {
2929    let node = graph.node(id);
2930    let elem_count = node.shape.elem_count();
2931    let inputs = node.inputs.clone();
2932    // Snapshot destructive-input metadata from the graph at compile
2933    // time so the executor can evict the destroyed input from its
2934    // cache after the op runs (Op::Release / Op::Move semantics).
2935    let destructive_input = node.op.destructive_input();
2936
2937    if matches!(node.op, Op::Const) {
2938        let output_layout = graph.layout(id);
2939        layout_cache.insert(id, output_layout.clone());
2940        return Ok(WorkItem {
2941            node_id: id,
2942            inputs,
2943            elem_count,
2944            dtype: node.dtype,
2945            target_backend: BackendId::Cpu,
2946            kind: WorkItemKind::ConstAdopt,
2947            compiled: None,
2948            output_layout,
2949            destructive_input,
2950            output_bundle: None,
2951        });
2952    }
2953
2954    if node.op.is_view_op() {
2955        if inputs.len() != 1 {
2956            return Err(Error::Msg(format!(
2957                "view op {:?} expects 1 input, got {}",
2958                node.op,
2959                inputs.len(),
2960            ))
2961            .bt());
2962        }
2963        // Layout is read from the graph's side-table — populated by
2964        // `Graph::push` at construction time for view ops, and by
2965        // graph-rewriting opt passes that emit view nodes. The
2966        // compiler does not re-derive: graph.layout(id) is the single
2967        // source of truth.
2968        let output_layout = graph.layout(id);
2969        layout_cache.insert(id, output_layout.clone());
2970        // Inherit the upstream's target_backend (or default CPU) —
2971        // metadata-only adoption doesn't actually run on a backend,
2972        // but downstream consumers look at target_backend so it
2973        // needs to be set sensibly. Any device works.
2974        let target_backend = graph
2975            .target_backend(id)
2976            .or_else(|| graph.target_backend(inputs[0]))
2977            .unwrap_or(BackendId::Cpu);
2978        return Ok(WorkItem {
2979            node_id: id,
2980            inputs,
2981            elem_count,
2982            dtype: node.dtype,
2983            target_backend,
2984            kind: WorkItemKind::ViewOf {
2985                input: node.inputs[0],
2986            },
2987            compiled: None,
2988            output_layout,
2989            destructive_input,
2990            output_bundle: None,
2991        });
2992    }
2993
2994    // Op::View — multi-output projection (Option C, Session 4).
2995    // Structurally identical to a metadata-only view op at realize
2996    // time: clone the producer's Storage Arc into the View's cache
2997    // slot. The graph's layout side-table, populated by
2998    // `Tensor::view`, already carries the slot's effective layout
2999    // (slot.byte_offset baked into start_offset in slot-dtype-element
3000    // units).
3001    if let Op::View { .. } = node.op {
3002        if inputs.len() != 1 {
3003            return Err(Error::Msg(format!(
3004                "Op::View expects 1 input (the producer), got {}",
3005                inputs.len(),
3006            ))
3007            .bt());
3008        }
3009        let output_layout = graph.layout(id);
3010        layout_cache.insert(id, output_layout.clone());
3011        let target_backend = graph
3012            .target_backend(id)
3013            .or_else(|| graph.target_backend(inputs[0]))
3014            .unwrap_or(BackendId::Cpu);
3015        return Ok(WorkItem {
3016            node_id: id,
3017            inputs: inputs.clone(),
3018            elem_count,
3019            dtype: node.dtype,
3020            target_backend,
3021            kind: WorkItemKind::SlotView {
3022                producer: inputs[0],
3023            },
3024            compiled: None,
3025            output_layout,
3026            destructive_input,
3027            output_bundle: None,
3028        });
3029    }
3030
3031    // Op::ViewOwned — copies the slot's bytes into a fresh
3032    // contiguous Storage at realize time. Output layout is
3033    // contiguous starting at offset 0 (the memcpy produced an
3034    // independent buffer).
3035    if let Op::ViewOwned { slot } = node.op {
3036        if inputs.len() != 1 {
3037            return Err(Error::Msg(format!(
3038                "Op::ViewOwned expects 1 input (the producer), got {}",
3039                inputs.len(),
3040            ))
3041            .bt());
3042        }
3043        let output_layout = Layout::contiguous(node.shape.clone());
3044        layout_cache.insert(id, output_layout.clone());
3045        let target_backend = graph
3046            .target_backend(id)
3047            .or_else(|| graph.target_backend(inputs[0]))
3048            .unwrap_or(BackendId::Cpu);
3049        return Ok(WorkItem {
3050            node_id: id,
3051            inputs: inputs.clone(),
3052            elem_count,
3053            dtype: node.dtype,
3054            target_backend,
3055            kind: WorkItemKind::SlotOwn {
3056                producer: inputs[0],
3057                slot,
3058            },
3059            compiled: None,
3060            output_layout,
3061            destructive_input,
3062            output_bundle: None,
3063        });
3064    }
3065
3066    if matches!(node.op, Op::Release) {
3067        // Op::Release produces a zero-element marker output. The
3068        // marker storage is CPU + 0 bytes — nothing reads it; it
3069        // exists so cache lookups on the Release NodeId resolve.
3070        // The actual deallocation of `inputs[0]` happens in the
3071        // realize loop via `destructive_input` cleanup.
3072        if inputs.len() != 1 {
3073            return Err(
3074                Error::Msg(format!("Op::Release expects 1 input, got {}", inputs.len(),)).bt(),
3075            );
3076        }
3077        let output_layout = Layout::contiguous(node.shape.clone());
3078        layout_cache.insert(id, output_layout.clone());
3079        // Inherit the source's target_backend so any downstream
3080        // backend-aware logic (telemetry, scheduling) sees a sensible
3081        // value. The marker doesn't actually run on any backend.
3082        let target_backend = graph
3083            .target_backend(id)
3084            .or_else(|| graph.target_backend(inputs[0]))
3085            .unwrap_or(BackendId::Cpu);
3086        return Ok(WorkItem {
3087            node_id: id,
3088            inputs,
3089            elem_count,
3090            dtype: node.dtype,
3091            target_backend,
3092            kind: WorkItemKind::ReleaseMarker,
3093            compiled: None,
3094            output_layout,
3095            destructive_input,
3096            output_bundle: None,
3097        });
3098    }
3099
3100    // In-place ops (Phase 3 of in-place ops infrastructure): kernel
3101    // lookup goes through the standard binding-table path, but the
3102    // executor adopts the target's Arc as the output instead of
3103    // allocating fresh bytes. The compile-time predicate is exactly
3104    // `op.destructive_input().is_some()` AND NOT one of the
3105    // structural ops (WriteSlice / ZeroFill / Release / Move) which
3106    // have their own dedicated WorkItemKind arms in this function.
3107    if !matches!(
3108        node.op,
3109        Op::WriteSlice { .. }
3110            | Op::WriteSliceRotating { .. }
3111            | Op::WriteSliceDoff { .. }
3112            | Op::ZeroFill
3113            | Op::Release
3114            | Op::Move { .. },
3115    ) && let Some(target_idx) = node.op.destructive_input()
3116    {
3117        if inputs.len() <= target_idx {
3118            return Err(Error::Msg(format!(
3119                "in-place op {:?} declares destructive_input={target_idx} \
3120                     but has only {} input(s)",
3121                node.op,
3122                inputs.len(),
3123            ))
3124            .bt());
3125        }
3126        let target_backend = graph.target_backend(id).ok_or_else(|| {
3127            Error::Msg(format!(
3128                "PipelinedExecutor: in-place op node {id:?} has no target_backend set",
3129            ))
3130            .bt()
3131        })?;
3132        let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3133            Error::Msg(format!(
3134                "PipelinedExecutor: in-place op {:?} has no op_to_op_kind mapping",
3135                node.op,
3136            ))
3137            .bt()
3138        })?;
3139        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3140        let dtypes = build_lookup_dtypes(graph, node);
3141        let compiled = resolve_compiled(
3142            graph,
3143            node,
3144            op_kind,
3145            &dtypes,
3146            target_backend,
3147            op_params,
3148            bindings,
3149        )?;
3150        // Output adopts target's Layout (same Storage Arc, same shape).
3151        let output_layout = graph.layout(inputs[target_idx]);
3152        layout_cache.insert(id, output_layout.clone());
3153        return Ok(WorkItem {
3154            node_id: id,
3155            inputs: inputs.clone(),
3156            elem_count,
3157            dtype: node.dtype,
3158            target_backend,
3159            kind: WorkItemKind::InplaceKernel { target_idx },
3160            compiled: Some(compiled),
3161            output_layout,
3162            destructive_input,
3163            output_bundle: None,
3164        });
3165    }
3166
3167    if matches!(node.op, Op::WriteSlice { .. }) {
3168        // WriteSlice: kernel lookup happens like a normal kernel, but
3169        // the work item carries a dedicated kind so the executor
3170        // knows to adopt the destination's Arc as the output rather
3171        // than allocating a fresh buffer. The destination's NodeId is
3172        // captured here so the executor doesn't have to re-derive it.
3173        if inputs.len() != 2 {
3174            return Err(Error::Msg(format!(
3175                "Op::WriteSlice expects 2 inputs (destination, source), got {}",
3176                inputs.len(),
3177            ))
3178            .bt());
3179        }
3180        let target_backend = graph.target_backend(id).ok_or_else(|| {
3181            Error::Msg(format!(
3182                "PipelinedExecutor: WriteSlice node {:?} has no target_backend set",
3183                id
3184            ))
3185            .bt()
3186        })?;
3187        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3188        let dtypes = build_lookup_dtypes(graph, node);
3189        let compiled = resolve_compiled(
3190            graph,
3191            node,
3192            OpKind::WriteSlice,
3193            &dtypes,
3194            target_backend,
3195            op_params,
3196            bindings,
3197        )?;
3198        // Output adopts the destination's Layout — same Storage Arc,
3199        // same shape. Downstream consumers that want a post-write
3200        // sub-extent compose an explicit Op::Slice (WriteSlice does
3201        // not encode partial extents).
3202        let output_layout = graph.layout(inputs[0]);
3203        layout_cache.insert(id, output_layout.clone());
3204        return Ok(WorkItem {
3205            node_id: id,
3206            inputs: inputs.clone(),
3207            elem_count,
3208            dtype: node.dtype,
3209            target_backend,
3210            kind: WorkItemKind::WriteSlice {
3211                dest: inputs[0],
3212                source: inputs[1],
3213            },
3214            compiled: Some(compiled),
3215            output_layout,
3216            destructive_input,
3217            output_bundle: None,
3218        });
3219    }
3220
3221    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3222        // WriteSliceRotating: same shape as WriteSlice but with a
3223        // third input (position scalar). Dispatch through the
3224        // binding table at `OpKind::WriteSliceRotating`; the
3225        // executor's arm reads the position from `position`'s
3226        // storage and the kernel splits across the ring boundary.
3227        if inputs.len() != 3 {
3228            return Err(Error::Msg(format!(
3229                "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
3230                inputs.len(),
3231            ))
3232            .bt());
3233        }
3234        let target_backend = graph.target_backend(id).ok_or_else(|| {
3235            Error::Msg(format!(
3236                "PipelinedExecutor: WriteSliceRotating node {:?} has no target_backend set",
3237                id
3238            ))
3239            .bt()
3240        })?;
3241        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3242        let dtypes = build_lookup_dtypes(graph, node);
3243        let compiled = resolve_compiled(
3244            graph,
3245            node,
3246            OpKind::WriteSliceRotating,
3247            &dtypes,
3248            target_backend,
3249            op_params,
3250            bindings,
3251        )?;
3252        let output_layout = graph.layout(inputs[0]);
3253        layout_cache.insert(id, output_layout.clone());
3254        return Ok(WorkItem {
3255            node_id: id,
3256            inputs: inputs.clone(),
3257            elem_count,
3258            dtype: node.dtype,
3259            target_backend,
3260            kind: WorkItemKind::WriteSliceRotating {
3261                dest: inputs[0],
3262                source: inputs[1],
3263                position: inputs[2],
3264            },
3265            compiled: Some(compiled),
3266            output_layout,
3267            destructive_input,
3268            output_bundle: None,
3269        });
3270    }
3271
3272    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3273        // WriteSliceDoff: same shape as WriteSlice but with a third
3274        // input (device-resident I64 offset). Dispatch through the
3275        // binding table at `OpKind::WriteSliceDoff`; the executor's arm
3276        // threads the offset's device pointer straight to the kernel
3277        // (no D2H, capture-safe).
3278        if inputs.len() != 3 {
3279            return Err(Error::Msg(format!(
3280                "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
3281                inputs.len(),
3282            ))
3283            .bt());
3284        }
3285        let target_backend = graph.target_backend(id).ok_or_else(|| {
3286            Error::Msg(format!(
3287                "PipelinedExecutor: WriteSliceDoff node {:?} has no target_backend set",
3288                id
3289            ))
3290            .bt()
3291        })?;
3292        let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3293        let dtypes = build_lookup_dtypes(graph, node);
3294        let compiled = resolve_compiled(
3295            graph,
3296            node,
3297            OpKind::WriteSliceDoff,
3298            &dtypes,
3299            target_backend,
3300            op_params,
3301            bindings,
3302        )?;
3303        let output_layout = graph.layout(inputs[0]);
3304        layout_cache.insert(id, output_layout.clone());
3305        return Ok(WorkItem {
3306            node_id: id,
3307            inputs: inputs.clone(),
3308            elem_count,
3309            dtype: node.dtype,
3310            target_backend,
3311            kind: WorkItemKind::WriteSliceDoff {
3312                dest: inputs[0],
3313                source: inputs[1],
3314                offset: inputs[2],
3315            },
3316            compiled: Some(compiled),
3317            output_layout,
3318            destructive_input,
3319            output_bundle: None,
3320        });
3321    }
3322
3323    if let Op::Alloc { target } = node.op {
3324        // Op::Alloc { target }: produce a fresh zero-init Storage on
3325        // `target` with node.shape * node.dtype. Zero inputs.
3326        // Direct executor dispatch via WorkItemKind::Alloc — no
3327        // binding-table lookup (the device handle threading isn't
3328        // expressible through the binding table's current key shape).
3329        if !inputs.is_empty() {
3330            return Err(
3331                Error::Msg(format!("Op::Alloc expects 0 inputs, got {}", inputs.len(),)).bt(),
3332            );
3333        }
3334        let output_layout = Layout::contiguous(node.shape.clone());
3335        layout_cache.insert(id, output_layout.clone());
3336        // target_backend is informational here (the executor's Alloc
3337        // arm consults target_location for allocation routing); set
3338        // it to target's backend for consistency with how downstream
3339        // nodes inherit/read it.
3340        let target_backend = target.backend();
3341        return Ok(WorkItem {
3342            node_id: id,
3343            inputs,
3344            elem_count,
3345            dtype: node.dtype,
3346            target_backend,
3347            kind: WorkItemKind::Alloc {
3348                target_location: target,
3349            },
3350            compiled: None,
3351            output_layout,
3352            destructive_input,
3353            output_bundle: None,
3354        });
3355    }
3356
3357    if let Op::Iota { len } = node.op {
3358        // Op::Iota { len }: 0-input F32 position generator
3359        // [0.0, 1.0, …, (len-1)]. Direct executor dispatch via
3360        // WorkItemKind::Iota — no binding-table lookup (a leaf has no
3361        // inputs[0] to inherit a backend from). Modeled on Op::Alloc.
3362        if !inputs.is_empty() {
3363            return Err(
3364                Error::Msg(format!("Op::Iota expects 0 inputs, got {}", inputs.len(),)).bt(),
3365            );
3366        }
3367        let output_layout = Layout::contiguous(node.shape.clone());
3368        layout_cache.insert(id, output_layout.clone());
3369        // Leaf: the planner may not place a 0-input node, so fall back to
3370        // CPU. Iota is a tiny host-side generator; its only consumer today
3371        // is the CPU flash-attn decomposition's alibi bias.
3372        let target_backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3373        return Ok(WorkItem {
3374            node_id: id,
3375            inputs,
3376            elem_count,
3377            dtype: node.dtype,
3378            target_backend,
3379            kind: WorkItemKind::Iota {
3380                len,
3381                target_location: graph.placement(id),
3382            },
3383            compiled: None,
3384            output_layout,
3385            destructive_input,
3386            output_bundle: None,
3387        });
3388    }
3389
3390    if matches!(node.op, Op::ZeroFill) {
3391        // Op::ZeroFill: 1 input (the buffer to zero); output aliases
3392        // input's Storage Arc (destructive in-place). No binding-
3393        // table lookup — per-backend dispatch in execute_work_item.
3394        if inputs.len() != 1 {
3395            return Err(Error::Msg(format!(
3396                "Op::ZeroFill expects 1 input, got {}",
3397                inputs.len(),
3398            ))
3399            .bt());
3400        }
3401        // Output layout: contiguous in the node's shape. We don't
3402        // require the input to be contiguous (auto_contiguize in the
3403        // executor handles strided inputs), but the destructive
3404        // semantic means callers should only ZeroFill an Op::Alloc
3405        // output today.
3406        let output_layout = Layout::contiguous(node.shape.clone());
3407        layout_cache.insert(id, output_layout.clone());
3408        let target_backend = graph
3409            .target_backend(id)
3410            .or_else(|| graph.target_backend(inputs[0]))
3411            .unwrap_or(BackendId::Cpu);
3412        return Ok(WorkItem {
3413            node_id: id,
3414            inputs,
3415            elem_count,
3416            dtype: node.dtype,
3417            target_backend,
3418            kind: WorkItemKind::ZeroFill,
3419            compiled: None,
3420            output_layout,
3421            destructive_input,
3422            output_bundle: None,
3423        });
3424    }
3425
3426    if let Op::Copy { target } = node.op {
3427        // Op::Copy { target }: download bytes from the source residency
3428        // to a fresh Storage allocated on `target`. Kernel lookup uses
3429        // `target_backend` = source backend (set by `prepare()` on the
3430        // realize device the source is on); the wrapper does the actual
3431        // transfer (e.g. Vulkan::download_bytes → memcpy into a CPU
3432        // CpuStorageBytes). The output Storage's variant is determined
3433        // by `target_location` and allocated in `execute_work_item`'s
3434        // WorkItemKind::Copy arm.
3435        if inputs.len() != 1 {
3436            return Err(
3437                Error::Msg(format!("Op::Copy expects 1 input, got {}", inputs.len(),)).bt(),
3438            );
3439        }
3440        let target_backend = graph.target_backend(id).ok_or_else(|| {
3441            Error::Msg(format!(
3442                "PipelinedExecutor: Op::Copy node {:?} has no target_backend \
3443                 set (= source backend, the one whose kernel runs the \
3444                 download)",
3445                id
3446            ))
3447            .bt()
3448        })?;
3449        let op_params = OpParams::None;
3450        let dtypes = build_lookup_dtypes(graph, node);
3451        let compiled = resolve_compiled(
3452            graph,
3453            node,
3454            OpKind::Copy,
3455            &dtypes,
3456            target_backend,
3457            op_params,
3458            bindings,
3459        )?;
3460        // Output layout: contiguous in the node's shape (mirrors the
3461        // source's logical shape). Auto-contiguize on the input side
3462        // (in execute_work_item) handles strided source views by
3463        // materializing them into a contiguous source buffer before
3464        // the kernel runs.
3465        let output_layout = Layout::contiguous(node.shape.clone());
3466        layout_cache.insert(id, output_layout.clone());
3467        return Ok(WorkItem {
3468            node_id: id,
3469            inputs,
3470            elem_count,
3471            dtype: node.dtype,
3472            target_backend,
3473            kind: WorkItemKind::Copy {
3474                target_location: target,
3475            },
3476            compiled: Some(compiled),
3477            output_layout,
3478            destructive_input,
3479            output_bundle: None,
3480        });
3481    }
3482
3483    if let Op::Move { target } = node.op {
3484        // Op::Move { target }: identical data-movement half to
3485        // Op::Copy — kernel lookup at (OpKind::Copy, [dt, dt],
3486        // source_backend); output allocated on `target` by the
3487        // executor's Copy/Move arm. The destructive half (release
3488        // the source) rides the realize loop's `destructive_input`
3489        // cleanup via the snapshot taken at the top of this function
3490        // (`Op::Move::destructive_input() == Some(0)`). Ordering
3491        // safety (a Move must not strand a sibling consumer of its
3492        // source) is `execution_plan`/`derive_ordering`'s job — the
3493        // Move is pinned after every non-destructive reader of the
3494        // source's alias set before any work item is emitted.
3495        if inputs.len() != 1 {
3496            return Err(
3497                Error::Msg(format!("Op::Move expects 1 input, got {}", inputs.len(),)).bt(),
3498            );
3499        }
3500        let target_backend = graph.target_backend(id).ok_or_else(|| {
3501            Error::Msg(format!(
3502                "PipelinedExecutor: Op::Move node {:?} has no target_backend \
3503                 set (= source backend, the one whose kernel runs the \
3504                 transfer)",
3505                id
3506            ))
3507            .bt()
3508        })?;
3509        let op_params = OpParams::None;
3510        let dtypes = build_lookup_dtypes(graph, node);
3511        let compiled = resolve_compiled(
3512            graph,
3513            node,
3514            OpKind::Copy,
3515            &dtypes,
3516            target_backend,
3517            op_params,
3518            bindings,
3519        )?;
3520        // Output layout: contiguous in the node's shape, same as
3521        // Op::Copy (the transfer materializes strided sources via
3522        // auto-contiguize on the input side).
3523        let output_layout = Layout::contiguous(node.shape.clone());
3524        layout_cache.insert(id, output_layout.clone());
3525        return Ok(WorkItem {
3526            node_id: id,
3527            inputs,
3528            elem_count,
3529            dtype: node.dtype,
3530            target_backend,
3531            kind: WorkItemKind::Move {
3532                target_location: target,
3533            },
3534            compiled: Some(compiled),
3535            output_layout,
3536            destructive_input,
3537            output_bundle: None,
3538        });
3539    }
3540
3541    if matches!(node.op, Op::Reshape(_)) {
3542        if inputs.len() != 1 {
3543            return Err(
3544                Error::Msg(format!("Op::Reshape expects 1 input, got {}", inputs.len(),)).bt(),
3545            );
3546        }
3547        let input_layout = graph.layout(inputs[0]);
3548        // Output is contiguous in the new shape — bytes per element
3549        // are unchanged, so a contiguous input flows through with
3550        // zero copy. A non-contiguous input is auto-contiguized at
3551        // execute time and the result is naturally contiguous.
3552        let output_layout = Layout::contiguous(node.shape.clone());
3553        layout_cache.insert(id, output_layout.clone());
3554        let target_backend = graph
3555            .target_backend(id)
3556            .or_else(|| graph.target_backend(inputs[0]))
3557            .unwrap_or(BackendId::Cpu);
3558        // Sanity: same total element count.
3559        let in_elem_count = input_layout.shape().elem_count();
3560        if in_elem_count != elem_count {
3561            return Err(Error::Msg(format!(
3562                "Op::Reshape changes element count: input {} → output {}",
3563                in_elem_count, elem_count,
3564            ))
3565            .bt());
3566        }
3567        return Ok(WorkItem {
3568            node_id: id,
3569            inputs,
3570            elem_count,
3571            dtype: node.dtype,
3572            target_backend,
3573            kind: WorkItemKind::ContiguizeOf {
3574                input: node.inputs[0],
3575            },
3576            compiled: None,
3577            output_layout,
3578            destructive_input,
3579            output_bundle: None,
3580        });
3581    }
3582
3583    if matches!(node.op, Op::Contiguize) {
3584        // Op::Contiguize: same execute-time path as Reshape, but
3585        // output shape == input shape so there's no element-count
3586        // check. Zero-copy when input is already contiguous +
3587        // zero-offset (the ContiguizeOf arm in execute_work_item
3588        // adopts the input Arc); otherwise auto_contiguize allocates
3589        // a fresh contiguous Storage on the input's backend.
3590        if inputs.len() != 1 {
3591            return Err(Error::Msg(format!(
3592                "Op::Contiguize expects 1 input, got {}",
3593                inputs.len(),
3594            ))
3595            .bt());
3596        }
3597        let output_layout = Layout::contiguous(node.shape.clone());
3598        layout_cache.insert(id, output_layout.clone());
3599        let target_backend = graph
3600            .target_backend(id)
3601            .or_else(|| graph.target_backend(inputs[0]))
3602            .unwrap_or(BackendId::Cpu);
3603        return Ok(WorkItem {
3604            node_id: id,
3605            inputs,
3606            elem_count,
3607            dtype: node.dtype,
3608            target_backend,
3609            kind: WorkItemKind::ContiguizeOf {
3610                input: node.inputs[0],
3611            },
3612            compiled: None,
3613            output_layout,
3614            destructive_input,
3615            output_bundle: None,
3616        });
3617    }
3618
3619    // Runtime fused op — a JIT-adopted (Tier-2) kernel. `Op::Fused(fid, _)`
3620    // with `fid.is_runtime()` has no `OpKind` (the op was synthesized after
3621    // startup): its kernel resolves from the SAME binding table as every
3622    // static kernel, under `BindingKey::RuntimeFused(fid)` — the dtype tuple
3623    // is the key, so an absent kernel AND a dtype mismatch are one honest
3624    // `NoBackendForOp` miss. A deterministic *lookup*, not a decision: the
3625    // optimizer's gate emitted the arm only when this kernel was bound, and
3626    // pinned `target_backend` (`runtime-fused-op-registration.md` §6). The
3627    // guards are invariant checks, never live fallbacks.
3628    if let Op::Fused(fid, _) = &node.op
3629        && fid.is_runtime()
3630    {
3631        let target_backend = graph.target_backend(id).ok_or_else(|| {
3632            Error::Msg(format!(
3633                "PipelinedExecutor: runtime fused op {:?} (node {:?}) has no \
3634                     target_backend — the arm emitter pins it at emission",
3635                fid, id,
3636            ))
3637            .bt()
3638        })?;
3639        // v1: single-output only. Reject a multi-output bundle explicitly
3640        // rather than silently dropping it.
3641        if graph.output_views_arc(id).is_some() {
3642            return Err(Error::Msg(format!(
3643                "PipelinedExecutor: runtime fused op {:?} (node {:?}) carries a \
3644                     multi-output bundle — synthesized kernels are single-output in v1",
3645                fid, id,
3646            ))
3647            .bt());
3648        }
3649        let dtypes = build_lookup_dtypes(graph, node);
3650        let (kernel, caps) = bindings.lookup_with_caps(
3651            crate::kernel::BindingKey::RuntimeFused(*fid),
3652            &dtypes,
3653            target_backend,
3654        )?;
3655        let output_layout = Layout::contiguous(node.shape.clone());
3656        layout_cache.insert(id, output_layout.clone());
3657        // Deliberate, not a fallthrough to `op_to_op_params` (which doesn't
3658        // know runtime ops): the node's `Runtime { scalars }` — the live
3659        // `extract:` values, pattern pre-order — becomes `JitScalars` (the
3660        // launch appends them as the kernel's trailing `p{i}` args); a
3661        // param-free op carries `None` (its launch is layout-driven:
3662        // pointers + element count).
3663        let op_params = match &node.op {
3664            Op::Fused(_, FusedOpParams::Runtime { scalars }) if !scalars.is_empty() => {
3665                OpParams::JitScalars {
3666                    scalars: scalars.clone(),
3667                }
3668            }
3669            _ => OpParams::None,
3670        };
3671        let compiled = CompiledNode {
3672            op: OpKind::RuntimeFused,
3673            dtypes: KernelDTypes::from_slice(&dtypes),
3674            backend: target_backend,
3675            kernel,
3676            caps,
3677            op_params,
3678            est_ns: 0,
3679        };
3680        return Ok(WorkItem {
3681            node_id: id,
3682            inputs,
3683            elem_count,
3684            dtype: node.dtype,
3685            target_backend,
3686            kind: WorkItemKind::Kernel,
3687            compiled: Some(compiled),
3688            output_layout,
3689            destructive_input,
3690            output_bundle: None,
3691        });
3692    }
3693
3694    let target_backend = graph.target_backend(id).ok_or_else(|| {
3695        Error::Msg(format!(
3696            "PipelinedExecutor: node {:?} ({:?}) has no target_backend set",
3697            id, node.op
3698        ))
3699        .bt()
3700    })?;
3701
3702    let op_kind = op_to_op_kind(&node.op).ok_or_else(|| {
3703        Error::Msg(format!(
3704            "PipelinedExecutor: op {:?} not yet mapped to an OpKind \
3705             (Phase C migrates more ops as they're registered)",
3706            node.op,
3707        ))
3708        .bt()
3709    })?;
3710
3711    let op_params = op_to_op_params(graph, node, id, layout_cache, sym_env)?;
3712    // Build the per-operand dtype list for the binding-table lookup —
3713    // inputs in order, then outputs. Variadic uniform-dtype ops
3714    // (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3715    // match how registrations index them.
3716    let dtypes = build_lookup_dtypes(graph, node);
3717    let compiled = resolve_compiled(
3718        graph,
3719        node,
3720        op_kind,
3721        &dtypes,
3722        target_backend,
3723        op_params,
3724        bindings,
3725    )?;
3726    let output_layout = Layout::contiguous(node.shape.clone());
3727    layout_cache.insert(id, output_layout.clone());
3728    // Multi-output: snapshot the producer's bundle metadata. When
3729    // `Some(_)`, the Kernel arm allocates a single Storage sized to
3730    // fit every slot and attaches the bundle via
3731    // `Storage::with_bundle` so downstream Op::View/Op::ViewOwned
3732    // resolve correctly.
3733    let output_bundle = graph.output_views_arc(id);
3734    Ok(WorkItem {
3735        node_id: id,
3736        inputs,
3737        elem_count,
3738        dtype: node.dtype,
3739        target_backend,
3740        kind: WorkItemKind::Kernel,
3741        compiled: Some(compiled),
3742        output_layout,
3743        destructive_input,
3744        output_bundle,
3745    })
3746}
3747
3748/// Build the per-operand dtype list used as the binding-table lookup
3749/// key. Inputs in order, then the output. Variadic-uniform ops
3750/// (Concat) collapse to the canonical `[T_in, T_out]` shorthand to
3751/// match how those wrappers are registered (otherwise an N-way concat
3752/// would need N+1 distinct registrations per dtype).
3753///
3754/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3755/// to key the route picker's binding-table lookup the same way the
3756/// pipelined path does.
3757pub(crate) fn build_lookup_dtypes(graph: &Graph, node: &Node) -> Vec<DType> {
3758    if matches!(node.op, Op::Concat { .. }) {
3759        // Concat: all inputs share node.dtype by construction.
3760        let in_dt = node
3761            .inputs
3762            .first()
3763            .map(|&id| graph.node(id).dtype)
3764            .unwrap_or(node.dtype);
3765        return vec![in_dt, node.dtype];
3766    }
3767    if matches!(node.op, Op::WriteSlice { .. }) {
3768        // WriteSlice: the destination (inputs[0]) is exposed to the
3769        // executor as the OUTPUT slot (in-place adoption), not as an
3770        // input the kernel reads. Canonicalize the binding-table key
3771        // to `[T_source, T_out]` so registrations match the kernel's
3772        // actual surface (one input slab + one output buffer).
3773        let src_dt = node
3774            .inputs
3775            .get(1)
3776            .map(|&id| graph.node(id).dtype)
3777            .unwrap_or(node.dtype);
3778        return vec![src_dt, node.dtype];
3779    }
3780    if matches!(node.op, Op::WriteSliceRotating { .. }) {
3781        // Same canonicalization as WriteSlice: dest = output slot;
3782        // position (inputs[2]) is read by the kernel via the
3783        // position-input parameter, not the binding-table key.
3784        let src_dt = node
3785            .inputs
3786            .get(1)
3787            .map(|&id| graph.node(id).dtype)
3788            .unwrap_or(node.dtype);
3789        return vec![src_dt, node.dtype];
3790    }
3791    if matches!(node.op, Op::WriteSliceDoff { .. }) {
3792        // Same canonicalization as WriteSlice: dest = output slot;
3793        // offset (inputs[2], I64) is a non-key runtime operand read by
3794        // the kernel via its device pointer, not the binding-table key.
3795        let src_dt = node
3796            .inputs
3797            .get(1)
3798            .map(|&id| graph.node(id).dtype)
3799            .unwrap_or(node.dtype);
3800        return vec![src_dt, node.dtype];
3801    }
3802    let mut dts: Vec<DType> = node.inputs.iter().map(|&id| graph.node(id).dtype).collect();
3803    dts.push(node.dtype);
3804    dts
3805}
3806
3807/// SoftmaxLastDim is reachable only through `Op::Fused(FusedOps::
3808/// SOFTMAX_LAST_DIM, _)` post-step-5 (the legacy `Op::SoftmaxLastDim`
3809/// primitive variant was retired). This helper collapses the
3810/// op-to-OpKind/OpParams shapes for callers that want a single-arm
3811/// match.
3812fn op_is_softmax_last_dim(op: &Op) -> bool {
3813    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM)
3814}
3815
3816/// FusedLinear is reachable only through `Op::Fused(FusedOps::
3817/// FUSED_LINEAR, _)` post-step-5.
3818fn op_is_fused_linear(op: &Op) -> bool {
3819    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR)
3820}
3821
3822/// RowScaledMatMul (row 172 item 1): `(a @ b) * row_scale`, reached only through
3823/// `Op::Fused(FusedOps::ROW_SCALED_MATMUL, _)`. Shares FusedLinear's
3824/// `OpParams::Matmul` params; its third input is the `[..., M, 1]` row scale.
3825fn op_is_row_scaled_matmul(op: &Op) -> bool {
3826    matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL)
3827}
3828
3829/// Does the executor have an arm that runs `op` on `backend`? Only for ops it dispatches DIRECTLY
3830/// (no binding-table kernel, so the planner cannot reject them for lack of a binding). `None` means
3831/// the op is not direct-dispatched and this answer does not apply (the binding table decides).
3832///
3833/// Source of truth for [`check_direct_arms_wired`]; keep in step with the `execute_work_item` arms.
3834pub(crate) fn direct_arm_wired(op: &Op, backend: BackendId) -> Option<bool> {
3835    match op {
3836        // CPU generates it; CUDA generates on the host and uploads (GAP-380 a2). The cuda arm is
3837        // compiled only with the `cuda` feature, and a CUDA stamp cannot arise without it.
3838        Op::Iota { .. } => Some(
3839            backend == BackendId::Cpu || (cfg!(feature = "cuda") && backend == BackendId::Cuda),
3840        ),
3841        _ => None,
3842    }
3843}
3844
3845/// Plan-time guard (PM, 2026-11-12): a node stamped for a backend whose executor has no arm for its
3846/// op fails HERE, with the node and op named, instead of as an `Err` inside the executor mid-run.
3847/// Run after the backend stamp. A graph with every arm wired is a no-op.
3848pub(crate) fn check_direct_arms_wired(graph: &Graph, roots: &[NodeId]) -> Result<()> {
3849    for id in fuel_graph::topo_order_multi(graph, roots) {
3850        let node = graph.node(id);
3851        let backend = graph.target_backend(id).unwrap_or(BackendId::Cpu);
3852        if direct_arm_wired(&node.op, backend) == Some(false) {
3853            return Err(Error::Msg(format!(
3854                "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)",
3855                id.0,
3856                node.op,
3857                node.shape,
3858                node.dtype,
3859            ))
3860            .bt());
3861        }
3862    }
3863    Ok(())
3864}
3865
3866/// Map a `fuel_graph::Op` to a `fuel_ir::dispatch::OpKind`.
3867/// Returns `None` for ops that haven't been wired into the new
3868/// dispatch path yet — Phase C extends this as op families migrate.
3869///
3870/// `pub(crate)` — `crate::plan::compile_plan` (step 9b) reuses this
3871/// to skip nodes the binding-table doesn't index (view ops,
3872/// `Op::Const`, not-yet-migrated ops) when building bindings.
3873pub(crate) fn op_to_op_kind(op: &Op) -> Option<OpKind> {
3874    match op {
3875        Op::Add => Some(OpKind::AddElementwise),
3876        Op::Sub => Some(OpKind::SubElementwise),
3877        Op::Mul => Some(OpKind::MulElementwise),
3878        Op::Div => Some(OpKind::DivElementwise),
3879        Op::Relu => Some(OpKind::ReluElementwise),
3880        Op::Neg => Some(OpKind::NegElementwise),
3881        Op::Sqr => Some(OpKind::SqrElementwise),
3882        Op::Sqrt => Some(OpKind::SqrtElementwise),
3883        Op::Tanh => Some(OpKind::TanhElementwise),
3884        Op::Exp => Some(OpKind::ExpElementwise),
3885        Op::Log => Some(OpKind::LogElementwise),
3886        Op::Sin => Some(OpKind::SinElementwise),
3887        Op::Cos => Some(OpKind::CosElementwise),
3888        Op::Sigmoid => Some(OpKind::SigmoidElementwise),
3889        Op::Silu => Some(OpKind::SiluElementwise),
3890        Op::GeluTanh => Some(OpKind::GeluTanhElementwise),
3891        Op::Step => Some(OpKind::StepElementwise),
3892        Op::Recip => Some(OpKind::RecipElementwise),
3893        Op::Abs => Some(OpKind::AbsElementwise),
3894        Op::Equal => Some(OpKind::EqualElementwise),
3895        Op::Ne => Some(OpKind::NotEqualElementwise),
3896        Op::Lt => Some(OpKind::LessElementwise),
3897        Op::Le => Some(OpKind::LessEqualElementwise),
3898        Op::Gt => Some(OpKind::GreaterElementwise),
3899        Op::Ge => Some(OpKind::GreaterEqualElementwise),
3900        Op::Where => Some(OpKind::Where),
3901        Op::Floor => Some(OpKind::FloorElementwise),
3902        Op::Ceil => Some(OpKind::CeilElementwise),
3903        Op::Round => Some(OpKind::RoundElementwise),
3904        Op::Sign => Some(OpKind::SignElementwise),
3905        Op::Erf => Some(OpKind::ErfElementwise),
3906        Op::Gelu => Some(OpKind::GeluElementwise),
3907        Op::Pow => Some(OpKind::PowElementwise),
3908        Op::Rsqrt => Some(OpKind::RsqrtElementwise),
3909        Op::Rem => Some(OpKind::RemElementwise),
3910        Op::Flip { .. } => Some(OpKind::Flip),
3911        Op::Roll { .. } => Some(OpKind::Roll),
3912        Op::CumSum { .. } => Some(OpKind::CumSum),
3913        Op::Triu { .. } => Some(OpKind::Triu),
3914        Op::Tril { .. } => Some(OpKind::Tril),
3915        Op::LogSoftmaxLastDim => Some(OpKind::LogSoftmaxLastDim),
3916        Op::LogSoftmaxLastDimBackward => Some(OpKind::LogSoftmaxLastDimBackward),
3917        Op::MaskedFill { .. } => Some(OpKind::MaskedFill),
3918        Op::Pad { .. } => Some(OpKind::Pad),
3919        Op::PadBackward { .. } => Some(OpKind::PadBackward),
3920        Op::SumDim(_) => Some(OpKind::SumReduce),
3921        Op::MaxDim(_) => Some(OpKind::MaxReduce),
3922        Op::MinDim(_) => Some(OpKind::MinReduce),
3923        Op::MeanDim(_) => Some(OpKind::MeanReduce),
3924        Op::SumAll => Some(OpKind::SumReduce),
3925        Op::MaxAll => Some(OpKind::MaxReduce),
3926        Op::MinAll => Some(OpKind::MinReduce),
3927        Op::MeanAll => Some(OpKind::MeanReduce),
3928        Op::MatMul => Some(OpKind::MatMul),
3929        Op::Cast(_) => Some(OpKind::Cast),
3930        // Phase 7.6 step 5: fused-op dispatch routes through
3931        // `Op::Fused(fid, _)`; the legacy `Op::Conv2D` /
3932        // `Op::FusedLinear` / `Op::SoftmaxLastDim` /
3933        // `Op::RmsNormLastDim` / `Op::LayerNormLastDim` / `Op::Rope`
3934        // arms were dropped together with the variants.
3935        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV2D => Some(OpKind::Conv2D),
3936        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` /
3937        // `Op::FlashAttn` / `Op::PagedAttn` arms dropped with the
3938        // variants; dispatch flows only through `Op::Fused`.
3939        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D => {
3940            Some(OpKind::ConvTranspose2D)
3941        }
3942        Op::ReduceSumTo(_) => Some(OpKind::ReduceSumTo),
3943        Op::ReduceMaxTo(_) => Some(OpKind::ReduceMaxTo),
3944        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FLASH_ATTN => {
3945            Some(OpKind::FlashAttn)
3946        }
3947        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::PAGED_ATTN => {
3948            Some(OpKind::PagedAttn)
3949        }
3950        Op::AddScalar(_) => Some(OpKind::Affine),
3951        Op::MulScalar(_) => Some(OpKind::Affine),
3952        Op::Clamp { .. } => Some(OpKind::ClampElementwise),
3953        Op::PowI(_) => Some(OpKind::PowIElementwise),
3954        Op::Maximum => Some(OpKind::MaximumElementwise),
3955        Op::Minimum => Some(OpKind::MinimumElementwise),
3956        Op::Concat { .. } => Some(OpKind::Concat),
3957        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM => {
3958            Some(OpKind::SoftmaxLastDim)
3959        }
3960        // Phase 7.6 step 6 follow-up: backward helpers now route
3961        // through the byte-level binding table too.
3962        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD => {
3963            Some(OpKind::SoftmaxLastDimBackward)
3964        }
3965        Op::Fused(fid, _)
3966            if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
3967        {
3968            Some(OpKind::LayerNormLastDimBackward)
3969        }
3970        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD => {
3971            Some(OpKind::RmsNormLastDimBackward)
3972        }
3973        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
3974            Some(OpKind::ReduceMaxToBackward)
3975        }
3976        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::POWI_BACKWARD => {
3977            Some(OpKind::PowIElementwiseBackward)
3978        }
3979        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::FUSED_LINEAR => {
3980            Some(OpKind::FusedLinear)
3981        }
3982        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL => {
3983            Some(OpKind::RowScaledMatMul)
3984        }
3985        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::TOP_K_LAST_DIM => {
3986            Some(OpKind::TopKLastDim)
3987        }
3988        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::MATMUL_TOP_K => {
3989            Some(OpKind::MatMulTopK)
3990        }
3991        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM => {
3992            Some(OpKind::RmsNormLastDim)
3993        }
3994        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM => {
3995            Some(OpKind::LayerNormLastDim)
3996        }
3997        Op::IndexSelect { .. } => Some(OpKind::IndexSelect),
3998        Op::Gather { .. } => Some(OpKind::Gather),
3999        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::ROPE => Some(OpKind::Rope),
4000        Op::IndexAdd { .. } => Some(OpKind::IndexAdd),
4001        Op::ScatterAdd { .. } => Some(OpKind::ScatterAdd),
4002        Op::NonZeroIndices { .. } => Some(OpKind::NonZeroIndices),
4003        Op::ArgMaxDim(_) => Some(OpKind::ArgMaxDim),
4004        Op::ArgMinDim(_) => Some(OpKind::ArgMinDim),
4005        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
4006        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::QMATMUL => {
4007            Some(OpKind::QMatMul)
4008        }
4009        Op::WriteSlice { .. } => Some(OpKind::WriteSlice),
4010        Op::WriteSliceRotating { .. } => Some(OpKind::WriteSliceRotating),
4011        Op::WriteSliceDoff { .. } => Some(OpKind::WriteSliceDoff),
4012        // Phase 2 of bridge-retirement (post-9c): Op::Copy dispatches
4013        // through the binding table at OpKind::Copy. The BackendId
4014        // axis encodes the source backend (the kernel runs there —
4015        // download from local memory). The executor handles output
4016        // allocation on the target via a dedicated WorkItemKind::Copy
4017        // arm, since target_location differs from target_backend for
4018        // this op (the only one with that property today).
4019        Op::Copy { .. } => Some(OpKind::Copy),
4020        // Op::Move dispatches the same data-movement kernel as
4021        // Op::Copy — the destructive release of the source is
4022        // realize-loop bookkeeping (`destructive_input` cleanup), not
4023        // a kernel. Same OpKind, same source-backend key convention.
4024        // `compile_plan` skips both (residency-determined, not a
4025        // picker decision).
4026        Op::Move { .. } => Some(OpKind::Copy),
4027        // Phase 3 of the in-place ops infrastructure: each in-place Op
4028        // variant maps to its OpKind so the binding-table dispatch can
4029        // resolve a kernel. The executor's dedicated WorkItemKind
4030        // arms (added alongside) handle the storage-Arc adoption.
4031        Op::ReluInplace => Some(OpKind::ReluInplace),
4032        Op::SiluInplace => Some(OpKind::SiluInplace),
4033        Op::GeluTanhInplace => Some(OpKind::GeluTanhInplace),
4034        Op::TanhInplace => Some(OpKind::TanhInplace),
4035        Op::SigmoidInplace => Some(OpKind::SigmoidInplace),
4036        Op::NegInplace => Some(OpKind::NegInplace),
4037        Op::AbsInplace => Some(OpKind::AbsInplace),
4038        Op::SqrInplace => Some(OpKind::SqrInplace),
4039        Op::SqrtInplace => Some(OpKind::SqrtInplace),
4040        Op::RsqrtInplace => Some(OpKind::RsqrtInplace),
4041        Op::RecipInplace => Some(OpKind::RecipInplace),
4042        Op::ExpInplace => Some(OpKind::ExpInplace),
4043        Op::LogInplace => Some(OpKind::LogInplace),
4044        Op::SinInplace => Some(OpKind::SinInplace),
4045        Op::CosInplace => Some(OpKind::CosInplace),
4046        Op::SignInplace => Some(OpKind::SignInplace),
4047        Op::FloorInplace => Some(OpKind::FloorInplace),
4048        Op::CeilInplace => Some(OpKind::CeilInplace),
4049        Op::RoundInplace => Some(OpKind::RoundInplace),
4050        Op::ErfInplace => Some(OpKind::ErfInplace),
4051        Op::GeluInplace => Some(OpKind::GeluInplace),
4052        Op::ClampInplace { .. } => Some(OpKind::ClampInplace),
4053        Op::PowIInplace(_) => Some(OpKind::PowIInplace),
4054        // In-place binary variants (Add/Sub/Mul/Div/MaskedFill) and
4055        // their OpKind siblings are tracked by a parallel session and
4056        // toggle in and out of the Op enum as that work progresses.
4057        // No multi-output arm references them; nothing to map here in
4058        // the current HEAD.
4059        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::INPLACE_AFFINE => {
4060            Some(OpKind::InplaceAffine)
4061        }
4062        Op::Fused(fid, _)
4063            if *fid == fuel_graph::registry::FusedOps::FUSED_SOFTMAX_CROSS_ENTROPY =>
4064        {
4065            Some(OpKind::FusedSoftmaxCrossEntropy)
4066        }
4067        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::CAUSAL_CONV1D => {
4068            Some(OpKind::CausalConv1d)
4069        }
4070        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SELECTIVE_SCAN => {
4071            Some(OpKind::SelectiveScan)
4072        }
4073        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SSD_CHUNK_SCAN => {
4074            Some(OpKind::SsdChunkScan)
4075        }
4076        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::NF4_MATMUL => {
4077            Some(OpKind::Nf4Matmul)
4078        }
4079        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::AWQ_MATMUL => {
4080            Some(OpKind::AwqMatmul)
4081        }
4082        // Phase 3a (post-9c): Op::Alloc + Op::ZeroFill are structural
4083        // ops dispatched directly via `WorkItemKind::Alloc` /
4084        // `WorkItemKind::ZeroFill` (no binding-table lookup).
4085        // `compile_plan` skips these.
4086        Op::Alloc { .. } | Op::ZeroFill => None,
4087        _ => None,
4088    }
4089}
4090
4091/// Build the [`OpParams`] for `node`'s op. Most ops use
4092/// `OpParams::None`; reductions / matmul / conv / slice carry their
4093/// op-specific extras here. The graph is consulted to read input
4094/// shapes (e.g. reductions need the input shape to walk the
4095/// multi-index — Storage only carries bytes + dtype).
4096///
4097/// Phase C — extends as op families migrate. Returns Err if a
4098/// graph-shape lookup fails (currently can't, but the signature is
4099/// `Result` so future cases needing validation slot in cleanly).
4100/// Encode an `f64` value into the byte pattern of `dtype`. Used by
4101/// `Op::Pad` (Constant mode) to pre-convert the fill value once at
4102/// op_params time, so the kernel itself stays dtype-agnostic.
4103fn encode_value_to_bytes(dtype: DType, value: f64) -> Result<Vec<u8>> {
4104    match dtype {
4105        DType::F32 => Ok((value as f32).to_le_bytes().to_vec()),
4106        DType::F64 => Ok(value.to_le_bytes().to_vec()),
4107        DType::BF16 => Ok(half::bf16::from_f32(value as f32).to_le_bytes().to_vec()),
4108        DType::F16 => Ok(half::f16::from_f32(value as f32).to_le_bytes().to_vec()),
4109        DType::U8 => Ok(vec![value as u8]),
4110        DType::U32 => Ok((value as u32).to_le_bytes().to_vec()),
4111        other => Err(Error::Msg(format!(
4112            "encode_value_to_bytes: dtype {other:?} not yet supported for Pad fill",
4113        ))
4114        .bt()),
4115    }
4116}
4117
4118/// Encode a typed `Scalar` to its little-endian byte representation.
4119/// Used by Op::MaskedFill so the kernel only sees bytes — never has
4120/// to know the value's dtype.
4121fn scalar_to_bytes(s: fuel_ir::Scalar) -> Vec<u8> {
4122    use fuel_ir::Scalar;
4123    match s {
4124        Scalar::U8(v) => vec![v],
4125        Scalar::I8(v) => vec![v as u8],
4126        Scalar::U32(v) => v.to_le_bytes().to_vec(),
4127        Scalar::I16(v) => v.to_le_bytes().to_vec(),
4128        Scalar::I32(v) => v.to_le_bytes().to_vec(),
4129        Scalar::I64(v) => v.to_le_bytes().to_vec(),
4130        Scalar::BF16(v) => v.to_le_bytes().to_vec(),
4131        Scalar::F16(v) => v.to_le_bytes().to_vec(),
4132        Scalar::F32(v) => v.to_le_bytes().to_vec(),
4133        Scalar::F64(v) => v.to_le_bytes().to_vec(),
4134        Scalar::Bool(b) => vec![b as u8],
4135        Scalar::F8E4M3(v) => vec![v.to_bits()],
4136        Scalar::F8E5M2(v) => vec![v.to_bits()],
4137        // OCP-MX E8M0 block scale is a raw byte on the wire (`2^(X-127)`,
4138        // decoded kernel-side); a single byte is its own LE encoding.
4139        Scalar::F8E8M0(v) => vec![v],
4140    }
4141}
4142
4143fn op_to_op_params(
4144    graph: &Graph,
4145    node: &Node,
4146    node_id: NodeId,
4147    layout_cache: &HashMap<NodeId, Layout>,
4148    sym_env: &SymEnv,
4149) -> Result<OpParams> {
4150    // Helper: read an input's layout from the compiler-thread-local
4151    // cache (which is current within the realize call), falling back
4152    // to the graph's side-table if the input wasn't visited (which
4153    // shouldn't happen in topo order, but the fallback keeps the
4154    // path safe).
4155    let input_layout = |input_id: NodeId| -> Layout {
4156        layout_cache
4157            .get(&input_id)
4158            .cloned()
4159            .unwrap_or_else(|| graph.layout(input_id))
4160    };
4161    Ok(match &node.op {
4162        // Phase 7.6 step 5 (final): legacy `Op::QMatMul` arm dropped.
4163        Op::Fused(_, fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n }) => {
4164            // Inputs: (activations f32 [..., m, k], weight_bytes
4165            // u32-typed). Output shape (this Node's shape) is
4166            // [..., m, n]. Flatten leading dims into batch_count.
4167            if node.inputs.len() != 2 {
4168                return Err(Error::Msg(format!(
4169                    "Op::QMatMul expects 2 inputs (activations, weight_bytes), got {}",
4170                    node.inputs.len(),
4171                ))
4172                .bt());
4173            }
4174            let act_layout = input_layout(node.inputs[0]);
4175            let act_dims = act_layout.shape().dims();
4176            if act_dims.len() < 2 {
4177                return Err(Error::Msg(format!(
4178                    "Op::QMatMul: activations must be rank ≥ 2, got {act_dims:?}",
4179                ))
4180                .bt());
4181            }
4182            let m = act_dims[act_dims.len() - 2];
4183            let k_act = act_dims[act_dims.len() - 1];
4184            if k_act != *k {
4185                return Err(Error::Msg(format!(
4186                    "Op::QMatMul: activation last dim ({k_act}) must equal Op's k ({k})",
4187                ))
4188                .bt());
4189            }
4190            let batch_count: usize = act_dims[..act_dims.len() - 2].iter().product();
4191            OpParams::QMatMul {
4192                quant_type: *quant_type,
4193                batch_count,
4194                m,
4195                n: *n,
4196                k: *k,
4197            }
4198        }
4199        Op::ArgMaxDim(d) | Op::ArgMinDim(d) => {
4200            // Reuse OpParams::Reduce — same shape contract; the
4201            // single reduce dim is the argmax/argmin axis. Input
4202            // layout flows through KernelRef's `layouts[0]`.
4203            OpParams::Reduce {
4204                dims: vec![*d],
4205                keepdim: false,
4206            }
4207        }
4208        Op::SumDim(d) | Op::MaxDim(d) | Op::MinDim(d) | Op::MeanDim(d) => OpParams::Reduce {
4209            dims: vec![*d],
4210            keepdim: false,
4211        },
4212        Op::SumAll | Op::MaxAll | Op::MinAll | Op::MeanAll => {
4213            let il = input_layout(node.inputs[0]);
4214            let rank = il.shape().rank();
4215            OpParams::Reduce {
4216                dims: (0..rank).collect(),
4217                keepdim: false,
4218            }
4219        }
4220        Op::MatMul => {
4221            // Batched matmul: lhs `[..lhs_batch.., m, k]` @
4222            // rhs `[..rhs_batch.., k, n]` → out `[..lhs_batch.., m, n]`.
4223            // Per-axis the batch dims either match or follow GQA-style
4224            // divisibility (lhs_dim > rhs_dim && lhs_dim % rhs_dim == 0);
4225            // the kernel honors the latter via `rhs_idx = lhs_idx / n_rep`.
4226            if node.inputs.len() != 2 {
4227                return Err(Error::Msg(format!(
4228                    "Op::MatMul expects 2 inputs, got {}",
4229                    node.inputs.len(),
4230                ))
4231                .bt());
4232            }
4233            let lhs = input_layout(node.inputs[0]);
4234            let rhs = input_layout(node.inputs[1]);
4235            let lhs_dims = lhs.shape().dims();
4236            let rhs_dims = rhs.shape().dims();
4237            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4238                return Err(Error::Msg(format!(
4239                    "Op::MatMul requires both inputs rank ≥ 2; got lhs={:?} rhs={:?}",
4240                    lhs_dims, rhs_dims,
4241                ))
4242                .bt());
4243            }
4244            if lhs_dims.len() != rhs_dims.len() {
4245                return Err(Error::Msg(format!(
4246                    "Op::MatMul: ranks must match (auto-broadcast happens at \
4247                     graph construction time); got lhs rank {} vs rhs rank {}",
4248                    lhs_dims.len(),
4249                    rhs_dims.len(),
4250                ))
4251                .bt());
4252            }
4253            let rank = lhs_dims.len();
4254            let batch_rank = rank - 2;
4255            // Per-axis validation: equal or GQA-divisible.
4256            for i in 0..batch_rank {
4257                let la = lhs_dims[i];
4258                let ra = rhs_dims[i];
4259                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4260                if !ok {
4261                    return Err(Error::Msg(format!(
4262                        "Op::MatMul: batch dim {i} disallowed combination \
4263                         (lhs={la}, rhs={ra}); must be equal or \
4264                         GQA-divisible (lhs > rhs && lhs % rhs == 0)",
4265                    ))
4266                    .bt());
4267                }
4268            }
4269            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4270            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4271            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4272            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4273            if k_lhs != k_rhs {
4274                return Err(Error::Msg(format!(
4275                    "Op::MatMul: contracting dims disagree — lhs trailing is \
4276                     [{m}, {k_lhs}], rhs trailing is [{k_rhs}, {n}]",
4277                ))
4278                .bt());
4279            }
4280            // Data-determined-M (sparse-MoE): a side-table row count makes
4281            // `m` the capacity and this the compute count. Dual-path,
4282            // mirroring WriteSlice: resolve in the compile-time SymEnv
4283            // (static / input-determined) now; else DEFER a producer-bound
4284            // sym to execute; else it is a genuine caller error.
4285            let m_compute = match graph.matmul_row_count(node_id) {
4286                None => MatmulM::All,
4287                Some(dyn_m) => match dyn_m.resolve(sym_env) {
4288                    Some(c) => {
4289                        if c > m {
4290                            return Err(Error::Msg(format!(
4291                                "Op::MatMul: resolved row count {c} exceeds capacity {m}",
4292                            ))
4293                            .bt());
4294                        }
4295                        MatmulM::Rows(c)
4296                    }
4297                    None => match dyn_m {
4298                        fuel_ir::DynScalar::Sym(s) if graph.binds_data_determined_sym(s) => {
4299                            MatmulM::Deferred(dyn_m)
4300                        }
4301                        _ => {
4302                            return Err(Error::Msg(format!(
4303                                "Op::MatMul: dynamic row count {dyn_m:?} is unbound in the \
4304                                 SymEnv at compile and no producer binds it (not \
4305                                 data-determined)",
4306                            ))
4307                            .bt());
4308                        }
4309                    },
4310                },
4311            };
4312            OpParams::Matmul {
4313                lhs_batch_dims,
4314                rhs_batch_dims,
4315                m,
4316                n,
4317                k: k_lhs,
4318                m_compute,
4319            }
4320        }
4321        // Phase 7.6 step 4: legacy `Op::FusedLinear` and registry-extended
4322        // `Op::Fused(FUSED_LINEAR, _)` share the same shape contract and
4323        // params encoding (reuses OpParams::Matmul). One body covers both.
4324        op if op_is_fused_linear(op) || op_is_row_scaled_matmul(op) => {
4325            // Inputs: [a, b, bias]. Same shape semantics as MatMul on
4326            // a/b; bias is rank-1 [N] and broadcasts along all leading
4327            // dims. We reuse OpParams::Matmul (kernel reads bias from
4328            // inputs[2] directly).
4329            if node.inputs.len() != 3 {
4330                return Err(Error::Msg(format!(
4331                    "Op::FusedLinear expects 3 inputs (a, b, bias), got {}",
4332                    node.inputs.len(),
4333                ))
4334                .bt());
4335            }
4336            let lhs = input_layout(node.inputs[0]);
4337            let rhs = input_layout(node.inputs[1]);
4338            let bias = input_layout(node.inputs[2]);
4339            let lhs_dims = lhs.shape().dims();
4340            let rhs_dims = rhs.shape().dims();
4341            let bias_dims = bias.shape().dims();
4342            if lhs_dims.len() < 2 || rhs_dims.len() < 2 {
4343                return Err(Error::Msg(format!(
4344                    "Op::FusedLinear requires both a, b rank ≥ 2; got a={:?} b={:?}",
4345                    lhs_dims, rhs_dims,
4346                ))
4347                .bt());
4348            }
4349            if lhs_dims.len() != rhs_dims.len() {
4350                return Err(Error::Msg(format!(
4351                    "Op::FusedLinear: ranks must match (auto-broadcast happens at \
4352                     graph construction time); got a rank {} vs b rank {}",
4353                    lhs_dims.len(),
4354                    rhs_dims.len(),
4355                ))
4356                .bt());
4357            }
4358            let rank = lhs_dims.len();
4359            let batch_rank = rank - 2;
4360            for i in 0..batch_rank {
4361                let la = lhs_dims[i];
4362                let ra = rhs_dims[i];
4363                let ok = la == ra || (ra > 0 && la > ra && la % ra == 0);
4364                if !ok {
4365                    return Err(Error::Msg(format!(
4366                        "Op::FusedLinear: batch dim {i} disallowed (a={la}, b={ra})",
4367                    ))
4368                    .bt());
4369                }
4370            }
4371            let lhs_batch_dims: Vec<usize> = lhs_dims[..batch_rank].to_vec();
4372            let rhs_batch_dims: Vec<usize> = rhs_dims[..batch_rank].to_vec();
4373            let (m, k_lhs) = (lhs_dims[rank - 2], lhs_dims[rank - 1]);
4374            let (k_rhs, n) = (rhs_dims[rank - 2], rhs_dims[rank - 1]);
4375            if k_lhs != k_rhs {
4376                return Err(Error::Msg(format!(
4377                    "Op::FusedLinear: contracting dims disagree — a trailing is \
4378                     [{m}, {k_lhs}], b trailing is [{k_rhs}, {n}]",
4379                ))
4380                .bt());
4381            }
4382            if op_is_row_scaled_matmul(&node.op) {
4383                // The row scale is `[..lhs batch, M, 1]`.
4384                let mut want = lhs_batch_dims.clone();
4385                want.push(m);
4386                want.push(1);
4387                if bias_dims != want.as_slice() {
4388                    return Err(Error::Msg(format!(
4389                        "Op::RowScaledMatMul: row_scale must be {want:?}, got {bias_dims:?}",
4390                    ))
4391                    .bt());
4392                }
4393            } else if bias_dims.len() != 1 || bias_dims[0] != n {
4394                return Err(Error::Msg(format!(
4395                    "Op::FusedLinear: bias must be rank-1 [{n}], got {bias_dims:?}",
4396                ))
4397                .bt());
4398            }
4399            OpParams::Matmul {
4400                lhs_batch_dims,
4401                rhs_batch_dims,
4402                m,
4403                n,
4404                k: k_lhs,
4405                // FusedLinear is always static-M (dense linear layer).
4406                m_compute: MatmulM::All,
4407            }
4408        }
4409        // FusedSoftmaxCrossEntropy: flatten logits `[..., V]` to
4410        // `[n_rows, V]` for the kernel. n_rows is the product of all
4411        // leading dims (≥1 even for rank-1 logits, where targets are
4412        // a scalar). The kernel walks rows internally.
4413        Op::Fused(
4414            _,
4415            fuel_graph::registry::FusedOpParams::FusedSoftmaxCrossEntropy {
4416                reduction,
4417                ignore_index,
4418            },
4419        ) => {
4420            if node.inputs.len() != 2 {
4421                return Err(Error::Msg(format!(
4422                    "FusedSoftmaxCrossEntropy expects 2 inputs (logits, targets), got {}",
4423                    node.inputs.len(),
4424                ))
4425                .bt());
4426            }
4427            let logits_layout = input_layout(node.inputs[0]);
4428            let logits_dims = logits_layout.shape().dims();
4429            if logits_dims.is_empty() {
4430                return Err(Error::Msg(
4431                    "FusedSoftmaxCrossEntropy: logits must have rank ≥ 1".to_string(),
4432                )
4433                .bt());
4434            }
4435            let vocab = *logits_dims.last().unwrap();
4436            let n_rows: usize = logits_dims[..logits_dims.len() - 1]
4437                .iter()
4438                .product::<usize>()
4439                .max(1);
4440            let targets_layout = input_layout(node.inputs[1]);
4441            let target_count: usize = targets_layout
4442                .shape()
4443                .dims()
4444                .iter()
4445                .product::<usize>()
4446                .max(1);
4447            if target_count != n_rows {
4448                return Err(Error::Msg(format!(
4449                    "FusedSoftmaxCrossEntropy: targets element count {target_count} must \
4450                     equal logits row count {n_rows} (logits {logits_dims:?}, targets {:?})",
4451                    targets_layout.shape().dims(),
4452                ))
4453                .bt());
4454            }
4455            OpParams::FusedSoftmaxCrossEntropy {
4456                n_rows,
4457                vocab,
4458                reduction: *reduction,
4459                ignore_index: *ignore_index,
4460            }
4461        }
4462        // CausalConv1d: derive (batch, channels, seq_in, seq_out, kernel)
4463        // from the input layouts. x is `[batch, channels, seq_in]`
4464        // (caller pre-pads with kernel-1 zeros), weight is
4465        // `[channels, 1, kernel]`. seq_out = seq_in - (kernel - 1).
4466        Op::Fused(_, fuel_graph::registry::FusedOpParams::CausalConv1d { use_silu }) => {
4467            if node.inputs.len() != 3 {
4468                return Err(Error::Msg(format!(
4469                    "CausalConv1d expects 3 inputs (x, weight, bias), got {}",
4470                    node.inputs.len(),
4471                ))
4472                .bt());
4473            }
4474            let x_layout = input_layout(node.inputs[0]);
4475            let w_layout = input_layout(node.inputs[1]);
4476            let x_dims = x_layout.shape().dims();
4477            let w_dims = w_layout.shape().dims();
4478            if x_dims.len() != 3 {
4479                return Err(Error::Msg(format!(
4480                    "CausalConv1d: x must be rank 3 [batch, channels, seq+pad], got {x_dims:?}",
4481                ))
4482                .bt());
4483            }
4484            if w_dims.len() != 3 {
4485                return Err(Error::Msg(format!(
4486                    "CausalConv1d: weight must be rank 3 [channels, 1, kernel], got {w_dims:?}",
4487                ))
4488                .bt());
4489            }
4490            let batch = x_dims[0];
4491            let channels = x_dims[1];
4492            let seq_in = x_dims[2];
4493            let kernel = w_dims[2];
4494            if seq_in < kernel - 1 {
4495                return Err(Error::Msg(format!(
4496                    "CausalConv1d: x time dim {seq_in} must be ≥ kernel-1 = {} \
4497                     (caller must pre-pad with kernel-1 zeros)",
4498                    kernel - 1,
4499                ))
4500                .bt());
4501            }
4502            let seq_out = seq_in - (kernel - 1);
4503            OpParams::CausalConv1d {
4504                batch,
4505                channels,
4506                seq_in,
4507                seq_out,
4508                kernel,
4509                use_silu: *use_silu,
4510            }
4511        }
4512        // SelectiveScan: derive (batch, seqlen, dim, dstate) from the
4513        // input layouts. u: [batch, seqlen, dim]; a: [dim, dstate].
4514        Op::Fused(_, fuel_graph::registry::FusedOpParams::SelectiveScan { delta_softplus }) => {
4515            if node.inputs.len() != 5 {
4516                return Err(Error::Msg(format!(
4517                    "SelectiveScan expects 5 inputs (u, delta, a, b, c), got {}",
4518                    node.inputs.len(),
4519                ))
4520                .bt());
4521            }
4522            let u_layout = input_layout(node.inputs[0]);
4523            let a_layout = input_layout(node.inputs[2]);
4524            let u_dims = u_layout.shape().dims();
4525            let a_dims = a_layout.shape().dims();
4526            if u_dims.len() != 3 {
4527                return Err(Error::Msg(format!(
4528                    "SelectiveScan: u must be rank 3 [batch, seqlen, dim], got {u_dims:?}",
4529                ))
4530                .bt());
4531            }
4532            if a_dims.len() != 2 {
4533                return Err(Error::Msg(format!(
4534                    "SelectiveScan: a must be rank 2 [dim, dstate], got {a_dims:?}",
4535                ))
4536                .bt());
4537            }
4538            let batch = u_dims[0];
4539            let seqlen = u_dims[1];
4540            let dim = u_dims[2];
4541            let dstate = a_dims[1];
4542            if a_dims[0] != dim {
4543                return Err(Error::Msg(format!(
4544                    "SelectiveScan: a's first dim {} must equal dim {dim}",
4545                    a_dims[0],
4546                ))
4547                .bt());
4548            }
4549            OpParams::SelectiveScan {
4550                batch,
4551                seqlen,
4552                dim,
4553                dstate,
4554                delta_softplus: *delta_softplus,
4555            }
4556        }
4557        // SsdChunkScan: derive (batch, seqlen, heads, head_dim,
4558        // state_dim) from x and b layouts. x: [batch, seqlen, heads,
4559        // head_dim]; b: [batch, seqlen, heads, state_dim].
4560        Op::Fused(_, fuel_graph::registry::FusedOpParams::SsdChunkScan { chunk_size }) => {
4561            if node.inputs.len() != 5 {
4562                return Err(Error::Msg(format!(
4563                    "SsdChunkScan expects 5 inputs (x, dt, a, b, c), got {}",
4564                    node.inputs.len(),
4565                ))
4566                .bt());
4567            }
4568            let x_layout = input_layout(node.inputs[0]);
4569            let b_layout = input_layout(node.inputs[3]);
4570            let x_dims = x_layout.shape().dims();
4571            let b_dims = b_layout.shape().dims();
4572            if x_dims.len() != 4 {
4573                return Err(Error::Msg(format!(
4574                    "SsdChunkScan: x must be rank 4 [batch, seqlen, heads, head_dim], got {x_dims:?}",
4575                ))
4576                .bt());
4577            }
4578            if b_dims.len() != 4 {
4579                return Err(Error::Msg(format!(
4580                    "SsdChunkScan: b must be rank 4 [batch, seqlen, heads, state_dim], got {b_dims:?}",
4581                ))
4582                .bt());
4583            }
4584            let batch = x_dims[0];
4585            let seqlen = x_dims[1];
4586            let heads = x_dims[2];
4587            let head_dim = x_dims[3];
4588            let state_dim = b_dims[3];
4589            OpParams::SsdChunkScan {
4590                batch,
4591                seqlen,
4592                heads,
4593                head_dim,
4594                state_dim,
4595                chunk_size: *chunk_size,
4596            }
4597        }
4598        // Nf4Matmul: derive (batch, m, n, k) from activations + w_packed
4599        // layouts. activations: [..., m, k] (leading dims flatten into
4600        // batch); w_packed: [n, k/2] U8.
4601        Op::Fused(_, fuel_graph::registry::FusedOpParams::Nf4Matmul { block_size }) => {
4602            if node.inputs.len() != 3 {
4603                return Err(Error::Msg(format!(
4604                    "Nf4Matmul expects 3 inputs (activations, w_packed, absmax), got {}",
4605                    node.inputs.len(),
4606                ))
4607                .bt());
4608            }
4609            let a_layout = input_layout(node.inputs[0]);
4610            let w_layout = input_layout(node.inputs[1]);
4611            let a_dims = a_layout.shape().dims();
4612            let w_dims = w_layout.shape().dims();
4613            if a_dims.len() < 2 {
4614                return Err(Error::Msg(format!(
4615                    "Nf4Matmul: activations must be rank ≥ 2, got {a_dims:?}",
4616                ))
4617                .bt());
4618            }
4619            if w_dims.len() != 2 {
4620                return Err(Error::Msg(format!(
4621                    "Nf4Matmul: w_packed must be rank 2 [n, k/2], got {w_dims:?}",
4622                ))
4623                .bt());
4624            }
4625            let m = a_dims[a_dims.len() - 2];
4626            let k = a_dims[a_dims.len() - 1];
4627            let n = w_dims[0];
4628            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4629            if k % 2 != 0 {
4630                return Err(Error::Msg(format!(
4631                    "Nf4Matmul: k={k} must be even (w_packed holds 2 nibbles per byte along k)",
4632                ))
4633                .bt());
4634            }
4635            if k % *block_size != 0 {
4636                return Err(Error::Msg(format!(
4637                    "Nf4Matmul: k={k} must be a multiple of block_size={block_size}",
4638                ))
4639                .bt());
4640            }
4641            if w_dims[1] != k / 2 {
4642                return Err(Error::Msg(format!(
4643                    "Nf4Matmul: w_packed second dim {} must equal k/2 = {}",
4644                    w_dims[1],
4645                    k / 2,
4646                ))
4647                .bt());
4648            }
4649            OpParams::Nf4Matmul {
4650                batch,
4651                m,
4652                n,
4653                k,
4654                block_size: *block_size,
4655            }
4656        }
4657        // TopKLastDim (row 172 item 2): `rows` = product of the leading dims,
4658        // `n` = the last axis, `k` from the node's params (validated at build time).
4659        Op::Fused(fid, fp) if *fid == fuel_graph::registry::FusedOps::TOP_K_LAST_DIM => {
4660            let fuel_graph::registry::FusedOpParams::TopKLastDim { k } = fp else {
4661                return Err(Error::Msg(format!(
4662                    "TopKLastDim: expected FusedOpParams::TopKLastDim, got {fp:?}"
4663                ))
4664                .bt());
4665            };
4666            if node.inputs.len() != 1 {
4667                return Err(Error::Msg(format!(
4668                    "TopKLastDim expects 1 input, got {}",
4669                    node.inputs.len()
4670                ))
4671                .bt());
4672            }
4673            let x = input_layout(node.inputs[0]);
4674            let dims = x.shape().dims();
4675            let Some((&n, lead)) = dims.split_last() else {
4676                return Err(Error::Msg("TopKLastDim: input must be rank >= 1".to_string()).bt());
4677            };
4678            if *k == 0 || *k > n {
4679                return Err(Error::Msg(format!("TopKLastDim: k = {k} must be in 1..={n}")).bt());
4680            }
4681            OpParams::TopKLastDim {
4682                rows: lead.iter().product::<usize>().max(1),
4683                n,
4684                k: *k,
4685            }
4686        }
4687        // MatMulTopK (row 172 item 2 step B): a [.., m, k] @ b [.., k, n], equal
4688        // batch dims, then top_k over n.
4689        Op::Fused(fid, fp) if *fid == fuel_graph::registry::FusedOps::MATMUL_TOP_K => {
4690            let fuel_graph::registry::FusedOpParams::MatMulTopK { k: top_k } = fp else {
4691                return Err(Error::Msg(format!(
4692                    "MatMulTopK: expected FusedOpParams::MatMulTopK, got {fp:?}"
4693                ))
4694                .bt());
4695            };
4696            if node.inputs.len() != 2 {
4697                return Err(Error::Msg(format!(
4698                    "MatMulTopK expects 2 inputs (a, b), got {}",
4699                    node.inputs.len()
4700                ))
4701                .bt());
4702            }
4703            let a = input_layout(node.inputs[0]);
4704            let b = input_layout(node.inputs[1]);
4705            let (ad, bd) = (a.shape().dims(), b.shape().dims());
4706            if ad.len() < 2 || ad.len() != bd.len() || ad[..ad.len() - 2] != bd[..bd.len() - 2] {
4707                return Err(Error::Msg(format!(
4708                    "MatMulTopK: a {ad:?} and b {bd:?} need equal rank >= 2 and equal batch dims"
4709                ))
4710                .bt());
4711            }
4712            let r = ad.len();
4713            let (m, k) = (ad[r - 2], ad[r - 1]);
4714            let (k2, n) = (bd[r - 2], bd[r - 1]);
4715            if k != k2 {
4716                return Err(Error::Msg(format!(
4717                    "MatMulTopK: contracting dims disagree (a trailing [{m}, {k}], b trailing [{k2}, {n}])"
4718                ))
4719                .bt());
4720            }
4721            if *top_k == 0 || *top_k > n {
4722                return Err(Error::Msg(format!("MatMulTopK: k = {top_k} must be in 1..={n}")).bt());
4723            }
4724            OpParams::MatMulTopK {
4725                batch: ad[..r - 2].iter().product::<usize>().max(1),
4726                m,
4727                n,
4728                k,
4729                top_k: *top_k,
4730            }
4731        }
4732        // AwqMatmul: (batch, m, n, k) from activations [..., m, k] and the
4733        // kernel-layout weight [n, k/8]; the padded zeros/scales widths are the
4734        // op's own build-time invariant (checked by `awq_matmul`).
4735        Op::Fused(
4736            _,
4737            fuel_graph::registry::FusedOpParams::AwqMatmul {
4738                group_size,
4739                split_k_iters,
4740            },
4741        ) => {
4742            if node.inputs.len() != 4 {
4743                return Err(Error::Msg(format!(
4744                    "AwqMatmul expects 4 inputs (activations, weight, zeros, scales), got {}",
4745                    node.inputs.len(),
4746                ))
4747                .bt());
4748            }
4749            let a_layout = input_layout(node.inputs[0]);
4750            let w_layout = input_layout(node.inputs[1]);
4751            let a_dims = a_layout.shape().dims();
4752            let w_dims = w_layout.shape().dims();
4753            if a_dims.len() < 2 {
4754                return Err(Error::Msg(format!(
4755                    "AwqMatmul: activations must be rank ≥ 2, got {a_dims:?}",
4756                ))
4757                .bt());
4758            }
4759            if w_dims.len() != 2 {
4760                return Err(Error::Msg(format!(
4761                    "AwqMatmul: weight must be rank 2 [n, k/8], got {w_dims:?}",
4762                ))
4763                .bt());
4764            }
4765            let m = a_dims[a_dims.len() - 2];
4766            let k = a_dims[a_dims.len() - 1];
4767            let n = w_dims[0];
4768            let batch: usize = a_dims[..a_dims.len() - 2].iter().product::<usize>().max(1);
4769            if k % 8 != 0 || w_dims[1] != k / 8 {
4770                return Err(Error::Msg(format!(
4771                    "AwqMatmul: weight second dim {} must equal k/8 for k={k} (a multiple of 8)",
4772                    w_dims[1],
4773                ))
4774                .bt());
4775            }
4776            OpParams::AwqMatmul {
4777                batch,
4778                m,
4779                n,
4780                k,
4781                group_size: *group_size,
4782                split_k_iters: *split_k_iters,
4783            }
4784        }
4785        // Phase 7.6 step 3: SoftmaxLastDim flows through
4786        // `Op::Fused(FusedOps::SOFTMAX_LAST_DIM, _)`. The
4787        // SOFTMAX_LAST_DIM_BACKWARD variant added in step 6
4788        // follow-up shares the same `outer × last_dim` shape
4789        // contract (input 0 is `y` for forward / forward-output
4790        // for backward; both rank-≥1 with last-dim as the
4791        // reduction axis).
4792        op if op_is_softmax_last_dim(op)
4793            || matches!(op, Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM_BACKWARD) =>
4794        {
4795            let il = input_layout(node.inputs[0]);
4796            let dims = il.shape().dims();
4797            if dims.is_empty() {
4798                return Err(Error::Msg("Op::SoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4799            }
4800            let last_dim = *dims.last().unwrap();
4801            let outer_count: usize = dims[..dims.len() - 1].iter().product();
4802            OpParams::SoftmaxLastDim {
4803                outer_count,
4804                last_dim,
4805            }
4806        }
4807        Op::Flip { dim } => {
4808            // Single input. Precompute the flat-3-axis split
4809            // (outer × dim × inner) from the input shape.
4810            if node.inputs.len() != 1 {
4811                return Err(Error::Msg(format!(
4812                    "Op::Flip expects 1 input, got {}",
4813                    node.inputs.len(),
4814                ))
4815                .bt());
4816            }
4817            let in_layout = input_layout(node.inputs[0]);
4818            let in_dims = in_layout.shape().dims();
4819            if *dim >= in_dims.len() {
4820                return Err(Error::Msg(format!(
4821                    "Op::Flip: dim {dim} out of range for rank {}",
4822                    in_dims.len(),
4823                ))
4824                .bt());
4825            }
4826            let outer_count: usize = in_dims[..*dim].iter().product();
4827            let dim_size = in_dims[*dim];
4828            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4829            OpParams::Flip {
4830                outer_count,
4831                dim_size,
4832                inner_count,
4833                axis: *dim,
4834            }
4835        }
4836        Op::Roll { dim, shift } => {
4837            if node.inputs.len() != 1 {
4838                return Err(Error::Msg(format!(
4839                    "Op::Roll expects 1 input, got {}",
4840                    node.inputs.len(),
4841                ))
4842                .bt());
4843            }
4844            let in_layout = input_layout(node.inputs[0]);
4845            let in_dims = in_layout.shape().dims();
4846            if *dim >= in_dims.len() {
4847                return Err(Error::Msg(format!(
4848                    "Op::Roll: dim {dim} out of range for rank {}",
4849                    in_dims.len(),
4850                ))
4851                .bt());
4852            }
4853            let outer_count: usize = in_dims[..*dim].iter().product();
4854            let dim_size = in_dims[*dim];
4855            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4856            OpParams::Roll {
4857                outer_count,
4858                dim_size,
4859                inner_count,
4860                shift: *shift,
4861                axis: *dim,
4862            }
4863        }
4864        Op::CumSum { dim } => {
4865            if node.inputs.len() != 1 {
4866                return Err(Error::Msg(format!(
4867                    "Op::CumSum expects 1 input, got {}",
4868                    node.inputs.len(),
4869                ))
4870                .bt());
4871            }
4872            let in_layout = input_layout(node.inputs[0]);
4873            let in_dims = in_layout.shape().dims();
4874            if *dim >= in_dims.len() {
4875                return Err(Error::Msg(format!(
4876                    "Op::CumSum: dim {dim} out of range for rank {}",
4877                    in_dims.len(),
4878                ))
4879                .bt());
4880            }
4881            let outer_count: usize = in_dims[..*dim].iter().product();
4882            let dim_size = in_dims[*dim];
4883            let inner_count: usize = in_dims[*dim + 1..].iter().product();
4884            OpParams::CumSum {
4885                outer_count,
4886                dim_size,
4887                inner_count,
4888                axis: *dim,
4889            }
4890        }
4891        Op::Triu { diagonal } | Op::Tril { diagonal } => {
4892            if node.inputs.len() != 1 {
4893                return Err(Error::Msg(format!(
4894                    "Op::Triu/Tril expects 1 input, got {}",
4895                    node.inputs.len(),
4896                ))
4897                .bt());
4898            }
4899            let in_layout = input_layout(node.inputs[0]);
4900            let in_dims = in_layout.shape().dims();
4901            if in_dims.len() < 2 {
4902                return Err(Error::Msg(format!(
4903                    "Op::Triu/Tril requires rank >= 2, got {}",
4904                    in_dims.len(),
4905                ))
4906                .bt());
4907            }
4908            let rows = in_dims[in_dims.len() - 2];
4909            let cols = in_dims[in_dims.len() - 1];
4910            let batch_count: usize = in_dims[..in_dims.len() - 2]
4911                .iter()
4912                .product::<usize>()
4913                .max(1);
4914            OpParams::Triangular {
4915                batch_count,
4916                rows,
4917                cols,
4918                diagonal: *diagonal,
4919            }
4920        }
4921        Op::LogSoftmaxLastDim => {
4922            if node.inputs.len() != 1 {
4923                return Err(Error::Msg(format!(
4924                    "Op::LogSoftmaxLastDim expects 1 input, got {}",
4925                    node.inputs.len(),
4926                ))
4927                .bt());
4928            }
4929            let in_layout = input_layout(node.inputs[0]);
4930            let in_dims = in_layout.shape().dims();
4931            if in_dims.is_empty() {
4932                return Err(Error::Msg("Op::LogSoftmaxLastDim requires rank ≥ 1".to_string()).bt());
4933            }
4934            let last_dim = *in_dims.last().unwrap();
4935            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4936            OpParams::LogSoftmaxLastDim {
4937                outer_count,
4938                last_dim,
4939            }
4940        }
4941        Op::LogSoftmaxLastDimBackward => {
4942            // Inputs: (forward_output_y, upstream_grad). Same shape contract
4943            // as SoftmaxLastDimBackward — last-dim row-wise dispatch.
4944            if node.inputs.len() != 2 {
4945                return Err(Error::Msg(format!(
4946                    "Op::LogSoftmaxLastDimBackward expects 2 inputs, got {}",
4947                    node.inputs.len(),
4948                ))
4949                .bt());
4950            }
4951            let in_layout = input_layout(node.inputs[0]);
4952            let in_dims = in_layout.shape().dims();
4953            if in_dims.is_empty() {
4954                return Err(Error::Msg(
4955                    "Op::LogSoftmaxLastDimBackward requires rank ≥ 1".to_string(),
4956                )
4957                .bt());
4958            }
4959            let last_dim = *in_dims.last().unwrap();
4960            let outer_count: usize = in_dims[..in_dims.len() - 1].iter().product();
4961            OpParams::LogSoftmaxLastDim {
4962                outer_count,
4963                last_dim,
4964            }
4965        }
4966        Op::MaskedFill { value } => {
4967            if node.inputs.len() != 2 {
4968                return Err(Error::Msg(format!(
4969                    "Op::MaskedFill expects 2 inputs (x, mask), got {}",
4970                    node.inputs.len(),
4971                ))
4972                .bt());
4973            }
4974            let fill_bytes = scalar_to_bytes(*value);
4975            OpParams::MaskedFill { fill_bytes }
4976        }
4977        // Op::MaskedFillInplace tracked by the parallel in-place
4978        // binary family session — not in HEAD's Op enum right now.
4979        Op::PadBackward {
4980            in_shape,
4981            padding,
4982            mode,
4983        } => {
4984            // Single input is the upstream gradient; output is the
4985            // input gradient (shape == `in_shape`).
4986            if node.inputs.len() != 1 {
4987                return Err(Error::Msg(format!(
4988                    "Op::PadBackward expects 1 input, got {}",
4989                    node.inputs.len(),
4990                ))
4991                .bt());
4992            }
4993            let in_dims: Vec<usize> = in_shape.dims().to_vec();
4994            // Output of the original forward Pad is the input shape
4995            // of the backward (== upstream's shape).
4996            let out_dims: Vec<usize> = in_dims
4997                .iter()
4998                .zip(padding.iter())
4999                .map(|(&d, &(b, a))| d + b + a)
5000                .collect();
5001            let mode_tag: u8 = match mode {
5002                fuel_graph::PadMode::Constant => 0,
5003                fuel_graph::PadMode::Reflect => 1,
5004                fuel_graph::PadMode::Replicate => 2,
5005            };
5006            OpParams::PadBackward {
5007                in_shape: in_dims,
5008                out_shape: out_dims,
5009                padding: padding.clone(),
5010                mode_tag,
5011            }
5012        }
5013        Op::Pad {
5014            padding,
5015            mode,
5016            value,
5017        } => {
5018            if node.inputs.len() != 1 {
5019                return Err(Error::Msg(format!(
5020                    "Op::Pad expects 1 input, got {}",
5021                    node.inputs.len(),
5022                ))
5023                .bt());
5024            }
5025            let in_layout = input_layout(node.inputs[0]);
5026            let in_dims: Vec<usize> = in_layout.shape().dims().to_vec();
5027            if padding.len() != in_dims.len() {
5028                return Err(Error::Msg(format!(
5029                    "Op::Pad: padding.len() ({}) != input rank ({})",
5030                    padding.len(),
5031                    in_dims.len(),
5032                ))
5033                .bt());
5034            }
5035            let out_dims: Vec<usize> = in_dims
5036                .iter()
5037                .zip(padding.iter())
5038                .map(|(&d, &(b, a))| d + b + a)
5039                .collect();
5040            let mode_tag: u8 = match mode {
5041                fuel_graph::PadMode::Constant => 0,
5042                fuel_graph::PadMode::Reflect => 1,
5043                fuel_graph::PadMode::Replicate => 2,
5044            };
5045            // Encode fill value as bytes for the output dtype. The
5046            // kernel is dtype-agnostic — it just memcopies the
5047            // pattern. Conversion happens once here per node, not
5048            // per element in the kernel.
5049            let fill_bytes = encode_value_to_bytes(node.dtype, *value)?;
5050            OpParams::Pad {
5051                in_shape: in_dims,
5052                out_shape: out_dims,
5053                padding: padding.clone(),
5054                mode_tag,
5055                fill_bytes,
5056            }
5057        }
5058        Op::IndexAdd { dim } => {
5059            // Inputs: (base, indices, src). All same dtype except
5060            // indices is U32. Output shape == base shape.
5061            if node.inputs.len() != 3 {
5062                return Err(Error::Msg(format!(
5063                    "Op::IndexAdd expects 3 inputs (base, indices, src), got {}",
5064                    node.inputs.len(),
5065                ))
5066                .bt());
5067            }
5068            let base_layout = input_layout(node.inputs[0]);
5069            let idx_layout = input_layout(node.inputs[1]);
5070            let src_layout = input_layout(node.inputs[2]);
5071            let base_dims = base_layout.shape().dims();
5072            let idx_dims = idx_layout.shape().dims();
5073            let src_dims = src_layout.shape().dims();
5074            if *dim >= base_dims.len() {
5075                return Err(Error::Msg(format!(
5076                    "Op::IndexAdd: dim {dim} out of range for base rank {}",
5077                    base_dims.len(),
5078                ))
5079                .bt());
5080            }
5081            if idx_dims.len() != 1 {
5082                return Err(Error::Msg(format!(
5083                    "Op::IndexAdd: indices must be rank 1, got {idx_dims:?}",
5084                ))
5085                .bt());
5086            }
5087            if base_dims.len() != src_dims.len() {
5088                return Err(Error::Msg(format!(
5089                    "Op::IndexAdd: base rank ({}) != src rank ({})",
5090                    base_dims.len(),
5091                    src_dims.len(),
5092                ))
5093                .bt());
5094            }
5095            let outer_count: usize = base_dims[..*dim].iter().product();
5096            let base_dim_size = base_dims[*dim];
5097            let inner_count: usize = base_dims[*dim + 1..].iter().product();
5098            let n_indices = idx_dims[0];
5099            OpParams::IndexAdd {
5100                outer_count,
5101                base_dim_size,
5102                n_indices,
5103                inner_count,
5104            }
5105        }
5106        Op::ScatterAdd { dim } => {
5107            if node.inputs.len() != 3 {
5108                return Err(Error::Msg(format!(
5109                    "Op::ScatterAdd expects 3 inputs (base, indices, src), got {}",
5110                    node.inputs.len(),
5111                ))
5112                .bt());
5113            }
5114            let base_layout = input_layout(node.inputs[0]);
5115            let src_layout = input_layout(node.inputs[2]);
5116            let base_shape: Vec<usize> = base_layout.shape().dims().to_vec();
5117            let src_shape: Vec<usize> = src_layout.shape().dims().to_vec();
5118            if base_shape.len() != src_shape.len() {
5119                return Err(Error::Msg(format!(
5120                    "Op::ScatterAdd: base rank ({}) != src rank ({})",
5121                    base_shape.len(),
5122                    src_shape.len(),
5123                ))
5124                .bt());
5125            }
5126            if *dim >= base_shape.len() {
5127                return Err(Error::Msg(format!(
5128                    "Op::ScatterAdd: dim {dim} out of range for rank {}",
5129                    base_shape.len(),
5130                ))
5131                .bt());
5132            }
5133            OpParams::ScatterAdd {
5134                base_shape,
5135                src_shape,
5136                dim: *dim,
5137            }
5138        }
5139        // Phase 7.6 step 5: Rope routes through the registry; the
5140        // legacy `Op::Rope` arm was retired with the variant.
5141        Op::Fused(_, fuel_graph::registry::FusedOpParams::Rope) => {
5142            // Inputs: (x, cos, sin). x is [..., seq, head_dim];
5143            // cos/sin are [seq, head_dim] (validated at graph build).
5144            if node.inputs.len() != 3 {
5145                return Err(Error::Msg(format!(
5146                    "Op::Rope expects 3 inputs (x, cos, sin), got {}",
5147                    node.inputs.len(),
5148                ))
5149                .bt());
5150            }
5151            let x_layout = input_layout(node.inputs[0]);
5152            let x_dims = x_layout.shape().dims();
5153            if x_dims.len() < 2 {
5154                return Err(
5155                    Error::Msg(format!("Op::Rope: x must have rank ≥ 2, got {x_dims:?}",)).bt(),
5156                );
5157            }
5158            let head_dim = *x_dims.last().unwrap();
5159            let seq = x_dims[x_dims.len() - 2];
5160            let outer_count: usize = x_dims[..x_dims.len() - 2].iter().product();
5161            OpParams::Rope {
5162                outer_count,
5163                seq,
5164                head_dim,
5165            }
5166        }
5167        Op::Gather { dim } => {
5168            // inputs[0] = source, inputs[1] = U32 indices (same rank).
5169            if node.inputs.len() != 2 {
5170                return Err(Error::Msg(format!(
5171                    "Op::Gather expects 2 inputs (source, indices), got {}",
5172                    node.inputs.len(),
5173                ))
5174                .bt());
5175            }
5176            let src_layout = input_layout(node.inputs[0]);
5177            let idx_layout = input_layout(node.inputs[1]);
5178            let source_shape: Vec<usize> = src_layout.shape().dims().to_vec();
5179            let output_shape: Vec<usize> = idx_layout.shape().dims().to_vec();
5180            if source_shape.len() != output_shape.len() {
5181                return Err(Error::Msg(format!(
5182                    "Op::Gather: source rank ({}) != indices rank ({})",
5183                    source_shape.len(),
5184                    output_shape.len(),
5185                ))
5186                .bt());
5187            }
5188            if *dim >= source_shape.len() {
5189                return Err(Error::Msg(format!(
5190                    "Op::Gather: dim {dim} out of range for rank {}",
5191                    source_shape.len(),
5192                ))
5193                .bt());
5194            }
5195            OpParams::Gather {
5196                source_shape,
5197                output_shape,
5198                dim: *dim,
5199            }
5200        }
5201        Op::NonZeroIndices { count_sym } => {
5202            // inputs[0] = x (the value tensor). capacity == x.elem_count();
5203            // the bundled output is [indices [capacity] U32 ; count [1] U32].
5204            if node.inputs.len() != 1 {
5205                return Err(Error::Msg(format!(
5206                    "Op::NonZeroIndices expects 1 input, got {}",
5207                    node.inputs.len(),
5208                ))
5209                .bt());
5210            }
5211            let x_layout = input_layout(node.inputs[0]);
5212            let capacity = x_layout.shape().elem_count();
5213            OpParams::NonZeroIndices {
5214                capacity,
5215                count_sym: *count_sym,
5216            }
5217        }
5218        Op::IndexSelect { dim } => {
5219            // inputs[0] = source, inputs[1] = U32 indices (rank 1).
5220            if node.inputs.len() != 2 {
5221                return Err(Error::Msg(format!(
5222                    "Op::IndexSelect expects 2 inputs (source, indices), got {}",
5223                    node.inputs.len(),
5224                ))
5225                .bt());
5226            }
5227            let src_layout = input_layout(node.inputs[0]);
5228            let idx_layout = input_layout(node.inputs[1]);
5229            let src_dims = src_layout.shape().dims();
5230            let idx_dims = idx_layout.shape().dims();
5231            if *dim >= src_dims.len() {
5232                return Err(Error::Msg(format!(
5233                    "Op::IndexSelect: dim {dim} out of range for source rank {}",
5234                    src_dims.len(),
5235                ))
5236                .bt());
5237            }
5238            if idx_dims.len() != 1 {
5239                return Err(Error::Msg(format!(
5240                    "Op::IndexSelect: indices must be rank 1, got shape {idx_dims:?}",
5241                ))
5242                .bt());
5243            }
5244            let outer_count: usize = src_dims[..*dim].iter().product();
5245            let source_dim_size = src_dims[*dim];
5246            let inner_count: usize = src_dims[*dim + 1..].iter().product();
5247            let n_indices = idx_dims[0];
5248            OpParams::IndexSelect {
5249                outer_count,
5250                source_dim_size,
5251                n_indices,
5252                inner_count,
5253            }
5254        }
5255        // Phase 7.6 step 5: legacy `Op::RmsNormLastDim` /
5256        // `Op::LayerNormLastDim` arms retired with the variants;
5257        // both now route through `Op::Fused(NORM_LAST_DIM, _)`.
5258        // Step 6 follow-up extends this arm to also cover the
5259        // backward variants (same outer × last_dim + eps geometry).
5260        Op::Fused(fid, params)
5261            if *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM
5262                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM
5263                || *fid == fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM_BACKWARD
5264                || *fid == fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM_BACKWARD =>
5265        {
5266            let eps = match params {
5267                fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps } => *eps,
5268                fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps } => *eps,
5269                fuel_graph::registry::FusedOpParams::RmsNormLastDimBackward { eps } => *eps,
5270                fuel_graph::registry::FusedOpParams::LayerNormLastDimBackward { eps } => *eps,
5271                _ => {
5272                    return Err(Error::Msg(format!(
5273                        "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) expected \
5274                     RmsNormLastDim[Backward] or LayerNormLastDim[Backward] params, got {params:?}",
5275                    ))
5276                    .bt());
5277                }
5278            };
5279            let il = input_layout(node.inputs[0]);
5280            let dims = il.shape().dims();
5281            if dims.is_empty() {
5282                return Err(Error::Msg(
5283                    "Op::Fused(NORM_LAST_DIM[_BACKWARD], _) requires rank ≥ 1".to_string(),
5284                )
5285                .bt());
5286            }
5287            let last_dim = *dims.last().unwrap();
5288            let outer_count: usize = dims[..dims.len() - 1].iter().product();
5289            OpParams::NormLastDim {
5290                outer_count,
5291                last_dim,
5292                eps,
5293            }
5294        }
5295        // ReduceMaxToBackward: shape pair via the new
5296        // OpParams::ReduceMaxToBackward variant. x's shape is
5297        // `input_shape`; upstream's shape is `output_shape`.
5298        Op::Fused(fid, _) if *fid == fuel_graph::registry::FusedOps::REDUCE_MAX_TO_BACKWARD => {
5299            if node.inputs.len() != 2 {
5300                return Err(Error::Msg(format!(
5301                    "Op::Fused(REDUCE_MAX_TO_BACKWARD) expects 2 inputs, got {}",
5302                    node.inputs.len(),
5303                ))
5304                .bt());
5305            }
5306            let x_layout = input_layout(node.inputs[0]);
5307            let up_layout = input_layout(node.inputs[1]);
5308            let input_shape: Vec<usize> = x_layout.shape().dims().to_vec();
5309            let output_shape: Vec<usize> = up_layout.shape().dims().to_vec();
5310            OpParams::ReduceMaxToBackward {
5311                input_shape,
5312                output_shape,
5313            }
5314        }
5315        Op::Concat { dim } => {
5316            // Output's shape: [..., total_dim, ...]. Compute outer
5317            // and inner counts from output_shape[..dim] and
5318            // [dim+1..]; per-input dim sizes from each input's
5319            // layout shape at index `dim`.
5320            if node.inputs.is_empty() {
5321                return Err(Error::Msg("Op::Concat requires at least 1 input".to_string()).bt());
5322            }
5323            let out_dims = node.shape.dims();
5324            if *dim >= out_dims.len() {
5325                return Err(Error::Msg(format!(
5326                    "Op::Concat: dim {dim} out of range for output rank {}",
5327                    out_dims.len(),
5328                ))
5329                .bt());
5330            }
5331            let outer_count: usize = out_dims[..*dim].iter().product();
5332            let inner_count: usize = out_dims[*dim + 1..].iter().product();
5333            let mut input_dim_sizes: Vec<usize> = Vec::with_capacity(node.inputs.len());
5334            for in_id in &node.inputs {
5335                let il = input_layout(*in_id);
5336                let il_dims = il.shape().dims();
5337                if *dim >= il_dims.len() {
5338                    return Err(Error::Msg(format!(
5339                        "Op::Concat: input {in_id:?} has rank {} but concat dim is {dim}",
5340                        il_dims.len(),
5341                    ))
5342                    .bt());
5343                }
5344                input_dim_sizes.push(il_dims[*dim]);
5345            }
5346            OpParams::Concat {
5347                outer_count,
5348                input_dim_sizes,
5349                inner_count,
5350                axis: *dim,
5351            }
5352        }
5353        Op::AddScalar(c) => OpParams::Affine { mul: 1.0, add: *c },
5354        Op::MulScalar(c) => OpParams::Affine { mul: *c, add: 0.0 },
5355        Op::Clamp { min, max } => OpParams::Clamp {
5356            min: *min,
5357            max: *max,
5358        },
5359        Op::PowI(exp) => OpParams::PowI { exp: *exp },
5360        Op::ClampInplace { min, max } => OpParams::Clamp {
5361            min: *min,
5362            max: *max,
5363        },
5364        Op::PowIInplace(exp) => OpParams::PowI { exp: *exp },
5365        // PowI backward — `(x, upstream) → grad_x = exp · x^(exp-1) ·
5366        // upstream`. Pulls the same `exp` as the forward through
5367        // FusedOpParams::PowIBackward (autograd carries it across).
5368        Op::Fused(_, fuel_graph::registry::FusedOpParams::PowIBackward { exp }) => {
5369            OpParams::PowI { exp: *exp }
5370        }
5371        // In-place affine (Phase 3 of the in-place ops infrastructure):
5372        // reuse the existing `OpParams::Affine` payload — the kernel
5373        // side doesn't care whether the destination is fresh or aliases
5374        // the input; the structural decision lives in the executor's
5375        // dedicated `WorkItemKind::InplaceKernel` arm.
5376        Op::Fused(_, fuel_graph::registry::FusedOpParams::InplaceAffine { mul, add }) => {
5377            OpParams::Affine {
5378                mul: *mul,
5379                add: *add,
5380            }
5381        }
5382        // Phase 7.6 step 5: legacy `Op::Conv2D` arm retired with the
5383        // variant; Conv2D routes through `Op::Fused(CONV2D, _)`.
5384        Op::Fused(
5385            _,
5386            fuel_graph::registry::FusedOpParams::Conv2D {
5387                stride,
5388                padding,
5389                groups,
5390            },
5391        ) => {
5392            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5393            // [Cout, Cin/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5394            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5395            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5396                return Err(Error::Msg(format!(
5397                    "Op::Conv2D expects 2 or 3 inputs, got {}",
5398                    node.inputs.len(),
5399                ))
5400                .bt());
5401            }
5402            let x_layout = input_layout(node.inputs[0]);
5403            let w_layout = input_layout(node.inputs[1]);
5404            let x_dims = x_layout.shape().dims();
5405            let w_dims = w_layout.shape().dims();
5406            if x_dims.len() != 4 || w_dims.len() != 4 {
5407                return Err(Error::Msg(format!(
5408                    "Op::Conv2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5409                ))
5410                .bt());
5411            }
5412            let out_dims = node.shape.dims();
5413            if out_dims.len() != 4 {
5414                return Err(Error::Msg(format!(
5415                    "Op::Conv2D output must be rank 4, got {out_dims:?}",
5416                ))
5417                .bt());
5418            }
5419            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5420            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5421            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5422            OpParams::Conv2D {
5423                x_shape,
5424                w_shape,
5425                out_shape,
5426                stride: *stride,
5427                padding: *padding,
5428                dilation: (1, 1),
5429                groups: *groups,
5430            }
5431        }
5432        // Phase 7.6 step 5 (final): legacy `Op::PagedAttn` arm dropped.
5433        Op::Fused(
5434            _,
5435            fuel_graph::registry::FusedOpParams::PagedAttn {
5436                softmax_scale,
5437                block_size,
5438                softcap,
5439            },
5440        ) => {
5441            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k_cache [num_blocks,
5442            // block_size, Hkv, D], inputs[2]=v_cache same shape,
5443            // inputs[3]=block_table [B, max_blocks_per_seq] U32,
5444            // inputs[4]=context_lens [B] U32, inputs[5]=alibi [Hq] (optional).
5445            if node.inputs.len() != 5 && node.inputs.len() != 6 {
5446                return Err(Error::Msg(format!(
5447                    "Op::PagedAttn expects 5 or 6 inputs, got {}",
5448                    node.inputs.len(),
5449                ))
5450                .bt());
5451            }
5452            let q_layout = input_layout(node.inputs[0]);
5453            let kc_layout = input_layout(node.inputs[1]);
5454            let vc_layout = input_layout(node.inputs[2]);
5455            let bt_layout = input_layout(node.inputs[3]);
5456            let q_dims = q_layout.shape().dims();
5457            let kc_dims = kc_layout.shape().dims();
5458            let vc_dims = vc_layout.shape().dims();
5459            let bt_dims = bt_layout.shape().dims();
5460            if q_dims.len() != 4 || kc_dims.len() != 4 || vc_dims.len() != 4 {
5461                return Err(Error::Msg(format!(
5462                    "Op::PagedAttn requires rank-4 q/k_cache/v_cache; \
5463                     got q={q_dims:?} k_cache={kc_dims:?} v_cache={vc_dims:?}",
5464                ))
5465                .bt());
5466            }
5467            if kc_dims != vc_dims {
5468                return Err(Error::Msg(format!(
5469                    "Op::PagedAttn: k_cache {kc_dims:?} and v_cache {vc_dims:?} must match",
5470                ))
5471                .bt());
5472            }
5473            if bt_dims.len() != 2 {
5474                return Err(Error::Msg(format!(
5475                    "Op::PagedAttn: block_table must be rank 2 [B, max_blocks_per_seq], got {bt_dims:?}",
5476                ))
5477                .bt());
5478            }
5479            if kc_dims[1] != *block_size {
5480                return Err(Error::Msg(format!(
5481                    "Op::PagedAttn: k_cache block_size dim ({}) must equal Op's block_size ({})",
5482                    kc_dims[1], block_size,
5483                ))
5484                .bt());
5485            }
5486            OpParams::PagedAttn {
5487                b: q_dims[0],
5488                hq: q_dims[1],
5489                hkv: kc_dims[2],
5490                sq: q_dims[2],
5491                d: q_dims[3],
5492                block_size: *block_size,
5493                max_blocks_per_seq: bt_dims[1],
5494                num_blocks: kc_dims[0],
5495                softmax_scale: *softmax_scale,
5496                softcap: *softcap,
5497            }
5498        }
5499        // Phase 7.6 step 5 (final): legacy `Op::FlashAttn` arm dropped.
5500        Op::Fused(
5501            _,
5502            fuel_graph::registry::FusedOpParams::FlashAttn {
5503                softmax_scale,
5504                causal,
5505                window_size_left,
5506                window_size_right,
5507                softcap,
5508                k_len,
5509            },
5510        ) => {
5511            // Inputs[0]=q [B,Hq,Sq,D], inputs[1]=k [B,Hkv,Sk,D],
5512            // inputs[2]=v [B,Hkv,Sk,D], inputs[3]=alibi_slopes [Hq] (optional).
5513            // `sk` is the PHYSICAL K extent (capacity, for strides/bytes);
5514            // `k_len` (resolved below) is the LOGICAL attended length.
5515            if node.inputs.len() != 3 && node.inputs.len() != 4 {
5516                return Err(Error::Msg(format!(
5517                    "Op::FlashAttn expects 3 or 4 inputs, got {}",
5518                    node.inputs.len(),
5519                ))
5520                .bt());
5521            }
5522            let q_layout = input_layout(node.inputs[0]);
5523            let k_layout = input_layout(node.inputs[1]);
5524            let v_layout = input_layout(node.inputs[2]);
5525            let q_dims = q_layout.shape().dims();
5526            let k_dims = k_layout.shape().dims();
5527            let v_dims = v_layout.shape().dims();
5528            if q_dims.len() != 4 || k_dims.len() != 4 || v_dims.len() != 4 {
5529                return Err(Error::Msg(format!(
5530                    "Op::FlashAttn requires rank-4 q/k/v; got q={q_dims:?} k={k_dims:?} v={v_dims:?}",
5531                ))
5532                .bt());
5533            }
5534            if k_dims != v_dims {
5535                return Err(Error::Msg(format!(
5536                    "Op::FlashAttn: k {k_dims:?} and v {v_dims:?} must share shape",
5537                ))
5538                .bt());
5539            }
5540            if q_dims[0] != k_dims[0] || q_dims[3] != k_dims[3] {
5541                return Err(Error::Msg(format!(
5542                    "Op::FlashAttn: q {q_dims:?} and k {k_dims:?} must share B and D",
5543                ))
5544                .bt());
5545            }
5546            let sk = k_dims[2];
5547            // Resolve the logical attended length. `None` ⇒ attend the
5548            // full K extent (today's behavior). `Some(dyn)` ⇒ resolve
5549            // against the per-pass SymEnv; the resolved length must fit
5550            // the capacity and cover Sq (a valid causal prefix).
5551            let attended_k_len = match k_len {
5552                None => sk,
5553                Some(dyn_k) => {
5554                    let kl = dyn_k.resolve(sym_env).ok_or_else(|| {
5555                        Error::Msg(format!(
5556                            "Op::FlashAttn: dynamic k_len {dyn_k:?} is unbound in the SymEnv at realize",
5557                        ))
5558                        .bt()
5559                    })?;
5560                    if kl > sk {
5561                        return Err(Error::Msg(format!(
5562                            "Op::FlashAttn: resolved k_len ({kl}) exceeds K capacity ({sk})",
5563                        ))
5564                        .bt());
5565                    }
5566                    if kl < q_dims[2] {
5567                        return Err(Error::Msg(format!(
5568                            "Op::FlashAttn: resolved k_len ({kl}) < Sq ({}) — not a valid causal prefix",
5569                            q_dims[2],
5570                        ))
5571                        .bt());
5572                    }
5573                    kl
5574                }
5575            };
5576            OpParams::FlashAttn {
5577                b: q_dims[0],
5578                hq: q_dims[1],
5579                hkv: k_dims[1],
5580                sq: q_dims[2],
5581                sk,
5582                d: q_dims[3],
5583                k_len: attended_k_len,
5584                softmax_scale: *softmax_scale,
5585                causal: *causal,
5586                window_size_left: *window_size_left,
5587                window_size_right: *window_size_right,
5588                softcap: *softcap,
5589            }
5590        }
5591        Op::ReduceSumTo(target_shape) => {
5592            if node.inputs.len() != 1 {
5593                return Err(Error::Msg(format!(
5594                    "Op::ReduceSumTo expects 1 input, got {}",
5595                    node.inputs.len(),
5596                ))
5597                .bt());
5598            }
5599            let in_layout = input_layout(node.inputs[0]);
5600            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5601            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5602            OpParams::ReduceSumTo {
5603                input_shape,
5604                output_shape,
5605            }
5606        }
5607        Op::ReduceMaxTo(target_shape) => {
5608            if node.inputs.len() != 1 {
5609                return Err(Error::Msg(format!(
5610                    "Op::ReduceMaxTo expects 1 input, got {}",
5611                    node.inputs.len(),
5612                ))
5613                .bt());
5614            }
5615            let in_layout = input_layout(node.inputs[0]);
5616            let input_shape: Vec<usize> = in_layout.shape().dims().to_vec();
5617            let output_shape: Vec<usize> = target_shape.dims().to_vec();
5618            OpParams::ReduceMaxTo {
5619                input_shape,
5620                output_shape,
5621            }
5622        }
5623        // Phase 7.6 step 5 (final): legacy `Op::ConvTranspose2D` arm dropped.
5624        Op::Fused(
5625            _,
5626            fuel_graph::registry::FusedOpParams::ConvTranspose2D {
5627                stride,
5628                padding,
5629                output_padding,
5630                dilation,
5631                groups,
5632            },
5633        ) => {
5634            // Inputs[0] = x [N, Cin, Hin, Win]; inputs[1] = weight
5635            // [Cin, Cout/groups, Kh, Kw]; inputs[2] (optional) = bias [Cout].
5636            // Output (this Node's shape) = [N, Cout, Hout, Wout].
5637            if node.inputs.len() != 2 && node.inputs.len() != 3 {
5638                return Err(Error::Msg(format!(
5639                    "Op::ConvTranspose2D expects 2 or 3 inputs, got {}",
5640                    node.inputs.len(),
5641                ))
5642                .bt());
5643            }
5644            let x_layout = input_layout(node.inputs[0]);
5645            let w_layout = input_layout(node.inputs[1]);
5646            let x_dims = x_layout.shape().dims();
5647            let w_dims = w_layout.shape().dims();
5648            if x_dims.len() != 4 || w_dims.len() != 4 {
5649                return Err(Error::Msg(format!(
5650                    "Op::ConvTranspose2D requires rank-4 x and weight; got x={x_dims:?} w={w_dims:?}",
5651                ))
5652                .bt());
5653            }
5654            let out_dims = node.shape.dims();
5655            if out_dims.len() != 4 {
5656                return Err(Error::Msg(format!(
5657                    "Op::ConvTranspose2D output must be rank 4, got {out_dims:?}",
5658                ))
5659                .bt());
5660            }
5661            let x_shape = [x_dims[0], x_dims[1], x_dims[2], x_dims[3]];
5662            let w_shape = [w_dims[0], w_dims[1], w_dims[2], w_dims[3]];
5663            let out_shape = [out_dims[0], out_dims[1], out_dims[2], out_dims[3]];
5664            OpParams::ConvTranspose2D {
5665                x_shape,
5666                w_shape,
5667                out_shape,
5668                stride: *stride,
5669                padding: *padding,
5670                output_padding: *output_padding,
5671                dilation: *dilation,
5672                groups: *groups,
5673            }
5674        }
5675        Op::WriteSlice { ranges, dyn_offset } => {
5676            // inputs[0] = destination (its shape == this node's shape
5677            // since WriteSlice's output adopts the destination's
5678            // Layout). inputs[1] = source slab; its shape is implied
5679            // by `ranges`. The kernel needs the destination shape to
5680            // compute strides for the slab walk.
5681            if node.inputs.len() != 2 {
5682                return Err(Error::Msg(format!(
5683                    "Op::WriteSlice expects 2 inputs (destination, source), got {}",
5684                    node.inputs.len(),
5685                ))
5686                .bt());
5687            }
5688            let dest_dims = node.shape.dims().to_vec();
5689            if ranges.len() != dest_dims.len() {
5690                return Err(Error::Msg(format!(
5691                    "Op::WriteSlice: ranges.len() ({}) must equal destination rank ({})",
5692                    ranges.len(),
5693                    dest_dims.len(),
5694                ))
5695                .bt());
5696            }
5697            // Phase D symbolic extents: when present, resolve the runtime
5698            // start offset against the per-pass SymEnv, overriding
5699            // `ranges[axis].0`. The slab WIDTH on that axis stays
5700            // `ranges[axis].1 - ranges[axis].0`, so the effective range
5701            // becomes `(base, base + width)`. `None` ⇒ fully static, and
5702            // the SymEnv is never consulted (empty-env realize unchanged).
5703            //
5704            // DUAL-PATH (increment 2b — data-determined dynamic shapes):
5705            //  - The offset resolves in the compile-time `sym_env` (static,
5706            //    or an INPUT-determined `cached_len`): bake it into `ranges`
5707            //    now, exactly as before.
5708            //  - It is UNBOUND at compile AND a producer in this graph binds
5709            //    it (`Op::NonZeroIndices`'s count, etc.): it is
5710            //    DATA-DETERMINED — leave `ranges[axis]` as the static
5711            //    placeholder and DEFER, carrying the `DynScalar` in
5712            //    `deferred_dyn_offset`. The `WorkItemKind::WriteSlice`
5713            //    executor arm resolves it from `produced_syms` (after the
5714            //    producer runs) and bounds-checks the resolved range there.
5715            //  - It is unbound AND no producer binds it: a genuine caller
5716            //    error → surface it here (preserves the unbound-error path).
5717            let mut ranges = ranges.clone();
5718            let mut deferred_dyn_offset: Option<(usize, fuel_ir::DynScalar)> = None;
5719            if let Some((axis, off)) = dyn_offset {
5720                if *axis >= ranges.len() {
5721                    return Err(Error::Msg(format!(
5722                        "Op::WriteSlice: dyn_offset axis ({axis}) out of bounds for rank {}",
5723                        ranges.len(),
5724                    ))
5725                    .bt());
5726                }
5727                match off.resolve(sym_env) {
5728                    Some(base) => {
5729                        let (start, end) = ranges[*axis];
5730                        let width = end - start;
5731                        ranges[*axis] = (base, base + width);
5732                    }
5733                    None => {
5734                        let is_data_determined = matches!(off, fuel_ir::DynScalar::Sym(s)
5735                            if graph.binds_data_determined_sym(*s));
5736                        if is_data_determined {
5737                            deferred_dyn_offset = Some((*axis, *off));
5738                        } else {
5739                            return Err(Error::Msg(format!(
5740                                "Op::WriteSlice: dynamic offset {off:?} on axis {axis} is \
5741                                 unbound in the SymEnv at realize (and no producer in the \
5742                                 graph binds it, so it is not data-determined)",
5743                            ))
5744                            .bt());
5745                        }
5746                    }
5747                }
5748            }
5749            for (i, &(start, end)) in ranges.iter().enumerate() {
5750                // The deferred axis still holds its static placeholder; the
5751                // executor bounds-checks the resolved range after producing
5752                // the count. Every other axis is fully known now.
5753                if deferred_dyn_offset.is_some_and(|(a, _)| a == i) {
5754                    continue;
5755                }
5756                if end < start || end > dest_dims[i] {
5757                    return Err(Error::Msg(format!(
5758                        "Op::WriteSlice: ranges[{i}] = ({start}, {end}) invalid \
5759                         for destination dim {i} = {}",
5760                        dest_dims[i],
5761                    ))
5762                    .bt());
5763                }
5764            }
5765            OpParams::WriteSlice {
5766                dest_shape: dest_dims,
5767                ranges,
5768                deferred_dyn_offset,
5769            }
5770        }
5771        Op::WriteSliceRotating {
5772            axis,
5773            modulus,
5774            ranges,
5775        } => {
5776            // inputs[0] = destination, inputs[1] = source slab,
5777            // inputs[2] = dynamic position scalar (U32). The builder
5778            // already validated rank / dtype / shape parity; the
5779            // exec-time check below mirrors WriteSlice for the
5780            // structural invariants the executor depends on.
5781            if node.inputs.len() != 3 {
5782                return Err(Error::Msg(format!(
5783                    "Op::WriteSliceRotating expects 3 inputs (destination, source, position), got {}",
5784                    node.inputs.len(),
5785                ))
5786                .bt());
5787            }
5788            let dest_dims = node.shape.dims().to_vec();
5789            if ranges.len() != dest_dims.len() {
5790                return Err(Error::Msg(format!(
5791                    "Op::WriteSliceRotating: ranges.len() ({}) must equal destination rank ({})",
5792                    ranges.len(),
5793                    dest_dims.len(),
5794                ))
5795                .bt());
5796            }
5797            if *axis >= dest_dims.len() {
5798                return Err(Error::Msg(format!(
5799                    "Op::WriteSliceRotating: axis {axis} out of bounds for rank {}",
5800                    dest_dims.len(),
5801                ))
5802                .bt());
5803            }
5804            if *modulus == 0 || *modulus > dest_dims[*axis] {
5805                return Err(Error::Msg(format!(
5806                    "Op::WriteSliceRotating: modulus {modulus} invalid for dest_shape[{axis}] = {}",
5807                    dest_dims[*axis],
5808                ))
5809                .bt());
5810            }
5811            OpParams::WriteSliceRotating {
5812                dest_shape: dest_dims,
5813                axis: *axis,
5814                modulus: *modulus,
5815                ranges: ranges.clone(),
5816            }
5817        }
5818        Op::WriteSliceDoff { axis, ranges } => {
5819            // inputs[0] = destination, inputs[1] = source slab,
5820            // inputs[2] = device-resident I64 offset scalar. The
5821            // builder validated rank / dtype / static-width parity; the
5822            // exec-time check below mirrors WriteSliceRotating minus the
5823            // modulus (no wrap). Bounds on the *dynamic* offset are the
5824            // caller's contract (device-only, un-checkable here).
5825            if node.inputs.len() != 3 {
5826                return Err(Error::Msg(format!(
5827                    "Op::WriteSliceDoff expects 3 inputs (destination, source, offset), got {}",
5828                    node.inputs.len(),
5829                ))
5830                .bt());
5831            }
5832            let dest_dims = node.shape.dims().to_vec();
5833            if ranges.len() != dest_dims.len() {
5834                return Err(Error::Msg(format!(
5835                    "Op::WriteSliceDoff: ranges.len() ({}) must equal destination rank ({})",
5836                    ranges.len(),
5837                    dest_dims.len(),
5838                ))
5839                .bt());
5840            }
5841            if *axis >= dest_dims.len() {
5842                return Err(Error::Msg(format!(
5843                    "Op::WriteSliceDoff: axis {axis} out of bounds for rank {}",
5844                    dest_dims.len(),
5845                ))
5846                .bt());
5847            }
5848            OpParams::WriteSliceDoff {
5849                dest_shape: dest_dims,
5850                axis: *axis,
5851                ranges: ranges.clone(),
5852            }
5853        }
5854        _ => OpParams::None,
5855    })
5856}
5857
5858/// The unchecked out-of-range index reads of one run (GAP-415).
5859#[cfg(feature = "cuda")]
5860type IndexReads = fuel_cuda_backend::index_read_check::IndexReadChecks;
5861
5862/// Non-CUDA builds note nothing, so there is nothing to check.
5863#[cfg(not(feature = "cuda"))]
5864#[derive(Default)]
5865struct IndexReads {}
5866
5867#[cfg(not(feature = "cuda"))]
5868impl IndexReads {
5869    fn check(&mut self) -> Result<()> {
5870        Ok(())
5871    }
5872}
5873
5874/// Note the index operand of a just-launched CUDA `index_select` or `gather`.
5875#[cfg(feature = "cuda")]
5876fn note_index_read(
5877    reads: &mut IndexReads,
5878    params: &OpParams,
5879    inputs: &[Arc<RwLock<Storage>>],
5880) -> Result<()> {
5881    let (op, numel, bound) = match params {
5882        OpParams::IndexSelect {
5883            source_dim_size,
5884            n_indices,
5885            ..
5886        } => ("index_select", *n_indices, *source_dim_size),
5887        OpParams::Gather {
5888            source_shape,
5889            output_shape,
5890            dim,
5891        } => {
5892            let bound = source_shape.get(*dim).copied().ok_or_else(|| {
5893                Error::Msg(format!("gather: dim {dim} is outside {source_shape:?}")).bt()
5894            })?;
5895            ("gather", output_shape.iter().product(), bound)
5896        }
5897        _ => return Ok(()),
5898    };
5899    let index = inputs
5900        .get(1)
5901        .ok_or_else(|| Error::Msg(format!("{op}: no index operand")).bt())?;
5902    let guard = index.read().map_err(|_| poisoned("index storage"))?;
5903    match &guard.inner {
5904        fuel_memory::BackendStorage::Cuda(c) => reads.note(op, c, numel, bound),
5905        other => Err(Error::Msg(format!(
5906            "{op}: CUDA kernel with a {:?} index operand",
5907            other.backend_id()
5908        ))
5909        .bt()),
5910    }
5911}
5912
5913/// Execute one work item. Three branches by `WorkItemKind`:
5914///
5915/// - `ConstAdopt` — verify cache has an entry pre-seeded by the
5916///   caller; record the layout from the WorkItem.
5917/// - `ViewOf { input }` — clone the input's Storage Arc into the
5918///   output slot (bytes are shared); record the strided layout
5919///   from the WorkItem.
5920/// - `Kernel` — gather input Arcs, allocate the output, run the
5921///   compiled kernel, store the result; record the contiguous
5922///   layout from the WorkItem.
5923///
5924/// Best-effort: prefix a realize-time node error with the failing node's graph
5925/// location — `Graph::describe_node` renders `Node#N (op, out shape, dtype,
5926/// inputs=[...])`, enough to grep-locate the offending op in a large graph. The
5927/// legacy per-node executors (`fuel-graph-executor`, the retired
5928/// `fuel-reference-backend`) wrapped panics this way; the PipelinedExecutor
5929/// surfaces the raw kernel error, so a dtype/shape/OOB failure deep in a model
5930/// arrived with no graph coordinate. On a graph read-lock failure the original
5931/// error passes through unchanged — the location is a navigation aid, never
5932/// worth masking the real error with a lock issue. Zero happy-path cost: only
5933/// the error branch touches the graph.
5934fn with_node_location(graph: &Arc<RwLock<Graph>>, node_id: NodeId, err: Error) -> Error {
5935    match graph.read() {
5936        Ok(g) => err.context(g.describe_node(node_id)),
5937        Err(_) => err,
5938    }
5939}
5940
5941/// Execute one [`WorkItem`] against the cache, returning the node's
5942/// [`CompletionHandle`].
5943///
5944/// Step E A4b-1: the producing arms (Kernel / WriteSlice / WriteSliceRotating /
5945/// in-place / cross-device Copy alloc) return the handle from `execute_compiled`
5946/// *without* waiting it inline — the realize loop stores it in its per-node
5947/// handle map and drains at realize-end. Non-producing arms (const adopt, view,
5948/// slot projection, release marker, contiguize) are pure Arc-clones / host
5949/// allocs whose work is already complete → [`CompletionHandle::Ready`].
5950/// Read a data-determined runtime count from bundle slot 1 of a
5951/// just-realized producer and bind it into the per-pass `SymEnv` under
5952/// `count_sym` — the data-dependent dynamic-shapes seam (increment 2a).
5953/// The producer's bundle is `[indices [capacity] U32 ; count [1] U32]`;
5954/// slot 1's single U32 starts at byte `capacity * 4` (after the
5955/// `capacity`-element U32 primary slot). CPU only for now — device
5956/// backends need a D2H after the completion handle is waited (a documented
5957/// follow-up; the whole data-dependent path is CPU-first). Called AFTER
5958/// `execute_compiled`, whose CPU path returns a `Ready` handle, so the
5959/// bytes are already valid.
5960fn bind_data_determined_count(
5961    arc: &Arc<RwLock<Storage>>,
5962    capacity: usize,
5963    count_sym: fuel_ir::SymId,
5964    produced_syms: &mut SymEnv,
5965) -> Result<()> {
5966    let guard = arc
5967        .read()
5968        .map_err(|_| poisoned("NonZeroIndices output storage"))?;
5969    let count_byte_off = capacity * std::mem::size_of::<u32>();
5970    let end = count_byte_off + std::mem::size_of::<u32>();
5971    // The non-CPU `BackendStorage` variants are cfg-gated; with GPU
5972    // features off, `Cpu` is the only variant and the fallback arm is
5973    // unreachable (a documented CPU-first limitation, not dead logic).
5974    #[allow(unreachable_patterns)]
5975    let count = match &guard.inner {
5976        fuel_memory::BackendStorage::Cpu(cpu_bytes) => {
5977            let bytes = cpu_bytes.bytes();
5978            if end > bytes.len() {
5979                return Err(Error::Msg(format!(
5980                    "NonZeroIndices: count slot byte range [{count_byte_off}..{end}) \
5981                     exceeds bundle byte length {}",
5982                    bytes.len(),
5983                ))
5984                .bt());
5985            }
5986            u32::from_le_bytes(
5987                bytes[count_byte_off..end]
5988                    .try_into()
5989                    .expect("4 bytes → u32"),
5990            )
5991        }
5992        other => {
5993            return Err(Error::Msg(format!(
5994                "NonZeroIndices: data-determined count read is CPU-only today; got \
5995                 BackendStorage::{:?} (device backends need a D2H after the completion \
5996                 handle is waited — a documented follow-up)",
5997                other.backend_id(),
5998            ))
5999            .bt());
6000        }
6001    };
6002    produced_syms.bind(count_sym, count as usize)?;
6003    Ok(())
6004}
6005
6006/// Increment 2b — the consumer half of data-dependent dynamic shapes. When
6007/// a `WriteSlice`'s offset is DATA-DETERMINED (its `SymId` is produced
6008/// mid-pass, so `op_to_op_params` deferred it into
6009/// `OpParams::WriteSlice::deferred_dyn_offset` instead of baking it at
6010/// compile), resolve it HERE from `produced_syms` — populated by the
6011/// producer's execute step (single-threaded topological order guarantees
6012/// the producer already ran). Returns a patched clone of the `CompiledNode`
6013/// with the resolved `ranges` (and `deferred_dyn_offset` cleared) for the
6014/// kernel; `None` when there is nothing to defer (the common path — no
6015/// clone). Bounds-checks the resolved range (deferred past compile).
6016fn resolve_deferred_write_slice(
6017    compiled: &CompiledNode,
6018    produced_syms: &SymEnv,
6019    node_id: NodeId,
6020) -> Result<Option<CompiledNode>> {
6021    let OpParams::WriteSlice {
6022        dest_shape,
6023        ranges,
6024        deferred_dyn_offset,
6025    } = &compiled.op_params
6026    else {
6027        return Ok(None);
6028    };
6029    let Some((axis, off)) = deferred_dyn_offset else {
6030        return Ok(None);
6031    };
6032    let base = off.resolve(produced_syms).ok_or_else(|| {
6033        Error::Msg(format!(
6034            "Op::WriteSlice {node_id:?}: data-determined offset {off:?} on axis {axis} is \
6035             unbound in produced_syms at execute (its producer did not run / bind it)",
6036        ))
6037        .bt()
6038    })?;
6039    let mut ranges = ranges.clone();
6040    let (start, end) = ranges[*axis];
6041    let width = end - start;
6042    let resolved = (base, base + width);
6043    if resolved.1 > dest_shape[*axis] {
6044        return Err(Error::Msg(format!(
6045            "Op::WriteSlice {node_id:?}: resolved data-determined range {resolved:?} on axis \
6046             {axis} exceeds destination dim = {}",
6047            dest_shape[*axis],
6048        ))
6049        .bt());
6050    }
6051    ranges[*axis] = resolved;
6052    let mut patched = compiled.clone();
6053    patched.op_params = OpParams::WriteSlice {
6054        dest_shape: dest_shape.clone(),
6055        ranges,
6056        deferred_dyn_offset: None,
6057    };
6058    Ok(Some(patched))
6059}
6060
6061/// Dynamic-M matmul: when a matmul's row count is DATA-DETERMINED
6062/// (`MatmulM::Deferred`, deferred by `op_to_op_params` because a producer
6063/// binds its `SymId` mid-pass), resolve it HERE from `produced_syms` and
6064/// run the kernel against a patched clone whose `m_compute` is
6065/// `MatmulM::Rows(count)`. Mirrors `resolve_deferred_write_slice`. `None`
6066/// when nothing is deferred (the common path — no clone). The kernel then
6067/// computes exactly `count` rows of the `m`-row capacity buffer.
6068fn resolve_deferred_matmul(
6069    compiled: &CompiledNode,
6070    produced_syms: &SymEnv,
6071    node_id: NodeId,
6072) -> Result<Option<CompiledNode>> {
6073    let OpParams::Matmul {
6074        lhs_batch_dims,
6075        rhs_batch_dims,
6076        m,
6077        n,
6078        k,
6079        m_compute,
6080    } = &compiled.op_params
6081    else {
6082        return Ok(None);
6083    };
6084    let MatmulM::Deferred(dyn_m) = m_compute else {
6085        return Ok(None);
6086    };
6087    let rows = dyn_m.resolve(produced_syms).ok_or_else(|| {
6088        Error::Msg(format!(
6089            "Op::MatMul {node_id:?}: data-determined row count {dyn_m:?} is unbound in \
6090             produced_syms at execute (its producer did not run / bind it)",
6091        ))
6092        .bt()
6093    })?;
6094    if rows > *m {
6095        return Err(Error::Msg(format!(
6096            "Op::MatMul {node_id:?}: resolved row count {rows} exceeds capacity {m}",
6097        ))
6098        .bt());
6099    }
6100    let mut patched = compiled.clone();
6101    patched.op_params = OpParams::Matmul {
6102        lhs_batch_dims: lhs_batch_dims.clone(),
6103        rhs_batch_dims: rhs_batch_dims.clone(),
6104        m: *m,
6105        n: *n,
6106        k: *k,
6107        m_compute: MatmulM::Rows(rows),
6108    };
6109    Ok(Some(patched))
6110}
6111
6112fn execute_work_item(
6113    item: &WorkItem,
6114    cache: &mut StorageCache,
6115    #[cfg_attr(
6116        not(any(feature = "cuda", feature = "vulkan")),
6117        allow(unused_variables)
6118    )]
6119    devices: &mut DeviceRegistry,
6120    layout_cache: &mut HashMap<NodeId, Layout>,
6121    produced_syms: &mut SymEnv,
6122    // Step E A4b open question #4 — "event only where waited": whether
6123    // THIS item's node id is in the realize's `WaitSet` (`will_be_waited`
6124    // in `pipelined.rs`, computed once per item by the caller). Forwarded
6125    // to every `execute_compiled_with_wait_hint` call below so a CUDA
6126    // kernel with no mid-walk reader skips its `Event` entirely.
6127    will_be_waited: bool,
6128    // CapturedRun executor build-out: persistent-output mode. `None` on
6129    // every existing realize path ⇒ byte-identical (fresh alloc, nothing
6130    // recorded). `Some(Record)` records each Kernel output's fixed Arc;
6131    // `Some(Reuse)` reuses the recorded buffer (no alloc — capture-safe)
6132    // and the write-into kernel path writes into it in place. Only the
6133    // `Kernel` arm consults it; every other arm ignores it.
6134    mut persistent: Option<&mut PersistentOutputs>,
6135    // GAP-415: where an index-reading CUDA kernel notes its index operand.
6136    #[cfg_attr(not(feature = "cuda"), allow(unused_variables))] index_reads: Option<
6137        &mut IndexReads,
6138    >,
6139) -> Result<CompletionHandle> {
6140    match &item.kind {
6141        WorkItemKind::ConstAdopt => {
6142            if !cache.contains_key(&item.node_id) {
6143                return Err(Error::Msg(format!(
6144                    "PipelinedExecutor: Const node {:?} not in input cache",
6145                    item.node_id
6146                ))
6147                .bt());
6148            }
6149            // Layout for input cache entries was seeded at realize
6150            // start; refresh from the WorkItem in case the side-table
6151            // was set after seeding.
6152            layout_cache.insert(item.node_id, item.output_layout.clone());
6153            Ok(CompletionHandle::Ready)
6154        }
6155        WorkItemKind::ViewOf { input } => {
6156            let input_arc = cache.get(input).cloned().ok_or_else(|| {
6157                Error::Msg(format!(
6158                    "PipelinedExecutor: view-op input {:?} of {:?} not realized",
6159                    input, item.node_id,
6160                ))
6161                .bt()
6162            })?;
6163            cache.insert(item.node_id, input_arc);
6164            layout_cache.insert(item.node_id, item.output_layout.clone());
6165            Ok(CompletionHandle::Ready)
6166        }
6167        WorkItemKind::SlotView { producer } => {
6168            // Op::View — multi-output projection. Same realization
6169            // shape as ViewOf: clone the producer's Storage Arc into
6170            // the View's cache slot. The WorkItem's output_layout was
6171            // computed at graph-build time by `Tensor::view`, with
6172            // the slot's byte_offset baked into start_offset (in
6173            // slot-dtype-element units). Downstream kernels reading
6174            // the producer's bytes as the slot's dtype starting at
6175            // that offset see the slot's typed window.
6176            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
6177                Error::Msg(format!(
6178                    "PipelinedExecutor: Op::View producer {:?} of {:?} not realized",
6179                    producer, item.node_id,
6180                ))
6181                .bt()
6182            })?;
6183            cache.insert(item.node_id, producer_arc);
6184            layout_cache.insert(item.node_id, item.output_layout.clone());
6185            Ok(CompletionHandle::Ready)
6186        }
6187        WorkItemKind::SlotOwn { producer, slot } => {
6188            // Op::ViewOwned — allocate a fresh Storage of the slot's
6189            // (shape, dtype) on the producer's device and copy the
6190            // slot's bytes in. Per-backend fast paths:
6191            //   - CPU:    direct &[u8]→&mut[u8] memcpy via CpuStorageBytes
6192            //   - CUDA:   D2D via CudaStorageBytes::slot_copy_to_new
6193            //             (cuMemcpyDtoDAsync with offset src pointer)
6194            //   - Vulkan: vkCmdCopyBuffer via
6195            //             VulkanBackend::slot_copy_to_new_handle
6196            //             (srcOffset/dstOffset/size)
6197            // For backends without a copy-with-offset hook we fall
6198            // back to a host round-trip (`to_host_buffer_dyn` →
6199            // slice → `storage_from_host_buffer_owned_dyn`), which
6200            // works but is wasteful.
6201            let producer_arc = cache.get(producer).cloned().ok_or_else(|| {
6202                Error::Msg(format!(
6203                    "PipelinedExecutor: Op::ViewOwned producer {:?} of {:?} not realized",
6204                    producer, item.node_id,
6205                ))
6206                .bt()
6207            })?;
6208            let new_storage = {
6209                let guard = producer_arc
6210                    .read()
6211                    .map_err(|_| poisoned("ViewOwned producer storage"))?;
6212                let bundle = guard.bundle().ok_or_else(|| {
6213                    Error::Msg(format!(
6214                        "Op::ViewOwned: producer {:?} has no bundle side-table \
6215                         — the multi-output authoring contract requires \
6216                         Storage::with_bundle / new_bundled at allocation \
6217                         time. Node {:?} slot {} cannot resolve its source.",
6218                        producer, item.node_id, slot,
6219                    ))
6220                    .bt()
6221                })?;
6222                let sv = bundle.get(*slot as usize).cloned().ok_or_else(|| {
6223                    Error::Msg(format!(
6224                        "Op::ViewOwned: slot {} out of range for producer {:?} \
6225                         (bundle has {} slots)",
6226                        slot,
6227                        producer,
6228                        bundle.len(),
6229                    ))
6230                    .bt()
6231                })?;
6232                use fuel_memory::BackendStorage;
6233                match &guard.inner {
6234                    BackendStorage::Cpu(cpu_bytes) => {
6235                        let src_bytes = cpu_bytes.bytes();
6236                        let end = sv.byte_offset + sv.len_bytes();
6237                        if end > src_bytes.len() {
6238                            return Err(Error::Msg(format!(
6239                                "Op::ViewOwned: slot {} byte range [{}..{}) \
6240                                 exceeds producer's CPU byte length {}",
6241                                slot,
6242                                sv.byte_offset,
6243                                end,
6244                                src_bytes.len(),
6245                            ))
6246                            .bt());
6247                        }
6248                        let owned = fuel_cpu_backend::CpuStorageBytes::from_bytes(
6249                            &src_bytes[sv.byte_offset..end],
6250                        );
6251                        fuel_memory::Storage::new(BackendStorage::Cpu(owned), sv.dtype)
6252                    }
6253                    #[cfg(feature = "cuda")]
6254                    BackendStorage::Cuda(cuda_bytes) => {
6255                        let dst = cuda_bytes.slot_copy_to_new(sv.byte_offset, sv.len_bytes())?;
6256                        fuel_memory::Storage::new(BackendStorage::Cuda(dst), sv.dtype)
6257                    }
6258                    #[cfg(feature = "vulkan")]
6259                    BackendStorage::Vulkan(vk_bytes) => {
6260                        let backend = vk_bytes.backend().ok_or_else(|| {
6261                            Error::Msg(format!(
6262                                "Op::ViewOwned: producer {:?} is on Vulkan but \
6263                                 its storage has no VulkanBackend handle. \
6264                                 Storages flowing through the pipelined executor \
6265                                 must be constructed via alloc_bytes_handle / \
6266                                 upload_bytes_handle so the bundle's slot extraction \
6267                                 path can reach the backend.",
6268                                producer,
6269                            ))
6270                            .bt()
6271                        })?;
6272                        let dst = backend.slot_copy_to_new_handle(
6273                            vk_bytes,
6274                            sv.byte_offset,
6275                            sv.len_bytes(),
6276                        )?;
6277                        fuel_memory::Storage::new(BackendStorage::Vulkan(dst), sv.dtype)
6278                    }
6279                    #[allow(unreachable_patterns)]
6280                    _ => {
6281                        return Err(Error::Msg(format!(
6282                            "Op::ViewOwned: producer {:?} is on a backend \
6283                             without a slot-copy-with-offset hook \
6284                             (CPU + CUDA + Vulkan wired). Add a per-backend \
6285                             `slot_copy_to_new`-equivalent and extend the \
6286                             match arm.",
6287                            producer,
6288                        ))
6289                        .bt());
6290                    }
6291                }
6292            };
6293            cache.insert(item.node_id, Arc::new(RwLock::new(new_storage)));
6294            layout_cache.insert(item.node_id, item.output_layout.clone());
6295            // A4b-1: Op::ViewOwned's slot copy (CUDA D2D) is same-stream; its
6296            // completion is carried by the realize-end full-stream sync in
6297            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
6298            Ok(CompletionHandle::Ready)
6299        }
6300        WorkItemKind::WriteSlice { dest, source } => {
6301            let compiled = item.compiled.as_ref().ok_or_else(|| {
6302                Error::Msg(format!(
6303                    "PipelinedExecutor: WriteSlice work item {:?} has no compiled node",
6304                    item.node_id,
6305                ))
6306                .bt()
6307            })?;
6308            // Increment 2b: if the offset is DATA-DETERMINED, resolve it from
6309            // the producer-bound `produced_syms` and run the kernel against
6310            // the patched (resolved-range) node. `None` on the common path.
6311            let patched_ws = resolve_deferred_write_slice(compiled, produced_syms, item.node_id)?;
6312            let compiled = patched_ws.as_ref().unwrap_or(compiled);
6313            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6314                Error::Msg(format!(
6315                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} not realized",
6316                    dest, item.node_id,
6317                ))
6318                .bt()
6319            })?;
6320            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6321                Error::Msg(format!(
6322                    "PipelinedExecutor: WriteSlice source {:?} of {:?} not realized",
6323                    source, item.node_id,
6324                ))
6325                .bt()
6326            })?;
6327            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6328                Error::Msg(format!(
6329                    "PipelinedExecutor: WriteSlice destination {:?} of {:?} has no cached layout",
6330                    dest, item.node_id,
6331                ))
6332                .bt()
6333            })?;
6334            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6335                Error::Msg(format!(
6336                    "PipelinedExecutor: WriteSlice source {:?} of {:?} has no cached layout",
6337                    source, item.node_id,
6338                ))
6339                .bt()
6340            })?;
6341            // v1 contract: destination must be contiguous + zero
6342            // offset. Strided dests would force the kernel to walk
6343            // both source and dest strides; defer until KV cache
6344            // exposes a non-contig dest. Source CAN be non-contig —
6345            // we auto-contiguize it here so the kernel sees a flat
6346            // slab.
6347            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6348                return Err(Error::Msg(format!(
6349                    "Op::WriteSlice (Phase E.3.2 v1): destination {:?} must be \
6350                     contiguous + zero-offset; got Layout {:?}",
6351                    dest, dest_layout,
6352                ))
6353                .bt());
6354            }
6355            let source_arc_contig = {
6356                let s_dtype = source_arc
6357                    .read()
6358                    .map_err(|_| poisoned("WriteSlice source storage"))?
6359                    .dtype;
6360                let s_len_bytes = source_arc
6361                    .read()
6362                    .map_err(|_| poisoned("WriteSlice source storage"))?
6363                    .inner
6364                    .len_bytes();
6365                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6366                let bytes_match_shape = s_len_bytes == layout_bytes;
6367                let already_contig = source_layout.is_contiguous()
6368                    && source_layout.start_offset() == 0
6369                    && bytes_match_shape;
6370                if already_contig {
6371                    source_arc
6372                } else {
6373                    auto_contiguize(&source_arc, &source_layout)?
6374                }
6375            };
6376            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6377            // The kernel sees inputs=[source] and outputs=[dest_arc].
6378            // The dest input slot is intentionally absent — the kernel
6379            // doesn't read from dest; it only writes to its bytes
6380            // through the output slot's write lock.
6381            let input_arcs = vec![source_arc_contig];
6382            let mut output_arcs = vec![dest_arc.clone()];
6383            let kernel_layouts = vec![source_layout_kernel, dest_layout.clone()];
6384            // A4b-1: defer the wait — return the handle to the realize loop.
6385            let handle = execute_compiled_with_wait_hint(
6386                compiled,
6387                &input_arcs,
6388                &mut output_arcs,
6389                &kernel_layouts,
6390                will_be_waited,
6391            )?;
6392            // Adopt the dest Arc at this WriteSlice node's slot. The
6393            // realize loop's destructive_input cleanup evicts the
6394            // dest's own NodeId from the cache afterward — downstream
6395            // readers go through this node's NodeId.
6396            cache.insert(item.node_id, dest_arc);
6397            layout_cache.insert(item.node_id, item.output_layout.clone());
6398            Ok(handle)
6399        }
6400        WorkItemKind::WriteSliceRotating {
6401            dest,
6402            source,
6403            position,
6404        } => {
6405            // Same shape as WriteSlice but with a position input.
6406            // Kernel sees `[source, position]` as inputs; `dest` is the
6407            // pre-allocated output buffer (in-place adoption).
6408            let compiled = item.compiled.as_ref().ok_or_else(|| {
6409                Error::Msg(format!(
6410                    "PipelinedExecutor: WriteSliceRotating work item {:?} has no compiled node",
6411                    item.node_id,
6412                ))
6413                .bt()
6414            })?;
6415            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6416                Error::Msg(format!(
6417                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} not realized",
6418                    dest, item.node_id,
6419                ))
6420                .bt()
6421            })?;
6422            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6423                Error::Msg(format!(
6424                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} not realized",
6425                    source, item.node_id,
6426                ))
6427                .bt()
6428            })?;
6429            let position_arc = cache.get(position).cloned().ok_or_else(|| {
6430                Error::Msg(format!(
6431                    "PipelinedExecutor: WriteSliceRotating position {:?} of {:?} not realized",
6432                    position, item.node_id,
6433                ))
6434                .bt()
6435            })?;
6436            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6437                Error::Msg(format!(
6438                    "PipelinedExecutor: WriteSliceRotating destination {:?} of {:?} has no cached layout",
6439                    dest, item.node_id,
6440                ))
6441                .bt()
6442            })?;
6443            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6444                Error::Msg(format!(
6445                    "PipelinedExecutor: WriteSliceRotating source {:?} of {:?} has no cached layout",
6446                    source, item.node_id,
6447                ))
6448                .bt()
6449            })?;
6450            // v1: destination contiguous + zero offset (same as WriteSlice).
6451            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6452                return Err(Error::Msg(format!(
6453                    "Op::WriteSliceRotating (v1): destination {:?} must be \
6454                     contiguous + zero-offset; got Layout {:?}",
6455                    dest, dest_layout,
6456                ))
6457                .bt());
6458            }
6459            let source_arc_contig = {
6460                let s_dtype = source_arc
6461                    .read()
6462                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6463                    .dtype;
6464                let s_len_bytes = source_arc
6465                    .read()
6466                    .map_err(|_| poisoned("WriteSliceRotating source storage"))?
6467                    .inner
6468                    .len_bytes();
6469                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6470                let bytes_match_shape = s_len_bytes == layout_bytes;
6471                let already_contig = source_layout.is_contiguous()
6472                    && source_layout.start_offset() == 0
6473                    && bytes_match_shape;
6474                if already_contig {
6475                    source_arc
6476                } else {
6477                    auto_contiguize(&source_arc, &source_layout)?
6478                }
6479            };
6480            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6481            let position_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6482            let input_arcs = vec![source_arc_contig, position_arc];
6483            let mut output_arcs = vec![dest_arc.clone()];
6484            let kernel_layouts = vec![source_layout_kernel, position_layout, dest_layout.clone()];
6485            // A4b-1: defer the wait — return the handle to the realize loop.
6486            let handle = execute_compiled_with_wait_hint(
6487                compiled,
6488                &input_arcs,
6489                &mut output_arcs,
6490                &kernel_layouts,
6491                will_be_waited,
6492            )?;
6493            cache.insert(item.node_id, dest_arc);
6494            layout_cache.insert(item.node_id, item.output_layout.clone());
6495            Ok(handle)
6496        }
6497        WorkItemKind::WriteSliceDoff {
6498            dest,
6499            source,
6500            offset,
6501        } => {
6502            // Same shape as WriteSliceRotating: kernel sees
6503            // `[source, offset]` as inputs; `dest` is the pre-allocated
6504            // output buffer (in-place adoption). The offset (rank-0
6505            // I64) is passed through as a kernel input — the CUDA
6506            // wrapper threads its device pointer straight to the kernel
6507            // (no D2H), which is what makes a captured graph replay at
6508            // the host-updated position.
6509            let compiled = item.compiled.as_ref().ok_or_else(|| {
6510                Error::Msg(format!(
6511                    "PipelinedExecutor: WriteSliceDoff work item {:?} has no compiled node",
6512                    item.node_id,
6513                ))
6514                .bt()
6515            })?;
6516            let dest_arc = cache.get(dest).cloned().ok_or_else(|| {
6517                Error::Msg(format!(
6518                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} not realized",
6519                    dest, item.node_id,
6520                ))
6521                .bt()
6522            })?;
6523            let source_arc = cache.get(source).cloned().ok_or_else(|| {
6524                Error::Msg(format!(
6525                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} not realized",
6526                    source, item.node_id,
6527                ))
6528                .bt()
6529            })?;
6530            let offset_arc = cache.get(offset).cloned().ok_or_else(|| {
6531                Error::Msg(format!(
6532                    "PipelinedExecutor: WriteSliceDoff offset {:?} of {:?} not realized",
6533                    offset, item.node_id,
6534                ))
6535                .bt()
6536            })?;
6537            let dest_layout = layout_cache.get(dest).cloned().ok_or_else(|| {
6538                Error::Msg(format!(
6539                    "PipelinedExecutor: WriteSliceDoff destination {:?} of {:?} has no cached layout",
6540                    dest, item.node_id,
6541                ))
6542                .bt()
6543            })?;
6544            let source_layout = layout_cache.get(source).cloned().ok_or_else(|| {
6545                Error::Msg(format!(
6546                    "PipelinedExecutor: WriteSliceDoff source {:?} of {:?} has no cached layout",
6547                    source, item.node_id,
6548                ))
6549                .bt()
6550            })?;
6551            // v1: destination contiguous + zero offset (same as WriteSlice).
6552            if !dest_layout.is_contiguous() || dest_layout.start_offset() != 0 {
6553                return Err(Error::Msg(format!(
6554                    "Op::WriteSliceDoff (v1): destination {:?} must be \
6555                     contiguous + zero-offset; got Layout {:?}",
6556                    dest, dest_layout,
6557                ))
6558                .bt());
6559            }
6560            let source_arc_contig = {
6561                let s_dtype = source_arc
6562                    .read()
6563                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6564                    .dtype;
6565                let s_len_bytes = source_arc
6566                    .read()
6567                    .map_err(|_| poisoned("WriteSliceDoff source storage"))?
6568                    .inner
6569                    .len_bytes();
6570                let layout_bytes = source_layout.shape().elem_count() * s_dtype.size_in_bytes();
6571                let bytes_match_shape = s_len_bytes == layout_bytes;
6572                let already_contig = source_layout.is_contiguous()
6573                    && source_layout.start_offset() == 0
6574                    && bytes_match_shape;
6575                if already_contig {
6576                    source_arc
6577                } else {
6578                    auto_contiguize(&source_arc, &source_layout)?
6579                }
6580            };
6581            let source_layout_kernel = fuel_ir::Layout::contiguous(source_layout.shape().clone());
6582            let offset_layout = fuel_ir::Layout::contiguous(fuel_ir::Shape::from_dims(&[]));
6583            let input_arcs = vec![source_arc_contig, offset_arc];
6584            let mut output_arcs = vec![dest_arc.clone()];
6585            let kernel_layouts = vec![source_layout_kernel, offset_layout, dest_layout.clone()];
6586            // A4b-1: defer the wait — return the handle to the realize loop.
6587            let handle = execute_compiled_with_wait_hint(
6588                compiled,
6589                &input_arcs,
6590                &mut output_arcs,
6591                &kernel_layouts,
6592                will_be_waited,
6593            )?;
6594            cache.insert(item.node_id, dest_arc);
6595            layout_cache.insert(item.node_id, item.output_layout.clone());
6596            Ok(handle)
6597        }
6598        WorkItemKind::Alloc { target_location } => {
6599            // Op::Alloc { target }: allocate a fresh, zero-init storage
6600            // on target_location. No inputs, no kernel call — direct
6601            // executor dispatch. For non-CPU targets the per-backend
6602            // device handle comes from the `DeviceRegistry` the caller
6603            // handed the realize (a `*_with_devices` entry point).
6604            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6605            // default-feature build sees it unused. GAP-229: 68161981's
6606            // unused_variables --fix renamed it `_n_bytes` at default
6607            // features and broke `--features vulkan` (E0425). Guard the
6608            // decline instead of the name so the binding stays usable.
6609            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6610            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6611            let alloced: Storage = match target_location {
6612                // CPU has no separate uninit alloc primitive in safe
6613                // Rust (`vec![0; n]` is the canonical path). Op::Alloc
6614                // on CPU returns zero-init storage; the following
6615                // Op::ZeroFill is a redundant memset the optimizer
6616                // can elide and LLVM folds away regardless.
6617                DeviceLocation::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?,
6618                #[cfg(feature = "cuda")]
6619                DeviceLocation::Cuda { gpu_id } => {
6620                    let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6621                        Error::Msg(format!(
6622                            "Op::Alloc on Cuda {{ gpu_id: {} }}: no CUDA \
6623                             device registered for this place. Hand the device to \
6624                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6625                             entry point).",
6626                            gpu_id,
6627                        ))
6628                        .bt()
6629                    })?;
6630                    // Phase 3a follow-up: true uninit alloc via
6631                    // baracuda alpha.30's unsafe alloc. The bytes are
6632                    // uninit until a subsequent Op::ZeroFill or full-
6633                    // overwrite op runs. The byte-storage Arc has no
6634                    // typed-slice accessor that would dereference
6635                    // uninit bytes.
6636                    let cuda_bytes =
6637                        fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6638                    Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6639                }
6640                #[cfg(not(feature = "cuda"))]
6641                DeviceLocation::Cuda { .. } => {
6642                    return Err(Error::Msg(
6643                        "Op::Alloc on Cuda but fuel-storage wasn't built \
6644                         with --features cuda"
6645                            .to_string(),
6646                    )
6647                    .bt());
6648                }
6649                #[cfg(feature = "vulkan")]
6650                DeviceLocation::Vulkan { gpu_id } => {
6651                    let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6652                        Error::Msg(format!(
6653                            "Op::Alloc on Vulkan {{ gpu_id: {} }}: no Vulkan \
6654                             device registered for this place. Hand the device to \
6655                             the realize in a `DeviceRegistry` (a `*_with_devices` \
6656                             entry point).",
6657                            gpu_id,
6658                        ))
6659                        .bt()
6660                    })?;
6661                    // Phase 3a follow-up: true uninit alloc. The old
6662                    // `upload_bytes_handle(vec![0u8; n])` host-staged
6663                    // zeros (~2× the bandwidth of a device-side fill);
6664                    // we now allocate uninit and rely on a paired
6665                    // Op::ZeroFill (vkCmdFillBuffer) for the
6666                    // initialization. Faster KV-cache init on Vulkan.
6667                    let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
6668                    Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
6669                }
6670                #[cfg(not(feature = "vulkan"))]
6671                DeviceLocation::Vulkan { .. } => {
6672                    return Err(Error::Msg(
6673                        "Op::Alloc on Vulkan but fuel-storage wasn't built \
6674                         with --features vulkan"
6675                            .to_string(),
6676                    )
6677                    .bt());
6678                }
6679                other => {
6680                    return Err(Error::Msg(format!(
6681                        "Op::Alloc on {:?}: target not yet wired (CPU + \
6682                         CUDA + Vulkan land in Phase 3a of bridge-retirement; \
6683                         Metal extends when its byte-storage substrate is \
6684                         ready).",
6685                        other,
6686                    ))
6687                    .bt());
6688                }
6689            };
6690            cache.insert(item.node_id, Arc::new(RwLock::new(alloced)));
6691            layout_cache.insert(item.node_id, item.output_layout.clone());
6692            Ok(CompletionHandle::Ready)
6693        }
6694        WorkItemKind::Iota {
6695            len,
6696            target_location,
6697        } => {
6698            // Op::Iota { len }: 0-input F32 position generator
6699            // [0.0, 1.0, …, (len-1)]. Direct executor dispatch (no kernel /
6700            // binding-table lookup), like WorkItemKind::Alloc. Generated on the host, then, for a
6701            // CUDA target, uploaded (an Iota is a tiny index constant: a device kernel would cost a
6702            // launch to save a few hundred bytes of transfer). The decomposed PAGED_ATTN recipe
6703            // (GAP-380) is the CUDA consumer; a build without the `cuda` feature, or any other
6704            // non-CPU backend, still errors rather than guessing.
6705            #[cfg(feature = "cuda")]
6706            if item.target_backend == BackendId::Cuda {
6707                let gpu_id = match target_location {
6708                    Some(DeviceLocation::Cuda { gpu_id }) => *gpu_id,
6709                    _ => 0,
6710                };
6711                let cuda_dev = devices.cuda(gpu_id).ok_or_else(|| {
6712                    Error::Msg(format!(
6713                        "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."
6714                    ))
6715                    .bt()
6716                })?;
6717                let bytes: Vec<u8> = (0..*len).flat_map(|i| (i as f32).to_le_bytes()).collect();
6718                let cuda_bytes =
6719                    fuel_cuda_backend::CudaStorageBytes::from_cpu_bytes(&cuda_dev, &bytes)?;
6720                let st = Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype);
6721                cache.insert(item.node_id, Arc::new(RwLock::new(st)));
6722                layout_cache.insert(item.node_id, item.output_layout.clone());
6723                return Ok(CompletionHandle::Ready);
6724            }
6725            #[cfg(not(feature = "cuda"))]
6726            let _ = target_location;
6727            if item.target_backend != BackendId::Cpu {
6728                return Err(Error::Msg(format!(
6729                    "WorkItemKind::Iota: only CPU is wired today, got {:?}",
6730                    item.target_backend,
6731                ))
6732                .bt());
6733            }
6734            let v: Vec<f32> = (0..*len).map(|i| i as f32).collect();
6735            let iota = fuel_memory::from_slice_cpu(&v);
6736            cache.insert(item.node_id, Arc::new(RwLock::new(iota)));
6737            layout_cache.insert(item.node_id, item.output_layout.clone());
6738            Ok(CompletionHandle::Ready)
6739        }
6740        WorkItemKind::ZeroFill => {
6741            // Op::ZeroFill: in-place zero the input's bytes. Output
6742            // adopts the input's Storage Arc (same Storage; bytes
6743            // are mutated). Direct per-backend dispatch — no kernel
6744            // call, no binding-table lookup.
6745            if item.inputs.len() != 1 {
6746                return Err(Error::Msg(format!(
6747                    "PipelinedExecutor: ZeroFill work item {:?} expects \
6748                     1 input, got {}",
6749                    item.node_id,
6750                    item.inputs.len(),
6751                ))
6752                .bt());
6753            }
6754            let src_id = item.inputs[0];
6755            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6756                Error::Msg(format!(
6757                    "PipelinedExecutor: ZeroFill input {:?} of {:?} \
6758                     not realized",
6759                    src_id, item.node_id,
6760                ))
6761                .bt()
6762            })?;
6763            // Per-backend in-place fill. Acquired the write lock once
6764            // for the duration of the fill — kernels on async backends
6765            // (CUDA / Vulkan) issue the memset and return; the fence
6766            // happens when downstream readers acquire the read lock
6767            // through the executor's standard synchronization path.
6768            {
6769                let mut guard = src_arc
6770                    .write()
6771                    .map_err(|_| poisoned("ZeroFill destination storage"))?;
6772                match &mut guard.inner {
6773                    fuel_memory::BackendStorage::Cpu(c) => {
6774                        let bytes = c.bytes_mut();
6775                        bytes.fill(0);
6776                    }
6777                    #[cfg(feature = "cuda")]
6778                    fuel_memory::BackendStorage::Cuda(c) => {
6779                        c.zero_async()?;
6780                    }
6781                    #[cfg(feature = "vulkan")]
6782                    fuel_memory::BackendStorage::Vulkan(v) => {
6783                        let backend = v
6784                            .backend()
6785                            .ok_or_else(|| {
6786                                Error::Msg(
6787                                    "Op::ZeroFill on Vulkan: input has no \
6788                                 attached backend handle. Storage must \
6789                                 come from VulkanBackend::alloc_bytes_handle \
6790                                 / upload_bytes_handle."
6791                                        .to_string(),
6792                                )
6793                                .bt()
6794                            })?
6795                            .clone();
6796                        backend.fill_bytes_zero(v)?;
6797                    }
6798                    #[allow(unreachable_patterns)]
6799                    other => {
6800                        return Err(Error::Msg(format!(
6801                            "Op::ZeroFill: backend not wired ({other:?}); \
6802                             CPU + CUDA + Vulkan covered, Metal extends \
6803                             when its byte-storage substrate is ready.",
6804                        ))
6805                        .bt());
6806                    }
6807                }
6808            }
6809            // Adopt the (now-zero) Storage Arc at this node's slot.
6810            // Downstream readers go through `node_id`; the original
6811            // input's NodeId is evicted from the cache by the
6812            // realize loop's destructive_input cleanup.
6813            cache.insert(item.node_id, src_arc);
6814            layout_cache.insert(item.node_id, item.output_layout.clone());
6815            // A4b-1: ZeroFill's CUDA memset is same-stream (and Op::Alloc
6816            // typically zero-inits, so this is usually elided). Its completion
6817            // is carried by the realize-end full-stream sync in `to_cpu_bytes`
6818            // (unchanged) and same-stream ordering — `Ready` is behavior-preserving.
6819            Ok(CompletionHandle::Ready)
6820        }
6821        WorkItemKind::Copy { target_location } | WorkItemKind::Move { target_location } => {
6822            // Op::Copy / Op::Move { target }: kernel lookup at
6823            // (OpKind::Copy, [dt, dt], source_backend) — the wrapper
6824            // downloads from its own residency into a freshly-
6825            // allocated output on `target_location`. We auto-
6826            // contiguize the input first so the kernel always sees
6827            // the logical view's bytes (a transpose-view source
6828            // materializes into a contiguous buffer before download).
6829            //
6830            // Move shares this entire data-movement half; its
6831            // destructive half (release the source) is driven by the
6832            // realize loop's `destructive_input` cleanup after this
6833            // arm returns — see `WorkItemKind::Move`.
6834            let op_label = if matches!(item.kind, WorkItemKind::Move { .. }) {
6835                "Move"
6836            } else {
6837                "Copy"
6838            };
6839            let compiled = item.compiled.as_ref().ok_or_else(|| {
6840                Error::Msg(format!(
6841                    "PipelinedExecutor: {op_label} work item {:?} has no compiled node",
6842                    item.node_id,
6843                ))
6844                .bt()
6845            })?;
6846            if item.inputs.len() != 1 {
6847                return Err(Error::Msg(format!(
6848                    "PipelinedExecutor: {op_label} work item {:?} expects 1 input, got {}",
6849                    item.node_id,
6850                    item.inputs.len(),
6851                ))
6852                .bt());
6853            }
6854            let src_id = item.inputs[0];
6855            let src_arc = cache.get(&src_id).cloned().ok_or_else(|| {
6856                Error::Msg(format!(
6857                    "PipelinedExecutor: {op_label} input {:?} of {:?} not realized",
6858                    src_id, item.node_id,
6859                ))
6860                .bt()
6861            })?;
6862            // Multi-output Option C guard: Op::Copy on a bundled
6863            // producer would silently drop the bundle metadata on
6864            // the destination, and the auto-contiguize step below
6865            // would treat the bundle as a flat slot-0-shaped buffer
6866            // and corrupt non-primary slots. Until the per-backend
6867            // whole-bundle-Copy hook lands, point callers at the
6868            // supported per-slot path:
6869            // Op::View → Op::Copy → Op::ViewOwned.
6870            //
6871            // Exception: when the immediate input is an Op::View
6872            // projection (its layout's byte extent is strictly less
6873            // than the bundle's total bytes), the View has already
6874            // narrowed the slab. auto-contiguize walks the View's
6875            // layout and produces a flat slot-shaped buffer that's
6876            // correctly sized — no data loss, no slot corruption.
6877            // The guard only fires when the Copy targets the bundle
6878            // root directly.
6879            {
6880                let guard = src_arc
6881                    .read()
6882                    .map_err(|_| poisoned("Copy source storage"))?;
6883                if guard.is_bundled() {
6884                    let layout_bytes_for_guard = layout_cache
6885                        .get(&src_id)
6886                        .map(|l| l.shape().elem_count() * guard.dtype.size_in_bytes())
6887                        .unwrap_or(usize::MAX);
6888                    let bundle_bytes = guard.inner.len_bytes();
6889                    let is_whole_bundle = layout_bytes_for_guard >= bundle_bytes;
6890                    if is_whole_bundle {
6891                        return Err(Error::Msg(format!(
6892                            "PipelinedExecutor: Op::{op_label} on a bundled producer \
6893                             ({:?}) is not yet supported (Option C followup). \
6894                             Use Op::View → Op::Copy → Op::ViewOwned for \
6895                             per-slot cross-device moves, or wait for the \
6896                             per-backend whole-bundle-Copy hook.",
6897                            src_id,
6898                        ))
6899                        .bt());
6900                    }
6901                }
6902            }
6903            let src_layout = layout_cache.get(&src_id).cloned().ok_or_else(|| {
6904                Error::Msg(format!(
6905                    "PipelinedExecutor: {op_label} input {:?} of {:?} has no cached layout",
6906                    src_id, item.node_id,
6907                ))
6908                .bt()
6909            })?;
6910            let src_dtype = src_arc
6911                .read()
6912                .map_err(|_| poisoned("Copy source storage"))?
6913                .dtype;
6914            let src_len_bytes = src_arc
6915                .read()
6916                .map_err(|_| poisoned("Copy source storage"))?
6917                .inner
6918                .len_bytes();
6919            let layout_bytes = src_layout.shape().elem_count() * src_dtype.size_in_bytes();
6920            let bytes_match_shape = src_len_bytes == layout_bytes;
6921            let already_contig =
6922                src_layout.is_contiguous() && src_layout.start_offset() == 0 && bytes_match_shape;
6923            let src_input = if already_contig {
6924                src_arc
6925            } else {
6926                auto_contiguize(&src_arc, &src_layout)?
6927            };
6928            let kernel_input_layout = fuel_ir::Layout::contiguous(src_layout.shape().clone());
6929            // CapturedRun build-out (4b-ζ): in Reuse (capture/replay) mode,
6930            // reuse the fixed-address buffer recorded during the warm run
6931            // instead of allocating — device allocation is illegal inside a
6932            // capture scope. Only a same-device CUDA target_location ever
6933            // reaches Reuse mode for a Copy node in practice: capture_decode's
6934            // validation loop rejects every Cpu/Vulkan target_location before
6935            // a capture scope is ever entered (Move is rejected unconditionally
6936            // there too), so this arm trusts that invariant rather than
6937            // re-deriving it — the `DeviceLocation::Cuda` guard below is just
6938            // belt-and-suspenders for any other Reuse-mode caller.
6939            let reuse_arc = match &persistent {
6940                Some(p) if p.mode == PersistentMode::Reuse => match target_location {
6941                    DeviceLocation::Cuda { .. } => p.map.get(&item.node_id).cloned(),
6942                    _ => None,
6943                },
6944                _ => None,
6945            };
6946            // Allocate the output on `target_location`. Phase 2
6947            // covered D2H (target=Cpu); Phase 3b extends to H2D
6948            // (target=Cuda / Vulkan from a CPU source). For non-CPU
6949            // targets the device handle comes from the caller's
6950            // `DeviceRegistry` (a `*_with_devices` entry point), as for
6951            // Op::Alloc.
6952            // Used only by the Vulkan arm below (alloc_bytes_handle); a
6953            // default-feature build sees it unused. GAP-229: 68161981's
6954            // unused_variables --fix renamed it `_n_bytes` at default
6955            // features and broke `--features vulkan` (E0425). Guard the
6956            // decline instead of the name so the binding stays usable.
6957            #[cfg_attr(not(feature = "vulkan"), allow(unused_variables))]
6958            let n_bytes = item.elem_count * item.dtype.size_in_bytes();
6959            let input_arcs = vec![src_input];
6960            let mut output_arcs = if let Some(arc) = reuse_arc {
6961                vec![arc]
6962            } else {
6963                let output = match target_location {
6964                    DeviceLocation::Cpu => {
6965                        fuel_memory::alloc_cpu_zeroed(item.dtype, item.elem_count)?
6966                    }
6967                    #[cfg(feature = "cuda")]
6968                    DeviceLocation::Cuda { gpu_id } => {
6969                        let cuda_dev = devices.cuda(*gpu_id).ok_or_else(|| {
6970                            Error::Msg(format!(
6971                                "Op::{op_label} on Cuda {{ gpu_id: {} }}: no CUDA \
6972                                 device registered for this place. Hand the device to \
6973                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
6974                                 entry point) before an H2D Op::{op_label}.",
6975                                gpu_id,
6976                            ))
6977                            .bt()
6978                        })?;
6979                        let cuda_bytes =
6980                            fuel_cuda_backend::CudaStorageBytes::alloc_uninit(&cuda_dev, n_bytes)?;
6981                        Storage::new(fuel_memory::BackendStorage::Cuda(cuda_bytes), item.dtype)
6982                    }
6983                    #[cfg(not(feature = "cuda"))]
6984                    DeviceLocation::Cuda { .. } => {
6985                        return Err(Error::Msg(format!(
6986                            "Op::{op_label} target Cuda but fuel-storage wasn't built \
6987                             with --features cuda",
6988                        ))
6989                        .bt());
6990                    }
6991                    #[cfg(feature = "vulkan")]
6992                    DeviceLocation::Vulkan { gpu_id } => {
6993                        let backend = devices.vulkan(*gpu_id).ok_or_else(|| {
6994                            Error::Msg(format!(
6995                                "Op::{op_label} on Vulkan {{ gpu_id: {} }}: no Vulkan \
6996                                 device registered for this place. Hand the device to \
6997                                 the realize in a `DeviceRegistry` (a `*_with_devices` \
6998                                 entry point) before an H2D Op::{op_label}.",
6999                                gpu_id,
7000                            ))
7001                            .bt()
7002                        })?;
7003                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
7004                        Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), item.dtype)
7005                    }
7006                    #[cfg(not(feature = "vulkan"))]
7007                    DeviceLocation::Vulkan { .. } => {
7008                        return Err(Error::Msg(format!(
7009                            "Op::{op_label} target Vulkan but fuel-storage wasn't built \
7010                             with --features vulkan",
7011                        ))
7012                        .bt());
7013                    }
7014                    other => {
7015                        return Err(Error::Msg(format!(
7016                            "PipelinedExecutor: Op::{op_label} target_location {:?} not yet \
7017                             wired (CPU + CUDA + Vulkan covered; Metal extends when \
7018                             its byte-storage substrate is ready).",
7019                            other
7020                        ))
7021                        .bt());
7022                    }
7023                };
7024                vec![Arc::new(RwLock::new(output))]
7025            };
7026            let kernel_layouts = vec![kernel_input_layout, item.output_layout.clone()];
7027            // A4b-1: defer the wait — return the handle to the realize loop.
7028            let handle = execute_compiled_with_wait_hint(
7029                compiled,
7030                &input_arcs,
7031                &mut output_arcs,
7032                &kernel_layouts,
7033                will_be_waited,
7034            )?;
7035            let arc = output_arcs.into_iter().next().expect("one output");
7036            // CapturedRun build-out (4b-ζ): Record (warm) mode remembers this
7037            // node's fixed output buffer so the capture run reuses the
7038            // identical device address. No-op in Reuse mode (the buffer came
7039            // FROM the map) and in None mode. Mirrors the Kernel arm's
7040            // Record-mode snapshot (above) exactly.
7041            if let Some(p) = persistent.as_deref_mut()
7042                && p.mode == PersistentMode::Record
7043            {
7044                p.map.insert(item.node_id, Arc::clone(&arc));
7045            }
7046            cache.insert(item.node_id, arc);
7047            layout_cache.insert(item.node_id, item.output_layout.clone());
7048            Ok(handle)
7049        }
7050        WorkItemKind::ReleaseMarker => {
7051            // Emit a zero-byte CPU storage at the Release node's
7052            // slot. Per Op::Release's contract the marker is never
7053            // read — this exists so any downstream cache lookup of
7054            // `release_id` resolves rather than failing. The actual
7055            // deallocation of `inputs[0]` is driven by the realize
7056            // loop's `destructive_input` cleanup (Phase B).
7057            let marker = fuel_memory::alloc_cpu_zeroed(item.dtype, 0)?;
7058            cache.insert(item.node_id, Arc::new(RwLock::new(marker)));
7059            layout_cache.insert(item.node_id, item.output_layout.clone());
7060            Ok(CompletionHandle::Ready)
7061        }
7062        WorkItemKind::ContiguizeOf { input } => {
7063            let input_arc = cache.get(input).cloned().ok_or_else(|| {
7064                Error::Msg(format!(
7065                    "PipelinedExecutor: reshape input {:?} of {:?} not realized",
7066                    input, item.node_id,
7067                ))
7068                .bt()
7069            })?;
7070            let input_layout = layout_cache.get(input).cloned().ok_or_else(|| {
7071                Error::Msg(format!(
7072                    "PipelinedExecutor: reshape input {:?} of {:?} has no cached layout",
7073                    input, item.node_id,
7074                ))
7075                .bt()
7076            })?;
7077            // CapturedRun build-out (4b-γ): in Reuse (capture/replay) mode,
7078            // reuse the fixed-address buffer recorded during the warm run —
7079            // device allocation is illegal inside a capture scope. Always
7080            // write-into when reusing (skip the zero-copy-vs-allocate
7081            // branch entirely): a given ContiguizeOf node's zero-copy-ness
7082            // is a static layout/stride property, identical across the warm
7083            // and capture passes (both replay the same compiled item list
7084            // with the same static layouts per capture_decode's own
7085            // design), so if this node ever needed the map entry it
7086            // allocated on warm too and the entry is guaranteed present.
7087            let reuse_arc = match &persistent {
7088                Some(p) if p.mode == PersistentMode::Reuse => p.map.get(&item.node_id).cloned(),
7089                _ => None,
7090            };
7091            let out_arc = if let Some(dest_arc) = reuse_arc {
7092                contiguize_into(&dest_arc, &input_arc, &input_layout)?;
7093                dest_arc
7094            } else if input_layout.is_contiguous() && input_layout.start_offset() == 0 {
7095                // Zero-copy when the input is already contiguous + zero
7096                // offset — never allocates, so Record mode has nothing to
7097                // record for this node (no fixed address to reuse).
7098                input_arc
7099            } else {
7100                // Allocate + copy via the contiguize kernel.
7101                let arc = auto_contiguize(&input_arc, &input_layout)?;
7102                if let Some(p) = persistent.as_deref_mut()
7103                    && p.mode == PersistentMode::Record
7104                {
7105                    p.map.insert(item.node_id, Arc::clone(&arc));
7106                }
7107                arc
7108            };
7109            cache.insert(item.node_id, out_arc);
7110            layout_cache.insert(item.node_id, item.output_layout.clone());
7111            // A4b-1: a materializing contiguize (CUDA) is same-stream; its
7112            // completion is carried by the realize-end full-stream sync in
7113            // `to_cpu_bytes` (unchanged) — `Ready` here is behavior-preserving.
7114            Ok(CompletionHandle::Ready)
7115        }
7116        WorkItemKind::Kernel => {
7117            let compiled = item.compiled.as_ref().ok_or_else(|| {
7118                Error::Msg(format!(
7119                    "PipelinedExecutor: Kernel work item {:?} has no compiled node",
7120                    item.node_id,
7121                ))
7122                .bt()
7123            })?;
7124            // Dynamic-M matmul (sparse MoE): resolve a DATA-DETERMINED row
7125            // count from the producer-bound `produced_syms` and run against
7126            // the patched (resolved-M) node. `None` on the common path.
7127            let patched_mm = resolve_deferred_matmul(compiled, produced_syms, item.node_id)?;
7128            let compiled = patched_mm.as_ref().unwrap_or(compiled);
7129            // Gather input Arcs from the cache, auto-contiguizing
7130            // any input whose layout is non-contiguous (typically
7131            // produced by an upstream metadata-only view op).
7132            // Today's kernels assume contiguous; this pass keeps
7133            // that invariant true at every kernel call site.
7134            //
7135            // We assemble a parallel `kernel_layouts` vec — the layout
7136            // of the bytes the kernel actually receives. After
7137            // auto-contiguize, that's `Layout::contiguous(shape)` for
7138            // the input's shape; for inputs already contiguous we use
7139            // the cached layout directly. Output layout comes last.
7140            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::with_capacity(item.inputs.len());
7141            let mut kernel_layouts: Vec<fuel_ir::Layout> =
7142                Vec::with_capacity(item.inputs.len() + 1);
7143            // The kernel's `strided_input` cap lets non-contiguous
7144            // inputs (broadcast, transpose, etc.) flow through without
7145            // materialization — the kernel walks strides itself. Inputs
7146            // with non-zero `start_offset` still go through auto-
7147            // Contiguize today; offset honoring on the byte buffer is
7148            // a separate concern from stride support.
7149            let kernel_handles_strided = compiled.caps.strided_input;
7150            let t_gather = crate::compiled::op_profile::PhaseTimer::start("kernel.gather_inputs");
7151            for in_id in &item.inputs {
7152                let in_arc = cache.get(in_id).cloned().ok_or_else(|| {
7153                    Error::Msg(format!(
7154                        "PipelinedExecutor: input {:?} of {:?} not realized",
7155                        in_id, item.node_id,
7156                    ))
7157                    .bt()
7158                })?;
7159                let in_layout = layout_cache.get(in_id).cloned().ok_or_else(|| {
7160                    Error::Msg(format!(
7161                        "PipelinedExecutor: input {:?} of {:?} has no cached layout",
7162                        in_id, item.node_id,
7163                    ))
7164                    .bt()
7165                })?;
7166                // "Already contig" means more than `is_contiguous()`:
7167                // the LAYOUT's element count must also match the
7168                // STORAGE's byte count for shape-validating kernels
7169                // (concat_cpu, etc.) that read `storage.len_bytes()`.
7170                // A first-N slice view has `is_contiguous() == true`
7171                // (strides match canonical [1] for shape [N]) but its
7172                // storage is the parent's full bytes — too big. In
7173                // that case we auto-contiguize to materialize only
7174                // the view's portion as a fresh storage.
7175                //
7176                // Same constraint applies to strided_ok: kernels that
7177                // declare strided support can walk strided inputs, but
7178                // the byte count check at the kernel surface still
7179                // assumes storage.len_bytes() == layout.elem_count() *
7180                // dtype.size_bytes(). Until kernels universally trust
7181                // layout over storage, we conservatively materialize.
7182                let in_dtype = in_arc.read().map_err(|_| poisoned("input storage"))?.dtype;
7183                let in_len_bytes = in_arc
7184                    .read()
7185                    .map_err(|_| poisoned("input storage"))?
7186                    .inner
7187                    .len_bytes();
7188                let layout_bytes = in_layout.shape().elem_count() * in_dtype.size_in_bytes();
7189                let bytes_match_shape = in_len_bytes == layout_bytes;
7190                let already_contig =
7191                    in_layout.is_contiguous() && in_layout.start_offset() == 0 && bytes_match_shape;
7192                let strided_ok =
7193                    kernel_handles_strided && in_layout.start_offset() == 0 && bytes_match_shape;
7194                if already_contig || strided_ok {
7195                    input_arcs.push(in_arc);
7196                    kernel_layouts.push(in_layout);
7197                } else {
7198                    let contig_arc = auto_contiguize(&in_arc, &in_layout)?;
7199                    input_arcs.push(contig_arc);
7200                    kernel_layouts.push(fuel_ir::Layout::contiguous(in_layout.shape().clone()));
7201                }
7202            }
7203            drop(t_gather);
7204            kernel_layouts.push(item.output_layout.clone());
7205
7206            // Allocate output on the target backend. For GPU backends
7207            // we derive the device handle from the first input —
7208            // every kernel has ≥1 input (Op::Const is handled via
7209            // ConstAdopt, never via Kernel), and an input on the
7210            // target backend carries its own device. This avoids
7211            // threading a device handle through `realize`.
7212            //
7213            // Multi-output (Option C, item 3): when the WorkItem
7214            // carries an `output_bundle`, size the allocation to
7215            // span every slot's bytes (primary-dtype-element count
7216            // rounded up from the bundle's total byte span) and
7217            // attach the bundle metadata after allocation.
7218            let (alloc_elem_count, bundle_to_attach) = match &item.output_bundle {
7219                Some(bundle) => {
7220                    let dtype_bytes = item.dtype.size_in_bytes().max(1);
7221                    let total_bytes = bundle.iter().fold(0usize, |acc, s| {
7222                        let end = s.byte_offset.saturating_add(s.len_bytes());
7223                        acc.max(end)
7224                    });
7225                    let elems = total_bytes.div_ceil(dtype_bytes);
7226                    (elems, Some(Arc::clone(bundle)))
7227                }
7228                None => (item.elem_count, None),
7229            };
7230            // CapturedRun build-out: in Reuse (capture/replay) mode, reuse the
7231            // FIXED-ADDRESS buffer recorded during the warm run instead of
7232            // allocating — device allocation is illegal inside a capture scope,
7233            // and reusing the same address is what makes the captured graph's
7234            // baked kernel arguments valid on replay. In Record (warm) or None
7235            // mode, allocate as usual (below).
7236            let reuse_arc = match &persistent {
7237                Some(p) if p.mode == PersistentMode::Reuse => {
7238                    Some(p.map.get(&item.node_id).cloned().ok_or_else(|| {
7239                        Error::Msg(format!(
7240                            "PipelinedExecutor: capture (reuse) mode has no persistent \
7241                             output buffer for kernel node {:?}; the warm (record) run \
7242                             must realize every kernel node before capture",
7243                            item.node_id,
7244                        ))
7245                        .bt()
7246                    })?)
7247                }
7248                _ => None,
7249            };
7250            let t_alloc = crate::compiled::op_profile::PhaseTimer::start("kernel.alloc_output");
7251            let mut output_arcs = if let Some(arc) = reuse_arc {
7252                vec![arc]
7253            } else {
7254                let output = match item.target_backend {
7255                    BackendId::Cpu => fuel_memory::alloc_cpu_zeroed(item.dtype, alloc_elem_count)?,
7256                    #[cfg(feature = "cuda")]
7257                    BackendId::Cuda => {
7258                        let first_in = input_arcs.first().ok_or_else(|| {
7259                            Error::Msg(format!(
7260                                "PipelinedExecutor: kernel {:?} on Cuda has no inputs; \
7261                             cannot derive device for output allocation",
7262                                item.node_id,
7263                            ))
7264                            .bt()
7265                        })?;
7266                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
7267                        let cuda_in = match &guard.inner {
7268                            fuel_memory::BackendStorage::Cuda(c) => c,
7269                            other => {
7270                                return Err(Error::Msg(format!(
7271                                    "PipelinedExecutor: kernel {:?} target_backend=Cuda but \
7272                                 input has BackendStorage::{:?}; mixed-backend kernels \
7273                                 require an explicit Op::Copy first",
7274                                    item.node_id,
7275                                    other.backend_id(),
7276                                ))
7277                                .bt());
7278                            }
7279                        };
7280                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
7281                        let cuda_bytes =
7282                            fuel_cuda_backend::CudaStorageBytes::alloc(cuda_in.device(), n_bytes)?;
7283                        fuel_memory::Storage::new(
7284                            fuel_memory::BackendStorage::Cuda(cuda_bytes),
7285                            item.dtype,
7286                        )
7287                    }
7288                    #[cfg(feature = "vulkan")]
7289                    BackendId::Vulkan => {
7290                        // Mirror the CUDA path: derive the backend handle
7291                        // from the first input's `VulkanStorageBytes::backend()`.
7292                        // Vulkan catch-up V.1.B (2026-05-21) — requires
7293                        // inputs constructed via `alloc_bytes_handle` /
7294                        // `upload_bytes_handle` so they carry the
7295                        // `Arc<VulkanBackend>` (mirroring CUDA's
7296                        // `Arc<CudaDevice>`).
7297                        let first_in = input_arcs.first().ok_or_else(|| {
7298                            Error::Msg(format!(
7299                                "PipelinedExecutor: kernel {:?} on Vulkan has no inputs; \
7300                             cannot derive backend handle for output allocation",
7301                                item.node_id,
7302                            ))
7303                            .bt()
7304                        })?;
7305                        let guard = first_in.read().map_err(|_| poisoned("input storage"))?;
7306                        let vk_in = match &guard.inner {
7307                            fuel_memory::BackendStorage::Vulkan(v) => v,
7308                            other => {
7309                                return Err(Error::Msg(format!(
7310                                    "PipelinedExecutor: kernel {:?} target_backend=Vulkan but \
7311                                 input has BackendStorage::{:?}; mixed-backend kernels \
7312                                 require an explicit Op::Copy first",
7313                                    item.node_id,
7314                                    other.backend_id(),
7315                                ))
7316                                .bt());
7317                            }
7318                        };
7319                        let backend = vk_in.backend().ok_or_else(|| {
7320                            Error::Msg(format!(
7321                                "PipelinedExecutor: Vulkan kernel {:?} input has no backend \
7322                             handle. Storages flowing through the pipelined executor's \
7323                             Vulkan path must be constructed via \
7324                             VulkanBackend::alloc_bytes_handle / upload_bytes_handle \
7325                             (not the legacy alloc_bytes / upload_bytes which leave \
7326                             VulkanStorageBytes::backend = None).",
7327                                item.node_id,
7328                            ))
7329                            .bt()
7330                        })?;
7331                        let n_bytes = alloc_elem_count * item.dtype.size_in_bytes();
7332                        let vk_bytes = backend.alloc_bytes_handle(n_bytes)?;
7333                        fuel_memory::Storage::new(
7334                            fuel_memory::BackendStorage::Vulkan(vk_bytes),
7335                            item.dtype,
7336                        )
7337                    }
7338                    other => {
7339                        return Err(Error::Msg(format!(
7340                            "PipelinedExecutor: target_backend {:?} output allocation \
7341                         not yet implemented (CPU + CUDA + Vulkan wired; Metal extends later)",
7342                            other
7343                        ))
7344                        .bt());
7345                    }
7346                };
7347                // Attach bundle metadata when this is a multi-output op.
7348                // The kernel sees the allocated bytes; the bundle lives
7349                // at the Storage wrapper level so downstream Op::View /
7350                // Op::ViewOwned can resolve their slot windows.
7351                let output = match bundle_to_attach {
7352                    Some(bundle) => output.with_bundle(bundle)?,
7353                    None => output,
7354                };
7355                vec![Arc::new(RwLock::new(output))]
7356            };
7357            drop(t_alloc);
7358
7359            // A4b-1: defer the wait — return the handle to the realize loop.
7360            let t_launch =
7361                crate::compiled::op_profile::PhaseTimer::start("kernel.execute_compiled");
7362            let handle = execute_compiled_with_wait_hint(
7363                compiled,
7364                &input_arcs,
7365                &mut output_arcs,
7366                &kernel_layouts,
7367                will_be_waited,
7368            )?;
7369            drop(t_launch);
7370            #[cfg(feature = "cuda")]
7371            if item.target_backend == BackendId::Cuda
7372                && let Some(reads) = index_reads
7373            {
7374                note_index_read(reads, &compiled.op_params, &input_arcs)?;
7375            }
7376
7377            let arc = output_arcs.into_iter().next().expect("one output");
7378
7379            // CapturedRun build-out: Record (warm) mode remembers this node's
7380            // fixed output buffer so the capture run reuses the identical
7381            // device address. No-op in Reuse mode (the buffer came FROM the
7382            // map) and in None mode.
7383            if let Some(p) = persistent
7384                && p.mode == PersistentMode::Record
7385            {
7386                p.map.insert(item.node_id, Arc::clone(&arc));
7387            }
7388
7389            // Data-determined dynamic-shapes seam (increment 2a): a
7390            // producer that computes a runtime count publishes it into the
7391            // per-pass `SymEnv` so downstream ops can consume it as a
7392            // dynamic extent. `Op::NonZeroIndices` writes its count into
7393            // bundle slot 1; read it back and bind `count_sym`. This is the
7394            // FIRST op to bind a *data-determined* symbol mid-realize (all
7395            // prior binds are host-known before realize). Single-threaded:
7396            // the executor runs items topologically, so this bind precedes
7397            // any consumer's execute-time resolution.
7398            if let OpParams::NonZeroIndices {
7399                capacity,
7400                count_sym,
7401            } = &compiled.op_params
7402            {
7403                bind_data_determined_count(&arc, *capacity, *count_sym, produced_syms)?;
7404            }
7405
7406            cache.insert(item.node_id, arc);
7407            layout_cache.insert(item.node_id, item.output_layout.clone());
7408            Ok(handle)
7409        }
7410        WorkItemKind::InplaceKernel { target_idx } => {
7411            let compiled = item.compiled.as_ref().ok_or_else(|| {
7412                Error::Msg(format!(
7413                    "PipelinedExecutor: InplaceKernel work item {:?} has no compiled node",
7414                    item.node_id,
7415                ))
7416                .bt()
7417            })?;
7418            let target_id = *item.inputs.get(*target_idx).ok_or_else(|| {
7419                Error::Msg(format!(
7420                    "PipelinedExecutor: InplaceKernel work item {:?} target_idx={} \
7421                     out of bounds (inputs.len()={})",
7422                    item.node_id,
7423                    target_idx,
7424                    item.inputs.len(),
7425                ))
7426                .bt()
7427            })?;
7428            let target_arc = cache.get(&target_id).cloned().ok_or_else(|| {
7429                Error::Msg(format!(
7430                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} not realized",
7431                    target_id, item.node_id,
7432                ))
7433                .bt()
7434            })?;
7435            let target_layout = layout_cache.get(&target_id).cloned().ok_or_else(|| {
7436                Error::Msg(format!(
7437                    "PipelinedExecutor: InplaceKernel target {:?} of {:?} has no cached layout",
7438                    target_id, item.node_id,
7439                ))
7440                .bt()
7441            })?;
7442            // v1 contract: target must be contiguous + zero offset.
7443            // Strided in-place targets would force the kernel to walk
7444            // strides for writes too; defer until a concrete consumer
7445            // needs it (mirrors `Op::WriteSlice`'s v1 dest contract).
7446            if !target_layout.is_contiguous() || target_layout.start_offset() != 0 {
7447                return Err(Error::Msg(format!(
7448                    "InplaceKernel (Phase 3 v1): target {:?} must be contiguous + \
7449                     zero-offset; got Layout {:?}",
7450                    target_id, target_layout,
7451                ))
7452                .bt());
7453            }
7454            // Kernel sees inputs=[non-target IR inputs in order] and
7455            // outputs=[target_arc]. For unary in-place (1 IR input at
7456            // target_idx=0) the input vec is empty, matching the
7457            // original Phase 3e contract. For binary in-place
7458            // (target_idx=0, 2 IR inputs) the wrapper sees the
7459            // non-destructive RHS as `inputs[0]`. The wrapper acquires
7460            // outputs[0]'s write lock and mutates through its
7461            // bytes_mut(). Layout vector contains the kernel's
7462            // inputs+outputs layouts in that order.
7463            let mut input_arcs: Vec<Arc<RwLock<Storage>>> = Vec::new();
7464            let mut kernel_layouts: Vec<Layout> = Vec::new();
7465            for (i, &input_id) in item.inputs.iter().enumerate() {
7466                if i == *target_idx {
7467                    continue;
7468                }
7469                let arc = cache.get(&input_id).cloned().ok_or_else(|| {
7470                    Error::Msg(format!(
7471                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7472                         not realized",
7473                        input_id, item.node_id,
7474                    ))
7475                    .bt()
7476                })?;
7477                let lay = layout_cache.get(&input_id).cloned().ok_or_else(|| {
7478                    Error::Msg(format!(
7479                        "PipelinedExecutor: InplaceKernel non-target input {:?} of {:?} \
7480                         has no cached layout",
7481                        input_id, item.node_id,
7482                    ))
7483                    .bt()
7484                })?;
7485                input_arcs.push(arc);
7486                kernel_layouts.push(lay);
7487            }
7488            let mut output_arcs = vec![target_arc.clone()];
7489            kernel_layouts.push(target_layout.clone());
7490            // A4b-1: defer the wait — return the handle to the realize loop.
7491            let handle = execute_compiled_with_wait_hint(
7492                compiled,
7493                &input_arcs,
7494                &mut output_arcs,
7495                &kernel_layouts,
7496                will_be_waited,
7497            )?;
7498            // Adopt the target Arc at this node's slot. The realize
7499            // loop's destructive_input cleanup evicts the target's own
7500            // NodeId from the cache afterward.
7501            cache.insert(item.node_id, target_arc);
7502            layout_cache.insert(item.node_id, item.output_layout.clone());
7503            Ok(handle)
7504        }
7505    }
7506}
7507
7508fn poisoned(what: &'static str) -> Error {
7509    Error::Msg(format!("PipelinedExecutor: {} poisoned", what)).bt()
7510}
7511
7512/// Step E A4b-1: record a node's [`CompletionHandle`] in the executor's
7513/// per-node handle map.
7514///
7515/// `Ready` handles (CPU / Vulkan / view-and-alloc arms) carry no async work, so
7516/// we DON'T store them — keeping the map to genuinely-pending entries makes the
7517/// realize-end empty-after-drain assert (open question #6) meaningful and keeps
7518/// the drain O(pending) rather than O(nodes). A re-used NodeId (in-place adopt
7519/// re-keys an existing slot) waits the prior handle first so nothing leaks.
7520#[inline]
7521/// ROADMAP row 158: after a kernel node was submitted, add its compile-time estimate to the device it
7522/// landed on. The device comes from the OUTPUT storage (the same source `produce_pending` reads), so a
7523/// node stamped for one backend but realized elsewhere is priced where it actually runs. Nothing is added
7524/// for a non-kernel item, a CPU output, a `0` estimate, or a storage that cannot name its device.
7525fn feed_backlog(
7526    ledger: &mut crate::dispatch::BacklogLedger,
7527    cache: &StorageCache,
7528    item: &WorkItem,
7529) {
7530    // OFF by default (`FUEL_BACKLOG_FEED`, `set_backlog_feed_enabled`): see `dispatch::BACKLOG_FEED_ENV`.
7531    if !crate::dispatch::backlog_feed_enabled() {
7532        return;
7533    }
7534    // Take back what the GPU has already finished first, so the picker reads QUEUED work, not everything
7535    // this realize has submitted so far.
7536    ledger.retire_completed();
7537    let Some(compiled) = item.compiled.as_ref() else {
7538        return;
7539    };
7540    if !matches!(item.kind, WorkItemKind::Kernel) || compiled.est_ns == 0 {
7541        return;
7542    }
7543    let Some(arc) = cache.get(&item.node_id) else {
7544        return;
7545    };
7546    let Ok(guard) = arc.read() else {
7547        return;
7548    };
7549    if let Some(loc) = guard.inner.location() {
7550        match completion_probe(&guard.inner) {
7551            Some(done) if !crate::dispatch::backlog_retire_disabled() => {
7552                ledger.add_until(loc, compiled.est_ns, done)
7553            }
7554            _ => ledger.add(loc, compiled.est_ns),
7555        }
7556    }
7557}
7558
7559/// A non-blocking "has the work just submitted into this storage finished?" probe, from the backend that
7560/// holds it (ROADMAP row 158): Vulkan reads its dispatch clock against the count stamped now, after the
7561/// kernel was recorded; CUDA records an event on the device stream now and queries it. `None` for a backend
7562/// with no probe (the estimate then stays until the end of the realize).
7563fn completion_probe(
7564    inner: &fuel_memory::BackendStorage,
7565) -> Option<Box<dyn Fn() -> bool + Send + Sync>> {
7566    match inner {
7567        #[cfg(feature = "vulkan")]
7568        fuel_memory::BackendStorage::Vulkan(v) => {
7569            let clock = v.backend()?.dispatch_clock();
7570            let stamp = clock.recorded();
7571            Some(Box::new(move || clock.retired() >= stamp))
7572        }
7573        #[cfg(feature = "cuda")]
7574        fuel_memory::BackendStorage::Cuda(c) => {
7575            let ev = c.record_completion_event().ok()?;
7576            // A failed query counts as finished: a fault surfaces at the realize's own sync, and the
7577            // estimate must not stay on the backlog because the probe could not answer.
7578            Some(Box::new(move || ev.is_complete().unwrap_or(true)))
7579        }
7580        #[allow(unreachable_patterns)]
7581        _ => None,
7582    }
7583}
7584
7585fn store_handle(
7586    handles: &mut HashMap<NodeId, CompletionHandle>,
7587    node_id: NodeId,
7588    handle: CompletionHandle,
7589) {
7590    if matches!(handle, CompletionHandle::Ready) {
7591        // A prior pending handle at this slot must still be waited (don't drop a
7592        // Pending silently). In practice NodeIds are unique per realize, so this
7593        // is just defensive.
7594        if let Some(prev) = handles.remove(&node_id) {
7595            let _ = prev.wait();
7596        }
7597        return;
7598    }
7599    if let Some(prev) = handles.insert(node_id, handle) {
7600        let _ = prev.wait();
7601    }
7602}
7603
7604/// Step E A4b-3: the FINER cross-device producer wait.
7605///
7606/// Before dispatching a cross-device `Op::Copy` / `Op::Move` WorkItem, the
7607/// executor calls this on the copy's single source input. It removes the
7608/// source producer's [`CompletionHandle`] from the map and waits it — so the
7609/// specific producer P is complete before the D2H reads P's device buffer,
7610/// WITHOUT draining the whole source device (the conservative pre-A4b-3
7611/// behavior, where `to_cpu_bytes`'s `device.synchronize()` blocked on ALL
7612/// in-flight work on that device — including the OTHER sub-DAG's independent
7613/// work A4b-4 wants to overlap).
7614///
7615/// - **CUDA producer** → waits P's recorded `Event` (`cuEventSynchronize`):
7616///   fires after P + its already-ordered stream predecessors, nothing else.
7617/// - **Absent / `Ready` producer** (CPU producer, or a Vulkan producer — which
7618///   under A4b-2 is `Ready` mid-walk because nothing is submitted until
7619///   realize-end) → no-op. A Vulkan SOURCE's own ordering is handled inside
7620///   `download_bytes` (it `force_flush`es the open batch then reads), so there
7621///   is no mid-walk Vulkan handle to wait here; the cross-device Vulkan→CPU hop
7622///   stays correct without one.
7623///
7624/// Removing the handle here (rather than waiting it again at realize-end) keeps
7625/// `drain_handles`' post-drain empty-map assert meaningful and avoids a
7626/// double-wait. Waiting it twice would be harmless (`cuEventSynchronize` on an
7627/// already-signalled event is a fast no-op), but the consume-once contract is
7628/// cleaner. The producing node's *storage* stays in the cache for downstream
7629/// readers; only its completion handle is consumed.
7630fn wait_producer_handle(
7631    handles: &mut HashMap<NodeId, CompletionHandle>,
7632    producer: NodeId,
7633) -> Result<()> {
7634    if let Some(handle) = handles.remove(&producer) {
7635        handle.wait()?;
7636    }
7637    Ok(())
7638}
7639
7640/// Step E A4b-1: realize-end drain — wait every outstanding async handle, then
7641/// clear the map.
7642///
7643/// **Event-recording / wait strategy (A4b-1 §1.2).** CUDA has one stream per
7644/// device, and an `Event` recorded after a node's launch signals when that
7645/// node *and all prior stream work* have completed. So once the
7646/// latest-recorded event on a device has signalled, every earlier event on that
7647/// device is already signalled too: waiting them is a non-blocking
7648/// `cuEventQuery` fast-path, not N host stalls. We therefore wait every stored
7649/// handle (correct + simple).
7650///
7651/// **Open question #4 — "event only where waited" — RESOLVED.** Recording an
7652/// `Event` for every node was measured negligible on a 32-op synthetic, but
7653/// real decode graphs run 150-200+ ops; `pipelined`'s `WaitSet` pre-scan (see
7654/// `compiler_work_and_wait_set_for` / `build_wait_set`) now restricts event
7655/// production to the nodes some later cross-device `Copy`/`Move` will
7656/// individually wait — same-device-only ("elided") nodes get
7657/// `CompletionHandle::Ready` with no `cuEventCreate`/`cuEventRecord` at all
7658/// (`execute_compiled_with_wait_hint`). This drain therefore now retires only
7659/// the (typically few) wait-set handles that were never consumed mid-walk by
7660/// `wait_producer_handle`; it is no longer sufficient on its own to guarantee
7661/// every enqueued CUDA kernel has completed — `sync_active_cuda_devices` below
7662/// covers the elided remainder. We keep a per-node handle (rather than a
7663/// single per-device event) for the wait-set members because A4b-3's finer
7664/// cross-device wait needs to wait a *specific producer's* completion — the
7665/// per-node handle is that seam.
7666fn drain_handles(handles: &mut HashMap<NodeId, CompletionHandle>) -> Result<()> {
7667    for (_node, handle) in handles.drain() {
7668        handle.wait()?;
7669    }
7670    // Open question #6: once handles are stored instead of `wait`ed inline, the
7671    // `#[must_use]` on `CompletionHandle` can't catch a leaked (never-waited)
7672    // handle at the call site. The drain consumes the whole map, so it is empty
7673    // here by construction; assert it to catch a future leak (e.g. a new
7674    // dispatch path that forgets to thread its handle through `store_handle`).
7675    debug_assert!(
7676        handles.is_empty(),
7677        "A4b-1: handle map must be empty after drain"
7678    );
7679    Ok(())
7680}
7681
7682/// Step E A4b open question #4 step 3 — the realize-end complement to the
7683/// "event only where waited" elision. Because most CUDA nodes in a long
7684/// single-device chain no longer record an `Event` (see `drain_handles`'s
7685/// doc), this does ONE blanket `cuStreamSynchronize` per CUDA device that
7686/// still holds LIVE storage in `cache` — the realize target(s) plus any
7687/// surviving intermediates — instead of relying on per-node handles to cover
7688/// them.
7689///
7690/// **Why this is safe + sufficient.** CUDA has one stream per device, and
7691/// this executor dispatches strictly sequentially (one work item at a time,
7692/// in topological order) — so by the time a live node's own kernel was
7693/// launched, every same-device ancestor it depends on was ALREADY enqueued
7694/// earlier on the SAME stream. Stream ordering (not a host wait) guarantees
7695/// those ancestors run to completion no later than the live node's own
7696/// kernel. Syncing the live node's device therefore flushes its entire
7697/// same-device dependency chain, elided or not. Cross-device ancestors are
7698/// unaffected by elision — they always went through an `Op::Copy`/`Move`,
7699/// whose producer is in the `WaitSet` and was already waited explicitly at
7700/// the cross-device boundary (`wait_producer_handle`), mid-walk.
7701///
7702/// **Why evicted (non-live) intermediates don't need this.** A node whose
7703/// storage was evicted before realize-end (the `destructive_input` cleanup)
7704/// is never read by anything this realize returns; A3's stream-ordered
7705/// alloc/free already makes its eventual completion safe without a host
7706/// wait (the driver serializes the free after the freeing stream position,
7707/// same as any other stream-ordered op) — nothing to synchronize for.
7708///
7709/// No-op when `cache` holds no CUDA storage (CPU/Vulkan-only realize).
7710#[cfg(feature = "cuda")]
7711fn sync_active_cuda_devices(cache: &StorageCache) -> Result<()> {
7712    let mut devices: HashMap<fuel_ir::DeviceLocation, fuel_cuda_backend::CudaDevice> =
7713        HashMap::new();
7714    for arc in cache.values() {
7715        let guard = arc
7716            .read()
7717            .map_err(|_| poisoned("cache storage (cuda realize-end sync scan)"))?;
7718        if let fuel_memory::BackendStorage::Cuda(c) = &guard.inner {
7719            devices
7720                .entry(c.device().location())
7721                .or_insert_with(|| c.device().clone());
7722        }
7723    }
7724    for dev in devices.values() {
7725        dev.synchronize()?;
7726    }
7727    Ok(())
7728}
7729
7730/// Non-CUDA builds never produce CUDA storage, so there is nothing to sync —
7731/// keeps the call site unconditional across both feature configurations.
7732#[cfg(not(feature = "cuda"))]
7733fn sync_active_cuda_devices(_cache: &StorageCache) -> Result<()> {
7734    Ok(())
7735}
7736
7737/// Step E A4b-2: a Vulkan [`Completion`](crate::compiled::Completion) over an
7738/// in-flight (submitted, not-yet-waited) batch. `wait` blocks on the batch's
7739/// fence (`vkWaitForFences`) — which fires when the whole submitted command
7740/// buffer has retired on the single compute queue — then releases the batch
7741/// (frees the CB / descriptor sets / transient buffers / retired pool, all now
7742/// idle on the GPU).
7743///
7744/// The fence is per-BATCH, not per-node: one `submit_pending` flushes every op
7745/// recorded since the last submit, so this single handle covers a contiguous run
7746/// of Vulkan nodes (the A2 batching win, preserved — fewer fences, larger
7747/// submissions). `backend` keeps the [`VulkanBackend`] alive so the
7748/// post-fence pool retire + the `DeviceInner` the batch's resources reference
7749/// outlive the wait.
7750///
7751/// `Send` (required by `Completion`): every owned field is `Send` — `Fence` /
7752/// `CommandBuffer` / `DescriptorSet` / `Buffer` / `Allocation` / `CommandPool`
7753/// are all `Send` in vulkane (Arc-of-`DeviceInner` + explicit `unsafe impl`s),
7754/// and `Arc<VulkanBackend>` is `Send + Sync`.
7755/// Step E B1: `batch` is an `Option` ONLY so [`Drop`] can coexist with the
7756/// by-value `into_wait` consume. A type with a `Drop` impl cannot be
7757/// destructured by move (`let VulkanCompletion { backend, batch } = self`,
7758/// E0509), so `into_wait` `take()`s the batch out of the `Option` instead of
7759/// moving it out of the struct, then lets the normal `Drop` run. In every
7760/// reachable state the batch is `Some` until exactly one `into_wait` consumes it.
7761#[cfg(feature = "vulkan")]
7762struct VulkanCompletion {
7763    backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7764    batch: Option<fuel_vulkan_backend::SubmittedBatch>,
7765    /// The device this submitted batch counts against in the in-flight counter
7766    /// (Step E B1). `Drop` decrements this slot.
7767    loc: fuel_ir::DeviceLocation,
7768}
7769
7770/// Step E A4b-4: the element type of the executor's in-flight-Vulkan-batch list.
7771/// A [`VulkanCompletion`] on a Vulkan build; a zero-sized placeholder otherwise
7772/// so the realize loops carry one `Vec<InflightVulkan>` local without `cfg` on
7773/// every use site (the helpers `eager_submit_all_vulkan` / `drain_inflight_vulkan`
7774/// are the only code that ever pushes/drains it, and they are `cfg`-gated).
7775#[cfg(feature = "vulkan")]
7776type InflightVulkan = VulkanCompletion;
7777#[cfg(not(feature = "vulkan"))]
7778type InflightVulkan = ();
7779
7780/// Step E A4b-4: is the cross-device copy's SOURCE buffer Vulkan-resident?
7781///
7782/// Used at the cross-device `Op::Copy`/`Op::Move` boundary to decide whether the
7783/// executor must wait the in-flight Vulkan batches before the copy. A Vulkan→CPU
7784/// D2H reads the source on the host, and the Vulkan `download` path only
7785/// `force_flush`es the OPEN batch (never the executor's eagerly-submitted
7786/// in-flight ones), so for a VULKAN source we must `drain_inflight_vulkan` first
7787/// to read completed data. For a CUDA / CPU source we must NOT wait Vulkan — the
7788/// copy doesn't read any Vulkan buffer, and waiting Vulkan there would needlessly
7789/// serialize the independent Vulkan sub-DAG (killing the overlap A4b-4 exists to
7790/// win). Returns `false` when the producer's storage isn't in the cache (treated
7791/// as not-Vulkan → no Vulkan wait; the CUDA/CPU producer handle still covers it).
7792#[cfg(feature = "vulkan")]
7793fn copy_source_is_vulkan(cache: &StorageCache, producer: NodeId) -> Result<bool> {
7794    if let Some(arc) = cache.get(&producer) {
7795        let guard = arc
7796            .read()
7797            .map_err(|_| poisoned("storage lock probing copy-source backend"))?;
7798        return Ok(matches!(
7799            guard.inner,
7800            fuel_memory::BackendStorage::Vulkan(_)
7801        ));
7802    }
7803    Ok(false)
7804}
7805
7806#[cfg(not(feature = "vulkan"))]
7807#[inline]
7808fn copy_source_is_vulkan(_cache: &StorageCache, _producer: NodeId) -> Result<bool> {
7809    Ok(false)
7810}
7811
7812#[cfg(feature = "vulkan")]
7813impl crate::compiled::Completion for VulkanCompletion {
7814    fn wait(self: Box<Self>) -> Result<()> {
7815        // Move the whole `VulkanCompletion` out of the `Box` (allowed even with a
7816        // `Drop` impl — it's a full move, not a destructure) and consume by value.
7817        (*self).into_wait()
7818    }
7819}
7820
7821#[cfg(feature = "vulkan")]
7822impl VulkanCompletion {
7823    /// Build the handle for an eagerly-submitted Vulkan batch and register it as
7824    /// one in-flight batch on `loc` (Step E B1). The matching decrement is in
7825    /// [`Drop`]. `loc` is the backend's `DeviceLocation::Vulkan { gpu_id }`.
7826    fn new(
7827        backend: Arc<fuel_vulkan_backend::VulkanBackend>,
7828        batch: fuel_vulkan_backend::SubmittedBatch,
7829        loc: fuel_ir::DeviceLocation,
7830    ) -> Self {
7831        crate::dispatch::inflight_inc(loc);
7832        Self {
7833            backend,
7834            batch: Some(batch),
7835            loc,
7836        }
7837    }
7838
7839    /// Block on this batch's fence, retire pools, then free the batch. Consumes
7840    /// `self` by value (the by-value sibling of the boxed `Completion::wait`),
7841    /// used by the executor's `inflight_vulkan` drain (A4b-4) where we hold the
7842    /// `VulkanCompletion` unboxed in a `Vec`.
7843    ///
7844    /// Step E B1: `take()`s the batch out of the `Option` (NOT a destructure
7845    /// move — that's illegal with a `Drop` impl) and waits it; the in-flight
7846    /// decrement then rides `self`'s `Drop` as this returns. So a wait-consume
7847    /// and a bare drop (e.g. an error unwinding before the wait) BOTH decrement
7848    /// exactly once, and `into_wait` never double-counts.
7849    fn into_wait(mut self) -> Result<()> {
7850        // `wait_submitted` consumes the batch by value: waits the fence, retires
7851        // pools, then drops the batch (UAF-safe — nothing the in-flight CB
7852        // references frees before the fence signals). After a `new` the batch is
7853        // always `Some`; `take` leaves `None` so `Drop` doesn't touch it again.
7854        if let Some(batch) = self.batch.take() {
7855            self.backend.wait_submitted(batch)?;
7856        }
7857        Ok(())
7858        // `self` drops here → `inflight_dec(self.loc)`.
7859    }
7860
7861    /// Step E A2.1 (deferred-deletion): retain an evicted DATA buffer until THIS
7862    /// in-flight batch's fence signals, then free it post-fence (on the batch's
7863    /// `Drop` — guaranteed post-fence by follow-on #2). Delegates to
7864    /// [`fuel_vulkan_backend::SubmittedBatch::retain_buffer`].
7865    ///
7866    /// The executor calls this for every in-flight batch when it evicts a Vulkan
7867    /// buffer those batches' CBs may read, INSTEAD of host-blocking on a drain.
7868    /// `batch` is `Some` in every reachable mid-walk state (it is `take`n only by
7869    /// `into_wait`/`wait`, which consume the whole `VulkanCompletion`), so the
7870    /// retain always lands on a live in-flight batch.
7871    fn retain_data(&mut self, buf: std::sync::Arc<fuel_vulkan_backend::VulkanBuffer>) {
7872        if let Some(batch) = self.batch.as_mut() {
7873            batch.retain_buffer(buf);
7874        }
7875    }
7876}
7877
7878#[cfg(feature = "vulkan")]
7879impl Drop for VulkanCompletion {
7880    fn drop(&mut self) {
7881        // The single in-flight decrement for a Vulkan batch — fires whether the
7882        // batch was waited (`into_wait` / `wait`) or merely dropped (error
7883        // unwind), so the per-device count returns to baseline. Relaxed +
7884        // saturating (a scheduling hint, never a correctness gate).
7885        crate::dispatch::inflight_dec(self.loc);
7886    }
7887}
7888
7889/// Step E A4b-4 — eager Vulkan submission during the walk (the OVERLAP enabler).
7890///
7891/// Submits each DISTINCT Vulkan backend's currently-open batch WITHOUT waiting,
7892/// pushing the resulting in-flight [`VulkanCompletion`]s onto `inflight` so the
7893/// executor waits them later (at the in-flight-lifetime guard / realize-end). An
7894/// empty open batch yields `None` and is skipped (idempotent).
7895///
7896/// This is what makes a Vulkan sub-DAG actually START on the iGPU while the
7897/// executor records/dispatches the next (CUDA) chunk — without it the Vulkan
7898/// batch sits merely *recorded* until realize-end and never overlaps the CUDA
7899/// stream (design §5). Called ONLY on a genuinely multi-backend realize (gated by
7900/// the executor's `multi_backend` flag); on a single-device graph it is never
7901/// reached, so pure-Vulkan stays byte-identical to A4b-2 (one realize-end submit).
7902///
7903/// **Whole-chunk granularity (UAF/race-safety, design §4 + the Vulkan
7904/// single-queue OOO-completion semantics).** We submit only at chunk boundaries
7905/// and before a cross-device wait — never mid-chunk — so the batch handed to the
7906/// GPU is a COMPLETE contiguous run of Vulkan nodes with all its intra-CB
7907/// dependency barriers (`recorder.rs` `vkCmdPipelineBarrier`) already in place.
7908/// Vulkan only guarantees that batches on one queue BEGIN in submission order;
7909/// they may overlap / complete out of order, so a split mid-chunk would lose the
7910/// write-before-read ordering for ops that read an earlier op's buffer in the
7911/// SAME chunk. By submitting whole chunks and re-syncing (`drain_inflight_vulkan`)
7912/// before any later Vulkan op records, before any cross-device copy, and before
7913/// any Vulkan-referenced eviction, no in-flight batch is ever read or freed while
7914/// still running.
7915#[cfg(feature = "vulkan")]
7916fn eager_submit_all_vulkan(
7917    cache: &StorageCache,
7918    inflight: &mut Vec<VulkanCompletion>,
7919) -> Result<()> {
7920    // Collect distinct Vulkan backends referenced by the cache (dedup by gpu_id).
7921    let mut seen: Vec<usize> = Vec::new();
7922    let mut backends: Vec<Arc<fuel_vulkan_backend::VulkanBackend>> = Vec::new();
7923    for arc in cache.values() {
7924        let guard = arc
7925            .read()
7926            .map_err(|_| poisoned("storage lock during eager vulkan submit"))?;
7927        if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
7928            && let Some(backend) = v.backend()
7929            && !seen.contains(&backend.gpu_id)
7930        {
7931            seen.push(backend.gpu_id);
7932            backends.push(backend.clone());
7933        }
7934    }
7935    for backend in backends {
7936        // Step E B1: the per-device location for the in-flight counter. A batch
7937        // submitted here is one in-flight unit on this iGPU until its handle's
7938        // `Drop` (after `drain_inflight_vulkan` / realize-end).
7939        let loc = DeviceLocation::Vulkan {
7940            gpu_id: backend.gpu_id,
7941        };
7942        if let Some(batch) = backend.submit_pending()? {
7943            inflight.push(VulkanCompletion::new(backend, batch, loc));
7944        }
7945    }
7946    Ok(())
7947}
7948
7949#[cfg(not(feature = "vulkan"))]
7950#[inline]
7951fn eager_submit_all_vulkan(
7952    _cache: &StorageCache,
7953    _inflight: &mut Vec<InflightVulkan>,
7954) -> Result<()> {
7955    Ok(())
7956}
7957
7958/// Step E A4b-4 — wait every in-flight (eagerly-submitted) Vulkan batch, then
7959/// clear the list. The re-sync half of [`eager_submit_all_vulkan`].
7960///
7961/// Each `into_wait` blocks on the batch fence (`vkWaitForFences`), retires the
7962/// backend's descriptor pools, and frees the batch (CB / descriptor sets /
7963/// transient buffers / retired command pool — all now idle on the GPU). After
7964/// this returns, NO submitted Vulkan command buffer is still executing, so it is
7965/// safe to (a) record a new Vulkan op that may read a just-produced buffer,
7966/// (b) D2H-copy a Vulkan buffer on the host, or (c) free a buffer a batch read.
7967///
7968/// Because the eager submit happened at the PRIOR chunk boundary and an
7969/// intervening (e.g. CUDA) chunk has since been recorded/dispatched, the fence is
7970/// typically already signalled here — the wait is a fast no-op, and the iGPU work
7971/// genuinely overlapped the other device's stream. Waiting the Vulkan fence does
7972/// NOT touch the CUDA stream, so the other device keeps running (concurrency
7973/// preserved — design §5 "the per-device guards don't cross-stall").
7974#[cfg(feature = "vulkan")]
7975fn drain_inflight_vulkan(inflight: &mut Vec<VulkanCompletion>) -> Result<()> {
7976    for vc in inflight.drain(..) {
7977        vc.into_wait()?;
7978    }
7979    Ok(())
7980}
7981
7982#[cfg(not(feature = "vulkan"))]
7983#[inline]
7984fn drain_inflight_vulkan(_inflight: &mut Vec<InflightVulkan>) -> Result<()> {
7985    Ok(())
7986}
7987
7988/// Step E A4b-2: the realize-end Vulkan drain, SPLIT into submit-then-wait.
7989///
7990/// Replaces A2's `force_flush_all_vulkan` (which submitted + waited atomically
7991/// inside `force_flush`). For each DISTINCT Vulkan backend referenced by the
7992/// cache, `submit_pending` submits the still-open batch WITHOUT waiting (→ a
7993/// `SubmittedBatch`), wraps it in the executor's [`VulkanCompletion`] handle, and
7994/// `wait`s it. Net for a pure-Vulkan realize: the batch still accumulates across
7995/// the whole walk (the per-op path keeps returning `Ready`; no eager submit —
7996/// that is A4b-4) and is submitted ONCE here, then waited — **byte-identical to
7997/// A2**, same single submission at realize-end, just split through the handle.
7998///
7999/// Idempotent across repeated cache arcs: the first `submit_pending` on a backend
8000/// returns `Some(batch)`; subsequent calls on the same backend see an empty batch
8001/// and return `None` (skipped) — exactly the `force_flush` idempotence A2 relied
8002/// on. No-op for a non-Vulkan build.
8003#[cfg(feature = "vulkan")]
8004fn drain_vulkan_pending(cache: &StorageCache) -> Result<()> {
8005    use crate::compiled::CompletionHandle;
8006    for arc in cache.values() {
8007        let backend = {
8008            let guard = arc
8009                .read()
8010                .map_err(|_| poisoned("storage lock during vulkan submit_pending"))?;
8011            match &guard.inner {
8012                fuel_memory::BackendStorage::Vulkan(v) => v.backend().cloned(),
8013                _ => None,
8014            }
8015        };
8016        let Some(backend) = backend else { continue };
8017        // Submit the open batch (if any) without waiting, then wait via the
8018        // completion handle. Empty batch → None → nothing to wait.
8019        // Step E B1: `new` increments the in-flight counter for this device;
8020        // `handle.wait()` waits + drops the `VulkanCompletion`, decrementing it
8021        // — a balanced submit/retire even on this transient realize-end path.
8022        let loc = DeviceLocation::Vulkan {
8023            gpu_id: backend.gpu_id,
8024        };
8025        if let Some(batch) = backend.submit_pending()? {
8026            let handle: CompletionHandle =
8027                CompletionHandle::Pending(Box::new(VulkanCompletion::new(backend, batch, loc)));
8028            handle.wait()?;
8029        }
8030    }
8031    Ok(())
8032}
8033
8034#[cfg(not(feature = "vulkan"))]
8035fn drain_vulkan_pending(_cache: &StorageCache) -> Result<()> {
8036    Ok(())
8037}
8038
8039/// Step E A2: force the Vulkan backend behind `arc` (if any) to submit + WAIT
8040/// its open batch — the blocking drain before freeing a buffer the batch may
8041/// reference (a destructive eviction) so a recorded-but-unsubmitted command never
8042/// reads freed memory. No-op for non-Vulkan storage, an empty batch, or a
8043/// non-Vulkan build.
8044///
8045/// **Retained for the SINGLE-DEVICE path (byte-identical to pre-A2.1).** A2.1's
8046/// deferred-deletion ([`defer_evicted_vulkan_buffer`]) replaces this only on a
8047/// MULTI-backend realize, where eager-submit + in-flight tracking + the
8048/// realize-end `drain_inflight_vulkan` are all live. On a single-device Vulkan
8049/// realize the A4b machinery is gated off (`multi_backend == false`): the
8050/// cross-batch RAW guard (`pipelined.rs:832`) does not run, so a later Vulkan op
8051/// reading a buffer an eager-submitted batch wrote could race (separate
8052/// submissions only BEGIN in order, may overlap). The blocking `force_flush`
8053/// (submit + wait) is the coherent eviction drain there — exactly the original
8054/// behavior — so single-device stays byte-identical and UAF-safe.
8055#[cfg(feature = "vulkan")]
8056fn force_flush_vulkan(arc: &Arc<RwLock<Storage>>) -> Result<()> {
8057    let guard = arc
8058        .read()
8059        .map_err(|_| poisoned("storage lock during vulkan force_flush"))?;
8060    if let fuel_memory::BackendStorage::Vulkan(v) = &guard.inner
8061        && let Some(backend) = v.backend()
8062    {
8063        backend.force_flush()?;
8064    }
8065    Ok(())
8066}
8067
8068#[cfg(not(feature = "vulkan"))]
8069fn force_flush_vulkan(_arc: &Arc<RwLock<Storage>>) -> Result<()> {
8070    Ok(())
8071}
8072
8073/// Step E A2.1 — DEFERRED-DELETION of a Vulkan data buffer evicted while Vulkan
8074/// work is in flight (the throughput refinement that REPLACES the eviction-time
8075/// drain on a MULTI-backend realize). Called at the per-NodeId destructive
8076/// eviction (`Op::Release`/`Op::Move` cleanup) for the buffer about to leave the
8077/// cache, INSTEAD of `drain_inflight_vulkan` + `force_flush` (two host-blocking
8078/// fence waits) — so the iGPU work the executor was overlapping with CUDA is not
8079/// stalled at every eviction.
8080///
8081/// Two classes of Vulkan reader can hold a reference to `destroyed`'s buffer at
8082/// the eviction:
8083///   1. the **in-flight** `SubmittedBatch`es in `inflight` (submitted CBs, each
8084///      fenced), and
8085///   2. the **open**, not-yet-submitted recorder batch (recorded commands, NO
8086///      fence yet).
8087///
8088/// We make BOTH fence-gated without blocking the host:
8089///   - `eager_submit_all_vulkan` submits the open batch WITHOUT waiting, turning
8090///     it into one more in-flight `SubmittedBatch` (now fenced) pushed onto
8091///     `inflight`. (Whole-chunk granularity — UAF/race-safe per its contract; at a
8092///     destructive eviction the open batch is a contiguous Vulkan run.)
8093///   - We then move a refcount clone of the evicted buffer's `Arc<VulkanBuffer>`
8094///     into EVERY in-flight batch (conservative: we cannot cheaply map
8095///     buffer→batch, exactly the reason the old drain waited *all* of them). Each
8096///     batch frees its retained clone POST-fence on `Drop` (follow-on #2).
8097///
8098/// After this returns the caller `cache.remove`s `destroyed`; the cache's
8099/// `Arc<RwLock<Storage>>` drops, but the buffer's recycler
8100/// (`VulkanBuffer::drop`) reclaims it only when its LAST `Arc` drops — and the
8101/// retained clones keep it alive until their owning batches' fences signal. So the
8102/// GPU's last read of the buffer strictly precedes the free (NO use-after-free),
8103/// the host never blocks at the eviction (the iGPU keeps overlapping CUDA — the
8104/// throughput win), and every batch (hence every retained buffer) is drained by
8105/// realize-end at the latest (`drain_inflight_vulkan`, `pipelined.rs:916/1238`,
8106/// runs unconditionally → NO leak).
8107///
8108/// **Multi-backend only** (the call site gates `if multi_backend`). On a
8109/// single-device realize the open batch is drained by the blocking
8110/// [`force_flush_vulkan`] instead (byte-identical to pre-A2.1; see its doc for
8111/// why the deferred path is unsafe without the cross-batch RAW guard). No-op for a
8112/// non-Vulkan storage, an empty open + no in-flight batches, or a non-Vulkan build.
8113/// Open-batch size (dispatches) at which a deferred eviction submits the batch so the
8114/// GPU runs it while the host keeps recording.
8115#[cfg(feature = "vulkan")]
8116const EVICT_SUBMIT_MIN_DISPATCHES: usize = 48;
8117
8118#[cfg(feature = "vulkan")]
8119fn defer_evicted_vulkan_buffer(
8120    cache: &StorageCache,
8121    destroyed: NodeId,
8122    inflight: &mut Vec<VulkanCompletion>,
8123) -> Result<()> {
8124    // Pull the evicted buffer's device Arc (and its backend) out of the cache BEFORE
8125    // it is removed. Non-Vulkan storage, a host-evicted (no device buffer) Vulkan
8126    // storage, or an absent entry → nothing to retain (no Vulkan reader can hold a
8127    // device buffer).
8128    let (buf, backend) = {
8129        let Some(arc) = cache.get(&destroyed) else {
8130            return Ok(());
8131        };
8132        let guard = arc
8133            .read()
8134            .map_err(|_| poisoned("storage lock during deferred-eviction retain"))?;
8135        match &guard.inner {
8136            fuel_memory::BackendStorage::Vulkan(v) => (v.device_buffer_arc(), v.backend().cloned()),
8137            _ => (None, None),
8138        }
8139    };
8140    let Some(buf) = buf else { return Ok(()) };
8141
8142    // The OPEN batch may hold recorded-but-unsubmitted commands that read `destroyed`:
8143    // retain the buffer on the open batch itself (freed post-fence once that batch is
8144    // submitted and waited). This neither submits nor waits — it used to eager-submit
8145    // here, i.e. one queue submit per eviction (61 per Qwen3 decode step).
8146    // Whether the open batch held recorded work (so the retain above actually kept a reader's
8147    // buffer alive instead of blocking): read BEFORE the eager submit below empties it.
8148    let retained_in_open_batch = backend.as_ref().is_some_and(|b| b.open_batch_len() > 0);
8149    if let Some(backend) = &backend {
8150        backend.retain_in_open_batch(buf.clone());
8151    }
8152    // Retain a clone of the evicted buffer in EVERY in-flight batch. Each frees it
8153    // POST-fence on `Drop` — the buffer outlives the GPU's last read with no host
8154    // block. Conservative over all batches (no cheap buffer→batch map); over-retention
8155    // only lengthens the lifetime, never a UAF, and all batches drain by realize-end.
8156    for vc in inflight.iter_mut() {
8157        vc.retain_data(buf.clone());
8158    }
8159    // Keep the GPU fed: submit the open batch once it has grown by a chunk.
8160    if let Some(backend) = backend
8161        && backend.open_batch_len() >= EVICT_SUBMIT_MIN_DISPATCHES
8162    {
8163        eager_submit_all_vulkan(cache, inflight)?;
8164    }
8165    // Step E A2.1 — throughput-observability. Count a DEFERRED retain that
8166    // actually replaced a host block: an evicted Vulkan buffer retained onto ≥1
8167    // in-flight batch (the open-batch eager-submit and/or pre-existing in-flight
8168    // batches). Pre-A2.1 every such site host-blocked (`force_flush` and/or
8169    // `drain_inflight_vulkan`); now it does not. A test reads
8170    // [`deferred_eviction_retains`] to assert the deferred path fired without a
8171    // drain (deterministic — no wall-clock, which is noisy on this box). When
8172    // `inflight` is empty AND the open batch was empty there was genuinely no in-flight/open
8173    // Vulkan reader to wait for, so no host block was avoided (and none was needed) — not
8174    // counted. A retain onto a non-empty OPEN batch counts (GAP-371: the counter used to look
8175    // only at in-flight batches, so an eviction inside the still-open batch, which is the
8176    // common single-chunk case, never advanced it even though it avoided the host block).
8177    if retained_in_open_batch || !inflight.is_empty() {
8178        DEFERRED_EVICTION_RETAINS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8179    }
8180    Ok(())
8181}
8182
8183/// Step E A2.1 — cumulative count of deferred-deletion retains that replaced a
8184/// host-blocking eviction drain (an evicted Vulkan buffer retained onto ≥1
8185/// in-flight batch instead of waiting it). Process-global, `Relaxed` — a pure
8186/// test/telemetry observation, never a correctness gate (mirrors the B1 in-flight
8187/// counter idiom). Read by the live deferred-eviction throughput test.
8188#[cfg(feature = "vulkan")]
8189pub static DEFERRED_EVICTION_RETAINS: std::sync::atomic::AtomicUsize =
8190    std::sync::atomic::AtomicUsize::new(0);
8191
8192/// Read the A2.1 deferred-eviction-retain counter (see
8193/// [`DEFERRED_EVICTION_RETAINS`]). `pub` so the live throughput test can assert a
8194/// deferred retain fired (the eviction did NOT host-block on a Vulkan fence).
8195#[cfg(feature = "vulkan")]
8196pub fn deferred_eviction_retains() -> usize {
8197    DEFERRED_EVICTION_RETAINS.load(std::sync::atomic::Ordering::Relaxed)
8198}
8199
8200#[cfg(not(feature = "vulkan"))]
8201#[inline]
8202fn defer_evicted_vulkan_buffer(
8203    _cache: &StorageCache,
8204    _destroyed: NodeId,
8205    _inflight: &mut Vec<InflightVulkan>,
8206) -> Result<()> {
8207    Ok(())
8208}
8209
8210/// Materialize a contiguous Storage Arc from a non-contiguous one.
8211/// Allocates a fresh buffer on the input's backend and copies the
8212/// strided / offset / broadcast input into it via the backend's
8213/// contiguize kernel. The returned Arc is a brand-new buffer; the
8214/// caller is responsible for replacing the cache entry only for the
8215/// duration of one kernel call (the upstream view op's output stays
8216/// in the cache so other consumers still see the strided view).
8217///
8218/// Stage 4 of Layout-on-Node — auto-Contiguize.
8219fn auto_contiguize(arc: &Arc<RwLock<Storage>>, layout: &Layout) -> Result<Arc<RwLock<Storage>>> {
8220    let in_guard = arc
8221        .read()
8222        .map_err(|_| poisoned("input storage lock during auto_contiguize"))?;
8223    let dtype = in_guard.dtype;
8224    let dtype_size = dtype.size_in_bytes();
8225    let new_storage = match &in_guard.inner {
8226        fuel_memory::BackendStorage::Cpu(c) => {
8227            let new_bytes = fuel_cpu_backend::byte_kernels::contiguize_cpu(c, layout, dtype_size)?;
8228            Storage::new(fuel_memory::BackendStorage::Cpu(new_bytes), dtype)
8229        }
8230        #[cfg(feature = "cuda")]
8231        fuel_memory::BackendStorage::Cuda(c) => {
8232            // Native baracuda contiguize (alpha.29). Byte-width-
8233            // dispatched: 1/2/4/8/16 byte elements all route to the
8234            // appropriate kernel. Handles signed strides (Flip),
8235            // zero strides (BroadcastTo), and non-zero element offset.
8236            //
8237            // Three host-side fast paths bake into the baracuda
8238            // launchers: already-contiguous → single cuMemcpyDtoDAsync;
8239            // innermost-stride-1 → per-outer-coord run copy; generic
8240            // → one thread per output element. Retires the prior
8241            // D2H → CPU contiguize_cpu → H2D fallback (two device
8242            // round-trips per non-contig input).
8243            let contig = fuel_cuda_backend::baracuda::contiguize::contiguize_to_fresh(
8244                c, layout, dtype_size,
8245            )?;
8246            Storage::new(fuel_memory::BackendStorage::Cuda(contig), dtype)
8247        }
8248        #[cfg(feature = "vulkan")]
8249        fuel_memory::BackendStorage::Vulkan(v) => {
8250            // Native `strided_copy_signed_*` kernel when it applies (2/4/8-byte
8251            // elements; see `contiguize_vulkan`). Otherwise the V.1.B host round trip:
8252            // D2H → CPU contiguize_cpu → H2D, which forces a flush and a wait
8253            // per call.
8254            let backend = v.backend().ok_or_else(|| {
8255                Error::Msg(
8256                    "auto_contiguize: Vulkan input has no backend handle. \
8257                     Storages flowing through the pipelined executor's Vulkan \
8258                     path must be constructed via VulkanBackend::alloc_bytes_handle \
8259                     / upload_bytes_handle (not the legacy alloc_bytes / \
8260                     upload_bytes which leave VulkanStorageBytes::backend = None)."
8261                        .to_string(),
8262                )
8263                .bt()
8264            })?;
8265            if let Some(native) = fuel_vulkan_backend::contiguize_vulkan(v, layout, dtype_size)? {
8266                return Ok(Arc::new(RwLock::new(Storage::new(
8267                    fuel_memory::BackendStorage::Vulkan(native),
8268                    dtype,
8269                ))));
8270            }
8271            let _t = crate::compiled::op_profile::PhaseTimer::start(
8272                "auto_contiguize.vulkan_host_roundtrip",
8273            );
8274            let host_bytes = backend.download_bytes(v)?;
8275            let host_cpu = fuel_cpu_backend::byte_storage::CpuStorageBytes::from_bytes(&host_bytes);
8276            let contig_cpu =
8277                fuel_cpu_backend::byte_kernels::contiguize_cpu(&host_cpu, layout, dtype_size)?;
8278            let host_contig_bytes = contig_cpu.bytes().to_vec();
8279            let vk_bytes = backend.upload_bytes_handle(&host_contig_bytes)?;
8280            Storage::new(fuel_memory::BackendStorage::Vulkan(vk_bytes), dtype)
8281        }
8282        #[allow(unreachable_patterns)]
8283        _ => {
8284            return Err(Error::Msg(
8285                "auto_contiguize: backend not wired (CPU + CUDA + Vulkan are \
8286                 wired today; Metal extends this match when its byte-storage \
8287                 substrate lands)"
8288                    .to_string(),
8289            )
8290            .bt());
8291        }
8292    };
8293    Ok(Arc::new(RwLock::new(new_storage)))
8294}
8295
8296/// Write-into sibling of [`auto_contiguize`] (CapturedRun executor
8297/// build-out, 4b-γ): materializes a contiguous copy of `arc` at `layout`
8298/// INTO `dest`'s EXISTING buffer instead of allocating a fresh one — the
8299/// path `WorkItemKind::ContiguizeOf`'s Reuse-mode branch needs (device
8300/// allocation is illegal inside a capture scope). `dest` must already be
8301/// sized to the contiguized output's byte count — true by construction,
8302/// since the persistent map only ever holds a buffer THIS SAME code path
8303/// (the warm-run `auto_contiguize` allocation) sized.
8304///
8305/// CUDA-only today: `PersistentOutputs::reuse` (Reuse mode) is only ever
8306/// constructed inside [`PipelinedExecutor::capture_decode`], which is
8307/// `#[cfg(feature = "cuda")]`-gated and validates every compute node
8308/// targets `Cuda` — a CPU or Vulkan storage can never actually reach this
8309/// function in practice. Per this project's "never panic on production
8310/// paths" rule, the other backends still surface a typed gap rather than
8311/// silently mishandling it (never a crash).
8312#[cfg_attr(not(feature = "cuda"), allow(unused_variables))]
8313fn contiguize_into(
8314    dest: &Arc<RwLock<Storage>>,
8315    arc: &Arc<RwLock<Storage>>,
8316    layout: &Layout,
8317) -> Result<()> {
8318    let in_guard = arc
8319        .read()
8320        .map_err(|_| poisoned("input storage lock during contiguize_into"))?;
8321    match &in_guard.inner {
8322        #[cfg(feature = "cuda")]
8323        fuel_memory::BackendStorage::Cuda(src_cuda) => {
8324            let dtype_size = in_guard.dtype.size_in_bytes();
8325            let mut dest_guard = dest
8326                .write()
8327                .map_err(|_| poisoned("dest storage lock during contiguize_into"))?;
8328            let dest_cuda = match &mut dest_guard.inner {
8329                fuel_memory::BackendStorage::Cuda(d) => d,
8330                other => {
8331                    return Err(Error::Msg(format!(
8332                        "contiguize_into: dest is BackendStorage::{:?}, not Cuda",
8333                        other.backend_id(),
8334                    ))
8335                    .bt());
8336                }
8337            };
8338            fuel_cuda_backend::baracuda::contiguize::contiguize_into(
8339                src_cuda, layout, dest_cuda, dtype_size,
8340            )
8341        }
8342        #[allow(unreachable_patterns)]
8343        _ => Err(Error::Msg(
8344            "contiguize_into: only CUDA is wired (PersistentOutputs::reuse / \
8345             capture_decode is CUDA-only today — no CPU/Vulkan consumer exists \
8346             yet; extend this match if one appears)"
8347                .to_string(),
8348        )
8349        .bt()),
8350    }
8351}
8352
8353#[cfg(test)]
8354mod backend_neutral_tests {
8355    use super::*;
8356
8357    #[test]
8358    fn only_deviceless_items_are_backend_neutral() {
8359        let n = NodeId(0);
8360        // Adopting an input-cache entry or aliasing a producer touches no device.
8361        assert!(is_backend_neutral(&WorkItemKind::ConstAdopt));
8362        assert!(is_backend_neutral(&WorkItemKind::ViewOf { input: n }));
8363        assert!(is_backend_neutral(&WorkItemKind::SlotView { producer: n }));
8364        // Contiguize runs on its input's backend; its own `target_backend` is a
8365        // placeholder, so it must not count as a backend switch.
8366        assert!(is_backend_neutral(&WorkItemKind::ContiguizeOf { input: n }));
8367        // Sabotage siblings: anything that runs a kernel of its own or moves bytes
8368        // across devices is NOT, so a real backend switch still arms the
8369        // chunk-boundary logic.
8370        assert!(!is_backend_neutral(&WorkItemKind::Kernel));
8371        assert!(!is_backend_neutral(&WorkItemKind::Copy {
8372            target_location: DeviceLocation::Cpu
8373        }));
8374        assert!(!is_backend_neutral(&WorkItemKind::WriteSlice {
8375            dest: n,
8376            source: n
8377        }));
8378    }
8379}
8380
8381#[cfg(test)]
8382mod tests {
8383    // ---- GAP-380 (a2): the plan-time arm guard ----------------------------------------------
8384
8385    fn iota_graph(backend: BackendId) -> (Graph, NodeId) {
8386        let mut g = Graph::new();
8387        let id = g.push(Node {
8388            op: Op::Iota { len: 4 },
8389            inputs: vec![],
8390            shape: fuel_ir::Shape::from_dims(&[4]),
8391            dtype: DType::F32,
8392        });
8393        g.set_target_backend(id, backend);
8394        (g, id)
8395    }
8396
8397    #[test]
8398    fn an_iota_on_a_backend_with_no_arm_fails_at_plan_time_naming_node_and_op() {
8399        let (g, id) = iota_graph(BackendId::Vulkan);
8400        let err = check_direct_arms_wired(&g, &[id])
8401            .expect_err("Vulkan has no Iota arm")
8402            .to_string();
8403        assert!(
8404            err.contains(&format!("Node#{}", id.0)),
8405            "names the node: {err}"
8406        );
8407        assert!(err.contains("Iota"), "names the op: {err}");
8408        assert!(err.contains("Vulkan"), "names the backend: {err}");
8409    }
8410
8411    /// Sabotage siblings: the same guard passes where the arm IS wired, so the red above is the
8412    /// missing arm and not the guard rejecting everything.
8413    #[test]
8414    fn an_iota_on_cpu_passes_the_arm_guard_and_other_ops_are_not_direct_dispatched() {
8415        let (g, id) = iota_graph(BackendId::Cpu);
8416        check_direct_arms_wired(&g, &[id]).expect("CPU Iota is wired");
8417        assert_eq!(
8418            direct_arm_wired(&Op::Add, BackendId::Cuda),
8419            None,
8420            "Add goes through the binding table"
8421        );
8422        assert_eq!(
8423            direct_arm_wired(&Op::Iota { len: 1 }, BackendId::Cpu),
8424            Some(true)
8425        );
8426        assert_eq!(
8427            direct_arm_wired(&Op::Iota { len: 1 }, BackendId::Cuda),
8428            Some(cfg!(feature = "cuda")),
8429            "the CUDA arm is wired exactly when the cuda feature compiles it"
8430        );
8431    }
8432
8433    use super::*;
8434    use fuel_graph::Node;
8435    use fuel_ir::Shape;
8436
8437    /// Task 5 (C6): `Op::Scan` has no native kernel in Phase 1 — it is
8438    /// always lowered/re-fused before execution — so `op_to_op_kind` must
8439    /// fall through its `_ => None` wildcard for it, exactly like any other
8440    /// not-yet-wired op. Regression lock, not born-red: this is expected to
8441    /// pass immediately.
8442    #[test]
8443    fn scan_has_no_dispatch_op_kind() {
8444        use fuel_graph::{Op, ScanEmit};
8445        assert_eq!(
8446            crate::pipelined::op_to_op_kind(&Op::Scan {
8447                n_carries: 1,
8448                n_xs: 0,
8449                bound: 2,
8450                emit: ScanEmit::All,
8451                early_exit: None
8452            }),
8453            None,
8454        );
8455    }
8456
8457    /// Step E A4b open question #4 — "event only where waited", step 1.
8458    /// `build_wait_set` collects exactly the producers of `Op::Copy`/`Move`
8459    /// nodes in the order: a same-device-only node (never copied/moved) must
8460    /// be ABSENT, and the Copy's own node id must not appear either (it is
8461    /// not its own producer).
8462    #[test]
8463    fn build_wait_set_collects_only_cross_device_copy_producers() {
8464        let mut g = Graph::new();
8465        let const_id = g.push(Node {
8466            op: Op::Const,
8467            inputs: vec![],
8468            shape: Shape::from_dims(&[4]),
8469            dtype: DType::F32,
8470        });
8471        // Same-device-only consumer of const_id — never fed into a Copy/Move.
8472        let same_device_id = g.push(Node {
8473            op: Op::Contiguize,
8474            inputs: vec![const_id],
8475            shape: Shape::from_dims(&[4]),
8476            dtype: DType::F32,
8477        });
8478        // A cross-device Copy whose producer is `same_device_id`.
8479        let copy_id = g.push(Node {
8480            op: Op::Copy {
8481                target: DeviceLocation::Cuda { gpu_id: 0 },
8482            },
8483            inputs: vec![same_device_id],
8484            shape: Shape::from_dims(&[4]),
8485            dtype: DType::F32,
8486        });
8487        let order = vec![const_id, same_device_id, copy_id];
8488
8489        let set = build_wait_set(&g, &order);
8490        assert!(
8491            set.contains(&same_device_id),
8492            "the Copy's producer must be in the wait set"
8493        );
8494        assert!(
8495            !set.contains(&const_id),
8496            "a node with no Copy/Move consumer must be absent from the wait set"
8497        );
8498        assert!(
8499            !set.contains(&copy_id),
8500            "the Copy node itself is not its own producer"
8501        );
8502        assert_eq!(
8503            set.len(),
8504            1,
8505            "only the one true cross-device producer is in the set"
8506        );
8507    }
8508
8509    /// A `Move` producer is collected the same way as a `Copy` producer.
8510    #[test]
8511    fn build_wait_set_collects_move_producers_too() {
8512        let mut g = Graph::new();
8513        let const_id = g.push(Node {
8514            op: Op::Const,
8515            inputs: vec![],
8516            shape: Shape::from_dims(&[4]),
8517            dtype: DType::F32,
8518        });
8519        let move_id = g.push(Node {
8520            op: Op::Move {
8521                target: DeviceLocation::Cpu,
8522            },
8523            inputs: vec![const_id],
8524            shape: Shape::from_dims(&[4]),
8525            dtype: DType::F32,
8526        });
8527        let order = vec![const_id, move_id];
8528
8529        let set = build_wait_set(&g, &order);
8530        assert!(
8531            set.contains(&const_id),
8532            "the Move's producer must be in the wait set"
8533        );
8534        assert_eq!(set.len(), 1);
8535    }
8536
8537    /// A CPU-only order (no `Op::Copy`/`Op::Move` anywhere) yields an empty
8538    /// wait set — every node in it is eligible for elision.
8539    #[test]
8540    fn build_wait_set_is_empty_for_cpu_only_order() {
8541        let mut g = Graph::new();
8542        let const_id = g.push(Node {
8543            op: Op::Const,
8544            inputs: vec![],
8545            shape: Shape::from_dims(&[4]),
8546            dtype: DType::F32,
8547        });
8548        let contig_id = g.push(Node {
8549            op: Op::Contiguize,
8550            inputs: vec![const_id],
8551            shape: Shape::from_dims(&[4]),
8552            dtype: DType::F32,
8553        });
8554        let order = vec![const_id, contig_id];
8555
8556        let set = build_wait_set(&g, &order);
8557        assert!(
8558            set.is_empty(),
8559            "a CPU-only order (no Copy/Move) yields an empty wait set"
8560        );
8561    }
8562
8563    /// `will_be_waited`'s two arms: the conservative `None` fallback (the
8564    /// `OrderSource::Streaming` case) is always `true`; a `Some(set)` checks
8565    /// membership.
8566    #[test]
8567    fn will_be_waited_none_is_conservative_true_for_any_node() {
8568        let ws: WaitSet = None;
8569        assert!(will_be_waited(&ws, NodeId(0)));
8570        assert!(will_be_waited(&ws, NodeId(12345)));
8571    }
8572
8573    #[test]
8574    fn will_be_waited_some_checks_membership() {
8575        let mut set = HashSet::new();
8576        set.insert(NodeId(3));
8577        let ws: WaitSet = Some(set);
8578        assert!(will_be_waited(&ws, NodeId(3)), "member must be waited");
8579        assert!(!will_be_waited(&ws, NodeId(4)), "non-member must be elided");
8580    }
8581
8582    /// A4b-1 test double: a `Completion` whose `wait` flips a shared flag, so a
8583    /// test can observe whether the drain actually waited it.
8584    struct FlagCompletion(std::sync::Arc<std::sync::atomic::AtomicUsize>);
8585    impl crate::compiled::Completion for FlagCompletion {
8586        fn wait(self: Box<Self>) -> Result<()> {
8587            self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
8588            Ok(())
8589        }
8590    }
8591
8592    /// A4b-1: `store_handle` keeps only `Pending` handles (so the post-drain
8593    /// empty-map assert is meaningful and the drain is O(pending)), and
8594    /// `drain_handles` waits each pending handle exactly once then empties the map.
8595    #[test]
8596    fn handle_map_stores_pending_and_drains_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
8602        // Ready handles are not stored.
8603        store_handle(&mut handles, NodeId(1), CompletionHandle::Ready);
8604        assert!(handles.is_empty(), "Ready handles must not be stored");
8605
8606        // Two pending handles are stored and each waited once on drain.
8607        let waited = StdArc::new(AtomicUsize::new(0));
8608        store_handle(
8609            &mut handles,
8610            NodeId(2),
8611            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8612        );
8613        store_handle(
8614            &mut handles,
8615            NodeId(3),
8616            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8617        );
8618        assert_eq!(handles.len(), 2);
8619
8620        drain_handles(&mut handles).expect("drain");
8621        assert_eq!(
8622            waited.load(Ordering::SeqCst),
8623            2,
8624            "each pending handle waited once"
8625        );
8626        assert!(handles.is_empty(), "map empty after drain");
8627    }
8628
8629    /// A4b-1: re-keying a NodeId with a new Pending handle waits the prior one
8630    /// (no leaked async work), and storing `Ready` over a prior Pending also
8631    /// waits it. Defensive — NodeIds are unique per realize in practice.
8632    #[test]
8633    fn handle_map_rekey_waits_previous() {
8634        use std::sync::Arc as StdArc;
8635        use std::sync::atomic::{AtomicUsize, Ordering};
8636
8637        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8638        let waited = StdArc::new(AtomicUsize::new(0));
8639
8640        store_handle(
8641            &mut handles,
8642            NodeId(7),
8643            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8644        );
8645        // Re-key with another Pending → prior is waited.
8646        store_handle(
8647            &mut handles,
8648            NodeId(7),
8649            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8650        );
8651        assert_eq!(
8652            waited.load(Ordering::SeqCst),
8653            1,
8654            "rekey waited the prior pending"
8655        );
8656
8657        // Store Ready over the live Pending → it is waited too.
8658        store_handle(&mut handles, NodeId(7), CompletionHandle::Ready);
8659        assert_eq!(
8660            waited.load(Ordering::SeqCst),
8661            2,
8662            "Ready-over-Pending waited it"
8663        );
8664        assert!(handles.is_empty());
8665
8666        drain_handles(&mut handles).expect("drain empty");
8667    }
8668
8669    /// A4b-3: `wait_producer_handle` waits the named producer's handle EXACTLY
8670    /// once and removes it from the map (the finer cross-device source-drain
8671    /// consumes the producer's completion before the Copy reads its buffer), and
8672    /// is a no-op for an absent producer (CPU / Vulkan-`Ready` source, or an
8673    /// already-consumed handle). The realize-end drain then waits only what
8674    /// remains — no double-wait.
8675    #[test]
8676    fn wait_producer_handle_consumes_named_handle_once() {
8677        use std::sync::Arc as StdArc;
8678        use std::sync::atomic::{AtomicUsize, Ordering};
8679
8680        let mut handles: HashMap<NodeId, CompletionHandle> = HashMap::new();
8681        let waited = StdArc::new(AtomicUsize::new(0));
8682
8683        // Two producers in flight; the Copy's source is NodeId(2).
8684        store_handle(
8685            &mut handles,
8686            NodeId(2),
8687            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8688        );
8689        store_handle(
8690            &mut handles,
8691            NodeId(5),
8692            CompletionHandle::Pending(Box::new(FlagCompletion(waited.clone()))),
8693        );
8694
8695        // Absent producer → no-op (a CPU/Vulkan-Ready source has no handle).
8696        wait_producer_handle(&mut handles, NodeId(99)).expect("absent is no-op");
8697        assert_eq!(
8698            waited.load(Ordering::SeqCst),
8699            0,
8700            "absent producer waited nothing"
8701        );
8702        assert_eq!(handles.len(), 2);
8703
8704        // The cross-device copy's source: waited once, removed from the map.
8705        wait_producer_handle(&mut handles, NodeId(2)).expect("wait source");
8706        assert_eq!(
8707            waited.load(Ordering::SeqCst),
8708            1,
8709            "source producer waited once"
8710        );
8711        assert!(!handles.contains_key(&NodeId(2)), "source handle consumed");
8712        assert!(
8713            handles.contains_key(&NodeId(5)),
8714            "unrelated handle untouched"
8715        );
8716
8717        // Re-waiting the (now absent) source is a no-op — no double-wait.
8718        wait_producer_handle(&mut handles, NodeId(2)).expect("re-wait is no-op");
8719        assert_eq!(waited.load(Ordering::SeqCst), 1, "no double-wait");
8720
8721        // Realize-end drain waits only the remaining unrelated producer.
8722        drain_handles(&mut handles).expect("drain");
8723        assert_eq!(
8724            waited.load(Ordering::SeqCst),
8725            2,
8726            "drain waited the remaining one"
8727        );
8728        assert!(handles.is_empty());
8729    }
8730
8731    /// Op::Contiguize on a contiguous-already input is zero-copy:
8732    /// the executor adopts the input Storage Arc unchanged.
8733    #[test]
8734    fn op_contiguize_zero_copy_on_contiguous_input() {
8735        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
8736
8737        let graph = Arc::new(RwLock::new(Graph::new()));
8738        let (const_id, contig_id) = {
8739            let mut g = graph.write().unwrap();
8740            let const_id = g.push(Node {
8741                op: Op::Const,
8742                inputs: vec![],
8743                shape: Shape::from_dims(&[2, 2]),
8744                dtype: DType::F32,
8745            });
8746            let contig_id = g.push(Node {
8747                op: Op::Contiguize,
8748                inputs: vec![const_id],
8749                shape: Shape::from_dims(&[2, 2]),
8750                dtype: DType::F32,
8751            });
8752            // No need to set target_backend on Contiguize — the
8753            // executor inherits or defaults to CPU.
8754            (const_id, contig_id)
8755        };
8756
8757        let mut inputs = StorageCache::new();
8758        let input_arc = Arc::new(RwLock::new(storage));
8759        let input_arc_for_compare = Arc::clone(&input_arc);
8760        inputs.insert(const_id, input_arc);
8761
8762        let (result_arc, _) =
8763            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8764
8765        // Same Arc → zero-copy adoption. Compare by raw pointer.
8766        assert!(
8767            Arc::ptr_eq(&result_arc, &input_arc_for_compare),
8768            "Op::Contiguize on contiguous input must adopt the input Arc (zero copy)",
8769        );
8770    }
8771
8772    /// Op::Contiguize on a strided input (here: a transposed view)
8773    /// materializes a fresh contiguous Storage. The output bytes
8774    /// reflect the strided view's logical content, not the input
8775    /// storage's underlying memory order.
8776    #[test]
8777    fn op_contiguize_materializes_on_strided_input() {
8778        // 2x3 row-major: [[1,2,3],[4,5,6]] → transpose → 3x2:
8779        // [[1,4],[2,5],[3,6]]. The transposed view shares the
8780        // original buffer; Op::Contiguize on the transpose
8781        // materializes contiguous bytes matching the transposed
8782        // logical order.
8783        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
8784
8785        let graph = Arc::new(RwLock::new(Graph::new()));
8786        let (const_id, _transpose_id, contig_id) = {
8787            let mut g = graph.write().unwrap();
8788            let const_id = g.push(Node {
8789                op: Op::Const,
8790                inputs: vec![],
8791                shape: Shape::from_dims(&[2, 3]),
8792                dtype: DType::F32,
8793            });
8794            let transpose_id = g.push(Node {
8795                op: Op::Transpose,
8796                inputs: vec![const_id],
8797                shape: Shape::from_dims(&[3, 2]),
8798                dtype: DType::F32,
8799            });
8800            let contig_id = g.push(Node {
8801                op: Op::Contiguize,
8802                inputs: vec![transpose_id],
8803                shape: Shape::from_dims(&[3, 2]),
8804                dtype: DType::F32,
8805            });
8806            (const_id, transpose_id, contig_id)
8807        };
8808
8809        let mut inputs = StorageCache::new();
8810        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
8811
8812        let (result_arc, _) =
8813            PipelinedExecutor::realize(graph, contig_id, inputs).expect("realize");
8814
8815        let guard = result_arc.read().unwrap();
8816        let cpu = if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8817            c
8818        } else {
8819            panic!("expected Cpu storage");
8820        };
8821        let typed: &[f32] = cpu.as_slice().expect("f32 cast");
8822        // Transposed logical order: [1,4,2,5,3,6].
8823        assert_eq!(
8824            typed,
8825            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0],
8826            "contiguized transpose must reflect logical (transposed) byte order",
8827        );
8828    }
8829
8830    /// E2E: 3-node graph (Const + Const + Add), pre-seeded inputs,
8831    /// realized through the compiler+executor thread pair, returns
8832    /// expected sum bytes.
8833    #[test]
8834    fn pipelined_realize_const_const_add() {
8835        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
8836        let rhs_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
8837
8838        let graph = Arc::new(RwLock::new(Graph::new()));
8839        let (lhs_id, rhs_id, add_id) = {
8840            let mut g = graph.write().unwrap();
8841            let lhs_id = g.push(Node {
8842                op: Op::Const,
8843                inputs: vec![],
8844                shape: Shape::from_dims(&[3]),
8845                dtype: DType::F32,
8846            });
8847            let rhs_id = g.push(Node {
8848                op: Op::Const,
8849                inputs: vec![],
8850                shape: Shape::from_dims(&[3]),
8851                dtype: DType::F32,
8852            });
8853            let add_id = g.push(Node {
8854                op: Op::Add,
8855                inputs: vec![lhs_id, rhs_id],
8856                shape: Shape::from_dims(&[3]),
8857                dtype: DType::F32,
8858            });
8859            g.set_target_backend(add_id, BackendId::Cpu);
8860            (lhs_id, rhs_id, add_id)
8861        };
8862
8863        let mut inputs = StorageCache::new();
8864        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
8865        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
8866
8867        let (result_arc, _result_layout) =
8868            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
8869
8870        let guard = result_arc.read().unwrap();
8871        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
8872            let typed: &[f32] = c.as_slice().expect("f32 cast");
8873            assert_eq!(typed, &[11.0, 22.0, 33.0]);
8874        } else {
8875            panic!("expected CPU output");
8876        }
8877    }
8878
8879    /// PR-C1 behavior contract: `realize_with_optimized_route` with an
8880    /// **empty** route (the no-pressure / no-telemetry case) is
8881    /// byte-identical to `realize_with_optimized` (arm-0). On a branchless
8882    /// graph the route has no branches to resolve, so both must produce
8883    /// the same bytes — realize is unchanged from Phase B.
8884    #[test]
8885    fn realize_with_optimized_route_empty_equals_arm0() {
8886        use crate::optimize::OptimizedGraph;
8887
8888        let build = || {
8889            let graph = Arc::new(RwLock::new(Graph::new()));
8890            let (lhs_id, rhs_id, add_id) = {
8891                let mut g = graph.write().unwrap();
8892                let lhs_id = g.push(Node {
8893                    op: Op::Const,
8894                    inputs: vec![],
8895                    shape: Shape::from_dims(&[3]),
8896                    dtype: DType::F32,
8897                });
8898                let rhs_id = g.push(Node {
8899                    op: Op::Const,
8900                    inputs: vec![],
8901                    shape: Shape::from_dims(&[3]),
8902                    dtype: DType::F32,
8903                });
8904                let add_id = g.push(Node {
8905                    op: Op::Add,
8906                    inputs: vec![lhs_id, rhs_id],
8907                    shape: Shape::from_dims(&[3]),
8908                    dtype: DType::F32,
8909                });
8910                g.set_target_backend(add_id, BackendId::Cpu);
8911                (lhs_id, rhs_id, add_id)
8912            };
8913            let mut inputs = StorageCache::new();
8914            inputs.insert(
8915                lhs_id,
8916                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
8917                    1.0_f32, 2.0, 3.0,
8918                ]))),
8919            );
8920            inputs.insert(
8921                rhs_id,
8922                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
8923                    10.0_f32, 20.0, 30.0,
8924                ]))),
8925            );
8926            (graph, add_id, inputs)
8927        };
8928
8929        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
8930            let guard = arc.read().unwrap();
8931            match &guard.inner {
8932                fuel_memory::BackendStorage::Cpu(c) => {
8933                    c.as_slice::<f32>().expect("f32 cast").to_vec()
8934                }
8935                _ => panic!("expected CPU output"),
8936            }
8937        };
8938
8939        // Stamp the fixture with the LIVE topology generation rather than a
8940        // hard-coded 0. The executor's chunk-boundary check compares the plan's
8941        // stamped generation against `topology_generation()`; a real
8942        // `OptimizedGraph` carries the generation snapshotted at optimize time
8943        // (`plan.rs` `compile_plan`, which reads it *after* the bindings table
8944        // is warm), so it already reflects every registered backend. Force
8945        // `global_bindings()` init here so any feature-gated auto-registration
8946        // has run and settled the counter before we read it — otherwise a stale
8947        // read would be bumped out from under us the first time realize warms
8948        // the bindings. Under default features this is 0; under
8949        // `--features vulkan`, `register_derived_gpu_caps` bumps it to 1.
8950        drop(global_bindings());
8951        let live_gen = crate::dispatch::topology_generation();
8952
8953        // Arm-0 path.
8954        let (g_a, add_a, in_a) = build();
8955        let opt_a = OptimizedGraph {
8956            roots: vec![add_a],
8957            generation: live_gen,
8958            placements: None,
8959            eviction: None,
8960        };
8961        let (arm0_arc, _) = PipelinedExecutor::realize_with_optimized(g_a, add_a, in_a, &opt_a)
8962            .expect("arm-0 realize");
8963        let arm0 = read_bytes(&arm0_arc);
8964
8965        // Empty-route path — must match arm-0 exactly.
8966        let (g_r, add_r, in_r) = build();
8967        let opt_r = OptimizedGraph {
8968            roots: vec![add_r],
8969            generation: live_gen,
8970            placements: None,
8971            eviction: None,
8972        };
8973        let empty_route = PickedRoute::new();
8974        let (route_arc, _) =
8975            PipelinedExecutor::realize_with_optimized_route(g_r, add_r, in_r, &opt_r, &empty_route)
8976                .expect("empty-route realize");
8977        let routed = read_bytes(&route_arc);
8978
8979        assert_eq!(arm0, vec![11.0, 22.0, 33.0]);
8980        assert_eq!(
8981            routed, arm0,
8982            "an empty route realizes byte-identically to arm-0 (Phase B contract)",
8983        );
8984    }
8985
8986    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
8987    /// §5): [`PipelinedExecutor::realize_with_optimized_picking_cached_env`]
8988    /// over a shared `order_cache` must (a) realize byte-identically to the
8989    /// uncached arm-0 path, on both the cold (empty cache) and warm
8990    /// (populated cache) call, and (b) actually populate the cache on the
8991    /// first call rather than silently never using it.
8992    #[test]
8993    fn realize_with_optimized_picking_cached_env_matches_arm0_cold_and_warm() {
8994        use crate::optimize::OptimizedGraph;
8995        use std::sync::OnceLock;
8996
8997        let build = || {
8998            let graph = Arc::new(RwLock::new(Graph::new()));
8999            let (lhs_id, rhs_id, add_id) = {
9000                let mut g = graph.write().unwrap();
9001                let lhs_id = g.push(Node {
9002                    op: Op::Const,
9003                    inputs: vec![],
9004                    shape: Shape::from_dims(&[3]),
9005                    dtype: DType::F32,
9006                });
9007                let rhs_id = g.push(Node {
9008                    op: Op::Const,
9009                    inputs: vec![],
9010                    shape: Shape::from_dims(&[3]),
9011                    dtype: DType::F32,
9012                });
9013                let add_id = g.push(Node {
9014                    op: Op::Add,
9015                    inputs: vec![lhs_id, rhs_id],
9016                    shape: Shape::from_dims(&[3]),
9017                    dtype: DType::F32,
9018                });
9019                g.set_target_backend(add_id, BackendId::Cpu);
9020                (lhs_id, rhs_id, add_id)
9021            };
9022            let mut inputs = StorageCache::new();
9023            inputs.insert(
9024                lhs_id,
9025                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9026                    1.0_f32, 2.0, 3.0,
9027                ]))),
9028            );
9029            inputs.insert(
9030                rhs_id,
9031                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9032                    10.0_f32, 20.0, 30.0,
9033                ]))),
9034            );
9035            (graph, add_id, inputs)
9036        };
9037        let read_bytes = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9038            let guard = arc.read().unwrap();
9039            match &guard.inner {
9040                fuel_memory::BackendStorage::Cpu(c) => {
9041                    c.as_slice::<f32>().expect("f32 cast").to_vec()
9042                }
9043                _ => panic!("expected CPU output"),
9044            }
9045        };
9046
9047        drop(global_bindings());
9048        let live_gen = crate::dispatch::topology_generation();
9049
9050        let (g, add, inputs) = build();
9051        let optimized = OptimizedGraph {
9052            roots: vec![add],
9053            generation: live_gen,
9054            placements: None,
9055            eviction: None,
9056        };
9057        let order_cache: OnceLock<Vec<NodeId>> = OnceLock::new();
9058        assert!(order_cache.get().is_none(), "sanity: cache starts empty");
9059
9060        // Cold call: cache miss, must compute AND populate.
9061        let (cold_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9062            g.clone(),
9063            add,
9064            inputs,
9065            &optimized,
9066            &order_cache,
9067            None,
9068            None,
9069            SymEnv::default(),
9070        )
9071        .expect("cold cached realize");
9072        assert_eq!(read_bytes(&cold_arc), vec![11.0, 22.0, 33.0]);
9073        assert!(
9074            order_cache.get().is_some(),
9075            "the cold call must populate order_cache, not leave it empty"
9076        );
9077        let cached_order_after_cold = order_cache.get().unwrap().clone();
9078
9079        // Warm call: cache hit. Fresh inputs (same graph, new values) so the
9080        // realized OUTPUT differs from the cold call while the dispatch
9081        // ORDER (what's cached) must not change.
9082        let mut warm_inputs = StorageCache::new();
9083        warm_inputs.insert(
9084            g.read().unwrap().node(add).inputs[0],
9085            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9086                100.0_f32, 200.0, 300.0,
9087            ]))),
9088        );
9089        warm_inputs.insert(
9090            g.read().unwrap().node(add).inputs[1],
9091            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9092                1.0_f32, 2.0, 3.0,
9093            ]))),
9094        );
9095        let (warm_arc, _) = PipelinedExecutor::realize_with_optimized_picking_cached_env(
9096            g,
9097            add,
9098            warm_inputs,
9099            &optimized,
9100            &order_cache,
9101            None,
9102            None,
9103            SymEnv::default(),
9104        )
9105        .expect("warm cached realize");
9106        assert_eq!(
9107            read_bytes(&warm_arc),
9108            vec![101.0, 202.0, 303.0],
9109            "warm call must realize its OWN rebound inputs, not replay stale output",
9110        );
9111        assert_eq!(
9112            order_cache.get().unwrap(),
9113            &cached_order_after_cold,
9114            "the warm call must reuse the SAME cached order, not recompute a different one",
9115        );
9116    }
9117
9118    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
9119    /// §5), PM review question: does `OrderSource::Cached` weaken the
9120    /// existing `TopologyChanged` chunk-boundary check? No — proven at the
9121    /// unit level (not a live topology-bump integration test, deliberately:
9122    /// `bump_topology_generation()` mutates a process-wide atomic shared by
9123    /// every concurrently-running test in this binary, including the cold/
9124    /// warm cache test above, which reads it into a local at the start of
9125    /// ITS OWN body and would flake if another test's bump landed mid-call;
9126    /// introducing that cross-test hazard isn't worth it when the two arms'
9127    /// `generation_for` expressions are provably identical). `generation_for`
9128    /// is private to this module, so it's tested directly here: given the
9129    /// SAME `&OptimizedGraph`, `Cached` and `Optimized` must report the
9130    /// IDENTICAL generation — the chunk-boundary check that compares this
9131    /// value against the LIVE `topology_generation()` fires exactly the
9132    /// same way for both, so caching cannot silently skip or weaken it.
9133    #[test]
9134    fn cached_generation_for_matches_optimized_generation_for() {
9135        let optimized = OptimizedGraph {
9136            roots: vec![NodeId(0)],
9137            generation: 42,
9138            placements: None,
9139            eviction: None,
9140        };
9141        let order_cache: std::sync::OnceLock<Vec<NodeId>> = std::sync::OnceLock::new();
9142
9143        let optimized_gen = generation_for(&OrderSource::Optimized {
9144            optimized: &optimized,
9145            route: None,
9146        });
9147        let cached_gen = generation_for(&OrderSource::Cached {
9148            optimized: &optimized,
9149            order_cache: &order_cache,
9150        });
9151        assert_eq!(
9152            optimized_gen,
9153            Some(42),
9154            "sanity: Optimized reports the OptimizedGraph's own generation",
9155        );
9156        assert_eq!(
9157            cached_gen, optimized_gen,
9158            "Cached must report the SAME generation as Optimized for the same \
9159             OptimizedGraph -- the TopologyChanged check cannot tell the two apart, \
9160             by construction, so caching cannot silently weaken it",
9161        );
9162    }
9163
9164    /// **PR-C3 reorder-invariance gate (CPU, runnable — ORDERING level).**
9165    /// The auto-overlap reorder is a HINT: it changes only *which order*
9166    /// independent device runs dispatch in, never *which* nodes run nor the
9167    /// result. The byte-identical-OUTPUT proof is necessarily LIVE (the
9168    /// reorder fires only on a ≥2-device graph, which needs ≥2 real backends
9169    /// to realize — see `cuda_vulkan_multidevice_realize_live`'s
9170    /// `[22,86,192,340]` oracle, which now flows through this reorder, plus
9171    /// the dual-GPU `cuda_vulkan_overlap_bench_live` arbitrary-graph
9172    /// auto-overlap gate). THIS test proves the ordering-level invariant on a
9173    /// CPU-only path: the C3 reorder of a two-device graph is a valid
9174    /// topological **permutation** of the un-reordered topo order — same node
9175    /// multiset, every node still after its inputs — that genuinely DIFFERS
9176    /// from the un-reordered order (so the reorder fired). Because the
9177    /// executor caches each node's result and every op is deterministic,
9178    /// realizing any valid topological order yields identical bytes; this
9179    /// test guards the precondition (a valid permutation) that makes that so.
9180    #[test]
9181    fn c3_reorder_is_a_valid_topo_permutation() {
9182        // Two INDEPENDENT device sub-chains over distinct consts reconverging
9183        // at a final CUDA add, the Vulkan root bridged to CUDA by an explicit
9184        // Op::Copy (a residency seam = its own run). Reconverge inputs in the
9185        // "wrong" (cuda-first) order, the order the un-reordered topo DFS pops
9186        // CUDA-last — exactly the arbitrary-graph shape the auto-overlap pass
9187        // must fix. The chains are UNARY (Relu) so each stays a single
9188        // contiguous run (no const-re-read fan-in fragmenting them), exactly
9189        // like the live benchmark's `relu(mul·add)` chains; the CUDA chain is
9190        // HEAVIER (4 vs 2) so the critical-path reorder emits it first.
9191        // (Stamps only; not realized here — the ordering proof, CPU-runnable.)
9192        let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9193            g.push(Node {
9194                op,
9195                inputs,
9196                shape: Shape::from_dims(&[3]),
9197                dtype: DType::F32,
9198            })
9199        };
9200        let mut g = Graph::new();
9201        let ca = n(&mut g, Op::Const, vec![]);
9202        let cb = n(&mut g, Op::Const, vec![]);
9203        // CUDA chain — HEAVIER (4 unary stages, one contiguous run).
9204        let mut cprev = ca;
9205        for _ in 0..4 {
9206            cprev = n(&mut g, Op::Relu, vec![cprev]);
9207            g.set_target_backend(cprev, BackendId::Cuda);
9208        }
9209        let c2 = cprev; // CUDA chunk root
9210        // Vulkan chain — lighter (2 unary stages).
9211        let mut vprev = cb;
9212        for _ in 0..2 {
9213            vprev = n(&mut g, Op::Relu, vec![vprev]);
9214            g.set_target_backend(vprev, BackendId::Vulkan);
9215        }
9216        let v2 = vprev; // Vulkan chunk root
9217        // Vulkan -> CUDA copy (residency seam), then reconverge on CUDA with
9218        // inputs [cuda_root, copy] (cuda-first).
9219        let copy = g.push(Node {
9220            op: Op::Copy {
9221                target: DeviceLocation::Cuda { gpu_id: 0 },
9222            },
9223            inputs: vec![v2],
9224            shape: Shape::from_dims(&[3]),
9225            dtype: DType::F32,
9226        });
9227        g.set_target_backend(copy, BackendId::Cuda);
9228        let out = n(&mut g, Op::Add, vec![c2, copy]);
9229        g.set_target_backend(out, BackendId::Cuda);
9230
9231        let unreordered = execution_plan(&g, &[out]);
9232        let reordered = fuel_graph::lower_runs_arm0(&g, &[out]);
9233
9234        // (1) The reorder FIRED — the order changed (else the test is
9235        //     vacuous + auto-overlap did nothing on an arbitrary graph).
9236        assert_ne!(
9237            reordered, unreordered,
9238            "the C3 reorder must change the order on a two-device graph; \
9239             reordered={reordered:?} unreordered={unreordered:?}",
9240        );
9241
9242        // (2) Same node multiset — a permutation, no add/drop.
9243        let mut a = unreordered.clone();
9244        let mut b = reordered.clone();
9245        a.sort();
9246        b.sort();
9247        assert_eq!(a, b, "the reorder is a permutation of the same node set");
9248
9249        // (3) The reordered order is a VALID topological order: every node
9250        //     appears after all of its inputs that are in the order.
9251        let pos: std::collections::HashMap<NodeId, usize> = reordered
9252            .iter()
9253            .enumerate()
9254            .map(|(i, &node)| (node, i))
9255            .collect();
9256        for (i, &node) in reordered.iter().enumerate() {
9257            for &inp in &g.node(node).inputs {
9258                if let Some(&j) = pos.get(&inp) {
9259                    assert!(
9260                        j < i,
9261                        "input {inp:?} of {node:?} must precede it in the reordered \
9262                         order; reordered={reordered:?}",
9263                    );
9264                }
9265            }
9266        }
9267
9268        // (4) The overlap-relevant property: BOTH device producer chunks
9269        //     (the CUDA root c2, the Vulkan root v2) are emitted BEFORE the
9270        //     host-blocking cross-device copy — the A4b overlap topology the
9271        //     un-reordered cuda-last DFS violates — AND the HEAVIER CUDA chunk
9272        //     is emitted first (critical-path: the auto-submit device runs
9273        //     earliest, the live-overlap regression guard).
9274        let p = |node: NodeId| pos[&node];
9275        assert!(p(c2) < p(copy), "CUDA chunk before the cross-device copy");
9276        assert!(p(v2) < p(copy), "Vulkan chunk before the cross-device copy");
9277        assert!(
9278            p(c2) < p(v2),
9279            "the heavier CUDA chunk is emitted before the lighter Vulkan chunk \
9280             (critical-path heavy-first); reordered={reordered:?}",
9281        );
9282    }
9283
9284    /// **C3 follow-on — the OPERAND-ORDER-INVARIANCE gate (CPU, runnable —
9285    /// the reliable operand-independence proof).** The residual the live
9286    /// `cuda_vulkan_overlap_bench_live` benchmark targets is whether the
9287    /// reconverge OPERAND order (`xc.add(&xv)` vs `xv.add(&xc)`) changes the
9288    /// wall-clock overlap. Wall-clock is thermally noisy on a heterogeneous
9289    /// dev box; the DETERMINISTIC root guarantee is this: the C3-reordered
9290    /// dispatch order the executor consumes is **byte-identical for both
9291    /// operand orders**. If the lowered order is the same, the executor
9292    /// processes the SAME WorkItem stream with the SAME cross-device
9293    /// submit/wait timing, so overlap cannot depend on the operand order.
9294    ///
9295    /// This builds the SAME two-device reconverge as
9296    /// `c3_reorder_is_a_valid_topo_permutation` but TWICE — once cuda-first
9297    /// (`add(cuda_root, copy)`), once vulkan-first (`add(copy, cuda_root)`)
9298    /// — over structurally identical graphs (same node ids, only the
9299    /// reconverge's two inputs swapped) and asserts `lower_runs_arm0` emits
9300    /// the identical op/device run sequence. The live executor trace confirms
9301    /// the same: both operand orders produce the identical WorkItem stream
9302    /// (the eager-submit/drain/wait sequence at every cross-device copy is the
9303    /// same, and the CUDA chunk is enqueued first in both).
9304    #[test]
9305    fn c3_reorder_is_operand_order_invariant() {
9306        // Build the two-device reconverge with the reconverge inputs in the
9307        // given order; return (graph, out) over a FRESH graph so node ids line
9308        // up 1:1 between the two builds (only the add's input order differs).
9309        let build = |cuda_first: bool| -> (Graph, NodeId) {
9310            let n = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9311                g.push(Node {
9312                    op,
9313                    inputs,
9314                    shape: Shape::from_dims(&[3]),
9315                    dtype: DType::F32,
9316                })
9317            };
9318            let mut g = Graph::new();
9319            let ca = n(&mut g, Op::Const, vec![]);
9320            let cb = n(&mut g, Op::Const, vec![]);
9321            let mut cprev = ca;
9322            for _ in 0..4 {
9323                cprev = n(&mut g, Op::Relu, vec![cprev]);
9324                g.set_target_backend(cprev, BackendId::Cuda);
9325            }
9326            let c2 = cprev;
9327            let mut vprev = cb;
9328            for _ in 0..2 {
9329                vprev = n(&mut g, Op::Relu, vec![vprev]);
9330                g.set_target_backend(vprev, BackendId::Vulkan);
9331            }
9332            let v2 = vprev;
9333            let copy = g.push(Node {
9334                op: Op::Copy {
9335                    target: DeviceLocation::Cuda { gpu_id: 0 },
9336                },
9337                inputs: vec![v2],
9338                shape: Shape::from_dims(&[3]),
9339                dtype: DType::F32,
9340            });
9341            g.set_target_backend(copy, BackendId::Cuda);
9342            // The ONE knob: the reconverge's two inputs, swapped.
9343            let inputs = if cuda_first {
9344                vec![c2, copy]
9345            } else {
9346                vec![copy, c2]
9347            };
9348            let out = n(&mut g, Op::Add, inputs);
9349            g.set_target_backend(out, BackendId::Cuda);
9350            (g, out)
9351        };
9352
9353        let (g_cf, out_cf) = build(true);
9354        let (g_vf, out_vf) = build(false);
9355
9356        // Lower both via the production path (dispatch_order → lower_runs_arm0
9357        // → device_alternating_order, the C3 reorder).
9358        let order_cf = fuel_graph::lower_runs_arm0(&g_cf, &[out_cf]);
9359        let order_vf = fuel_graph::lower_runs_arm0(&g_vf, &[out_vf]);
9360
9361        // The decisive guarantee: the lowered dispatch order — as an
9362        // (op, device) sequence — is IDENTICAL for both operand orders. (Node
9363        // ids can differ if the build assigned them differently, but here the
9364        // builds are structurally identical so even the ids match; compare the
9365        // op/device sequence to be robust + descriptive on failure.)
9366        let tag = |g: &Graph, ids: &[NodeId]| -> Vec<(String, Option<BackendId>)> {
9367            ids.iter()
9368                .map(|&id| (format!("{:?}", g.node(id).op), g.target_backend(id)))
9369                .collect()
9370        };
9371        let seq_cf = tag(&g_cf, &order_cf);
9372        let seq_vf = tag(&g_vf, &order_vf);
9373        assert_eq!(
9374            seq_cf, seq_vf,
9375            "the C3-reordered dispatch order MUST be identical for both \
9376             reconverge operand orders (operand-order-invariance — the \
9377             executor then sees the same WorkItem stream regardless of \
9378             operand order, so overlap is operand-insensitive).\n\
9379             cuda-first = {seq_cf:?}\nvulkan-first = {seq_vf:?}",
9380        );
9381    }
9382
9383    /// A selector that always takes the LAST arm (arm 1) so a non-arm-0
9384    /// pick is observable (a `WinnerSelector` picks arm-0 ⇒ empty route).
9385    #[cfg(test)]
9386    #[derive(Debug)]
9387    struct PickLast;
9388    #[cfg(test)]
9389    impl RuntimeSelector for PickLast {
9390        fn select<'a>(
9391            &self,
9392            set: &'a crate::ranker::AlternativeSet,
9393        ) -> Option<&'a crate::ranker::Candidate> {
9394            set.alternatives().last()
9395        }
9396    }
9397
9398    /// Build the 2-arm diamond (mirrors `route_picker::tests::diamond`):
9399    /// arm-0 on CUDA, arm-1 on CPU; the arm exits carry their
9400    /// `target_backend` so the picker reads each arm's placement. Returns
9401    /// `(graph_arc, branch, post)`.
9402    #[cfg(test)]
9403    fn picking_diamond() -> (Arc<RwLock<Graph>>, NodeId, NodeId) {
9404        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9405            g.push(Node {
9406                op,
9407                inputs,
9408                shape: Shape::from_dims(&[2]),
9409                dtype: DType::F32,
9410            })
9411        };
9412        let mut g = Graph::new();
9413        let pre = node(&mut g, Op::Const, vec![]);
9414        let diverge = node(&mut g, Op::Relu, vec![pre]);
9415        let arm0 = node(&mut g, Op::Silu, vec![diverge]);
9416        let arm1 = node(&mut g, Op::GeluTanh, vec![diverge]);
9417        g.set_target_backend(arm0, BackendId::Cuda);
9418        g.set_target_backend(arm1, BackendId::Cpu);
9419        let reconverge = node(&mut g, Op::Relu, vec![arm0]);
9420        let mut b = g.open_branch(diverge);
9421        b.add_arm(arm0);
9422        b.add_arm(arm1);
9423        let branch = b
9424            .finalize_branches(&mut g, reconverge)
9425            .expect("well-formed 2-arm branch")
9426            .expect("2 arms survive");
9427        let post = node(&mut g, Op::Tanh, vec![reconverge]);
9428        (Arc::new(RwLock::new(g)), branch, post)
9429    }
9430
9431    /// Step E Phase C, PR C1: the streaming picking entry's gate.
9432    /// `streaming_pick_for` (the streaming successor of the old one-shot
9433    /// `pick_route_for`) must (1) return `Some(pick)` when a selector + a
9434    /// branch are present (⇒ the `OrderSource::Streaming` walk), (2) return
9435    /// `None` with no selector (the `runtime_selector_disabled` opt-out ⇒
9436    /// arm-0), and (3) short-circuit to `None` on a branchless graph (the
9437    /// fast-path ⇒ the untouched `dispatch_order` lowering).
9438    #[test]
9439    fn streaming_pick_for_gates() {
9440        let (graph, _branch, post) = picking_diamond();
9441        let _ = post;
9442
9443        // (1) selector + branch ⇒ Some(pick).
9444        let sel: Arc<dyn RuntimeSelector> = Arc::new(PickLast);
9445        assert!(
9446            PipelinedExecutor::streaming_pick_for(&graph, Some(sel.clone()), None)
9447                .expect("ok")
9448                .is_some(),
9449            "selector + branch ⇒ a streaming pick",
9450        );
9451
9452        // (2) no selector ⇒ None (arm-0 lowering).
9453        assert!(
9454            PipelinedExecutor::streaming_pick_for(&graph, None, None)
9455                .expect("ok")
9456                .is_none(),
9457            "no selector ⇒ no streaming pick (arm-0 lowering)",
9458        );
9459
9460        // (3) branchless graph + selector ⇒ None (the fast-path).
9461        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9462            g.push(Node {
9463                op,
9464                inputs,
9465                shape: Shape::from_dims(&[2]),
9466                dtype: DType::F32,
9467            })
9468        };
9469        let bl_graph = {
9470            let mut g = Graph::new();
9471            let c1 = node(&mut g, Op::Const, vec![]);
9472            let c2 = node(&mut g, Op::Const, vec![]);
9473            let add = node(&mut g, Op::Add, vec![c1, c2]);
9474            g.set_target_backend(add, BackendId::Cpu);
9475            Arc::new(RwLock::new(g))
9476        };
9477        assert!(
9478            PipelinedExecutor::streaming_pick_for(&bl_graph, Some(sel), None)
9479                .expect("ok")
9480                .is_none(),
9481            "branchless graph ⇒ no branches ⇒ no streaming pick (fast-path)",
9482        );
9483    }
9484
9485    /// **C1 byte-identity gate (executor layer).** The STREAMED dispatch
9486    /// order — produced by the compiler thread's lazy per-branch resolution
9487    /// (`walk_picked_route_streaming` over `resolve_branch`, the same path
9488    /// `order_for(OrderSource::Streaming)` collects) — equals the ONE-SHOT
9489    /// order (`lower_picked_route` over the route the eager `pick_route`
9490    /// resolves) on the branched diamond, for both arm-0 (WinnerSelector)
9491    /// and arm-1 (PickLast). This is the proof that C1 changes *when* a
9492    /// branch resolves, not *which* arm — the same selector, the same
9493    /// `resolve_branch`, the same emitted order.
9494    #[test]
9495    fn streamed_order_equals_one_shot() {
9496        let (graph, _branch, post) = picking_diamond();
9497        let g = graph.read().unwrap();
9498        let bindings = global_bindings();
9499
9500        for sel in [
9501            Arc::new(crate::ranker::WinnerSelector) as Arc<dyn RuntimeSelector>,
9502            Arc::new(PickLast) as Arc<dyn RuntimeSelector>,
9503        ] {
9504            // One-shot: resolve the whole route, then lower.
9505            let one_shot_route = pick_route(&g, &[post], &bindings, sel.as_ref(), None);
9506            let one_shot = fuel_graph::lower_picked_route(&g, &[post], &one_shot_route);
9507
9508            // Streamed: resolve each branch lazily at the frontier via the
9509            // SAME `resolve_branch` the compiler thread uses.
9510            let streamed = fuel_graph::lower_picked_route_streaming(&g, &[post], |branch| {
9511                resolve_branch(&g, branch, &bindings, sel.as_ref())
9512            });
9513
9514            assert_eq!(
9515                streamed, one_shot,
9516                "streamed order must equal one-shot for selector {sel:?}",
9517            );
9518        }
9519    }
9520
9521    /// ROW 157 / GAP-385: with ONE branch in the graph, the executor realizes a PICKED multi-node arm to the
9522    /// same numbers as arm 0. This is NOT shown for chained branches: with two or more in a row it failed
9523    /// (`input ... not realized`) until the lowering-order fix of 2026-11-17 (ROADMAP row 158); see
9524    /// `chained_branches_realize_equal_to_arm_zero_for_every_combination_of_arms_on_cpu`.
9525    ///
9526    /// A residual block on the host: `c1 -> relu -> silu -> tanh -> add(c1, .)`. The branch is built by
9527    /// the pathfinder's own `record_branch` (so the clone logic under test is the shipped code) with
9528    /// the alternative backend set to `Cpu`, which lets arm 1 run on this box. The route `{branch: 1}`
9529    /// makes the executor run the cloned three-node stretch; the result must equal the arm-0 result.
9530    ///
9531    /// What this does NOT show: a cross-device arm (the real alternative is another backend, with
9532    /// copies at its entry and exit), nor which arm a live selector picks. The same-backend arms mean
9533    /// the selector cannot map back to arm 1, so the route is given explicitly.
9534    #[test]
9535    fn a_single_picked_multi_node_arm_realizes_equal_to_arm_zero_on_cpu() {
9536        let (arm0, arm1) = realize_residual_block_both_arms(false);
9537        assert_eq!(
9538            arm1, arm0,
9539            "the cloned stretch computes what arm 0 computes"
9540        );
9541        assert_eq!(arm0.len(), 3);
9542        assert!(arm0.iter().all(|v| v.is_finite()));
9543    }
9544
9545    /// POSITIVE CONTROL for the test above (one branch): when the cloned stretch computes something else
9546    /// (Gelu in place of Silu, built by hand), the picked-arm result DIFFERS from arm 0. Without this the
9547    /// equality could pass by the executor ignoring the route and running arm 0 both times.
9548    #[test]
9549    fn a_picked_multi_node_arm_that_differs_changes_the_result() {
9550        let (arm0, arm1) = realize_residual_block_both_arms(true);
9551        assert_ne!(arm1, arm0, "the route must really run the cloned arm");
9552    }
9553
9554    /// Realize `c1 -> relu -> silu -> tanh -> add(c1, .)` through arm 0 and through arm 1. Arm 1 is the
9555    /// clone `record_branch` makes, or, when `control` is set, a hand-built clone whose middle node is
9556    /// Gelu instead of Silu.
9557    #[cfg(test)]
9558    fn realize_residual_block_both_arms(control: bool) -> (Vec<f32>, Vec<f32>) {
9559        use crate::optimize::OptimizedGraph;
9560        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
9561            match &arc.read().unwrap().inner {
9562                fuel_memory::BackendStorage::Cpu(c) => c.as_slice::<f32>().expect("f32").to_vec(),
9563                _ => panic!("expected CPU output"),
9564            }
9565        };
9566        let build = || {
9567            let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9568                let id = g.push(Node {
9569                    op,
9570                    inputs,
9571                    shape: Shape::from_dims(&[3]),
9572                    dtype: DType::F32,
9573                });
9574                g.set_target_backend(id, BackendId::Cpu);
9575                id
9576            };
9577            let mut g = Graph::new();
9578            let c1 = node(&mut g, Op::Const, vec![]);
9579            let r = node(&mut g, Op::Relu, vec![c1]);
9580            let s = node(&mut g, Op::Silu, vec![r]);
9581            let t = node(&mut g, Op::Tanh, vec![s]);
9582            let res = node(&mut g, Op::Add, vec![c1, t]);
9583            let branch = if control {
9584                let r2 = node(&mut g, Op::Relu, vec![c1]);
9585                let s2 = node(&mut g, Op::GeluTanh, vec![r2]);
9586                let t2 = node(&mut g, Op::Tanh, vec![s2]);
9587                let mut b = g.open_branch(c1);
9588                b.add_arm(t);
9589                b.add_arm(t2);
9590                b.finalize_branches(&mut g, res)
9591                    .expect("well-formed")
9592                    .expect("2 arms")
9593            } else {
9594                crate::region_pathfinder::record_branch(
9595                    &mut g,
9596                    c1,
9597                    res,
9598                    &[r, s, t],
9599                    t,
9600                    BackendId::Cpu,
9601                )
9602                .expect("the region records a 2-arm branch")
9603            };
9604            let mut inputs = StorageCache::new();
9605            inputs.insert(
9606                c1,
9607                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
9608                    -1.0_f32, 0.5, 2.0,
9609                ]))),
9610            );
9611            (Arc::new(RwLock::new(g)), res, branch, inputs)
9612        };
9613
9614        drop(global_bindings());
9615        let run = |pick_arm1: bool| -> Vec<f32> {
9616            // Another test registering a backend or kernels bumps the process-wide topology generation
9617            // (`bump_topology_generation`, shared by every concurrently running test), and the executor
9618            // then returns `TopologyChanged` ("rebuild and retry") for a plan stamped before the bump.
9619            // Measured: 1 in ~55 full-suite runs at 17 threads, 6 in 110, every one the message
9620            // "generation N ... generation M"; it is not arm choice. Follow the error's own contract
9621            // with a bounded rebuild, and fail loudly on anything else or on 20 stale stamps in a row.
9622            for _attempt in 0..20 {
9623                let (graph, res, branch, inputs) = build();
9624                let opt = OptimizedGraph {
9625                    roots: vec![res],
9626                    generation: crate::dispatch::topology_generation(),
9627                    placements: None,
9628                    eviction: None,
9629                };
9630                let mut route = PickedRoute::new();
9631                if pick_arm1 {
9632                    route.insert(branch, 1);
9633                }
9634                match PipelinedExecutor::realize_with_optimized_route(
9635                    graph, res, inputs, &opt, &route,
9636                ) {
9637                    Ok((arc, _)) => return read(&arc),
9638                    Err(e) if format!("{e}").contains("topology generation") => continue,
9639                    Err(e) => panic!("realize: {e}"),
9640                }
9641            }
9642            panic!("realize: topology generation changed on 20 consecutive attempts")
9643        };
9644        (run(false), run(true))
9645    }
9646
9647    // ===== Row 158: chained region branches with a NON-ZERO arm chosen. The first real run of arm 1 on a
9648    //        GPU failed with "reshape input NodeId(2) of NodeId(3) not realized"; it reproduces on CPU
9649    //        and was a lowering-order bug (`fuel-graph/src/run.rs`): the chosen arm's run was emitted
9650    //        after the reconverge that reads it whenever two or more branches were chained. =====
9651
9652    /// `ids, table -> IndexSelect -> Reshape -> block*` where each block is the residual stretch
9653    /// `relu -> silu -> tanh -> add(x, .)` recorded as a 2-arm branch (arm 1 = the clone), so block `i`'s
9654    /// reconverge is block `i + 1`'s diverge (the shape of the toy Llama graph). Returns
9655    /// `(graph, root, branches, ids_const, table_const, head nodes)`.
9656    #[cfg(test)]
9657    fn head_then_region_chain(
9658        blocks: usize,
9659    ) -> (Graph, NodeId, Vec<NodeId>, NodeId, NodeId, Vec<NodeId>) {
9660        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>, dims: &[usize], dt: DType| {
9661            let id = g.push(Node {
9662                op,
9663                inputs,
9664                shape: Shape::from_dims(dims),
9665                dtype: dt,
9666            });
9667            g.set_target_backend(id, BackendId::Cpu);
9668            id
9669        };
9670        let mut g = Graph::new();
9671        let ids = node(&mut g, Op::Const, vec![], &[3], DType::U32);
9672        let table = node(&mut g, Op::Const, vec![], &[8, 4], DType::F32);
9673        let gathered = node(
9674            &mut g,
9675            Op::IndexSelect { dim: 0 },
9676            vec![table, ids],
9677            &[3, 4],
9678            DType::F32,
9679        );
9680        let mut x = node(
9681            &mut g,
9682            Op::Reshape(Shape::from_dims(&[1, 3, 4])),
9683            vec![gathered],
9684            &[1, 3, 4],
9685            DType::F32,
9686        );
9687        let head = vec![gathered, x];
9688        let mut branches = Vec::new();
9689        for _ in 0..blocks {
9690            let r = node(&mut g, Op::Relu, vec![x], &[1, 3, 4], DType::F32);
9691            let s = node(&mut g, Op::Silu, vec![r], &[1, 3, 4], DType::F32);
9692            let t = node(&mut g, Op::Tanh, vec![s], &[1, 3, 4], DType::F32);
9693            let res = node(&mut g, Op::Add, vec![x, t], &[1, 3, 4], DType::F32);
9694            let branch = crate::region_pathfinder::record_branch(
9695                &mut g,
9696                x,
9697                res,
9698                &[r, s, t],
9699                t,
9700                BackendId::Cpu,
9701            )
9702            .expect("the block records a 2-arm branch");
9703            branches.push(branch);
9704            x = res;
9705        }
9706        (g, x, branches, ids, table, head)
9707    }
9708
9709    /// The route that sends branch `i` to arm 1 iff bit `i` of `mask` is set.
9710    #[cfg(test)]
9711    fn route_from_mask(branches: &[NodeId], mask: usize) -> PickedRoute {
9712        let mut route = PickedRoute::new();
9713        for (i, &b) in branches.iter().enumerate() {
9714            if mask >> i & 1 == 1 {
9715                route.insert(b, 1);
9716            }
9717        }
9718        route
9719    }
9720
9721    /// Why `order` is not a valid dispatch order for the route `mask`, or `None` when it is. Valid: every
9722    /// emitted node's inputs are emitted earlier, are leaves, or are an arm-0 exit whose branch chose
9723    /// arm 1 and whose arm-1 exit was emitted earlier (the alias the compiler thread inserts); the chosen
9724    /// arm's exit is emitted and the other arm's is not.
9725    #[cfg(test)]
9726    fn why_invalid_order(
9727        g: &Graph,
9728        branches: &[NodeId],
9729        mask: usize,
9730        order: &[NodeId],
9731    ) -> Option<String> {
9732        let mut alias: HashMap<NodeId, NodeId> = HashMap::new();
9733        for (i, &b) in branches.iter().enumerate() {
9734            if mask >> i & 1 == 1 {
9735                alias.insert(g.node(b).inputs[0], g.node(b).inputs[1]);
9736            }
9737        }
9738        let mut emitted: HashSet<NodeId> = HashSet::new();
9739        for &n in order {
9740            for &inp in &g.node(n).inputs {
9741                let ok = emitted.contains(&inp)
9742                    || matches!(g.node(inp).op, Op::Const)
9743                    || alias.get(&inp).is_some_and(|a| emitted.contains(a));
9744                if !ok {
9745                    return Some(format!(
9746                        "node {n:?} ({:?}) is emitted before its input {inp:?} ({:?})",
9747                        g.node(n).op,
9748                        g.node(inp).op
9749                    ));
9750                }
9751            }
9752            emitted.insert(n);
9753        }
9754        for (i, &b) in branches.iter().enumerate() {
9755            let arms = &g.node(b).inputs;
9756            let (chosen, other) = if mask >> i & 1 == 1 {
9757                (arms[1], arms[0])
9758            } else {
9759                (arms[0], arms[1])
9760            };
9761            if !emitted.contains(&chosen) {
9762                return Some(format!(
9763                    "branch {i}: the chosen arm exit {chosen:?} is not emitted"
9764                ));
9765            }
9766            if emitted.contains(&other) {
9767                return Some(format!(
9768                    "branch {i}: the other arm exit {other:?} is emitted"
9769                ));
9770            }
9771        }
9772        None
9773    }
9774
9775    /// LOWERING level (no executor): for 1 to 4 chained branches and EVERY combination of arms (not only
9776    /// all arm 1), the frozen and the streaming lowering each emit a valid order, and the two orders are
9777    /// identical for the same picks. Before the fix N=1 passed and every N >= 2 with an arm 1 failed.
9778    #[test]
9779    fn chained_branches_lower_to_a_valid_order_for_every_combination_of_arms() {
9780        for blocks in 1..=4usize {
9781            let (g, root, branches, _ids, _table, head) = head_then_region_chain(blocks);
9782            for mask in 0..(1usize << blocks) {
9783                let route = route_from_mask(&branches, mask);
9784                let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
9785                let streaming = fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
9786                    route.get(&b).copied().unwrap_or(0)
9787                });
9788                for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
9789                    assert_eq!(
9790                        why_invalid_order(&g, &branches, mask, order),
9791                        None,
9792                        "{name} lowering, blocks={blocks} mask={mask:#b}: order={order:?}"
9793                    );
9794                    assert!(
9795                        head.iter().all(|h| order.contains(h)),
9796                        "{name}, blocks={blocks} mask={mask:#b}: the head must be emitted"
9797                    );
9798                }
9799                assert_eq!(
9800                    frozen, streaming,
9801                    "blocks={blocks} mask={mask:#b}: frozen and streaming differ"
9802                );
9803            }
9804        }
9805    }
9806
9807    /// ROW 158: a chain of CROSS-DEVICE region branches. Block `i` is `e = relu(x); d = silu(e);
9808    /// a = add(d, e); t = tanh(a); res = add(d, t)`, the stretch `a, t` is recorded with its alternative on
9809    /// `Cuda { gpu_id: 0 }` (arm 1) and its exit brought back to the host, and the residency pass inserts
9810    /// the inbound copies of BOTH external inputs (`d` and `e`) of the clone. `res` is the next block's `x`.
9811    /// Returns `(graph, root, branches)`.
9812    #[cfg(test)]
9813    fn cross_device_chain(blocks: usize) -> (Graph, NodeId, Vec<NodeId>) {
9814        use crate::region_pathfinder::try_record_branch;
9815        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
9816        let mut g = Graph::new();
9817        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9818            let id = g.push(Node {
9819                op,
9820                inputs,
9821                shape: Shape::from_dims(&[4]),
9822                dtype: DType::F32,
9823            });
9824            g.set_placement(id, DeviceLocation::Cpu);
9825            g.set_target_backend(id, BackendId::Cpu);
9826            id
9827        };
9828        let mut x = node(&mut g, Op::Const, vec![]);
9829        let mut branches = Vec::new();
9830        for _ in 0..blocks {
9831            let e = node(&mut g, Op::Relu, vec![x]);
9832            let d = node(&mut g, Op::Silu, vec![e]);
9833            let a = node(&mut g, Op::Add, vec![d, e]);
9834            let t = node(&mut g, Op::Tanh, vec![a]);
9835            let res = node(&mut g, Op::Add, vec![d, t]);
9836            let branch = try_record_branch(
9837                &mut g,
9838                d,
9839                res,
9840                &[a, t],
9841                t,
9842                BackendId::Cuda,
9843                cuda0,
9844                DeviceLocation::Cpu,
9845            )
9846            .expect("well-formed branch")
9847            .expect("two arms");
9848            branches.push(branch);
9849            x = res;
9850        }
9851        crate::optimize::insert_residency_copies(
9852            &mut g,
9853            &[x],
9854            &crate::plan::ExecutionPlan::empty(),
9855            DeviceLocation::Cpu,
9856            None,
9857        );
9858        (g, x, branches)
9859    }
9860
9861    /// LOWERING level: the cross-device chain (inbound copies, exit copies, two external inputs per arm)
9862    /// lowers to a valid order for 1 to 4 blocks and EVERY combination of arms, frozen and streaming
9863    /// identical. Found on a GPU run: with the chosen arm's runs moved to the slot of the first run that
9864    /// opens an arm, an inbound `Copy` ran before the main-chain node it reads (`Copy input NodeId(130) of
9865    /// NodeId(255) not realized`).
9866    #[test]
9867    fn cross_device_chains_lower_to_a_valid_order_for_every_combination_of_arms() {
9868        for blocks in 1..=4usize {
9869            let (g, root, branches) = cross_device_chain(blocks);
9870            for mask in 0..(1usize << blocks) {
9871                let route = route_from_mask(&branches, mask);
9872                let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
9873                let streaming = fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
9874                    route.get(&b).copied().unwrap_or(0)
9875                });
9876                for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
9877                    assert_eq!(
9878                        why_invalid_order(&g, &branches, mask, order),
9879                        None,
9880                        "{name} lowering, blocks={blocks} mask={mask:#b}: order={order:?}"
9881                    );
9882                }
9883                assert_eq!(
9884                    frozen, streaming,
9885                    "blocks={blocks} mask={mask:#b}: frozen and streaming differ"
9886                );
9887            }
9888        }
9889    }
9890
9891    /// A chain of cross-device region branches whose stretch reads a SHARED EARLY value `h` (computed once,
9892    /// before any diverge) as well as its diverge `d`: `fillers` nodes sit between the previous block and
9893    /// `d`, and `h` enters the stretch at its first node (`second_in_middle == false`) or its second.
9894    /// The residency pass inserts ONE inbound copy of `h` onto the alternative device and CSEs it between
9895    /// every block's arm 1, so that copy is in branch 1's arm 1 and in branch 2's arm 1 at once.
9896    #[cfg(test)]
9897    fn shared_early_input_chain(
9898        blocks: usize,
9899        fillers: usize,
9900        second_in_middle: bool,
9901    ) -> (Graph, NodeId, Vec<NodeId>) {
9902        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
9903        let mut g = Graph::new();
9904        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
9905            let id = g.push(Node {
9906                op,
9907                inputs,
9908                shape: Shape::from_dims(&[4]),
9909                dtype: DType::F32,
9910            });
9911            g.set_placement(id, DeviceLocation::Cpu);
9912            g.set_target_backend(id, BackendId::Cpu);
9913            id
9914        };
9915        let c1 = node(&mut g, Op::Const, vec![]);
9916        // The early value: NOT downstream of any diverge, so it is outside every stretch.
9917        let h = node(&mut g, Op::Relu, vec![c1]);
9918        let mut x = node(&mut g, Op::Const, vec![]);
9919        let mut branches = Vec::new();
9920        for _ in 0..blocks {
9921            let mut d = x;
9922            for _ in 0..fillers {
9923                d = node(&mut g, Op::Silu, vec![d]);
9924            }
9925            let (a, t) = if second_in_middle {
9926                let s1 = node(&mut g, Op::Tanh, vec![d]);
9927                let s2 = node(&mut g, Op::Add, vec![s1, h]);
9928                (s1, s2)
9929            } else {
9930                let s1 = node(&mut g, Op::Add, vec![d, h]);
9931                let s2 = node(&mut g, Op::Tanh, vec![s1]);
9932                (s1, s2)
9933            };
9934            let res = node(&mut g, Op::Add, vec![d, t]);
9935            let branch = crate::region_pathfinder::try_record_branch(
9936                &mut g,
9937                d,
9938                res,
9939                &[a, t],
9940                t,
9941                BackendId::Cuda,
9942                cuda0,
9943                DeviceLocation::Cpu,
9944            )
9945            .expect("well-formed branch")
9946            .expect("two arms");
9947            branches.push(branch);
9948            x = res;
9949        }
9950
9951        crate::optimize::insert_residency_copies(
9952            &mut g,
9953            &[x],
9954            &crate::plan::ExecutionPlan::empty(),
9955            DeviceLocation::Cpu,
9956            None,
9957        );
9958        (g, x, branches)
9959    }
9960
9961    /// LOWERING level, 140 shapes (1 to 3 blocks x 0 to 4 fillers x both entry positions x EVERY
9962    /// combination of arms; the frozen and the streaming order may differ here, as they may on any multi-device
9963    /// graph, but BOTH must be valid): a shared inbound copy must run when ANY branch's chosen arm reads it, and the
9964    /// chosen arm's runs must come before the reconverge. Under the first-slot relocation with per-branch
9965    /// skip sets, 80 of the 140 (a node emitted before its input) were invalid; this is the CPU form of the
9966    /// GPU failures `Copy input NodeId(130) of NodeId(255) not realized` and `cpu kernel wrapper called
9967    /// with non-CPU input` (ROADMAP row 158).
9968    #[test]
9969    fn cross_device_chains_with_a_shared_early_input_lower_to_a_valid_order_for_every_combination_of_arms()
9970     {
9971        let mut shapes = 0;
9972        for blocks in 1..=3usize {
9973            for fillers in 0..=4usize {
9974                for second_in_middle in [false, true] {
9975                    let (g, root, branches) =
9976                        shared_early_input_chain(blocks, fillers, second_in_middle);
9977                    for mask in 0..(1usize << blocks) {
9978                        shapes += 1;
9979                        let route = route_from_mask(&branches, mask);
9980                        let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
9981                        let streaming =
9982                            fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
9983                                route.get(&b).copied().unwrap_or(0)
9984                            });
9985                        for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
9986                            assert_eq!(
9987                                why_invalid_order(&g, &branches, mask, order),
9988                                None,
9989                                "{name} lowering, blocks={blocks} fillers={fillers} second_in_middle={second_in_middle} mask={mask:#b}: order={order:?}"
9990                            );
9991                        }
9992                    }
9993                }
9994            }
9995        }
9996        assert_eq!(shapes, 140, "the family size changed: re-pin it");
9997    }
9998
9999    /// A chain of cross-device region branches whose stretch reads EXTERNAL values besides its diverge.
10000    /// `ext[i]` is what block `i`'s stretch reads: 0 = the shared early value `h`, 1 = the value two blocks
10001    /// back (a skip connection), 2 = both. `entry` is the stretch node that reads them (0 = the first, 1 =
10002    /// the second); `fillers` nodes sit between the previous block and the diverge. The residency pass
10003    /// inserts one inbound copy per (value, device) and CSEs it between regions, so a copy can sit in
10004    /// several branches' arm 1 at once and its natural position in the base order is set by whichever
10005    /// branch reaches it first. Lowering only: the ops are structural (an `Add` may have three inputs).
10006    #[cfg(test)]
10007    fn pattern_chain(ext: &[u8], entry: usize, fillers: usize) -> (Graph, NodeId, Vec<NodeId>) {
10008        let cuda0 = DeviceLocation::Cuda { gpu_id: 0 };
10009        let mut g = Graph::new();
10010        let node = |g: &mut Graph, op: Op, inputs: Vec<NodeId>| {
10011            let id = g.push(Node {
10012                op,
10013                inputs,
10014                shape: Shape::from_dims(&[4]),
10015                dtype: DType::F32,
10016            });
10017            g.set_placement(id, DeviceLocation::Cpu);
10018            g.set_target_backend(id, BackendId::Cpu);
10019            id
10020        };
10021        let c1 = node(&mut g, Op::Const, vec![]);
10022        let h = node(&mut g, Op::Relu, vec![c1]);
10023        let mut two_back = node(&mut g, Op::Const, vec![]);
10024        let mut x = node(&mut g, Op::Const, vec![]);
10025        let mut one_back = x;
10026        let mut branches = Vec::new();
10027        for &kind in ext {
10028            let mut d = x;
10029            for _ in 0..fillers {
10030                d = node(&mut g, Op::Silu, vec![d]);
10031            }
10032            let externals: Vec<NodeId> = match kind {
10033                0 => vec![h],
10034                1 => vec![two_back],
10035                _ => vec![h, two_back],
10036            };
10037            let (first, last) = if entry == 0 {
10038                let mut inputs = vec![d];
10039                inputs.extend(externals);
10040                let a = node(&mut g, Op::Add, inputs);
10041                let t = node(&mut g, Op::Tanh, vec![a]);
10042                (a, t)
10043            } else {
10044                let a = node(&mut g, Op::Tanh, vec![d]);
10045                let mut inputs = vec![a];
10046                inputs.extend(externals);
10047                let t = node(&mut g, Op::Add, inputs);
10048                (a, t)
10049            };
10050            let res = node(&mut g, Op::Add, vec![d, last]);
10051            let branch = crate::region_pathfinder::try_record_branch(
10052                &mut g,
10053                d,
10054                res,
10055                &[first, last],
10056                last,
10057                BackendId::Cuda,
10058                cuda0,
10059                DeviceLocation::Cpu,
10060            )
10061            .expect("well-formed branch")
10062            .expect("two arms");
10063            branches.push(branch);
10064            two_back = one_back;
10065            one_back = x;
10066            x = res;
10067        }
10068        crate::optimize::insert_residency_copies(
10069            &mut g,
10070            &[x],
10071            &crate::plan::ExecutionPlan::empty(),
10072            DeviceLocation::Cpu,
10073            None,
10074        );
10075        (g, x, branches)
10076    }
10077
10078    /// LOWERING level, 1548 (shape, arm combination) cases: 1 to 3 chained cross-device branches, every
10079    /// per-block external-input pattern (`h`, a skip connection, both), both entry positions, 0 to 2
10080    /// fillers, EVERY combination of arms; frozen and streaming lowering each valid. With the chosen arm's
10081    /// late runs moved to the FIRST arm slot, 644 checks failed with `Copy (onto Cuda) is emitted before
10082    /// its input`, the CPU form of the GPU failure `Copy input NodeId(130) of NodeId(255) not realized`:
10083    /// the first run opening an arm of the branch was an arm-1 inbound copy shared with another region and
10084    /// positioned early, and the other arm-1 runs were moved there, before the node they read.
10085    #[test]
10086    fn cross_device_chains_with_shared_and_skip_inputs_lower_to_a_valid_order_for_every_combination_of_arms()
10087     {
10088        let mut cases = 0;
10089        for blocks in 1..=3usize {
10090            for code in 0..3usize.pow(blocks as u32) {
10091                let ext: Vec<u8> = (0..blocks)
10092                    .map(|i| ((code / 3usize.pow(i as u32)) % 3) as u8)
10093                    .collect();
10094                for entry in 0..2usize {
10095                    for fillers in 0..=2usize {
10096                        let (g, root, branches) = pattern_chain(&ext, entry, fillers);
10097                        for mask in 0..(1usize << blocks) {
10098                            cases += 1;
10099                            let route = route_from_mask(&branches, mask);
10100                            let frozen = fuel_graph::lower_picked_route(&g, &[root], &route);
10101                            let streaming =
10102                                fuel_graph::lower_picked_route_streaming(&g, &[root], |b| {
10103                                    route.get(&b).copied().unwrap_or(0)
10104                                });
10105                            for (name, order) in [("frozen", &frozen), ("streaming", &streaming)] {
10106                                assert_eq!(
10107                                    why_invalid_order(&g, &branches, mask, order),
10108                                    None,
10109                                    "{name} lowering, ext={ext:?} entry={entry} fillers={fillers} mask={mask:#b}: order={order:?}"
10110                                );
10111                            }
10112                        }
10113                    }
10114                }
10115            }
10116        }
10117        assert_eq!(cases, 1548, "the family size changed: re-pin it");
10118    }
10119
10120    /// EXECUTOR level on CPU: the chain realized for every combination of arms (2 and 3 blocks, every
10121    /// mask, arm 1 = the clone on the same backend) equals arm 0. Before the fix any chain of two or more
10122    /// with an arm 1 failed with "input ... not realized".
10123    #[test]
10124    fn chained_branches_realize_equal_to_arm_zero_for_every_combination_of_arms_on_cpu() {
10125        use crate::optimize::OptimizedGraph;
10126        let read = |arc: &Arc<RwLock<Storage>>| -> Vec<f32> {
10127            match &arc.read().unwrap().inner {
10128                fuel_memory::BackendStorage::Cpu(c) => c.as_slice::<f32>().expect("f32").to_vec(),
10129                _ => panic!("expected CPU output"),
10130            }
10131        };
10132        drop(global_bindings());
10133        // Hold the generation still between building the stamp and realizing (ROADMAP row 165).
10134        let _gate = crate::dispatch::TOPOLOGY_TEST_GATE
10135            .write()
10136            .unwrap_or_else(|p| p.into_inner());
10137        let run = |blocks: usize, mask: usize| -> Vec<f32> {
10138            let (g, root, branches, ids, table, _head) = head_then_region_chain(blocks);
10139            let mut inputs = StorageCache::new();
10140            inputs.insert(
10141                ids,
10142                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1_u32, 4, 6]))),
10143            );
10144            let table_vals: Vec<f32> = (0..32).map(|i| (i as f32 - 16.0) / 8.0).collect();
10145            inputs.insert(
10146                table,
10147                Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&table_vals))),
10148            );
10149            let opt = OptimizedGraph {
10150                roots: vec![root],
10151                generation: crate::dispatch::topology_generation(),
10152                placements: None,
10153                eviction: None,
10154            };
10155            let route = route_from_mask(&branches, mask);
10156            let (arc, _) = PipelinedExecutor::realize_with_optimized_route(
10157                Arc::new(RwLock::new(g)),
10158                root,
10159                inputs,
10160                &opt,
10161                &route,
10162            )
10163            .unwrap_or_else(|e| panic!("realize (blocks={blocks}, mask={mask:#b}): {e}"));
10164            read(&arc)
10165        };
10166        for blocks in 1..=3usize {
10167            let arm0 = run(blocks, 0);
10168            assert_eq!(arm0.len(), 12);
10169            assert!(arm0.iter().all(|v| v.is_finite()));
10170            for mask in 1..(1usize << blocks) {
10171                assert_eq!(
10172                    run(blocks, mask),
10173                    arm0,
10174                    "blocks={blocks} mask={mask:#b}: a cloned stretch computes what arm 0 computes"
10175                );
10176            }
10177        }
10178    }
10179
10180    /// Realizing a node whose target_backend isn't set surfaces a
10181    /// typed error (no panic).
10182    #[test]
10183    fn pipelined_errors_on_unset_target_backend() {
10184        let graph = Arc::new(RwLock::new(Graph::new()));
10185        let (lhs_id, rhs_id, add_id) = {
10186            let mut g = graph.write().unwrap();
10187            let lhs = g.push(Node {
10188                op: Op::Const,
10189                inputs: vec![],
10190                shape: Shape::from_dims(&[2]),
10191                dtype: DType::F32,
10192            });
10193            let rhs = g.push(Node {
10194                op: Op::Const,
10195                inputs: vec![],
10196                shape: Shape::from_dims(&[2]),
10197                dtype: DType::F32,
10198            });
10199            // Deliberately do NOT call set_target_backend on the Add.
10200            let add = g.push(Node {
10201                op: Op::Add,
10202                inputs: vec![lhs, rhs],
10203                shape: Shape::from_dims(&[2]),
10204                dtype: DType::F32,
10205            });
10206            (lhs, rhs, add)
10207        };
10208
10209        let mut inputs = StorageCache::new();
10210        inputs.insert(
10211            lhs_id,
10212            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]))),
10213        );
10214        inputs.insert(
10215            rhs_id,
10216            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]))),
10217        );
10218
10219        let result = PipelinedExecutor::realize(graph, add_id, inputs);
10220        assert!(result.is_err(), "missing target_backend must error");
10221        let msg = result.unwrap_err().to_string();
10222        assert!(
10223            msg.contains("target_backend"),
10224            "error names the unmet precondition: {msg}"
10225        );
10226    }
10227
10228    /// Realizing a Const-only graph adopts the pre-seeded input
10229    /// without calling any kernel.
10230    #[test]
10231    fn pipelined_realize_const_only() {
10232        let storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0]);
10233
10234        let graph = Arc::new(RwLock::new(Graph::new()));
10235        let const_id = {
10236            let mut g = graph.write().unwrap();
10237            g.push(Node {
10238                op: Op::Const,
10239                inputs: vec![],
10240                shape: Shape::from_dims(&[3]),
10241                dtype: DType::F32,
10242            })
10243        };
10244
10245        let mut inputs = StorageCache::new();
10246        inputs.insert(const_id, Arc::new(RwLock::new(storage)));
10247
10248        let (result_arc, _) =
10249            PipelinedExecutor::realize(graph, const_id, inputs).expect("realize const");
10250        let guard = result_arc.read().unwrap();
10251        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10252            let typed: &[f32] = c.as_slice().unwrap();
10253            assert_eq!(typed, &[5.0, 6.0, 7.0]);
10254        }
10255    }
10256
10257    /// Missing input-cache entry for a Const surfaces a typed error.
10258    #[test]
10259    fn pipelined_errors_on_missing_const_input() {
10260        let graph = Arc::new(RwLock::new(Graph::new()));
10261        let const_id = {
10262            let mut g = graph.write().unwrap();
10263            g.push(Node {
10264                op: Op::Const,
10265                inputs: vec![],
10266                shape: Shape::from_dims(&[2]),
10267                dtype: DType::F32,
10268            })
10269        };
10270        // Deliberately empty input cache.
10271        let inputs = StorageCache::new();
10272        let result = PipelinedExecutor::realize(graph, const_id, inputs);
10273        assert!(result.is_err());
10274    }
10275
10276    /// E2E: 2-node graph (Const + Relu) — exercises the unary
10277    /// dispatch wrapper + kernel through the pipelined executor.
10278    #[test]
10279    fn pipelined_realize_const_relu() {
10280        let storage = fuel_memory::from_slice_cpu(&[-1.0_f32, 0.0, 0.5, -3.5, 7.25]);
10281        let graph = Arc::new(RwLock::new(Graph::new()));
10282        let (in_id, relu_id) = {
10283            let mut g = graph.write().unwrap();
10284            let in_id = g.push(Node {
10285                op: Op::Const,
10286                inputs: vec![],
10287                shape: Shape::from_dims(&[5]),
10288                dtype: DType::F32,
10289            });
10290            let relu_id = g.push(Node {
10291                op: Op::Relu,
10292                inputs: vec![in_id],
10293                shape: Shape::from_dims(&[5]),
10294                dtype: DType::F32,
10295            });
10296            g.set_target_backend(relu_id, BackendId::Cpu);
10297            (in_id, relu_id)
10298        };
10299        let mut inputs = StorageCache::new();
10300        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10301
10302        let (result_arc, _) = PipelinedExecutor::realize(graph, relu_id, inputs).expect("realize");
10303        let guard = result_arc.read().unwrap();
10304        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10305            let typed: &[f32] = c.as_slice().expect("f32 cast");
10306            assert_eq!(typed, &[0.0, 0.0, 0.5, 0.0, 7.25]);
10307        }
10308    }
10309
10310    /// E2E: Const + Const + Sub + Mul + Div — exercises three more
10311    /// of the freshly-migrated binary kernels in one graph. Verifies
10312    /// that intermediates flow through the cache as expected.
10313    #[test]
10314    fn pipelined_realize_chained_binary_ops() {
10315        let a_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
10316        let b_storage = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0]);
10317        let c_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 4.0]);
10318
10319        let graph = Arc::new(RwLock::new(Graph::new()));
10320        let (a_id, b_id, c_id, sub_id, mul_id, div_id) = {
10321            let mut g = graph.write().unwrap();
10322            let a = g.push(Node {
10323                op: Op::Const,
10324                inputs: vec![],
10325                shape: Shape::from_dims(&[2]),
10326                dtype: DType::F32,
10327            });
10328            let b = g.push(Node {
10329                op: Op::Const,
10330                inputs: vec![],
10331                shape: Shape::from_dims(&[2]),
10332                dtype: DType::F32,
10333            });
10334            let c = g.push(Node {
10335                op: Op::Const,
10336                inputs: vec![],
10337                shape: Shape::from_dims(&[2]),
10338                dtype: DType::F32,
10339            });
10340            // (a - b)         = [7, 15]
10341            let sub = g.push(Node {
10342                op: Op::Sub,
10343                inputs: vec![a, b],
10344                shape: Shape::from_dims(&[2]),
10345                dtype: DType::F32,
10346            });
10347            // (a - b) * c     = [14, 60]
10348            let mul = g.push(Node {
10349                op: Op::Mul,
10350                inputs: vec![sub, c],
10351                shape: Shape::from_dims(&[2]),
10352                dtype: DType::F32,
10353            });
10354            // ((a-b)*c) / b   = [14/3, 12]
10355            let div = g.push(Node {
10356                op: Op::Div,
10357                inputs: vec![mul, b],
10358                shape: Shape::from_dims(&[2]),
10359                dtype: DType::F32,
10360            });
10361            g.set_target_backend(sub, BackendId::Cpu);
10362            g.set_target_backend(mul, BackendId::Cpu);
10363            g.set_target_backend(div, BackendId::Cpu);
10364            (a, b, c, sub, mul, div)
10365        };
10366
10367        let _ = (sub_id, mul_id);
10368        let mut inputs = StorageCache::new();
10369        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
10370        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
10371        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
10372
10373        let (result_arc, _) = PipelinedExecutor::realize(graph, div_id, inputs).expect("realize");
10374        let guard = result_arc.read().unwrap();
10375        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
10376            let typed: &[f32] = c.as_slice().unwrap();
10377            assert!((typed[0] - (14.0_f32 / 3.0)).abs() < 1e-6);
10378            assert!((typed[1] - 12.0).abs() < 1e-6);
10379        }
10380    }
10381
10382    /// E2E: Const + Transpose — verifies metadata-only view ops
10383    /// share the input's Storage Arc and produce a strided Layout.
10384    /// Stage 3 of Layout-on-Node.
10385    #[test]
10386    fn pipelined_realize_transpose_is_metadata_only() {
10387        // shape [2, 3]; transpose → shape [3, 2], strided
10388        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10389        let graph = Arc::new(RwLock::new(Graph::new()));
10390        let (in_id, t_id) = {
10391            let mut g = graph.write().unwrap();
10392            let in_id = g.push(Node {
10393                op: Op::Const,
10394                inputs: vec![],
10395                shape: Shape::from_dims(&[2, 3]),
10396                dtype: DType::F32,
10397            });
10398            let t_id = g.push(Node {
10399                op: Op::Transpose,
10400                inputs: vec![in_id],
10401                shape: Shape::from_dims(&[3, 2]),
10402                dtype: DType::F32,
10403            });
10404            // Note: NO set_target_backend — transpose is metadata-only
10405            // and doesn't run on a backend.
10406            (in_id, t_id)
10407        };
10408        let mut inputs = StorageCache::new();
10409        let in_arc = Arc::new(RwLock::new(storage));
10410        inputs.insert(in_id, Arc::clone(&in_arc));
10411
10412        let (result_arc, result_layout) =
10413            PipelinedExecutor::realize(graph, t_id, inputs).expect("realize");
10414
10415        // The output Storage Arc is the SAME Arc as the input —
10416        // metadata-only adoption shares bytes.
10417        assert!(
10418            Arc::ptr_eq(&result_arc, &in_arc),
10419            "transpose must share input bytes"
10420        );
10421
10422        // The output Layout is the transposed view.
10423        assert_eq!(result_layout.shape().dims(), &[3, 2]);
10424        assert_eq!(result_layout.stride(), &[1, 3]);
10425        assert!(!result_layout.is_contiguous());
10426    }
10427
10428    /// E2E: Const + Flip(dim=0) — verifies Op::Flip is metadata-only.
10429    /// The output Storage Arc must be the SAME Arc (no copy);
10430    /// the output Layout has a negated stride at dim 0 and a
10431    /// shifted start_offset.
10432    #[test]
10433    fn pipelined_realize_flip_is_metadata_only() {
10434        // shape [3, 4]; flip dim 0 → shape [3, 4], stride [-4, 1], offset 8.
10435        let data: Vec<f32> = (1..=12).map(|x| x as f32).collect();
10436        let storage = fuel_memory::from_slice_cpu(&data);
10437        let graph = Arc::new(RwLock::new(Graph::new()));
10438        let (in_id, f_id) = {
10439            let mut g = graph.write().unwrap();
10440            let in_id = g.push(Node {
10441                op: Op::Const,
10442                inputs: vec![],
10443                shape: Shape::from_dims(&[3, 4]),
10444                dtype: DType::F32,
10445            });
10446            let f_id = g.push(Node {
10447                op: Op::Flip { dim: 0 },
10448                inputs: vec![in_id],
10449                shape: Shape::from_dims(&[3, 4]),
10450                dtype: DType::F32,
10451            });
10452            (in_id, f_id)
10453        };
10454        let mut inputs = StorageCache::new();
10455        let in_arc = Arc::new(RwLock::new(storage));
10456        inputs.insert(in_id, Arc::clone(&in_arc));
10457
10458        let (result_arc, result_layout) =
10459            PipelinedExecutor::realize(graph, f_id, inputs).expect("realize");
10460
10461        assert!(
10462            Arc::ptr_eq(&result_arc, &in_arc),
10463            "flip must share input bytes"
10464        );
10465        assert_eq!(result_layout.shape().dims(), &[3, 4]);
10466        assert_eq!(result_layout.stride(), &[-4_isize, 1]);
10467        assert_eq!(result_layout.start_offset(), 8);
10468        assert!(!result_layout.is_contiguous());
10469    }
10470
10471    /// E2E: Const + Permute(rank-3 axes [2, 0, 1]) — verifies the
10472    /// general permute path through metadata-only adoption.
10473    #[test]
10474    fn pipelined_realize_permute_is_metadata_only() {
10475        // shape [2, 3, 4]; permute axes [2, 0, 1] → shape [4, 2, 3]
10476        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
10477        let storage = fuel_memory::from_slice_cpu(&data);
10478        let graph = Arc::new(RwLock::new(Graph::new()));
10479        let (in_id, p_id) = {
10480            let mut g = graph.write().unwrap();
10481            let in_id = g.push(Node {
10482                op: Op::Const,
10483                inputs: vec![],
10484                shape: Shape::from_dims(&[2, 3, 4]),
10485                dtype: DType::F32,
10486            });
10487            let p_id = g.push(Node {
10488                op: Op::Permute(vec![2, 0, 1]),
10489                inputs: vec![in_id],
10490                shape: Shape::from_dims(&[4, 2, 3]),
10491                dtype: DType::F32,
10492            });
10493            (in_id, p_id)
10494        };
10495        let mut inputs = StorageCache::new();
10496        let in_arc = Arc::new(RwLock::new(storage));
10497        inputs.insert(in_id, Arc::clone(&in_arc));
10498
10499        let (result_arc, result_layout) =
10500            PipelinedExecutor::realize(graph, p_id, inputs).expect("realize");
10501
10502        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10503        assert_eq!(result_layout.shape().dims(), &[4, 2, 3]);
10504        // Original strides for shape [2, 3, 4] are [12, 4, 1].
10505        // After permute axes [2, 0, 1]: [strides[2], strides[0], strides[1]] = [1, 12, 4].
10506        assert_eq!(result_layout.stride(), &[1, 12, 4]);
10507    }
10508
10509    /// E2E: Const + Cast(f32→f64) — verifies cast through the
10510    /// pipelined executor. Output Storage has the target dtype;
10511    /// bytes encode the widened values.
10512    #[test]
10513    fn pipelined_realize_cast_f32_to_f64() {
10514        let storage = fuel_memory::from_slice_cpu(&[1.5_f32, -2.25, 100.0]);
10515        let graph = Arc::new(RwLock::new(Graph::new()));
10516        let (in_id, c_id) = {
10517            let mut g = graph.write().unwrap();
10518            let in_id = g.push(Node {
10519                op: Op::Const,
10520                inputs: vec![],
10521                shape: Shape::from_dims(&[3]),
10522                dtype: DType::F32,
10523            });
10524            let c_id = g.push(Node {
10525                op: Op::Cast(DType::F64),
10526                inputs: vec![in_id],
10527                shape: Shape::from_dims(&[3]),
10528                dtype: DType::F64,
10529            });
10530            g.set_target_backend(c_id, BackendId::Cpu);
10531            (in_id, c_id)
10532        };
10533        let mut inputs = StorageCache::new();
10534        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10535
10536        let (result_arc, result_layout) =
10537            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
10538        assert_eq!(result_layout.shape().dims(), &[3]);
10539
10540        let guard = result_arc.read().unwrap();
10541        assert_eq!(guard.dtype, DType::F64);
10542        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10543            panic!("expected Cpu storage");
10544        };
10545        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.5_f64, -2.25, 100.0]);
10546    }
10547
10548    /// E2E: Const + Cast(f32→bf16) + Cast(bf16→f32) — round trip
10549    /// through bf16; verifies the Cast wrapper's source-dtype
10550    /// dispatch (different sources hit different match arms).
10551    /// Inputs chosen to round-trip exactly through bf16.
10552    #[test]
10553    fn pipelined_realize_cast_round_trip_via_bf16() {
10554        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, -3.0, 0.5]);
10555        let graph = Arc::new(RwLock::new(Graph::new()));
10556        let (in_id, c1_id, c2_id) = {
10557            let mut g = graph.write().unwrap();
10558            let in_id = g.push(Node {
10559                op: Op::Const,
10560                inputs: vec![],
10561                shape: Shape::from_dims(&[4]),
10562                dtype: DType::F32,
10563            });
10564            let c1_id = g.push(Node {
10565                op: Op::Cast(DType::BF16),
10566                inputs: vec![in_id],
10567                shape: Shape::from_dims(&[4]),
10568                dtype: DType::BF16,
10569            });
10570            let c2_id = g.push(Node {
10571                op: Op::Cast(DType::F32),
10572                inputs: vec![c1_id],
10573                shape: Shape::from_dims(&[4]),
10574                dtype: DType::F32,
10575            });
10576            g.set_target_backend(c1_id, BackendId::Cpu);
10577            g.set_target_backend(c2_id, BackendId::Cpu);
10578            (in_id, c1_id, c2_id)
10579        };
10580        let _ = c1_id;
10581        let mut inputs = StorageCache::new();
10582        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10583
10584        let (result_arc, _) = PipelinedExecutor::realize(graph, c2_id, inputs).expect("realize");
10585        let guard = result_arc.read().unwrap();
10586        assert_eq!(guard.dtype, DType::F32);
10587        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10588            panic!("expected Cpu storage");
10589        };
10590        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0_f32, 2.0, -3.0, 0.5]);
10591    }
10592
10593    /// E2E: Const + Slice — slice is metadata-only; the output Arc
10594    /// shares bytes with the input, and the Layout's start_offset
10595    /// + narrowed shape reflect the slice. Stage 3 of Layout-on-Node
10596    ///
10597    /// extended to cover Op::Slice via Layout::narrow.
10598    #[test]
10599    fn pipelined_realize_slice_is_metadata_only() {
10600        // shape [5]; slice dim 0 from index 1 with len 3 → shape [3]
10601        // Source: [10, 20, 30, 40, 50]; slice → [20, 30, 40]
10602        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10603        let graph = Arc::new(RwLock::new(Graph::new()));
10604        let (in_id, s_id) = {
10605            let mut g = graph.write().unwrap();
10606            let in_id = g.push(Node {
10607                op: Op::Const,
10608                inputs: vec![],
10609                shape: Shape::from_dims(&[5]),
10610                dtype: DType::F32,
10611            });
10612            let s_id = g.push(Node {
10613                op: Op::Slice {
10614                    dim: 0,
10615                    start: 1,
10616                    len: 3,
10617                },
10618                inputs: vec![in_id],
10619                shape: Shape::from_dims(&[3]),
10620                dtype: DType::F32,
10621            });
10622            (in_id, s_id)
10623        };
10624        let mut inputs = StorageCache::new();
10625        let in_arc = Arc::new(RwLock::new(storage));
10626        inputs.insert(in_id, Arc::clone(&in_arc));
10627
10628        let (result_arc, result_layout) =
10629            PipelinedExecutor::realize(graph, s_id, inputs).expect("realize");
10630
10631        // Bytes shared with the input.
10632        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10633        assert_eq!(result_layout.shape().dims(), &[3]);
10634        // Slice into a contiguous source: the resulting layout has
10635        // start_offset = original_stride[0] * start = 1 * 1 = 1,
10636        // and stride [1] (still contiguous within the narrowed dim).
10637        assert_eq!(result_layout.start_offset(), 1);
10638        assert_eq!(result_layout.stride(), &[1]);
10639    }
10640
10641    /// E2E: Const + Slice + SumAll — slice is metadata-only, but
10642    /// sum needs contiguous bytes, so auto-Contiguize materializes
10643    /// the slice before reduce. Tests the stage 3+4 integration
10644    /// through Op::Slice. Sum of `[20, 30, 40]` is 90.
10645    #[test]
10646    fn pipelined_realize_slice_then_sum_all() {
10647        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
10648        let graph = Arc::new(RwLock::new(Graph::new()));
10649        let (in_id, s_id, sum_id) = {
10650            let mut g = graph.write().unwrap();
10651            let in_id = g.push(Node {
10652                op: Op::Const,
10653                inputs: vec![],
10654                shape: Shape::from_dims(&[5]),
10655                dtype: DType::F32,
10656            });
10657            let s_id = g.push(Node {
10658                op: Op::Slice {
10659                    dim: 0,
10660                    start: 1,
10661                    len: 3,
10662                },
10663                inputs: vec![in_id],
10664                shape: Shape::from_dims(&[3]),
10665                dtype: DType::F32,
10666            });
10667            let sum_id = g.push(Node {
10668                op: Op::SumAll,
10669                inputs: vec![s_id],
10670                shape: Shape::from_dims(&[]),
10671                dtype: DType::F32,
10672            });
10673            g.set_target_backend(sum_id, BackendId::Cpu);
10674            (in_id, s_id, sum_id)
10675        };
10676        let _ = s_id;
10677        let mut inputs = StorageCache::new();
10678        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10679
10680        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
10681        let guard = result_arc.read().unwrap();
10682        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10683            panic!("expected Cpu storage");
10684        };
10685        assert_eq!(c.as_slice::<f32>().unwrap(), &[90.0]);
10686    }
10687
10688    /// E2E: Const + Flip + ReluElementwise — Flip is metadata-only,
10689    /// then a kernel that doesn't yet handle negative strides forces
10690    /// auto-Contiguize to materialize through StridedIndex (which
10691    /// handles signed strides natively). Verifies the post-flip
10692    /// data ordering ([4, 3, 2, 1]) is correctly seen by the kernel.
10693    #[test]
10694    fn pipelined_realize_flip_then_relu_materializes_in_reverse() {
10695        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
10696        let graph = Arc::new(RwLock::new(Graph::new()));
10697        let (in_id, _f_id, r_id) = {
10698            let mut g = graph.write().unwrap();
10699            let in_id = g.push(Node {
10700                op: Op::Const,
10701                inputs: vec![],
10702                shape: Shape::from_dims(&[4]),
10703                dtype: DType::F32,
10704            });
10705            let f_id = g.push(Node {
10706                op: Op::Flip { dim: 0 },
10707                inputs: vec![in_id],
10708                shape: Shape::from_dims(&[4]),
10709                dtype: DType::F32,
10710            });
10711            let r_id = g.push(Node {
10712                op: Op::Relu,
10713                inputs: vec![f_id],
10714                shape: Shape::from_dims(&[4]),
10715                dtype: DType::F32,
10716            });
10717            g.set_target_backend(r_id, BackendId::Cpu);
10718            (in_id, f_id, r_id)
10719        };
10720        let mut inputs = StorageCache::new();
10721        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
10722
10723        let (result_arc, result_layout) =
10724            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
10725        let guard = result_arc.read().unwrap();
10726        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10727            panic!("expected Cpu storage");
10728        };
10729        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 3.0, 2.0, 1.0]);
10730        assert_eq!(result_layout.shape().dims(), &[4]);
10731        assert!(result_layout.is_contiguous(), "relu output is contiguous");
10732    }
10733
10734    /// E2E: Const + BroadcastTo — verifies that broadcast layouts
10735    /// have stride 0 on the broadcast dim while sharing the input's
10736    /// bytes. Stage 3 of Layout-on-Node.
10737    #[test]
10738    fn pipelined_realize_broadcast_is_metadata_only() {
10739        // shape [3]; broadcast to [4, 3] — leading dim is 0-stride
10740        let storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
10741        let graph = Arc::new(RwLock::new(Graph::new()));
10742        let (in_id, b_id) = {
10743            let mut g = graph.write().unwrap();
10744            let in_id = g.push(Node {
10745                op: Op::Const,
10746                inputs: vec![],
10747                shape: Shape::from_dims(&[3]),
10748                dtype: DType::F32,
10749            });
10750            let b_id = g.push(Node {
10751                op: Op::BroadcastTo(Shape::from_dims(&[4, 3])),
10752                inputs: vec![in_id],
10753                shape: Shape::from_dims(&[4, 3]),
10754                dtype: DType::F32,
10755            });
10756            (in_id, b_id)
10757        };
10758        let mut inputs = StorageCache::new();
10759        let in_arc = Arc::new(RwLock::new(storage));
10760        inputs.insert(in_id, Arc::clone(&in_arc));
10761
10762        let (result_arc, result_layout) =
10763            PipelinedExecutor::realize(graph, b_id, inputs).expect("realize");
10764
10765        assert!(Arc::ptr_eq(&result_arc, &in_arc));
10766        assert_eq!(result_layout.shape().dims(), &[4, 3]);
10767        // Broadcasted leading dim has stride 0.
10768        assert_eq!(result_layout.stride(), &[0, 1]);
10769    }
10770
10771    /// E2E: Const + Const + MatMul — exercises rank-2 matmul
10772    /// through the pipelined executor. Inputs are contiguous (no
10773    /// auto-Contiguize needed); the kernel walks them via the
10774    /// (m, n, k) carried in OpParams::Matmul.
10775    #[test]
10776    fn pipelined_realize_matmul_2x3_times_3x2() {
10777        // [[1, 2, 3], [4, 5, 6]] @ [[7, 8], [9, 10], [11, 12]]
10778        //   = [[58, 64], [139, 154]]
10779        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
10780        let rhs_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
10781
10782        let graph = Arc::new(RwLock::new(Graph::new()));
10783        let (lhs_id, rhs_id, mm_id) = {
10784            let mut g = graph.write().unwrap();
10785            let lhs = g.push(Node {
10786                op: Op::Const,
10787                inputs: vec![],
10788                shape: Shape::from_dims(&[2, 3]),
10789                dtype: DType::F32,
10790            });
10791            let rhs = g.push(Node {
10792                op: Op::Const,
10793                inputs: vec![],
10794                shape: Shape::from_dims(&[3, 2]),
10795                dtype: DType::F32,
10796            });
10797            let mm = g.push(Node {
10798                op: Op::MatMul,
10799                inputs: vec![lhs, rhs],
10800                shape: Shape::from_dims(&[2, 2]),
10801                dtype: DType::F32,
10802            });
10803            g.set_target_backend(mm, BackendId::Cpu);
10804            (lhs, rhs, mm)
10805        };
10806        let mut inputs = StorageCache::new();
10807        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10808        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10809
10810        let (result_arc, result_layout) =
10811            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10812        assert_eq!(result_layout.shape().dims(), &[2, 2]);
10813        assert!(result_layout.is_contiguous());
10814
10815        let guard = result_arc.read().unwrap();
10816        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10817            panic!("expected Cpu storage");
10818        };
10819        assert_eq!(c.as_slice::<f32>().unwrap(), &[58.0, 64.0, 139.0, 154.0]);
10820    }
10821
10822    /// E2E: batched matmul through the pipelined executor. Two
10823    /// batches of [2, 2] @ [2, 2]; the kernel iterates over
10824    /// `batch_count` and produces concatenated outputs.
10825    #[test]
10826    fn pipelined_realize_matmul_batched_2x_2x2_times_2x2() {
10827        let lhs_storage = fuel_memory::from_slice_cpu(&[
10828            1.0_f32, 2.0, 3.0, 4.0, // batch 0
10829            1.0, 0.0, 0.0, 1.0, // batch 1 (identity)
10830        ]);
10831        let rhs_storage = fuel_memory::from_slice_cpu(&[
10832            5.0_f32, 6.0, 7.0, 8.0, // batch 0
10833            10.0, 20.0, 30.0, 40.0, // batch 1
10834        ]);
10835
10836        let graph = Arc::new(RwLock::new(Graph::new()));
10837        let (lhs_id, rhs_id, mm_id) = {
10838            let mut g = graph.write().unwrap();
10839            let lhs = g.push(Node {
10840                op: Op::Const,
10841                inputs: vec![],
10842                shape: Shape::from_dims(&[2, 2, 2]),
10843                dtype: DType::F32,
10844            });
10845            let rhs = g.push(Node {
10846                op: Op::Const,
10847                inputs: vec![],
10848                shape: Shape::from_dims(&[2, 2, 2]),
10849                dtype: DType::F32,
10850            });
10851            let mm = g.push(Node {
10852                op: Op::MatMul,
10853                inputs: vec![lhs, rhs],
10854                shape: Shape::from_dims(&[2, 2, 2]),
10855                dtype: DType::F32,
10856            });
10857            g.set_target_backend(mm, BackendId::Cpu);
10858            (lhs, rhs, mm)
10859        };
10860        let mut inputs = StorageCache::new();
10861        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
10862        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
10863
10864        let (result_arc, result_layout) =
10865            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
10866        assert_eq!(result_layout.shape().dims(), &[2, 2, 2]);
10867        assert!(result_layout.is_contiguous());
10868
10869        let guard = result_arc.read().unwrap();
10870        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10871            panic!("expected Cpu storage");
10872        };
10873        // batch 0: [[1,2],[3,4]] @ [[5,6],[7,8]] = [[19,22],[43,50]]
10874        // batch 1: identity @ [[10,20],[30,40]]   = [[10,20],[30,40]]
10875        assert_eq!(
10876            c.as_slice::<f32>().unwrap(),
10877            &[19.0, 22.0, 43.0, 50.0, 10.0, 20.0, 30.0, 40.0]
10878        );
10879    }
10880
10881    /// E2E: F64 elementwise add through the pipelined executor.
10882    /// Verifies that capability-driven dispatch correctly routes
10883    /// (AddElementwise, F64) to the f64 wrapper/kernel.
10884    #[test]
10885    fn pipelined_realize_add_f64() {
10886        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
10887        let rhs = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0, 30.0]);
10888        let graph = Arc::new(RwLock::new(Graph::new()));
10889        let (l_id, r_id, op_id) = {
10890            let mut g = graph.write().unwrap();
10891            let l = g.push(Node {
10892                op: Op::Const,
10893                inputs: vec![],
10894                shape: Shape::from_dims(&[3]),
10895                dtype: DType::F64,
10896            });
10897            let r = g.push(Node {
10898                op: Op::Const,
10899                inputs: vec![],
10900                shape: Shape::from_dims(&[3]),
10901                dtype: DType::F64,
10902            });
10903            let op = g.push(Node {
10904                op: Op::Add,
10905                inputs: vec![l, r],
10906                shape: Shape::from_dims(&[3]),
10907                dtype: DType::F64,
10908            });
10909            g.set_target_backend(op, BackendId::Cpu);
10910            (l, r, op)
10911        };
10912        let mut inputs = StorageCache::new();
10913        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10914        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10915        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
10916        let guard = result_arc.read().unwrap();
10917        assert_eq!(guard.dtype, DType::F64);
10918        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10919            panic!("expected Cpu storage");
10920        };
10921        assert_eq!(c.as_slice::<f64>().unwrap(), &[11.0_f64, 22.0, 33.0]);
10922    }
10923
10924    /// E2E: Op::Equal F32 → Bool mask through the pipelined executor (GAP-168c).
10925    /// Verifies (a) the binding-table key `(EqualElementwise, [F32, F32, U8],
10926    /// Cpu)` resolves, (b) the executor allocates a U8-sized output
10927    /// buffer (1 byte per element, not 4), (c) the kernel writes the
10928    /// expected mask bits including IEEE-754 NaN handling
10929    /// (`NaN == NaN` is false).
10930    #[test]
10931    fn pipelined_realize_eq_f32_to_bool_mask() {
10932        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10933        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10934        let graph = Arc::new(RwLock::new(Graph::new()));
10935        let (l_id, r_id, eq_id) = {
10936            let mut g = graph.write().unwrap();
10937            let l = g.push(Node {
10938                op: Op::Const,
10939                inputs: vec![],
10940                shape: Shape::from_dims(&[5]),
10941                dtype: DType::F32,
10942            });
10943            let r = g.push(Node {
10944                op: Op::Const,
10945                inputs: vec![],
10946                shape: Shape::from_dims(&[5]),
10947                dtype: DType::F32,
10948            });
10949            let eq = g.push(Node {
10950                op: Op::Equal,
10951                inputs: vec![l, r],
10952                shape: Shape::from_dims(&[5]),
10953                dtype: DType::Bool,
10954            });
10955            g.set_target_backend(eq, BackendId::Cpu);
10956            (l, r, eq)
10957        };
10958        let mut inputs = StorageCache::new();
10959        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
10960        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
10961        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
10962        let guard = result_arc.read().unwrap();
10963        assert_eq!(guard.dtype, DType::Bool);
10964        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
10965            panic!("expected Cpu storage");
10966        };
10967        let mask: &[u8] = c.as_slice().expect("u8 view");
10968        // Index 0: 1.0 == 1.0 → 1.
10969        // Index 1: 2.0 != 5.0 → 0.
10970        // Index 2: 3.0 == 3.0 → 1.
10971        // Index 3: NaN == NaN → 0 (IEEE-754).
10972        // Index 4: 0.0 == -0.0 → 1 (IEEE-754 zero equality).
10973        assert_eq!(mask, &[1, 0, 1, 0, 1]);
10974    }
10975
10976    /// E2E: Op::Ne F32 → Bool mask. Mirrors the Eq F32 test with
10977    /// inverted predicate; NaN-vs-NaN slot now yields `1` (since
10978    /// `NaN != NaN` per IEEE-754).
10979    #[test]
10980    fn pipelined_realize_ne_f32_to_bool_mask() {
10981        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, f32::NAN, 0.0]);
10982        let rhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -0.0]);
10983        let graph = Arc::new(RwLock::new(Graph::new()));
10984        let (l_id, r_id, ne_id) = {
10985            let mut g = graph.write().unwrap();
10986            let l = g.push(Node {
10987                op: Op::Const,
10988                inputs: vec![],
10989                shape: Shape::from_dims(&[5]),
10990                dtype: DType::F32,
10991            });
10992            let r = g.push(Node {
10993                op: Op::Const,
10994                inputs: vec![],
10995                shape: Shape::from_dims(&[5]),
10996                dtype: DType::F32,
10997            });
10998            let ne = g.push(Node {
10999                op: Op::Ne,
11000                inputs: vec![l, r],
11001                shape: Shape::from_dims(&[5]),
11002                dtype: DType::Bool,
11003            });
11004            g.set_target_backend(ne, BackendId::Cpu);
11005            (l, r, ne)
11006        };
11007        let mut inputs = StorageCache::new();
11008        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11009        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11010        let (result_arc, _) = PipelinedExecutor::realize(graph, ne_id, inputs).expect("realize");
11011        let guard = result_arc.read().unwrap();
11012        assert_eq!(guard.dtype, DType::Bool);
11013        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11014            panic!("expected Cpu storage");
11015        };
11016        let mask: &[u8] = c.as_slice().expect("u8 view");
11017        // Inverse of the Eq test:
11018        // 1.0 != 1.0 → 0;  2.0 != 5.0 → 1;  3.0 != 3.0 → 0;
11019        // NaN != NaN → 1 (IEEE-754);  0.0 != -0.0 → 0 (IEEE-754).
11020        assert_eq!(mask, &[0, 1, 0, 1, 0]);
11021    }
11022
11023    /// E2E: Op::Lt F32 → Bool mask. Confirms strict-less-than semantics
11024    /// + IEEE-754 NaN handling (any comparison with NaN is unordered →
11025    ///
11026    /// `0`).
11027    #[test]
11028    fn pipelined_realize_lt_f32_to_bool_mask() {
11029        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
11030        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11031        let graph = Arc::new(RwLock::new(Graph::new()));
11032        let (l_id, r_id, lt_id) = {
11033            let mut g = graph.write().unwrap();
11034            let l = g.push(Node {
11035                op: Op::Const,
11036                inputs: vec![],
11037                shape: Shape::from_dims(&[5]),
11038                dtype: DType::F32,
11039            });
11040            let r = g.push(Node {
11041                op: Op::Const,
11042                inputs: vec![],
11043                shape: Shape::from_dims(&[5]),
11044                dtype: DType::F32,
11045            });
11046            let lt = g.push(Node {
11047                op: Op::Lt,
11048                inputs: vec![l, r],
11049                shape: Shape::from_dims(&[5]),
11050                dtype: DType::Bool,
11051            });
11052            g.set_target_backend(lt, BackendId::Cpu);
11053            (l, r, lt)
11054        };
11055        let mut inputs = StorageCache::new();
11056        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11057        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11058        let (result_arc, _) = PipelinedExecutor::realize(graph, lt_id, inputs).expect("realize");
11059        let guard = result_arc.read().unwrap();
11060        assert_eq!(guard.dtype, DType::Bool);
11061        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11062            panic!("expected Cpu storage");
11063        };
11064        let mask: &[u8] = c.as_slice().expect("u8 view");
11065        // 1.0 < 2.0 → 1;  5.0 < 5.0 → 0 (strict);  3.0 < 3.0 → 0;
11066        // NaN < 0.0 → 0 (unordered);  -1.0 < 0.0 → 1.
11067        assert_eq!(mask, &[1, 0, 0, 0, 1]);
11068    }
11069
11070    /// E2E: Op::Le F32 → Bool mask. Distinct from Lt at the equal slot
11071    /// (`5.0 <= 5.0` = 1, vs Lt's `5.0 < 5.0` = 0). NaN unordered → 0.
11072    #[test]
11073    fn pipelined_realize_le_f32_to_bool_mask() {
11074        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0, f32::NAN, -1.0]);
11075        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 2.0, 0.0, 0.0]);
11076        let graph = Arc::new(RwLock::new(Graph::new()));
11077        let (l_id, r_id, le_id) = {
11078            let mut g = graph.write().unwrap();
11079            let l = g.push(Node {
11080                op: Op::Const,
11081                inputs: vec![],
11082                shape: Shape::from_dims(&[5]),
11083                dtype: DType::F32,
11084            });
11085            let r = g.push(Node {
11086                op: Op::Const,
11087                inputs: vec![],
11088                shape: Shape::from_dims(&[5]),
11089                dtype: DType::F32,
11090            });
11091            let le = g.push(Node {
11092                op: Op::Le,
11093                inputs: vec![l, r],
11094                shape: Shape::from_dims(&[5]),
11095                dtype: DType::Bool,
11096            });
11097            g.set_target_backend(le, BackendId::Cpu);
11098            (l, r, le)
11099        };
11100        let mut inputs = StorageCache::new();
11101        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11102        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11103        let (result_arc, _) = PipelinedExecutor::realize(graph, le_id, inputs).expect("realize");
11104        let guard = result_arc.read().unwrap();
11105        assert_eq!(guard.dtype, DType::Bool);
11106        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11107            panic!("expected Cpu storage");
11108        };
11109        let mask: &[u8] = c.as_slice().expect("u8 view");
11110        // 1.0 <= 2.0 → 1;  5.0 <= 5.0 → 1 (key Lt difference);
11111        // 3.0 <= 2.0 → 0;  NaN <= 0.0 → 0 (unordered);  -1.0 <= 0.0 → 1.
11112        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11113    }
11114
11115    /// E2E: Op::Gt F32 → Bool mask. Strict-greater: equality slot is
11116    /// `0`. NaN unordered → `0`.
11117    #[test]
11118    fn pipelined_realize_gt_f32_to_bool_mask() {
11119        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 1.0]);
11120        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11121        let graph = Arc::new(RwLock::new(Graph::new()));
11122        let (l_id, r_id, gt_id) = {
11123            let mut g = graph.write().unwrap();
11124            let l = g.push(Node {
11125                op: Op::Const,
11126                inputs: vec![],
11127                shape: Shape::from_dims(&[5]),
11128                dtype: DType::F32,
11129            });
11130            let r = g.push(Node {
11131                op: Op::Const,
11132                inputs: vec![],
11133                shape: Shape::from_dims(&[5]),
11134                dtype: DType::F32,
11135            });
11136            let gt = g.push(Node {
11137                op: Op::Gt,
11138                inputs: vec![l, r],
11139                shape: Shape::from_dims(&[5]),
11140                dtype: DType::Bool,
11141            });
11142            g.set_target_backend(gt, BackendId::Cpu);
11143            (l, r, gt)
11144        };
11145        let mut inputs = StorageCache::new();
11146        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11147        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11148        let (result_arc, _) = PipelinedExecutor::realize(graph, gt_id, inputs).expect("realize");
11149        let guard = result_arc.read().unwrap();
11150        assert_eq!(guard.dtype, DType::Bool);
11151        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11152            panic!("expected Cpu storage");
11153        };
11154        let mask: &[u8] = c.as_slice().expect("u8 view");
11155        // 3.0 > 2.0 → 1;  5.0 > 5.0 → 0 (strict);  2.0 > 3.0 → 0;
11156        // NaN > 0.0 → 0 (unordered);  1.0 > 0.0 → 1.
11157        assert_eq!(mask, &[1, 0, 0, 0, 1]);
11158    }
11159
11160    /// E2E: Op::Ge F32 → Bool mask. Greater-or-equal: equality slot
11161    /// is `1` (distinguishes from Gt). NaN unordered → `0`. Closes
11162    /// the comparison family with full `[Eq, Ne, Lt, Le, Gt, Ge]`
11163    /// coverage.
11164    #[test]
11165    fn pipelined_realize_ge_f32_to_bool_mask() {
11166        let lhs = fuel_memory::from_slice_cpu(&[3.0_f32, 5.0, 2.0, f32::NAN, 0.0]);
11167        let rhs = fuel_memory::from_slice_cpu(&[2.0_f32, 5.0, 3.0, 0.0, 0.0]);
11168        let graph = Arc::new(RwLock::new(Graph::new()));
11169        let (l_id, r_id, ge_id) = {
11170            let mut g = graph.write().unwrap();
11171            let l = g.push(Node {
11172                op: Op::Const,
11173                inputs: vec![],
11174                shape: Shape::from_dims(&[5]),
11175                dtype: DType::F32,
11176            });
11177            let r = g.push(Node {
11178                op: Op::Const,
11179                inputs: vec![],
11180                shape: Shape::from_dims(&[5]),
11181                dtype: DType::F32,
11182            });
11183            let ge = g.push(Node {
11184                op: Op::Ge,
11185                inputs: vec![l, r],
11186                shape: Shape::from_dims(&[5]),
11187                dtype: DType::Bool,
11188            });
11189            g.set_target_backend(ge, BackendId::Cpu);
11190            (l, r, ge)
11191        };
11192        let mut inputs = StorageCache::new();
11193        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11194        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11195        let (result_arc, _) = PipelinedExecutor::realize(graph, ge_id, inputs).expect("realize");
11196        let guard = result_arc.read().unwrap();
11197        assert_eq!(guard.dtype, DType::Bool);
11198        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11199            panic!("expected Cpu storage");
11200        };
11201        let mask: &[u8] = c.as_slice().expect("u8 view");
11202        // 3.0 >= 2.0 → 1;  5.0 >= 5.0 → 1 (key Gt difference);
11203        // 2.0 >= 3.0 → 0;  NaN >= 0.0 → 0 (unordered);  0.0 >= 0.0 → 1.
11204        assert_eq!(mask, &[1, 1, 0, 0, 1]);
11205    }
11206
11207    /// E2E: Op::Equal F64 → Bool mask. Confirms the F64 wrapper is
11208    /// independently registered and routed (binding-table key
11209    /// `(EqualElementwise, [F64, F64, U8], Cpu)`).
11210    #[test]
11211    fn pipelined_realize_eq_f64_to_bool_mask() {
11212        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0]);
11213        let rhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 4.0]);
11214        let graph = Arc::new(RwLock::new(Graph::new()));
11215        let (l_id, r_id, eq_id) = {
11216            let mut g = graph.write().unwrap();
11217            let l = g.push(Node {
11218                op: Op::Const,
11219                inputs: vec![],
11220                shape: Shape::from_dims(&[3]),
11221                dtype: DType::F64,
11222            });
11223            let r = g.push(Node {
11224                op: Op::Const,
11225                inputs: vec![],
11226                shape: Shape::from_dims(&[3]),
11227                dtype: DType::F64,
11228            });
11229            let eq = g.push(Node {
11230                op: Op::Equal,
11231                inputs: vec![l, r],
11232                shape: Shape::from_dims(&[3]),
11233                dtype: DType::Bool,
11234            });
11235            g.set_target_backend(eq, BackendId::Cpu);
11236            (l, r, eq)
11237        };
11238        let mut inputs = StorageCache::new();
11239        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11240        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11241        let (result_arc, _) = PipelinedExecutor::realize(graph, eq_id, inputs).expect("realize");
11242        let guard = result_arc.read().unwrap();
11243        assert_eq!(guard.dtype, DType::Bool);
11244        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11245            panic!("expected Cpu storage");
11246        };
11247        let mask: &[u8] = c.as_slice().expect("u8 view");
11248        assert_eq!(mask, &[1, 1, 0]);
11249    }
11250
11251    /// E2E: Op::Where ternary select — `out[i] = if cond[i] != 0 { a[i] } else { b[i] }`.
11252    /// Validates (a) the binding-table key `(Where, [Bool, F32, F32, F32], Cpu)`
11253    /// resolves to the where_f32 wrapper, (b) the Bool cond input drives
11254    /// the per-slot pick, (c) outputs preserve the input dtype.
11255    ///
11256    /// GAP-168(c): the cond STORAGE is tagged Bool, not merely the graph node.
11257    /// Bool and U8 are byte-identical, so leaving the storage U8 under a Bool
11258    /// node is exactly the mismatch this cut exists to make visible.
11259    #[test]
11260    fn pipelined_realize_where_f32_picks_per_slot_from_bool_mask() {
11261        // cond = [1, 0, 1, 0, 1]; a = [1, 2, 3, 4, 5]; b = [10, 20, 30, 40, 50]
11262        // expected = [1, 20, 3, 40, 5]
11263        let mut cond_storage = fuel_memory::from_slice_cpu(&[1u8, 0, 1, 0, 1]);
11264        cond_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
11265        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0]);
11266        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0]);
11267        let graph = Arc::new(RwLock::new(Graph::new()));
11268        let (cond_id, a_id, b_id, where_id) = {
11269            let mut g = graph.write().unwrap();
11270            let cond = g.push(Node {
11271                op: Op::Const,
11272                inputs: vec![],
11273                shape: Shape::from_dims(&[5]),
11274                dtype: DType::Bool,
11275            });
11276            let a = g.push(Node {
11277                op: Op::Const,
11278                inputs: vec![],
11279                shape: Shape::from_dims(&[5]),
11280                dtype: DType::F32,
11281            });
11282            let b = g.push(Node {
11283                op: Op::Const,
11284                inputs: vec![],
11285                shape: Shape::from_dims(&[5]),
11286                dtype: DType::F32,
11287            });
11288            let w = g.push(Node {
11289                op: Op::Where,
11290                inputs: vec![cond, a, b],
11291                shape: Shape::from_dims(&[5]),
11292                dtype: DType::F32,
11293            });
11294            g.set_target_backend(w, BackendId::Cpu);
11295            (cond, a, b, w)
11296        };
11297        let mut inputs = StorageCache::new();
11298        inputs.insert(cond_id, Arc::new(RwLock::new(cond_storage)));
11299        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11300        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11301        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11302        let guard = result_arc.read().unwrap();
11303        assert_eq!(guard.dtype, DType::F32);
11304        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11305            panic!("expected Cpu storage");
11306        };
11307        let out: &[f32] = c.as_slice().expect("f32 view");
11308        assert_eq!(out, &[1.0, 20.0, 3.0, 40.0, 5.0]);
11309    }
11310
11311    /// E2E: full chain `eq → where`. Compares two f32 vectors, then
11312    /// uses the resulting Bool mask to pick from a third tensor (or a
11313    /// fallback). Validates the comparison-family + Where ops compose
11314    /// end-to-end.
11315    #[test]
11316    fn pipelined_realize_eq_then_where_full_chain() {
11317        // a = [1, 2, 3]; b = [1, 5, 3] → eq = [1, 0, 1]
11318        // pick = [10, 20, 30]; fallback = [99, 99, 99]
11319        // result = [10, 99, 30]
11320        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
11321        let b_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 3.0]);
11322        let pick_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
11323        let fb_storage = fuel_memory::from_slice_cpu(&[99.0_f32, 99.0, 99.0]);
11324        let graph = Arc::new(RwLock::new(Graph::new()));
11325        let (a_id, b_id, pick_id, fb_id, where_id) = {
11326            let mut g = graph.write().unwrap();
11327            let a = g.push(Node {
11328                op: Op::Const,
11329                inputs: vec![],
11330                shape: Shape::from_dims(&[3]),
11331                dtype: DType::F32,
11332            });
11333            let b = g.push(Node {
11334                op: Op::Const,
11335                inputs: vec![],
11336                shape: Shape::from_dims(&[3]),
11337                dtype: DType::F32,
11338            });
11339            let pick = g.push(Node {
11340                op: Op::Const,
11341                inputs: vec![],
11342                shape: Shape::from_dims(&[3]),
11343                dtype: DType::F32,
11344            });
11345            let fb = g.push(Node {
11346                op: Op::Const,
11347                inputs: vec![],
11348                shape: Shape::from_dims(&[3]),
11349                dtype: DType::F32,
11350            });
11351            let eq = g.push(Node {
11352                op: Op::Equal,
11353                inputs: vec![a, b],
11354                shape: Shape::from_dims(&[3]),
11355                dtype: DType::Bool,
11356            });
11357            let w = g.push(Node {
11358                op: Op::Where,
11359                inputs: vec![eq, pick, fb],
11360                shape: Shape::from_dims(&[3]),
11361                dtype: DType::F32,
11362            });
11363            g.set_target_backend(eq, BackendId::Cpu);
11364            g.set_target_backend(w, BackendId::Cpu);
11365            (a, b, pick, fb, w)
11366        };
11367        let mut inputs = StorageCache::new();
11368        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
11369        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
11370        inputs.insert(pick_id, Arc::new(RwLock::new(pick_storage)));
11371        inputs.insert(fb_id, Arc::new(RwLock::new(fb_storage)));
11372        let (result_arc, _) = PipelinedExecutor::realize(graph, where_id, inputs).expect("realize");
11373        let guard = result_arc.read().unwrap();
11374        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11375            panic!("expected Cpu storage");
11376        };
11377        let out: &[f32] = c.as_slice().expect("f32 view");
11378        assert_eq!(out, &[10.0, 99.0, 30.0]);
11379    }
11380
11381    /// E2E: Q4_0 QMatMul through the pipelined executor — proves
11382    /// quantized weights can flow into the unified path. Activations
11383    /// are F32, weights are U32-typed (raw block bytes).
11384    /// Construct a Q4_0 weight tensor where every weight = 1.0
11385    /// (d=1.0, every nibble=9 → 1*(9-8)=1), so A @ W^T computes
11386    /// the per-row sum of activations.
11387    #[test]
11388    fn pipelined_realize_qmatmul_q4_0_unit_weight_sums_activations() {
11389        use fuel_graph::QuantType;
11390        use half::f16;
11391        let block_size = std::mem::size_of::<fuel_quantized::BlockQ4_0>();
11392        let mut w_bytes = vec![0u8; 2 * block_size];
11393        for block_idx in 0..2 {
11394            let off = block_idx * block_size;
11395            let d_bytes = f16::from_f32(1.0).to_le_bytes();
11396            w_bytes[off..off + 2].copy_from_slice(&d_bytes);
11397            for i in 0..16 {
11398                w_bytes[off + 2 + i] = 0x99;
11399            }
11400        }
11401        // Weight tensor is U32-typed (rank-1, length = bytes/4)
11402        let w_storage = fuel_memory::Storage::new(
11403            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11404                &w_bytes,
11405            )),
11406            DType::U32,
11407        );
11408
11409        let act_vec: Vec<f32> = (1..=32).map(|x| x as f32).collect();
11410        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11411
11412        let graph = Arc::new(RwLock::new(Graph::new()));
11413        let (act_id, w_id, mm_id) = {
11414            let mut g = graph.write().unwrap();
11415            let act = g.push(Node {
11416                op: Op::Const,
11417                inputs: vec![],
11418                shape: Shape::from_dims(&[1, 32]),
11419                dtype: DType::F32,
11420            });
11421            let w = g.push(Node {
11422                op: Op::Const,
11423                inputs: vec![],
11424                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11425                dtype: DType::U32,
11426            });
11427            let mm = g.push(Node {
11428                op: Op::Fused(
11429                    fuel_graph::registry::FusedOps::QMATMUL,
11430                    fuel_graph::registry::FusedOpParams::QMatMul {
11431                        quant_type: QuantType::Q4_0,
11432                        k: 32,
11433                        n: 2,
11434                    },
11435                ),
11436                inputs: vec![act, w],
11437                shape: Shape::from_dims(&[1, 2]),
11438                dtype: DType::F32,
11439            });
11440            g.set_target_backend(mm, BackendId::Cpu);
11441            (act, w, mm)
11442        };
11443        let mut inputs = StorageCache::new();
11444        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11445        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11446        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11447        let guard = result_arc.read().unwrap();
11448        assert_eq!(guard.dtype, DType::F32);
11449        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11450            panic!("expected Cpu storage");
11451        };
11452        let r: &[f32] = c.as_slice().unwrap();
11453        // Both rows = sum(1..=32) = 528, within Q8_1 round-trip
11454        // tolerance.
11455        assert!((r[0] - 528.0).abs() < 0.5, "got {}, want 528", r[0]);
11456        assert!((r[1] - 528.0).abs() < 0.5, "got {}, want 528", r[1]);
11457    }
11458
11459    /// E2E: QMatMul with Q5_0 weights — verifies the new quant
11460    /// dispatch arm picks `qmatmul_q5_0_f32`. We build weights by
11461    /// quantizing all-ones via `BlockQ5_0::from_float`, then
11462    /// compare pipelined output against the direct fuel_quantized
11463    /// matmul on the same blocks.
11464    #[test]
11465    fn pipelined_realize_qmatmul_q5_0_against_reference() {
11466        use fuel_graph::QuantType;
11467        use fuel_quantized::{BlockQ5_0, GgmlType};
11468        let n = 2;
11469        let k = 64; // 2 blocks per row
11470        // Quantize an all-ones [n, k] weight matrix.
11471        let w_f32 = vec![1.0_f32; n * k];
11472        let blocks_per_row = k / BlockQ5_0::BLCK_SIZE;
11473        let mut w_blocks = vec![BlockQ5_0::zeros(); n * blocks_per_row];
11474        BlockQ5_0::from_float(&w_f32, &mut w_blocks);
11475        // Reinterpret block slice as bytes (BlockQ5_0 is #[repr(C)]).
11476        let bytes_per_block = std::mem::size_of::<BlockQ5_0>();
11477        let w_bytes: Vec<u8> = unsafe {
11478            std::slice::from_raw_parts(
11479                w_blocks.as_ptr() as *const u8,
11480                w_blocks.len() * bytes_per_block,
11481            )
11482        }
11483        .to_vec();
11484        let w_storage = fuel_memory::Storage::new(
11485            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11486                &w_bytes,
11487            )),
11488            DType::U32,
11489        );
11490        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32).collect();
11491        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11492        // Reference: direct matmul through fuel_quantized.
11493        let mut ref_out = vec![0.0_f32; n];
11494        fuel_quantized::matmul::<BlockQ5_0>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11495            .expect("ref matmul");
11496
11497        let graph = Arc::new(RwLock::new(Graph::new()));
11498        let (act_id, w_id, mm_id) = {
11499            let mut g = graph.write().unwrap();
11500            let act = g.push(Node {
11501                op: Op::Const,
11502                inputs: vec![],
11503                shape: Shape::from_dims(&[1, k]),
11504                dtype: DType::F32,
11505            });
11506            let w = g.push(Node {
11507                op: Op::Const,
11508                inputs: vec![],
11509                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11510                dtype: DType::U32,
11511            });
11512            let mm = g.push(Node {
11513                op: Op::Fused(
11514                    fuel_graph::registry::FusedOps::QMATMUL,
11515                    fuel_graph::registry::FusedOpParams::QMatMul {
11516                        quant_type: QuantType::Q5_0,
11517                        k,
11518                        n,
11519                    },
11520                ),
11521                inputs: vec![act, w],
11522                shape: Shape::from_dims(&[1, n]),
11523                dtype: DType::F32,
11524            });
11525            g.set_target_backend(mm, BackendId::Cpu);
11526            (act, w, mm)
11527        };
11528        let mut inputs = StorageCache::new();
11529        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11530        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11531        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11532        let guard = result_arc.read().unwrap();
11533        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11534            panic!("expected Cpu storage");
11535        };
11536        let r: &[f32] = c.as_slice().unwrap();
11537        // Bit-exact against same kernel via the trait, since both
11538        // paths run fuel_quantized::matmul<BlockQ5_0>.
11539        assert_eq!(
11540            r,
11541            ref_out.as_slice(),
11542            "pipelined Q5_0 differs from reference: got {r:?}, want {ref_out:?}"
11543        );
11544    }
11545
11546    /// E2E: QMatMul with Q6K (256-element super-block k-quant).
11547    /// Same idea as the Q5_0 test — bit-exact against the
11548    /// reference fuel_quantized::matmul<BlockQ6K>. Confirms the
11549    /// dispatch arm wires `qmatmul_q6k_f32` correctly.
11550    #[test]
11551    fn pipelined_realize_qmatmul_q6k_against_reference() {
11552        use fuel_graph::QuantType;
11553        use fuel_quantized::{BlockQ6K, GgmlType};
11554        let n = 2;
11555        let k = 256; // 1 super-block per row
11556        let w_f32 = vec![1.0_f32; n * k];
11557        let blocks_per_row = k / BlockQ6K::BLCK_SIZE;
11558        let mut w_blocks = vec![BlockQ6K::zeros(); n * blocks_per_row];
11559        BlockQ6K::from_float(&w_f32, &mut w_blocks);
11560        let bytes_per_block = std::mem::size_of::<BlockQ6K>();
11561        let w_bytes: Vec<u8> = unsafe {
11562            std::slice::from_raw_parts(
11563                w_blocks.as_ptr() as *const u8,
11564                w_blocks.len() * bytes_per_block,
11565            )
11566        }
11567        .to_vec();
11568        let w_storage = fuel_memory::Storage::new(
11569            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11570                &w_bytes,
11571            )),
11572            DType::U32,
11573        );
11574        let act_vec: Vec<f32> = (1..=k).map(|x| x as f32 / 100.0).collect();
11575        let act_storage = fuel_memory::from_slice_cpu(&act_vec);
11576        let mut ref_out = vec![0.0_f32; n];
11577        fuel_quantized::matmul::<BlockQ6K>((1, k, n), &act_vec, &w_blocks, &mut ref_out)
11578            .expect("ref matmul");
11579
11580        let graph = Arc::new(RwLock::new(Graph::new()));
11581        let (act_id, w_id, mm_id) = {
11582            let mut g = graph.write().unwrap();
11583            let act = g.push(Node {
11584                op: Op::Const,
11585                inputs: vec![],
11586                shape: Shape::from_dims(&[1, k]),
11587                dtype: DType::F32,
11588            });
11589            let w = g.push(Node {
11590                op: Op::Const,
11591                inputs: vec![],
11592                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11593                dtype: DType::U32,
11594            });
11595            let mm = g.push(Node {
11596                op: Op::Fused(
11597                    fuel_graph::registry::FusedOps::QMATMUL,
11598                    fuel_graph::registry::FusedOpParams::QMatMul {
11599                        quant_type: QuantType::Q6K,
11600                        k,
11601                        n,
11602                    },
11603                ),
11604                inputs: vec![act, w],
11605                shape: Shape::from_dims(&[1, n]),
11606                dtype: DType::F32,
11607            });
11608            g.set_target_backend(mm, BackendId::Cpu);
11609            (act, w, mm)
11610        };
11611        let mut inputs = StorageCache::new();
11612        inputs.insert(act_id, Arc::new(RwLock::new(act_storage)));
11613        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11614        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11615        let guard = result_arc.read().unwrap();
11616        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11617            panic!("expected Cpu storage");
11618        };
11619        let r: &[f32] = c.as_slice().unwrap();
11620        assert_eq!(
11621            r,
11622            ref_out.as_slice(),
11623            "pipelined Q6K differs from reference: got {r:?}, want {ref_out:?}"
11624        );
11625    }
11626
11627    /// E2E: `QMatMul` through the pipelined executor for the formats added with the float route
11628    /// (Q3_K, Q5_K, IQ4_NL, IQ4_XS, IQ3_S; board 307: dequantized tile by tile, multiplied in
11629    /// float). The weights are the type's own blocks from random bytes (a small finite `d`), the
11630    /// reference is `fuel_quantized::matmul`, and the dispatch arm must be the one for that type:
11631    /// a wrong `quant_type` arm decodes the same bytes differently and is far from the reference.
11632    fn qmatmul_e2e_random_blocks<T: fuel_quantized::GgmlType>(quant_type: fuel_graph::QuantType) {
11633        let (m, n, k) = (3, 5, 512);
11634        let size = std::mem::size_of::<T>();
11635        let count = n * k / T::BLCK_SIZE;
11636        let mut seed = 0x9E37_79B9_u32;
11637        let mut w_bytes: Vec<u8> = (0..count * size)
11638            .map(|_| {
11639                seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
11640                (seed >> 24) as u8
11641            })
11642            .collect();
11643        let d = half::f16::from_f32(0.02).to_le_bytes();
11644        for b in 0..count {
11645            w_bytes[b * size..b * size + 2].copy_from_slice(&d);
11646        }
11647        let mut w_blocks = vec![T::zeros(); count];
11648        bytemuck::cast_slice_mut::<T, u8>(&mut w_blocks).copy_from_slice(&w_bytes);
11649        let act_vec: Vec<f32> = (0..m * k).map(|x| ((x % 17) as f32 - 8.0) / 8.0).collect();
11650        let mut ref_out = vec![0.0_f32; m * n];
11651        fuel_quantized::matmul::<T>((m, k, n), &act_vec, &w_blocks, &mut ref_out).expect("ref");
11652
11653        let w_storage = fuel_memory::Storage::new(
11654            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_bytes(
11655                &w_bytes,
11656            )),
11657            DType::U32,
11658        );
11659        let graph = Arc::new(RwLock::new(Graph::new()));
11660        let (act_id, w_id, mm_id) = {
11661            let mut g = graph.write().unwrap();
11662            let act = g.push(Node {
11663                op: Op::Const,
11664                inputs: vec![],
11665                shape: Shape::from_dims(&[m, k]),
11666                dtype: DType::F32,
11667            });
11668            let w = g.push(Node {
11669                op: Op::Const,
11670                inputs: vec![],
11671                shape: Shape::from_dims(&[w_bytes.len() / 4]),
11672                dtype: DType::U32,
11673            });
11674            let mm = g.push(Node {
11675                op: Op::Fused(
11676                    fuel_graph::registry::FusedOps::QMATMUL,
11677                    fuel_graph::registry::FusedOpParams::QMatMul { quant_type, k, n },
11678                ),
11679                inputs: vec![act, w],
11680                shape: Shape::from_dims(&[m, n]),
11681                dtype: DType::F32,
11682            });
11683            g.set_target_backend(mm, BackendId::Cpu);
11684            (act, w, mm)
11685        };
11686        let mut inputs = StorageCache::new();
11687        inputs.insert(
11688            act_id,
11689            Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&act_vec))),
11690        );
11691        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
11692        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11693        let guard = result_arc.read().unwrap();
11694        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11695            panic!("expected Cpu storage");
11696        };
11697        let r: &[f32] = c.as_slice().unwrap();
11698        let scale = ref_out.iter().fold(1e-6_f32, |a, v| a.max(v.abs()));
11699        let worst = r
11700            .iter()
11701            .zip(&ref_out)
11702            .fold(0.0_f32, |a, (x, y)| a.max((x - y).abs()));
11703        assert!(
11704            worst <= 1e-5 * scale,
11705            "{quant_type:?}: pipelined differs from the reference by {worst} (scale {scale})"
11706        );
11707        assert!(
11708            scale > 1e-3,
11709            "{quant_type:?}: the product is all zeros, the test is vacuous"
11710        );
11711    }
11712
11713    #[test]
11714    fn pipelined_realize_qmatmul_float_route_formats_against_reference() {
11715        use fuel_graph::QuantType;
11716        use fuel_quantized::iq_grid_types::BlockIq3S;
11717        use fuel_quantized::iq4::{BlockIq4Nl, BlockIq4Xs};
11718        use fuel_quantized::{BlockQ3K, BlockQ5K};
11719        qmatmul_e2e_random_blocks::<BlockQ3K>(QuantType::Q3K);
11720        qmatmul_e2e_random_blocks::<BlockQ5K>(QuantType::Q5K);
11721        qmatmul_e2e_random_blocks::<BlockIq4Nl>(QuantType::Iq4Nl);
11722        qmatmul_e2e_random_blocks::<BlockIq4Xs>(QuantType::Iq4Xs);
11723        qmatmul_e2e_random_blocks::<BlockIq3S>(QuantType::Iq3S);
11724    }
11725
11726    /// E2E: BF16 RmsNormLastDim through the pipelined executor.
11727    /// Verifies that capability-driven dispatch routes the
11728    /// half-float norm op to the bf16-specific kernel (which
11729    /// accumulates in f32 internally).
11730    #[test]
11731    fn pipelined_realize_rms_norm_bf16() {
11732        let v: Vec<half::bf16> = [3.0_f32, 4.0]
11733            .iter()
11734            .map(|&x| half::bf16::from_f32(x))
11735            .collect();
11736        let storage = fuel_memory::from_slice_cpu(&v);
11737        let graph = Arc::new(RwLock::new(Graph::new()));
11738        let (in_id, op_id) = {
11739            let mut g = graph.write().unwrap();
11740            let in_id = g.push(Node {
11741                op: Op::Const,
11742                inputs: vec![],
11743                shape: Shape::from_dims(&[1, 2]),
11744                dtype: DType::BF16,
11745            });
11746            let op_id = g.push(Node {
11747                op: Op::Fused(
11748                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
11749                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
11750                ),
11751                inputs: vec![in_id],
11752                shape: Shape::from_dims(&[1, 2]),
11753                dtype: DType::BF16,
11754            });
11755            g.set_target_backend(op_id, BackendId::Cpu);
11756            (in_id, op_id)
11757        };
11758        let mut inputs = StorageCache::new();
11759        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11760        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11761        let guard = result_arc.read().unwrap();
11762        assert_eq!(guard.dtype, DType::BF16);
11763        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11764            panic!("expected Cpu storage");
11765        };
11766        let r: &[half::bf16] = c.as_slice().unwrap();
11767        let rms = (12.5_f32).sqrt();
11768        // bf16's ~3-digit mantissa absorbs the divisor; allow ~5%.
11769        assert!((r[0].to_f32() - 3.0 / rms).abs() < 0.05);
11770        assert!((r[1].to_f32() - 4.0 / rms).abs() < 0.05);
11771    }
11772
11773    /// E2E: BF16 matmul through the pipelined executor — proves
11774    /// the LLM forward-pass blocker (every transformer layer
11775    /// is dominated by matmul). Identity matmul on bf16 round-
11776    /// trips small integers exactly.
11777    #[test]
11778    fn pipelined_realize_matmul_bf16_identity() {
11779        let lhs_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
11780            .iter()
11781            .map(|&x| half::bf16::from_f32(x))
11782            .collect();
11783        let rhs_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
11784            .iter()
11785            .map(|&x| half::bf16::from_f32(x))
11786            .collect();
11787        let lhs = fuel_memory::from_slice_cpu(&lhs_v);
11788        let rhs = fuel_memory::from_slice_cpu(&rhs_v);
11789        let graph = Arc::new(RwLock::new(Graph::new()));
11790        let (l_id, r_id, mm_id) = {
11791            let mut g = graph.write().unwrap();
11792            let l = g.push(Node {
11793                op: Op::Const,
11794                inputs: vec![],
11795                shape: Shape::from_dims(&[2, 2]),
11796                dtype: DType::BF16,
11797            });
11798            let r = g.push(Node {
11799                op: Op::Const,
11800                inputs: vec![],
11801                shape: Shape::from_dims(&[2, 2]),
11802                dtype: DType::BF16,
11803            });
11804            let mm = g.push(Node {
11805                op: Op::MatMul,
11806                inputs: vec![l, r],
11807                shape: Shape::from_dims(&[2, 2]),
11808                dtype: DType::BF16,
11809            });
11810            g.set_target_backend(mm, BackendId::Cpu);
11811            (l, r, mm)
11812        };
11813        let mut inputs = StorageCache::new();
11814        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11815        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11816        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11817        let guard = result_arc.read().unwrap();
11818        assert_eq!(guard.dtype, DType::BF16);
11819        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11820            panic!("expected Cpu storage");
11821        };
11822        let r: &[half::bf16] = c.as_slice().unwrap();
11823        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11824        assert_eq!(result_f32, vec![1.0, 2.0, 3.0, 4.0]);
11825    }
11826
11827    /// E2E (ROADMAP row 34): a mixed `[F32, W, F32]` matmul (f32 activation, half weight) runs on
11828    /// the CPU through the NATIVE kernel, with the weight left half-width: the output is f32 and
11829    /// equals the f64 matmul over the widened weights to f32 accumulation error. The weight is
11830    /// rounded to its stored half type first.
11831    fn mixed_cpu_matmul_matches_f64(weight_dtype: DType) {
11832        let (m, n, k) = (3_usize, 5_usize, 7_usize);
11833        let a: Vec<f32> = (0..m * k)
11834            .map(|i| ((i * 37 % 19) as f32 - 9.0) / 8.0)
11835            .collect();
11836        let w_f32: Vec<f32> = (0..k * n)
11837            .map(|i| ((i * 53 % 23) as f32 - 11.0) / 10.0)
11838            .collect();
11839        let (w_storage, widened): (_, Vec<f32>) = if weight_dtype == DType::BF16 {
11840            let h: Vec<half::bf16> = w_f32.iter().map(|&x| half::bf16::from_f32(x)).collect();
11841            let wide = h.iter().map(|x| x.to_f32()).collect();
11842            (fuel_memory::from_slice_cpu(&h), wide)
11843        } else {
11844            let h: Vec<half::f16> = w_f32.iter().map(|&x| half::f16::from_f32(x)).collect();
11845            let wide = h.iter().map(|x| x.to_f32()).collect();
11846            (fuel_memory::from_slice_cpu(&h), wide)
11847        };
11848        let graph = Arc::new(RwLock::new(Graph::new()));
11849        let (l_id, r_id, mm_id) = {
11850            let mut g = graph.write().unwrap();
11851            let l = g.push(Node {
11852                op: Op::Const,
11853                inputs: vec![],
11854                shape: Shape::from_dims(&[m, k]),
11855                dtype: DType::F32,
11856            });
11857            let r = g.push(Node {
11858                op: Op::Const,
11859                inputs: vec![],
11860                shape: Shape::from_dims(&[k, n]),
11861                dtype: weight_dtype,
11862            });
11863            let mm = g.push(Node {
11864                op: Op::MatMul,
11865                inputs: vec![l, r],
11866                shape: Shape::from_dims(&[m, n]),
11867                dtype: DType::F32,
11868            });
11869            g.set_target_backend(mm, BackendId::Cpu);
11870            (l, r, mm)
11871        };
11872        let mut inputs = StorageCache::new();
11873        inputs.insert(l_id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&a))));
11874        inputs.insert(r_id, Arc::new(RwLock::new(w_storage)));
11875        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
11876        let guard = result_arc.read().unwrap();
11877        assert_eq!(guard.dtype, DType::F32);
11878        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11879            panic!("expected Cpu storage");
11880        };
11881        let got: &[f32] = c.as_slice().unwrap();
11882        for i in 0..m {
11883            for j in 0..n {
11884                let want: f64 = (0..k)
11885                    .map(|kk| a[i * k + kk] as f64 * widened[kk * n + j] as f64)
11886                    .sum();
11887                let err = (got[i * n + j] as f64 - want).abs();
11888                assert!(
11889                    err < 1e-5,
11890                    "{weight_dtype:?} [{i},{j}]: got {}, want {want}",
11891                    got[i * n + j]
11892                );
11893            }
11894        }
11895    }
11896
11897    #[test]
11898    fn pipelined_realize_mixed_f32_bf16_matmul_is_native_on_cpu() {
11899        mixed_cpu_matmul_matches_f64(DType::BF16);
11900    }
11901
11902    #[test]
11903    fn pipelined_realize_mixed_f32_f16_matmul_is_native_on_cpu() {
11904        mixed_cpu_matmul_matches_f64(DType::F16);
11905    }
11906
11907    /// E2E: F16 sum-reduce — verifies bf16/f16 reduction dispatch
11908    /// works through the executor.
11909    #[test]
11910    fn pipelined_realize_sum_dim_f16() {
11911        let v: Vec<half::f16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
11912            .iter()
11913            .map(|&x| half::f16::from_f32(x))
11914            .collect();
11915        let storage = fuel_memory::from_slice_cpu(&v);
11916        let graph = Arc::new(RwLock::new(Graph::new()));
11917        let (in_id, sum_id) = {
11918            let mut g = graph.write().unwrap();
11919            let in_id = g.push(Node {
11920                op: Op::Const,
11921                inputs: vec![],
11922                shape: Shape::from_dims(&[2, 3]),
11923                dtype: DType::F16,
11924            });
11925            let sum_id = g.push(Node {
11926                op: Op::SumDim(1),
11927                inputs: vec![in_id],
11928                shape: Shape::from_dims(&[2]),
11929                dtype: DType::F16,
11930            });
11931            g.set_target_backend(sum_id, BackendId::Cpu);
11932            (in_id, sum_id)
11933        };
11934        let mut inputs = StorageCache::new();
11935        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
11936        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
11937        let guard = result_arc.read().unwrap();
11938        assert_eq!(guard.dtype, DType::F16);
11939        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11940            panic!("expected Cpu storage");
11941        };
11942        let r: &[half::f16] = c.as_slice().unwrap();
11943        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11944        assert_eq!(result_f32, vec![6.0, 15.0]);
11945    }
11946
11947    /// E2E: BF16 elementwise add through the pipelined executor.
11948    #[test]
11949    fn pipelined_realize_add_bf16() {
11950        let lhs_vec: Vec<half::bf16> = [1.0_f32, 2.0, 3.0]
11951            .iter()
11952            .map(|&x| half::bf16::from_f32(x))
11953            .collect();
11954        let rhs_vec: Vec<half::bf16> = [10.0_f32, 20.0, 30.0]
11955            .iter()
11956            .map(|&x| half::bf16::from_f32(x))
11957            .collect();
11958        let lhs = fuel_memory::from_slice_cpu(&lhs_vec);
11959        let rhs = fuel_memory::from_slice_cpu(&rhs_vec);
11960        let graph = Arc::new(RwLock::new(Graph::new()));
11961        let (l_id, r_id, op_id) = {
11962            let mut g = graph.write().unwrap();
11963            let l = g.push(Node {
11964                op: Op::Const,
11965                inputs: vec![],
11966                shape: Shape::from_dims(&[3]),
11967                dtype: DType::BF16,
11968            });
11969            let r = g.push(Node {
11970                op: Op::Const,
11971                inputs: vec![],
11972                shape: Shape::from_dims(&[3]),
11973                dtype: DType::BF16,
11974            });
11975            let op = g.push(Node {
11976                op: Op::Add,
11977                inputs: vec![l, r],
11978                shape: Shape::from_dims(&[3]),
11979                dtype: DType::BF16,
11980            });
11981            g.set_target_backend(op, BackendId::Cpu);
11982            (l, r, op)
11983        };
11984        let mut inputs = StorageCache::new();
11985        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
11986        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
11987        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
11988        let guard = result_arc.read().unwrap();
11989        assert_eq!(guard.dtype, DType::BF16);
11990        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
11991            panic!("expected Cpu storage");
11992        };
11993        let r: &[half::bf16] = c.as_slice().unwrap();
11994        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
11995        assert_eq!(result_f32, vec![11.0, 22.0, 33.0]);
11996    }
11997
11998    /// E2E: F16 unary chain — Const + Sqr + Sqrt — verifies F16
11999    /// dispatch works and the via-f32 round-trip kernels behave
12000    /// correctly through the executor.
12001    #[test]
12002    fn pipelined_realize_sqr_then_sqrt_f16() {
12003        let v: Vec<half::f16> = [1.0_f32, 4.0, 9.0]
12004            .iter()
12005            .map(|&x| half::f16::from_f32(x))
12006            .collect();
12007        let storage = fuel_memory::from_slice_cpu(&v);
12008        let graph = Arc::new(RwLock::new(Graph::new()));
12009        let (in_id, sqrt_id) = {
12010            let mut g = graph.write().unwrap();
12011            let in_id = g.push(Node {
12012                op: Op::Const,
12013                inputs: vec![],
12014                shape: Shape::from_dims(&[3]),
12015                dtype: DType::F16,
12016            });
12017            let sqr_id = g.push(Node {
12018                op: Op::Sqr,
12019                inputs: vec![in_id],
12020                shape: Shape::from_dims(&[3]),
12021                dtype: DType::F16,
12022            });
12023            let sqrt_id = g.push(Node {
12024                op: Op::Sqrt,
12025                inputs: vec![sqr_id],
12026                shape: Shape::from_dims(&[3]),
12027                dtype: DType::F16,
12028            });
12029            g.set_target_backend(sqr_id, BackendId::Cpu);
12030            g.set_target_backend(sqrt_id, BackendId::Cpu);
12031            (in_id, sqrt_id)
12032        };
12033        let mut inputs = StorageCache::new();
12034        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12035        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
12036        let guard = result_arc.read().unwrap();
12037        assert_eq!(guard.dtype, DType::F16);
12038        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12039            panic!("expected Cpu storage");
12040        };
12041        let r: &[half::f16] = c.as_slice().unwrap();
12042        let result_f32: Vec<f32> = r.iter().map(|x| x.to_f32()).collect();
12043        // f16 has ~3 decimal digits; sqrt(sqr(x)) = |x| within rounding.
12044        for (got, want) in result_f32.iter().zip(&[1.0_f32, 4.0, 9.0]) {
12045            assert!((got - want).abs() < 0.05, "got {got}, want {want}");
12046        }
12047    }
12048
12049    /// E2E: F64 sum-reduce along one dim through the pipelined
12050    /// executor.
12051    #[test]
12052    fn pipelined_realize_sum_dim_f64() {
12053        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
12054        let graph = Arc::new(RwLock::new(Graph::new()));
12055        let (in_id, sum_id) = {
12056            let mut g = graph.write().unwrap();
12057            let in_id = g.push(Node {
12058                op: Op::Const,
12059                inputs: vec![],
12060                shape: Shape::from_dims(&[2, 3]),
12061                dtype: DType::F64,
12062            });
12063            let sum_id = g.push(Node {
12064                op: Op::SumDim(1),
12065                inputs: vec![in_id],
12066                shape: Shape::from_dims(&[2]),
12067                dtype: DType::F64,
12068            });
12069            g.set_target_backend(sum_id, BackendId::Cpu);
12070            (in_id, sum_id)
12071        };
12072        let mut inputs = StorageCache::new();
12073        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12074        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
12075        let guard = result_arc.read().unwrap();
12076        assert_eq!(guard.dtype, DType::F64);
12077        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12078            panic!("expected Cpu storage");
12079        };
12080        assert_eq!(c.as_slice::<f64>().unwrap(), &[6.0_f64, 15.0]);
12081    }
12082
12083    /// E2E: F64 matmul through the pipelined executor.
12084    #[test]
12085    fn pipelined_realize_matmul_2x3_times_3x2_f64() {
12086        let lhs = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
12087        let rhs = fuel_memory::from_slice_cpu(&[7.0_f64, 8.0, 9.0, 10.0, 11.0, 12.0]);
12088        let graph = Arc::new(RwLock::new(Graph::new()));
12089        let (l_id, r_id, mm_id) = {
12090            let mut g = graph.write().unwrap();
12091            let l = g.push(Node {
12092                op: Op::Const,
12093                inputs: vec![],
12094                shape: Shape::from_dims(&[2, 3]),
12095                dtype: DType::F64,
12096            });
12097            let r = g.push(Node {
12098                op: Op::Const,
12099                inputs: vec![],
12100                shape: Shape::from_dims(&[3, 2]),
12101                dtype: DType::F64,
12102            });
12103            let mm = g.push(Node {
12104                op: Op::MatMul,
12105                inputs: vec![l, r],
12106                shape: Shape::from_dims(&[2, 2]),
12107                dtype: DType::F64,
12108            });
12109            g.set_target_backend(mm, BackendId::Cpu);
12110            (l, r, mm)
12111        };
12112        let mut inputs = StorageCache::new();
12113        inputs.insert(l_id, Arc::new(RwLock::new(lhs)));
12114        inputs.insert(r_id, Arc::new(RwLock::new(rhs)));
12115        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
12116        let guard = result_arc.read().unwrap();
12117        assert_eq!(guard.dtype, DType::F64);
12118        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12119            panic!("expected Cpu storage");
12120        };
12121        assert_eq!(
12122            c.as_slice::<f64>().unwrap(),
12123            &[58.0_f64, 64.0, 139.0, 154.0]
12124        );
12125    }
12126
12127    /// E2E: F64 unary chain — Const + Sqr + Sqrt — verifies that
12128    /// the kernel-binding lookup picks the f64 entries when the
12129    /// graph nodes carry DType::F64.
12130    #[test]
12131    fn pipelined_realize_sqr_then_sqrt_f64() {
12132        let storage = fuel_memory::from_slice_cpu(&[1.0_f64, 4.0, 9.0]);
12133        let graph = Arc::new(RwLock::new(Graph::new()));
12134        let (in_id, sqrt_id) = {
12135            let mut g = graph.write().unwrap();
12136            let in_id = g.push(Node {
12137                op: Op::Const,
12138                inputs: vec![],
12139                shape: Shape::from_dims(&[3]),
12140                dtype: DType::F64,
12141            });
12142            let sqr_id = g.push(Node {
12143                op: Op::Sqr,
12144                inputs: vec![in_id],
12145                shape: Shape::from_dims(&[3]),
12146                dtype: DType::F64,
12147            });
12148            let sqrt_id = g.push(Node {
12149                op: Op::Sqrt,
12150                inputs: vec![sqr_id],
12151                shape: Shape::from_dims(&[3]),
12152                dtype: DType::F64,
12153            });
12154            g.set_target_backend(sqr_id, BackendId::Cpu);
12155            g.set_target_backend(sqrt_id, BackendId::Cpu);
12156            (in_id, sqrt_id)
12157        };
12158        let mut inputs = StorageCache::new();
12159        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12160        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
12161        let guard = result_arc.read().unwrap();
12162        assert_eq!(guard.dtype, DType::F64);
12163        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12164            panic!("expected Cpu storage");
12165        };
12166        assert_eq!(c.as_slice::<f64>().unwrap(), &[1.0_f64, 4.0, 9.0]);
12167    }
12168
12169    /// E2E: ArgMaxDim — produces U32 output indices.
12170    #[test]
12171    fn pipelined_realize_argmax_dim() {
12172        // input [2, 3] = [[1, 5, 2], [9, 0, 4]]
12173        // argmax dim=1 → [1, 0]
12174        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, 2.0, 9.0, 0.0, 4.0]);
12175        let graph = Arc::new(RwLock::new(Graph::new()));
12176        let (in_id, op_id) = {
12177            let mut g = graph.write().unwrap();
12178            let in_id = g.push(Node {
12179                op: Op::Const,
12180                inputs: vec![],
12181                shape: Shape::from_dims(&[2, 3]),
12182                dtype: DType::F32,
12183            });
12184            let op_id = g.push(Node {
12185                op: Op::ArgMaxDim(1),
12186                inputs: vec![in_id],
12187                shape: Shape::from_dims(&[2]),
12188                dtype: DType::U32,
12189            });
12190            g.set_target_backend(op_id, BackendId::Cpu);
12191            (in_id, op_id)
12192        };
12193        let mut inputs = StorageCache::new();
12194        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12195        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12196        let guard = result_arc.read().unwrap();
12197        assert_eq!(guard.dtype, DType::U32);
12198        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12199            panic!("expected Cpu storage");
12200        };
12201        assert_eq!(c.as_slice::<u32>().unwrap(), &[1u32, 0]);
12202    }
12203
12204    /// E2E: IndexAdd along outer dim — accumulate updates into a
12205    /// rank-1 base tensor at indexed positions.
12206    #[test]
12207    fn pipelined_realize_index_add_simple() {
12208        let base = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
12209        let indices = fuel_memory::from_slice_cpu(&[0u32, 0]);
12210        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12211        let graph = Arc::new(RwLock::new(Graph::new()));
12212        let (b_id, i_id, s_id, op_id) = {
12213            let mut g = graph.write().unwrap();
12214            let b = g.push(Node {
12215                op: Op::Const,
12216                inputs: vec![],
12217                shape: Shape::from_dims(&[3]),
12218                dtype: DType::F32,
12219            });
12220            let i = g.push(Node {
12221                op: Op::Const,
12222                inputs: vec![],
12223                shape: Shape::from_dims(&[2]),
12224                dtype: DType::U32,
12225            });
12226            let s = g.push(Node {
12227                op: Op::Const,
12228                inputs: vec![],
12229                shape: Shape::from_dims(&[2]),
12230                dtype: DType::F32,
12231            });
12232            let op = g.push(Node {
12233                op: Op::IndexAdd { dim: 0 },
12234                inputs: vec![b, i, s],
12235                shape: Shape::from_dims(&[3]),
12236                dtype: DType::F32,
12237            });
12238            g.set_target_backend(op, BackendId::Cpu);
12239            (b, i, s, op)
12240        };
12241        let mut inputs = StorageCache::new();
12242        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12243        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12244        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12245        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12246        let guard = result_arc.read().unwrap();
12247        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12248            panic!("expected Cpu storage");
12249        };
12250        // 10 + 1 + 2 = 13; 20 untouched; 30 untouched.
12251        assert_eq!(c.as_slice::<f32>().unwrap(), &[13.0, 20.0, 30.0]);
12252    }
12253
12254    /// E2E: ScatterAdd along outer dim — same-rank indices, base
12255    /// starts as zeros, src adds values at scatter positions.
12256    #[test]
12257    fn pipelined_realize_scatter_add_outer_dim() {
12258        // base [3, 2] = zeros; indices [2, 2] = [[0, 1], [2, 0]];
12259        // src [2, 2] = [[1, 2], [3, 4]]; dim=0
12260        // → out = [[1, 4], [0, 2], [3, 0]]
12261        let base = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
12262        let indices = fuel_memory::from_slice_cpu(&[0u32, 1, 2, 0]);
12263        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12264        let graph = Arc::new(RwLock::new(Graph::new()));
12265        let (b_id, i_id, s_id, op_id) = {
12266            let mut g = graph.write().unwrap();
12267            let b = g.push(Node {
12268                op: Op::Const,
12269                inputs: vec![],
12270                shape: Shape::from_dims(&[3, 2]),
12271                dtype: DType::F32,
12272            });
12273            let i = g.push(Node {
12274                op: Op::Const,
12275                inputs: vec![],
12276                shape: Shape::from_dims(&[2, 2]),
12277                dtype: DType::U32,
12278            });
12279            let s = g.push(Node {
12280                op: Op::Const,
12281                inputs: vec![],
12282                shape: Shape::from_dims(&[2, 2]),
12283                dtype: DType::F32,
12284            });
12285            let op = g.push(Node {
12286                op: Op::ScatterAdd { dim: 0 },
12287                inputs: vec![b, i, s],
12288                shape: Shape::from_dims(&[3, 2]),
12289                dtype: DType::F32,
12290            });
12291            g.set_target_backend(op, BackendId::Cpu);
12292            (b, i, s, op)
12293        };
12294        let mut inputs = StorageCache::new();
12295        inputs.insert(b_id, Arc::new(RwLock::new(base)));
12296        inputs.insert(i_id, Arc::new(RwLock::new(indices)));
12297        inputs.insert(s_id, Arc::new(RwLock::new(src)));
12298        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12299        let guard = result_arc.read().unwrap();
12300        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12301            panic!("expected Cpu storage");
12302        };
12303        assert_eq!(
12304            c.as_slice::<f32>().unwrap(),
12305            &[1.0, 4.0, 0.0, 2.0, 3.0, 0.0]
12306        );
12307    }
12308
12309    /// E2E: Rope through the pipelined executor. cos=0, sin=1
12310    /// rotates the head_dim halves with sign per the rotate_half
12311    /// convention.
12312    #[test]
12313    fn pipelined_realize_rope_pi_over_two() {
12314        // x [1, 1, 4] = [1, 2, 3, 4]. cos=[0,0,0,0], sin=[1,1,1,1].
12315        // Expected: [-3, -4, 1, 2].
12316        let x = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
12317        let cos = fuel_memory::from_slice_cpu(&[0.0_f32, 0.0, 0.0, 0.0]);
12318        let sin = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12319        let graph = Arc::new(RwLock::new(Graph::new()));
12320        let (x_id, cos_id, sin_id, r_id) = {
12321            let mut g = graph.write().unwrap();
12322            let x = g.push(Node {
12323                op: Op::Const,
12324                inputs: vec![],
12325                shape: Shape::from_dims(&[1, 1, 4]),
12326                dtype: DType::F32,
12327            });
12328            let c = g.push(Node {
12329                op: Op::Const,
12330                inputs: vec![],
12331                shape: Shape::from_dims(&[1, 4]),
12332                dtype: DType::F32,
12333            });
12334            let s = g.push(Node {
12335                op: Op::Const,
12336                inputs: vec![],
12337                shape: Shape::from_dims(&[1, 4]),
12338                dtype: DType::F32,
12339            });
12340            let r = g.push(Node {
12341                op: Op::Fused(
12342                    fuel_graph::registry::FusedOps::ROPE,
12343                    fuel_graph::registry::FusedOpParams::Rope,
12344                ),
12345                inputs: vec![x, c, s],
12346                shape: Shape::from_dims(&[1, 1, 4]),
12347                dtype: DType::F32,
12348            });
12349            g.set_target_backend(r, BackendId::Cpu);
12350            (x, c, s, r)
12351        };
12352        let mut inputs = StorageCache::new();
12353        inputs.insert(x_id, Arc::new(RwLock::new(x)));
12354        inputs.insert(cos_id, Arc::new(RwLock::new(cos)));
12355        inputs.insert(sin_id, Arc::new(RwLock::new(sin)));
12356        let (result_arc, _) = PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
12357        let guard = result_arc.read().unwrap();
12358        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12359            panic!("expected Cpu storage");
12360        };
12361        assert_eq!(c.as_slice::<f32>().unwrap(), &[-3.0, -4.0, 1.0, 2.0]);
12362    }
12363
12364    /// E2E: Gather along inner dim. Source [2, 4]; indices [2, 3];
12365    /// output [2, 3] = picks from each row by per-row indices.
12366    #[test]
12367    fn pipelined_realize_gather_inner_dim() {
12368        let source =
12369            fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0]);
12370        let indices = fuel_memory::from_slice_cpu(&[0u32, 2, 1, 3, 0, 0]);
12371        let graph = Arc::new(RwLock::new(Graph::new()));
12372        let (src_id, idx_id, g_id) = {
12373            let mut g = graph.write().unwrap();
12374            let s = g.push(Node {
12375                op: Op::Const,
12376                inputs: vec![],
12377                shape: Shape::from_dims(&[2, 4]),
12378                dtype: DType::F32,
12379            });
12380            let i = g.push(Node {
12381                op: Op::Const,
12382                inputs: vec![],
12383                shape: Shape::from_dims(&[2, 3]),
12384                dtype: DType::U32,
12385            });
12386            let g_id = g.push(Node {
12387                op: Op::Gather { dim: 1 },
12388                inputs: vec![s, i],
12389                shape: Shape::from_dims(&[2, 3]),
12390                dtype: DType::F32,
12391            });
12392            g.set_target_backend(g_id, BackendId::Cpu);
12393            (s, i, g_id)
12394        };
12395        let mut inputs = StorageCache::new();
12396        inputs.insert(src_id, Arc::new(RwLock::new(source)));
12397        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12398        let (result_arc, _) = PipelinedExecutor::realize(graph, g_id, inputs).expect("realize");
12399        let guard = result_arc.read().unwrap();
12400        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12401            panic!("expected Cpu storage");
12402        };
12403        assert_eq!(
12404            c.as_slice::<f32>().unwrap(),
12405            &[10.0, 30.0, 20.0, 80.0, 50.0, 50.0]
12406        );
12407    }
12408
12409    /// E2E: IndexSelect — embedding-table lookup. Source is a
12410    /// `[vocab=4, d_model=3]` table; indices are token IDs;
12411    /// output is `[seq=3, d_model=3]` with the picked rows.
12412    #[test]
12413    fn pipelined_realize_index_select_embedding_lookup() {
12414        let table = fuel_memory::from_slice_cpu(&[
12415            10.0_f32, 11.0, 12.0, // row 0
12416            20.0, 21.0, 22.0, // row 1
12417            30.0, 31.0, 32.0, // row 2
12418            40.0, 41.0, 42.0, // row 3
12419        ]);
12420        let indices = fuel_memory::from_slice_cpu(&[2u32, 0, 2]);
12421        let graph = Arc::new(RwLock::new(Graph::new()));
12422        let (table_id, idx_id, sel_id) = {
12423            let mut g = graph.write().unwrap();
12424            let t = g.push(Node {
12425                op: Op::Const,
12426                inputs: vec![],
12427                shape: Shape::from_dims(&[4, 3]),
12428                dtype: DType::F32,
12429            });
12430            let i = g.push(Node {
12431                op: Op::Const,
12432                inputs: vec![],
12433                shape: Shape::from_dims(&[3]),
12434                dtype: DType::U32,
12435            });
12436            let s = g.push(Node {
12437                op: Op::IndexSelect { dim: 0 },
12438                inputs: vec![t, i],
12439                shape: Shape::from_dims(&[3, 3]),
12440                dtype: DType::F32,
12441            });
12442            g.set_target_backend(s, BackendId::Cpu);
12443            (t, i, s)
12444        };
12445        let mut inputs = StorageCache::new();
12446        inputs.insert(table_id, Arc::new(RwLock::new(table)));
12447        inputs.insert(idx_id, Arc::new(RwLock::new(indices)));
12448        let (result_arc, result_layout) =
12449            PipelinedExecutor::realize(graph, sel_id, inputs).expect("realize");
12450        assert_eq!(result_layout.shape().dims(), &[3, 3]);
12451        let guard = result_arc.read().unwrap();
12452        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12453            panic!("expected Cpu storage");
12454        };
12455        assert_eq!(
12456            c.as_slice::<f32>().unwrap(),
12457            &[30.0, 31.0, 32.0, 10.0, 11.0, 12.0, 30.0, 31.0, 32.0]
12458        );
12459    }
12460
12461    /// E2E: RmsNormLastDim on a 2-row input. Each row's output
12462    /// has unit RMS up to the eps-induced bias.
12463    #[test]
12464    fn pipelined_realize_rms_norm_last_dim() {
12465        let storage = fuel_memory::from_slice_cpu(&[
12466            3.0_f32, 4.0, // row 0: rms = sqrt(12.5)
12467            6.0, 8.0, // row 1: rms = sqrt(50.0) = 5*sqrt(2)
12468        ]);
12469        let graph = Arc::new(RwLock::new(Graph::new()));
12470        let (in_id, op_id) = {
12471            let mut g = graph.write().unwrap();
12472            let in_id = g.push(Node {
12473                op: Op::Const,
12474                inputs: vec![],
12475                shape: Shape::from_dims(&[2, 2]),
12476                dtype: DType::F32,
12477            });
12478            let op_id = g.push(Node {
12479                op: Op::Fused(
12480                    fuel_graph::registry::FusedOps::RMS_NORM_LAST_DIM,
12481                    fuel_graph::registry::FusedOpParams::RmsNormLastDim { eps: 0.0 },
12482                ),
12483                inputs: vec![in_id],
12484                shape: Shape::from_dims(&[2, 2]),
12485                dtype: DType::F32,
12486            });
12487            g.set_target_backend(op_id, BackendId::Cpu);
12488            (in_id, op_id)
12489        };
12490        let mut inputs = StorageCache::new();
12491        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12492        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12493        let guard = result_arc.read().unwrap();
12494        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12495            panic!("expected Cpu storage");
12496        };
12497        let result: &[f32] = c.as_slice().unwrap();
12498        // Row 0: rms = sqrt(12.5). Output = [3, 4] / sqrt(12.5).
12499        let rms0 = (12.5_f32).sqrt();
12500        assert!((result[0] - 3.0 / rms0).abs() < 1e-6);
12501        assert!((result[1] - 4.0 / rms0).abs() < 1e-6);
12502        // Row 1: rms = sqrt(50). Output = [6, 8] / sqrt(50).
12503        let rms1 = (50.0_f32).sqrt();
12504        assert!((result[2] - 6.0 / rms1).abs() < 1e-6);
12505        assert!((result[3] - 8.0 / rms1).abs() < 1e-6);
12506    }
12507
12508    /// E2E: LayerNormLastDim — each row's output has zero mean and
12509    /// unit variance.
12510    #[test]
12511    fn pipelined_realize_layer_norm_last_dim() {
12512        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 10.0, 20.0, 30.0]);
12513        let graph = Arc::new(RwLock::new(Graph::new()));
12514        let (in_id, op_id) = {
12515            let mut g = graph.write().unwrap();
12516            let in_id = g.push(Node {
12517                op: Op::Const,
12518                inputs: vec![],
12519                shape: Shape::from_dims(&[2, 3]),
12520                dtype: DType::F32,
12521            });
12522            let op_id = g.push(Node {
12523                op: Op::Fused(
12524                    fuel_graph::registry::FusedOps::LAYER_NORM_LAST_DIM,
12525                    fuel_graph::registry::FusedOpParams::LayerNormLastDim { eps: 0.0 },
12526                ),
12527                inputs: vec![in_id],
12528                shape: Shape::from_dims(&[2, 3]),
12529                dtype: DType::F32,
12530            });
12531            g.set_target_backend(op_id, BackendId::Cpu);
12532            (in_id, op_id)
12533        };
12534        let mut inputs = StorageCache::new();
12535        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12536        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12537        let guard = result_arc.read().unwrap();
12538        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12539            panic!("expected Cpu storage");
12540        };
12541        let result: &[f32] = c.as_slice().unwrap();
12542        // Each row should have mean ~0 and var ~1.
12543        for row in 0..2 {
12544            let off = row * 3;
12545            let sum: f32 = result[off..off + 3].iter().sum();
12546            let mean = sum / 3.0;
12547            assert!(mean.abs() < 1e-6, "row {row} mean should be 0, got {mean}");
12548            let var: f32 = result[off..off + 3]
12549                .iter()
12550                .map(|v| (v - mean).powi(2))
12551                .sum::<f32>()
12552                / 3.0;
12553            assert!(
12554                (var - 1.0).abs() < 1e-6,
12555                "row {row} var should be 1, got {var}"
12556            );
12557        }
12558    }
12559
12560    /// E2E: SoftmaxLastDim on a 2-row input. Each row should sum
12561    /// to 1; uniform row gives uniform output.
12562    #[test]
12563    fn pipelined_realize_softmax_last_dim() {
12564        // Row 0: [1, 1, 1, 1] → uniform 0.25 each
12565        // Row 1: [0, 0, 0, 100] → effectively a one-hot at position 3
12566        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 100.0]);
12567        let graph = Arc::new(RwLock::new(Graph::new()));
12568        let (in_id, op_id) = {
12569            let mut g = graph.write().unwrap();
12570            let in_id = g.push(Node {
12571                op: Op::Const,
12572                inputs: vec![],
12573                shape: Shape::from_dims(&[2, 4]),
12574                dtype: DType::F32,
12575            });
12576            let op_id = g.push(Node {
12577                op: Op::Fused(
12578                    fuel_graph::registry::FusedOps::SOFTMAX_LAST_DIM,
12579                    fuel_graph::registry::FusedOpParams::SoftmaxLastDim,
12580                ),
12581                inputs: vec![in_id],
12582                shape: Shape::from_dims(&[2, 4]),
12583                dtype: DType::F32,
12584            });
12585            g.set_target_backend(op_id, BackendId::Cpu);
12586            (in_id, op_id)
12587        };
12588        let mut inputs = StorageCache::new();
12589        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12590        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12591        let guard = result_arc.read().unwrap();
12592        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12593            panic!("expected Cpu storage");
12594        };
12595        let result: &[f32] = c.as_slice().unwrap();
12596
12597        // Row 0: uniform 0.25
12598        for v in &result[..4] {
12599            assert!((v - 0.25).abs() < 1e-7);
12600        }
12601        // Row 1: positions 0..3 ≈ 0, position 4 (= last column) ≈ 1
12602        // (e^100 dominates).
12603        for v in &result[4..7] {
12604            assert!(
12605                *v < 1e-30,
12606                "row-1 leading positions should be near 0, got {v}"
12607            );
12608        }
12609        assert!(
12610            result[7] > 0.999,
12611            "row-1 last position should dominate, got {}",
12612            result[7]
12613        );
12614        // Each row sums to 1.
12615        let row0_sum: f32 = result[..4].iter().sum();
12616        let row1_sum: f32 = result[4..].iter().sum();
12617        assert!((row0_sum - 1.0).abs() < 1e-6);
12618        assert!((row1_sum - 1.0).abs() < 1e-6);
12619    }
12620
12621    /// E2E: Concat along inner dim — two [2, 3] tensors → [2, 6].
12622    #[test]
12623    fn pipelined_realize_concat_inner_dim() {
12624        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
12625        let b = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0, 9.0, 10.0, 11.0, 12.0]);
12626        let graph = Arc::new(RwLock::new(Graph::new()));
12627        let (a_id, b_id, c_id) = {
12628            let mut g = graph.write().unwrap();
12629            let a = g.push(Node {
12630                op: Op::Const,
12631                inputs: vec![],
12632                shape: Shape::from_dims(&[2, 3]),
12633                dtype: DType::F32,
12634            });
12635            let b = g.push(Node {
12636                op: Op::Const,
12637                inputs: vec![],
12638                shape: Shape::from_dims(&[2, 3]),
12639                dtype: DType::F32,
12640            });
12641            let c = g.push(Node {
12642                op: Op::Concat { dim: 1 },
12643                inputs: vec![a, b],
12644                shape: Shape::from_dims(&[2, 6]),
12645                dtype: DType::F32,
12646            });
12647            g.set_target_backend(c, BackendId::Cpu);
12648            (a, b, c)
12649        };
12650        let mut inputs = StorageCache::new();
12651        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12652        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12653        let (result_arc, result_layout) =
12654            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12655        assert_eq!(result_layout.shape().dims(), &[2, 6]);
12656        let guard = result_arc.read().unwrap();
12657        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12658            panic!("expected Cpu storage");
12659        };
12660        assert_eq!(
12661            c.as_slice::<f32>().unwrap(),
12662            &[
12663                1.0, 2.0, 3.0, 7.0, 8.0, 9.0, 4.0, 5.0, 6.0, 10.0, 11.0, 12.0
12664            ]
12665        );
12666    }
12667
12668    /// E2E: Concat with three inputs along outer dim — verifies
12669    /// variable-arity input handling through the executor.
12670    #[test]
12671    fn pipelined_realize_concat_three_inputs_outer() {
12672        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
12673        let b = fuel_memory::from_slice_cpu(&[3.0_f32, 4.0]);
12674        let c = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
12675        let graph = Arc::new(RwLock::new(Graph::new()));
12676        let (a_id, b_id, c_id, cat_id) = {
12677            let mut g = graph.write().unwrap();
12678            let a = g.push(Node {
12679                op: Op::Const,
12680                inputs: vec![],
12681                shape: Shape::from_dims(&[2]),
12682                dtype: DType::F32,
12683            });
12684            let b = g.push(Node {
12685                op: Op::Const,
12686                inputs: vec![],
12687                shape: Shape::from_dims(&[2]),
12688                dtype: DType::F32,
12689            });
12690            let c = g.push(Node {
12691                op: Op::Const,
12692                inputs: vec![],
12693                shape: Shape::from_dims(&[2]),
12694                dtype: DType::F32,
12695            });
12696            let cat = g.push(Node {
12697                op: Op::Concat { dim: 0 },
12698                inputs: vec![a, b, c],
12699                shape: Shape::from_dims(&[6]),
12700                dtype: DType::F32,
12701            });
12702            g.set_target_backend(cat, BackendId::Cpu);
12703            (a, b, c, cat)
12704        };
12705        let mut inputs = StorageCache::new();
12706        inputs.insert(a_id, Arc::new(RwLock::new(a)));
12707        inputs.insert(b_id, Arc::new(RwLock::new(b)));
12708        inputs.insert(c_id, Arc::new(RwLock::new(c)));
12709        let (result_arc, _) = PipelinedExecutor::realize(graph, cat_id, inputs).expect("realize");
12710        let guard = result_arc.read().unwrap();
12711        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12712            panic!("expected Cpu storage");
12713        };
12714        assert_eq!(
12715            c.as_slice::<f32>().unwrap(),
12716            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
12717        );
12718    }
12719
12720    /// E2E: AddScalar — graph emits Op::AddScalar; the executor
12721    /// maps it to OpKind::Affine with mul=1, add=c.
12722    #[test]
12723    fn pipelined_realize_add_scalar() {
12724        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
12725        let graph = Arc::new(RwLock::new(Graph::new()));
12726        let (in_id, op_id) = {
12727            let mut g = graph.write().unwrap();
12728            let in_id = g.push(Node {
12729                op: Op::Const,
12730                inputs: vec![],
12731                shape: Shape::from_dims(&[3]),
12732                dtype: DType::F32,
12733            });
12734            let op_id = g.push(Node {
12735                op: Op::AddScalar(10.0),
12736                inputs: vec![in_id],
12737                shape: Shape::from_dims(&[3]),
12738                dtype: DType::F32,
12739            });
12740            g.set_target_backend(op_id, BackendId::Cpu);
12741            (in_id, op_id)
12742        };
12743        let mut inputs = StorageCache::new();
12744        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12745        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12746        let guard = result_arc.read().unwrap();
12747        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12748            panic!("expected Cpu storage");
12749        };
12750        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 12.0, 13.0]);
12751    }
12752
12753    /// E2E: Clamp — clamp values to [-2, 2].
12754    #[test]
12755    fn pipelined_realize_clamp() {
12756        let storage = fuel_memory::from_slice_cpu(&[-5.0_f32, 0.5, 100.0]);
12757        let graph = Arc::new(RwLock::new(Graph::new()));
12758        let (in_id, op_id) = {
12759            let mut g = graph.write().unwrap();
12760            let in_id = g.push(Node {
12761                op: Op::Const,
12762                inputs: vec![],
12763                shape: Shape::from_dims(&[3]),
12764                dtype: DType::F32,
12765            });
12766            let op_id = g.push(Node {
12767                op: Op::Clamp {
12768                    min: -2.0,
12769                    max: 2.0,
12770                },
12771                inputs: vec![in_id],
12772                shape: Shape::from_dims(&[3]),
12773                dtype: DType::F32,
12774            });
12775            g.set_target_backend(op_id, BackendId::Cpu);
12776            (in_id, op_id)
12777        };
12778        let mut inputs = StorageCache::new();
12779        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
12780        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12781        let guard = result_arc.read().unwrap();
12782        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12783            panic!("expected Cpu storage");
12784        };
12785        assert_eq!(c.as_slice::<f32>().unwrap(), &[-2.0, 0.5, 2.0]);
12786    }
12787
12788    /// E2E: Maximum — elementwise tensor max.
12789    #[test]
12790    fn pipelined_realize_maximum_elementwise() {
12791        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 5.0, -3.0]);
12792        let rhs_storage = fuel_memory::from_slice_cpu(&[2.0_f32, 1.0, -1.0]);
12793        let graph = Arc::new(RwLock::new(Graph::new()));
12794        let (lhs_id, rhs_id, op_id) = {
12795            let mut g = graph.write().unwrap();
12796            let lhs = g.push(Node {
12797                op: Op::Const,
12798                inputs: vec![],
12799                shape: Shape::from_dims(&[3]),
12800                dtype: DType::F32,
12801            });
12802            let rhs = g.push(Node {
12803                op: Op::Const,
12804                inputs: vec![],
12805                shape: Shape::from_dims(&[3]),
12806                dtype: DType::F32,
12807            });
12808            let op = g.push(Node {
12809                op: Op::Maximum,
12810                inputs: vec![lhs, rhs],
12811                shape: Shape::from_dims(&[3]),
12812                dtype: DType::F32,
12813            });
12814            g.set_target_backend(op, BackendId::Cpu);
12815            (lhs, rhs, op)
12816        };
12817        let mut inputs = StorageCache::new();
12818        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
12819        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
12820        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
12821        let guard = result_arc.read().unwrap();
12822        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12823            panic!("expected Cpu storage");
12824        };
12825        assert_eq!(c.as_slice::<f32>().unwrap(), &[2.0, 5.0, -1.0]);
12826    }
12827
12828    /// E2E: Const + Const + Conv2D — the 2×2 sum-kernel test from
12829    /// byte_kernels driven through the pipelined executor.
12830    #[test]
12831    fn pipelined_realize_conv2d_2x2_sum_kernel() {
12832        // x [1, 1, 3, 3]: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
12833        // weight [1, 1, 2, 2]: all-ones
12834        // → out [1, 1, 2, 2]: [[12, 16], [24, 28]]
12835        let x_storage =
12836            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12837        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12838
12839        let graph = Arc::new(RwLock::new(Graph::new()));
12840        let (x_id, w_id, c_id) = {
12841            let mut g = graph.write().unwrap();
12842            let x = g.push(Node {
12843                op: Op::Const,
12844                inputs: vec![],
12845                shape: Shape::from_dims(&[1, 1, 3, 3]),
12846                dtype: DType::F32,
12847            });
12848            let w = g.push(Node {
12849                op: Op::Const,
12850                inputs: vec![],
12851                shape: Shape::from_dims(&[1, 1, 2, 2]),
12852                dtype: DType::F32,
12853            });
12854            let c = g.push(Node {
12855                op: Op::Fused(
12856                    fuel_graph::registry::FusedOps::CONV2D,
12857                    fuel_graph::registry::FusedOpParams::Conv2D {
12858                        stride: (1, 1),
12859                        padding: (0, 0),
12860                        groups: 1,
12861                    },
12862                ),
12863                inputs: vec![x, w],
12864                shape: Shape::from_dims(&[1, 1, 2, 2]),
12865                dtype: DType::F32,
12866            });
12867            g.set_target_backend(c, BackendId::Cpu);
12868            (x, w, c)
12869        };
12870        let mut inputs = StorageCache::new();
12871        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12872        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12873
12874        let (result_arc, result_layout) =
12875            PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12876        assert_eq!(result_layout.shape().dims(), &[1, 1, 2, 2]);
12877
12878        let guard = result_arc.read().unwrap();
12879        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12880            panic!("expected Cpu storage");
12881        };
12882        assert_eq!(c.as_slice::<f32>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12883    }
12884
12885    /// E2E: Conv2D with bias (3 inputs).
12886    #[test]
12887    fn pipelined_realize_conv2d_with_bias() {
12888        let x_storage =
12889            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12890        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
12891        let bias_storage = fuel_memory::from_slice_cpu(&[100.0_f32]);
12892
12893        let graph = Arc::new(RwLock::new(Graph::new()));
12894        let (x_id, w_id, b_id, c_id) = {
12895            let mut g = graph.write().unwrap();
12896            let x = g.push(Node {
12897                op: Op::Const,
12898                inputs: vec![],
12899                shape: Shape::from_dims(&[1, 1, 3, 3]),
12900                dtype: DType::F32,
12901            });
12902            let w = g.push(Node {
12903                op: Op::Const,
12904                inputs: vec![],
12905                shape: Shape::from_dims(&[1, 1, 2, 2]),
12906                dtype: DType::F32,
12907            });
12908            let b = g.push(Node {
12909                op: Op::Const,
12910                inputs: vec![],
12911                shape: Shape::from_dims(&[1]),
12912                dtype: DType::F32,
12913            });
12914            let c = g.push(Node {
12915                op: Op::Fused(
12916                    fuel_graph::registry::FusedOps::CONV2D,
12917                    fuel_graph::registry::FusedOpParams::Conv2D {
12918                        stride: (1, 1),
12919                        padding: (0, 0),
12920                        groups: 1,
12921                    },
12922                ),
12923                inputs: vec![x, w, b],
12924                shape: Shape::from_dims(&[1, 1, 2, 2]),
12925                dtype: DType::F32,
12926            });
12927            g.set_target_backend(c, BackendId::Cpu);
12928            (x, w, b, c)
12929        };
12930        let mut inputs = StorageCache::new();
12931        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12932        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12933        inputs.insert(b_id, Arc::new(RwLock::new(bias_storage)));
12934
12935        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12936        let guard = result_arc.read().unwrap();
12937        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12938            panic!("expected Cpu storage");
12939        };
12940        assert_eq!(c.as_slice::<f32>().unwrap(), &[112.0, 116.0, 124.0, 128.0]);
12941    }
12942
12943    /// E2E: Conv2D in F64 — same 2x2 sum-kernel test as F32, on doubles.
12944    #[test]
12945    fn pipelined_realize_conv2d_f64() {
12946        let x_storage =
12947            fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
12948        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
12949
12950        let graph = Arc::new(RwLock::new(Graph::new()));
12951        let (x_id, w_id, c_id) = {
12952            let mut g = graph.write().unwrap();
12953            let x = g.push(Node {
12954                op: Op::Const,
12955                inputs: vec![],
12956                shape: Shape::from_dims(&[1, 1, 3, 3]),
12957                dtype: DType::F64,
12958            });
12959            let w = g.push(Node {
12960                op: Op::Const,
12961                inputs: vec![],
12962                shape: Shape::from_dims(&[1, 1, 2, 2]),
12963                dtype: DType::F64,
12964            });
12965            let c = g.push(Node {
12966                op: Op::Fused(
12967                    fuel_graph::registry::FusedOps::CONV2D,
12968                    fuel_graph::registry::FusedOpParams::Conv2D {
12969                        stride: (1, 1),
12970                        padding: (0, 0),
12971                        groups: 1,
12972                    },
12973                ),
12974                inputs: vec![x, w],
12975                shape: Shape::from_dims(&[1, 1, 2, 2]),
12976                dtype: DType::F64,
12977            });
12978            g.set_target_backend(c, BackendId::Cpu);
12979            (x, w, c)
12980        };
12981        let mut inputs = StorageCache::new();
12982        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
12983        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
12984        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
12985        let guard = result_arc.read().unwrap();
12986        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
12987            panic!("expected Cpu storage");
12988        };
12989        assert_eq!(c.as_slice::<f64>().unwrap(), &[12.0, 16.0, 24.0, 28.0]);
12990    }
12991
12992    /// E2E: Conv2D in BF16 — f32-accumulator path. Tolerant compare.
12993    #[test]
12994    fn pipelined_realize_conv2d_bf16() {
12995        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]
12996            .iter()
12997            .map(|v| half::bf16::from_f32(*v))
12998            .collect();
12999        let w_data: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
13000            .iter()
13001            .map(|v| half::bf16::from_f32(*v))
13002            .collect();
13003        let x_storage = fuel_memory::from_slice_cpu(&x_data);
13004        let w_storage = fuel_memory::from_slice_cpu(&w_data);
13005
13006        let graph = Arc::new(RwLock::new(Graph::new()));
13007        let (x_id, w_id, c_id) = {
13008            let mut g = graph.write().unwrap();
13009            let x = g.push(Node {
13010                op: Op::Const,
13011                inputs: vec![],
13012                shape: Shape::from_dims(&[1, 1, 3, 3]),
13013                dtype: DType::BF16,
13014            });
13015            let w = g.push(Node {
13016                op: Op::Const,
13017                inputs: vec![],
13018                shape: Shape::from_dims(&[1, 1, 2, 2]),
13019                dtype: DType::BF16,
13020            });
13021            let c = g.push(Node {
13022                op: Op::Fused(
13023                    fuel_graph::registry::FusedOps::CONV2D,
13024                    fuel_graph::registry::FusedOpParams::Conv2D {
13025                        stride: (1, 1),
13026                        padding: (0, 0),
13027                        groups: 1,
13028                    },
13029                ),
13030                inputs: vec![x, w],
13031                shape: Shape::from_dims(&[1, 1, 2, 2]),
13032                dtype: DType::BF16,
13033            });
13034            g.set_target_backend(c, BackendId::Cpu);
13035            (x, w, c)
13036        };
13037        let mut inputs = StorageCache::new();
13038        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13039        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13040        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13041        let guard = result_arc.read().unwrap();
13042        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13043            panic!("expected Cpu storage");
13044        };
13045        let got: Vec<f32> = c
13046            .as_slice::<half::bf16>()
13047            .unwrap()
13048            .iter()
13049            .map(|v| v.to_f32())
13050            .collect();
13051        let want = [12.0_f32, 16.0, 24.0, 28.0];
13052        for (g, w) in got.iter().zip(want.iter()) {
13053            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13054        }
13055    }
13056
13057    /// E2E: Conv2D in F16 — f32-accumulator path. Tolerant compare.
13058    #[test]
13059    fn pipelined_realize_conv2d_f16() {
13060        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]
13061            .iter()
13062            .map(|v| half::f16::from_f32(*v))
13063            .collect();
13064        let w_data: Vec<half::f16> = [1.0_f32, 1.0, 1.0, 1.0]
13065            .iter()
13066            .map(|v| half::f16::from_f32(*v))
13067            .collect();
13068        let x_storage = fuel_memory::from_slice_cpu(&x_data);
13069        let w_storage = fuel_memory::from_slice_cpu(&w_data);
13070
13071        let graph = Arc::new(RwLock::new(Graph::new()));
13072        let (x_id, w_id, c_id) = {
13073            let mut g = graph.write().unwrap();
13074            let x = g.push(Node {
13075                op: Op::Const,
13076                inputs: vec![],
13077                shape: Shape::from_dims(&[1, 1, 3, 3]),
13078                dtype: DType::F16,
13079            });
13080            let w = g.push(Node {
13081                op: Op::Const,
13082                inputs: vec![],
13083                shape: Shape::from_dims(&[1, 1, 2, 2]),
13084                dtype: DType::F16,
13085            });
13086            let c = g.push(Node {
13087                op: Op::Fused(
13088                    fuel_graph::registry::FusedOps::CONV2D,
13089                    fuel_graph::registry::FusedOpParams::Conv2D {
13090                        stride: (1, 1),
13091                        padding: (0, 0),
13092                        groups: 1,
13093                    },
13094                ),
13095                inputs: vec![x, w],
13096                shape: Shape::from_dims(&[1, 1, 2, 2]),
13097                dtype: DType::F16,
13098            });
13099            g.set_target_backend(c, BackendId::Cpu);
13100            (x, w, c)
13101        };
13102        let mut inputs = StorageCache::new();
13103        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
13104        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
13105        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
13106        let guard = result_arc.read().unwrap();
13107        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13108            panic!("expected Cpu storage");
13109        };
13110        let got: Vec<f32> = c
13111            .as_slice::<half::f16>()
13112            .unwrap()
13113            .iter()
13114            .map(|v| v.to_f32())
13115            .collect();
13116        let want = [12.0_f32, 16.0, 24.0, 28.0];
13117        for (g, w) in got.iter().zip(want.iter()) {
13118            assert!((g - w).abs() < 0.05, "got {got:?} want {want:?}");
13119        }
13120    }
13121
13122    /// E2E: Op::PagedAttn — F32, single-head, B=1, Sq=1.
13123    /// Same setup as the FlashAttn smoke test, but the K/V live in a
13124    /// paged cache that we look up via block_table.
13125    /// Layout:
13126    ///   block_size=2, num_blocks=1, max_blocks_per_seq=1.
13127    ///   k_cache shape [1, 2, 1, 2] = num_blocks × block_size × Hkv × D.
13128    ///   k_cache[block 0, slot 0, h 0] = [1, 0]
13129    ///   k_cache[block 0, slot 1, h 0] = [0, 1]
13130    ///   v_cache values: [10, 0] / [0, 10]
13131    ///   block_table[b=0, logical_block 0] = 0 (physical)
13132    ///   context_lens[0] = 2
13133    ///   q[0, 0, 0] = [2, 0]
13134    /// Causal is implicit (q_pos = ctx_len - Sq + sq = 2 - 1 + 0 = 1, both keys admissible).
13135    /// Same softmax math as FlashAttn → ~[8.808, 1.192].
13136    #[test]
13137    fn pipelined_realize_paged_attn_f32() {
13138        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13139        let k_cache = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13140        let v_cache = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13141        let block_table_u32 = fuel_memory::Storage::new(
13142            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13143                0_u32,
13144            ])),
13145            DType::U32,
13146        );
13147        let context_lens_u32 = fuel_memory::Storage::new(
13148            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13149                2_u32,
13150            ])),
13151            DType::U32,
13152        );
13153        let graph = Arc::new(RwLock::new(Graph::new()));
13154        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13155            let mut g = graph.write().unwrap();
13156            let q = g.push(Node {
13157                op: Op::Const,
13158                inputs: vec![],
13159                shape: Shape::from_dims(&[1, 1, 1, 2]),
13160                dtype: DType::F32,
13161            });
13162            let kc = g.push(Node {
13163                op: Op::Const,
13164                inputs: vec![],
13165                shape: Shape::from_dims(&[1, 2, 1, 2]),
13166                dtype: DType::F32,
13167            });
13168            let vc = g.push(Node {
13169                op: Op::Const,
13170                inputs: vec![],
13171                shape: Shape::from_dims(&[1, 2, 1, 2]),
13172                dtype: DType::F32,
13173            });
13174            let bt = g.push(Node {
13175                op: Op::Const,
13176                inputs: vec![],
13177                shape: Shape::from_dims(&[1, 1]),
13178                dtype: DType::U32,
13179            });
13180            let cl = g.push(Node {
13181                op: Op::Const,
13182                inputs: vec![],
13183                shape: Shape::from_dims(&[1]),
13184                dtype: DType::U32,
13185            });
13186            let op = g.push(Node {
13187                op: Op::Fused(
13188                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13189                    fuel_graph::registry::FusedOpParams::PagedAttn {
13190                        softmax_scale: 1.0,
13191                        block_size: 2,
13192                        softcap: None,
13193                    },
13194                ),
13195                inputs: vec![q, kc, vc, bt, cl],
13196                shape: Shape::from_dims(&[1, 1, 1, 2]),
13197                dtype: DType::F32,
13198            });
13199            g.set_target_backend(op, BackendId::Cpu);
13200            (q, kc, vc, bt, cl, op)
13201        };
13202        let mut inputs = StorageCache::new();
13203        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13204        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13205        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13206        inputs.insert(bt_id, Arc::new(RwLock::new(block_table_u32)));
13207        inputs.insert(cl_id, Arc::new(RwLock::new(context_lens_u32)));
13208        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13209        let guard = result_arc.read().unwrap();
13210        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13211            panic!("expected Cpu storage");
13212        };
13213        let r = c.as_slice::<f32>().unwrap();
13214        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13215        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13216        assert!(
13217            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13218            "row[0]: got {} expected {}",
13219            r[0],
13220            10.0 * expected_p0
13221        );
13222        assert!(
13223            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13224            "row[1]: got {} expected {}",
13225            r[1],
13226            10.0 * expected_p1
13227        );
13228    }
13229
13230    /// E2E: PagedAttn BF16 — same single-row test, tolerant.
13231    #[test]
13232    fn pipelined_realize_paged_attn_bf16() {
13233        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13234            .iter()
13235            .map(|x| half::bf16::from_f32(*x))
13236            .collect();
13237        let kc_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13238            .iter()
13239            .map(|x| half::bf16::from_f32(*x))
13240            .collect();
13241        let vc_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13242            .iter()
13243            .map(|x| half::bf16::from_f32(*x))
13244            .collect();
13245        let q = fuel_memory::from_slice_cpu(&q_v);
13246        let k_cache = fuel_memory::from_slice_cpu(&kc_v);
13247        let v_cache = fuel_memory::from_slice_cpu(&vc_v);
13248        let bt = fuel_memory::Storage::new(
13249            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13250                0_u32,
13251            ])),
13252            DType::U32,
13253        );
13254        let cl = fuel_memory::Storage::new(
13255            fuel_memory::BackendStorage::Cpu(fuel_cpu_backend::CpuStorageBytes::from_slice(&[
13256                2_u32,
13257            ])),
13258            DType::U32,
13259        );
13260        let graph = Arc::new(RwLock::new(Graph::new()));
13261        let (q_id, kc_id, vc_id, bt_id, cl_id, op_id) = {
13262            let mut g = graph.write().unwrap();
13263            let q = g.push(Node {
13264                op: Op::Const,
13265                inputs: vec![],
13266                shape: Shape::from_dims(&[1, 1, 1, 2]),
13267                dtype: DType::BF16,
13268            });
13269            let kc = g.push(Node {
13270                op: Op::Const,
13271                inputs: vec![],
13272                shape: Shape::from_dims(&[1, 2, 1, 2]),
13273                dtype: DType::BF16,
13274            });
13275            let vc = g.push(Node {
13276                op: Op::Const,
13277                inputs: vec![],
13278                shape: Shape::from_dims(&[1, 2, 1, 2]),
13279                dtype: DType::BF16,
13280            });
13281            let bt = g.push(Node {
13282                op: Op::Const,
13283                inputs: vec![],
13284                shape: Shape::from_dims(&[1, 1]),
13285                dtype: DType::U32,
13286            });
13287            let cl = g.push(Node {
13288                op: Op::Const,
13289                inputs: vec![],
13290                shape: Shape::from_dims(&[1]),
13291                dtype: DType::U32,
13292            });
13293            let op = g.push(Node {
13294                op: Op::Fused(
13295                    fuel_graph::registry::FusedOps::PAGED_ATTN,
13296                    fuel_graph::registry::FusedOpParams::PagedAttn {
13297                        softmax_scale: 1.0,
13298                        block_size: 2,
13299                        softcap: None,
13300                    },
13301                ),
13302                inputs: vec![q, kc, vc, bt, cl],
13303                shape: Shape::from_dims(&[1, 1, 1, 2]),
13304                dtype: DType::BF16,
13305            });
13306            g.set_target_backend(op, BackendId::Cpu);
13307            (q, kc, vc, bt, cl, op)
13308        };
13309        let mut inputs = StorageCache::new();
13310        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13311        inputs.insert(kc_id, Arc::new(RwLock::new(k_cache)));
13312        inputs.insert(vc_id, Arc::new(RwLock::new(v_cache)));
13313        inputs.insert(bt_id, Arc::new(RwLock::new(bt)));
13314        inputs.insert(cl_id, Arc::new(RwLock::new(cl)));
13315        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13316        let guard = result_arc.read().unwrap();
13317        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13318            panic!("expected Cpu storage");
13319        };
13320        let got: Vec<f32> = c
13321            .as_slice::<half::bf16>()
13322            .unwrap()
13323            .iter()
13324            .map(|v| v.to_f32())
13325            .collect();
13326        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13327        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13328        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13329        for (g, w) in got.iter().zip(want.iter()) {
13330            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13331        }
13332    }
13333
13334    /// E2E: Op::FlashAttn — F32 single-head, single-batch, no mask.
13335    /// q = [[2.0, 0.0]], k = [[1.0, 0.0], [0.0, 1.0]], v = [[10, 0], [0, 10]]
13336    /// scale = 1.0
13337    /// scores = q · kᵀ = [2.0, 0.0]
13338    /// softmax = [e^2/(e^2+1), 1/(e^2+1)] ≈ [0.8808, 0.1192]
13339    /// out = softmax @ v = [10*0.8808, 10*0.1192] ≈ [8.808, 1.192]
13340    #[test]
13341    fn pipelined_realize_flash_attn_f32() {
13342        // [B=1, H=1, S=1or2, D=2]
13343        let q = fuel_memory::from_slice_cpu(&[2.0_f32, 0.0]);
13344        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13345        let v = fuel_memory::from_slice_cpu(&[10.0_f32, 0.0, 0.0, 10.0]);
13346        let graph = Arc::new(RwLock::new(Graph::new()));
13347        let (q_id, k_id, v_id, op_id) = {
13348            let mut g = graph.write().unwrap();
13349            let q = g.push(Node {
13350                op: Op::Const,
13351                inputs: vec![],
13352                shape: Shape::from_dims(&[1, 1, 1, 2]),
13353                dtype: DType::F32,
13354            });
13355            let k = g.push(Node {
13356                op: Op::Const,
13357                inputs: vec![],
13358                shape: Shape::from_dims(&[1, 1, 2, 2]),
13359                dtype: DType::F32,
13360            });
13361            let v = g.push(Node {
13362                op: Op::Const,
13363                inputs: vec![],
13364                shape: Shape::from_dims(&[1, 1, 2, 2]),
13365                dtype: DType::F32,
13366            });
13367            let op = g.push(Node {
13368                op: Op::Fused(
13369                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13370                    fuel_graph::registry::FusedOpParams::FlashAttn {
13371                        softmax_scale: 1.0,
13372                        causal: false,
13373                        window_size_left: None,
13374                        window_size_right: None,
13375                        softcap: None,
13376                        k_len: None,
13377                    },
13378                ),
13379                inputs: vec![q, k, v],
13380                shape: Shape::from_dims(&[1, 1, 1, 2]),
13381                dtype: DType::F32,
13382            });
13383            g.set_target_backend(op, BackendId::Cpu);
13384            (q, k, v, op)
13385        };
13386        let mut inputs = StorageCache::new();
13387        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13388        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13389        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13390        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13391        let guard = result_arc.read().unwrap();
13392        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13393            panic!("expected Cpu storage");
13394        };
13395        let r = c.as_slice::<f32>().unwrap();
13396        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13397        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13398        assert!(
13399            (r[0] - 10.0 * expected_p0).abs() < 1e-5,
13400            "row[0]: got {} expected {}",
13401            r[0],
13402            10.0 * expected_p0
13403        );
13404        assert!(
13405            (r[1] - 10.0 * expected_p1).abs() < 1e-5,
13406            "row[1]: got {} expected {}",
13407            r[1],
13408            10.0 * expected_p1
13409        );
13410    }
13411
13412    /// E2E: FlashAttn with causal mask — second query position
13413    /// attends to both keys (positions 0 and 1), first only attends
13414    /// to key 0 (everything beyond is masked).
13415    #[test]
13416    fn pipelined_realize_flash_attn_causal_f32() {
13417        // q [1,1,2,2]: query 0 = [1, 0], query 1 = [0, 1]
13418        // k [1,1,2,2]: keys = [[1, 0], [0, 1]]
13419        // v [1,1,2,2]: values = [[5, 6], [7, 8]]
13420        // softmax_scale=1, causal:
13421        //   query 0: only key 0 admissible → out = v[0] = [5, 6]
13422        //   query 1: both admissible. scores = q1·k = [0, 1]
13423        //            softmax = [1/(e+1), e/(e+1)]
13424        //            out = scores · v = [(5)/(e+1) + 7e/(e+1), 6/(e+1) + 8e/(e+1)]
13425        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13426        let k = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13427        let v = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
13428        let graph = Arc::new(RwLock::new(Graph::new()));
13429        let (q_id, k_id, v_id, op_id) = {
13430            let mut g = graph.write().unwrap();
13431            let q = g.push(Node {
13432                op: Op::Const,
13433                inputs: vec![],
13434                shape: Shape::from_dims(&[1, 1, 2, 2]),
13435                dtype: DType::F32,
13436            });
13437            let k = g.push(Node {
13438                op: Op::Const,
13439                inputs: vec![],
13440                shape: Shape::from_dims(&[1, 1, 2, 2]),
13441                dtype: DType::F32,
13442            });
13443            let v = g.push(Node {
13444                op: Op::Const,
13445                inputs: vec![],
13446                shape: Shape::from_dims(&[1, 1, 2, 2]),
13447                dtype: DType::F32,
13448            });
13449            let op = g.push(Node {
13450                op: Op::Fused(
13451                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13452                    fuel_graph::registry::FusedOpParams::FlashAttn {
13453                        softmax_scale: 1.0,
13454                        causal: true,
13455                        window_size_left: None,
13456                        window_size_right: None,
13457                        softcap: None,
13458                        k_len: None,
13459                    },
13460                ),
13461                inputs: vec![q, k, v],
13462                shape: Shape::from_dims(&[1, 1, 2, 2]),
13463                dtype: DType::F32,
13464            });
13465            g.set_target_backend(op, BackendId::Cpu);
13466            (q, k, v, op)
13467        };
13468        let mut inputs = StorageCache::new();
13469        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13470        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13471        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13472        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13473        let guard = result_arc.read().unwrap();
13474        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13475            panic!("expected Cpu storage");
13476        };
13477        let r = c.as_slice::<f32>().unwrap();
13478        // Query 0 sees only key 0 → output = v[0]
13479        assert!((r[0] - 5.0).abs() < 1e-5, "got {}", r[0]);
13480        assert!((r[1] - 6.0).abs() < 1e-5, "got {}", r[1]);
13481        // Query 1 sees both. softmax([0, 1]) = [1/(e+1), e/(e+1)]
13482        let denom = (1.0_f32).exp() + 1.0;
13483        let expected_a = 5.0 / denom + 7.0 * (1.0_f32).exp() / denom;
13484        let expected_b = 6.0 / denom + 8.0 * (1.0_f32).exp() / denom;
13485        assert!(
13486            (r[2] - expected_a).abs() < 1e-5,
13487            "row1[0]: got {} expected {}",
13488            r[2],
13489            expected_a
13490        );
13491        assert!(
13492            (r[3] - expected_b).abs() < 1e-5,
13493            "row1[1]: got {} expected {}",
13494            r[3],
13495            expected_b
13496        );
13497    }
13498
13499    /// E2E: FlashAttn over a fixed-**capacity** K/V with a runtime
13500    /// `k_len` resolved through a `SymEnv` (Phase D symbolic extents).
13501    /// Only the first `k_len` rows are attended; trailing "poison" rows
13502    /// in the capacity buffer are ignored, and the causal mask is
13503    /// bottom-right-aligned at offset `k_len - Sq`. This is flash decode
13504    /// over a persistent KV-cache: K/V are `[.., max_seq, ..]` capacity
13505    /// and the live prefix grows per token.
13506    #[test]
13507    fn pipelined_realize_flash_attn_dynamic_k_len() {
13508        use fuel_ir::{DynScalar, SymId};
13509        // q [1,1,2,2]; K/V capacity [1,1,4,2]; bind k_len = 3 so row 3
13510        // (the "poison" row) is never attended.
13511        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13512        let k = fuel_memory::from_slice_cpu(&[
13513            1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0, 100.0,
13514            100.0, // poison row 3 — must be ignored (k_len=3)
13515        ]);
13516        let v = fuel_memory::from_slice_cpu(&[
13517            5.0_f32, 6.0, 7.0, 8.0, 9.0, 10.0, 999.0,
13518            999.0, // poison row 3 — must be ignored
13519        ]);
13520        let sym = SymId(0);
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(sym)),
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        let mut env = SymEnv::new();
13566        env.bind(sym, 3).unwrap();
13567        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, op_id, inputs, env)
13568            .expect("realize_with_env");
13569        let guard = result_arc.read().unwrap();
13570        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13571            panic!("expected Cpu storage");
13572        };
13573        let r = c.as_slice::<f32>().unwrap();
13574        let e = 1.0_f32.exp();
13575        // causal_offset = k_len - Sq = 3 - 2 = 1.
13576        // Query 0 (abs pos 1): keys {0,1}. scores [1,0] → softmax [e,1]/(e+1).
13577        let d0 = e + 1.0;
13578        let e0x = (5.0 * e + 7.0) / d0;
13579        let e0y = (6.0 * e + 8.0) / d0;
13580        // Query 1 (abs pos 2): keys {0,1,2}. scores [0,1,1] → [1,e,e]/(1+2e).
13581        let d1 = 1.0 + 2.0 * e;
13582        let e1x = (5.0 + 7.0 * e + 9.0 * e) / d1;
13583        let e1y = (6.0 + 8.0 * e + 10.0 * e) / d1;
13584        for (got, want) in r.iter().zip([e0x, e0y, e1x, e1y].iter()) {
13585            assert!(
13586                (got - want).abs() < 1e-4,
13587                "flash dyn k_len: got {got}, want {want} (full output {r:?}); \
13588                 a poison-contaminated value means the capacity rows past k_len leaked in",
13589            );
13590        }
13591    }
13592
13593    /// A flash `k_len` symbol unbound in the `SymEnv` surfaces a typed
13594    /// error at realize (never a panic).
13595    #[test]
13596    fn pipelined_realize_flash_attn_dynamic_k_len_unbound_errors() {
13597        use fuel_ir::{DynScalar, SymId};
13598        let q = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
13599        let k = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13600        let v = fuel_memory::from_slice_cpu(&[0.0_f32; 16]);
13601        let graph = Arc::new(RwLock::new(Graph::new()));
13602        let (q_id, k_id, v_id, op_id) = {
13603            let mut g = graph.write().unwrap();
13604            let q = g.push(Node {
13605                op: Op::Const,
13606                inputs: vec![],
13607                shape: Shape::from_dims(&[1, 1, 2, 2]),
13608                dtype: DType::F32,
13609            });
13610            let k = g.push(Node {
13611                op: Op::Const,
13612                inputs: vec![],
13613                shape: Shape::from_dims(&[1, 1, 4, 2]),
13614                dtype: DType::F32,
13615            });
13616            let v = g.push(Node {
13617                op: Op::Const,
13618                inputs: vec![],
13619                shape: Shape::from_dims(&[1, 1, 4, 2]),
13620                dtype: DType::F32,
13621            });
13622            let op = g.push(Node {
13623                op: Op::Fused(
13624                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13625                    fuel_graph::registry::FusedOpParams::FlashAttn {
13626                        softmax_scale: 1.0,
13627                        causal: true,
13628                        window_size_left: None,
13629                        window_size_right: None,
13630                        softcap: None,
13631                        k_len: Some(DynScalar::Sym(SymId(0))),
13632                    },
13633                ),
13634                inputs: vec![q, k, v],
13635                shape: Shape::from_dims(&[1, 1, 2, 2]),
13636                dtype: DType::F32,
13637            });
13638            g.set_target_backend(op, BackendId::Cpu);
13639            (q, k, v, op)
13640        };
13641        let mut inputs = StorageCache::new();
13642        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13643        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13644        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13645        // Empty env — the k_len symbol is unbound.
13646        let result = PipelinedExecutor::realize_with_env(graph, op_id, inputs, SymEnv::new());
13647        assert!(
13648            result.is_err(),
13649            "unbound flash k_len symbol must surface a typed error"
13650        );
13651    }
13652
13653    /// E2E: FlashAttn BF16 — same single-row test as f32, tolerant.
13654    #[test]
13655    fn pipelined_realize_flash_attn_bf16() {
13656        let q_v: Vec<half::bf16> = [2.0_f32, 0.0]
13657            .iter()
13658            .map(|x| half::bf16::from_f32(*x))
13659            .collect();
13660        let k_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0]
13661            .iter()
13662            .map(|x| half::bf16::from_f32(*x))
13663            .collect();
13664        let v_v: Vec<half::bf16> = [10.0_f32, 0.0, 0.0, 10.0]
13665            .iter()
13666            .map(|x| half::bf16::from_f32(*x))
13667            .collect();
13668        let q = fuel_memory::from_slice_cpu(&q_v);
13669        let k = fuel_memory::from_slice_cpu(&k_v);
13670        let v = fuel_memory::from_slice_cpu(&v_v);
13671        let graph = Arc::new(RwLock::new(Graph::new()));
13672        let (q_id, k_id, v_id, op_id) = {
13673            let mut g = graph.write().unwrap();
13674            let q = g.push(Node {
13675                op: Op::Const,
13676                inputs: vec![],
13677                shape: Shape::from_dims(&[1, 1, 1, 2]),
13678                dtype: DType::BF16,
13679            });
13680            let k = g.push(Node {
13681                op: Op::Const,
13682                inputs: vec![],
13683                shape: Shape::from_dims(&[1, 1, 2, 2]),
13684                dtype: DType::BF16,
13685            });
13686            let v = g.push(Node {
13687                op: Op::Const,
13688                inputs: vec![],
13689                shape: Shape::from_dims(&[1, 1, 2, 2]),
13690                dtype: DType::BF16,
13691            });
13692            let op = g.push(Node {
13693                op: Op::Fused(
13694                    fuel_graph::registry::FusedOps::FLASH_ATTN,
13695                    fuel_graph::registry::FusedOpParams::FlashAttn {
13696                        softmax_scale: 1.0,
13697                        causal: false,
13698                        window_size_left: None,
13699                        window_size_right: None,
13700                        softcap: None,
13701                        k_len: None,
13702                    },
13703                ),
13704                inputs: vec![q, k, v],
13705                shape: Shape::from_dims(&[1, 1, 1, 2]),
13706                dtype: DType::BF16,
13707            });
13708            g.set_target_backend(op, BackendId::Cpu);
13709            (q, k, v, op)
13710        };
13711        let mut inputs = StorageCache::new();
13712        inputs.insert(q_id, Arc::new(RwLock::new(q)));
13713        inputs.insert(k_id, Arc::new(RwLock::new(k)));
13714        inputs.insert(v_id, Arc::new(RwLock::new(v)));
13715        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13716        let guard = result_arc.read().unwrap();
13717        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13718            panic!("expected Cpu storage");
13719        };
13720        let got: Vec<f32> = c
13721            .as_slice::<half::bf16>()
13722            .unwrap()
13723            .iter()
13724            .map(|v| v.to_f32())
13725            .collect();
13726        let expected_p0 = 2.0_f32.exp() / (2.0_f32.exp() + 1.0);
13727        let expected_p1 = 1.0_f32 / (2.0_f32.exp() + 1.0);
13728        let want = [10.0 * expected_p0, 10.0 * expected_p1];
13729        for (g, w) in got.iter().zip(want.iter()) {
13730            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13731        }
13732    }
13733
13734    /// E2E: Op::FusedLinear — F32. a[1,2,3] @ b[1,3,2] + bias[2].
13735    /// a = [[[1,2,3],[4,5,6]]], b = [[[1,0],[0,1],[1,1]]], bias=[10,20]
13736    /// matmul = [[1+0+3, 0+2+3], [4+0+6, 0+5+6]] = [[4, 5], [10, 11]]
13737    /// + bias = [[14, 25], [20, 31]]
13738    #[test]
13739    fn pipelined_realize_fused_linear_f32() {
13740        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13741        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13742        let bias = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
13743        let graph = Arc::new(RwLock::new(Graph::new()));
13744        let (a_id, b_id, bias_id, op_id) = {
13745            let mut g = graph.write().unwrap();
13746            let a = g.push(Node {
13747                op: Op::Const,
13748                inputs: vec![],
13749                shape: Shape::from_dims(&[1, 2, 3]),
13750                dtype: DType::F32,
13751            });
13752            let b = g.push(Node {
13753                op: Op::Const,
13754                inputs: vec![],
13755                shape: Shape::from_dims(&[1, 3, 2]),
13756                dtype: DType::F32,
13757            });
13758            let bias = g.push(Node {
13759                op: Op::Const,
13760                inputs: vec![],
13761                shape: Shape::from_dims(&[2]),
13762                dtype: DType::F32,
13763            });
13764            let op = g.push(Node {
13765                op: Op::Fused(
13766                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13767                    fuel_graph::registry::FusedOpParams::FusedLinear,
13768                ),
13769                inputs: vec![a, b, bias],
13770                shape: Shape::from_dims(&[1, 2, 2]),
13771                dtype: DType::F32,
13772            });
13773            g.set_target_backend(op, BackendId::Cpu);
13774            (a, b, bias, op)
13775        };
13776        let mut inputs = StorageCache::new();
13777        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13778        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13779        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13780        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13781        let guard = result_arc.read().unwrap();
13782        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13783            panic!("expected Cpu storage");
13784        };
13785        assert_eq!(c.as_slice::<f32>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13786    }
13787
13788    /// E2E: FusedLinear F64 — same shape test on doubles.
13789    #[test]
13790    fn pipelined_realize_fused_linear_f64() {
13791        let a = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
13792        let b = fuel_memory::from_slice_cpu(&[1.0_f64, 0.0, 0.0, 1.0, 1.0, 1.0]);
13793        let bias = fuel_memory::from_slice_cpu(&[10.0_f64, 20.0]);
13794        let graph = Arc::new(RwLock::new(Graph::new()));
13795        let (a_id, b_id, bias_id, op_id) = {
13796            let mut g = graph.write().unwrap();
13797            let a = g.push(Node {
13798                op: Op::Const,
13799                inputs: vec![],
13800                shape: Shape::from_dims(&[1, 2, 3]),
13801                dtype: DType::F64,
13802            });
13803            let b = g.push(Node {
13804                op: Op::Const,
13805                inputs: vec![],
13806                shape: Shape::from_dims(&[1, 3, 2]),
13807                dtype: DType::F64,
13808            });
13809            let bias = g.push(Node {
13810                op: Op::Const,
13811                inputs: vec![],
13812                shape: Shape::from_dims(&[2]),
13813                dtype: DType::F64,
13814            });
13815            let op = g.push(Node {
13816                op: Op::Fused(
13817                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13818                    fuel_graph::registry::FusedOpParams::FusedLinear,
13819                ),
13820                inputs: vec![a, b, bias],
13821                shape: Shape::from_dims(&[1, 2, 2]),
13822                dtype: DType::F64,
13823            });
13824            g.set_target_backend(op, BackendId::Cpu);
13825            (a, b, bias, op)
13826        };
13827        let mut inputs = StorageCache::new();
13828        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13829        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13830        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13831        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13832        let guard = result_arc.read().unwrap();
13833        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13834            panic!("expected Cpu storage");
13835        };
13836        assert_eq!(c.as_slice::<f64>().unwrap(), &[14.0, 25.0, 20.0, 31.0]);
13837    }
13838
13839    /// E2E (row 172 item 1): RowScaledMatMul F32 on CPU. a [1,2,3] @ b [1,3,2]
13840    /// = [[4, 5], [10, 11]]... computed by hand below; each row is scaled by its
13841    /// own entry of row_scale [1,2,1] = [2, 10]. A per-column or unscaled result
13842    /// would differ, so this discriminates the epilogue.
13843    #[test]
13844    fn pipelined_realize_row_scaled_matmul_f32() {
13845        // a rows: [1,2,3], [4,5,6]; b = [[1,0],[0,1],[1,1]].
13846        // a@b = [[1+3, 2+3], [4+6, 5+6]] = [[4, 5], [10, 11]].
13847        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13848        let b = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]);
13849        let scale = fuel_memory::from_slice_cpu(&[2.0_f32, 10.0]);
13850        let graph = Arc::new(RwLock::new(Graph::new()));
13851        let (a_id, b_id, s_id, op_id) = {
13852            let mut g = graph.write().unwrap();
13853            let mut konst = |dims: &[usize]| {
13854                g.push(Node {
13855                    op: Op::Const,
13856                    inputs: vec![],
13857                    shape: Shape::from_dims(dims),
13858                    dtype: DType::F32,
13859                })
13860            };
13861            let (a, b, s) = (konst(&[1, 2, 3]), konst(&[1, 3, 2]), konst(&[1, 2, 1]));
13862            let op = g.push(Node {
13863                op: Op::Fused(
13864                    fuel_graph::registry::FusedOps::ROW_SCALED_MATMUL,
13865                    fuel_graph::registry::FusedOpParams::RowScaledMatMul,
13866                ),
13867                inputs: vec![a, b, s],
13868                shape: Shape::from_dims(&[1, 2, 2]),
13869                dtype: DType::F32,
13870            });
13871            g.set_target_backend(op, BackendId::Cpu);
13872            (a, b, s, op)
13873        };
13874        let mut inputs = StorageCache::new();
13875        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13876        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13877        inputs.insert(s_id, Arc::new(RwLock::new(scale)));
13878        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13879        let guard = result_arc.read().unwrap();
13880        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13881            panic!("expected Cpu storage");
13882        };
13883        assert_eq!(c.as_slice::<f32>().unwrap(), &[8.0, 10.0, 100.0, 110.0]);
13884    }
13885
13886    /// E2E: FusedLinear BF16 — tolerant compare.
13887    #[test]
13888    fn pipelined_realize_fused_linear_bf16() {
13889        let a_v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
13890            .iter()
13891            .map(|x| half::bf16::from_f32(*x))
13892            .collect();
13893        let b_v: Vec<half::bf16> = [1.0_f32, 0.0, 0.0, 1.0, 1.0, 1.0]
13894            .iter()
13895            .map(|x| half::bf16::from_f32(*x))
13896            .collect();
13897        let bias_v: Vec<half::bf16> = [10.0_f32, 20.0]
13898            .iter()
13899            .map(|x| half::bf16::from_f32(*x))
13900            .collect();
13901        let a = fuel_memory::from_slice_cpu(&a_v);
13902        let b = fuel_memory::from_slice_cpu(&b_v);
13903        let bias = fuel_memory::from_slice_cpu(&bias_v);
13904        let graph = Arc::new(RwLock::new(Graph::new()));
13905        let (a_id, b_id, bias_id, op_id) = {
13906            let mut g = graph.write().unwrap();
13907            let a = g.push(Node {
13908                op: Op::Const,
13909                inputs: vec![],
13910                shape: Shape::from_dims(&[1, 2, 3]),
13911                dtype: DType::BF16,
13912            });
13913            let b = g.push(Node {
13914                op: Op::Const,
13915                inputs: vec![],
13916                shape: Shape::from_dims(&[1, 3, 2]),
13917                dtype: DType::BF16,
13918            });
13919            let bias = g.push(Node {
13920                op: Op::Const,
13921                inputs: vec![],
13922                shape: Shape::from_dims(&[2]),
13923                dtype: DType::BF16,
13924            });
13925            let op = g.push(Node {
13926                op: Op::Fused(
13927                    fuel_graph::registry::FusedOps::FUSED_LINEAR,
13928                    fuel_graph::registry::FusedOpParams::FusedLinear,
13929                ),
13930                inputs: vec![a, b, bias],
13931                shape: Shape::from_dims(&[1, 2, 2]),
13932                dtype: DType::BF16,
13933            });
13934            g.set_target_backend(op, BackendId::Cpu);
13935            (a, b, bias, op)
13936        };
13937        let mut inputs = StorageCache::new();
13938        inputs.insert(a_id, Arc::new(RwLock::new(a)));
13939        inputs.insert(b_id, Arc::new(RwLock::new(b)));
13940        inputs.insert(bias_id, Arc::new(RwLock::new(bias)));
13941        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13942        let guard = result_arc.read().unwrap();
13943        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13944            panic!("expected Cpu storage");
13945        };
13946        let got: Vec<f32> = c
13947            .as_slice::<half::bf16>()
13948            .unwrap()
13949            .iter()
13950            .map(|v| v.to_f32())
13951            .collect();
13952        let want = [14.0_f32, 25.0, 20.0, 31.0];
13953        for (g, w) in got.iter().zip(want.iter()) {
13954            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
13955        }
13956    }
13957
13958    /// E2E: Op::ReduceSumTo — sum the leading axis of a [2,3] tensor.
13959    /// Input [[1,2,3],[4,5,6]] → output [5,7,9].
13960    #[test]
13961    fn pipelined_realize_reduce_sum_to_f32_drops_leading_axis() {
13962        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
13963        let graph = Arc::new(RwLock::new(Graph::new()));
13964        let (in_id, op_id) = {
13965            let mut g = graph.write().unwrap();
13966            let in_id = g.push(Node {
13967                op: Op::Const,
13968                inputs: vec![],
13969                shape: Shape::from_dims(&[2, 3]),
13970                dtype: DType::F32,
13971            });
13972            let op_id = g.push(Node {
13973                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
13974                inputs: vec![in_id],
13975                shape: Shape::from_dims(&[3]),
13976                dtype: DType::F32,
13977            });
13978            g.set_target_backend(op_id, BackendId::Cpu);
13979            (in_id, op_id)
13980        };
13981        let mut inputs = StorageCache::new();
13982        inputs.insert(in_id, Arc::new(RwLock::new(v)));
13983        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
13984        let guard = result_arc.read().unwrap();
13985        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
13986            panic!("expected Cpu storage");
13987        };
13988        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 7.0, 9.0]);
13989    }
13990
13991    /// E2E: Op::ReduceSumTo — keep-dim with 1 in the middle.
13992    /// Input [2,3,4] → [2,1,4] sums along dim 1.
13993    #[test]
13994    fn pipelined_realize_reduce_sum_to_f32_keepdim_middle() {
13995        // [2,3,4]: layer 0 = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
13996        //          layer 1 = [[13..16],[17..20],[21..24]]
13997        let mut v: Vec<f32> = (1..=24).map(|x| x as f32).collect();
13998        let _ = &mut v;
13999        let s = fuel_memory::from_slice_cpu(&v);
14000        let graph = Arc::new(RwLock::new(Graph::new()));
14001        let (in_id, op_id) = {
14002            let mut g = graph.write().unwrap();
14003            let in_id = g.push(Node {
14004                op: Op::Const,
14005                inputs: vec![],
14006                shape: Shape::from_dims(&[2, 3, 4]),
14007                dtype: DType::F32,
14008            });
14009            let op_id = g.push(Node {
14010                op: Op::ReduceSumTo(Shape::from_dims(&[2, 1, 4])),
14011                inputs: vec![in_id],
14012                shape: Shape::from_dims(&[2, 1, 4]),
14013                dtype: DType::F32,
14014            });
14015            g.set_target_backend(op_id, BackendId::Cpu);
14016            (in_id, op_id)
14017        };
14018        let mut inputs = StorageCache::new();
14019        inputs.insert(in_id, Arc::new(RwLock::new(s)));
14020        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14021        let guard = result_arc.read().unwrap();
14022        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14023            panic!("expected Cpu storage");
14024        };
14025        // layer0 dim1-sum: col j = 1+5+9, 2+6+10, 3+7+11, 4+8+12 = [15,18,21,24]
14026        // layer1 dim1-sum: col j = 13+17+21, 14+18+22, 15+19+23, 16+20+24 = [51,54,57,60]
14027        assert_eq!(
14028            c.as_slice::<f32>().unwrap(),
14029            &[15.0, 18.0, 21.0, 24.0, 51.0, 54.0, 57.0, 60.0],
14030        );
14031    }
14032
14033    /// E2E: ReduceSumTo F64 — same drop-leading-axis test on doubles.
14034    #[test]
14035    fn pipelined_realize_reduce_sum_to_f64() {
14036        let v = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0, 5.0, 6.0]);
14037        let graph = Arc::new(RwLock::new(Graph::new()));
14038        let (in_id, op_id) = {
14039            let mut g = graph.write().unwrap();
14040            let in_id = g.push(Node {
14041                op: Op::Const,
14042                inputs: vec![],
14043                shape: Shape::from_dims(&[2, 3]),
14044                dtype: DType::F64,
14045            });
14046            let op_id = g.push(Node {
14047                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
14048                inputs: vec![in_id],
14049                shape: Shape::from_dims(&[3]),
14050                dtype: DType::F64,
14051            });
14052            g.set_target_backend(op_id, BackendId::Cpu);
14053            (in_id, op_id)
14054        };
14055        let mut inputs = StorageCache::new();
14056        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14057        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14058        let guard = result_arc.read().unwrap();
14059        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14060            panic!("expected Cpu storage");
14061        };
14062        assert_eq!(c.as_slice::<f64>().unwrap(), &[5.0, 7.0, 9.0]);
14063    }
14064
14065    /// E2E: Op::ReduceMaxTo F32 — drop the leading axis with max-reduce.
14066    #[test]
14067    fn pipelined_realize_reduce_max_to_f32_drops_leading_axis() {
14068        // Input [2,3]: row 0 = [1, 7, 3], row 1 = [4, 2, 6]. Max along
14069        // dim 0: [4, 7, 6].
14070        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 7.0, 3.0, 4.0, 2.0, 6.0]);
14071        let graph = Arc::new(RwLock::new(Graph::new()));
14072        let (in_id, op_id) = {
14073            let mut g = graph.write().unwrap();
14074            let in_id = g.push(Node {
14075                op: Op::Const,
14076                inputs: vec![],
14077                shape: Shape::from_dims(&[2, 3]),
14078                dtype: DType::F32,
14079            });
14080            let op_id = g.push(Node {
14081                op: Op::ReduceMaxTo(Shape::from_dims(&[3])),
14082                inputs: vec![in_id],
14083                shape: Shape::from_dims(&[3]),
14084                dtype: DType::F32,
14085            });
14086            g.set_target_backend(op_id, BackendId::Cpu);
14087            (in_id, op_id)
14088        };
14089        let mut inputs = StorageCache::new();
14090        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14091        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14092        let guard = result_arc.read().unwrap();
14093        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14094            panic!("expected Cpu storage");
14095        };
14096        assert_eq!(c.as_slice::<f32>().unwrap(), &[4.0, 7.0, 6.0]);
14097    }
14098
14099    /// E2E: Op::ReduceMaxTo F32 — keep-dim with 1 in the trailing axis.
14100    /// Mirrors the SoftmaxLastDim lowering's max-side shape: input
14101    /// [..., last] → [..., 1].
14102    #[test]
14103    fn pipelined_realize_reduce_max_to_f32_keepdim_trailing() {
14104        // Input [2, 3]: row maxes = [3, 6].
14105        let v = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14106        let graph = Arc::new(RwLock::new(Graph::new()));
14107        let (in_id, op_id) = {
14108            let mut g = graph.write().unwrap();
14109            let in_id = g.push(Node {
14110                op: Op::Const,
14111                inputs: vec![],
14112                shape: Shape::from_dims(&[2, 3]),
14113                dtype: DType::F32,
14114            });
14115            let op_id = g.push(Node {
14116                op: Op::ReduceMaxTo(Shape::from_dims(&[2, 1])),
14117                inputs: vec![in_id],
14118                shape: Shape::from_dims(&[2, 1]),
14119                dtype: DType::F32,
14120            });
14121            g.set_target_backend(op_id, BackendId::Cpu);
14122            (in_id, op_id)
14123        };
14124        let mut inputs = StorageCache::new();
14125        inputs.insert(in_id, Arc::new(RwLock::new(v)));
14126        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14127        let guard = result_arc.read().unwrap();
14128        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14129            panic!("expected Cpu storage");
14130        };
14131        assert_eq!(c.as_slice::<f32>().unwrap(), &[3.0, 6.0]);
14132    }
14133
14134    /// E2E: ReduceSumTo BF16 — tolerant compare via f32-acc.
14135    #[test]
14136    fn pipelined_realize_reduce_sum_to_bf16() {
14137        let v: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]
14138            .iter()
14139            .map(|x| half::bf16::from_f32(*x))
14140            .collect();
14141        let s = fuel_memory::from_slice_cpu(&v);
14142        let graph = Arc::new(RwLock::new(Graph::new()));
14143        let (in_id, op_id) = {
14144            let mut g = graph.write().unwrap();
14145            let in_id = g.push(Node {
14146                op: Op::Const,
14147                inputs: vec![],
14148                shape: Shape::from_dims(&[2, 3]),
14149                dtype: DType::BF16,
14150            });
14151            let op_id = g.push(Node {
14152                op: Op::ReduceSumTo(Shape::from_dims(&[3])),
14153                inputs: vec![in_id],
14154                shape: Shape::from_dims(&[3]),
14155                dtype: DType::BF16,
14156            });
14157            g.set_target_backend(op_id, BackendId::Cpu);
14158            (in_id, op_id)
14159        };
14160        let mut inputs = StorageCache::new();
14161        inputs.insert(in_id, Arc::new(RwLock::new(s)));
14162        let (result_arc, _) = PipelinedExecutor::realize(graph, op_id, inputs).expect("realize");
14163        let guard = result_arc.read().unwrap();
14164        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14165            panic!("expected Cpu storage");
14166        };
14167        let got: Vec<f32> = c
14168            .as_slice::<half::bf16>()
14169            .unwrap()
14170            .iter()
14171            .map(|v| v.to_f32())
14172            .collect();
14173        let want = [5.0_f32, 7.0, 9.0];
14174        for (g, w) in got.iter().zip(want.iter()) {
14175            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14176        }
14177    }
14178
14179    /// E2E: Op::ConvTranspose2D — F32 spread test.
14180    /// x = [[1, 2], [3, 4]] shape [1,1,2,2], all-ones kernel
14181    /// shape [1,1,2,2], stride=1, padding=0, dilation=1, no bias.
14182    /// Expected output (3x3):
14183    ///   [[1,  3, 2],
14184    ///    [4, 10, 6],
14185    ///    [3,  7, 4]]
14186    #[test]
14187    fn pipelined_realize_conv_transpose2d_f32() {
14188        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14189        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 1.0, 1.0, 1.0]);
14190        let graph = Arc::new(RwLock::new(Graph::new()));
14191        let (x_id, w_id, c_id) = {
14192            let mut g = graph.write().unwrap();
14193            let x = g.push(Node {
14194                op: Op::Const,
14195                inputs: vec![],
14196                shape: Shape::from_dims(&[1, 1, 2, 2]),
14197                dtype: DType::F32,
14198            });
14199            let w = g.push(Node {
14200                op: Op::Const,
14201                inputs: vec![],
14202                shape: Shape::from_dims(&[1, 1, 2, 2]),
14203                dtype: DType::F32,
14204            });
14205            let c = g.push(Node {
14206                op: Op::Fused(
14207                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14208                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14209                        stride: (1, 1),
14210                        padding: (0, 0),
14211                        output_padding: (0, 0),
14212                        dilation: (1, 1),
14213                        groups: 1,
14214                    },
14215                ),
14216                inputs: vec![x, w],
14217                shape: Shape::from_dims(&[1, 1, 3, 3]),
14218                dtype: DType::F32,
14219            });
14220            g.set_target_backend(c, BackendId::Cpu);
14221            (x, w, c)
14222        };
14223        let mut inputs = StorageCache::new();
14224        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14225        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14226        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14227        let guard = result_arc.read().unwrap();
14228        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14229            panic!("expected Cpu storage");
14230        };
14231        assert_eq!(
14232            c.as_slice::<f32>().unwrap(),
14233            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14234        );
14235    }
14236
14237    /// E2E: ConvTranspose2D F64 — same shape test.
14238    #[test]
14239    fn pipelined_realize_conv_transpose2d_f64() {
14240        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 2.0, 3.0, 4.0]);
14241        let w_storage = fuel_memory::from_slice_cpu(&[1.0_f64, 1.0, 1.0, 1.0]);
14242        let graph = Arc::new(RwLock::new(Graph::new()));
14243        let (x_id, w_id, c_id) = {
14244            let mut g = graph.write().unwrap();
14245            let x = g.push(Node {
14246                op: Op::Const,
14247                inputs: vec![],
14248                shape: Shape::from_dims(&[1, 1, 2, 2]),
14249                dtype: DType::F64,
14250            });
14251            let w = g.push(Node {
14252                op: Op::Const,
14253                inputs: vec![],
14254                shape: Shape::from_dims(&[1, 1, 2, 2]),
14255                dtype: DType::F64,
14256            });
14257            let c = g.push(Node {
14258                op: Op::Fused(
14259                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14260                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14261                        stride: (1, 1),
14262                        padding: (0, 0),
14263                        output_padding: (0, 0),
14264                        dilation: (1, 1),
14265                        groups: 1,
14266                    },
14267                ),
14268                inputs: vec![x, w],
14269                shape: Shape::from_dims(&[1, 1, 3, 3]),
14270                dtype: DType::F64,
14271            });
14272            g.set_target_backend(c, BackendId::Cpu);
14273            (x, w, c)
14274        };
14275        let mut inputs = StorageCache::new();
14276        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14277        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14278        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14279        let guard = result_arc.read().unwrap();
14280        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14281            panic!("expected Cpu storage");
14282        };
14283        assert_eq!(
14284            c.as_slice::<f64>().unwrap(),
14285            &[1.0, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0],
14286        );
14287    }
14288
14289    /// E2E: ConvTranspose2D BF16 — tolerant compare via f32-acc.
14290    #[test]
14291    fn pipelined_realize_conv_transpose2d_bf16() {
14292        let x: Vec<half::bf16> = [1.0_f32, 2.0, 3.0, 4.0]
14293            .iter()
14294            .map(|v| half::bf16::from_f32(*v))
14295            .collect();
14296        let w: Vec<half::bf16> = [1.0_f32, 1.0, 1.0, 1.0]
14297            .iter()
14298            .map(|v| half::bf16::from_f32(*v))
14299            .collect();
14300        let x_storage = fuel_memory::from_slice_cpu(&x);
14301        let w_storage = fuel_memory::from_slice_cpu(&w);
14302        let graph = Arc::new(RwLock::new(Graph::new()));
14303        let (x_id, w_id, c_id) = {
14304            let mut g = graph.write().unwrap();
14305            let x = g.push(Node {
14306                op: Op::Const,
14307                inputs: vec![],
14308                shape: Shape::from_dims(&[1, 1, 2, 2]),
14309                dtype: DType::BF16,
14310            });
14311            let w = g.push(Node {
14312                op: Op::Const,
14313                inputs: vec![],
14314                shape: Shape::from_dims(&[1, 1, 2, 2]),
14315                dtype: DType::BF16,
14316            });
14317            let c = g.push(Node {
14318                op: Op::Fused(
14319                    fuel_graph::registry::FusedOps::CONV_TRANSPOSE2D,
14320                    fuel_graph::registry::FusedOpParams::ConvTranspose2D {
14321                        stride: (1, 1),
14322                        padding: (0, 0),
14323                        output_padding: (0, 0),
14324                        dilation: (1, 1),
14325                        groups: 1,
14326                    },
14327                ),
14328                inputs: vec![x, w],
14329                shape: Shape::from_dims(&[1, 1, 3, 3]),
14330                dtype: DType::BF16,
14331            });
14332            g.set_target_backend(c, BackendId::Cpu);
14333            (x, w, c)
14334        };
14335        let mut inputs = StorageCache::new();
14336        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
14337        inputs.insert(w_id, Arc::new(RwLock::new(w_storage)));
14338        let (result_arc, _) = PipelinedExecutor::realize(graph, c_id, inputs).expect("realize");
14339        let guard = result_arc.read().unwrap();
14340        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14341            panic!("expected Cpu storage");
14342        };
14343        let got: Vec<f32> = c
14344            .as_slice::<half::bf16>()
14345            .unwrap()
14346            .iter()
14347            .map(|v| v.to_f32())
14348            .collect();
14349        let want = [1.0_f32, 3.0, 2.0, 4.0, 10.0, 6.0, 3.0, 7.0, 4.0];
14350        for (g, w) in got.iter().zip(want.iter()) {
14351            assert!((g - w).abs() < 0.5, "got {got:?} want {want:?}");
14352        }
14353    }
14354
14355    /// E2E: GQA-style matmul through the pipelined executor.
14356    /// lhs has 4 batch heads, rhs has 2; each rhs head is shared
14357    /// by 2 lhs heads. Output's batch dim follows lhs (4 heads).
14358    #[test]
14359    fn pipelined_realize_matmul_gqa() {
14360        // lhs [4, 1, 2]: heads 0..3 are [[1,2]], [[3,4]], [[5,6]], [[7,8]]
14361        // rhs [2, 2, 1]: heads 0,1 are [[1],[0]], [[0],[1]]
14362        // Expected out [4, 1, 1]: [[1]], [[3]], [[6]], [[8]]
14363        let lhs_storage =
14364            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]);
14365        let rhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 0.0, 0.0, 1.0]);
14366
14367        let graph = Arc::new(RwLock::new(Graph::new()));
14368        let (lhs_id, rhs_id, mm_id) = {
14369            let mut g = graph.write().unwrap();
14370            let lhs = g.push(Node {
14371                op: Op::Const,
14372                inputs: vec![],
14373                shape: Shape::from_dims(&[4, 1, 2]),
14374                dtype: DType::F32,
14375            });
14376            let rhs = g.push(Node {
14377                op: Op::Const,
14378                inputs: vec![],
14379                shape: Shape::from_dims(&[2, 2, 1]),
14380                dtype: DType::F32,
14381            });
14382            let mm = g.push(Node {
14383                op: Op::MatMul,
14384                inputs: vec![lhs, rhs],
14385                shape: Shape::from_dims(&[4, 1, 1]),
14386                dtype: DType::F32,
14387            });
14388            g.set_target_backend(mm, BackendId::Cpu);
14389            (lhs, rhs, mm)
14390        };
14391        let mut inputs = StorageCache::new();
14392        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14393        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14394
14395        let (result_arc, result_layout) =
14396            PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14397        assert_eq!(result_layout.shape().dims(), &[4, 1, 1]);
14398
14399        let guard = result_arc.read().unwrap();
14400        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14401            panic!("expected Cpu storage");
14402        };
14403        assert_eq!(c.as_slice::<f32>().unwrap(), &[1.0, 3.0, 6.0, 8.0]);
14404    }
14405
14406    /// E2E: matmul with a transposed rhs — proves stage 3+4
14407    /// integration carries through the matmul path. The transpose
14408    /// is metadata-only; auto-Contiguize materializes the strided
14409    /// rhs before the matmul kernel sees it.
14410    #[test]
14411    fn pipelined_realize_matmul_with_transposed_rhs() {
14412        // lhs [[1, 2], [3, 4]], rhs original [[5, 6], [7, 8]]
14413        // rhs.T = [[5, 7], [6, 8]]
14414        // lhs @ rhs.T = [[1*5+2*6, 1*7+2*8], [3*5+4*6, 3*7+4*8]]
14415        //             = [[17, 23], [39, 53]]
14416        let lhs_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
14417        let rhs_storage = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0, 7.0, 8.0]);
14418
14419        let graph = Arc::new(RwLock::new(Graph::new()));
14420        let (lhs_id, rhs_id, t_id, mm_id) = {
14421            let mut g = graph.write().unwrap();
14422            let lhs = g.push(Node {
14423                op: Op::Const,
14424                inputs: vec![],
14425                shape: Shape::from_dims(&[2, 2]),
14426                dtype: DType::F32,
14427            });
14428            let rhs = g.push(Node {
14429                op: Op::Const,
14430                inputs: vec![],
14431                shape: Shape::from_dims(&[2, 2]),
14432                dtype: DType::F32,
14433            });
14434            let t = g.push(Node {
14435                op: Op::Transpose,
14436                inputs: vec![rhs],
14437                shape: Shape::from_dims(&[2, 2]),
14438                dtype: DType::F32,
14439            });
14440            let mm = g.push(Node {
14441                op: Op::MatMul,
14442                inputs: vec![lhs, t],
14443                shape: Shape::from_dims(&[2, 2]),
14444                dtype: DType::F32,
14445            });
14446            g.set_target_backend(mm, BackendId::Cpu);
14447            (lhs, rhs, t, mm)
14448        };
14449        let _ = t_id;
14450        let mut inputs = StorageCache::new();
14451        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs_storage)));
14452        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs_storage)));
14453
14454        let (result_arc, _) = PipelinedExecutor::realize(graph, mm_id, inputs).expect("realize");
14455        let guard = result_arc.read().unwrap();
14456        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14457            panic!("expected Cpu storage");
14458        };
14459        assert_eq!(c.as_slice::<f32>().unwrap(), &[17.0, 23.0, 39.0, 53.0]);
14460    }
14461
14462    /// E2E: Const + Reshape — contiguous-input reshape is zero
14463    /// copy. The output Storage Arc is the input Arc; the layout
14464    /// is contiguous in the new shape.
14465    #[test]
14466    fn pipelined_realize_reshape_zero_copy_when_contiguous() {
14467        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14468        let graph = Arc::new(RwLock::new(Graph::new()));
14469        let (in_id, r_id) = {
14470            let mut g = graph.write().unwrap();
14471            let in_id = g.push(Node {
14472                op: Op::Const,
14473                inputs: vec![],
14474                shape: Shape::from_dims(&[2, 3]),
14475                dtype: DType::F32,
14476            });
14477            let r_id = g.push(Node {
14478                op: Op::Reshape(Shape::from_dims(&[3, 2])),
14479                inputs: vec![in_id],
14480                shape: Shape::from_dims(&[3, 2]),
14481                dtype: DType::F32,
14482            });
14483            (in_id, r_id)
14484        };
14485        let mut inputs = StorageCache::new();
14486        let in_arc = Arc::new(RwLock::new(storage));
14487        inputs.insert(in_id, Arc::clone(&in_arc));
14488
14489        let (result_arc, result_layout) =
14490            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14491
14492        // Zero copy — same Arc.
14493        assert!(
14494            Arc::ptr_eq(&result_arc, &in_arc),
14495            "contiguous reshape must zero-copy"
14496        );
14497        assert_eq!(result_layout.shape().dims(), &[3, 2]);
14498        assert!(result_layout.is_contiguous());
14499
14500        // Bytes are unchanged; just reinterpreted as [3, 2].
14501        let guard = result_arc.read().unwrap();
14502        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14503            panic!("expected Cpu storage");
14504        };
14505        assert_eq!(
14506            c.as_slice::<f32>().unwrap(),
14507            &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
14508        );
14509    }
14510
14511    /// E2E: Const + Transpose + Reshape — reshape on a strided
14512    /// input auto-contiguizes the bytes. Output Arc is fresh
14513    /// (NOT the input Arc); the bytes are the materialized
14514    /// transposed layout.
14515    #[test]
14516    fn pipelined_realize_reshape_materializes_when_strided() {
14517        // shape [2, 3]: 1 2 3 / 4 5 6
14518        // Transpose → [3, 2] strided
14519        // Reshape → [6] (forces materialization)
14520        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14521        let graph = Arc::new(RwLock::new(Graph::new()));
14522        let (in_id, t_id, r_id) = {
14523            let mut g = graph.write().unwrap();
14524            let in_id = g.push(Node {
14525                op: Op::Const,
14526                inputs: vec![],
14527                shape: Shape::from_dims(&[2, 3]),
14528                dtype: DType::F32,
14529            });
14530            let t_id = g.push(Node {
14531                op: Op::Transpose,
14532                inputs: vec![in_id],
14533                shape: Shape::from_dims(&[3, 2]),
14534                dtype: DType::F32,
14535            });
14536            let r_id = g.push(Node {
14537                op: Op::Reshape(Shape::from_dims(&[6])),
14538                inputs: vec![t_id],
14539                shape: Shape::from_dims(&[6]),
14540                dtype: DType::F32,
14541            });
14542            (in_id, t_id, r_id)
14543        };
14544        let _ = t_id;
14545        let mut inputs = StorageCache::new();
14546        let in_arc = Arc::new(RwLock::new(storage));
14547        inputs.insert(in_id, Arc::clone(&in_arc));
14548
14549        let (result_arc, result_layout) =
14550            PipelinedExecutor::realize(graph, r_id, inputs).expect("realize");
14551
14552        // Fresh Arc — auto-contiguize allocated new bytes.
14553        assert!(!Arc::ptr_eq(&result_arc, &in_arc));
14554        assert_eq!(result_layout.shape().dims(), &[6]);
14555        assert!(result_layout.is_contiguous());
14556
14557        // Materialized transposed bytes flattened: [1, 4, 2, 5, 3, 6].
14558        let guard = result_arc.read().unwrap();
14559        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14560            panic!("expected Cpu storage");
14561        };
14562        assert_eq!(
14563            c.as_slice::<f32>().unwrap(),
14564            &[1.0, 4.0, 2.0, 5.0, 3.0, 6.0]
14565        );
14566    }
14567
14568    /// E2E: Const + Transpose + SumDim — exercises stage 3
14569    /// (metadata-only Transpose, strided intermediate Layout) +
14570    /// stage 4 (auto-Contiguize before reduce kernel) end-to-end.
14571    /// The transpose makes the intermediate non-contiguous; the
14572    /// reduce wrapper would have failed in stage 2; with stage 4's
14573    /// auto-Contiguize, the kernel sees the materialized contiguous
14574    /// transposed bytes and produces the right answer.
14575    #[test]
14576    fn pipelined_realize_transpose_then_sum_dim_e2e() {
14577        // shape [2, 3]: rows are [1, 2, 3], [4, 5, 6]
14578        // After transpose: shape [3, 2], rows are [1, 4], [2, 5], [3, 6]
14579        // After SumDim(1): shape [3], values [5, 7, 9]
14580        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14581        let graph = Arc::new(RwLock::new(Graph::new()));
14582        let (in_id, t_id, sum_id) = {
14583            let mut g = graph.write().unwrap();
14584            let in_id = g.push(Node {
14585                op: Op::Const,
14586                inputs: vec![],
14587                shape: Shape::from_dims(&[2, 3]),
14588                dtype: DType::F32,
14589            });
14590            let t_id = g.push(Node {
14591                op: Op::Transpose,
14592                inputs: vec![in_id],
14593                shape: Shape::from_dims(&[3, 2]),
14594                dtype: DType::F32,
14595            });
14596            let sum_id = g.push(Node {
14597                op: Op::SumDim(1),
14598                inputs: vec![t_id],
14599                shape: Shape::from_dims(&[3]),
14600                dtype: DType::F32,
14601            });
14602            // Only the reduce kernel runs on the backend; the
14603            // transpose is metadata-only and doesn't need a target.
14604            g.set_target_backend(sum_id, BackendId::Cpu);
14605            (in_id, t_id, sum_id)
14606        };
14607        let _ = t_id;
14608        let mut inputs = StorageCache::new();
14609        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14610
14611        let (result_arc, result_layout) =
14612            PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14613
14614        // The reduce output is contiguous (kernel-produced).
14615        assert_eq!(result_layout.shape().dims(), &[3]);
14616        assert!(result_layout.is_contiguous());
14617
14618        let guard = result_arc.read().unwrap();
14619        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14620            panic!("expected Cpu storage");
14621        };
14622        let typed: &[f32] = c.as_slice().unwrap();
14623        assert_eq!(typed, &[5.0, 7.0, 9.0]);
14624    }
14625
14626    /// E2E: Const + BroadcastTo + Add — broadcast intermediate
14627    /// auto-contiguizes for the Add kernel; the result is the
14628    /// expected sum.
14629    #[test]
14630    fn pipelined_realize_broadcast_then_add_e2e() {
14631        // shape [3]: [10, 20, 30]
14632        // BroadcastTo [2, 3]: [[10, 20, 30], [10, 20, 30]]
14633        // Plus shape [2, 3]: [[1, 2, 3], [4, 5, 6]]
14634        // Result: [[11, 22, 33], [14, 25, 36]]
14635        let bc_input = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
14636        let plus_input = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14637        let graph = Arc::new(RwLock::new(Graph::new()));
14638        let (bc_in_id, plus_in_id, b_id, add_id) = {
14639            let mut g = graph.write().unwrap();
14640            let bc_in = g.push(Node {
14641                op: Op::Const,
14642                inputs: vec![],
14643                shape: Shape::from_dims(&[3]),
14644                dtype: DType::F32,
14645            });
14646            let plus_in = g.push(Node {
14647                op: Op::Const,
14648                inputs: vec![],
14649                shape: Shape::from_dims(&[2, 3]),
14650                dtype: DType::F32,
14651            });
14652            let b = g.push(Node {
14653                op: Op::BroadcastTo(Shape::from_dims(&[2, 3])),
14654                inputs: vec![bc_in],
14655                shape: Shape::from_dims(&[2, 3]),
14656                dtype: DType::F32,
14657            });
14658            let add = g.push(Node {
14659                op: Op::Add,
14660                inputs: vec![b, plus_in],
14661                shape: Shape::from_dims(&[2, 3]),
14662                dtype: DType::F32,
14663            });
14664            g.set_target_backend(add, BackendId::Cpu);
14665            (bc_in, plus_in, b, add)
14666        };
14667        let _ = b_id;
14668        let mut inputs = StorageCache::new();
14669        inputs.insert(bc_in_id, Arc::new(RwLock::new(bc_input)));
14670        inputs.insert(plus_in_id, Arc::new(RwLock::new(plus_input)));
14671
14672        let (result_arc, _result_layout) =
14673            PipelinedExecutor::realize(graph, add_id, inputs).expect("realize");
14674        let guard = result_arc.read().unwrap();
14675        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14676            panic!("expected Cpu storage");
14677        };
14678        let typed: &[f32] = c.as_slice().unwrap();
14679        assert_eq!(typed, &[11.0, 22.0, 33.0, 14.0, 25.0, 36.0]);
14680    }
14681
14682    /// E2E: Const + SumDim — verifies that `OpParams::Reduce`
14683    /// flows from the graph (input shape via `op_to_op_params`)
14684    /// through compile_one and reaches the reduce kernel.
14685    #[test]
14686    fn pipelined_realize_sum_dim() {
14687        // shape [2, 3]; reduce dim 1 → output shape [2]
14688        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
14689        let graph = Arc::new(RwLock::new(Graph::new()));
14690        let (in_id, sum_id) = {
14691            let mut g = graph.write().unwrap();
14692            let in_id = g.push(Node {
14693                op: Op::Const,
14694                inputs: vec![],
14695                shape: Shape::from_dims(&[2, 3]),
14696                dtype: DType::F32,
14697            });
14698            let sum_id = g.push(Node {
14699                op: Op::SumDim(1),
14700                inputs: vec![in_id],
14701                shape: Shape::from_dims(&[2]),
14702                dtype: DType::F32,
14703            });
14704            g.set_target_backend(sum_id, BackendId::Cpu);
14705            (in_id, sum_id)
14706        };
14707        let mut inputs = StorageCache::new();
14708        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14709
14710        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14711        let guard = result_arc.read().unwrap();
14712        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14713            let typed: &[f32] = c.as_slice().unwrap();
14714            assert_eq!(typed, &[6.0, 15.0]);
14715        }
14716    }
14717
14718    /// E2E: SumAll on a rank-3 input, exercising the all-dims branch
14719    /// of `op_to_op_params` (every dim reduced, rank-0 output).
14720    #[test]
14721    fn pipelined_realize_sum_all_rank3() {
14722        let data: Vec<f32> = (1..=24).map(|x| x as f32).collect();
14723        let storage = fuel_memory::from_slice_cpu(&data);
14724        let graph = Arc::new(RwLock::new(Graph::new()));
14725        let (in_id, sum_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(&[2, 3, 4]),
14731                dtype: DType::F32,
14732            });
14733            let sum_id = g.push(Node {
14734                op: Op::SumAll,
14735                inputs: vec![in_id],
14736                shape: Shape::from_dims(&[]),
14737                dtype: DType::F32,
14738            });
14739            g.set_target_backend(sum_id, BackendId::Cpu);
14740            (in_id, sum_id)
14741        };
14742        let mut inputs = StorageCache::new();
14743        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14744
14745        let (result_arc, _) = PipelinedExecutor::realize(graph, sum_id, inputs).expect("realize");
14746        let guard = result_arc.read().unwrap();
14747        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14748            let typed: &[f32] = c.as_slice().unwrap();
14749            // 1 + 2 + ... + 24 = 300
14750            assert_eq!(typed, &[300.0]);
14751        }
14752    }
14753
14754    /// E2E: MaxDim + MeanDim chained — verifies all four reduce
14755    /// OpKinds reach their wrappers via the OpParams plumbing.
14756    #[test]
14757    fn pipelined_realize_max_then_mean() {
14758        // shape [2, 3], MaxDim(1) → [2], MeanDim(0) → []
14759        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 9.0, 3.0, 4.0, 2.0, 8.0]);
14760        let graph = Arc::new(RwLock::new(Graph::new()));
14761        let (in_id, mean_id) = {
14762            let mut g = graph.write().unwrap();
14763            let in_id = g.push(Node {
14764                op: Op::Const,
14765                inputs: vec![],
14766                shape: Shape::from_dims(&[2, 3]),
14767                dtype: DType::F32,
14768            });
14769            let max_id = g.push(Node {
14770                op: Op::MaxDim(1),
14771                inputs: vec![in_id],
14772                shape: Shape::from_dims(&[2]),
14773                dtype: DType::F32,
14774            });
14775            let mean_id = g.push(Node {
14776                op: Op::MeanDim(0),
14777                inputs: vec![max_id],
14778                shape: Shape::from_dims(&[]),
14779                dtype: DType::F32,
14780            });
14781            g.set_target_backend(max_id, BackendId::Cpu);
14782            g.set_target_backend(mean_id, BackendId::Cpu);
14783            (in_id, mean_id)
14784        };
14785        let mut inputs = StorageCache::new();
14786        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14787
14788        let (result_arc, _) = PipelinedExecutor::realize(graph, mean_id, inputs).expect("realize");
14789        let guard = result_arc.read().unwrap();
14790        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14791            let typed: &[f32] = c.as_slice().unwrap();
14792            // MaxDim(1) on [[1,9,3],[4,2,8]] = [9, 8]; MeanDim(0) = 8.5
14793            assert_eq!(typed, &[8.5]);
14794        }
14795    }
14796
14797    /// E2E: Sigmoid + Silu — exercises two of the more compositional
14798    /// new unary kernels through the pipelined executor. Verifies
14799    /// the additional `op_to_op_kind` mappings reach the right
14800    /// dispatch wrappers.
14801    #[test]
14802    fn pipelined_realize_sigmoid_then_silu() {
14803        let storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, -1.0]);
14804        let graph = Arc::new(RwLock::new(Graph::new()));
14805        let (in_id, sig_id, silu_id) = {
14806            let mut g = graph.write().unwrap();
14807            let in_id = g.push(Node {
14808                op: Op::Const,
14809                inputs: vec![],
14810                shape: Shape::from_dims(&[3]),
14811                dtype: DType::F32,
14812            });
14813            let sig_id = g.push(Node {
14814                op: Op::Sigmoid,
14815                inputs: vec![in_id],
14816                shape: Shape::from_dims(&[3]),
14817                dtype: DType::F32,
14818            });
14819            // Silu of the sigmoid output — chains to confirm cache flow.
14820            let silu_id = g.push(Node {
14821                op: Op::Silu,
14822                inputs: vec![sig_id],
14823                shape: Shape::from_dims(&[3]),
14824                dtype: DType::F32,
14825            });
14826            g.set_target_backend(sig_id, BackendId::Cpu);
14827            g.set_target_backend(silu_id, BackendId::Cpu);
14828            (in_id, sig_id, silu_id)
14829        };
14830        let _ = sig_id;
14831        let mut inputs = StorageCache::new();
14832        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14833
14834        let (result_arc, _) = PipelinedExecutor::realize(graph, silu_id, inputs).expect("realize");
14835        let guard = result_arc.read().unwrap();
14836        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14837            let typed: &[f32] = c.as_slice().unwrap();
14838            // sigmoid(0) = 0.5; silu(0.5) = 0.5 * sigmoid(0.5) ≈ 0.3112
14839            assert!((typed[0] - 0.5 * (1.0 / (1.0 + (-0.5_f32).exp()))).abs() < 1e-6);
14840        }
14841    }
14842
14843    /// E2E: chained unary ops — Const + Sqr + Sqrt should be a noop
14844    /// for non-negative inputs. Exercises the cache reuse path.
14845    #[test]
14846    fn pipelined_realize_chained_unary_sqr_then_sqrt() {
14847        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 4.0, 9.0]);
14848        let graph = Arc::new(RwLock::new(Graph::new()));
14849        let (in_id, sqrt_id) = {
14850            let mut g = graph.write().unwrap();
14851            let in_id = g.push(Node {
14852                op: Op::Const,
14853                inputs: vec![],
14854                shape: Shape::from_dims(&[3]),
14855                dtype: DType::F32,
14856            });
14857            let sqr_id = g.push(Node {
14858                op: Op::Sqr,
14859                inputs: vec![in_id],
14860                shape: Shape::from_dims(&[3]),
14861                dtype: DType::F32,
14862            });
14863            let sqrt_id = g.push(Node {
14864                op: Op::Sqrt,
14865                inputs: vec![sqr_id],
14866                shape: Shape::from_dims(&[3]),
14867                dtype: DType::F32,
14868            });
14869            g.set_target_backend(sqr_id, BackendId::Cpu);
14870            g.set_target_backend(sqrt_id, BackendId::Cpu);
14871            (in_id, sqrt_id)
14872        };
14873        let mut inputs = StorageCache::new();
14874        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14875
14876        let (result_arc, _) = PipelinedExecutor::realize(graph, sqrt_id, inputs).expect("realize");
14877        let guard = result_arc.read().unwrap();
14878        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14879            let typed: &[f32] = c.as_slice().unwrap();
14880            // sqrt(sqr(x)) == |x| == x for non-negative inputs.
14881            assert_eq!(typed, &[1.0, 4.0, 9.0]);
14882        }
14883    }
14884
14885    /// Multi-stage pipelined: Const + Const + Add + Add (chain of
14886    /// two adds). Tests that work items are processed in topo order
14887    /// and intermediate results are cached and reused.
14888    #[test]
14889    fn pipelined_realize_chained_adds() {
14890        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
14891        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
14892        let c_storage = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
14893
14894        let graph = Arc::new(RwLock::new(Graph::new()));
14895        let (a_id, b_id, c_id, ab_id, abc_id) = {
14896            let mut g = graph.write().unwrap();
14897            let a = g.push(Node {
14898                op: Op::Const,
14899                inputs: vec![],
14900                shape: Shape::from_dims(&[2]),
14901                dtype: DType::F32,
14902            });
14903            let b = g.push(Node {
14904                op: Op::Const,
14905                inputs: vec![],
14906                shape: Shape::from_dims(&[2]),
14907                dtype: DType::F32,
14908            });
14909            let c = g.push(Node {
14910                op: Op::Const,
14911                inputs: vec![],
14912                shape: Shape::from_dims(&[2]),
14913                dtype: DType::F32,
14914            });
14915            let ab = g.push(Node {
14916                op: Op::Add,
14917                inputs: vec![a, b],
14918                shape: Shape::from_dims(&[2]),
14919                dtype: DType::F32,
14920            });
14921            let abc = g.push(Node {
14922                op: Op::Add,
14923                inputs: vec![ab, c],
14924                shape: Shape::from_dims(&[2]),
14925                dtype: DType::F32,
14926            });
14927            g.set_target_backend(ab, BackendId::Cpu);
14928            g.set_target_backend(abc, BackendId::Cpu);
14929            (a, b, c, ab, abc)
14930        };
14931
14932        let mut inputs = StorageCache::new();
14933        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
14934        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
14935        inputs.insert(c_id, Arc::new(RwLock::new(c_storage)));
14936
14937        let (result_arc, _) = PipelinedExecutor::realize(graph, abc_id, inputs).expect("realize");
14938        // Suppress unused warning for the intermediate id.
14939        let _ = ab_id;
14940
14941        let guard = result_arc.read().unwrap();
14942        if let fuel_memory::BackendStorage::Cpu(c) = &guard.inner {
14943            let typed: &[f32] = c.as_slice().unwrap();
14944            // (1+10) + 100 = 111;  (2+20) + 200 = 222.
14945            assert_eq!(typed, &[111.0, 222.0]);
14946        }
14947    }
14948
14949    /// E2E: triu(diagonal=0) on a 3×3 matrix.
14950    /// Input:  [1 2 3 / 4 5 6 / 7 8 9]
14951    /// Output: [1 2 3 / 0 5 6 / 0 0 9]
14952    #[test]
14953    fn pipelined_realize_triu_3x3_diag0() {
14954        let storage =
14955            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14956        let graph = Arc::new(RwLock::new(Graph::new()));
14957        let (in_id, out_id) = {
14958            let mut g = graph.write().unwrap();
14959            let in_id = g.push(Node {
14960                op: Op::Const,
14961                inputs: vec![],
14962                shape: Shape::from_dims(&[3, 3]),
14963                dtype: DType::F32,
14964            });
14965            let out_id = g.push(Node {
14966                op: Op::Triu { diagonal: 0 },
14967                inputs: vec![in_id],
14968                shape: Shape::from_dims(&[3, 3]),
14969                dtype: DType::F32,
14970            });
14971            g.set_target_backend(out_id, BackendId::Cpu);
14972            (in_id, out_id)
14973        };
14974        let mut inputs = StorageCache::new();
14975        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
14976        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
14977        let guard = result_arc.read().unwrap();
14978        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
14979            panic!("expected Cpu storage");
14980        };
14981        let out: &[f32] = c.as_slice().unwrap();
14982        assert_eq!(out, &[1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 0.0, 0.0, 9.0,]);
14983    }
14984
14985    /// E2E: tril(diagonal=0) on a 3×3 matrix — the canonical causal mask.
14986    /// Output: [1 0 0 / 4 5 0 / 7 8 9]
14987    #[test]
14988    fn pipelined_realize_tril_3x3_diag0_causal_mask() {
14989        let storage =
14990            fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]);
14991        let graph = Arc::new(RwLock::new(Graph::new()));
14992        let (in_id, out_id) = {
14993            let mut g = graph.write().unwrap();
14994            let in_id = g.push(Node {
14995                op: Op::Const,
14996                inputs: vec![],
14997                shape: Shape::from_dims(&[3, 3]),
14998                dtype: DType::F32,
14999            });
15000            let out_id = g.push(Node {
15001                op: Op::Tril { diagonal: 0 },
15002                inputs: vec![in_id],
15003                shape: Shape::from_dims(&[3, 3]),
15004                dtype: DType::F32,
15005            });
15006            g.set_target_backend(out_id, BackendId::Cpu);
15007            (in_id, out_id)
15008        };
15009        let mut inputs = StorageCache::new();
15010        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15011        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15012        let guard = result_arc.read().unwrap();
15013        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15014            panic!("expected Cpu storage");
15015        };
15016        let out: &[f32] = c.as_slice().unwrap();
15017        assert_eq!(out, &[1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0,]);
15018    }
15019
15020    /// E2E: log_softmax over a 2×3 input. Rows are [1,2,3] and [3,2,1].
15021    /// log_softmax(row) = row - max - log(sum exp(row - max)).
15022    /// Row 0: max=3, exp(-2)+exp(-1)+exp(0) = 0.135+0.368+1.0 = 1.503;
15023    ///        log(1.503) ≈ 0.4076; out = [1-3-0.4076, 2-3-0.4076, 3-3-0.4076]
15024    ///                              = [-2.4076, -1.4076, -0.4076]
15025    /// Row 1 is row 0 reversed: [-0.4076, -1.4076, -2.4076].
15026    #[test]
15027    fn pipelined_realize_log_softmax_last_dim() {
15028        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 3.0, 2.0, 1.0]);
15029        let graph = Arc::new(RwLock::new(Graph::new()));
15030        let (in_id, out_id) = {
15031            let mut g = graph.write().unwrap();
15032            let in_id = g.push(Node {
15033                op: Op::Const,
15034                inputs: vec![],
15035                shape: Shape::from_dims(&[2, 3]),
15036                dtype: DType::F32,
15037            });
15038            let out_id = g.push(Node {
15039                op: Op::LogSoftmaxLastDim,
15040                inputs: vec![in_id],
15041                shape: Shape::from_dims(&[2, 3]),
15042                dtype: DType::F32,
15043            });
15044            g.set_target_backend(out_id, BackendId::Cpu);
15045            (in_id, out_id)
15046        };
15047        let mut inputs = StorageCache::new();
15048        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15049        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15050        let guard = result_arc.read().unwrap();
15051        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15052            panic!("expected Cpu storage");
15053        };
15054        let out: &[f32] = c.as_slice().unwrap();
15055        let expected = [
15056            -2.407_606,
15057            -1.4076059,
15058            -0.40760595_f32,
15059            -0.40760595,
15060            -1.4076059,
15061            -2.407_606,
15062        ];
15063        for (a, b) in out.iter().zip(expected.iter()) {
15064            assert!((a - b).abs() < 1e-5, "log_softmax mismatch: {a} vs {b}");
15065        }
15066        // The exp() of the output should sum to 1 per row.
15067        for row in out.chunks(3) {
15068            let sum: f32 = row.iter().map(|x| x.exp()).sum();
15069            assert!(
15070                (sum - 1.0).abs() < 1e-5,
15071                "softmax(log_softmax) row sum != 1: {sum}"
15072            );
15073        }
15074    }
15075
15076    // --- side-effect roots + destructive cleanup (9c Phase B) -----
15077
15078    /// Side-effect roots get merged into the realize walk even when
15079    /// not reachable from the user's targets. The production trigger
15080    /// is `Op::Release` (emitted by `ResidencyEvictionRule`); this
15081    /// test uses that exact shape.
15082    ///
15083    /// Graph: Const(a) + Const(b) → Add (user target); separate
15084    /// Const(c) → Release(c) (side-effect root, not reachable from
15085    /// Add). After realize_many on `[add]`, the Add should be in the
15086    /// output AND the Release should have fired (verified by the
15087    /// fact that realize succeeded — Op::Release in the walk used to
15088    /// fail compilation pre-Phase B+).
15089    #[test]
15090    fn pipelined_realize_merges_op_release_side_effect_root() {
15091        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0]);
15092        let b = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15093        let c = fuel_memory::from_slice_cpu(&[100.0_f32, 200.0]);
15094        let graph = Arc::new(RwLock::new(Graph::new()));
15095        let (a_id, b_id, c_id, add_id, release_id) = {
15096            let mut g = graph.write().unwrap();
15097            let a = g.push(Node {
15098                op: Op::Const,
15099                inputs: vec![],
15100                shape: Shape::from_dims(&[2]),
15101                dtype: DType::F32,
15102            });
15103            let b = g.push(Node {
15104                op: Op::Const,
15105                inputs: vec![],
15106                shape: Shape::from_dims(&[2]),
15107                dtype: DType::F32,
15108            });
15109            // c is NOT reachable from add; its Release IS marked as
15110            // a side-effect root.
15111            let c = g.push(Node {
15112                op: Op::Const,
15113                inputs: vec![],
15114                shape: Shape::from_dims(&[2]),
15115                dtype: DType::F32,
15116            });
15117            let add = g.push(Node {
15118                op: Op::Add,
15119                inputs: vec![a, b],
15120                shape: Shape::from_dims(&[2]),
15121                dtype: DType::F32,
15122            });
15123            // Production shape: Op::Release on c, marked as
15124            // side-effect root so it fires even though no graph
15125            // node reads its output.
15126            let release = g.push(Node {
15127                op: Op::Release,
15128                inputs: vec![c],
15129                shape: Shape::from_dims(&[0]),
15130                dtype: DType::F32,
15131            });
15132            g.set_target_backend(add, BackendId::Cpu);
15133            g.set_target_backend(release, BackendId::Cpu);
15134            g.add_side_effect_root(release);
15135            (a, b, c, add, release)
15136        };
15137        let mut inputs = StorageCache::new();
15138        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15139        inputs.insert(b_id, Arc::new(RwLock::new(b)));
15140        let c_arc = Arc::new(RwLock::new(c));
15141        let c_arc_external = Arc::clone(&c_arc);
15142        inputs.insert(c_id, c_arc);
15143
15144        // Only `add` is requested. The Release on c is a side-effect
15145        // root that must still fire.
15146        let out = PipelinedExecutor::realize_many(graph, &[add_id], inputs).expect("realize_many");
15147        assert_eq!(out.len(), 1);
15148        let add_guard = out[0].0.read().unwrap();
15149        let fuel_memory::BackendStorage::Cpu(arr) = &add_guard.inner else {
15150            panic!()
15151        };
15152        assert_eq!(arr.as_slice::<f32>().unwrap(), &[11.0, 22.0]);
15153
15154        // The Release's destructive_input cleanup dropped the
15155        // cache's Arc to c. The only Arc to c that survives is the
15156        // external one this test holds — confirms the eviction
15157        // actually freed the cache's reference.
15158        assert_eq!(
15159            Arc::strong_count(&c_arc_external),
15160            1,
15161            "Op::Release should evict the cache's Arc to its source; \
15162             only the test's external clone should remain",
15163        );
15164        let _ = release_id;
15165    }
15166
15167    /// `compile_one` emits a `WorkItemKind::ReleaseMarker` for
15168    /// `Op::Release` with `destructive_input = Some(0)`. Verify
15169    /// the WorkItem shape via a direct compile_one call.
15170    #[test]
15171    fn compile_one_emits_release_marker_with_destructive_input() {
15172        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15173        let (src_id, release_id) = {
15174            let mut g = graph_rc.write().unwrap();
15175            let src = g.push(Node {
15176                op: Op::Const,
15177                inputs: vec![],
15178                shape: Shape::from_dims(&[2]),
15179                dtype: DType::F32,
15180            });
15181            let release = g.push(Node {
15182                op: Op::Release,
15183                inputs: vec![src],
15184                shape: Shape::from_dims(&[0]),
15185                dtype: DType::F32,
15186            });
15187            g.set_target_backend(release, BackendId::Cpu);
15188            (src, release)
15189        };
15190        let g = graph_rc.read().unwrap();
15191        let bindings = crate::dispatch::global_bindings();
15192        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15193        let item = compile_one(
15194            &g,
15195            release_id,
15196            &mut layout_cache,
15197            &bindings,
15198            &SymEnv::default(),
15199        )
15200        .expect("compile_one Op::Release");
15201        assert!(matches!(item.kind, WorkItemKind::ReleaseMarker));
15202        assert_eq!(item.destructive_input, Some(0));
15203        assert_eq!(item.inputs, vec![src_id]);
15204        assert_eq!(
15205            item.elem_count, 0,
15206            "Release output is the zero-element marker"
15207        );
15208    }
15209
15210    // --- Op::Move (executor-unification Session 1, gap 13) --------
15211
15212    /// `compile_one` emits a `WorkItemKind::Move` for `Op::Move` with
15213    /// `destructive_input = Some(0)` and a resolved transfer kernel
15214    /// (binding-table lookup at `(OpKind::Copy, [dt, dt], source
15215    /// backend)` — Move shares Op::Copy's data-movement kernel).
15216    #[test]
15217    fn compile_one_emits_move_with_destructive_input() {
15218        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15219        let (src_id, move_id) = {
15220            let mut g = graph_rc.write().unwrap();
15221            let src = g.push(Node {
15222                op: Op::Const,
15223                inputs: vec![],
15224                shape: Shape::from_dims(&[2]),
15225                dtype: DType::F32,
15226            });
15227            let mv = g.push(Node {
15228                op: Op::Move {
15229                    target: DeviceLocation::Cpu,
15230                },
15231                inputs: vec![src],
15232                shape: Shape::from_dims(&[2]),
15233                dtype: DType::F32,
15234            });
15235            g.set_target_backend(mv, BackendId::Cpu);
15236            (src, mv)
15237        };
15238        let g = graph_rc.read().unwrap();
15239        let bindings = crate::dispatch::global_bindings();
15240        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15241        let item = compile_one(
15242            &g,
15243            move_id,
15244            &mut layout_cache,
15245            &bindings,
15246            &SymEnv::default(),
15247        )
15248        .expect("compile_one Op::Move");
15249        assert!(matches!(
15250            item.kind,
15251            WorkItemKind::Move {
15252                target_location: DeviceLocation::Cpu
15253            },
15254        ));
15255        assert_eq!(item.destructive_input, Some(0), "Move destroys its source");
15256        assert_eq!(item.inputs, vec![src_id]);
15257        assert!(
15258            item.compiled.is_some(),
15259            "Move resolves a transfer kernel at (OpKind::Copy, [dt, dt], source backend)",
15260        );
15261    }
15262
15263    // --- runtime fused op (JIT-adopted Tier-2 kernel) --------------
15264
15265    /// `compile_one` resolves an `Op::Fused(fid, Runtime)` node with
15266    /// `fid.is_runtime()` from the runtime-kernel sidecar (never the
15267    /// binding table): `WorkItemKind::Kernel`, `compiled.op ==
15268    /// OpKind::RuntimeFused`, and the kernel pointer is exactly the one
15269    /// `adopt_runtime_fused` bound.
15270    #[test]
15271    fn compile_one_resolves_runtime_fused_from_the_sidecar() {
15272        fn sentinel_kernel(
15273            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15274            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15275            _layouts: &[Layout],
15276            _params: &crate::kernel::OpParams,
15277        ) -> Result<()> {
15278            Ok(())
15279        }
15280        // A region shape unique to this test (process-global sidecar; see
15281        // runtime_fused_pathfinder's tests for the collision rationale).
15282        let region = fuel_graph::jit::PatternNode::Op {
15283            op: fuel_graph::jit::OpTag::Exp,
15284            attrs: fuel_graph::jit::OpAttrs::default(),
15285            operands: vec![fuel_graph::jit::PatternNode::Op {
15286                op: fuel_graph::jit::OpTag::Sub,
15287                attrs: fuel_graph::jit::OpAttrs::default(),
15288                operands: vec![
15289                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15290                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15291                ],
15292            }],
15293        };
15294        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15295            "test::compile_one::exp_sub",
15296            region,
15297            sentinel_kernel as crate::kernel::KernelRef,
15298            vec![DType::F32, DType::F32, DType::F32],
15299            BackendId::Cpu,
15300        )
15301        .expect("registrable region");
15302
15303        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15304        let fused_id = {
15305            let mut g = graph_rc.write().unwrap();
15306            let s = Shape::from_dims(&[4]);
15307            let a = g.push(Node {
15308                op: Op::Const,
15309                inputs: vec![],
15310                shape: s.clone(),
15311                dtype: DType::F32,
15312            });
15313            let b = g.push(Node {
15314                op: Op::Const,
15315                inputs: vec![],
15316                shape: s.clone(),
15317                dtype: DType::F32,
15318            });
15319            let fused = g.push(Node {
15320                op: Op::Fused(
15321                    rid,
15322                    fuel_graph::registry::FusedOpParams::Runtime {
15323                        scalars: Vec::new(),
15324                    },
15325                ),
15326                inputs: vec![a, b],
15327                shape: s,
15328                dtype: DType::F32,
15329            });
15330            // The arm emitter pins the backend; mirror that here.
15331            g.set_target_backend(fused, BackendId::Cpu);
15332            fused
15333        };
15334        let g = graph_rc.read().unwrap();
15335        let bindings = crate::dispatch::global_bindings();
15336        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15337        let item = compile_one(
15338            &g,
15339            fused_id,
15340            &mut layout_cache,
15341            &bindings,
15342            &SymEnv::default(),
15343        )
15344        .expect("compile_one runtime fused op");
15345        assert!(matches!(item.kind, WorkItemKind::Kernel));
15346        let compiled = item.compiled.expect("resolved a kernel");
15347        assert_eq!(compiled.op, fuel_ir::dispatch::OpKind::RuntimeFused);
15348        assert_eq!(compiled.backend, BackendId::Cpu);
15349        assert!(
15350            std::ptr::fn_addr_eq(compiled.kernel, sentinel_kernel as crate::kernel::KernelRef),
15351            "the kernel pointer is exactly the adopted one",
15352        );
15353        assert!(
15354            layout_cache.contains_key(&fused_id),
15355            "output layout cached for consumers"
15356        );
15357    }
15358
15359    /// The dtype belt-and-suspenders guard: an `Op::Fused(runtime)` node
15360    /// whose per-operand dtypes disagree with the adopted kernel's tuple is
15361    /// a typed error, not a silent wrong-kernel dispatch.
15362    #[test]
15363    fn compile_one_rejects_runtime_fused_dtype_mismatch() {
15364        fn noop_kernel(
15365            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15366            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15367            _layouts: &[Layout],
15368            _params: &crate::kernel::OpParams,
15369        ) -> Result<()> {
15370            Ok(())
15371        }
15372        let region = fuel_graph::jit::PatternNode::Op {
15373            op: fuel_graph::jit::OpTag::Log,
15374            attrs: fuel_graph::jit::OpAttrs::default(),
15375            operands: vec![fuel_graph::jit::PatternNode::Op {
15376                op: fuel_graph::jit::OpTag::Maximum,
15377                attrs: fuel_graph::jit::OpAttrs::default(),
15378                operands: vec![
15379                    fuel_graph::jit::PatternNode::Bind { index: 0 },
15380                    fuel_graph::jit::PatternNode::Bind { index: 1 },
15381                ],
15382            }],
15383        };
15384        // Adopted for F32 operands…
15385        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15386            "test::compile_one::log_maximum",
15387            region,
15388            noop_kernel as crate::kernel::KernelRef,
15389            vec![DType::F32, DType::F32, DType::F32],
15390            BackendId::Cpu,
15391        )
15392        .expect("registrable region");
15393
15394        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15395        let fused_id = {
15396            let mut g = graph_rc.write().unwrap();
15397            let s = Shape::from_dims(&[4]);
15398            // …but the node's operands are F64.
15399            let a = g.push(Node {
15400                op: Op::Const,
15401                inputs: vec![],
15402                shape: s.clone(),
15403                dtype: DType::F64,
15404            });
15405            let b = g.push(Node {
15406                op: Op::Const,
15407                inputs: vec![],
15408                shape: s.clone(),
15409                dtype: DType::F64,
15410            });
15411            let fused = g.push(Node {
15412                op: Op::Fused(
15413                    rid,
15414                    fuel_graph::registry::FusedOpParams::Runtime {
15415                        scalars: Vec::new(),
15416                    },
15417                ),
15418                inputs: vec![a, b],
15419                shape: s,
15420                dtype: DType::F64,
15421            });
15422            g.set_target_backend(fused, BackendId::Cpu);
15423            fused
15424        };
15425        let g = graph_rc.read().unwrap();
15426        let bindings = crate::dispatch::global_bindings();
15427        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15428        let err = match compile_one(
15429            &g,
15430            fused_id,
15431            &mut layout_cache,
15432            &bindings,
15433            &SymEnv::default(),
15434        ) {
15435            Ok(_) => panic!("dtype mismatch must be a typed error"),
15436            Err(e) => e,
15437        };
15438        // Post-fold, the dtype tuple IS the binding key: a mismatch is the
15439        // same honest `NoBackendForOp` miss as an absent kernel — reported
15440        // with the `RuntimeFused` diagnostic op tag, never a wrong-kernel bind.
15441        assert!(
15442            matches!(
15443                err,
15444                fuel_ir::Error::NoBackendForOp {
15445                    op: fuel_ir::dispatch::OpKind::RuntimeFused,
15446                    ..
15447                }
15448            ),
15449            "a dtype mismatch is an honest binding miss: {err}",
15450        );
15451    }
15452
15453    /// A runtime fused node carrying live `Runtime { scalars }` compiles with
15454    /// `OpParams::JitScalars` — the launch channel for the kernel's trailing
15455    /// `p{i}` args. (A param-free node keeps `OpParams::None`, covered by
15456    /// `compile_one_resolves_runtime_fused_from_the_sidecar`.)
15457    #[test]
15458    fn compile_one_maps_runtime_scalars_to_jit_scalars() {
15459        fn noop_kernel(
15460            _inputs: &[Arc<RwLock<fuel_memory::Storage>>],
15461            _outputs: &mut [Arc<RwLock<fuel_memory::Storage>>],
15462            _layouts: &[Layout],
15463            _params: &crate::kernel::OpParams,
15464        ) -> Result<()> {
15465            Ok(())
15466        }
15467        // Unique slot-template region (process-global sidecar).
15468        let region = fuel_graph::jit::PatternNode::Op {
15469            op: fuel_graph::jit::OpTag::Floor,
15470            attrs: fuel_graph::jit::OpAttrs::default(),
15471            operands: vec![fuel_graph::jit::PatternNode::Op {
15472                op: fuel_graph::jit::OpTag::MulScalar,
15473                attrs: fuel_graph::jit::OpAttrs::default(), // open slot
15474                operands: vec![fuel_graph::jit::PatternNode::Bind { index: 0 }],
15475            }],
15476        };
15477        let rid = crate::runtime_fused_kernels::adopt_runtime_fused(
15478            "test::compile_one::floor_mul_scalar",
15479            region,
15480            noop_kernel as crate::kernel::KernelRef,
15481            vec![DType::F32, DType::F32],
15482            BackendId::Cpu,
15483        )
15484        .expect("slot template registrable");
15485
15486        let graph_rc = Arc::new(RwLock::new(Graph::new()));
15487        let fused_id = {
15488            let mut g = graph_rc.write().unwrap();
15489            let s = Shape::from_dims(&[4]);
15490            let x = g.push(Node {
15491                op: Op::Const,
15492                inputs: vec![],
15493                shape: s.clone(),
15494                dtype: DType::F32,
15495            });
15496            let fused = g.push(Node {
15497                op: Op::Fused(
15498                    rid,
15499                    fuel_graph::registry::FusedOpParams::Runtime {
15500                        scalars: vec![3.5, -1.25],
15501                    },
15502                ),
15503                inputs: vec![x],
15504                shape: s,
15505                dtype: DType::F32,
15506            });
15507            g.set_target_backend(fused, BackendId::Cpu);
15508            fused
15509        };
15510        let g = graph_rc.read().unwrap();
15511        let bindings = crate::dispatch::global_bindings();
15512        let mut layout_cache: HashMap<NodeId, Layout> = HashMap::new();
15513        let item = compile_one(
15514            &g,
15515            fused_id,
15516            &mut layout_cache,
15517            &bindings,
15518            &SymEnv::default(),
15519        )
15520        .expect("compile_one runtime fused op with scalars");
15521        let compiled = item.compiled.expect("resolved a kernel");
15522        assert!(
15523            matches!(
15524                &compiled.op_params,
15525                crate::kernel::OpParams::JitScalars { scalars } if scalars == &vec![3.5, -1.25]
15526            ),
15527            "Runtime scalars ride into OpParams::JitScalars, got {:?}",
15528            compiled.op_params,
15529        );
15530    }
15531
15532    /// Move-to-same-device is the degenerate case: per the legacy
15533    /// `GraphExecutor` contract (`Op::Copy | Op::Move` shared arm →
15534    /// `backend.copy_to`) it is a plain copy — fresh storage on the
15535    /// same device, data intact — and the source is still evicted
15536    /// afterward (destructive semantics don't depend on the devices
15537    /// differing).
15538    #[test]
15539    fn pipelined_op_move_same_device_is_plain_copy() {
15540        let src = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15541        let graph = Arc::new(RwLock::new(Graph::new()));
15542        let (src_id, move_id) = {
15543            let mut g = graph.write().unwrap();
15544            let src = g.push(Node {
15545                op: Op::Const,
15546                inputs: vec![],
15547                shape: Shape::from_dims(&[4]),
15548                dtype: DType::F32,
15549            });
15550            let mv = g.push(Node {
15551                op: Op::Move {
15552                    target: DeviceLocation::Cpu,
15553                },
15554                inputs: vec![src],
15555                shape: Shape::from_dims(&[4]),
15556                dtype: DType::F32,
15557            });
15558            g.set_target_backend(mv, BackendId::Cpu);
15559            (src, mv)
15560        };
15561        let src_arc = Arc::new(RwLock::new(src));
15562        let src_arc_external = Arc::clone(&src_arc);
15563        let mut inputs = StorageCache::new();
15564        inputs.insert(src_id, src_arc);
15565
15566        let (out, layout) =
15567            PipelinedExecutor::realize(graph, move_id, inputs).expect("realize Op::Move");
15568        let guard = out.read().unwrap();
15569        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15570            panic!()
15571        };
15572        assert_eq!(
15573            c.as_slice::<f32>().unwrap(),
15574            &[1.0, 2.0, 3.0, 4.0],
15575            "Op::Move output should carry input's data to target",
15576        );
15577        assert!(layout.is_contiguous());
15578        drop(guard);
15579        assert!(
15580            !Arc::ptr_eq(&out, &src_arc_external),
15581            "same-device Move is a plain copy — fresh storage, not an alias",
15582        );
15583        // The realize loop's destructive_input cleanup dropped the
15584        // cache's Arc to the source; only the test's external clone
15585        // survives.
15586        assert_eq!(
15587            Arc::strong_count(&src_arc_external),
15588            1,
15589            "Op::Move should evict the cache's Arc to its source",
15590        );
15591    }
15592
15593    /// The multiple-consumer-source case: a Move must NOT strand
15594    /// another consumer of its source. `execution_plan` (via
15595    /// `derive_ordering`, keyed off `destructive_input`) pins the
15596    /// Move AFTER the sibling reader; the executor's post-Move cache
15597    /// eviction then can't break the reader. Mirrors the legacy
15598    /// `op_move_pinned_after_sibling_reader_via_derive_ordering`
15599    /// test in fuel-graph-router/tests/cross_device.rs.
15600    ///
15601    ///   a   = const [1, 2, 3, 4]
15602    ///   b   = relu(a)        (non-destructive sibling reader)
15603    ///   m   = move(a, Cpu)   (destructive — evicts a once run)
15604    ///   out = add(b, m)      → [2, 4, 6, 8]
15605    #[test]
15606    fn pipelined_op_move_multi_consumer_source_not_stranded() {
15607        let a = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15608        let graph = Arc::new(RwLock::new(Graph::new()));
15609        let (a_id, out_id) = {
15610            let mut g = graph.write().unwrap();
15611            let a = g.push(Node {
15612                op: Op::Const,
15613                inputs: vec![],
15614                shape: Shape::from_dims(&[4]),
15615                dtype: DType::F32,
15616            });
15617            let b = g.push(Node {
15618                op: Op::Relu,
15619                inputs: vec![a],
15620                shape: Shape::from_dims(&[4]),
15621                dtype: DType::F32,
15622            });
15623            let m = g.push(Node {
15624                op: Op::Move {
15625                    target: DeviceLocation::Cpu,
15626                },
15627                inputs: vec![a],
15628                shape: Shape::from_dims(&[4]),
15629                dtype: DType::F32,
15630            });
15631            let out = g.push(Node {
15632                op: Op::Add,
15633                inputs: vec![b, m],
15634                shape: Shape::from_dims(&[4]),
15635                dtype: DType::F32,
15636            });
15637            g.set_target_backend(b, BackendId::Cpu);
15638            g.set_target_backend(m, BackendId::Cpu);
15639            g.set_target_backend(out, BackendId::Cpu);
15640            (a, out)
15641        };
15642        let mut inputs = StorageCache::new();
15643        inputs.insert(a_id, Arc::new(RwLock::new(a)));
15644
15645        let (out, _) = PipelinedExecutor::realize(graph, out_id, inputs)
15646            .expect("realize add(relu(a), move(a))");
15647        let guard = out.read().unwrap();
15648        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15649            panic!()
15650        };
15651        assert_eq!(
15652            c.as_slice::<f32>().unwrap(),
15653            &[2.0, 4.0, 6.0, 8.0],
15654            "relu(a) must run before move(a) evicts a",
15655        );
15656    }
15657
15658    /// A Move whose source is itself in the realize target set must
15659    /// not evict it — the caller asked for the source's storage. The
15660    /// destructive cleanup's `target_set` gate covers Move exactly
15661    /// like Release.
15662    #[test]
15663    fn pipelined_op_move_source_in_target_set_not_evicted() {
15664        let a = fuel_memory::from_slice_cpu(&[5.0_f32, 6.0]);
15665        let graph = Arc::new(RwLock::new(Graph::new()));
15666        let (a_id, move_id) = {
15667            let mut g = graph.write().unwrap();
15668            let a = g.push(Node {
15669                op: Op::Const,
15670                inputs: vec![],
15671                shape: Shape::from_dims(&[2]),
15672                dtype: DType::F32,
15673            });
15674            let mv = g.push(Node {
15675                op: Op::Move {
15676                    target: DeviceLocation::Cpu,
15677                },
15678                inputs: vec![a],
15679                shape: Shape::from_dims(&[2]),
15680                dtype: DType::F32,
15681            });
15682            g.set_target_backend(mv, BackendId::Cpu);
15683            (a, mv)
15684        };
15685        let a_arc = Arc::new(RwLock::new(a));
15686        let a_arc_external = Arc::clone(&a_arc);
15687        let mut inputs = StorageCache::new();
15688        inputs.insert(a_id, a_arc);
15689
15690        let out = PipelinedExecutor::realize_many(graph, &[move_id, a_id], inputs)
15691            .expect("realize_many [move, source]");
15692        assert_eq!(out.len(), 2);
15693        let mv_guard = out[0].0.read().unwrap();
15694        let fuel_memory::BackendStorage::Cpu(c) = &mv_guard.inner else {
15695            panic!()
15696        };
15697        assert_eq!(c.as_slice::<f32>().unwrap(), &[5.0, 6.0]);
15698        assert!(
15699            Arc::ptr_eq(&out[1].0, &a_arc_external),
15700            "requested source must survive the Move's destructive cleanup",
15701        );
15702    }
15703
15704    // --- realize_many (Phase 7.6 step 9c Phase A) ----------------
15705
15706    /// realize_many on empty targets returns an empty Vec — no graph
15707    /// walk, no panic.
15708    #[test]
15709    fn pipelined_realize_many_empty_targets() {
15710        let graph = Arc::new(RwLock::new(Graph::new()));
15711        let inputs = StorageCache::new();
15712        let out = PipelinedExecutor::realize_many(graph, &[], inputs).expect("realize_many");
15713        assert!(out.is_empty());
15714    }
15715
15716    /// realize_many with two independent target chains. Each chain's
15717    /// output is in the cache; the shared topo walk realizes both.
15718    /// Verifies parallel chain handling + return order matches input.
15719    #[test]
15720    fn pipelined_realize_many_two_independent_targets() {
15721        let lhs = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15722        let rhs = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15723        let graph = Arc::new(RwLock::new(Graph::new()));
15724        let (lhs_id, rhs_id, add_id, mul_id) = {
15725            let mut g = graph.write().unwrap();
15726            let lhs = g.push(Node {
15727                op: Op::Const,
15728                inputs: vec![],
15729                shape: Shape::from_dims(&[3]),
15730                dtype: DType::F32,
15731            });
15732            let rhs = g.push(Node {
15733                op: Op::Const,
15734                inputs: vec![],
15735                shape: Shape::from_dims(&[3]),
15736                dtype: DType::F32,
15737            });
15738            let add = g.push(Node {
15739                op: Op::Add,
15740                inputs: vec![lhs, rhs],
15741                shape: Shape::from_dims(&[3]),
15742                dtype: DType::F32,
15743            });
15744            let mul = g.push(Node {
15745                op: Op::Mul,
15746                inputs: vec![lhs, rhs],
15747                shape: Shape::from_dims(&[3]),
15748                dtype: DType::F32,
15749            });
15750            g.set_target_backend(add, BackendId::Cpu);
15751            g.set_target_backend(mul, BackendId::Cpu);
15752            (lhs, rhs, add, mul)
15753        };
15754        let mut inputs = StorageCache::new();
15755        inputs.insert(lhs_id, Arc::new(RwLock::new(lhs)));
15756        inputs.insert(rhs_id, Arc::new(RwLock::new(rhs)));
15757
15758        // Pass mul first to confirm return order matches targets order
15759        // (not graph order — graph order would put add first).
15760        let out = PipelinedExecutor::realize_many(graph, &[mul_id, add_id], inputs)
15761            .expect("realize_many");
15762        assert_eq!(out.len(), 2);
15763
15764        let mul_guard = out[0].0.read().unwrap();
15765        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15766            panic!()
15767        };
15768        assert_eq!(c.as_slice::<f32>().unwrap(), &[10.0, 40.0, 90.0]);
15769
15770        let add_guard = out[1].0.read().unwrap();
15771        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15772            panic!()
15773        };
15774        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15775    }
15776
15777    /// realize_many with the same NodeId twice — caller asking for
15778    /// the same output twice. Both outputs are the same Arc (cheap).
15779    #[test]
15780    fn pipelined_realize_many_duplicate_target_returns_same_arc() {
15781        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15782        let graph = Arc::new(RwLock::new(Graph::new()));
15783        let (in_id, neg_id) = {
15784            let mut g = graph.write().unwrap();
15785            let in_id = g.push(Node {
15786                op: Op::Const,
15787                inputs: vec![],
15788                shape: Shape::from_dims(&[3]),
15789                dtype: DType::F32,
15790            });
15791            let neg = g.push(Node {
15792                op: Op::Neg,
15793                inputs: vec![in_id],
15794                shape: Shape::from_dims(&[3]),
15795                dtype: DType::F32,
15796            });
15797            g.set_target_backend(neg, BackendId::Cpu);
15798            (in_id, neg)
15799        };
15800        let mut inputs = StorageCache::new();
15801        inputs.insert(in_id, Arc::new(RwLock::new(storage)));
15802
15803        let out = PipelinedExecutor::realize_many(graph, &[neg_id, neg_id], inputs)
15804            .expect("realize_many");
15805        assert_eq!(out.len(), 2);
15806        assert!(
15807            Arc::ptr_eq(&out[0].0, &out[1].0),
15808            "duplicate target should share the same storage Arc",
15809        );
15810    }
15811
15812    /// realize_many with shared upstream nodes evaluates the shared
15813    /// chunk exactly once. Two targets `f = a + b` and `g = (a + b) * a`
15814    /// — `a + b` is computed once.
15815    #[test]
15816    fn pipelined_realize_many_shared_subgraph_evaluates_once() {
15817        let a_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
15818        let b_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0, 30.0]);
15819        let graph = Arc::new(RwLock::new(Graph::new()));
15820        let (a_id, b_id, add_id, mul_id) = {
15821            let mut g = graph.write().unwrap();
15822            let a = g.push(Node {
15823                op: Op::Const,
15824                inputs: vec![],
15825                shape: Shape::from_dims(&[3]),
15826                dtype: DType::F32,
15827            });
15828            let b = g.push(Node {
15829                op: Op::Const,
15830                inputs: vec![],
15831                shape: Shape::from_dims(&[3]),
15832                dtype: DType::F32,
15833            });
15834            let add = g.push(Node {
15835                op: Op::Add,
15836                inputs: vec![a, b],
15837                shape: Shape::from_dims(&[3]),
15838                dtype: DType::F32,
15839            });
15840            let mul = g.push(Node {
15841                op: Op::Mul,
15842                inputs: vec![add, a],
15843                shape: Shape::from_dims(&[3]),
15844                dtype: DType::F32,
15845            });
15846            g.set_target_backend(add, BackendId::Cpu);
15847            g.set_target_backend(mul, BackendId::Cpu);
15848            (a, b, add, mul)
15849        };
15850        let mut inputs = StorageCache::new();
15851        inputs.insert(a_id, Arc::new(RwLock::new(a_storage)));
15852        inputs.insert(b_id, Arc::new(RwLock::new(b_storage)));
15853
15854        let out = PipelinedExecutor::realize_many(graph, &[add_id, mul_id], inputs)
15855            .expect("realize_many");
15856        assert_eq!(out.len(), 2);
15857
15858        let add_guard = out[0].0.read().unwrap();
15859        let fuel_memory::BackendStorage::Cpu(c) = &add_guard.inner else {
15860            panic!()
15861        };
15862        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 22.0, 33.0]);
15863
15864        let mul_guard = out[1].0.read().unwrap();
15865        let fuel_memory::BackendStorage::Cpu(c) = &mul_guard.inner else {
15866            panic!()
15867        };
15868        // (a + b) * a = [11*1, 22*2, 33*3] = [11, 44, 99].
15869        assert_eq!(c.as_slice::<f32>().unwrap(), &[11.0, 44.0, 99.0]);
15870    }
15871
15872    /// E2E: masked_fill with -inf — the attention masking pattern.
15873    /// x = [1, 2, 3, 4]; mask = [0, 1, 0, 1]; value = -1000.
15874    /// out = [1, -1000, 3, -1000].
15875    #[test]
15876    fn pipelined_realize_masked_fill_attention_pattern() {
15877        let x_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0]);
15878        let mut mask_storage = fuel_memory::from_slice_cpu(&[0u8, 1, 0, 1]);
15879        mask_storage.dtype = DType::Bool; // GAP-168(c): a Bool mask, not U8 bytes
15880        let graph = Arc::new(RwLock::new(Graph::new()));
15881        let (x_id, mask_id, out_id) = {
15882            let mut g = graph.write().unwrap();
15883            let x = g.push(Node {
15884                op: Op::Const,
15885                inputs: vec![],
15886                shape: Shape::from_dims(&[4]),
15887                dtype: DType::F32,
15888            });
15889            let mask = g.push(Node {
15890                op: Op::Const,
15891                inputs: vec![],
15892                shape: Shape::from_dims(&[4]),
15893                dtype: DType::Bool,
15894            });
15895            let out = g.push(Node {
15896                op: Op::MaskedFill {
15897                    value: fuel_ir::Scalar::F32(-1000.0),
15898                },
15899                inputs: vec![x, mask],
15900                shape: Shape::from_dims(&[4]),
15901                dtype: DType::F32,
15902            });
15903            g.set_target_backend(out, BackendId::Cpu);
15904            (x, mask, out)
15905        };
15906        let mut inputs = StorageCache::new();
15907        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
15908        inputs.insert(mask_id, Arc::new(RwLock::new(mask_storage)));
15909        let (result_arc, _) = PipelinedExecutor::realize(graph, out_id, inputs).expect("realize");
15910        let guard = result_arc.read().unwrap();
15911        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15912            panic!("expected Cpu storage");
15913        };
15914        let out: &[f32] = c.as_slice().unwrap();
15915        assert_eq!(out, &[1.0, -1000.0, 3.0, -1000.0]);
15916    }
15917
15918    // ---- WriteSlice (Phase 7.6 step 9c E.3.2) -------------------------------
15919
15920    /// E2E: pipelined realize of `Op::WriteSlice` writing a [1, 3, 2]
15921    /// source slab into a [4, 3, 2] destination at axis-0 row 2 — the
15922    /// canonical KV-cache append shape.
15923    #[test]
15924    fn pipelined_realize_write_slice_kv_cache_append() {
15925        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 24]);
15926        let src_storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0, 4.0, 5.0, 6.0]);
15927        let graph = Arc::new(RwLock::new(Graph::new()));
15928        let (dest_id, src_id, ws_id) = {
15929            let mut g = graph.write().unwrap();
15930            let dest = g.push(Node {
15931                op: Op::Const,
15932                inputs: vec![],
15933                shape: Shape::from_dims(&[4, 3, 2]),
15934                dtype: DType::F32,
15935            });
15936            let src = g.push(Node {
15937                op: Op::Const,
15938                inputs: vec![],
15939                shape: Shape::from_dims(&[1, 3, 2]),
15940                dtype: DType::F32,
15941            });
15942            let ws = g.push(Node {
15943                op: Op::WriteSlice {
15944                    ranges: vec![(2, 3), (0, 3), (0, 2)],
15945                    dyn_offset: None,
15946                },
15947                inputs: vec![dest, src],
15948                shape: Shape::from_dims(&[4, 3, 2]), // adopts dest shape
15949                dtype: DType::F32,
15950            });
15951            g.set_target_backend(ws, BackendId::Cpu);
15952            (dest, src, ws)
15953        };
15954        let mut inputs = StorageCache::new();
15955        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
15956        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
15957        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
15958        let guard = result_arc.read().unwrap();
15959        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
15960            panic!("expected Cpu storage");
15961        };
15962        let out: &[f32] = c.as_slice().unwrap();
15963        let expected = [
15964            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,
15965            6.0, // row 2 = source
15966            0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
15967        ];
15968        assert_eq!(out, &expected);
15969    }
15970
15971    /// E2E: pipelined realize of `Op::WriteSlice` adopts the
15972    /// destination's Storage Arc as the output slot (in-place
15973    /// alias) — the resulting Arc points to the SAME bytes the
15974    /// destination was constructed from.
15975    #[test]
15976    fn pipelined_realize_write_slice_aliases_dest_storage() {
15977        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
15978        let src_storage = fuel_memory::from_slice_cpu(&[10.0_f32, 20.0]);
15979        let graph = Arc::new(RwLock::new(Graph::new()));
15980        let (dest_id, src_id, ws_id, dest_arc_external) = {
15981            let mut g = graph.write().unwrap();
15982            let dest = g.push(Node {
15983                op: Op::Const,
15984                inputs: vec![],
15985                shape: Shape::from_dims(&[3, 2]),
15986                dtype: DType::F32,
15987            });
15988            let src = g.push(Node {
15989                op: Op::Const,
15990                inputs: vec![],
15991                shape: Shape::from_dims(&[1, 2]),
15992                dtype: DType::F32,
15993            });
15994            let ws = g.push(Node {
15995                op: Op::WriteSlice {
15996                    ranges: vec![(1, 2), (0, 2)],
15997                    dyn_offset: None,
15998                },
15999                inputs: vec![dest, src],
16000                shape: Shape::from_dims(&[3, 2]),
16001                dtype: DType::F32,
16002            });
16003            g.set_target_backend(ws, BackendId::Cpu);
16004            let arc = Arc::new(RwLock::new(dest_storage));
16005            (dest, src, ws, arc)
16006        };
16007        let mut inputs = StorageCache::new();
16008        inputs.insert(dest_id, Arc::clone(&dest_arc_external));
16009        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16010        let (result_arc, _) = PipelinedExecutor::realize(graph, ws_id, inputs).expect("realize");
16011        // Bytes were written into the same Arc the caller held —
16012        // the WriteSlice op aliases dest's Storage Arc, not allocates
16013        // a fresh buffer.
16014        assert!(
16015            Arc::ptr_eq(&result_arc, &dest_arc_external),
16016            "WriteSlice output Arc must be the same Arc as the destination's"
16017        );
16018        let guard = dest_arc_external.read().unwrap();
16019        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16020            panic!("expected Cpu storage");
16021        };
16022        let out: &[f32] = c.as_slice().unwrap();
16023        assert_eq!(out, &[0.0, 0.0, 10.0, 20.0, 0.0, 0.0]);
16024    }
16025
16026    // ---- WriteSlice dynamic offset (Phase D symbolic extents) ---------------
16027
16028    /// E2E: pipelined realize of `Op::WriteSlice` with a runtime start
16029    /// offset (`dyn_offset`) resolved through a per-pass `SymEnv`. The
16030    /// width-2 source slab lands at the bound offset (3), not the static
16031    /// `ranges[0].0` placeholder (0) — the persistent-decode KV-cache
16032    /// write at a per-token `cached_len`.
16033    #[test]
16034    fn pipelined_realize_write_slice_dynamic_offset() {
16035        use fuel_ir::{DynScalar, SymId};
16036        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16037        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16038        let graph = Arc::new(RwLock::new(Graph::new()));
16039        let sym = SymId(0);
16040        let (dest_id, src_id, ws_id) = {
16041            let mut g = graph.write().unwrap();
16042            let dest = g.push(Node {
16043                op: Op::Const,
16044                inputs: vec![],
16045                shape: Shape::from_dims(&[6]),
16046                dtype: DType::F32,
16047            });
16048            let src = g.push(Node {
16049                op: Op::Const,
16050                inputs: vec![],
16051                shape: Shape::from_dims(&[2]),
16052                dtype: DType::F32,
16053            });
16054            let ws = g.push(Node {
16055                // ranges[0] = (0, 2): the start is a placeholder (ignored —
16056                // overridden by dyn_offset); only the width (2) is read.
16057                op: Op::WriteSlice {
16058                    ranges: vec![(0, 2)],
16059                    dyn_offset: Some((0, DynScalar::Sym(sym))),
16060                },
16061                inputs: vec![dest, src],
16062                shape: Shape::from_dims(&[6]),
16063                dtype: DType::F32,
16064            });
16065            g.set_target_backend(ws, BackendId::Cpu);
16066            (dest, src, ws)
16067        };
16068        let mut inputs = StorageCache::new();
16069        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16070        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16071
16072        // Bind cached_len = 3: the slab must land at indices [3, 4].
16073        let mut env = SymEnv::new();
16074        env.bind(sym, 3).unwrap();
16075
16076        let (result_arc, _) = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env)
16077            .expect("realize_with_env");
16078        let guard = result_arc.read().unwrap();
16079        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16080            panic!("expected Cpu storage");
16081        };
16082        let out: &[f32] = c.as_slice().unwrap();
16083        assert_eq!(
16084            out,
16085            &[0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
16086            "slab must land at the SymEnv-bound offset 3, not the static placeholder 0",
16087        );
16088    }
16089
16090    /// Increment 2a — the data-determined bind seam. After
16091    /// `Op::NonZeroIndices` realizes, the executor reads its runtime count
16092    /// from bundle slot 1 and PUBLISHES it into the produced `SymEnv` under
16093    /// `count_sym`. This is the first op to bind a *data-determined* symbol
16094    /// mid-realize (all prior binds are host-known before realize) — the
16095    /// keystone capability for SSM decode / MoE sparsity / MLA KV.
16096    #[test]
16097    fn pipelined_realize_nonzero_indices_publishes_count() {
16098        use fuel_ir::SymId;
16099        use fuel_ir::storage::{OutputViewSpec, compose_bundle};
16100        // flat [0,1,0,1,1,0] → 3 nonzeros at 1,3,4; capacity 6.
16101        let x_storage = fuel_memory::from_slice_cpu(&[0.0_f32, 1.0, 0.0, 1.0, 1.0, 0.0]);
16102        let graph = Arc::new(RwLock::new(Graph::new()));
16103        let count_sym = SymId(0);
16104        let (x_id, nzi_id) = {
16105            let mut g = graph.write().unwrap();
16106            let x = g.push(Node {
16107                op: Op::Const,
16108                inputs: vec![],
16109                shape: Shape::from_dims(&[2, 3]),
16110                dtype: DType::F32,
16111            });
16112            let capacity = 6usize;
16113            let idx_shape = Shape::from_dims(&[capacity]);
16114            let cnt_shape = Shape::from_dims(&[1]);
16115            let specs = vec![
16116                OutputViewSpec {
16117                    dtype: DType::U32,
16118                    shape: idx_shape.clone(),
16119                    layout: Layout::contiguous(idx_shape.clone()),
16120                    name: Some("indices"),
16121                },
16122                OutputViewSpec {
16123                    dtype: DType::U32,
16124                    shape: cnt_shape.clone(),
16125                    layout: Layout::contiguous(cnt_shape),
16126                    name: Some("count"),
16127                },
16128            ];
16129            let (_bytes, views) = compose_bundle(&specs).unwrap();
16130            let nzi = g.push(Node {
16131                op: Op::NonZeroIndices { count_sym },
16132                inputs: vec![x],
16133                shape: idx_shape,
16134                dtype: DType::U32,
16135            });
16136            g.set_output_views(nzi, Arc::from(views.into_boxed_slice()))
16137                .unwrap();
16138            g.set_target_backend(nzi, BackendId::Cpu);
16139            (x, nzi)
16140        };
16141        let mut inputs = StorageCache::new();
16142        inputs.insert(x_id, Arc::new(RwLock::new(x_storage)));
16143
16144        let (_arc, _layout, produced) =
16145            PipelinedExecutor::realize_with_env_producing(graph, nzi_id, inputs, SymEnv::new())
16146                .expect("realize_with_env_producing");
16147
16148        assert_eq!(
16149            produced.get(count_sym),
16150            Some(3),
16151            "the executor must publish the data-determined nonzero count into the SymEnv",
16152        );
16153    }
16154
16155    /// A `dyn_offset` whose symbol is unbound in the `SymEnv` surfaces a
16156    /// typed error at realize (never a panic).
16157    #[test]
16158    fn pipelined_realize_write_slice_dynamic_offset_unbound_errors() {
16159        use fuel_ir::{DynScalar, SymId};
16160        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16161        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16162        let graph = Arc::new(RwLock::new(Graph::new()));
16163        let (dest_id, src_id, ws_id) = {
16164            let mut g = graph.write().unwrap();
16165            let dest = g.push(Node {
16166                op: Op::Const,
16167                inputs: vec![],
16168                shape: Shape::from_dims(&[6]),
16169                dtype: DType::F32,
16170            });
16171            let src = g.push(Node {
16172                op: Op::Const,
16173                inputs: vec![],
16174                shape: Shape::from_dims(&[2]),
16175                dtype: DType::F32,
16176            });
16177            let ws = g.push(Node {
16178                op: Op::WriteSlice {
16179                    ranges: vec![(0, 2)],
16180                    dyn_offset: Some((0, DynScalar::Sym(SymId(0)))),
16181                },
16182                inputs: vec![dest, src],
16183                shape: Shape::from_dims(&[6]),
16184                dtype: DType::F32,
16185            });
16186            g.set_target_backend(ws, BackendId::Cpu);
16187            (dest, src, ws)
16188        };
16189        let mut inputs = StorageCache::new();
16190        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16191        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16192        // Empty env — the symbol is unbound.
16193        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, SymEnv::new());
16194        assert!(
16195            result.is_err(),
16196            "unbound dyn_offset symbol must surface a typed error, not a panic",
16197        );
16198    }
16199
16200    /// A runtime offset whose resolved slab runs past the destination
16201    /// capacity errors at realize (never an out-of-bounds write).
16202    #[test]
16203    fn pipelined_realize_write_slice_dynamic_offset_out_of_capacity_errors() {
16204        use fuel_ir::{DynScalar, SymId};
16205        let dest_storage = fuel_memory::from_slice_cpu(&[0.0_f32; 6]);
16206        let src_storage = fuel_memory::from_slice_cpu(&[7.0_f32, 8.0]);
16207        let graph = Arc::new(RwLock::new(Graph::new()));
16208        let sym = SymId(0);
16209        let (dest_id, src_id, ws_id) = {
16210            let mut g = graph.write().unwrap();
16211            let dest = g.push(Node {
16212                op: Op::Const,
16213                inputs: vec![],
16214                shape: Shape::from_dims(&[6]),
16215                dtype: DType::F32,
16216            });
16217            let src = g.push(Node {
16218                op: Op::Const,
16219                inputs: vec![],
16220                shape: Shape::from_dims(&[2]),
16221                dtype: DType::F32,
16222            });
16223            let ws = g.push(Node {
16224                op: Op::WriteSlice {
16225                    ranges: vec![(0, 2)],
16226                    dyn_offset: Some((0, DynScalar::Sym(sym))),
16227                },
16228                inputs: vec![dest, src],
16229                shape: Shape::from_dims(&[6]),
16230                dtype: DType::F32,
16231            });
16232            g.set_target_backend(ws, BackendId::Cpu);
16233            (dest, src, ws)
16234        };
16235        let mut inputs = StorageCache::new();
16236        inputs.insert(dest_id, Arc::new(RwLock::new(dest_storage)));
16237        inputs.insert(src_id, Arc::new(RwLock::new(src_storage)));
16238        // offset 5 + width 2 = 7 > capacity 6.
16239        let mut env = SymEnv::new();
16240        env.bind(sym, 5).unwrap();
16241        let result = PipelinedExecutor::realize_with_env(graph, ws_id, inputs, env);
16242        assert!(
16243            result.is_err(),
16244            "resolved slab past destination capacity must surface a typed error",
16245        );
16246    }
16247
16248    /// Regression for the PipelinedExecutor ordering-integration session.
16249    ///
16250    /// Graph: `x = Const`, `step_x = Step(x)`, `y = SigmoidInplace(x)`.
16251    /// `Step` and `SigmoidInplace` are both readers of `x`; `Step` is
16252    /// non-destructive, `SigmoidInplace` mutates `x`'s storage. The
16253    /// correct semantic is for `Step` to read PRE-mutation bytes.
16254    ///
16255    /// Pre-this-session (raw `topo_order_multi`): the two are siblings
16256    /// in topo order and the tie-break is unspecified — `SigmoidInplace`
16257    /// could run first, making `step_x` see post-sigmoid bytes
16258    /// (`[1, 1, 1, 1]` because every sigmoid output is positive).
16259    ///
16260    /// Post-this-session: `execution_plan` consults `derive_ordering`,
16261    /// which pins `SigmoidInplace` AFTER every other reader of `x`.
16262    /// `step_x` deterministically sees `x` and is `[1, 0, 1, 0]`.
16263    #[test]
16264    fn pipelined_inplace_with_multiple_readers_orders_correctly() {
16265        use fuel_ir::Shape;
16266        let data = [1.0_f32, -2.0, 3.0, -4.0];
16267        let src_storage = fuel_memory::from_slice_cpu(&data);
16268
16269        let graph = Arc::new(RwLock::new(Graph::new()));
16270        let (x_id, step_id, sig_id) = {
16271            let mut g = graph.write().unwrap();
16272            let x = g.push(Node {
16273                op: Op::Const,
16274                inputs: vec![],
16275                shape: Shape::from_dims(&[4]),
16276                dtype: DType::F32,
16277            });
16278            let step = g.push(Node {
16279                op: Op::Step,
16280                inputs: vec![x],
16281                shape: Shape::from_dims(&[4]),
16282                dtype: DType::F32,
16283            });
16284            let sig = g.push(Node {
16285                op: Op::SigmoidInplace,
16286                inputs: vec![x],
16287                shape: Shape::from_dims(&[4]),
16288                dtype: DType::F32,
16289            });
16290            g.set_target_backend(step, BackendId::Cpu);
16291            g.set_target_backend(sig, BackendId::Cpu);
16292            (x, step, sig)
16293        };
16294
16295        let mut cache = StorageCache::new();
16296        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16297
16298        let results = PipelinedExecutor::realize_many(graph, &[step_id, sig_id], cache)
16299            .expect("realize_many");
16300
16301        // step_x must reflect pre-mutation x: sign of [1, -2, 3, -4] →
16302        // [1, 0, 1, 0]. If the executor ran SigmoidInplace first, step
16303        // would see all-positive sigmoid outputs and produce [1, 1, 1, 1].
16304        let step_guard = results[0].0.read().unwrap();
16305        let fuel_memory::BackendStorage::Cpu(c) = &step_guard.inner else {
16306            panic!("expected Cpu storage for step output");
16307        };
16308        let step_out: &[f32] = c.as_slice().expect("f32 cast");
16309        assert_eq!(
16310            step_out,
16311            &[1.0_f32, 0.0, 1.0, 0.0],
16312            "Step must run before SigmoidInplace; got post-mutation bytes"
16313        );
16314        drop(step_guard);
16315
16316        // SigmoidInplace's output Arc IS the mutated cache entry — bytes
16317        // approximate sigmoid([1, -2, 3, -4]).
16318        let sig_guard = results[1].0.read().unwrap();
16319        let fuel_memory::BackendStorage::Cpu(c) = &sig_guard.inner else {
16320            panic!("expected Cpu storage for sigmoid output");
16321        };
16322        let sig_out: &[f32] = c.as_slice().expect("f32 cast");
16323        let sig_ref = [
16324            1.0_f32 / (1.0 + (-1.0_f32).exp()),
16325            1.0_f32 / (1.0 + (2.0_f32).exp()),
16326            1.0_f32 / (1.0 + (-3.0_f32).exp()),
16327            1.0_f32 / (1.0 + (4.0_f32).exp()),
16328        ];
16329        for (got, want) in sig_out.iter().zip(sig_ref.iter()) {
16330            assert!((got - want).abs() < 1e-6, "sigmoid: got {got}, want {want}");
16331        }
16332    }
16333
16334    /// Regression for the PipelinedExecutor ordering-integration session.
16335    ///
16336    /// Canonical residual-connection pattern:
16337    ///   `x = Const`, `y = ReluInplace(x)`, `z = Add(y, x)`.
16338    ///
16339    /// Pre-this-session: `derive_ordering` was never run, so the cycle
16340    /// (Add must precede ReluInplace per ordering edge; Add must follow
16341    /// ReluInplace per data-flow edge through y) was undetected. The
16342    /// executor produced `z = relu(x) + relu(x) = [2, 0, 6, 0]` —
16343    /// silently wrong.
16344    ///
16345    /// Post-this-session: `insert_safety_copies` runs before
16346    /// `execution_plan`, inserts `Op::Copy(x) → x_safe`, rewires Add's
16347    /// `x` input to `x_safe`. Result: `z = relu(x) + x = [2, -2, 6, -4]`.
16348    #[test]
16349    fn pipelined_residual_connection_inserts_safety_copy() {
16350        use fuel_ir::Shape;
16351        let data = [1.0_f32, -2.0, 3.0, -4.0];
16352        let src_storage = fuel_memory::from_slice_cpu(&data);
16353
16354        let graph = Arc::new(RwLock::new(Graph::new()));
16355        let (x_id, _y_id, z_id) = {
16356            let mut g = graph.write().unwrap();
16357            let x = g.push(Node {
16358                op: Op::Const,
16359                inputs: vec![],
16360                shape: Shape::from_dims(&[4]),
16361                dtype: DType::F32,
16362            });
16363            let y = g.push(Node {
16364                op: Op::ReluInplace,
16365                inputs: vec![x],
16366                shape: Shape::from_dims(&[4]),
16367                dtype: DType::F32,
16368            });
16369            let z = g.push(Node {
16370                op: Op::Add,
16371                inputs: vec![y, x],
16372                shape: Shape::from_dims(&[4]),
16373                dtype: DType::F32,
16374            });
16375            g.set_target_backend(y, BackendId::Cpu);
16376            g.set_target_backend(z, BackendId::Cpu);
16377            (x, y, z)
16378        };
16379
16380        let mut cache = StorageCache::new();
16381        cache.insert(x_id, Arc::new(RwLock::new(src_storage)));
16382
16383        let (result_arc, _) = PipelinedExecutor::realize(graph, z_id, cache)
16384            .expect("realize z — insert_safety_copies must break the cycle");
16385
16386        let guard = result_arc.read().unwrap();
16387        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16388            panic!("expected Cpu storage");
16389        };
16390        let got: &[f32] = c.as_slice().expect("f32 cast");
16391        assert_eq!(
16392            got,
16393            &[2.0_f32, -2.0, 6.0, -4.0],
16394            "Add must read pre-mutation x via the inserted safety copy"
16395        );
16396    }
16397
16398    // ------------------------------------------------------------------
16399    // Item 3 end-to-end: SelectiveScan through the bundled-output
16400    // PipelinedExecutor path. The producer allocates bundled
16401    // (y_bytes + last_state_bytes), the kernel writes both slots,
16402    // and the bundled-tuple builder returns each via Op::View.
16403    // ------------------------------------------------------------------
16404
16405    fn cpu_const_f32(
16406        graph: &Arc<RwLock<Graph>>,
16407        cache: &mut StorageCache,
16408        data: &[f32],
16409        dims: &[usize],
16410    ) -> NodeId {
16411        let id = {
16412            let mut g = graph.write().unwrap();
16413            g.push(Node {
16414                op: Op::Const,
16415                inputs: vec![],
16416                shape: Shape::from_dims(dims),
16417                dtype: DType::F32,
16418            })
16419        };
16420        cache.insert(id, Arc::new(RwLock::new(fuel_memory::from_slice_cpu(data))));
16421        id
16422    }
16423
16424    /// `selective_scan_bundled` realizes both `y` and `last_state` in
16425    /// a single `realize_many` pass; the Views project the same
16426    /// producer's bundled Storage Arc and the numerics match the
16427    /// hand-computed single-step kernel test (b=1,s=1,d=1,k=1).
16428    #[test]
16429    fn pipelined_realize_selective_scan_bundled_produces_y_and_last_state() {
16430        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16431        let mut cache = StorageCache::new();
16432
16433        let u_id = cpu_const_f32(&graph, &mut cache, &[3.0], &[1, 1, 1]);
16434        let delta_id = cpu_const_f32(&graph, &mut cache, &[1.0], &[1, 1, 1]);
16435        let a_id = cpu_const_f32(&graph, &mut cache, &[-1.0], &[1, 1]);
16436        let b_id = cpu_const_f32(&graph, &mut cache, &[2.0], &[1, 1, 1]);
16437        let c_id = cpu_const_f32(&graph, &mut cache, &[0.5], &[1, 1, 1]);
16438
16439        let (y_id, last_state_id) = {
16440            let u_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), u_id);
16441            let delta_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), delta_id);
16442            let a_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
16443            let b_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
16444            let c_t = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), c_id);
16445            let (y, last_state) = u_t
16446                .selective_scan_bundled(&delta_t, &a_t, &b_t, &c_t, /* delta_softplus */ false)
16447                .expect("selective_scan_bundled");
16448            (y.id(), last_state.id())
16449        };
16450        // Set target_backend on the producer (View nodes inherit it).
16451        {
16452            let mut g = graph.write().unwrap();
16453            let producer = g.node(y_id).inputs[0];
16454            g.set_target_backend(producer, BackendId::Cpu);
16455        }
16456
16457        let outputs =
16458            PipelinedExecutor::realize_many(Arc::clone(&graph), &[y_id, last_state_id], cache)
16459                .expect("realize_many");
16460        let (y_arc, y_layout) = outputs[0].clone();
16461        let (last_state_arc, last_state_layout) = outputs[1].clone();
16462
16463        // Both Views project the same bundled producer Storage Arc.
16464        assert!(
16465            Arc::ptr_eq(&y_arc, &last_state_arc),
16466            "y and last_state Views project the SAME bundled producer Storage",
16467        );
16468
16469        // Hand-computed numerics (single-step recurrence):
16470        // h[0,0,0] = exp(1.0 * -1.0) * 0 + 1.0 * 2.0 * 3.0 = 6.0
16471        // y[0,0,0] = h * c = 6.0 * 0.5 = 3.0
16472        // last_state[0,0,0] = h = 6.0
16473        let guard = y_arc.read().unwrap();
16474        let fuel_memory::BackendStorage::Cpu(c_bytes) = &guard.inner else {
16475            panic!("expected Cpu storage");
16476        };
16477        let typed: &[f32] = c_bytes.as_slice().expect("f32 cast");
16478        assert_eq!(y_layout.start_offset(), 0);
16479        let y_value = typed[y_layout.start_offset()];
16480        assert!((y_value - 3.0).abs() < 1e-5, "y expected 3.0 got {y_value}");
16481        assert_eq!(
16482            last_state_layout.start_offset(),
16483            1,
16484            "slot 1 byte_offset 4 / sizeof(f32) = 1",
16485        );
16486        let ls_value = typed[last_state_layout.start_offset()];
16487        assert!(
16488            (ls_value - 6.0).abs() < 1e-5,
16489            "last_state expected 6.0 got {ls_value}"
16490        );
16491    }
16492
16493    /// E2E (row 172 item 2): TopKLastDim f32 on CPU through the bundled
16494    /// two-slot output. Row 0 has a NaN and tied values, row 1 distinct values;
16495    /// k = 3. The `values` View reads slot 0 and the `indices` View slot 1 of the
16496    /// SAME bundled storage (the indices slot starts 4-byte aligned).
16497    #[test]
16498    fn pipelined_realize_top_k_last_dim_bundled_values_and_indices() {
16499        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16500        let mut cache = StorageCache::new();
16501        let x_id = cpu_const_f32(
16502            &graph,
16503            &mut cache,
16504            &[1.0, 5.0, f32::NAN, 5.0, 2.0, 3.0, 3.0, 3.0, -1.0, 9.0],
16505            &[2, 5],
16506        );
16507        let (v_id, i_id) = {
16508            let x = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), x_id);
16509            let (v, i) = x.top_k_last_dim(3).expect("top_k_last_dim");
16510            (v.id(), i.id())
16511        };
16512        {
16513            let mut g = graph.write().unwrap();
16514            let producer = g.node(v_id).inputs[0];
16515            g.set_target_backend(producer, BackendId::Cpu);
16516        }
16517        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[v_id, i_id], cache)
16518            .expect("realize_many");
16519        let (arc, v_layout) = outputs[0].clone();
16520        let (_, i_layout) = outputs[1].clone();
16521        let guard = arc.read().unwrap();
16522        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16523            panic!("expected Cpu storage");
16524        };
16525        let bytes = c.bytes();
16526        let vo = v_layout.start_offset() * 4;
16527        let io = i_layout.start_offset() * 4;
16528        let vals: Vec<f32> = bytes[vo..vo + 24]
16529            .chunks(4)
16530            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16531            .collect();
16532        let idx: Vec<u32> = bytes[io..io + 24]
16533            .chunks(4)
16534            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16535            .collect();
16536        assert_eq!(idx, vec![2, 1, 3, 4, 0, 1], "NaN first, ties by index");
16537        assert!(vals[0].is_nan());
16538        assert_eq!(&vals[1..], &[5.0, 5.0, 9.0, 3.0, 3.0]);
16539    }
16540
16541    /// E2E (row 172 item 2 step B): MatMulTopK f32 on CPU. Distinct matmul
16542    /// results, so the selection does not depend on accumulation order; the
16543    /// values and indices equal a hand matmul + top-2.
16544    #[test]
16545    fn pipelined_realize_matmul_top_k_f32() {
16546        // a [1, 2, 3], b [1, 3, 4]; row r of the result = a[r] @ b.
16547        let a = [1.0_f32, 2.0, 3.0, -1.0, 0.5, 2.0];
16548        let b = [
16549            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,
16550        ];
16551        let mut want_v = Vec::new();
16552        let mut want_i = Vec::new();
16553        for r in 0..2 {
16554            let row: Vec<f32> = (0..4)
16555                .map(|j| (0..3).map(|q| a[r * 3 + q] * b[q * 4 + j]).sum())
16556                .collect();
16557            let mut idx: Vec<usize> = (0..4).collect();
16558            idx.sort_by(|&x, &y| row[y].partial_cmp(&row[x]).unwrap());
16559            for &i in &idx[..2] {
16560                want_v.push(row[i]);
16561                want_i.push(i as u32);
16562            }
16563        }
16564        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16565        let mut cache = StorageCache::new();
16566        let a_id = cpu_const_f32(&graph, &mut cache, &a, &[1, 2, 3]);
16567        let b_id = cpu_const_f32(&graph, &mut cache, &b, &[1, 3, 4]);
16568        let (v_id, i_id) = {
16569            let at = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), a_id);
16570            let bt = fuel_graph::NodeHandle::from_existing(Arc::clone(&graph), b_id);
16571            let (v, i) = at.matmul_top_k(&bt, 2).expect("matmul_top_k");
16572            (v.id(), i.id())
16573        };
16574        {
16575            let mut g = graph.write().unwrap();
16576            let producer = g.node(v_id).inputs[0];
16577            g.set_target_backend(producer, BackendId::Cpu);
16578        }
16579        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[v_id, i_id], cache)
16580            .expect("realize_many");
16581        let (arc, v_layout) = outputs[0].clone();
16582        let (_, i_layout) = outputs[1].clone();
16583        let guard = arc.read().unwrap();
16584        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16585            panic!("expected Cpu storage");
16586        };
16587        let bytes = c.bytes();
16588        let (vo, io) = (v_layout.start_offset() * 4, i_layout.start_offset() * 4);
16589        let vals: Vec<f32> = bytes[vo..vo + 16]
16590            .chunks(4)
16591            .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16592            .collect();
16593        let idx: Vec<u32> = bytes[io..io + 16]
16594            .chunks(4)
16595            .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
16596            .collect();
16597        assert_eq!(idx, want_i);
16598        assert_eq!(vals, want_v);
16599    }
16600
16601    // ---- Ordering-defect repros (MLA decode multi-round WriteSlice) -----
16602
16603    /// DIAGNOSTIC (not a repro by itself): a plain single-hop view chain
16604    /// `S = Slice(X); K = Relu(S)` competing with a SECOND destructive
16605    /// WriteSlice on `X` (`Y = WriteSlice(X, ...)`) within one
16606    /// `realize_many` call. `collect_alias_set` adds `S` to `X`'s alias
16607    /// set (Slice IS `is_view_op`), so `derive_ordering` pins `Y` after
16608    /// `S`'s reader `K` directly. This form is expected to STAY GREEN —
16609    /// recorded here as the control that isolates the Reshape-specific
16610    /// gap exercised by the next test.
16611    #[test]
16612    fn pipelined_write_slice_round2_plain_slice_reader_not_stranded() {
16613        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16614        let mut cache = StorageCache::new();
16615
16616        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16617        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16618        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16619
16620        let (k_id, y_id) = {
16621            let mut g = graph.write().unwrap();
16622            let x_id = g.push(Node {
16623                op: Op::WriteSlice {
16624                    ranges: vec![(0, 2)],
16625                    dyn_offset: None,
16626                },
16627                inputs: vec![b_id, src1_id],
16628                shape: Shape::from_dims(&[4]),
16629                dtype: DType::F32,
16630            });
16631            let s_id = g.push(Node {
16632                op: Op::Slice {
16633                    dim: 0,
16634                    start: 0,
16635                    len: 2,
16636                },
16637                inputs: vec![x_id],
16638                shape: Shape::from_dims(&[2]),
16639                dtype: DType::F32,
16640            });
16641            let k_id = g.push(Node {
16642                op: Op::Relu,
16643                inputs: vec![s_id],
16644                shape: Shape::from_dims(&[2]),
16645                dtype: DType::F32,
16646            });
16647            // Round 2 OVERLAPS round 1's [0,2) range so a wrong-order
16648            // execution would be numerically visible in K's output.
16649            let y_id = g.push(Node {
16650                op: Op::WriteSlice {
16651                    ranges: vec![(0, 2)],
16652                    dyn_offset: None,
16653                },
16654                inputs: vec![x_id, src2_id],
16655                shape: Shape::from_dims(&[4]),
16656                dtype: DType::F32,
16657            });
16658            g.set_target_backend(x_id, BackendId::Cpu);
16659            g.set_target_backend(k_id, BackendId::Cpu);
16660            g.set_target_backend(y_id, BackendId::Cpu);
16661            (k_id, y_id)
16662        };
16663
16664        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16665        eprintln!("[diagnostic plain-slice] execution_plan = {:?}", plan,);
16666
16667        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16668            .expect("realize_many: plain slice reader must not error");
16669        let (k_arc, _) = &outputs[0];
16670        let guard = k_arc.read().unwrap();
16671        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16672            panic!("expected Cpu storage");
16673        };
16674        let out: &[f32] = c.as_slice().unwrap();
16675        assert_eq!(
16676            out,
16677            &[1.0, 2.0],
16678            "K = relu(slice(X,0,2)) must read PRE-round-2 bytes; got {:?}",
16679            out,
16680        );
16681    }
16682
16683    /// CRITICAL SUSPECT #2 repro: `Op::Reshape`/`Op::Contiguize` compile
16684    /// to `WorkItemKind::ContiguizeOf`, which zero-copy ADOPTS the
16685    /// input's Storage Arc when the input is contiguous at offset 0 —
16686    /// but `Op::Reshape` is NOT in `collect_alias_set`'s alias-extending
16687    /// predicate (only `Op::is_view_op` + `Op::View{..}`). So for
16688    /// `X = write_slice(B, src1); S = X.slice(0, 0, 2) [offset-0
16689    /// contiguous]; R = S.reshape([2]); K = relu(R); Y =
16690    /// write_slice(X, src2)`, `collect_alias_set(X)` stops at `{X, S}`
16691    /// — `R` never enters the alias set, so `derive_ordering` never
16692    /// scans `R`'s consumers (`K`) for pinning against `Y`. `K` and `Y`
16693    /// become simultaneously "ready" once `R` completes, and
16694    /// `execution_plan`'s stable tiebreak (smaller `topo_order_multi`
16695    /// position wins) can schedule `Y` (destructive) BEFORE `K` — `K`
16696    /// then dereferences `R`'s adopted Arc (== `X`'s Arc, mutated
16697    /// in-place by `Y`) and silently reads POST-`Y` bytes. No error;
16698    /// wrong numbers.
16699    #[test]
16700    fn pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes() {
16701        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16702        let mut cache = StorageCache::new();
16703
16704        let b_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16705        let src1_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16706        let src2_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16707
16708        let (x_id, k_id, y_id) = {
16709            let mut g = graph.write().unwrap();
16710            let x_id = g.push(Node {
16711                op: Op::WriteSlice {
16712                    ranges: vec![(0, 2)],
16713                    dyn_offset: None,
16714                },
16715                inputs: vec![b_id, src1_id],
16716                shape: Shape::from_dims(&[4]),
16717                dtype: DType::F32,
16718            });
16719            let s_id = g.push(Node {
16720                // OFFSET-0 contiguous prefix slice — ContiguizeOf's
16721                // zero-copy fast path requires this at execute time.
16722                op: Op::Slice {
16723                    dim: 0,
16724                    start: 0,
16725                    len: 2,
16726                },
16727                inputs: vec![x_id],
16728                shape: Shape::from_dims(&[2]),
16729                dtype: DType::F32,
16730            });
16731            let r_id = g.push(Node {
16732                op: Op::Reshape(Shape::from_dims(&[2])),
16733                inputs: vec![s_id],
16734                shape: Shape::from_dims(&[2]),
16735                dtype: DType::F32,
16736            });
16737            let k_id = g.push(Node {
16738                op: Op::Relu,
16739                inputs: vec![r_id],
16740                shape: Shape::from_dims(&[2]),
16741                dtype: DType::F32,
16742            });
16743            // Round 2 OVERLAPS round 1's [0,2) range (not the [2,4)
16744            // tail) so a wrong-order execution is numerically visible
16745            // in K's output — a disjoint round 2 would corrupt bytes
16746            // K never reads, masking the defect.
16747            let y_id = g.push(Node {
16748                op: Op::WriteSlice {
16749                    ranges: vec![(0, 2)],
16750                    dyn_offset: None,
16751                },
16752                inputs: vec![x_id, src2_id],
16753                shape: Shape::from_dims(&[4]),
16754                dtype: DType::F32,
16755            });
16756            g.set_target_backend(x_id, BackendId::Cpu);
16757            g.set_target_backend(k_id, BackendId::Cpu);
16758            g.set_target_backend(y_id, BackendId::Cpu);
16759            (x_id, k_id, y_id)
16760        };
16761        let _ = x_id;
16762
16763        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[k_id, y_id]);
16764        eprintln!(
16765            "[diagnostic reshape-adopted-arc] execution_plan = {:?}",
16766            plan,
16767        );
16768
16769        let outputs = PipelinedExecutor::realize_many(Arc::clone(&graph), &[k_id, y_id], cache)
16770            .expect("realize_many");
16771        let (k_arc, _) = &outputs[0];
16772        let guard = k_arc.read().unwrap();
16773        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16774            panic!("expected Cpu storage");
16775        };
16776        let out: &[f32] = c.as_slice().unwrap();
16777        // K = relu(reshape(slice(X,0,2))) must read PRE-round-2 bytes:
16778        // relu([1.0, 2.0]) = [1.0, 2.0]. Round 2 overwrites the SAME
16779        // [0,2) range with [99.0, 98.0] — if Y (round 2) runs before K
16780        // (the ordering defect), K instead observes [99.0, 98.0].
16781        assert_eq!(
16782            out,
16783            &[1.0, 2.0],
16784            "K must read PRE-round-2 bytes through the adopted Arc; got {:?} \
16785             (post-round-2 corruption if this fails)",
16786            out,
16787        );
16788    }
16789
16790    /// The MLA-decode shape from `rebind_latent_cache_fresh_graph`'s doc
16791    /// (`fuel-core/src/lazy_deepseek2.rs`): layer L's post-append buffer
16792    /// `X_L_N` (round N) is read TWICE within one realize call — once
16793    /// (non-destructively) through a Slice+Reshape "attention math" view
16794    /// chain whose result becomes an ancestor of layer L+1's round-N
16795    /// write, and again as the DESTINATION of layer L's round-(N+1)
16796    /// append. Reproduces the same Reshape-adoption gap as
16797    /// `pipelined_write_slice_reshape_adopted_arc_reader_reads_pre_write_bytes`
16798    /// at 2-layer scale, confirming the defect is not an artifact of the
16799    /// single-hop minimal form.
16800    #[test]
16801    fn pipelined_write_slice_mla_two_layer_round2_reshape_reader_not_stranded() {
16802        let graph: Arc<RwLock<Graph>> = Arc::new(RwLock::new(Graph::new()));
16803        let mut cache = StorageCache::new();
16804
16805        let b_l_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16806        let src_l_n_id = cpu_const_f32(&graph, &mut cache, &[1.0, 2.0], &[2]);
16807        let b_l1_id = cpu_const_f32(&graph, &mut cache, &[0.0, 0.0, 0.0, 0.0], &[4]);
16808        let src_l_n1_id = cpu_const_f32(&graph, &mut cache, &[99.0, 98.0], &[2]);
16809
16810        let (x_l_n1_id, x_l1_n_id) = {
16811            let mut g = graph.write().unwrap();
16812            // Round N, layer L: append src_l_n into b_l.
16813            let x_l_n = g.push(Node {
16814                op: Op::WriteSlice {
16815                    ranges: vec![(0, 2)],
16816                    dyn_offset: None,
16817                },
16818                inputs: vec![b_l_id, src_l_n_id],
16819                shape: Shape::from_dims(&[4]),
16820                dtype: DType::F32,
16821            });
16822            // "Attention math" for round N at layer L: read the filled
16823            // prefix, reshape (head-split-style hop), then a kernel.
16824            let s_l_n = g.push(Node {
16825                op: Op::Slice {
16826                    dim: 0,
16827                    start: 0,
16828                    len: 2,
16829                },
16830                inputs: vec![x_l_n],
16831                shape: Shape::from_dims(&[2]),
16832                dtype: DType::F32,
16833            });
16834            let rs_l_n = g.push(Node {
16835                op: Op::Reshape(Shape::from_dims(&[2])),
16836                inputs: vec![s_l_n],
16837                shape: Shape::from_dims(&[2]),
16838                dtype: DType::F32,
16839            });
16840            let r_l_n = g.push(Node {
16841                op: Op::Relu,
16842                inputs: vec![rs_l_n],
16843                shape: Shape::from_dims(&[2]),
16844                dtype: DType::F32,
16845            });
16846            // Round N, layer L+1: append the attention-math result.
16847            let x_l1_n = g.push(Node {
16848                op: Op::WriteSlice {
16849                    ranges: vec![(0, 2)],
16850                    dyn_offset: None,
16851                },
16852                inputs: vec![b_l1_id, r_l_n],
16853                shape: Shape::from_dims(&[4]),
16854                dtype: DType::F32,
16855            });
16856            // Round N+1, layer L: append into x_l_n directly (SAME node
16857            // s_l_n/rs_l_n/r_l_n read from) — OVERLAPPING range so a
16858            // wrong-order execution is numerically visible downstream.
16859            let x_l_n1 = g.push(Node {
16860                op: Op::WriteSlice {
16861                    ranges: vec![(0, 2)],
16862                    dyn_offset: None,
16863                },
16864                inputs: vec![x_l_n, src_l_n1_id],
16865                shape: Shape::from_dims(&[4]),
16866                dtype: DType::F32,
16867            });
16868            g.set_target_backend(x_l_n, BackendId::Cpu);
16869            g.set_target_backend(r_l_n, BackendId::Cpu);
16870            g.set_target_backend(x_l1_n, BackendId::Cpu);
16871            g.set_target_backend(x_l_n1, BackendId::Cpu);
16872            (x_l_n1, x_l1_n)
16873        };
16874
16875        let plan = fuel_graph::opt::execution_plan(&graph.read().unwrap(), &[x_l1_n_id, x_l_n1_id]);
16876        eprintln!("[diagnostic mla-2-layer] execution_plan = {:?}", plan);
16877
16878        let outputs =
16879            PipelinedExecutor::realize_many(Arc::clone(&graph), &[x_l1_n_id, x_l_n1_id], cache)
16880                .expect("realize_many");
16881        // outputs[0] = x_l1_n = write_slice(b_l1, relu(reshape(slice(x_l_n))))
16882        // Must reflect round-N's PRE-round-(N+1) bytes: relu([1,2]) = [1,2].
16883        let (x_l1_n_arc, _) = &outputs[0];
16884        let guard = x_l1_n_arc.read().unwrap();
16885        let fuel_memory::BackendStorage::Cpu(c) = &guard.inner else {
16886            panic!("expected Cpu storage");
16887        };
16888        let out: &[f32] = c.as_slice().unwrap();
16889        assert_eq!(
16890            out,
16891            &[1.0, 2.0, 0.0, 0.0],
16892            "layer L+1's round-N append must reflect PRE-round-(N+1) attention \
16893             math output; got {:?} (post-round-(N+1) corruption if this fails)",
16894            out,
16895        );
16896    }
16897}