interplane.Get Omega
Read in your language

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

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / tests / kv_restart_test.rs

1143 lines · 40526 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//! C7 (sc#484; ADR 0003 sections 4.1, 6.5, 7.5 and 11): persistent KV across a
17//! real process restart, through the daemon wiring
18//! (`shared_kv::enable_persistent_kv`), on a temp-dir host filesystem store.
19//!
20//! Every restart test runs real child processes: the test binary re-runs itself
21//! (`std::env::current_exe`, the pattern of `approved_crash_test.rs:80-89`)
22//! with `--exact restart_child --ignored`, and the role in `KV_RS_ROLE`. Child 1
23//! parks and exits; child 2 is a fresh process that recovers the store from
24//! disk and restores. Host only: no GPU, no CUDA. The greedy test uses the CPU
25//! reference backend (`ReferenceCpuBackend`) with the reference test weights.
26//!
27//! Geometry of the painted tests (as in kv_park_restore_test.rs): block size 4,
28//! chunk of 2 blocks (8 tokens). A 14-token prompt with `max_tokens = 3`
29//! finishes with a computed prefix of 16 tokens: two full chunks.
30
31use aien_abi_core::{
32 AienInferenceBackend, DecodeOutput, ModelConfig, SamplingParams, ScheduledBatch,
33 SequenceRequest, StepMetrics,
34};
35use aien_inference_abi::backend::TensorBackend;
36use aien_inference_abi::{ReferenceCpuBackend, TransformerWeights};
37use aien_kv_cache::{create_shared_kv_manager_with_pool, KvDType, KvPoolConfig, SharedKvManager};
38use aien_kv_store::{EngineConfig, EngineIdentity, StoreState, WeightFormat};
39use aien_runtime::compute_config::HostEngineIdentity;
40use aien_runtime::kv_residency::KvResidencyStatus;
41use aien_runtime::shared_kv::{
42 build_shared_kv_runtime, enable_persistent_kv, KvPersistSettings, ModelKvBinding,
43 SharedKvSizing,
44};
45use aien_runtime::spine::AienRuntimeSpine;
46use aien_scheduler::{ChannelCompletionSink, CompletionEvent, SchedulerConfig, SequenceId};
47use async_trait::async_trait;
48use parking_lot::Mutex;
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::time::{Duration, Instant};
52
53const BLOCK: usize = 4;
54const CHUNK_BLOCKS: u32 = 2;
55const TOTAL_BLOCKS: usize = 64;
56
57// ---------------------------------------------------------------------------
58// Backend stand-in for the painted tests (no K/V writes: the test paints them)
59// ---------------------------------------------------------------------------
60
61#[derive(Default)]
62struct Rec {
63 prefills: Vec<(u64, usize)>,
64 restores: Vec<(u64, usize)>,
65}
66
67struct PaintBackend {
68 rec: Arc<Mutex<Rec>>,
69}
70
71#[async_trait]
72impl AienInferenceBackend for PaintBackend {
73 async fn load_model(&mut self, _config: &ModelConfig) -> Result<(), String> {
74 Ok(())
75 }
76
77 async fn execute_step(
78 &mut self,
79 batch: &ScheduledBatch,
80 ) -> Result<(Vec<DecodeOutput>, StepMetrics), String> {
81 let mut rec = self.rec.lock();
82 let mut outputs = Vec::new();
83 for r in &batch.prefill_requests {
84 rec.prefills.push((r.request_id, r.prompt_tokens.len()));
85 outputs.push(DecodeOutput::Token {
86 request_id: r.request_id,
87 token_id: 100,
88 logprob: None,
89 });
90 }
91 for &id in &batch.decode_requests {
92 outputs.push(DecodeOutput::Token {
93 request_id: id,
94 token_id: 101,
95 logprob: None,
96 });
97 }
98 Ok((outputs, StepMetrics::default()))
99 }
100
101 fn restore_sequence(&mut self, seq_id: u64, tokens: &[u32]) -> Result<(), String> {
102 self.rec.lock().restores.push((seq_id, tokens.len()));
103 Ok(())
104 }
105}
106
107// ---------------------------------------------------------------------------
108// Identity inputs
109// ---------------------------------------------------------------------------
110
111/// The model the painted pool stands for (1 layer, 1 KV head, head dim 8).
112fn paint_model(rms_norm_eps: f32) -> ModelConfig {
113 ModelConfig {
114 model_id: "c7-paint".to_string(),
115 max_sequence_length: 256,
116 block_size: BLOCK,
117 num_layers: 1,
118 num_heads: 1,
119 head_dim: 8,
120 num_kv_heads: 1,
121 hidden_dim: 8,
122 intermediate_dim: 16,
123 vocab_size: 97,
124 rms_norm_eps,
125 rope_theta: 10000.0,
126 rope_scaling: None,
127 tie_word_embeddings: false,
128 eos_token_ids: Vec::new(),
129 qk_norm: false,
130 }
131}
132
133/// The CPU reference model of the greedy test (shared_kv_runtime_test.rs).
134fn greedy_model() -> ModelConfig {
135 ModelConfig {
136 model_id: "c7-greedy-reference".to_string(),
137 max_sequence_length: 256,
138 block_size: BLOCK,
139 num_layers: 3,
140 num_heads: 4,
141 head_dim: 8,
142 num_kv_heads: 2,
143 hidden_dim: 32,
144 intermediate_dim: 64,
145 vocab_size: 97,
146 rms_norm_eps: 1e-5,
147 rope_theta: 10000.0,
148 rope_scaling: None,
149 tie_word_embeddings: false,
150 eos_token_ids: Vec::new(),
151 qk_norm: false,
152 }
153}
154
155fn scheduler() -> SchedulerConfig {
156 SchedulerConfig {
157 max_batch_size: 16,
158 max_batch_tokens: 4096,
159 max_prefill_tokens: 4096,
160 prefill_chunk_size: 4096,
161 chunk_prefill: true,
162 watermark_blocks: 0,
163 }
164}
165
166/// A 0700 temp dir: the host store refuses a root others can reach and
167/// `tempfile` follows the umask (ADR 0003 section 19).
168fn private_tempdir() -> tempfile::TempDir {
169 use std::os::unix::fs::PermissionsExt;
170 tempfile::Builder::new()
171 .permissions(std::fs::Permissions::from_mode(0o700))
172 .tempdir()
173 .expect("tempdir")
174}
175
176/// A generated test store key (ADR 0003 section 20), never a vault secret. The
177/// same key across "restarts" so restored objects open.
178const TEST_STORE_KEY: &str = "6b3f0c2d9a1e4f5b7c8d0e1f2a3b4c5d6e7f8091a2b3c4d5e6f708192a3b4c5d";
179
180fn settings(dir: &Path) -> KvPersistSettings {
181 let dir = dir.to_string_lossy().to_string();
182 KvPersistSettings::from_lookup(|k| match k {
183 "AIEN_KV_STORE_DIR" => Some(dir.clone()),
184 "AIEN_KV_STORE_KEY" => Some(TEST_STORE_KEY.to_string()),
185 "AIEN_KV_CHUNK_BLOCKS" => Some(CHUNK_BLOCKS.to_string()),
186 _ => None,
187 })
188 .expect("settings")
189}
190
191fn env_or(name: &str, default: &str) -> String {
192 std::env::var(name).unwrap_or_else(|_| default.to_string())
193}
194
195// ---------------------------------------------------------------------------
196// Painted rig (A1, A3)
197// ---------------------------------------------------------------------------
198
199struct PaintRig {
200 spine: AienRuntimeSpine,
201 backend: PaintBackend,
202 rec: Arc<Mutex<Rec>>,
203 kv: SharedKvManager,
204}
205
206fn paint_pool() -> SharedKvManager {
207 create_shared_kv_manager_with_pool(
208 TOTAL_BLOCKS,
209 BLOCK,
210 KvPoolConfig {
211 num_blocks: TOTAL_BLOCKS,
212 block_size: BLOCK,
213 num_layers: 1,
214 num_kv_heads: 1,
215 head_dim: 8,
216 dtype: KvDType::Bf16,
217 },
218 )
219 .expect("pool")
220}
221
222/// The daemon path: spine over one pool, then `enable_persistent_kv`.
223/// The engine identity of the painted runs (ADR 1.2.2, sc#504). Each input can
224/// be overridden by the parent through `KV_RS_WF`, `KV_RS_BUILD`, `KV_RS_ROUND`
225/// and `KV_RS_WHOLE_PROMPT`, so one restart test changes exactly one of them.
226struct PaintEngine {
227 build: String,
228 round: String,
229 weight_format: WeightFormat,
230 config_digest: [u8; 32],
231}
232
233impl PaintEngine {
234 fn from_env() -> Self {
235 let weight_format = match env_or("KV_RS_WF", "as-file").as_str() {
236 "as-file" => WeightFormat::AsFile,
237 "bf16" => WeightFormat::Bf16,
238 "fp8-experts" => WeightFormat::Fp8Experts,
239 "fp8-all" => WeightFormat::Fp8All,
240 other => panic!("KV_RS_WF {other:?}"),
241 };
242 let config = EngineConfig {
243 num_experts: 0,
244 experts_per_token: 0,
245 expert_intermediate_dim: 0,
246 whole_prompt_prefill: env_or("KV_RS_WHOLE_PROMPT", "0") == "1",
247 device_router: false,
248 matmul_path: "c7-paint",
249 };
250 Self {
251 build: env_or("KV_RS_BUILD", "c7-paint-build"),
252 round: env_or("KV_RS_ROUND", "c7-paint@epoch-1"),
253 weight_format,
254 config_digest: config.digest().expect("engine config digest"),
255 }
256 }
257
258 fn identity(&self) -> EngineIdentity<'_> {
259 EngineIdentity {
260 weight_format: self.weight_format,
261 engine_build_id: &self.build,
262 rounding_class: &self.round,
263 engine_config_digest: self.config_digest,
264 }
265 }
266}
267
268fn paint_rig(dir: &Path, sha: u8, eps: f32) -> PaintRig {
269 let kv = paint_pool();
270 let mut spine = AienRuntimeSpine::new(64, scheduler(), kv.clone());
271 let model = paint_model(eps);
272 let engine = PaintEngine::from_env();
273 let line = enable_persistent_kv(
274 &mut spine,
275 &settings(dir),
276 &ModelKvBinding {
277 model: &model,
278 arith_id: "c7-paint-backend",
279 model_sha256: [sha; 32],
280 model_digest_kind: "sha256",
281 engine: engine.identity(),
282 },
283 None,
284 )
285 .expect("enable persistent KV")
286 .expect("persistence on with a store dir");
287 assert!(line.contains("persistent KV"), "startup line: {line}");
288 let rec = Arc::new(Mutex::new(Rec::default()));
289 PaintRig {
290 spine,
291 backend: PaintBackend { rec: rec.clone() },
292 rec,
293 kv,
294 }
295}
296
297fn kv_status(spine: &AienRuntimeSpine) -> KvResidencyStatus {
298 spine.kv_residency_status().expect("residency installed")
299}
300
301fn store_state(spine: &AienRuntimeSpine) -> StoreState {
302 spine
303 .kv_residency()
304 .expect("residency")
305 .store_capacity()
306 .state
307}
308
309/// Recovery runs on the storage worker in slices; the step loop keeps running
310/// meanwhile. Wait (bounded) until the walk is done and admission is open.
311fn wait_store_open(spine: &AienRuntimeSpine) {
312 let t0 = Instant::now();
313 while store_state(spine) == StoreState::Recovering {
314 assert!(
315 t0.elapsed() < Duration::from_secs(10),
316 "recovery never ended"
317 );
318 std::thread::sleep(Duration::from_millis(1));
319 }
320 assert_eq!(store_state(spine), StoreState::Open);
321}
322
323fn finished(spine: &AienRuntimeSpine, seq: u64) -> bool {
324 SequenceId::from_u64(seq)
325 .ok()
326 .and_then(|id| spine.scheduler.arena().get(id).map(|_| ()))
327 .is_none()
328}
329
330fn request(prompt: &[u32], max_tokens: usize) -> SequenceRequest {
331 SequenceRequest {
332 request_id: 0,
333 prompt_tokens: prompt.to_vec(),
334 sampling_params: SamplingParams {
335 temperature: 0.0,
336 top_p: 1.0,
337 max_tokens,
338 stop_token_ids: vec![],
339 },
340 arrival_time_ns: 0,
341 priority: 1,
342 }
343}
344
345async fn paint_step_until(r: &mut PaintRig, what: &str, cond: impl Fn(&PaintRig) -> bool) {
346 let t0 = Instant::now();
347 loop {
348 if cond(r) {
349 return;
350 }
351 assert!(
352 t0.elapsed() < Duration::from_secs(10),
353 "timed out waiting for: {what}; status {:?}",
354 kv_status(&r.spine)
355 );
356 r.spine.step(&mut r.backend).await.expect("step");
357 std::thread::sleep(Duration::from_millis(1));
358 }
359}
360
361/// Distinct bytes for block `j` of the parked turn; `salt` makes a different
362/// pattern (the negative control expects it and must fail).
363fn pattern(j: usize, len: usize, salt: u8) -> Vec<u8> {
364 (0..len)
365 .map(|i| {
366 (j as u8)
367 .wrapping_mul(29)
368 .wrapping_add(7)
369 .wrapping_add(salt)
370 ^ (i as u8)
371 })
372 .collect()
373}
374
375fn table_blocks(kv: &SharedKvManager, seq: u64) -> Vec<usize> {
376 kv.read()
377 .get_block_table(seq)
378 .expect("block table")
379 .block_ids
380 .clone()
381}
382
383fn read_block(kv: &SharedKvManager, b: usize) -> Vec<u8> {
384 let kv = kv.read();
385 let pool = kv.pool().expect("pool");
386 let len = pool.block_bytes();
387 // SAFETY: test-only read of one in-range pool block under the KV read lock.
388 unsafe { std::slice::from_raw_parts(pool.base_ptr().add(b * len), len) }.to_vec()
389}
390
391fn paint(kv: &SharedKvManager, seq: u64) {
392 let mut kv = kv.write();
393 let blocks = kv.get_block_table(seq).expect("table").block_ids.clone();
394 let pool = kv.pool_mut().expect("pool");
395 let len = pool.block_bytes();
396 let base = pool.base_mut_ptr();
397 for (j, &b) in blocks.iter().enumerate() {
398 let bytes = pattern(j, len, 0);
399 // SAFETY: in-range pool block, written under the KV write lock.
400 unsafe { std::ptr::copy_nonoverlapping(bytes.as_ptr(), base.add(b * len), len) };
401 }
402}
403
404fn prompt14() -> Vec<u32> {
405 (1..=14u32).map(|t| t * 3 + 1).collect()
406}
407
408/// `prompt14()` plus the two computed generated tokens (100, 101) plus four
409/// new tokens: restorable prefix 16 tokens, two full chunks.
410fn restore_prompt() -> Vec<u32> {
411 let mut v = prompt14();
412 v.extend_from_slice(&[100, 101, 500, 501, 502, 503]);
413 v
414}
415
416/// Shuts the store down with the configured drain deadline (ADR 7.5) and
417/// checks that every park reached its terminal before the process exits.
418fn drain(spine: &AienRuntimeSpine) {
419 let handle = spine.kv_drain_handle().expect("drain handle");
420 let report = handle.drain();
421 assert!(
422 report.unfinished.is_empty(),
423 "unfinished at exit: {:?}",
424 report.unfinished
425 );
426}
427
428async fn child_paint_park(dir: &Path) {
429 let sha: u8 = env_or("KV_RS_SHA", "7").parse().expect("sha");
430 let eps: f32 = env_or("KV_RS_EPS", "0.00001").parse().expect("eps");
431 let mut r = paint_rig(dir, sha, eps);
432 wait_store_open(&r.spine);
433 let seq = r.spine.submit_request(request(&prompt14(), 3));
434 r.spine.step(&mut r.backend).await.expect("prefill step");
435 paint(&r.kv, seq);
436 paint_step_until(&mut r, "turn finished and parks published", |r| {
437 let s = kv_status(&r.spine);
438 finished(&r.spine, seq) && s.parking_jobs == 0 && s.stats.park_published_total == 2
439 })
440 .await;
441 drain(&r.spine);
442}
443
444async fn child_paint_restore(dir: &Path) {
445 let sha: u8 = env_or("KV_RS_SHA", "7").parse().expect("sha");
446 let eps: f32 = env_or("KV_RS_EPS", "0.00001").parse().expect("eps");
447 let salt: u8 = env_or("KV_RS_SALT", "0").parse().expect("salt");
448 let expect = env_or("KV_RS_EXPECT", "restored");
449 let mut r = paint_rig(dir, sha, eps);
450 wait_store_open(&r.spine);
451
452 // A6 (restart accounting): every object found at recovery is counted,
453 // whatever its namespace. The miss role runs right after the park, so it
454 // finds exactly the two parked chunks (of another namespace); later
455 // children also find what earlier restore children parked.
456 let cap = r.spine.kv_residency().expect("residency").store_capacity();
457 if expect == "miss" {
458 assert_eq!(cap.objects, 2, "both parked chunks rediscovered: {cap:?}");
459 } else {
460 assert!(cap.objects >= 2, "parked chunks rediscovered: {cap:?}");
461 }
462 assert!(cap.used_bytes > 0, "{cap:?}");
463
464 let prompt = restore_prompt();
465 let seq = r.spine.submit_request(request(&prompt, 3));
466 if expect == "restored" {
467 paint_step_until(&mut r, "restore committed", |r| {
468 r.rec.lock().restores.iter().any(|&(id, _)| id == seq)
469 })
470 .await;
471 let s = kv_status(&r.spine);
472 assert_eq!(s.stats.restore_tokens_total, 16, "{s:?}");
473 let len = r.kv.read().pool().expect("pool").block_bytes();
474 let blocks = table_blocks(&r.kv, seq);
475 for (j, &b) in blocks.iter().take(4).enumerate() {
476 assert_eq!(
477 read_block(&r.kv, b),
478 pattern(j, len, salt),
479 "restored block {j} differs from the bytes parked before the restart"
480 );
481 }
482 } else {
483 paint_step_until(&mut r, "request finished", |r| finished(&r.spine, seq)).await;
484 let s = kv_status(&r.spine);
485 assert_eq!(
486 s.stats.restore_jobs_total, 0,
487 "foreign namespace served: {s:?}"
488 );
489 assert_eq!(s.stats.restore_fallback_prefill_total, 1, "{s:?}");
490 assert!(r.rec.lock().restores.is_empty());
491 let first = r
492 .rec
493 .lock()
494 .prefills
495 .iter()
496 .find(|(id, _)| *id == seq)
497 .map(|&(_, n)| n);
498 assert_eq!(
499 first,
500 Some(prompt.len()),
501 "plain prefill from position zero"
502 );
503 }
504 // Let this turn's own parks reach their terminals, so the drain has
505 // nothing to cancel.
506 paint_step_until(&mut r, "turn finished and parks terminal", |r| {
507 finished(&r.spine, seq) && kv_status(&r.spine).parking_jobs == 0
508 })
509 .await;
510 drain(&r.spine);
511}
512
513// ---------------------------------------------------------------------------
514// Greedy rig (A2): the CPU reference backend over the shared pool
515// ---------------------------------------------------------------------------
516
517fn prompt17() -> Vec<u32> {
518 vec![
519 5, 17, 42, 3, 88, 61, 9, 23, 70, 11, 36, 2, 44, 19, 80, 7, 31,
520 ]
521}
522
523const GREEDY_TOKENS: usize = 4;
524
525/// Runs `prompt17()` greedily on a fresh runtime, with persistence through
526/// the daemon wiring when `dir` is given. Returns the generated tokens and the
527/// spine (for status and the drain).
528async fn greedy_run(dir: Option<&Path>) -> (Vec<u32>, AienRuntimeSpine) {
529 let config = greedy_model();
530 let weights = TransformerWeights::reference_test_weights(&config);
531 let (mut spine, mut backend) = build_shared_kv_runtime(
532 weights,
533 Arc::new(ReferenceCpuBackend::new()),
534 scheduler(),
535 SharedKvSizing {
536 arena_capacity: 64,
537 total_blocks: TOTAL_BLOCKS,
538 },
539 )
540 .expect("runtime");
541 let host_engine =
542 HostEngineIdentity::reference(ReferenceCpuBackend::new().name()).expect("engine identity");
543 if let Some(dir) = dir {
544 enable_persistent_kv(
545 &mut spine,
546 &settings(dir),
547 &ModelKvBinding {
548 model: &config,
549 arith_id: ReferenceCpuBackend::new().name(),
550 model_sha256: [3u8; 32],
551 model_digest_kind: "sha256",
552 engine: host_engine.identity(),
553 },
554 None,
555 )
556 .expect("enable")
557 .expect("on");
558 wait_store_open(&spine);
559 }
560 let (sink, mut rx) = ChannelCompletionSink::channel();
561 let sink_id = spine.register_completion_sink(Arc::new(sink));
562 let seq = spine
563 .submit_work(
564 Arc::from(prompt17()),
565 SamplingParams {
566 temperature: 0.0,
567 top_p: 1.0,
568 max_tokens: GREEDY_TOKENS,
569 stop_token_ids: vec![],
570 },
571 1,
572 Some(sink_id),
573 )
574 .expect("submit");
575 let t0 = Instant::now();
576 loop {
577 let parks_done = spine
578 .kv_residency_status()
579 .is_none_or(|s| s.parking_jobs == 0);
580 if finished(&spine, seq) && parks_done {
581 break;
582 }
583 assert!(t0.elapsed() < Duration::from_secs(20), "greedy run stuck");
584 spine.step(&mut backend).await.expect("step");
585 std::thread::sleep(Duration::from_millis(1));
586 }
587 let mut tokens = Vec::new();
588 while let Ok(ev) = rx.try_recv() {
589 if let CompletionEvent::Token { token, .. } = ev {
590 tokens.push(token);
591 }
592 }
593 assert_eq!(tokens.len(), GREEDY_TOKENS, "every greedy token reported");
594 (tokens, spine)
595}
596
597fn write_tokens(path: &Path, tokens: &[u32]) {
598 let text: Vec<String> = tokens.iter().map(u32::to_string).collect();
599 std::fs::write(path, text.join(",")).expect("write tokens");
600}
601
602fn read_tokens(path: &Path) -> Vec<u32> {
603 std::fs::read_to_string(path)
604 .expect("tokens file")
605 .split(',')
606 .map(|t| t.parse().expect("token"))
607 .collect()
608}
609
610async fn child_greedy(dir: &Path, out: &Path, expect_restore: bool) {
611 let (tokens, spine) = greedy_run(Some(dir)).await;
612 let s = kv_status(&spine);
613 if expect_restore {
614 assert_eq!(s.stats.restore_tokens_total, 16, "restored prefix: {s:?}");
615 assert_eq!(s.stats.restore_committed_total, 1, "{s:?}");
616 } else {
617 assert_eq!(s.stats.restore_jobs_total, 0, "cold run restored: {s:?}");
618 assert!(s.stats.park_published_total >= 2, "{s:?}");
619 }
620 write_tokens(out, &tokens);
621 drain(&spine);
622}
623
624// ---------------------------------------------------------------------------
625// The child entry point and the parent's spawner
626// ---------------------------------------------------------------------------
627
628/// Hidden helper: the child. Does nothing unless the parent set `KV_RS_ROLE`.
629#[tokio::test]
630#[ignore]
631async fn restart_child() {
632 let (Ok(role), Ok(dir)) = (std::env::var("KV_RS_ROLE"), std::env::var("KV_RS_DIR")) else {
633 return;
634 };
635 let dir = PathBuf::from(dir);
636 match role.as_str() {
637 "paint-park" => child_paint_park(&dir).await,
638 "paint-restore" => child_paint_restore(&dir).await,
639 "greedy-park" => child_greedy(&dir, &dir.join("cold.txt"), false).await,
640 "greedy-restore" => child_greedy(&dir, &dir.join("restored.txt"), true).await,
641 other => panic!("unknown role {other}"),
642 }
643}
644
645/// Runs one child process; returns whether it succeeded.
646fn run_child(role: &str, dir: &Path, env: &[(&str, &str)]) -> bool {
647 let mut cmd = std::process::Command::new(std::env::current_exe().expect("current_exe"));
648 cmd.args([
649 "--exact",
650 "restart_child",
651 "--ignored",
652 "--nocapture",
653 "--test-threads=1",
654 ]);
655 // The child reads only what the parent hands it.
656 for (k, _) in std::env::vars() {
657 if k.starts_with("AIEN_KV_") || k.starts_with("KV_RS_") {
658 cmd.env_remove(k);
659 }
660 }
661 cmd.env("KV_RS_ROLE", role).env("KV_RS_DIR", dir);
662 for (k, v) in env {
663 cmd.env(k, v);
664 }
665 let out = cmd.output().expect("spawn child");
666 if !out.status.success() {
667 eprintln!(
668 "child {role} {env:?} failed: {:?}\n{}",
669 out.status,
670 String::from_utf8_lossy(&out.stdout)
671 .lines()
672 .chain(String::from_utf8_lossy(&out.stderr).lines())
673 .filter(|l| l.contains("panicked")
674 || l.contains("assert")
675 || l.contains("left")
676 || l.contains("right")
677 || l.contains("differs"))
678 .collect::<Vec<_>>()
679 .join("\n")
680 );
681 }
682 out.status.success()
683}
684
685// ---------------------------------------------------------------------------
686// Tests
687// ---------------------------------------------------------------------------
688
689/// A1 (process restart row of ADR 11): child 1 parks a painted turn on a host
690/// filesystem store and exits through the drain; child 2, a new process,
691/// recovers the store from disk and restores the prefix into its own pool with
692/// the bytes child 1 parked. Negative control: a child 2 that expects a
693/// different byte pattern must fail, so the comparison is not vacuous.
694#[test]
695fn process_restart_rediscovers_and_restores_identical_bytes() {
696 let dir = private_tempdir();
697 assert!(
698 run_child("paint-park", dir.path(), &[]),
699 "child 1 (park) failed"
700 );
701 assert!(
702 run_child("paint-restore", dir.path(), &[]),
703 "child 2 (restore after restart) failed"
704 );
705 assert!(
706 !run_child("paint-restore", dir.path(), &[("KV_RS_SALT", "1")]),
707 "negative control: a child expecting other bytes passed"
708 );
709}
710
711/// A2 (ADR 6.5): a prompt run cold records its greedy tokens and parks; after
712/// a process restart the same prompt restores its 16-token prefix, prefills the
713/// remainder on the same CPU backend and must emit the same greedy tokens.
714/// The in-process run without persistence is the uninterrupted baseline.
715#[tokio::test]
716async fn greedy_continuation_after_restart_matches_uninterrupted_baseline() {
717 let dir = private_tempdir();
718 assert!(
719 run_child("greedy-park", dir.path(), &[]),
720 "cold child failed"
721 );
722 assert!(
723 run_child("greedy-restore", dir.path(), &[]),
724 "restored child failed"
725 );
726 let cold = read_tokens(&dir.path().join("cold.txt"));
727 let restored = read_tokens(&dir.path().join("restored.txt"));
728 let (baseline, _) = greedy_run(None).await;
729 assert_eq!(
730 cold, baseline,
731 "cold child differs from the in-process baseline"
732 );
733 assert_eq!(
734 restored, baseline,
735 "greedy continuation after restart differs from the uninterrupted baseline"
736 );
737}
738
739/// A3 end to end: objects parked under one weights digest are rediscovered
740/// and counted after a restart, but a runtime with another digest never
741/// serves them (plain prefill). Positive control: the right digest restores.
742#[test]
743fn wrong_model_digest_namespace_is_never_served_after_restart() {
744 let dir = private_tempdir();
745 assert!(run_child("paint-park", dir.path(), &[("KV_RS_SHA", "7")]));
746 assert!(
747 run_child(
748 "paint-restore",
749 dir.path(),
750 &[("KV_RS_SHA", "8"), ("KV_RS_EXPECT", "miss")]
751 ),
752 "a foreign weights digest was served or not counted"
753 );
754 assert!(
755 run_child("paint-restore", dir.path(), &[("KV_RS_SHA", "7")]),
756 "positive control: the parking digest must restore"
757 );
758}
759
760/// Review finding 1 end to end: same weights digest, different `rms_norm_eps`
761/// in the resolved `ModelConfig`: a different compute-config digest, so a
762/// different namespace, never served after a restart.
763#[test]
764fn different_rms_norm_eps_namespace_is_never_served_after_restart() {
765 let dir = private_tempdir();
766 assert!(run_child(
767 "paint-park",
768 dir.path(),
769 &[("KV_RS_EPS", "0.00001")]
770 ));
771 assert!(
772 run_child(
773 "paint-restore",
774 dir.path(),
775 &[("KV_RS_EPS", "0.000001"), ("KV_RS_EXPECT", "miss")]
776 ),
777 "a different rms_norm_eps was served"
778 );
779 assert!(
780 run_child("paint-restore", dir.path(), &[("KV_RS_EPS", "0.00001")]),
781 "positive control: the parking eps must restore"
782 );
783}
784
785/// sc#504 (ADR 1.2.2): park under one engine identity, restart with exactly
786/// one engine input changed: the parked objects are rediscovered and counted,
787/// never served (plain prefill from position zero). Positive control: the
788/// parking identity restores.
789fn engine_change_is_never_served_after_restart(var: &str, parked: &str, changed: &str) {
790 let dir = private_tempdir();
791 assert!(run_child("paint-park", dir.path(), &[(var, parked)]));
792 assert!(
793 run_child(
794 "paint-restore",
795 dir.path(),
796 &[(var, changed), ("KV_RS_EXPECT", "miss")]
797 ),
798 "{var}={changed} served objects parked with {var}={parked}"
799 );
800 assert!(
801 run_child("paint-restore", dir.path(), &[(var, parked)]),
802 "positive control: {var}={parked} must restore"
803 );
804}
805
806#[test]
807fn weight_format_change_is_never_served_after_restart() {
808 engine_change_is_never_served_after_restart("KV_RS_WF", "bf16", "fp8-experts");
809}
810
811#[test]
812fn engine_build_change_is_never_served_after_restart() {
813 engine_change_is_never_served_after_restart("KV_RS_BUILD", "omega@aaaa", "omega@bbbb");
814}
815
816#[test]
817fn rounding_class_change_is_never_served_after_restart() {
818 engine_change_is_never_served_after_restart("KV_RS_ROUND", "class-a", "class-b");
819}
820
821#[test]
822fn whole_prompt_prefill_change_is_never_served_after_restart() {
823 engine_change_is_never_served_after_restart("KV_RS_WHOLE_PROMPT", "0", "1");
824}
825
826/// A8 (METRICS_AND_SETTINGS): the status report carries the pool allocation
827/// in bytes, which never changes when blocks are freed, separately from the
828/// block counts, and the persistent-KV fields when persistence is on.
829#[tokio::test]
830async fn metrics_report_allocated_bytes_separately_from_free_blocks() {
831 let dir = private_tempdir();
832 let mut r = paint_rig(dir.path(), 7, 1e-5);
833 wait_store_open(&r.spine);
834 let pool_bytes = r.kv.read().pool().expect("pool").layout().total_bytes as u64;
835
836 let before = r.spine.status_report();
837 assert_eq!(before.kv_pool_allocated_bytes, pool_bytes);
838 assert_eq!(before.kv_pool_total_blocks, TOTAL_BLOCKS);
839 assert_eq!(before.kv_pool_free_blocks, TOTAL_BLOCKS);
840 assert_eq!(before.kv_pool_used_blocks, 0);
841 let p = before.kv_persist.clone().expect("persistent KV fields");
842 assert_eq!(p.kv_store_state, "open");
843 assert!(p.kv_store_quota_bytes > 0);
844
845 let seq = r.spine.submit_request(request(&prompt14(), 3));
846 r.spine.step(&mut r.backend).await.expect("step");
847 let during = r.spine.status_report();
848 assert!(during.kv_pool_free_blocks < TOTAL_BLOCKS, "blocks in use");
849 assert_eq!(
850 during.kv_pool_used_blocks + during.kv_pool_free_blocks,
851 TOTAL_BLOCKS
852 );
853 assert_eq!(
854 during.kv_pool_allocated_bytes, pool_bytes,
855 "allocation is constant"
856 );
857
858 paint_step_until(&mut r, "turn finished and parked", |r| {
859 finished(&r.spine, seq) && kv_status(&r.spine).parking_jobs == 0
860 })
861 .await;
862 let after = r.spine.status_report();
863 assert_eq!(after.kv_pool_free_blocks, TOTAL_BLOCKS, "blocks freed");
864 assert_eq!(
865 after.kv_pool_allocated_bytes, pool_bytes,
866 "freeing blocks does not release RAM"
867 );
868 let p = after.kv_persist.expect("persistent KV fields");
869 assert_eq!(p.kv_park_jobs_total, 2);
870 assert!(p.kv_store_persisted_objects >= 2);
871 assert!(p.kv_store_persisted_bytes > 0);
872 drain(&r.spine);
873}
874
875/// `AIEN_KV_STORE_DIR` unset: no store, no hook, no status fields, nothing on
876/// disk. The runtime behaves exactly as before.
877#[tokio::test]
878async fn persistence_off_when_store_dir_unset_changes_nothing() {
879 let kv = paint_pool();
880 let mut spine = AienRuntimeSpine::new(64, scheduler(), kv.clone());
881 let off = KvPersistSettings::from_lookup(|_| None).expect("defaults");
882 let model = paint_model(1e-5);
883 let got = enable_persistent_kv(
884 &mut spine,
885 &off,
886 &ModelKvBinding {
887 model: &model,
888 arith_id: "x",
889 model_sha256: [7; 32],
890 model_digest_kind: "sha256",
891 engine: PaintEngine::from_env().identity(),
892 },
893 None,
894 )
895 .expect("off is not an error");
896 assert!(got.is_none());
897 assert!(spine.kv_residency().is_none());
898 assert!(spine.kv_drain_handle().is_none());
899 assert!(spine.status_report().kv_persist.is_none());
900
901 let rec = Arc::new(Mutex::new(Rec::default()));
902 let mut backend = PaintBackend { rec: rec.clone() };
903 let seq = spine.submit_request(request(&prompt14(), 2));
904 for _ in 0..5 {
905 spine.step(&mut backend).await.expect("step");
906 }
907 assert!(finished(&spine, seq));
908 assert_eq!(kv.read().free_block_count(), TOTAL_BLOCKS);
909 assert_eq!(kv.read().holder_block_count(), 0, "nothing parked");
910}
911
912/// `AIEN_KV_STORE_DIR` set but `AIEN_KV_STORE_KEY` missing or malformed: fail
913/// closed (ADR 0003 section 20). No store is opened, nothing is written, no
914/// park and no restore; requests run as plain prefill, and the status says why.
915#[tokio::test]
916async fn persistence_refused_without_a_valid_store_key_runs_plain_and_says_why() {
917 let short = &TEST_STORE_KEY[..62];
918 let long = format!("{TEST_STORE_KEY}00");
919 for (label, key, reason) in [
920 ("missing", None, "key_missing"),
921 ("malformed", Some("not-a-key"), "key_malformed"),
922 ("short", Some(short), "key_malformed"),
923 ("long", Some(long.as_str()), "key_malformed"),
924 ] {
925 let nanos = std::time::SystemTime::now()
926 .duration_since(std::time::UNIX_EPOCH)
927 .unwrap()
928 .as_nanos();
929 let dir = std::env::temp_dir().join(format!(
930 "aien-kv-c7-nokey-{label}-{}-{nanos}",
931 std::process::id()
932 ));
933 std::fs::create_dir_all(&dir).unwrap();
934 let d = dir.to_string_lossy().to_string();
935 let s = KvPersistSettings::from_lookup(|k| match k {
936 "AIEN_KV_STORE_DIR" => Some(d.clone()),
937 "AIEN_KV_CHUNK_BLOCKS" => Some(CHUNK_BLOCKS.to_string()),
938 "AIEN_KV_STORE_KEY" => key.map(str::to_string),
939 _ => None,
940 })
941 .expect("a bad key is a refusal, not a start failure");
942 let kv = paint_pool();
943 let mut spine = AienRuntimeSpine::new(64, scheduler(), kv.clone());
944 let model = paint_model(1e-5);
945 let line = enable_persistent_kv(
946 &mut spine,
947 &s,
948 &ModelKvBinding {
949 model: &model,
950 arith_id: "c7-paint-backend",
951 model_sha256: [7; 32],
952 model_digest_kind: "sha256",
953 engine: PaintEngine::from_env().identity(),
954 },
955 None,
956 )
957 .expect("refusal is not an error")
958 .expect("the refusal is announced");
959 assert!(
960 line.contains("REFUSED") && line.contains(reason),
961 "{label}: {line}"
962 );
963 assert!(spine.kv_residency().is_none(), "{label}: no store");
964 assert!(spine.kv_drain_handle().is_none());
965 let p = spine
966 .status_report()
967 .kv_persist
968 .expect("refusal is visible in the status");
969 assert_eq!(p.kv_store_state, "refused", "{label}");
970 assert_eq!(p.kv_store_refused_reason, reason, "{label}");
971 assert!(p.kv_store_key_refused_total >= 1, "{label}");
972 assert!(
973 std::fs::read_dir(&dir).unwrap().next().is_none(),
974 "{label}: nothing written under the store dir"
975 );
976 let _ = std::fs::remove_dir_all(&dir);
977
978 let rec = Arc::new(Mutex::new(Rec::default()));
979 let mut backend = PaintBackend { rec: rec.clone() };
980 let seq = spine.submit_request(request(&prompt14(), 2));
981 for _ in 0..5 {
982 spine.step(&mut backend).await.expect("step");
983 }
984 assert!(finished(&spine, seq), "{label}: plain prefill still serves");
985 assert_eq!(kv.read().holder_block_count(), 0, "{label}: nothing parked");
986 }
987}
988
989/// The settings Debug text never carries the store key.
990#[test]
991fn persistent_kv_settings_debug_never_shows_the_store_key() {
992 let s = settings(Path::new("/tmp/kv-c7-debug"));
993 let shown = format!("{s:?}");
994 assert!(!shown.contains(&TEST_STORE_KEY[..16]), "{shown}");
995}
996
997/// A bad persistent-KV setting stops the start, and the message names the
998/// setting.
999#[test]
1000fn bad_persistent_kv_settings_fail_startup_with_the_setting_name() {
1001 for name in [
1002 "AIEN_KV_CHUNK_BLOCKS",
1003 "AIEN_KV_RESTORE_MAX_BLOCKS",
1004 "AIEN_KV_RESTORE_RETRY_WINDOW_MS",
1005 "AIEN_KV_STORE_QUOTA_BYTES",
1006 "AIEN_KV_STORE_MAX_OBJECTS",
1007 "AIEN_KV_STORE_RECOVERY_SLICE_MS",
1008 "AIEN_KV_STORE_MAX_RESTORE_OPS",
1009 "AIEN_KV_STORE_MAX_PARK_OPS",
1010 "AIEN_KV_STORE_MAX_INFLIGHT_BYTES",
1011 "AIEN_KV_STORE_MAX_WAITERS_PER_JOB",
1012 "AIEN_KV_STORE_DRAIN_MS",
1013 "AIEN_KV_PARK",
1014 "AIEN_KV_RESTORE",
1015 ] {
1016 let err = KvPersistSettings::from_lookup(|k| match k {
1017 "AIEN_KV_STORE_DIR" => Some("/tmp/kv-c7".to_string()),
1018 k if k == name => Some("bogus".to_string()),
1019 _ => None,
1020 })
1021 .expect_err(name);
1022 assert!(err.contains(name), "{name}: error does not name it: {err}");
1023 }
1024 let ok = KvPersistSettings::from_lookup(|k| {
1025 (k == "AIEN_KV_RESTORE_RETRY_WINDOW_MS").then(|| "1500".to_string())
1026 })
1027 .expect("valid window");
1028 assert_eq!(ok.restore_retry_window_ms, 1500);
1029 let default = KvPersistSettings::from_lookup(|_| None).expect("defaults");
1030 assert_eq!(default.restore_retry_window_ms, 60_000);
1031}
1032
1033/// The `AIEN_STEP_LOG=1` line gains the persistent-KV counters under their
1034/// METRICS_AND_SETTINGS names.
1035#[test]
1036fn step_log_line_carries_kv_counters() {
1037 let mut s = KvResidencyStatus::default();
1038 s.stats.park_jobs_total = 3;
1039 s.stats.park_failed_total = 1;
1040 s.stats.park_indeterminate_total = 2;
1041 s.stats.restore_jobs_total = 4;
1042 s.stats.restore_fallback_prefill_total = 5;
1043 s.stats.store_stale_completions_total = 6;
1044 s.holder_blocks = 7;
1045 s.restore_inflight_blocks = 8;
1046 let line = aien_runtime::server::kv_step_log_fields(&s);
1047 for want in [
1048 "kv_park_jobs_total=3",
1049 "kv_park_failed_total=1",
1050 "kv_park_indeterminate_total=2",
1051 "kv_restore_jobs_total=4",
1052 "kv_restore_fallback_prefill_total=5",
1053 "kv_store_stale_completions_total=6",
1054 "kv_pool_holder_blocks=7",
1055 "kv_restore_inflight_blocks=8",
1056 ] {
1057 assert!(line.contains(want), "missing {want}: {line}");
1058 }
1059}
1060
1061/// ADR 11: every row of the guarantee matrix carries one of PLANNED,
1062/// TESTED(test name), NOT CLAIMED or NOT_RUN in both adapter columns, and each
1063/// TESTED row names a test that exists in this workspace.
1064#[test]
1065fn guarantee_matrix_rows_are_labelled() {
1066 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
1067 let adr = std::fs::read_to_string(
1068 root.join("docs/adr/0003-persistent-kv-identity-storage-contract-and-ownership.md"),
1069 )
1070 .expect("ADR 0003");
1071 let section = adr
1072 .split("## 11. Guarantee matrix")
1073 .nth(1)
1074 .expect("section 11")
1075 .split("\n## ")
1076 .next()
1077 .expect("section body");
1078 let rows: Vec<Vec<String>> = section
1079 .lines()
1080 .filter(|l| l.starts_with('|'))
1081 .skip(2) // header and separator
1082 .map(|l| {
1083 l.trim_matches('|')
1084 .split('|')
1085 .map(|c| c.trim().to_string())
1086 .collect()
1087 })
1088 .collect();
1089 assert_eq!(rows.len(), 6, "matrix rows");
1090
1091 let mut sources = String::new();
1092 collect_rs(&root.join("crates"), &mut sources);
1093 let mut tested = Vec::new();
1094 for row in &rows {
1095 for cell in &row[1..3] {
1096 let ok = ["PLANNED", "TESTED(", "NOT CLAIMED", "NOT_RUN"]
1097 .iter()
1098 .any(|l| cell.starts_with(l));
1099 assert!(ok, "row {:?}: unlabelled cell {cell:?}", row[0]);
1100 if let Some(rest) = cell.strip_prefix("TESTED(") {
1101 let name = rest.split(')').next().expect("receipt");
1102 for test in name.split(',').map(str::trim) {
1103 assert!(
1104 sources.contains(&format!("fn {test}(")),
1105 "row {:?} names test {test} which does not exist",
1106 row[0]
1107 );
1108 tested.push(test.to_string());
1109 }
1110 }
1111 }
1112 }
1113 // The C7 rows this cut proves.
1114 for must in [
1115 "process_restart_rediscovers_and_restores_identical_bytes",
1116 "greedy_continuation_after_restart_matches_uninterrupted_baseline",
1117 "store_then_recreate_adapter_serves_same_bytes",
1118 ] {
1119 assert!(
1120 tested.iter().any(|t| t == must),
1121 "{must} not labelled TESTED"
1122 );
1123 }
1124}
1125
1126fn collect_rs(dir: &Path, out: &mut String) {
1127 let Ok(entries) = std::fs::read_dir(dir) else {
1128 return;
1129 };
1130 for e in entries.flatten() {
1131 let p = e.path();
1132 if p.is_dir() {
1133 if p.file_name().is_some_and(|n| n == "target") {
1134 continue;
1135 }
1136 collect_rs(&p, out);
1137 } else if p.extension().is_some_and(|x| x == "rs") {
1138 if let Ok(s) = std::fs::read_to_string(&p) {
1139 out.push_str(&s);
1140 }
1141 }
1142 }
1143}