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-inference-abi / tests / prefill_pool_exhaustion.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 | //! PREFILL-I25: a KV pool that runs out during a prefill append or a |
| 17 | //! single-token decode step must fail LOUDLY and leave a retryable state. |
| 18 | //! |
| 19 | //! Before the fix, `prefill_prompt_layer_by_layer_paged` turned an |
| 20 | //! out-of-blocks error from `append_token_with_slot` into `None` (`.ok()`), |
| 21 | //! dropped the K/V write result, and returned Ok: the appended tokens were |
| 22 | //! silently not stored in the pool. The single-token path |
| 23 | //! (`forward_token_impl_paged`) had the same `.ok()` on its slot. |
| 24 | //! |
| 25 | //! Runs on the CPU reference backend with synthetic reference weights and a |
| 26 | //! tiny paged pool (block size 4), so it needs no checkpoint and takes |
| 27 | //! seconds. It is not ignored. |
| 28 | //! |
| 29 | //! Receipt: written as JSON to the path in env `AIEN_I25_RECEIPT` (when set) |
| 30 | //! BEFORE any assertion fires. Every check has its own marker in its failure |
| 31 | //! message; all check outcomes are printed first so every marker that |
| 32 | //! applies is in the log. |
| 33 | //! |
| 34 | //! Checks and markers: |
| 35 | //! - x_prefill_exhaustion_is_loud POOL_SILENT_SUCCESS_VIOLATION |
| 36 | //! (POOL_ERROR_PREFIX_VIOLATION when the Err lacks the stable prefix or |
| 37 | //! the needed/available numbers) |
| 38 | //! - x_prefill_exhaustion_is_atomic POOL_PARTIAL_STATE_VIOLATION |
| 39 | //! - x_prefill_clean_path_unchanged CLEAN_PATH_VIOLATION |
| 40 | //! - x_exact_fit_ok BOUNDARY_VIOLATION |
| 41 | //! - x_decode_exhaustion_is_loud POOL_SILENT_SUCCESS_VIOLATION |
| 42 | //! - x_recovers_after_free RETRY_VIOLATION |
| 43 | //! |
| 44 | //! A check whose precondition is not met (for example the atomicity check |
| 45 | //! when the append did not fail at all) is recorded with `applicable: false` |
| 46 | //! and passes vacuously; the check that owns that precondition fails instead. |
| 47 | //! |
| 48 | //! Scenarios: the prompt is 6 tokens (one full block of 4 and a tail with 2 |
| 49 | //! tokens). The second prefill chunk appends 11 tokens (ends mid-block) or |
| 50 | //! 10 tokens (ends exactly on a block boundary), with the prompt's tail |
| 51 | //! either private or shared with a second sequence (so the first append |
| 52 | //! needs a copy-on-write block). The number of new blocks each scenario |
| 53 | //! needs is computed by `oracle_new_blocks` from first principles, not by |
| 54 | //! the backend's own helper. |
| 55 | |
| 56 | use aien_inference_abi::{ |
| 57 | AienInferenceBackend, DecodeOutput, FinishReason, ModelConfig, NativeTransformerBackend, |
| 58 | ScheduledBatch, TransformerWeights, |
| 59 | }; |
| 60 | use std::collections::HashMap; |
| 61 | |
| 62 | const BLOCK_SIZE: usize = 4; |
| 63 | /// Prompt tokens: 6 = one full block of 4 plus a partly filled tail of 2. |
| 64 | const PROMPT_LEN: usize = 6; |
| 65 | /// Second-chunk lengths: 11 ends mid-block (17 tokens), 10 ends exactly on a |
| 66 | /// block boundary (16 tokens). |
| 67 | const APPEND_LENS: [usize; 2] = [11, 10]; |
| 68 | /// Pool used for the exhaustion and boundary scenarios. |
| 69 | const SMALL_POOL: usize = 24; |
| 70 | /// Pool that is always large enough. |
| 71 | const BIG_POOL: usize = 64; |
| 72 | |
| 73 | const SEQ: u64 = 7001; |
| 74 | const WITNESS: u64 = 7002; |
| 75 | const FILLER: u64 = 7003; |
| 76 | const CONTROL: u64 = 7004; |
| 77 | |
| 78 | /// The stable prefix of every pool-exhaustion error. Kept as a literal here |
| 79 | /// (not imported from the crate) so a renamed or reworded prefix is caught. |
| 80 | const PREFIX: &str = "KV pool exhausted:"; |
| 81 | |
| 82 | const M_SILENT: &str = "POOL_SILENT_SUCCESS_VIOLATION"; |
| 83 | const M_PREFIX: &str = "POOL_ERROR_PREFIX_VIOLATION"; |
| 84 | const M_PARTIAL: &str = "POOL_PARTIAL_STATE_VIOLATION"; |
| 85 | const M_CLEAN: &str = "CLEAN_PATH_VIOLATION"; |
| 86 | const M_BOUNDARY: &str = "BOUNDARY_VIOLATION"; |
| 87 | const M_RETRY: &str = "RETRY_VIOLATION"; |
| 88 | |
| 89 | type Planes = Vec<(Vec<f32>, Vec<f32>)>; |
| 90 | |
| 91 | /// One scenario: is the prompt's tail shared with `WITNESS`, and how many |
| 92 | /// tokens does the second prefill chunk append. |
| 93 | #[derive(Clone, Copy)] |
| 94 | struct Scenario { |
| 95 | shared_tail: bool, |
| 96 | len: usize, |
| 97 | } |
| 98 | |
| 99 | impl Scenario { |
| 100 | fn label(&self) -> String { |
| 101 | format!("shared_tail={} append_len={}", self.shared_tail, self.len) |
| 102 | } |
| 103 | |
| 104 | /// New blocks this scenario's append needs. |
| 105 | fn need(&self) -> usize { |
| 106 | oracle_new_blocks(PROMPT_LEN, self.len, self.shared_tail) |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | fn scenarios() -> Vec<Scenario> { |
| 111 | let mut all = Vec::new(); |
| 112 | for len in APPEND_LENS { |
| 113 | for shared_tail in [false, true] { |
| 114 | all.push(Scenario { shared_tail, len }); |
| 115 | } |
| 116 | } |
| 117 | all |
| 118 | } |
| 119 | |
| 120 | fn config() -> ModelConfig { |
| 121 | ModelConfig { |
| 122 | num_layers: 2, |
| 123 | num_heads: 4, |
| 124 | num_kv_heads: 2, |
| 125 | head_dim: 16, |
| 126 | hidden_dim: 64, |
| 127 | intermediate_dim: 128, |
| 128 | vocab_size: 256, |
| 129 | block_size: BLOCK_SIZE, |
| 130 | ..Default::default() |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | fn backend(total_blocks: usize) -> NativeTransformerBackend { |
| 135 | let weights = TransformerWeights::reference_test_weights(&config()); |
| 136 | NativeTransformerBackend::with_paged_kv(weights, total_blocks, BLOCK_SIZE) |
| 137 | .expect("small paged backend") |
| 138 | } |
| 139 | |
| 140 | /// Deterministic tokens `start..start+n` of one fixed stream (ids 3..=255). |
| 141 | fn tokens(start: usize, n: usize) -> Vec<u32> { |
| 142 | (start..start + n) |
| 143 | .map(|i| ((i * 37 + 11) % 253 + 3) as u32) |
| 144 | .collect() |
| 145 | } |
| 146 | |
| 147 | fn free_blocks(be: &NativeTransformerBackend) -> usize { |
| 148 | let kv = be.kv_manager.as_ref().expect("kv manager").read(); |
| 149 | kv.free_block_count() |
| 150 | } |
| 151 | |
| 152 | fn table_of(be: &NativeTransformerBackend, id: u64) -> (Vec<usize>, usize) { |
| 153 | let kv = be.kv_manager.as_ref().expect("kv manager").read(); |
| 154 | let table = kv.get_block_table(id).expect("block table"); |
| 155 | (table.block_ids.clone(), table.total_tokens) |
| 156 | } |
| 157 | |
| 158 | /// K and V of every layer over the table's tokens, gathered from the pool. |
| 159 | fn kv_planes(be: &NativeTransformerBackend, id: u64) -> Planes { |
| 160 | let kv = be.kv_manager.as_ref().expect("kv manager").read(); |
| 161 | let mut planes: Planes = Vec::new(); |
| 162 | for layer in 0..config().num_layers { |
| 163 | planes.push(kv.gather_layer_kv(id, layer).expect("gather layer kv")); |
| 164 | } |
| 165 | planes |
| 166 | } |
| 167 | |
| 168 | /// Everything the atomicity check compares before and after a failed call. |
| 169 | struct Snap { |
| 170 | ids: Vec<usize>, |
| 171 | total: usize, |
| 172 | free: usize, |
| 173 | seq_tokens: Vec<u32>, |
| 174 | planes: Planes, |
| 175 | } |
| 176 | |
| 177 | fn snap(be: &NativeTransformerBackend, id: u64) -> Snap { |
| 178 | let (ids, total) = table_of(be, id); |
| 179 | Snap { |
| 180 | ids, |
| 181 | total, |
| 182 | free: free_blocks(be), |
| 183 | seq_tokens: be.sequences[&id].tokens.clone(), |
| 184 | planes: kv_planes(be, id), |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | /// Field-by-field differences between two snapshots (empty = identical). |
| 189 | fn snap_diff(a: &Snap, b: &Snap) -> Vec<String> { |
| 190 | let mut d = Vec::new(); |
| 191 | if a.ids != b.ids { |
| 192 | d.push(format!("block ids {:?} -> {:?}", a.ids, b.ids)); |
| 193 | } |
| 194 | if a.total != b.total { |
| 195 | d.push(format!("table total_tokens {} -> {}", a.total, b.total)); |
| 196 | } |
| 197 | if a.free != b.free { |
| 198 | d.push(format!("free blocks {} -> {}", a.free, b.free)); |
| 199 | } |
| 200 | if a.seq_tokens != b.seq_tokens { |
| 201 | d.push(format!( |
| 202 | "backend sequence tokens {} -> {}", |
| 203 | a.seq_tokens.len(), |
| 204 | b.seq_tokens.len() |
| 205 | )); |
| 206 | } |
| 207 | if !planes_equal(&a.planes, &b.planes) { |
| 208 | d.push("pool K/V of the sequence changed".to_string()); |
| 209 | } |
| 210 | d |
| 211 | } |
| 212 | |
| 213 | /// Bitwise equality of two gathered K/V sets (tolerance 0.0). |
| 214 | fn planes_equal(a: &Planes, b: &Planes) -> bool { |
| 215 | a.len() == b.len() |
| 216 | && a.iter().zip(b.iter()).all(|(x, y)| { |
| 217 | x.0.len() == y.0.len() |
| 218 | && x.1.len() == y.1.len() |
| 219 | && x.0 |
| 220 | .iter() |
| 221 | .zip(y.0.iter()) |
| 222 | .all(|(p, q)| p.to_bits() == q.to_bits()) |
| 223 | && x.1 |
| 224 | .iter() |
| 225 | .zip(y.1.iter()) |
| 226 | .all(|(p, q)| p.to_bits() == q.to_bits()) |
| 227 | }) |
| 228 | } |
| 229 | |
| 230 | /// Largest absolute K or V difference (for the message only; equality is bitwise). |
| 231 | fn planes_max_abs_diff(a: &Planes, b: &Planes) -> f32 { |
| 232 | if a.len() != b.len() { |
| 233 | return f32::INFINITY; |
| 234 | } |
| 235 | let mut max = 0.0f32; |
| 236 | for (x, y) in a.iter().zip(b.iter()) { |
| 237 | if x.0.len() != y.0.len() || x.1.len() != y.1.len() { |
| 238 | return f32::INFINITY; |
| 239 | } |
| 240 | for (p, q) in x.0.iter().zip(y.0.iter()).chain(x.1.iter().zip(y.1.iter())) { |
| 241 | max = max.max((p - q).abs()); |
| 242 | } |
| 243 | } |
| 244 | max |
| 245 | } |
| 246 | |
| 247 | /// One-shot control: the first `len` tokens of the stream prefilled in one |
| 248 | /// call on a backend with a large pool. |
| 249 | fn control_planes(len: usize) -> Planes { |
| 250 | let mut control = backend(BIG_POOL); |
| 251 | control |
| 252 | .prefill_sequence(CONTROL, &tokens(0, len)) |
| 253 | .expect("control prefill"); |
| 254 | kv_planes(&control, CONTROL) |
| 255 | } |
| 256 | |
| 257 | /// Independent oracle for how many new blocks the append needs. It does not |
| 258 | /// use the backend's helper: blocks after minus blocks before, plus one |
| 259 | /// copy-on-write block when the table's partly filled tail is shared. |
| 260 | fn oracle_new_blocks(prompt: usize, appended: usize, shared_partial_tail: bool) -> usize { |
| 261 | let before = prompt.div_ceil(BLOCK_SIZE); |
| 262 | let after = (prompt + appended).div_ceil(BLOCK_SIZE); |
| 263 | let cow = |
| 264 | usize::from(shared_partial_tail && !prompt.is_multiple_of(BLOCK_SIZE) && appended > 0); |
| 265 | after - before + cow |
| 266 | } |
| 267 | |
| 268 | /// Allocates `FILLER` so that exactly `target` blocks stay free. |
| 269 | fn fill_pool_to(be: &NativeTransformerBackend, target: usize) { |
| 270 | let free = free_blocks(be); |
| 271 | assert!( |
| 272 | free >= target, |
| 273 | "setup: only {free} blocks free, cannot leave {target}" |
| 274 | ); |
| 275 | if free > target { |
| 276 | let filler = vec![1u32; (free - target) * BLOCK_SIZE]; |
| 277 | be.kv_manager |
| 278 | .as_ref() |
| 279 | .expect("kv manager") |
| 280 | .write() |
| 281 | .allocate_sequence(FILLER, &filler) |
| 282 | .expect("filler allocation"); |
| 283 | } |
| 284 | assert_eq!(free_blocks(be), target, "setup: free blocks after filler"); |
| 285 | } |
| 286 | |
| 287 | /// Backend with a pool of `total_blocks`, the prompt prefilled for `SEQ`, the |
| 288 | /// tail optionally shared with `WITNESS`, and (when `free_target` is given) |
| 289 | /// the pool filled by `FILLER` until exactly `free_target` blocks are free. |
| 290 | fn setup( |
| 291 | total_blocks: usize, |
| 292 | shared_tail: bool, |
| 293 | free_target: Option<usize>, |
| 294 | ) -> NativeTransformerBackend { |
| 295 | let mut be = backend(total_blocks); |
| 296 | be.prefill_sequence(SEQ, &tokens(0, PROMPT_LEN)) |
| 297 | .expect("prompt prefill"); |
| 298 | if shared_tail { |
| 299 | be.kv_manager |
| 300 | .as_ref() |
| 301 | .expect("kv manager") |
| 302 | .write() |
| 303 | .fork_sequence(SEQ, WITNESS) |
| 304 | .expect("witness fork"); |
| 305 | } |
| 306 | if let Some(target) = free_target { |
| 307 | fill_pool_to(&be, target); |
| 308 | } |
| 309 | be |
| 310 | } |
| 311 | |
| 312 | /// The append under test: a second prefill chunk of `len` tokens for `SEQ`, |
| 313 | /// at positions `PROMPT_LEN..PROMPT_LEN + len`. |
| 314 | fn append(be: &mut NativeTransformerBackend, len: usize) -> Result<Vec<f32>, String> { |
| 315 | be.prefill_sequence(SEQ, &tokens(PROMPT_LEN, len)) |
| 316 | } |
| 317 | |
| 318 | struct Check { |
| 319 | name: &'static str, |
| 320 | marker: &'static str, |
| 321 | pass: bool, |
| 322 | applicable: bool, |
| 323 | message: String, |
| 324 | } |
| 325 | |
| 326 | fn check_loud() -> Check { |
| 327 | let mut notes = Vec::new(); |
| 328 | let mut silent = false; |
| 329 | let mut bad_error = false; |
| 330 | for sc in scenarios() { |
| 331 | let need = sc.need(); |
| 332 | let mut be = setup(SMALL_POOL, sc.shared_tail, Some(need - 1)); |
| 333 | match append(&mut be, sc.len) { |
| 334 | Ok(_) => { |
| 335 | silent = true; |
| 336 | notes.push(format!( |
| 337 | "{}: append returned Ok with {} free blocks but {need} needed", |
| 338 | sc.label(), |
| 339 | need - 1 |
| 340 | )); |
| 341 | } |
| 342 | Err(e) => { |
| 343 | let needs = format!("needs {need} new KV blocks"); |
| 344 | let only = format!("only {} are free", need - 1); |
| 345 | if e.starts_with(PREFIX) && e.contains(&needs) && e.contains(&only) { |
| 346 | notes.push(format!("{}: loud Err: {e}", sc.label())); |
| 347 | } else { |
| 348 | bad_error = true; |
| 349 | notes.push(format!( |
| 350 | "{}: Err must start with {PREFIX:?} and contain {needs:?} and \ |
| 351 | {only:?}, got: {e}", |
| 352 | sc.label() |
| 353 | )); |
| 354 | } |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | Check { |
| 359 | name: "x_prefill_exhaustion_is_loud", |
| 360 | marker: if silent { M_SILENT } else { M_PREFIX }, |
| 361 | pass: !silent && !bad_error, |
| 362 | applicable: true, |
| 363 | message: notes.join("; "), |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | fn check_atomic() -> Check { |
| 368 | let mut notes = Vec::new(); |
| 369 | let mut applied = false; |
| 370 | let mut pass = true; |
| 371 | for sc in scenarios() { |
| 372 | let need = sc.need(); |
| 373 | let mut be = setup(SMALL_POOL, sc.shared_tail, Some(need - 1)); |
| 374 | let before = snap(&be, SEQ); |
| 375 | match append(&mut be, sc.len) { |
| 376 | Ok(_) => notes.push(format!( |
| 377 | "{}: append did not fail, atomicity not applicable", |
| 378 | sc.label() |
| 379 | )), |
| 380 | Err(_) => { |
| 381 | applied = true; |
| 382 | let diff = snap_diff(&before, &snap(&be, SEQ)); |
| 383 | if diff.is_empty() { |
| 384 | notes.push(format!("{}: state unchanged", sc.label())); |
| 385 | } else { |
| 386 | pass = false; |
| 387 | notes.push(format!( |
| 388 | "{}: failed append left partial state: {}", |
| 389 | sc.label(), |
| 390 | diff.join(", ") |
| 391 | )); |
| 392 | } |
| 393 | } |
| 394 | } |
| 395 | } |
| 396 | Check { |
| 397 | name: "x_prefill_exhaustion_is_atomic", |
| 398 | marker: M_PARTIAL, |
| 399 | pass, |
| 400 | applicable: applied, |
| 401 | message: notes.join("; "), |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | /// Appends `sc.len` tokens on `be` (pool large enough) and compares the |
| 406 | /// result with the one-shot control. Returns notes and whether everything |
| 407 | /// matched exactly. |
| 408 | fn append_matches_control( |
| 409 | be: &mut NativeTransformerBackend, |
| 410 | sc: Scenario, |
| 411 | stage: &str, |
| 412 | ) -> (Vec<String>, bool) { |
| 413 | let label = format!("{} {stage}", sc.label()); |
| 414 | if let Err(e) = append(be, sc.len) { |
| 415 | return (vec![format!("{label}: append returned Err: {e}")], false); |
| 416 | } |
| 417 | let mut notes = Vec::new(); |
| 418 | let mut ok = true; |
| 419 | let full = PROMPT_LEN + sc.len; |
| 420 | let (_, total) = table_of(be, SEQ); |
| 421 | if total != full { |
| 422 | ok = false; |
| 423 | notes.push(format!( |
| 424 | "{label}: table holds {total} tokens, expected {full}" |
| 425 | )); |
| 426 | } |
| 427 | if be.sequences[&SEQ].tokens != tokens(0, full) { |
| 428 | ok = false; |
| 429 | notes.push(format!( |
| 430 | "{label}: backend sequence tokens differ from the stream" |
| 431 | )); |
| 432 | } |
| 433 | let got = kv_planes(be, SEQ); |
| 434 | let want = control_planes(full); |
| 435 | if planes_equal(&got, &want) { |
| 436 | notes.push(format!("{label}: K/V equals the one-shot control exactly")); |
| 437 | } else { |
| 438 | ok = false; |
| 439 | notes.push(format!( |
| 440 | "{label}: pool K/V differs from the one-shot control (max abs diff {})", |
| 441 | planes_max_abs_diff(&got, &want) |
| 442 | )); |
| 443 | } |
| 444 | (notes, ok) |
| 445 | } |
| 446 | |
| 447 | /// The witness shares the old blocks and must be untouched by the append: its |
| 448 | /// K/V equals a prompt-only control. |
| 449 | fn witness_untouched(be: &NativeTransformerBackend) -> bool { |
| 450 | planes_equal(&kv_planes(be, WITNESS), &control_planes(PROMPT_LEN)) |
| 451 | } |
| 452 | |
| 453 | fn check_clean_path() -> Check { |
| 454 | let mut notes = Vec::new(); |
| 455 | let mut pass = true; |
| 456 | for sc in scenarios() { |
| 457 | let mut be = setup(BIG_POOL, sc.shared_tail, None); |
| 458 | let (n, ok) = append_matches_control(&mut be, sc, "clean"); |
| 459 | notes.extend(n); |
| 460 | pass &= ok; |
| 461 | if sc.shared_tail { |
| 462 | if witness_untouched(&be) { |
| 463 | notes.push(format!("{}: witness K/V untouched", sc.label())); |
| 464 | } else { |
| 465 | pass = false; |
| 466 | notes.push(format!("{}: witness K/V changed by the append", sc.label())); |
| 467 | } |
| 468 | } |
| 469 | } |
| 470 | Check { |
| 471 | name: "x_prefill_clean_path_unchanged", |
| 472 | marker: M_CLEAN, |
| 473 | pass, |
| 474 | applicable: true, |
| 475 | message: notes.join("; "), |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | /// Exactly as many free blocks as the append needs: it must succeed, store |
| 480 | /// the right K/V, and drain the pool to zero. |
| 481 | fn check_exact_fit() -> Check { |
| 482 | let mut notes = Vec::new(); |
| 483 | let mut pass = true; |
| 484 | for sc in scenarios() { |
| 485 | let need = sc.need(); |
| 486 | let mut be = setup(SMALL_POOL, sc.shared_tail, Some(need)); |
| 487 | let (n, ok) = append_matches_control(&mut be, sc, "exact fit"); |
| 488 | notes.extend(n); |
| 489 | pass &= ok; |
| 490 | let free_after = free_blocks(&be); |
| 491 | if free_after != 0 { |
| 492 | pass = false; |
| 493 | notes.push(format!( |
| 494 | "{} exact fit: {free_after} blocks free after the append, expected 0", |
| 495 | sc.label() |
| 496 | )); |
| 497 | } |
| 498 | } |
| 499 | Check { |
| 500 | name: "x_exact_fit_ok", |
| 501 | marker: M_BOUNDARY, |
| 502 | pass, |
| 503 | applicable: true, |
| 504 | message: notes.join("; "), |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | /// Single-token path (`forward_token_impl_paged`, reached through |
| 509 | /// `decode_branch_step`): a branch whose shared tail block is full needs a new |
| 510 | /// block, and the pool has none. |
| 511 | fn decode_single_token_leg() -> (bool, String) { |
| 512 | let mut be = backend(SMALL_POOL); |
| 513 | let ctx = be |
| 514 | .create_context(&tokens(0, 2 * BLOCK_SIZE)) |
| 515 | .expect("context"); |
| 516 | let branch = be.fork_context(ctx).expect("branch"); |
| 517 | fill_pool_to(&be, 0); |
| 518 | let before = table_of(&be, branch.0); |
| 519 | let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 520 | be.decode_branch_step(branch) |
| 521 | })); |
| 522 | match outcome { |
| 523 | Ok(Ok((tok, _))) => ( |
| 524 | false, |
| 525 | format!("decode_branch_step returned Ok (token {tok}) with no free block"), |
| 526 | ), |
| 527 | Ok(Err(e)) if e.starts_with(PREFIX) => { |
| 528 | let after = table_of(&be, branch.0); |
| 529 | if after == before && free_blocks(&be) == 0 { |
| 530 | (true, format!("single-token path loud Err: {e}")) |
| 531 | } else { |
| 532 | ( |
| 533 | false, |
| 534 | format!("single-token Err left partial state: {before:?} -> {after:?}"), |
| 535 | ) |
| 536 | } |
| 537 | } |
| 538 | Ok(Err(e)) => ( |
| 539 | false, |
| 540 | format!("single-token Err lacks the prefix {PREFIX:?}: {e}"), |
| 541 | ), |
| 542 | Err(payload) => { |
| 543 | let msg = payload |
| 544 | .downcast_ref::<String>() |
| 545 | .cloned() |
| 546 | .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_string())) |
| 547 | .unwrap_or_else(|| "non-string panic".to_string()); |
| 548 | ( |
| 549 | false, |
| 550 | format!("decode_branch_step panicked instead of returning a loud Err: {msg}"), |
| 551 | ) |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | |
| 556 | /// Batched path (`execute_step` decode request, `forward_decode_batch`): the |
| 557 | /// slot is reserved before compute and a full pool already ends the sequence |
| 558 | /// as `Preempted`; it must never emit a token. |
| 559 | async fn decode_batched_leg() -> (bool, String) { |
| 560 | let mut be = backend(SMALL_POOL); |
| 561 | be.prefill_sequence(SEQ, &tokens(0, 2 * BLOCK_SIZE)) |
| 562 | .expect("prefill"); |
| 563 | fill_pool_to(&be, 0); |
| 564 | let before = table_of(&be, SEQ); |
| 565 | let batch = ScheduledBatch { |
| 566 | prefill_requests: Vec::new(), |
| 567 | decode_requests: vec![SEQ], |
| 568 | block_tables: HashMap::new(), |
| 569 | step_id: 0, |
| 570 | }; |
| 571 | match be.execute_step(&batch).await { |
| 572 | Ok((outputs, _metrics)) => { |
| 573 | let token = outputs |
| 574 | .iter() |
| 575 | .any(|o| matches!(o, DecodeOutput::Token { request_id, .. } if *request_id == SEQ)); |
| 576 | let preempted = outputs.iter().any(|o| { |
| 577 | matches!( |
| 578 | o, |
| 579 | DecodeOutput::Finished { request_id, reason: FinishReason::Preempted, .. } |
| 580 | if *request_id == SEQ |
| 581 | ) |
| 582 | }); |
| 583 | let unchanged = table_of(&be, SEQ) == before; |
| 584 | ( |
| 585 | !token && preempted && unchanged, |
| 586 | format!( |
| 587 | "batched decode outputs: token_emitted={token}, preempted={preempted}, \ |
| 588 | table_unchanged={unchanged}" |
| 589 | ), |
| 590 | ) |
| 591 | } |
| 592 | Err(e) if e.starts_with(PREFIX) => (true, format!("batched decode loud Err: {e}")), |
| 593 | Err(e) => (false, format!("batched decode Err lacks the prefix: {e}")), |
| 594 | } |
| 595 | } |
| 596 | |
| 597 | async fn check_decode() -> Check { |
| 598 | let (single_ok, single_msg) = decode_single_token_leg(); |
| 599 | let (batched_ok, batched_msg) = decode_batched_leg().await; |
| 600 | Check { |
| 601 | name: "x_decode_exhaustion_is_loud", |
| 602 | marker: M_SILENT, |
| 603 | pass: single_ok && batched_ok, |
| 604 | applicable: true, |
| 605 | message: format!("{single_msg}; {batched_msg}"), |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | /// After a failed append, freeing the other sequence and repeating the very |
| 610 | /// same append must succeed with the exact K/V of the one-shot control. |
| 611 | fn check_recovers() -> Check { |
| 612 | let mut notes = Vec::new(); |
| 613 | let mut applied = false; |
| 614 | let mut pass = true; |
| 615 | for sc in scenarios() { |
| 616 | let need = sc.need(); |
| 617 | let mut be = setup(SMALL_POOL, sc.shared_tail, Some(need - 1)); |
| 618 | if append(&mut be, sc.len).is_ok() { |
| 619 | notes.push(format!( |
| 620 | "{}: first append did not fail, retry not applicable", |
| 621 | sc.label() |
| 622 | )); |
| 623 | continue; |
| 624 | } |
| 625 | applied = true; |
| 626 | be.kv_manager |
| 627 | .as_ref() |
| 628 | .expect("kv manager") |
| 629 | .write() |
| 630 | .free_sequence(FILLER) |
| 631 | .expect("free filler"); |
| 632 | let (n, ok) = append_matches_control(&mut be, sc, "retry"); |
| 633 | notes.extend(n); |
| 634 | pass &= ok; |
| 635 | if sc.shared_tail && !witness_untouched(&be) { |
| 636 | pass = false; |
| 637 | notes.push(format!( |
| 638 | "{}: witness K/V changed across the failed and retried append", |
| 639 | sc.label() |
| 640 | )); |
| 641 | } |
| 642 | } |
| 643 | Check { |
| 644 | name: "x_recovers_after_free", |
| 645 | marker: M_RETRY, |
| 646 | pass, |
| 647 | applicable: applied, |
| 648 | message: notes.join("; "), |
| 649 | } |
| 650 | } |
| 651 | |
| 652 | fn write_receipt(checks: &[Check], finished: bool) { |
| 653 | let Ok(path) = std::env::var("AIEN_I25_RECEIPT") else { |
| 654 | return; |
| 655 | }; |
| 656 | let all_pass = finished && checks.iter().all(|c| c.pass); |
| 657 | let receipt = serde_json::json!({ |
| 658 | "test": "prefill_pool_exhaustion", |
| 659 | "block_size": BLOCK_SIZE, |
| 660 | "prompt_len": PROMPT_LEN, |
| 661 | "append_lens": APPEND_LENS, |
| 662 | "small_pool_blocks": SMALL_POOL, |
| 663 | "finished": finished, |
| 664 | "pass": all_pass, |
| 665 | "checks": checks |
| 666 | .iter() |
| 667 | .map(|c| serde_json::json!({ |
| 668 | "name": c.name, |
| 669 | "marker": c.marker, |
| 670 | "pass": c.pass, |
| 671 | "applicable": c.applicable, |
| 672 | "message": c.message, |
| 673 | })) |
| 674 | .collect::<Vec<_>>(), |
| 675 | }); |
| 676 | if let Some(parent) = std::path::Path::new(&path).parent() { |
| 677 | let _ = std::fs::create_dir_all(parent); |
| 678 | } |
| 679 | std::fs::write( |
| 680 | &path, |
| 681 | serde_json::to_string_pretty(&receipt).expect("receipt json"), |
| 682 | ) |
| 683 | .expect("write receipt"); |
| 684 | } |
| 685 | |
| 686 | #[tokio::test] |
| 687 | async fn prefill_pool_exhaustion_is_loud_atomic_and_retryable() { |
| 688 | // A not-finished receipt exists from the start so a crash still leaves |
| 689 | // evidence (pass is false until every check ran). |
| 690 | write_receipt(&[], false); |
| 691 | |
| 692 | let checks = [ |
| 693 | check_loud(), |
| 694 | check_atomic(), |
| 695 | check_clean_path(), |
| 696 | check_exact_fit(), |
| 697 | check_decode().await, |
| 698 | check_recovers(), |
| 699 | ]; |
| 700 | write_receipt(&checks, true); |
| 701 | |
| 702 | // Print every check's outcome before any assert fires, so every marker |
| 703 | // that applies is in the log. |
| 704 | for c in &checks { |
| 705 | if c.pass { |
| 706 | println!( |
| 707 | "PREFILL_I25 check {} PASS (applicable={}): {}", |
| 708 | c.name, c.applicable, c.message |
| 709 | ); |
| 710 | } else { |
| 711 | println!( |
| 712 | "PREFILL_I25 check {} FAIL: {}: {}", |
| 713 | c.name, c.marker, c.message |
| 714 | ); |
| 715 | } |
| 716 | } |
| 717 | for c in &checks { |
| 718 | assert!(c.pass, "{}: {}", c.marker, c.message); |
| 719 | } |
| 720 | } |