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

273 lines · 9868 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//! NEXT-PHASE-2 v3: the external Cortex record mark, RecoverComposeHome
17//! keeping the old mark, the reserved repair key, and the reconcile-failed
18//! refusal, through the real compose home (ACCEPTANCE-v3 section 2).
19//!
20//! With librx_compose.a linked this drives the bridge as the daemon does (no
21//! socket); in a stub build it only checks the refusal.
22#[path = "support/home_guard.rs"]
23mod home_guard;
24
25use aien_runtime::compose::{ComposeBridge, ComposeProposer, Generation};
26use aien_runtime::control::{ComposeNoteReport, ControlResponse};
27use aien_runtime::cortex_mark::{self, Mark};
28use aien_runtime::effects::{self, IntentRequest};
29use serde_json::{json, Value};
30use std::path::{Path, PathBuf};
31use std::sync::{Arc, Mutex, MutexGuard};
32
33/// rxc_host allows 4 open handles per process (RXC_HOST_MAX_HANDLES): the
34/// tests that open homes run one at a time.
35static SERIAL: Mutex<()> = Mutex::new(());
36
37fn serial() -> MutexGuard<'static, ()> {
38 SERIAL.lock().unwrap_or_else(|e| e.into_inner())
39}
40
41fn proposer() -> ComposeProposer {
42 Arc::new(|_prompt: &str, _limit: std::time::Duration| {
43 Ok(Generation {
44 text: "filename: NOTES.md\nnote\n".into(),
45 tokens: 4,
46 finish_reason: Some("eos".into()),
47 ..Default::default()
48 })
49 })
50}
51
52fn noted(r: ControlResponse) -> ComposeNoteReport {
53 match r {
54 ControlResponse::ComposeNoted(n) => n,
55 other => panic!("expected ComposeNoted, got {other:?}"),
56 }
57}
58
59fn total(b: &ComposeBridge) -> u64 {
60 match b.recall(&[], None) {
61 ControlResponse::ComposeRecalled(r) => r.records_total,
62 other => panic!("recall: {other:?}"),
63 }
64}
65
66fn recall_error(b: &ComposeBridge) -> String {
67 match b.recall(&[], None) {
68 ControlResponse::Error(e) => e,
69 other => panic!("expected a refusal, got {other:?}"),
70 }
71}
72
73fn mark_of(home: &Path) -> Mark {
74 cortex_mark::read(&cortex_mark::mark_path(home))
75 .unwrap()
76 .expect("mark present")
77}
78
79fn grant(b: &ComposeBridge, n: u32) -> u64 {
80 // Any host record will do: only the journal length matters here, and a
81 // caller can no longer write an authorization (sovereign-core #261).
82 noted(b.note(
83 "constraint",
84 &json!({"approver": "drake", "n": n}).to_string(),
85 &[],
86 ))
87 .id
88}
89
90/// A home with history; returns (tempdir, home dir, records after setup).
91fn setup() -> Option<(tempfile::TempDir, PathBuf)> {
92 let tmp = tempfile::tempdir().unwrap();
93 let home = tmp.path().join("compose");
94 let b = ComposeBridge::new(home.clone(), proposer(), "test");
95 let r = b.note("constraint", "keep changes inside the workspace", &[]);
96 if !aien_omega_compose::LINKED {
97 assert!(matches!(r, ControlResponse::Error(_)));
98 return None;
99 }
100 noted(r);
101 // New home: a mark exists and matches the journal.
102 let n = total(&b);
103 let m = mark_of(&home);
104 assert_eq!(m.records, n);
105 assert!(m.seq >= 1);
106 Some((tmp, home))
107}
108
109#[test]
110fn boundary_cut_is_refused_and_recover_keeps_the_old_mark() {
111 let _home = home_guard::home_slot();
112 let _serial = serial();
113 let Some((_tmp, home)) = setup() else { return };
114 let cx = home.join("cortex.cx");
115 let b = ComposeBridge::new(home.clone(), proposer(), "test");
116 grant(&b, 1);
117 let size_before_a2 = std::fs::metadata(&cx).unwrap().len();
118 grant(&b, 2);
119 let m = mark_of(&home);
120 assert_eq!(m.records, total(&b));
121 drop(b);
122
123 // Cut exactly at the record boundary before grant 2.
124 let f = std::fs::OpenOptions::new().write(true).open(&cx).unwrap();
125 f.set_len(size_before_a2).unwrap();
126 drop(f);
127 let damaged = std::fs::read(&cx).unwrap();
128 let mark_bytes = std::fs::read(cortex_mark::mark_path(&home)).unwrap();
129 let b = ComposeBridge::new(home.clone(), proposer(), "test");
130 let e = recall_error(&b);
131 assert!(e.contains("E_MARK_TRUNCATED"), "{e}");
132 assert!(e.contains("1 record(s) lost"), "{e}");
133 // A refusal touches nothing.
134 assert_eq!(std::fs::read(&cx).unwrap(), damaged);
135 assert_eq!(
136 std::fs::read(cortex_mark::mark_path(&home)).unwrap(),
137 mark_bytes
138 );
139
140 // Recover: the old mark is kept, a repair record names the loss.
141 let rep = match b.recover() {
142 ControlResponse::ComposeRecovered(r) => *r,
143 other => panic!("recover: {other:?}"),
144 };
145 assert_eq!(rep.mark_lost, 1, "{rep:?}");
146 let kept = PathBuf::from(rep.mark_kept_as.clone().unwrap());
147 assert!(kept
148 .to_string_lossy()
149 .ends_with(&format!(".cortex-mark.lost-{}", m.seq)));
150 assert_eq!(std::fs::read(&kept).unwrap(), mark_bytes);
151 assert!(rep.mark_repair_record > 0);
152 let r = match b.recall(&[rep.mark_repair_record], None) {
153 ControlResponse::ComposeRecalled(r) => *r,
154 other => panic!("recall after recover: {other:?}"),
155 };
156 let t: Value = serde_json::from_str(r.cited[0].text.as_deref().unwrap()).unwrap();
157 assert_eq!(t["repair"], "cortex-mark");
158 assert_eq!(t["lost"], 1);
159 assert_eq!(r.cited[0].note.as_deref(), Some("constraint"));
160 let fresh = mark_of(&home);
161 assert_eq!(fresh.records, r.records_total);
162 assert!(fresh.seq > m.seq);
163 drop(b);
164 // Opens again cleanly.
165 let b = ComposeBridge::new(home.clone(), proposer(), "test");
166 total(&b);
167}
168
169#[test]
170fn crash_between_append_and_mark_is_not_corruption() {
171 let _home = home_guard::home_slot();
172 let _serial = serial();
173 let Some((_tmp, home)) = setup() else { return };
174 let mp = cortex_mark::mark_path(&home);
175 let b = ComposeBridge::new(home.clone(), proposer(), "test");
176 total(&b);
177 let before = std::fs::read(&mp).unwrap();
178 let m0 = mark_of(&home);
179 grant(&b, 1);
180 drop(b);
181 // The on-disk state of a process killed after the append, before its
182 // mark update: the journal is one record longer than the mark.
183 std::fs::write(&mp, &before).unwrap();
184 let b = ComposeBridge::new(home.clone(), proposer(), "test");
185 let n = total(&b);
186 let m1 = mark_of(&home);
187 assert_eq!(m1.records, n);
188 assert!(m1.seq > m0.seq);
189}
190
191#[test]
192fn digest_mismatch_and_damaged_mark_are_refused() {
193 let _home = home_guard::home_slot();
194 let _serial = serial();
195 let Some((_tmp, home)) = setup() else { return };
196 let mp = cortex_mark::mark_path(&home);
197 let mut m = mark_of(&home);
198 m.digest = [0x5a; 32];
199 cortex_mark::write(&mp, &m).unwrap();
200 let b = ComposeBridge::new(home.clone(), proposer(), "test");
201 let e = recall_error(&b);
202 assert!(e.contains("E_MARK_DIGEST"), "{e}");
203 drop(b);
204
205 std::fs::write(&mp, b"not a mark").unwrap();
206 let b = ComposeBridge::new(home.clone(), proposer(), "test");
207 let e = recall_error(&b);
208 assert!(e.contains("(E_MARK)"), "{e}");
209 let rep = match b.recover() {
210 ControlResponse::ComposeRecovered(r) => *r,
211 other => panic!("recover: {other:?}"),
212 };
213 let kept = rep.mark_kept_as.unwrap();
214 assert!(kept.ends_with(".cortex-mark.lost-damaged"), "{kept}");
215 assert_eq!(std::fs::read(&kept).unwrap(), b"not a mark");
216 total(&b);
217}
218
219#[test]
220fn missing_mark_is_adopted_not_refused() {
221 let _home = home_guard::home_slot();
222 let _serial = serial();
223 let Some((_tmp, home)) = setup() else { return };
224 let mp = cortex_mark::mark_path(&home);
225 std::fs::remove_file(&mp).unwrap();
226 let b = ComposeBridge::new(home.clone(), proposer(), "test");
227 let n = total(&b);
228 let m = mark_of(&home);
229 assert_eq!((m.records, m.seq), (n, 1));
230}
231
232#[test]
233fn repair_key_is_reserved() {
234 assert!(effects::check_reserved_note("constraint", r#"{"repair":"cortex-mark"}"#).is_err());
235 assert!(effects::check_reserved_note("constraint", r#"{"note":"x"}"#).is_ok());
236 assert!(effects::check_reserved_note("constraint", "plain text").is_ok());
237}
238
239#[test]
240fn effect_commands_refuse_until_reconcile_succeeds() {
241 let _home = home_guard::home_slot();
242 let _serial = serial();
243 let Some((tmp, home)) = setup() else { return };
244 let b = ComposeBridge::new(home.clone(), proposer(), "test");
245 b.set_reconcile_failed("failed: test".into());
246 let req = IntentRequest {
247 authorization: 1,
248 proposal_sha256: "00".into(),
249 path: "NOTES.md".into(),
250 target: tmp.path().join("NOTES.md").display().to_string(),
251 content_sha256: "00".into(),
252 executor_pid: 0,
253 executor_start: 0,
254 };
255 let refused = |r: ControlResponse| match r {
256 ControlResponse::Error(e) => e,
257 other => panic!("expected an error, got {other:?}"),
258 };
259 let e = refused(effects::open_intent(&b, &req));
260 assert!(e.starts_with("EFFECT_REFUSED ReconcileFailed:"), "{e}");
261 let e = refused(effects::ack(&b, 1, &json!({})));
262 assert!(e.starts_with("EFFECT_REFUSED ReconcileFailed:"), "{e}");
263 // Authorize and recall stay available.
264 grant(&b, 1);
265 total(&b);
266 assert!(matches!(
267 effects::reconcile(&b, None, "test"),
268 ControlResponse::ComposeReconciled(_)
269 ));
270 assert_eq!(b.reconcile_failed(), None);
271 let e = refused(effects::open_intent(&b, &req));
272 assert!(!e.contains("ReconcileFailed"), "{e}");
273}