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-kv-store / tests / validate_tests.rs

364 lines · 11526 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//! `validate_record` refuses every corruption with the named error and without
17//! touching the heap (ADR 0003 section 1.4, CUTS C1 red test
18//! `validate_refuses_before_any_allocation`). This file is its own test binary
19//! so its counting global allocator sees only this binary.
20
21mod common;
22
23use aien_kv_store::{validate_record, ChunkHeader, KvError, RecordHeader};
24use common::*;
25use sha2::{Digest, Sha256};
26use std::alloc::{GlobalAlloc, Layout, System};
27use std::cell::Cell;
28
29struct CountingAlloc;
30
31thread_local! {
32 static ARMED: Cell<bool> = const { Cell::new(false) };
33 static COUNT: Cell<usize> = const { Cell::new(0) };
34}
35
36fn bump() {
37 ARMED.with(|a| {
38 if a.get() {
39 COUNT.with(|c| c.set(c.get() + 1));
40 }
41 });
42}
43
44unsafe impl GlobalAlloc for CountingAlloc {
45 unsafe fn alloc(&self, l: Layout) -> *mut u8 {
46 bump();
47 System.alloc(l)
48 }
49 unsafe fn dealloc(&self, p: *mut u8, l: Layout) {
50 System.dealloc(p, l)
51 }
52 unsafe fn alloc_zeroed(&self, l: Layout) -> *mut u8 {
53 bump();
54 System.alloc_zeroed(l)
55 }
56 unsafe fn realloc(&self, p: *mut u8, l: Layout, n: usize) -> *mut u8 {
57 bump();
58 System.realloc(p, l, n)
59 }
60}
61
62#[global_allocator]
63static A: CountingAlloc = CountingAlloc;
64
65/// Run `f` and return its result with the number of heap allocations it made.
66fn counted<T>(f: impl FnOnce() -> T) -> (T, usize) {
67 COUNT.with(|c| c.set(0));
68 ARMED.with(|a| a.set(true));
69 let out = f();
70 ARMED.with(|a| a.set(false));
71 (out, COUNT.with(|c| c.get()))
72}
73
74fn reseal(b: &mut [u8; 4096]) {
75 let d = Sha256::digest(&b[..224]);
76 b[224..256].copy_from_slice(&d);
77}
78
79fn put32(b: &mut [u8; 4096], off: usize, v: u32) {
80 b[off..off + 4].copy_from_slice(&v.to_le_bytes());
81}
82
83struct Fixture {
84 expect: ChunkHeader,
85 /// The 4096-byte header region.
86 bytes: [u8; 4096],
87 file_size: u64,
88 segment_bytes: u64,
89}
90
91fn fixture() -> Fixture {
92 let (rec, digests) = sample_record();
93 let bytes = rec.encode_region(&digests).unwrap();
94 Fixture {
95 expect: rec.chunk,
96 bytes,
97 file_size: 4096 + rec.chunk.payload_len,
98 segment_bytes: sample().segment_bytes(rec.chunk.token_count).unwrap(),
99 }
100}
101
102fn check(f: &Fixture) -> Result<RecordHeader, KvError> {
103 validate_record(&f.bytes, f.file_size, &f.expect, f.segment_bytes)
104}
105
106#[test]
107fn counter_detects_allocation() {
108 // Negative control: the harness would notice a heap use.
109 let (_, n) = counted(|| std::hint::black_box(Vec::<u8>::with_capacity(64)));
110 assert!(n >= 1, "counting allocator is not counting");
111}
112
113#[test]
114fn valid_record_passes_with_zero_allocations() {
115 let f = fixture();
116 let (r, n) = counted(|| check(&f));
117 assert_eq!(n, 0);
118 let r = r.expect("valid record");
119 assert_eq!(r.chunk, f.expect);
120 assert_eq!(r.payload_sha256, sample_record().0.payload_sha256);
121}
122
123#[test]
124fn validate_refuses_before_any_allocation() {
125 type Corrupt = (&'static str, KvError, fn(&mut Fixture));
126 let cases: Vec<Corrupt> = vec![
127 ("wrong magic", KvError::BadMagic, |f| f.bytes[0] = b'X'),
128 ("wrong version", KvError::UnsupportedVersion, |f| {
129 f.bytes[8] = 2;
130 reseal(&mut f.bytes);
131 }),
132 ("wrong header hash", KvError::HeaderChecksum, |f| {
133 f.bytes[230] ^= 1;
134 }),
135 ("wrong namespace", KvError::NamespaceMismatch, |f| {
136 f.bytes[16] ^= 1;
137 reseal(&mut f.bytes);
138 }),
139 ("wrong key", KvError::KeyMismatch, |f| {
140 f.bytes[48] ^= 1;
141 reseal(&mut f.bytes);
142 }),
143 ("wrong parent", KvError::ParentMismatch, |f| {
144 f.bytes[80] ^= 1;
145 reseal(&mut f.bytes);
146 }),
147 ("wrong position", KvError::PositionMismatch, |f| {
148 put32(&mut f.bytes, 144, 256);
149 reseal(&mut f.bytes);
150 }),
151 ("token_count 0", KvError::TokenCountOutOfRange, |f| {
152 put32(&mut f.bytes, 148, 0);
153 reseal(&mut f.bytes);
154 }),
155 (
156 "token_count over chunk_tokens",
157 KvError::TokenCountOutOfRange,
158 |f| {
159 put32(&mut f.bytes, 148, 257);
160 reseal(&mut f.bytes);
161 },
162 ),
163 ("wrong geometry", KvError::GeometryMismatch, |f| {
164 put32(&mut f.bytes, 164, 9); // num_kv_heads
165 reseal(&mut f.bytes);
166 }),
167 ("wrong payload_len", KvError::PayloadLenMismatch, |f| {
168 f.bytes[176] ^= 1;
169 reseal(&mut f.bytes);
170 }),
171 (
172 "file shorter than header+payload",
173 KvError::FileSizeMismatch,
174 |f| {
175 f.file_size -= 1;
176 },
177 ),
178 (
179 "file longer than header+payload",
180 KvError::FileSizeMismatch,
181 |f| {
182 f.file_size += 1;
183 },
184 ),
185 (
186 "nonzero byte at the end of the padding",
187 KvError::BadPadding,
188 |f| {
189 f.bytes[4063] = 1;
190 },
191 ),
192 (
193 "nonzero byte right after the digest table",
194 KvError::BadPadding,
195 |f| {
196 f.bytes[256 + 32 * 16] = 1;
197 },
198 ),
199 (
200 "segment digest flipped in the table",
201 KvError::SegmentRootMismatch,
202 |f| {
203 f.bytes[256] ^= 1;
204 },
205 ),
206 (
207 "root at offset 184 flipped",
208 KvError::SegmentRootMismatch,
209 |f| {
210 f.bytes[184] ^= 1;
211 reseal(&mut f.bytes);
212 },
213 ),
214 (
215 "121 segments of the derived size",
216 KvError::TooManySegments,
217 |f| {
218 f.segment_bytes = 69_905;
219 },
220 ),
221 (
222 "file size of the old 256-byte layout",
223 KvError::FileSizeMismatch,
224 |f| {
225 f.file_size = 256 + f.expect.payload_len;
226 },
227 ),
228 ("region cut short", KvError::Truncated, |_| {}),
229 ("truncated header", KvError::Truncated, |_| {}),
230 ];
231 assert!(cases.len() >= 19);
232 for (name, want, corrupt) in cases {
233 let mut f = fixture();
234 corrupt(&mut f);
235 let slice: &[u8] = match name {
236 "truncated header" => &f.bytes[..200],
237 "region cut short" => &f.bytes[..4095],
238 _ => &f.bytes,
239 };
240 let (got, allocs) =
241 counted(|| validate_record(slice, f.file_size, &f.expect, f.segment_bytes));
242 assert_eq!(got, Err(want), "{name}");
243 assert_eq!(allocs, 0, "{name}: validation allocated");
244 }
245}
246
247#[test]
248fn validation_reports_the_first_failure_in_adr_order() {
249 // Magic and namespace both wrong: magic wins.
250 let mut f = fixture();
251 f.bytes[0] = b'X';
252 f.bytes[16] ^= 1;
253 reseal(&mut f.bytes);
254 assert_eq!(check(&f), Err(KvError::BadMagic));
255 // Namespace and key both wrong (hash valid): namespace wins.
256 let mut f = fixture();
257 f.bytes[16] ^= 1;
258 f.bytes[48] ^= 1;
259 reseal(&mut f.bytes);
260 assert_eq!(check(&f), Err(KvError::NamespaceMismatch));
261}
262
263#[test]
264fn partial_flag_must_agree_with_token_count() {
265 // A header claiming partial_tail on a full chunk is refused.
266 let mut f = fixture();
267 f.bytes[174] = 1;
268 reseal(&mut f.bytes);
269 assert_eq!(check(&f), Err(KvError::BadFlags));
270 // A reserved flag bit is refused.
271 let mut f = fixture();
272 f.bytes[175] = 0x80;
273 reseal(&mut f.bytes);
274 assert_eq!(check(&f), Err(KvError::BadFlags));
275}
276
277#[test]
278fn file_size_is_4096_plus_payload() {
279 let f = fixture();
280 assert_eq!(f.file_size, 4096 + f.expect.payload_len);
281 assert!(check(&f).is_ok());
282 // The C1 layout (256-byte header) is refused.
283 let mut old = fixture();
284 old.file_size = 256 + old.expect.payload_len;
285 assert_eq!(check(&old), Err(KvError::FileSizeMismatch));
286}
287
288#[test]
289fn validate_refuses_nonzero_padding() {
290 // Every single byte outside the struct and the table must be zero.
291 let f0 = fixture();
292 let table_end = 256 + 32 * 16;
293 for off in [table_end, table_end + 1, 1000, 4062, 4063] {
294 let mut f = fixture();
295 f.bytes[off] = 0x01;
296 assert_eq!(check(&f), Err(KvError::BadPadding), "offset {off}");
297 }
298 // A nonzero digest byte inside the table is not padding.
299 let mut f = fixture();
300 f.bytes[table_end - 1] ^= 1;
301 assert_eq!(check(&f), Err(KvError::SegmentRootMismatch));
302 // The seal slot (4064..4096) is not padding: the seal module checks it.
303 for off in [4064, 4080, 4095] {
304 let mut f = fixture();
305 f.bytes[off] = 0x01;
306 assert!(check(&f).is_ok(), "seal slot offset {off}");
307 }
308 assert!(check(&f0).is_ok());
309}
310
311#[test]
312fn validate_refuses_segment_root_mismatch() {
313 // Swapping two digests keeps the multiset but changes the root.
314 let mut f = fixture();
315 let (a, b) = (256, 288);
316 let first: [u8; 32] = f.bytes[a..a + 32].try_into().unwrap();
317 let second: [u8; 32] = f.bytes[b..b + 32].try_into().unwrap();
318 f.bytes[a..a + 32].copy_from_slice(&second);
319 f.bytes[b..b + 32].copy_from_slice(&first);
320 assert_eq!(check(&f), Err(KvError::SegmentRootMismatch));
321 // A root that does not match the table (struct resealed) is refused too.
322 let mut f = fixture();
323 f.bytes[200] ^= 1;
324 reseal(&mut f.bytes);
325 assert_eq!(check(&f), Err(KvError::SegmentRootMismatch));
326}
327
328#[test]
329fn validate_refuses_more_than_119_segments() {
330 let f = fixture();
331 let n_at = |sb: u64| f.expect.payload_len.div_ceil(sb);
332 // 119 segments is the boundary (the table ends at the seal slot, 4064)
333 // and is accepted when the table is whole.
334 let sb119 = f.expect.payload_len.div_ceil(119);
335 assert_eq!(n_at(sb119), 119);
336 let digests = seg_digests("edge", 119);
337 let rec = RecordHeader {
338 chunk: f.expect,
339 payload_sha256: aien_kv_store::payload_root(&digests),
340 };
341 let edge = Fixture {
342 bytes: rec.encode_region(&digests).unwrap(),
343 segment_bytes: sb119,
344 expect: f.expect,
345 file_size: f.file_size,
346 };
347 assert!(check(&edge).is_ok(), "exactly 119 segments is valid");
348 // One more segment is refused before the table is read.
349 let sb120 = f.expect.payload_len.div_ceil(120);
350 assert_eq!(n_at(sb120), 120);
351 let over = Fixture {
352 segment_bytes: sb120,
353 ..edge
354 };
355 let (got, allocs) = counted(|| check(&over));
356 assert_eq!(got, Err(KvError::TooManySegments));
357 assert_eq!(allocs, 0);
358 // A zero segment size is a geometry error, not a panic.
359 let zero = Fixture {
360 segment_bytes: 0,
361 ..over
362 };
363 assert_eq!(check(&zero), Err(KvError::InvalidGeometry));
364}