//! Typestate prefix tracking and hybrid GDN+KV checkpoint pool. //! //! Mirrors `PrefixState` and `nextCkptBoundary` in `proofs/slab_ring_dma.lean`: //! eliminates uninitialized MTP hidden-state reuse (F-03) and ghost/skipped checkpoints (F-06). /// Explicit typestate of the live engine prefix on GPU. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum PrefixState { Empty, TargetOnly { len: usize }, TargetWithMtp { len: usize, mtp_len: usize }, } impl PrefixState { pub fn target_only(len: usize) -> Self { if len == 0 { Self::Empty } else { Self::TargetOnly { len } } } pub fn target_with_mtp(len: usize, mtp_len: usize) -> Result { if len == 0 || mtp_len + 1 != len { return Err("TargetWithMtp requires len > 0 and mtp_len + 1 == len"); } Ok(Self::TargetWithMtp { len, mtp_len }) } pub fn len(&self) -> usize { match *self { Self::Empty => 0, Self::TargetOnly { len } | Self::TargetWithMtp { len, .. } => len, } } pub fn is_empty(&self) -> bool { self.len() == 0 } pub fn has_valid_mtp_hid(&self) -> bool { matches!(self, Self::TargetWithMtp { .. }) } /// Returns `true` iff this state can be strictly extended by a prompt of length `prompt_len`. pub fn can_reuse(&self, prompt_len: usize, use_mtp: bool) -> bool { match *self { Self::Empty => false, Self::TargetOnly { len } => !use_mtp && len < prompt_len, Self::TargetWithMtp { len, .. } => len < prompt_len, } } } /// Next checkpoint boundary strictly greater than `cur` on a grid of stride `stride > 0`. pub fn next_ckpt_boundary(cur: usize, stride: usize) -> usize { assert!(stride > 0, "checkpoint stride must be > 0"); ((cur / stride) + 1) * stride } #[derive(Debug, Clone)] pub struct HybridCkptEntry { pub slot: usize, pub lru_tick: u64, pub prefix: Vec, } /// Metadata pool for GPU hybrid (SWA / Full-KV / GDN) prefix checkpoints. /// Separates `peek_slot` from `commit_slot` so failed GPU allocations never leave ghost entries. #[derive(Debug, Clone)] pub struct HybridPrefixPool { capacity: usize, tick: u64, entries: Vec, } impl HybridPrefixPool { pub fn new(capacity: usize) -> Self { Self { capacity: capacity.max(1), tick: 0, entries: Vec::new(), } } pub fn clear(&mut self) { self.entries.clear(); } pub fn entries(&self) -> &[HybridCkptEntry] { &self.entries } /// Longest strict prefix (`0 < entry.prefix.len() < prompt.len()`) matching `prompt`. pub fn find_best_strict_prefix(&self, prompt: &[i32]) -> Option<&HybridCkptEntry> { self.entries .iter() .filter(|e| !e.prefix.is_empty() && e.prefix.len() < prompt.len() && prompt.starts_with(&e.prefix)) .max_by_key(|e| e.prefix.len()) } /// Drops all checkpoints deeper than `limit` (must run whenever KV/GDN diverges at `limit`). pub fn invalidate_above(&mut self, limit: usize) { self.entries.retain(|e| e.prefix.len() <= limit); } /// Selects a backing slot without mutating pool metadata. pub fn peek_slot(&self, prefix: &[i32]) -> Option { if prefix.is_empty() { return None; } if let Some(e) = self.entries.iter().find(|e| e.prefix == prefix) { return Some(e.slot); } if self.entries.len() < self.capacity { let mut used = vec![false; self.capacity]; for e in &self.entries { if e.slot < self.capacity { used[e.slot] = true; } } return used.iter().position(|&u| !u); } self.entries.iter().min_by_key(|e| e.lru_tick).map(|e| e.slot) } /// Commits metadata ONLY after GPU snapshot allocation & copy succeeded. pub fn commit_slot(&mut self, slot: usize, prefix: Vec) { if slot >= self.capacity || prefix.is_empty() { return; } self.tick += 1; if let Some(e) = self.entries.iter_mut().find(|e| e.slot == slot) { e.lru_tick = self.tick; e.prefix = prefix; } else { self.entries.push(HybridCkptEntry { slot, lru_tick: self.tick, prefix, }); } } } #[cfg(test)] mod tests { use super::*; #[test] fn f03_turn1_len1_no_mtp_cannot_reuse_with_mtp() { let st = PrefixState::target_only(1); assert!(!st.has_valid_mtp_hid()); assert!(!st.can_reuse(5, true)); assert!(st.can_reuse(5, false)); let st_mtp = PrefixState::target_with_mtp(4, 3).unwrap(); assert!(st_mtp.has_valid_mtp_hid()); assert!(st_mtp.can_reuse(5, true)); assert!(!st_mtp.can_reuse(4, true)); // must be strict prefix } #[test] fn f06_non_aligned_ckpt_grid_and_two_phase_commit() { assert_eq!(next_ckpt_boundary(125, 512), 512); assert_eq!(next_ckpt_boundary(512, 512), 1024); assert_eq!(next_ckpt_boundary(637, 512), 1024); let mut pool = HybridPrefixPool::new(2); let s0 = pool.peek_slot(&[1, 2, 3]).unwrap(); assert!(pool.entries().is_empty()); // failed GPU alloc leaves zero ghost entries pool.commit_slot(s0, vec![1, 2, 3]); assert_eq!(pool.entries().len(), 1); assert_eq!(pool.find_best_strict_prefix(&[1, 2, 3, 4]).unwrap().slot, s0); pool.invalidate_above(2); assert!(pool.entries().is_empty()); } }