diff --git a/crates/aien-inference-abi/src/qwen38_omega.rs b/crates/aien-inference-abi/src/qwen38_omega.rs index 28ee17d8..a5b7a835 100644 --- a/crates/aien-inference-abi/src/qwen38_omega.rs +++ b/crates/aien-inference-abi/src/qwen38_omega.rs @@ -218,6 +218,48 @@ impl Qwen38Snapshot { ); (na != nb || self.pos != o.pos).then_some(na.min(nb)) } + + /// Host bytes the copy holds. + pub fn bytes(&self) -> usize { + (self.tails.len() + self.states.len()) * 4 + } + + /// The copy as bytes (the shared prompt cache's files): position, the two lengths (u64 LE), + /// then every f32's bits LE. [`Self::from_bytes`] gives back the identical copy. + pub fn to_bytes(&self) -> Vec { + let mut b = Vec::with_capacity(24 + self.bytes()); + for n in [self.pos, self.tails.len(), self.states.len()] { + b.extend_from_slice(&(n as u64).to_le_bytes()); + } + for v in self.tails.iter().chain(&self.states) { + b.extend_from_slice(&v.to_bits().to_le_bytes()); + } + b + } + + pub fn from_bytes(b: &[u8]) -> Result { + let word = |i: usize| -> Result { + b.get(i * 8..i * 8 + 8) + .map(|w| u64::from_le_bytes(w.try_into().expect("8 bytes")) as usize) + .ok_or_else(|| "snapshot bytes: short header".to_string()) + }; + let (pos, nt, ns) = (word(0)?, word(1)?, word(2)?); + let body = &b[24..]; + if nt.checked_add(ns).and_then(|n| n.checked_mul(4)) != Some(body.len()) { + return Err(format!( + "snapshot bytes: {} body bytes for {nt} + {ns} floats", + body.len() + )); + } + let mut f = body + .chunks_exact(4) + .map(|c| f32::from_bits(u32::from_le_bytes(c.try_into().expect("4 bytes")))); + Ok(Self { + pos, + tails: f.by_ref().take(nt).collect(), + states: f.collect(), + }) + } } /// Memory the whole model needs with a KV cache of `max_pos` positions and prefill buffers for diff --git a/crates/aien-inference-abi/src/qwen38_omega/rows.rs b/crates/aien-inference-abi/src/qwen38_omega/rows.rs index 3ce90561..7028c1d1 100644 --- a/crates/aien-inference-abi/src/qwen38_omega/rows.rs +++ b/crates/aien-inference-abi/src/qwen38_omega/rows.rs @@ -350,6 +350,73 @@ impl Qwen38Omega { Ok(()) } + /// bf16 values one position of a row's KV cache holds (every attention layer, K and V). + pub fn row_kv_values(&self) -> usize { + self.rows + .first() + .and_then(|r| r.attn.as_ref()) + .map_or(0, Attn256Cache::pos_values) + } + + /// Copies row `r`'s attention K/V at positions `from .. from + count` into `out` (host + /// memory). With [`Self::row_snapshot`] (DeltaNet state and position) this is the whole + /// conversation state: the shared prompt cache (sc L375) restores both into any row. + pub fn row_kv_read( + &mut self, + r: usize, + from: usize, + count: usize, + out: &mut Vec, + ) -> Result<(), String> { + let n = self.rows.len(); + let row = self + .rows + .get_mut(r) + .ok_or_else(|| format!("row {r} of {n}"))?; + match row.attn.as_mut() { + Some(a) => a.read_rows(from, count, out).map_err(gpu("row kv read")), + None => { + out.clear(); + Ok(()) + } + } + } + + /// Writes [`Self::row_kv_read`]'s copy back into row `r` at positions `from .. from + count`. + pub fn row_kv_write( + &mut self, + r: usize, + from: usize, + count: usize, + data: &[u16], + ) -> Result<(), String> { + let n = self.rows.len(); + let row = self + .rows + .get_mut(r) + .ok_or_else(|| format!("row {r} of {n}"))?; + match row.attn.as_mut() { + Some(a) => a.write_rows(from, count, data).map_err(gpu("row kv write")), + None if data.is_empty() => Ok(()), + None => Err("row_kv_write: this model has no attention cache".into()), + } + } + + /// Moves row `r`'s next position (the prompt cache's position mutant only: the state is not + /// touched). + pub fn row_set_pos(&mut self, r: usize, pos: usize) -> Result<(), String> { + let n = self.rows.len(); + let row = self + .rows + .get_mut(r) + .ok_or_else(|| format!("row {r} of {n}"))?; + if pos > row.max_pos { + return Err(format!("row_set_pos: {pos} past the row's {}", row.max_pos)); + } + row.pos = pos; + Ok(()) + } + /// Tokens row `r` holds (its next position) and the most it holds. pub fn row_pos(&self, r: usize) -> Option<(usize, usize)> { self.rows.get(r).map(|row| (row.pos, row.max_pos)) diff --git a/crates/aien-omega-q38/src/lib.rs b/crates/aien-omega-q38/src/lib.rs index 8c3dd0ad..a407d1b1 100644 --- a/crates/aien-omega-q38/src/lib.rs +++ b/crates/aien-omega-q38/src/lib.rs @@ -313,6 +313,23 @@ mod ffi { /// compiled default 256). Experiments only: the multi-row launch refuses any value but 256. pub fn omega_gpu_decode_attn256_set_per_split(per_split: u32); pub fn omega_gpu_decode_attn_last_error() -> *const c_char; + pub fn omega_gpu_decode_attn256_cache_write( + c: *mut OmegaGpuDecodeAttn256Cache, + layer: u32, + kv_head: u32, + pos: u32, + count: u32, + k: *const u16, + v: *const u16, + ) -> i32; + pub fn omega_gpu_decode_attn256_cache_read( + c: *mut OmegaGpuDecodeAttn256Cache, + layer: u32, + kv_head: u32, + pos: u32, + k: *mut u16, + v: *mut u16, + ) -> i32; pub fn omega_gpu_q38_graph_create( cfg: *const GraphConfig, @@ -821,6 +838,8 @@ pub struct Attn256Cache { layers: usize, max_pos: usize, rotary: usize, + /// KV heads per layer (the 27B 4, the 35B 2). + kv_heads: usize, } // SAFETY: an owning handle to device buffers; moved between threads, never shared unlocked. @@ -904,6 +923,7 @@ impl Attn256Cache { layers, max_pos, rotary, + kv_heads: if kv_heads == 0 { 4 } else { kv_heads }, }) } #[cfg(not(has_omega_q38))] @@ -921,6 +941,112 @@ impl Attn256Cache { self.max_pos } + /// bf16 values one position holds across every layer: K and V, `kv_heads` x 256 each. + pub fn pos_values(&self) -> usize { + self.layers * self.kv_heads * 2 * HEAD_DIM + } + + /// Copies positions `pos .. pos + count` of every layer into `out` (bf16 bits, resized to + /// `count * pos_values()`), laid out `[layer][kv_head][K count x 256 | V count x 256]`, the + /// order [`Self::write_rows`] takes back. Plain host reads of the cache (omega + /// `omega_gpu_decode_attn256_cache_read`, one position per call): no chip launch. + pub fn read_rows( + &mut self, + pos: usize, + count: usize, + out: &mut Vec, + ) -> Result<(), OmegaGpuError> { + if pos + count > self.max_pos { + return Err(bad(format!( + "attn256 read_rows: {pos} + {count} past max_pos {}", + self.max_pos + ))); + } + out.resize(count * self.pos_values(), 0); + #[cfg(has_omega_q38)] + { + let n = count * HEAD_DIM; + for (lh, block) in out.chunks_exact_mut(2 * n).enumerate() { + let (layer, head) = (lh / self.kv_heads, lh % self.kv_heads); + let (k, v) = block.split_at_mut(n); + for i in 0..count { + let s = i * HEAD_DIM..(i + 1) * HEAD_DIM; + // SAFETY: ptr is live; k and v slices hold 256 bf16 each. + let rc = unsafe { + ffi::omega_gpu_decode_attn256_cache_read( + self.ptr, + layer as u32, + head as u32, + (pos + i) as u32, + k[s.clone()].as_mut_ptr(), + v[s].as_mut_ptr(), + ) + }; + if rc != 0 { + // SAFETY: no arguments. + let detail = c_text(unsafe { ffi::omega_gpu_decode_attn_last_error() }); + return Err(rc_err("attn256 cache_read", rc, detail)); + } + } + } + Ok(()) + } + #[cfg(not(has_omega_q38))] + { + Err(OmegaGpuError::Unavailable) + } + } + + /// Writes [`Self::read_rows`]'s bytes back at positions `pos .. pos + count` (omega + /// `omega_gpu_decode_attn256_cache_write`, one range per layer and KV head). + pub fn write_rows( + &mut self, + pos: usize, + count: usize, + data: &[u16], + ) -> Result<(), OmegaGpuError> { + if pos + count > self.max_pos { + return Err(bad(format!( + "attn256 write_rows: {pos} + {count} past max_pos {}", + self.max_pos + ))); + } + check_len("attn256 write_rows", count * self.pos_values(), data.len())?; + if count == 0 { + return Ok(()); + } + #[cfg(has_omega_q38)] + { + let n = count * HEAD_DIM; + for (lh, block) in data.chunks_exact(2 * n).enumerate() { + let (layer, head) = (lh / self.kv_heads, lh % self.kv_heads); + let (k, v) = block.split_at(n); + // SAFETY: ptr is live; k and v hold count x 256 bf16 each. + let rc = unsafe { + ffi::omega_gpu_decode_attn256_cache_write( + self.ptr, + layer as u32, + head as u32, + pos as u32, + count as u32, + k.as_ptr(), + v.as_ptr(), + ) + }; + if rc != 0 { + // SAFETY: no arguments. + let detail = c_text(unsafe { ffi::omega_gpu_decode_attn_last_error() }); + return Err(rc_err("attn256 cache_write", rc, detail)); + } + } + Ok(()) + } + #[cfg(not(has_omega_q38))] + { + Err(OmegaGpuError::Unavailable) + } + } + /// The C handle (`OmegaGpuDecodeAttn256Cache *`) for [`GraphConfig::attn`]; null in the /// stub. Stays owned by `self`. pub fn as_raw(&self) -> *mut c_void { diff --git a/crates/aien-serve-http/src/engine.rs b/crates/aien-serve-http/src/engine.rs index 2a5abade..5f69390e 100644 --- a/crates/aien-serve-http/src/engine.rs +++ b/crates/aien-serve-http/src/engine.rs @@ -116,6 +116,19 @@ pub trait Engine: Send + Sync { params: &GenerateParams, on_token: &mut dyn FnMut(u32) -> bool, ) -> Result; + /// [`Self::generate_with_test`] with token positions of `prompt` worth a prompt cache + /// checkpoint (sc L375: the tool boundaries). Engines without a prompt cache ignore them. + fn generate_marked( + &self, + prompt: &[u32], + marks: &[usize], + params: &GenerateParams, + test: &TestSwitches, + on_token: &mut dyn FnMut(u32) -> bool, + ) -> Result { + let _ = marks; + self.generate_with_test(prompt, params, test, on_token) + } /// Persistent KV status and counters for `/health` (sc#505). `None` (the default, and the /// omega door with `AIEN_KV_STORE_DIR` unset) leaves `/health` exactly as it was. fn persistence_status(&self) -> Option { @@ -205,8 +218,12 @@ pub struct TestSwitches { pub row_swap: Option, /// L369 chunked prompt reading: tokens per chunk for this prompt (`0` = token by token). pub prefill_chunk: Option, - /// L375 shared prompt cache: may this request read from or write to the pool. + /// L375 shared prompt cache: `false` reads this prompt cold (no pool, no row reuse, nothing + /// saved to the pool), the reference the cache must match. pub prefix_pool: Option, + /// L375 negative control: a restore from the pool lands one position early for this row (it + /// must go red); the row saves nothing and starts its next conversation cold. + pub prefix_mutant: Option, /// L313 bf16 DeltaNet state: load-only on the chip (the train starts a second server /// for it); listed so a case can name it and the server can say so. pub state_bf16: Option, @@ -214,13 +231,14 @@ pub struct TestSwitches { impl TestSwitches { /// Every switch name, in the request's spelling. - pub const NAMES: [&'static str; 7] = [ + pub const NAMES: [&'static str; 8] = [ "stroke", "exact_head", "mutant", "row_swap", "prefill_chunk", "prefix_pool", + "prefix_mutant", "state_bf16", ]; @@ -256,6 +274,7 @@ impl TestSwitches { "row_swap" => t.row_swap = Some(uint()?), "prefill_chunk" => t.prefill_chunk = Some(uint()? as usize), "prefix_pool" => t.prefix_pool = Some(bool_()?), + "prefix_mutant" => t.prefix_mutant = Some(bool_()?), "state_bf16" => t.state_bf16 = Some(bool_()?), other => return Err(format!("aien_test.{other}: no such switch")), } @@ -284,6 +303,9 @@ impl TestSwitches { if self.prefix_pool.is_some() { n.push("prefix_pool"); } + if self.prefix_mutant.is_some() { + n.push("prefix_mutant"); + } if self.state_bf16.is_some() { n.push("state_bf16"); } @@ -299,6 +321,8 @@ impl TestSwitches { #[derive(Debug, Clone)] pub struct GroupJob { pub prompt: Vec, + /// Prompt cache checkpoint hints (tool boundaries; sc L375, DRA-86); empty: none. + pub marks: Vec, pub params: GenerateParams, /// Set by the caller to stop this job even before it emits a token (a reader still taking in /// its part when the client leaves). `None`: only `on_token` returning `false` stops it. diff --git a/crates/aien-serve-http/src/lib.rs b/crates/aien-serve-http/src/lib.rs index d5787984..01ba9eab 100644 --- a/crates/aien-serve-http/src/lib.rs +++ b/crates/aien-serve-http/src/lib.rs @@ -26,12 +26,14 @@ pub mod engine; pub mod kv_persist; pub mod omega_engine; pub mod openai; +pub mod q36_prefix; pub mod qwen36_batch; pub mod qwen38_engine; pub mod readers; pub mod sampling; pub mod server; pub mod text; +pub mod tool_cache; pub mod tools; pub use codec::{ByteCodec, Codec, HfCodec}; diff --git a/crates/aien-serve-http/src/q36_prefix.rs b/crates/aien-serve-http/src/q36_prefix.rs new file mode 100644 index 00000000..d9e75b15 --- /dev/null +++ b/crates/aien-serve-http/src/q36_prefix.rs @@ -0,0 +1,960 @@ +//! The 35B door's shared prompt cache (sc L375, Drake 2026-10-21: "I cannot be waiting 6.5 +//! minutes to talk to Hermes"). +//! +//! Every new Hermes chat starts with the same ~11k tokens of tool descriptions and ~6k of system +//! text. The batch door's per-row reuse only continues the same conversation on the same row; +//! this pool is shared by every row. While a row reads a prompt, the door saves the row's whole +//! state at checkpoints (every [`EVERY`] tokens, at the end of the first turn and at the last +//! turn header): the DeltaNet tails and states, the position, and the attention K/V written since +//! the previous checkpoint of the same prefix. The checkpoints form a tree: a node holds the K/V +//! of positions `kv_from .. pos` and its parent holds the rest, so a shared prefix's K/V is held +//! once. A joining prompt restores the deepest node whose tokens it starts with (compared token +//! for token, never by hash alone) and reads only the tail. +//! +//! Exact by construction: the restored row holds the bytes the reading row held at that +//! position, and every later token runs the same kernels in the same order. +//! +//! Memory: LRU by bytes over the leaves (a parent outlives its children), budget +//! `AIEN_Q36_PREFIX_POOL_GB` (default 16; 0 turns the pool off). The pool runs only with +//! `AIEN_Q36_PREFIX=1` (DRA-86: default off). +//! +//! Disk (coordinator 12:07Z, Drake: "11,000 words can stay where they need to stay"): with +//! `AIEN_Q36_PREFIX_DIR` set (a private directory, `AIEN_KV_STORE_KEY` required) every node is +//! also written as one sealed file (AES-256-GCM, aien-kv-store's `SealKey`; the header binds the +//! namespace, the token digest, the parent and the lengths) on a writer thread, and every stored +//! node is loaded back at start, before the door takes requests. The namespace binds the +//! checkpoint digest, the linked `libomega_gpu.a` sha256, the state shape, [`NUMERICS_EPOCH`] +//! and every `AIEN_Q36_*` / `AIEN_OMEGA_*` switch except the pool's own: a file made under +//! anything else is never opened. Any problem with a file ends in discarding it (a cold read). +use std::collections::HashMap; +use std::io::Write; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::path::{Path, PathBuf}; +use std::sync::{mpsc, Arc}; +use std::time::Instant; + +use aien_kv_store::record::{HEADER_REGION_LEN, SEAL_SLOT_OFFSET}; +use aien_kv_store::seal::SealKey; +use sha2::{Digest, Sha256}; + +/// Tokens between two checkpoints of one prompt (`AIEN_Q36_PREFIX_EVERY`). +pub const EVERY: usize = 2048; +/// Default pool budget in GiB (`AIEN_Q36_PREFIX_POOL_GB`; DRA-86 G4: 16 GiB). +pub const POOL_GB: f64 = 16.0; +/// The switch: the shared prompt cache runs only with `AIEN_Q36_PREFIX=1` (default off). +pub const SWITCH_ENV: &str = "AIEN_Q36_PREFIX"; +/// Bump when an sc change moves a state byte for the same lib and weights (stored files made +/// before it are then never opened). +pub const NUMERICS_EPOCH: u32 = 1; +/// The position mutant (`AIEN_Q36_PREFIX_MUTANT=1`): a restored row continues one position +/// early. The gate must go red with it. +pub const MUTANT_ENV: &str = "AIEN_Q36_PREFIX_MUTANT"; + +const MAGIC: &[u8; 16] = b"AIEN-Q36-PREFIX1"; +const FILE_EXT: &str = "q36p"; + +/// What a row's state copy must offer the pool. +pub trait PoolSnap: Send + Sync + 'static { + fn host_bytes(&self) -> usize; + fn to_bytes(&self) -> Vec; + /// `to_bytes().len()` without making the bytes. + fn bytes_len(&self) -> usize { + self.to_bytes().len() + } + fn from_bytes(b: &[u8]) -> Result + where + Self: Sized; + /// The position the state continues at, when the state records it (a restore refuses a + /// state whose position is not the node's token count). + fn pos(&self) -> Option { + None + } +} + +impl PoolSnap for aien_inference_abi::qwen38_omega::Qwen38Snapshot { + fn host_bytes(&self) -> usize { + self.bytes() + } + fn to_bytes(&self) -> Vec { + Self::to_bytes(self) + } + fn bytes_len(&self) -> usize { + 24 + self.bytes() + } + fn from_bytes(b: &[u8]) -> Result { + Self::from_bytes(b) + } + fn pos(&self) -> Option { + Some(self.pos) + } +} + +/// The pool's settings from the environment. +#[derive(Debug, Clone)] +pub struct PoolConfig { + pub budget: usize, + pub every: usize, + pub dir: Option, + pub mutant: bool, +} + +impl PoolConfig { + pub fn from_env() -> Result { + Self::from_lookup(|k| std::env::var(k).ok()) + } + + pub fn from_lookup(get: impl Fn(&str) -> Option) -> Result { + let on = match get(SWITCH_ENV).as_deref() { + None | Some("") | Some("0") => false, + Some("1") => true, + Some(v) => return Err(format!("{SWITCH_ENV}={v}: 0 or 1")), + }; + let gb = match get("AIEN_Q36_PREFIX_POOL_GB") { + Some(v) => v + .parse::() + .ok() + .filter(|g| g.is_finite() && *g >= 0.0) + .ok_or(format!("AIEN_Q36_PREFIX_POOL_GB={v}: a number of GiB >= 0"))?, + None => POOL_GB, + }; + let every = match get("AIEN_Q36_PREFIX_EVERY") { + Some(v) => v + .parse::() + .ok() + .filter(|&n| n >= 1) + .ok_or(format!("AIEN_Q36_PREFIX_EVERY={v}: a whole number >= 1"))?, + None => EVERY, + }; + Ok(Self { + budget: if on { + (gb * (1u64 << 30) as f64) as usize + } else { + 0 + }, + every, + dir: get("AIEN_Q36_PREFIX_DIR") + .filter(|s| !s.is_empty()) + .map(PathBuf::from), + mutant: get(MUTANT_ENV).as_deref() == Some("1"), + }) + } +} + +/// One checkpoint: the row's state after `tokens`. +pub struct Node { + parent: Option, + tokens: Vec, + /// K/V of positions `kv_from .. tokens.len()` (the parent holds the ones before). + kv_from: usize, + kv: Arc>, + snap: Arc, + digest: [u8; 32], + /// The pool's tag (model, chip library, state shape, numeric switches) when it was saved. + tag: [u8; 32], + children: usize, + last_used: u64, +} + +impl Node { + fn bytes(&self) -> usize { + self.kv.len() * 2 + self.snap.host_bytes() + self.tokens.len() * 4 + } +} + +/// What a restore copies into a row: the K/V pieces root first, then the deepest state. +pub struct Restore<'a, S> { + pub pos: usize, + pub kv: Vec<(usize, &'a [u16])>, + pub snap: &'a S, + /// The bytes this conversation's chain holds resident in the pool (every node root first). + pub resident: usize, +} + +/// Why a restore was refused (the row then reads the prompt cold; nothing was written to it). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Refused { + /// The node was evicted. + Gone, + /// A node of the chain was saved under another model, chip library or switch tag. + Stale { pos: usize }, + /// The node's tokens (or their digest) are not the prompt's. + TokenMismatch { pos: usize }, + /// A K/V piece does not start where the one before ended. + KvGap { kv_from: usize, expected: usize }, + /// A K/V piece holds another number of values than its span. + KvLength { pos: usize, values: usize, expected: usize }, + /// The state continues at another position than the node's token count. + StateLength { state: usize, pos: usize }, +} + +impl std::fmt::Display for Refused { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Gone => write!(f, "node gone"), + Self::Stale { pos } => write!(f, "stale node at {pos} (another model/lib tag)"), + Self::TokenMismatch { pos } => write!(f, "node at {pos} holds other tokens"), + Self::KvGap { kv_from, expected } => { + write!(f, "K/V gap: piece starts at {kv_from}, not {expected}") + } + Self::KvLength { + pos, + values, + expected, + } => write!(f, "K/V of node at {pos}: {values} values, not {expected}"), + Self::StateLength { state, pos } => { + write!(f, "state continues at {state}, node holds {pos} tokens") + } + } + } +} + +#[derive(Debug, Default, Clone, Copy)] +pub struct PoolCounters { + pub nodes: usize, + pub bytes: usize, + pub hits: u64, + pub misses: u64, + pub saved: u64, + pub evicted: u64, + pub loaded: u64, + pub discarded: u64, + pub refused: u64, +} + +/// The shared pool (owned by the scheduler thread). +pub struct PrefixPool { + nodes: HashMap>, + next_id: u64, + budget: usize, + bytes: usize, + clock: u64, + every: usize, + mutant: bool, + store: Option, + counters: PoolCounters, + tag: [u8; 32], + /// Test-only: restore without the refusal checks (the unchecked base, as a negative control). + unchecked: bool, +} + +fn digest_of(tokens: &[u32]) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"AIEN-Q36-PREFIX-TOKENS-V1\0"); + for t in tokens { + h.update(t.to_le_bytes()); + } + h.finalize().into() +} + +fn hex(b: &[u8]) -> String { + b.iter().map(|x| format!("{x:02x}")).collect() +} + +impl PrefixPool { + pub fn new(cfg: &PoolConfig) -> Self { + Self { + nodes: HashMap::new(), + next_id: 1, + budget: cfg.budget, + bytes: 0, + clock: 0, + every: cfg.every, + mutant: cfg.mutant, + store: None, + counters: PoolCounters::default(), + tag: [0; 32], + unchecked: false, + } + } + + /// Binds the pool to `tag` (the model, chip library, state shape and numeric switches): a + /// node saved under another tag is refused at restore and dropped. + pub fn bind_tag(&mut self, tag: [u8; 32]) { + self.tag = tag; + } + + #[cfg(test)] + pub(crate) fn set_unchecked(&mut self, on: bool) { + self.unchecked = on; + } + + /// The bytes the chain ending at the node for `tokens` holds resident (nodes, bytes): one + /// conversation's share of the pool. + pub fn resident(&self, tokens: &[u32]) -> Option<(usize, usize)> { + let (&id, _) = self.nodes.iter().find(|(_, n)| n.tokens[..] == *tokens)?; + let chain = self.chain(id)?; + Some(( + chain.len(), + chain.iter().map(|i| self.nodes[i].bytes()).sum(), + )) + } + + /// Node `id` and its ancestors, deepest first. + fn chain(&self, id: u64) -> Option> { + let mut chain = Vec::new(); + let mut at = Some(id); + while let Some(i) = at { + chain.push(i); + at = self.nodes.get(&i)?.parent; + } + Some(chain) + } + + /// Why node `id` must not be restored as the state after `tokens` with `kv_values` K/V + /// values per position, if it must not. + fn check(&self, chain: &[u64], tokens: &[u32], kv_values: usize) -> Result<(), Refused> { + let deepest = &self.nodes[&chain[0]]; + if deepest.tokens[..] != *tokens || deepest.digest != digest_of(tokens) { + return Err(Refused::TokenMismatch { + pos: deepest.tokens.len(), + }); + } + let mut expected = 0; + for i in chain.iter().rev() { + let n = &self.nodes[i]; + let pos = n.tokens.len(); + if n.tag != self.tag { + return Err(Refused::Stale { pos }); + } + if !tokens.starts_with(&n.tokens) { + return Err(Refused::TokenMismatch { pos }); + } + if n.kv_from != expected || n.kv_from > pos { + return Err(Refused::KvGap { + kv_from: n.kv_from, + expected, + }); + } + let want = (pos - n.kv_from) * kv_values; + if n.kv.len() != want { + return Err(Refused::KvLength { + pos, + values: n.kv.len(), + expected: want, + }); + } + expected = pos; + } + match deepest.snap.pos() { + Some(state) if state != tokens.len() => Err(Refused::StateLength { + state, + pos: tokens.len(), + }), + _ => Ok(()), + } + } + + pub fn budget(&self) -> usize { + self.budget + } + + pub fn on(&self) -> bool { + self.budget > 0 + } + + pub fn mutant(&self) -> bool { + self.mutant + } + + pub fn every(&self) -> usize { + self.every + } + + pub fn counters(&self) -> PoolCounters { + PoolCounters { + nodes: self.nodes.len(), + bytes: self.bytes, + ..self.counters + } + } + + /// The deepest node whose tokens `prompt` starts with, holding at most `max` tokens. + pub fn longest(&self, prompt: &[u32], max: usize) -> Option<(u64, usize)> { + self.nodes + .iter() + .filter(|(_, n)| n.tokens.len() <= max && prompt.starts_with(&n.tokens)) + .max_by_key(|(_, n)| n.tokens.len()) + .map(|(&id, n)| (id, n.tokens.len())) + } + + /// Where `prompt` leaves the pool: the longest run of leading tokens it shares with a node + /// that it does not wholly continue (`None` when it shares none, or continues every node it + /// touches). + pub fn divergence(&self, prompt: &[u32]) -> Option { + self.nodes + .values() + .map(|n| { + n.tokens + .iter() + .zip(prompt) + .take_while(|(a, b)| a == b) + .count() + }) + .zip(self.nodes.values()) + .filter(|&(k, n)| k > 0 && k < n.tokens.len()) + .map(|(k, _)| k) + .max() + } + + /// Counts a join's lookup (`hit`: the pool gave the longest reuse). + pub fn note_lookup(&mut self, hit: bool) { + if hit { + self.counters.hits += 1; + } else { + self.counters.misses += 1; + } + } + + /// The copies a restore of node `id` as the state after `tokens` (with `kv_values` K/V values + /// per position) writes, and marks the chain used. Refused, nothing is to be written: a + /// stale chain is dropped with every other node of another tag, a broken leaf is dropped. + pub fn restore( + &mut self, + id: u64, + tokens: &[u32], + kv_values: usize, + ) -> Result, Refused> { + let chain = self.chain(id).ok_or(Refused::Gone)?; + if !self.unchecked { + if let Err(e) = self.check(&chain, tokens, kv_values) { + self.counters.refused += 1; + if matches!(e, Refused::Stale { .. }) { + let tag = self.tag; + while let Some(v) = self + .nodes + .iter() + .find(|(_, n)| n.tag != tag && n.children == 0) + .map(|(&i, _)| i) + { + self.remove(v); + } + } else if self.nodes[&id].children == 0 { + self.remove(id); + } + return Err(e); + } + } + self.clock += 1; + for i in &chain { + self.nodes.get_mut(i).expect("chain node").last_used = self.clock; + } + let deepest = &self.nodes[&id]; + Ok(Restore { + pos: deepest.tokens.len(), + kv: chain + .iter() + .rev() + .map(|i| { + let n = &self.nodes[i]; + (n.kv_from, &n.kv[..]) + }) + .collect(), + snap: &deepest.snap, + resident: chain.iter().map(|i| self.nodes[i].bytes()).sum(), + }) + } + + /// Whether `tokens` is already a node (and marks it used). + pub fn touch(&mut self, tokens: &[u32]) -> bool { + self.clock += 1; + let c = self.clock; + match self.nodes.values_mut().find(|n| n.tokens[..] == *tokens) { + Some(n) => { + n.last_used = c; + true + } + None => false, + } + } + + /// Where a new node for `tokens` starts its K/V: its parent (the deepest proper prefix). + pub fn parent_for(&self, tokens: &[u32]) -> Option<(u64, usize)> { + self.longest(tokens, tokens.len().saturating_sub(1)) + } + + /// Adds the state after `tokens` (K/V from `kv_from`, the parent's length), then evicts to + /// the budget. Returns false when the node alone does not fit. + pub fn insert(&mut self, tokens: Vec, parent: Option, kv: Vec, snap: S) -> bool { + let kv_from = parent.map_or(0, |p| self.nodes[&p].tokens.len()); + let id = self.add(tokens, parent, kv_from, Arc::new(kv), Arc::new(snap)); + if let Some(st) = &self.store { + let n = &self.nodes[&id]; + let parent_digest = parent.map(|p| self.nodes[&p].digest); + st.write(n, parent_digest); + } + self.counters.saved += 1; + self.evict(id); + self.nodes.contains_key(&id) + } + + fn add( + &mut self, + tokens: Vec, + parent: Option, + kv_from: usize, + kv: Arc>, + snap: Arc, + ) -> u64 { + self.clock += 1; + let id = self.next_id; + self.next_id += 1; + if let Some(p) = parent { + self.nodes.get_mut(&p).expect("parent node").children += 1; + } + let n = Node { + parent, + digest: digest_of(&tokens), + tokens, + kv_from, + kv, + snap, + children: 0, + last_used: self.clock, + tag: self.tag, + }; + self.bytes += n.bytes(); + self.nodes.insert(id, n); + id + } + + /// Drops least recently used leaves until the pool fits; `fresh` goes last. + fn evict(&mut self, fresh: u64) { + while self.bytes > self.budget { + let victim = self + .nodes + .iter() + .filter(|(&i, n)| n.children == 0 && i != fresh) + .min_by_key(|(_, n)| n.last_used) + .map(|(&i, _)| i) + .or_else(|| self.nodes.contains_key(&fresh).then_some(fresh)); + let Some(v) = victim else { break }; + self.remove(v); + self.counters.evicted += 1; + } + } + + /// Drops leaf `v` (and its stored file). + fn remove(&mut self, v: u64) { + let n = self.nodes.remove(&v).expect("victim"); + self.bytes -= n.bytes(); + if let Some(p) = n.parent { + if let Some(pn) = self.nodes.get_mut(&p) { + pn.children -= 1; + } + } + if let Some(st) = &self.store { + st.delete(&n.digest, n.tokens.len()); + } + } + + /// Opens the sealed store at `dir` and loads every node it holds (parents first) that fits + /// the budget; later nodes are written there too. `shape` checks a loaded state against + /// this model (bytes per K/V position, state bytes). + pub fn open_store( + &mut self, + dir: &Path, + key: SealKey, + namespace: [u8; 32], + kv_values: usize, + snap_ok: impl Fn(&S) -> bool, + ) -> Result<(), String> { + open_private_dir(dir)?; + // The seal budget's per-store usage counts (aien-kv-store `SealKey::seal_file`). + open_private_dir(&dir.join(aien_kv_store::seal::USAGE_DIR_NAME))?; + let t0 = Instant::now(); + let mut found: Vec = Vec::new(); + let rd = std::fs::read_dir(dir).map_err(|e| format!("{}: {e}", dir.display()))?; + for ent in rd.flatten() { + let p = ent.path(); + if p.extension().and_then(|e| e.to_str()) != Some(FILE_EXT) { + continue; + } + match read_node(&p, &key, &namespace, kv_values) { + Ok(l) => found.push(l), + Err(e) => { + eprintln!( + "aien-serve-http: q36 prefix: discarding {}: {e}", + p.display() + ); + let _ = std::fs::remove_file(&p); + self.counters.discarded += 1; + } + } + } + found.sort_by_key(|l| l.tokens.len()); + let mut by_digest: HashMap<[u8; 32], u64> = HashMap::new(); + for l in found { + let parent = match l.parent { + None if l.kv_from == 0 => Ok(None), + None => Err("no parent but K/V starts past 0".to_string()), + Some(pd) => match by_digest.get(&pd) { + Some(&p) + if self.nodes[&p].tokens.len() == l.kv_from + && l.tokens.starts_with(&self.nodes[&p].tokens) => + { + Ok(Some(p)) + } + Some(_) => Err("parent does not match".into()), + None => Err("parent not loaded".into()), + }, + }; + let snap = parent.and_then(|p| { + S::from_bytes(&l.snap) + .and_then(|s| { + if snap_ok(&s) { + Ok(s) + } else { + Err("state of another shape".into()) + } + }) + .map(|s| (p, s)) + }); + let fits = + self.bytes + l.tokens.len() * 4 + l.kv.len() * 2 + l.snap.len() <= self.budget; + match snap { + Ok((parent, snap)) if fits => { + let d = digest_of(&l.tokens); + let id = self.add(l.tokens, parent, l.kv_from, Arc::new(l.kv), Arc::new(snap)); + by_digest.insert(d, id); + self.counters.loaded += 1; + } + r => { + let why = match r { + Err(e) => e, + Ok(_) => "over the pool budget".into(), + }; + eprintln!( + "aien-serve-http: q36 prefix: discarding {}: {why}", + l.path.display() + ); + let _ = std::fs::remove_file(&l.path); + self.counters.discarded += 1; + } + } + } + eprintln!( + "aien-serve-http: q36 prefix: store {} open: {} nodes loaded ({:.1} MiB), {} discarded, in {:.1} s", + dir.display(), + self.counters.loaded, + self.bytes as f64 / (1u64 << 20) as f64, + self.counters.discarded, + t0.elapsed().as_secs_f64() + ); + self.store = Some(Store::start(dir.to_path_buf(), Arc::new(key), namespace)); + Ok(()) + } + + /// Waits for every queued write (tests and shutdown). + pub fn flush(&self) { + if let Some(st) = &self.store { + st.flush(); + } + } +} + +/// The namespace a stored node must carry: the weights, the linked chip library, the state shape, +/// [`NUMERICS_EPOCH`] and the run switches that can move a state byte. +pub fn namespace( + checkpoint: &[u8; 32], + lib_sha256: &str, + kv_values: usize, + snap_bytes: usize, + env: &[(String, String)], +) -> [u8; 32] { + let mut h = Sha256::new(); + h.update(b"AIEN-Q36-PREFIX-NS-V1\0"); + h.update(checkpoint); + h.update(lib_sha256.as_bytes()); + h.update(NUMERICS_EPOCH.to_le_bytes()); + h.update((kv_values as u64).to_le_bytes()); + h.update((snap_bytes as u64).to_le_bytes()); + let mut env = env.to_vec(); + env.sort(); + for (k, v) in env { + h.update(format!("\n{k}={v}").as_bytes()); + } + h.finalize().into() +} + +/// The switches the namespace binds: every `AIEN_Q36_*` and `AIEN_OMEGA_*` variable except the +/// pool's own settings and the beat's prompt share (neither moves a state byte); the mutant is +/// bound, so a mutant run never feeds the store of a real one. +pub fn numeric_env(vars: impl Iterator) -> Vec<(String, String)> { + vars.filter(|(k, _)| { + (k.starts_with("AIEN_Q36_") || k.starts_with("AIEN_OMEGA_")) + && (!k.starts_with("AIEN_Q36_PREFIX_") || k == MUTANT_ENV) + && k != "AIEN_Q36_PROMPT_PER_BEAT" + && k != SWITCH_ENV + && k != "AIEN_OMEGA_GPU_LIB" + }) + .collect() +} + +/// The directory rules of aien-kv-store's host store, kept short: an existing directory must be +/// ours and private (0700); a missing one is made so. +fn open_private_dir(dir: &Path) -> Result<(), String> { + match std::fs::symlink_metadata(dir) { + Ok(m) => { + if !m.is_dir() { + return Err(format!("{}: not a directory", dir.display())); + } + // SAFETY: plain libc call without arguments. + let uid = unsafe { libc::geteuid() }; + if m.uid() != uid { + return Err(format!("{}: not owned by this user", dir.display())); + } + if m.permissions().mode() & 0o077 != 0 { + return Err(format!( + "{}: mode {:o}, must be private (0700)", + dir.display(), + m.permissions().mode() & 0o777 + )); + } + Ok(()) + } + Err(_) => std::fs::DirBuilder::new() + .mode(0o700) + .create(dir) + .map_err(|e| format!("{}: {e}", dir.display())), + } +} + +fn file_name(digest: &[u8; 32], pos: usize) -> String { + format!("{}-{pos}.{FILE_EXT}", hex(&digest[..16])) +} + +struct Loaded { + path: PathBuf, + tokens: Vec, + parent: Option<[u8; 32]>, + kv_from: usize, + kv: Vec, + snap: Vec, +} + +fn u64_at(b: &[u8], o: usize) -> usize { + u64::from_le_bytes(b[o..o + 8].try_into().expect("8 bytes")) as usize +} + +/// Header region layout (bytes `0 .. SEAL_SLOT_OFFSET` are associated data of the seal): +/// magic 16 | namespace 32 | token digest 32 | parent digest 32 (zeros: none) | has parent 8 | +/// tokens 8 | kv_from 8 | kv values 8 | state bytes 8. +fn header( + n: &Node, + parent: Option<[u8; 32]>, + ns: &[u8; 32], + snap_len: usize, +) -> Vec { + let mut r = vec![0u8; HEADER_REGION_LEN]; + r[0..16].copy_from_slice(MAGIC); + r[16..48].copy_from_slice(ns); + r[48..80].copy_from_slice(&n.digest); + r[80..112].copy_from_slice(&parent.unwrap_or([0; 32])); + for (i, v) in [ + usize::from(parent.is_some()), + n.tokens.len(), + n.kv_from, + n.kv.len(), + snap_len, + ] + .into_iter() + .enumerate() + { + r[112 + i * 8..120 + i * 8].copy_from_slice(&(v as u64).to_le_bytes()); + } + const { assert!(152 <= SEAL_SLOT_OFFSET) }; + r +} + +fn read_node(p: &Path, key: &SealKey, ns: &[u8; 32], kv_values: usize) -> Result { + let mut file = std::fs::read(p).map_err(|e| e.to_string())?; + if file.len() < HEADER_REGION_LEN { + return Err("short file".into()); + } + let (region, payload) = file.split_at_mut(HEADER_REGION_LEN); + if ®ion[0..16] != MAGIC { + return Err("not a prompt cache file".into()); + } + if region[16..48] != ns[..] { + return Err("made under another model, build or switch set".into()); + } + let (has_parent, nt, kv_from, nkv, nsnap) = ( + u64_at(region, 112), + u64_at(region, 120), + u64_at(region, 128), + u64_at(region, 136), + u64_at(region, 144), + ); + let want = nt + .checked_mul(4) + .and_then(|a| nkv.checked_mul(2).and_then(|b| a.checked_add(b))) + .and_then(|a| a.checked_add(nsnap)); + if want != Some(payload.len()) { + return Err("lengths do not match the file".into()); + } + if kv_from > nt || nkv != (nt - kv_from) * kv_values { + return Err("K/V length does not match the positions".into()); + } + key.open_payload(region, payload) + .map_err(|e| format!("seal refused ({e:?})"))?; + let tokens: Vec = payload[..nt * 4] + .as_chunks::<4>() + .0 + .iter() + .map(|c| u32::from_le_bytes(*c)) + .collect(); + if digest_of(&tokens)[..] != region[48..80] { + return Err("token digest does not match".into()); + } + let kv: Vec = payload[nt * 4..nt * 4 + nkv * 2] + .as_chunks::<2>() + .0 + .iter() + .map(|c| u16::from_le_bytes(*c)) + .collect(); + let mut pd = [0u8; 32]; + pd.copy_from_slice(®ion[80..112]); + Ok(Loaded { + path: p.to_path_buf(), + tokens, + parent: (has_parent == 1).then_some(pd), + kv_from, + kv, + snap: payload[nt * 4 + nkv * 2..].to_vec(), + }) +} + +enum Msg { + Write { + name: String, + region: Vec, + tokens: Vec, + kv: Arc>, + snap: Arc, + }, + Delete(String), + Flush(mpsc::SyncSender<()>), +} + +/// One write or delete, run on the writer thread with the store dir and key. +type StoreJob = Box; + +/// The writer thread: seals and writes nodes, deletes evicted ones. +struct Store { + tx: mpsc::Sender, + ns: [u8; 32], +} + +impl Store { + fn start(dir: PathBuf, key: Arc, ns: [u8; 32]) -> Self { + let (tx, rx) = mpsc::channel::>(); + std::thread::Builder::new() + .name("q36-prefix-store".into()) + .spawn(move || { + while let Ok(job) = rx.recv() { + job(&dir, &key); + } + }) + .expect("q36 prefix store thread"); + Self { tx, ns } + } + + fn send(&self, m: Msg) { + let job: StoreJob = Box::new(move |dir, key| match m { + Msg::Write { + name, + region, + tokens, + kv, + snap, + } => { + if let Err(e) = write_file(dir, key, &name, region, &tokens, &kv, &*snap) { + eprintln!("aien-serve-http: q36 prefix: writing {name} failed: {e}"); + } + } + Msg::Delete(name) => { + let _ = std::fs::remove_file(dir.join(name)); + } + Msg::Flush(done) => { + let _ = done.send(()); + } + }); + let _ = self.tx.send(job); + } + + fn write(&self, n: &Node, parent: Option<[u8; 32]>) { + // The state's byte length goes in the header; the writer thread checks its bytes against it. + let snap_len = n.snap.bytes_len(); + self.send(Msg::Write { + name: file_name(&n.digest, n.tokens.len()), + region: header(n, parent, &self.ns, snap_len), + tokens: n.tokens.clone(), + kv: Arc::clone(&n.kv), + snap: Arc::clone(&n.snap), + }); + } + + fn delete(&self, digest: &[u8; 32], pos: usize) { + self.send::(Msg::Delete(file_name(digest, pos))); + } + + fn flush(&self) { + let (tx, rx) = mpsc::sync_channel(1); + self.send::(Msg::Flush(tx)); + let _ = rx.recv(); + } +} + +/// A stand-in state type for messages that carry none. +struct NoSnap; +impl PoolSnap for NoSnap { + fn host_bytes(&self) -> usize { + 0 + } + fn to_bytes(&self) -> Vec { + Vec::new() + } + fn from_bytes(_: &[u8]) -> Result { + Ok(Self) + } +} + +fn write_file( + dir: &Path, + key: &SealKey, + name: &str, + region: Vec, + tokens: &[u32], + kv: &[u16], + snap: &S, +) -> Result<(), String> { + let sb = snap.to_bytes(); + if u64_at(®ion, 144) != sb.len() { + return Err("state length changed".into()); + } + let mut file = region; + file.reserve(tokens.len() * 4 + kv.len() * 2 + sb.len()); + for t in tokens { + file.extend_from_slice(&t.to_le_bytes()); + } + for v in kv { + file.extend_from_slice(&v.to_le_bytes()); + } + file.extend_from_slice(&sb); + key.seal_file(&dir.join(aien_kv_store::seal::USAGE_DIR_NAME), &mut file) + .map_err(|e| format!("seal: {e:?}"))?; + let tmp = dir.join(format!(".{name}.tmp")); + let mut f = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(&tmp) + .map_err(|e| format!("{}: {e}", tmp.display()))?; + f.write_all(&file).map_err(|e| e.to_string())?; + f.sync_all().map_err(|e| e.to_string())?; + std::fs::rename(&tmp, dir.join(name)).map_err(|e| e.to_string()) +} + +#[cfg(test)] +mod tests; diff --git a/crates/aien-serve-http/src/q36_prefix/tests.rs b/crates/aien-serve-http/src/q36_prefix/tests.rs new file mode 100644 index 00000000..8a5e486e --- /dev/null +++ b/crates/aien-serve-http/src/q36_prefix/tests.rs @@ -0,0 +1,420 @@ +//! Host tests of the shared prompt cache: longest match, leaf-first LRU, the sealed store +//! (round trip, tamper, another namespace), the switch, and the restore refusals (DRA-86). +use super::*; + +#[derive(Debug, Clone, PartialEq, Default)] +struct S(Vec); + +impl PoolSnap for S { + fn host_bytes(&self) -> usize { + self.0.len() + } + fn to_bytes(&self) -> Vec { + self.0.clone() + } + fn from_bytes(b: &[u8]) -> Result { + Ok(Self(b.to_vec())) + } + /// `put` fills the state with its token count. + fn pos(&self) -> Option { + self.0.first().map(|&b| b as usize) + } +} + +fn cfg(budget: usize) -> PoolConfig { + PoolConfig { + budget, + every: 4, + dir: None, + mutant: false, + } +} + +fn toks(n: usize, salt: u32) -> Vec { + (0..n as u32) + .map(|i| if i < 6 { i } else { i * 31 + salt }) + .collect() +} + +/// Inserts the node for `t` under its deepest prefix, K/V one value per position. +fn put(p: &mut PrefixPool, t: &[u32]) -> bool { + let (parent, from) = p.parent_for(t).map_or((None, 0), |(i, n)| (Some(i), n)); + let kv: Vec = t[from..].iter().map(|&x| x as u16).collect(); + p.insert(t.to_vec(), parent, kv, S(vec![t.len() as u8; 8])) +} + +#[test] +fn the_longest_node_the_prompt_continues_wins_and_its_kv_comes_root_first() { + let mut p = PrefixPool::new(&cfg(1 << 20)); + let a = toks(20, 0); + for n in [4, 8, 12] { + put(&mut p, &a[..n]); + } + let mut b = a.clone(); + b[10] = 9999; + let (id, n) = p.longest(&b, b.len() - 1).unwrap(); + assert_eq!(n, 8); + let r = p.restore(id, &b[..8], 1).unwrap(); + assert_eq!(r.pos, 8); + let kv: Vec = r.kv.iter().flat_map(|(_, k)| k.iter().copied()).collect(); + assert_eq!(kv, a[..8].iter().map(|&x| x as u16).collect::>()); + assert_eq!(r.kv.iter().map(|&(f, _)| f).collect::>(), [0, 4]); + assert_eq!(r.snap, &S(vec![8; 8])); + // At most `max` tokens: the last prompt token is always read. + assert_eq!(p.longest(&a[..12], 11).map(|x| x.1), Some(8)); + assert_eq!(p.divergence(&b), Some(10)); + assert_eq!(p.divergence(&a), None); +} + +#[test] +fn eviction_drops_least_recently_used_leaves_and_keeps_parents_of_live_children() { + let a = toks(16, 0); + let b = toks(16, 7); + // Node bytes: whole prefix 4 B a token + its K/V delta 2 B a value + 8 B state: a4 32, a8 48, + // a12 64, b8 48, b12 64 (256 in all), a16 80. + let mut p = PrefixPool::new(&cfg(300)); + for n in [4, 8, 12] { + put(&mut p, &a[..n]); + } + put(&mut p, &b[..8]); // parent: a[..4] (b shares 6 tokens with a); 4 kv values + put(&mut p, &b[..12]); + assert_eq!(p.counters().nodes, 5); + let (id, n) = p.longest(&a, 15).unwrap(); + assert!(p.restore(id, &a[..n], 1).is_ok()); // a's chain is now the newest + put(&mut p, &a[..16]); // over budget: b[..12] (the oldest leaf) goes, then nothing else + let c = p.counters(); + assert_eq!((c.nodes, c.evicted), (5, 1)); + assert_eq!(p.longest(&b, 15).map(|x| x.1), Some(8)); + assert_eq!(p.longest(&a, 16).map(|x| x.1), Some(16)); +} + +fn tmp_dir(tag: &str) -> PathBuf { + let d = std::env::temp_dir().join(format!("l375-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d +} + +fn key() -> SealKey { + SealKey::from_bytes([7; 32]) +} + +fn files(d: &Path) -> Vec { + let mut v: Vec = std::fs::read_dir(d) + .unwrap() + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().and_then(|e| e.to_str()) == Some(FILE_EXT)) + .collect(); + v.sort(); + v +} + +#[test] +fn the_store_brings_every_node_back_after_a_restart() { + let d = tmp_dir("rt"); + let ns = [3u8; 32]; + let a = toks(12, 0); + { + let mut p = PrefixPool::::new(&cfg(1 << 20)); + p.open_store(&d, key(), ns, 1, |_| true).unwrap(); + for n in [4, 8, 12] { + put(&mut p, &a[..n]); + } + p.flush(); + } + assert_eq!(files(&d).len(), 3); + let mode = std::fs::metadata(&d).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o700); + let mut q = PrefixPool::::new(&cfg(1 << 20)); + q.open_store(&d, key(), ns, 1, |_| true).unwrap(); + assert_eq!(q.counters().loaded, 3); + let (id, n) = q.longest(&a, 12).unwrap(); + assert_eq!(n, 12); + let r = q.restore(id, &a, 1).unwrap(); + let kv: Vec = r.kv.iter().flat_map(|(_, k)| k.iter().copied()).collect(); + assert_eq!(kv, a.iter().map(|&x| x as u16).collect::>()); + assert_eq!(r.snap, &S(vec![12; 8])); + // Eviction deletes the file too. + std::fs::remove_dir_all(&d).unwrap(); +} + +#[test] +fn a_tampered_file_another_key_or_another_namespace_is_discarded() { + let d = tmp_dir("tamper"); + let ns = [3u8; 32]; + let a = toks(8, 0); + { + let mut p = PrefixPool::::new(&cfg(1 << 20)); + p.open_store(&d, key(), ns, 1, |_| true).unwrap(); + put(&mut p, &a[..4]); + put(&mut p, &a[..8]); + p.flush(); + } + // Another namespace: nothing opens (and the files go). + let mut q = PrefixPool::::new(&cfg(1 << 20)); + q.open_store(&d, key(), [4u8; 32], 1, |_| true).unwrap(); + assert_eq!((q.counters().loaded, q.counters().discarded), (0, 2)); + drop(q); + { + let mut p = PrefixPool::::new(&cfg(1 << 20)); + p.open_store(&d, key(), ns, 1, |_| true).unwrap(); + put(&mut p, &a[..4]); + put(&mut p, &a[..8]); + p.flush(); + } + // One flipped payload byte in the root: it and its child (no parent) are discarded. + let f = files(&d) + .into_iter() + .find(|p| p.to_string_lossy().ends_with("-4.q36p")) + .unwrap(); + let mut b = std::fs::read(&f).unwrap(); + let last = b.len() - 1; + b[last] ^= 1; + std::fs::write(&f, b).unwrap(); + let mut q = PrefixPool::::new(&cfg(1 << 20)); + q.open_store(&d, key(), ns, 1, |_| true).unwrap(); + assert_eq!((q.counters().loaded, q.counters().discarded), (0, 2)); + drop(q); + // Another key. + { + let mut p = PrefixPool::::new(&cfg(1 << 20)); + p.open_store(&d, key(), ns, 1, |_| true).unwrap(); + put(&mut p, &a[..4]); + p.flush(); + } + let mut q = PrefixPool::::new(&cfg(1 << 20)); + q.open_store(&d, SealKey::from_bytes([8; 32]), ns, 1, |_| true) + .unwrap(); + assert_eq!(q.counters().loaded, 0); + std::fs::remove_dir_all(&d).unwrap(); +} + +#[test] +fn a_shared_directory_is_refused() { + let d = tmp_dir("mode"); + std::fs::create_dir(&d).unwrap(); + std::fs::set_permissions(&d, std::fs::Permissions::from_mode(0o755)).unwrap(); + let mut p = PrefixPool::::new(&cfg(1 << 20)); + assert!(p.open_store(&d, key(), [0; 32], 1, |_| true).is_err()); + std::fs::remove_dir_all(&d).unwrap(); +} + +#[test] +fn the_namespace_binds_switches_but_not_the_pools_own() { + let e = |v: &[(&str, &str)]| numeric_env(v.iter().map(|(k, v)| (k.to_string(), v.to_string()))); + let base = e(&[ + ("AIEN_Q36_STROKE", "0"), + ("AIEN_Q36_PREFIX_POOL_GB", "8"), + ("HOME", "/x"), + ]); + assert_eq!(base, [("AIEN_Q36_STROKE".to_string(), "0".to_string())]); + let m = e(&[("AIEN_Q36_PREFIX_MUTANT", "1"), ("AIEN_Q36_PREFIX", "1")]); + assert_eq!(m.len(), 1, "the switch moves no state byte; the mutant is bound"); + let ck = [1u8; 32]; + assert_ne!( + namespace(&ck, "aa", 1, 2, &base), + namespace(&ck, "aa", 1, 2, &e(&[("AIEN_Q36_STROKE", "1")])) + ); + assert_ne!( + namespace(&ck, "aa", 1, 2, &base), + namespace(&ck, "ab", 1, 2, &base) + ); +} + +// ---- DRA-86: the switch, the budget default and the restore refusals ---- + +#[test] +fn the_cache_is_off_without_the_switch_and_16_gib_with_it() { + let off = PoolConfig::from_lookup(|_| None).unwrap(); + assert_eq!(off.budget, 0); + assert!(!PrefixPool::::new(&off).on()); + let gb_only = + PoolConfig::from_lookup(|k| (k == "AIEN_Q36_PREFIX_POOL_GB").then(|| "4".into())).unwrap(); + assert_eq!(gb_only.budget, 0, "the budget alone must not turn the cache on"); + let on = PoolConfig::from_lookup(|k| (k == SWITCH_ENV).then(|| "1".into())).unwrap(); + assert_eq!(on.budget, 16 << 30); + let half = PoolConfig::from_lookup(|k| match k { + SWITCH_ENV => Some("1".into()), + "AIEN_Q36_PREFIX_POOL_GB" => Some("0.5".into()), + _ => None, + }) + .unwrap(); + assert_eq!(half.budget, 1 << 29); + assert!(PoolConfig::from_lookup(|k| (k == SWITCH_ENV).then(|| "yes".into())).is_err()); +} + +/// A pool holding a[..4], a[..8], a[..12] (a = toks(16, 0)); the id of a[..12]. +fn chain() -> (PrefixPool, Vec, u64) { + let mut p = PrefixPool::new(&cfg(1 << 20)); + let a = toks(16, 0); + for n in [4, 8, 12] { + assert!(put(&mut p, &a[..n])); + } + let (id, n) = p.longest(&a, 12).unwrap(); + assert_eq!(n, 12); + (p, a, id) +} + +fn node<'a>(p: &'a mut PrefixPool, t: &[u32]) -> &'a mut Node { + p.nodes.values_mut().find(|n| n.tokens[..] == *t).unwrap() +} + +#[test] +fn a_restore_gives_back_the_saved_bytes_and_its_conversation_resident_size() { + let (mut p, a, id) = chain(); + let r = p.restore(id, &a[..12], 1).unwrap(); + let kv: Vec = r.kv.iter().flat_map(|(_, k)| k.iter().copied()).collect(); + assert_eq!(kv, a[..12].iter().map(|&x| x as u16).collect::>()); + assert_eq!(r.kv.iter().map(|&(f, _)| f).collect::>(), [0, 4, 8]); + assert_eq!(r.snap, &S(vec![12; 8])); + // Node bytes 4 B a token + 2 B a K/V value + 8 B state: 32 + 48 + 64. + assert_eq!(r.resident, 144); + assert_eq!(p.resident(&a[..12]), Some((3, 144))); + assert_eq!(p.resident(&a[..8]), Some((2, 80))); + assert_eq!(p.counters().refused, 0); +} + +#[test] +fn a_node_of_another_model_or_lib_tag_is_refused_and_dropped() { + let (mut p, a, id) = chain(); + p.bind_tag([1; 32]); // the chip library or the weights moved + assert_eq!( + p.restore(id, &a[..12], 1).err(), + Some(Refused::Stale { pos: 4 }) + ); + let c = p.counters(); + assert_eq!((c.nodes, c.bytes, c.refused), (0, 0, 1)); + // Nodes saved under the new tag restore. + assert!(put(&mut p, &a[..4])); + let (id, _) = p.longest(&a, 15).unwrap(); + assert!(p.restore(id, &a[..4], 1).is_ok()); +} + +#[test] +fn a_node_restored_as_other_tokens_or_one_turn_off_is_refused() { + let (mut p, a, id) = chain(); + let mut b = a[..12].to_vec(); + b[11] ^= 1; + assert_eq!( + p.restore(id, &b, 1).err(), + Some(Refused::TokenMismatch { pos: 12 }) + ); + // The node after 12 tokens offered as the state after 11 or 13: off by one, refused. + let (mut p, a, id) = chain(); + assert!(matches!( + p.restore(id, &a[..11], 1), + Err(Refused::TokenMismatch { .. }) + )); + let (mut p, a, id) = chain(); + assert!(matches!( + p.restore(id, &a[..13], 1), + Err(Refused::TokenMismatch { .. }) + )); + // A stored digest that is not the tokens' (a corrupted node) is refused too. + let (mut p, a, id) = chain(); + node(&mut p, &a[..12]).digest[0] ^= 1; + assert_eq!( + p.restore(id, &a[..12], 1).err(), + Some(Refused::TokenMismatch { pos: 12 }) + ); +} + +#[test] +fn a_kv_gap_or_a_kv_or_state_length_mismatch_is_refused() { + let (mut p, a, id) = chain(); + node(&mut p, &a[..12]).kv_from = 9; + assert_eq!( + p.restore(id, &a[..12], 1).err(), + Some(Refused::KvGap { + kv_from: 9, + expected: 8 + }) + ); + let (mut p, a, id) = chain(); + Arc::make_mut(&mut node(&mut p, &a[..8]).kv).pop(); + assert_eq!( + p.restore(id, &a[..12], 1).err(), + Some(Refused::KvLength { + pos: 8, + values: 3, + expected: 4 + }) + ); + // Two K/V values a position where the pool holds one. + let (mut p, a, id) = chain(); + assert!(matches!( + p.restore(id, &a[..12], 2), + Err(Refused::KvLength { .. }) + )); + // The state continues at 11 for a node of 12 tokens. + let (mut p, a, id) = chain(); + node(&mut p, &a[..12]).snap = Arc::new(S(vec![11; 8])); + assert_eq!( + p.restore(id, &a[..12], 1).err(), + Some(Refused::StateLength { state: 11, pos: 12 }) + ); + // A refused leaf is dropped; its parent stays. + assert_eq!(p.longest(&a, 15).map(|x| x.1), Some(8)); +} + +#[test] +fn the_budget_evicts_the_least_recently_used_leaf_and_drops_a_node_alone_over_it() { + let a = toks(16, 0); + let b = toks(16, 7); + // a4 32 B, a8 48, then b8 under a4 (4 K/V values): 32 + 8 + 8 = 48 B; budget 120. + let mut p = PrefixPool::new(&cfg(120)); + put(&mut p, &a[..4]); + put(&mut p, &a[..8]); + put(&mut p, &b[..8]); + let c = p.counters(); + assert_eq!( + (c.nodes, c.bytes, c.evicted), + (2, 80, 1), + "a8 (the oldest leaf) goes" + ); + assert!(c.bytes <= p.budget()); + assert_eq!(p.longest(&a, 15).map(|x| x.1), Some(4)); + assert_eq!(p.longest(&b, 15).map(|x| x.1), Some(8)); + // A node bigger than the whole budget is dropped at once. + let mut q = PrefixPool::new(&cfg(40)); + assert!(!put(&mut q, &a[..8])); + assert_eq!(q.counters().nodes, 0); +} + +type Spoil = Box, &[u32]) -> Vec>; + +/// The negative control: the base's restore (no checks) hands every bad node above to the row. +#[test] +fn the_unchecked_base_restores_every_bad_node() { + let bad: Vec = vec![ + Box::new(|p, a| { + p.bind_tag([1; 32]); + a[..12].to_vec() + }), + Box::new(|_, a| a[..13].to_vec()), + Box::new(|p, a| { + node(p, &a[..12]).kv_from = 9; + a[..12].to_vec() + }), + Box::new(|p, a| { + Arc::make_mut(&mut node(p, &a[..8]).kv).pop(); + a[..12].to_vec() + }), + Box::new(|p, a| { + node(p, &a[..12]).snap = Arc::new(S(vec![11; 8])); + a[..12].to_vec() + }), + ]; + for (k, f) in bad.iter().enumerate() { + let (mut checked, a, id) = chain(); + let t = f(&mut checked, &a); + assert!(checked.restore(id, &t, 1).is_err(), "case {k} not refused"); + let (mut base, a, id) = chain(); + base.set_unchecked(true); + let t = f(&mut base, &a); + assert!( + base.restore(id, &t, 1).is_ok(), + "case {k}: the base refuses it too" + ); + } +} diff --git a/crates/aien-serve-http/src/qwen36_batch.rs b/crates/aien-serve-http/src/qwen36_batch.rs index ade10290..0470a774 100644 --- a/crates/aien-serve-http/src/qwen36_batch.rs +++ b/crates/aien-serve-http/src/qwen36_batch.rs @@ -40,6 +40,7 @@ use crate::engine::{ Engine, EngineError, FinishReason, GenerateOutcome, GenerateParams, GroupJob, TestSwitches, }; use crate::omega_engine::{GpuLock, GPU_LOCK_PATH}; +use crate::q36_prefix::{PoolConfig, PoolSnap, PrefixPool}; use crate::qwen38_engine::{ admit_load, is_moe_dir, rss_bytes, CHIP_GREEDY_ENV, KEEP_FREE, LOAD_LOCK_WAIT, PREFILL_CHUNK, REQUEST_LOCK_WAIT, @@ -68,6 +69,10 @@ fn env_usize(name: &str, default: usize) -> usize { } } +/// Fewest tokens between two of the server's checkpoint marks the door keeps (each checkpoint +/// holds a full DeltaNet state copy). +pub const MARK_GAP: usize = 512; + fn prompt_per_beat() -> Result { match std::env::var("AIEN_Q36_PROMPT_PER_BEAT") { Ok(v) => match v.parse::() { @@ -147,10 +152,30 @@ pub trait RowStep: Send + 'static { last.ok_or_else(|| "prefill_row: no tokens".to_string()) } /// A host copy of a row's state. - type Snap: Default + Send; + type Snap: Default + PoolSnap; fn row_snapshot(&mut self, r: usize, snap: &mut Self::Snap) -> Result<(), String>; - /// Puts a copy back into row `r` (any row). + /// Puts a copy back into row `r` (any row; the K/V stays: see `row_kv_write`). fn row_restore(&mut self, r: usize, snap: &Self::Snap) -> Result<(), String>; + /// Values one position of a row's K/V holds (the shared prompt cache's copies). + fn row_kv_values(&self) -> usize; + /// Copies row `r`'s K/V at positions `from .. from + count` into `out`. + fn row_kv_read( + &mut self, + r: usize, + from: usize, + count: usize, + out: &mut Vec, + ) -> Result<(), String>; + /// Writes a `row_kv_read` copy into row `r` at positions `from .. from + count`. + fn row_kv_write( + &mut self, + r: usize, + from: usize, + count: usize, + data: &[u16], + ) -> Result<(), String>; + /// Moves row `r`'s next position (the prompt cache's position mutant only). + fn row_set_pos(&mut self, r: usize, pos: usize) -> Result<(), String>; } impl RowStep for Qwen38Omega { @@ -180,12 +205,38 @@ impl RowStep for Qwen38Omega { fn row_restore(&mut self, r: usize, snap: &Qwen38Snapshot) -> Result<(), String> { Qwen38Omega::row_restore(self, r, snap) } + fn row_kv_values(&self) -> usize { + Qwen38Omega::row_kv_values(self) + } + fn row_kv_read( + &mut self, + r: usize, + from: usize, + count: usize, + out: &mut Vec, + ) -> Result<(), String> { + Qwen38Omega::row_kv_read(self, r, from, count, out) + } + fn row_kv_write( + &mut self, + r: usize, + from: usize, + count: usize, + data: &[u16], + ) -> Result<(), String> { + Qwen38Omega::row_kv_write(self, r, from, count, data) + } + fn row_set_pos(&mut self, r: usize, pos: usize) -> Result<(), String> { + Qwen38Omega::row_set_pos(self, r, pos) + } } /// A request handed to the scheduler. The channel carries a `Vec`: one request, or a group /// ([`Engine::generate_group`]) that is seated all in the same beat. struct Job { prompt: Vec, + /// Token positions worth a prompt cache checkpoint (tool boundaries, from the server). + marks: Vec, params: GenerateParams, /// The job's events go out tagged with its place in its group (0 for a single request). out: mpsc::SyncSender<(usize, Ev)>, @@ -202,7 +253,14 @@ struct Job { /// The merge train's switches the batch door applies per request (`Engine::test_switches_honored`). #[cfg(feature = "aien-test-switches")] -const TEST_SWITCHES_HONORED: &[&str] = &["stroke", "exact_head", "mutant", "row_swap"]; +const TEST_SWITCHES_HONORED: &[&str] = &[ + "stroke", + "exact_head", + "mutant", + "row_swap", + "prefix_pool", + "prefix_mutant", +]; /// The per-step row switches of a request (`stroke`, `exact_head`, `mutant`). fn row_test(t: &TestSwitches) -> RowTest { @@ -329,6 +387,10 @@ struct Row { /// The tokens `snap` holds (empty: none). snap_tokens: Vec, snap: T, + /// A test mutant ran on this row (a graph mutant, or a pool restore one position off): its + /// state is off its history. It saves no checkpoint and is forgotten when its conversation + /// ends (the flag stays with the row through a test row swap). + tainted: bool, } /// One conversation in flight on the scheduler thread. @@ -340,6 +402,8 @@ struct Active { reused: usize, /// Where to copy the state on the way in: the prompt's last turn header (`<|im_start|>`). snap_at: Option, + /// Positions (ascending) where the shared prompt cache saves the row's state on the way in. + cps: Vec, observer: SamplingObserver, emitted: usize, /// Logits after the last fed token, until sampled. @@ -402,6 +466,11 @@ impl Qwen36BatchDoor { // The main graph is never stepped here: its own state is one 256-position pass. let need = need_bytes(&c, 256, PREFILL_CHUNK); let keep = keep_free()?; + // The prompt cache store binds the weights' digest: hashed beside the upload. + let ck_digest = std::env::var_os("AIEN_Q36_PREFIX_DIR").map(|_| { + let d = dir.to_path_buf(); + std::thread::spawn(move || crate::kv_persist::checkpoint_digest(&d).map(|(h, _)| h)) + }); let mut t0 = Instant::now(); let (lock, mut model) = admit_then_open( || GpuLock::acquire_queued_at(Path::new(GPU_LOCK_PATH), LOAD_LOCK_WAIT), @@ -433,6 +502,7 @@ impl Qwen36BatchDoor { model.add_rows(slots, max_pos)?; let after = mem_available(); let measured = before.saturating_sub(after); + let pool = open_pool(ck_digest, &mut model)?; drop(lock); eprintln!( "aien-serve-http: qwen36-batch engine ready in {:.1} s: context {max_context} tokens, {slots} rows, weights {:.2} GB resident, per-row state {:.1} MiB on paper, {:.1} MiB measured (MemAvailable {} MiB -> {} MiB), rss {:.2} GB, prompt tokens per beat {per_beat}", @@ -444,13 +514,14 @@ impl Qwen36BatchDoor { after >> 20, rss_bytes() as f64 / 1e9, ); - let mut door = Self::with_stepper( + let mut door = Self::with_stepper_pool( model, max_context, PathBuf::from(GPU_LOCK_PATH), REQUEST_LOCK_WAIT, per_beat, std::env::var(CHIP_GREEDY_ENV).as_deref() != Ok("0"), + pool, )?; door.slot_bytes_measured = measured; door.slot_bytes_on_paper = on_paper; @@ -466,6 +537,30 @@ impl Qwen36BatchDoor { lock_wait: Duration, prompt_per_beat: usize, chip_greedy: bool, + ) -> Result { + let off = + PoolConfig::from_lookup(|k| (k == "AIEN_Q36_PREFIX_POOL_GB").then(|| "0".into()))?; + Self::with_stepper_pool( + model, + max_context, + lock_path, + lock_wait, + prompt_per_beat, + chip_greedy, + PrefixPool::new(&off), + ) + } + + /// [`Self::with_stepper`] with the shared prompt cache `pool` (sc L375). + #[allow(clippy::too_many_arguments)] + pub fn with_stepper_pool( + model: S, + max_context: usize, + lock_path: PathBuf, + lock_wait: Duration, + prompt_per_beat: usize, + chip_greedy: bool, + pool: PrefixPool, ) -> Result { let slots = model.row_count(); if slots == 0 { @@ -479,6 +574,7 @@ impl Qwen36BatchDoor { history: Vec::new(), last_used: 0, snap_tokens: Vec::new(), + tainted: false, snap: S::Snap::default(), }) .collect(), @@ -493,6 +589,7 @@ impl Qwen36BatchDoor { pf_min: env_usize("AIEN_Q36_PREFILL_MIN", Q36_PREFILL_MIN).max(1), chip_greedy, beat: 0, + pool, }; std::thread::Builder::new() .name("qwen36-batch".into()) @@ -527,22 +624,18 @@ impl Engine for Qwen36BatchDoor { p: &GenerateParams, on_token: &mut dyn FnMut(u32) -> bool, ) -> Result { - self.generate_test(prompt, p, TestSwitches::default(), on_token) - } - - #[cfg(feature = "aien-test-switches")] - fn test_switches_honored(&self) -> &'static [&'static str] { - TEST_SWITCHES_HONORED + self.generate_marked(prompt, &[], p, &TestSwitches::default(), on_token) } - #[cfg(feature = "aien-test-switches")] - fn generate_with_test( + fn generate_marked( &self, prompt: &[u32], + marks: &[usize], p: &GenerateParams, test: &TestSwitches, on_token: &mut dyn FnMut(u32) -> bool, ) -> Result { + #[cfg(feature = "aien-test-switches")] if let Some(bad) = test .names() .into_iter() @@ -552,7 +645,30 @@ impl Engine for Qwen36BatchDoor { "aien_test.{bad} is not a switch of the batch door (honored: {TEST_SWITCHES_HONORED:?})" ))); } - self.generate_test(prompt, p, test.clone(), on_token) + #[cfg(not(feature = "aien-test-switches"))] + if !test.is_empty() { + return Err(EngineError::Failed(format!( + "aien_test switches {:?}: this build has no test switches", + test.names() + ))); + } + self.generate_test(prompt, marks, p, test.clone(), on_token) + } + + #[cfg(feature = "aien-test-switches")] + fn test_switches_honored(&self) -> &'static [&'static str] { + TEST_SWITCHES_HONORED + } + + #[cfg(feature = "aien-test-switches")] + fn generate_with_test( + &self, + prompt: &[u32], + p: &GenerateParams, + test: &TestSwitches, + on_token: &mut dyn FnMut(u32) -> bool, + ) -> Result { + self.generate_marked(prompt, &[], p, test, on_token) } fn generate_group( @@ -565,16 +681,19 @@ impl Engine for Qwen36BatchDoor { } impl Qwen36BatchDoor { - /// The request path; `test` is empty on the served path (`Engine::generate`). + /// The request path; `test` is empty on the served path, `marks` are the server's + /// checkpoint hints (tool boundaries). fn generate_test( &self, prompt: &[u32], + marks: &[usize], p: &GenerateParams, test: TestSwitches, on_token: &mut dyn FnMut(u32) -> bool, ) -> Result { let job = GroupJob { prompt: prompt.to_vec(), + marks: marks.to_vec(), params: p.clone(), cancel: None, test, @@ -645,6 +764,7 @@ impl Qwen36BatchDoor { .enumerate() .map(|(i, j)| Job { prompt: j.prompt.clone(), + marks: j.marks.clone(), params: j.params.clone(), out: otx.clone(), tag: i, @@ -687,6 +807,8 @@ struct Scheduler { /// Greedy replies take the graph's token (`AIEN_SERVE_CHIP_GREEDY=0` turns it off). chip_greedy: bool, beat: u64, + /// The shared prompt cache (sc L375). + pool: PrefixPool, } /// Totals over one busy spell (first arrival to last departure). @@ -796,17 +918,23 @@ impl Scheduler { let mut pf_err: Option = None; if self.pf_chunk > 0 { for (k, a) in active.iter_mut().enumerate() { - if !a.prefilling() - || a.snap_at == Some(a.fed) - || !row_test(&a.job.test).is_plain() - { + if !a.prefilling() || !row_test(&a.job.test).is_plain() { + continue; + } + // The prompt cache's checkpoint here (L375); chunks stop at the next one. + if a.cps.first() == Some(&a.fed) { + a.cps.remove(0); + self.save_checkpoint(a.row, &a.job.prompt[..a.fed]); + } + if a.snap_at == Some(a.fed) { continue; } let plen = a.job.prompt.len(); - let stop = match a.snap_at { - Some(s) if s > a.fed => s, - _ => plen, - }; + let stop = [a.snap_at, a.cps.first().copied()] + .into_iter() + .flatten() + .filter(|&s| s > a.fed) + .fold(plen, usize::min); let n = (stop - a.fed).min(self.pf_chunk); if n < self.pf_min { continue; @@ -853,6 +981,13 @@ impl Scheduler { // One beat: every decoding row feeds its sampled token in the first step; the rows // still feeding their prompt feed up to `per_beat` prompt tokens, one per step. for sub in 0..self.per_beat { + // The shared prompt cache's checkpoints, before the token at that position goes in. + for a in active.iter_mut() { + if a.prefilling() && a.cps.first() == Some(&a.fed) { + a.cps.remove(0); + self.save_checkpoint(a.row, &a.job.prompt[..a.fed]); + } + } // Each joining prompt's state copy at its last turn header, before that token goes in. for a in active.iter_mut() { if a.prefilling() && a.snap_at == Some(a.fed) { @@ -952,15 +1087,18 @@ impl Scheduler { } } - /// Seats the request on a free row: the longest state some free row holds that the prompt - /// continues (its live tokens, or its copy at its last turn header), else the least recently - /// used row, emptied. The single door's reuse rule ([`aien_inference_abi::qwen38_omega::plan_reuse`]), per row. + /// Seats the request on a free row: the longest state the prompt continues among the free + /// rows (live tokens, or the copy at the last turn header) and the shared prompt cache (sc + /// L375), else the least recently used row, emptied. The single door's reuse rule + /// ([`aien_inference_abi::qwen38_omega::plan_reuse`]) per row, plus the pool. fn admit(&mut self, job: Job, active: &mut Vec) { let plen = job.prompt.len(); let fits = |s: &[u32]| !s.is_empty() && s.len() < plen && job.prompt.starts_with(s); // (index in `free`, tokens reused, from the copy) let mut best: Option<(usize, usize, bool)> = None; - for (i, &r) in self.free.iter().enumerate() { + // The merge train's `prefix_pool: false`: a cold read, nothing reused or saved. + let cold = job.test.prefix_pool == Some(false); + for (i, &r) in self.free.iter().enumerate().filter(|_| !cold) { let row = &self.rows[r]; for (s, from_snap) in [(&row.history, false), (&row.snap_tokens, true)] { if fits(s) && best.is_none_or(|(_, n, _)| s.len() > n) { @@ -968,21 +1106,52 @@ impl Scheduler { } } } - let (i, reused, from_snap) = best.unwrap_or_else(|| { - let i = (0..self.free.len()) - .min_by_key(|&i| self.rows[self.free[i]].last_used) - .expect("admit is called with a free row"); - (i, 0, false) - }); + // The pool, when it reaches further than every free row. + let from_pool = if self.pool.on() && !cold { + let hit = self + .pool + .longest(&job.prompt, plen - 1) + .filter(|&(_, n)| best.is_none_or(|(_, b, _)| n > b)); + self.pool.note_lookup(hit.is_some()); + hit + } else { + None + }; + let lru = (0..self.free.len()) + .min_by_key(|&i| self.rows[self.free[i]].last_used) + .expect("admit is called with a free row"); + let (i, mut reused, from_snap) = match (from_pool, best) { + (Some((_, n)), _) => (lru, n, false), + (None, Some(b)) => b, + (None, None) => (lru, 0, false), + }; let row = self.free.swap_remove(i); - let r = { + let mut from_pool = from_pool; + let r = if let Some((id, n)) = from_pool { + let off = job.test.prefix_mutant == Some(true); + match self.restore_from_pool(row, id, &job.prompt[..n], off) { + Ok(true) => Ok(()), + Ok(false) => { + // Refused before any write: the row reads the whole prompt cold. + from_pool = None; + reused = 0; + let rr = &mut self.rows[row]; + rr.tainted = false; + self.model.row_reset(row) + } + Err(e) => Err(e), + } + } else { let rr = &mut self.rows[row]; if from_snap { self.model .row_restore(row, &rr.snap) .map(|()| rr.history = rr.snap_tokens.clone()) } else if reused == 0 { + // The new prompt rewrites the K/V the row's own copy relies on. rr.history.clear(); + rr.snap_tokens.clear(); + rr.tainted = false; self.model.row_reset(row) } else { Ok(()) @@ -1002,13 +1171,26 @@ impl Scheduler { .iter() .rposition(|&t| t == IM_START) .filter(|&k| k > 0 && k >= reused && self.rows[row].snap_tokens[..] != job.prompt[..k]); + let cps = self.checkpoints(&job, reused); eprintln!( - "aien-serve-http: qwen36-batch: join: prompt {plen} tok, reuse {reused} tok ({}, row {row}), queued {} ms, now {} rows", - if reused == 0 { "cold" } else if from_snap { "snapshot" } else { "live" }, + "aien-serve-http: qwen36-batch: join: prompt {plen} tok, reuse {reused} tok ({}, row {row}), {} cache checkpoints, queued {} ms, now {} rows", + if from_pool.is_some() { + "prompt cache" + } else if reused == 0 { + "cold" + } else if from_snap { + "snapshot" + } else { + "live" + }, + cps.len(), job.t_queued.elapsed().as_millis(), active.len() + 1, ); let observer = SamplingObserver::new(&job.params); + if job.test.mutant.is_some_and(|m| m != 0) { + self.rows[row].tainted = true; + } let job_swap = job.test.row_swap.filter(|&k| k >= 1); let chip_greedy = self.chip_greedy && observer.is_greedy(); active.push(Active { @@ -1017,6 +1199,7 @@ impl Scheduler { fed: reused, reused, snap_at, + cps, observer, emitted: 0, logits: None, @@ -1062,6 +1245,145 @@ impl Scheduler { } } + /// Copies pool node `id` (the state after `tokens`) into `row`: the K/V pieces root first, + /// then the DeltaNet state and position. `Ok(false)`: the pool refused the node (stale tag, + /// other tokens, a K/V gap or length, a state at another position) before anything was + /// written; the caller reads the prompt cold. On an error the row's state is unknown (the + /// caller empties its bookkeeping; the next cold join resets it). `off_by_one` (the merge + /// train's `prefix_mutant`, or `AIEN_Q36_PREFIX_MUTANT` for the whole door): the gate's + /// control, the row continues one position early. + fn restore_from_pool( + &mut self, + row: usize, + id: u64, + tokens: &[u32], + off_by_one: bool, + ) -> Result { + let off_by_one = off_by_one || self.pool.mutant(); + let t = Instant::now(); + let rr = &mut self.rows[row]; + rr.history.clear(); + rr.snap_tokens.clear(); // the K/V below rewrites what the row's own copy relies on + let vals = self.model.row_kv_values(); + let rs = match self.pool.restore(id, tokens, vals) { + Ok(rs) => rs, + Err(why) => { + eprintln!( + "aien-serve-http: qwen36-batch: prompt cache restore refused ({} tok, row {row}): {why}; reading cold", + tokens.len() + ); + return Ok(false); + } + }; + let resident = rs.resident; + let mut bytes = 0usize; + for &(from, kv) in &rs.kv { + let count = kv.len().checked_div(vals).unwrap_or(0); + self.model.row_kv_write(row, from, count, kv)?; + bytes += kv.len() * 2; + } + self.model.row_restore(row, rs.snap)?; + bytes += rs.snap.host_bytes(); + if off_by_one { + self.rows[row].tainted = true; + self.model.row_set_pos(row, tokens.len() - 1)?; + } + self.rows[row].history = tokens.to_vec(); + eprintln!( + "aien-serve-http: qwen36-batch: prompt cache restore: {} tok into row {row}, {:.1} MiB in {} ms, conversation resident {:.1} MiB{}", + tokens.len(), + bytes as f64 / (1u64 << 20) as f64, + t.elapsed().as_millis(), + resident as f64 / (1u64 << 20) as f64, + if off_by_one { " (POSITION MUTANT)" } else { "" }, + ); + Ok(true) + } + + /// Where the pool saves this prompt's state on the way in (ascending, past `reused`, before + /// the last prompt token): every `every` tokens, the server's marks (tool boundaries, at + /// least `MARK_GAP` apart), the end of the first turn, the last turn header, and where the + /// prompt leaves the pool's longest match (the next prompt that changes there restores up to + /// it: coordinator 12:10Z, diff on arrival). + /// Only a row on the served path saves: none with a merge-train switch other than + /// `prefix_pool: true` (a mutant's state must never reach another conversation). + fn checkpoints(&self, job: &Job, reused: usize) -> Vec { + let mut served = job.test.clone(); + served.prefix_pool = served.prefix_pool.filter(|&on| !on); + if !self.pool.on() || !served.is_empty() { + return Vec::new(); + } + let (p, plen) = (&job.prompt, job.prompt.len()); + let every = self.pool.every(); + let mut v: Vec = (1..=plen / every).map(|k| k * every).collect(); + let mut last_mark = 0usize; + for &m in &job.marks { + if m >= last_mark + MARK_GAP { + v.push(m); + last_mark = m; + } + } + let mut heads = p + .iter() + .enumerate() + .filter(|&(k, &t)| k > 0 && t == IM_START) + .map(|(k, _)| k); + v.extend(heads.next()); // the end of the first turn + v.extend(p.iter().rposition(|&t| t == IM_START).filter(|&k| k > 0)); + v.extend(self.pool.divergence(p)); + v.retain(|&x| x > reused && x < plen); + v.sort_unstable(); + v.dedup(); + v + } + + /// Saves `row`'s state (it holds exactly `tokens`) into the pool: the K/V since the deepest + /// node `tokens` continues, the DeltaNet state and position. + fn save_checkpoint(&mut self, row: usize, tokens: &[u32]) { + if self.rows[row].tainted { + return; + } + if self.pool.touch(tokens) { + return; + } + let t = Instant::now(); + let (parent, from) = match self.pool.parent_for(tokens) { + Some((id, n)) => (Some(id), n), + None => (None, 0), + }; + let mut kv = Vec::new(); + let mut snap = S::Snap::default(); + let r = self + .model + .row_kv_read(row, from, tokens.len() - from, &mut kv) + .and_then(|()| self.model.row_snapshot(row, &mut snap)); + match r { + Ok(()) => { + let bytes = kv.len() * 2 + snap.host_bytes(); + let kept = self.pool.insert(tokens.to_vec(), parent, kv, snap); + let c = self.pool.counters(); + let (cn, cb) = self.pool.resident(tokens).unwrap_or((0, 0)); + eprintln!( + "aien-serve-http: qwen36-batch: prompt cache save: {} tok (K/V from {from}) from row {row}, {:.1} MiB in {} ms{}; conversation resident {cn} nodes {:.1} MiB; pool {} nodes {:.1} MiB of {:.1} GiB, {} evicted, {} refused", + tokens.len(), + bytes as f64 / (1u64 << 20) as f64, + t.elapsed().as_millis(), + if kept { "" } else { ", over budget, dropped" }, + cb as f64 / (1u64 << 20) as f64, + c.nodes, + c.bytes as f64 / (1u64 << 20) as f64, + self.pool.budget() as f64 / (1u64 << 30) as f64, + c.evicted, + c.refused, + ); + } + Err(e) => eprintln!( + "aien-serve-http: qwen36-batch: prompt cache save at {} tok from row {row} failed: {e}", + tokens.len() + ), + } + } + /// Samples the row's next token from its logits and emits it; `Some(reason)` when the row is /// done (the token is not fed). Mirrors the single door's loop exactly. fn sample_one(a: &mut Active, max_context: usize) -> Option { @@ -1131,6 +1453,13 @@ impl Scheduler { row.history.clear(); row.snap_tokens.clear(); } + if row.tainted { + // A test mutant left this row's state (and its copy) off its history: the next + // conversation on the row starts cold. + row.history.clear(); + row.snap_tokens.clear(); + row.tainted = false; + } let ev = match err { Some(e) => Ev::Failed(e), None => Ev::Done(GenerateOutcome { @@ -1148,3 +1477,83 @@ impl Scheduler { #[cfg(test)] mod tests; + +/// The shared prompt cache from the environment (sc L375), with its sealed store loaded (before +/// the door takes requests) when `AIEN_Q36_PREFIX_DIR` is set. A store that cannot open, or any +/// mutant or test switch, leaves the pool in memory only. Runs under the load lock (the state +/// probe reads row 0 on the chip). +fn open_pool( + ck_digest: Option>>, + model: &mut Qwen38Omega, +) -> Result, String> { + use crate::q36_prefix::{namespace, numeric_env}; + let cfg = PoolConfig::from_env()?; + let mut pool = PrefixPool::new(&cfg); + if !pool.on() { + eprintln!( + "aien-serve-http: qwen36-batch: prompt cache off (needs AIEN_Q36_PREFIX=1 and AIEN_Q36_PREFIX_POOL_GB > 0)" + ); + return Ok(pool); + } + let kv_values = model.row_kv_values(); + let mut probe = Qwen38Snapshot::default(); + model.row_snapshot(0, &mut probe)?; + let snap_bytes = probe.bytes(); + let env = numeric_env(std::env::vars()); + let lib = aien_omega_gpu::native_identity().archive_sha256; + // In memory the weights are this process's own; the tag binds the chip library, the state + // shape and the numeric switches (a node of another tag is refused at restore). + pool.bind_tag(namespace(&[0; 32], lib, kv_values, snap_bytes, &env)); + eprintln!( + "aien-serve-http: qwen36-batch: prompt cache on: budget {:.1} GiB, checkpoint every {} tok, K/V {} B per token, state {:.1} MiB per checkpoint{}", + cfg.budget as f64 / (1u64 << 30) as f64, + cfg.every, + kv_values * 2, + snap_bytes as f64 / (1u64 << 20) as f64, + if cfg.mutant { ", POSITION MUTANT" } else { "" }, + ); + let Some(sdir) = cfg.dir.as_ref() else { + return Ok(pool); + }; + let off = |why: String| { + eprintln!( + "aien-serve-http: qwen36-batch: prompt cache store {} off: {why}; the pool stays in memory", + sdir.display() + ); + }; + if cfg.mutant + || env + .iter() + .any(|(k, _)| k.contains("MUTANT") || k.contains("_TEST_")) + { + off("a mutant or test switch is set (its states are never stored)".into()); + return Ok(pool); + } + if lib.is_empty() { + off("the linked libomega_gpu.a has no sha256".into()); + return Ok(pool); + } + let key = match aien_kv_store::seal::SealKey::take_from_process_env() { + Ok(k) => k, + Err(e) => { + off(format!("{e}")); + return Ok(pool); + } + }; + let ck = match ck_digest.map(|h| h.join()) { + Some(Ok(Ok(h))) => h, + Some(Ok(Err(e))) => { + off(format!("checkpoint digest: {e}")); + return Ok(pool); + } + _ => { + off("checkpoint digest thread failed".into()); + return Ok(pool); + } + }; + let ns = namespace(&ck, lib, kv_values, snap_bytes, &env); + if let Err(e) = pool.open_store(sdir, key, ns, kv_values, |s| s.bytes() == snap_bytes) { + off(e); + } + Ok(pool) +} diff --git a/crates/aien-serve-http/src/qwen36_batch/tests.rs b/crates/aien-serve-http/src/qwen36_batch/tests.rs index ead5418f..279778f0 100644 --- a/crates/aien-serve-http/src/qwen36_batch/tests.rs +++ b/crates/aien-serve-http/src/qwen36_batch/tests.rs @@ -13,9 +13,12 @@ fn mix(mut z: u64) -> u64 { z ^ (z >> 31) } -/// A row model whose next token depends on every token fed so far and its position. +/// A row model whose next token depends on every token fed so far and its position: a running +/// state (the DeltaNet part, copied by `row_snapshot`) and one K/V value per position (copied by +/// `row_kv_read`), every one of which the next step reads, like attention. struct Fake { rows: Vec<(u64, usize)>, + kv: Vec>, /// Swap two fed rows' states once, at the first step from this one on that feeds two rows /// whose states differ (two rows seated this beat both hold the empty state, and swapping /// equal states changes nothing). @@ -32,6 +35,7 @@ impl Fake { ( Self { rows: vec![(0, 0); n], + kv: vec![vec![0; 4096]; n], swap_at, steps: 0, fed: Arc::clone(&fed), @@ -55,6 +59,33 @@ impl RowStep for Fake { fn row_count(&self) -> usize { self.rows.len() } + fn row_kv_values(&self) -> usize { + 1 + } + fn row_kv_read( + &mut self, + r: usize, + from: usize, + count: usize, + out: &mut Vec, + ) -> Result<(), String> { + *out = self.kv[r][from..from + count].to_vec(); + Ok(()) + } + fn row_kv_write( + &mut self, + r: usize, + from: usize, + count: usize, + data: &[u16], + ) -> Result<(), String> { + self.kv[r][from..from + count].copy_from_slice(data); + Ok(()) + } + fn row_set_pos(&mut self, r: usize, pos: usize) -> Result<(), String> { + self.rows[r].1 = pos; + Ok(()) + } fn row_reset(&mut self, r: usize) -> Result<(), String> { self.rows[r] = (0, 0); Ok(()) @@ -76,26 +107,37 @@ impl RowStep for Fake { if let Some((a, b)) = pair { self.swap_at = None; self.rows.swap(feed[a].row, feed[b].row); + self.kv.swap(feed[a].row, feed[b].row); } } - let mut outs = Vec::new(); - for f in feed { - let (st, pos) = &mut self.rows[f.row]; - *st = mix(*st ^ (u64::from(f.token) << 20) ^ *pos as u64); - *pos += 1; - self.fed.fetch_add(1, Ordering::SeqCst); - let logits: Vec = (0..VOCAB) - .map(|j| (mix(*st ^ j as u64) % 1_000_000) as f32) - .collect(); - // The chip's argmax follows the host greedy rule. - let token = crate::sampling::sample_next(&logits, &greedy(1), 0); - outs.push(RowOut { - token, - logits: f.logits.then_some(logits), - stats: GraphStats::default(), - }); + Ok(feed.iter().map(|f| self.step_one(f, 0)).collect()) + } +} + +impl Fake { + /// One row's step: the state folds the token, the position and every K/V value before it + /// (attention) and leaves its own K/V value; `mutant != 0` changes this row's state only. + fn step_one(&mut self, f: &RowFeed, mutant: i32) -> RowOut { + let (st, pos) = &mut self.rows[f.row]; + let kv = &mut self.kv[f.row]; + let att = kv[..*pos].iter().fold(0u64, |h, &v| mix(h ^ u64::from(v))); + *st = mix(*st ^ (u64::from(f.token) << 20) ^ *pos as u64 ^ (att << 1)); + if mutant != 0 { + *st = mix(*st ^ 0xdead_0000 ^ mutant as u64); + } + kv[*pos] = (mix(*st ^ 7) & 0xffff) as u16; + *pos += 1; + self.fed.fetch_add(1, Ordering::SeqCst); + let logits: Vec = (0..VOCAB) + .map(|j| (mix(*st ^ j as u64) % 1_000_000) as f32) + .collect(); + // The chip's argmax follows the host greedy rule. + let token = crate::sampling::sample_next(&logits, &greedy(1), 0); + RowOut { + token, + logits: f.logits.then_some(logits), + stats: GraphStats::default(), } - Ok(outs) } } @@ -300,27 +342,10 @@ fn the_graphs_greedy_token_equals_the_host_argmax_path() { /// other row's; strokes and the exact head leave the words alone (the chip's contract for them). impl Fake { fn step_rows_switched(&mut self, feed: &[RowFeed], tests: &[RowTest]) -> Vec { - let mut outs = Vec::new(); - for (i, f) in feed.iter().enumerate() { - let t = tests.get(i).copied().unwrap_or_default(); - let (st, pos) = &mut self.rows[f.row]; - *st = mix(*st ^ (u64::from(f.token) << 20) ^ *pos as u64); - if t.mutant != 0 { - *st = mix(*st ^ 0xdead_0000 ^ t.mutant as u64); - } - *pos += 1; - self.fed.fetch_add(1, Ordering::SeqCst); - let logits: Vec = (0..VOCAB) - .map(|j| (mix(*st ^ j as u64) % 1_000_000) as f32) - .collect(); - let token = crate::sampling::sample_next(&logits, &greedy(1), 0); - outs.push(RowOut { - token, - logits: f.logits.then_some(logits), - stats: GraphStats::default(), - }); - } - outs + feed.iter() + .enumerate() + .map(|(i, f)| self.step_one(f, tests.get(i).map_or(0, |t| t.mutant))) + .collect() } } @@ -341,6 +366,30 @@ impl RowStep for SwitchedFake { fn row_reset(&mut self, r: usize) -> Result<(), String> { self.0.row_reset(r) } + fn row_kv_values(&self) -> usize { + self.0.row_kv_values() + } + fn row_kv_read( + &mut self, + r: usize, + from: usize, + n: usize, + out: &mut Vec, + ) -> Result<(), String> { + self.0.row_kv_read(r, from, n, out) + } + fn row_kv_write( + &mut self, + r: usize, + from: usize, + n: usize, + data: &[u16], + ) -> Result<(), String> { + self.0.row_kv_write(r, from, n, data) + } + fn row_set_pos(&mut self, r: usize, pos: usize) -> Result<(), String> { + self.0.row_set_pos(r, pos) + } fn step_rows(&mut self, feed: &[RowFeed]) -> Result, String> { self.0.step_rows(feed) } @@ -370,7 +419,7 @@ fn switched_door(rows: usize) -> Qwen36BatchDoor { fn run_test(d: &Qwen36BatchDoor, prompt: &[u32], n: usize, t: TestSwitches) -> Vec { let mut words = Vec::new(); - d.generate_test(prompt, &greedy(n), t, &mut |tok| { + d.generate_test(prompt, &[], &greedy(n), t, &mut |tok| { words.push(tok); true }) @@ -485,6 +534,7 @@ fn no_switches_is_the_served_path_on_a_stepper_without_them() { assert_eq!(run_test(&d, &p, 5, TestSwitches::default()), alone(&p, 5)); let r = d.generate_test( &p, + &[], &greedy(5), TestSwitches { mutant: Some(4), @@ -499,7 +549,8 @@ fn no_switches_is_the_served_path_on_a_stepper_without_them() { fn the_switch_names_round_trip_from_json() { let t = TestSwitches::from_json(&serde_json::json!({ "stroke": false, "exact_head": true, "mutant": 4, "row_swap": 7, - "prefill_chunk": 128, "prefix_pool": false, "state_bf16": null + "prefill_chunk": 128, "prefix_pool": false, "prefix_mutant": true, + "state_bf16": null })) .unwrap(); assert_eq!( @@ -510,7 +561,8 @@ fn the_switch_names_round_trip_from_json() { "mutant", "row_swap", "prefill_chunk", - "prefix_pool" + "prefix_pool", + "prefix_mutant" ] ); assert!(TestSwitches::from_json(&serde_json::json!({"strokes": true})).is_err()); @@ -571,6 +623,7 @@ fn group_jobs() -> Vec { p.truncate(Q36_PREFILL_MIN - 1); p }, + marks: Vec::new(), params: greedy(n), cancel: None, test: TestSwitches::default(), @@ -842,6 +895,7 @@ fn a_reader_that_fell_behind_fails_even_when_its_done_fits() { let fell = Arc::new(AtomicBool::new(false)); let job = Job { prompt: vec![1, 2, 3], + marks: Vec::new(), params: greedy(10), out: otx, tag: 0, @@ -887,3 +941,238 @@ fn a_reader_that_fell_behind_fails_even_when_its_done_fits() { other => panic!("a truncated reply reported as {other:?}"), } } + +impl PoolSnap for (u64, usize) { + fn host_bytes(&self) -> usize { + 16 + } + fn to_bytes(&self) -> Vec { + [self.0.to_le_bytes(), (self.1 as u64).to_le_bytes()].concat() + } + fn from_bytes(b: &[u8]) -> Result { + let w = |i: usize| u64::from_le_bytes(b[i * 8..i * 8 + 8].try_into().unwrap()); + (b.len() == 16) + .then(|| (w(0), w(1) as usize)) + .ok_or_else(|| "16 bytes".to_string()) + } + fn pos(&self) -> Option { + Some(self.1) + } +} + +/// A door with the shared prompt cache (checkpoint every `every` tokens). +fn pool_door(rows: usize, every: usize, mutant: bool) -> (Qwen36BatchDoor, Arc) { + let cfg = PoolConfig::from_lookup(|k| match k { + "AIEN_Q36_PREFIX" => Some("1".into()), + "AIEN_Q36_PREFIX_EVERY" => Some(every.to_string()), + "AIEN_Q36_PREFIX_MUTANT" => mutant.then(|| "1".into()), + _ => None, + }) + .unwrap(); + let (f, fed) = Fake::new(rows, None); + let d = Qwen36BatchDoor::with_stepper_pool( + f, + 4096, + lock_file(), + Duration::from_secs(5), + 16, + true, + PrefixPool::new(&cfg), + ) + .unwrap(); + (d, fed) +} + +/// A Hermes-shaped prompt: a long shared head (the tools block and system text), then `tail`. +fn hermes(tail: u32, head: usize) -> Vec { + let mut p = vec![IM_START]; + p.extend((0..head as u32).map(|i| 3 + i % 89)); + p.push(IM_START); + p.extend([5, 6, 7, tail, tail + 1, tail + 2]); + p.push(IM_START); + p.extend([8, 9]); + p +} + +#[test] +fn a_new_chat_restores_the_shared_head_and_says_the_same_words() { + let (a, b) = (hermes(40, 120), hermes(60, 120)); + let cold = alone(&b, 12); + let (d, fed) = pool_door(2, 32, false); + let (wa, _) = run(&d, &a, &greedy(12)); + assert_eq!(wa, alone(&a, 12)); + // b shares 122 tokens with a; the pool's deepest common node is the end of the first turn. + let before = fed.load(Ordering::SeqCst); + let (wb, _) = run(&d, &b, &greedy(12)); + let fed_b = fed.load(Ordering::SeqCst) - before; + assert_eq!(wb, cold, "restored words differ from the cold read"); + assert!( + fed_b < b.len() - 100, + "the shared head was read again ({fed_b} tokens fed for a {}-token prompt)", + b.len() + ); +} + +#[test] +fn the_restore_position_mutant_is_caught() { + let (a, b) = (hermes(40, 120), hermes(60, 120)); + let cold = alone(&b, 12); + let (d, _) = pool_door(2, 32, true); + run(&d, &a, &greedy(12)); + let (wb, _) = run(&d, &b, &greedy(12)); + assert_ne!(wb, cold, "restoring one position off must change the words"); +} + +#[test] +fn a_changed_token_rereads_from_the_nearest_checkpoint_and_the_next_chat_from_the_change() { + // Chat 2 changes one token at 100 (inside the head): it restores the checkpoint at 96 and + // saves one at 100 on the way in, so chat 3 (another change at 101) restores 100. + let a = hermes(40, 200); + let mut b = a.clone(); + b[100] = 2; + let mut c = b.clone(); + c[101] = 2; + let (d, fed) = pool_door(3, 32, false); + run(&d, &a, &greedy(4)); + let n0 = fed.load(Ordering::SeqCst); + let (wb, _) = run(&d, &b, &greedy(4)); + let n1 = fed.load(Ordering::SeqCst); + assert_eq!(wb, alone(&b, 4)); + assert_eq!( + n1 - n0, + b.len() - 96 + 3, + "chat 2 should read from the checkpoint at 96" + ); + let (wc, _) = run(&d, &c, &greedy(4)); + let n2 = fed.load(Ordering::SeqCst); + assert_eq!(wc, alone(&c, 4)); + assert_eq!( + n2 - n1, + c.len() - 100 + 3, + "chat 3 should read from the change at 100" + ); +} + +#[test] +fn a_cold_prompt_on_a_row_voids_the_rows_own_header_copy() { + // One row: a (with turn headers) leaves its own copy at its last header; b (no header past + // 0, so no new copy) rewrites the row's K/V from 0; a continued must not restore a's copy + // over b's K/V. + let a = hermes(40, 30); + let b: Vec = (0..80).map(|i| 1 + (i * 7) % 90).collect(); + let mut a2 = a[..a.len() - 2].to_vec(); + a2.extend([11, 12, IM_START, 13]); + let (d, _) = door(1, None, 16); + run(&d, &a, &greedy(4)); + run(&d, &b, &greedy(4)); + let (w, _) = run(&d, &a2, &greedy(6)); + assert_eq!(w, alone(&a2, 6)); +} + +#[test] +fn prefix_pool_off_reads_the_whole_prompt_cold() { + // The merge train's reference: `prefix_pool: false` reuses nothing, the pool on the next. + let (a, b) = (hermes(40, 120), hermes(60, 120)); + let (d, fed) = pool_door(2, 32, false); + run(&d, &a, &greedy(6)); + let off = TestSwitches { + prefix_pool: Some(false), + ..TestSwitches::default() + }; + let n0 = fed.load(Ordering::SeqCst); + let w_off = run_test(&d, &b, 6, off); + let n1 = fed.load(Ordering::SeqCst); + assert_eq!(w_off, alone(&b, 6)); + assert_eq!(n1 - n0, b.len() + 5, "a cold read feeds every prompt token"); + let mut b2 = hermes(80, 120); + b2.push(9); + let (w_on, _) = run(&d, &b2, &greedy(6)); + assert_eq!(w_on, alone(&b2, 6)); + assert!(fed.load(Ordering::SeqCst) - n1 < b2.len() - 100); +} + +#[test] +fn prefix_mutant_goes_red_and_poisons_nothing() { + // One row: chat a fills the pool; b restores one position off (red); b's next turn on the + // same row must not continue the mutant's state, and the pool must hold none of it. + let (a, b) = (hermes(40, 120), hermes(60, 120)); + let (d, _) = pool_door(1, 32, false); + run(&d, &a, &greedy(6)); + let mutant = TestSwitches { + prefix_mutant: Some(true), + ..TestSwitches::default() + }; + let wb = run_test(&d, &b, 6, mutant); + assert_ne!( + wb, + alone(&b, 6), + "restoring one position off must change the words" + ); + let mut b2 = b.clone(); + b2.extend(&wb[..5]); + b2.extend([IM_START, 8, 9, 10]); + let (w2, _) = run(&d, &b2, &greedy(6)); + assert_eq!( + w2, + alone(&b2, 6), + "the mutant's row or checkpoints were reused" + ); +} + +#[test] +fn a_graph_mutant_row_starts_its_next_conversation_cold() { + // L384's `mutant` switch leaves the row's state off its history; the next turn must not + // continue it. + let d = switched_door(1); + let p = hermes(40, 60); + let w = run_test( + &d, + &p, + 6, + TestSwitches { + mutant: Some(4), + ..TestSwitches::default() + }, + ); + let mut p2 = p.clone(); + p2.extend(&w[..5]); + p2.extend([IM_START, 8, 9, 10]); + assert_eq!(run_test(&d, &p2, 6, TestSwitches::default()), alone(&p2, 6)); +} + +// ---- DRA-86: a refused pool node is read cold, never restored ---- + +/// A one-row door whose pool already holds a spoiled node for `b[..n]`: `kv_len` K/V values, +/// a state that is not `b`'s, saved under tag 0 and then bound to `tag`. `unchecked`: the +/// base's restore without the refusal checks (the negative control). +fn spoiled_door(b: &[u32], n: usize, kv_len: usize, tag: [u8; 32], unchecked: bool) -> Qwen36BatchDoor { + let cfg = PoolConfig::from_lookup(|k| (k == "AIEN_Q36_PREFIX").then(|| "1".into())).unwrap(); + let mut pool = PrefixPool::new(&cfg); + assert!(pool.insert(b[..n].to_vec(), None, vec![7; kv_len], (0xdead_beef, n))); + pool.bind_tag(tag); + pool.set_unchecked(unchecked); + let (f, _) = Fake::new(1, None); + Qwen36BatchDoor::with_stepper_pool( + f, + 4096, + lock_file(), + Duration::from_secs(5), + 16, + true, + pool, + ) + .unwrap() +} + +#[test] +fn a_stale_or_short_pool_node_is_refused_and_the_prompt_read_cold() { + let b = hermes(60, 120); + let cold = alone(&b, 12); + // Another model/lib tag; then a K/V piece one position short under the pool's own tag. + for (what, kv_len, tag) in [("stale tag", 100, [9; 32]), ("K/V length", 99, [0; 32])] { + let (w, _) = run(&spoiled_door(&b, 100, kv_len, tag, false), &b, &greedy(12)); + assert_eq!(w, cold, "{what}: the refused node was not read cold"); + let (w, _) = run(&spoiled_door(&b, 100, kv_len, tag, true), &b, &greedy(12)); + assert_ne!(w, cold, "{what}: the unchecked base should restore the spoiled node"); + } +} diff --git a/crates/aien-serve-http/src/server.rs b/crates/aien-serve-http/src/server.rs index 2483cac1..e7bd867a 100644 --- a/crates/aien-serve-http/src/server.rs +++ b/crates/aien-serve-http/src/server.rs @@ -106,6 +106,8 @@ pub struct AppState { allowed_hosts: [String; 3], started: Instant, counter: AtomicU64, + /// Stable-first tool order and tool boundary marks for the door's prompt cache (sc L375). + tool_cache: crate::tool_cache::ToolCache, } /// An OpenAI-shaped error with its HTTP status. @@ -228,6 +230,8 @@ impl IntoResponse for ApiError { struct Prepared { prompt_tokens: Vec, + /// Prompt cache checkpoint hints (tool boundaries) for the engine. + marks: Vec, params: GenerateParams, stop_strings: Vec, stream: bool, @@ -318,7 +322,9 @@ pub async fn serve_until( let listener = tokio::net::TcpListener::bind(SocketAddr::new(cfg.bind, cfg.port)).await?; let addr = listener.local_addr()?; let gate = Arc::new(Semaphore::new(engine.concurrency().max(1))); + let tool_cache = crate::tool_cache::ToolCache::for_engine(engine.kind()); let state = Arc::new(AppState { + tool_cache, engine, codec, cfg, @@ -749,6 +755,7 @@ fn run_readers( .iter() .map(|p| crate::engine::GroupJob { prompt: p.prompt_tokens.clone(), + marks: p.marks.clone(), params: p.params.clone(), cancel: Some(Arc::clone(&cancel)), test: p.test.clone(), @@ -976,6 +983,7 @@ fn prepare(state: &AppState, req: ChatRequest) -> Result { .collect(), _ => Vec::new(), }; + let tool_defs = state.tool_cache.arrange(tool_defs); let has_tools = !tool_defs.is_empty(); if req.messages.is_empty() { return Err(ApiError::bad_request("messages must be a non-empty array")); @@ -1057,6 +1065,13 @@ fn prepare(state: &AppState, req: ChatRequest) -> Result { if prompt_tokens.is_empty() { return Err(ApiError::bad_request("the rendered prompt is empty")); } + let marks = if has_tools { + state + .tool_cache + .marks(&*state.codec, &prompt_text, &tool_defs, &prompt_tokens) + } else { + Vec::new() + }; let ctx = cfg .max_context_tokens @@ -1126,6 +1141,7 @@ fn prepare(state: &AppState, req: ChatRequest) -> Result { Ok(Prepared { prompt_tokens, + marks, params: GenerateParams { max_new_tokens, temperature, @@ -1241,8 +1257,9 @@ fn run_generation( let mut stopped_by_string = false; let mut client_gone = false; let test_report = (!prepared.test.is_empty()).then(|| prepared.test.names()); - let result = engine.generate_with_test( + let result = engine.generate_marked( &prepared.prompt_tokens, + &prepared.marks, &prepared.params, &prepared.test, &mut |tok| { diff --git a/crates/aien-serve-http/src/tool_cache.rs b/crates/aien-serve-http/src/tool_cache.rs new file mode 100644 index 00000000..7dd04e2c --- /dev/null +++ b/crates/aien-serve-http/src/tool_cache.rs @@ -0,0 +1,312 @@ +//! The server's half of the 35B door's shared prompt cache (sc L375, coordinator 12:10Z). +//! +//! - **Stable-first tool order.** Hermes sends the same ~11k tokens of tool definitions with +//! every chat. The door restores the longest token prefix it has already read, so the server +//! renders the tools in a remembered order: tools whose definition is unchanged keep their +//! remembered place, a changed or new tool goes to the end. One changed tool then costs only +//! the tools after its old place once, and itself (plus what follows the block) after that. +//! The order (names and definition digests only) lives in `tool-order.json` in +//! `AIEN_Q36_PREFIX_DIR` when set, so it survives restarts with the pool it matches. +//! - **Tool boundary marks.** The token positions right after each tool line, handed to the door +//! ([`crate::engine::Engine::generate_marked`]) as checkpoint hints. A mark is kept only when +//! the encoded text up to it is exactly a prefix of the prompt's tokens; marks are cached per +//! rendered head, so a repeated tools block is encoded once. +//! +//! On only for the batch door (`omega-qwen36-batch`) with `AIEN_SERVE_TOOL_ORDER` not `0`. +use std::collections::HashMap; +use std::io::Write; +use std::os::unix::fs::OpenOptionsExt; +use std::path::PathBuf; +use std::sync::Mutex; + +use serde_json::Value; +use sha2::{Digest, Sha256}; + +use crate::codec::Codec; + +/// Rendered tools blocks whose marks are kept. +const MARK_CACHE: usize = 8; + +#[derive(Default)] +struct Inner { + /// Remembered order: (tool name, definition digest). + order: Vec<(String, String)>, + /// Marks per digest of the rendered text up to the end of the tools block. + marks: HashMap<[u8; 32], (u64, Vec)>, + clock: u64, +} + +pub struct ToolCache { + on: bool, + file: Option, + inner: Mutex, +} + +fn tool_name(t: &Value) -> Option<&str> { + t.get("function") + .and_then(|f| f.get("name")) + .or_else(|| t.get("name")) + .and_then(Value::as_str) +} + +fn digest(t: &Value) -> String { + Sha256::digest(crate::tools::tojson(t).as_bytes()) + .iter() + .map(|b| format!("{b:02x}")) + .collect() +} + +impl ToolCache { + /// For an engine of `kind`: on for the batch door unless `AIEN_SERVE_TOOL_ORDER=0`; the + /// remembered order is read from `AIEN_Q36_PREFIX_DIR/tool-order.json` when there. + pub fn for_engine(kind: &str) -> Self { + let on = kind == "omega-qwen36-batch" + && std::env::var("AIEN_SERVE_TOOL_ORDER").as_deref() != Ok("0"); + let file = std::env::var_os("AIEN_Q36_PREFIX_DIR") + .filter(|_| on) + .map(|d| PathBuf::from(d).join("tool-order.json")); + let order = file + .as_ref() + .and_then(|f| std::fs::read(f).ok()) + .and_then(|b| serde_json::from_slice::>(&b).ok()) + .unwrap_or_default(); + Self { + on, + file, + inner: Mutex::new(Inner { + order, + ..Inner::default() + }), + } + } + + /// Off: tools render in request order and no marks are made. + pub fn off() -> Self { + Self { + on: false, + file: None, + inner: Mutex::new(Inner::default()), + } + } + + /// The request's tools in the stable-first order (see the module doc); the remembered order + /// is updated (and saved) when the request changed it. Unchanged when off, or when a tool has + /// no name or two tools share one. + pub fn arrange(&self, tools: Vec) -> Vec { + if !self.on || tools.len() < 2 { + return tools; + } + let keys: Option> = tools + .iter() + .map(|t| tool_name(t).map(|n| (n.to_string(), digest(t)))) + .collect(); + let Some(keys) = keys else { return tools }; + let mut names: Vec<&str> = keys.iter().map(|(n, _)| n.as_str()).collect(); + names.sort_unstable(); + if names.windows(2).any(|w| w[0] == w[1]) { + return tools; + } + let Ok(mut g) = self.inner.lock() else { + return tools; + }; + let place = |k: &(String, String)| g.order.iter().position(|o| o == k); + let mut kept: Vec<(usize, usize)> = Vec::new(); // (remembered place, request index) + let mut moved: Vec = Vec::new(); + for (i, k) in keys.iter().enumerate() { + match place(k) { + Some(p) => kept.push((p, i)), + None => moved.push(i), + } + } + kept.sort_unstable(); + let idx: Vec = kept + .iter() + .map(|&(_, i)| i) + .chain(moved.iter().copied()) + .collect(); + if !moved.is_empty() { + let changed: Vec<&str> = moved.iter().map(|&i| keys[i].0.as_str()).collect(); + g.order.retain(|(n, _)| !changed.contains(&n.as_str())); + g.order.extend(moved.iter().map(|&i| keys[i].clone())); + if let Some(f) = &self.file { + if let Err(e) = save(f, &g.order) { + eprintln!( + "aien-serve-http: tool order: saving {} failed: {e}", + f.display() + ); + } + } + eprintln!( + "aien-serve-http: tool order: {} of {} tools new or changed, moved to the end: {}", + moved.len(), + tools.len(), + changed.join(", ") + ); + } + drop(g); + let mut slots: Vec> = tools.into_iter().map(Some).collect(); + idx.into_iter().filter_map(|i| slots[i].take()).collect() + } + + /// Token positions of `tokens` (the encoded `text`) right after each tool line of the tools + /// block (`tools` as rendered, in order); only positions where the encoded text up to the + /// boundary is exactly a prefix of `tokens`. + pub fn marks( + &self, + codec: &dyn Codec, + text: &str, + tools: &[Value], + tokens: &[u32], + ) -> Vec { + if !self.on || tools.is_empty() { + return Vec::new(); + } + // Boundaries: just after the "\n" before each tool line and before "". + let Some(mut at) = text.find("").map(|k| k + "".len()) else { + return Vec::new(); + }; + let mut cuts = Vec::with_capacity(tools.len() + 1); + for t in tools { + let line = format!("\n{}", crate::tools::tojson(t)); + match text[at..].find(&line) { + Some(0) => { + cuts.push(at + 1); + at += line.len(); + } + _ => return Vec::new(), + } + } + if !text[at..].starts_with("\n") { + return Vec::new(); + } + cuts.push(at + 1); + let key: [u8; 32] = Sha256::digest(&text.as_bytes()[..at]).into(); + let Ok(mut g) = self.inner.lock() else { + return Vec::new(); + }; + g.clock += 1; + let c = g.clock; + if let Some((used, m)) = g.marks.get_mut(&key) { + *used = c; + return m.clone(); + } + drop(g); + let marks: Vec = cuts + .iter() + .filter_map(|&b| { + let t = codec.encode(&text[..b]).ok()?; + tokens.starts_with(&t).then_some(t.len()) + }) + .collect(); + if let Ok(mut g) = self.inner.lock() { + if g.marks.len() >= MARK_CACHE { + if let Some(old) = g.marks.iter().min_by_key(|(_, (u, _))| *u).map(|(k, _)| *k) { + g.marks.remove(&old); + } + } + g.marks.insert(key, (c, marks.clone())); + } + eprintln!( + "aien-serve-http: tool marks: {} of {} boundaries exact", + marks.len(), + cuts.len() + ); + marks + } +} + +fn save(f: &std::path::Path, order: &[(String, String)]) -> std::io::Result<()> { + let tmp = f.with_extension("json.tmp"); + let mut o = std::fs::OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(0o600) + .open(&tmp)?; + o.write_all(&serde_json::to_vec(order).map_err(std::io::Error::other)?)?; + o.sync_all()?; + std::fs::rename(tmp, f) +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn on() -> ToolCache { + ToolCache { + on: true, + file: None, + inner: Mutex::new(Inner::default()), + } + } + + fn t(name: &str, d: &str) -> Value { + json!({"type": "function", "function": {"name": name, "description": d}}) + } + + fn names(v: &[Value]) -> Vec<&str> { + v.iter().map(|x| tool_name(x).unwrap()).collect() + } + + #[test] + fn a_changed_tool_moves_to_the_end_and_the_rest_keep_their_place() { + let c = on(); + let first = c.arrange(vec![t("a", "1"), t("b", "1"), t("c", "1")]); + assert_eq!(names(&first), ["a", "b", "c"]); + // Another client order: the remembered one wins. + let again = c.arrange(vec![t("c", "1"), t("a", "1"), t("b", "1")]); + assert_eq!(names(&again), ["a", "b", "c"]); + // b changes: it goes last, and stays last while unchanged. + let changed = c.arrange(vec![t("a", "1"), t("b", "2"), t("c", "1")]); + assert_eq!(names(&changed), ["a", "c", "b"]); + let next = c.arrange(vec![t("a", "1"), t("b", "2"), t("c", "1"), t("d", "1")]); + assert_eq!(names(&next), ["a", "c", "b", "d"]); + // A tool missing from one request keeps its place for the next. + let without = c.arrange(vec![t("b", "2"), t("a", "1")]); + assert_eq!(names(&without), ["a", "b"]); + let back = c.arrange(vec![t("d", "1"), t("c", "1"), t("a", "1"), t("b", "2")]); + assert_eq!(names(&back), ["a", "c", "b", "d"]); + } + + #[test] + fn off_or_duplicate_names_keep_the_request_order() { + let v = vec![t("b", "1"), t("a", "1")]; + assert_eq!(names(&ToolCache::off().arrange(v.clone())), ["b", "a"]); + let c = on(); + c.arrange(vec![t("a", "1"), t("b", "1")]); + let dup = vec![t("b", "1"), t("a", "1"), t("a", "2")]; + assert_eq!(names(&c.arrange(dup)), ["b", "a", "a"]); + } + + /// A codec whose tokens are the text's characters. + struct Chars; + impl Codec for Chars { + fn render_chat(&self, _: &[(&str, &str)]) -> Result { + Ok(String::new()) + } + fn stop_token_ids(&self) -> Vec { + Vec::new() + } + fn encode(&self, text: &str) -> Result, crate::codec::CodecError> { + Ok(text.chars().map(u32::from).collect()) + } + fn decode(&self, ids: &[u32]) -> Result { + Ok(ids.iter().filter_map(|&i| char::from_u32(i)).collect()) + } + } + + #[test] + fn marks_sit_right_after_each_tool_line() { + let tools = vec![t("a", "1"), t("b", "22")]; + let sys = crate::tools::system_with_tools(&tools, Some("be brief")); + let text = format!("<|im_start|>system\n{sys}<|im_end|>\n"); + let tokens = Chars.encode(&text).unwrap(); + let m = on().marks(&Chars, &text, &tools, &tokens); + assert_eq!(m.len(), 3); + let open = text.find("").unwrap() + "\n".len(); + assert_eq!(m[0], open); + assert!(text[..m[1]].ends_with("}\n") && text[m[1]..].starts_with('{')); + assert!(text[m[2]..].starts_with("")); + } +} diff --git a/docs/MERGE_TRAIN.md b/docs/MERGE_TRAIN.md index d97d0d72..4e6d9ad9 100644 --- a/docs/MERGE_TRAIN.md +++ b/docs/MERGE_TRAIN.md @@ -33,7 +33,9 @@ A test build (`cargo build --release -p aien-serve-http --features aien-test-swi | `exact_head` | `false`: the plain one-pass head instead of the exact two-pass head | `true` | | `mutant` | graph mutant `k` (the `AIEN_Q36_TEST_MUTANT` numbers) for this row's steps | `0` | | `row_swap` | at this row's `k`-th step the scheduler trades rows with another decoding conversation (both go red) | off | -| `prefill_chunk`, `prefix_pool`, `state_bf16` | names reserved for L369, L375, L313; refused until their lever wires them | | +| `prefix_pool` | L375 shared prompt cache. `false`: this prompt is read cold (no pool, no row reuse, nothing saved to the pool), the reference the cache must match | `true` | +| `prefix_mutant` | L375 red control: a restore from the pool lands one position early for this row. The row saves nothing and its next conversation starts cold | off | +| `prefill_chunk`, `state_bf16` | names reserved for L369, L313; refused until their lever wires them | | Honesty rules, enforced in code: diff --git a/evidence/dra86-prefix-20261031/README.md b/evidence/dra86-prefix-20261031/README.md new file mode 100644 index 00000000..ea235e42 --- /dev/null +++ b/evidence/dra86-prefix-20261031/README.md @@ -0,0 +1,57 @@ +# DRA-86: prompt cache for the 35B batch door (G4), 2026-10-31 + +Status: IMPLEMENTED and EXERCISED on host (cargo tests, mock door). Chip: NOT_RUN. Nothing here has run on the GB10. + +## What the gate checks (G4) + +| G4 item | step | judged by | +|---|---|---| +| switch default off | 1 `ref` | the door logs `prompt cache off (needs AIEN_Q36_PREFIX=1 …)` without the switch | +| red first | 2 `red` | `AIEN_Q36_PREFIX_MUTANT=1` (a restored row continues one position early) must change at least one turn 2 | +| token identity, set32 + l369-long | 3 `green` | 35 conversations x 2 turns all SAME vs step 1; every turn 2 restored, none refused; `budget 16.0 GiB` | +| stale snapshot refused (model/bin/env) | 4a/4b/4c | sealed store: 4b reloads and restores, 4c (another numeric env key = another namespace) discards every node and reads cold, SAME | +| budget enforced, resident bytes reported | 5 `budget` | `AIEN_Q36_PREFIX_POOL_GB=0.5`: every save line carries `conversation resident … MiB`, pool <= 512 MiB, evictions > 0, SAME | +| turn-2 TTFT 32k cached + 1k new | 6a `warm`, 6b `cold` | HTTP TTFT (client, first content delta) and the door's restore ms and prefill ms; RECORDED, compared with the model below | + +Off-by-one turn, token mismatch, KV gap, KV/state length mismatch and model/lib tag: refused inside the pool before any +write (`crates/aien-serve-http/src/q36_prefix/tests.rs`: `a_node_restored_as_other_tokens_or_one_turn_off_is_refused`, +`a_kv_gap_or_a_kv_or_state_length_mismatch_is_refused`, `a_node_of_another_model_or_lib_tag_is_refused_and_dropped`; +door level `a_stale_or_short_pool_node_is_refused_and_the_prompt_read_cold`). A chip run cannot provoke them from +outside, so the chip gate covers the namespace and the mutant, and the host tests cover the rest. Shape refusal for the +device copy is in the CUDApp module (`src/omega_gpu_q36_prefix.c`, `tests/gpu_q36_prefix_test.c`). + +## Files + +- `window-dra86.sh`: `plan`, `run BIN OUT STEP…` (lock, lease, watchdog, receipts; from window-dra65.sh), probes `conv`, `time`. +- `set32.json` (copy of evidence/dra65-prefill-20261031/set32.json), `SHA256SUMS` (it plus l369 long-256/2048/8192). +- `hosttest/`: `mock86.py` (mock batch door with the door's log wording), `fake-serve.sh`, `runtests.sh`. + +Host check: `nice -n 19 taskset -c 5 bash evidence/dra86-prefix-20261031/hosttest/runtests.sh` -> 13 `ok`, +`runtests: 0 failed` (plan; no window NOT_RUN; all 9 steps PASS on the exact mock; store key reaches 4a/4b/4c, one key, +in no receipt; red without effect FAIL; green after a failed red NOT_RUN; red without restore INCONCLUSIVE; green +without restore FAIL; stale namespace loaded FAIL; 4b alone NOT_RUN; green on an empty OUT NOT_RUN; budget probe at +16 GiB FAIL; no leftover process; lock free). + +## Model (MODELED, WolframLanguageEvaluator) + +Bytes per conversation (10 attention layers, K+V bf16, 2 x 512 per layer; 30 DeltaNet layers, state 2 MiB + conv tail 192 KiB): + +- `kv = 10*2*2*32768*512; st = 30*2097152; tl = 30*196608; {kv, st, tl, kv+st+tl, N[(kv+st+tl)/2^20], Floor[16*2^30/(kv+st+tl)], 2*2*512*10}` + -> `{671088640, 62914560, 5898240, 739901440, 705.625, 23, 20480}` + (32k-token conversation 739,901,440 B = 705.6 MiB; 23 such in the 16 GiB default; K/V 20,480 B per token.) + +Turn-2 TTFT (QMMA peak 237.5 TFLOPS, 4.87 GFLOP per token, attention 163,840 FLOP per (q,k) pair, bandwidth 273 GB/s, +33.6 GB weight pass overlapped with the GEMMs, 1,024 new tokens after 32,768 cached, restore = 2 x blob / bandwidth, +`e` = fraction of QMMA peak the prefill reaches): + +- `peak = 237.5*10^12; bw = 273*10^9; f = 4.87*10^9; a = 163840; n = 1024; c = 32768; w = 33.6*10^9; snap = 739901440; gemm = n f/peak; pairs = n c + n (n + 1)/2; attn = pairs a/peak; wt = w/bw; rst = 2 snap/bw; t2[e_] := Max[gemm/e, wt] + attn/e + rst; m = n + c; cold = m f/peak + (m (m + 1)/2) a/peak; {gemm, pairs, attn, wt, rst, t2[1], cold, snap + 20480 n, FindRoot[t2[e] == 0.4, {e, 0.2}], t2[0.3]}` + -> `{0.02099738947368421, 34079232, 0.02350964787738947, 0.12307692307692307, 578048/106640625, 0.15200709432427592, 1.0867966145158738, 760872960, {e -> 0.11279612850417702}, 0.20686293937151803}` +- warm turn 2 0.152 s at peak (restore 5.4 ms), cold 33k prompt 1.087 s, 760,872,960 B per conversation incl. the + 1k turn; G4's 0.4 s holds above 11.3 % of QMMA peak; 0.207 s at 30 %. +- Not met by today's prefill: the batch door's measured chunked prefill is ~250 tok/s, so 1,024 new tokens alone + take ~4 s. G4's 0.4 s needs DRA-82's tensor-core prefill; step 6 records the split (restore ms, prefill ms). + +Step estimates (s): `start=60; dec=0.0201; pf=250; pfl=120; t1set=756*dec+874*dec; t2setCold=(756+874+32*12)*dec+32*16*dec; t2setWarm=(32*12)*dec+32*16*dec+32*0.5; t1long=(256+2486+8210)/pf+72*dec; t2longCold=(256+2486+8210+72+36)/pf+48*dec; t2longWarm=(36)*dec+48*dec+3*0.5; ref=start+t1set+t2setCold+t1long+t2longCold; green=start+t1set+t2setWarm+t1long+t2longWarm; st4a=start+2486/pf+24*dec+20; st4=start+2486/pf+24*dec+(2486+60)/pf+16*dec; budget=start+3*((256+2486+8210)/3/pf)+2*(10952/pf)+200*dec; c=32840; n=1050; warm=start+c/pfl+16*dec+3*(1+n/pf+16*dec); cold=start+c/pfl+16*dec+(c+n)/pfl+16*dec; N[{ref,green,st4a,st4,budget,warm,cold}]` +-> `{233.9956, 175.2162, 90.4264, 80.932, 195.444, 350.553, 616.727}`; the script rounds up to 240/180/180/95/85/85/200/355/620. +Assumptions: batch server start 60 s; decode 0.0201 s/token (short set32 prompts stepped at the same rate); long +prompts 250 tok/s; the ~32.8k prompt a deliberately slow 120 tok/s; restore 0.5 s per turn 2; store flush 20 s. diff --git a/evidence/dra86-prefix-20261031/SHA256SUMS b/evidence/dra86-prefix-20261031/SHA256SUMS new file mode 100644 index 00000000..0cf1ec9e --- /dev/null +++ b/evidence/dra86-prefix-20261031/SHA256SUMS @@ -0,0 +1,4 @@ +d0bcb237803b0299d0a45ceb3bf1660628a369d286fcd82da617a7a31d5f2941 evidence/dra86-prefix-20261031/set32.json +153a5f88932393b2be56fd81f8914d44218169c614ebc5b2753069c9a09bc3a1 evidence/merge-train/l369/long-256.txt +26a44c508412e213de876eb54bb90390426b086c887a68b90fa78f7470425ee3 evidence/merge-train/l369/long-2048.txt +2bcc84b25c418cba83df9546344fd4ae28962c314e03defe2aab62a8e6c8abb9 evidence/merge-train/l369/long-8192.txt diff --git a/evidence/dra86-prefix-20261031/hosttest/fake-serve.sh b/evidence/dra86-prefix-20261031/hosttest/fake-serve.sh new file mode 100755 index 00000000..6033636a --- /dev/null +++ b/evidence/dra86-prefix-20261031/hosttest/fake-serve.sh @@ -0,0 +1,8 @@ +#!/usr/bin/env bash +# dra86 mock door for the host check of window-dra86.sh run (never the real server): takes the server's flags, +# keeps --port, and serves mock86.py with this process's environment (the step's server env). +port=; while [ $# -gt 0 ]; do [ "$1" = --port ] && port=$2; shift; done +echo "fake-serve pid $$ sid $(ps -o sid= -p $$ | tr -d " ") MOCK_M=${MOCK_M:-exact} key_len=${#AIEN_KV_STORE_KEY} lock_fds=$(ls -l /proc/$$/fd | grep -c "$(basename "$DRA86_TEST_LOCK")")" >&2 +# The store key the door received goes to a test-only file outside the receipts (runtests.sh greps the receipts for it). +[ -n "${AIEN_KV_STORE_KEY:-}" ] && [ -n "${DRA86_KEYSEEN:-}" ] && echo "$AIEN_KV_STORE_KEY" >> "$DRA86_KEYSEEN" +exec python3 "$(dirname "$0")/mock86.py" "$port" diff --git a/evidence/dra86-prefix-20261031/hosttest/mock86.py b/evidence/dra86-prefix-20261031/hosttest/mock86.py new file mode 100644 index 00000000..2115b663 --- /dev/null +++ b/evidence/dra86-prefix-20261031/hosttest/mock86.py @@ -0,0 +1,70 @@ +# dra86 mock batch door (host check of window-dra86.sh only, never the chip): greedy ids are a hash of the +# messages; the prompt cache is modelled from the door's env and log wording (qwen36_batch.rs, q36_prefix.rs). +# MOCK_M: exact | nomut (the position mutant changes nothing) | norestore (turn 2 never restored) | +# ignore_ns (the store loads nodes of another namespace) +import hashlib, json, os, sys, time, http.server +E = os.environ; M = E.get('MOCK_M', 'exact') +ON = E.get('AIEN_Q36_PREFIX') == '1'; MUT = E.get('AIEN_Q36_PREFIX_MUTANT') == '1' +GB = float(E.get('AIEN_Q36_PREFIX_POOL_GB', '16')); BUDGET = GB * 1024 +NS = hashlib.sha256(json.dumps(sorted((k, v) for k, v in E.items() if (k.startswith('AIEN_Q36_') or k.startswith('AIEN_OMEGA_')) + and (not k.startswith('AIEN_Q36_PREFIX_') or k == 'AIEN_Q36_PREFIX_MUTANT'))).encode()).hexdigest()[:16] +DIR = E.get('AIEN_Q36_PREFIX_DIR'); KEY = E.pop('AIEN_KV_STORE_KEY', None) +def say(s): sys.stderr.write('aien-serve-http: qwen36-batch: ' + s + '\n'); sys.stderr.flush() +pool = [] # [conversation key, MiB] +def kv_mib(tok): return tok * 20480 / 2**20 +def total(): return sum(m for _, m in pool) +if not ON or GB <= 0: + say('prompt cache off (needs AIEN_Q36_PREFIX=1 and AIEN_Q36_PREFIX_POOL_GB > 0)') +else: + say('prompt cache on: budget %.1f GiB, checkpoint every 2048 tok, K/V 20480 B per token, state 65.6 MiB per checkpoint%s' + % (GB, ', POSITION MUTANT' if MUT else '')) + if DIR: + if MUT: say('prompt cache store %s off: a mutant or test switch is set (its states are never stored); the pool stays in memory' % DIR) + elif KEY is None or len(KEY) != 64: say('prompt cache store %s off: key missing; the pool stays in memory' % DIR) + else: + ld = dc = 0 + for f in sorted(os.listdir(DIR)): + if not f.endswith('.q36p'): continue + ns, key, m = open(os.path.join(DIR, f)).read().split('\t') + if ns == NS or M == 'ignore_ns': pool.append([key, float(m)]); ld += 1 + else: + sys.stderr.write('aien-serve-http: q36 prefix: discarding %s: another namespace\n' % f); os.remove(os.path.join(DIR, f)); dc += 1 + sys.stderr.write('aien-serve-http: q36 prefix: store %s open: %d nodes loaded (%.1f MiB), %d discarded, in 0.0 s\n' % (DIR, ld, total(), dc)) + sys.stderr.flush() +evicted = 0 +def ntok(msgs): return sum(max(1, len(m['content']) // 4) for m in msgs) + 4 * len(msgs) + 3 +def save(key, tok): + global evicted + nodes = max(1, tok // 2048) + 1; per = 65.6 + kv_mib(tok) / nodes + for i in range(nodes): + pool.append([key, per]) + while total() > BUDGET and len(pool) > 1: pool.pop(0); evicted += 1 + res = sum(m for k, m in pool if k == key); rn = sum(1 for k, _ in pool if k == key) + say('prompt cache save: %d tok (K/V from %d) from row 0, %.1f MiB in 2 ms; conversation resident %d nodes %.1f MiB; pool %d nodes %.1f MiB of %.1f GiB, %d evicted, 0 refused' + % ((i + 1) * tok // nodes, i * tok // nodes, per, rn, res, len(pool), total(), GB, evicted)) + if DIR and KEY and not MUT: + open(os.path.join(DIR, '%s-%d.q36p' % (hashlib.sha256(key.encode()).hexdigest()[:16], i)), 'w').write('%s\t%s\t%f' % (NS, key, per)) +class H(http.server.BaseHTTPRequestHandler): + def log_message(s, *a): pass + def out(s, code, b, ct='application/json'): + s.send_response(code); s.send_header('Content-Type', ct); s.send_header('Content-Length', str(len(b))); s.end_headers(); s.wfile.write(b) + def do_GET(s): s.out(200, json.dumps({'data': [{'id': 'mock86'}]}).encode()) + def do_POST(s): + q = json.loads(s.rfile.read(int(s.headers['Content-Length']))); msgs = q['messages']; n = q['max_tokens'] + h = hashlib.sha256(json.dumps(msgs).encode()).digest(); ids = [h[i % 32] + 256 * i for i in range(n)] + key = msgs[0]['content']; tok = ntok(msgs); reuse = 0; t0 = time.time() + if len(msgs) == 3 and ON and GB > 0 and M != 'norestore' and any(k == key for k, _ in pool): + reuse = ntok(msgs[:2]); res = sum(m for k, m in pool if k == key) + say('prompt cache restore: %d tok into row 0, %.1f MiB in 3 ms, conversation resident %.1f MiB%s' % (reuse, res, res, ' (POSITION MUTANT)' if MUT else '')) + if MUT and M != 'nomut': ids[min(2, n - 1)] += 1 + say('join: prompt %d tok, reuse %d tok (%s, row 0), 0 cache checkpoints, queued 0 ms, now 1 rows' % (tok, reuse, 'prompt cache' if reuse else 'cold')) + if ON and GB > 0 and len(msgs) == 1: save(key, tok) + say('leave: row 0, prompt %d tok (reused %d), prefill %d ms, decode %d tok in 1 ms over %d beats, mean rows 1.00, wall 1.0 ms/token, Stop' + % (tok, reuse, int((time.time() - t0) * 1000) + 1, n, n)) + text = 'answer %s' % h.hex()[:12] + if q.get('stream'): + ev = [{'choices': [{'delta': {'content': text}}]}, {'choices': [], 'usage': {'prompt_tokens': tok, 'completion_tokens': n}}] + return s.out(200, (''.join('data: ' + json.dumps(e) + '\n\n' for e in ev) + 'data: [DONE]\n\n').encode(), 'text/event-stream') + s.out(200, json.dumps({'choices': [{'message': {'content': text}, 'finish_reason': 'stop'}], + 'usage': {'prompt_tokens': tok, 'completion_tokens': n, 'aien_token_ids': ids}}).encode()) +http.server.ThreadingHTTPServer(('127.0.0.1', int(sys.argv[1])), H).serve_forever() diff --git a/evidence/dra86-prefix-20261031/hosttest/runtests.out b/evidence/dra86-prefix-20261031/hosttest/runtests.out new file mode 100644 index 00000000..88e5230f --- /dev/null +++ b/evidence/dra86-prefix-20261031/hosttest/runtests.out @@ -0,0 +1,75 @@ + +== T0 plan +step server env (batch door, --batch-slots 8) probe needs est_s +1 - conv ref - 240 +2 AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_MUTANT=1 conv red 1 180 +3 AIEN_Q36_PREFIX=1 conv green 1 2 180 +4a AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_DIR=OUT/4a/store AIEN_KV_STORE_KEY=(run key) conv write 1 95 +4b AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_DIR=OUT/4a/store AIEN_KV_STORE_KEY=(run key) conv reload 1 4a! 85 +4c AIEN_Q36_PREFIX=1 AIEN_Q36_NS_PROBE=1 AIEN_Q36_PREFIX_DIR=OUT/4a/store AIEN_KV_STORE_KEY=(run key) conv other 1 4a! 4b! 85 +5 AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_POOL_GB=0.5 conv budget 1 200 +6a AIEN_Q36_PREFIX=1 time warm - 355 +6b - time cold - 620 +needs: N = step N earlier in this run or its passing step receipt in OUT/N; N! = earlier in this run (the store key). +Queue slices (chip/DRA-86, cap 1060 s each): s01-identity = 1 2 3 (600 s), s02-controls = 4a 4b 4c 5 (465 s), s03-time = 6a 6b (975 s). +ok plan (rc 0) + +== T1 no SPARK_WINDOW -> NOT_RUN +window-dra86: NOT_RUN: no SPARK_WINDOW: run as 'spark-window run bash /tmp/pdra4-wt/DRA-86/sc/evidence/dra86-prefix-20261031/window-dra86.sh run ...' inside a --quiet exclusive window +ok no window (rc 3) + +== T2 every step on the exact mock door +ok all steps (rc 0) +{"step":"1","rc":0,"verdict":"RECORDED","why":"","r":"RECORDED","rwhy":"","same":0,"diff":0,"restored":0,"turn2":35} +{"step":"2","rc":0,"verdict":"PASS","why":"","r":"PASS","rwhy":"","same":35,"diff":35,"restored":35,"turn2":35} +{"step":"3","rc":0,"verdict":"PASS","why":"","r":"PASS","rwhy":"","same":70,"diff":0,"restored":35,"turn2":35} +{"step":"4a","rc":0,"verdict":"RECORDED","why":"","r":"RECORDED","rwhy":"2 sealed nodes","same":1,"diff":0,"restored":0,"turn2":0} +{"step":"4b","rc":0,"verdict":"PASS","why":"","r":"PASS","rwhy":"","same":1,"diff":0,"restored":1,"turn2":1} +{"step":"4c","rc":0,"verdict":"PASS","why":"","r":"PASS","rwhy":"","same":1,"diff":0,"restored":0,"turn2":1} +{"step":"5","rc":0,"verdict":"PASS","why":"","r":"PASS","rwhy":"9 saves, max evicted 4","same":6,"diff":0,"restored":3,"turn2":3} +{"step":"6a","rc":0,"verdict":"RECORDED","why":"","r":"RECORDED","rwhy":null,"same":null,"diff":null,"restored":null,"turn2":null} +{"step":"6b","rc":0,"verdict":"RECORDED","why":"","r":"RECORDED","rwhy":null,"same":null,"diff":null,"restored":null,"turn2":null} +{"kind":"warm","run":1,"ok":true,"http_ttft_s":0.02486896514892578,"reused_tok":33065,"door_restore_ms":3,"door_prefill_ms":1} +{"kind":"warm","run":2,"ok":true,"http_ttft_s":0.01871967315673828,"reused_tok":33065,"door_restore_ms":3,"door_prefill_ms":1} +{"kind":"warm","run":3,"ok":true,"http_ttft_s":0.017479658126831055,"reused_tok":33065,"door_restore_ms":3,"door_prefill_ms":1} +{"kind":"cold","run":1,"ok":true,"http_ttft_s":0.020830392837524414,"reused_tok":0,"door_restore_ms":null,"door_prefill_ms":1} +store key: 3 server starts got it, 1 distinct, files under the receipts that contain it: 0 +ok key reached 4a 4b 4c, one key, never in a receipt (rc 0) +2 + +== T3 red mutant that changes nothing (MOCK_M=nomut): step 2 FAIL +ok red without effect (rc 1) +{"step":"2","rc":1,"verdict":"FAIL","why":"","r":"FAIL","rwhy":"no turn 2 differs: the gate cannot see the off-by-one","same":70,"diff":0,"restored":35,"turn2":35} + +== T4 green after that failed red: NOT_RUN (red receipt not passing) +window-dra86: NOT_RUN: step 3 needs step 2 earlier in this run or its passing step receipt in /tmp/dra86-hosttest/o1/2 for bin 4e13db1b9505c5e100bb10374c863c74d84500942dfbef74eab3c39114dd6004 +ok green without red (rc 3) + +== T5 red again, then a door that never restores (MOCK_M=norestore): red INCONCLUSIVE +ok red without restore (rc 2) +{"step":"2","rc":2,"verdict":"INCONCLUSIVE","why":"","r":"INCONCLUSIVE","rwhy":"35 turn 2 without a restore line","same":70,"diff":0,"restored":0,"turn2":35} + +== T6 exact red, then green on a door that never restores: green FAIL +ok red (rc 0) +ok green without restore (rc 1) +{"step":"3","rc":1,"verdict":"FAIL","why":"","r":"FAIL","rwhy":"35 turn 2 not restored from the cache","same":70,"diff":0,"restored":0,"turn2":35} + +== T7 store that loads another namespace (MOCK_M=ignore_ns): 4c FAIL +ok stale store loaded (rc 1) +{"step":"4c","rc":1,"verdict":"FAIL","why":"","r":"FAIL","rwhy":"loaded 2 discarded 0 restored 1 (want 0, >= 1, 0)","same":1,"diff":0,"restored":1,"turn2":1} + +== T8 4b without 4a in the run: NOT_RUN +window-dra86: NOT_RUN: step 4b needs step 4a earlier in this run (the store and its key live for one run) +ok reload alone (rc 3) + +== T9 green on an empty OUT: NOT_RUN +window-dra86: NOT_RUN: step 3 needs step 1 earlier in this run or its passing step receipt in /tmp/dra86-hosttest/o9/1 for bin 4e13db1b9505c5e100bb10374c863c74d84500942dfbef74eab3c39114dd6004 +ok green on empty OUT (rc 3) + +== T10 budget step with the default budget (step 3 env, probe budget): FAIL (no eviction, not 0.5 GiB) +{"verdict":"FAIL","why":"the budget is not 0.5 GiB"} +ok budget at 16 GiB (rc 1) + +leftover processes: 0 +lock free +runtests: 0 failed diff --git a/evidence/dra86-prefix-20261031/hosttest/runtests.sh b/evidence/dra86-prefix-20261031/hosttest/runtests.sh new file mode 100755 index 00000000..f06efaba --- /dev/null +++ b/evidence/dra86-prefix-20261031/hosttest/runtests.sh @@ -0,0 +1,48 @@ +#!/usr/bin/env bash +# Host check of window-dra86.sh against the mock door (fake-serve.sh -> mock86.py); scratch lock, never the chip. +# Run as: nice -n 19 taskset -c 5 bash evidence/dra86-prefix-20261031/hosttest/runtests.sh (port 18986) +set -u +H=$(cd "$(dirname "$0")" && pwd); S=$(cd "$H/.." && pwd)/window-dra86.sh +T=${DRA86_HOSTTEST_DIR:-/tmp/dra86-hosttest}; rm -rf "$T"; mkdir -p "$T/win" +export DRA86_KEYSEEN=$T/keys.seen SPARK_WINDOW=w-test-86 SPARK_WINDOW_DIR=$T/win DRA86_TEST_LOCK=$T/t.lock DRA86_TEST_PORT=18986 +: > "$DRA86_TEST_LOCK"; B=$H/fake-serve.sh; fails=0 +win() { rm -f "$T/win/expired"; date -u +%FT%TZ > "$T/win/held"; echo 60 > "$T/win/lease"; } +sr() { jq -c '{step, rc, verdict, why, r: .result.verdict, rwhy: .result.why, same: .result.same, diff: .result.diff, restored: .result.restored, turn2: .result.turn2}' "$1/step-receipt.json" 2>/dev/null || echo "no receipt $1"; } +expect() { # + if [ "$2" = "$3" ]; then echo "ok $1 (rc $3)"; else echo "FAIL $1: want rc $2, got $3"; fails=$((fails + 1)); fi +} +t() { echo; echo "== $*"; } + +t "T0 plan"; bash "$S" plan; expect "plan" 0 $? +t "T1 no SPARK_WINDOW -> NOT_RUN"; env -u SPARK_WINDOW bash "$S" run "$B" "$T/o0" 1 2>&1 | tail -n 1; expect "no window" 3 ${PIPESTATUS[0]} +t "T2 every step on the exact mock door"; win +bash "$S" run "$B" "$T/o1" 1 2 3 4a 4b 4c 5 6a 6b > /dev/null 2> "$T/t2.err"; rc=$?; expect "all steps" 0 $rc +for s in 1 2 3 4a 4b 4c 5 6a 6b; do sr "$T/o1/$s"; done +jq -c '{kind, run, ok, http_ttft_s, reused_tok, door_restore_ms, door_prefill_ms}' "$T/o1/6a/time.jsonl" "$T/o1/6b/time.jsonl" +nk=$(sort -u "$DRA86_KEYSEEN" | wc -l); nl=$(wc -l < "$DRA86_KEYSEEN"); leak=$(grep -rlF -f "$DRA86_KEYSEEN" "$T/o1" | wc -l) +echo "store key: $nl server starts got it, $nk distinct, files under the receipts that contain it: $leak" +[ "$nl" = 3 ] && [ "$nk" = 1 ] && [ "$leak" = 0 ]; expect "key reached 4a 4b 4c, one key, never in a receipt" 0 $? +grep -c 'GPU-START\|GPU-END' "$T/o1/board.log" +t "T3 red mutant that changes nothing (MOCK_M=nomut): step 2 FAIL"; win +MOCK_M=nomut bash "$S" run "$B" "$T/o1" 2 > /dev/null 2>&1; expect "red without effect" 1 $?; sr "$T/o1/2" +t "T4 green after that failed red: NOT_RUN (red receipt not passing)"; win +bash "$S" run "$B" "$T/o1" 3 2>&1 >/dev/null | tail -n 1; expect "green without red" 3 ${PIPESTATUS[0]} +t "T5 red again, then a door that never restores (MOCK_M=norestore): red INCONCLUSIVE"; win +MOCK_M=norestore bash "$S" run "$B" "$T/o1" 2 > /dev/null 2>&1; expect "red without restore" 2 $?; sr "$T/o1/2" +t "T6 exact red, then green on a door that never restores: green FAIL"; win +bash "$S" run "$B" "$T/o1" 2 > /dev/null 2>&1; expect "red" 0 $? +MOCK_M=norestore bash "$S" run "$B" "$T/o1" 3 > /dev/null 2>&1; expect "green without restore" 1 $?; sr "$T/o1/3" +t "T7 store that loads another namespace (MOCK_M=ignore_ns): 4c FAIL"; win +MOCK_M=ignore_ns bash "$S" run "$B" "$T/o1" 4a 4b 4c > /dev/null 2>&1; expect "stale store loaded" 1 $?; sr "$T/o1/4c" +t "T8 4b without 4a in the run: NOT_RUN"; win +bash "$S" run "$B" "$T/o1" 4b 2>&1 >/dev/null | tail -n 1; expect "reload alone" 3 ${PIPESTATUS[0]} +t "T9 green on an empty OUT: NOT_RUN"; win +bash "$S" run "$B" "$T/o9" 3 2>&1 >/dev/null | tail -n 1; expect "green on empty OUT" 3 ${PIPESTATUS[0]} +t "T10 budget step with the default budget (step 3 env, probe budget): FAIL (no eviction, not 0.5 GiB)" +AIEN_Q36_PREFIX=1 python3 "$H/mock86.py" 18987 2> "$T/t10.log" & mp=$!; sleep 1 +SHA=$(sha256sum < "$B" | cut -c1-64) +DRA86_SERVER_LOG=$T/t10.log bash "$S" conv 18987 "$T/o10" budget "$SHA" x "$T/o1/1/conv.jsonl" | jq -c '{verdict, why}'; expect "budget at 16 GiB" 1 ${PIPESTATUS[0]} +kill $mp; wait $mp 2>/dev/null +echo; leftover=$(pgrep -f 'mock86.py|window-dra86.sh _watch' | wc -l); echo "leftover processes: $leftover" +flock -n "$DRA86_TEST_LOCK" true && echo "lock free" || { echo "lock HELD"; fails=$((fails + 1)); } +echo "runtests: $fails failed"; [ $fails = 0 ] diff --git a/evidence/dra86-prefix-20261031/set32.json b/evidence/dra86-prefix-20261031/set32.json new file mode 100644 index 00000000..97744947 --- /dev/null +++ b/evidence/dra86-prefix-20261031/set32.json @@ -0,0 +1,1136 @@ +{ + "set": "dra65-32", + "about": "DRA-65 32-prompt set = the merge train concurrent-32 prompts (evidence/q36-batch-20261021/prompts.txt, ntok rule i==0?24:8+(i*7)%41); goldens = reference build bin-5b726818 (plain correct path: prompt fed token by token, no speed levers), each request alone, recorded 2026-10-21T02:44:22Z, imported to the merge-train store 2026-10-21T14:36:32Z; pre-DRA-65 by date", + "prompts_file": "evidence/q36-batch-20261021/prompts.txt", + "prompts_sha256": "7a171b54c2effda998d2884e3f6868b55123fa8ba779dcf2762dff4c64a1fa29", + "defaults": { + "temperature": 0, + "chat_template_kwargs": { + "enable_thinking": false + }, + "aien_return_token_ids": true + }, + "judge": "exact id identity per prompt (the door returns no logit margins, so the 0.1-logit band cannot be judged here: any flip is FAIL)", + "prompts": [ + { + "i": 0, + "user": "Write a C function that returns the larger of two ints.", + "max_tokens": 24, + "prompt_tokens": 24, + "golden_ids": [ + 71093, + 66, + 198, + 390, + 1866, + 1494, + 264, + 11, + 514, + 292, + 8, + 313, + 198, + 262, + 460, + 318, + 64, + 835, + 292, + 8, + 907, + 264, + 535, + 292 + ], + "finish": "length", + "ref_sha256": "1160441d7c54df52ee42250ae40cdc4b04671da9e1b6742fd10a25fbd400985f" + }, + { + "i": 1, + "user": "What is the capital of Australia? Answer in one sentence.", + "max_tokens": 15, + "prompt_tokens": 24, + "golden_ids": [ + 760, + 6511, + 314, + 8071, + 369, + 66463, + 13 + ], + "finish": "stop", + "ref_sha256": "d89145567b7eba7b4585ffe60941f5ef9c5d4b3106f15e2533f7f609a1d5185c" + }, + { + "i": 2, + "user": "Explain in two sentences why the sky is blue.", + "max_tokens": 22, + "prompt_tokens": 23, + "golden_ids": [ + 29108, + 4009, + 23716, + 8964, + 579, + 16078, + 321, + 369, + 35742, + 303, + 660, + 17425, + 539, + 660, + 279, + 43034, + 321, + 18167, + 303, + 279, + 3594, + 13 + ], + "finish": "length", + "ref_sha256": "0e3cd9ab0c23c929a9a6357a08e43228194ad04e92f4535016ba3a5197dc9bc0" + }, + { + "i": 3, + "user": "List five prime numbers greater than 100.", + "max_tokens": 29, + "prompt_tokens": 23, + "golden_ids": [ + 8160, + 513, + 4097, + 9944, + 4947, + 6826, + 1056, + 220, + 16, + 15, + 15, + 25, + 271, + 16, + 13, + 2972, + 16, + 15, + 16, + 332, + 198, + 17, + 13, + 2972, + 16, + 15, + 18, + 332, + 198 + ], + "finish": "length", + "ref_sha256": "9c10e0160d0ec6d3b686cf69f9928055936f979250ba2b3ff235655c95980803" + }, + { + "i": 4, + "user": "Translate to French: The train leaves at seven in the morning.", + "max_tokens": 36, + "prompt_tokens": 25, + "golden_ids": [ + 2229, + 5257, + 919, + 3656, + 33190, + 72491, + 3717, + 175926, + 13 + ], + "finish": "stop", + "ref_sha256": "3bdf30ac3ad47d0f37b51943bcf622772b94fd26a768e07c972b0fbc08dfd19d" + }, + { + "i": 5, + "user": "Write a haiku about a lighthouse in winter.", + "max_tokens": 43, + "prompt_tokens": 23, + "golden_ids": [ + 60187, + 16563, + 383, + 279, + 9506, + 11, + 198, + 3320, + 21682, + 14663, + 279, + 19088, + 6121, + 11, + 198, + 91986, + 337, + 2785, + 279, + 13071, + 13 + ], + "finish": "stop", + "ref_sha256": "3db756863a419713f68fb147da9182ed46c4d8252c7524aef2f602619f7dbe76" + }, + { + "i": 6, + "user": "What is 17 times 23? Show the steps.", + "max_tokens": 9, + "prompt_tokens": 26, + "golden_ids": [ + 1206, + 10724, + 393, + 16, + 22, + 1088, + 14695, + 220, + 17 + ], + "finish": "length", + "ref_sha256": "0dd734e6877fdb926c41be7ba2afcc86801d37a528882bd39b76f8e3c20dcaa2" + }, + { + "i": 7, + "user": "Give three tips for writing clear commit messages.", + "max_tokens": 16, + "prompt_tokens": 21, + "golden_ids": [ + 8160, + 513, + 2250, + 7326, + 10104, + 364, + 4237, + 2708, + 321, + 7139, + 5099, + 6397, + 25, + 271, + 16, + 13 + ], + "finish": "length", + "ref_sha256": "4194298c7d7b55c120180bae0e985afeaa478a2c4bb83f1ba5cbd836ed3a1097" + }, + { + "i": 8, + "user": "Write a Rust function that reverses a string.", + "max_tokens": 23, + "prompt_tokens": 22, + "golden_ids": [ + 71093, + 34602, + 198, + 9299, + 5003, + 9637, + 3773, + 1104, + 25, + 594, + 485, + 8, + 1411, + 894, + 313, + 198, + 262, + 274, + 82127, + 973, + 7055, + 973, + 16873 + ], + "finish": "length", + "ref_sha256": "cb4ce8306f3398464f0222f357f19045d2779ac88a72dd2fd2964ea1b3ba9e38" + }, + { + "i": 9, + "user": "Summarize the plot of Romeo and Juliet in three sentences.", + "max_tokens": 30, + "prompt_tokens": 25, + "golden_ids": [ + 11280, + 3777, + 31059, + 494, + 1115, + 49058, + 8259, + 11, + 67815, + 9503, + 4511, + 321, + 68613, + 7761, + 46805, + 11, + 40361, + 30774, + 1238, + 6236, + 506, + 264, + 4776, + 13, + 10643, + 10973, + 369, + 53507, + 948, + 67815 + ], + "finish": "length", + "ref_sha256": "2006031bcddb5bf56ee7b575a9e0c96a359eb7a92bedc9b7f2277f68f50a74fd" + }, + { + "i": 10, + "user": "What does a transformer's attention layer compute? Be brief.", + "max_tokens": 37, + "prompt_tokens": 24, + "golden_ids": [ + 2064, + 55288, + 264, + 35604, + 2542, + 314, + 869, + 22166, + 11, + 1332, + 279, + 13914, + 318, + 51319, + 11857, + 8, + 513, + 10521, + 539, + 279, + 23967, + 1881, + 3134, + 321, + 1328, + 22166, + 13 + ], + "finish": "stop", + "ref_sha256": "ee7a975635266296abbdbff1f987105ae4a6ea5f5e159d1f80d03fa1a9958eac" + }, + { + "i": 11, + "user": "Name the planets of the solar system in order from the Sun.", + "max_tokens": 44, + "prompt_tokens": 25, + "golden_ids": [ + 8160, + 513, + 279, + 7810, + 31784, + 314, + 279, + 12570, + 1785, + 303, + 1906, + 494, + 279, + 7806, + 25, + 271, + 16, + 13, + 2972, + 25863, + 24648, + 332, + 198, + 17, + 13, + 2972, + 53, + 36614, + 332, + 198, + 18, + 13, + 2972, + 42373, + 332, + 198, + 19, + 13, + 2972, + 44, + 1506, + 332, + 198, + 20 + ], + "finish": "length", + "ref_sha256": "5f7796407586354c677537bd952108b5c78f05976bb1c1983da9660ab463da3a" + }, + { + "i": 12, + "user": "Write a SQL query that counts orders per customer.", + "max_tokens": 10, + "prompt_tokens": 22, + "golden_ids": [ + 71093, + 3427, + 198, + 4703, + 5813, + 816, + 11, + 23241, + 27733, + 5574 + ], + "finish": "length", + "ref_sha256": "21649ba27a51bbe56a600c62a4e80e5950adcc2a6a2fe96927e3b722ff996117" + }, + { + "i": 13, + "user": "Why does ice float on water?", + "max_tokens": 17, + "prompt_tokens": 19, + "golden_ids": [ + 49604, + 46303, + 383, + 2919, + 1521, + 424, + 369, + 2972, + 1657, + 27044, + 332, + 1056, + 14058, + 2919, + 13, + 271, + 7732 + ], + "finish": "length", + "ref_sha256": "9115ce326ccb9ed8b594df270866729abc7dea04c8e0d7849183a1b6a4013b34" + }, + { + "i": 14, + "user": "Write a bash one-liner that counts lines in all .txt files in a folder.", + "max_tokens": 24, + "prompt_tokens": 30, + "golden_ids": [ + 71093, + 44675, + 198, + 3772, + 641, + 471, + 2721, + 17038, + 220, + 16, + 471, + 591, + 57129, + 8324, + 1, + 471, + 11411, + 25700, + 471, + 75, + 4535, + 478, + 735, + 9495 + ], + "finish": "length", + "ref_sha256": "2e8db9effc918a567c93ebc9a002215a7aca716003bc8c055a2f54ee62e7acbd" + }, + { + "i": 15, + "user": "Describe a bicycle gear system to a ten-year-old.", + "max_tokens": 31, + "prompt_tokens": 23, + "golden_ids": [ + 49338, + 488, + 513, + 19232, + 678, + 12591, + 685, + 264, + 2098, + 30239, + 23198, + 13, + 1049, + 725, + 2503, + 944, + 11, + 1245, + 30, + 4465, + 13795, + 2579, + 8545, + 11, + 321, + 488, + 3029, + 6992, + 2184, + 13569, + 13 + ], + "finish": "length", + "ref_sha256": "990ee87702c062286443413a43f7b211302ad3af15ec95bf84e0624e836c4d9f" + }, + { + "i": 16, + "user": "What is the difference between TCP and UDP? Two sentences.", + "max_tokens": 38, + "prompt_tokens": 24, + "golden_ids": [ + 48218, + 369, + 264, + 3511, + 33924, + 11176, + 421, + 34475, + 14294, + 11, + 11128, + 9403, + 314, + 795, + 1472, + 1412, + 15464, + 286, + 321, + 311, + 1405, + 2641, + 23038, + 13, + 733, + 12503, + 11, + 40986, + 369, + 264, + 3511, + 1657, + 11176, + 421, + 43195, + 4603, + 4478, + 321 + ], + "finish": "length", + "ref_sha256": "c6cc3038fc9751cd5f686e0c8bf9e96c268a2ba0d5794d4684ff8f1285857efe" + }, + { + "i": 17, + "user": "Write a limerick about a cat who learned to code.", + "max_tokens": 45, + "prompt_tokens": 25, + "golden_ids": [ + 32, + 7993, + 852, + 1362, + 913, + 383, + 264, + 13232, + 11, + 198, + 54, + 5356, + 1970, + 421, + 557, + 16724, + 430, + 264, + 57131, + 13, + 198, + 1465, + 7156, + 3438, + 440, + 264, + 3865, + 81, + 11, + 198, + 2939, + 8097, + 1396, + 27583, + 11, + 198, + 6820, + 551, + 725, + 279, + 11808, + 314, + 279, + 3421, + 13 + ], + "finish": "length", + "ref_sha256": "d3181419484825b2029340cf6af228cc2fc3dbae2207073c940bec8c0aec64ab" + }, + { + "i": 18, + "user": "Convert 100 degrees Fahrenheit to Celsius and explain the formula.", + "max_tokens": 11, + "prompt_tokens": 26, + "golden_ids": [ + 13962, + 12650, + 21134, + 198, + 332, + 16, + 15, + 15, + 11995, + 66401, + 369 + ], + "finish": "length", + "ref_sha256": "2e810d7ed4b007385e06b9f646225ecb46fa1af428e540dd989addfe51239f63" + }, + { + "i": 19, + "user": "Give a short definition of entropy in thermodynamics.", + "max_tokens": 18, + "prompt_tokens": 22, + "golden_ids": [ + 623, + 28868, + 76214, + 11, + 2972, + 47500, + 332, + 369, + 264, + 1528, + 709, + 421, + 10633, + 279, + 8122, + 314, + 18684, + 11 + ], + "finish": "length", + "ref_sha256": "df16bacb0096b417348b5b09202ec3036574e81b75dbe194b7051640e62c5b05" + }, + { + "i": 20, + "user": "Write a Python-free pseudocode for binary search.", + "max_tokens": 25, + "prompt_tokens": 22, + "golden_ids": [ + 8160, + 369, + 279, + 48939, + 42242, + 364, + 279, + 2972, + 20682, + 7304, + 332, + 11767, + 13, + 271, + 13962, + 2601, + 367, + 1255, + 198, + 9, + 256, + 561, + 1879, + 1287, + 1510 + ], + "finish": "length", + "ref_sha256": "76a00aef96743aae5f035055f92cbb0850ae3183b77edd04f201a5717c85fa92" + }, + { + "i": 21, + "user": "What are the three primary colors of light?", + "max_tokens": 32, + "prompt_tokens": 21, + "golden_ids": [ + 27775, + 383, + 279, + 15694, + 314, + 2972, + 698, + 3295, + 1829, + 25936, + 332, + 318, + 7949, + 16298, + 310, + 3000, + 7916, + 1040, + 6165, + 14864, + 11, + 7712, + 38685, + 11, + 321, + 6228, + 17188, + 681, + 279, + 2250, + 5839, + 7736 + ], + "finish": "length", + "ref_sha256": "8af1b096cf45a772446b309ec704e4ecf1a2d6f8b16a201ec4e5181a771f6aa4" + }, + { + "i": 22, + "user": "Suggest a name for a coffee shop run by robots, and say why.", + "max_tokens": 39, + "prompt_tokens": 28, + "golden_ids": [ + 8160, + 369, + 264, + 23032, + 364, + 264, + 803, + 11, + 3055, + 440, + 279, + 31626, + 4661, + 424, + 25, + 271, + 13962, + 2972, + 657, + 25, + 561, + 38989, + 291, + 20284, + 332, + 271, + 13962, + 2972, + 9930, + 411, + 803, + 4138, + 64700, + 271, + 16, + 13, + 220, + 2972, + 8864 + ], + "finish": "length", + "ref_sha256": "4af3e06ce741e8b6199a7a040cd3be9fb24f712be611e281d09cfdac63d6174a" + }, + { + "i": 23, + "user": "Explain what a hash map is in one paragraph.", + "max_tokens": 46, + "prompt_tokens": 23, + "golden_ids": [ + 32, + 5010, + 2336, + 369, + 264, + 795, + 5759, + 421, + 5004, + 449, + 66571, + 1287, + 7859, + 795, + 913, + 11, + 264, + 5759, + 421, + 628, + 2336, + 6679, + 310, + 2663, + 11, + 539, + 1608, + 264, + 5010, + 709, + 310, + 12204, + 449, + 1857, + 1083, + 449, + 1287, + 314, + 40718, + 466, + 15250, + 494, + 864, + 279, + 12321, + 869 + ], + "finish": "length", + "ref_sha256": "3ea511c6a6c81cb8d195187e8f8030e141edef306768c44944658a4f030162f2" + }, + { + "i": 24, + "user": "Write the first four lines of a sea shanty.", + "max_tokens": 12, + "prompt_tokens": 23, + "golden_ids": [ + 760, + 9662, + 424, + 1204, + 4577, + 3808, + 279, + 30065, + 11, + 198, + 760, + 16382 + ], + "finish": "length", + "ref_sha256": "14045453e1920ab5e473ab357dde290c7d2bb44e8c8a9584647ef541b235077c" + }, + { + "i": 25, + "user": "How many seconds are in a day? Show the multiplication.", + "max_tokens": 19, + "prompt_tokens": 24, + "golden_ids": [ + 1206, + 10724, + 279, + 1324, + 314, + 6283, + 303, + 264, + 1834, + 11, + 567, + 1387, + 1441, + 279, + 7896, + 314, + 854, + 2923, + 13909 + ], + "finish": "length", + "ref_sha256": "d0c0ac7e377f47eaa255866d0d387aefb51b9d2b2fedb7982798a0cfa4d4b44f" + }, + { + "i": 26, + "user": "What is the boiling point of water at the top of Mount Everest, roughly?", + "max_tokens": 26, + "prompt_tokens": 28, + "golden_ids": [ + 13962, + 59977, + 48704, + 2567, + 271, + 1206, + 7995, + 279, + 48161, + 1406, + 314, + 2919, + 506, + 279, + 1844, + 314, + 10113, + 83489, + 11, + 567, + 1902, + 3418, + 279, + 4864, + 1881, + 42900 + ], + "finish": "length", + "ref_sha256": "f2cd985dda2a49869a5cab6952577804225ce0dad8d36732c2bef342c6aba159" + }, + { + "i": 27, + "user": "Write a JavaScript function that checks whether a number is even.", + "max_tokens": 33, + "prompt_tokens": 24, + "golden_ids": [ + 71093, + 13670, + 198, + 1628, + 369, + 12777, + 7815, + 8, + 313, + 198, + 262, + 460, + 1572, + 984, + 220, + 17, + 1981, + 220, + 15, + 26, + 198, + 92, + 198, + 71093 + ], + "finish": "stop", + "ref_sha256": "c3d491b3023dd54ee733b536d7ee7f83516e95f9c43f2781000ff610813d6c36" + }, + { + "i": 28, + "user": "Explain photosynthesis in plain words.", + "max_tokens": 40, + "prompt_tokens": 20, + "golden_ids": [ + 37405, + 314, + 7022, + 71163, + 430, + 264, + 2972, + 981, + 10430, + 1817, + 332, + 421, + 10462, + 958, + 310, + 1236, + 836, + 1765, + 3487, + 13, + 271, + 8160, + 725, + 1204, + 424, + 4138, + 303, + 4145, + 7123, + 25, + 271, + 13962, + 10838, + 234, + 109, + 561, + 49453, + 198, + 2052, + 1720 + ], + "finish": "length", + "ref_sha256": "e6f92c8632513565cab6270765fb40f2d84db8d7b842471efdf8907789cd8179" + }, + { + "i": 29, + "user": "Give two reasons a bridge might use a suspension design.", + "max_tokens": 47, + "prompt_tokens": 23, + "golden_ids": [ + 8160, + 513, + 1330, + 5839, + 7715, + 264, + 13759, + 2493, + 958, + 264, + 23538, + 2790, + 25, + 271, + 13962, + 220, + 16, + 13, + 34791, + 310, + 11564, + 5546, + 26709, + 2924, + 198, + 90898, + 2558, + 37683, + 513, + 1968, + 40541, + 15873, + 364, + 25786, + 1546, + 6669, + 12497, + 314, + 2919, + 466, + 5365, + 82446, + 13, + 25215, + 22690, + 466, + 5157 + ], + "finish": "length", + "ref_sha256": "ca5f6f9e1cd0de542c8ca6c1c3a9adc8f1adfbd76b6b0209db49dd16eb631d68" + }, + { + "i": 30, + "user": "Write a polite email declining a meeting invitation.", + "max_tokens": 13, + "prompt_tokens": 21, + "golden_ids": [ + 12646, + 25, + 997, + 25, + 28107, + 80370, + 471, + 498, + 62394, + 31819, + 14, + 1851, + 60 + ], + "finish": "length", + "ref_sha256": "babd437d849e8ceca3ee5632b4e1e12327574cfa3ce5383e0c5d76e2023b3d64" + }, + { + "i": 31, + "user": "What is a mutex and when would you use one?", + "max_tokens": 20, + "prompt_tokens": 23, + "golden_ids": [ + 2, + 63979, + 318, + 49708, + 899, + 1326, + 8686, + 8, + 271, + 550, + 3437, + 2091, + 264, + 63979, + 30, + 271, + 32, + 2972, + 21670, + 332 + ], + "finish": "length", + "ref_sha256": "705bf4bdc3d0d99530c5a567ba128998c3b437a09dabc12bd4ba1fe396de5cc8" + } + ], + "source_dir": "~/.local/state/aien-q36/merge-train/refs/qwen3.6-35b-a3b-fp8-95a723d0/5b726818/", + "ref_note": "prompts[i].ref_sha256 = sha256 of source_dir/alone/.json" +} diff --git a/evidence/dra86-prefix-20261031/window-dra86.sh b/evidence/dra86-prefix-20261031/window-dra86.sh new file mode 100755 index 00000000..76996eda --- /dev/null +++ b/evidence/dra86-prefix-20261031/window-dra86.sh @@ -0,0 +1,448 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# DRA-86 chip window (G4: the shared prompt cache of the batch door, AIEN_Q36_PREFIX=1). Adapted from +# evidence/dra65-prefill-20261031/window-dra65.sh (#862): the same lock, lease, watchdog and receipt machinery. +# The single chip queue (~/handoffs/pdra4-hive/chip/run-queue.sh) runs it through the slices +# chip/DRA-86/s01-identity.sh (steps 1 2 3), s02-controls.sh (4a 4b 4c 5), s03-time-warm.sh (6a), s04-time-cold.sh (6b); each carries the +# header `# pdra4-gb10: none`, so the runner opens `spark-window open ... --gb10 none --quiet exclusive --lease 20` +# (18091 and Flint stopped by the runner's preflight) and the slice runs +# spark-window run bash window-dra86.sh run BIN OUT STEP [STEP ...] +# BIN = the server binary built from this branch, OUT = a receipt root shared by every lease (step N writes OUT/N/). +# The server's chip reservation only accepts /tmp/aien-gb10.lock held by one of its ancestors, so this script takes +# `flock -o` on it itself and starts every server as its child, in its own session (setsid, pid file +# OUT/.server..pid), with AIEN_GB10_LOCK_HELD=1 and the affinity reset of the live start scripts. +# DRA86_LOCK_WAIT=N: wait at most N s for the lock (default 0). DRA86_CAP_S=N: end N s after `held` (slices: 1060). +# Exit 3 = NOT_RUN, chip untouched: no SPARK_WINDOW, a window that holds the chip lock itself, the lock held by +# someone else, a listener on 18091/18300/18310 or the test port, a compute app on the chip, the binary or model +# missing, a step without the steps it needs (below), or the steps' estimate longer than the lease has left. +# A step that ends after the deadline or with SPARK_WINDOW_DIR/expired present is INCONCLUSIVE (rc 2). +# window-dra86.sh plan (no window needed: the steps, their server env and estimated durations) +# +# Steps (all on the batch door, one request at a time, greedy, thinking off): +# 1 ref prompt cache OFF (no AIEN_Q36_PREFIX): 35 conversations (set32 + l369 long-256/2048/8192), turn 1 +# and turn 2 (turn 1 + its answer + a fixed follow-up). Their ids are the references (same binary). +# The log must say "prompt cache off" (the switch defaults off). +# 2 red AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_MUTANT=1 (a restored row continues one position early): PASS = +# at least one turn 2 differs from step 1, every turn 2 restored (log line), no NO_IDS/SHORT. +# 3 green AIEN_Q36_PREFIX=1 (default budget): PASS = every turn 1 and turn 2 equals step 1, every turn 2 +# restored from the cache and none refused, the log says "budget 16.0 GiB". Needs 1 and 2 (red). +# 4a write AIEN_Q36_PREFIX=1 + sealed store OUT/4a/store (a key made for this run, never written down): +# long-2048 turn 1 only; the store must hold its nodes. 4b and 4c must follow in the same run. +# 4b reload same env: the store loads >= 1 node; long-2048 turn 2 is restored from it and equals step 1. +# 4c other same env + AIEN_Q36_NS_PROBE=1 (a numeric env key: another namespace = another model/lib/env): +# the store discards every node (0 loaded, >= 1 discarded); turn 2 reads cold and equals step 1. +# 5 budget AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_POOL_GB=0.5: the three long conversations; PASS = every save line +# reports the conversation's resident bytes and a pool <= 512 MiB, at least one eviction, every +# turn equal to step 1. +# 6a time AIEN_Q36_PREFIX=1: turn 1 = ~32.8k-token prompt (long-8192 x 4), then 3 turn-2 runs adding ~1k new +# tokens each (streamed): HTTP TTFT (client) and the door's restore ms + prefill ms per run. +# 6b time prompt cache off: the same turn 1 and turn-2 run 1, read cold (the control TTFT). +# Probes (an already running server on PORT; `run` calls them; the host check runs them against a mock door): +# window-dra86.sh conv PORT OUT KIND BIN_SHA256 LABEL [REF_JSONL] KIND ref|red|green|write|reload|other|budget +# window-dra86.sh time PORT OUT KIND BIN_SHA256 LABEL KIND warm|cold +# Per turn vs the reference: SAME, DIFF (a flip inside the common length, or more ids), SHORT (strict prefix), +# NO_IDS (HTTP error, missing or empty ids). Exit 0 = PASS/RECORDED, 1 = FAIL, 2 = INCONCLUSIVE or refused, +# 3 = NOT_RUN, 4 = interrupted. `run` stops at the first step that does not exit 0 and returns its code. +set -uo pipefail +HERE=$(cd "$(dirname "$0")" && pwd); REPO=$(cd "$HERE/../.." && pwd); SELF=$HERE/$(basename "$0") +die() { echo "window-dra86: $*" >&2; exit 2; } +not_run() { echo "window-dra86: NOT_RUN: $*" >&2; exit 3; } +left_s() { + local cap=${1:-999999} l + if [ -n "${DRA86_DEADLINE:-}" ]; then l=$((DRA86_DEADLINE - $(date +%s))); [ "$l" -lt "$cap" ] || l=$cap; else l=$cap; fi + echo "$l"; [ "$l" -gt 0 ] +} + +# step -> server env, probe, needs, estimated seconds. MODELED (Wolfram, PLAN.md): batch start 60 s, decode 0.0201 +# s/token (short prompts stepped at the same rate), chunked prompts 250 tok/s, the ~32.8k prompt 120 tok/s +# (a deliberately slow bound), restore 0.5-1 s; upper bounds at max_tokens. +STEPS_ALL="1 2 3 4a 4b 4c 5 6a 6b" +step_def() { + ENVS=(); STORE=0; NEEDS=""; case $1 in + 1) PROBE="conv ref"; EST=240 ;; + 2) ENVS=(AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_MUTANT=1); PROBE="conv red"; EST=180; NEEDS="1" ;; + 3) ENVS=(AIEN_Q36_PREFIX=1); PROBE="conv green"; EST=180; NEEDS="1 2" ;; + 4a) ENVS=(AIEN_Q36_PREFIX=1); STORE=1; PROBE="conv write"; EST=95; NEEDS="1" ;; + 4b) ENVS=(AIEN_Q36_PREFIX=1); STORE=1; PROBE="conv reload"; EST=85; NEEDS="1 4a!" ;; + 4c) ENVS=(AIEN_Q36_PREFIX=1 AIEN_Q36_NS_PROBE=1); STORE=1; PROBE="conv other"; EST=85; NEEDS="1 4a! 4b!" ;; + 5) ENVS=(AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_POOL_GB=0.5); PROBE="conv budget"; EST=200; NEEDS="1" ;; + 6a) ENVS=(AIEN_Q36_PREFIX=1); PROBE="time warm"; EST=355 ;; + 6b) PROBE="time cold"; EST=620 ;; + *) return 1 ;; + esac +} +# step_ok OUT STEP SHA: that step's run receipt passed for this binary inside the lease. +step_ok() { + jq -e --arg b "$3" '.rc == 0 and .bin_sha256 == $b and (.lock_holder | length) > 0 and .lease_expired == false' \ + "$1/$2/step-receipt.json" > /dev/null 2>&1 +} + +case ${1:-} in +plan) + printf '%-4s %-62s %-12s %-10s %s\n' step "server env (batch door, --batch-slots 8)" probe needs est_s + for s in $STEPS_ALL; do + step_def $s; e="${ENVS[*]:-}"; [ $STORE = 1 ] && e="$e AIEN_Q36_PREFIX_DIR=OUT/4a/store AIEN_KV_STORE_KEY=(run key)" + printf '%-4s %-62s %-12s %-10s %s\n' $s "${e:--}" "$PROBE" "${NEEDS:--}" $EST + done + echo "needs: N = step N earlier in this run or its passing step receipt in OUT/N; N! = earlier in this run (the store key)." + echo "Queue slices (chip/DRA-86, cap 1060 s each): s01-identity = 1 2 3 (600 s), s02-controls = 4a 4b 4c 5 (465 s), s03-time-warm = 6a (355 s), s04-time-cold = 6b (620 s)." + exit 0 ;; +_watch) # _watch MAIN HOLDER DEADLINE PIDFILE (own session; started by run) + M=$2; H=$3; DL=$4; PF=$5 + while kill -0 "$M" 2>/dev/null && kill -0 "$H" 2>/dev/null && [ "$(date +%s)" -lt "$DL" ]; do sleep 1; done + why="deadline"; kill -0 "$M" 2>/dev/null || why="run shell $M gone"; kill -0 "$H" 2>/dev/null || why="lock holder $H gone" + pg=$(cat "$PF" 2>/dev/null) + if [ -n "$pg" ] && kill -0 -- "-$pg" 2>/dev/null; then + echo "$(date -u +%FT%TZ) watchdog: $why: TERM server group $pg" + kill -TERM -- "-$pg" 2>/dev/null + for _ in $(seq 20); do kill -0 -- "-$pg" 2>/dev/null || break; sleep 1; done + kill -KILL -- "-$pg" 2>/dev/null; rm -f "$PF" + fi + if [ "$why" = deadline ]; then for _ in $(seq 40); do kill -0 "$M" 2>/dev/null || break; sleep 1; done; fi + kill -0 "$M" 2>/dev/null && { echo "$(date -u +%FT%TZ) watchdog: $why: TERM run shell $M"; kill -TERM "$M"; } + exit 0 ;; +run) + [ -n "${SPARK_WINDOW:-}" ] || not_run "no SPARK_WINDOW: run as 'spark-window run bash $0 run ...' inside a --quiet exclusive window" + [ $# -ge 4 ] || die "usage: run BIN OUT STEP [STEP ...]" + # DRA86_TEST_LOCK (host check only): another lock file; the binary must be a script (a mock door, never the + # ELF server), the chip and live-port checks are skipped and board lines go to OUT/board.log. + LOCK=${DRA86_TEST_LOCK:-/tmp/aien-gb10.lock}; TEST=${DRA86_TEST_LOCK:+1} + g=$(cat "${SPARK_WINDOW_DIR:-/nonexistent}/gb10" 2>/dev/null) + case $g in exclusive|shared) not_run "window $SPARK_WINDOW holds the chip lock (gb10 $g): open it with --gb10 none (queue slice header '# pdra4-gb10: none')" ;; esac + if [ "${DRA86_LOCKED:-}" != "$SPARK_WINDOW" ]; then + lw=${DRA86_LOCK_WAIT:-0}; case $lw in ''|*[!0-9]*) die "DRA86_LOCK_WAIT=$lw: whole seconds" ;; esac + wflag=(-n); [ "$lw" -gt 0 ] && wflag=(-w "$lw") + DRA86_LOCKED=$SPARK_WINDOW flock "${wflag[@]}" -o -E 75 "$LOCK" bash "$SELF" "$@" & FL=$! + trap 'kill -TERM $FL 2>/dev/null' INT TERM HUP + while :; do wait $FL; rc=$?; kill -0 $FL 2>/dev/null || break; done + [ $rc = 75 ] && not_run "$LOCK is held by another process (waited $lw s); this script takes it itself (open the window with --gb10 none)" + exit $rc + fi + BIN=$(readlink -f "$2"); OUT=$(readlink -m "$3"); shift 3; STEPS=("$@") + WIN=$SPARK_WINDOW + ino=$(stat -c %i "$LOCK") || not_run "$LOCK missing" + holders=$(awk -v ino="$ino" '$2 == "FLOCK" && $4 == "WRITE" { split($6, a, ":"); if (a[3] == ino) print $5 }' /proc/locks | sort -u) + anc=" "; p=$$ + while [ "$p" -gt 1 ]; do anc="$anc$p "; p=$(awk '{print $4}' "/proc/$p/stat" 2>/dev/null) || break; done + HOLDER=; for h in $holders; do case "$anc" in *" $h "*) HOLDER=$h ;; esac; done + [ -n "$HOLDER" ] || not_run "$LOCK held by pid(s) '${holders}', none an ancestor of $$ ($anc)" + if [ -n "$TEST" ]; then + [ -x "$BIN" ] && [ "$(head -c 4 "$BIN" | od -An -c | tr -d ' ')" != '177ELF' ] \ + || not_run "test lock $LOCK held by ancestor $HOLDER; DRA86_TEST_LOCK only runs a script mock door, never the server binary" + fi + [ -x "$BIN" ] || not_run "binary $BIN missing" + SHA=$(sha256sum < "$BIN" | cut -c1-64) + # Steps known; every need met (earlier in this run, or a passing step receipt in OUT unless marked !). + total=0; seen=" " + for s in "${STEPS[@]}"; do + step_def "$s" || die "unknown step $s (see: $0 plan)" + [ -n "$TEST" ] && EST=5 + total=$((total + EST)) + for n in $NEEDS; do + case $n in + *!) case "$seen" in *" ${n%!} "*) ;; *) not_run "step $s needs step ${n%!} earlier in this run (the store and its key live for one run)" ;; esac ;; + *) case "$seen" in *" $n "*) ;; *) step_ok "$OUT" "$n" "$SHA" || not_run "step $s needs step $n earlier in this run or its passing step receipt in $OUT/$n for bin $SHA" ;; esac ;; + esac + done + seen="$seen$s " + done + lease=$(cat "${SPARK_WINDOW_DIR:-/nonexistent}/lease" 2>/dev/null); held=$(cat "${SPARK_WINDOW_DIR:-/nonexistent}/held" 2>/dev/null) + [ -n "$lease" ] && [ -n "$held" ] || not_run "no lease/held in SPARK_WINDOW_DIR='${SPARK_WINDOW_DIR:-}'" + [ -e "$SPARK_WINDOW_DIR/expired" ] && not_run "the lease has expired ($SPARK_WINDOW_DIR/expired)" + heldt=$(date -d "$held" +%s) || not_run "cannot read held time '$held'" + DEADLINE=$(( heldt + lease * ${SPARK_LEASE_UNIT_S:-60} )) + cap=${DRA86_CAP_S:-}; case $cap in '') ;; *[!0-9]*) die "DRA86_CAP_S=$cap: whole seconds" ;; + *) [ $((heldt + cap)) -ge "$DEADLINE" ] || DEADLINE=$((heldt + cap)) ;; esac + export DRA86_DEADLINE=$DEADLINE + left=$(( DEADLINE - $(date +%s) )) + [ "$total" -le "$left" ] || not_run "steps ${STEPS[*]} estimate $total s, the lease has $left s left" + PORT=${DRA86_TEST_PORT:-18192}; [ -n "$TEST" ] || PORT=18192 + MODEL=$HOME/models/qwen3.6-35b-a3b-fp8-95a723d0 + for t in curl jq ss flock setsid timeout sha256sum od; do command -v $t > /dev/null || not_run "$t missing"; done + [ -z "$(ss -ltnH "sport = :$PORT")" ] || not_run "a listener is on $PORT" + if [ -z "$TEST" ]; then + command -v nvidia-smi > /dev/null || not_run "nvidia-smi missing" + for port in 18091 18300 18310; do [ -z "$(ss -ltnH "sport = :$port")" ] || not_run "a listener is on $port"; done + apps=$(nvidia-smi --query-compute-apps=pid,process_name,used_memory --format=csv,noheader 2>&1) || not_run "nvidia-smi failed: $apps" + [ -z "$apps" ] || not_run "compute apps on the chip: $apps" + [ -f "$MODEL/config.json" ] || not_run "model $MODEL missing" + fi + mkdir -p "$OUT" || not_run "cannot create $OUT" + PIDF=$OUT/.server.$$.pid + log() { echo "$(date -u +%FT%TZ) $*" | tee -a "$OUT/run.log" >&2; } + board() { + if [ -n "$TEST" ]; then echo "$(date -u +%FT%TZ) DRA86PrefixCache: $*" >> "$OUT/board.log" + else echo "$(date -u +%FT%TZ) DRA86PrefixCache: $*" >> "$HOME/handoffs/BOARD.md"; fi + } + # The sealed store's key: 32 random bytes for this run only, handed to the server's environment (the server + # reads it once and removes it), never written to a file or a receipt. + KEY=$(od -An -tx1 -N32 /dev/urandom | tr -d ' \n'); [ ${#KEY} = 64 ] || not_run "no store key" + SERVER= + stop_server() { + [ -n "$SERVER" ] || return 0 + kill -TERM -- "-$SERVER" 2>/dev/null + for _ in $(seq 20); do kill -0 -- "-$SERVER" 2>/dev/null || break; sleep 1; done + kill -KILL -- "-$SERVER" 2>/dev/null; wait "$SERVER" 2>/dev/null; rm -f "$PIDF"; SERVER= + } + # start_server LOG: ENVS (+ the store) from step_def; the live start-35b-batch.sh flags on a loopback test port. + start_server() { + local aff cpus lim l senv=() + [ "$STORE" = 1 ] && senv=(AIEN_Q36_PREFIX_DIR="$OUT/4a/store" AIEN_KV_STORE_KEY="$KEY") + cpus=$(cat /sys/devices/system/cpu/online); [ -n "$TEST" ] && cpus=0-9 + aff=(taskset -c "$cpus"); "${aff[@]}" true 2> /dev/null || aff=() + (cd "$(dirname "$BIN")" && exec setsid "${aff[@]}" env AIEN_GB10_LOCK_HELD=1 AIEN_SERVE_GPU_LOCK=/tmp/aien-serve-$PORT.lock \ + AIEN_Q36_STROKE=0 "${ENVS[@]}" "${senv[@]}" "$BIN" --engine omega --model-dir "$MODEL" --port $PORT --bind 127.0.0.1 \ + --max-tokens-cap 16384 --thinking off --max-context 49152 --batch-slots 8) > "$1" 2>&1 < /dev/null & + SERVER=$!; echo "$SERVER" > "$PIDF" + lim=$(left_s 300) || { log "no lease time left to start the server"; stop_server; return 1; } + for _ in $(seq "$lim"); do + kill -0 "$SERVER" 2>/dev/null || { log "server exited during load: $1"; wait "$SERVER" 2>/dev/null; rm -f "$PIDF"; SERVER=; return 1; } + curl -s -m 2 127.0.0.1:$PORT/health > /dev/null && break; sleep 1 + done + curl -s -m 2 127.0.0.1:$PORT/health > /dev/null || { log "server not healthy in $lim s"; stop_server; return 1; } + [ "$(ps -o sid= -p "$SERVER" | tr -d ' ')" = "$SERVER" ] || { log "server $SERVER is not its own session leader"; stop_server; return 1; } + l=$(ss -ltnH "sport = :$PORT" | awk '{print $4}') + if [ -z "$l" ] || echo "$l" | grep -qv '^127\.0\.0\.1:'; then log "listener check FAILED on $PORT: $l"; stop_server; return 1; fi + } + trap 'stop_server; KEY=; board "GPU-END dra-86 window-dra86.sh window $WIN steps ${STEPS[*]} -> $OUT (rc ${RC:-?})"' EXIT + trap 'log "interrupted"; RC=4; exit 4' INT TERM + setsid bash "$SELF" _watch $$ "$HOLDER" "$DEADLINE" "$PIDF" >> "$OUT/watch.log" 2>&1 < /dev/null & + board "GPU-START dra-86 window-dra86.sh window $WIN steps ${STEPS[*]} (est $total s, lease left $left s; gb10 lock held by our pid $HOLDER; bin $SHA)" + log "window $WIN lock holder $HOLDER bin $BIN sha256 $SHA steps ${STEPS[*]} est $total s left $left s deadline $(date -u -d @$DEADLINE +%FT%TZ)" + RC=0 + for s in "${STEPS[@]}"; do + step_def "$s"; [ -n "$TEST" ] && EST=5 + D=$OUT/$s; mkdir -p "$D"; t0=$(date +%s); why= + [ "$s" = 4a ] && { rm -rf "$D/store"; mkdir -m 700 "$D/store"; } + log "step $s: batch door, env '${ENVS[*]:-}'$([ $STORE = 1 ] && echo " + store $OUT/4a/store"), $PROBE, est $EST s" + if [ $((t0 + EST)) -gt "$DEADLINE" ]; then + ready=-1; RC=3; why="not started: est $EST s, $((DEADLINE - t0)) s left"; : > "$D/probe.out" + elif start_server "$D/server.log"; then + ready=$(( $(date +%s) - t0 )) + read -r kind a1 <<<"$PROBE" + args=("$kind" $PORT "$D" "$a1" "$SHA" "dra86-$s") + [ "$kind" = conv ] && [ "$a1" != ref ] && args+=("$OUT/1/conv.jsonl") + if lim=$(left_s); then + DRA86_SERVER_LOG=$D/server.log DRA86_STORE=$OUT/4a/store DRA86_RED=$OUT/2/conv-receipt.json \ + timeout -k 10 "$lim" bash "$SELF" "${args[@]}" > "$D/probe.out"; RC=$? + case $RC in 124|137) RC=2; why="probe stopped at the lease deadline" ;; esac + else + RC=2; why="no lease time left for the probe" + fi + stop_server + else + ready=-1; RC=3; why="server did not come up" + fi + el=$(( $(date +%s) - t0 )); expired=false + if [ -e "$SPARK_WINDOW_DIR/expired" ] || [ "$(date +%s)" -ge "$DEADLINE" ]; then + expired=true; [ $RC = 3 ] || { RC=2; why="lease expired before the step ended${why:+ ($why)}"; } + fi + pj=$(tail -n 1 "$D/probe.out" 2>/dev/null | jq -c . 2>/dev/null); [ -n "$pj" ] || pj=null + case $RC in 0) v=$(jq -r '.verdict // "PASS"' <<<"$pj") ;; 1) v=FAIL ;; 2) v=INCONCLUSIVE ;; 3) v=NOT_RUN ;; *) v=INCONCLUSIVE ;; esac + e="${ENVS[*]:-}"; [ $STORE = 1 ] && e="$e AIEN_Q36_PREFIX_DIR=$OUT/4a/store AIEN_KV_STORE_KEY=(run key)" + jq -cn --arg s "$s" --arg w "$WIN" --arg b "$BIN" --arg h "$SHA" --arg e "$e" --arg p "$PROBE" \ + --argjson est $EST --argjson ready $ready --argjson el $el --argjson rc $RC --arg hold "$HOLDER" --arg at "$(date -u +%FT%TZ)" \ + --argjson probe "$pj" --argjson x $expired --arg v "$v" --arg why "$why" --argjson dl "$DEADLINE" \ + '{step:$s, window:$w, bin:$b, bin_sha256:$h, door:"batch", env:$e, probe:$p, est_s:$est, server_ready_s:$ready, elapsed_s:$el, + rc:$rc, verdict:$v, why:$why, lease_expired:$x, deadline:$dl, lock_holder:$hold, at:$at, result:$probe}' \ + | tee "$D/step-receipt.json" + [ $RC = 0 ] || { log "step $s rc $RC ($v${why:+: $why}): stopping"; exit $RC; } + done + exit 0 ;; +esac + +[ -n "${SPARK_WINDOW:-}" ] || not_run "no SPARK_WINDOW: the probes run from '$0 run' inside a window" +WIN=$SPARK_WINDOW +MODE=${1:-}; PORT=${2:-}; OUT=${3:-}; KIND=${4:-}; BIN=${5:-}; LABEL=${6:-}; REF=${7:-} +[ -n "$MODE" ] && [ -n "$PORT" ] && [ -n "$OUT" ] && [ -n "$KIND" ] || die "usage: see the header" +[[ $BIN =~ ^[0-9a-f]{64}$ ]] || die "BIN_SHA256 must be the server binary's sha256" +[ -n "$LABEL" ] || die "LABEL missing" +URL=http://127.0.0.1:$PORT +(cd "$REPO" && sha256sum -c --quiet "$HERE/SHA256SUMS") || die "pinned inputs changed" +mkdir -p "$OUT" +SLOG=${DRA86_SERVER_LOG:-} +MODEL=$(curl -s -m 10 "$URL/v1/models" | jq -r '.data[0].id // empty' 2>/dev/null) +[ -n "$MODEL" ] || die "no model on $URL" +SET=$HERE/set32.json; DEF=$(jq -c .defaults "$SET"); L369=$REPO/evidence/merge-train/l369 +printf '%s' "Now say that again in fewer words." > "$OUT/follow.txt"; FOLLOW=$OUT/follow.txt +# Bodies go through files and stdin: a ~33k-token prompt is over Linux's 128 KiB limit for one argv string. +req() { # [stream] + jq -cn --arg m "$MODEL" --slurpfile msg "$1" --argjson n "$2" --argjson d "$DEF" --argjson s "${3:-false}" \ + '$d + {model:$m, messages:$msg[0], max_tokens:$n} + (if $s then {stream:true, stream_options:{include_usage:true}} else {} end)' +} +user() { jq -cn --rawfile u "$1" '[{role:"user",content:$u}]'; } # +turn2() { jq -cn --rawfile u "$1" --rawfile a "$2" --rawfile f "$3" \ + '[{role:"user",content:$u},{role:"assistant",content:$a},{role:"user",content:$f}]'; } # files +ask() { # : prints the HTTP code (000 without lease time left) + local m; m=$(left_s 1800) || { : > "$3"; echo 000; return; } + req "$1" "$2" | curl -s -m "$m" -o "$3" -w '%{http_code}' "$URL/v1/chat/completions" -H 'Content-Type: application/json' --data-binary @- +} +ids() { jq -c '.usage.aien_token_ids | select(type == "array" and length > 0)' "$1" 2>/dev/null; } +idsj() { local x; x=$(ids "$1"); echo "${x:-null}"; } +judge() { # : SAME|DIFF|SHORT|NO_IDS + local got; [ "$1" = 200 ] || { echo NO_IDS; return; } + got=$(ids "$2"); [ -n "$got" ] || { echo NO_IDS; return; } + jq -rn --argjson g "$got" --argjson w "$3" ' + ([$g, $w] | map(length) | min) as $m + | if $g == $w then "SAME" + elif ([range(0; $m) | select($g[.] != $w[.])] | length) > 0 then "DIFF" + elif ($g | length) > ($w | length) then "DIFF" + else "SHORT" end' +} +nlines() { if [ -n "$SLOG" ] && [ -f "$SLOG" ]; then wc -l < "$SLOG"; else echo 0; fi; } +since() { [ -n "$SLOG" ] && [ -f "$SLOG" ] && tail -n "+$(($1 + 1))" "$SLOG"; } +# cases KIND: lines "namemax_tokenssource" (source: set32 index or an l369 file) +cases() { + case $1 in + ref|red|green) for i in $(seq 0 31); do printf 'p%s\t%s\tset:%s\n' $i "$(jq -r ".prompts[$i].max_tokens" "$SET")" $i; done + for n in long-256 long-2048 long-8192; do printf '%s\t24\tfile:%s\n' $n $n; done ;; + write|reload|other) printf 'long-2048\t24\tfile:long-2048\n' ;; + budget) for n in long-256 long-2048 long-8192; do printf '%s\t24\tfile:%s\n' $n $n; done ;; + esac +} +text_of() { case $1 in set:*) jq -j ".prompts[${1#set:}].user" "$SET" ;; file:*) cat "$L369/${1#file:}.txt" ;; esac; } + +case $MODE in +conv) + case $KIND in ref|red|green|write|reload|other|budget) ;; *) die "conv KIND ref|red|green|write|reload|other|budget" ;; esac + if [ "$KIND" != ref ]; then [ -f "$REF" ] || die "reference $REF missing (step 1 first)"; fi + [ -n "$SLOG" ] || die "DRA86_SERVER_LOG unset: the verdicts read the door's log" + : > "$OUT/conv.jsonl" + declare -A n=([SAME]=0 [DIFF]=0 [SHORT]=0 [NO_IDS]=0 [REC]=0); t2n=0; restored=0; refused=0; d2=0 + while IFS=$'\t' read -r name mt src; do + U=$OUT/$name.user.txt; A=$OUT/$name.a1.txt; text_of "$src" > "$U"; r1=null; r2=null + [ "$KIND" = ref ] || { r1=$(jq -c --arg n "$name" 'select(.name == $n) | .ids1' "$REF"); r2=$(jq -c --arg n "$name" 'select(.name == $n) | .ids2' "$REF"); } + [ -n "$r1" ] || r1=null; [ -n "$r2" ] || r2=null + v1=-; h1=-; a1= + if [ "$KIND" = reload ] || [ "$KIND" = other ]; then + a1=$(jq -r --arg n "$name" 'select(.name == $n) | .text1' "$REF") + else + user "$U" > "$OUT/$name.t1.msg"; h1=$(ask "$OUT/$name.t1.msg" "$mt" "$OUT/$name.t1.raw") + if [ "$KIND" = ref ]; then v1=REC; [ -n "$(ids "$OUT/$name.t1.raw")" ] && [ "$h1" = 200 ] || v1=NO_IDS + else v1=$(judge "$h1" "$OUT/$name.t1.raw" "$r1"); fi + n[$v1]=$((n[$v1] + 1)); a1=$(jq -r '.choices[0].message.content // empty' "$OUT/$name.t1.raw" 2>/dev/null) + fi + v2=-; h2=-; rl=; fl=; jl= + if [ "$KIND" != write ]; then + printf '%s' "$a1" > "$A"; turn2 "$U" "$A" "$FOLLOW" > "$OUT/$name.t2.msg" + b=$(nlines); h2=$(ask "$OUT/$name.t2.msg" 16 "$OUT/$name.t2.raw"); seg=$(since "$b") + rl=$(grep -E 'prompt cache restore: ' <<<"$seg" | tail -n 1); fl=$(grep -E 'prompt cache restore refused' <<<"$seg" | tail -n 1) + jl=$(grep -E 'qwen36-batch: join: ' <<<"$seg" | tail -n 1) + if [ "$KIND" = ref ]; then v2=REC; [ -n "$(ids "$OUT/$name.t2.raw")" ] && [ "$h2" = 200 ] || v2=NO_IDS + else v2=$(judge "$h2" "$OUT/$name.t2.raw" "$r2"); fi + n[$v2]=$((n[$v2] + 1)); t2n=$((t2n + 1)); [ -n "$rl" ] && restored=$((restored + 1)); [ -n "$fl" ] && refused=$((refused + 1)) + [ "$v2" = DIFF ] && d2=$((d2 + 1)) + fi + jq -cn --arg n "$name" --arg v1 "$v1" --arg v2 "$v2" --arg h1 "$h1" --arg h2 "$h2" --arg a1 "$a1" --arg rl "$rl" --arg fl "$fl" --arg jl "$jl" \ + --arg win "$WIN" --arg b "$BIN" --argjson g1 "$(idsj "$OUT/$name.t1.raw")" --argjson g2 "$(idsj "$OUT/$name.t2.raw")" \ + '{name:$n, t1:$v1, t2:$v2, http1:$h1, http2:$h2, ids1:$g1, ids2:$g2, text1:$a1, restore_log:$rl, refused_log:$fl, join_log:$jl, window:$win, bin_sha256:$b}' \ + 2>/dev/null >> "$OUT/conv.jsonl" || echo "{\"name\":\"$name\",\"t1\":\"NO_IDS\",\"t2\":\"NO_IDS\"}" >> "$OUT/conv.jsonl" + done < <(cases "$KIND") + all=$(cat "$SLOG" 2>/dev/null); why= + bad=$((n[NO_IDS] + n[SHORT])); verdict=FAIL; rc=1 + case $KIND in + ref) + if [ "${n[NO_IDS]}" -gt 0 ]; then verdict=INCONCLUSIVE; rc=2; why="a turn without ids" + elif grep -q 'prompt cache off' <<<"$all"; then verdict=RECORDED; rc=0 + else why="no 'prompt cache off' line: the switch is not off by default"; fi ;; + red) + if [ $bad -gt 0 ]; then verdict=INCONCLUSIVE; rc=2; why="NO_IDS/SHORT turns" + elif ! grep -q 'prompt cache on: .*POSITION MUTANT' <<<"$all"; then verdict=INCONCLUSIVE; rc=2; why="the mutant is not on" + elif [ $restored -lt $t2n ]; then verdict=INCONCLUSIVE; rc=2; why="$((t2n - restored)) turn 2 without a restore line" + elif [ $d2 -gt 0 ]; then verdict=PASS; rc=0 + else why="no turn 2 differs: the gate cannot see the off-by-one"; fi ;; + green) + if [ "${n[NO_IDS]}" -gt 0 ]; then verdict=INCONCLUSIVE; rc=2; why="a turn without ids" + elif [ -n "${DRA86_RED:-}" ] && ! jq -e --arg b "$BIN" '.verdict == "PASS" and .kind == "red" and .bin_sha256 == $b' "$DRA86_RED" > /dev/null 2>&1; then + verdict=INCONCLUSIVE; rc=2; why="no red PASS receipt for this binary at $DRA86_RED" + elif ! grep -q 'prompt cache on: budget 16.0 GiB' <<<"$all"; then why="the default budget is not 16.0 GiB" + elif [ "${n[SAME]}" -ne $((2 * t2n)) ]; then why="$((2 * t2n - n[SAME])) turns differ from the cold reference" + elif [ $restored -ne $t2n ]; then why="$((t2n - restored)) turn 2 not restored from the cache" + elif [ $refused -gt 0 ]; then why="$refused restore refused" + else verdict=PASS; rc=0; fi ;; + write) + for _ in $(seq 60); do ls "$DRA86_STORE"/*.q36p > /dev/null 2>&1 && ! ls "$DRA86_STORE"/.*.tmp > /dev/null 2>&1 && break; sleep 1; done + files=$(ls "$DRA86_STORE"/*.q36p 2>/dev/null | wc -l) + if [ "${n[NO_IDS]}" -gt 0 ]; then verdict=INCONCLUSIVE; rc=2; why="no ids" + elif ! grep -q 'q36 prefix: store .* open: 0 nodes loaded' <<<"$all"; then why="the store did not open empty" + elif [ "${n[SAME]}" -ne 1 ]; then why="turn 1 differs from the reference" + elif [ "$files" -lt 1 ]; then why="no sealed node in $DRA86_STORE" + else verdict=RECORDED; rc=0; why="$files sealed nodes"; fi ;; + reload|other) + ol=$(grep -E 'q36 prefix: store .* open: ' <<<"$all" | tail -n 1) + ld=$(sed -nE 's/.* open: ([0-9]+) nodes loaded .*/\1/p' <<<"$ol"); dc=$(sed -nE 's/.*\), ([0-9]+) discarded.*/\1/p' <<<"$ol") + if [ "${n[NO_IDS]}" -gt 0 ]; then verdict=INCONCLUSIVE; rc=2; why="no ids" + elif [ -z "$ol" ]; then why="no store open line" + elif [ "${n[SAME]}" -ne 1 ]; then why="turn 2 differs from the cold reference" + elif [ "$KIND" = reload ]; then + if [ "${ld:-0}" -ge 1 ] && [ $restored = 1 ]; then verdict=PASS; rc=0; else why="loaded ${ld:-?}, restored $restored (want >= 1 and 1)"; fi + else + if [ "${ld:-1}" = 0 ] && [ "${dc:-0}" -ge 1 ] && [ $restored = 0 ]; then verdict=PASS; rc=0 + else why="loaded ${ld:-?} discarded ${dc:-?} restored $restored (want 0, >= 1, 0)"; fi + fi ;; + budget) + sv=$(grep -E 'prompt cache save: ' <<<"$all") + ns=$(grep -c . <<<"$sv"); nr=$(grep -c 'conversation resident [0-9]* nodes [0-9.]* MiB' <<<"$sv") + over=$(sed -nE 's/.*; pool [0-9]+ nodes ([0-9.]+) MiB of .*/\1/p' <<<"$sv" | awk '$1 > 512.0' | wc -l) + ev=$(sed -nE 's/.* ([0-9]+) evicted, .*/\1/p' <<<"$sv" | sort -n | tail -n 1) + if [ "${n[NO_IDS]}" -gt 0 ]; then verdict=INCONCLUSIVE; rc=2; why="a turn without ids" + elif ! grep -q 'prompt cache on: budget 0.5 GiB' <<<"$all"; then why="the budget is not 0.5 GiB" + elif [ -z "$sv" ]; then why="no save line" + elif [ "$nr" -ne "$ns" ]; then why="$((ns - nr)) save lines without the conversation's resident bytes" + elif [ "$over" -gt 0 ]; then why="$over save lines report a pool over 512 MiB" + elif [ "${ev:-0}" -lt 1 ]; then why="nothing evicted" + elif [ "${n[SAME]}" -ne 6 ]; then why="$((6 - n[SAME])) turns differ from the cold reference" + else verdict=PASS; rc=0; why="$ns saves, max evicted $ev"; fi ;; + esac + jq -cn --arg k "$KIND" --arg v $verdict --arg b "$BIN" --arg l "$LABEL" --arg why "$why" --argjson s "${n[SAME]}" --argjson d "${n[DIFF]}" \ + --argjson sh "${n[SHORT]}" --argjson x "${n[NO_IDS]}" --argjson rc "${n[REC]}" --argjson t2 $t2n --argjson rs $restored --argjson rf $refused \ + --arg port "$PORT" --arg at "$(date -u +%FT%TZ)" --arg win "$WIN" \ + '{case:"conv", kind:$k, verdict:$v, why:$why, bin_sha256:$b, label:$l, window:$win, same:$s, diff:$d, short:$sh, no_ids:$x, recorded:$rc, + turn2:$t2, restored:$rs, refused:$rf, port:$port, at:$at}' | tee "$OUT/conv-receipt.json" + exit $rc ;; +time) + case $KIND in warm) runs="1 2 3" ;; cold) runs="1" ;; *) die "time KIND warm|cold" ;; esac + # turn 1: ~32.8k tokens (long-8192 x 4); turn 2 adds "Part r." + long-256 x 4 (~1k tokens). + L32=$OUT/l32.txt; for _ in 1 2 3 4; do cat "$L369/long-8192.txt"; printf '\n\n'; done > "$L32" + : > "$OUT/time.jsonl"; ok=1 + user "$L32" > "$OUT/t1.msg"; h1=$(ask "$OUT/t1.msg" 16 "$OUT/t1.raw") + jq -j '.choices[0].message.content // empty' "$OUT/t1.raw" > "$OUT/a1.txt" 2>/dev/null + p1=$(jq -r '.usage.prompt_tokens // empty' "$OUT/t1.raw" 2>/dev/null) + [ "$h1" = 200 ] && [ -s "$OUT/a1.txt" ] || ok=0 + for run in $runs; do + o=$OUT/t2-r$run; : > "$o.sse" + { printf 'Part %s.\n' "$run"; for _ in 1 2 3 4; do cat "$L369/long-256.txt"; printf '\n\n'; done; } > "$o.new.txt" + turn2 "$L32" "$OUT/a1.txt" "$o.new.txt" > "$o.msg"; req "$o.msg" 16 true > "$o.body" # built before t0 + b=$(nlines); t0=$(date +%s.%N); first="" + if m=$(left_s 1800); then + while IFS= read -r line; do + [ -z "$first" ] && [[ $line =~ ^data:.*\"content\":\ *\"[^\"] ]] && first=$(date +%s.%N) + printf '%s\n' "$line" >> "$o.sse" + done < <(curl -s -N -m "$m" -w '\nHTTP %{http_code}\n' "$URL/v1/chat/completions" -H 'Content-Type: application/json' \ + --data-binary "@$o.body") + fi + t1=$(date +%s.%N); seg=$(since "$b") + code=$(grep -o '^HTTP [0-9]*' "$o.sse" | tail -n 1 | cut -c6-) + usage=$(grep '^data: {' "$o.sse" | sed 's/^data: //' | jq -c 'select(.usage != null) | .usage' 2>/dev/null | tail -n 1) + rl=$(grep -E 'prompt cache restore: ' <<<"$seg" | tail -n 1); jl=$(grep -E 'qwen36-batch: join: ' <<<"$seg" | tail -n 1) + ll=$(grep -E 'qwen36-batch: leave: ' <<<"$seg" | tail -n 1) + rms=$(sed -nE 's/.* MiB in ([0-9]+) ms, conversation resident.*/\1/p' <<<"$rl"); pms=$(sed -nE 's/.*, prefill ([0-9]+) ms,.*/\1/p' <<<"$ll") + reuse=$(sed -nE 's/.* reuse ([0-9]+) tok .*/\1/p' <<<"$jl"); pt=$(sed -nE 's/.*join: prompt ([0-9]+) tok,.*/\1/p' <<<"$jl") + good=$(jq -n --arg c "${code:-}" --arg f "$first" --argjson u "${usage:-null}" --arg k "$KIND" --arg rl "$rl" --arg p "$pms" \ + '$c == "200" and $f != "" and ($u | type) == "object" and (($u.completion_tokens // 0) > 0) and $p != "" + and (if $k == "warm" then $rl != "" else $rl == "" end)') + [ "$good" = true ] || ok=0 + jq -cn --arg k "$KIND" --argjson r $run --arg b "$BIN" --arg l "$LABEL" --arg h "${code:-}" --arg t0 "$t0" --arg tf "$first" \ + --arg t1 "$t1" --argjson u "${usage:-null}" --argjson g "$good" --arg win "$WIN" --arg rms "$rms" --arg pms "$pms" \ + --arg reuse "$reuse" --arg pt "$pt" --arg p1 "$p1" --arg rl "$rl" --arg ll "$ll" \ + '{kind:$k, run:$r, bin_sha256:$b, label:$l, window:$win, http:$h, ok:$g, t0:$t0, t_first:$tf, t_end:$t1, + http_ttft_s:(if $tf == "" then null else (($tf | tonumber) - ($t0 | tonumber)) end), + turn1_prompt_tok:($p1 | tonumber? // null), turn2_prompt_tok:($pt | tonumber? // null), reused_tok:($reuse | tonumber? // null), + door_restore_ms:($rms | tonumber? // null), door_prefill_ms:($pms | tonumber? // null), restore_log:$rl, leave_log:$ll, usage:$u}' \ + | tee -a "$OUT/time.jsonl" + done + if [ $ok = 1 ]; then jq -cn --arg k "$KIND" --arg win "$WIN" --arg b "$BIN" --arg l "$LABEL" '{case:"time", kind:$k, verdict:"RECORDED", window:$win, bin_sha256:$b, label:$l}'; exit 0; fi + jq -cn --arg k "$KIND" --arg win "$WIN" --arg b "$BIN" --arg l "$LABEL" \ + '{case:"time", kind:$k, verdict:"INCONCLUSIVE", window:$win, bin_sha256:$b, label:$l, why:"turn 1 failed, or a run had no HTTP 200, first delta, usage, leave line, or (warm) restore line / (cold) a restore"}'; exit 2 ;; +*) die "mode plan|run|conv|time" ;; +esac diff --git a/evidence/l375/ask.sh b/evidence/l375/ask.sh new file mode 100755 index 00000000..cce0ef8a --- /dev/null +++ b/evidence/l375/ask.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# ask.sh : streams one chat request; writes .ids (generated token +# ids from usage.aien_token_ids) and appends " ttft_ms= total_ms=..." to /times.txt +set -uo pipefail +port=$1; req=$2; tag=$3; od=$4 +t0=$(date +%s%N); first="" +curl -sN --max-time 1800 -H 'Content-Type: application/json' --data-binary @"$req" "http://127.0.0.1:$port/v1/chat/completions" > "$od/$tag.sse" & +cpid=$! +# The first delta with text: poll the growing file (1 ms grain is enough against seconds). +while kill -0 $cpid 2>/dev/null; do + if [ -z "$first" ] && grep -q '"content":"[^"]\|"reasoning_content":"[^"]\|"tool_calls"' "$od/$tag.sse" 2>/dev/null; then first=$(date +%s%N); fi + sleep 0.001 +done +wait $cpid +t1=$(date +%s%N) +[ -z "$first" ] && first=$t1 +grep -o '"aien_token_ids":\[[0-9,]*\]' "$od/$tag.sse" | tail -1 | grep -o '[0-9][0-9,]*' > "$od/$tag.ids" +echo "$tag ttft_ms=$(( (first - t0) / 1000000 )) total_ms=$(( (t1 - t0) / 1000000 )) ids=$(tr ',' '\n' < "$od/$tag.ids" | grep -c .)" | tee -a "$od/times.txt" diff --git a/evidence/l375/gate.sh b/evidence/l375/gate.sh new file mode 100755 index 00000000..74fa538f --- /dev/null +++ b/evidence/l375/gate.sh @@ -0,0 +1,79 @@ +#!/bin/bash +# L375 chip gate: shared prompt cache on the 35B batch door. Loads an extra 35B ONLY under q36-extra +# (port 18097, 1 row, never 18091). Phases: B pool+store (cold, second chat, cold-vs-restored, tool +# change, goldens), C restart on the same store (first chat after restart, restored-from-disk words), +# D position mutant (must go red). Usage: gate.sh +set -uo pipefail +BIN=$1 +EV=$HOME/workspace/sc-q36-prefix/evidence/l375 +OD=$EV/run-$(date -u +%Y%m%dT%H%MZ); mkdir -p "$OD" +M=$HOME/models/qwen3.6-35b-a3b-fp8-95a723d0 +PORT=18097 +NEED=${Q36_EXTRA_NEED_GB:-44} +POOL_GB=${POOL_GB:-6} +STORE=$(mktemp -d /tmp/l375-store-XXXXXX); chmod 700 "$STORE" +KEY=$(openssl rand -hex 32) # a test key, held in this shell only +cd "$EV" +./mkreq.sh "$OD/req1.json" "In one sentence, which tool would you use to read a file?" > /dev/null +./mkreq.sh "$OD/req2.json" "Name two tools that could list a directory." > /dev/null +./mkreq.sh "$OD/req3.json" "In one sentence, which tool would you use to read a file?" 7 > /dev/null +./mkreq.sh "$OD/req4.json" "What is the date today, according to your instructions?" > /dev/null +./mkreq.sh "$OD/g1.json" "Write a haiku about a lighthouse." -1 4 > /dev/null +./mkreq.sh "$OD/g2.json" "Explain what a hash table is in two sentences." -1 4 > /dev/null +sha256sum "$BIN/aien-serve-http" > "$OD/bin.sha256" +SPID="" +start() { + local tag=$1; shift + echo "$(date -u +%FT%TZ) phase $tag: waiting for the q36-extra slot" | tee -a "$OD/gate.log" + Q36_EXTRA_LEDGER=L375 Q36_EXTRA_WAIT=7200 Q36_EXTRA_NEED_GB=$NEED q36-extra env AIEN_Q36_STROKE=0 AIEN_Q36_PREFIX=1 AIEN_Q36_PREFIX_POOL_GB=$POOL_GB "$@" \ + "$BIN/aien-serve-http" --engine omega --model-dir "$M" --port $PORT --max-context 32768 \ + --max-tokens-cap 512 --thinking off --batch-slots 1 > "$OD/server-$tag.log" 2>&1 & + SPID=$! + for i in $(seq 1 1200); do + curl -sf "http://127.0.0.1:$PORT/health" > /dev/null 2>&1 && { echo "$(date -u +%FT%TZ) phase $tag: up" | tee -a "$OD/gate.log"; return 0; } + kill -0 $SPID 2>/dev/null || { echo "phase $tag: server exited" | tee -a "$OD/gate.log"; tail -5 "$OD/server-$tag.log" >> "$OD/gate.log"; return 1; } + sleep 3 + done + return 1 +} +stop() { + # Let the store writer finish (no temp files, file count steady) before stopping. + local prev=-1 n + for i in $(seq 1 120); do + n=$(ls "$STORE" | grep -c .); ls -a "$STORE" | grep -q '\.tmp$' || { [ "$n" = "$prev" ] && break; } + prev=$n; sleep 2 + done + kill $SPID; wait $SPID 2>/dev/null + echo "$(date -u +%FT%TZ) stopped, store holds $(ls "$STORE" | grep -c q36p) nodes, $(du -sh "$STORE" | cut -f1)" | tee -a "$OD/gate.log" +} +ask() { + ./ask.sh $PORT "$OD/$1.json" "$2" "$OD" >> "$OD/gate.log" + if [ ! -s "$OD/$2.ids" ]; then + echo "ABORT: $2 gave no tokens: $(head -c 300 "$OD/$2.sse")" | tee -a "$OD/gate.log"; kill $SPID; wait $SPID 2>/dev/null; rm -rf "$STORE"; exit 1 + fi +} + +start B AIEN_Q36_PREFIX_DIR="$STORE" AIEN_KV_STORE_KEY="$KEY" || exit 1 +ask req1 b1; ask req2 b2; ask req1 b1r; ask req3 b3; ask req1 b1x +ask g1 g1a; ask g2 g2a; ask g1 g1b; ask g2 g2b +stop +start C AIEN_Q36_PREFIX_DIR="$STORE" AIEN_KV_STORE_KEY="$KEY" || exit 1 +ask req4 c4; ask req1 c1 +stop +start D AIEN_Q36_PREFIX_MUTANT=1 || exit 1 +ask g1 d1a; ask g2 d2; ask g1 d1b +stop +rm -rf "$STORE" +same() { cmp -s "$OD/$1.ids" "$OD/$2.ids" && [ -s "$OD/$1.ids" ]; } +{ + echo "== verdict" + same b1 b1r && echo "PASS cold req1 == restored req1 (pool, same server)" || echo "FAIL cold req1 != restored req1" + same b1 b1x && echo "PASS cold req1 == req1 after the tool-change chat" || echo "FAIL req1 after tool change differs" + same b1 c1 && echo "PASS cold req1 == req1 restored from disk after restart" || echo "FAIL req1 from disk differs" + same g1a g1b && echo "PASS golden g1 cold == restored" || echo "FAIL golden g1" + same g2a g2b && echo "PASS golden g2 cold == restored" || echo "FAIL golden g2" + same g1a d1a && echo "PASS mutant server cold g1 == cold g1" || echo "FAIL mutant server cold g1 differs" + same d1a d1b && echo "FAIL mutant NOT caught (restored one position early, same words)" || echo "PASS mutant red: restore one position early changes the words" + echo "== times"; cat "$OD/times.txt" + echo "== door log"; grep -h "join:\|prompt cache restore\|store .* open\|prompt cache on\|tool marks\|tool order" "$OD"/server-*.log | sed 's/^aien-serve-http: //' | head -60 +} | tee "$OD/verdict.txt" diff --git a/evidence/l375/mkreq.sh b/evidence/l375/mkreq.sh new file mode 100755 index 00000000..55188b43 --- /dev/null +++ b/evidence/l375/mkreq.sh @@ -0,0 +1,24 @@ +#!/bin/bash +# L375: a Hermes-shaped chat request (no real dump on the Spark yet): 40 tools (~11k tokens, tool +# descriptions cut from this repo's docs), a ~6k-token system text whose last lines are a date line +# and a memory block (as Hermes renders them), then one user turn. Deterministic. +# mkreq.sh [changed-tool-index] [ntools] +set -euo pipefail +out=$1; user=$2; changed=${3:--1}; ntools=${4:-40} +cd "$(git rev-parse --show-toplevel)" +mapfile -t docs < <(find docs -name '*.md' -size +3k | sort | head -70) +tools='[]' +for i in $(seq 0 $((ntools - 1))); do + d=$(head -c 1500 "${docs[$i]}" | tr -s '\n' ' ' | cut -c1-1050) + [ "$i" = "$changed" ] && d="CHANGED: $d" + tools=$(jq -c --arg n "$(printf 'tool_%02d' $i)" --arg d "$d" '. + [{type:"function",function:{name:$n,description:$d, + parameters:{type:"object",properties:{path:{type:"string",description:"Absolute path the tool works on"}, + limit:{type:"integer",description:"Most items to return"}},required:["path"]}}}]' <<<"$tools") +done +sys="" +for i in $(seq 40 69); do sys+=$(head -c 900 "${docs[$i]}" | tr -s '\n' ' ')$'\n\n'; done +sys+=$'Current date: 2026-10-21 (Tuesday)\n\nMEMORY:\n- Drake prefers plain English.\n- The Spark serves the 35B on port 18091.\n' +jq -n --argjson tools "$tools" --arg sys "$sys" --arg user "$user" \ + '{model:"qwen3.6-35b-a3b-fp8", stream:true, temperature:0, max_tokens:48, aien_return_token_ids:true, tools:$tools, + messages:[{role:"system",content:$sys},{role:"user",content:$user}]}' > "$out" +echo "$out: $(wc -c < "$out") bytes" diff --git a/evidence/l375/run-window.sh b/evidence/l375/run-window.sh new file mode 100755 index 00000000..a63c61b9 --- /dev/null +++ b/evidence/l375/run-window.sh @@ -0,0 +1,12 @@ +#!/bin/bash +# L375: the chip gate inside its own spark-window (gb10 + quiet exclusive: the gate reports times), +# first come first served behind the windows already in line. Usage: run-window.sh +set -uo pipefail +cd "$(dirname "$0")" +out=$(spark-window open l375-prefix --ledger L375 --lease 60 --wait 2>&1) +id=$(grep -oE '[0-9]{8}T[0-9]{6}Z-[0-9a-f]{6}' <<<"$out" | tail -1) +[ -n "$id" ] || { echo "no window: $out"; exit 1; } +echo "$(date -u +%FT%TZ) window $id open" +spark-window run ./gate.sh "$1" +spark-window close "$id" +echo "$(date -u +%FT%TZ) window $id closed" diff --git a/evidence/merge-train/l375/prefix.sh b/evidence/merge-train/l375/prefix.sh new file mode 100755 index 00000000..4f14878a --- /dev/null +++ b/evidence/merge-train/l375/prefix.sh @@ -0,0 +1,77 @@ +#!/bin/bash +# L375 on the merge train: the 35B door's shared prompt cache, against the train's server. +# prefix.sh +# One server, one request at a time, Hermes-shaped requests (evidence/l375/mkreq.sh with 21 tools and a long +# system text, then one user turn; 16,830 prompt tokens with 20 tools, measured by the 35B tokenizer): +# 1 a chat A, cache on (fills the cache) +# 2 b-pool chat B: same head, another user message, cache on: restores the head +# 3 b-cold chat B with aien_test.prefix_pool false (read cold): ids must equal 2 +# 4 c-pool chat C: one tool description changed (it moves to the end of the tools), cache on +# 5 c-cold chat C read cold: ids must equal 4 +# 6 d-mutant chat D with aien_test.prefix_mutant (the restore lands one position early) +# 7 d-cold chat D read cold: ids must DIFFER from 6 (the red control) +# PASS (exit 0): 2 == 3, 4 == 5, 6 != 7, and the server log shows a prompt cache restore for 2, 4 and 6. +# FAIL: exit 1. No verdict: exit 2 (switch not honored, no ids, no echo, prompt over the context: the case +# needs MERGE_TRAIN_CTX >= 18432). Receipts (time to first word, tokens re-read) in /RESULTS.txt. +set -u +P=${1:?port}; O=${2:?out}; LOG=${3:?server log} +D=$(cd "$(dirname "$0")" && pwd); REPO=$(cd "$D/../../.." && pwd) +mkdir -p "$O"; : > "$O/times.txt" +nov() { echo "l375 prefix: NO VERDICT: $*" | tee "$O/verdict.txt"; exit 2; } +curl -s -m 10 "http://127.0.0.1:$P/health" > "$O/health.json" || nov "no answer from port $P" +for s in prefix_pool prefix_mutant; do + jq -e --arg s "$s" '.aien_test.honored | index($s)' "$O/health.json" > /dev/null || nov "switch $s not honored (lever not in this build)" +done +M=$(curl -s -m 10 "http://127.0.0.1:$P/v1/models" | jq -r '.data[0].id // empty'); [ -n "$M" ] || nov "no model id" + +req() { # + (cd "$REPO" && bash evidence/l375/mkreq.sh "$O/$1.base.json" "$2" "$3" 21 > /dev/null) || nov "mkreq failed for $1" + jq --arg m "$M" --argjson t "$4" '.model = $m | if $t == null then . else .aien_test = $t end' \ + "$O/$1.base.json" > "$O/$1.json" +} +ask() { # : one streamed request; ids, time to first word, the server log lines it wrote + local n0 k; n0=$(wc -l < "$LOG") + bash "$REPO/evidence/l375/ask.sh" "$P" "$O/$1.json" "$1" "$O" > /dev/null + tail -n +"$((n0 + 1))" "$LOG" | grep -E 'qwen36-batch: (join|leave|prompt cache)|tool (order|marks)' > "$O/$1.log" + grep -q 'context_length_exceeded' "$O/$1.sse" && nov "$1: prompt over the server's context (needs MERGE_TRAIN_CTX >= 18432)" + if grep -qE '^(data: )?\{"error":' "$O/$1.sse" || [ ! -s "$O/$1.ids" ]; then + echo "l375 prefix: FAIL: $1: the server failed the request (see $O/$1.sse)" | tee "$O/verdict.txt"; exit 1 + fi + for k in $(jq -r '.aien_test // {} | keys[]' "$O/$1.json"); do + grep -q "\"applied\":\[[^]]*\"$k\"" "$O/$1.sse" || nov "$1: the reply does not echo $k in usage.aien_test.applied" + done +} +restored() { grep -q 'join: .*(prompt cache, row' "$O/$1.log"; } + +req a "Summarise what the batch door does in two sentences." -1 null; ask a +req b-pool "List three risks of a shared prompt cache." -1 null; ask b-pool +req b-cold "List three risks of a shared prompt cache." -1 '{"prefix_pool":false}'; ask b-cold +req c-pool "Which tool would you use to read a file?" 10 null; ask c-pool +req c-cold "Which tool would you use to read a file?" 10 '{"prefix_pool":false}'; ask c-cold +req d-mutant "Name one thing the merge train checks." 10 '{"prefix_mutant":true}'; ask d-mutant +req d-cold "Name one thing the merge train checks." 10 '{"prefix_pool":false}'; ask d-cold + +fail=() +cmp -s "$O/b-pool.ids" "$O/b-cold.ids" || fail+=("chat B: cache words != cold words") +cmp -s "$O/c-pool.ids" "$O/c-cold.ids" || fail+=("chat C (tool changed): cache words != cold words") +cmp -s "$O/d-mutant.ids" "$O/d-cold.ids" && fail+=("RED-FAIL: the one-position-off restore gave the cold words") +for t in b-pool c-pool d-mutant; do restored "$t" || fail+=("$t: no prompt cache restore in the server log"); done +for t in b-cold c-cold d-cold; do grep -q "join: prompt [0-9]* tok, reuse 0 tok (cold" "$O/$t.log" || fail+=("$t: not a cold read in the server log"); done +grep -q "POSITION MUTANT" "$O/d-mutant.log" || fail+=("d-mutant: no POSITION MUTANT restore in the server log") + +{ + echo "L375 prompt cache on the merge train, port $P, model $M, $(date -u +%FT%H:%MZ)" + echo "time to first word (ms) and server join lines:" + for t in a b-pool b-cold c-pool c-cold d-mutant d-cold; do + echo " $(grep "^$t " "$O/times.txt")" + grep -o 'join: prompt [0-9]* tok, reuse [0-9]* tok ([a-z ]*' "$O/$t.log" | sed 's/^/ /' + done + echo "tool order: $(grep -ho 'tool order: .*' "$O"/c-pool.log | head -1)" + echo "cache saves: $(cat "$O"/*.log | grep -c 'prompt cache save:'), restores: $(cat "$O"/*.log | grep -c 'prompt cache restore:')" + grep -h 'prompt cache restore:' "$O"/*.log | sed 's/^.*prompt cache restore: / restore: /' | head -5 +} > "$O/RESULTS.txt" + +if [ ${#fail[@]} -eq 0 ]; then + echo "l375 prefix: PASS (B and C identical cold vs cache, mutant red, restores seen)" | tee "$O/verdict.txt"; exit 0 +fi +printf 'l375 prefix: FAIL: %s\n' "${fail[@]}" | tee "$O/verdict.txt"; exit 1 diff --git a/evidence/merge-train/suite.json b/evidence/merge-train/suite.json index c8c2b212..d9a32e2a 100644 --- a/evidence/merge-train/suite.json +++ b/evidence/merge-train/suite.json @@ -116,7 +116,7 @@ "id": "L375", "name": "shared prompt prefix", "present": { - "build": "prefix" + "switch": "prefix_pool" }, "arms": [ "plain" @@ -375,6 +375,23 @@ "$OUT/readers-gate" ], "about": "L371 eight readers: id listed; short input == plain ids; a ~5.6k-token excerpt is read by 8 readers (contiguous parts, notes each) and the final answer joins two far-apart facts; plain id has no aien_readers (red control). Needs 8 free rows (L371_READERS overrides). Not an exactness gate: readers are opt-in by id." + }, + { + "id": "l375-prefix", + "kind": "script", + "script": "evidence/merge-train/l375/prefix.sh", + "arms": [ + "plain" + ], + "levers": [ + "L375" + ], + "args": [ + "$PORT", + "$OUT/l375-prefix", + "$SERVER_LOG" + ], + "about": "L375 shared prompt cache: Hermes-shaped ~17k-token chats on the train server, cache on vs aien_test.prefix_pool false (cold) word for word (a new user message, then one changed tool), aien_test.prefix_mutant red; time-to-first-word receipts in RESULTS.txt. Needs MERGE_TRAIN_CTX >= 18432" } ] }