interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-kernel / src / continuity_tests.rs

456 lines · 15484 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
16use super::*;
17use crate::store::engine::{MountState, ObjectInput, Store, StoreDevice};
18use crate::store::genesis::genesis_units;
19use crate::store::v1::STORE_UNIT_BYTES;
20use alloc::vec;
21
22const UUID: [u8; 16] = [0x5a; 16];
23const AGENT: [u8; 32] = [0x11; 32];
24
25#[derive(Clone)]
26struct Mem {
27 units: Vec<[u8; STORE_UNIT_BYTES]>,
28 /// Writes accepted before the device "loses power" (None = unlimited).
29 writes_left: Option<usize>,
30}
31
32impl StoreDevice for Mem {
33 type Error = ();
34 fn region_units(&self) -> u64 {
35 self.units.len() as u64
36 }
37 fn read_unit(
38 &mut self,
39 unit: u64,
40 out: &mut [u8; STORE_UNIT_BYTES],
41 ) -> core::result::Result<(), ()> {
42 *out = *self.units.get(unit as usize).ok_or(())?;
43 Ok(())
44 }
45 fn write_unit(
46 &mut self,
47 unit: u64,
48 bytes: &[u8; STORE_UNIT_BYTES],
49 ) -> core::result::Result<(), ()> {
50 if let Some(left) = self.writes_left.as_mut() {
51 if *left == 0 {
52 return Err(());
53 }
54 *left -= 1;
55 }
56 *self.units.get_mut(unit as usize).ok_or(())? = *bytes;
57 Ok(())
58 }
59 fn flush(&mut self) -> core::result::Result<(), ()> {
60 Ok(())
61 }
62}
63
64fn formatted() -> Mem {
65 let mut units = vec![[0u8; STORE_UNIT_BYTES]; 256];
66 for (i, u) in genesis_units(UUID, 256).iter().enumerate() {
67 units[i] = *u;
68 }
69 Mem {
70 units,
71 writes_left: None,
72 }
73}
74
75fn open(dev: Mem) -> Store<Mem> {
76 Store::open(dev).expect("store opens")
77}
78
79fn fact(text: &str) -> CortexRecord {
80 CortexRecord {
81 status: Epistemic::OperatorDecision,
82 evidence_hash: [0x42; 32],
83 statement: text.as_bytes().to_vec(),
84 }
85}
86
87fn provisioned() -> Store<Mem> {
88 let mut store = open(formatted());
89 provision(&mut store, AGENT, UUID, ProvisionSource::Qualification).unwrap();
90 store
91}
92
93/// Simulates a cold restart: drop everything in memory, reopen the medium.
94fn restart(store: Store<Mem>) -> Store<Mem> {
95 open(store.into_device())
96}
97
98#[test]
99fn unprovisioned_store_never_mints_an_identity() {
100 let mut store = open(formatted());
101 let generation = store.generation();
102 assert_eq!(resolve(&mut store), Err(ContinuityError::Unprovisioned));
103 assert_eq!(
104 resume(&mut store).map(|_| ()),
105 Err(ContinuityError::Unprovisioned)
106 );
107 assert_eq!(store.generation(), generation, "nothing was written");
108 assert!(store.catalog().entries.is_empty());
109}
110
111#[test]
112fn provision_then_cold_restart_returns_the_same_identity_and_memory() {
113 let mut store = provisioned();
114 let c1 = resolve(&mut store).unwrap();
115 assert_eq!(c1.root.agent_id, AGENT);
116 assert_eq!(c1.manifest.sequence, 1);
117 assert_eq!(c1.manifest.incarnation, 1);
118
119 // Commit memory and a branch fork.
120 let mut state = c1.state.clone();
121 let child = state.fork(&c1.root.root_branch).unwrap();
122 let c2 = commit(
123 &mut store,
124 &c1,
125 Update {
126 state: Some(state),
127 cortex: vec![fact("the operator's name is Drake"), fact("M4 is next")],
128 },
129 false,
130 )
131 .unwrap();
132 assert_eq!(c2.cortex.len(), 2);
133
134 // Cold restart: same identity, same memory, same lineage, incarnation + 1.
135 let mut store = restart(store);
136 let (c3, committed) = resume(&mut store).unwrap();
137 assert!(committed);
138 assert_eq!(c3.root_id, c1.root_id);
139 assert_eq!(c3.root.agent_id, AGENT);
140 assert_eq!(c3.manifest.incarnation, 2);
141 assert_eq!(c3.manifest.sequence, 3);
142 assert_eq!(c3.cortex, c2.cortex);
143 let branch = c3.state.branch(&child).expect("forked branch survived");
144 assert_eq!(branch.parent, Some(c1.root.root_branch));
145 assert_eq!(branch.depth, 1);
146
147 // A second restart advances only the incarnation.
148 let mut store = restart(store);
149 let (c4, _) = resume(&mut store).unwrap();
150 assert_eq!(c4.manifest.incarnation, 3);
151 assert_eq!(c4.root, c3.root);
152 assert_eq!(c4.state, c3.state);
153 assert_eq!(c4.cortex, c3.cortex);
154}
155
156#[test]
157fn provisioning_twice_is_refused() {
158 let mut store = provisioned();
159 assert_eq!(
160 provision(&mut store, [0x22; 32], UUID, ProvisionSource::Operator).map(|_| ()),
161 Err(ContinuityError::AlreadyProvisioned)
162 );
163 assert_eq!(resolve(&mut store).unwrap().root.agent_id, AGENT);
164}
165
166#[test]
167fn two_roots_stop_with_conflict() {
168 let mut store = provisioned();
169 // Bypass `provision` to plant a second root, as corruption or a bad merge could.
170 let other = AgentRoot {
171 agent_id: [0x22; 32],
172 store_uuid: UUID,
173 root_branch: root_branch_id(&[0x22; 32]),
174 provisioned_generation: 9,
175 source: ProvisionSource::Operator,
176 }
177 .encode();
178 store
179 .transact(&[ObjectInput {
180 kind: KIND_AGENT_ROOT,
181 version: STORE_OBJECT_VERSION,
182 bytes: &other,
183 }])
184 .unwrap();
185 assert_eq!(resolve(&mut store), Err(ContinuityError::Conflict));
186 assert_eq!(
187 resume(&mut store).map(|_| ()),
188 Err(ContinuityError::Conflict)
189 );
190}
191
192#[test]
193fn forked_or_gapped_manifest_chains_are_corrupt() {
194 // Fork: two manifests both claiming sequence 2.
195 let mut store = provisioned();
196 let c1 = resolve(&mut store).unwrap();
197 let mut bad = c1.manifest.clone();
198 bad.previous = Some(c1.manifest_id);
199 bad.sequence = 2;
200 bad.incarnation = 7;
201 let bytes = bad.encode().unwrap();
202 commit(&mut store, &c1, Update::default(), true).unwrap();
203 store
204 .transact(&[ObjectInput {
205 kind: KIND_MANIFEST,
206 version: STORE_OBJECT_VERSION,
207 bytes: &bytes,
208 }])
209 .unwrap();
210 assert!(matches!(
211 resolve(&mut store),
212 Err(ContinuityError::Corrupt(_))
213 ));
214
215 // Gap: a manifest at sequence 5 with nothing between.
216 let mut store = provisioned();
217 let c1 = resolve(&mut store).unwrap();
218 let mut gap = c1.manifest.clone();
219 gap.previous = Some(c1.manifest_id);
220 gap.sequence = 5;
221 let bytes = gap.encode().unwrap();
222 store
223 .transact(&[ObjectInput {
224 kind: KIND_MANIFEST,
225 version: STORE_OBJECT_VERSION,
226 bytes: &bytes,
227 }])
228 .unwrap();
229 assert!(matches!(
230 resolve(&mut store),
231 Err(ContinuityError::Corrupt(_))
232 ));
233}
234
235#[test]
236fn degraded_mount_resumes_read_only() {
237 let store = provisioned();
238 let mut dev = store.into_device();
239 // Plant a malformed peer superblock: the engine mounts DegradedRecovery.
240 let active = Store::open(dev.clone()).unwrap().active_slot() as usize;
241 dev.units[1 - active] = [0xa5; STORE_UNIT_BYTES];
242 dev.units[1 - active][..8].copy_from_slice(b"AIENSTR1");
243 let mut store = open(dev);
244 assert_eq!(store.mount_state(), MountState::DegradedRecovery);
245 let generation = store.generation();
246 let (c, committed) = resume(&mut store).unwrap();
247 assert!(!committed);
248 assert_eq!(c.root.agent_id, AGENT);
249 assert_eq!(store.generation(), generation, "nothing was committed");
250 assert_eq!(
251 commit(&mut store, &c, Update::default(), true).map(|_| ()),
252 Err(ContinuityError::ReadOnly)
253 );
254}
255
256#[test]
257fn a_crash_at_every_write_of_a_commit_leaves_old_or_new_never_a_third_state() {
258 let mut base = provisioned();
259 let c1 = resolve(&mut base).unwrap();
260 let before = base.into_device();
261
262 let update = || Update {
263 state: None,
264 cortex: vec![fact("remember across the crash")],
265 };
266 // Count the unit writes one continuity commit performs.
267 let mut counting = before.clone();
268 counting.writes_left = Some(usize::MAX);
269 let mut counted = open(counting);
270 commit(&mut counted, &c1, update(), true).unwrap();
271 let total = usize::MAX - counted.into_device().writes_left.unwrap();
272 assert!(total >= 4, "payload, catalog, commit record and superblock");
273
274 // Cut power before each write in turn (0..total) and after the last one.
275 for allowed in 0..=total {
276 let mut dev = before.clone();
277 dev.writes_left = Some(allowed);
278 let mut store = open(dev);
279 let _ = commit(&mut store, &c1, update(), true);
280 // Power returns: reopen the medium as written so far.
281 let mut dev = store.into_device();
282 dev.writes_left = None;
283 let mut store = open(dev);
284 let c = resolve(&mut store).unwrap();
285 assert_eq!(
286 c.root.agent_id, AGENT,
287 "identity survives a crash at write {allowed}"
288 );
289 match c.manifest.sequence {
290 1 => assert!(c.cortex.is_empty()),
291 2 => assert_eq!(c.cortex, vec![fact("remember across the crash")]),
292 s => panic!("third state: sequence {s} after crash at write {allowed}"),
293 }
294 if allowed == total {
295 assert_eq!(c.manifest.sequence, 2, "all writes landed: the new state");
296 }
297 }
298}
299
300#[test]
301fn encodings_round_trip_and_reject_tampering() {
302 let root = AgentRoot {
303 agent_id: AGENT,
304 store_uuid: UUID,
305 root_branch: root_branch_id(&AGENT),
306 provisioned_generation: 2,
307 source: ProvisionSource::Operator,
308 };
309 let bytes = root.encode();
310 assert_eq!(AgentRoot::decode(&bytes).unwrap(), root);
311
312 // Every single-byte flip is rejected or changes the decoded value.
313 for i in 0..bytes.len() {
314 let mut t = bytes.clone();
315 t[i] ^= 0x01;
316 if let Ok(decoded) = AgentRoot::decode(&t) {
317 assert_ne!(decoded, root, "flip at byte {i} went unnoticed");
318 }
319 }
320 // Truncation and trailing bytes are rejected.
321 assert!(AgentRoot::decode(&bytes[..bytes.len() - 1]).is_err());
322 let mut long = bytes.clone();
323 long.push(0);
324 assert!(AgentRoot::decode(&long).is_err());
325 // A root branch that does not derive from the agent is rejected.
326 let mut wrong = root;
327 wrong.root_branch = [0x99; 32];
328 assert!(AgentRoot::decode(&wrong.encode()).is_err());
329
330 let seg = WalSegment {
331 sequence: 3,
332 records: vec![fact("a"), fact("bb")],
333 };
334 assert_eq!(WalSegment::decode(&seg.encode().unwrap()).unwrap(), seg);
335
336 let mut state = AgentState::genesis(AGENT, 1);
337 let child = state.fork(&root_branch_id(&AGENT)).unwrap();
338 state.fork(&child).unwrap();
339 assert_eq!(AgentState::decode(&state.encode().unwrap()).unwrap(), state);
340}
341
342#[test]
343fn branch_table_validation_rejects_broken_lineage() {
344 let mut state = AgentState::genesis(AGENT, 1);
345 let root = root_branch_id(&AGENT);
346 let child = state.fork(&root).unwrap();
347 assert!(state.validate().is_ok());
348
349 let mut t = state.clone();
350 t.branches.iter_mut().find(|b| b.id == child).unwrap().depth = 5;
351 assert!(t.validate().is_err(), "wrong depth");
352
353 let mut t = state.clone();
354 t.branches.iter_mut().find(|b| b.id == root).unwrap().forks = 2;
355 assert!(t.validate().is_err(), "missing fork index 1");
356
357 let mut t = state.clone();
358 t.branches.retain(|b| b.id != root);
359 assert!(t.validate().is_err(), "no root");
360}
361
362/// Byte offset of branch `i`'s `forks` field in an encoded branch table:
363/// header 16 + agent 32 + written_at 8 + count 4 + reserved 4, then 80-byte
364/// rows of id 32, parent 32, depth 4, reserved 4, forks 8 (continuity.rs:394-407).
365fn forks_offset(i: usize) -> usize {
366 HEADER_BYTES + 32 + 8 + 4 + 4 + i * BRANCH_BYTES + 32 + 32 + 4 + 4
367}
368
369#[test]
370fn wrapping_fork_sum_is_refused_like_the_c_codec() {
371 // {root forks = 2^64-1, child index 0 forks = 2}: the u64 sum wraps to 1,
372 // which equals the one child. With a plain `.sum()` a --release build
373 // (overflow checks off) accepts this table; the C codec refuses it
374 // (cc_state_validate, native/kernel/svc/continuity_codec.c). The oracle must refuse as well.
375 let mut state = AgentState::genesis(AGENT, 1);
376 let root = root_branch_id(&AGENT);
377 let child = state.fork(&root).unwrap();
378 let honest = state.encode().unwrap();
379
380 let mut t = state.clone();
381 t.branches.iter_mut().find(|b| b.id == root).unwrap().forks = u64::MAX;
382 t.branches.iter_mut().find(|b| b.id == child).unwrap().forks = 2;
383 assert_eq!(
384 t.validate(),
385 Err(ContinuityError::Corrupt("fork indexes are not contiguous"))
386 );
387
388 // Same table through the decoder, built by patching honest bytes.
389 let ri = state.branches.iter().position(|b| b.id == root).unwrap();
390 let ci = state.branches.iter().position(|b| b.id == child).unwrap();
391 let mut bytes = honest.clone();
392 let (r, c) = (forks_offset(ri), forks_offset(ci));
393 assert_eq!(
394 bytes[r..r + 8],
395 1u64.to_le_bytes(),
396 "layout check: root forks"
397 );
398 assert_eq!(
399 bytes[c..c + 8],
400 0u64.to_le_bytes(),
401 "layout check: child forks"
402 );
403 bytes[r..r + 8].copy_from_slice(&u64::MAX.to_le_bytes());
404 bytes[c..c + 8].copy_from_slice(&2u64.to_le_bytes());
405 assert_eq!(
406 AgentState::decode(&bytes),
407 Err(ContinuityError::Corrupt("fork indexes are not contiguous"))
408 );
409 assert_eq!(AgentState::decode(&honest), Ok(state));
410}
411
412#[test]
413fn branch_table_at_the_maximum_legal_fork_sum_is_accepted() {
414 // MAX_BRANCHES rows = one root + 255 children: fork sum 255, the largest
415 // a valid table can have.
416 let mut state = AgentState::genesis(AGENT, 1);
417 let root = root_branch_id(&AGENT);
418 for _ in 1..MAX_BRANCHES {
419 state.fork(&root).unwrap();
420 }
421 assert_eq!(state.branches.len(), MAX_BRANCHES);
422 let sum: u64 = state.branches.iter().map(|b| b.forks).sum();
423 assert_eq!(sum, (MAX_BRANCHES - 1) as u64);
424 assert_eq!(state.validate(), Ok(()));
425 let bytes = state.encode().unwrap();
426 assert_eq!(AgentState::decode(&bytes), Ok(state.clone()));
427 // One more child is past the format bound, not a wrap.
428 assert_eq!(
429 state.fork(&root),
430 Err(ContinuityError::Limit("too many branches"))
431 );
432}
433
434#[test]
435fn huge_fork_count_with_underivable_child_is_refused_without_spinning() {
436 // Root forks = 2^64-1 and a child whose id is no derived index: an
437 // uncapped `0..forks` scan would run ~2^64 hashes. Capped at MAX_BRANCHES
438 // like C (cc_state_validate), it is refused after <= 256 hashes with
439 // C's class and text (cc_state_validate).
440 let root = root_branch_id(&AGENT);
441 let rogue = [0x77u8; 32];
442 assert!((0..MAX_BRANCHES as u64).all(|i| child_branch_id(&root, i) != rogue));
443 let mut t = AgentState::genesis(AGENT, 1);
444 t.branches[0].forks = u64::MAX;
445 t.branches.push(Branch {
446 id: rogue,
447 parent: Some(root),
448 depth: 1,
449 forks: 0,
450 });
451 t.branches.sort_by_key(|a| a.id);
452 assert_eq!(
453 t.validate(),
454 Err(ContinuityError::Corrupt("branch lineage is inconsistent"))
455 );
456}