Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/crates/aien-serve-http/tests/kv_persist.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / crates / aien-serve-http / tests / kv_persist.rs` 1100 lines ยท 39957 bytes Raw Blame History 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 //! Persistent KV park and restore on the omega door (sc#505), host only. 17 //! 18 //! The engine is the real `OmegaEngine` over the tiny in-memory checkpoint with a host bf16 19 //! pool (`host_test_engine`), the store is the real sealed host store in a private temp dir, 20 //! and the key is generated per test from /dev/urandom. The GPU lock is a private file, never 21 //! the hive's `/tmp/aien-gb10.lock`. 22 23 use std::collections::HashMap; 24 use std::io::{Read, Write}; 25 use std::net::TcpStream; 26 use std::path::{Path, PathBuf}; 27 use std::sync::atomic::{AtomicUsize, Ordering}; 28 use std::sync::{Arc, Mutex}; 29 use std::time::{Duration, Instant}; 30 31 use aien_inference_abi::qwen3_moe_omega::{host_test_engine, OmegaEngine, WeightFormat}; 32 use aien_serve_http::codec::ByteCodec; 33 use aien_serve_http::engine::{Engine, GenerateParams}; 34 use aien_serve_http::kv_persist::{self, OmegaBuild, PersistState}; 35 use aien_serve_http::omega_engine::{GpuLock, OmegaDoor}; 36 use aien_serve_http::sampling::sample_next; 37 use aien_serve_http::server::{serve, serve_until, ServerConfig}; 38 39 const CONTEXT: usize = 256; 40 const WAIT: Duration = Duration::from_secs(20); 41 42 static NEXT: AtomicUsize = AtomicUsize::new(0); 43 44 /// A private scratch dir (0700) under the system temp dir, removed on drop. 45 struct Scratch(PathBuf); 46 47 impl Scratch { 48 fn new(tag: &str) -> Self { 49 use std::os::unix::fs::PermissionsExt; 50 let n = NEXT.fetch_add(1, Ordering::SeqCst); 51 let p = std::env::temp_dir().join(format!("pkv505-{tag}-{}-{n}", std::process::id())); 52 let _ = std::fs::remove_dir_all(&p); 53 std::fs::create_dir_all(&p).unwrap(); 54 std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o700)).unwrap(); 55 Self(p) 56 } 57 fn store(&self) -> PathBuf { 58 self.0.join("store") 59 } 60 fn lock(&self) -> PathBuf { 61 self.0.join("gpu.lock") 62 } 63 } 64 65 impl Drop for Scratch { 66 fn drop(&mut self) { 67 let _ = std::fs::remove_dir_all(&self.0); 68 } 69 } 70 71 /// 64 hex digits from /dev/urandom (a fresh key per test, never printed). 72 fn gen_key() -> String { 73 let mut b = [0u8; 32]; 74 std::fs::File::open("/dev/urandom") 75 .unwrap() 76 .read_exact(&mut b) 77 .unwrap(); 78 b.iter().map(|x| format!("{x:02x}")).collect() 79 } 80 81 fn test_build() -> OmegaBuild { 82 OmegaBuild { 83 omega_commit: "`d0889a944b02066f84fec71af7b9bbb92f5c986f`".into(), 84 gpu_link: "pinned-source".into(), 85 gpu_archive_sha256: "11".repeat(32), 86 gpu_digest: "unrecorded".into(), 87 gpu_target: "aarch64-unknown-linux-gnu".into(), 88 sc_commit: "22".repeat(20), 89 sc_dirty: false, 90 } 91 } 92 93 /// Everything one door start depends on; a test changes one field. 94 #[derive(Clone)] 95 struct Setup { 96 weights: WeightFormat, 97 build: OmegaBuild, 98 env: Vec<(String, String)>, 99 store_vars: Vec<(String, String)>, 100 } 101 102 impl Setup { 103 fn new(store: &Path, key: &str) -> Self { 104 Self { 105 weights: WeightFormat::Fp8All, 106 build: test_build(), 107 env: Vec::new(), 108 store_vars: vec![ 109 ("AIEN_KV_STORE_DIR".into(), store.display().to_string()), 110 ("AIEN_KV_STORE_KEY".into(), key.into()), 111 ("AIEN_KV_CHUNK_BLOCKS".into(), "1".into()), 112 ], 113 } 114 } 115 fn without(mut self, var: &str) -> Self { 116 self.store_vars.retain(|(k, _)| k != var); 117 self 118 } 119 fn with_var(mut self, var: &str, v: &str) -> Self { 120 self.store_vars.retain(|(k, _)| k != var); 121 self.store_vars.push((var.into(), v.into())); 122 self 123 } 124 } 125 126 fn engine(weights: WeightFormat) -> OmegaEngine { 127 host_test_engine::engine(weights, CONTEXT).unwrap() 128 } 129 130 /// A door with persistence started from `s` (the startup line is returned). 131 fn door(scratch: &Scratch, s: &Setup) -> (OmegaDoor, String) { 132 door_with_fault(scratch, s, None) 133 } 134 135 /// [`door`] with the store's test-only stall (`AIEN_KV_TEST_FAULT`, sc#507). 136 fn door_with_fault(scratch: &Scratch, s: &Setup, fault: Option<&str>) -> (OmegaDoor, String) { 137 door_at(scratch, s, fault, Duration::from_secs(5)) 138 } 139 140 /// [`door_with_fault`] whose generations wait `lock_wait` for the GPU lock. 141 fn door_at( 142 scratch: &Scratch, 143 s: &Setup, 144 fault: Option<&str>, 145 lock_wait: Duration, 146 ) -> (OmegaDoor, String) { 147 let mut d = OmegaDoor::from_parts(engine(s.weights), scratch.lock(), lock_wait); 148 let vars: HashMap = s.store_vars.iter().cloned().collect(); 149 let settings = 150 kv_persist::settings_from_lookup(|n| vars.get(n).cloned()).expect("store dir is set"); 151 let identity = kv_persist::OmegaKvIdentity::new(&kv_persist::IdentityInputs { 152 model_id: "tiny-qwen3-moe", 153 model_sha256: [7u8; 32], 154 model_digest_kind: "file", 155 config: &host_test_engine::config(), 156 rope_scaling: false, 157 weights: s.weights, 158 switches: d.kv_switches(), 159 build: &s.build, 160 env: &s.env, 161 }); 162 let fault = kv_persist::TestFault::from_lookup(|n| { 163 (n == kv_persist::TEST_FAULT_ENV) 164 .then(|| fault.map(str::to_string)) 165 .flatten() 166 }); 167 let (state, line) = kv_persist::open_with_test_fault(settings, identity, fault); 168 if let PersistState::On(p) = &state { 169 assert!(p.wait_ready(WAIT), "store recovery did not finish"); 170 } 171 d.set_persistence(state); 172 (d, line) 173 } 174 175 fn plain_door(scratch: &Scratch) -> OmegaDoor { 176 OmegaDoor::from_parts( 177 engine(WeightFormat::Fp8All), 178 scratch.lock(), 179 Duration::from_secs(5), 180 ) 181 } 182 183 fn greedy(n: usize) -> GenerateParams { 184 GenerateParams { 185 max_new_tokens: n, 186 temperature: 0.0, 187 top_p: 1.0, 188 top_k: 0, 189 seed: 1, 190 stop_token_ids: vec![], 191 } 192 } 193 194 fn turn(d: &OmegaDoor, prompt: &[u32]) -> Vec { 195 let mut out = Vec::new(); 196 d.generate(prompt, &greedy(6), &mut |t| { 197 out.push(t); 198 true 199 }) 200 .unwrap(); 201 out 202 } 203 204 fn prompt1() -> Vec { 205 (0..40u32).map(|i| (i * 7 + 3) % 64).collect() 206 } 207 208 /// Second turn prompt: everything the door holds after turn 1 plus a few new tokens (a chat turn 209 /// that extends the conversation). 210 fn prompt2(history: &[u32]) -> Vec { 211 let mut p = history.to_vec(); 212 p.extend([5, 6, 7, 9]); 213 p 214 } 215 216 fn counters(d: &OmegaDoor) -> kv_persist::PersistCounters { 217 match d.persistence() { 218 PersistState::On(p) => p.counters(), 219 _ => panic!("persistence is not on"), 220 } 221 } 222 223 /// The uninterrupted reference: one plain door that keeps running, turn 2 reuses its RAM prefix. 224 fn uninterrupted(scratch: &Scratch) -> (Vec, Vec, Vec) { 225 let d = plain_door(scratch); 226 let p1 = prompt1(); 227 let o1 = turn(&d, &p1); 228 let h1 = d.history(); 229 let o2 = turn(&d, &prompt2(&h1)); 230 (o1, h1, o2) 231 } 232 233 /// Turn 1 on a persistence door, wait for the parks, stop it (drains the store). 234 fn park_turn1(scratch: &Scratch, s: &Setup) -> (Vec, Vec) { 235 let (a, line) = door(scratch, s); 236 assert!(line.contains("persistent KV: on"), "{line}"); 237 let o1 = turn(&a, &prompt1()); 238 let h1 = a.history(); 239 match a.persistence() { 240 PersistState::On(p) => assert!(p.wait_idle(WAIT), "parks did not finish"), 241 _ => unreachable!(), 242 } 243 let c = counters(&a); 244 assert!( 245 c.parked_chunks >= 3 && c.park_bytes > 0 && c.park_failed == 0, 246 "{c:?}" 247 ); 248 drop(a); 249 (o1, h1) 250 } 251 252 #[test] 253 fn park_then_restart_then_restore_equals_the_uninterrupted_run() { 254 let scratch = Scratch::new("restore"); 255 let s = Setup::new(&scratch.store(), &gen_key()); 256 let (o1, h1) = park_turn1(&scratch, &s); 257 let (u1, uh1, u2) = uninterrupted(&scratch); 258 assert_eq!( 259 (&o1, &h1), 260 (&u1, &uh1), 261 "turn 1 differs with persistence on" 262 ); 263 264 // "Restart": a new engine and a new store handle on the same directory and key. 265 let (b, _) = door(&scratch, &s); 266 let r2 = turn(&b, &prompt2(&h1)); 267 let c = counters(&b); 268 assert_eq!(c.restores, 1, "{c:?}"); 269 assert_eq!( 270 c.restored_tokens, 271 h1.len() as u64, 272 "restored up to the uninterrupted reuse point: {c:?}" 273 ); 274 assert_eq!( 275 r2, u2, 276 "restored continuation differs from the uninterrupted run" 277 ); 278 assert_eq!( 279 b.reused_last(), 280 h1.len(), 281 "the engine reused the restored prefix" 282 ); 283 } 284 285 #[test] 286 fn the_last_prompt_token_is_always_recomputed() { 287 let scratch = Scratch::new("last"); 288 let s = Setup::new(&scratch.store(), &gen_key()); 289 let (_, h1) = park_turn1(&scratch, &s); 290 // Prompt 2 is exactly the parked history: everything is stored, but the last token is stepped. 291 let (b, _) = door(&scratch, &s); 292 let _ = turn(&b, &h1); 293 let c = counters(&b); 294 assert_eq!(c.restores, 1, "{c:?}"); 295 assert_eq!(c.restored_tokens, (h1.len() - 1) as u64, "{c:?}"); 296 assert_eq!(b.reused_last(), h1.len() - 1); 297 } 298 299 #[test] 300 fn a_longer_ram_prefix_is_not_replaced_by_the_store() { 301 let scratch = Scratch::new("ram"); 302 let s = Setup::new(&scratch.store(), &gen_key()); 303 let (a, _) = door(&scratch, &s); 304 let _ = turn(&a, &prompt1()); 305 let h1 = a.history(); 306 match a.persistence() { 307 PersistState::On(p) => assert!(p.wait_idle(WAIT)), 308 _ => unreachable!(), 309 } 310 let _ = turn(&a, &prompt2(&h1)); 311 let c = counters(&a); 312 assert_eq!( 313 c.restores, 0, 314 "the RAM prefix is as long as the store's: {c:?}" 315 ); 316 assert_eq!(a.reused_last(), h1.len()); 317 } 318 319 /// Each identity input changed alone: the parked prefix is never served. 320 #[test] 321 fn each_identity_input_changed_alone_is_never_served() { 322 let scratch = Scratch::new("ident"); 323 let key = gen_key(); 324 let base = Setup::new(&scratch.store(), &key); 325 let (_, h1) = park_turn1(&scratch, &base); 326 let mut variants: Vec<(&str, Setup)> = Vec::new(); 327 let mut v = base.clone(); 328 v.weights = WeightFormat::Fp8Experts; 329 variants.push(("weights fp8-experts", v)); 330 let mut v = base.clone(); 331 v.weights = WeightFormat::Bf16; 332 variants.push(("weights bf16", v)); 333 let mut v = base.clone(); 334 v.build.omega_commit = "e".repeat(40); 335 variants.push(("omega commit", v)); 336 let mut v = base.clone(); 337 v.build.gpu_archive_sha256 = "33".repeat(32); 338 variants.push(("gpu archive digest", v)); 339 let mut v = base.clone(); 340 v.build.sc_commit = "44".repeat(20); 341 variants.push(("engine commit", v)); 342 let mut v = base.clone(); 343 v.env.push(("AIEN_OMEGA_FP8_GEMV".into(), "0".into())); 344 variants.push(("omega fp8 gemv switch", v)); 345 let mut v = base.clone(); 346 v.env 347 .push(("AIEN_OMEGA_DGRAPH_PREFETCH".into(), "1".into())); 348 variants.push(("decode graph prefetch switch", v)); 349 variants.push(( 350 "sharing namespace", 351 base.clone().with_var("AIEN_KV_STORE_NAMESPACE", "other"), 352 )); 353 for (what, v) in variants { 354 let (b, line) = door(&scratch, &v); 355 assert!(line.contains("persistent KV: on"), "{what}: {line}"); 356 let _ = turn(&b, &prompt2(&h1)); 357 let c = counters(&b); 358 assert_eq!( 359 c.restores, 0, 360 "{what} changed, yet the parked prefix was served: {c:?}" 361 ); 362 assert!( 363 c.restore_misses.get("not-found").copied().unwrap_or(0) >= 1, 364 "{what}: {c:?}" 365 ); 366 assert!(b.reused_last() < h1.len(), "{what}"); 367 } 368 // The base setup still restores (the store is intact). 369 let (b, _) = door(&scratch, &base); 370 let _ = turn(&b, &prompt2(&h1)); 371 assert_eq!(counters(&b).restores, 1); 372 } 373 374 #[test] 375 fn unknown_omega_switches_and_the_mutants_refuse_persistence() { 376 let scratch = Scratch::new("mutant"); 377 let base = Setup::new(&scratch.store(), &gen_key()); 378 for (k, v) in [ 379 ("OWN30B_DECODE_GRAPH_MUTANT", "skip-norm"), 380 ("AIEN_OMEGA_SOMETHING_NEW", "1"), 381 ] { 382 let mut s = base.clone(); 383 s.env.push((k.into(), v.into())); 384 let (d, line) = door(&scratch, &s); 385 assert!(line.contains("REFUSED") && line.contains(k), "{k}: {line}"); 386 assert!(matches!(d.persistence(), PersistState::Refused(_))); 387 let _ = turn(&d, &prompt1()); 388 } 389 } 390 391 #[test] 392 fn switch_off_reads_only_the_store_dir_and_changes_nothing() { 393 for dir in [None, Some("")] { 394 let seen = Mutex::new(Vec::::new()); 395 let got = kv_persist::settings_from_lookup(|n| { 396 seen.lock().unwrap().push(n.to_string()); 397 if n == "AIEN_KV_STORE_DIR" { 398 dir.map(String::from) 399 } else { 400 Some("garbage that must not be read".into()) 401 } 402 }); 403 assert!(got.is_none()); 404 assert_eq!(*seen.lock().unwrap(), vec!["AIEN_KV_STORE_DIR".to_string()]); 405 } 406 407 // Tokens: the door with persistence off equals the engine called the way the door always 408 // called it (its own sampler, prefix reuse across turns). 409 let scratch = Scratch::new("off"); 410 let d = plain_door(&scratch); 411 assert!(matches!(d.persistence(), PersistState::Off)); 412 assert!(d.persistence_status().is_none()); 413 let raw = engine(WeightFormat::Fp8All); 414 let p = greedy(6); 415 let q = aien_inference_abi::qwen3_moe_omega::GenerateParams { 416 max_new_tokens: p.max_new_tokens, 417 temperature: p.temperature, 418 top_p: p.top_p, 419 top_k: p.top_k, 420 seed: p.seed, 421 stop_token_ids: p.stop_token_ids.clone(), 422 }; 423 let raw_turn = |prompt: &[u32]| { 424 let mut out = Vec::new(); 425 raw.generate_with( 426 prompt, 427 &q, 428 &mut |lg: &[f32], step| sample_next(lg, &p, step), 429 &mut |t| { 430 out.push(t); 431 true 432 }, 433 ) 434 .unwrap(); 435 out 436 }; 437 let p1 = prompt1(); 438 assert_eq!(turn(&d, &p1), raw_turn(&p1)); 439 let p2 = prompt2(&d.history()); 440 assert_eq!(turn(&d, &p2), raw_turn(&p2)); 441 442 // Health: the same keys as before persistence existed. 443 let rt = tokio::runtime::Runtime::new().unwrap(); 444 let cfg = ServerConfig { 445 port: 0, 446 model_id: "m".into(), 447 bearer_token: "integration-test-private-credential".into(), 448 ..ServerConfig::default() 449 }; 450 let (addr, _h) = rt 451 .block_on(serve(cfg, Arc::new(d), Arc::new(ByteCodec))) 452 .unwrap(); 453 let v = get_json(addr, "/health"); 454 let mut keys: Vec<&str> = v.as_object().unwrap().keys().map(|s| s.as_str()).collect(); 455 keys.sort(); 456 assert_eq!(keys, ["busy", "engine", "model", "status", "uptime_s"]); 457 } 458 459 #[test] 460 fn health_reports_the_persistence_counters_when_on() { 461 let scratch = Scratch::new("health"); 462 let s = Setup::new(&scratch.store(), &gen_key()); 463 let (d, _) = door(&scratch, &s); 464 let _ = turn(&d, &prompt1()); 465 let rt = tokio::runtime::Runtime::new().unwrap(); 466 let cfg = ServerConfig { 467 port: 0, 468 model_id: "m".into(), 469 bearer_token: "integration-test-private-credential".into(), 470 ..ServerConfig::default() 471 }; 472 let (addr, _h) = rt 473 .block_on(serve(cfg, Arc::new(d), Arc::new(ByteCodec))) 474 .unwrap(); 475 let v = get_json(addr, "/health"); 476 let pk = &v["persistent_kv"]; 477 assert_eq!(pk["state"], "on", "{v}"); 478 for k in [ 479 "parked_chunks", 480 "park_bytes", 481 "park_dropped", 482 "restores", 483 "restored_tokens", 484 "restore_bytes", 485 "restore_misses", 486 "refusals", 487 "seal", 488 "recovery", 489 "io", 490 ] { 491 assert!(!pk[k].is_null(), "missing {k}: {pk}"); 492 } 493 for k in [ 494 "done", 495 "failed", 496 "corrupt_deleted", 497 "tmp_deleted", 498 "unlink_failures", 499 "foreign_files", 500 ] { 501 assert!(!pk["recovery"][k].is_null(), "missing recovery.{k}: {pk}"); 502 } 503 for k in [ 504 "read_bytes", 505 "write_bytes", 506 "published", 507 "failed", 508 "disk_full", 509 ] { 510 assert!(!pk["io"][k].is_null(), "missing io.{k}: {pk}"); 511 } 512 assert!( 513 pk["io"]["write_bytes"].as_u64().unwrap() > 0, 514 "the park wrote: {pk}" 515 ); 516 } 517 518 #[test] 519 fn a_corrupted_store_file_is_never_served() { 520 let scratch = Scratch::new("corrupt"); 521 let s = Setup::new(&scratch.store(), &gen_key()); 522 let (_, h1) = park_turn1(&scratch, &s); 523 let mut flipped = 0; 524 for f in files_under(&scratch.store().join("objects")) { 525 let mut b = std::fs::read(&f).unwrap(); 526 let mid = b.len() / 2; 527 b[mid] ^= 0x40; 528 std::fs::write(&f, &b).unwrap(); 529 flipped += 1; 530 } 531 assert!(flipped >= 3, "expected parked objects, found {flipped}"); 532 let (b, _) = door(&scratch, &s); 533 let r2 = turn(&b, &prompt2(&h1)); 534 let c = counters(&b); 535 assert_eq!(c.restores, 0, "{c:?}"); 536 assert_eq!( 537 r2, 538 plain_turn2(&scratch, &h1), 539 "a refused restore must be a plain recompute" 540 ); 541 } 542 543 #[test] 544 fn a_wrong_key_is_never_served() { 545 let scratch = Scratch::new("wrongkey"); 546 let s = Setup::new(&scratch.store(), &gen_key()); 547 let (_, h1) = park_turn1(&scratch, &s); 548 let other = s.clone().with_var("AIEN_KV_STORE_KEY", &gen_key()); 549 let (b, _) = door(&scratch, &other); 550 let r2 = turn(&b, &prompt2(&h1)); 551 if let PersistState::On(_) = b.persistence() { 552 assert_eq!(counters(&b).restores, 0); 553 } 554 assert_eq!(r2, plain_turn2(&scratch, &h1)); 555 } 556 557 #[test] 558 fn a_missing_or_malformed_key_refuses_and_runs_plain() { 559 let scratch = Scratch::new("nokey"); 560 let base = Setup::new(&scratch.store(), &gen_key()); 561 for s in [ 562 base.clone().without("AIEN_KV_STORE_KEY"), 563 base.clone().with_var("AIEN_KV_STORE_KEY", "abc"), 564 ] { 565 let (d, line) = door(&scratch, &s); 566 assert!(line.contains("REFUSED"), "{line}"); 567 assert!(matches!(d.persistence(), PersistState::Refused(_))); 568 let st = d.persistence_status().unwrap(); 569 assert_eq!(st["state"], "refused"); 570 let _ = turn(&d, &prompt1()); 571 } 572 assert!( 573 !scratch.store().exists(), 574 "a refused start must not create the store" 575 ); 576 } 577 578 #[test] 579 fn an_unsafe_store_dir_refuses_and_runs_plain() { 580 use std::os::unix::fs::PermissionsExt; 581 let scratch = Scratch::new("unsafe"); 582 let open = scratch.0.join("open"); 583 std::fs::create_dir_all(&open).unwrap(); 584 std::fs::set_permissions(&open, std::fs::Permissions::from_mode(0o777)).unwrap(); 585 let s = Setup::new(&open.join("store"), &gen_key()); 586 let (d, line) = door(&scratch, &s); 587 assert!(line.contains("REFUSED"), "{line}"); 588 assert!(matches!(d.persistence(), PersistState::Refused(_))); 589 let _ = turn(&d, &prompt1()); 590 } 591 592 fn plain_turn2(scratch: &Scratch, h1: &[u32]) -> Vec { 593 let d = plain_door(scratch); 594 turn(&d, &prompt2(h1)) 595 } 596 597 fn files_under(dir: &Path) -> Vec { 598 let mut out = Vec::new(); 599 let Ok(rd) = std::fs::read_dir(dir) else { 600 return out; 601 }; 602 for e in rd.flatten() { 603 let p = e.path(); 604 if p.is_dir() { 605 out.extend(files_under(&p)); 606 } else { 607 out.push(p); 608 } 609 } 610 out 611 } 612 613 fn get_json(addr: std::net::SocketAddr, path: &str) -> serde_json::Value { 614 let mut s = TcpStream::connect(addr).unwrap(); 615 s.set_read_timeout(Some(Duration::from_secs(10))).unwrap(); 616 write!( 617 s, 618 "GET {path} HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n" 619 ) 620 .unwrap(); 621 let mut raw = Vec::new(); 622 s.read_to_end(&mut raw).unwrap(); 623 let text = String::from_utf8(raw).unwrap(); 624 let body = text.split_once("\r\n\r\n").unwrap().1; 625 serde_json::from_str(body).unwrap_or_else(|e| panic!("{e}: {body}")) 626 } 627 628 fn pk_of(d: &OmegaDoor) -> &kv_persist::KvPersistence { 629 match d.persistence() { 630 PersistState::On(p) => p, 631 _ => panic!("persistence is not on"), 632 } 633 } 634 635 /// Copies `src` to `dst` with its modes (a crash image of the store taken while a write is in 636 /// flight: what a power cut or `kill -9` leaves on disk). 637 fn copy_tree(src: &Path, dst: &Path) { 638 use std::os::unix::fs::PermissionsExt; 639 std::fs::create_dir_all(dst).unwrap(); 640 let mode = std::fs::metadata(src).unwrap().permissions().mode(); 641 std::fs::set_permissions(dst, std::fs::Permissions::from_mode(mode)).unwrap(); 642 for e in std::fs::read_dir(src).unwrap().flatten() { 643 let (p, q) = (e.path(), dst.join(e.file_name())); 644 if p.is_dir() { 645 copy_tree(&p, &q); 646 } else { 647 std::fs::copy(&p, &q).unwrap(); 648 } 649 } 650 } 651 652 fn wait_for(what: &str, mut ok: impl FnMut() -> bool) { 653 let t0 = std::time::Instant::now(); 654 while !ok() { 655 assert!(t0.elapsed() < WAIT, "timed out waiting for {what}"); 656 std::thread::sleep(Duration::from_millis(5)); 657 } 658 } 659 660 #[test] 661 fn the_test_fault_spec_is_parsed_strictly() { 662 let parse = |v: &str| kv_persist::TestFault::from_lookup(|_| Some(v.to_string())); 663 assert!(parse("").unwrap().is_none(), "empty = unset"); 664 for ok in ["p1:5", "p2:0", "p3:100:1", "p4:1:2", "p5:7", "load:12000:1"] { 665 assert_eq!(parse(ok).unwrap().unwrap().spec(), ok); 666 } 667 for bad in [ 668 "p3", "p6:5", "p3:x", "p3:5:y", "p3:5:1:2", "load:-1", "P3:5", 669 ] { 670 assert!(parse(bad).is_err(), "{bad} must refuse"); 671 } 672 // A malformed spec refuses persistence (fail closed); the door runs plain. 673 let scratch = Scratch::new("badfault"); 674 let s = Setup::new(&scratch.store(), &gen_key()); 675 let (d, line) = door_with_fault(&scratch, &s, Some("p9:1")); 676 assert!( 677 line.contains("REFUSED") && line.contains("AIEN_KV_TEST_FAULT"), 678 "{line}" 679 ); 680 assert!(matches!(d.persistence(), PersistState::Refused(_))); 681 } 682 683 #[test] 684 fn a_write_interrupted_before_publish_is_never_served() { 685 // The park stalls before its rename; the store is imaged at that moment (the kill -9 of 686 // the chip check), the temp file is torn in half, and a new door opens the image. 687 let scratch = Scratch::new("torn"); 688 let s = Setup::new(&scratch.store(), &gen_key()); 689 let (a, line) = door_with_fault(&scratch, &s, Some("p3:60000")); 690 assert!(line.contains("TEST FAULT"), "{line}"); 691 let h1 = { 692 let _ = turn(&a, &prompt1()); 693 a.history() 694 }; 695 let tmp = scratch.store().join("tmp"); 696 wait_for("a temp file", || !files_under(&tmp).is_empty()); 697 let image = scratch.0.join("image"); 698 copy_tree(&scratch.store(), &image); 699 // The stalled worker would keep the first door alive for a minute: leave it behind, as 700 // the killed process would. 701 std::mem::forget(a); 702 let torn = files_under(&image.join("tmp")); 703 assert!(!torn.is_empty()); 704 for t in &torn { 705 let len = std::fs::metadata(t).unwrap().len(); 706 std::fs::OpenOptions::new() 707 .write(true) 708 .open(t) 709 .unwrap() 710 .set_len(len / 2) 711 .unwrap(); 712 } 713 assert!( 714 files_under(&image.join("objects")).is_empty(), 715 "nothing was published" 716 ); 717 let si = Setup::new(&image, "").with_var("AIEN_KV_STORE_KEY", &s.store_vars[1].1); 718 let (b, _) = door(&scratch, &si); 719 let r2 = turn(&b, &prompt2(&h1)); 720 let c = counters(&b); 721 assert_eq!(c.restores, 0, "{c:?}"); 722 assert_eq!( 723 r2, 724 plain_turn2(&scratch, &h1), 725 "a torn write must be a plain recompute" 726 ); 727 assert!( 728 files_under(&image.join("tmp")).is_empty(), 729 "recovery removes the torn temp" 730 ); 731 if let PersistState::On(pk) = b.persistence() { 732 let v = pk.status_json(); 733 assert!( 734 v["recovery"]["tmp_deleted"].as_u64().unwrap() >= 1, 735 "health counts the removed temp: {v}" 736 ); 737 assert_eq!(v["recovery"]["done"], true, "{v}"); 738 } else { 739 panic!("persistence should be on"); 740 } 741 } 742 743 #[test] 744 fn a_restore_that_completes_after_its_timeout_is_never_served() { 745 // The load of turn 2 stalls past LOAD_TIMEOUT: the door gives up, prefills, and the late 746 // completion that arrives afterwards is dropped. The store itself stays good. 747 let scratch = Scratch::new("lateload"); 748 let s = Setup::new(&scratch.store(), &gen_key()); 749 let (_, h1) = park_turn1(&scratch, &s); 750 let late = kv_persist::LOAD_TIMEOUT + Duration::from_secs(2); 751 let spec = format!("load:{}:1", late.as_millis()); 752 let (b, _) = door_with_fault(&scratch, &s, Some(&spec)); 753 let r2 = turn(&b, &prompt2(&h1)); 754 let c = counters(&b); 755 assert_eq!(c.restores, 0, "{c:?}"); 756 assert_eq!(c.restore_misses.get("timeout"), Some(&1), "{c:?}"); 757 let plain = plain_turn2(&scratch, &h1); 758 assert_eq!(r2, plain); 759 std::thread::sleep(Duration::from_secs(3)); 760 let c = counters(&b); 761 assert_eq!( 762 c.restores, 0, 763 "the late completion must not count as a restore: {c:?}" 764 ); 765 // A new conversation on the same door is not touched by the stale completion. 766 let fresh: Vec = (0..30u32).map(|i| (i * 5 + 1) % 64).collect(); 767 assert_eq!(turn(&b, &fresh), turn(&plain_door(&scratch), &fresh)); 768 drop(b); 769 let (c2, _) = door(&scratch, &s); 770 assert_eq!(turn(&c2, &prompt2(&h1)), plain); 771 assert_eq!( 772 counters(&c2).restores, 773 1, 774 "the store still serves after the stale load" 775 ); 776 } 777 778 #[test] 779 fn a_park_that_lands_after_the_conversation_moved_on_is_harmless() { 780 // The first park of turn 1 stalls; turn 2 and a diverging turn run while it is in flight 781 // (turn 2 resubmits the chunks the store does not hold yet). Every answer equals the 782 // uninterrupted run, and after a restart the late parks restore turn 2 exactly. 783 let scratch = Scratch::new("latepark"); 784 let s = Setup::new(&scratch.store(), &gen_key()); 785 let (u1, uh1, u2) = uninterrupted(&scratch); 786 let (a, _) = door_with_fault(&scratch, &s, Some("p3:1500:1")); 787 assert_eq!(turn(&a, &prompt1()), u1); 788 let h1 = a.history(); 789 assert_eq!(h1, uh1); 790 assert_eq!(turn(&a, &prompt2(&h1)), u2); 791 let mut other = h1.clone(); 792 other.extend([1, 2, 3, 4]); 793 let plain_other = turn(&plain_door(&scratch), &other); 794 assert_eq!(turn(&a, &other), plain_other); 795 assert!(pk_of(&a).wait_idle(WAIT), "parks did not finish"); 796 let c = counters(&a); 797 assert!(c.parked_chunks >= 3 && c.park_failed == 0, "{c:?}"); 798 drop(a); 799 let (b, _) = door(&scratch, &s); 800 assert_eq!(turn(&b, &prompt2(&h1)), u2); 801 assert_eq!(counters(&b).restores, 1); 802 } 803 804 #[test] 805 fn a_graceful_shutdown_releases_the_engine_and_flushes_the_parks() { 806 // serve_until: on shutdown the server stops and lets go of the engine; dropping the door 807 // then drains the parks still in flight (each stalls 2 s) and leaves no temp file. The 808 // stall is long so the parks are still in flight when the door drops even on a starved 809 // host (with 200 ms they sometimes finished first and the drain went untested); the test 810 // checks that just before the drop. 811 // 812 // The drain budget (`AIEN_KV_STORE_DRAIN_MS`, 2 s by default) is wall-clock time, and when 813 // it runs out the store cancels the parks it has not started (ADR 0003 section 7.5). Three 814 // stalled parks on a host whose test threads are starved (nice 19 behind busy cores) can 815 // need more than 2 s, so with the default budget this test failed under load without any 816 // defect. It checks that the drop drains, not how fast the host is: the budget is WAIT, like 817 // every other wait for the parks in this file, and the drop must return as soon as the 818 // parks are done, well before that budget runs out. 819 let scratch = Scratch::new("shutdown"); 820 let s = Setup::new(&scratch.store(), &gen_key()) 821 .with_var("AIEN_KV_STORE_DRAIN_MS", &WAIT.as_millis().to_string()); 822 let (d, _) = door_with_fault(&scratch, &s, Some("p3:2000")); 823 let _ = turn(&d, &prompt1()); 824 let h1 = d.history(); 825 let keep = Arc::new(d); 826 let rt = tokio::runtime::Runtime::new().unwrap(); 827 let cfg = ServerConfig { 828 port: 0, 829 model_id: "m".into(), 830 bearer_token: "integration-test-private-credential".into(), 831 ..ServerConfig::default() 832 }; 833 let (tx, rx) = tokio::sync::oneshot::channel::<()>(); 834 let engine: Arc = keep.clone(); 835 let (addr, h) = rt 836 .block_on(serve_until(cfg, engine, Arc::new(ByteCodec), async { 837 let _ = rx.await; 838 })) 839 .unwrap(); 840 assert_eq!(get_json(addr, "/health")["status"], "ok"); 841 tx.send(()).unwrap(); 842 rt.block_on(h).unwrap(); 843 assert!(TcpStream::connect(addr).is_err(), "the listener is closed"); 844 wait_for("the server to release the engine", || { 845 Arc::strong_count(&keep) == 1 846 }); 847 let parked_before = pk_of(&keep).counters().parked_chunks; 848 assert!( 849 parked_before < 3, 850 "the parks are still in flight before the drop" 851 ); 852 let t0 = Instant::now(); 853 drop(keep); 854 let took = t0.elapsed(); 855 assert!( 856 took < WAIT, 857 "the drop waited out the drain budget ({took:?}): the parks did not finish" 858 ); 859 assert!( 860 files_under(&scratch.store().join("tmp")).is_empty(), 861 "no temp file left" 862 ); 863 let objects = files_under(&scratch.store().join("objects")).len(); 864 assert!( 865 objects >= 3, 866 "the parks were flushed: {objects} objects, {parked_before} parked before the drop, \ 867 the drop took {took:?}" 868 ); 869 let (b, _) = door(&scratch, &s); 870 let _ = turn(&b, &prompt2(&h1)); 871 assert_eq!(counters(&b).restores, 1); 872 } 873 874 /// #514 chip findings: on the 30B model one 256-token chunk is 25 MB. The storage worker's park 875 /// budget (a quarter of `AIEN_KV_STORE_MAX_INFLIGHT_BYTES`, 64 MB by default) holds two chunks, 876 /// so a 2079-token turn parked 2 of 9 chunks and refused the rest; its restore budget (the other 877 /// three quarters, 192 MB) is smaller than that turn's 204 MB, so the whole restore was refused. 878 /// Here the park budget holds exactly one chunk and the restore budget three, for a 7-chunk 879 /// history: every chunk must still be parked and the restart must restore the whole history. 880 #[test] 881 fn a_turn_larger_than_the_park_and_restore_budgets_is_parked_and_restored_in_full() { 882 let long: Vec = (0..100u32).map(|i| (i * 11 + 5) % 64).collect(); 883 let probe = Scratch::new("budget-probe"); 884 let (a, line) = door(&probe, &Setup::new(&probe.store(), &gen_key())); 885 assert!(line.contains("persistent KV: on"), "{line}"); 886 let _ = turn(&a, &long); 887 assert!(pk_of(&a).wait_idle(WAIT)); 888 let c = counters(&a); 889 assert!(c.parked_chunks >= 7 && c.park_refused == 0, "{c:?}"); 890 let (n, per_chunk) = (c.parked_chunks, c.park_bytes / c.parked_chunks); 891 drop(a); 892 893 let scratch = Scratch::new("budget"); 894 let budget = 4 * (per_chunk + aien_kv_store::record::HEADER_REGION_LEN as u64); 895 let s = Setup::new(&scratch.store(), &gen_key()) 896 .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &budget.to_string()); 897 let (a, line) = door(&scratch, &s); 898 assert!(line.contains("persistent KV: on"), "{line}"); 899 let _ = turn(&a, &long); 900 let h1 = a.history(); 901 assert!(pk_of(&a).wait_idle(WAIT)); 902 let c = counters(&a); 903 assert_eq!( 904 (c.parked_chunks, c.park_refused, c.park_failed), 905 (n, 0, 0), 906 "every chunk parked through a one-chunk park budget: {c:?}" 907 ); 908 drop(a); 909 910 let plain = plain_door(&scratch); 911 let _ = turn(&plain, &long); 912 let u2 = turn(&plain, &prompt2(&plain.history())); 913 let (b, _) = door(&scratch, &s); 914 let r2 = turn(&b, &prompt2(&h1)); 915 let c = counters(&b); 916 assert_eq!( 917 (c.restores, c.restored_tokens), 918 (1, h1.len() as u64), 919 "the whole history restored through a three-chunk restore budget: {c:?}" 920 ); 921 assert_eq!( 922 r2, u2, 923 "restored continuation differs from the uninterrupted run" 924 ); 925 } 926 927 /// What the storage worker charges for one chunk of these tests: its payload (one block at 928 /// `AIEN_KV_CHUNK_BLOCKS=1`, the same for every chunk) plus the header region. Probed by parking a 929 /// turn on a door with the default budgets. 930 fn chunk_charge() -> u64 { 931 let probe = Scratch::new("charge-probe"); 932 let (a, line) = door(&probe, &Setup::new(&probe.store(), &gen_key())); 933 assert!(line.contains("persistent KV: on"), "{line}"); 934 let _ = turn(&a, &prompt1()); 935 assert!(pk_of(&a).wait_idle(WAIT)); 936 let c = counters(&a); 937 assert!(c.parked_chunks > 0 && c.park_refused == 0, "{c:?}"); 938 c.park_bytes / c.parked_chunks + aien_kv_store::record::HEADER_REGION_LEN as u64 939 } 940 941 /// sc#523 item 2: a chunk that can never fit the worker's park budget (a quarter of 942 /// `AIEN_KV_STORE_MAX_INFLIGHT_BYTES`) or restore budget (the rest) is refused at open, not 943 /// spun on at every turn until the credit wait runs out. 944 #[test] 945 fn a_chunk_larger_than_the_park_or_restore_budget_refuses_at_open() { 946 let c = chunk_charge(); 947 let scratch = Scratch::new("oversize"); 948 let s = Setup::new(&scratch.store(), &gen_key()); 949 // Park budget one byte short of a chunk, restore budget three chunks: parking can never run. 950 let short_park = s 951 .clone() 952 .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &(4 * c - 4).to_string()); 953 let (d, line) = door(&scratch, &short_park); 954 assert!( 955 line.contains("REFUSED") && line.contains("park budget"), 956 "{line}" 957 ); 958 assert!(matches!(d.persistence(), PersistState::Refused(_))); 959 let t0 = Instant::now(); 960 assert_eq!( 961 turn(&d, &prompt1()), 962 turn(&plain_door(&scratch), &prompt1()) 963 ); 964 assert!(t0.elapsed() < Duration::from_secs(5), "{:?}", t0.elapsed()); 965 drop(d); 966 // The same budgets with parking off: restore alone fits, so persistence is on. 967 let (d, line) = door(&scratch, &short_park.clone().with_var("AIEN_KV_PARK", "0")); 968 assert!(line.contains("persistent KV: on"), "{line}"); 969 drop(d); 970 // Restore budget (three quarters of one chunk) short of a chunk: restoring can never run. 971 let short_restore = s 972 .with_var("AIEN_KV_PARK", "0") 973 .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &c.to_string()); 974 let (d, line) = door(&scratch, &short_restore); 975 assert!( 976 line.contains("REFUSED") && line.contains("restore budget"), 977 "{line}" 978 ); 979 assert!(matches!(d.persistence(), PersistState::Refused(_))); 980 } 981 982 /// sc#523 item 3: one fetch holds the request for at most [`kv_persist::LOAD_TIMEOUT`] in all, 983 /// submit phase and wait phase together. The restore budget holds one chunk, so each of the three 984 /// loads of turn 2 waits for the one before; each load stalls 4 s, so the last is submitted at 985 /// about 8 s and lands at about 12 s. 986 #[test] 987 fn one_fetch_waits_at_most_the_load_timeout_over_submit_and_wait() { 988 let c = chunk_charge(); 989 let scratch = Scratch::new("onedeadline"); 990 let s = Setup::new(&scratch.store(), &gen_key()); 991 let (_, h1) = park_turn1(&scratch, &s); 992 let narrow = s 993 .clone() 994 .with_var("AIEN_KV_PARK", "0") 995 .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &(2 * c).to_string()); 996 let (b, line) = door_with_fault(&scratch, &narrow, Some("load:4000:3")); 997 assert!(line.contains("persistent KV: on"), "{line}"); 998 let t0 = Instant::now(); 999 let r2 = turn(&b, &prompt2(&h1)); 1000 let took = t0.elapsed(); 1001 let c = counters(&b); 1002 assert_eq!( 1003 (c.restores, c.restore_misses.get("timeout").copied()), 1004 (0, Some(1)), 1005 "turn 2 took {took:?}: {c:?}" 1006 ); 1007 assert!( 1008 took < kv_persist::LOAD_TIMEOUT + Duration::from_secs(2), 1009 "one fetch held the request {took:?}" 1010 ); 1011 assert_eq!(r2, plain_turn2(&scratch, &h1)); 1012 } 1013 1014 /// sc#523 item 4: a refused park drops the rest of its chain (a chain with a hole cannot be 1015 /// restored past it); the dropped chunks are counted. The park budget holds one chunk and the 1016 /// first park stalls past [`kv_persist::PARK_CREDIT_WAIT`], so chunk 2 is refused and the rest 1017 /// is dropped. 1018 #[test] 1019 fn a_refused_park_counts_the_chunks_it_drops() { 1020 let c = chunk_charge(); 1021 let scratch = Scratch::new("parkdrop"); 1022 let s = Setup::new(&scratch.store(), &gen_key()) 1023 .with_var("AIEN_KV_STORE_MAX_INFLIGHT_BYTES", &(4 * c).to_string()); 1024 let stall = kv_persist::PARK_CREDIT_WAIT + Duration::from_secs(2); 1025 let (a, line) = door_with_fault(&scratch, &s, Some(&format!("p3:{}:1", stall.as_millis()))); 1026 assert!(line.contains("persistent KV: on"), "{line}"); 1027 let _ = turn(&a, &prompt1()); 1028 let chunks = a.history().len().div_ceil(16) as u64; 1029 assert!(chunks >= 3, "{chunks}"); 1030 assert!(pk_of(&a).wait_idle(WAIT)); 1031 let v = pk_of(&a).status_json(); 1032 assert_eq!(v["chunk_tokens"], 16, "{v}"); 1033 assert_eq!( 1034 ( 1035 v["parked_chunks"].as_u64(), 1036 v["park_refused"].as_u64(), 1037 v["park_dropped"].as_u64() 1038 ), 1039 (Some(1), Some(1), Some(chunks - 2)), 1040 "every chunk of the turn is accounted for: {v}" 1041 ); 1042 } 1043 1044 /// sc#523 item 5: a prefix loaded from the store but never imported because the GPU lock stayed 1045 /// busy is counted as a restore miss (`gpu-lock-busy`), not lost from the counters. 1046 #[test] 1047 fn a_fetched_prefix_left_unused_by_a_busy_gpu_lock_is_a_miss() { 1048 let scratch = Scratch::new("lockbusy"); 1049 let s = Setup::new(&scratch.store(), &gen_key()); 1050 let (_, h1) = park_turn1(&scratch, &s); 1051 let (b, _) = door_at(&scratch, &s, None, Duration::from_millis(200)); 1052 let held = GpuLock::acquire_at(&scratch.lock(), Duration::from_secs(1)).unwrap(); 1053 let r = b.generate(&prompt2(&h1), &greedy(6), &mut |_| true); 1054 assert!( 1055 r.is_err(), 1056 "the door must answer busy while the lock is held" 1057 ); 1058 let c = counters(&b); 1059 assert_eq!( 1060 (c.restores, c.restore_misses.get("gpu-lock-busy").copied()), 1061 (0, Some(1)), 1062 "{c:?}" 1063 ); 1064 drop(held); 1065 assert_eq!(turn(&b, &prompt2(&h1)), plain_turn2(&scratch, &h1)); 1066 assert_eq!(counters(&b).restores, 1, "the store still serves"); 1067 } 1068 1069 /// sc#523 item 10: the startup read strips the store key from the environment whether or not 1070 /// `AIEN_KV_STORE_DIR` is set (a key exported for nothing must not reach a child either). 1071 #[test] 1072 fn the_startup_read_strips_the_store_key_with_or_without_the_store_dir() { 1073 let key = gen_key(); 1074 for dir in [None, Some(""), Some("/nonexistent/pkv523")] { 1075 let stripped = Mutex::new(Vec::::new()); 1076 let got = kv_persist::take_settings( 1077 |n| match n { 1078 "AIEN_KV_STORE_DIR" => dir.map(String::from), 1079 "AIEN_KV_STORE_KEY" => Some(key.clone()), 1080 _ => None, 1081 }, 1082 |k| stripped.lock().unwrap().push(k.to_string()), 1083 ); 1084 assert_eq!( 1085 *stripped.lock().unwrap(), 1086 vec!["AIEN_KV_STORE_KEY".to_string()], 1087 "dir {dir:?}" 1088 ); 1089 match dir { 1090 Some(d) if !d.is_empty() => { 1091 let s = got.expect("dir set").expect("settings parse"); 1092 assert!( 1093 matches!(s.store_key, Some(Ok(_))), 1094 "the key is in the settings" 1095 ); 1096 } 1097 _ => assert!(got.is_none(), "dir {dir:?}"), 1098 } 1099 } 1100 }