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-kv-cache / tests / kv_lifecycle_qualification.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 | //! KV lifecycle qualification (overnight CAND-0 campaign, lane L6-KV). |
| 17 | //! |
| 18 | //! Host-only checks on `AienKvManager` with a heap pool, no GPU, no model: |
| 19 | //! |
| 20 | //! - `freed_block_reuse_never_exposes_previous_sequence_kv`: a block freed by |
| 21 | //! one sequence and handed to another (fresh allocation, append into a new |
| 22 | //! block, copy-on-write destination) reads back zeros or the new owner's |
| 23 | //! own values in every slot of every layer, never the old owner's; the |
| 24 | //! freed sequence id is a stale identity that can neither read nor write. |
| 25 | //! - `sibling_appends_do_not_alter_parent_or_siblings`: copy-on-write isolation |
| 26 | //! between a parent and two forked children that all keep appending. |
| 27 | //! - `exhaustion_refuses_without_changing_state`: allocation, append, |
| 28 | //! copy-on-write and reservation on an empty pool all return `Err` and leave |
| 29 | //! every observable counter unchanged, including `cow_faults` (a refused |
| 30 | //! copy-on-write is not a fault that happened; the campaign verifier's |
| 31 | //! conservation model counts a fault only when the copy took a block). |
| 32 | //! - `device_cow_copy_failure_releases_the_new_block`: when the device copy of |
| 33 | //! a copy-on-write fails, the block taken for it goes back to the pool. |
| 34 | //! - `fixed_seed_random_lifecycle_keeps_accounting_consistent`: a fixed-seed |
| 35 | //! random program of admit (allocate + prefill fence), gated fork, append, |
| 36 | //! cancel, finish and reserve/rollback, checked after every step against a |
| 37 | //! reference model: ownership, conservation, content, admission prediction |
| 38 | //! (`blocks_needed_for_appends` equals the blocks an append really took), |
| 39 | //! copy-on-write count, atomic refusal on exhaustion, stale ids refused. |
| 40 | //! |
| 41 | //! The randomized property test over the same manager without the fixed seed |
| 42 | //! lives in crates/aien-replay/tests/kv_ownership_props.rs. |
| 43 | |
| 44 | use std::collections::BTreeMap; |
| 45 | |
| 46 | use aien_kv_cache::{ |
| 47 | AienKvManager, BufferRegion, HeapUnifiedBuffer, KvDType, KvPoolConfig, MemoryDevice, |
| 48 | PrefillState, |
| 49 | }; |
| 50 | use aien_platform::{Fence, PlatformError}; |
| 51 | |
| 52 | const BS: usize = 4; |
| 53 | const LAYERS: usize = 2; |
| 54 | const KV_HEADS: usize = 2; |
| 55 | const HEAD_DIM: usize = 2; |
| 56 | const KV_DIM: usize = KV_HEADS * HEAD_DIM; |
| 57 | |
| 58 | type Mgr = AienKvManager<HeapUnifiedBuffer>; |
| 59 | |
| 60 | fn new_mgr(total_blocks: usize) -> Mgr { |
| 61 | let cfg = KvPoolConfig { |
| 62 | num_blocks: total_blocks, |
| 63 | block_size: BS, |
| 64 | num_layers: LAYERS, |
| 65 | num_kv_heads: KV_HEADS, |
| 66 | head_dim: HEAD_DIM, |
| 67 | dtype: KvDType::Fp32, |
| 68 | }; |
| 69 | let buf = HeapUnifiedBuffer::allocate(cfg.total_bytes(), 64).expect("heap buffer"); |
| 70 | AienKvManager::with_buffer(total_blocks, BS, cfg, buf).expect("manager") |
| 71 | } |
| 72 | |
| 73 | /// K value of token `val` in `layer`; V is its negation. |
| 74 | fn kval(val: f32, layer: usize) -> f32 { |
| 75 | val + layer as f32 * 0.25 |
| 76 | } |
| 77 | |
| 78 | fn write_all_layers(m: &mut Mgr, block: usize, slot: usize, val: f32) { |
| 79 | for layer in 0..LAYERS { |
| 80 | let k = [kval(val, layer); KV_DIM]; |
| 81 | let v = [-kval(val, layer); KV_DIM]; |
| 82 | m.write_explicit_token_kv(block, layer, slot, &k, &v) |
| 83 | .expect("pool attached"); |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | /// Raw read of every slot of every layer of `block`, whatever the tables say. |
| 88 | fn raw_block(m: &Mgr, block: usize) -> Vec<f32> { |
| 89 | let pool = m.tensor_pool().expect("pool attached"); |
| 90 | let mut out = Vec::new(); |
| 91 | for layer in 0..LAYERS { |
| 92 | for slot in 0..BS { |
| 93 | let mut k = [0.0f32; KV_DIM]; |
| 94 | let mut v = [0.0f32; KV_DIM]; |
| 95 | pool.read_token_kv(block, layer, slot, &mut k, &mut v); |
| 96 | out.extend_from_slice(&k); |
| 97 | out.extend_from_slice(&v); |
| 98 | } |
| 99 | } |
| 100 | out |
| 101 | } |
| 102 | |
| 103 | /// Prefill a fresh sequence through the gate: allocate, write every prompt |
| 104 | /// token in every layer, mark pending, fire the completion fence. |
| 105 | fn admit(m: &mut Mgr, seq: u64, vals: &[f32]) -> Result<(), String> { |
| 106 | let prompt: Vec<u32> = (0..vals.len() as u32).collect(); |
| 107 | m.allocate_sequence(seq, &prompt)?; |
| 108 | for (pos, &val) in vals.iter().enumerate() { |
| 109 | for layer in 0..LAYERS { |
| 110 | m.write_token_kv( |
| 111 | seq, |
| 112 | pos, |
| 113 | layer, |
| 114 | &[kval(val, layer); KV_DIM], |
| 115 | &[-kval(val, layer); KV_DIM], |
| 116 | )?; |
| 117 | } |
| 118 | } |
| 119 | m.mark_prefill_pending(seq).map_err(|e| e.to_string())?; |
| 120 | m.complete_prefill(seq).map_err(|e| e.to_string())?; |
| 121 | Ok(()) |
| 122 | } |
| 123 | |
| 124 | fn append_val(m: &mut Mgr, seq: u64, val: f32) -> Result<(), String> { |
| 125 | let (block, slot) = m.append_token_with_slot(seq)?; |
| 126 | write_all_layers(m, block, slot, val); |
| 127 | Ok(()) |
| 128 | } |
| 129 | |
| 130 | /// Check that `seq` reads back exactly `vals` in every layer. |
| 131 | fn assert_content(m: &Mgr, seq: u64, vals: &[f32], what: &str) { |
| 132 | for layer in 0..LAYERS { |
| 133 | let (k, v) = m |
| 134 | .gather_layer_kv(seq, layer) |
| 135 | .unwrap_or_else(|e| panic!("{what}: gather seq {seq} layer {layer}: {e}")); |
| 136 | let want_k: Vec<f32> = vals |
| 137 | .iter() |
| 138 | .flat_map(|&x| [kval(x, layer); KV_DIM]) |
| 139 | .collect(); |
| 140 | let want_v: Vec<f32> = vals |
| 141 | .iter() |
| 142 | .flat_map(|&x| [-kval(x, layer); KV_DIM]) |
| 143 | .collect(); |
| 144 | assert_eq!(k, want_k, "{what}: seq {seq} layer {layer} K"); |
| 145 | assert_eq!(v, want_v, "{what}: seq {seq} layer {layer} V"); |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /// Everything a caller can observe about the manager, for atomicity checks. |
| 150 | #[derive(Debug, PartialEq)] |
| 151 | struct Snap { |
| 152 | free: usize, |
| 153 | allocated: usize, |
| 154 | tables: Vec<(u64, Vec<usize>, usize, PrefillState)>, |
| 155 | blocks: Vec<(usize, usize, bool)>, |
| 156 | cow_faults: usize, |
| 157 | metrics: (usize, usize, usize, usize, usize, usize), |
| 158 | } |
| 159 | |
| 160 | fn snap(m: &Mgr, seqs: impl IntoIterator<Item = u64>) -> Snap { |
| 161 | let mut tables = Vec::new(); |
| 162 | for seq in seqs { |
| 163 | if let Some(t) = m.get_block_table(seq) { |
| 164 | tables.push((seq, t.block_ids.clone(), t.total_tokens, t.prefill_state)); |
| 165 | } |
| 166 | } |
| 167 | let blocks = (0..m.total_block_count()) |
| 168 | .map(|b| { |
| 169 | let blk = m.get_block(b).expect("block"); |
| 170 | (blk.ref_count, blk.num_tokens, blk.is_shared) |
| 171 | }) |
| 172 | .collect(); |
| 173 | let km = m.metrics(); |
| 174 | Snap { |
| 175 | free: m.free_block_count(), |
| 176 | allocated: m.allocated_block_count(), |
| 177 | tables, |
| 178 | blocks, |
| 179 | cow_faults: m.cow_faults(), |
| 180 | metrics: ( |
| 181 | km.physical_pages, |
| 182 | km.logical_pages, |
| 183 | km.shared_pages, |
| 184 | km.private_pages, |
| 185 | km.cow_faults, |
| 186 | km.used_blocks, |
| 187 | ), |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | #[test] |
| 192 | fn freed_block_reuse_never_exposes_previous_sequence_kv() { |
| 193 | // The whole pool (4 blocks) belongs to sequence A first, every slot written. |
| 194 | let mut m = new_mgr(4); |
| 195 | let a_vals: Vec<f32> = (0..16).map(|i| 1000.0 + i as f32).collect(); |
| 196 | admit(&mut m, 1, &a_vals).unwrap(); |
| 197 | let a_blocks = m.get_block_table(1).unwrap().block_ids.clone(); |
| 198 | assert_eq!(a_blocks.len(), 4); |
| 199 | for &b in &a_blocks { |
| 200 | assert!(raw_block(&m, b).iter().all(|&x| x.abs() >= 1000.0)); |
| 201 | } |
| 202 | m.free_sequence(1).unwrap(); |
| 203 | assert_eq!(m.free_block_count(), 4); |
| 204 | |
| 205 | // Stale identity: the freed id can neither read nor write nor append. |
| 206 | assert!(m.get_block_table(1).is_none()); |
| 207 | assert!( |
| 208 | m.gather_layer_kv(1, 0).is_err(), |
| 209 | "stale id read must be refused" |
| 210 | ); |
| 211 | assert!( |
| 212 | m.write_token_kv(1, 0, 0, &[7.0; KV_DIM], &[7.0; KV_DIM]) |
| 213 | .is_err(), |
| 214 | "stale id write must be refused" |
| 215 | ); |
| 216 | assert!( |
| 217 | m.append_token_with_slot(1).is_err(), |
| 218 | "stale id append must be refused" |
| 219 | ); |
| 220 | assert_eq!(m.prefill_state(1), None); |
| 221 | assert_eq!( |
| 222 | m.free_block_count(), |
| 223 | 4, |
| 224 | "stale-id calls must not take blocks" |
| 225 | ); |
| 226 | |
| 227 | // Fresh allocation on recycled blocks: every slot of every layer is zero |
| 228 | // before the new owner writes anything. |
| 229 | let prompt: Vec<u32> = (0..6).collect(); |
| 230 | let b_blocks = m.allocate_sequence(2, &prompt).unwrap(); |
| 231 | assert_eq!(b_blocks.len(), 2); |
| 232 | for &b in &b_blocks { |
| 233 | assert!( |
| 234 | a_blocks.contains(&b), |
| 235 | "test precondition: block {b} is recycled" |
| 236 | ); |
| 237 | assert!( |
| 238 | raw_block(&m, b).iter().all(|&x| x == 0.0), |
| 239 | "STALE_KV_LEAK: recycled block {b} still holds the previous owner's KV at allocation" |
| 240 | ); |
| 241 | } |
| 242 | for layer in 0..LAYERS { |
| 243 | let (k, v) = m.gather_layer_kv(2, layer).unwrap(); |
| 244 | assert_eq!(k, vec![0.0; 6 * KV_DIM]); |
| 245 | assert_eq!(v, vec![0.0; 6 * KV_DIM]); |
| 246 | } |
| 247 | |
| 248 | // B prefills its own values, then appends across a block boundary into a |
| 249 | // third recycled block: zero before B writes it. |
| 250 | let b_vals: Vec<f32> = (0..6).map(|i| 2000.0 + i as f32).collect(); |
| 251 | for (pos, &val) in b_vals.iter().enumerate() { |
| 252 | for layer in 0..LAYERS { |
| 253 | m.write_token_kv( |
| 254 | 2, |
| 255 | pos, |
| 256 | layer, |
| 257 | &[kval(val, layer); KV_DIM], |
| 258 | &[-kval(val, layer); KV_DIM], |
| 259 | ) |
| 260 | .unwrap(); |
| 261 | } |
| 262 | } |
| 263 | m.mark_prefill_pending(2).unwrap(); |
| 264 | m.complete_prefill(2).unwrap(); |
| 265 | let mut b_all = b_vals.clone(); |
| 266 | for i in 0..3 { |
| 267 | let (block, slot) = m.append_token_with_slot(2).unwrap(); |
| 268 | if slot == 0 { |
| 269 | assert!(a_blocks.contains(&block)); |
| 270 | assert!( |
| 271 | raw_block(&m, block).iter().all(|&x| x == 0.0), |
| 272 | "STALE_KV_LEAK: block {block} taken by append holds old KV" |
| 273 | ); |
| 274 | } |
| 275 | let val = 2100.0 + i as f32; |
| 276 | write_all_layers(&mut m, block, slot, val); |
| 277 | b_all.push(val); |
| 278 | } |
| 279 | assert_content(&m, 2, &b_all, "B after appends"); |
| 280 | |
| 281 | // Copy-on-write into the last recycled block: the copy holds B's tokens in |
| 282 | // the used slots and zeros in the rest, never A's values. |
| 283 | m.fork_prefilled(2, 3).unwrap(); |
| 284 | let (cow_block, cow_slot) = m.append_token_with_slot(3).unwrap(); |
| 285 | assert!(a_blocks.contains(&cow_block)); |
| 286 | assert_eq!(cow_slot, b_all.len() % BS); |
| 287 | let raw = raw_block(&m, cow_block); |
| 288 | assert!( |
| 289 | raw.iter() |
| 290 | .all(|&x| x == 0.0 || (x.abs() >= 2000.0 && x.abs() < 3000.0)), |
| 291 | "STALE_KV_LEAK: copy-on-write destination {cow_block} exposes previous-owner KV: {raw:?}" |
| 292 | ); |
| 293 | write_all_layers(&mut m, cow_block, cow_slot, 3000.0); |
| 294 | let mut c_all = b_all.clone(); |
| 295 | c_all.push(3000.0); |
| 296 | assert_content(&m, 3, &c_all, "C after copy-on-write"); |
| 297 | assert_content(&m, 2, &b_all, "B after C's copy-on-write"); |
| 298 | |
| 299 | m.free_sequence(2).unwrap(); |
| 300 | m.free_sequence(3).unwrap(); |
| 301 | assert_eq!(m.free_block_count(), 4); |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn sibling_appends_do_not_alter_parent_or_siblings() { |
| 306 | let mut m = new_mgr(32); |
| 307 | let parent: Vec<f32> = (0..6).map(|i| 10.0 + i as f32).collect(); // ends mid-block |
| 308 | admit(&mut m, 1, &parent).unwrap(); |
| 309 | m.fork_prefilled(1, 2).unwrap(); |
| 310 | m.fork_prefilled(1, 3).unwrap(); |
| 311 | assert_eq!(m.prefill_state(1), Some(PrefillState::SharedFrozen)); |
| 312 | assert_eq!(m.prefill_state(2), Some(PrefillState::SharedFrozen)); |
| 313 | // children inherit the computed prefix |
| 314 | assert_content(&m, 2, &parent, "child 2 inherits prefix"); |
| 315 | assert_content(&m, 3, &parent, "child 3 inherits prefix"); |
| 316 | |
| 317 | let mut c2 = parent.clone(); |
| 318 | let mut c3 = parent.clone(); |
| 319 | let mut p = parent.clone(); |
| 320 | for i in 0..7 { |
| 321 | let v = 200.0 + i as f32; |
| 322 | append_val(&mut m, 2, v).unwrap(); |
| 323 | c2.push(v); |
| 324 | assert_content(&m, 1, &p, "parent while child 2 appends"); |
| 325 | assert_content(&m, 3, &c3, "child 3 while child 2 appends"); |
| 326 | } |
| 327 | for i in 0..3 { |
| 328 | let v = 300.0 + i as f32; |
| 329 | append_val(&mut m, 3, v).unwrap(); |
| 330 | c3.push(v); |
| 331 | } |
| 332 | for i in 0..5 { |
| 333 | let v = 100.0 + i as f32; |
| 334 | append_val(&mut m, 1, v).unwrap(); |
| 335 | p.push(v); |
| 336 | } |
| 337 | assert_content(&m, 1, &p, "parent after all appends"); |
| 338 | assert_content(&m, 2, &c2, "child 2 after all appends"); |
| 339 | assert_content(&m, 3, &c3, "child 3 after all appends"); |
| 340 | // the full prefix block is still shared by all three |
| 341 | let first = m.get_block_table(1).unwrap().block_ids[0]; |
| 342 | assert_eq!(m.get_block(first).unwrap().ref_count, 3); |
| 343 | for s in 1..=3 { |
| 344 | m.free_sequence(s).unwrap(); |
| 345 | } |
| 346 | assert_eq!(m.free_block_count(), 32); |
| 347 | } |
| 348 | |
| 349 | #[test] |
| 350 | fn exhaustion_refuses_without_changing_state() { |
| 351 | // 3 blocks: root (6 tokens, 2 blocks, tail partial) forked to a child, |
| 352 | // and a third sequence holding the last block, full. |
| 353 | let mut m = new_mgr(3); |
| 354 | admit(&mut m, 1, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap(); |
| 355 | m.fork_prefilled(1, 2).unwrap(); |
| 356 | admit(&mut m, 3, &[7.0, 8.0, 9.0, 10.0]).unwrap(); |
| 357 | assert_eq!(m.free_block_count(), 0); |
| 358 | let seqs = [1u64, 2, 3, 4]; |
| 359 | let before = snap(&m, seqs); |
| 360 | |
| 361 | assert!( |
| 362 | m.allocate_sequence(4, &[0; 4]).is_err(), |
| 363 | "allocation on an empty pool" |
| 364 | ); |
| 365 | assert_eq!(snap(&m, seqs), before, "refused allocation changed state"); |
| 366 | |
| 367 | assert_eq!(m.blocks_needed_for_appends(3, 1), 1); |
| 368 | assert!( |
| 369 | m.append_token_with_slot(3).is_err(), |
| 370 | "append past a full private tail" |
| 371 | ); |
| 372 | assert_eq!( |
| 373 | snap(&m, seqs), |
| 374 | before, |
| 375 | "refused fresh-block append changed state" |
| 376 | ); |
| 377 | |
| 378 | assert_eq!(m.blocks_needed_for_appends(2, 1), 1); |
| 379 | assert!( |
| 380 | m.append_token_with_slot(2).is_err(), |
| 381 | "copy-on-write on an empty pool" |
| 382 | ); |
| 383 | assert_eq!( |
| 384 | snap(&m, seqs), |
| 385 | before, |
| 386 | "COW_COUNTER_VIOLATION: refused copy-on-write changed state (cow_faults counts a fault that never happened)" |
| 387 | ); |
| 388 | |
| 389 | assert!(m.reserve_token(2).is_err(), "reservation on an empty pool"); |
| 390 | assert_eq!(snap(&m, seqs), before, "refused reservation changed state"); |
| 391 | |
| 392 | // content survived every refusal |
| 393 | assert_content( |
| 394 | &m, |
| 395 | 1, |
| 396 | &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], |
| 397 | "root after refusals", |
| 398 | ); |
| 399 | assert_content( |
| 400 | &m, |
| 401 | 2, |
| 402 | &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], |
| 403 | "child after refusals", |
| 404 | ); |
| 405 | assert_content(&m, 3, &[7.0, 8.0, 9.0, 10.0], "third after refusals"); |
| 406 | |
| 407 | // once a block is free the same copy-on-write succeeds and counts once |
| 408 | m.free_sequence(3).unwrap(); |
| 409 | append_val(&mut m, 2, 99.0).unwrap(); |
| 410 | assert_eq!(m.cow_faults(), 1, "exactly one copy-on-write happened"); |
| 411 | assert_eq!(m.metrics().cow_faults, 1); |
| 412 | assert_content( |
| 413 | &m, |
| 414 | 2, |
| 415 | &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 99.0], |
| 416 | "child after retry", |
| 417 | ); |
| 418 | assert_content( |
| 419 | &m, |
| 420 | 1, |
| 421 | &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], |
| 422 | "root after child retry", |
| 423 | ); |
| 424 | } |
| 425 | |
| 426 | /// A memory device whose every operation fails. |
| 427 | struct FailingDevice; |
| 428 | |
| 429 | impl MemoryDevice for FailingDevice { |
| 430 | fn copy(&self, _src: BufferRegion, _dst: BufferRegion) -> Result<Fence, PlatformError> { |
| 431 | Err(PlatformError::DeviceUnavailable) |
| 432 | } |
| 433 | fn zero(&self, _dst: BufferRegion) -> Result<Fence, PlatformError> { |
| 434 | Err(PlatformError::DeviceUnavailable) |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | #[test] |
| 439 | fn device_cow_copy_failure_releases_the_new_block() { |
| 440 | let mut m = new_mgr(4); |
| 441 | admit(&mut m, 1, &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]).unwrap(); |
| 442 | m.fork_prefilled(1, 2).unwrap(); |
| 443 | let seqs = [1u64, 2]; |
| 444 | let before = snap(&m, seqs); |
| 445 | assert!( |
| 446 | m.append_token_with_slot_device(&FailingDevice, 2).is_err(), |
| 447 | "a failed device copy must fail the append" |
| 448 | ); |
| 449 | assert_eq!( |
| 450 | snap(&m, seqs), |
| 451 | before, |
| 452 | "COW_DEVICE_LEAK: failed device copy changed state (block taken and never returned, or cow_faults bumped)" |
| 453 | ); |
| 454 | m.free_sequence(1).unwrap(); |
| 455 | m.free_sequence(2).unwrap(); |
| 456 | assert_eq!(m.free_block_count(), 4, "COW_DEVICE_LEAK: block leaked"); |
| 457 | } |
| 458 | |
| 459 | // --------------------------------------------------------------------------- |
| 460 | // Fixed-seed random lifecycle |
| 461 | // --------------------------------------------------------------------------- |
| 462 | |
| 463 | const RAND_BLOCKS: usize = 12; |
| 464 | const RAND_IDS: u64 = 8; |
| 465 | |
| 466 | struct Lcg(u64); |
| 467 | impl Lcg { |
| 468 | fn next(&mut self) -> u64 { |
| 469 | self.0 = self |
| 470 | .0 |
| 471 | .wrapping_mul(6364136223846793005) |
| 472 | .wrapping_add(1442695040888963407); |
| 473 | self.0 >> 33 |
| 474 | } |
| 475 | fn below(&mut self, n: u64) -> u64 { |
| 476 | self.next() % n |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | /// Reference model: each live sequence's token values. |
| 481 | type Model = BTreeMap<u64, Vec<f32>>; |
| 482 | |
| 483 | fn check_invariants(m: &Mgr, model: &Model, cow_model: usize, ctx: &str) { |
| 484 | assert_eq!( |
| 485 | m.active_sequence_count(), |
| 486 | model.len(), |
| 487 | "{ctx}: live sequences" |
| 488 | ); |
| 489 | let mut holders = [0usize; RAND_BLOCKS]; |
| 490 | let mut logical = 0usize; |
| 491 | for (&seq, vals) in model { |
| 492 | let t = m |
| 493 | .get_block_table(seq) |
| 494 | .unwrap_or_else(|| panic!("{ctx}: seq {seq} has no table")); |
| 495 | assert!(t.is_prefill_ready(), "{ctx}: admitted seq {seq} not ready"); |
| 496 | assert_eq!(t.total_tokens, vals.len(), "{ctx}: seq {seq} tokens"); |
| 497 | assert_eq!( |
| 498 | t.block_ids.len(), |
| 499 | vals.len().div_ceil(BS), |
| 500 | "{ctx}: seq {seq} blocks" |
| 501 | ); |
| 502 | let mut in_blocks = 0; |
| 503 | for (i, &b) in t.block_ids.iter().enumerate() { |
| 504 | holders[b] += 1; |
| 505 | let n = m.get_block(b).unwrap().num_tokens; |
| 506 | if i + 1 < t.block_ids.len() { |
| 507 | assert_eq!(n, BS, "{ctx}: seq {seq} non-tail block {b} not full"); |
| 508 | } |
| 509 | in_blocks += n; |
| 510 | } |
| 511 | assert_eq!(in_blocks, vals.len(), "{ctx}: seq {seq} tokens in blocks"); |
| 512 | logical += t.block_ids.len(); |
| 513 | assert_content(m, seq, vals, ctx); |
| 514 | } |
| 515 | let mut referenced = 0; |
| 516 | for (b, &h) in holders.iter().enumerate() { |
| 517 | let blk = m.get_block(b).unwrap(); |
| 518 | assert_eq!(blk.ref_count, h, "{ctx}: block {b} ref_count vs holders"); |
| 519 | if h > 0 { |
| 520 | referenced += 1; |
| 521 | assert_eq!(blk.is_shared, h > 1, "{ctx}: block {b} is_shared"); |
| 522 | } else { |
| 523 | assert_eq!( |
| 524 | blk.num_tokens, 0, |
| 525 | "{ctx}: free block {b} keeps a token count" |
| 526 | ); |
| 527 | } |
| 528 | } |
| 529 | assert_eq!( |
| 530 | m.free_block_count() + referenced, |
| 531 | RAND_BLOCKS, |
| 532 | "{ctx}: free + referenced != pool (leak or double free)" |
| 533 | ); |
| 534 | assert_eq!( |
| 535 | m.allocated_block_count(), |
| 536 | referenced, |
| 537 | "{ctx}: allocated count" |
| 538 | ); |
| 539 | let km = m.metrics(); |
| 540 | assert_eq!(km.physical_pages, referenced, "{ctx}: metrics physical"); |
| 541 | assert_eq!(km.logical_pages, logical, "{ctx}: metrics logical"); |
| 542 | assert_eq!( |
| 543 | km.shared_pages + km.private_pages, |
| 544 | referenced, |
| 545 | "{ctx}: shared + private" |
| 546 | ); |
| 547 | assert_eq!( |
| 548 | m.cow_faults(), |
| 549 | cow_model, |
| 550 | "{ctx}: cow_faults vs successful copy-on-writes" |
| 551 | ); |
| 552 | } |
| 553 | |
| 554 | fn run_program(seed: u64, steps: usize) -> (usize, usize, usize) { |
| 555 | let mut rng = Lcg(seed); |
| 556 | let mut m = new_mgr(RAND_BLOCKS); |
| 557 | let mut model = Model::new(); |
| 558 | let mut retired: Vec<u64> = Vec::new(); |
| 559 | let mut counter = 0u32; |
| 560 | let mut cow_model = 0usize; |
| 561 | let (mut refusals, mut cows, mut forks) = (0usize, 0usize, 0usize); |
| 562 | let all_ids = 0..RAND_IDS; |
| 563 | for step in 0..steps { |
| 564 | let op = rng.below(100); |
| 565 | let seq = rng.below(RAND_IDS); |
| 566 | let ctx = format!("seed {seed:#x} step {step} op {op} seq {seq}"); |
| 567 | let before = snap(&m, all_ids.clone()); |
| 568 | match op { |
| 569 | // admit a new sequence (allocate + prefill fence) |
| 570 | 0..=14 => { |
| 571 | if model.contains_key(&seq) { |
| 572 | continue; |
| 573 | } |
| 574 | let n = 1 + rng.below(9) as usize; |
| 575 | let need = m.incremental_blocks_needed(seq, n); |
| 576 | assert_eq!(need, n.div_ceil(BS), "{ctx}: admission need for a new id"); |
| 577 | let vals: Vec<f32> = (0..n) |
| 578 | .map(|_| { |
| 579 | counter += 1; |
| 580 | counter as f32 |
| 581 | }) |
| 582 | .collect(); |
| 583 | match admit(&mut m, seq, &vals) { |
| 584 | Ok(()) => { |
| 585 | assert!(need <= before.free, "{ctx}: admitted beyond free blocks"); |
| 586 | model.insert(seq, vals); |
| 587 | } |
| 588 | Err(_) => { |
| 589 | assert!(need > before.free, "{ctx}: refused admission with room"); |
| 590 | assert_eq!( |
| 591 | snap(&m, all_ids.clone()), |
| 592 | before, |
| 593 | "{ctx}: refused admit changed state" |
| 594 | ); |
| 595 | refusals += 1; |
| 596 | } |
| 597 | } |
| 598 | } |
| 599 | // gated fork onto a fresh or live child id |
| 600 | 15..=34 => { |
| 601 | let child = rng.below(RAND_IDS); |
| 602 | if child == seq { |
| 603 | continue; |
| 604 | } |
| 605 | match m.fork_prefilled(seq, child) { |
| 606 | Ok(_) => { |
| 607 | let vals = model |
| 608 | .get(&seq) |
| 609 | .unwrap_or_else(|| panic!("{ctx}: fork of missing parent succeeded")) |
| 610 | .clone(); |
| 611 | model.insert(child, vals); |
| 612 | forks += 1; |
| 613 | } |
| 614 | Err(_) => { |
| 615 | assert!( |
| 616 | !model.contains_key(&seq), |
| 617 | "{ctx}: fork of live ready parent refused" |
| 618 | ); |
| 619 | assert_eq!( |
| 620 | snap(&m, all_ids.clone()), |
| 621 | before, |
| 622 | "{ctx}: refused fork changed state" |
| 623 | ); |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | // append (decode one token) |
| 628 | 35..=74 => { |
| 629 | if !model.contains_key(&seq) { |
| 630 | assert!( |
| 631 | m.append_token_with_slot(seq).is_err(), |
| 632 | "{ctx}: append to dead id" |
| 633 | ); |
| 634 | assert_eq!( |
| 635 | snap(&m, all_ids.clone()), |
| 636 | before, |
| 637 | "{ctx}: dead-id append changed state" |
| 638 | ); |
| 639 | continue; |
| 640 | } |
| 641 | let predicted = m.blocks_needed_for_appends(seq, 1); |
| 642 | let tail = *m.get_block_table(seq).unwrap().block_ids.last().unwrap(); |
| 643 | let tb = m.get_block(tail).unwrap(); |
| 644 | let will_cow = tb.is_shared && tb.num_tokens < BS; |
| 645 | counter += 1; |
| 646 | let val = counter as f32; |
| 647 | match append_val(&mut m, seq, val) { |
| 648 | Ok(()) => { |
| 649 | assert_eq!( |
| 650 | before.free - m.free_block_count(), |
| 651 | predicted, |
| 652 | "{ctx}: blocks_needed_for_appends disagrees with the real append" |
| 653 | ); |
| 654 | if will_cow { |
| 655 | cow_model += 1; |
| 656 | cows += 1; |
| 657 | } |
| 658 | model.get_mut(&seq).unwrap().push(val); |
| 659 | } |
| 660 | Err(_) => { |
| 661 | assert!(predicted > before.free, "{ctx}: append refused with room"); |
| 662 | assert_eq!( |
| 663 | snap(&m, all_ids.clone()), |
| 664 | before, |
| 665 | "{ctx}: refused append changed state" |
| 666 | ); |
| 667 | refusals += 1; |
| 668 | } |
| 669 | } |
| 670 | } |
| 671 | // cancel or finish: both release the sequence |
| 672 | 75..=89 => { |
| 673 | let live = model.remove(&seq).is_some(); |
| 674 | assert_eq!(m.free_sequence(seq).is_ok(), live, "{ctx}: free result"); |
| 675 | if live { |
| 676 | retired.push(seq); |
| 677 | // the released id is stale: no table, no read, no write |
| 678 | assert!( |
| 679 | m.get_block_table(seq).is_none(), |
| 680 | "{ctx}: freed table survives" |
| 681 | ); |
| 682 | assert!( |
| 683 | m.gather_layer_kv(seq, 0).is_err(), |
| 684 | "{ctx}: stale read allowed" |
| 685 | ); |
| 686 | assert!( |
| 687 | m.write_token_kv(seq, 0, 0, &[1.0; KV_DIM], &[1.0; KV_DIM]) |
| 688 | .is_err(), |
| 689 | "{ctx}: stale write allowed" |
| 690 | ); |
| 691 | } |
| 692 | } |
| 693 | // reserve then roll back: no observable change |
| 694 | 90..=95 => { |
| 695 | if let Ok(r) = m.reserve_token(seq) { |
| 696 | assert!(model.contains_key(&seq), "{ctx}: reserve on dead id"); |
| 697 | m.rollback(r).unwrap(); |
| 698 | } |
| 699 | assert_eq!( |
| 700 | snap(&m, all_ids.clone()), |
| 701 | before, |
| 702 | "{ctx}: reserve+rollback changed state" |
| 703 | ); |
| 704 | } |
| 705 | // reserve then commit: same as an append |
| 706 | _ => { |
| 707 | if !model.contains_key(&seq) { |
| 708 | continue; |
| 709 | } |
| 710 | let predicted = m.blocks_needed_for_appends(seq, 1); |
| 711 | let tail = *m.get_block_table(seq).unwrap().block_ids.last().unwrap(); |
| 712 | let tb = m.get_block(tail).unwrap(); |
| 713 | let will_cow = tb.is_shared && tb.num_tokens < BS; |
| 714 | match m.reserve_token(seq) { |
| 715 | Ok(r) => { |
| 716 | let (block, slot) = (r.block_id, r.slot); |
| 717 | m.commit(r).unwrap(); |
| 718 | assert_eq!( |
| 719 | before.free - m.free_block_count(), |
| 720 | predicted, |
| 721 | "{ctx}: reserve need" |
| 722 | ); |
| 723 | if will_cow { |
| 724 | cow_model += 1; |
| 725 | cows += 1; |
| 726 | } |
| 727 | counter += 1; |
| 728 | let val = counter as f32; |
| 729 | write_all_layers(&mut m, block, slot, val); |
| 730 | model.get_mut(&seq).unwrap().push(val); |
| 731 | } |
| 732 | Err(_) => { |
| 733 | assert!(predicted > before.free, "{ctx}: reserve refused with room"); |
| 734 | assert_eq!( |
| 735 | snap(&m, all_ids.clone()), |
| 736 | before, |
| 737 | "{ctx}: refused reserve changed state" |
| 738 | ); |
| 739 | refusals += 1; |
| 740 | } |
| 741 | } |
| 742 | } |
| 743 | } |
| 744 | check_invariants(&m, &model, cow_model, &ctx); |
| 745 | } |
| 746 | // drain: finishing everything returns the whole pool |
| 747 | let live: Vec<u64> = model.keys().copied().collect(); |
| 748 | for seq in live { |
| 749 | m.free_sequence(seq).unwrap(); |
| 750 | model.remove(&seq); |
| 751 | check_invariants( |
| 752 | &m, |
| 753 | &model, |
| 754 | cow_model, |
| 755 | &format!("seed {seed:#x} drain {seq}"), |
| 756 | ); |
| 757 | } |
| 758 | assert_eq!(m.free_block_count(), RAND_BLOCKS); |
| 759 | assert!(!retired.is_empty()); |
| 760 | (refusals, cows, forks) |
| 761 | } |
| 762 | |
| 763 | #[test] |
| 764 | fn fixed_seed_random_lifecycle_keeps_accounting_consistent() { |
| 765 | let mut totals = (0usize, 0usize, 0usize); |
| 766 | for seed in [0x4c36_4b56u64, 1, 2, 3, 0xdead_beef] { |
| 767 | let (r, c, f) = run_program(seed, 600); |
| 768 | totals = (totals.0 + r, totals.1 + c, totals.2 + f); |
| 769 | } |
| 770 | // the program must actually reach exhaustion, copy-on-write and forks, |
| 771 | // or the checks above proved nothing about them |
| 772 | assert!(totals.0 > 0, "no exhaustion refusal was exercised"); |
| 773 | assert!(totals.1 > 0, "no copy-on-write was exercised"); |
| 774 | assert!(totals.2 > 0, "no fork was exercised"); |
| 775 | println!( |
| 776 | "fixed-seed lifecycle: {} refusals, {} copy-on-writes, {} forks over 5 x 600 steps", |
| 777 | totals.0, totals.1, totals.2 |
| 778 | ); |
| 779 | } |