aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#168 (code only)
Apply it
git checkout -b patch-259bf59f00eda76d 1015829861a189e6735f9af911ef100a004e725b curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/259bf59f00eda76d.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
168
d70fc9916d0c2fb6aa51125a78362ce36350d3c5
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":168,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/168","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:11Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/crates/aien-inference-abi/src/transformer_backend.rs b/crates/aien-inference-abi/src/transformer_backend.rs index 0ea923dd..fc456044 100644 --- a/crates/aien-inference-abi/src/transformer_backend.rs +++ b/crates/aien-inference-abi/src/transformer_backend.rs @@ -10,7 +10,9 @@ use crate::{ AienInferenceBackend, AienUsageReceipt, BranchHandle, ContextHandle, DecodeOutput, FinishReason, ModelConfig, SamplingParams, ScheduledBatch, StepMetrics, }; -use aien_kv_cache::{create_shared_kv_manager_with_pool, KvDType, KvPoolConfig, SharedKvManager}; +use aien_kv_cache::{ + create_shared_kv_manager_with_pool, AienKvManager, KvDType, KvPoolConfig, SharedKvManager, +}; use async_trait::async_trait; use std::collections::HashMap; use std::sync::atomic::{AtomicU64, Ordering}; @@ -18,6 +20,12 @@ use std::sync::Arc; static NEXT_HANDLE_ID: AtomicU64 = AtomicU64::new(1); +/// Stable prefix of every error returned when the paged KV pool cannot supply +/// the blocks a prefill append or a single-token decode step needs +/// (PREFILL-I25). The rest of the message says how many new blocks were needed +/// and how many were free. Callers and tests may match on this prefix. +pub const KV_POOL_EXHAUSTED_PREFIX: &str = "KV pool exhausted:"; + /// splitmix64 mixing step (the generator behind java.util.SplittableRandom): /// a bijective 64-bit mixer, in-house, no outside crate. fn splitmix64(mut z: u64) -> u64 { @@ -282,7 +290,7 @@ impl NativeTransformerBackend { seq, seq_id, self.kv_manager.as_ref(), - ); + )?; let logits = Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &last_hidden); Ok(logits) @@ -315,7 +323,7 @@ impl NativeTransformerBackend { seq, handle.0, self.kv_manager.as_ref(), - ); + )?; Ok(handle) } @@ -387,7 +395,7 @@ impl NativeTransformerBackend { let pos = seq.tokens.len().saturating_sub(1); let last_token = *seq.tokens.last().unwrap_or(&1); - let hidden = Self::forward_token_impl_paged( + let hidden = Self::try_forward_token_impl_paged( &self.weights, &*self.tensor_backend, last_token, @@ -395,7 +403,7 @@ impl NativeTransformerBackend { seq, branch.0, self.kv_manager.as_ref(), - ); + )?; let logits = Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &hidden); let (sampled_tok, _) = sample_argmax(&logits); @@ -414,7 +422,7 @@ impl NativeTransformerBackend { .ok_or_else(|| format!("Branch {} not found", branch.0))?; let pos = seq.tokens.len(); - let _hidden = Self::forward_token_impl_paged( + let _hidden = Self::try_forward_token_impl_paged( &self.weights, &*self.tensor_backend, token, @@ -422,7 +430,7 @@ impl NativeTransformerBackend { seq, branch.0, self.kv_manager.as_ref(), - ); + )?; seq.tokens.push(token); Ok(()) } @@ -487,7 +495,7 @@ impl NativeTransformerBackend { let pos = seq.tokens.len().saturating_sub(1); let last_token = *seq.tokens.last().unwrap_or(&1); - let hidden = Self::forward_token_impl_paged( + let hidden = match Self::try_forward_token_impl_paged( &self.weights, &*self.tensor_backend, last_token, @@ -495,7 +503,15 @@ impl NativeTransformerBackend { seq, seq_id, self.kv_manager.as_ref(), - ); + ) { + Ok(hidden) => hidden, + Err(e) => { + // This standalone generator owns its KV: do not leak the + // sequence when a decode step cannot get a block. + self.release_sequence(seq_id); + return Err(e); + } + }; let next_logits = Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &hidden); @@ -634,7 +650,77 @@ impl NativeTransformerBackend { Self::forward_token_impl_paged(weights, backend, token_id, pos, seq_state, 0, None) } + /// How many fresh physical blocks `appends` consecutive + /// `AienKvManager::append_token_with_slot` calls on `seq_id` would + /// allocate, computed read-only from the table's tail block with the same + /// rule as aien-kv-cache `append_token_with_slot`: + /// - empty table: the first append allocates a block; + /// - shared tail block, partly filled: copy-on-write, one fresh block; + /// - shared tail block, full: one fresh block; + /// - private tail block: its free slots take appends first; + /// + /// then every further `block_size` appends need one more fresh block. + /// Returns 0 when the sequence has no block table (the append itself then + /// reports the missing sequence). + fn kv_blocks_needed_for_appends(kv: &AienKvManager, seq_id: u64, appends: usize) -> usize { + if appends == 0 { + return 0; + } + let Some(table) = kv.get_block_table(seq_id) else { + return 0; + }; + let block_size = kv.block_size(); + let mut remaining = appends; + let mut needed = 0usize; + // Free slots left in the tail block once the first append has resolved. + let tail_free = match table.block_ids.last().and_then(|&id| kv.get_block(id)) { + None => { + // Empty table: the first append allocates a block holding 1 token. + needed += 1; + remaining -= 1; + block_size - 1 + } + Some(blk) if blk.is_shared => { + // Copy-on-write of a partly filled tail, or a fresh block after a + // full one: either way one fresh private block takes this append. + needed += 1; + remaining -= 1; + if blk.num_tokens < block_size { + block_size - (blk.num_tokens + 1) + } else { + block_size - 1 + } + } + Some(blk) => block_size.saturating_sub(blk.num_tokens), + }; + remaining -= remaining.min(tail_free); + needed + remaining.div_ceil(block_size) + } + + /// `Some((needed, available))` when `appends` appends to `seq_id` need more + /// new blocks than the pool has free, `None` when they fit. Read-only. + fn kv_pool_shortfall( + kv: &AienKvManager, + seq_id: u64, + appends: usize, + ) -> Option<(usize, usize)> { + let needed = Self::kv_blocks_needed_for_appends(kv, seq_id, appends); + let available = kv.available_blocks(); + (needed > available).then_some((needed, available)) + } + + /// Message for a capacity failure; always starts with `KV_POOL_EXHAUSTED_PREFIX`. + fn kv_pool_exhausted_error(what: &str, seq_id: u64, needed: usize, available: usize) -> String { + format!( + "{KV_POOL_EXHAUSTED_PREFIX} {what} for sequence {seq_id} needs {needed} new KV blocks \ + but only {available} are free; the block table, the pool and the sequence state are unchanged" + ) + } + /// Forward pass executing one token forward pass through the transformer with optional paged COW KV. + /// + /// Panics when the paged KV pool cannot supply the block this token needs + /// (see `try_forward_token_impl_paged`, which returns the error instead). pub fn forward_token_impl_paged( weights: &TransformerWeights, backend: &dyn TensorBackend, @@ -644,6 +730,28 @@ impl NativeTransformerBackend { seq_id: u64, kv_manager: Option<&SharedKvManager>, ) -> Vec<f32> { + Self::try_forward_token_impl_paged( + weights, backend, token_id, pos, seq_state, seq_id, kv_manager, + ) + .unwrap_or_else(|e| panic!("forward_token_impl_paged: {e}")) + } + + /// Same as `forward_token_impl_paged`, but returns a loud `Err` (message + /// starting with `KV_POOL_EXHAUSTED_PREFIX`) when the paged KV pool has no + /// block for this token, instead of continuing with no stored K/V + /// (PREFILL-I25). The capacity check runs before anything is mutated, so a + /// failed call leaves the block table, the pool and `seq_state` unchanged. + /// A sequence with no block table in the manager still takes the dense + /// per-layer cache path, as before. + pub fn try_forward_token_impl_paged( + weights: &TransformerWeights, + backend: &dyn TensorBackend, + token_id: u32, + pos: usize, + seq_state: &mut SequenceState, + seq_id: u64, + kv_manager: Option<&SharedKvManager>, + ) -> Result<Vec<f32>, String> { let hidden_dim = weights.config.hidden_dim(); let num_heads = weights.config.num_heads; let num_kv_heads = weights.config.num_kv_heads; @@ -670,10 +778,34 @@ impl NativeTransformerBackend { let mut activated = vec![0.0f32; intermediate_dim]; let mut mlp_out = vec![0.0f32; hidden_dim]; - let block_slot = if let Some(mgr) = kv_manager { - mgr.write().append_token_with_slot(seq_id).ok() - } else { - None + // Reserve this token's slot. A full pool is a loud error (checked before + // anything is mutated), never a silent fall back to "no stored K/V". + // A sequence with no block table in the manager keeps the dense + // per-layer cache path, as before. + let block_slot = match kv_manager { + Some(mgr) => { + let mut w = mgr.write(); + if w.get_block_table(seq_id).is_some() { + if let Some((needed, available)) = Self::kv_pool_shortfall(&w, seq_id, 1) { + return Err(Self::kv_pool_exhausted_error( + &format!("decode step at position {pos}"), + seq_id, + needed, + available, + )); + } + let slot = w.append_token_with_slot(seq_id).map_err(|e| { + format!( + "{KV_POOL_EXHAUSTED_PREFIX} append of position {pos} for sequence \ + {seq_id} failed after the capacity check: {e}" + ) + })?; + Some(slot) + } else { + None + } + } + None => None, }; for (layer_idx, layer_w) in weights.layers.iter().enumerate() { @@ -693,9 +825,21 @@ impl NativeTransformerBackend { ); if let (Some((block_id, slot)), Some(mgr)) = (block_slot, kv_manager) { - let _ = mgr - .write() - .write_explicit_token_kv(block_id, layer_idx, slot, &k, &v); + { + let mut w = mgr.write(); + // A manager with no physical pool has nowhere to store K/V; + // that case is skipped, as before. With a pool the write + // cannot fail silently any more. + if w.tensor_pool().is_some() { + w.write_explicit_token_kv(block_id, layer_idx, slot, &k, &v) + .map_err(|e| { + format!( + "KV write failed for sequence {seq_id} layer {layer_idx} \ + position {pos}: {e}" + ) + })?; + } + } let mgr_read = mgr.read(); if let (Some(pool), Some(table)) = @@ -776,7 +920,7 @@ impl NativeTransformerBackend { let mut x_final = vec![0.0f32; hidden_dim]; backend.rmsnorm(&mut x_final, &x, &weights.final_norm, eps); - x_final + Ok(x_final) } pub fn compute_logits_impl( @@ -812,9 +956,17 @@ impl NativeTransformerBackend { 0, None, ) + .unwrap_or_else(|e| panic!("prefill without a KV manager cannot hit the KV pool: {e}")) } /// Prefill all prompt tokens layer-by-layer with optional paged COW KV registration. + /// + /// In paged mode, positions beyond the block table's allocated length are + /// appended to the table. If the pool cannot supply the blocks those + /// appends need, the call fails with an `Err` starting with + /// `KV_POOL_EXHAUSTED_PREFIX` BEFORE anything is mutated: the block table, + /// the free-block count and `seq_state` stay exactly as they were, so the + /// same call can be retried once blocks are freed (PREFILL-I25). pub fn prefill_prompt_layer_by_layer_paged( weights: &TransformerWeights, backend: &dyn TensorBackend, @@ -822,18 +974,19 @@ impl NativeTransformerBackend { seq_state: &mut SequenceState, seq_id: u64, kv_manager: Option<&SharedKvManager>, - ) -> Vec<f32> { + ) -> Result<Vec<f32>, String> { let n = prompt_tokens.len(); if n == 0 { - return Vec::new(); + return Ok(Vec::new()); } // Tokens already in this sequence (earlier prefill chunks). This chunk's // token t sits at absolute position `offset + t`: that position drives RoPE, // the paged block/slot, and the causal attention length. let offset = seq_state.tokens.len(); if n == 1 && offset == 0 { - seq_state.tokens.push(prompt_tokens[0]); - return Self::forward_token_impl_paged( + // The token is recorded only after the forward pass succeeded, so a + // loud KV failure leaves `seq_state` untouched. + let hidden = Self::try_forward_token_impl_paged( weights, backend, prompt_tokens[0], @@ -841,7 +994,9 @@ impl NativeTransformerBackend { seq_state, seq_id, kv_manager, - ); + )?; + seq_state.tokens.push(prompt_tokens[0]); + return Ok(hidden); } let hidden_dim = weights.config.hidden_dim(); @@ -854,6 +1009,49 @@ impl NativeTransformerBackend { let eps = weights.config.rms_norm_eps; let theta = weights.config.rope_theta; + // Paged mode: one physical (block, slot) per absolute position, resolved once + // (not per layer). Positions inside the table's allocated length (the + // scheduler allocates the whole prompt up front) use the existing blocks; + // positions beyond it are appended to the table. Resolved first, before + // `seq_state` is touched, so a pool that cannot hold the appends fails the + // whole call cleanly (PREFILL-I25). + let num_layers = weights.config.num_layers; + let mut paged_slots: Vec<Option<(usize, usize)>> = vec![None; n]; + if let Some(mgr) = kv_manager { + let mut w = mgr.write(); + if w.tensor_pool().is_some() { + let block_size = w.block_size(); + if let Some(tbl) = w.get_block_table(seq_id).cloned() { + let covered = + |p: usize| p < tbl.total_tokens && p / block_size < tbl.block_ids.len(); + let appends = (0..n).filter(|&t| !covered(offset + t)).count(); + if let Some((needed, available)) = Self::kv_pool_shortfall(&w, seq_id, appends) + { + return Err(Self::kv_pool_exhausted_error( + &format!("prefill of {n} tokens at position {offset}"), + seq_id, + needed, + available, + )); + } + for (t, slot_out) in paged_slots.iter_mut().enumerate() { + let p = offset + t; + *slot_out = if covered(p) { + Some((tbl.block_ids[p / block_size], p % block_size)) + } else { + let slot = w.append_token_with_slot(seq_id).map_err(|e| { + format!( + "{KV_POOL_EXHAUSTED_PREFIX} append of position {p} for \ + sequence {seq_id} failed after the capacity check: {e}" + ) + })?; + Some(slot) + }; + } + } + } + } + seq_state.tokens.extend_from_slice(prompt_tokens); let mut states: Vec<Vec<f32>> = prompt_tokens @@ -878,30 +1076,6 @@ impl NativeTransformerBackend { let mut act_batch = vec![0.0f32; n * intermediate_dim]; let mut mlp_out_batch = vec![0.0f32; n * hidden_dim]; - // Paged mode: one physical (block, slot) per absolute position, resolved once - // (not per layer). Positions inside the table's allocated length (the - // scheduler allocates the whole prompt up front) use the existing blocks; - // positions beyond it are appended to the table. - let num_layers = weights.config.num_layers; - let mut paged_slots: Vec<Option<(usize, usize)>> = vec![None; n]; - if let Some(mgr) = kv_manager { - let mut w = mgr.write(); - if w.tensor_pool().is_some() { - let block_size = w.block_size(); - if let Some(tbl) = w.get_block_table(seq_id).cloned() { - for (t, slot_out) in paged_slots.iter_mut().enumerate() { - let p = offset + t; - *slot_out = if p < tbl.total_tokens && p / block_size < tbl.block_ids.len() - { - Some((tbl.block_ids[p / block_size], p % block_size)) - } else { - w.append_token_with_slot(seq_id).ok() - }; - } - } - } - } - // The dense per-layer cache must hold K/V for positions 0..offset before this // chunk's attention runs. Paged mode clears it after each prefill, so rebuild // it from the physical pool. @@ -967,9 +1141,16 @@ impl NativeTransformerBackend { backend.apply_rope(q_t, k_t, pos, head_dim, num_heads, num_kv_heads, theta); if let (Some((block_id, slot)), Some(mgr)) = (paged_slots[t], kv_manager) { - let _ = mgr - .write() - .write_explicit_token_kv(block_id, layer_idx, slot, k_t, v_t); + // Slots exist only when a physical pool is attached, so this + // write has nowhere to fail silently; any error is loud. + mgr.write() + .write_explicit_token_kv(block_id, layer_idx, slot, k_t, v_t) + .map_err(|e| { + format!( + "KV write failed for sequence {seq_id} layer {layer_idx} \ + position {pos}: {e}" + ) + })?; } kv_cache.cached_k.push(k_t.to_vec()); @@ -1069,7 +1250,7 @@ impl NativeTransformerBackend { let last_x = &states[n - 1]; let mut x_final = vec![0.0f32; hidden_dim]; backend.rmsnorm(&mut x_final, last_x, &weights.final_norm, eps); - x_final + Ok(x_final) } /// Single-token forward pass executing through the configured TensorBackend trait. @@ -1656,9 +1837,6 @@ impl AienInferenceBackend for NativeTransformerBackend { // PREFILL-E2E C6: decode of this request uses its sampling params. self.sampling .insert(req.request_id, req.sampling_params.clone()); - // A further prefill chunk: the sample held from the previous chunk was - // mid-prompt and is discarded. - self.pending_prefill_token.remove(&req.request_id); if let Some(kv_mgr) = &self.kv_manager { let mut mgr = kv_mgr.write(); @@ -1682,7 +1860,12 @@ impl AienInferenceBackend for NativeTransformerBackend { seq, req.request_id, self.kv_manager.as_ref(), - ); + )?; + // A further prefill chunk: the sample held from the previous chunk was + // mid-prompt and is discarded. Done only after this chunk succeeded, so a + // chunk that fails loudly (KV pool exhausted) keeps the held sample and + // can be retried against unchanged state (PREFILL-I25). + self.pending_prefill_token.remove(&req.request_id); let logits = Self::compute_logits_impl(&self.weights, &*self.tensor_backend, &last_hidden); diff --git a/crates/aien-inference-abi/tests/prefill_pool_exhaustion.rs b/crates/aien-inference-abi/tests/prefill_pool_exhaustion.rs new file mode 100644 index 00000000..07e26c0e --- /dev/null +++ b/crates/aien-inference-abi/tests/prefill_pool_exhaustion.rs @@ -0,0 +1,705 @@ +//! PREFILL-I25: a KV pool that runs out during a prefill append or a +//! single-token decode step must fail LOUDLY and leave a retryable state. +//! +//! Before the fix, `prefill_prompt_layer_by_layer_paged` turned an +//! out-of-blocks error from `append_token_with_slot` into `None` (`.ok()`), +//! dropped the K/V write result, and returned Ok: the appended tokens were +//! silently not stored in the pool. The single-token path +//! (`forward_token_impl_paged`) had the same `.ok()` on its slot. +//! +//! Runs on the CPU reference backend with synthetic reference weights and a +//! tiny paged pool (block size 4), so it needs no checkpoint and takes +//! seconds. It is not ignored. +//! +//! Receipt: written as JSON to the path in env `AIEN_I25_RECEIPT` (when set) +//! BEFORE any assertion fires. Every check has its own marker in its failure +//! message; all check outcomes are printed first so every marker that +//! applies is in the log. +//! +//! Checks and markers: +//! - x_prefill_exhaustion_is_loud POOL_SILENT_SUCCESS_VIOLATION +//! (POOL_ERROR_PREFIX_VIOLATION when the Err lacks the stable prefix or +//! the needed/available numbers) +//! - x_prefill_exhaustion_is_atomic POOL_PARTIAL_STATE_VIOLATION +//! - x_prefill_clean_path_unchanged CLEAN_PATH_VIOLATION +//! - x_exact_fit_ok BOUNDARY_VIOLATION +//! - x_decode_exhaustion_is_loud POOL_SILENT_SUCCESS_VIOLATION +//! - x_recovers_after_free RETRY_VIOLATION +//! +//! A check whose precondition is not met (for example the atomicity check +//! when the append did not fail at all) is recorded with `applicable: false` +//! and passes vacuously; the check that owns that precondition fails instead. +//! +//! Scenarios: the prompt is 6 tokens (one full block of 4 and a tail with 2 +//! tokens). The second prefill chunk appends 11 tokens (ends mid-block) or +//! 10 tokens (ends exactly on a block boundary), with the prompt's tail +//! either private or shared with a second sequence (so the first append +//! needs a copy-on-write block). The number of new blocks each scenario +//! needs is computed by `oracle_new_blocks` from first principles, not by +//! the backend's own helper. + +use aien_inference_abi::{ + AienInferenceBackend, DecodeOutput, FinishReason, ModelConfig, NativeTransformerBackend, + ScheduledBatch, TransformerWeights, +}; +use std::collections::HashMap; + +const BLOCK_SIZE: usize = 4; +/// Prompt tokens: 6 = one full block of 4 plus a partly filled tail of 2. +const PROMPT_LEN: usize = 6; +/// Second-chunk lengths: 11 ends mid-block (17 tokens), 10 ends exactly on a +/// block boundary (16 tokens). +const APPEND_LENS: [usize; 2] = [11, 10]; +/// Pool used for the exhaustion and boundary scenarios. +const SMALL_POOL: usize = 24; +/// Pool that is always large enough. +const BIG_POOL: usize = 64; + +const SEQ: u64 = 7001; +const WITNESS: u64 = 7002; +const FILLER: u64 = 7003; +const CONTROL: u64 = 7004; + +/// The stable prefix of every pool-exhaustion error. Kept as a literal here +/// (not imported from the crate) so a renamed or reworded prefix is caught. +const PREFIX: &str = "KV pool exhausted:"; + +const M_SILENT: &str = "POOL_SILENT_SUCCESS_VIOLATION"; +const M_PREFIX: &str = "POOL_ERROR_PREFIX_VIOLATION"; +const M_PARTIAL: &str = "POOL_PARTIAL_STATE_VIOLATION"; +const M_CLEAN: &str = "CLEAN_PATH_VIOLATION"; +const M_BOUNDARY: &str = "BOUNDARY_VIOLATION"; +const M_RETRY: &str = "RETRY_VIOLATION"; + +type Planes = Vec<(Vec<f32>, Vec<f32>)>; + +/// One scenario: is the prompt's tail shared with `WITNESS`, and how many +/// tokens does the second prefill chunk append. +#[derive(Clone, Copy)] +struct Scenario { + shared_tail: bool, + len: usize, +} + +impl Scenario { + fn label(&self) -> String { + format!("shared_tail={} append_len={}", self.shared_tail, self.len) + } + + /// New blocks this scenario's append needs. + fn need(&self) -> usize { + oracle_new_blocks(PROMPT_LEN, self.len, self.shared_tail) + } +} + +fn scenarios() -> Vec<Scenario> { + let mut all = Vec::new(); + for len in APPEND_LENS { + for shared_tail in [false, true] { + all.push(Scenario { shared_tail, len }); + } + } + all +} + +fn config() -> ModelConfig { + ModelConfig { + num_layers: 2, + num_heads: 4, + num_kv_heads: 2, + head_dim: 16, + hidden_dim: 64, + intermediate_dim: 128, + vocab_size: 256, + block_size: BLOCK_SIZE, + ..Default::default() + } +} + +fn backend(total_blocks: usize) -> NativeTransformerBackend { + let weights = TransformerWeights::reference_test_weights(&config()); + NativeTransformerBackend::with_paged_kv(weights, total_blocks, BLOCK_SIZE) + .expect("small paged backend") +} + +/// Deterministic tokens `start..start+n` of one fixed stream (ids 3..=255). +fn tokens(start: usize, n: usize) -> Vec<u32> { + (start..start + n) + .map(|i| ((i * 37 + 11) % 253 + 3) as u32) + .collect() +} + +fn free_blocks(be: &NativeTransformerBackend) -> usize { + let kv = be.kv_manager.as_ref().expect("kv manager").read(); + kv.free_block_count() +} + +fn table_of(be: &NativeTransformerBackend, id: u64) -> (Vec<usize>, usize) { + let kv = be.kv_manager.as_ref().expect("kv manager").read(); + let table = kv.get_block_table(id).expect("block table"); + (table.block_ids.clone(), table.total_tokens) +} + +/// K and V of every layer over the table's tokens, gathered from the pool. +fn kv_planes(be: &NativeTransformerBackend, id: u64) -> Planes { + let kv = be.kv_manager.as_ref().expect("kv manager").read(); + let mut planes: Planes = Vec::new(); + for layer in 0..config().num_layers { + planes.push(kv.gather_layer_kv(id, layer).expect("gather layer kv")); + } + planes +} + +/// Everything the atomicity check compares before and after a failed call. +struct Snap { + ids: Vec<usize>, + total: usize, + free: usize, + seq_tokens: Vec<u32>, + planes: Planes, +} + +fn snap(be: &NativeTransformerBackend, id: u64) -> Snap { + let (ids, total) = table_of(be, id); + Snap { + ids, + total, + free: free_blocks(be), + seq_tokens: be.sequences[&id].tokens.clone(), + planes: kv_planes(be, id), + } +} + +/// Field-by-field differences between two snapshots (empty = identical). +fn snap_diff(a: &Snap, b: &Snap) -> Vec<String> { + let mut d = Vec::new(); + if a.ids != b.ids { + d.push(format!("block ids {:?} -> {:?}", a.ids, b.ids)); + } + if a.total != b.total { + d.push(format!("table total_tokens {} -> {}", a.total, b.total)); + } + if a.free != b.free { + d.push(format!("free blocks {} -> {}", a.free, b.free)); + } + if a.seq_tokens != b.seq_tokens { + d.push(format!( + "backend sequence tokens {} -> {}", + a.seq_tokens.len(), + b.seq_tokens.len() + )); + } + if !planes_equal(&a.planes, &b.planes) { + d.push("pool K/V of the sequence changed".to_string()); + } + d +} + +/// Bitwise equality of two gathered K/V sets (tolerance 0.0). +fn planes_equal(a: &Planes, b: &Planes) -> bool { + a.len() == b.len() + && a.iter().zip(b.iter()).all(|(x, y)| { + x.0.len() == y.0.len() + && x.1.len() == y.1.len() + && x.0 + .iter() + .zip(y.0.iter()) + .all(|(p, q)| p.to_bits() == q.to_bits()) + && x.1 + .iter() + .zip(y.1.iter()) + .all(|(p, q)| p.to_bits() == q.to_bits()) + }) +} + +/// Largest absolute K or V difference (for the message only; equality is bitwise). +fn planes_max_abs_diff(a: &Planes, b: &Planes) -> f32 { + if a.len() != b.len() { + return f32::INFINITY; + } + let mut max = 0.0f32; + for (x, y) in a.iter().zip(b.iter()) { + if x.0.len() != y.0.len() || x.1.len() != y.1.len() { + return f32::INFINITY; + } + for (p, q) in x.0.iter().zip(y.0.iter()).chain(x.1.iter().zip(y.1.iter())) { + max = max.max((p - q).abs()); + } + } + max +} + +/// One-shot control: the first `len` tokens of the stream prefilled in one +/// call on a backend with a large pool. +fn control_planes(len: usize) -> Planes { + let mut control = backend(BIG_POOL); + control + .prefill_sequence(CONTROL, &tokens(0, len)) + .expect("control prefill"); + kv_planes(&control, CONTROL) +} + +/// Independent oracle for how many new blocks the append needs. It does not +/// use the backend's helper: blocks after minus blocks before, plus one +/// copy-on-write block when the table's partly filled tail is shared. +fn oracle_new_blocks(prompt: usize, appended: usize, shared_partial_tail: bool) -> usize { + let before = prompt.div_ceil(BLOCK_SIZE); + let after = (prompt + appended).div_ceil(BLOCK_SIZE); + let cow = + usize::from(shared_partial_tail && !prompt.is_multiple_of(BLOCK_SIZE) && appended > 0); + after - before + cow +} + +/// Allocates `FILLER` so that exactly `target` blocks stay free. +fn fill_pool_to(be: &NativeTransformerBackend, target: usize) { + let free = free_blocks(be); + assert!( + free >= target, + "setup: only {free} blocks free, cannot leave {target}" + ); + if free > target { + let filler = vec![1u32; (free - target) * BLOCK_SIZE]; + be.kv_manager + .as_ref() + .expect("kv manager") + .write() + .allocate_sequence(FILLER, &filler) + .expect("filler allocation"); + } + assert_eq!(free_blocks(be), target, "setup: free blocks after filler"); +} + +/// Backend with a pool of `total_blocks`, the prompt prefilled for `SEQ`, the +/// tail optionally shared with `WITNESS`, and (when `free_target` is given) +/// the pool filled by `FILLER` until exactly `free_target` blocks are free. +fn setup( + total_blocks: usize, + shared_tail: bool, + free_target: Option<usize>, +) -> NativeTransformerBackend { + let mut be = backend(total_blocks); + be.prefill_sequence(SEQ, &tokens(0, PROMPT_LEN)) + .expect("prompt prefill"); + if shared_tail { + be.kv_manager + .as_ref() + .expect("kv manager") + .write() + .fork_sequence(SEQ, WITNESS) + .expect("witness fork"); + } + if let Some(target) = free_target { + fill_pool_to(&be, target); + } + be +} + +/// The append under test: a second prefill chunk of `len` tokens for `SEQ`, +/// at positions `PROMPT_LEN..PROMPT_LEN + len`. +fn append(be: &mut NativeTransformerBackend, len: usize) -> Result<Vec<f32>, String> { + be.prefill_sequence(SEQ, &tokens(PROMPT_LEN, len)) +} + +struct Check { + name: &'static str, + marker: &'static str, + pass: bool, + applicable: bool, + message: String, +} + +fn check_loud() -> Check { + let mut notes = Vec::new(); + let mut silent = false; + let mut bad_error = false; + for sc in scenarios() { + let need = sc.need(); + let mut be = setup(SMALL_POOL, sc.shared_tail, Some(need - 1)); + match append(&mut be, sc.len) { + Ok(_) => { + silent = true; + notes.push(format!( + "{}: append returned Ok with {} free blocks but {need} needed", + sc.label(), + need - 1 + )); + } + Err(e) => { + let needs = format!("needs {need} new KV blocks"); + let only = format!("only {} are free", need - 1); + if e.starts_with(PREFIX) && e.contains(&needs) && e.contains(&only) { + notes.push(format!("{}: loud Err: {e}", sc.label())); + } else { + bad_error = true; + notes.push(format!( + "{}: Err must start with {PREFIX:?} and contain {needs:?} and \ + {only:?}, got: {e}", + sc.label() + )); + } + } + } + } + Check { + name: "x_prefill_exhaustion_is_loud", + marker: if silent { M_SILENT } else { M_PREFIX }, + pass: !silent && !bad_error, + applicable: true, + message: notes.join("; "), + } +} + +fn check_atomic() -> Check { + let mut notes = Vec::new(); + let mut applied = false; + let mut pass = true; + for sc in scenarios() { + let need = sc.need(); + let mut be = setup(SMALL_POOL, sc.shared_tail, Some(need - 1)); + let before = snap(&be, SEQ); + match append(&mut be, sc.len) { + Ok(_) => notes.push(format!( + "{}: append did not fail, atomicity not applicable", + sc.label() + )), + Err(_) => { + applied = true; + let diff = snap_diff(&before, &snap(&be, SEQ)); + if diff.is_empty() { + notes.push(format!("{}: state unchanged", sc.label())); + } else { + pass = false; + notes.push(format!( + "{}: failed append left partial state: {}", + sc.label(), + diff.join(", ") + )); + } + } + } + } + Check { + name: "x_prefill_exhaustion_is_atomic", + marker: M_PARTIAL, + pass, + applicable: applied, + message: notes.join("; "), + } +} + +/// Appends `sc.len` tokens on `be` (pool large enough) and compares the +/// result with the one-shot control. Returns notes and whether everything +/// matched exactly. +fn append_matches_control( + be: &mut NativeTransformerBackend, + sc: Scenario, + stage: &str, +) -> (Vec<String>, bool) { + let label = format!("{} {stage}", sc.label()); + if let Err(e) = append(be, sc.len) { + return (vec![format!("{label}: append returned Err: {e}")], false); + } + let mut notes = Vec::new(); + let mut ok = true; + let full = PROMPT_LEN + sc.len; + let (_, total) = table_of(be, SEQ); + if total != full { + ok = false; + notes.push(format!( + "{label}: table holds {total} tokens, expected {full}" + )); + } + if be.sequences[&SEQ].tokens != tokens(0, full) { + ok = false; + notes.push(format!( + "{label}: backend sequence tokens differ from the stream" + )); + } + let got = kv_planes(be, SEQ); + let want = control_planes(full); + if planes_equal(&got, &want) { + notes.push(format!("{label}: K/V equals the one-shot control exactly")); + } else { + ok = false; + notes.push(format!( + "{label}: pool K/V differs from the one-shot control (max abs diff {})", + planes_max_abs_diff(&got, &want) + )); + } + (notes, ok) +} + +/// The witness shares the old blocks and must be untouched by the append: its +/// K/V equals a prompt-only control. +fn witness_untouched(be: &NativeTransformerBackend) -> bool { + planes_equal(&kv_planes(be, WITNESS), &control_planes(PROMPT_LEN)) +} + +fn check_clean_path() -> Check { + let mut notes = Vec::new(); + let mut pass = true; + for sc in scenarios() { + let mut be = setup(BIG_POOL, sc.shared_tail, None); + let (n, ok) = append_matches_control(&mut be, sc, "clean"); + notes.extend(n); + pass &= ok; + if sc.shared_tail { + if witness_untouched(&be) { + notes.push(format!("{}: witness K/V untouched", sc.label())); + } else { + pass = false; + notes.push(format!("{}: witness K/V changed by the append", sc.label())); + } + } + } + Check { + name: "x_prefill_clean_path_unchanged", + marker: M_CLEAN, + pass, + applicable: true, + message: notes.join("; "), + } +} + +/// Exactly as many free blocks as the append needs: it must succeed, store +/// the right K/V, and drain the pool to zero. +fn check_exact_fit() -> Check { + let mut notes = Vec::new(); + let mut pass = true; + for sc in scenarios() { + let need = sc.need(); + let mut be = setup(SMALL_POOL, sc.shared_tail, Some(need)); + let (n, ok) = append_matches_control(&mut be, sc, "exact fit"); + notes.extend(n); + pass &= ok; + let free_after = free_blocks(&be); + if free_after != 0 { + pass = false; + notes.push(format!( + "{} exact fit: {free_after} blocks free after the append, expected 0", + sc.label() + )); + } + } + Check { + name: "x_exact_fit_ok", + marker: M_BOUNDARY, + pass, + applicable: true, + message: notes.join("; "), + } +} + +/// Single-token path (`forward_token_impl_paged`, reached through +/// `decode_branch_step`): a branch whose shared tail block is full needs a new +/// block, and the pool has none. +fn decode_single_token_leg() -> (bool, String) { + let mut be = backend(SMALL_POOL); + let ctx = be + .create_context(&tokens(0, 2 * BLOCK_SIZE)) + .expect("context"); + let branch = be.fork_context(ctx).expect("branch"); + fill_pool_to(&be, 0); + let before = table_of(&be, branch.0); + let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + be.decode_branch_step(branch) + })); + match outcome { + Ok(Ok((tok, _))) => ( + false, + format!("decode_branch_step returned Ok (token {tok}) with no free block"), + ), + Ok(Err(e)) if e.starts_with(PREFIX) => { + let after = table_of(&be, branch.0); + if after == before && free_blocks(&be) == 0 { + (true, format!("single-token path loud Err: {e}")) + } else { + ( + false, + format!("single-token Err left partial state: {before:?} -> {after:?}"), + ) + } + } + Ok(Err(e)) => ( + false, + format!("single-token Err lacks the prefix {PREFIX:?}: {e}"), + ), + Err(payload) => { + let msg = payload + .downcast_ref::<String>() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string())) + .unwrap_or_else(|| "non-string panic".to_string()); + ( + false, + format!("decode_branch_step panicked instead of returning a loud Err: {msg}"), + ) + } + } +} + +/// Batched path (`execute_step` decode request, `forward_decode_batch`): the +/// slot is reserved before compute and a full pool already ends the sequence +/// as `Preempted`; it must never emit a token. +async fn decode_batched_leg() -> (bool, String) { + let mut be = backend(SMALL_POOL); + be.prefill_sequence(SEQ, &tokens(0, 2 * BLOCK_SIZE)) + .expect("prefill"); + fill_pool_to(&be, 0); + let before = table_of(&be, SEQ); + let batch = ScheduledBatch { + prefill_requests: Vec::new(), + decode_requests: vec![SEQ], + block_tables: HashMap::new(), + step_id: 0, + }; + match be.execute_step(&batch).await { + Ok((outputs, _metrics)) => { + let token = outputs + .iter() + .any(|o| matches!(o, DecodeOutput::Token { request_id, .. } if *request_id == SEQ)); + let preempted = outputs.iter().any(|o| { + matches!( + o, + DecodeOutput::Finished { request_id, reason: FinishReason::Preempted, .. } + if *request_id == SEQ + ) + }); + let unchanged = table_of(&be, SEQ) == before; + ( + !token && preempted && unchanged, + format!( + "batched decode outputs: token_emitted={token}, preempted={preempted}, \ + table_unchanged={unchanged}" + ), + ) + } + Err(e) if e.starts_with(PREFIX) => (true, format!("batched decode loud Err: {e}")), + Err(e) => (false, format!("batched decode Err lacks the prefix: {e}")), + } +} + +async fn check_decode() -> Check { + let (single_ok, single_msg) = decode_single_token_leg(); + let (batched_ok, batched_msg) = decode_batched_leg().await; + Check { + name: "x_decode_exhaustion_is_loud", + marker: M_SILENT, + pass: single_ok && batched_ok, + applicable: true, + message: format!("{single_msg}; {batched_msg}"), + } +} + +/// After a failed append, freeing the other sequence and repeating the very +/// same append must succeed with the exact K/V of the one-shot control. +fn check_recovers() -> Check { + let mut notes = Vec::new(); + let mut applied = false; + let mut pass = true; + for sc in scenarios() { + let need = sc.need(); + let mut be = setup(SMALL_POOL, sc.shared_tail, Some(need - 1)); + if append(&mut be, sc.len).is_ok() { + notes.push(format!( + "{}: first append did not fail, retry not applicable", + sc.label() + )); + continue; + } + applied = true; + be.kv_manager + .as_ref() + .expect("kv manager") + .write() + .free_sequence(FILLER) + .expect("free filler"); + let (n, ok) = append_matches_control(&mut be, sc, "retry"); + notes.extend(n); + pass &= ok; + if sc.shared_tail && !witness_untouched(&be) { + pass = false; + notes.push(format!( + "{}: witness K/V changed across the failed and retried append", + sc.label() + )); + } + } + Check { + name: "x_recovers_after_free", + marker: M_RETRY, + pass, + applicable: applied, + message: notes.join("; "), + } +} + +fn write_receipt(checks: &[Check], finished: bool) { + let Ok(path) = std::env::var("AIEN_I25_RECEIPT") else { + return; + }; + let all_pass = finished && checks.iter().all(|c| c.pass); + let receipt = serde_json::json!({ + "test": "prefill_pool_exhaustion", + "block_size": BLOCK_SIZE, + "prompt_len": PROMPT_LEN, + "append_lens": APPEND_LENS, + "small_pool_blocks": SMALL_POOL, + "finished": finished, + "pass": all_pass, + "checks": checks + .iter() + .map(|c| serde_json::json!({ + "name": c.name, + "marker": c.marker, + "pass": c.pass, + "applicable": c.applicable, + "message": c.message, + })) + .collect::<Vec<_>>(), + }); + if let Some(parent) = std::path::Path::new(&path).parent() { + let _ = std::fs::create_dir_all(parent); + } + std::fs::write( + &path, + serde_json::to_string_pretty(&receipt).expect("receipt json"), + ) + .expect("write receipt"); +} + +#[tokio::test] +async fn prefill_pool_exhaustion_is_loud_atomic_and_retryable() { + // A not-finished receipt exists from the start so a crash still leaves + // evidence (pass is false until every check ran). + write_receipt(&[], false); + + let checks = [ + check_loud(), + check_atomic(), + check_clean_path(), + check_exact_fit(), + check_decode().await, + check_recovers(), + ]; + write_receipt(&checks, true); + + // Print every check's outcome before any assert fires, so every marker + // that applies is in the log. + for c in &checks { + if c.pass { + println!( + "PREFILL_I25 check {} PASS (applicable={}): {}", + c.name, c.applicable, c.message + ); + } else { + println!( + "PREFILL_I25 check {} FAIL: {}: {}", + c.name, c.marker, c.message + ); + } + } + for c in &checks { + assert!(c.pass, "{}: {}", c.marker, c.message); + } +}