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-replay / src / lib.rs

406 lines · 12785 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//! aien-replay: Rust reference reader/verifier for the TRN1 execution
17//! transcript (aien-protocols `specs/execution-transcript/`, contract 0.1.0,
18//! wire schema 1).
19//!
20//! ADR 0024: Rust here is scaffolding. Omega is the destination. This crate
21//! only reads bytes, applies the spec's check order (section 7) and prints the
22//! spec's outcome lines (section 8). It writes nothing and imports no runtime.
23
24use sha2::{Digest, Sha256};
25
26pub type Hash = [u8; 32];
27
28pub const HEADER_LEN: usize = 48;
29pub const RECORD_HEADER_LEN: usize = 56;
30pub const MAX_RECORDS: u64 = 4096;
31pub const MAX_IDENT: u32 = 65536;
32pub const MAX_ANNOT: u32 = 65536;
33pub const MAX_INPUT_CONTENT: u32 = 4096;
34const T_END: u16 = 0xFFFF;
35
36/// Refusal codes, spec section 6.
37pub mod code {
38 pub const MAGIC: i32 = -1;
39 pub const VERSION: i32 = -2;
40 pub const LENGTH: i32 = -3;
41 pub const NONCANONICAL: i32 = -4;
42 pub const UNKNOWN: i32 = -5;
43 pub const SHAPE: i32 = -6;
44 pub const GAP: i32 = -7;
45 pub const CHAIN: i32 = -8;
46 pub const DIGEST: i32 = -9;
47 pub const TRUNCATED: i32 = -10;
48}
49
50/// Mutation hook. `mutations/run_mutants.sh trn1` rewrites this constant to
51/// the name of one check, which switches that check off, and requires the
52/// shared corpus to notice. In the real build it names no check.
53const MUTANT: &str = "";
54#[inline(always)]
55fn on(check: &str) -> bool {
56 MUTANT != check
57}
58
59/// Subsystem registry, spec section 5.2.
60pub fn subsystem_name(id: u16) -> Option<&'static str> {
61 Some(match id {
62 0 => "transcript",
63 1 => "omega-world",
64 2 => "omega-cortex",
65 3 => "omega-jspace",
66 4 => "aienos-kernel",
67 5 => "aienos-argus",
68 6 => "aienos-store",
69 7 => "sovcore-runtime",
70 8 => "sovcore-scheduler",
71 9 => "sovcore-kv",
72 10 => "external",
73 _ => return None,
74 })
75}
76
77enum IdentRule {
78 Exact(u32),
79 ExternalInput,
80 Crumb,
81}
82
83/// Record type registry, spec section 5.1. None = unknown type.
84fn ident_rule(t: u16) -> Option<IdentRule> {
85 use IdentRule::*;
86 Some(match t {
87 1 => Exact(32),
88 2 | 3 | 5 => Exact(24),
89 4 | 14 => Exact(40),
90 6 | 10 | 13 => Exact(48),
91 7 => Exact(32),
92 8 | 9 => Exact(56),
93 11 => ExternalInput,
94 12 => Exact(16),
95 15 => Crumb,
96 16 => Exact(200),
97 T_END => Exact(16),
98 _ => return None,
99 })
100}
101
102/// An accepted transcript.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub struct Accepted {
105 pub records: u64,
106 pub run_id: Hash,
107 pub final_digest: Hash,
108 /// Per record (index 0 = record 1): compared digest and subsystem id.
109 pub compared: Vec<(Hash, u16)>,
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub enum Verdict {
114 Accept(Accepted),
115 Refuse { code: i32, event: u64 },
116}
117
118fn u16le(b: &[u8]) -> u16 {
119 u16::from_le_bytes([b[0], b[1]])
120}
121fn u32le(b: &[u8]) -> u32 {
122 u32::from_le_bytes(b[..4].try_into().expect("4 bytes"))
123}
124fn u64le(b: &[u8]) -> u64 {
125 u64::from_le_bytes(b[..8].try_into().expect("8 bytes"))
126}
127fn zero(b: &[u8]) -> bool {
128 b.iter().all(|&x| x == 0)
129}
130fn sha(parts: &[&[u8]]) -> Hash {
131 let mut h = Sha256::new();
132 for p in parts {
133 h.update(p);
134 }
135 h.finalize().into()
136}
137
138/// RX_CRUMB canonical bytes (spec 5.3): true if they parse to exactly their length.
139fn crumb_shape(c: &[u8]) -> bool {
140 let mut o = 0usize;
141 let need = |o: usize, k: usize| c.len() - o >= k;
142 if !need(o, 36) {
143 return false;
144 }
145 let id = u64le(c);
146 o += 36;
147 for (limit, each) in [(8u32, 24usize), (8, 16), (8, 24)] {
148 if !need(o, 4) {
149 return false;
150 }
151 let k = u32le(&c[o..]);
152 o += 4;
153 if k > limit || !need(o, k as usize * each) {
154 return false;
155 }
156 o += k as usize * each;
157 }
158 if !need(o, 8) {
159 return false; // reason i32 + n_parents u32
160 }
161 let parents = u32le(&c[o + 4..]);
162 o += 8;
163 if parents > 65 {
164 return false;
165 }
166 for _ in 0..parents {
167 if !need(o, 8) {
168 return false;
169 }
170 let p = u64le(&c[o..]);
171 o += 8;
172 if p >= 1 && p < id {
173 if !need(o, 32) {
174 return false;
175 }
176 o += 32;
177 }
178 }
179 o == c.len()
180}
181
182/// Reserved fields inside an identity (step 9). True if all are zero.
183fn ident_reserved_ok(t: u16, id: &[u8]) -> bool {
184 match t {
185 3 => u32le(&id[20..]) == 0,
186 6 | 11 | 12 | 14 => u32le(&id[4..]) == 0,
187 7 => zero(&id[5..8]),
188 10 => u32le(&id[12..]) == 0,
189 16 => zero(&id[129..136]),
190 T_END => u64le(&id[8..]) == 0,
191 _ => true,
192 }
193}
194
195/// Verify one transcript buffer, spec section 7 check order.
196pub fn verify(b: &[u8]) -> Verdict {
197 let refuse = |code, event| Verdict::Refuse { code, event };
198 let n = b.len();
199
200 // Header.
201 if n < 4 {
202 return refuse(code::LENGTH, 0);
203 }
204 if on("magic") && &b[..4] != b"TRN1" {
205 return refuse(code::MAGIC, 0);
206 }
207 if n < 6 {
208 return refuse(code::LENGTH, 0);
209 }
210 if on("version") && u16le(&b[4..]) != 1 {
211 return refuse(code::VERSION, 0);
212 }
213 if n < HEADER_LEN {
214 return refuse(code::LENGTH, 0);
215 }
216 if on("hdr_flags") && u16le(&b[6..]) != 0 {
217 return refuse(code::NONCANONICAL, 0);
218 }
219 let producer = u16le(&b[40..]);
220 if on("producer") && (producer == 0 || subsystem_name(producer).is_none()) {
221 return refuse(code::UNKNOWN, 0);
222 }
223 if on("hdr_reserved") && !zero(&b[42..48]) {
224 return refuse(code::NONCANONICAL, 0);
225 }
226 let run_id: Hash = b[8..40].try_into().expect("32 bytes");
227 let mut prev = sha(&[&b[..HEADER_LEN]]);
228 let mut o = HEADER_LEN;
229 let mut compared = Vec::new();
230 let mut argus_after: Option<Hash> = None;
231
232 for k in 1u64.. {
233 // 1. record header present
234 if o == n {
235 return if on("truncated") {
236 refuse(code::TRUNCATED, k)
237 } else {
238 refuse(0, k)
239 };
240 }
241 if n - o < RECORD_HEADER_LEN || k > MAX_RECORDS {
242 return refuse(code::LENGTH, k);
243 }
244 let r = &b[o..];
245 let (t, sub) = (u16le(r), u16le(&r[2..]));
246 let (ilen, alen) = (u32le(&r[4..]), u32le(&r[8..]));
247 // 2. known type and subsystem
248 let rule = ident_rule(t);
249 if on("type") && rule.is_none() {
250 return refuse(code::UNKNOWN, k);
251 }
252 if on("subsystem") && subsystem_name(sub).is_none() {
253 return refuse(code::UNKNOWN, k);
254 }
255 // 3. reserved
256 if on("rec_reserved") && u32le(&r[12..]) != 0 {
257 return refuse(code::NONCANONICAL, k);
258 }
259 // 4. length limits
260 if on("limit") && (ilen > MAX_IDENT || alen > MAX_ANNOT) {
261 return refuse(code::LENGTH, k);
262 }
263 // 5. sequence
264 if on("seq") && u64le(&r[16..]) != k {
265 return refuse(code::GAP, k);
266 }
267 // 6. chain
268 if on("prev") && r[24..56] != prev {
269 return refuse(code::CHAIN, k);
270 }
271 // 7. body present
272 let body = ilen as u64 + alen as u64;
273 if ((n - o - RECORD_HEADER_LEN) as u64) < body {
274 return refuse(code::LENGTH, k);
275 }
276 let rec_len = RECORD_HEADER_LEN + body as usize;
277 let id = &r[RECORD_HEADER_LEN..RECORD_HEADER_LEN + ilen as usize];
278
279 // 8. shape
280 let len_ok = match rule {
281 Some(IdentRule::Exact(x)) => ilen == x,
282 Some(IdentRule::ExternalInput) => (48..=48 + MAX_INPUT_CONTENT).contains(&ilen),
283 Some(IdentRule::Crumb) => ilen >= 32,
284 None => true, // only reachable with the "type" check mutated off
285 };
286 if on("ident_len") && !len_ok {
287 return refuse(code::SHAPE, k);
288 }
289 // Body fields below are read only when the length is right, so a
290 // mutated-off length check cannot index out of range.
291 if on("end_subsystem") && (t == T_END) != (sub == 0) {
292 return refuse(code::SHAPE, k);
293 }
294 if on("cap_op") && t == 7 && len_ok && !(1..=6).contains(&id[4]) {
295 return refuse(code::SHAPE, k);
296 }
297 if on("crash_seq") && t == 13 && len_ok && u64le(&id[8..]) >= k {
298 return refuse(code::SHAPE, k);
299 }
300 if on("crumb_shape") && t == 15 && ilen >= 32 && !crumb_shape(&id[32..]) {
301 return refuse(code::SHAPE, k);
302 }
303 if on("argus_flag") && t == 16 && len_ok && id[128] > 1 {
304 return refuse(code::SHAPE, k);
305 }
306 if on("end_annot") && t == T_END && alen != 0 {
307 return refuse(code::SHAPE, k);
308 }
309 // 9. reserved fields inside the identity
310 if on("body_reserved") && len_ok && !ident_reserved_ok(t, id) {
311 return refuse(code::NONCANONICAL, k);
312 }
313 // 10. embedded digests
314 if t == 15
315 && ilen >= 32
316 && on("crumb_digest")
317 && sha(&[b"AIEN_RX_CAUSAL_V1", &id[32..]]) != id[..32]
318 {
319 return refuse(code::DIGEST, k);
320 }
321 if t == 11 && ilen > 48 && on("input_digest") && sha(&[&id[48..]]) != id[16..48] {
322 return refuse(code::DIGEST, k);
323 }
324 if t == 16 && len_ok {
325 let before: Hash = id[136..168].try_into().expect("32 bytes");
326 let after: Hash = id[168..200].try_into().expect("32 bytes");
327 if on("argus_cont") && argus_after.is_some_and(|a| a != before) {
328 return refuse(code::DIGEST, k);
329 }
330 let want = if id[128] != 0 {
331 sha(&[&before, &id[..128]])
332 } else {
333 before
334 };
335 if on("argus_link") && want != after {
336 return refuse(code::DIGEST, k);
337 }
338 argus_after = Some(after);
339 }
340
341 // record digest (chain) and compared digest (replay)
342 prev = sha(&[&r[..rec_len]]);
343 let cmp = sha(&[b"AIEN_TRN1_CMP", &r[0..4], &r[16..24], &r[4..8], id]);
344 compared.push((cmp, sub));
345 o += rec_len;
346
347 // 11. END
348 if t == T_END {
349 if on("end_count") && (ilen < 8 || u64le(id) != k) {
350 return refuse(code::GAP, k);
351 }
352 if on("trailing") && o != n {
353 return refuse(code::LENGTH, k + 1);
354 }
355 return Verdict::Accept(Accepted {
356 records: k,
357 run_id,
358 final_digest: prev,
359 compared,
360 });
361 }
362 }
363 unreachable!("record loop only exits by return")
364}
365
366fn hex(d: &Hash) -> String {
367 d.iter().map(|x| format!("{x:02x}")).collect()
368}
369
370/// Verify outcome line, spec section 8.
371pub fn verdict_line(v: &Verdict) -> String {
372 match v {
373 Verdict::Accept(a) => format!(
374 "ok records={} run={} final={}",
375 a.records,
376 hex(&a.run_id),
377 hex(&a.final_digest)
378 ),
379 Verdict::Refuse { code, event } => format!("refuse {code} event={event}"),
380 }
381}
382
383/// Compare outcome line, spec section 8: expected first, actual second.
384pub fn compare_line(expected: &Verdict, actual: &Verdict) -> String {
385 let (e, a) = match (expected, actual) {
386 (Verdict::Refuse { code, event }, _) => {
387 return format!("refuse expected {code} event={event}")
388 }
389 (_, Verdict::Refuse { code, event }) => {
390 return format!("refuse actual {code} event={event}")
391 }
392 (Verdict::Accept(e), Verdict::Accept(a)) => (e, a),
393 };
394 for (i, (x, y)) in e.compared.iter().zip(&a.compared).enumerate() {
395 if x.0 != y.0 {
396 return format!(
397 "DIVERGENCE event={} expected={} actual={} subsystem={}",
398 i + 1,
399 hex(&x.0),
400 hex(&y.0),
401 subsystem_name(x.1).unwrap_or("?")
402 );
403 }
404 }
405 format!("MATCH through {}", e.records.min(a.records))
406}