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 / tools / aien-test / src / why.rs

632 lines · 22664 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-test why GATE`: the evidence chain behind one gate, read from the
17//! receipts already in the evidence store (ADR 0028 Decision 8).
18//!
19//! The report is plain lines, one fact per line, starting at the gate and
20//! walking down its dependencies. Each gate gets one state:
21//!
22//! - PASS: the newest receipt for this commit says PASS and everything the
23//! gate depends on is PASS too.
24//! - FAILED: the newest receipt for this commit says FAIL.
25//! - BLOCKED: hardware or an operator step is missing.
26//! - MISSING IMPLEMENTATION: the gate has no `run.exec` to run.
27//! - NEEDS RERUN: no receipt for this commit, a NOT_RUN receipt, or a PASS
28//! that rests on a dependency which is not PASS.
29//! - STALE: there are receipts, but only for other commits.
30//!
31//! What this checks, and says so in its output: that a receipt exists, what
32//! its verdict is, and whether it was made at the current commit. Since Slice
33//! C it also says, per gate, what the digest cache would do now: reuse an
34//! earlier receipt, or run again and which of the manifest, program, inputs,
35//! machine or dependencies changed (`crate::cache::explain_chain`).
36
37use crate::evidence::{Index, Stored};
38use crate::graph::Graph;
39use crate::manifest;
40use crate::verdict::Verdict;
41use std::collections::{BTreeMap, BTreeSet};
42use std::fs;
43use std::path::Path;
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum State {
47 Pass,
48 Failed,
49 Blocked,
50 MissingImplementation,
51 NeedsRerun,
52 Stale,
53}
54
55impl State {
56 pub fn label(self) -> &'static str {
57 match self {
58 State::Pass => "PASS",
59 State::Failed => "FAILED",
60 State::Blocked => "BLOCKED",
61 State::MissingImplementation => "MISSING IMPLEMENTATION",
62 State::NeedsRerun => "NEEDS RERUN",
63 State::Stale => "STALE",
64 }
65 }
66}
67
68/// What the store holds for one gate.
69enum Evidence<'a> {
70 /// Newest receipt made at the current commit.
71 Current(&'a Stored),
72 /// No receipt for this commit; the newest one for any other commit.
73 Other(&'a Stored),
74 Absent,
75}
76
77fn evidence<'a>(index: &'a Index, commit: &str, gate: &str) -> Evidence<'a> {
78 if let Some(r) = index.latest_at(gate, commit) {
79 return Evidence::Current(r);
80 }
81 match index.latest(gate) {
82 Some(r) => Evidence::Other(r),
83 None => Evidence::Absent,
84 }
85}
86
87fn own_state(e: &Evidence<'_>) -> State {
88 match e {
89 Evidence::Current(r) => match r.verdict() {
90 Some(Verdict::Pass) => State::Pass,
91 Some(Verdict::Fail) => State::Failed,
92 Some(Verdict::BlockedHardware) | Some(Verdict::BlockedOperator) => State::Blocked,
93 Some(Verdict::MissingImplementation) => State::MissingImplementation,
94 Some(Verdict::NotRun) | None => State::NeedsRerun,
95 },
96 Evidence::Other(_) => State::Stale,
97 Evidence::Absent => State::NeedsRerun,
98 }
99}
100
101/// The first 12 characters, enough to recognise a digest or commit.
102fn short(s: &str) -> String {
103 s.chars().take(12).collect()
104}
105
106fn last_observation(r: &Stored, name: &str) -> Option<String> {
107 let all = r.value["core"]["observations"].as_array()?;
108 all.iter()
109 .rev()
110 .find(|o| o["name"] == name)
111 .map(|o| o["value"].to_string())
112}
113
114/// For a FAIL receipt: the first expectation rule that did not hold, with the
115/// value the test reported for it.
116fn failing_rule_fact(r: &Stored) -> Option<String> {
117 let rules = r.value["core"]["rules"].as_array()?;
118 let first = rules.iter().find(|x| x["held"] == false)?;
119 let text = first["rule"].as_str()?;
120 let seen = manifest::parse_rule(text)
121 .ok()
122 .and_then(|rule| last_observation(r, &rule.name));
123 Some(match seen {
124 Some(v) => format!("first rule that did not hold: {text} (observed {v})"),
125 None => format!("first rule that did not hold: {text} (no such observation)"),
126 })
127}
128
129fn receipt_facts(r: &Stored) -> Vec<String> {
130 let verdict = r.verdict().map_or("UNKNOWN", |v| v.as_str());
131 let mut facts = Vec::new();
132 if r.reason().is_empty() {
133 facts.push(format!(
134 "receipt {} for this commit: {verdict}",
135 short(&r.digest)
136 ));
137 } else {
138 facts.push(format!(
139 "receipt {} for this commit: {verdict}, reason {}",
140 short(&r.digest),
141 r.reason()
142 ));
143 }
144 if r.verdict() == Some(Verdict::Fail) {
145 match r.reason() {
146 "rc_nonzero" => {
147 if let Some(code) = r.value["core"]["exit_status"].as_i64() {
148 facts.push(format!("the program exited with status {code}"));
149 }
150 }
151 "timeout" => facts.push("the run hit its time limit and was stopped".to_string()),
152 "prepare_failed" => facts.push(
153 "the prepare step (the build before the run) failed, so the gate never ran"
154 .to_string(),
155 ),
156 _ => {}
157 }
158 if let Some(f) = failing_rule_fact(r) {
159 facts.push(f);
160 }
161 }
162 let exceeded = r.value["volatile"]["timeout_exceeded"] == true;
163 if exceeded && r.value["volatile"]["pool"] == "gb10" && r.reason() != "timeout" {
164 facts.push(
165 "ran past its time limit; gb10 jobs are never killed, so it was left to finish"
166 .to_string(),
167 );
168 }
169 if r.value["core"]["tree_clean_before"] == false {
170 facts.push("the working tree had uncommitted changes when it ran".to_string());
171 }
172 facts
173}
174
175struct Report<'a> {
176 graph: &'a Graph,
177 index: &'a Index,
178 commit: &'a str,
179 /// The state of every gate in the chain, dependencies included.
180 states: BTreeMap<usize, State>,
181 shown: BTreeSet<usize>,
182 lines: Vec<String>,
183 /// Plain lines about the digest cache, per gate.
184 cache: &'a BTreeMap<usize, Vec<String>>,
185}
186
187impl Report<'_> {
188 fn state(&self, i: usize) -> State {
189 self.states.get(&i).copied().unwrap_or(State::NeedsRerun)
190 }
191
192 fn facts(&self, i: usize) -> Vec<String> {
193 let node = self.graph.node(i);
194 let ev = evidence(self.index, self.commit, &node.id);
195 let mut facts = match &ev {
196 Evidence::Current(r) => receipt_facts(r),
197 Evidence::Other(r) => vec![format!(
198 "newest receipt {} is for commit {}, not the current commit {}",
199 short(&r.digest),
200 short(r.commit()),
201 short(self.commit)
202 )],
203 Evidence::Absent => vec!["no receipt in the evidence store".to_string()],
204 };
205 if let Some(c) = self
206 .graph
207 .index_of(&node.id)
208 .and_then(|i| self.cache.get(&i))
209 {
210 facts.extend(c.iter().cloned());
211 }
212 if own_state(&ev) == State::Pass {
213 for &d in &node.deps {
214 if self.state(d) != State::Pass {
215 facts.push(format!(
216 "rests on {}, which is {}",
217 self.graph.node(d).id,
218 self.state(d).label()
219 ));
220 }
221 }
222 }
223 facts
224 }
225
226 fn render(&mut self, i: usize, depth: usize) {
227 let pad = " ".repeat(depth);
228 let id = self.graph.node(i).id.clone();
229 let label = self.state(i).label();
230 if !self.shown.insert(i) {
231 self.lines.push(format!("{pad}{id}: {label} (shown above)"));
232 return;
233 }
234 self.lines.push(format!("{pad}{id}: {label}"));
235 for fact in self.facts(i) {
236 self.lines.push(format!("{pad} - {fact}"));
237 }
238 let deps = self.graph.node(i).deps.clone();
239 for d in deps {
240 self.render(d, depth + 1);
241 }
242 }
243}
244
245/// The state of every gate `target` rests on, and of `target` itself: a gate
246/// whose own receipt is PASS still counts as needing a rerun when something it
247/// depends on is not PASS.
248pub fn states(graph: &Graph, index: &Index, commit: &str, target: usize) -> BTreeMap<usize, State> {
249 let chain = graph.with_dependencies(&[target]);
250 let mut out: BTreeMap<usize, State> = BTreeMap::new();
251 // Dependencies come before the gates that need them in this order.
252 for &i in graph.order() {
253 if !chain.contains(&i) {
254 continue;
255 }
256 let node = graph.node(i);
257 let own = own_state(&evidence(index, commit, &node.id));
258 let deps_pass = node.deps.iter().all(|d| out.get(d) == Some(&State::Pass));
259 let state = if own == State::Pass && !deps_pass {
260 State::NeedsRerun
261 } else {
262 own
263 };
264 out.insert(i, state);
265 }
266 out
267}
268
269/// The full report for `target` at `commit`, as lines to print.
270pub fn explain(
271 graph: &Graph,
272 index: &Index,
273 commit: &str,
274 target: usize,
275 cache: &BTreeMap<usize, Vec<String>>,
276) -> Vec<String> {
277 let mut report = Report {
278 graph,
279 index,
280 commit,
281 states: states(graph, index, commit, target),
282 shown: BTreeSet::new(),
283 lines: Vec::new(),
284 cache,
285 };
286 report.lines.push(format!(
287 "why {} at commit {}",
288 graph.node(target).id,
289 short(commit)
290 ));
291 report.render(target, 0);
292 report.lines.push(
293 "checked: whether a receipt exists, its verdict, and whether it is for the current commit"
294 .to_string(),
295 );
296 report.lines.push(
297 "cache: a result is reused only when the manifest, program, declared inputs, machine and dependency receipts all have the same digests as an earlier fresh run; anything else, a dirty tree, or --no-cache runs the gate"
298 .to_string(),
299 );
300 report.lines
301}
302
303/// Find the gate a user means by `name`: a gate id, or the path of a `.gate`
304/// file (relative to `cwd`) whose gate id is in the graph.
305pub fn resolve_target(graph: &Graph, cwd: &Path, name: &str) -> Result<usize, String> {
306 if let Some(i) = graph.index_of(name) {
307 return Ok(i);
308 }
309 let path = cwd.join(name);
310 if path.is_file() {
311 let bytes = fs::read(&path).map_err(|e| format!("cannot read {name}: {e}"))?;
312 let m = manifest::parse(&bytes).map_err(|e| e.0)?;
313 return graph.index_of(&m.gate).ok_or_else(|| {
314 format!(
315 "gate {} in {name} is not part of this repository's gate graph",
316 m.gate
317 )
318 });
319 }
320 Err(format!("no gate named {name}"))
321}
322
323/// The state of `target` alone, for callers that only need the verdict word.
324pub fn state_of(graph: &Graph, index: &Index, commit: &str, target: usize) -> State {
325 states(graph, index, commit, target)
326 .get(&target)
327 .copied()
328 .unwrap_or(State::NeedsRerun)
329}
330
331#[cfg(test)]
332mod tests {
333 use super::*;
334 use crate::evidence::{build_receipt, Store};
335 use crate::graph;
336 use crate::testutil::{write_file, TempDir};
337 use serde_json::json;
338 use std::path::PathBuf;
339
340 const X: &str = "1111111111111111111111111111111111111111";
341 const Y: &str = "2222222222222222222222222222222222222222";
342
343 fn gate_text(id: &str, deps: &[&str]) -> String {
344 let dep_block = if deps.is_empty() {
345 String::new()
346 } else {
347 format!(
348 "depends_on:\n{}",
349 deps.iter()
350 .map(|d| format!(" - {d}\n"))
351 .collect::<String>()
352 )
353 };
354 format!(
355 "gate: {id}\nmanifest_version: 1\nowner: o\nrequires:\n - host\nrun:\n exec: x.sh\nexpects:\n exit: 0\n observe: []\n verdict: PASS\ntimeout: 5s\n{dep_block}"
356 )
357 }
358
359 fn graph_of(spec: &[(&str, &[&str])]) -> Graph {
360 let entries = spec
361 .iter()
362 .map(|(id, deps)| {
363 (
364 PathBuf::from(format!("tests/{id}.gate")),
365 manifest::parse(gate_text(id, deps).as_bytes()).unwrap(),
366 )
367 })
368 .collect();
369 graph::build(entries).unwrap()
370 }
371
372 /// Write one receipt; `finished` orders receipts of the same gate.
373 fn put(store: &Store, gate: &str, commit: &str, verdict: &str, reason: &str, finished: &str) {
374 let r = build_receipt(
375 json!({
376 "gate": gate,
377 "commit": commit,
378 "derived_verdict": verdict,
379 "reason": reason,
380 "exit_status": null,
381 "observations": [],
382 "rules": [],
383 "tree_clean_before": true,
384 "dependencies": [],
385 }),
386 json!({ "finished_utc": finished, "pool": "host", "timeout_exceeded": false }),
387 );
388 store.put_receipt(&r).unwrap();
389 }
390
391 fn pass(store: &Store, gate: &str, commit: &str) {
392 put(store, gate, commit, "PASS", "", "2026-10-02T10:00:00Z");
393 }
394
395 fn text(lines: &[String]) -> String {
396 lines.join("\n")
397 }
398
399 fn id(g: &Graph, name: &str) -> usize {
400 g.index_of(name).unwrap()
401 }
402
403 #[test]
404 fn a_chain_shows_each_gate_with_its_state() {
405 let g = graph_of(&[("G-A", &[]), ("G-B", &["G-A"]), ("G-C", &["G-B"])]);
406 let ev = TempDir::new("why1");
407 let store = Store::new(ev.path());
408 pass(&store, "G-A", X);
409 let r = build_receipt(
410 json!({
411 "gate": "G-B", "commit": X, "derived_verdict": "FAIL", "reason": "rc_nonzero",
412 "exit_status": 2,
413 "observations": [{ "name": "n", "value": 4 }],
414 "rules": [{ "rule": "n == 3", "held": false }],
415 "tree_clean_before": true, "dependencies": [],
416 }),
417 json!({ "finished_utc": "2026-10-02T10:00:01Z", "pool": "host", "timeout_exceeded": false }),
418 );
419 store.put_receipt(&r).unwrap();
420 let index = Index::load(&store);
421 let out = text(&explain(&g, &index, X, id(&g, "G-C"), &BTreeMap::new()));
422 assert!(out.contains("G-C: NEEDS RERUN"), "{out}");
423 assert!(out.contains("no receipt in the evidence store"), "{out}");
424 assert!(out.contains("G-B: FAILED"), "{out}");
425 assert!(out.contains("the program exited with status 2"), "{out}");
426 assert!(
427 out.contains("first rule that did not hold: n == 3 (observed 4)"),
428 "{out}"
429 );
430 assert!(out.contains("G-A: PASS"), "{out}");
431 // The tree reads top down: C, then B, then A.
432 let (c, b, a) = (
433 out.find("G-C:").unwrap(),
434 out.find("G-B:").unwrap(),
435 out.find("G-A:").unwrap(),
436 );
437 assert!(c < b && b < a, "{out}");
438 }
439
440 #[test]
441 fn receipts_for_other_commits_are_stale() {
442 let g = graph_of(&[("G-A", &[])]);
443 let ev = TempDir::new("why2");
444 let store = Store::new(ev.path());
445 pass(&store, "G-A", Y);
446 let index = Index::load(&store);
447 assert_eq!(state_of(&g, &index, X, 0), State::Stale);
448 let out = text(&explain(&g, &index, X, 0, &BTreeMap::new()));
449 assert!(out.contains("G-A: STALE"), "{out}");
450 assert!(out.contains("is for commit 222222222222"), "{out}");
451 assert_eq!(state_of(&g, &index, Y, 0), State::Pass);
452 }
453
454 #[test]
455 fn a_pass_resting_on_a_failure_needs_a_rerun() {
456 let g = graph_of(&[("G-A", &[]), ("G-B", &["G-A"])]);
457 let ev = TempDir::new("why3");
458 let store = Store::new(ev.path());
459 put(
460 &store,
461 "G-A",
462 X,
463 "FAIL",
464 "rc_nonzero",
465 "2026-10-02T10:00:00Z",
466 );
467 pass(&store, "G-B", X);
468 let index = Index::load(&store);
469 assert_eq!(state_of(&g, &index, X, id(&g, "G-B")), State::NeedsRerun);
470 let out = text(&explain(&g, &index, X, id(&g, "G-B"), &BTreeMap::new()));
471 assert!(out.contains("rests on G-A, which is FAILED"), "{out}");
472 }
473
474 #[test]
475 fn blocked_and_missing_implementation_have_their_own_states() {
476 let g = graph_of(&[("G-A", &[]), ("G-B", &[]), ("G-C", &[])]);
477 let ev = TempDir::new("why4");
478 let store = Store::new(ev.path());
479 put(
480 &store,
481 "G-A",
482 X,
483 "BLOCKED_HARDWARE",
484 "NO_GB10",
485 "2026-10-02T10:00:00Z",
486 );
487 put(
488 &store,
489 "G-B",
490 X,
491 "MISSING_IMPLEMENTATION",
492 "NO_RUN_EXEC",
493 "2026-10-02T10:00:00Z",
494 );
495 put(
496 &store,
497 "G-C",
498 X,
499 "NOT_RUN",
500 "dirty_tree",
501 "2026-10-02T10:00:00Z",
502 );
503 let index = Index::load(&store);
504 assert_eq!(state_of(&g, &index, X, id(&g, "G-A")), State::Blocked);
505 assert_eq!(
506 state_of(&g, &index, X, id(&g, "G-B")),
507 State::MissingImplementation
508 );
509 assert_eq!(state_of(&g, &index, X, id(&g, "G-C")), State::NeedsRerun);
510 let out = text(&explain(&g, &index, X, id(&g, "G-A"), &BTreeMap::new()));
511 assert!(out.contains("BLOCKED_HARDWARE, reason NO_GB10"), "{out}");
512 }
513
514 #[test]
515 fn the_newest_receipt_for_the_commit_wins() {
516 let g = graph_of(&[("G-A", &[])]);
517 let ev = TempDir::new("why5");
518 let store = Store::new(ev.path());
519 put(
520 &store,
521 "G-A",
522 X,
523 "FAIL",
524 "rc_nonzero",
525 "2026-10-02T10:00:00Z",
526 );
527 put(&store, "G-A", X, "PASS", "", "2026-10-02T11:00:00Z");
528 let index = Index::load(&store);
529 assert_eq!(state_of(&g, &index, X, 0), State::Pass);
530 put(&store, "G-A", X, "FAIL", "timeout", "2026-10-02T12:00:00Z");
531 let index = Index::load(&store);
532 assert_eq!(state_of(&g, &index, X, 0), State::Failed);
533 }
534
535 #[test]
536 fn an_exceeded_gb10_timeout_is_reported() {
537 let g = graph_of(&[("G-A", &[])]);
538 let ev = TempDir::new("why6");
539 let store = Store::new(ev.path());
540 let r = build_receipt(
541 json!({
542 "gate": "G-A", "commit": X, "derived_verdict": "PASS", "reason": "",
543 "exit_status": 0, "observations": [], "rules": [],
544 "tree_clean_before": true, "dependencies": [],
545 }),
546 json!({ "finished_utc": "2026-10-02T10:00:00Z", "pool": "gb10", "timeout_exceeded": true }),
547 );
548 store.put_receipt(&r).unwrap();
549 let index = Index::load(&store);
550 let out = text(&explain(&g, &index, X, 0, &BTreeMap::new()));
551 assert!(out.contains("gb10 jobs are never killed"), "{out}");
552 assert!(out.contains("G-A: PASS"), "{out}");
553 }
554
555 #[test]
556 fn a_gate_reached_twice_is_expanded_once() {
557 let g = graph_of(&[
558 ("G-A", &[]),
559 ("G-B", &["G-A"]),
560 ("G-C", &["G-A"]),
561 ("G-D", &["G-B", "G-C"]),
562 ]);
563 let ev = TempDir::new("why7");
564 let store = Store::new(ev.path());
565 for gate in ["G-A", "G-B", "G-C", "G-D"] {
566 pass(&store, gate, X);
567 }
568 let index = Index::load(&store);
569 let lines = explain(&g, &index, X, id(&g, "G-D"), &BTreeMap::new());
570 let out = text(&lines);
571 assert_eq!(out.matches("G-A: PASS").count(), 2, "{out}");
572 assert_eq!(out.matches("(shown above)").count(), 1, "{out}");
573 assert_eq!(out.matches("for this commit: PASS").count(), 4, "{out}");
574 }
575
576 #[test]
577 fn the_report_says_what_it_checks_and_how_the_cache_decides() {
578 let g = graph_of(&[("G-A", &[])]);
579 let ev = TempDir::new("why8");
580 let index = Index::load(&Store::new(ev.path()));
581 let lines = explain(&g, &index, X, 0, &BTreeMap::new());
582 let out = text(&lines);
583 assert!(out.contains("checked: whether a receipt exists"), "{out}");
584 assert!(out.contains("cache: a result is reused only when"), "{out}");
585 assert!(!out.contains("Slice C"), "{out}");
586 assert!(lines[0].starts_with("why G-A at commit 111111111111"));
587 }
588
589 #[test]
590 fn a_gate_is_found_by_id_or_by_file() {
591 let g = graph_of(&[("G-A", &[]), ("G-B", &["G-A"])]);
592 let dir = TempDir::new("why10");
593 write_file(
594 dir.path(),
595 "tests/b.gate",
596 &gate_text("G-B", &["G-A"]),
597 false,
598 );
599 assert_eq!(resolve_target(&g, dir.path(), "G-B"), Ok(1));
600 assert_eq!(resolve_target(&g, dir.path(), "tests/b.gate"), Ok(1));
601 assert!(resolve_target(&g, dir.path(), "G-NOPE").is_err());
602 write_file(dir.path(), "tests/z.gate", &gate_text("G-Z", &[]), false);
603 let e = resolve_target(&g, dir.path(), "tests/z.gate").unwrap_err();
604 assert!(e.contains("not part of"), "{e}");
605 }
606
607 #[test]
608 fn short_never_splits_a_character() {
609 assert_eq!(short("abc"), "abc");
610 assert_eq!(short("0123456789abcdef"), "0123456789ab");
611 assert_eq!(short("ééééééééééééééé").chars().count(), 12);
612 }
613
614 #[test]
615 fn a_receipt_that_ran_on_a_dirty_tree_says_so() {
616 let g = graph_of(&[("G-A", &[])]);
617 let ev = TempDir::new("why9");
618 let store = Store::new(ev.path());
619 let r = build_receipt(
620 json!({
621 "gate": "G-A", "commit": X, "derived_verdict": "PASS", "reason": "",
622 "exit_status": 0, "observations": [], "rules": [],
623 "tree_clean_before": false, "dependencies": [],
624 }),
625 json!({ "finished_utc": "2026-10-02T10:00:00Z", "pool": "host", "timeout_exceeded": false }),
626 );
627 store.put_receipt(&r).unwrap();
628 let index = Index::load(&store);
629 let out = text(&explain(&g, &index, X, 0, &BTreeMap::new()));
630 assert!(out.contains("uncommitted changes"), "{out}");
631 }
632}