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-proof / src / import.rs

621 lines · 23427 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//! Import external qualification output as receipts.
17//!
18//! Other repositories (SEED-0B runs, rollback verifiers, Store v1 crash
19//! tests) emit a small machine readable assertion file. `import` turns that
20//! file plus explicit source, artifact, and dependency references into a
21//! sealed EvidenceReceiptV1. Prose is never parsed; the input contract is
22//! JSON and any deviation fails closed.
23
24use std::path::Path;
25use std::time::{SystemTime, UNIX_EPOCH};
26
27use crate::evidence::{
28 check_commit, Assertion, LeaseRef, LedgerRef, Mutation, Receipt, Tier, Verdict, SCHEMA,
29 SCHEMA_VERSION,
30};
31use crate::lease::check_resource_name;
32
33/// Machine readable assertion file produced by each test setup.
34#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
35#[serde(deny_unknown_fields)]
36pub struct AssertionFile {
37 pub assertions: Vec<AssertionInput>,
38 /// Optional top level result. When absent it is derived from the
39 /// assertions. A claimed PASS with a failing assertion is refused.
40 #[serde(default)]
41 pub result: Option<String>,
42}
43
44/// One assertion line in the input file.
45#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
46#[serde(deny_unknown_fields)]
47pub struct AssertionInput {
48 pub id: String,
49 #[serde(default)]
50 pub expected: String,
51 #[serde(default)]
52 pub observed: String,
53 pub result: AssertionResult,
54 #[serde(default)]
55 pub source: String,
56 #[serde(default)]
57 pub note: String,
58}
59
60/// Accepts `pass`/`fail` strings or booleans.
61#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
62#[serde(untagged)]
63pub enum AssertionResult {
64 Bool(bool),
65 Word(String),
66}
67
68impl AssertionResult {
69 fn pass(&self) -> Result<bool, String> {
70 match self {
71 AssertionResult::Bool(b) => Ok(*b),
72 AssertionResult::Word(w) => match w.to_ascii_lowercase().as_str() {
73 "pass" => Ok(true),
74 "fail" => Ok(false),
75 _ => Err(format!("assertion result must be pass or fail, got {w:?}")),
76 },
77 }
78 }
79}
80
81/// All inputs needed to mint a receipt from external output.
82#[derive(Debug, Clone, Default)]
83pub struct ImportRequest {
84 pub repo: String,
85 pub commit: String,
86 pub dirty: bool,
87 pub kind: String,
88 pub tier: String,
89 pub toolchain: String,
90 pub procedure: String,
91 pub machine: String,
92 pub input_artifacts: Vec<String>,
93 pub output_artifacts: Vec<String>,
94 pub dependencies: Vec<String>,
95 pub declared_mutation: Option<String>,
96 pub observed_mutation: Option<String>,
97 pub authority: String,
98 pub output_digest: Option<String>,
99 pub output_file: Option<String>,
100 pub external_refs: Vec<String>,
101 pub ledger_index: Option<u64>,
102 pub ledger_hash: Option<String>,
103 pub lease_hold: Option<String>,
104 pub lease_resource: Option<String>,
105 pub timestamp: Option<u64>,
106}
107
108fn now() -> u64 {
109 SystemTime::now()
110 .duration_since(UNIX_EPOCH)
111 .map(|d| d.as_secs())
112 .unwrap_or(0)
113}
114
115/// Parse and validate the assertion file. Never sniffs prose.
116pub fn read_assertion_file(path: &Path) -> Result<(Vec<Assertion>, Verdict), String> {
117 let text =
118 std::fs::read_to_string(path).map_err(|e| format!("cannot read assertion file: {e}"))?;
119 let file: AssertionFile =
120 serde_json::from_str(&text).map_err(|e| format!("assertion file invalid: {e}"))?;
121 if file.assertions.is_empty() {
122 return Err("assertion file must carry at least one assertion".to_string());
123 }
124 let mut out = Vec::with_capacity(file.assertions.len());
125 for input in &file.assertions {
126 if input.id.trim().is_empty() {
127 return Err("assertion id must not be empty".to_string());
128 }
129 out.push(Assertion {
130 id: input.id.clone(),
131 expected: input.expected.clone(),
132 observed: input.observed.clone(),
133 pass: input.result.pass()?,
134 source: input.source.clone(),
135 note: input.note.clone(),
136 });
137 }
138 let derived = if out.iter().all(|a| a.pass) {
139 Verdict::Pass
140 } else {
141 Verdict::Fail
142 };
143 if let Some(claimed) = file.result {
144 let verdict = Verdict::parse(&claimed).ok_or_else(|| format!("bad result {claimed:?}"))?;
145 if verdict == Verdict::Pass && derived != Verdict::Pass {
146 return Err("assertion file claims PASS but an assertion failed".to_string());
147 }
148 // A setup may only downgrade (BLOCKED, INCOMPLETE, SKIPPED), never
149 // upgrade a failing run. FAIL stays FAIL.
150 if derived == Verdict::Fail && verdict == Verdict::Pass {
151 return Err("cannot upgrade a failing run to PASS".to_string());
152 }
153 if derived == Verdict::Pass && verdict == Verdict::Fail {
154 return Err("file claims FAIL but every assertion passed".to_string());
155 }
156 Ok((out, verdict))
157 } else {
158 Ok((out, derived))
159 }
160}
161
162// Canonical store assertion IDs live in store_assert.rs; this table only
163// groups them per qualification kind.
164use crate::store_assert::*;
165fn store_required_assertions(kind: &str) -> Option<&'static [&'static str]> {
166 match kind {
167 "store-v1-format" => Some(&[
168 STORE_FORMAT_VALID,
169 STORE_OBJECT_IDS_VALID,
170 STORE_CATALOG_VALID,
171 STORE_COMMIT_VALID,
172 STORE_FULL_GRAPH_VALID,
173 ]),
174 "store-v1-host" => Some(&[
175 STORE_PREVIOUS_OR_NEW_ONLY,
176 STORE_CONFLICT_FAIL_CLOSED,
177 STORE_INCONSISTENT_HISTORY_FAIL_CLOSED,
178 STORE_IO_ERROR_NOT_FALLBACK,
179 STORE_NOSPACE_ZERO_WRITES,
180 STORE_OPEN_SIDE_EFFECT_FREE,
181 ]),
182 "store-v1-qemu" => Some(&[
183 STORE_PREVIOUS_OR_NEW_ONLY,
184 STORE_FULL_GRAPH_VALID,
185 STORE_QEMU_REBOOT_RECOVERED,
186 ]),
187 _ => None,
188 }
189}
190
191/// Store qualification profile for kinds starting with "store-".
192/// Checks source identity, tier allow list, artifact and assertion
193/// presence, assertion origin, PASS consistency, mutation allow list,
194/// and the per-kind required assertion set. Output digest presence for
195/// PASS stays enforced by `build_receipt`.
196pub fn validate_store_profile(
197 req: &ImportRequest,
198 assertions: &[Assertion],
199 result: Verdict,
200) -> Result<(), String> {
201 if req.repo.trim().is_empty() {
202 return Err("store qualification requires non-empty repo".to_string());
203 }
204 check_commit(&req.commit)?;
205 if req.procedure.trim().is_empty() {
206 return Err("store qualification requires non-empty procedure".to_string());
207 }
208 if req.procedure.trim() == "TBD" {
209 return Err("store qualification requires a named procedure, got \"TBD\"".to_string());
210 }
211 let tier = Tier::parse(&req.tier).ok_or_else(|| {
212 format!(
213 "store qualification kind {:?} has unknown tier {:?}",
214 req.kind, req.tier
215 )
216 })?;
217 match tier {
218 Tier::HostTest | Tier::Qemu | Tier::QemuSecurity => {}
219 _ => {
220 return Err(format!(
221 "store qualification kind {:?} refuses tier {:?}",
222 req.kind,
223 tier.as_str()
224 ));
225 }
226 }
227 if req.input_artifacts.is_empty() {
228 return Err("store qualification requires at least one input artifact digest".to_string());
229 }
230 if assertions.is_empty() {
231 return Err("store qualification requires at least one assertion".to_string());
232 }
233 for a in assertions {
234 if a.source.trim().is_empty() {
235 return Err(format!(
236 "store qualification requires assertion source for {:?}",
237 a.id
238 ));
239 }
240 }
241 if result == Verdict::Pass && assertions.iter().any(|a| !a.pass) {
242 return Err("store qualification claims PASS but an assertion failed".to_string());
243 }
244 let declared = match &req.declared_mutation {
245 Some(s) => Mutation::parse(s).ok_or_else(|| format!("unknown mutation class {s:?}"))?,
246 None => Mutation::None,
247 };
248 match declared {
249 Mutation::None
250 | Mutation::VolatileOnly
251 | Mutation::RemovableMediaOnly
252 | Mutation::BoundedTestRegionWrite => {}
253 _ => {
254 return Err(format!(
255 "store qualification kind {:?} refuses declared mutation {:?}",
256 req.kind,
257 declared.as_str()
258 ));
259 }
260 }
261 if let Some(required) = store_required_assertions(req.kind.as_str()) {
262 for id in required {
263 let ok = assertions.iter().any(|a| a.id == *id && a.pass);
264 if !ok {
265 return Err(format!(
266 "store qualification kind {:?} missing required passing assertion {:?}",
267 req.kind, id
268 ));
269 }
270 }
271 }
272 Ok(())
273}
274
275/// Build a sealed receipt from validated inputs. Hardware tiers require an
276/// explicit declared mutation and a lease reference; PASS receipts require
277/// an output digest (direct hex or hashed from an output file).
278pub fn build_receipt(
279 req: &ImportRequest,
280 assertions: Vec<Assertion>,
281 result: Verdict,
282) -> Result<Receipt, String> {
283 if req.kind.starts_with("store-") {
284 validate_store_profile(req, &assertions, result)?;
285 }
286 if req.kind == crate::formal::KIND {
287 crate::formal::validate_formal_profile(req, &assertions, result)?;
288 }
289 let tier = Tier::parse(&req.tier)
290 .ok_or_else(|| format!("unknown qualification tier {:?}", req.tier))?;
291 check_commit(&req.commit)?;
292 if req.repo.trim().is_empty() {
293 return Err("repo must not be empty".to_string());
294 }
295 if req.kind.trim().is_empty() {
296 return Err("gate/kind must not be empty".to_string());
297 }
298 if req.procedure.trim().is_empty() {
299 return Err("procedure identity must not be empty".to_string());
300 }
301 if req.machine.trim().is_empty() {
302 return Err("machine identity must not be empty".to_string());
303 }
304 for dep in &req.dependencies {
305 let low = dep.to_ascii_lowercase();
306 if low.len() != 64 || !low.bytes().all(|b| b.is_ascii_hexdigit()) {
307 return Err(format!("dependency {dep:?} is not a 64 digit receipt hash"));
308 }
309 }
310 let declared = match &req.declared_mutation {
311 Some(s) => Mutation::parse(s).ok_or_else(|| format!("unknown mutation class {s:?}"))?,
312 None => {
313 if tier.is_hardware() {
314 return Err("hardware receipts require --declared-mutation".to_string());
315 }
316 Mutation::None
317 }
318 };
319 let observed = match &req.observed_mutation {
320 Some(s) => Mutation::parse(s).ok_or_else(|| format!("unknown mutation class {s:?}"))?,
321 None => declared,
322 };
323 let output_digest = match (&req.output_digest, &req.output_file) {
324 (Some(hex), _) => {
325 if hex.len() != 64 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
326 return Err("output digest must be 64 hex digits (BLAKE3)".to_string());
327 }
328 hex.to_ascii_lowercase()
329 }
330 (None, Some(path)) => {
331 let bytes = std::fs::read(path).map_err(|e| format!("cannot read output file: {e}"))?;
332 blake3::hash(&bytes).to_hex().to_string()
333 }
334 (None, None) => {
335 if result == Verdict::Pass {
336 return Err("PASS receipts require --output-digest or --output-file".to_string());
337 }
338 "0".repeat(64)
339 }
340 };
341 let ledger = match (req.ledger_index, &req.ledger_hash) {
342 (Some(index), Some(hash)) => {
343 if hash.len() != 64 || !hash.bytes().all(|b| b.is_ascii_hexdigit()) {
344 return Err("ledger hash must be 64 hex digits".to_string());
345 }
346 Some(LedgerRef {
347 index,
348 hash: hash.to_ascii_lowercase(),
349 })
350 }
351 (None, None) => None,
352 _ => return Err("ledger reference needs both index and hash".to_string()),
353 };
354 let lease = match (&req.lease_hold, &req.lease_resource) {
355 (Some(hold), Some(resource)) => {
356 check_resource_name(resource)?;
357 if hold.len() != 64 || !hold.bytes().all(|b| b.is_ascii_hexdigit()) {
358 return Err("lease hold id must be 64 hex digits".to_string());
359 }
360 Some(LeaseRef {
361 hold_id: hold.to_ascii_lowercase(),
362 resource: resource.clone(),
363 })
364 }
365 (None, None) => None,
366 _ => return Err("lease binding needs both hold id and resource".to_string()),
367 };
368 if tier.is_hardware() && lease.is_none() {
369 return Err("hardware receipts require --lease-hold and --lease-resource".to_string());
370 }
371 let mut receipt = Receipt {
372 schema: SCHEMA.to_string(),
373 version: SCHEMA_VERSION,
374 id: String::new(),
375 kind: req.kind.clone(),
376 tier,
377 result,
378 timestamp: req.timestamp.unwrap_or_else(now),
379 repo: req.repo.clone(),
380 commit: req.commit.to_ascii_lowercase(),
381 dirty: req.dirty,
382 toolchain: req.toolchain.clone(),
383 procedure: req.procedure.clone(),
384 machine: req.machine.clone(),
385 env_class: tier.as_str().to_string(),
386 input_artifacts: req.input_artifacts.clone(),
387 output_artifacts: req.output_artifacts.clone(),
388 assertions,
389 dependencies: req
390 .dependencies
391 .iter()
392 .map(|d| d.to_ascii_lowercase())
393 .collect(),
394 declared_mutation: declared,
395 observed_mutation: observed,
396 authority: req.authority.clone(),
397 output_digest,
398 external_refs: req.external_refs.clone(),
399 ledger,
400 lease,
401 required_features: vec![],
402 reserved: String::new(),
403 };
404 let id = crate::evidence::receipt_id(&receipt)?;
405 receipt.id = id;
406 // Final self check: identity plus consistency, fail closed.
407 let text = serde_json::to_vec(&receipt).map_err(|e| e.to_string())?;
408 let (_, report) = crate::evidence::verify_bytes(&text)?;
409 if report.status == Verdict::Fail {
410 return Err(format!(
411 "built receipt fails self check: {}",
412 report.reasons.join("; ")
413 ));
414 }
415 Ok(receipt)
416}
417
418#[cfg(test)]
419mod tests {
420 use super::*;
421 use crate::evidence::{store_receipt, verify_bytes};
422
423 fn write(path: &Path, text: &str) {
424 std::fs::write(path, text).unwrap();
425 }
426
427 fn req() -> ImportRequest {
428 ImportRequest {
429 repo: "https://github.com/aien-dev/aienux".to_string(),
430 commit: "a".repeat(40),
431 dirty: false,
432 kind: "seed-0b-qemu".to_string(),
433 tier: "QEMU".to_string(),
434 toolchain: "rustc 1.90.0".to_string(),
435 procedure: "scripts/qemu_seed0b.sh".to_string(),
436 machine: "qemu-virt-aarch64".to_string(),
437 input_artifacts: vec!["blake3:".to_string() + &"b".repeat(64)],
438 output_digest: Some("c".repeat(64)),
439 ..Default::default()
440 }
441 }
442
443 #[test]
444 fn import_roundtrip() {
445 let dir = crate::testutil::temp_dir("import-ok");
446 let file = dir.join("assert.json");
447 write(
448 &file,
449 r#"{"assertions": [{"id": "artifact_signature_valid", "expected": "valid", "observed": "valid", "result": "pass", "source": "qemu"}]}"#,
450 );
451 let (assertions, result) = read_assertion_file(&file).unwrap();
452 assert_eq!(result, Verdict::Pass);
453 let receipt = build_receipt(&req(), assertions, result).unwrap();
454 let store = crate::testutil::temp_dir("import-store");
455 let id = store_receipt(&store, &receipt).unwrap();
456 assert_eq!(id, receipt.id);
457 let text = std::fs::read(store.join("receipts").join(format!("{id}.json"))).unwrap();
458 let (_, report) = verify_bytes(&text).unwrap();
459 assert_eq!(report.status, Verdict::Pass);
460 }
461
462 #[test]
463 fn prose_is_never_parsed() {
464 let dir = crate::testutil::temp_dir("import-prose");
465 let file = dir.join("assert.json");
466 write(&file, "all tests passed, trust me");
467 assert!(read_assertion_file(&file).is_err());
468 }
469
470 #[test]
471 fn claimed_pass_with_failed_assertion_refused() {
472 let dir = crate::testutil::temp_dir("import-liar");
473 let file = dir.join("assert.json");
474 write(
475 &file,
476 r#"{"result": "PASS", "assertions": [{"id": "x", "result": "fail"}]}"#,
477 );
478 assert!(read_assertion_file(&file).is_err());
479 }
480
481 #[test]
482 fn hardware_import_needs_mutation_and_lease() {
483 let dir = crate::testutil::temp_dir("import-hw");
484 let file = dir.join("assert.json");
485 write(&file, r#"{"assertions": [{"id": "x", "result": "pass"}]}"#);
486 let (assertions, result) = read_assertion_file(&file).unwrap();
487 let mut r = req();
488 r.tier = "MACHINE1_ATTENDED".to_string();
489 r.machine = "machine-1".to_string();
490 assert!(build_receipt(&r, assertions.clone(), result).is_err());
491 r.declared_mutation = Some("REMOVABLE_MEDIA_ONLY".to_string());
492 assert!(build_receipt(&r, assertions.clone(), result).is_err());
493 r.lease_hold = Some("e".repeat(64));
494 r.lease_resource = Some("machine-1".to_string());
495 r.procedure = "scripts/seed0b_machine1.sh".to_string();
496 let receipt = build_receipt(&r, assertions, result).unwrap();
497 assert_eq!(receipt.env_class, "MACHINE1_ATTENDED");
498 let _ = dir;
499 }
500
501 #[test]
502 fn unknown_tier_and_mutation_refused() {
503 let dir = crate::testutil::temp_dir("import-bad-enum");
504 let file = dir.join("assert.json");
505 write(&file, r#"{"assertions": [{"id": "x", "result": "pass"}]}"#);
506 let (assertions, result) = read_assertion_file(&file).unwrap();
507 let mut r = req();
508 r.tier = "REAL_HARDWARE".to_string();
509 assert!(build_receipt(&r, assertions.clone(), result).is_err());
510 r.tier = "QEMU".to_string();
511 r.declared_mutation = Some("FORMAT_EVERYTHING".to_string());
512 assert!(build_receipt(&r, assertions, result).is_err());
513 let _ = dir;
514 }
515
516 fn store_req(kind: &str, tier: &str) -> ImportRequest {
517 let mut r = req();
518 r.kind = kind.to_string();
519 r.tier = tier.to_string();
520 r.procedure = "scripts/store_test.sh".to_string();
521 r.machine = "store-test-runner".to_string();
522 r
523 }
524
525 fn store_assertion(id: &str) -> Assertion {
526 Assertion {
527 id: id.to_string(),
528 expected: String::new(),
529 observed: String::new(),
530 pass: true,
531 source: "store run log".to_string(),
532 note: String::new(),
533 }
534 }
535
536 fn format_assertions() -> Vec<Assertion> {
537 vec![
538 store_assertion("store_format_valid"),
539 store_assertion("store_object_ids_valid"),
540 store_assertion("store_catalog_valid"),
541 store_assertion("store_commit_valid"),
542 store_assertion("store_full_graph_valid"),
543 ]
544 }
545
546 fn host_assertions() -> Vec<Assertion> {
547 vec![
548 store_assertion("store_previous_or_new_only"),
549 store_assertion("store_conflict_fail_closed"),
550 store_assertion("store_inconsistent_history_fail_closed"),
551 store_assertion("store_io_error_not_fallback"),
552 store_assertion("store_nospace_zero_writes"),
553 store_assertion("store_open_side_effect_free"),
554 ]
555 }
556
557 #[test]
558 fn store_format_valid_passes_profile() {
559 let r = store_req("store-v1-format", "HOST_TEST");
560 let assertions = format_assertions();
561 validate_store_profile(&r, &assertions, Verdict::Pass).unwrap();
562 let receipt = build_receipt(&r, assertions, Verdict::Pass).unwrap();
563 assert_eq!(receipt.kind, "store-v1-format");
564 assert_eq!(receipt.tier, Tier::HostTest);
565 }
566
567 #[test]
568 fn store_format_missing_required_refused() {
569 let r = store_req("store-v1-format", "HOST_TEST");
570 let mut assertions = format_assertions();
571 assertions.retain(|a| a.id != "store_commit_valid");
572 let err = validate_store_profile(&r, &assertions, Verdict::Pass).unwrap_err();
573 assert!(err.contains("store_commit_valid"), "got: {err}");
574 assert!(err.contains("store-v1-format"), "got: {err}");
575 assert!(build_receipt(&r, assertions, Verdict::Pass).is_err());
576 }
577
578 #[test]
579 fn store_empty_source_refused() {
580 let r = store_req("store-v1-format", "QEMU");
581 let mut assertions = format_assertions();
582 assertions[0].source.clear();
583 let err = validate_store_profile(&r, &assertions, Verdict::Pass).unwrap_err();
584 assert!(err.contains("source"), "got: {err}");
585 assert!(err.contains("store_format_valid"), "got: {err}");
586 assert!(build_receipt(&r, assertions, Verdict::Pass).is_err());
587 }
588
589 #[test]
590 fn store_host_machine1_tier_refused() {
591 let r = store_req("store-v1-host", "MACHINE1_ATTENDED");
592 let assertions = host_assertions();
593 let err = validate_store_profile(&r, &assertions, Verdict::Pass).unwrap_err();
594 assert!(err.contains("MACHINE1_ATTENDED"), "got: {err}");
595 assert!(build_receipt(&r, assertions, Verdict::Pass).is_err());
596 }
597
598 #[test]
599 fn store_destructive_mutation_refused() {
600 let mut r = store_req("store-v1-format", "QEMU");
601 r.declared_mutation = Some("DESTRUCTIVE_STORAGE".to_string());
602 let assertions = format_assertions();
603 let err = validate_store_profile(&r, &assertions, Verdict::Pass).unwrap_err();
604 assert!(err.contains("DESTRUCTIVE_STORAGE"), "got: {err}");
605 assert!(build_receipt(&r, assertions, Verdict::Pass).is_err());
606 }
607
608 #[test]
609 fn store_future_unknown_subkind_has_no_required_set() {
610 assert!(store_required_assertions("store-v1-future").is_none());
611 let r = store_req("store-v1-future", "QEMU");
612 let assertions = vec![store_assertion("store_future_check")];
613 validate_store_profile(&r, &assertions, Verdict::Pass).unwrap();
614 let receipt = build_receipt(&r, assertions, Verdict::Pass).unwrap();
615 assert_eq!(receipt.kind, "store-v1-future");
616 let mut bad = store_req("store-v1-future", "QEMU");
617 bad.procedure = "TBD".to_string();
618 let assertions = vec![store_assertion("store_future_check")];
619 assert!(build_receipt(&bad, assertions, Verdict::Pass).is_err());
620 }
621}