Skip to main content

fuel_tensor/
inference_context.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2//! Persistent inference state for the pipelined executor (Phase 7.6
3//! step 9c, sub-phase E.3.0).
4//!
5//! ## What this module owns
6//!
7//! - **[`InferenceContext`]**: a host-side per-session struct holding
8//!   long-lived `Arc<RwLock<Storage>>` references that survive across
9//!   realize calls. Replaces the legacy executor's `const_pool`
10//!   for the pipelined dispatch world. Today's backing is a simple
11//!   in-memory `HashMap<NodeId, Arc<...>>`; future work may swap this
12//!   for an mmap-backed coherent store per
13//!   `project_unified_durable_tensor_store.md`.
14//!
15//! - **[`KvCache`]**, **[`KvLayer`]**, **[`KvLayerId`]**, **[`KvSlot`]**,
16//!   **[`AuthorityState`]**: the backend-erased KV cache primitive that
17//!   replaced `lazy::KVCache<B>` and `lazy::LlamaKVCache` (both
18//!   retired — E.3.3.D and Unification Session 4 E.3.4). Single
19//!   concrete type with no generic-over-B parameter; each layer holds
20//!   `Arc<RwLock<Storage>>` for K and V plus side-table metadata
21//!   (layout, monotonic version, coherence authority).
22//!
23//! ## What this module deliberately does NOT do (yet)
24//!
25//! - **Pre-allocated buffers** (added Phase E.3.3.A, 2026-05-20):
26//!   [`KvCache::with_capacity`] eagerly allocates `[1, n_kv_heads,
27//!   max_seq_len, head_dim]` zero-initialized K + V buffers on a
28//!   target device. Subsequent forward steps write into these via
29//!   `Op::WriteSlice` rather than growing-by-replacement. The legacy
30//!   [`KvCache::with_dims`] constructor stays available for callers
31//!   not yet on the pre-allocated path (grow-by-replace works without
32//!   changes).
33//! - **Multi-device coherence protocol**: the `authority` and
34//!   `version` fields exist as placeholders. No protocol consults
35//!   them yet — every layer starts and stays `AuthorityState::Host`
36//!   for the lifetime of the session in single-device usage.
37//!   Phase J (multi-GPU) activates the protocol.
38//! - **Weight persistence**: weights stay in the graph's storage_map
39//!   per the design discussion; the persistent map handles KV layers
40//!   and transient cross-step state only.
41
42use std::collections::HashMap;
43use std::sync::atomic::{AtomicUsize, Ordering};
44use std::sync::{Arc, RwLock};
45
46use fuel_dispatch::{
47    optimize::OptimizedGraph,
48    pipelined::{PipelinedExecutor, StorageCache},
49};
50use fuel_graph::{Graph, Node, NodeId, Op};
51use fuel_ir::{DType, DeviceLocation, Error, Layout, Result, SType, Shape, SymEnv, SymId};
52use fuel_memory::{BackendStorage, Storage};
53
54use crate::Device;
55use crate::decode_shape::KvAllocId;
56
57// ===========================================================================
58// KV cache primitive types
59// ===========================================================================
60
61/// Identifies a single key-or-value tensor within a [`KvCache`].
62/// Stable across realize calls — the graph-level NodeId may churn
63/// per step (each `Op::WriteSlice` produces a fresh NodeId pointing
64/// at the same Storage Arc) but the logical KV slot identity stays.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
66pub struct KvLayerId {
67    pub layer_idx: usize,
68    pub slot: KvSlot,
69}
70
71/// Which half of a KV pair a [`KvLayerId`] addresses.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub enum KvSlot {
74    K,
75    V,
76}
77
78/// Coherence authority for one KV slot's storage. Placeholder for the
79/// multi-device protocol; today every slot starts and stays
80/// [`AuthorityState::Host`] for the lifetime of the session unless
81/// future code explicitly transitions it.
82///
83/// The intended protocol (deferred until multi-GPU lands):
84/// - **Host**: the host has the most recent version. Devices may
85///   hold stale copies. The default at session start.
86/// - **Device(loc)**: a device owns the most recent version. The
87///   host's copy may be stale until an explicit flush.
88#[derive(Debug, Clone)]
89pub enum AuthorityState {
90    Host,
91    Device(DeviceLocation),
92}
93
94/// One layer's K + V slots in a backend-erased KV cache.
95///
96/// Storage Arcs are dispatch-erased: each Arc points at a
97/// [`fuel_memory::BackendStorage`] enum variant (`Cpu`, `Cuda`,
98/// `Vulkan`, `Metal`). The graph references these Arcs via the
99/// persistent map in [`InferenceContext`]; readers see the bytes
100/// through whichever Layout the graph carries for the consuming
101/// NodeId.
102pub struct KvLayer {
103    pub k: Arc<RwLock<Storage>>,
104    pub v: Arc<RwLock<Storage>>,
105    /// View layout into `k` describing the live extent. For the grow-
106    /// by-replacement pattern (today) the layout matches the storage's
107    /// full shape. For pre-allocated buffers (Phase E.3.2) the layout
108    /// describes the leading `[..., cached_len, ...]` slice.
109    pub k_layout: Layout,
110    pub v_layout: Layout,
111    /// Monotonic write version for K. Bumps on every successful
112    /// `Op::WriteSlice` targeting this slot. Used by the future
113    /// multi-device coherence protocol to detect staleness.
114    pub k_version: u64,
115    pub v_version: u64,
116    /// Coherence authority per slot. K and V can in principle diverge
117    /// (a future optimization that decouples their update cadence
118    /// could exploit this), though standard transformer decoding
119    /// updates both together every step.
120    pub k_authority: AuthorityState,
121    pub v_authority: AuthorityState,
122}
123
124/// Backend-erased KV cache. Replaces `lazy::KVCache<B>` and
125/// `lazy::LlamaKVCache`. Indexed by global layer index; `layers[i]`
126/// is `None` if layer `i` hasn't been populated yet.
127///
128/// Pipeline-parallel friendly: when a model is split across devices,
129/// each device's cache holds entries only for its layer range; other
130/// indices are `None`. The model code queries `cache.layer(global_i)`
131/// regardless of which device owns it; the storage Arc inside
132/// [`KvLayer`] carries the device identity via its
133/// [`fuel_memory::BackendStorage`] variant.
134pub struct KvCache {
135    pub layers: Vec<Option<KvLayer>>,
136    pub cached_len: usize,
137    pub n_kv_heads: usize,
138    pub head_dim: usize,
139    /// Identity of the *allocation* backing this cache — the thing a held
140    /// [`DecodeSession`] is welded to. Private with an [`Self::alloc_id`]
141    /// reader so it cannot be assigned by hand: every path that replaces
142    /// storage ([`Self::clear`], [`Self::set_layer`]) re-mints it, and
143    /// [`Self::truncate_to`] deliberately does not. See [`KvAllocId`].
144    alloc_id: KvAllocId,
145    /// Pre-allocated capacity along the sequence axis. `Some(n)` when
146    /// constructed via [`KvCache::with_capacity`] — every layer's K + V
147    /// storage holds `[1, n_kv_heads, n, head_dim]` of zeros and the
148    /// forward path writes into it via `Op::WriteSlice`. `None` for the
149    /// legacy [`KvCache::with_dims`] grow-by-replacement constructor.
150    pub max_seq_len: Option<usize>,
151    /// Dtype the pre-allocated buffers were allocated with. `Some(dt)`
152    /// in the [`KvCache::with_capacity`] path, `None` in the legacy
153    /// `with_dims` path (which leaves dtype to whatever the first
154    /// inserted layer specifies).
155    pub dtype: Option<DType>,
156    /// Where this cache's storage lives — `Some(loc)` only while every
157    /// buffer is one [`Self::with_capacity`] allocated on `loc`, `None`
158    /// the moment that stops being provable.
159    ///
160    /// Exists for [`DecodeSession::rebind_kv`], which splices these `Arc`s
161    /// into a graph whose placement stamps and residency `Op::Copy`s were
162    /// baked against the *previous* cache. Shape it can prove from the
163    /// storage itself; residency it cannot — `fuel_memory::Storage` exposes
164    /// a backend *variant*, and `VulkanStorage` records no device ordinal at
165    /// all, so a multi-GPU swap is invisible from the bytes. The cache is
166    /// therefore the honest carrier: it is handed a `&Device` at the one
167    /// moment residency is known for certain.
168    ///
169    /// `None` means "cannot prove", not "CPU" — and every consumer must
170    /// treat it as a refusal. [`Self::with_dims`] never had a device;
171    /// [`Self::set_layer`] installs caller-supplied storage from anywhere.
172    /// Both therefore forfeit re-bind and fall back to a plan rebuild,
173    /// which is what shipped in GAP-014 and is safe by construction.
174    device_location: Option<DeviceLocation>,
175}
176
177impl KvCache {
178    /// Legacy grow-by-replacement constructor. Layers start `None`; the
179    /// caller calls [`Self::set_layer`] each forward step with a freshly
180    /// allocated `KvLayer` whose storage is sized to the current cached
181    /// length. Subsequent steps replace the layer entirely with a
182    /// larger buffer.
183    ///
184    /// Replaced by [`Self::with_capacity`] when the caller knows the
185    /// generation's max sequence length up-front (the common case for
186    /// autoregressive decoding).
187    pub fn with_dims(n_layers: usize, n_kv_heads: usize, head_dim: usize) -> Self {
188        Self {
189            layers: (0..n_layers).map(|_| None).collect(),
190            cached_len: 0,
191            n_kv_heads,
192            head_dim,
193            max_seq_len: None,
194            dtype: None,
195            alloc_id: KvAllocId::next(),
196            // No device was named, and this constructor's whole shape is
197            // grow-by-replacement — the storage a plan baked is replaced
198            // every step anyway. Unprovable residency, and nothing lost.
199            device_location: None,
200        }
201    }
202
203    /// Pre-allocated KV cache. Every layer's K + V storage is allocated
204    /// up-front as a `[1, n_kv_heads, max_seq_len, head_dim]` zero
205    /// buffer on `device` with `dtype`. Subsequent forward steps write
206    /// fresh K/V slabs into these buffers via `Op::WriteSlice` rather
207    /// than growing-by-replacement.
208    ///
209    /// Memory footprint: `n_layers * 2 * n_kv_heads * max_seq_len *
210    /// head_dim * dtype_size` bytes. For Llama-7B at max_seq_len=4096,
211    /// bf16: 32 * 2 * 8 * 4096 * 128 * 2 ≈ 512 MiB.
212    ///
213    /// Returns `Err` if any per-layer allocation fails (e.g. CUDA OOM)
214    /// or the requested device hasn't been wired up in
215    /// [`crate::pipelined_bridge`] (Vulkan / Metal — D2H/H2D for those still
216    /// goes through the legacy executor).
217    pub fn with_capacity(
218        n_layers: usize,
219        n_kv_heads: usize,
220        head_dim: usize,
221        max_seq_len: usize,
222        dtype: DType,
223        device: &Device,
224    ) -> Result<Self> {
225        // Bridge-retirement Phase 3a (post-9c): allocate the 2N K/V
226        // buffers via `Op::Alloc` graph emission, not direct backend
227        // calls. The executor's `WorkItemKind::Alloc` arm dispatches
228        // per-backend; the per-`DeviceLocation` match that used to
229        // live in `alloc_zeroed_on` is now in the executor (the
230        // architectural dispatch layer).
231        let shape = Shape::from_dims(&[1, n_kv_heads, max_seq_len, head_dim]);
232        let layout = Layout::contiguous(shape.clone());
233        let target_loc = device.location();
234
235        // Build the transient graph. For non-CPU targets the first
236        // node is an `Op::Const` placeholder whose StorageCache entry
237        // carries a small "device anchor" storage — the executor's
238        // Alloc arm searches the cache for any storage on the target
239        // backend to derive the device handle, so this entry makes
240        // the first Op::Alloc's device lookup succeed. The anchor's
241        // NodeId must exist in the graph so `realize_many`'s
242        // `layout_cache` seeding (which calls `g.layout(id)` on every
243        // cache key) doesn't panic.
244        let graph = Arc::new(RwLock::new(Graph::new()));
245        let cache = StorageCache::new();
246        // Emit pairs of (Op::Alloc, Op::ZeroFill) per K/V slot. The
247        // ZeroFill consumes the Alloc destructively (in-place fill,
248        // output adopts the Alloc's Storage Arc). Realizing the
249        // ZeroFill IDs produces zero-initialized device storages.
250        //
251        // Phase 3a follow-up architecture: Op::Alloc gives uninit
252        // memory; Op::ZeroFill explicitly fills with zero. On Vulkan
253        // this replaces the host-staged-zeros path with device-side
254        // `vkCmdFillBuffer` (~2× the bandwidth saved). On CUDA the
255        // pair becomes uninit `cuMemAlloc` + async `cuMemsetD8Async`
256        // — same total cost as the old `alloc_zeros` but exposes the
257        // ZeroFill as a first-class graph node the optimizer can
258        // see (and skip if a downstream op covers the full buffer).
259        let zero_fill_ids: Vec<NodeId> = {
260            let mut g = graph
261                .write()
262                .map_err(|_| Error::Msg("graph lock poisoned during KvCache build".into()).bt())?;
263            (0..(2 * n_layers))
264                .map(|_| {
265                    let alloc_id = g.push(Node {
266                        op: Op::Alloc { target: target_loc },
267                        inputs: vec![],
268                        shape: shape.clone(),
269                        dtype,
270                    });
271                    g.push(Node {
272                        op: Op::ZeroFill,
273                        inputs: vec![alloc_id],
274                        shape: shape.clone(),
275                        dtype,
276                    })
277                })
278                .collect()
279        };
280
281        // Realize all 2*n_layers Op::ZeroFill targets in one pass —
282        // PipelinedExecutor::realize_many shares the compile/execute
283        // pipeline so device-handle reuse is automatic, and the
284        // executor's destructive_input cleanup evicts the Op::Alloc
285        // intermediate NodeIds while the ZeroFill targets adopt the
286        // same Arcs (post-fill bytes).
287        let realized = PipelinedExecutor::realize_many_with_devices(
288            Arc::clone(&graph),
289            &zero_fill_ids,
290            cache,
291            crate::pipelined_bridge::primary_device_registry(device)?,
292        )?;
293        if realized.len() != 2 * n_layers {
294            return Err(Error::Msg(format!(
295                "KvCache::with_capacity: realize_many returned {} storages \
296                 for {} Op::ZeroFill targets — internal bug",
297                realized.len(),
298                2 * n_layers,
299            ))
300            .bt());
301        }
302
303        // Never-panic: the length is checked above, but the production path
304        // must not `.expect()` — surface a typed `Err` if the iterator runs
305        // short. (Same pattern as `alloc_batched_kv` below.)
306        let mut realized_iter = realized.into_iter();
307        let short = |what: &str, l: usize| {
308            Error::Msg(format!(
309                "alloc_kv: realize_many yielded fewer storages than expected \
310                 (ran out at layer {l} fetching {what})"
311            ))
312            .bt()
313        };
314        let mut layers: Vec<Option<KvLayer>> = Vec::with_capacity(n_layers);
315        for l in 0..n_layers {
316            let (k_arc, _) = realized_iter.next().ok_or_else(|| short("K", l))?;
317            let (v_arc, _) = realized_iter.next().ok_or_else(|| short("V", l))?;
318            layers.push(Some(KvLayer {
319                k: k_arc,
320                v: v_arc,
321                k_layout: layout.clone(),
322                v_layout: layout.clone(),
323                k_version: 0,
324                v_version: 0,
325                k_authority: AuthorityState::Host,
326                v_authority: AuthorityState::Host,
327            }));
328        }
329
330        // Silence the unused-bind lint for elem_count when this
331        // path no longer needs the legacy alloc helper.
332        let _ = (n_kv_heads, max_seq_len, head_dim);
333
334        Ok(Self {
335            layers,
336            cached_len: 0,
337            n_kv_heads,
338            head_dim,
339            max_seq_len: Some(max_seq_len),
340            dtype: Some(dtype),
341            alloc_id: KvAllocId::next(),
342            // Every buffer above was `Op::Alloc { target: target_loc }`, so
343            // this is measured at the allocation, not inferred later.
344            device_location: Some(target_loc),
345        })
346    }
347
348    /// Borrow the K-or-V storage Arc for a given layer + slot. Used by
349    /// the forward path to bind cache storage to per-step Const nodes
350    /// via [`InferenceContext::insert`]. Returns `None` if the layer
351    /// isn't populated (with_dims path before first
352    /// [`Self::set_layer`]) or `layer_idx` is out of range.
353    pub fn slot_storage(&self, layer_idx: usize, slot: KvSlot) -> Option<Arc<RwLock<Storage>>> {
354        let layer = self.layer(layer_idx)?;
355        Some(match slot {
356            KvSlot::K => Arc::clone(&layer.k),
357            KvSlot::V => Arc::clone(&layer.v),
358        })
359    }
360
361    /// Bump a slot's monotonic version counter. Called after every
362    /// successful `Op::WriteSlice` targeting the slot — the forward
363    /// path invokes this once per (layer, slot) per step.
364    ///
365    /// The version is consumed by the future multi-device coherence
366    /// protocol (placeholder today — see [`AuthorityState`]).
367    pub fn bump_version(&mut self, layer_idx: usize, slot: KvSlot) {
368        if let Some(layer) = self.layer_mut(layer_idx) {
369            match slot {
370                KvSlot::K => layer.k_version += 1,
371                KvSlot::V => layer.v_version += 1,
372            }
373        }
374    }
375
376    pub fn n_layers(&self) -> usize {
377        self.layers.len()
378    }
379
380    pub fn layer(&self, li: usize) -> Option<&KvLayer> {
381        self.layers.get(li).and_then(|o| o.as_ref())
382    }
383
384    pub fn layer_mut(&mut self, li: usize) -> Option<&mut KvLayer> {
385        self.layers.get_mut(li).and_then(|o| o.as_mut())
386    }
387
388    /// Identity of the storage this cache currently owns — the value a held
389    /// [`DecodeSession`]'s validity key carries so a cache **swap** cannot be
390    /// mistaken for a continuation. See [`KvAllocId`] for why re-allocation
391    /// re-mints it and rewinding does not.
392    pub fn alloc_id(&self) -> KvAllocId {
393        self.alloc_id
394    }
395
396    /// Where this cache's storage lives, or `None` when that is not provable.
397    /// See the field's doc — `None` is a refusal, never a CPU default.
398    pub fn device_location(&self) -> Option<DeviceLocation> {
399        self.device_location
400    }
401
402    /// Install a layer's storage, replacing whatever was there.
403    ///
404    /// This **re-mints [`Self::alloc_id`]**: the storage `Arc` a held plan
405    /// baked into its `base_cache` for this layer is no longer the storage
406    /// this cache reads, so any plan welded to the old one must be rebuilt.
407    /// It also clears [`Self::device_location`]: the storage arrives from the
408    /// caller, so where it lives is no longer something this cache measured.
409    /// That forfeits [`DecodeSession::rebind_kv`] for the rest of this cache's
410    /// life — deliberately, because an unprovable residency spliced into a
411    /// baked plan is the GAP-014 failure one layer down.
412    pub fn set_layer(&mut self, li: usize, layer: KvLayer) {
413        self.layers[li] = Some(layer);
414        self.alloc_id = KvAllocId::next();
415        self.device_location = None;
416    }
417
418    /// Drop every layer; reset `cached_len` to zero. Use between
419    /// independent generations (the cache's K/V shapes are tied to
420    /// a specific prompt prefix).
421    ///
422    /// **Re-mints [`Self::alloc_id`]** — every storage `Arc` is released, so
423    /// this is an allocation change, not a rewind. Contrast
424    /// [`Self::truncate_to`], which moves only `cached_len` and therefore must
425    /// preserve the id.
426    pub fn clear(&mut self) {
427        for layer in &mut self.layers {
428            *layer = None;
429        }
430        self.cached_len = 0;
431        self.alloc_id = KvAllocId::next();
432        // There is no storage left to have a residency. Repopulating goes
433        // through `set_layer`, which cannot prove one either.
434        self.device_location = None;
435    }
436
437    /// Shrink the cache to `new_len` cached positions. Speculative-
438    /// decoding's reject path calls this after a draft batch is
439    /// rejected by the target model.
440    ///
441    /// **Phase E.3.0 limitation**: this only updates `cached_len`;
442    /// the underlying storages and their layouts are *not* shrunk.
443    /// The grow-by-replacement pattern (today) means the next forward
444    /// pass would still see the old layout's full extent. Phase E.3.2
445    /// pairs this with pre-allocated buffers + `Op::WriteSlice` so
446    /// truncate becomes a pure metadata update — the trailing rows
447    /// of the pre-allocated buffer simply stop being read.
448    ///
449    /// **Deliberately does NOT touch [`Self::alloc_id`].** Rewinding the
450    /// conversation is not re-allocating the buffers: a held plan is still
451    /// welded to exactly the right storage, so invalidating here would forfeit
452    /// plan reuse on every rejected draft batch and buy no correctness. The
453    /// id names the allocation, never the conversation — see [`KvAllocId`].
454    pub fn truncate_to(&mut self, new_len: usize) {
455        if new_len < self.cached_len {
456            self.cached_len = new_len;
457        }
458    }
459
460    /// Write host-supplied K/V bytes into layer `layer_idx`'s `slot` buffer at
461    /// position range `[start, start+n)` — the `KvCache`-side sibling of
462    /// [`DeviceKvPool::write_block_bytes`](crate::kv_block_pool_device::DeviceKvPool::write_block_bytes).
463    ///
464    /// Builds a throwaway `Op::Const`(bytes) → `Op::WriteSlice` graph and
465    /// realizes it ONCE into the SAME buffer `Arc` this cache already holds —
466    /// it does **not** replace the Arc, so unlike [`Self::set_layer`] this
467    /// does **not** touch [`Self::alloc_id`] or [`Self::device_location`]: a
468    /// [`DecodeSession`] already welded to this cache's buffers (via
469    /// `base_cache`) sees the write transparently on its next token, with no
470    /// rebind and no rebuild — the write lands in the exact buffer the held
471    /// plan's `Op::WriteSlice` nodes already target.
472    ///
473    /// `bytes` is `n * n_kv_heads * head_dim * dtype.size_in_bytes()` raw
474    /// little-endian element bytes, row-major `[1, n_kv_heads, n, head_dim]`
475    /// — **HEAD-MAJOR** (position is axis 2). This is NOT the same layout as
476    /// [`DeviceKvPool`](crate::kv_block_pool_device::DeviceKvPool)'s
477    /// **position-major** `[block_size, Hkv, D]` block layout: a caller
478    /// moving bytes from the paged pool into a `KvCache` must transpose, a
479    /// plain memcpy silently produces wrong attention.
480    ///
481    /// `Err` (never a panic): this cache has no fixed dtype/capacity (built
482    /// via [`Self::with_dims`] rather than [`Self::with_capacity`] — this
483    /// primitive is `with_capacity`-only, since the legacy grow-by-replacement
484    /// path has no stable buffer to write into); `layer_idx` is out of range
485    /// or unpopulated; `start + n` exceeds the allocated `max_seq_len`; or
486    /// `bytes.len()` doesn't match the expected size for `n` positions.
487    pub fn write_bytes(
488        &self,
489        layer_idx: usize,
490        slot: KvSlot,
491        start: usize,
492        n: usize,
493        bytes: &[u8],
494        device: &Device,
495    ) -> Result<()> {
496        let dtype = self.dtype.ok_or_else(|| {
497            Error::Msg(
498                "KvCache::write_bytes: cache has no fixed dtype — not built via with_capacity"
499                    .into(),
500            )
501            .bt()
502        })?;
503        let max_seq_len = self.max_seq_len.ok_or_else(|| {
504            Error::Msg(
505                "KvCache::write_bytes: cache has no fixed capacity — not built via with_capacity"
506                    .into(),
507            )
508            .bt()
509        })?;
510        if start + n > max_seq_len {
511            return Err(Error::Msg(format!(
512                "KvCache::write_bytes: range [{start}, {}) exceeds max_seq_len {max_seq_len}",
513                start + n,
514            ))
515            .bt());
516        }
517        let elem_bytes = kv_cache_dtype_elem_bytes(dtype)?;
518        let want = n * self.n_kv_heads * self.head_dim * elem_bytes;
519        if bytes.len() != want {
520            return Err(Error::Msg(format!(
521                "KvCache::write_bytes: {} bytes != expected {want} \
522                 ([1, n_kv_heads {}, n {n}, head_dim {}] for {dtype:?})",
523                bytes.len(),
524                self.n_kv_heads,
525                self.head_dim,
526            ))
527            .bt());
528        }
529        let layer = self.layer(layer_idx).ok_or_else(|| {
530            Error::Msg(format!(
531                "KvCache::write_bytes: layer {layer_idx} out of range or unpopulated"
532            ))
533            .bt()
534        })?;
535        let buf = match slot {
536            KvSlot::K => Arc::clone(&layer.k),
537            KvSlot::V => Arc::clone(&layer.v),
538        };
539        let full_shape = Shape::from_dims(&[1, self.n_kv_heads, max_seq_len, self.head_dim]);
540        let src = kv_cache_const_from_bytes(
541            dtype,
542            bytes,
543            Shape::from_dims(&[1, self.n_kv_heads, n, self.head_dim]),
544            device,
545        )?;
546        let dest = src.const_placeholder_like(full_shape, dtype);
547        let ranges = vec![
548            (0, 1),
549            (0, self.n_kv_heads),
550            (start, start + n),
551            (0, self.head_dim),
552        ];
553        let post = dest.write_slice(&src, ranges)?;
554        let mut cache = StorageCache::new();
555        cache.insert(dest.node_id(), buf);
556        let _ = crate::pipelined_bridge::realize_one_bytes_with_initial(
557            post.graph_handle(),
558            post.node_id(),
559            device,
560            cache,
561        )?;
562        Ok(())
563    }
564}
565
566/// Byte width of one `KvCache` element for byte-level movement — the
567/// `KvCache`-side sibling of
568/// [`DeviceKvPool::dtype_elem_bytes`](crate::kv_block_pool_device::DeviceKvPool).
569/// F32/BF16 only, matching [`KvCache::write_bytes`]'s supported dtypes.
570fn kv_cache_dtype_elem_bytes(dtype: DType) -> Result<usize> {
571    match dtype {
572        DType::F32 => Ok(4),
573        DType::BF16 => Ok(2),
574        other => Err(Error::Msg(format!(
575            "KvCache: byte movement unsupported for dtype {other:?} (F32/BF16)",
576        ))
577        .bt()),
578    }
579}
580
581/// Build a fresh-graph `Op::Const` of `dtype` from raw little-endian element
582/// bytes — the `KvCache`-side sibling of
583/// [`DeviceKvPool::const_from_bytes`](crate::kv_block_pool_device::DeviceKvPool).
584/// Dispatches `dtype` to the matching typed graph constructor via
585/// alignment-safe `try_cast_slice` (never panics).
586fn kv_cache_const_from_bytes(
587    dtype: DType,
588    bytes: &[u8],
589    shape: Shape,
590    device: &Device,
591) -> Result<crate::lazy::Tensor> {
592    match dtype {
593        DType::F32 => {
594            let v: &[f32] = bytemuck::try_cast_slice(bytes).map_err(|e| {
595                Error::Msg(format!("kv_cache_const_from_bytes: f32 cast: {e:?}")).bt()
596            })?;
597            crate::lazy::Tensor::from_f32(v.to_vec(), shape, device)
598        }
599        DType::BF16 => {
600            let v: &[half::bf16] = bytemuck::try_cast_slice(bytes).map_err(|e| {
601                Error::Msg(format!("kv_cache_const_from_bytes: bf16 cast: {e:?}")).bt()
602            })?;
603            let anchor =
604                crate::lazy::Tensor::from_f32(vec![0.0f32], Shape::from_dims(&[1]), device)?;
605            crate::lazy::Tensor::from_bf16_on(anchor.graph(), v.to_vec(), shape, device)
606        }
607        other => Err(Error::Msg(format!(
608            "kv_cache_const_from_bytes: unsupported dtype {other:?} (F32/BF16)",
609        ))
610        .bt()),
611    }
612}
613
614/// One layer's `(K, V)` cache storages. A KV cache is a `Vec` of these, one
615/// per layer, and the two halves are always allocated and dropped together.
616type KvStoragePair = (Arc<RwLock<Storage>>, Arc<RwLock<Storage>>);
617
618/// Allocate `n_layers` pairs of zero-initialized `[k, n_kv_heads,
619/// max_seq_len, head_dim]` K/V buffers on `device` with `dtype` — the shared
620/// batch-slot KV buffer for the multi-session batched decode arm (serving
621/// Increment 1, C3). Same `Op::Alloc`→`Op::ZeroFill` emission +
622/// `PipelinedExecutor::realize_many` pattern as [`KvCache::with_capacity`],
623/// with the leading dim `k` (the batch slot) instead of `1`. Returns the
624/// per-layer `(K_arc, V_arc)` pairs; the caller binds them into a batched
625/// decode graph.
626///
627/// Returns `Err` if any allocation fails (fail-on-OOM, spec #6).
628pub fn alloc_batched_kv(
629    k: usize,
630    n_layers: usize,
631    n_kv_heads: usize,
632    head_dim: usize,
633    max_seq_len: usize,
634    dtype: DType,
635    device: &Device,
636) -> Result<Vec<KvStoragePair>> {
637    let shape = Shape::from_dims(&[k, n_kv_heads, max_seq_len, head_dim]);
638    let target_loc = device.location();
639
640    let graph = Arc::new(RwLock::new(Graph::new()));
641    let cache = StorageCache::new();
642
643    let zero_fill_ids: Vec<NodeId> = {
644        let mut g = graph
645            .write()
646            .map_err(|_| Error::Msg("graph lock poisoned during alloc_batched_kv".into()).bt())?;
647        (0..(2 * n_layers))
648            .map(|_| {
649                let alloc_id = g.push(Node {
650                    op: Op::Alloc { target: target_loc },
651                    inputs: vec![],
652                    shape: shape.clone(),
653                    dtype,
654                });
655                g.push(Node {
656                    op: Op::ZeroFill,
657                    inputs: vec![alloc_id],
658                    shape: shape.clone(),
659                    dtype,
660                })
661            })
662            .collect()
663    };
664
665    let realized = PipelinedExecutor::realize_many_with_devices(
666        Arc::clone(&graph),
667        &zero_fill_ids,
668        cache,
669        crate::pipelined_bridge::primary_device_registry(device)?,
670    )?;
671    if realized.len() != 2 * n_layers {
672        return Err(Error::Msg(format!(
673            "alloc_batched_kv: realize_many returned {} storages for {} Op::ZeroFill targets",
674            realized.len(),
675            2 * n_layers,
676        ))
677        .bt());
678    }
679
680    // Never-panic: the length is checked above, but the production path must
681    // not `.expect()` — surface a typed `Err` if the iterator is short.
682    let mut it = realized.into_iter();
683    let mut pairs = Vec::with_capacity(n_layers);
684    let short = || {
685        Error::Msg(
686            "alloc_batched_kv: realize_many yielded fewer storages than expected".to_string(),
687        )
688        .bt()
689    };
690    for _ in 0..n_layers {
691        let (k_arc, _) = it.next().ok_or_else(short)?;
692        let (v_arc, _) = it.next().ok_or_else(short)?;
693        pairs.push((k_arc, v_arc));
694    }
695    Ok(pairs)
696}
697
698// ===========================================================================
699// LatentKvCache — N-slot generalization of KvCache (MLA increment 4)
700// ===========================================================================
701
702/// One slot's persistent latent buffer within a [`LatentKvCache`] layer.
703/// The per-slot analogue of [`KvLayer`]'s `k`/`v` pair, generalized to an
704/// arbitrary slot count and independent per-slot trailing shape.
705pub struct LatentSlot {
706    pub storage: Arc<RwLock<Storage>>,
707    /// View layout into `storage`. For the pre-allocated (capacity)
708    /// buffers [`LatentKvCache::with_capacity`] allocates, the layout
709    /// matches the storage's full `[max_seq_len, ...trailing]` shape.
710    pub layout: Layout,
711    /// Monotonic write version. Bumps on every successful
712    /// `Op::WriteSlice` targeting this slot. Placeholder for the future
713    /// multi-device coherence protocol — mirrors [`KvLayer::k_version`] /
714    /// `v_version`.
715    pub version: u64,
716    /// Coherence authority. Placeholder — see [`AuthorityState`].
717    pub authority: AuthorityState,
718}
719
720/// Cross-graph, cross-forward-pass persistent **N-slot** decode cache —
721/// the [`KvCache`] generalization for latent-caching attention
722/// architectures.
723///
724/// [`KvCache`] hardwires a symmetric K/V pair (two buffers per layer,
725/// same shape). That's wrong for compression architectures:
726///
727///   - **Multi-head Latent Attention (DeepSeek-V2 MLA)**: per layer, a
728///     low-rank compressed latent `[kv_lora_rank]` (slot 0) **and** a
729///     single-head RoPE key `[qk_rope_head_dim]` (slot 1) — two slots of
730///     *different* trailing shape, neither a `[n_kv_heads, head_dim]` K/V.
731///   - **Two-projection attention / QKV pruning**: a single retained
732///     projection per layer — one slot.
733///
734/// `LatentKvCache` is this module's counterpart to
735/// [`crate::lazy_latent_cache::LatentCache`] — that type makes the
736/// exact same **per-layer, ordered list of latent buffers with
737/// independent trailing shapes** generalization for the **per-forward-
738/// pass** (single [`fuel_graph::Graph`]-anchored, functional
739/// append-and-thread) lifecycle. `LatentKvCache` is the **persistent**
740/// sibling: device-resident `Arc<RwLock<Storage>>` buffers that survive
741/// across graphs/forward calls and are mutated in place via
742/// `Op::WriteSlice`, exactly the relationship [`KvCache`] has to a plain
743/// per-pass K/V cache. Read both modules' docs together for the two
744/// lifecycles side by side.
745///
746/// # Shape contract
747///
748/// Slot `s` of every layer is a buffer `[max_seq_len, ...slot_trailing[s]]`
749/// — the capacity axis is dim **0**. This differs from [`KvCache`]'s `[1,
750/// n_kv_heads, max_seq_len, head_dim]` convention (capacity axis 2):
751/// a latent is a per-token *vector*, not a per-head *plane*, so there is
752/// no head axis to lead with. Matches [`crate::lazy_latent_cache::
753/// LatentCache`]'s dim-0 convention exactly — this type's per-slot
754/// buffer is byte-for-byte what that type's `slot_buffer_full` realizes,
755/// modulo device residency.
756pub struct LatentKvCache {
757    /// `layers[l]` is `None` until populated; `Some(slots)` holds one
758    /// [`LatentSlot`] per slot index (pipeline-parallel friendly — mirrors
759    /// [`KvCache::layers`]).
760    pub layers: Vec<Option<Vec<LatentSlot>>>,
761    pub cached_len: usize,
762    /// Per-slot trailing shape (past the leading capacity axis); its
763    /// length is the per-layer slot count.
764    pub slot_trailing: Vec<Vec<usize>>,
765    pub max_seq_len: usize,
766    pub dtype: DType,
767    /// Identity of the allocation backing this cache. Same role and same
768    /// re-mint rules as [`KvCache::alloc_id`] — MLA reuses [`DecodeSession`]
769    /// verbatim (its 2 latent slots ride `kv_nodes` as `(latent, kpe)` pairs),
770    /// so it inherits the same welding and needs the same guard.
771    alloc_id: KvAllocId,
772    /// Where the slot buffers live. Unconditional here, unlike
773    /// [`KvCache::device_location`]: this type has exactly one constructor
774    /// and it is handed a `&Device`, so residency is never unprovable.
775    device_location: DeviceLocation,
776}
777
778impl LatentKvCache {
779    /// Pre-allocated N-slot latent cache. Every layer's slot buffers are
780    /// allocated up-front as zero buffers on `device` with `dtype`,
781    /// shaped `[max_seq_len, ...slot_trailing[s]]`. Mirrors [`KvCache::
782    /// with_capacity`]'s `Op::Alloc` → `Op::ZeroFill` graph-emission
783    /// pattern exactly, generalized from a fixed 2-buffer (K, V) layer to
784    /// `slot_trailing.len()` buffers of independent shape.
785    ///
786    /// Returns `Err` for degenerate geometry (`n_layers == 0`,
787    /// `max_seq_len == 0`, or no slots) or if any per-layer allocation
788    /// fails (e.g. CUDA OOM / an unwired device).
789    pub fn with_capacity(
790        n_layers: usize,
791        max_seq_len: usize,
792        slot_trailing: Vec<Vec<usize>>,
793        dtype: DType,
794        device: &Device,
795    ) -> Result<Self> {
796        if n_layers == 0 {
797            return Err(
798                Error::Msg("LatentKvCache::with_capacity: n_layers must be >= 1".into()).bt(),
799            );
800        }
801        if max_seq_len == 0 {
802            return Err(Error::Msg(
803                "LatentKvCache::with_capacity: max_seq_len must be >= 1".into(),
804            )
805            .bt());
806        }
807        if slot_trailing.is_empty() {
808            return Err(Error::Msg(
809                "LatentKvCache::with_capacity: need at least one slot (slot_trailing empty)".into(),
810            )
811            .bt());
812        }
813        let n_slots = slot_trailing.len();
814        let shapes: Vec<Shape> = slot_trailing
815            .iter()
816            .map(|trailing| {
817                let mut dims = Vec::with_capacity(1 + trailing.len());
818                dims.push(max_seq_len);
819                dims.extend_from_slice(trailing);
820                Shape::from_dims(&dims)
821            })
822            .collect();
823        let layouts: Vec<Layout> = shapes
824            .iter()
825            .map(|s| Layout::contiguous(s.clone()))
826            .collect();
827        let target_loc = device.location();
828
829        // Transient graph, same device-anchor trick + Alloc/ZeroFill
830        // emission pattern as KvCache::with_capacity — see that
831        // constructor's doc for the full rationale.
832        let graph = Arc::new(RwLock::new(Graph::new()));
833        let cache = StorageCache::new();
834
835        // Emit (Op::Alloc, Op::ZeroFill) pairs for every (layer, slot),
836        // each shaped per its own slot's shape.
837        let mut zero_fill_ids: Vec<NodeId> = Vec::with_capacity(n_layers * n_slots);
838        {
839            let mut g = graph.write().map_err(|_| {
840                Error::Msg("graph lock poisoned during LatentKvCache build".into()).bt()
841            })?;
842            for _ in 0..n_layers {
843                for shape in &shapes {
844                    let alloc_id = g.push(Node {
845                        op: Op::Alloc { target: target_loc },
846                        inputs: vec![],
847                        shape: shape.clone(),
848                        dtype,
849                    });
850                    let zf_id = g.push(Node {
851                        op: Op::ZeroFill,
852                        inputs: vec![alloc_id],
853                        shape: shape.clone(),
854                        dtype,
855                    });
856                    zero_fill_ids.push(zf_id);
857                }
858            }
859        }
860
861        // Realize all n_layers * n_slots Op::ZeroFill targets in one pass
862        // — see KvCache::with_capacity's doc for why a single realize_many
863        // call is used instead of one realize per buffer.
864        let realized = PipelinedExecutor::realize_many_with_devices(
865            Arc::clone(&graph),
866            &zero_fill_ids,
867            cache,
868            crate::pipelined_bridge::primary_device_registry(device)?,
869        )?;
870        if realized.len() != n_layers * n_slots {
871            return Err(Error::Msg(format!(
872                "LatentKvCache::with_capacity: realize_many returned {} storages \
873                 for {} Op::ZeroFill targets — internal bug",
874                realized.len(),
875                n_layers * n_slots,
876            ))
877            .bt());
878        }
879
880        // Never-panic: length checked above; still surface a typed `Err`
881        // rather than `.expect()` on a production path.
882        let mut realized_iter = realized.into_iter();
883        let short = |l: usize| {
884            Error::Msg(format!(
885                "alloc_latent: realize_many yielded fewer storages than \
886                 expected (ran out at layer {l})"
887            ))
888            .bt()
889        };
890        let mut layers: Vec<Option<Vec<LatentSlot>>> = Vec::with_capacity(n_layers);
891        for l in 0..n_layers {
892            let mut slots = Vec::with_capacity(n_slots);
893            for layout in &layouts {
894                let (arc, _) = realized_iter.next().ok_or_else(|| short(l))?;
895                slots.push(LatentSlot {
896                    storage: arc,
897                    layout: layout.clone(),
898                    version: 0,
899                    authority: AuthorityState::Host,
900                });
901            }
902            layers.push(Some(slots));
903        }
904
905        Ok(Self {
906            layers,
907            cached_len: 0,
908            slot_trailing,
909            max_seq_len,
910            dtype,
911            alloc_id: KvAllocId::next(),
912            device_location: target_loc,
913        })
914    }
915
916    /// Borrow the slot `s` storage Arc for layer `layer_idx`. `None` if
917    /// the layer is unpopulated or either index is out of range. Used by
918    /// the forward path to bind cache storage to per-step Const nodes via
919    /// [`InferenceContext::insert`]. Mirrors [`KvCache::slot_storage`].
920    pub fn slot_storage(&self, layer_idx: usize, slot: usize) -> Option<Arc<RwLock<Storage>>> {
921        let layer = self.layers.get(layer_idx)?.as_ref()?;
922        layer.get(slot).map(|s| Arc::clone(&s.storage))
923    }
924
925    /// Bump slot `s`'s monotonic version counter for `layer_idx`. No-op
926    /// (never panics) if either index is out of range. Mirrors
927    /// [`KvCache::bump_version`].
928    pub fn bump_version(&mut self, layer_idx: usize, slot: usize) {
929        if let Some(Some(layer)) = self.layers.get_mut(layer_idx)
930            && let Some(s) = layer.get_mut(slot)
931        {
932            s.version += 1;
933        }
934    }
935
936    pub fn n_layers(&self) -> usize {
937        self.layers.len()
938    }
939
940    /// Number of slots per layer.
941    pub fn n_slots(&self) -> usize {
942        self.slot_trailing.len()
943    }
944
945    /// Trailing shape of slot `s` (past the leading capacity axis).
946    pub fn slot_trailing(&self, s: usize) -> &[usize] {
947        &self.slot_trailing[s]
948    }
949
950    /// Identity of the storage this cache currently owns. Mirrors
951    /// [`KvCache::alloc_id`]; see [`KvAllocId`].
952    pub fn alloc_id(&self) -> KvAllocId {
953        self.alloc_id
954    }
955
956    /// Drop every layer; reset `cached_len` to zero. Mirrors [`KvCache::clear`],
957    /// including the [`Self::alloc_id`] re-mint — every storage `Arc` is
958    /// released, so a plan welded to them must be rebuilt.
959    pub fn clear(&mut self) {
960        for layer in &mut self.layers {
961            *layer = None;
962        }
963        self.cached_len = 0;
964        self.alloc_id = KvAllocId::next();
965    }
966
967    /// Shrink the cache to `new_len` cached positions — metadata-only,
968    /// same Phase E.3.0 limitation and rationale as [`KvCache::
969    /// truncate_to`]: the underlying storages are not shrunk; the
970    /// pre-allocated buffers' trailing rows simply stop being read until
971    /// overwritten by a later `Op::WriteSlice` at the same positions.
972    ///
973    /// Deliberately preserves [`Self::alloc_id`] — a rewind is not a
974    /// re-allocation. Same rule as [`KvCache::truncate_to`].
975    pub fn truncate_to(&mut self, new_len: usize) {
976        if new_len < self.cached_len {
977            self.cached_len = new_len;
978        }
979    }
980}
981
982// ===========================================================================
983// Guarded KV re-bind (GAP-028)
984// ===========================================================================
985
986/// A KV allocation a held [`DecodeSession`] can be re-bound onto — the one
987/// abstraction over [`KvCache`] (K/V pairs) and [`LatentKvCache`] (MLA's
988/// `(latent, kpe)` pairs), which already share `DecodeSession` verbatim and
989/// therefore share its welding.
990///
991/// Deliberately narrow: identity, residency, and the storage behind a baked
992/// `kv_nodes` slot. Geometry is **not** here, because the guard does not ask
993/// this trait for it — it compares the incoming storage against the storage
994/// already baked into the plan, which is ground truth and cannot drift from
995/// whatever a cache believes about itself.
996pub trait KvRebindSource {
997    /// Identity of this allocation. See [`KvAllocId`].
998    fn alloc_id(&self) -> KvAllocId;
999    /// Where the storage lives, or `None` when that is not provable — which
1000    /// [`DecodeSession::rebind_kv`] treats as a refusal, never as a default.
1001    fn rebind_location(&self) -> Option<DeviceLocation>;
1002    /// Storage for slot `which` (0 or 1) of `layer` — the two halves of the
1003    /// plan's `kv_nodes[layer]` pair, in the order the builder bound them.
1004    fn rebind_slot(&self, layer: usize, which: usize) -> Option<Arc<RwLock<Storage>>>;
1005}
1006
1007impl KvRebindSource for KvCache {
1008    fn alloc_id(&self) -> KvAllocId {
1009        KvCache::alloc_id(self)
1010    }
1011    fn rebind_location(&self) -> Option<DeviceLocation> {
1012        self.device_location
1013    }
1014    fn rebind_slot(&self, layer: usize, which: usize) -> Option<Arc<RwLock<Storage>>> {
1015        // The builder pushes `(k_id, v_id)` — this order is the contract.
1016        let slot = match which {
1017            0 => KvSlot::K,
1018            1 => KvSlot::V,
1019            _ => return None,
1020        };
1021        self.slot_storage(layer, slot)
1022    }
1023}
1024
1025impl KvRebindSource for LatentKvCache {
1026    fn alloc_id(&self) -> KvAllocId {
1027        LatentKvCache::alloc_id(self)
1028    }
1029    fn rebind_location(&self) -> Option<DeviceLocation> {
1030        Some(self.device_location)
1031    }
1032    fn rebind_slot(&self, layer: usize, which: usize) -> Option<Arc<RwLock<Storage>>> {
1033        // MLA binds `(latent, kpe)` as slots 0 and 1 — same positional
1034        // contract as K/V above, which is why one `DecodeSession` serves both.
1035        self.slot_storage(layer, which)
1036    }
1037}
1038
1039/// Why a held plan could not be re-bound onto a replacement KV allocation.
1040///
1041/// A refusal is a normal outcome, not an error: the caller falls back to the
1042/// GAP-014 rebuild, which is correct by construction. The variants exist so
1043/// the guard's reasons are *nameable in a test* — the point of GAP-028 is that
1044/// this guard is load-bearing for correctness, so "it refused" is not enough
1045/// to know it refused for the right reason.
1046#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1047pub enum RebindRefusal {
1048    /// The replacement cannot say where its storage lives, so residency
1049    /// cannot be proven equal to the plan's. See [`KvCache::device_location`].
1050    ResidencyUnknown,
1051    /// The plan's placement stamps and residency copies were baked for a
1052    /// different device.
1053    ResidencyDiffers {
1054        baked: DeviceLocation,
1055        incoming: DeviceLocation,
1056    },
1057    /// The replacement has no storage for a slot the plan writes.
1058    MissingSlot { layer: usize, which: usize },
1059    /// A baked KV `Const` has no `base_cache` entry — an internal
1060    /// inconsistency in the held plan, not a property of the replacement.
1061    UnbakedSlot { layer: usize, which: usize },
1062    /// The replacement storage is not byte-interchangeable with the baked
1063    /// storage: different dtype, encoding, backend variant, or extent.
1064    StorageDiffers { layer: usize, which: usize },
1065    /// A storage lock was poisoned while comparing. Refuse rather than guess.
1066    LockPoisoned,
1067}
1068
1069/// Whether a held plan may serve a step, and if not, why not — **one** set of
1070/// comparisons, so the "is it valid" and "is only the allocation different"
1071/// questions cannot drift apart. [`DecodeSession::is_valid_for`] is a thin
1072/// view over this.
1073#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1074pub enum PlanValidity {
1075    /// Reuse the plan as-is.
1076    Valid,
1077    /// Everything the plan bakes still matches **except which KV allocation
1078    /// it is welded to.** A guarded [`DecodeSession::rebind_kv`] may rescue
1079    /// it; without one, the plan MUST NOT be reused — that is GAP-014.
1080    AllocationChanged,
1081    /// Something structural differs (shape, layer count, dtype, or the model
1082    /// itself). Rebuild.
1083    Stale,
1084}
1085
1086/// Everything about a storage that a baked graph depends on and that is
1087/// readable from the storage itself. Deliberately excludes residency, which
1088/// is NOT readable — see [`DecodeSession::rebind_kv`].
1089#[derive(PartialEq, Eq)]
1090struct StorageFingerprint {
1091    dtype: DType,
1092    stype: SType,
1093    bundled: bool,
1094    backend: std::mem::Discriminant<BackendStorage>,
1095    len_bytes: usize,
1096}
1097
1098fn fingerprint(s: &Arc<RwLock<Storage>>) -> Option<StorageFingerprint> {
1099    let g = s.read().ok()?;
1100    Some(StorageFingerprint {
1101        dtype: g.dtype,
1102        stype: g.stype.clone(),
1103        bundled: g.bundle.is_some(),
1104        backend: std::mem::discriminant(&g.inner),
1105        len_bytes: g.inner.len_bytes(),
1106    })
1107}
1108
1109/// May `incoming` stand in for `baked` inside an already-optimized graph?
1110/// `None` means a lock was poisoned and the question could not be answered —
1111/// which callers must treat as "no", not as "probably fine".
1112///
1113/// The two locks are taken one at a time and released before the next, so this
1114/// cannot deadlock even if some future caller passes overlapping storage.
1115fn storage_is_interchangeable(
1116    baked: &Arc<RwLock<Storage>>,
1117    incoming: &Arc<RwLock<Storage>>,
1118) -> Option<bool> {
1119    if Arc::ptr_eq(baked, incoming) {
1120        return Some(true);
1121    }
1122    let a = fingerprint(baked)?;
1123    let b = fingerprint(incoming)?;
1124    Some(a == b)
1125}
1126
1127// ===========================================================================
1128// DecodeSession (Phase D · D2b — plan-once persistent decode)
1129// ===========================================================================
1130
1131/// Per-token re-bound data-Const Arcs for a persistent decode step
1132/// (Phase D · D2b). Each is a device-resident `fuel_memory::Storage`
1133/// built from freshly recomputed host bytes (token-ids = the new token,
1134/// RoPE cos+sin at `position = cached_len`, mask with the shifted `-inf`
1135/// boundary). [`DecodeSession::realize_token`] overwrites the held
1136/// `base_cache`'s stable data-Const entries with these for the token.
1137pub struct DecodeTokenData {
1138    pub token_ids: Arc<RwLock<Storage>>,
1139    pub rope_cos: Arc<RwLock<Storage>>,
1140    pub rope_sin: Arc<RwLock<Storage>>,
1141    pub mask: Arc<RwLock<Storage>>,
1142    /// The device-resident KV-write offset (`cached_len` as a rank-0
1143    /// `I64`), present ONLY on the device-offset decode path (CUDA/CPU
1144    /// targets, where `Op::WriteSliceDoff` reads the start from this
1145    /// buffer at kernel launch — capture-ready). `None` on the SymEnv
1146    /// path (Vulkan), where the KV write is `Op::WriteSlice` with a
1147    /// `DynScalar::Sym(cached_len)` offset resolved host-side per token.
1148    pub offset: Option<Arc<RwLock<Storage>>>,
1149}
1150
1151/// Plan-once persistent decode state for one `LlamaModel` + one
1152/// [`KvCache`] capacity/dtype. Built on the first `seq == 1` decode token;
1153/// reused (graph + optimize view HELD, only the per-token data Consts +
1154/// `SymEnv` re-bound) for every subsequent token.
1155///
1156/// The ~1.8×/token win lives here: the decode-step graph is built +
1157/// `prepare`d (D2H `Op::Copy` spliced at the root) + `optimize_graph`'d
1158/// (placement stamps + residency `Op::Copy` + layout `Op::Contiguize`
1159/// baked in place) ONCE, then re-realized via the D2a prebuilt seam
1160/// ([`InferenceContext::realize_prebuilt_as_with_env`]) which SKIPS both
1161/// `prepare` and `optimize_graph`.
1162///
1163/// Held by the generate-loop owner (the caller of
1164/// `forward_with_kv_context_persistent`), NOT by the immutable
1165/// `LlamaModel` (the model is read-only weights; a session is per-
1166/// generation state). Constructed lazily as `Option<DecodeSession>` and
1167/// dropped-then-rebuilt on any validity-key mismatch / `TopologyChanged`
1168/// / a non-`seq==1` step (see `forward_with_kv_context_persistent`).
1169///
1170/// ## Why the graph is HELD here
1171///
1172/// D1 rebuilds a fresh `Tensor` graph every token and drops it after
1173/// realize. D2 keeps the `Arc<RwLock<Graph>>` alive on the session so the
1174/// already-optimized structure (the stamps + inserted copies) survives.
1175/// The cached [`OptimizedGraph`] holds only `{roots, generation}` — it
1176/// bakes NO Const data / storage / `SymEnv`, so reusing it is sound
1177/// **iff the graph structure + topology generation are unchanged** (D1's
1178/// input-independent-graph guarantee).
1179pub struct DecodeSession {
1180    /// The held decode-step graph, ALREADY optimized in place (stamps +
1181    /// residency/layout copies + D2H root splice baked in). Structure is
1182    /// stable across tokens (D1 guarantee).
1183    graph: Arc<RwLock<Graph>>,
1184    /// The cached optimize view from the first realize. Holds only
1185    /// `{roots, generation}`; valid while `graph` structure + topology
1186    /// generation are unchanged.
1187    optimized: OptimizedGraph,
1188    /// The realize root the executor was asked for — the D2H `Op::Copy`
1189    /// NodeId `prepare` spliced (NOT the logits node itself). Stable
1190    /// across tokens.
1191    effective_target: NodeId,
1192    /// The logits node (pre-D2H-splice) — `effective_target`'s input.
1193    /// Retained for D3 attribution / debugging; the executor is asked
1194    /// for `effective_target`. Also the CapturedRun replay TARGET
1195    /// (`CapturedDecodeSession::capture` must be given the pre-splice
1196    /// node — see [`Self::logits_node`]'s doc for why).
1197    logits_node: NodeId,
1198    /// Stable re-bindable token-ids Const (`[seq]` U32).
1199    token_ids_node: NodeId,
1200    /// Stable re-bindable RoPE cos table Const (`[seq, head_dim]` F32).
1201    rope_cos_node: NodeId,
1202    /// Stable re-bindable RoPE sin table Const (`[seq, head_dim]` F32).
1203    rope_sin_node: NodeId,
1204    /// Stable re-bindable causal mask Const (`[1, 1, seq, max_seq_len]`
1205    /// F32) — hoisted to ONE shared Const (was per-layer in D1).
1206    mask_node: NodeId,
1207    /// Per-layer `(k_const, v_const)` stable KV placeholder NodeIds. The
1208    /// KV Arcs are re-bound once at build time and mutated in place by
1209    /// `Op::WriteSlice`/`Op::WriteSliceDoff` each token (never re-inserted
1210    /// per token).
1211    kv_nodes: Vec<(NodeId, NodeId)>,
1212    /// The stable rank-0 `I64` KV-write offset Const, present ONLY on the
1213    /// **device-offset** decode path (CUDA/CPU — `Op::WriteSliceDoff`
1214    /// reads `cached_len` from this buffer device-side at launch, making
1215    /// the decode step CUDA-graph-capturable). `None` on the SymEnv path
1216    /// (Vulkan — the offset is host-resolved via `cached_len_sym`). When
1217    /// `Some`, `realize_token` re-binds the per-token offset Arc into the
1218    /// base-cache clone alongside token-ids/RoPE/mask.
1219    offset_node: Option<NodeId>,
1220    /// The symbol the per-pass `SymEnv` binds to `cached_len` each token.
1221    cached_len_sym: SymId,
1222    /// The symbol the per-pass `SymEnv` binds to the live **attended
1223    /// prefix length** (`cached_len + seq`) each token. This is the
1224    /// `k_len` the optimizer-emitted CUDA flash-decode arm resolves
1225    /// against (`decode_flash::DecodeFlashSpec::k_len`); distinct from
1226    /// `cached_len_sym` because the flash kernel attends `[0, k_len)`
1227    /// (the whole prefix including this token), while the KV-write lands
1228    /// at `[cached_len, cached_len + seq)`. Unreferenced on today's f32
1229    /// decode graph (no flash arm offered) — a harmless extra binding.
1230    attended_len_sym: SymId,
1231    /// The full realized [`StorageCache`] from the first realize — every
1232    /// reachable `Op::Const` (weights + the KV Arcs + the initial data
1233    /// Consts) that `build_const_cache` uploaded. Held because the
1234    /// prebuilt-realize path SKIPS the const-cache walk: each token we
1235    /// clone this and overwrite ONLY the per-token data-Const entries
1236    /// (token-ids / RoPE / mask). The weight Arcs + KV Arcs are stable
1237    /// (KV mutates in place via `Op::WriteSlice`).
1238    base_cache: StorageCache,
1239    /// The `seq` the held graph is shape-keyed to (always 1 for D2 decode).
1240    seq: usize,
1241    // ---- validity keys — rebuild if any change vs. the live cache/model ----
1242    max_seq_len: usize,
1243    n_layers: usize,
1244    cache_dtype: DType,
1245    /// The [`crate::decode_shape`] key this plan was baked against — model
1246    /// structure + weight identity. See [`Self::is_valid_for`].
1247    shape_key: u64,
1248    /// The KV **allocation** whose storage `Arc`s are baked into `base_cache`.
1249    /// `rebind_and_realize_prebuilt` never re-binds `kv_nodes`, so this plan
1250    /// reads and writes THESE buffers regardless of which cache the caller
1251    /// hands in — unless [`Self::rebind_kv`] re-points them — making the id,
1252    /// not the geometry, the thing that decides reuse. See [`KvAllocId`] and
1253    /// [`Self::is_valid_for`].
1254    alloc_id: KvAllocId,
1255    /// Where the KV `Arc`s baked into `base_cache` lived when this graph was
1256    /// optimized. The placement stamps and residency `Op::Copy`s in `graph`
1257    /// were chosen against THIS location, so [`Self::rebind_kv`] must refuse a
1258    /// replacement that lives anywhere else. `None` when the source could not
1259    /// prove it, which is likewise a refusal.
1260    kv_location: Option<DeviceLocation>,
1261    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1262    /// §5): the memoized dispatch order for this session's
1263    /// `(graph, effective_target, optimized)` triple, computed once on the
1264    /// first `realize_token` call and reused on every later one — measured
1265    /// as the single largest named per-token sub-cost prior to this cache
1266    /// (`extract_runs_multi` + `non_chosen_arm_nodes`, ~56ms/step on an RTX
1267    /// 4070). Empty at construction; `realize_token` never resets it, since
1268    /// a `DecodeSession` holds one shape-keyed graph for its whole lifetime
1269    /// (see `is_valid_for` — any mismatch rebuilds a fresh session with a
1270    /// fresh, empty cache, never reuses this one against a different graph).
1271    order_cache: std::sync::OnceLock<Vec<NodeId>>,
1272}
1273
1274impl DecodeSession {
1275    /// Assemble a held session from the artifacts a first-realize
1276    /// prebuild produced. `graph` is the (already prepared + optimized)
1277    /// held decode graph; `effective_target` / `optimized` come from
1278    /// [`InferenceContext::prebuild_optimized_as_with_env`]; the node ids
1279    /// are the STABLE data-Const NodeIds the builder minted.
1280    pub fn new(
1281        graph: Arc<RwLock<Graph>>,
1282        optimized: OptimizedGraph,
1283        effective_target: NodeId,
1284        logits_node: NodeId,
1285        token_ids_node: NodeId,
1286        rope_cos_node: NodeId,
1287        rope_sin_node: NodeId,
1288        mask_node: NodeId,
1289        kv_nodes: Vec<(NodeId, NodeId)>,
1290        offset_node: Option<NodeId>,
1291        cached_len_sym: SymId,
1292        attended_len_sym: SymId,
1293        base_cache: StorageCache,
1294        seq: usize,
1295        max_seq_len: usize,
1296        n_layers: usize,
1297        cache_dtype: DType,
1298        shape_key: u64,
1299        kv: &dyn KvRebindSource,
1300    ) -> Self {
1301        Self {
1302            shape_key,
1303            // Identity and residency are read from the SAME source in the same
1304            // breath, so they cannot describe different allocations — which a
1305            // pair of separate `alloc_id` / `location` parameters could.
1306            alloc_id: kv.alloc_id(),
1307            kv_location: kv.rebind_location(),
1308            graph,
1309            optimized,
1310            effective_target,
1311            logits_node,
1312            token_ids_node,
1313            rope_cos_node,
1314            rope_sin_node,
1315            mask_node,
1316            kv_nodes,
1317            offset_node,
1318            cached_len_sym,
1319            attended_len_sym,
1320            base_cache,
1321            seq,
1322            max_seq_len,
1323            n_layers,
1324            cache_dtype,
1325            order_cache: std::sync::OnceLock::new(),
1326        }
1327    }
1328
1329    /// Realize the held graph for one decode token via the D2a prebuilt
1330    /// seam (SKIP `prepare` + `optimize_graph`). `data` supplies the
1331    /// per-token re-bound data-Const Arcs (token-ids / RoPE cos+sin /
1332    /// mask); they overwrite the held `base_cache`'s entries for this
1333    /// token (the weight + KV Arcs stay from `base_cache`). `sym_env`
1334    /// binds `cached_len`. `TopologyChanged` surfaces typed (caller
1335    /// invalidates the session).
1336    pub fn realize_token(
1337        &self,
1338        device: &Device,
1339        data: DecodeTokenData,
1340        sym_env: &SymEnv,
1341    ) -> Result<Vec<f32>> {
1342        let _t = fuel_dispatch::compiled::op_profile::PhaseTimer::start("decode.realize_token");
1343        let mut cache = self.base_cache.clone();
1344        cache.insert(self.token_ids_node, data.token_ids);
1345        cache.insert(self.rope_cos_node, data.rope_cos);
1346        cache.insert(self.rope_sin_node, data.rope_sin);
1347        cache.insert(self.mask_node, data.mask);
1348        // Device-offset path (CUDA/CPU): re-bind the per-token KV-write
1349        // offset (`cached_len` as I64) into the base-cache clone so the
1350        // held `Op::WriteSliceDoff` nodes read the live position from a
1351        // fixed device buffer. On the SymEnv path both are `None` (the
1352        // offset rides `cached_len_sym` in `sym_env` instead).
1353        if let (Some(offset_node), Some(offset)) = (self.offset_node, data.offset) {
1354            cache.insert(offset_node, offset);
1355        }
1356        crate::pipelined_bridge::realize_one_prebuilt_cached_env::<f32>(
1357            &self.graph,
1358            self.effective_target,
1359            &self.optimized,
1360            &self.order_cache,
1361            device,
1362            cache,
1363            sym_env,
1364        )
1365    }
1366
1367    /// Whether this held session is valid for the given decode step.
1368    /// Rebuild (drop + build fresh) on any mismatch. `seq` must be 1
1369    /// (the held graph is the seq==1 decode graph); a change in
1370    /// `max_seq_len` / `n_layers` / `cache_dtype` means a different
1371    /// model/cache → the held graph's shapes are stale.
1372    /// May this held plan be reused for a step with these parameters?
1373    ///
1374    /// `shape_key` is the caller's [`crate::decode_shape`] key. Geometry alone
1375    /// is NOT sufficient and was the whole reason that module exists: a held
1376    /// graph bakes its op structure and its weight `Const`s, so two models at
1377    /// identical dims — a different architecture, or the same architecture with
1378    /// different weights — would otherwise be judged interchangeable and one
1379    /// would silently execute the other's baked plan.
1380    ///
1381    /// `alloc_id` is the live cache's [`KvCache::alloc_id`]. It is a SEPARATE
1382    /// question from `shape_key` and neither subsumes the other: `shape_key`
1383    /// names the model whose weights are baked in, `alloc_id` names the KV
1384    /// buffers the plan writes into. One model serving many concurrent
1385    /// requests has one `shape_key` and one allocation per request, and it is
1386    /// exactly that case — the slot-pooled server — where geometry-only keying
1387    /// hands request B a plan welded to request A's KV. Nothing errors: B just
1388    /// decodes over A's context at full speed.
1389    ///
1390    /// Both directions matter. Returning `true` too readily is a wrong answer
1391    /// at full speed; returning `false` too readily forfeits plan reuse
1392    /// (measured 223× on CUDA) while every correctness test stays green. That
1393    /// second direction is why `alloc_id` tracks the ALLOCATION and not the
1394    /// conversation — see [`KvCache::truncate_to`], which must not invalidate.
1395    pub fn is_valid_for(
1396        &self,
1397        seq: usize,
1398        max_seq_len: usize,
1399        n_layers: usize,
1400        cache_dtype: DType,
1401        shape_key: u64,
1402        alloc_id: KvAllocId,
1403    ) -> bool {
1404        matches!(
1405            self.validity_for(seq, max_seq_len, n_layers, cache_dtype, shape_key, alloc_id),
1406            PlanValidity::Valid,
1407        )
1408    }
1409
1410    /// The same comparisons as [`Self::is_valid_for`], reporting *which kind*
1411    /// of mismatch occurred rather than collapsing to a bool.
1412    ///
1413    /// The split exists so GAP-028 does not introduce a second predicate. A
1414    /// caller that wants to try [`Self::rebind_kv`] needs to know "everything
1415    /// matches except the allocation", and answering that with an
1416    /// `is_valid_ignoring_alloc` twin would leave two comparison lists to keep
1417    /// in sync — the exact drift that made
1418    /// `lazy::invalidate_decode_pair_if_stale` a shared free function instead
1419    /// of a per-model copy. There is one list, here.
1420    ///
1421    /// Note the asymmetry between the two non-`Valid` answers.
1422    /// `AllocationChanged` is a *conditional* verdict: it says a re-bind is
1423    /// worth attempting, NOT that one is safe. Everything it reports on is a
1424    /// property of the held plan; whether the incoming storage is actually
1425    /// interchangeable is [`Self::rebind_kv`]'s question, and it is answered
1426    /// against the storage itself.
1427    pub fn validity_for(
1428        &self,
1429        seq: usize,
1430        max_seq_len: usize,
1431        n_layers: usize,
1432        cache_dtype: DType,
1433        shape_key: u64,
1434        alloc_id: KvAllocId,
1435    ) -> PlanValidity {
1436        let structural = self.seq == seq
1437            && self.max_seq_len == max_seq_len
1438            && self.n_layers == n_layers
1439            && self.cache_dtype == cache_dtype
1440            && self.shape_key == shape_key;
1441        if !structural {
1442            return PlanValidity::Stale;
1443        }
1444        if self.alloc_id == alloc_id {
1445            PlanValidity::Valid
1446        } else {
1447            PlanValidity::AllocationChanged
1448        }
1449    }
1450
1451    /// Re-point the held plan's baked KV `Const`s at a replacement allocation,
1452    /// or refuse — the GAP-028 alternative to throwing the plan away.
1453    ///
1454    /// ## What this trades
1455    ///
1456    /// GAP-014 shipped invalidate-and-rebuild, which is safe **by
1457    /// construction**: a plan welded to storage it no longer serves is simply
1458    /// destroyed, and no guard can be wrong because there is no guard. This
1459    /// method replaces that with a guarantee that holds **by proof**. If the
1460    /// checks below ever accept an incompatible allocation, the failure mode is
1461    /// GAP-014 verbatim — a plan executing one request's tokens over another's
1462    /// KV, at full speed, with a plausible distribution and nothing to report.
1463    /// Every check here is therefore load-bearing for correctness, not for
1464    /// performance, and the cost of refusing wrongly is only a rebuild.
1465    ///
1466    /// ## What is checked, and against what
1467    ///
1468    /// Not against the cache's own description of itself — against the storage
1469    /// **already baked into `base_cache`**, which is ground truth and cannot
1470    /// disagree with the graph the way a `KvCache` field can. Per slot: dtype,
1471    /// encoding, backend variant, bundling, and byte extent. Byte extent is the
1472    /// load-bearing one: it collapses `batch × n_kv_heads × max_seq_len ×
1473    /// head_dim` into a single comparison that needs no reconstruction of the
1474    /// baked shape.
1475    ///
1476    /// Residency is the exception and is why [`KvRebindSource::rebind_location`]
1477    /// exists. `fuel_memory::Storage` exposes a backend *variant* but no device
1478    /// ordinal — `VulkanStorage` records none at all — so a same-geometry cache
1479    /// on a *different GPU of the same backend* is invisible from the bytes. It
1480    /// would pass every check above and be spliced into a graph whose placement
1481    /// stamps and residency `Op::Copy`s were baked for the old device. An
1482    /// unprovable residency is therefore a refusal, never a default.
1483    ///
1484    /// ## What the caller still owes
1485    ///
1486    /// **A re-bind invalidates any capture.** A `CapturedDecodeSession` records
1487    /// a CUDA graph over FIXED device addresses drawn from `base_cache`; after
1488    /// this returns `Ok`, some of those addresses name the old allocation.
1489    /// Callers must clear the capture alongside, on the same
1490    /// reader-before-owner rule that governs
1491    /// `lazy::invalidate_decode_pair_if_stale`.
1492    ///
1493    /// Structural validity is NOT rechecked here — call this only when
1494    /// [`Self::validity_for`] answered [`PlanValidity::AllocationChanged`].
1495    pub fn rebind_kv(
1496        &mut self,
1497        kv: &dyn KvRebindSource,
1498    ) -> core::result::Result<(), RebindRefusal> {
1499        let incoming_loc = kv
1500            .rebind_location()
1501            .ok_or(RebindRefusal::ResidencyUnknown)?;
1502        let baked_loc = self.kv_location.ok_or(RebindRefusal::ResidencyUnknown)?;
1503        if baked_loc != incoming_loc {
1504            return Err(RebindRefusal::ResidencyDiffers {
1505                baked: baked_loc,
1506                incoming: incoming_loc,
1507            });
1508        }
1509
1510        // Collect first, mutate second. A partial re-bind — some slots on the
1511        // new allocation, the rest still on the old — is the one state strictly
1512        // worse than either endpoint, and the only way to avoid it is to refuse
1513        // before touching `base_cache`.
1514        let mut staged: Vec<(NodeId, Arc<RwLock<Storage>>)> =
1515            Vec::with_capacity(self.kv_nodes.len() * 2);
1516        for (layer, &(k_node, v_node)) in self.kv_nodes.iter().enumerate() {
1517            for (which, node) in [(0usize, k_node), (1usize, v_node)] {
1518                let incoming = kv
1519                    .rebind_slot(layer, which)
1520                    .ok_or(RebindRefusal::MissingSlot { layer, which })?;
1521                let baked = self
1522                    .base_cache
1523                    .get(&node)
1524                    .ok_or(RebindRefusal::UnbakedSlot { layer, which })?;
1525                if !storage_is_interchangeable(baked, &incoming)
1526                    .ok_or(RebindRefusal::LockPoisoned)?
1527                {
1528                    return Err(RebindRefusal::StorageDiffers { layer, which });
1529                }
1530                staged.push((node, incoming));
1531            }
1532        }
1533
1534        for (node, arc) in staged {
1535            self.base_cache.insert(node, arc);
1536        }
1537        self.alloc_id = kv.alloc_id();
1538        Ok(())
1539    }
1540
1541    /// The held graph handle (the caller re-binds data Consts + realizes
1542    /// through it).
1543    pub fn graph(&self) -> &Arc<RwLock<Graph>> {
1544        &self.graph
1545    }
1546
1547    /// The cached optimize view (fed to the prebuilt-realize seam).
1548    pub fn optimized(&self) -> &OptimizedGraph {
1549        &self.optimized
1550    }
1551
1552    /// The D2H `Op::Copy` root the executor is asked for.
1553    pub fn effective_target(&self) -> NodeId {
1554        self.effective_target
1555    }
1556
1557    /// The logits node (pre-D2H-splice) — `capture_decode` hard-rejects
1558    /// any `Op::Copy`/`Move` in the captured graph (cross-device, not
1559    /// single-device-CUDA-capturable), so [`fuel_dispatch::pipelined::
1560    /// CapturedDecodeSession::capture`] must target THIS node, not
1561    /// [`Self::effective_target`] (the spliced D2H `Op::Copy` root).
1562    /// The D2H happens OUTSIDE the capture, after `replay_token` returns
1563    /// the device-resident output Arc.
1564    pub fn logits_node(&self) -> NodeId {
1565        self.logits_node
1566    }
1567    pub fn token_ids_node(&self) -> NodeId {
1568        self.token_ids_node
1569    }
1570    pub fn rope_cos_node(&self) -> NodeId {
1571        self.rope_cos_node
1572    }
1573    pub fn rope_sin_node(&self) -> NodeId {
1574        self.rope_sin_node
1575    }
1576    pub fn mask_node(&self) -> NodeId {
1577        self.mask_node
1578    }
1579    pub fn kv_nodes(&self) -> &[(NodeId, NodeId)] {
1580        &self.kv_nodes
1581    }
1582    /// The device-resident KV-write offset Const NodeId, `Some` only on
1583    /// the device-offset decode path (CUDA/CPU); `None` on Vulkan's
1584    /// SymEnv path. Used by the CapturedRun replay wiring (Phase 3) and
1585    /// the per-token offset re-bind.
1586    pub fn offset_node(&self) -> Option<NodeId> {
1587        self.offset_node
1588    }
1589    pub fn cached_len_sym(&self) -> SymId {
1590        self.cached_len_sym
1591    }
1592    pub fn attended_len_sym(&self) -> SymId {
1593        self.attended_len_sym
1594    }
1595    pub fn max_seq_len(&self) -> usize {
1596        self.max_seq_len
1597    }
1598
1599    /// Build the per-token [`SymEnv`] for one decode step: bind
1600    /// `cached_len_sym = cached_len` (the KV-write offset) AND
1601    /// `attended_len_sym = cached_len + seq` (the flash-arm `k_len` — the
1602    /// live attended prefix including this token). Both are bound each
1603    /// token; the attended-length binding is unreferenced on today's f32
1604    /// decode graph (no flash arm) and becomes load-bearing the moment a
1605    /// bf16/f16 CUDA decode offers the arm. Write-once per pass (a
1606    /// conflicting rebind surfaces a typed error, never a panic).
1607    /// # DO NOT DELETE THE `cached_len_sym` BINDING BECAUSE IT LOOKS DEAD
1608    ///
1609    /// **`LlamaModel` and `PhiModel` take DIFFERENT decode paths on CPU/F32,
1610    /// measured 2026-08-12 (GAP-029 2b):**
1611    ///
1612    /// ```text
1613    /// llama: offset_node.is_some() == true   → device-offset path; SymEnv INERT
1614    /// phi:   offset_node.is_some() == false  → SymEnv path;        SymEnv LIVE
1615    /// ```
1616    ///
1617    /// On the device-offset path the KV write offset rides a device-resident
1618    /// buffer (`Op::WriteSliceDoff` reads the start from
1619    /// [`DecodeTokenData::offset`] at launch), so **no symbol here drives
1620    /// Llama's write** and both bindings are inert for it. On the SymEnv path
1621    /// the offset rides `cached_len_sym`, and it is **load-bearing for Phi** —
1622    /// proved by negative control: binding it wrong moves Phi's logits
1623    /// (`phi_attended_len_sym_is_unreferenced_negative_control`).
1624    ///
1625    /// The trap this comment exists to prevent: someone profiling or tracing
1626    /// **the Llama path** sees a binding nothing consumes and removes it as dead
1627    /// code. **Their evidence would be about Llama; the requirement comes from
1628    /// Phi**, and the breakage would be silent — wrong KV write offsets, not a
1629    /// compile error. Whichever model you were looking at, you were looking at
1630    /// half the callers.
1631    ///
1632    /// `attended_len_sym` is separately inert on **both** paths today (F32, CPU,
1633    /// no flash arm) and is bound anyway: it becomes load-bearing the moment a
1634    /// bf16/f16 CUDA decode offers the flash arm, and binding it unconditionally
1635    /// is what makes that switch a no-op rather than a hunt. That claim is
1636    /// scoped — re-run the controls above before relying on it under any other
1637    /// dtype/graph.
1638    pub fn per_token_sym_env(&self, cached_len: usize) -> Result<SymEnv> {
1639        let mut env = SymEnv::new();
1640        env.bind(self.cached_len_sym, cached_len)?;
1641        env.bind(self.attended_len_sym, cached_len + self.seq)?;
1642        Ok(env)
1643    }
1644
1645    /// The held graph's node count. The D2b born-red test asserts this
1646    /// is stable from token 2 onward (no per-token node growth — the
1647    /// guard against an accidental re-splice / re-insert / a builder
1648    /// sneaking a `cached_len`-dependent shape back in).
1649    pub fn graph_node_count(&self) -> usize {
1650        self.graph.read().map(|g| g.len()).unwrap_or(0)
1651    }
1652
1653    /// The full realized [`StorageCache`] from the first realize (every
1654    /// weight Const + the KV Arcs + the initial per-token data Consts).
1655    /// The CapturedRun capture-building step clones this cheaply
1656    /// (Arc-clones only) and overwrites the per-token entries with fresh
1657    /// FIXED-address Arcs before handing the merged cache to
1658    /// [`fuel_dispatch::pipelined::CapturedDecodeSession::capture`] as
1659    /// `inputs`.
1660    pub fn base_cache(&self) -> &StorageCache {
1661        &self.base_cache
1662    }
1663}
1664
1665/// Runtime policy for the paged persistent decode path
1666/// (`LlamaModel::forward_paged_step_persistent`):
1667/// whether to build the plan
1668/// ONCE and reuse it across tokens, or re-plan every token (the pre-plan-once
1669/// behavior). The paged driver holds this per config and passes it each step;
1670/// **the driver default is [`PlanOnce`](Self::PlanOnce)** (set by
1671/// `PagedSessionScheduler::new`), with [`Replan`](Self::Replan) available as an
1672/// explicit opt-out.
1673///
1674/// The A/B rollout this flag was built for is DONE, and the default moved with
1675/// the result. Measured (nsys, Lightbulb, 2026-08-01; 16 tokens, same binary and
1676/// model, only the plan mode differing): `Replan` → `PlanOnce` is **29.7×** on
1677/// ms/token (8,192.0 → 275.8) and cuts host-ward DtoH 61% (101,691 → 40,088 MB)
1678/// at IDENTICAL kernel-launch count (17,802 in both arms — same compute, less
1679/// data movement). Shipping `Replan` as the default meant every consumer who did
1680/// not know to opt in paid that 29.7×.
1681///
1682/// It remains a real runtime flag — not a test hook — because toggling it in ONE
1683/// process is what lets the correctness gate run both arms off a single setup,
1684/// and because `Replan` is the parity reference the plan-once path is checked
1685/// against. On [`Replan`](Self::Replan) the persistent forward drops any held
1686/// session (so nothing stale lingers) and delegates to the re-planning
1687/// `LlamaModel::forward_paged_step`;
1688/// on [`PlanOnce`](Self::PlanOnce) it
1689/// builds-once / rebinds.
1690#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1691pub enum PagedDecodePlan {
1692    /// Re-plan (build + optimize the graph) every token — the pre-plan-once
1693    /// path. Drops any held [`PagedDecodeSession`] and routes to
1694    /// `LlamaModel::forward_paged_step`.
1695    Replan,
1696    /// Build + optimize the graph ONCE (into a [`PagedDecodeSession`]) and reuse
1697    /// it (rebinding only the per-token data) for every subsequent token.
1698    PlanOnce,
1699}
1700
1701/// Per-token re-bound data Consts for one PAGED decode step — the paged twin
1702/// of [`DecodeTokenData`]. The shapes are stable across tokens (that is the
1703/// whole point of the plan-once path); only the bytes change, so each is an
1704/// `Arc<RwLock<Storage>>` overwriting the held [`PagedDecodeSession`]'s
1705/// base-cache entry for its stable NodeId.
1706pub struct PagedDecodeTokenData {
1707    /// The single decode token id (`[1]` U32).
1708    pub token_ids: Arc<RwLock<Storage>>,
1709    /// RoPE cos table at THIS token's absolute position (`[1, head_dim]` F32).
1710    pub rope_cos: Arc<RwLock<Storage>>,
1711    /// RoPE sin table at THIS token's absolute position (`[1, head_dim]` F32).
1712    pub rope_sin: Arc<RwLock<Storage>>,
1713    /// Capacity-padded block table (`[1, max_blocks_cap]` U32) — the shape is
1714    /// FIXED by `max_blocks_cap`; the content grows a physical block whenever
1715    /// this token crosses a block boundary (padded tail stays 0, masked out).
1716    pub block_table: Arc<RwLock<Storage>>,
1717    /// Attended prefix length for this row (`[1]` U32) — the `Op::PagedAttn`
1718    /// mask cutoff (`Ge(pos, context_len) → −inf`) that neutralizes both the
1719    /// future positions AND the padded block_table tail.
1720    pub context_lens: Arc<RwLock<Storage>>,
1721    /// The flattened KV-write offset (`linear = phys·block_size + slot` as a
1722    /// rank-0 I64), present ONLY on the device-offset path (CPU/CUDA, where
1723    /// `Op::WriteSliceDoff` reads the start device-side). `None` on the SymEnv
1724    /// path (Vulkan), where the offset rides `write_sym` in the per-pass env.
1725    pub offset: Option<Arc<RwLock<Storage>>>,
1726}
1727
1728/// Plan-once persistent decode state for one PAGED (block-pool) decode
1729/// stream — the paged twin of [`DecodeSession`]. Built on the first
1730/// `seq == 1` paged decode token; reused (graph + optimize view HELD, only
1731/// the per-token data Consts + `SymEnv` re-bound) for every subsequent token.
1732///
1733/// Paged decode's structural variabilities that a re-plan would otherwise pay
1734/// EVERY token are removed here: (1) the fresh `Tensor` graph root becomes
1735/// a held graph with stable re-bindable Const placeholders; (2) the L-varying
1736/// `block_table` shape is pinned to `[1, max_blocks_cap]` (Task 1 padded
1737/// materialize); (3) the per-step KV-write range becomes ONE flattened
1738/// dynamic offset (Task 2 `build_decode_attn_off`). What remains per token is
1739/// shape-stable data re-bound into a clone of `base_cache` + one bound scalar.
1740///
1741/// The pool K/V buffer Arcs are bound ONCE into `base_cache` and mutate IN
1742/// PLACE via `Op::WriteSliceDoff`/`Op::WriteSliceDyn` each token (never
1743/// re-inserted) — exactly the contiguous KV relationship, so the write this
1744/// step lands in the pool and is visible next step.
1745///
1746/// Held by the paged generate-loop owner alongside the `DeviceKvPool` +
1747/// `SessionHandle`; the caller must NOT swap the pool/model out from under a
1748/// live session (the held `base_cache` references THIS pool's buffers). A
1749/// validity-key mismatch (`is_valid_for`) or `TopologyChanged` drops + rebuilds
1750/// it (see `LlamaModel::forward_paged_step_persistent`). Single-session (B = 1)
1751/// today; the ragged batched persistent path is a follow-on.
1752pub struct PagedDecodeSession {
1753    /// The held paged decode-step graph, ALREADY optimized in place. Structure
1754    /// is stable across tokens (variabilities #1–#3 removed).
1755    graph: Arc<RwLock<Graph>>,
1756    /// The cached optimize view from the first realize. Holds only
1757    /// `{roots, generation}`; valid while `graph` structure + topology
1758    /// generation are unchanged.
1759    optimized: OptimizedGraph,
1760    /// The realize root the executor is asked for (the D2H `Op::Copy` splice).
1761    effective_target: NodeId,
1762    /// The logits node (pre-D2H-splice) — retained for debugging/attribution.
1763    logits_node: NodeId,
1764    /// Stable re-bindable single-token-id Const (`[1]` U32).
1765    token_ids_node: NodeId,
1766    /// Stable re-bindable RoPE cos table Const (`[1, head_dim]` F32).
1767    rope_cos_node: NodeId,
1768    /// Stable re-bindable RoPE sin table Const (`[1, head_dim]` F32).
1769    rope_sin_node: NodeId,
1770    /// Stable re-bindable padded block_table Const (`[1, max_blocks_cap]` U32).
1771    block_table_node: NodeId,
1772    /// Stable re-bindable context_lens Const (`[1]` U32).
1773    context_lens_node: NodeId,
1774    /// Per-layer `(k_pool_ph, v_pool_ph)` stable KV placeholder NodeIds, bound
1775    /// ONCE to the pool buffers (viewed at `pool_shape_flat`) and mutated in
1776    /// place by the flattened-offset write each token.
1777    kv_nodes: Vec<(NodeId, NodeId)>,
1778    /// The stable rank-0 `I64` KV-write offset Const, present ONLY on the
1779    /// device-offset path (CPU/CUDA — `Op::WriteSliceDoff`). `None` on the
1780    /// SymEnv path (Vulkan — the offset rides `write_sym`).
1781    offset_node: Option<NodeId>,
1782    /// The symbol the per-pass `SymEnv` binds to the flattened write offset
1783    /// (`linear`) each token. Load-bearing on the SymEnv path; a harmless
1784    /// (unreferenced) extra binding on the device-offset path.
1785    write_sym: SymId,
1786    /// The full realized [`StorageCache`] from the first realize (weights +
1787    /// the pool KV Arcs + the initial per-token data Consts). Each token we
1788    /// clone this and overwrite ONLY the per-token data-Const entries; the
1789    /// weight + pool Arcs are stable (the pool mutates in place).
1790    base_cache: StorageCache,
1791    // ---- validity keys — rebuild if any change vs. the live pool ----
1792    max_blocks_cap: usize,
1793    n_layers: usize,
1794    block_size: usize,
1795    cache_dtype: DType,
1796    /// The model's `decode_shape_key()` at build time — family + structure-
1797    /// affecting config + WEIGHT IDENTITY (a never-recycled `ModelInstanceId`).
1798    ///
1799    /// Geometry alone cannot separate two models: `PagedDecodeSession` bakes the
1800    /// weight `Const`s, so two same-shaped models produce identical
1801    /// `(max_blocks_cap, n_layers, block_size, cache_dtype)` and a plan built for
1802    /// one would be judged valid for the other — silently computing the wrong
1803    /// architecture, or the right architecture with the wrong weights, at full
1804    /// speed. The contiguous twin closed this first; this is the paged half of
1805    /// the same hole.
1806    shape_key: u64,
1807    /// The [`DeviceKvPool`](crate::kv_block_pool_device::DeviceKvPool) whose
1808    /// per-layer block buffers are baked into `base_cache`. The paged half of
1809    /// the same welding: `rebind_and_realize_paged_prebuilt` re-binds the
1810    /// per-token data (token id, RoPE, block_table, context_lens, offset) and
1811    /// never the pool, so this plan reads THESE buffers whichever pool the
1812    /// caller passes. Two same-geometry pools are otherwise indistinguishable
1813    /// to the key. See [`KvAllocId`].
1814    alloc_id: KvAllocId,
1815    /// Count of REBIND realizes this session has served (one per
1816    /// [`Self::realize_token`]). The build itself realizes through the prebuild
1817    /// seam, NOT `realize_token`, so it stays 0 right after construction and
1818    /// increments only on each plan-reuse token. A DEVICE-INDEPENDENT plan-HIT
1819    /// signal (the `optimize_calls_thread_local` counter is CPU-scoped — GPU
1820    /// per-token uploads bump it), so the correctness gate can assert "this
1821    /// token reused the plan" on any backend. Interior-mutable (`realize_token`
1822    /// takes `&self`); `Relaxed` — it is telemetry, ordered by the caller.
1823    realize_count: AtomicUsize,
1824    /// `order_for` fix track (`docs/design/incremental-consumer-index.md`
1825    /// §5) — see [`DecodeSession::order_cache`]'s doc for the full
1826    /// argument; identical role here for the paged path.
1827    order_cache: std::sync::OnceLock<Vec<NodeId>>,
1828}
1829
1830impl PagedDecodeSession {
1831    /// Assemble a held paged session from the artifacts a first-realize
1832    /// prebuild produced. The node ids are the STABLE data-Const NodeIds the
1833    /// paged builder minted.
1834    pub fn new(
1835        graph: Arc<RwLock<Graph>>,
1836        optimized: OptimizedGraph,
1837        effective_target: NodeId,
1838        logits_node: NodeId,
1839        token_ids_node: NodeId,
1840        rope_cos_node: NodeId,
1841        rope_sin_node: NodeId,
1842        block_table_node: NodeId,
1843        context_lens_node: NodeId,
1844        kv_nodes: Vec<(NodeId, NodeId)>,
1845        offset_node: Option<NodeId>,
1846        write_sym: SymId,
1847        base_cache: StorageCache,
1848        max_blocks_cap: usize,
1849        n_layers: usize,
1850        block_size: usize,
1851        cache_dtype: DType,
1852        shape_key: u64,
1853        alloc_id: KvAllocId,
1854    ) -> Self {
1855        Self {
1856            alloc_id,
1857            graph,
1858            optimized,
1859            effective_target,
1860            logits_node,
1861            token_ids_node,
1862            rope_cos_node,
1863            rope_sin_node,
1864            block_table_node,
1865            context_lens_node,
1866            kv_nodes,
1867            offset_node,
1868            write_sym,
1869            base_cache,
1870            max_blocks_cap,
1871            n_layers,
1872            block_size,
1873            cache_dtype,
1874            shape_key,
1875            realize_count: AtomicUsize::new(0),
1876            order_cache: std::sync::OnceLock::new(),
1877        }
1878    }
1879
1880    /// Realize the held paged graph for one decode token via the prebuilt seam
1881    /// (SKIP `prepare` + `optimize_graph`). `data` supplies the per-token
1882    /// re-bound data-Const Arcs; they overwrite the held `base_cache`'s entries
1883    /// for this token (the weight + pool KV Arcs stay from `base_cache`).
1884    /// `sym_env` binds `write_sym` (load-bearing on the SymEnv path, harmless
1885    /// on the device-offset path). `TopologyChanged` surfaces typed (caller
1886    /// invalidates the session).
1887    pub fn realize_token(
1888        &self,
1889        device: &Device,
1890        data: PagedDecodeTokenData,
1891        sym_env: &SymEnv,
1892    ) -> Result<Vec<f32>> {
1893        let mut cache = self.base_cache.clone();
1894        cache.insert(self.token_ids_node, data.token_ids);
1895        cache.insert(self.rope_cos_node, data.rope_cos);
1896        cache.insert(self.rope_sin_node, data.rope_sin);
1897        cache.insert(self.block_table_node, data.block_table);
1898        cache.insert(self.context_lens_node, data.context_lens);
1899        if let (Some(offset_node), Some(offset)) = (self.offset_node, data.offset) {
1900            cache.insert(offset_node, offset);
1901        }
1902        // Device-independent plan-HIT tick: this token reuses the held plan
1903        // (the prebuild seam below SKIPs optimize). Bumped BEFORE the realize
1904        // so a realize error still records the attempted rebind.
1905        self.realize_count.fetch_add(1, Ordering::Relaxed);
1906        crate::pipelined_bridge::realize_one_prebuilt_cached_env::<f32>(
1907            &self.graph,
1908            self.effective_target,
1909            &self.optimized,
1910            &self.order_cache,
1911            device,
1912            cache,
1913            sym_env,
1914        )
1915    }
1916
1917    /// Whether this held session is valid for the given paged decode step.
1918    /// Rebuild (drop + build fresh) on any mismatch: a change in
1919    /// `max_blocks_cap` (the block_table shape key), `n_layers`, `block_size`,
1920    /// or `cache_dtype` means the held graph's shapes / offsets are stale.
1921    ///
1922    /// `alloc_id` is the live pool's
1923    /// [`DeviceKvPool::alloc_id`](crate::kv_block_pool_device::DeviceKvPool::alloc_id)
1924    /// — which POOL's buffers, as distinct from `shape_key`'s which MODEL's
1925    /// weights. Note it is deliberately not sensitive to block allocation:
1926    /// which physical blocks a session owns rides the per-token `block_table`
1927    /// rebind, so a generation that grows into new blocks keeps its plan.
1928    pub fn is_valid_for(
1929        &self,
1930        max_blocks_cap: usize,
1931        n_layers: usize,
1932        block_size: usize,
1933        cache_dtype: DType,
1934        shape_key: u64,
1935        alloc_id: KvAllocId,
1936    ) -> bool {
1937        self.max_blocks_cap == max_blocks_cap
1938            && self.n_layers == n_layers
1939            && self.block_size == block_size
1940            && self.cache_dtype == cache_dtype
1941            && self.shape_key == shape_key
1942            && self.alloc_id == alloc_id
1943    }
1944
1945    /// Build the per-token [`SymEnv`] for one paged decode step: bind
1946    /// `write_sym = linear` (the flattened KV-write offset). Load-bearing on
1947    /// the SymEnv path; a harmless unreferenced binding on the device-offset
1948    /// path (a conflicting rebind surfaces a typed error, never a panic).
1949    pub fn per_token_sym_env(&self, linear: usize) -> Result<SymEnv> {
1950        let mut env = SymEnv::new();
1951        env.bind(self.write_sym, linear)?;
1952        Ok(env)
1953    }
1954
1955    /// The held graph handle.
1956    pub fn graph(&self) -> &Arc<RwLock<Graph>> {
1957        &self.graph
1958    }
1959    /// The cached optimize view (fed to the prebuilt-realize seam).
1960    pub fn optimized(&self) -> &OptimizedGraph {
1961        &self.optimized
1962    }
1963    pub fn effective_target(&self) -> NodeId {
1964        self.effective_target
1965    }
1966    pub fn logits_node(&self) -> NodeId {
1967        self.logits_node
1968    }
1969    pub fn token_ids_node(&self) -> NodeId {
1970        self.token_ids_node
1971    }
1972    pub fn rope_cos_node(&self) -> NodeId {
1973        self.rope_cos_node
1974    }
1975    pub fn rope_sin_node(&self) -> NodeId {
1976        self.rope_sin_node
1977    }
1978    pub fn block_table_node(&self) -> NodeId {
1979        self.block_table_node
1980    }
1981    pub fn context_lens_node(&self) -> NodeId {
1982        self.context_lens_node
1983    }
1984    pub fn kv_nodes(&self) -> &[(NodeId, NodeId)] {
1985        &self.kv_nodes
1986    }
1987    pub fn offset_node(&self) -> Option<NodeId> {
1988        self.offset_node
1989    }
1990    pub fn write_sym(&self) -> SymId {
1991        self.write_sym
1992    }
1993    pub fn max_blocks_cap(&self) -> usize {
1994        self.max_blocks_cap
1995    }
1996
1997    /// How many REBIND (plan-reuse) tokens this session has served — a
1998    /// device-independent plan-HIT signal (see [`Self::realize_count`]). Zero
1999    /// right after the build; `n` after `n` reuse tokens. The correctness gate
2000    /// asserts this advances by exactly one per plan-once decode step.
2001    pub fn realize_count(&self) -> usize {
2002        self.realize_count.load(Ordering::Relaxed)
2003    }
2004
2005    /// The held graph's node count. The Task 3 born-red test asserts this is
2006    /// stable from token 2 onward (no per-token node growth — the guard
2007    /// against an accidental re-splice / re-insert).
2008    pub fn graph_node_count(&self) -> usize {
2009        self.graph.read().map(|g| g.len()).unwrap_or(0)
2010    }
2011
2012    /// The full realized [`StorageCache`] from the first realize.
2013    pub fn base_cache(&self) -> &StorageCache {
2014        &self.base_cache
2015    }
2016}
2017
2018// `alloc_zeroed_on` retired 2026-05-22 (bridge-retirement Phase 3a).
2019// Zero-init device allocation now flows through `Op::Alloc` graph
2020// emission + the executor's `WorkItemKind::Alloc` arm. The per-
2021// `DeviceLocation` match this function used to carry lives in
2022// `fuel-storage::pipelined::execute_work_item`'s Alloc arm; the
2023// per-realize device handles come from a `DeviceRegistry` built from the
2024// `Device` (`crate::pipelined_bridge::primary_device_registry`).
2025
2026// ===========================================================================
2027// InferenceContext
2028// ===========================================================================
2029
2030/// Per-session host-side context holding long-lived storage Arcs
2031/// that survive across realize calls.
2032///
2033/// The persistent map is the seam the unified-storage / mmap-coherence
2034/// backplane work later replaces (see
2035/// `project_unified_durable_tensor_store.md`); today it's a simple
2036/// in-memory `HashMap`. Each realize call clones the Arcs into the
2037/// executor's input cache; persistent entries reuse those Arcs
2038/// across calls instead of re-uploading.
2039///
2040/// ## Lifecycle
2041///
2042/// 1. Construct with a target device: `InferenceContext::new(device)`.
2043/// 2. Insert long-lived storages (KV layer storages, anything else
2044///    that should survive across realize calls):
2045///    `ctx.insert(node_id, arc)`.
2046/// 3. Realize: `ctx.realize_one_as::<f32>(&graph, target_node)`. The
2047///    persistent map is seeded into the executor's input cache; new
2048///    `Op::Const` nodes the graph references that aren't in the
2049///    persistent map get uploaded fresh from the graph's storage map.
2050/// 4. Subsequent realize calls reuse the persistent Arcs — no
2051///    re-upload, no D2H/H2D round-trip.
2052pub struct InferenceContext {
2053    device: Device,
2054    persistent: HashMap<NodeId, Arc<RwLock<Storage>>>,
2055    /// Held plan-once decode plan for `LlamaModel::forward_decode_step`
2056    /// — the carrier that lets a caller-driven decode loop get plan reuse
2057    /// WITHOUT threading an `Option<DecodeSession>` of its own.
2058    ///
2059    /// This exists because the ergonomic call shape and the fast call shape had
2060    /// drifted apart. `forward_with_kv_context(tokens, cache, ctx)` is the raw
2061    /// rebuild primitive; its persistent sibling takes a fourth argument, so a
2062    /// consumer hand-rolling a decode loop reaches the slow one and never learns
2063    /// the fast one exists. Not hypothetical: that gap cost a measured consumer
2064    /// 5,901 → 26.47 ms/token before anyone noticed (nsys, 2026-08-01).
2065    ///
2066    /// **One context per model.** Already this codebase's invariant — speculative
2067    /// decoding builds a separate `InferenceContext` for the draft and the target
2068    /// — and the held plan self-heals regardless: `DecodeSession::is_valid_for`
2069    /// drops it on any cache-geometry or dtype change.
2070    decode_session: Option<DecodeSession>,
2071}
2072
2073/// `FUEL_WEIGHT_RESIDENCY=0` turns the per-device weight residency off (the measurement control for
2074/// ROADMAP row 172: every realize then re-uploads its weights as it did before).
2075const WEIGHT_RESIDENCY_ENV: &str = "FUEL_WEIGHT_RESIDENCY";
2076
2077/// `FUEL_WEIGHT_RESIDENCY_BYTES=<n>` sets the weight residency's byte cap outright (0 turns it off),
2078/// replacing the share of the device's memory below.
2079const WEIGHT_RESIDENCY_BYTES_ENV: &str = "FUEL_WEIGHT_RESIDENCY_BYTES";
2080
2081/// The share of a device's reported memory the weight residency may hold, in percent.
2082///
2083/// 40% because the rest has to hold everything else a serving process puts on the same card: KV
2084/// caches, activations, the decode session's own buffers, a second model being warmed, and other
2085/// processes (a desktop compositor alone takes about 0.5 GB of an 8 GB laptop card). It is a ceiling
2086/// on what is RETAINED across contexts, not an extra cost for a single model: the decode session
2087/// shares the resident storages, so one model in use needs its weights on the card either way (measured
2088/// on the 4070, ROADMAP row 172). On the 8 GB 4070 this is a cap of about 3.2 GB, enough for
2089/// Qwen3-0.6B Q4_K_M (1.19 GB) with a second small model alongside.
2090const WEIGHT_RESIDENCY_SHARE_PERCENT: u64 = 40;
2091
2092/// The byte cap for `device`'s weight residency, or `None` for no residency.
2093///
2094/// `FUEL_WEIGHT_RESIDENCY_BYTES` wins when set. Otherwise the cap is [`WEIGHT_RESIDENCY_SHARE_PERCENT`]
2095/// of the device's reported total memory (Vulkan: the `VK_EXT_memory_budget` device-local budget; CUDA:
2096/// the driver's total). A device that cannot report it (a Vulkan driver without that extension, a
2097/// backend with no runtime surface) gets `None`: no signal means no residency, never a guessed cap,
2098/// so such a device behaves exactly as before.
2099fn weight_residency_cap(device: &Device) -> Option<u64> {
2100    if let Ok(v) = std::env::var(WEIGHT_RESIDENCY_BYTES_ENV) {
2101        return v.trim().parse::<u64>().ok().filter(|&n| n > 0);
2102    }
2103    let total = device.as_dyn().as_backend_runtime()?.total_bytes()?;
2104    Some(total / 100 * WEIGHT_RESIDENCY_SHARE_PERCENT).filter(|&n| n > 0)
2105}
2106
2107impl InferenceContext {
2108    pub fn new(device: Device) -> Self {
2109        Self {
2110            device,
2111            persistent: HashMap::new(),
2112            decode_session: None,
2113        }
2114    }
2115
2116    pub fn device(&self) -> &Device {
2117        &self.device
2118    }
2119
2120    /// Take the held decode plan out of the context, leaving `None`.
2121    ///
2122    /// Paired with [`Self::put_decode_session`]. The take/put dance exists for
2123    /// the borrow checker: the persistent forward needs `&mut InferenceContext`
2124    /// AND `&mut Option<DecodeSession>` at once, which it cannot have if the
2125    /// session lives inside the context. Callers outside
2126    /// `forward_decode_step` should not need either method.
2127    pub fn take_decode_session(&mut self) -> Option<DecodeSession> {
2128        self.decode_session.take()
2129    }
2130
2131    /// Put a decode plan back into the context. See [`Self::take_decode_session`].
2132    pub fn put_decode_session(&mut self, session: Option<DecodeSession>) {
2133        self.decode_session = session;
2134    }
2135
2136    /// Whether a decode plan is currently held. Observability hook — a caller
2137    /// that has decoded at least one token through
2138    /// `LlamaModel::forward_decode_step` holds one.
2139    pub fn has_decode_session(&self) -> bool {
2140        self.decode_session.is_some()
2141    }
2142
2143    /// Insert a long-lived storage at `node_id`. The Arc survives
2144    /// across subsequent realize calls and is treated as pre-realized
2145    /// for any graph that references `node_id` as a Const-shaped leaf.
2146    ///
2147    /// Replaces any prior entry at `node_id`.
2148    pub fn insert(&mut self, node_id: NodeId, storage: Arc<RwLock<Storage>>) {
2149        self.persistent.insert(node_id, storage);
2150    }
2151
2152    /// Remove the persistent entry at `node_id`. Returns the Arc if
2153    /// one was present. After this, the next realize that touches
2154    /// `node_id` will re-fetch from the graph's storage_map (and fail
2155    /// if the slot isn't populated there either).
2156    pub fn remove(&mut self, node_id: NodeId) -> Option<Arc<RwLock<Storage>>> {
2157        self.persistent.remove(&node_id)
2158    }
2159
2160    /// Whether the persistent map has an entry at `node_id`.
2161    pub fn contains(&self, node_id: NodeId) -> bool {
2162        self.persistent.contains_key(&node_id)
2163    }
2164
2165    /// Borrow the persistent entry at `node_id` if present.
2166    pub fn get(&self, node_id: NodeId) -> Option<&Arc<RwLock<Storage>>> {
2167        self.persistent.get(&node_id)
2168    }
2169
2170    /// Number of persistent slots.
2171    pub fn len(&self) -> usize {
2172        self.persistent.len()
2173    }
2174
2175    pub fn is_empty(&self) -> bool {
2176        self.persistent.is_empty()
2177    }
2178
2179    /// Drop every persistent entry. The Arcs are released; storages
2180    /// whose only remaining reference was the context's are freed
2181    /// (host memory for CPU, deferred-on-stream for async backends).
2182    pub fn clear_persistent(&mut self) {
2183        self.persistent.clear();
2184    }
2185
2186    /// Realize a single target. The persistent map is seeded into
2187    /// the executor's input cache via `Arc::clone` (the persistent
2188    /// entries survive the call). Op::Const NodeIds in the graph
2189    /// that aren't already in the persistent map get uploaded fresh
2190    /// from `graph.storage_for(id)` per the existing pipelined-bridge
2191    /// pattern.
2192    pub fn realize_one_as<T: bytemuck::Pod + fuel_ir::WithDType>(
2193        &self,
2194        graph: &Arc<RwLock<Graph>>,
2195        target: NodeId,
2196    ) -> Result<Vec<T>> {
2197        self.realize_one_as_with_env::<T>(graph, target, &SymEnv::default())
2198    }
2199
2200    /// Env-carrying counterpart of [`Self::realize_one_as`]: supplies a
2201    /// per-pass [`SymEnv`] binding the runtime values of any `DynScalar`
2202    /// op params (Phase D symbolic extents — e.g. the decode KV-cache
2203    /// write offset `cached_len`). The env is **per-pass** (re-supplied
2204    /// every forward step) while the persistent map is **per-session**;
2205    /// an empty env is byte-identical to [`Self::realize_one_as`].
2206    pub fn realize_one_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2207        &self,
2208        graph: &Arc<RwLock<Graph>>,
2209        target: NodeId,
2210        env: &SymEnv,
2211    ) -> Result<Vec<T>> {
2212        crate::pipelined_bridge::realize_one_as_with_initial_env::<T>(
2213            graph,
2214            target,
2215            &self.device,
2216            self.realize_cache(graph)?,
2217            env,
2218        )
2219    }
2220
2221    /// Phase D · D2a — first-realize that ALSO captures the reusable
2222    /// optimize artifacts for a later prebuilt (plan-once) re-realize.
2223    ///
2224    /// Runs the full `prepare` + `optimize_graph` + dispatch path ONCE (like
2225    /// [`Self::realize_one_as_with_env`]) and returns
2226    /// `(effective_target, OptimizedGraph, result)`. The caller (D2b's
2227    /// `DecodeSession`) holds the `effective_target` (the spliced D2H
2228    /// `Op::Copy` root) + the cached `OptimizedGraph` and feeds them to
2229    /// [`Self::realize_prebuilt_as_with_env`] on later tokens to SKIP the
2230    /// re-plan. See [`crate::pipelined_bridge::prebuild_optimized_env`].
2231    pub fn prebuild_optimized_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2232        &self,
2233        graph: &Arc<RwLock<Graph>>,
2234        target: NodeId,
2235        env: &SymEnv,
2236    ) -> Result<(NodeId, fuel_dispatch::optimize::OptimizedGraph, Vec<T>)> {
2237        crate::pipelined_bridge::prebuild_optimized_env::<T>(
2238            graph,
2239            target,
2240            &self.device,
2241            self.realize_cache(graph)?,
2242            env,
2243        )
2244    }
2245
2246    /// Phase D · D2b — first-realize that captures the reusable optimize
2247    /// artifacts AND the full realized [`StorageCache`] (all weight
2248    /// Consts uploaded by `build_const_cache`, merged over this context's
2249    /// persistent Arcs). The [`DecodeSession`] holds the cache so later
2250    /// prebuilt realizes (which SKIP the const-cache walk) still resolve
2251    /// every weight Const. Returns
2252    /// `(effective_target, OptimizedGraph, full_cache, result)`.
2253    pub fn prebuild_optimized_capturing_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2254        &self,
2255        graph: &Arc<RwLock<Graph>>,
2256        target: NodeId,
2257        env: &SymEnv,
2258    ) -> Result<(
2259        NodeId,
2260        fuel_dispatch::optimize::OptimizedGraph,
2261        StorageCache,
2262        Vec<T>,
2263    )> {
2264        crate::pipelined_bridge::prebuild_optimized_env_capturing_cache::<T>(
2265            graph,
2266            target,
2267            &self.device,
2268            self.realize_cache(graph)?,
2269            env,
2270        )
2271    }
2272
2273    /// Phase D · D2a — plan-once re-realize over a graph already prepared +
2274    /// optimized by a prior [`Self::prebuild_optimized_as_with_env`]. Skips
2275    /// BOTH `prepare` (no D2H re-splice / const-cache walk) AND
2276    /// `optimize_graph` (no re-plan / double-insert). Re-binds only the
2277    /// per-call `StorageCache` (this context's persistent Arcs, incl. the
2278    /// re-bound per-token data Consts) + `env`, then dispatches straight to
2279    /// the executor. `effective_target` + `optimized` come from the prebuild.
2280    ///
2281    /// A `TopologyChanged` error surfaces to the caller (typed, not
2282    /// retried) — the cached view is stale; invalidate + rebuild the session.
2283    pub fn realize_prebuilt_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2284        &self,
2285        graph: &Arc<RwLock<Graph>>,
2286        effective_target: NodeId,
2287        optimized: &fuel_dispatch::optimize::OptimizedGraph,
2288        env: &SymEnv,
2289    ) -> Result<Vec<T>> {
2290        crate::pipelined_bridge::realize_one_prebuilt_env::<T>(
2291            graph,
2292            effective_target,
2293            optimized,
2294            &self.device,
2295            self.cloned_persistent(),
2296            env,
2297        )
2298    }
2299
2300    /// Multi-target counterpart of [`Self::realize_one_as`].
2301    pub fn realize_many_as<T: bytemuck::Pod + fuel_ir::WithDType>(
2302        &self,
2303        graph: &Arc<RwLock<Graph>>,
2304        targets: &[NodeId],
2305    ) -> Result<Vec<Vec<T>>> {
2306        self.realize_many_as_with_env::<T>(graph, targets, &SymEnv::default())
2307    }
2308
2309    /// Env-carrying counterpart of [`Self::realize_many_as`] (Phase D
2310    /// symbolic extents). An empty env is byte-identical to
2311    /// [`Self::realize_many_as`].
2312    pub fn realize_many_as_with_env<T: bytemuck::Pod + fuel_ir::WithDType>(
2313        &self,
2314        graph: &Arc<RwLock<Graph>>,
2315        targets: &[NodeId],
2316        env: &SymEnv,
2317    ) -> Result<Vec<Vec<T>>> {
2318        crate::pipelined_bridge::realize_many_as_with_initial_env::<T>(
2319            graph,
2320            targets,
2321            &self.device,
2322            self.cloned_persistent(),
2323            env,
2324        )
2325    }
2326
2327    /// Realize-split counterpart of [`Self::realize_many_as`]: the
2328    /// first `n_host` targets are downloaded to host `Vec<T>`s, the
2329    /// rest come back as device-resident `(storage, layout)` pairs —
2330    /// no D2H for results that feed the next step's graph. See
2331    /// [`crate::pipelined_bridge::realize_split_as_with_initial`].
2332    pub fn realize_split_as<T: bytemuck::Pod + fuel_ir::WithDType>(
2333        &self,
2334        graph: &Arc<RwLock<Graph>>,
2335        targets: &[NodeId],
2336        n_host: usize,
2337    ) -> Result<crate::pipelined_bridge::SplitRealizeOutput<T>> {
2338        crate::pipelined_bridge::realize_split_as_with_initial::<T>(
2339            graph,
2340            targets,
2341            n_host,
2342            &self.device,
2343            self.cloned_persistent(),
2344        )
2345    }
2346
2347    /// [`Self::cloned_persistent`] plus, on a non-CPU device, the resident device copy of every weight
2348    /// `Const` of `graph` whose source array this device has already uploaded (uploading it now the
2349    /// first time). `build_const_cache` skips every node already in the cache, so a seeded weight costs
2350    /// the realize nothing. Per-call arrays (no live source) are left to `build_const_cache`.
2351    fn realize_cache(&self, graph: &Arc<RwLock<Graph>>) -> Result<StorageCache> {
2352        let mut cache = self.cloned_persistent();
2353        if self.device.location() == DeviceLocation::Cpu
2354            || std::env::var(WEIGHT_RESIDENCY_ENV).as_deref() == Ok("0")
2355        {
2356            return Ok(cache);
2357        }
2358        let Some(cap) = weight_residency_cap(&self.device) else {
2359            return Ok(cache);
2360        };
2361        let wanted: Vec<(NodeId, fuel_graph::ConstOrigin)> = {
2362            let g = graph
2363                .read()
2364                .map_err(|_| Error::Msg("graph lock poisoned".into()).bt())?;
2365            g.const_origins()
2366                .filter(|(id, _)| !cache.contains_key(id))
2367                .map(|(id, o)| (id, o.clone()))
2368                .collect()
2369        };
2370        let mut residency = self
2371            .device
2372            .weights
2373            .0
2374            .lock()
2375            .unwrap_or_else(|p| p.into_inner());
2376        // A model that was dropped since the last realize no longer holds its weights: let those go
2377        // before taking on new ones, so a model swap does not grow the device's residency.
2378        residency.set_cap(Some(cap));
2379        residency.sweep_orphans();
2380        for (id, origin) in wanted {
2381            let resident = residency.get_or_upload(&origin, || {
2382                let host = {
2383                    let g = graph
2384                        .read()
2385                        .map_err(|_| Error::Msg("graph lock poisoned".into()).bt())?;
2386                    let slot = g.storage_for(id).ok_or_else(|| {
2387                        Error::Msg(format!("weight Const {id:?} has no storage slot")).bt()
2388                    })?;
2389                    let slot = slot
2390                        .read()
2391                        .map_err(|_| Error::Msg("slot lock poisoned".into()).bt())?;
2392                    slot.as_dyn().to_host_buffer_dyn()?
2393                };
2394                crate::pipelined_bridge::upload_host_buffer_to_device(&self.device, host)
2395            })?;
2396            if let Some(storage) = resident {
2397                cache.insert(id, storage);
2398            }
2399        }
2400        Ok(cache)
2401    }
2402
2403    /// Build a [`StorageCache`] containing Arc-clones of every
2404    /// persistent entry. The clone is cheap (Arc refcount bumps); the
2405    /// returned `StorageCache` is consumed by the realize call but
2406    /// the original Arcs in `self.persistent` survive.
2407    fn cloned_persistent(&self) -> StorageCache {
2408        let mut out = StorageCache::with_capacity(self.persistent.len());
2409        for (id, arc) in &self.persistent {
2410            out.insert(*id, Arc::clone(arc));
2411        }
2412        out
2413    }
2414}
2415
2416// ===========================================================================
2417// Tests
2418// ===========================================================================
2419
2420#[cfg(test)]
2421mod tests {
2422    use super::*;
2423    use fuel_graph::{Node, Op};
2424    use fuel_ir::{DType, Shape};
2425
2426    /// `InferenceContext::insert` + immediate retrieval round-trips.
2427    #[test]
2428    fn context_insert_retrieve() {
2429        let mut ctx = InferenceContext::new(Device::cpu());
2430        let storage = fuel_memory::from_slice_cpu(&[1.0_f32, 2.0, 3.0]);
2431        let arc = Arc::new(RwLock::new(storage));
2432        let id = NodeId(42);
2433
2434        assert!(!ctx.contains(id));
2435        assert_eq!(ctx.len(), 0);
2436
2437        ctx.insert(id, Arc::clone(&arc));
2438
2439        assert!(ctx.contains(id));
2440        assert_eq!(ctx.len(), 1);
2441        // The returned Arc is the same as what we inserted.
2442        let retrieved = ctx.get(id).expect("just inserted");
2443        assert!(Arc::ptr_eq(retrieved, &arc));
2444    }
2445
2446    /// Inserted Arcs survive across realize calls. Build a minimal
2447    /// 3-node graph (Const + Const + Add). Both Const slots come
2448    /// from the context's persistent map (no graph.storage_map
2449    /// involvement). Realize twice; verify the persistent Arcs are
2450    /// still held by the context after each call.
2451    #[test]
2452    fn context_persistent_arc_survives_realize() {
2453        let lhs_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
2454            1.0_f32, 2.0, 3.0,
2455        ])));
2456        let rhs_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[
2457            10.0_f32, 20.0, 30.0,
2458        ])));
2459
2460        let graph = Arc::new(RwLock::new(Graph::new()));
2461        let (lhs_id, rhs_id, add_id) = {
2462            let mut g = graph.write().unwrap();
2463            let lhs = g.push(Node {
2464                op: Op::Const,
2465                inputs: vec![],
2466                shape: Shape::from_dims(&[3]),
2467                dtype: DType::F32,
2468            });
2469            let rhs = g.push(Node {
2470                op: Op::Const,
2471                inputs: vec![],
2472                shape: Shape::from_dims(&[3]),
2473                dtype: DType::F32,
2474            });
2475            let add = g.push(Node {
2476                op: Op::Add,
2477                inputs: vec![lhs, rhs],
2478                shape: Shape::from_dims(&[3]),
2479                dtype: DType::F32,
2480            });
2481            (lhs, rhs, add)
2482        };
2483
2484        let mut ctx = InferenceContext::new(Device::cpu());
2485        ctx.insert(lhs_id, Arc::clone(&lhs_arc));
2486        ctx.insert(rhs_id, Arc::clone(&rhs_arc));
2487
2488        // Before realize: each Arc held by the test (1) + context (1) = 2.
2489        assert_eq!(Arc::strong_count(&lhs_arc), 2);
2490        assert_eq!(Arc::strong_count(&rhs_arc), 2);
2491
2492        let out1 = ctx
2493            .realize_one_as::<f32>(&graph, add_id)
2494            .expect("first realize");
2495        assert_eq!(out1, vec![11.0, 22.0, 33.0]);
2496
2497        // After first realize: same count. The realize call's
2498        // cloned_persistent() bumped the counts to 3 during the call
2499        // and dropped them back to 2 when the call returned.
2500        assert_eq!(Arc::strong_count(&lhs_arc), 2);
2501        assert_eq!(Arc::strong_count(&rhs_arc), 2);
2502
2503        // Realize again — same Arcs get reused without re-upload.
2504        // This is the autoregressive-decoding pattern: weights stay
2505        // resident across forward passes.
2506        let out2 = ctx
2507            .realize_one_as::<f32>(&graph, add_id)
2508            .expect("second realize");
2509        assert_eq!(out2, vec![11.0, 22.0, 33.0]);
2510        assert_eq!(Arc::strong_count(&lhs_arc), 2);
2511        assert_eq!(Arc::strong_count(&rhs_arc), 2);
2512    }
2513
2514    /// Read back layer `layer_idx`'s `slot` buffer in full, as a flat
2515    /// row-major `[n_kv_heads * max_seq_len * head_dim]` f32 vec — test-only
2516    /// readback counterpart to [`KvCache::write_bytes`], deliberately NOT
2517    /// sliced, so a wrong write RANGE shows up as corruption anywhere in the
2518    /// buffer rather than being hidden by only reading the written window.
2519    fn read_kv_layer_f32(
2520        cache: &KvCache,
2521        layer_idx: usize,
2522        slot: KvSlot,
2523        device: &Device,
2524    ) -> Vec<f32> {
2525        let max_seq_len = cache.max_seq_len.expect("with_capacity cache");
2526        let full_shape = Shape::from_dims(&[1, cache.n_kv_heads, max_seq_len, cache.head_dim]);
2527        let buf = match slot {
2528            KvSlot::K => Arc::clone(&cache.layer(layer_idx).unwrap().k),
2529            KvSlot::V => Arc::clone(&cache.layer(layer_idx).unwrap().v),
2530        };
2531        let anchor =
2532            crate::lazy::Tensor::from_f32(vec![0.0f32], Shape::from_dims(&[1]), device).unwrap();
2533        let dest = anchor.const_placeholder_like(full_shape, DType::F32);
2534        let mut sc = StorageCache::new();
2535        sc.insert(dest.node_id(), buf);
2536        let bytes = crate::pipelined_bridge::realize_one_bytes_with_initial(
2537            dest.graph_handle(),
2538            dest.node_id(),
2539            device,
2540            sc,
2541        )
2542        .expect("readback realize");
2543        bytemuck::try_cast_slice::<u8, f32>(&bytes)
2544            .expect("f32 cast")
2545            .to_vec()
2546    }
2547
2548    /// Board item 86 (OverMind self-fork / Lightbulb KV-cache handoff design):
2549    /// [`KvCache::write_bytes`] must write EXACTLY the `[start, start+n)`
2550    /// position range on the right axis (2, head-major) and leave every other
2551    /// position untouched — a wrong range (e.g. accidentally position-major,
2552    /// axis 0) would either corrupt unrelated positions or silently land on
2553    /// the wrong head/position entirely, and reading back the FULL buffer
2554    /// (not just the written window) is what catches either failure.
2555    #[test]
2556    fn write_bytes_lands_at_the_correct_position_and_nowhere_else() {
2557        let device = Device::cpu();
2558        let (n_layers, n_kv_heads, head_dim, max_seq_len) = (1, 2, 3, 5);
2559        let cache = KvCache::with_capacity(
2560            n_layers,
2561            n_kv_heads,
2562            head_dim,
2563            max_seq_len,
2564            DType::F32,
2565            &device,
2566        )
2567        .expect("with_capacity");
2568
2569        let alloc_before = cache.alloc_id();
2570        let loc_before = cache.device_location();
2571
2572        // Write positions [1, 3) (n=2) with a distinctive, non-zero pattern —
2573        // zero would be indistinguishable from the buffer's own zero-init.
2574        let (start, n) = (1usize, 2usize);
2575        let payload: Vec<f32> = (0..(n * n_kv_heads * head_dim))
2576            .map(|i| 1000.0 + i as f32)
2577            .collect();
2578        cache
2579            .write_bytes(
2580                0,
2581                KvSlot::K,
2582                start,
2583                n,
2584                bytemuck::cast_slice(&payload),
2585                &device,
2586            )
2587            .expect("write_bytes");
2588
2589        // THE CORE CLAIM: no Arc replacement happened, so neither identity
2590        // marker moved — this is what makes a held DecodeSession safe to
2591        // keep using without a rebind or rebuild.
2592        assert_eq!(
2593            cache.alloc_id(),
2594            alloc_before,
2595            "write_bytes must not re-mint alloc_id (that would mean the Arc was replaced)",
2596        );
2597        assert_eq!(
2598            cache.device_location(),
2599            loc_before,
2600            "write_bytes must not clear device_location (that would mean residency became unprovable)",
2601        );
2602
2603        let full = read_kv_layer_f32(&cache, 0, KvSlot::K, &device);
2604        for h in 0..n_kv_heads {
2605            for p in 0..max_seq_len {
2606                for d in 0..head_dim {
2607                    let got = full[h * max_seq_len * head_dim + p * head_dim + d];
2608                    if (start..start + n).contains(&p) {
2609                        let local_p = p - start;
2610                        let want = 1000.0 + (h * n * head_dim + local_p * head_dim + d) as f32;
2611                        assert_eq!(
2612                            got, want,
2613                            "head {h} position {p} dim {d}: written value must land exactly here",
2614                        );
2615                    } else {
2616                        assert_eq!(
2617                            got,
2618                            0.0,
2619                            "head {h} position {p} dim {d}: outside [{start},{}) must stay \
2620                             untouched (zero-init) — a wrong write range would corrupt this",
2621                            start + n,
2622                        );
2623                    }
2624                }
2625            }
2626        }
2627    }
2628
2629    /// `write_bytes` is `with_capacity`-only (needs a fixed dtype + a stable
2630    /// buffer to write into) — a `with_dims` (grow-by-replacement) cache has
2631    /// neither, and must refuse with a typed error, never panic.
2632    #[test]
2633    fn write_bytes_refuses_a_with_dims_cache() {
2634        let device = Device::cpu();
2635        let cache = KvCache::with_dims(1, 2, 3);
2636        let err = cache
2637            .write_bytes(0, KvSlot::K, 0, 1, &[0u8; 24], &device)
2638            .expect_err("with_dims cache has no fixed dtype/capacity");
2639        assert!(
2640            err.to_string().contains("with_capacity"),
2641            "refusal must name the real constraint, got: {err}",
2642        );
2643    }
2644
2645    /// A range exceeding `max_seq_len` must refuse before touching anything —
2646    /// never silently clamp (which would write at the wrong position) and
2647    /// never panic.
2648    #[test]
2649    fn write_bytes_refuses_an_out_of_range_position() {
2650        let device = Device::cpu();
2651        let cache = KvCache::with_capacity(1, 2, 3, 5, DType::F32, &device).unwrap();
2652        let payload = vec![0.0f32; 2 * 2 * 3]; // n=2 positions, valid byte length
2653        let err = cache
2654            .write_bytes(
2655                0,
2656                KvSlot::K,
2657                4, // start=4, n=2 -> [4,6) exceeds max_seq_len=5
2658                2,
2659                bytemuck::cast_slice(&payload),
2660                &device,
2661            )
2662            .expect_err("range must be refused, not clamped");
2663        assert!(
2664            err.to_string().contains("max_seq_len"),
2665            "refusal must name the real constraint, got: {err}",
2666        );
2667    }
2668
2669    /// A `bytes` length that doesn't match `n * n_kv_heads * head_dim *
2670    /// dtype_size` must refuse — a mismatched length is the shape of exactly
2671    /// the bug this check exists to catch (a caller passing position-major
2672    /// pool bytes straight through without transposing to head-major).
2673    #[test]
2674    fn write_bytes_refuses_a_mismatched_byte_length() {
2675        let device = Device::cpu();
2676        let cache = KvCache::with_capacity(1, 2, 3, 5, DType::F32, &device).unwrap();
2677        let wrong_payload = vec![0.0f32; 5]; // not n_kv_heads*n*head_dim for any valid n
2678        let err = cache
2679            .write_bytes(
2680                0,
2681                KvSlot::K,
2682                0,
2683                1,
2684                bytemuck::cast_slice(&wrong_payload),
2685                &device,
2686            )
2687            .expect_err("mismatched byte length must be refused");
2688        assert!(
2689            err.to_string().contains("bytes"),
2690            "refusal must name the byte-length mismatch, got: {err}",
2691        );
2692    }
2693
2694    /// Phase D symbolic extents — the decode-shaped path: a persistent
2695    /// fixed-capacity buffer + an `Op::WriteSlice` whose start offset is
2696    /// a per-pass `SymEnv` binding (the KV-cache append at `cached_len`).
2697    /// `realize_one_as_with_env` threads the env from the session through
2698    /// the bridge to the executor; the width-2 slab lands at the bound
2699    /// offset (3), not the static placeholder (0). Re-realizing the SAME
2700    /// graph with a different binding lands the slab at the new offset —
2701    /// the input-independent-graph property persistent decode relies on.
2702    #[test]
2703    fn realize_one_as_with_env_resolves_write_slice_offset() {
2704        use fuel_ir::{DynScalar, SymId};
2705        let dest_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 6])));
2706        let src_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[7.0_f32, 8.0])));
2707        let graph = Arc::new(RwLock::new(Graph::new()));
2708        let sym = SymId(0);
2709        let (dest_id, src_id, ws_id) = {
2710            let mut g = graph.write().unwrap();
2711            let dest = g.push(Node {
2712                op: Op::Const,
2713                inputs: vec![],
2714                shape: Shape::from_dims(&[6]),
2715                dtype: DType::F32,
2716            });
2717            let src = g.push(Node {
2718                op: Op::Const,
2719                inputs: vec![],
2720                shape: Shape::from_dims(&[2]),
2721                dtype: DType::F32,
2722            });
2723            let ws = g.push(Node {
2724                op: Op::WriteSlice {
2725                    ranges: vec![(0, 2)],
2726                    dyn_offset: Some((0, DynScalar::Sym(sym))),
2727                },
2728                inputs: vec![dest, src],
2729                shape: Shape::from_dims(&[6]),
2730                dtype: DType::F32,
2731            });
2732            (dest, src, ws)
2733        };
2734        let mut ctx = InferenceContext::new(Device::cpu());
2735        ctx.insert(dest_id, Arc::clone(&dest_arc));
2736        ctx.insert(src_id, Arc::clone(&src_arc));
2737
2738        // Bind cached_len = 3: the slab must append at indices [3, 4].
2739        let mut env = SymEnv::new();
2740        env.bind(sym, 3).unwrap();
2741        let out = ctx
2742            .realize_one_as_with_env::<f32>(&graph, ws_id, &env)
2743            .expect("realize_one_as_with_env");
2744        assert_eq!(
2745            out,
2746            vec![0.0, 0.0, 0.0, 7.0, 8.0, 0.0],
2747            "KV slab must land at the SymEnv-bound cached_len=3, not the placeholder 0",
2748        );
2749
2750        // An empty env on a graph with an unbound dyn_offset surfaces a
2751        // typed error (never a panic) — the write-once contract's
2752        // "presence ⇒ produced" read at realize.
2753        let err = ctx.realize_one_as_with_env::<f32>(&graph, ws_id, &SymEnv::new());
2754        assert!(
2755            err.is_err(),
2756            "unbound cached_len must surface a typed error"
2757        );
2758    }
2759
2760    /// `KvCache::with_dims` produces a fresh cache of the right
2761    /// shape with all layers `None` and `cached_len = 0`.
2762    #[test]
2763    fn kv_cache_with_dims_constructs_fresh() {
2764        let cache = KvCache::with_dims(4, 8, 64);
2765        assert_eq!(cache.n_layers(), 4);
2766        assert_eq!(cache.cached_len, 0);
2767        assert_eq!(cache.n_kv_heads, 8);
2768        assert_eq!(cache.head_dim, 64);
2769        for li in 0..4 {
2770            assert!(cache.layer(li).is_none());
2771        }
2772    }
2773
2774    /// `KvCache::set_layer` + `layer` round-trip.
2775    #[test]
2776    fn kv_cache_set_and_get_layer() {
2777        let mut cache = KvCache::with_dims(2, 4, 8);
2778        let k_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 32])));
2779        let v_arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 32])));
2780        let layout = Layout::contiguous(Shape::from_dims(&[1, 4, 1, 8]));
2781        cache.set_layer(
2782            0,
2783            KvLayer {
2784                k: Arc::clone(&k_arc),
2785                v: Arc::clone(&v_arc),
2786                k_layout: layout.clone(),
2787                v_layout: layout.clone(),
2788                k_version: 0,
2789                v_version: 0,
2790                k_authority: AuthorityState::Host,
2791                v_authority: AuthorityState::Host,
2792            },
2793        );
2794        let layer = cache.layer(0).expect("just set");
2795        assert!(Arc::ptr_eq(&layer.k, &k_arc));
2796        assert!(Arc::ptr_eq(&layer.v, &v_arc));
2797        assert_eq!(layer.k_version, 0);
2798        assert!(matches!(layer.k_authority, AuthorityState::Host));
2799        assert!(cache.layer(1).is_none());
2800    }
2801
2802    /// `KvCache::clear` drops all layers and resets `cached_len`.
2803    #[test]
2804    fn kv_cache_clear_drops_layers() {
2805        let mut cache = KvCache::with_dims(2, 4, 8);
2806        let k = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 32])));
2807        let v = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 32])));
2808        let layout = Layout::contiguous(Shape::from_dims(&[1, 4, 1, 8]));
2809        cache.set_layer(
2810            0,
2811            KvLayer {
2812                k: Arc::clone(&k),
2813                v: Arc::clone(&v),
2814                k_layout: layout.clone(),
2815                v_layout: layout,
2816                k_version: 1,
2817                v_version: 1,
2818                k_authority: AuthorityState::Host,
2819                v_authority: AuthorityState::Host,
2820            },
2821        );
2822        cache.cached_len = 7;
2823        // Before clear: cache holds an Arc to k → strong_count 2.
2824        assert_eq!(Arc::strong_count(&k), 2);
2825
2826        cache.clear();
2827
2828        assert!(cache.layer(0).is_none());
2829        assert_eq!(cache.cached_len, 0);
2830        // After clear: cache's Arc dropped → strong_count 1.
2831        assert_eq!(Arc::strong_count(&k), 1);
2832    }
2833
2834    /// `KvCache::truncate_to` updates `cached_len` only (Phase E.3.0
2835    /// limitation; pre-allocated buffer + WriteSlice handles the
2836    /// in-place truncate in Phase E.3.2).
2837    #[test]
2838    fn kv_cache_truncate_updates_cached_len() {
2839        let mut cache = KvCache::with_dims(2, 4, 8);
2840        cache.cached_len = 16;
2841        cache.truncate_to(10);
2842        assert_eq!(cache.cached_len, 10);
2843        // Truncating to a value >= current is a no-op.
2844        cache.truncate_to(15);
2845        assert_eq!(cache.cached_len, 10);
2846        // Truncating to zero clears the live extent.
2847        cache.truncate_to(0);
2848        assert_eq!(cache.cached_len, 0);
2849    }
2850
2851    /// Authority + version fields are placeholders today; just
2852    /// confirm they default sensibly via `KvLayer` construction.
2853    #[test]
2854    fn kv_layer_default_authority_is_host() {
2855        let arc = Arc::new(RwLock::new(fuel_memory::from_slice_cpu(&[0.0_f32; 4])));
2856        let layout = Layout::contiguous(Shape::from_dims(&[4]));
2857        let layer = KvLayer {
2858            k: Arc::clone(&arc),
2859            v: Arc::clone(&arc),
2860            k_layout: layout.clone(),
2861            v_layout: layout,
2862            k_version: 0,
2863            v_version: 0,
2864            k_authority: AuthorityState::Host,
2865            v_authority: AuthorityState::Host,
2866        };
2867        assert!(matches!(layer.k_authority, AuthorityState::Host));
2868        assert!(matches!(layer.v_authority, AuthorityState::Host));
2869        assert_eq!(layer.k_version, 0);
2870        assert_eq!(layer.v_version, 0);
2871    }
2872
2873    // ---- KvCache::with_capacity + accessors (Phase E.3.3.A) -----------------
2874
2875    /// `with_capacity` allocates n_layers fresh K + V buffers on the
2876    /// CPU device. Each buffer is `n_kv_heads * max_seq_len * head_dim`
2877    /// elements of the requested dtype, zero-initialized, with the
2878    /// `[1, n_kv_heads, max_seq_len, head_dim]` layout pre-populated.
2879    #[test]
2880    // `BackendStorage::{Cuda,Vulkan,Metal}` are cfg-gated, so at default
2881    // features `Cpu` is the only variant and this `if let` is irrefutable;
2882    // under --features cuda/vulkan/metal the pattern is refutable, so a plain
2883    // `let` would be an E0005 there. Allow the default-features lint.
2884    #[allow(irrefutable_let_patterns)]
2885    fn kv_cache_with_capacity_allocates_all_layers_on_cpu() {
2886        let device = Device::cpu();
2887        let cache = KvCache::with_capacity(
2888            /* n_layers     */ 3,
2889            /* n_kv_heads   */ 4,
2890            /* head_dim     */ 16,
2891            /* max_seq_len  */ 32,
2892            DType::F32,
2893            &device,
2894        )
2895        .expect("with_capacity");
2896
2897        assert_eq!(cache.n_layers(), 3);
2898        assert_eq!(cache.cached_len, 0);
2899        assert_eq!(cache.n_kv_heads, 4);
2900        assert_eq!(cache.head_dim, 16);
2901        assert_eq!(cache.max_seq_len, Some(32));
2902        assert_eq!(cache.dtype, Some(DType::F32));
2903
2904        // Every layer is populated and has the expected layout.
2905        for li in 0..3 {
2906            let layer = cache.layer(li).expect("layer populated");
2907            assert_eq!(layer.k_layout.shape().dims(), &[1, 4, 32, 16]);
2908            assert_eq!(layer.v_layout.shape().dims(), &[1, 4, 32, 16]);
2909            // Bytes are zero-initialized: 4 (n_kv) * 32 (seq) * 16 (head)
2910            // * 4 (f32) = 8192 bytes per slot.
2911            let k_guard = layer.k.read().unwrap();
2912            assert_eq!(k_guard.inner.len_bytes(), 8192);
2913            assert_eq!(k_guard.dtype, DType::F32);
2914            // Spot-check zero init.
2915            if let BackendStorage::Cpu(c) = &k_guard.inner {
2916                let typed: &[f32] = c.as_slice().unwrap();
2917                assert!(typed.iter().all(|&x| x == 0.0));
2918            } else {
2919                panic!("expected CPU storage");
2920            }
2921        }
2922    }
2923
2924    /// `slot_storage(li, K)` returns the same Arc as `layer(li).k`.
2925    /// Used by the forward path to bind cache storage to per-step
2926    /// Const nodes.
2927    #[test]
2928    fn kv_cache_slot_storage_returns_layer_arc() {
2929        let device = Device::cpu();
2930        let cache =
2931            KvCache::with_capacity(2, 4, 8, 16, DType::F32, &device).expect("with_capacity");
2932
2933        let k_via_layer = Arc::clone(&cache.layer(0).unwrap().k);
2934        let k_via_slot = cache.slot_storage(0, KvSlot::K).expect("layer 0 K");
2935        assert!(
2936            Arc::ptr_eq(&k_via_layer, &k_via_slot),
2937            "slot_storage should return the same Arc as layer().k",
2938        );
2939
2940        let v_via_layer = Arc::clone(&cache.layer(1).unwrap().v);
2941        let v_via_slot = cache.slot_storage(1, KvSlot::V).expect("layer 1 V");
2942        assert!(Arc::ptr_eq(&v_via_layer, &v_via_slot));
2943    }
2944
2945    /// `slot_storage` returns `None` for an unpopulated layer (the
2946    /// with_dims path before the first set_layer) and for an out-of-
2947    /// range layer index.
2948    #[test]
2949    fn kv_cache_slot_storage_returns_none_for_unpopulated() {
2950        let cache = KvCache::with_dims(2, 4, 8);
2951        assert!(cache.slot_storage(0, KvSlot::K).is_none());
2952        assert!(cache.slot_storage(1, KvSlot::V).is_none());
2953        // Out of range.
2954        assert!(cache.slot_storage(5, KvSlot::K).is_none());
2955    }
2956
2957    /// `bump_version` advances the per-slot version counter
2958    /// independently for K and V.
2959    #[test]
2960    fn kv_cache_bump_version_advances_per_slot() {
2961        let device = Device::cpu();
2962        let mut cache =
2963            KvCache::with_capacity(1, 4, 8, 16, DType::F32, &device).expect("with_capacity");
2964        assert_eq!(cache.layer(0).unwrap().k_version, 0);
2965        assert_eq!(cache.layer(0).unwrap().v_version, 0);
2966
2967        cache.bump_version(0, KvSlot::K);
2968        cache.bump_version(0, KvSlot::K);
2969        cache.bump_version(0, KvSlot::V);
2970
2971        assert_eq!(cache.layer(0).unwrap().k_version, 2);
2972        assert_eq!(cache.layer(0).unwrap().v_version, 1);
2973    }
2974
2975    /// Bumping a version on an unpopulated layer is a no-op (not a
2976    /// panic). The `with_dims` path leaves layers `None`; the
2977    /// forward code shouldn't blow up if it calls bump_version
2978    /// before the layer is wired.
2979    #[test]
2980    fn kv_cache_bump_version_unpopulated_is_noop() {
2981        let mut cache = KvCache::with_dims(2, 4, 8);
2982        cache.bump_version(0, KvSlot::K);
2983        cache.bump_version(99, KvSlot::V); // out of range, also no-op
2984        assert!(cache.layer(0).is_none());
2985    }
2986
2987    /// Sanity: bf16 capacity allocation produces 2-byte elements.
2988    #[test]
2989    fn kv_cache_with_capacity_bf16_byte_count() {
2990        let device = Device::cpu();
2991        let cache =
2992            KvCache::with_capacity(1, 2, 4, 8, DType::BF16, &device).expect("with_capacity bf16");
2993        let layer = cache.layer(0).unwrap();
2994        // 2 (n_kv) * 8 (seq) * 4 (head) * 2 (bf16) = 128 bytes per slot.
2995        assert_eq!(layer.k.read().unwrap().inner.len_bytes(), 128);
2996        assert_eq!(cache.dtype, Some(DType::BF16));
2997    }
2998
2999    // ---- LatentKvCache (MLA increment 4 — persistent N-slot decode cache) --
3000
3001    /// `LatentKvCache::with_capacity` allocates `n_layers * n_slots` fresh
3002    /// zero-initialized buffers on the CPU device, one per (layer, slot),
3003    /// shaped `[max_seq_len, ...slot_trailing[s]]`.
3004    #[test]
3005    // Irrefutable only at default features: `BackendStorage::{Cuda,Vulkan,
3006    // Metal}` are cfg-gated, so under --features cuda/vulkan/metal this pattern
3007    // is refutable and a plain `let` would be an E0005. Allow the default lint.
3008    #[allow(irrefutable_let_patterns)]
3009    fn latent_kv_cache_with_capacity_allocates_all_layers_on_cpu() {
3010        let device = Device::cpu();
3011        let cache = LatentKvCache::with_capacity(
3012            /* n_layers    */ 3,
3013            /* max_seq_len */ 8,
3014            // MLA-shaped: slot 0 latent trailing [5], slot 1 k_pe trailing [2].
3015            vec![vec![5], vec![2]],
3016            DType::F32,
3017            &device,
3018        )
3019        .expect("with_capacity");
3020
3021        assert_eq!(cache.n_layers(), 3);
3022        assert_eq!(cache.n_slots(), 2);
3023        assert_eq!(cache.cached_len, 0);
3024        assert_eq!(cache.max_seq_len, 8);
3025        assert_eq!(cache.dtype, DType::F32);
3026        assert_eq!(cache.slot_trailing(0), &[5]);
3027        assert_eq!(cache.slot_trailing(1), &[2]);
3028
3029        for li in 0..3 {
3030            let latent = cache.slot_storage(li, 0).expect("latent slot populated");
3031            let kpe = cache.slot_storage(li, 1).expect("k_pe slot populated");
3032            // 8 (max_seq) * 5 (trailing) * 4 (f32) = 160 bytes.
3033            assert_eq!(latent.read().unwrap().inner.len_bytes(), 160);
3034            // 8 (max_seq) * 2 (trailing) * 4 (f32) = 64 bytes.
3035            assert_eq!(kpe.read().unwrap().inner.len_bytes(), 64);
3036            let guard = latent.read().unwrap();
3037            if let BackendStorage::Cpu(c) = &guard.inner {
3038                let typed: &[f32] = c.as_slice().unwrap();
3039                assert!(typed.iter().all(|&x| x == 0.0));
3040            } else {
3041                panic!("expected CPU storage");
3042            }
3043        }
3044    }
3045
3046    /// `slot_storage` returns `None` for an out-of-range layer or slot
3047    /// index (never panics).
3048    #[test]
3049    fn latent_kv_cache_slot_storage_returns_none_for_oob() {
3050        let device = Device::cpu();
3051        let cache = LatentKvCache::with_capacity(2, 4, vec![vec![3]], DType::F32, &device)
3052            .expect("with_capacity");
3053        assert!(cache.slot_storage(5, 0).is_none()); // layer OOB
3054        assert!(cache.slot_storage(0, 5).is_none()); // slot OOB
3055    }
3056
3057    /// `bump_version` advances the per-slot version counter independently
3058    /// per slot; out-of-range (layer, slot) is a no-op, never a panic.
3059    #[test]
3060    fn latent_kv_cache_bump_version_advances_per_slot_and_oob_is_noop() {
3061        let device = Device::cpu();
3062        let mut cache =
3063            LatentKvCache::with_capacity(1, 4, vec![vec![2], vec![1]], DType::F32, &device)
3064                .expect("with_capacity");
3065
3066        cache.bump_version(0, 0);
3067        cache.bump_version(0, 0);
3068        cache.bump_version(0, 1);
3069        cache.bump_version(99, 0); // layer OOB, no-op
3070        cache.bump_version(0, 99); // slot OOB, no-op
3071
3072        let layer0 = cache.layers[0].as_ref().expect("layer 0 populated");
3073        assert_eq!(layer0[0].version, 2);
3074        assert_eq!(layer0[1].version, 1);
3075    }
3076
3077    /// Degenerate geometry (`n_layers == 0`, `max_seq_len == 0`, or no
3078    /// slots) surfaces as a typed `Err`, never a panic.
3079    #[test]
3080    fn latent_kv_cache_with_capacity_rejects_bad_geometry() {
3081        let device = Device::cpu();
3082        assert!(LatentKvCache::with_capacity(0, 4, vec![vec![2]], DType::F32, &device).is_err());
3083        assert!(LatentKvCache::with_capacity(1, 0, vec![vec![2]], DType::F32, &device).is_err());
3084        assert!(LatentKvCache::with_capacity(1, 4, vec![], DType::F32, &device).is_err());
3085    }
3086
3087    /// ROADMAP row 172 control: a CPU realize never touches the device's weight residency (no upload, no
3088    /// entry, no hit), and the weights it computes with are exactly the source arrays.
3089    #[test]
3090    fn a_cpu_realize_leaves_the_weight_residency_untouched() {
3091        let dev = Device::cpu();
3092        let w: Arc<[f32]> = vec![1.0, 2.0, 3.0].into();
3093        let a =
3094            fuel_graph::NodeHandle::from_f32(Arc::clone(&w), Shape::from_dims(&[3]), dev.as_dyn())
3095                .unwrap();
3096        let b = a
3097            .const_f32_like(Arc::clone(&w), Shape::from_dims(&[3]))
3098            .unwrap();
3099        let y = a.add(&b);
3100        assert_eq!(
3101            a.graph().read().unwrap().const_origins().count(),
3102            2,
3103            "both weight Consts recorded their origin"
3104        );
3105        let ctx = InferenceContext::new(dev.clone());
3106        for _ in 0..2 {
3107            let out = ctx
3108                .realize_one_as_with_env::<f32>(y.graph(), y.id(), &SymEnv::new())
3109                .expect("cpu realize");
3110            assert_eq!(out, vec![2.0, 4.0, 6.0]);
3111        }
3112        assert_eq!(
3113            dev.weight_residency_stats(),
3114            crate::WeightResidencyStats::default(),
3115            "a CPU device must never use the residency"
3116        );
3117    }
3118}