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-campaign-verifier / src / kv.rs

618 lines · 20005 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//! KV conservation: rebuild allocator state from the mutation journal and compare it with the
17//! raw census and with AIEN's reported counters (SPEC.md Section 7).
18//!
19//! Gate 4 adds prefix-lease events; lease references then count toward `refcount(block)`.
20
21use crate::ids::SequenceId;
22use serde::{Deserialize, Serialize};
23use std::collections::{BTreeMap, BTreeSet};
24
25pub type BlockId = u32;
26
27/// One line of `kv_allocations.jsonl`.
28#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
29#[serde(tag = "event", rename_all = "snake_case")]
30pub enum KvEvent {
31 SequenceAllocated {
32 seq: SequenceId,
33 blocks: Vec<BlockId>,
34 },
35 Forked {
36 parent: SequenceId,
37 child: SequenceId,
38 },
39 BlockAppended {
40 seq: SequenceId,
41 block: BlockId,
42 },
43 CowFault {
44 seq: SequenceId,
45 index: usize,
46 old_block: BlockId,
47 new_block: BlockId,
48 },
49 /// Logged at dispatch with the resolved target block (SPEC.md invariant I2).
50 BlockWrite {
51 seq: SequenceId,
52 block: BlockId,
53 },
54 Released {
55 seq: SequenceId,
56 },
57}
58
59/// Allocator state as reconstructed by the verifier. Blocks absent from `refcounts` are free.
60#[derive(Debug, Clone, Default, PartialEq, Eq)]
61pub struct KvState {
62 pub pool_total: u32,
63 pub refcounts: BTreeMap<BlockId, u32>,
64 pub tables: BTreeMap<SequenceId, Vec<BlockId>>,
65 pub cow_faults: u64,
66}
67
68impl KvState {
69 pub fn new(pool_total: u32) -> Self {
70 Self {
71 pool_total,
72 ..Default::default()
73 }
74 }
75
76 fn take_free(&mut self, block: BlockId, at: usize, violations: &mut Vec<String>) -> bool {
77 if block >= self.pool_total {
78 violations.push(format!(
79 "event {at}: block {block} outside pool of {}",
80 self.pool_total
81 ));
82 return false;
83 }
84 if self.refcounts.contains_key(&block) {
85 violations.push(format!(
86 "event {at}: block {block} allocated while still referenced"
87 ));
88 return false;
89 }
90 self.refcounts.insert(block, 1);
91 true
92 }
93
94 fn decref(&mut self, block: BlockId, at: usize, violations: &mut Vec<String>) {
95 let Some(rc) = self.refcounts.get(&block).copied() else {
96 violations.push(format!("event {at}: refcount underflow on block {block}"));
97 return;
98 };
99 if rc > 1 {
100 self.refcounts.insert(block, rc - 1);
101 } else {
102 self.refcounts.remove(&block);
103 }
104 }
105}
106
107/// Replays the journal. Invalid events are reported and not applied, so one defect does not
108/// cascade into unrelated violations.
109pub fn replay(pool_total: u32, events: &[KvEvent]) -> (KvState, Vec<String>) {
110 let mut s = KvState::new(pool_total);
111 let mut v = Vec::new();
112
113 for (at, event) in events.iter().enumerate() {
114 match event {
115 KvEvent::SequenceAllocated { seq, blocks } => {
116 if s.tables.contains_key(seq) {
117 v.push(format!("event {at}: sequence {seq} allocated while live"));
118 continue;
119 }
120 let mut table = Vec::with_capacity(blocks.len());
121 for &b in blocks {
122 if s.take_free(b, at, &mut v) {
123 table.push(b);
124 }
125 }
126 s.tables.insert(*seq, table);
127 }
128 KvEvent::Forked { parent, child } => {
129 if s.tables.contains_key(child) {
130 v.push(format!("event {at}: fork into existing sequence {child}"));
131 continue;
132 }
133 let Some(table) = s.tables.get(parent).cloned() else {
134 v.push(format!("event {at}: fork from unknown parent {parent}"));
135 continue;
136 };
137 for &b in &table {
138 *s.refcounts.entry(b).or_insert(0) += 1;
139 }
140 s.tables.insert(*child, table);
141 }
142 KvEvent::BlockAppended { seq, block } => {
143 if !s.tables.contains_key(seq) {
144 v.push(format!("event {at}: append to unknown sequence {seq}"));
145 continue;
146 }
147 if s.take_free(*block, at, &mut v) {
148 if let Some(t) = s.tables.get_mut(seq) {
149 t.push(*block);
150 }
151 }
152 }
153 KvEvent::CowFault {
154 seq,
155 index,
156 old_block,
157 new_block,
158 } => {
159 let current = s.tables.get(seq).and_then(|t| t.get(*index)).copied();
160 if current != Some(*old_block) {
161 v.push(format!(
162 "event {at}: COW on {seq} index {index} expected block {old_block}, table has {current:?}"
163 ));
164 continue;
165 }
166 if s.refcounts.get(old_block).copied().unwrap_or(0) < 2 {
167 v.push(format!(
168 "event {at}: COW copy of private block {old_block} by {seq}"
169 ));
170 }
171 if !s.take_free(*new_block, at, &mut v) {
172 continue;
173 }
174 s.decref(*old_block, at, &mut v);
175 if let Some(t) = s.tables.get_mut(seq) {
176 t[*index] = *new_block;
177 }
178 s.cow_faults += 1;
179 }
180 KvEvent::BlockWrite { seq, block } => {
181 let owns = s.tables.get(seq).is_some_and(|t| t.contains(block));
182 if !owns {
183 v.push(format!(
184 "event {at}: {seq} wrote block {block} it does not reference"
185 ));
186 continue;
187 }
188 let rc = s.refcounts.get(block).copied().unwrap_or(0);
189 if rc > 1 {
190 v.push(format!(
191 "event {at}: {seq} wrote shared block {block} (refcount {rc}) without COW"
192 ));
193 }
194 }
195 KvEvent::Released { seq } => {
196 let Some(table) = s.tables.remove(seq) else {
197 v.push(format!(
198 "event {at}: release of unknown or already released sequence {seq}"
199 ));
200 continue;
201 };
202 for b in table {
203 s.decref(b, at, &mut v);
204 }
205 }
206 }
207 }
208
209 (s, v)
210}
211
212#[derive(Debug, Clone, Deserialize)]
213pub struct CensusBlock {
214 pub block_id: BlockId,
215 pub ref_count: u32,
216}
217
218#[derive(Debug, Clone, Deserialize)]
219pub struct CensusSequence {
220 pub seq: SequenceId,
221 pub block_ids: Vec<BlockId>,
222}
223
224/// `kv_census.json`: raw allocator state dumped at the end of a run.
225#[derive(Debug, Clone, Deserialize)]
226pub struct KvCensus {
227 pub pool_total: u32,
228 pub free_blocks: Vec<BlockId>,
229 pub blocks: Vec<CensusBlock>,
230 pub sequences: Vec<CensusSequence>,
231}
232
233/// `kv_metrics.json`: AIEN's own `KvMetrics`. Unknown fields are ignored.
234#[derive(Debug, Clone, Deserialize)]
235pub struct ReportedKvMetrics {
236 pub physical_pages: usize,
237 pub logical_pages: usize,
238 pub shared_pages: usize,
239 pub private_pages: usize,
240 pub cow_faults: usize,
241 pub used_blocks: usize,
242}
243
244/// Conservation equations evaluated on the census alone.
245pub fn check_census_conservation(c: &KvCensus) -> Vec<String> {
246 let mut v = Vec::new();
247
248 let mut free = BTreeSet::new();
249 for &b in &c.free_blocks {
250 if b >= c.pool_total {
251 v.push(format!("free block {b} outside pool of {}", c.pool_total));
252 }
253 if !free.insert(b) {
254 v.push(format!("block {b} appears twice in the free set"));
255 }
256 }
257
258 let mut recorded = BTreeMap::new();
259 for blk in c.blocks.iter().filter(|b| b.ref_count > 0) {
260 if recorded.insert(blk.block_id, blk.ref_count).is_some() {
261 v.push(format!("block {} has two census entries", blk.block_id));
262 }
263 }
264
265 let mut live = BTreeSet::new();
266 let mut referenced: BTreeMap<BlockId, u32> = BTreeMap::new();
267 for s in &c.sequences {
268 if !live.insert(s.seq) {
269 v.push(format!("duplicate live sequence {}", s.seq));
270 }
271 for &b in &s.block_ids {
272 *referenced.entry(b).or_insert(0) += 1;
273 }
274 }
275
276 if recorded.len() + free.len() != c.pool_total as usize {
277 v.push(format!(
278 "allocated {} + free {} != pool_total {}",
279 recorded.len(),
280 free.len(),
281 c.pool_total
282 ));
283 }
284 for b in referenced.keys() {
285 if free.contains(b) {
286 v.push(format!("referenced block {b} is in the free set"));
287 } else if !recorded.contains_key(b) {
288 v.push(format!("referenced block {b} has no refcount"));
289 }
290 }
291 for (b, rc) in &recorded {
292 let refs = referenced.get(b).copied().unwrap_or(0);
293 if refs == 0 {
294 v.push(format!("unreferenced block {b} is outside the free set"));
295 } else if refs != *rc {
296 v.push(format!(
297 "block {b}: refcount {rc} but {refs} table references"
298 ));
299 }
300 }
301
302 v
303}
304
305/// Journal replay must equal the raw census.
306pub fn check_replay_matches_census(r: &KvState, c: &KvCensus) -> Vec<String> {
307 let mut v = Vec::new();
308
309 if r.pool_total != c.pool_total {
310 v.push(format!(
311 "pool_total: contract {} vs census {}",
312 r.pool_total, c.pool_total
313 ));
314 }
315
316 let census_tables: BTreeMap<SequenceId, &Vec<BlockId>> =
317 c.sequences.iter().map(|s| (s.seq, &s.block_ids)).collect();
318 for (seq, table) in &r.tables {
319 match census_tables.get(seq) {
320 None => v.push(format!(
321 "sequence {seq} live in journal replay, absent from census"
322 )),
323 Some(t) if *t != table => v.push(format!(
324 "sequence {seq} block table differs: replay {table:?}, census {t:?}"
325 )),
326 Some(_) => {}
327 }
328 }
329 for seq in census_tables.keys() {
330 if !r.tables.contains_key(seq) {
331 v.push(format!(
332 "sequence {seq} live in census, absent from journal replay"
333 ));
334 }
335 }
336
337 let census_refs: BTreeMap<BlockId, u32> = c
338 .blocks
339 .iter()
340 .filter(|b| b.ref_count > 0)
341 .map(|b| (b.block_id, b.ref_count))
342 .collect();
343 let keys: BTreeSet<BlockId> = census_refs
344 .keys()
345 .chain(r.refcounts.keys())
346 .copied()
347 .collect();
348 for b in keys {
349 let replayed = r.refcounts.get(&b).copied().unwrap_or(0);
350 let census = census_refs.get(&b).copied().unwrap_or(0);
351 if replayed != census {
352 v.push(format!(
353 "block {b}: replay refcount {replayed}, census refcount {census}"
354 ));
355 }
356 }
357
358 let census_free: BTreeSet<BlockId> = c.free_blocks.iter().copied().collect();
359 let replay_free: BTreeSet<BlockId> = (0..r.pool_total)
360 .filter(|b| !r.refcounts.contains_key(b))
361 .collect();
362 for b in replay_free.difference(&census_free) {
363 v.push(format!("block {b} free in replay, not free in census"));
364 }
365 for b in census_free.difference(&replay_free) {
366 v.push(format!("block {b} free in census, not free in replay"));
367 }
368
369 v
370}
371
372/// Journal replay must equal AIEN's reported counters.
373pub fn check_replay_matches_metrics(r: &KvState, m: &ReportedKvMetrics) -> Vec<String> {
374 let physical = r.refcounts.len();
375 let logical: usize = r.tables.values().map(Vec::len).sum();
376 let shared = r.refcounts.values().filter(|&&rc| rc > 1).count();
377 let private = r.refcounts.values().filter(|&&rc| rc == 1).count();
378
379 let pairs = [
380 ("physical_pages", physical, m.physical_pages),
381 ("used_blocks", physical, m.used_blocks),
382 ("logical_pages", logical, m.logical_pages),
383 ("shared_pages", shared, m.shared_pages),
384 ("private_pages", private, m.private_pages),
385 ("cow_faults", r.cow_faults as usize, m.cow_faults),
386 ];
387 pairs
388 .iter()
389 .filter(|(_, replayed, reported)| replayed != reported)
390 .map(|(name, replayed, reported)| format!("{name}: replay {replayed}, reported {reported}"))
391 .collect()
392}
393
394#[cfg(test)]
395mod tests {
396 use super::*;
397
398 fn sid(slot: u32) -> SequenceId {
399 SequenceId {
400 boot_epoch: 1,
401 slot,
402 generation: 1,
403 }
404 }
405
406 fn census_of(s: &KvState) -> KvCensus {
407 KvCensus {
408 pool_total: s.pool_total,
409 free_blocks: (0..s.pool_total)
410 .filter(|b| !s.refcounts.contains_key(b))
411 .collect(),
412 blocks: s
413 .refcounts
414 .iter()
415 .map(|(&block_id, &ref_count)| CensusBlock {
416 block_id,
417 ref_count,
418 })
419 .collect(),
420 sequences: s
421 .tables
422 .iter()
423 .map(|(&seq, t)| CensusSequence {
424 seq,
425 block_ids: t.clone(),
426 })
427 .collect(),
428 }
429 }
430
431 #[test]
432 fn fork_diverge_release_conserves() {
433 let (p, a, b) = (sid(0), sid(1), sid(2));
434 let events = vec![
435 KvEvent::SequenceAllocated {
436 seq: p,
437 blocks: vec![0, 1],
438 },
439 KvEvent::Forked {
440 parent: p,
441 child: a,
442 },
443 KvEvent::Forked {
444 parent: p,
445 child: b,
446 },
447 KvEvent::CowFault {
448 seq: a,
449 index: 1,
450 old_block: 1,
451 new_block: 2,
452 },
453 KvEvent::BlockWrite { seq: a, block: 2 },
454 ];
455 let (state, violations) = replay(8, &events);
456 assert!(violations.is_empty(), "{violations:?}");
457 assert_eq!(state.refcounts.get(&0), Some(&3));
458 assert_eq!(state.refcounts.get(&1), Some(&2));
459 assert_eq!(state.refcounts.get(&2), Some(&1));
460
461 let census = census_of(&state);
462 assert!(check_census_conservation(&census).is_empty());
463 assert!(check_replay_matches_census(&state, &census).is_empty());
464
465 let mut events = events;
466 events.extend([
467 KvEvent::Released { seq: a },
468 KvEvent::Released { seq: b },
469 KvEvent::Released { seq: p },
470 ]);
471 let (state, violations) = replay(8, &events);
472 assert!(violations.is_empty(), "{violations:?}");
473 assert!(state.refcounts.is_empty());
474 assert!(state.tables.is_empty());
475 }
476
477 #[test]
478 fn duplicate_fork_is_a_violation_and_changes_nothing() {
479 let (p, a) = (sid(0), sid(1));
480 let fork = KvEvent::Forked {
481 parent: p,
482 child: a,
483 };
484 let events = vec![
485 KvEvent::SequenceAllocated {
486 seq: p,
487 blocks: vec![0],
488 },
489 fork.clone(),
490 fork,
491 ];
492 let (state, violations) = replay(4, &events);
493 assert_eq!(violations.len(), 1);
494 assert!(violations[0].contains("fork into existing sequence"));
495 assert_eq!(state.refcounts.get(&0), Some(&2));
496 }
497
498 #[test]
499 fn double_release_is_a_violation_without_underflow() {
500 let p = sid(0);
501 let events = vec![
502 KvEvent::SequenceAllocated {
503 seq: p,
504 blocks: vec![0],
505 },
506 KvEvent::Released { seq: p },
507 KvEvent::Released { seq: p },
508 ];
509 let (state, violations) = replay(4, &events);
510 assert_eq!(violations.len(), 1);
511 assert!(violations[0].contains("already released"));
512 assert!(state.refcounts.is_empty());
513 }
514
515 #[test]
516 fn write_to_shared_block_is_an_isolation_violation() {
517 let (p, a) = (sid(0), sid(1));
518 let events = vec![
519 KvEvent::SequenceAllocated {
520 seq: p,
521 blocks: vec![0],
522 },
523 KvEvent::Forked {
524 parent: p,
525 child: a,
526 },
527 KvEvent::BlockWrite { seq: a, block: 0 },
528 ];
529 let (_, violations) = replay(4, &events);
530 assert_eq!(violations.len(), 1);
531 assert!(violations[0].contains("without COW"));
532 }
533
534 #[test]
535 fn cow_of_private_block_is_flagged() {
536 let p = sid(0);
537 let events = vec![
538 KvEvent::SequenceAllocated {
539 seq: p,
540 blocks: vec![0],
541 },
542 KvEvent::CowFault {
543 seq: p,
544 index: 0,
545 old_block: 0,
546 new_block: 1,
547 },
548 ];
549 let (_, violations) = replay(4, &events);
550 assert!(violations.iter().any(|v| v.contains("private block")));
551 }
552
553 #[test]
554 fn journal_omitting_a_release_disagrees_with_census() {
555 let p = sid(0);
556 let journal = vec![KvEvent::SequenceAllocated {
557 seq: p,
558 blocks: vec![0, 1],
559 }];
560 let (state, _) = replay(4, &journal);
561 // The allocator actually released p, but the journal never logged it.
562 let census = census_of(&KvState::new(4));
563 let violations = check_replay_matches_census(&state, &census);
564 assert!(violations.iter().any(|v| v.contains("absent from census")));
565 }
566
567 #[test]
568 fn referenced_block_in_free_set_breaks_conservation() {
569 let p = sid(0);
570 let (state, _) = replay(
571 4,
572 &[KvEvent::SequenceAllocated {
573 seq: p,
574 blocks: vec![0],
575 }],
576 );
577 let mut census = census_of(&state);
578 census.free_blocks.push(0);
579 let violations = check_census_conservation(&census);
580 assert!(violations
581 .iter()
582 .any(|v| v.contains("referenced block 0 is in the free set")));
583 }
584
585 #[test]
586 fn reported_metrics_must_match_replay() {
587 let (p, a) = (sid(0), sid(1));
588 let (state, _) = replay(
589 4,
590 &[
591 KvEvent::SequenceAllocated {
592 seq: p,
593 blocks: vec![0, 1],
594 },
595 KvEvent::Forked {
596 parent: p,
597 child: a,
598 },
599 ],
600 );
601 let honest = ReportedKvMetrics {
602 physical_pages: 2,
603 logical_pages: 4,
604 shared_pages: 2,
605 private_pages: 0,
606 cow_faults: 0,
607 used_blocks: 2,
608 };
609 assert!(check_replay_matches_metrics(&state, &honest).is_empty());
610
611 let buggy = ReportedKvMetrics {
612 shared_pages: 1,
613 private_pages: 1,
614 ..honest
615 };
616 assert_eq!(check_replay_matches_metrics(&state, &buggy).len(), 2);
617 }
618}