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-serve-http / tests / kv_persist_chip.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 | //! Chip-only acceptance check of persistent KV on the omega engine (sc#505, locked by #499). |
| 17 | //! NOT run by `cargo test`: it loads the 30B checkpoint onto the chip. Run it only through |
| 18 | //! `scripts/own30b-pkv-chip-check.sh` (which builds natively and checks the chip is free): |
| 19 | //! |
| 20 | //! OWN30B_MODEL_DIR=... cargo test --release -p aien-serve-http --test kv_persist_chip -- --ignored |
| 21 | //! |
| 22 | //! In one process: turn 1, wait for the parks, turn 2 with the RAM prefix (the uninterrupted |
| 23 | //! run), then forget the RAM KV and run turn 2 again so it must restore from the store. The two |
| 24 | //! turn 2 replies and the K/V the engine holds afterwards must be identical, byte for byte. |
| 25 | //! The store key is generated in memory for the run; the store lives in a private temp dir. |
| 26 | //! Takes the hive GPU lock (/tmp/aien-gb10.lock) around each generation, as the server does. |
| 27 | |
| 28 | use std::io::Read; |
| 29 | use std::path::PathBuf; |
| 30 | use std::time::Duration; |
| 31 | |
| 32 | use aien_inference_abi::qwen3_moe_omega::WeightFormat; |
| 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::{OmegaDoor, PrefillMode}; |
| 36 | |
| 37 | fn gen_key() -> String { |
| 38 | let mut b = [0u8; 32]; |
| 39 | std::fs::File::open("/dev/urandom") |
| 40 | .unwrap() |
| 41 | .read_exact(&mut b) |
| 42 | .unwrap(); |
| 43 | b.iter().map(|x| format!("{x:02x}")).collect() |
| 44 | } |
| 45 | |
| 46 | fn turn(d: &OmegaDoor, prompt: &[u32], n: usize) -> Vec<u32> { |
| 47 | let p = GenerateParams { |
| 48 | max_new_tokens: n, |
| 49 | temperature: 0.0, |
| 50 | top_p: 1.0, |
| 51 | top_k: 0, |
| 52 | seed: 1, |
| 53 | stop_token_ids: vec![], |
| 54 | }; |
| 55 | let mut out = Vec::new(); |
| 56 | d.generate(prompt, &p, &mut |t| { |
| 57 | out.push(t); |
| 58 | true |
| 59 | }) |
| 60 | .unwrap(); |
| 61 | out |
| 62 | } |
| 63 | |
| 64 | #[test] |
| 65 | #[ignore = "chip-only: loads the 30B checkpoint on omega; run via scripts/own30b-pkv-chip-check.sh"] |
| 66 | fn restored_turn_two_equals_the_uninterrupted_turn_two_on_the_chip() { |
| 67 | let model = PathBuf::from(std::env::var("OWN30B_MODEL_DIR").expect("OWN30B_MODEL_DIR")); |
| 68 | let scratch = std::env::temp_dir().join(format!("pkv505-chip-{}", std::process::id())); |
| 69 | std::fs::create_dir_all(&scratch).unwrap(); |
| 70 | { |
| 71 | use std::os::unix::fs::PermissionsExt; |
| 72 | std::fs::set_permissions(&scratch, std::fs::Permissions::from_mode(0o700)).unwrap(); |
| 73 | } |
| 74 | let mut door = OmegaDoor::load( |
| 75 | &model, |
| 76 | 8192, |
| 77 | WeightFormat::Fp8All, |
| 78 | Some(2000), |
| 79 | PrefillMode::default(), |
| 80 | ) |
| 81 | .expect("omega load"); |
| 82 | let store = scratch.join("store"); |
| 83 | let key = gen_key(); |
| 84 | let settings = kv_persist::settings_from_lookup(|n| match n { |
| 85 | "AIEN_KV_STORE_DIR" => Some(store.display().to_string()), |
| 86 | "AIEN_KV_STORE_KEY" => Some(key.clone()), |
| 87 | _ => None, |
| 88 | }) |
| 89 | .unwrap(); |
| 90 | let env: Vec<(String, String)> = std::env::vars().collect(); |
| 91 | let (sha, kind) = kv_persist::checkpoint_digest(&model).unwrap(); |
| 92 | let identity = kv_persist::OmegaKvIdentity::new(&kv_persist::IdentityInputs { |
| 93 | model_id: "own30b-chip-check", |
| 94 | model_sha256: sha, |
| 95 | model_digest_kind: kind, |
| 96 | config: &door.config(), |
| 97 | rope_scaling: kv_persist::config_has_rope_scaling(&model).unwrap(), |
| 98 | weights: WeightFormat::Fp8All, |
| 99 | switches: door.kv_switches(), |
| 100 | build: &OmegaBuild::linked(), |
| 101 | env: &env, |
| 102 | }); |
| 103 | let (state, line) = kv_persist::open(settings, identity); |
| 104 | eprintln!("{line}"); |
| 105 | let PersistState::On(_) = &state else { |
| 106 | panic!("persistence refused: {line}") |
| 107 | }; |
| 108 | door.set_persistence(state); |
| 109 | let pk = match door.persistence() { |
| 110 | PersistState::On(p) => p, |
| 111 | _ => unreachable!(), |
| 112 | }; |
| 113 | assert!(pk.wait_ready(Duration::from_secs(60))); |
| 114 | |
| 115 | // A 600-token prompt (the same sentence ids repeated), then a continuation. |
| 116 | let p1: Vec<u32> = (0..600u32).map(|i| 1000 + (i * 37) % 5000).collect(); |
| 117 | let _ = turn(&door, &p1, 32); |
| 118 | assert!( |
| 119 | pk.wait_idle(Duration::from_secs(60)), |
| 120 | "parks did not finish" |
| 121 | ); |
| 122 | let h1 = door.history(); |
| 123 | let mut p2 = h1.clone(); |
| 124 | p2.extend([2000u32, 2001, 2002, 2003, 2004]); |
| 125 | |
| 126 | // Freeze the store as it was after turn 1 (the state a restarted server would find). |
| 127 | pk.set_park(false); |
| 128 | let t_u = turn(&door, &p2, 64); |
| 129 | let reused_u = door.reused_last(); |
| 130 | let h_u = door.history(); |
| 131 | let kv_u = door.export_kv_for_check(h_u.len()).unwrap(); |
| 132 | |
| 133 | door.reset_kv(); |
| 134 | let t_r = turn(&door, &p2, 64); |
| 135 | let c = pk.counters(); |
| 136 | eprintln!("counters after the restored turn: {c:?}"); |
| 137 | assert_eq!(c.restores, 1, "turn 2 did not restore: {c:?}"); |
| 138 | assert_eq!( |
| 139 | c.restored_tokens as usize, reused_u, |
| 140 | "restored up to the uninterrupted reuse point" |
| 141 | ); |
| 142 | assert_eq!(door.reused_last(), reused_u); |
| 143 | assert_eq!( |
| 144 | t_r, t_u, |
| 145 | "restored continuation differs from the uninterrupted run" |
| 146 | ); |
| 147 | assert_eq!(door.history(), h_u); |
| 148 | let kv_r = door.export_kv_for_check(h_u.len()).unwrap(); |
| 149 | assert!( |
| 150 | kv_r == kv_u, |
| 151 | "the K/V after the restored turn differs from the uninterrupted one" |
| 152 | ); |
| 153 | drop(door); |
| 154 | let _ = std::fs::remove_dir_all(&scratch); |
| 155 | } |
| 156 | |
| 157 | /// `/proc/self/io` `read_bytes`: bytes this process caused to be read from the block layer. |
| 158 | fn proc_read_bytes() -> u64 { |
| 159 | let s = std::fs::read_to_string("/proc/self/io").unwrap(); |
| 160 | s.lines() |
| 161 | .find_map(|l| l.strip_prefix("read_bytes: ")) |
| 162 | .unwrap() |
| 163 | .trim() |
| 164 | .parse() |
| 165 | .unwrap() |
| 166 | } |
| 167 | |
| 168 | /// Drops the page cache (DGX Spark known issues: `sync; echo 3 > /proc/sys/vm/drop_caches`). |
| 169 | fn drop_caches() { |
| 170 | let ok = std::process::Command::new("sudo") |
| 171 | .args(["-n", "sh", "-c", "sync; echo 3 > /proc/sys/vm/drop_caches"]) |
| 172 | .status() |
| 173 | .unwrap() |
| 174 | .success(); |
| 175 | assert!(ok, "drop_caches needs sudo -n"); |
| 176 | } |
| 177 | |
| 178 | fn store_objects(dir: &std::path::Path, out: &mut Vec<PathBuf>) { |
| 179 | for e in std::fs::read_dir(dir).unwrap() { |
| 180 | let p = e.unwrap().path(); |
| 181 | if p.is_dir() { |
| 182 | store_objects(&p, out); |
| 183 | } else { |
| 184 | out.push(p); |
| 185 | } |
| 186 | } |
| 187 | } |
| 188 | |
| 189 | fn ms(d: Duration) -> f64 { |
| 190 | d.as_secs_f64() * 1e3 |
| 191 | } |
| 192 | |
| 193 | fn summary(v: &mut [f64]) -> String { |
| 194 | v.sort_by(|a, b| a.partial_cmp(b).unwrap()); |
| 195 | format!( |
| 196 | "min={:.3} median={:.3} max={:.3} n={}", |
| 197 | v[0], |
| 198 | v[v.len() / 2], |
| 199 | v[v.len() - 1], |
| 200 | v.len() |
| 201 | ) |
| 202 | } |
| 203 | |
| 204 | /// Chip qualification of #514 (plan: docs/inference/evidence/pkv514-chip-20261014/PLAN.md): |
| 205 | /// the fused-cache export/import round trip byte for byte, the checkpoint cost, the NVMe restore |
| 206 | /// latency cold and warm, and the negative controls (a flipped payload byte must show, a |
| 207 | /// truncated payload and corrupted stored objects must be refused). Prints `SNAP` lines. |
| 208 | #[test] |
| 209 | #[ignore = "chip-only: loads the 30B checkpoint on omega; run by hand per the #514 plan"] |
| 210 | fn fused_cache_round_trip_cost_and_restore_latency_on_the_chip() { |
| 211 | use std::time::Instant; |
| 212 | const REPS: usize = 5; |
| 213 | let model = PathBuf::from(std::env::var("OWN30B_MODEL_DIR").expect("OWN30B_MODEL_DIR")); |
| 214 | // The store must be on the NVMe (not tmpfs) for a cold read. |
| 215 | let scratch_root = std::env::var("PKV_CHIP_SCRATCH") |
| 216 | .map(PathBuf::from) |
| 217 | .unwrap_or_else(|_| std::env::temp_dir()); |
| 218 | let scratch = scratch_root.join(format!("pkv514-chip-{}", std::process::id())); |
| 219 | std::fs::create_dir_all(&scratch).unwrap(); |
| 220 | { |
| 221 | use std::os::unix::fs::PermissionsExt; |
| 222 | std::fs::set_permissions(&scratch, std::fs::Permissions::from_mode(0o700)).unwrap(); |
| 223 | } |
| 224 | let mut door = OmegaDoor::load( |
| 225 | &model, |
| 226 | 8192, |
| 227 | WeightFormat::Fp8All, |
| 228 | Some(2000), |
| 229 | PrefillMode::default(), |
| 230 | ) |
| 231 | .expect("omega load"); |
| 232 | let sw = door.kv_switches(); |
| 233 | eprintln!("SNAP site=switches attention_path={}", sw.attention_path); |
| 234 | assert_eq!( |
| 235 | sw.attention_path, "fused", |
| 236 | "the live server runs the fused cache" |
| 237 | ); |
| 238 | let store = scratch.join("store"); |
| 239 | let key = gen_key(); |
| 240 | let settings = kv_persist::settings_from_lookup(|n| match n { |
| 241 | "AIEN_KV_STORE_DIR" => Some(store.display().to_string()), |
| 242 | "AIEN_KV_STORE_KEY" => Some(key.clone()), |
| 243 | _ => None, |
| 244 | }) |
| 245 | .unwrap(); |
| 246 | let env: Vec<(String, String)> = std::env::vars().collect(); |
| 247 | let (sha, kind) = kv_persist::checkpoint_digest(&model).unwrap(); |
| 248 | let identity = kv_persist::OmegaKvIdentity::new(&kv_persist::IdentityInputs { |
| 249 | model_id: "own30b-chip-check", |
| 250 | model_sha256: sha, |
| 251 | model_digest_kind: kind, |
| 252 | config: &door.config(), |
| 253 | rope_scaling: kv_persist::config_has_rope_scaling(&model).unwrap(), |
| 254 | weights: WeightFormat::Fp8All, |
| 255 | switches: door.kv_switches(), |
| 256 | build: &OmegaBuild::linked(), |
| 257 | env: &env, |
| 258 | }); |
| 259 | let (state, line) = kv_persist::open(settings, identity); |
| 260 | eprintln!("{line}"); |
| 261 | let PersistState::On(_) = &state else { |
| 262 | panic!("persistence refused: {line}") |
| 263 | }; |
| 264 | door.set_persistence(state); |
| 265 | let pk = match door.persistence() { |
| 266 | PersistState::On(p) => p, |
| 267 | _ => unreachable!(), |
| 268 | }; |
| 269 | assert!(pk.wait_ready(Duration::from_secs(60))); |
| 270 | |
| 271 | // Turn 1: a 2048-token prompt and 32 generated tokens, parked by the door. |
| 272 | let p1: Vec<u32> = (0..2048u32).map(|i| 1000 + (i * 37) % 5000).collect(); |
| 273 | let _ = turn(&door, &p1, 32); |
| 274 | assert!( |
| 275 | pk.wait_idle(Duration::from_secs(120)), |
| 276 | "parks did not finish" |
| 277 | ); |
| 278 | pk.set_park(false); |
| 279 | let c = pk.counters(); |
| 280 | let h = door.history(); |
| 281 | let n = h.len(); |
| 282 | eprintln!( |
| 283 | "SNAP site=park positions={n} parked_chunks={} park_bytes={} park_failed={} park_refused={}", |
| 284 | c.parked_chunks, c.park_bytes, c.park_failed, c.park_refused |
| 285 | ); |
| 286 | assert!(c.parked_chunks > 0 && c.park_failed == 0 && c.park_refused == 0); |
| 287 | |
| 288 | // Item 3: checkpoint cost, the export of the whole history under the GPU lock. |
| 289 | let mut t_export = Vec::new(); |
| 290 | let mut a: Option<Vec<u8>> = None; |
| 291 | for _ in 0..REPS { |
| 292 | let t0 = Instant::now(); |
| 293 | let x = door.export_kv_for_check(n).unwrap(); |
| 294 | t_export.push(ms(t0.elapsed())); |
| 295 | match &a { |
| 296 | None => a = Some(x), |
| 297 | Some(a) => assert!(*a == x, "two exports of the same KV differ"), |
| 298 | } |
| 299 | } |
| 300 | let a = a.unwrap(); |
| 301 | assert!(a.iter().any(|&b| b != 0), "export is all zeros"); |
| 302 | eprintln!( |
| 303 | "SNAP site=export positions={n} bytes={} ms_{}", |
| 304 | a.len(), |
| 305 | summary(&mut t_export) |
| 306 | ); |
| 307 | |
| 308 | // Item 1: export -> reset -> import -> export, byte for byte; import timed. |
| 309 | let mut t_import = Vec::new(); |
| 310 | for _ in 0..REPS { |
| 311 | door.reset_kv(); |
| 312 | assert!(door.history().is_empty()); |
| 313 | let t0 = Instant::now(); |
| 314 | door.restore_kv_for_check(&h, &a).unwrap(); |
| 315 | t_import.push(ms(t0.elapsed())); |
| 316 | assert_eq!(door.history(), h); |
| 317 | let b = door.export_kv_for_check(n).unwrap(); |
| 318 | assert!(b == a, "round trip export(import(A)) != A"); |
| 319 | } |
| 320 | eprintln!( |
| 321 | "SNAP site=round_trip identical=true reps={REPS} import_ms_{}", |
| 322 | summary(&mut t_import) |
| 323 | ); |
| 324 | |
| 325 | // Negative control: one flipped byte in the middle of the payload must come back flipped. |
| 326 | let mut bad = a.clone(); |
| 327 | let off = bad.len() / 2; |
| 328 | bad[off] ^= 0x40; |
| 329 | door.restore_kv_for_check(&h, &bad).unwrap(); |
| 330 | let b = door.export_kv_for_check(n).unwrap(); |
| 331 | let diff: Vec<usize> = (0..a.len()).filter(|&i| a[i] != b[i]).collect(); |
| 332 | eprintln!( |
| 333 | "SNAP site=neg_flip differing_bytes={} at={:?}", |
| 334 | diff.len(), |
| 335 | diff.first() |
| 336 | ); |
| 337 | assert_eq!( |
| 338 | diff, |
| 339 | vec![off], |
| 340 | "a flipped byte must show at exactly its offset" |
| 341 | ); |
| 342 | // Negative control: a truncated payload is refused and leaves an empty engine. |
| 343 | let r = door.restore_kv_for_check(&h, &a[..a.len() - 1]); |
| 344 | eprintln!( |
| 345 | "SNAP site=neg_truncated refused={} err={:?}", |
| 346 | r.is_err(), |
| 347 | r.as_ref().err() |
| 348 | ); |
| 349 | assert!(r.is_err() && door.history().is_empty()); |
| 350 | door.restore_kv_for_check(&h, &a).unwrap(); |
| 351 | assert!(door.export_kv_for_check(n).unwrap() == a); |
| 352 | |
| 353 | // Item 4: NVMe restore latency (lookup, read, decrypt, verify), warm then cold. |
| 354 | let mut p2 = h.clone(); |
| 355 | p2.extend([2000u32, 2001, 2002, 2003, 2004]); |
| 356 | let mut objs = Vec::new(); |
| 357 | store_objects(&store.join("objects"), &mut objs); |
| 358 | let obj_bytes: u64 = objs.iter().map(|p| p.metadata().unwrap().len()).sum(); |
| 359 | eprintln!( |
| 360 | "SNAP site=store objects={} object_bytes={obj_bytes}", |
| 361 | objs.len() |
| 362 | ); |
| 363 | let mut warm = Vec::new(); |
| 364 | for _ in 0..REPS { |
| 365 | let t0 = Instant::now(); |
| 366 | let f = pk.fetch(&p2, 0).expect("warm fetch"); |
| 367 | warm.push(ms(t0.elapsed())); |
| 368 | assert_eq!(f.tokens, n); |
| 369 | assert!(f.payload == a, "warm fetched payload != A"); |
| 370 | } |
| 371 | let mut cold = Vec::new(); |
| 372 | let mut cold_read = Vec::new(); |
| 373 | for _ in 0..REPS { |
| 374 | drop_caches(); |
| 375 | let r0 = proc_read_bytes(); |
| 376 | let t0 = Instant::now(); |
| 377 | let f = pk.fetch(&p2, 0).expect("cold fetch"); |
| 378 | cold.push(ms(t0.elapsed())); |
| 379 | let rb = proc_read_bytes() - r0; |
| 380 | cold_read.push(rb); |
| 381 | assert_eq!(f.tokens, n); |
| 382 | assert!(f.payload == a, "cold fetched payload != A"); |
| 383 | } |
| 384 | eprintln!("SNAP site=fetch_warm ms_{}", summary(&mut warm)); |
| 385 | eprintln!( |
| 386 | "SNAP site=fetch_cold ms_{} block_read_bytes={cold_read:?} object_bytes={obj_bytes}", |
| 387 | summary(&mut cold) |
| 388 | ); |
| 389 | // Cold is proven only if the reads reached the block layer. |
| 390 | assert!( |
| 391 | cold_read.iter().all(|&r| r >= obj_bytes), |
| 392 | "a cold fetch read less than the stored bytes from the device: not cold" |
| 393 | ); |
| 394 | |
| 395 | // Negative control: corrupt every stored object; the fetch must refuse. |
| 396 | let before = pk.counters().restore_misses; |
| 397 | for p in &objs { |
| 398 | let mut v = std::fs::read(p).unwrap(); |
| 399 | let m = v.len() / 2; |
| 400 | v[m] ^= 0x40; |
| 401 | std::fs::write(p, v).unwrap(); |
| 402 | } |
| 403 | drop_caches(); |
| 404 | let f = pk.fetch(&p2, 0); |
| 405 | let after = pk.counters().restore_misses; |
| 406 | eprintln!( |
| 407 | "SNAP site=neg_corrupt refused={} misses_before={before:?} misses_after={after:?}", |
| 408 | f.is_none() |
| 409 | ); |
| 410 | assert!(f.is_none(), "a corrupted checkpoint was served"); |
| 411 | assert!(after != before, "the refusal was not counted"); |
| 412 | drop(door); |
| 413 | let _ = std::fs::remove_dir_all(&scratch); |
| 414 | } |