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

421 lines · 13808 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//! Replay ledger for approved proposals (crate::approved_replay, sovereign-core #249 part B).
17//! Pure ledger rules run in every build; the journal tests need the linked
18//! composition library and are IGNORED in a stub build (cfg compose_linked, set by
19//! build.rs from aien-omega-compose's links metadata).
20//! A "crashed" claim is made by a child process (this test binary re-run with
21//! REPLAY_CHILD set) that claims and exits without settling.
22#[path = "support/home_guard.rs"]
23mod home_guard;
24
25use aien_runtime::approved_replay::{
26 self as replay, ClaimKeys, ClaimState, CommitEvidence, ReplayLedger, FIELD,
27};
28use aien_runtime::compose::{ComposeBridge, ComposeProposer};
29use aien_runtime::control::ComposeRecordView;
30use aien_runtime::effects;
31use serde_json::json;
32use std::path::Path;
33use std::sync::{Arc, Barrier};
34
35fn proposer() -> ComposeProposer {
36 Arc::new(|_: &str, _: std::time::Duration| panic!("no model on the replay path"))
37}
38
39fn bridge(dir: &Path) -> ComposeBridge {
40 ComposeBridge::new(dir.join("compose"), proposer(), "test:replay")
41}
42
43fn keys(n: &str) -> ClaimKeys {
44 let k = format!(
45 "{:0>64}",
46 n.bytes().map(|b| format!("{:02x}", b)).collect::<String>()
47 );
48 ClaimKeys {
49 approval_key: k[k.len() - 64..].to_string(),
50 request_id: format!("req-{n}"),
51 approval_id: format!("appr-{n}"),
52 trace_id: format!("trace-{n}"),
53 }
54}
55
56fn evidence() -> CommitEvidence {
57 CommitEvidence {
58 compose_proposal_sha256: "ab".repeat(32),
59 cx_promotion: 17,
60 cx_evidence: 15,
61 task: 99,
62 }
63}
64
65fn refused_as<T: std::fmt::Debug>(r: Result<T, replay::Refusal>, name: &str) -> replay::Refusal {
66 match r {
67 Err(e) => {
68 assert_eq!(e.name, name, "want {name}, got {e}");
69 assert!(e
70 .to_string()
71 .starts_with(&format!("REPLAY_REFUSED {name}:")));
72 e
73 }
74 Ok(v) => panic!("want REPLAY_REFUSED {name}, got {v:?}"),
75 }
76}
77
78// ---------- pure ledger rules (every build) ----------
79
80fn view(id: u64, text: serde_json::Value) -> ComposeRecordView {
81 ComposeRecordView {
82 id,
83 cls: 0,
84 kind: 0,
85 subject: 0,
86 tag: 4,
87 links: vec![],
88 digest: String::new(),
89 verified: true,
90 note: Some("effect".into()),
91 text: Some(text.to_string()),
92 }
93}
94
95fn accepted(id: u64, k: &ClaimKeys) -> ComposeRecordView {
96 // pid 0: an executor that is never alive (effects::executor_alive).
97 view(
98 id,
99 json!({FIELD: "accepted", "approval_key": k.approval_key, "request_id": k.request_id,
100 "approval_id": k.approval_id, "trace_id": k.trace_id,
101 "executor": {"pid": 0, "start": 0}}),
102 )
103}
104
105fn step(id: u64, claim: u64, phase: &str) -> ComposeRecordView {
106 view(
107 id,
108 json!({FIELD: phase, "claim": claim, "reason": "test", "evidence": evidence()}),
109 )
110}
111
112#[test]
113fn ledger_lifecycle_and_refusal_names() {
114 let k = keys("a");
115 let cases: Vec<(Vec<ComposeRecordView>, ClaimState, &str)> = vec![
116 (
117 vec![accepted(1, &k)],
118 ClaimState::Accepted,
119 "AlreadyConsumed",
120 ),
121 (
122 vec![accepted(1, &k), step(2, 1, "in_flight")],
123 ClaimState::InFlight,
124 "Uncertain",
125 ),
126 (
127 vec![
128 accepted(1, &k),
129 step(2, 1, "in_flight"),
130 step(3, 1, "committed"),
131 ],
132 ClaimState::Committed,
133 "AlreadyCommitted",
134 ),
135 (
136 vec![
137 accepted(1, &k),
138 step(2, 1, "in_flight"),
139 step(3, 1, "failed"),
140 ],
141 ClaimState::Failed,
142 "AlreadyFailed",
143 ),
144 (
145 vec![
146 accepted(1, &k),
147 step(2, 1, "in_flight"),
148 step(3, 1, "uncertain"),
149 ],
150 ClaimState::Uncertain,
151 "Uncertain",
152 ),
153 (
154 vec![accepted(1, &k), step(2, 1, "not_executed")],
155 ClaimState::NotExecuted,
156 "AlreadyConsumed",
157 ),
158 ];
159 for (recs, state, name) in cases {
160 let l = ReplayLedger::from_records(&recs).unwrap();
161 assert_eq!(l.claims[&1].state, state);
162 let r = l.check(&k).expect("claimed keys are refused");
163 assert_eq!(r.name, name, "{state:?}");
164 assert_eq!(r.claim, Some(1));
165 assert_eq!(r.evidence.is_some(), state == ClaimState::Committed);
166 }
167}
168
169#[test]
170fn ledger_each_key_is_claimed_on_its_own() {
171 let k = keys("a");
172 let l = ReplayLedger::from_records(&[accepted(1, &k)]).unwrap();
173 let mut only_request = keys("b");
174 only_request.request_id = k.request_id.clone();
175 let mut only_approval = keys("c");
176 only_approval.approval_id = k.approval_id.clone();
177 let mut only_key = keys("d");
178 only_key.approval_key = k.approval_key.clone();
179 for (what, other) in [
180 ("request", only_request),
181 ("approval", only_approval),
182 ("key", only_key),
183 ] {
184 assert!(l.check(&other).is_some(), "same {what} id must be refused");
185 }
186 assert!(l.check(&keys("e")).is_none(), "fresh keys are free");
187}
188
189#[test]
190fn ledger_refuses_corrupt_histories() {
191 let k = keys("a");
192 let bad: Vec<Vec<ComposeRecordView>> = vec![
193 vec![accepted(1, &k), accepted(2, &k)], // a key claimed twice
194 vec![accepted(1, &k), step(2, 1, "committed")], // committed without in_flight
195 vec![
196 accepted(1, &k),
197 step(2, 1, "in_flight"),
198 step(3, 1, "not_executed"),
199 ],
200 vec![
201 accepted(1, &k),
202 step(2, 1, "in_flight"),
203 step(3, 1, "committed"),
204 step(4, 1, "failed"),
205 ],
206 vec![step(2, 1, "in_flight")], // names no claim
207 vec![accepted(1, &k), step(2, 1, "bogus")],
208 ];
209 for recs in bad {
210 let e = ReplayLedger::from_records(&recs).unwrap_err();
211 assert_eq!(e.name, "CorruptLedger", "{e}");
212 }
213 let mut unverified = accepted(1, &k);
214 unverified.verified = false;
215 assert_eq!(
216 ReplayLedger::from_records(&[unverified]).unwrap_err().name,
217 "CorruptLedger"
218 );
219}
220
221#[test]
222fn compose_note_cannot_forge_replay_records() {
223 for phase in ["accepted", "in_flight", "committed", "declared"] {
224 let t = json!({FIELD: phase, "claim": 1}).to_string();
225 assert!(
226 effects::check_reserved_note("effect", &t).is_err(),
227 "{phase}"
228 );
229 }
230}
231
232// ---------- journal (linked composition library) ----------
233
234#[test]
235#[cfg_attr(
236 not(compose_linked),
237 ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)"
238)]
239fn claim_is_durable_and_single_use_across_restart() {
240 let _home = home_guard::home_slot();
241 let tmp = tempfile::tempdir().unwrap();
242 let k = keys("restart");
243 {
244 let b = bridge(tmp.path());
245 let c = replay::claim(&b, &k).unwrap();
246 // Same process, same keys: the running claim refuses.
247 refused_as(replay::claim(&b, &k), "InFlight");
248 replay::mark_in_flight(&b, &c).unwrap();
249 replay::commit(&b, &c, &evidence()).unwrap();
250 // Lifecycle cannot go backwards or repeat.
251 refused_as(replay::commit(&b, &c, &evidence()), "WrongState");
252 refused_as(replay::fail(&b, &c, "x"), "WrongState");
253 }
254 // A new bridge on the same compose home = a daemon restart.
255 let b = bridge(tmp.path());
256 assert!(replay::reconcile_at_start(&b)
257 .unwrap()
258 .contains("0 -> NOT_EXECUTED"));
259 let e = refused_as(replay::claim(&b, &k), "AlreadyCommitted");
260 assert_eq!(
261 e.evidence,
262 Some(evidence()),
263 "a lost response can be recovered"
264 );
265 for (what, changed) in [
266 (
267 "request",
268 ClaimKeys {
269 approval_key: keys("x").approval_key,
270 approval_id: "appr-x".into(),
271 ..k.clone()
272 },
273 ),
274 (
275 "approval",
276 ClaimKeys {
277 approval_key: keys("y").approval_key,
278 request_id: "req-y".into(),
279 ..k.clone()
280 },
281 ),
282 (
283 "key",
284 ClaimKeys {
285 request_id: "req-z".into(),
286 approval_id: "appr-z".into(),
287 ..k.clone()
288 },
289 ),
290 ] {
291 refused_as(replay::claim(&b, &changed), "AlreadyCommitted");
292 let _ = what;
293 }
294 // A fresh approval is accepted.
295 replay::claim(&b, &keys("fresh")).unwrap();
296}
297
298#[test]
299#[cfg_attr(
300 not(compose_linked),
301 ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)"
302)]
303fn failed_and_not_executed_claims_stay_consumed() {
304 let _home = home_guard::home_slot();
305 let tmp = tempfile::tempdir().unwrap();
306 let b = bridge(tmp.path());
307 let c = replay::claim(&b, &keys("ne")).unwrap();
308 replay::not_executed(&b, &c, "authentication refused after claim").unwrap();
309 refused_as(replay::claim(&b, &keys("ne")), "AlreadyConsumed");
310 let c = replay::claim(&b, &keys("f")).unwrap();
311 replay::mark_in_flight(&b, &c).unwrap();
312 replay::fail(&b, &c, "World did not commit").unwrap();
313 refused_as(replay::claim(&b, &keys("f")), "AlreadyFailed");
314 let c = replay::claim(&b, &keys("u")).unwrap();
315 replay::mark_in_flight(&b, &c).unwrap();
316 replay::uncertain(&b, &c, "run returned an error").unwrap();
317 refused_as(replay::claim(&b, &keys("u")), "Uncertain");
318 replay::declare(&b, c.id, false, "operator", "World checked: no commit").unwrap();
319 refused_as(replay::claim(&b, &keys("u")), "Uncertain");
320 refused_as(
321 replay::declare(&b, c.id, true, "operator", "again"),
322 "WrongState",
323 );
324}
325
326#[test]
327#[cfg_attr(
328 not(compose_linked),
329 ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)"
330)]
331fn concurrent_duplicates_at_most_one_claim() {
332 let _home = home_guard::home_slot();
333 let tmp = tempfile::tempdir().unwrap();
334 let b = Arc::new(bridge(tmp.path()));
335 let n = 16;
336 let gate = Arc::new(Barrier::new(n));
337 let hs: Vec<_> = (0..n)
338 .map(|i| {
339 let (b, gate) = (b.clone(), gate.clone());
340 std::thread::spawn(move || {
341 // Half the threads reuse only the request id, half the whole keys.
342 let mut k = keys("race");
343 if i % 2 == 1 {
344 k.approval_key = keys(&format!("r{i}")).approval_key;
345 k.approval_id = format!("appr-r{i}");
346 }
347 gate.wait();
348 replay::claim(&b, &k)
349 })
350 })
351 .collect();
352 let ok = hs
353 .into_iter()
354 .map(|h| h.join().unwrap())
355 .filter(|r| r.is_ok())
356 .count();
357 assert_eq!(ok, 1, "exactly one concurrent claim wins");
358}
359
360/// Child mode: claim (and optionally go in flight), then exit without settling.
361/// Run only by crash_child.
362#[test]
363#[ignore = "child mode, run by crash_before_and_during_execution_fail_closed"]
364fn child_claim_then_crash() {
365 let _home = home_guard::home_slot();
366 let Ok(mode) = std::env::var("REPLAY_CHILD") else {
367 return;
368 };
369 let dir = std::env::var("REPLAY_DIR").unwrap();
370 let b = bridge(Path::new(&dir));
371 let c = replay::claim(&b, &keys(&mode)).unwrap();
372 if mode == "inflight" {
373 replay::mark_in_flight(&b, &c).unwrap();
374 }
375 std::process::exit(0);
376}
377
378fn crash_child(dir: &Path, mode: &str) {
379 let st = std::process::Command::new(std::env::current_exe().unwrap())
380 .args([
381 "--exact",
382 "child_claim_then_crash",
383 "--ignored",
384 "--nocapture",
385 "--test-threads=1",
386 ])
387 .env("REPLAY_CHILD", mode)
388 .env("REPLAY_DIR", dir)
389 .status()
390 .unwrap();
391 assert!(st.success(), "child {mode}: {st}");
392}
393
394#[test]
395#[cfg_attr(
396 not(compose_linked),
397 ignore = "needs the linked librx_compose.a (AIEN_OMEGA_COMPOSE_LIB)"
398)]
399fn crash_before_and_during_execution_fail_closed() {
400 let tmp = tempfile::tempdir().unwrap();
401 crash_child(tmp.path(), "before");
402 crash_child(tmp.path(), "inflight");
403 let b = bridge(tmp.path());
404 // Before the start-up reconcile: a gone process is never "in flight", and
405 // neither claim can be taken again.
406 refused_as(replay::claim(&b, &keys("before")), "AlreadyConsumed");
407 refused_as(replay::claim(&b, &keys("inflight")), "Uncertain");
408 let s = replay::reconcile_at_start(&b).unwrap();
409 assert!(
410 s.contains("1 -> NOT_EXECUTED") && s.contains("1 -> UNCERTAIN"),
411 "{s}"
412 );
413 refused_as(replay::claim(&b, &keys("before")), "AlreadyConsumed");
414 refused_as(replay::claim(&b, &keys("inflight")), "Uncertain");
415 // The reconcile is idempotent: nothing left to settle.
416 let s = replay::reconcile_at_start(&b).unwrap();
417 assert!(
418 s.contains("0 -> NOT_EXECUTED") && s.contains("0 -> UNCERTAIN"),
419 "{s}"
420 );
421}