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-expert-residency / tests / residency_tests.rs

603 lines · 19956 bytes Raw Blame History
1mod common;
2
3use aien_expert_residency::{
4 Acquired, ExpertIdentity, ExpertPart, ExpertState, FailureCause, Phase, Pin, PinStatus,
5 Refusal, ResidencyManager, Stats,
6};
7use common::*;
8
9fn fetch(a: Acquired) -> (Pin, aien_expert_residency::FetchTicket) {
10 match a {
11 Acquired::Fetch(p, t) => (p, t),
12 other => panic!("expected a miss, got {other:?}"),
13 }
14}
15
16#[test]
17fn full_lifecycle_and_states() {
18 let mut m = manager(2);
19 let k = id(0, 5);
20 assert_eq!(m.state(&k), ExpertState::Absent);
21 let (pin, t) = fetch(m.acquire(k, SLOT, 100).unwrap());
22 assert_eq!(m.state(&k), ExpertState::Fetching);
23 assert_eq!(m.poll(&pin), Ok(PinStatus::Waiting(Phase::Fetching)));
24 m.mark_verified(&t).unwrap();
25 assert_eq!(m.state(&k), ExpertState::Verified);
26 m.mark_copying(&t).unwrap();
27 assert_eq!(m.state(&k), ExpertState::Copying);
28 m.publish(&t, 350).unwrap();
29 assert_eq!(m.state(&k), ExpertState::InUse);
30 assert_eq!(m.poll(&pin), Ok(PinStatus::Ready));
31 m.release(pin).unwrap();
32 assert_eq!(m.state(&k), ExpertState::Evictable);
33 let s = m.stats();
34 assert_eq!((s.misses, s.published, s.hits), (1, 1, 0));
35 assert_eq!((s.fetch_wait_ns_total, s.fetch_wait_ns_max), (250, 250));
36 assert_eq!(s.current_resident_bytes, SLOT);
37 assert_eq!(s.current_pins, 0);
38 m.check_invariants().unwrap();
39}
40
41#[test]
42fn published_without_pins_is_ready_not_evictable() {
43 let mut m = manager(2);
44 let k = id(1, 1);
45 let (pin, t) = fetch(m.acquire(k, SLOT, 0).unwrap());
46 m.release(pin).unwrap();
47 complete(&mut m, &t, 0);
48 assert_eq!(m.state(&k), ExpertState::Ready);
49}
50
51#[test]
52fn phase_steps_cannot_be_skipped_or_repeated() {
53 let mut m = manager(2);
54 let (pin, t) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap());
55 let slot = t.slot();
56 assert_eq!(
57 m.publish(&t, 0),
58 Err(Refusal::WrongPhase {
59 slot,
60 expected: Phase::Copying,
61 found: Phase::Fetching
62 })
63 );
64 assert!(matches!(
65 m.mark_copying(&t),
66 Err(Refusal::WrongPhase { .. })
67 ));
68 m.mark_verified(&t).unwrap();
69 assert!(matches!(
70 m.mark_verified(&t),
71 Err(Refusal::WrongPhase { .. })
72 ));
73 m.mark_copying(&t).unwrap();
74 m.publish(&t, 0).unwrap();
75 assert!(matches!(m.publish(&t, 0), Err(Refusal::WrongPhase { .. })));
76 // A published entry cannot be failed.
77 assert_eq!(
78 m.fail(&t, FailureCause::Read),
79 Err(Refusal::WrongPhase {
80 slot,
81 expected: Phase::Fetching,
82 found: Phase::Ready
83 })
84 );
85 m.release(pin).unwrap();
86 m.check_invariants().unwrap();
87}
88
89#[test]
90fn hit_and_join_counters() {
91 let mut m = manager(2);
92 let k = id(3, 9);
93 let (p1, t) = fetch(m.acquire(k, SLOT, 0).unwrap());
94 let p2 = match m.acquire(k, SLOT, 0).unwrap() {
95 Acquired::Pending(p) => p,
96 other => panic!("{other:?}"),
97 };
98 complete(&mut m, &t, 0);
99 let p3 = match m.acquire(k, SLOT, 0).unwrap() {
100 Acquired::Ready(p) => p,
101 other => panic!("{other:?}"),
102 };
103 let s = m.stats();
104 assert_eq!((s.misses, s.joined, s.hits, s.current_pins), (1, 1, 1, 3));
105 for p in [p1, p2, p3] {
106 m.release(p).unwrap();
107 }
108 m.check_invariants().unwrap();
109}
110
111#[test]
112fn eviction_is_lru_and_deterministic() {
113 let run = || {
114 let mut m = manager(3);
115 for e in 0..3 {
116 touch(&mut m, id(0, e));
117 }
118 // Use order now 0,1,2. Touch 0 so 1 is the oldest.
119 touch(&mut m, id(0, 0));
120 let mut order = Vec::new();
121 for e in 10..14 {
122 let victim = m.next_victim().unwrap();
123 let before: Vec<_> = (0..20)
124 .filter(|&x| m.state(&id(0, x)) != ExpertState::Absent)
125 .collect();
126 touch(&mut m, id(0, e));
127 let after: Vec<_> = (0..20)
128 .filter(|&x| m.state(&id(0, x)) != ExpertState::Absent)
129 .collect();
130 let gone: Vec<_> = before
131 .iter()
132 .filter(|x| !after.contains(x))
133 .copied()
134 .collect();
135 order.push((victim, gone));
136 }
137 m.check_invariants().unwrap();
138 (order, m.stats())
139 };
140 let (order, stats) = run();
141 let gone: Vec<u32> = order.iter().flat_map(|(_, g)| g.clone()).collect();
142 assert_eq!(gone, vec![1, 2, 0, 10]);
143 assert_eq!(stats.evictions, 4);
144 assert_eq!(run(), (order, stats), "same calls, same order");
145}
146
147#[test]
148fn pinned_entry_is_never_evicted() {
149 let mut m = manager(2);
150 let held = load(&mut m, id(0, 0)); // oldest, but pinned
151 touch(&mut m, id(0, 1));
152 for e in 2..50 {
153 touch(&mut m, id(1, e));
154 assert_eq!(m.state(&id(0, 0)), ExpertState::InUse);
155 assert_eq!(m.poll(&held), Ok(PinStatus::Ready));
156 }
157 m.release(held).unwrap();
158 touch(&mut m, id(2, 0));
159 touch(&mut m, id(2, 1));
160 assert_eq!(m.state(&id(0, 0)), ExpertState::Absent);
161 m.check_invariants().unwrap();
162}
163
164#[test]
165fn pinned_exhaustion_is_refused_without_side_effects() {
166 let mut m = manager(2);
167 let a = load(&mut m, id(0, 0));
168 let (b, tb) = fetch(m.acquire(id(0, 1), SLOT, 0).unwrap()); // in flight
169 let before = m.stats();
170 let r = m.acquire(id(0, 2), SLOT, 0);
171 assert_eq!(
172 r,
173 Err(Refusal::PinnedExhaustion {
174 slots: 2,
175 pinned: 2,
176 in_flight: 1
177 })
178 );
179 let after = m.stats();
180 assert_eq!(after.refusals, before.refusals + 1);
181 assert_eq!(after.evictions, before.evictions);
182 assert_eq!(m.state(&id(0, 2)), ExpertState::Absent);
183 // An in-flight entry with no pins is not evictable either.
184 m.release(b).unwrap();
185 assert!(matches!(
186 m.acquire(id(0, 2), SLOT, 0),
187 Err(Refusal::PinnedExhaustion {
188 pinned: 1,
189 in_flight: 1,
190 ..
191 })
192 ));
193 complete(&mut m, &tb, 0);
194 // Now id(0,1) is Ready and unpinned: it is the victim.
195 let (p, t) = fetch(m.acquire(id(0, 2), SLOT, 0).unwrap());
196 assert_eq!(m.state(&id(0, 1)), ExpertState::Absent);
197 complete(&mut m, &t, 0);
198 m.release(p).unwrap();
199 m.release(a).unwrap();
200 m.check_invariants().unwrap();
201}
202
203#[test]
204fn refused_miss_does_not_evict() {
205 let mut m = manager(1);
206 touch(&mut m, id(0, 0));
207 assert_eq!(
208 m.acquire(id(0, 1), SLOT + 1, 0),
209 Err(Refusal::ObjectTooLarge {
210 bytes: SLOT + 1,
211 slot_bytes: SLOT
212 })
213 );
214 assert_eq!(m.acquire(id(0, 1), 0, 0), Err(Refusal::ZeroSizedObject));
215 assert_eq!(m.state(&id(0, 0)), ExpertState::Evictable);
216 assert_eq!(m.stats().evictions, 0);
217}
218
219#[test]
220fn size_mismatch_is_refused() {
221 let mut m = manager(2);
222 touch(&mut m, id(0, 0));
223 assert_eq!(
224 m.acquire(id(0, 0), SLOT - 1, 0),
225 Err(Refusal::SizeMismatch {
226 admitted: SLOT,
227 requested: SLOT - 1
228 })
229 );
230 assert_eq!(m.stats().current_pins, 0);
231}
232
233#[test]
234fn backpressure_by_count_and_bytes() {
235 let mut m = ResidencyManager::new(config(8, 2, 3 * SLOT)).unwrap();
236 let (p1, t1) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap());
237 let (p2, t2) = fetch(m.acquire(id(0, 1), SLOT, 0).unwrap());
238 assert_eq!(
239 m.acquire(id(0, 2), SLOT, 0),
240 Err(Refusal::InFlightLimit { limit: 2 })
241 );
242 // Joining an in-flight fetch is not a new fetch: allowed.
243 let j = m.acquire(id(0, 0), SLOT, 0).unwrap();
244 complete(&mut m, &t1, 0);
245 assert_eq!(m.stats().current_in_flight, 1);
246
247 let mut m2 = ResidencyManager::new(config(8, 4, 2 * SLOT)).unwrap();
248 let (q1, s1) = fetch(m2.acquire(id(0, 0), SLOT, 0).unwrap());
249 let (q2, s2) = fetch(m2.acquire(id(0, 1), SLOT / 2, 0).unwrap());
250 assert_eq!(
251 m2.acquire(id(0, 2), SLOT, 0),
252 Err(Refusal::InFlightBytesLimit {
253 in_flight_bytes: SLOT + SLOT / 2,
254 requested: SLOT,
255 limit: 2 * SLOT
256 })
257 );
258 m2.fail(&s2, FailureCause::Cancelled).unwrap();
259 let (q3, s3) = fetch(m2.acquire(id(0, 2), SLOT, 0).unwrap());
260 for t in [&s1, &s3] {
261 complete(&mut m2, t, 0);
262 }
263 assert_eq!(m2.stats().peak_in_flight_bytes, 2 * SLOT);
264 for p in [q1, q2, q3] {
265 m2.release(p).unwrap();
266 }
267 complete(&mut m, &t2, 0);
268 for p in [p1, p2, j.pin_owned()] {
269 m.release(p).unwrap();
270 }
271 m.check_invariants().unwrap();
272 m2.check_invariants().unwrap();
273}
274
275trait PinOwned {
276 fn pin_owned(self) -> Pin;
277}
278impl PinOwned for Acquired {
279 fn pin_owned(self) -> Pin {
280 match self {
281 Acquired::Ready(p) | Acquired::Pending(p) | Acquired::Fetch(p, _) => p,
282 }
283 }
284}
285
286#[test]
287fn simultaneous_readers_hold_until_last_release() {
288 let mut m = manager(1);
289 let k = id(4, 4);
290 let readers: Vec<Pin> = (0..5).map(|_| load(&mut m, k)).collect();
291 assert_eq!(m.stats().current_pins, 5);
292 let mut readers = readers.into_iter();
293 for p in readers.by_ref().take(4) {
294 m.release(p).unwrap();
295 assert!(matches!(
296 m.acquire(id(5, 5), SLOT, 0),
297 Err(Refusal::PinnedExhaustion { .. })
298 ));
299 }
300 m.release(readers.next().unwrap()).unwrap();
301 touch(&mut m, id(5, 5));
302 assert_eq!(m.state(&k), ExpertState::Absent);
303 m.check_invariants().unwrap();
304}
305
306#[test]
307fn layer_crossing_and_part_identities_are_distinct() {
308 let mut m = manager(8);
309 let a = id(0, 7);
310 let b = id(1, 7);
311 let mut c = id(0, 7);
312 c.part = ExpertPart::GateUp;
313 let mut d = id(0, 7);
314 d.checkpoint_digest = [8; 32];
315 for k in [a, b, c, d] {
316 touch(&mut m, k);
317 }
318 assert_eq!(m.stats().misses, 4);
319 let slots: std::collections::BTreeSet<_> = [a, b, c, d]
320 .iter()
321 .map(|k| m.slot_of(k).unwrap().0)
322 .collect();
323 assert_eq!(slots.len(), 4);
324 touch(&mut m, a);
325 assert_eq!(m.stats().hits, 1);
326}
327
328#[test]
329fn aba_slot_reuse_refuses_stale_pin_and_ticket() {
330 let mut m = manager(1);
331 let (old_pin, old_t) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap());
332 let (slot, g1) = (old_t.slot(), old_t.generation());
333 complete(&mut m, &old_t, 0);
334 m.release(old_pin).unwrap();
335 // Reuse the same slot for another key.
336 let (new_pin, new_t) = fetch(m.acquire(id(9, 9), SLOT, 0).unwrap());
337 assert_eq!(new_t.slot(), slot);
338 assert!(new_t.generation() > g1);
339 assert_eq!(
340 m.mark_verified(&old_t),
341 Err(Refusal::StaleTicket {
342 slot,
343 generation: g1
344 })
345 );
346 assert_eq!(
347 m.fail(&old_t, FailureCause::Read),
348 Err(Refusal::StaleTicket {
349 slot,
350 generation: g1
351 })
352 );
353 // Same slot, re-admitted under the original key: still a new generation.
354 complete(&mut m, &new_t, 0);
355 m.release(new_pin).unwrap();
356 let (p3, t3) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap());
357 assert_eq!(t3.slot(), slot);
358 assert!(t3.generation() > new_t.generation());
359 assert!(matches!(
360 m.publish(&new_t, 0),
361 Err(Refusal::StaleTicket { .. })
362 ));
363 m.fail(&t3, FailureCause::Cancelled).unwrap();
364 assert!(matches!(m.poll(&p3), Err(Refusal::FetchFailed { .. })));
365 m.release(p3).unwrap();
366 m.check_invariants().unwrap();
367}
368
369#[test]
370fn failure_with_waiters_is_explicit_and_recoverable() {
371 let mut m = manager(2);
372 let k = id(2, 3);
373 let (p1, t) = fetch(m.acquire(k, SLOT, 0).unwrap());
374 let p2 = m.acquire(k, SLOT, 0).unwrap().pin_owned();
375 m.mark_verified(&t).unwrap();
376 m.fail(&t, FailureCause::DigestMismatch).unwrap();
377 let failed = Err(Refusal::FetchFailed {
378 slot: t.slot(),
379 generation: t.generation(),
380 cause: FailureCause::DigestMismatch,
381 });
382 assert_eq!(m.poll(&p1), failed);
383 assert_eq!(m.poll(&p2), failed);
384 // The key is unmapped at once: a retry is a clean miss in another slot.
385 assert_eq!(m.state(&k), ExpertState::Absent);
386 let (p3, t3) = fetch(m.acquire(k, SLOT, 0).unwrap());
387 assert_ne!(t3.slot(), t.slot());
388 // Failed slot is held for its waiters, so a third key has no room.
389 assert!(matches!(
390 m.acquire(id(7, 7), SLOT, 0),
391 Err(Refusal::PinnedExhaustion { .. })
392 ));
393 m.release(p1).unwrap();
394 m.release(p2).unwrap();
395 complete(&mut m, &t3, 0);
396 m.release(p3).unwrap();
397 touch(&mut m, id(7, 7));
398 let s = m.stats();
399 assert_eq!((s.failures, s.published), (1, 2));
400 assert_eq!(s.current_in_flight, 0);
401 m.check_invariants().unwrap();
402}
403
404#[test]
405fn failure_without_pins_frees_the_slot_at_once() {
406 let mut m = manager(1);
407 let (p, t) = fetch(m.acquire(id(0, 0), SLOT, 0).unwrap());
408 m.release(p).unwrap();
409 m.mark_verified(&t).unwrap();
410 m.mark_copying(&t).unwrap();
411 m.fail(&t, FailureCause::GpuFence).unwrap();
412 touch(&mut m, id(0, 1));
413 assert_eq!(m.stats().evictions, 0);
414 m.check_invariants().unwrap();
415}
416
417#[test]
418fn acquire_all_is_all_or_nothing() {
419 let mut m = manager(3);
420 touch(&mut m, id(0, 0));
421 let held = load(&mut m, id(0, 1));
422 // Request needs 3 distinct new keys plus a repeat; only 2 slots usable.
423 let req = [
424 (id(0, 1), SLOT),
425 (id(1, 0), SLOT),
426 (id(1, 0), SLOT),
427 (id(1, 1), SLOT),
428 (id(1, 2), SLOT),
429 ];
430 let before_pins = m.stats().current_pins;
431 let r = m.acquire_all(&req, 0);
432 assert!(matches!(r, Err(Refusal::PinnedExhaustion { .. })), "{r:?}");
433 let s = m.stats();
434 assert_eq!(s.current_pins, before_pins);
435 assert_eq!(s.current_in_flight, 0);
436 assert_eq!(s.rolled_back, 2);
437 assert_eq!(m.state(&id(1, 0)), ExpertState::Absent);
438 assert_eq!(m.state(&id(1, 1)), ExpertState::Absent);
439 assert_eq!(m.state(&id(0, 1)), ExpertState::InUse);
440 m.check_invariants().unwrap();
441
442 // A request that fits: all pinned, duplicates share one fetch.
443 let ok = m
444 .acquire_all(&[(id(0, 1), SLOT), (id(2, 0), SLOT), (id(2, 0), SLOT)], 0)
445 .unwrap();
446 assert!(matches!(ok[0], Acquired::Ready(_)));
447 assert!(matches!(ok[1], Acquired::Fetch(..)));
448 assert!(matches!(ok[2], Acquired::Pending(_)));
449 let mut pins = Vec::new();
450 for a in ok {
451 match a {
452 Acquired::Fetch(p, t) => {
453 complete(&mut m, &t, 0);
454 pins.push(p);
455 }
456 other => pins.push(other.pin_owned()),
457 }
458 }
459 for p in pins {
460 m.release(p).unwrap();
461 }
462 m.release(held).unwrap();
463 m.check_invariants().unwrap();
464}
465
466/// Random operation sequences against small caches. After every operation:
467/// internal invariants hold, every live pin still resolves to its own slot
468/// generation (so a pinned entry was never evicted or reused), and refusals
469/// leave pins untouched. The whole trace is reproduced exactly by a second
470/// run with the same seed.
471fn random_run(seed: u64, slots: u32, steps: usize) -> (Vec<String>, Stats) {
472 let mut m = ResidencyManager::<ExpertIdentity>::new(config(slots, 3, 3 * SLOT)).unwrap();
473 let mut rng = Rng(seed);
474 let mut pins: Vec<(ExpertIdentity, Pin)> = Vec::new();
475 let mut tickets: Vec<aien_expert_residency::FetchTicket> = Vec::new();
476 let mut trace = Vec::with_capacity(steps);
477 for step in 0..steps {
478 let op = rng.below(10);
479 let line = match op {
480 0..=3 => {
481 let k = id(rng.below(3) as u32, rng.below(6) as u32);
482 let predicted = m.next_victim();
483 let evictions = m.stats().evictions;
484 match m.acquire(k, SLOT, step as u64) {
485 Ok(Acquired::Fetch(p, t)) => {
486 if m.stats().evictions > evictions {
487 assert_eq!(
488 Some(t.slot()),
489 predicted,
490 "seed {seed} step {step}: not the LRU victim"
491 );
492 }
493 let s = format!("miss {k:?} -> {}", t.slot());
494 pins.push((k, p));
495 tickets.push(t);
496 s
497 }
498 Ok(a) => {
499 let s = format!("acq {a:?}");
500 pins.push((k, a.pin_owned()));
501 s
502 }
503 Err(r) => format!("refused {r:?}"),
504 }
505 }
506 4..=6 if !tickets.is_empty() => {
507 let i = rng.below(tickets.len() as u64) as usize;
508 let t = &tickets[i];
509 let r = match rng.below(4) {
510 0 => m.mark_verified(t),
511 1 => m.mark_copying(t),
512 2 => m.publish(t, step as u64),
513 _ => {
514 if rng.below(4) == 0 {
515 m.fail(t, FailureCause::Read)
516 } else {
517 m.publish(t, step as u64)
518 }
519 }
520 };
521 let s = format!("step {} {r:?}", t.slot());
522 let done = !matches!(
523 m.ticket_phase(t),
524 Ok(Phase::Fetching | Phase::Verified | Phase::Copying)
525 );
526 if done {
527 let _finished = tickets.swap_remove(i);
528 }
529 s
530 }
531 _ if !pins.is_empty() => {
532 let i = rng.below(pins.len() as u64) as usize;
533 let (k, p) = pins.swap_remove(i);
534 format!("rel {k:?} {:?}", m.release(p))
535 }
536 _ => "noop".into(),
537 };
538 m.check_invariants()
539 .unwrap_or_else(|e| panic!("seed {seed} step {step} {line}: {e}"));
540 for (k, p) in &pins {
541 match m.poll(p) {
542 Ok(_) => {
543 let (slot, g) = m.slot_of(k).expect("pinned key must stay admitted");
544 assert_eq!(
545 (slot, g),
546 (p.slot(), p.generation()),
547 "seed {seed} step {step}"
548 );
549 }
550 Err(Refusal::FetchFailed { .. }) => {}
551 Err(e) => panic!("seed {seed} step {step}: live pin refused {e:?}"),
552 }
553 }
554 trace.push(line);
555 }
556 let stats = m.stats();
557 // Drain: every remaining ticket is still in flight; fail it, then
558 // release every pin. The cache must be fully evictable again.
559 for t in tickets.drain(..) {
560 m.fail(&t, FailureCause::Cancelled).unwrap();
561 }
562 for (_, p) in pins.drain(..) {
563 m.release(p).unwrap();
564 }
565 m.check_invariants().unwrap();
566 assert_eq!(m.stats().current_pins, 0);
567 assert_eq!(m.stats().current_in_flight, 0);
568 (trace, stats)
569}
570
571#[test]
572fn property_random_sequences_hold_invariants() {
573 let mut total = Stats::default();
574 for seed in 1..=40u64 {
575 for slots in [1u32, 2, 3, 5] {
576 let (_, s) = random_run(seed * 0x1000_0001 + u64::from(slots), slots, 400);
577 total.hits += s.hits;
578 total.joined += s.joined;
579 total.evictions += s.evictions;
580 total.failures += s.failures;
581 total.refusals += s.refusals;
582 total.published += s.published;
583 }
584 }
585 // The generator must actually reach every interesting path.
586 eprintln!("property totals: {total:?}");
587 assert!(
588 total.hits > 0
589 && total.joined > 0
590 && total.evictions > 0
591 && total.failures > 0
592 && total.refusals > 0
593 && total.published > 0,
594 "{total:?}"
595 );
596}
597
598#[test]
599fn property_traces_are_deterministic() {
600 for seed in [3u64, 99, 12345] {
601 assert_eq!(random_run(seed, 3, 600), random_run(seed, 3, 600));
602 }
603}