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 / receipt_continuity_test.rs

409 lines · 14722 bytes Raw Blame History
1//! sovereign-core #408, recovery audit row 8: receipt continuity across a
2//! restart. The record mark names the newest record's digest and the record
3//! count; each Cortex record digest covers only its own record. So a record
4//! before the newest one, rewritten with a freshly computed digest, opened as
5//! if intact. The mark now also carries the running hash over every record
6//! digest (the same chain omega keeps in memory, `rx_cortex.c` chain_step),
7//! and the open recomputes it: a forged, reordered, removed or spliced record
8//! anywhere before the mark is refused by name (`E_MARK_CHAIN`).
9//!
10//! Each case rewrites `cortex.cx` the way someone with the file (and no key)
11//! can: every tampered record gets a valid digest, so omega's own open check
12//! passes and only the continuity check can catch it. Needs librx_compose.a;
13//! in a stub build the cases return early.
14#[path = "support/home_guard.rs"]
15mod home_guard;
16
17use aien_runtime::compose::{ComposeBridge, ComposeProposer, Generation};
18use aien_runtime::control::ControlResponse;
19use aien_runtime::cortex_mark;
20use serde_json::json;
21use sha2::{Digest, Sha256};
22use std::path::{Path, PathBuf};
23use std::sync::Arc;
24
25// Journal layout (omega rx_cortex.c): a 4-word header, then per record a
26// 13-word fixed part (marker, id, cls<<32|kind, subject, t, generation,
27// branch<<32|protect, tag, links x4, n), n payload words, 4 digest words.
28const HDR_BYTES: usize = 32;
29const FIXED: usize = 13;
30const W_ID: usize = 1;
31const W_T: usize = 4;
32const W_N: usize = 12;
33const DOMAIN: &[u8] = b"AIEN.CORTEX.OBJECT.V1";
34
35#[derive(Clone)]
36struct Rec {
37 w: [u64; FIXED],
38 payload: Vec<u64>,
39 digest: [u8; 32],
40}
41
42fn le(b: &[u8], i: usize) -> u64 {
43 u64::from_le_bytes(b[i..i + 8].try_into().unwrap())
44}
45
46/// omega `cx_digest`: sha256 over the domain, fixed words 1..13, payload.
47fn digest_of(w: &[u64; FIXED], payload: &[u64]) -> [u8; 32] {
48 let mut h = Sha256::new();
49 h.update(DOMAIN);
50 for x in &w[1..] {
51 h.update(x.to_le_bytes());
52 }
53 for x in payload {
54 h.update(x.to_le_bytes());
55 }
56 h.finalize().into()
57}
58
59fn read_journal(p: &Path) -> (Vec<u8>, Vec<Rec>) {
60 let b = std::fs::read(p).unwrap();
61 let hdr = b[..HDR_BYTES].to_vec();
62 let mut recs = Vec::new();
63 let mut at = HDR_BYTES;
64 while at < b.len() {
65 let mut w = [0u64; FIXED];
66 for (i, x) in w.iter_mut().enumerate() {
67 *x = le(&b, at + 8 * i);
68 }
69 let n = w[W_N] as usize;
70 let payload = (0..n).map(|i| le(&b, at + 8 * (FIXED + i))).collect();
71 let d0 = at + 8 * (FIXED + n);
72 let digest: [u8; 32] = b[d0..d0 + 32].try_into().unwrap();
73 recs.push(Rec { w, payload, digest });
74 at = d0 + 32;
75 }
76 assert_eq!(at, b.len(), "journal parse ends on a record boundary");
77 // Control: this parser and digest agree with every record omega wrote.
78 for (i, r) in recs.iter().enumerate() {
79 assert_eq!(r.w[W_ID], i as u64 + 1);
80 assert_eq!(digest_of(&r.w, &r.payload), r.digest, "record #{}", i + 1);
81 }
82 (hdr, recs)
83}
84
85/// Renumber every record to its position and give it a valid digest, as a
86/// forger without a key can.
87fn write_journal(p: &Path, hdr: &[u8], recs: &mut [Rec]) {
88 let mut b = hdr.to_vec();
89 for (i, r) in recs.iter_mut().enumerate() {
90 r.w[W_ID] = i as u64 + 1;
91 r.w[W_N] = r.payload.len() as u64;
92 r.digest = digest_of(&r.w, &r.payload);
93 for x in r.w.iter().chain(&r.payload) {
94 b.extend_from_slice(&x.to_le_bytes());
95 }
96 b.extend_from_slice(&r.digest);
97 }
98 std::fs::write(p, b).unwrap();
99}
100
101/// Rewrite the text of a host note payload (`[len, sha256 x4, bytes...]`)
102/// to `to` (same length), with a matching payload sha256.
103fn forge_note(r: &mut Rec, from: &str, to: &str) {
104 assert_eq!(from.len(), to.len());
105 let len = r.payload[0] as usize;
106 let mut bytes: Vec<u8> = r.payload[5..]
107 .iter()
108 .flat_map(|w| w.to_le_bytes())
109 .collect();
110 let text = String::from_utf8(bytes[..len].to_vec()).unwrap();
111 assert!(text.contains(from), "{text}");
112 let forged = text.replacen(from, to, 1);
113 bytes[..len].copy_from_slice(forged.as_bytes());
114 for (i, chunk) in bytes.chunks(8).enumerate() {
115 r.payload[5 + i] = u64::from_le_bytes(chunk.try_into().unwrap());
116 }
117 let sha: [u8; 32] = Sha256::digest(forged.as_bytes()).into();
118 for i in 0..4 {
119 r.payload[1 + i] = u64::from_le_bytes(sha[8 * i..8 * i + 8].try_into().unwrap());
120 }
121}
122
123fn proposer() -> ComposeProposer {
124 Arc::new(|_prompt: &str, _limit: std::time::Duration| {
125 Ok(Generation {
126 text: "filename: NOTES.md\nnote\n".into(),
127 tokens: 4,
128 finish_reason: Some("eos".into()),
129 ..Default::default()
130 })
131 })
132}
133
134fn total(b: &ComposeBridge) -> u64 {
135 match b.recall(&[], None) {
136 ControlResponse::ComposeRecalled(r) => r.records_total,
137 other => panic!("recall: {other:?}"),
138 }
139}
140
141/// What the restarted home answers: the refusal text, or why it opened.
142fn reopen_refusal(home: &Path) -> String {
143 let b = ComposeBridge::new(home.to_path_buf(), proposer(), "test");
144 match b.recall(&[], None) {
145 ControlResponse::Error(e) => e,
146 ControlResponse::ComposeRecalled(r) => panic!(
147 "tampered journal accepted after the restart: opened with {} records",
148 r.records_total
149 ),
150 other => panic!("unexpected answer {other:?}"),
151 }
152}
153
154/// A home with five consecutive constraint receipts and one more after them,
155/// closed (the restart). Returns (tempdir, home, receipt ids, mark records).
156fn setup() -> Option<(tempfile::TempDir, PathBuf, Vec<u64>, u64)> {
157 let tmp = tempfile::tempdir().unwrap();
158 let home = tmp.path().join("compose");
159 let b = ComposeBridge::new(home.clone(), proposer(), "test");
160 let r = b.note("constraint", "keep changes inside the workspace", &[]);
161 if !aien_omega_compose::LINKED {
162 assert!(matches!(r, ControlResponse::Error(_)));
163 return None;
164 }
165 let mut ids = Vec::new();
166 for n in 0..6 {
167 match b.note(
168 "constraint",
169 &json!({"approver": "drake", "n": n}).to_string(),
170 &[],
171 ) {
172 ControlResponse::ComposeNoted(x) => ids.push(x.id),
173 other => panic!("note: {other:?}"),
174 }
175 }
176 assert!(ids.windows(2).all(|w| w[1] == w[0] + 1), "{ids:?}");
177 let n = total(&b);
178 drop(b);
179 let m = cortex_mark::read(&cortex_mark::mark_path(&home))
180 .unwrap()
181 .unwrap();
182 assert_eq!(m.records, n);
183 // The receipts tampered below all sit before the newest marked record.
184 assert!(ids[4] < m.records, "{ids:?} vs mark {}", m.records);
185 // Negative control: untouched, the home reopens.
186 let b = ComposeBridge::new(home.clone(), proposer(), "test");
187 let after = total(&b);
188 drop(b);
189 let m = cortex_mark::read(&cortex_mark::mark_path(&home))
190 .unwrap()
191 .unwrap();
192 assert_eq!(m.records, after);
193 Some((tmp, home, ids, m.records))
194}
195
196fn idx(id: u64) -> usize {
197 id as usize - 1
198}
199
200#[test]
201fn forged_middle_receipt_is_refused() {
202 let _home = home_guard::home_slot();
203 let Some((_tmp, home, ids, _)) = setup() else {
204 return;
205 };
206 let cx = home.join("cortex.cx");
207 let (hdr, mut recs) = read_journal(&cx);
208 forge_note(&mut recs[idx(ids[2])], "drake", "decoy");
209 write_journal(&cx, &hdr, &mut recs);
210 let e = reopen_refusal(&home);
211 assert!(e.contains("E_MARK_CHAIN"), "{e}");
212}
213
214#[test]
215fn reordered_receipts_are_refused() {
216 let _home = home_guard::home_slot();
217 let Some((_tmp, home, ids, _)) = setup() else {
218 return;
219 };
220 let cx = home.join("cortex.cx");
221 let (hdr, mut recs) = read_journal(&cx);
222 // Swap two receipts; each keeps the logical time of its slot (omega
223 // refuses time going backwards on a subject).
224 let (a, b) = (idx(ids[1]), idx(ids[3]));
225 let (ta, tb) = (recs[a].w[W_T], recs[b].w[W_T]);
226 recs.swap(a, b);
227 recs[a].w[W_T] = ta;
228 recs[b].w[W_T] = tb;
229 write_journal(&cx, &hdr, &mut recs);
230 let e = reopen_refusal(&home);
231 assert!(e.contains("E_MARK_CHAIN"), "{e}");
232}
233
234#[test]
235fn gap_with_the_count_restored_is_refused() {
236 let _home = home_guard::home_slot();
237 let Some((_tmp, home, ids, _)) = setup() else {
238 return;
239 };
240 let cx = home.join("cortex.cx");
241 let (hdr, mut recs) = read_journal(&cx);
242 // Drop receipt 1, repeat receipt 3 after itself: same count, same
243 // newest record, one receipt gone.
244 let dup = recs[idx(ids[3])].clone();
245 recs.insert(idx(ids[3]) + 1, dup);
246 recs.remove(idx(ids[1]));
247 write_journal(&cx, &hdr, &mut recs);
248 let e = reopen_refusal(&home);
249 assert!(e.contains("E_MARK_CHAIN"), "{e}");
250}
251
252#[test]
253fn spliced_foreign_receipt_is_refused() {
254 let _home = home_guard::home_slot();
255 let Some((_tmp, home, ids, _)) = setup() else {
256 return;
257 };
258 // A receipt from another home, written by the same code.
259 let Some((_tmp2, other, other_ids, _)) = setup() else {
260 return;
261 };
262 let (_, foreign) = read_journal(&other.join("cortex.cx"));
263 let mut f = foreign[idx(other_ids[2])].clone();
264 forge_note(&mut f, "drake", "other");
265 let cx = home.join("cortex.cx");
266 let (hdr, mut recs) = read_journal(&cx);
267 let at = idx(ids[2]);
268 f.w[W_T] = recs[at].w[W_T];
269 recs[at] = f;
270 write_journal(&cx, &hdr, &mut recs);
271 let e = reopen_refusal(&home);
272 assert!(e.contains("E_MARK_CHAIN"), "{e}");
273}
274
275#[test]
276fn truncated_tail_is_refused() {
277 let _home = home_guard::home_slot();
278 let Some((_tmp, home, ids, _)) = setup() else {
279 return;
280 };
281 let cx = home.join("cortex.cx");
282 let (hdr, mut recs) = read_journal(&cx);
283 recs.truncate(idx(ids[3]));
284 write_journal(&cx, &hdr, &mut recs);
285 let e = reopen_refusal(&home);
286 assert!(e.contains("E_MARK_TRUNCATED"), "{e}");
287
288 // The same cut with the count padded back by repeating the last kept
289 // record: refused by name (omega's J-Space anchor or the mark).
290 let (hdr, mut recs) = read_journal(&cx);
291 let mark_records = cortex_mark::read(&cortex_mark::mark_path(&home))
292 .unwrap()
293 .unwrap()
294 .records;
295 let last = recs.last().unwrap().clone();
296 while (recs.len() as u64) < mark_records {
297 recs.push(last.clone());
298 }
299 write_journal(&cx, &hdr, &mut recs);
300 let e = reopen_refusal(&home);
301 assert!(
302 e.contains("E_MARK_DIGEST") || e.contains("E_MARK_CHAIN") || e.contains("E_REPLAY"),
303 "{e}"
304 );
305}
306
307#[test]
308fn chain_refusal_repairs_nothing_and_recover_keeps_the_old_mark() {
309 let _home = home_guard::home_slot();
310 let Some((_tmp, home, ids, _)) = setup() else {
311 return;
312 };
313 let cx = home.join("cortex.cx");
314 let mp = cortex_mark::mark_path(&home);
315 let (hdr, mut recs) = read_journal(&cx);
316 forge_note(&mut recs[idx(ids[1])], "drake", "decoy");
317 write_journal(&cx, &hdr, &mut recs);
318 let (journal, mark) = (std::fs::read(&cx).unwrap(), std::fs::read(&mp).unwrap());
319 let seq = cortex_mark::read(&mp).unwrap().unwrap().seq;
320 let e = reopen_refusal(&home);
321 assert!(e.contains("E_MARK_CHAIN"), "{e}");
322 // Nothing is repaired or rewritten: the tampered records stay as they
323 // were (the open's own start-up records may follow them, as for
324 // E_MARK_DIGEST) and the mark is untouched.
325 assert!(std::fs::read(&cx).unwrap().starts_with(&journal));
326 assert!(std::fs::read(&mp).unwrap() == mark);
327
328 // The operator's recover sets the mark aside and names why.
329 let b = ComposeBridge::new(home.clone(), proposer(), "test");
330 let rep = match b.recover() {
331 ControlResponse::ComposeRecovered(r) => *r,
332 other => panic!("recover: {other:?}"),
333 };
334 let kept = PathBuf::from(rep.mark_kept_as.clone().unwrap());
335 assert!(kept
336 .to_string_lossy()
337 .ends_with(&format!(".cortex-mark.lost-{seq}")));
338 assert_eq!(std::fs::read(&kept).unwrap(), mark);
339 let r = match b.recall(&[rep.mark_repair_record], None) {
340 ControlResponse::ComposeRecalled(r) => *r,
341 other => panic!("recall after recover: {other:?}"),
342 };
343 let t: serde_json::Value = serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap();
344 assert_eq!(t["repair"], "cortex-mark");
345 assert_eq!(t["why"], "records before the newest differ");
346 assert!(
347 t["old_chain"].as_str().is_some_and(|c| c.len() == 64),
348 "{t}"
349 );
350 drop(b);
351 let b = ComposeBridge::new(home.clone(), proposer(), "test");
352 total(&b);
353}
354
355#[test]
356fn version_1_mark_is_upgraded_then_checked() {
357 let _home = home_guard::home_slot();
358 let Some((_tmp, home, ids, _)) = setup() else {
359 return;
360 };
361 let cx = home.join("cortex.cx");
362 let mp = cortex_mark::mark_path(&home);
363 // An install older than the chain: the same mark without it.
364 let m = cortex_mark::read(&mp).unwrap().unwrap();
365 assert!(m.chain.is_some());
366 cortex_mark::write(&mp, &cortex_mark::Mark { chain: None, ..m }).unwrap();
367 assert_eq!(std::fs::read(&mp).unwrap().len(), cortex_mark::MARK_LEN_V1);
368 let b = ComposeBridge::new(home.clone(), proposer(), "test");
369 let n = total(&b);
370 drop(b);
371 let up = cortex_mark::read(&mp).unwrap().unwrap();
372 assert_eq!(up.records, n);
373 // The new chain is the chain over the journal as written.
374 let (hdr, mut recs) = read_journal(&cx);
375 assert_eq!(recs.len() as u64, n);
376 assert_eq!(
377 up.chain,
378 Some(cortex_mark::chain_over(recs.iter().map(|r| &r.digest)))
379 );
380 // From here on a forged receipt is refused.
381 forge_note(&mut recs[idx(ids[0])], "drake", "decoy");
382 write_journal(&cx, &hdr, &mut recs);
383 let e = reopen_refusal(&home);
384 assert!(e.contains("E_MARK_CHAIN"), "{e}");
385}
386
387#[test]
388fn zero_record_mark_with_a_chain_is_refused_as_a_damaged_mark() {
389 let _home = home_guard::home_slot();
390 let Some((_tmp, home, _ids, _)) = setup() else {
391 return;
392 };
393 let mp = cortex_mark::mark_path(&home);
394 let m = cortex_mark::read(&mp).unwrap().unwrap();
395 // A v2 mark claiming no records but carrying a non-initial chain: the
396 // mark contradicts itself; the refusal names the mark, not the journal.
397 cortex_mark::write(
398 &mp,
399 &cortex_mark::Mark {
400 records: 0,
401 digest: [0u8; 32],
402 chain: Some([0x5a; 32]),
403 ..m
404 },
405 )
406 .unwrap();
407 let e = reopen_refusal(&home);
408 assert!(e.contains("(E_MARK)") && e.contains("zero records"), "{e}");
409}