aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-replay / tests / kv_ownership_props.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! Property tests: KV block ownership under fork / append / free / reserve. |
| 17 | //! |
| 18 | //! A random program of KV operations runs against `AienKvManager` and against |
| 19 | //! a tiny reference model (each live sequence = the list of token values it |
| 20 | //! should read back). After every step the checks below must hold. Each check |
| 21 | //! has a named mutation in `mutations/kv.mutants` that it is known to catch; |
| 22 | //! `mutations/run_mutants.sh` proves that. |
| 23 | //! |
| 24 | //! - ownership: every block's ref_count equals the number of block tables |
| 25 | //! that hold it; `is_shared` is true exactly when ref_count > 1. |
| 26 | //! - conservation: free blocks + referenced blocks == pool size (no leak, no |
| 27 | //! double free), and every block a sequence holds is not on the free list. |
| 28 | //! - content: every sequence reads back exactly the values written to it, so |
| 29 | //! a write to one branch never shows up in another (copy-on-write isolation). |
| 30 | //! - rollback: reserve_token followed by rollback leaves the manager state |
| 31 | //! identical to before the reservation. |
| 32 | //! |
| 33 | //! Forking onto a sequence id that already exists replaces it and releases its |
| 34 | //! old blocks (issue #142; see `fork_onto_live_child_leaks_blocks` below). |
| 35 | |
| 36 | use aien_kv_cache::{AienKvManager, HeapUnifiedBuffer, KvDType, KvPoolConfig}; |
| 37 | use proptest::prelude::*; |
| 38 | use std::collections::BTreeMap; |
| 39 | |
| 40 | const TOTAL_BLOCKS: usize = 24; |
| 41 | const BLOCK_SIZE: usize = 4; |
| 42 | const SEQ_IDS: u64 = 6; |
| 43 | const KV_DIM: usize = 2; |
| 44 | |
| 45 | type Mgr = AienKvManager<HeapUnifiedBuffer>; |
| 46 | type Model = BTreeMap<u64, Vec<f32>>; |
| 47 | |
| 48 | fn new_mgr() -> Mgr { |
| 49 | let cfg = KvPoolConfig { |
| 50 | num_blocks: TOTAL_BLOCKS, |
| 51 | block_size: BLOCK_SIZE, |
| 52 | num_layers: 1, |
| 53 | num_kv_heads: 1, |
| 54 | head_dim: KV_DIM, |
| 55 | dtype: KvDType::Fp32, |
| 56 | }; |
| 57 | let buf = HeapUnifiedBuffer::allocate(cfg.total_bytes(), 64).expect("heap buffer"); |
| 58 | AienKvManager::with_buffer(TOTAL_BLOCKS, BLOCK_SIZE, cfg, buf).expect("manager") |
| 59 | } |
| 60 | |
| 61 | #[derive(Debug, Clone)] |
| 62 | enum Op { |
| 63 | Alloc { seq: u64, n: usize }, |
| 64 | Fork { parent: u64, child: u64 }, |
| 65 | Append { seq: u64 }, |
| 66 | Free { seq: u64 }, |
| 67 | ReserveRollback { seq: u64 }, |
| 68 | ReserveCommit { seq: u64 }, |
| 69 | } |
| 70 | |
| 71 | fn op() -> impl Strategy<Value = Op> { |
| 72 | let s = 0..SEQ_IDS; |
| 73 | prop_oneof![ |
| 74 | 1 => (s.clone(), 0usize..10).prop_map(|(seq, n)| Op::Alloc { seq, n }), |
| 75 | 3 => (s.clone(), s.clone()).prop_map(|(parent, child)| Op::Fork { parent, child }), |
| 76 | 4 => s.clone().prop_map(|seq| Op::Append { seq }), |
| 77 | 1 => s.clone().prop_map(|seq| Op::Free { seq }), |
| 78 | 2 => s.clone().prop_map(|seq| Op::ReserveRollback { seq }), |
| 79 | 1 => s.prop_map(|seq| Op::ReserveCommit { seq }), |
| 80 | ] |
| 81 | } |
| 82 | |
| 83 | /// Everything about the manager that a caller can observe, for equality. |
| 84 | #[derive(Debug, PartialEq)] |
| 85 | struct Observed { |
| 86 | tables: Vec<(u64, Vec<usize>, usize)>, |
| 87 | blocks: Vec<(usize, usize, bool)>, |
| 88 | free: usize, |
| 89 | content: Vec<(u64, Vec<f32>)>, |
| 90 | } |
| 91 | |
| 92 | fn observe(mgr: &Mgr, model: &Model) -> Observed { |
| 93 | let mut tables = Vec::new(); |
| 94 | let mut content = Vec::new(); |
| 95 | for &seq in model.keys() { |
| 96 | if let Some(t) = mgr.get_block_table(seq) { |
| 97 | tables.push((seq, t.block_ids.clone(), t.total_tokens)); |
| 98 | content.push(( |
| 99 | seq, |
| 100 | mgr.gather_layer_kv(seq, 0) |
| 101 | .map(|kv| kv.0) |
| 102 | .unwrap_or_default(), |
| 103 | )); |
| 104 | } |
| 105 | } |
| 106 | let blocks = (0..TOTAL_BLOCKS) |
| 107 | .map(|b| { |
| 108 | let blk = mgr.get_block(b).expect("block exists"); |
| 109 | (blk.ref_count, blk.num_tokens, blk.is_shared) |
| 110 | }) |
| 111 | .collect(); |
| 112 | Observed { |
| 113 | tables, |
| 114 | blocks, |
| 115 | free: mgr.free_block_count(), |
| 116 | content, |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | fn token_value(counter: &mut u32) -> f32 { |
| 121 | *counter += 1; |
| 122 | *counter as f32 |
| 123 | } |
| 124 | |
| 125 | fn write_token(mgr: &mut Mgr, block: usize, slot: usize, val: f32) { |
| 126 | let k = [val; KV_DIM]; |
| 127 | let v = [-val; KV_DIM]; |
| 128 | mgr.write_explicit_token_kv(block, 0, slot, &k, &v) |
| 129 | .expect("pool attached"); |
| 130 | } |
| 131 | |
| 132 | fn check(mgr: &Mgr, model: &Model) -> Result<(), TestCaseError> { |
| 133 | prop_assert_eq!( |
| 134 | mgr.active_sequence_count(), |
| 135 | model.len(), |
| 136 | "live sequence count" |
| 137 | ); |
| 138 | |
| 139 | let mut holders = vec![0usize; TOTAL_BLOCKS]; |
| 140 | for (&seq, values) in model { |
| 141 | let t = mgr |
| 142 | .get_block_table(seq) |
| 143 | .ok_or_else(|| TestCaseError::fail(format!("seq {seq} has no table")))?; |
| 144 | prop_assert_eq!(t.total_tokens, values.len(), "seq {} token count", seq); |
| 145 | prop_assert_eq!( |
| 146 | t.block_ids.len(), |
| 147 | values.len().div_ceil(BLOCK_SIZE), |
| 148 | "seq {} block count", |
| 149 | seq |
| 150 | ); |
| 151 | let mut in_blocks = 0; |
| 152 | for (i, &b) in t.block_ids.iter().enumerate() { |
| 153 | holders[b] += 1; |
| 154 | let n = mgr.get_block(b).expect("block").num_tokens; |
| 155 | if i + 1 < t.block_ids.len() { |
| 156 | prop_assert_eq!(n, BLOCK_SIZE, "seq {} non-tail block {} not full", seq, b); |
| 157 | } |
| 158 | in_blocks += n; |
| 159 | } |
| 160 | prop_assert_eq!( |
| 161 | in_blocks, |
| 162 | values.len(), |
| 163 | "seq {} tokens recorded in blocks", |
| 164 | seq |
| 165 | ); |
| 166 | |
| 167 | // content: what the sequence reads back is exactly what was written to it |
| 168 | let (k, v) = mgr.gather_layer_kv(seq, 0).map_err(TestCaseError::fail)?; |
| 169 | let want_k: Vec<f32> = values.iter().flat_map(|&x| [x; KV_DIM]).collect(); |
| 170 | let want_v: Vec<f32> = values.iter().flat_map(|&x| [-x; KV_DIM]).collect(); |
| 171 | prop_assert_eq!(k, want_k, "seq {} K content", seq); |
| 172 | prop_assert_eq!(v, want_v, "seq {} V content", seq); |
| 173 | } |
| 174 | |
| 175 | let mut referenced = 0; |
| 176 | for (b, &h) in holders.iter().enumerate() { |
| 177 | let blk = mgr.get_block(b).expect("block"); |
| 178 | prop_assert_eq!(blk.ref_count, h, "block {} ref_count vs holders", b); |
| 179 | if blk.ref_count > 0 { |
| 180 | referenced += 1; |
| 181 | prop_assert_eq!( |
| 182 | blk.is_shared, |
| 183 | blk.ref_count > 1, |
| 184 | "block {} is_shared flag", |
| 185 | b |
| 186 | ); |
| 187 | } |
| 188 | } |
| 189 | prop_assert_eq!( |
| 190 | mgr.free_block_count() + referenced, |
| 191 | TOTAL_BLOCKS, |
| 192 | "free + referenced must equal pool size (leak or double free)" |
| 193 | ); |
| 194 | Ok(()) |
| 195 | } |
| 196 | |
| 197 | fn apply( |
| 198 | mgr: &mut Mgr, |
| 199 | model: &mut Model, |
| 200 | counter: &mut u32, |
| 201 | op: &Op, |
| 202 | ) -> Result<(), TestCaseError> { |
| 203 | match *op { |
| 204 | Op::Alloc { seq, n } => { |
| 205 | if model.contains_key(&seq) { |
| 206 | // existing sequence: the call returns its table and changes nothing |
| 207 | mgr.allocate_sequence(seq, &[0; 3]) |
| 208 | .map_err(TestCaseError::fail)?; |
| 209 | return Ok(()); |
| 210 | } |
| 211 | let prompt: Vec<u32> = (0..n as u32).collect(); |
| 212 | if mgr.allocate_sequence(seq, &prompt).is_ok() { |
| 213 | let mut vals = Vec::with_capacity(n); |
| 214 | for pos in 0..n { |
| 215 | let val = token_value(counter); |
| 216 | mgr.write_token_kv(seq, pos, 0, &[val; KV_DIM], &[-val; KV_DIM]) |
| 217 | .map_err(TestCaseError::fail)?; |
| 218 | vals.push(val); |
| 219 | } |
| 220 | model.insert(seq, vals); |
| 221 | } |
| 222 | } |
| 223 | Op::Fork { parent, child } => { |
| 224 | if parent == child { |
| 225 | return Ok(()); // self-fork is refused, see fork_onto_self_is_refused_and_harmless |
| 226 | } |
| 227 | match mgr.fork_sequence(parent, child) { |
| 228 | Ok(_) => { |
| 229 | let vals = model |
| 230 | .get(&parent) |
| 231 | .cloned() |
| 232 | .ok_or_else(|| TestCaseError::fail("fork of missing parent succeeded"))?; |
| 233 | model.insert(child, vals); |
| 234 | } |
| 235 | Err(_) => prop_assert!(!model.contains_key(&parent), "fork of live parent refused"), |
| 236 | } |
| 237 | } |
| 238 | Op::Append { seq } => { |
| 239 | if let Ok((block, slot)) = mgr.append_token_with_slot(seq) { |
| 240 | let vals = model |
| 241 | .get_mut(&seq) |
| 242 | .ok_or_else(|| TestCaseError::fail("append to missing seq succeeded"))?; |
| 243 | prop_assert_eq!(slot, vals.len() % BLOCK_SIZE, "slot for seq {}", seq); |
| 244 | let val = token_value(counter); |
| 245 | write_token(mgr, block, slot, val); |
| 246 | vals.push(val); |
| 247 | } |
| 248 | } |
| 249 | Op::Free { seq } => { |
| 250 | let ok = mgr.free_sequence(seq).is_ok(); |
| 251 | prop_assert_eq!( |
| 252 | ok, |
| 253 | model.remove(&seq).is_some(), |
| 254 | "free result for seq {}", |
| 255 | seq |
| 256 | ); |
| 257 | } |
| 258 | Op::ReserveRollback { seq } => { |
| 259 | let before = observe(mgr, model); |
| 260 | if let Ok(r) = mgr.reserve_token(seq) { |
| 261 | prop_assert!(model.contains_key(&seq), "reserve on missing seq succeeded"); |
| 262 | mgr.rollback(r).map_err(TestCaseError::fail)?; |
| 263 | } |
| 264 | let after = observe(mgr, model); |
| 265 | prop_assert_eq!(before, after, "reserve+rollback must restore state"); |
| 266 | } |
| 267 | Op::ReserveCommit { seq } => { |
| 268 | if let Ok(r) = mgr.reserve_token(seq) { |
| 269 | let (block, slot) = (r.block_id, r.slot); |
| 270 | mgr.commit(r).map_err(TestCaseError::fail)?; |
| 271 | let vals = model |
| 272 | .get_mut(&seq) |
| 273 | .ok_or_else(|| TestCaseError::fail("reserve on missing seq succeeded"))?; |
| 274 | let val = token_value(counter); |
| 275 | write_token(mgr, block, slot, val); |
| 276 | vals.push(val); |
| 277 | } |
| 278 | } |
| 279 | } |
| 280 | Ok(()) |
| 281 | } |
| 282 | |
| 283 | /// Case count: PROPTEST_CASES if set, else 256 (8 under Miri, which is slow). |
| 284 | fn cases() -> u32 { |
| 285 | std::env::var("PROPTEST_CASES") |
| 286 | .ok() |
| 287 | .and_then(|s| s.parse().ok()) |
| 288 | .unwrap_or(if cfg!(miri) { 8 } else { 256 }) |
| 289 | } |
| 290 | |
| 291 | proptest! { |
| 292 | #![proptest_config(ProptestConfig { |
| 293 | cases: cases(), |
| 294 | failure_persistence: None, |
| 295 | ..ProptestConfig::default() |
| 296 | })] |
| 297 | |
| 298 | #[test] |
| 299 | fn kv_ownership_holds_under_random_programs(ops in prop::collection::vec(op(), 1..60)) { |
| 300 | let mut mgr = new_mgr(); |
| 301 | let mut model = Model::new(); |
| 302 | let mut counter = 0u32; |
| 303 | for op in &ops { |
| 304 | apply(&mut mgr, &mut model, &mut counter, op)?; |
| 305 | check(&mgr, &model)?; |
| 306 | } |
| 307 | // drain: freeing every live sequence returns the whole pool |
| 308 | let live: Vec<u64> = model.keys().copied().collect(); |
| 309 | for seq in live { |
| 310 | mgr.free_sequence(seq).map_err(TestCaseError::fail)?; |
| 311 | model.remove(&seq); |
| 312 | check(&mgr, &model)?; |
| 313 | } |
| 314 | prop_assert_eq!(mgr.free_block_count(), TOTAL_BLOCKS); |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | /// Issue #142: forking onto a sequence id that is still live replaces it and |
| 319 | /// must release its old blocks back to the pool. |
| 320 | #[test] |
| 321 | fn fork_onto_live_child_leaks_blocks() { |
| 322 | let mut mgr = new_mgr(); |
| 323 | mgr.allocate_sequence(1, &[1, 2, 3, 4, 5]).unwrap(); |
| 324 | mgr.allocate_sequence(2, &[1, 2, 3]).unwrap(); |
| 325 | // fork_sequence either refuses or releases seq 2's old block |
| 326 | let _ = mgr.fork_sequence(1, 2); |
| 327 | mgr.free_sequence(1).unwrap(); |
| 328 | mgr.free_sequence(2).unwrap(); |
| 329 | assert_eq!(mgr.free_block_count(), TOTAL_BLOCKS, "blocks leaked"); |
| 330 | } |
| 331 | |
| 332 | /// Re-forking onto a child that already shares the parent's blocks must keep |
| 333 | /// the counts right: nothing leaks and nothing is freed while still in use. |
| 334 | #[test] |
| 335 | fn refork_onto_existing_child_keeps_counts() { |
| 336 | let mut mgr = new_mgr(); |
| 337 | mgr.allocate_sequence(1, &[1, 2, 3, 4, 5]).unwrap(); |
| 338 | mgr.fork_sequence(1, 2).unwrap(); |
| 339 | mgr.fork_sequence(1, 2).unwrap(); |
| 340 | mgr.free_sequence(1).unwrap(); |
| 341 | assert!(mgr.get_block_table(2).is_some()); |
| 342 | mgr.free_sequence(2).unwrap(); |
| 343 | assert_eq!(mgr.free_block_count(), TOTAL_BLOCKS, "blocks leaked"); |
| 344 | } |
| 345 | |
| 346 | /// Forking a sequence onto itself is refused and leaves it untouched. |
| 347 | #[test] |
| 348 | fn fork_onto_self_is_refused_and_harmless() { |
| 349 | let mut mgr = new_mgr(); |
| 350 | mgr.allocate_sequence(1, &[1, 2, 3, 4, 5]).unwrap(); |
| 351 | let before = mgr.get_block_table(1).unwrap().block_ids.clone(); |
| 352 | assert!(mgr.fork_sequence(1, 1).is_err()); |
| 353 | assert_eq!(mgr.get_block_table(1).unwrap().block_ids, before); |
| 354 | mgr.free_sequence(1).unwrap(); |
| 355 | assert_eq!(mgr.free_block_count(), TOTAL_BLOCKS); |
| 356 | } |