From 5c6a6e145531645c3da8ebf1dd1d99ae39e5245b Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Thu, 1 Oct 2026 23:10:18 -0500 Subject: [PATCH 1/2] Add tools/aien-test: AIEN-TEST Slice A (ADR 0028) New workspace member implementing the first slice of the AIEN-TEST runner: strict .gate manifest parser, closed six-value verdict set derived from observations and manifest expectations, canonical-JSON EvidenceReceiptV1 with content-addressed blobs and refuse-overwrite writes, a process runner that kills the whole process group on timeout, and a serial host-pool runner that pins the commit, refuses a dirty tree and hashes the binary. Also adds a mutation harness (mutations/run_mutants.sh, 16 mutants). Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DsjWa6csUe4NxndCTmugHu --- Cargo.lock | 9 + Cargo.toml | 1 + tools/aien-test/Cargo.toml | 20 + tools/aien-test/mutations/aien-test.mutants | 18 + tools/aien-test/mutations/run_mutants.sh | 70 ++ tools/aien-test/src/cli.rs | 112 +++ tools/aien-test/src/evidence.rs | 369 ++++++++ tools/aien-test/src/lib.rs | 15 + tools/aien-test/src/main.rs | 92 ++ tools/aien-test/src/manifest.rs | 765 ++++++++++++++++ tools/aien-test/src/process.rs | 192 ++++ tools/aien-test/src/runner.rs | 946 ++++++++++++++++++++ tools/aien-test/src/testutil.rs | 87 ++ tools/aien-test/src/verdict.rs | 439 +++++++++ 14 files changed, 3135 insertions(+) create mode 100644 tools/aien-test/Cargo.toml create mode 100644 tools/aien-test/mutations/aien-test.mutants create mode 100755 tools/aien-test/mutations/run_mutants.sh create mode 100644 tools/aien-test/src/cli.rs create mode 100644 tools/aien-test/src/evidence.rs create mode 100644 tools/aien-test/src/lib.rs create mode 100644 tools/aien-test/src/main.rs create mode 100644 tools/aien-test/src/manifest.rs create mode 100644 tools/aien-test/src/process.rs create mode 100644 tools/aien-test/src/runner.rs create mode 100644 tools/aien-test/src/testutil.rs create mode 100644 tools/aien-test/src/verdict.rs diff --git a/Cargo.lock b/Cargo.lock index 48e3c5c9..9cbbe641 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -275,6 +275,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "aien-test" +version = "0.1.0" +dependencies = [ + "libc", + "serde_json", + "sha2 0.10.9", +] + [[package]] name = "android_system_properties" version = "0.1.6" diff --git a/Cargo.toml b/Cargo.toml index cff610c6..06bceb65 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -35,6 +35,7 @@ members = [ "crates/aien-campaign-verifier", "crates/aien-proof", "crates/crumbs", + "tools/aien-test", ] [workspace.package] diff --git a/tools/aien-test/Cargo.toml b/tools/aien-test/Cargo.toml new file mode 100644 index 00000000..90a07cb2 --- /dev/null +++ b/tools/aien-test/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "aien-test" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true +description = "AIEN-TEST Slice A: gate manifest parser, verdict derivation, immutable evidence receipts, host-pool serial runner (ADR 0028)" + +[dependencies] +libc = "0.2" +serde_json = "1.0" +sha2 = "0.10" + +[[bin]] +name = "aien-test" +path = "src/main.rs" + +[lib] +name = "aien_test" +path = "src/lib.rs" diff --git a/tools/aien-test/mutations/aien-test.mutants b/tools/aien-test/mutations/aien-test.mutants new file mode 100644 index 00000000..134fb2a3 --- /dev/null +++ b/tools/aien-test/mutations/aien-test.mutants @@ -0,0 +1,18 @@ +# Mutations of tools/aien-test/src/*.rs. Format: idfilesed expressionwhat it models. +# Each must be KILLED (a unit test fails) for run_mutants.sh to pass. +dirty_tree_not_refused runner.rs s#!before.is_empty() && !opts.allow_dirty#false# a dirty tree is no longer refused +timeout_not_enforced process.rs s#rx.recv_timeout(spec.timeout)#rx.recv().map_err(|_| mpsc::RecvTimeoutError::Disconnected)# the wall-clock timeout never fires +rule_mismatch_passes verdict.rs s#position(|r| !r.1)#position(|_r| false)# a failed expectation rule still yields PASS +receipt_overwrite_allowed evidence.rs s#opts.write(true).create_new(true).mode(0o444);#opts.write(true).create(true).truncate(true).mode(0o444);# an existing receipt can be overwritten +exit_status_ignored verdict.rs s#} else if f.exit_status != Some(m.expect_exit) {#} else if false {# a wrong exit status is not a failure +head_move_ignored runner.rs s#facts.head_moved = head_after != commit;#facts.head_moved = false;# HEAD moving during the run is not noticed +tree_change_ignored runner.rs s#facts.tree_changed_after = after != before;#facts.tree_changed_after = false;# a run that dirties the tree is not noticed +kill_leader_only process.rs s#libc::kill(-pid, sig);#libc::kill(pid, sig);# timeout kills the leader but not its process group +escape_hex_uppercase evidence.rs s#u{:04x}#u{:04X}# canonical encoding escapes control characters with upper-case hex +duplicate_key_allowed manifest.rs s#if entries.iter().any(|e| e.key == k) {#if false {# a repeated top-level key is accepted +unknown_key_allowed manifest.rs s#if !KNOWN.contains(&e.key.as_str()) {#if false {# an unknown top-level key is ignored +missing_exec_ignored verdict.rs s#if !exec_exists {#if false {# a missing run.exec is not MISSING_IMPLEMENTATION +last_value_becomes_first verdict.rs s#compare(rule.op, vals\[vals.len() - 1\], &rule.value)#compare(rule.op, vals[0], \&rule.value)# a repeated observation uses the first value, not the last +evidence_inside_not_refused runner.rs s#let evidence_inside = resolve(&opts.evidence_dir).starts_with(resolve(root));#let evidence_inside = false;# evidence may be written inside the tree under test +operator_gate_not_blocked verdict.rs s#if m.requires.iter().any(|r| r == "operator") {#if false {# a gate needing an operator runs anyway +timeout_checked_after_exit verdict.rs s#let (verdict, reason) = if f.timed_out {#let (verdict, reason) = if false {# a timed-out run is reported as rc_nonzero, not timeout diff --git a/tools/aien-test/mutations/run_mutants.sh b/tools/aien-test/mutations/run_mutants.sh new file mode 100755 index 00000000..a72f0451 --- /dev/null +++ b/tools/aien-test/mutations/run_mutants.sh @@ -0,0 +1,70 @@ +#!/bin/sh +# Prove the aien-test unit tests catch realistic faults. +# +# usage: tools/aien-test/mutations/run_mutants.sh +# +# Applies each line of aien-test.mutants (id TAB file TAB sed expression TAB +# what it models) to a scratch copy of the crate, runs `cargo test`, and +# expects a FAILED test (KILLED). Exit 0 only if every mutant is KILLED. A +# mutant whose sed changes nothing, or that does not compile, is BROKEN and +# fails the run. The real tree is never modified. +set -eu + +here=$(cd "$(dirname "$0")" && pwd) +crate=$(cd "$here/.." && pwd) +root=$(cd "$here/../../.." && pwd) +table="$here/aien-test.mutants" + +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT INT TERM +mkdir -p "$work/tools/aien-test" +(cd "$crate" && tar cf - --exclude=./target --exclude=./mutations .) | (cd "$work/tools/aien-test" && tar xf -) +cp "$root/Cargo.lock" "$work/Cargo.lock" +# Minimal workspace root: same [workspace.package] values, only this crate. +awk '/^members = \[/ { print "members = [\"tools/aien-test\"]"; skip = 1; next } + skip && /^\]/ { skip = 0; next } + !skip { print }' "$root/Cargo.toml" >"$work/Cargo.toml" + +export CARGO_TARGET_DIR="${MUTANT_TARGET_DIR:-$work/target}" +cargo=${CARGO:-cargo} +manifest="$work/tools/aien-test/Cargo.toml" + +# Sanity: the unmutated copy must pass, or every "kill" would be meaningless. +if ! $cargo test --offline --manifest-path "$manifest" >"$work/baseline.log" 2>&1; then + echo "BASELINE FAILED: the unmutated crate does not pass its own tests" + tail -n 30 "$work/baseline.log" + exit 1 +fi + +fail=0 +killed=0 +total=0 +tab=$(printf '\t') +while IFS="$tab" read -r id file expr what; do + case "$id" in '' | '#'*) continue ;; esac + total=$((total + 1)) + src="$work/tools/aien-test/src/$file" + cp "$crate/src/$file" "$src" + sed -i "$expr" "$src" + if cmp -s "$src" "$crate/src/$file"; then + echo "BROKEN $id: sed expression matched nothing" + fail=1 + continue + fi + log="$work/$id.log" + if $cargo test --offline --manifest-path "$manifest" >"$log" 2>&1; then + echo "SURVIVED $id ($what)" + fail=1 + elif grep -q "test result: FAILED" "$log"; then + echo "KILLED $id ($what)" + killed=$((killed + 1)) + else + echo "BROKEN $id: did not compile" + tail -n 20 "$log" + fail=1 + fi + cp "$crate/src/$file" "$src" +done <"$table" + +echo "killed=$killed total=$total" +exit "$fail" diff --git a/tools/aien-test/src/cli.rs b/tools/aien-test/src/cli.rs new file mode 100644 index 00000000..270ea2fe --- /dev/null +++ b/tools/aien-test/src/cli.rs @@ -0,0 +1,112 @@ +//! Argument parsing for `aien-test run GATE_FILE_OR_NAME [flags] [-- args]`. +//! Hand-written; the surface is small (ADR 0028 Decision 1 and 8). + +use std::path::PathBuf; + +pub const USAGE: &str = + "usage: aien-test run GATE_FILE_OR_NAME [--evidence-dir DIR] [--allow-dirty] [-- ARGS...]"; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Cli { + pub gate: String, + pub evidence_dir: Option, + pub allow_dirty: bool, + /// Arguments after `--`; they replace `run.args` (CR-061). + pub args: Option>, +} + +pub fn parse_args(argv: &[String]) -> Result { + match argv.first().map(|s| s.as_str()) { + Some("run") => {} + Some(other) => return Err(format!("unknown command {other:?}")), + None => return Err("no command".to_string()), + } + let mut gate: Option = None; + let mut evidence_dir: Option = None; + let mut allow_dirty = false; + let mut args: Option> = None; + let mut i = 1; + while i < argv.len() { + let a = argv[i].as_str(); + if a == "--" { + args = Some(argv[i + 1..].to_vec()); + break; + } else if a == "--evidence-dir" { + i += 1; + match argv.get(i) { + Some(v) => evidence_dir = Some(PathBuf::from(v)), + None => return Err("--evidence-dir needs a value".to_string()), + } + } else if a == "--allow-dirty" { + allow_dirty = true; + } else if a.starts_with('-') { + return Err(format!("unknown argument {a:?}")); + } else if gate.is_none() { + gate = Some(a.to_string()); + } else { + return Err(format!("unexpected argument {a:?}")); + } + i += 1; + } + match gate { + Some(gate) => Ok(Cli { + gate, + evidence_dir, + allow_dirty, + args, + }), + None => Err("missing GATE_FILE_OR_NAME".to_string()), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn v(a: &[&str]) -> Vec { + a.iter().map(|s| s.to_string()).collect() + } + + #[test] + fn minimal() { + let c = parse_args(&v(&["run", "G"])).unwrap(); + assert_eq!(c.gate, "G"); + assert!(!c.allow_dirty); + assert_eq!(c.args, None); + assert_eq!(c.evidence_dir, None); + } + + #[test] + fn full() { + let c = parse_args(&v(&[ + "run", + "--allow-dirty", + "G", + "--evidence-dir", + "/e", + "--", + "-x", + "y", + ])) + .unwrap(); + assert!(c.allow_dirty); + assert_eq!(c.evidence_dir, Some(PathBuf::from("/e"))); + assert_eq!(c.args, Some(v(&["-x", "y"]))); + } + + #[test] + fn empty_override_args_are_kept() { + let c = parse_args(&v(&["run", "G", "--"])).unwrap(); + assert_eq!(c.args, Some(Vec::new())); + } + + #[test] + fn errors() { + assert!(parse_args(&[]).is_err()); + assert!(parse_args(&v(&["test", "G"])).is_err()); + assert!(parse_args(&v(&["run"])).is_err()); + assert!(parse_args(&v(&["run", "G", "H"])).is_err()); + assert!(parse_args(&v(&["run", "G", "--bogus"])).is_err()); + assert!(parse_args(&v(&["run", "G", "--evidence-dir"])).is_err()); + } +} diff --git a/tools/aien-test/src/evidence.rs b/tools/aien-test/src/evidence.rs new file mode 100644 index 00000000..f89a0b78 --- /dev/null +++ b/tools/aien-test/src/evidence.rs @@ -0,0 +1,369 @@ +//! EvidenceReceiptV1 (ADR 0028 Decision 4): canonical JSON, sha256 digest, +//! content-addressed stdout/stderr blobs, immutable write (never overwrite). + +use serde_json::{json, Value}; +use sha2::{Digest, Sha256}; +use std::fmt; +use std::fs; +use std::io::{ErrorKind, Write}; +use std::os::unix::fs::OpenOptionsExt; +use std::path::{Path, PathBuf}; + +pub const SCHEMA: &str = "aien-test/EvidenceReceiptV1"; + +pub fn sha256_hex(bytes: &[u8]) -> String { + let mut h = Sha256::new(); + h.update(bytes); + let digest = h.finalize(); + let mut s = String::with_capacity(64); + for b in digest.iter() { + s.push_str(&format!("{b:02x}")); + } + s +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum StoreError { + /// A float or other value that canonical encoding forbids (C3). + Canon(String), + Io(String), + /// A file already exists at the content address with different bytes. + Collision(String), + /// Bytes read back after writing did not match their digest. + Verify(String), +} + +impl fmt::Display for StoreError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + StoreError::Canon(s) => write!(f, "canonical encoding error: {s}"), + StoreError::Io(s) => write!(f, "io error: {s}"), + StoreError::Collision(s) => write!(f, "evidence collision: {s}"), + StoreError::Verify(s) => write!(f, "evidence verify failed: {s}"), + } + } +} + +fn io_err(what: &str, e: std::io::Error) -> StoreError { + StoreError::Io(format!("{what}: {e}")) +} + +fn write_str(s: &str, out: &mut Vec) { + out.push(b'"'); + for c in s.chars() { + match c { + '"' => out.extend_from_slice(b"\\\""), + '\\' => out.extend_from_slice(b"\\\\"), + '\n' => out.extend_from_slice(b"\\n"), + '\r' => out.extend_from_slice(b"\\r"), + '\t' => out.extend_from_slice(b"\\t"), + c if (c as u32) < 0x20 => { + out.extend_from_slice(format!("\\u{:04x}", c as u32).as_bytes()) + } + c => { + let mut buf = [0u8; 4]; + out.extend_from_slice(c.encode_utf8(&mut buf).as_bytes()); + } + } + } + out.push(b'"'); +} + +fn write_value(v: &Value, out: &mut Vec) -> Result<(), StoreError> { + match v { + Value::Null => out.extend_from_slice(b"null"), + Value::Bool(true) => out.extend_from_slice(b"true"), + Value::Bool(false) => out.extend_from_slice(b"false"), + Value::Number(n) => { + if let Some(i) = n.as_i64() { + out.extend_from_slice(i.to_string().as_bytes()); + } else if let Some(u) = n.as_u64() { + out.extend_from_slice(u.to_string().as_bytes()); + } else { + return Err(StoreError::Canon(format!( + "floating point not allowed: {n}" + ))); + } + } + Value::String(s) => write_str(s, out), + Value::Array(a) => { + out.push(b'['); + for (i, x) in a.iter().enumerate() { + if i > 0 { + out.push(b','); + } + write_value(x, out)?; + } + out.push(b']'); + } + Value::Object(m) => { + let mut keys: Vec<&String> = m.keys().collect(); + keys.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + out.push(b'{'); + for (i, k) in keys.iter().enumerate() { + if i > 0 { + out.push(b','); + } + write_str(k, out); + out.push(b':'); + write_value(&m[k.as_str()], out)?; + } + out.push(b'}'); + } + } + Ok(()) +} + +/// Canonical bytes (C1 to C5): sorted keys, integers only, minimal escapes. +pub fn canonical(v: &Value) -> Result, StoreError> { + let mut out = Vec::new(); + write_value(v, &mut out)?; + Ok(out) +} + +pub fn canonical_digest(v: &Value) -> Result { + Ok(sha256_hex(&canonical(v)?)) +} + +pub fn build_receipt(core: Value, volatile: Value) -> Value { + json!({ "schema": SCHEMA, "core": core, "volatile": volatile }) +} + +pub struct Store { + dir: PathBuf, +} + +impl Store { + pub fn new(dir: &Path) -> Store { + Store { + dir: dir.to_path_buf(), + } + } + + pub fn dir(&self) -> &Path { + &self.dir + } + + /// Store a blob at `blobs/.log` via temp file and rename, then + /// re-verify. An existing blob with the same digest is success; an + /// existing file with other bytes is a collision. + pub fn put_blob(&self, bytes: &[u8]) -> Result { + let sha = sha256_hex(bytes); + let blobs = self.dir.join("blobs"); + fs::create_dir_all(&blobs).map_err(|e| io_err("create blobs dir", e))?; + let path = blobs.join(format!("{sha}.log")); + if path.exists() { + let existing = fs::read(&path).map_err(|e| io_err("read blob", e))?; + if sha256_hex(&existing) != sha { + return Err(StoreError::Collision(format!( + "blob {sha} exists with other bytes" + ))); + } + return Ok(sha); + } + let tmp = blobs.join(format!(".tmp-{sha}-{}", std::process::id())); + { + let mut f = fs::OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o444) + .open(&tmp) + .map_err(|e| io_err("create blob temp", e))?; + f.write_all(bytes).map_err(|e| io_err("write blob", e))?; + f.sync_all().map_err(|e| io_err("sync blob", e))?; + } + fs::rename(&tmp, &path).map_err(|e| io_err("rename blob", e))?; + let back = fs::read(&path).map_err(|e| io_err("read back blob", e))?; + if sha256_hex(&back) != sha { + return Err(StoreError::Verify(format!( + "blob {sha} digest mismatch after write" + ))); + } + Ok(sha) + } + + /// Write `.json` exclusively, mode 0444, canonical bytes plus one + /// LF. Identical existing content is success; different content is a + /// fatal collision. Never overwrites. + pub fn put_receipt(&self, receipt: &Value) -> Result<(String, PathBuf), StoreError> { + let bytes = canonical(receipt)?; + let digest = sha256_hex(&bytes); + fs::create_dir_all(&self.dir).map_err(|e| io_err("create evidence dir", e))?; + let path = self.dir.join(format!("{digest}.json")); + let mut want = bytes; + want.push(b'\n'); + let mut opts = fs::OpenOptions::new(); + opts.write(true).create_new(true).mode(0o444); + match opts.open(&path) { + Ok(mut f) => { + f.write_all(&want).map_err(|e| io_err("write receipt", e))?; + f.sync_all().map_err(|e| io_err("sync receipt", e))?; + } + Err(e) if e.kind() == ErrorKind::AlreadyExists => { + let existing = fs::read(&path).map_err(|e| io_err("read existing receipt", e))?; + if existing != want { + return Err(StoreError::Collision(format!( + "receipt {digest} exists with different bytes" + ))); + } + } + Err(e) => return Err(io_err("open receipt", e)), + } + let back = fs::read(&path).map_err(|e| io_err("read back receipt", e))?; + if back != want { + return Err(StoreError::Verify(format!( + "receipt {digest} differs after write" + ))); + } + Ok((digest, path)) + } +} + +/// Format seconds since the Unix epoch as `YYYY-MM-DDTHH:MM:SSZ`. +pub fn utc_string(secs: u64) -> String { + let days = (secs / 86_400) as i64; + let rem = secs % 86_400; + // Howard Hinnant's civil-from-days algorithm. + let z = days + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; + let y = yoe + era * 400; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let d = doy - (153 * mp + 2) / 5 + 1; + let m = if mp < 10 { mp + 3 } else { mp - 9 }; + let y = if m <= 2 { y + 1 } else { y }; + format!( + "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", + rem / 3600, + (rem % 3600) / 60, + rem % 60 + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::TempDir; + use std::os::unix::fs::PermissionsExt; + + #[test] + fn sha256_known_vectors() { + assert_eq!( + sha256_hex(b""), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + ); + assert_eq!( + sha256_hex(b"abc"), + "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" + ); + } + + #[test] + fn canonical_sorts_keys_and_is_compact() { + let v = json!({"b": [1, true, null], "a": {"z": "x", "y": -3}}); + assert_eq!( + String::from_utf8(canonical(&v).unwrap()).unwrap(), + r#"{"a":{"y":-3,"z":"x"},"b":[1,true,null]}"# + ); + } + + #[test] + fn canonical_escapes_per_c4() { + let v = json!("a\"b\\c\nd\r\te\u{1f}f\u{7f}\u{e9}"); + let s = String::from_utf8(canonical(&v).unwrap()).unwrap(); + assert_eq!(s, "\"a\\\"b\\\\c\\nd\\r\\te\\u001ff\u{7f}\u{e9}\""); + } + + #[test] + fn canonical_rejects_floats() { + assert!(canonical(&json!({"x": 1.5})).is_err()); + assert!(canonical(&json!([0.0])).is_err()); + } + + #[test] + fn canonical_digest_is_stable_across_key_order() { + let a = json!({"x": 1, "y": 2}); + let b = json!({"y": 2, "x": 1}); + assert_eq!(canonical_digest(&a).unwrap(), canonical_digest(&b).unwrap()); + } + + #[test] + fn utc_formatting() { + assert_eq!(utc_string(0), "1970-01-01T00:00:00Z"); + assert_eq!(utc_string(1_700_000_000), "2023-11-14T22:13:20Z"); + assert_eq!(utc_string(951_782_400), "2000-02-29T00:00:00Z"); + } + + #[test] + fn receipt_roundtrip_mode_and_name() { + let t = TempDir::new("ev1"); + let store = Store::new(t.path()); + let r = build_receipt(json!({"gate": "G"}), json!({"duration_ms": 5})); + let (digest, path) = store.put_receipt(&r).unwrap(); + assert_eq!(path, t.path().join(format!("{digest}.json"))); + let bytes = fs::read(&path).unwrap(); + assert_eq!(*bytes.last().unwrap(), b'\n'); + assert_eq!(sha256_hex(&bytes[..bytes.len() - 1]), digest); + let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777; + assert_eq!(mode, 0o444); + let back: Value = serde_json::from_slice(&bytes).unwrap(); + assert_eq!(back["schema"], SCHEMA); + } + + #[test] + fn identical_receipt_twice_is_success() { + let t = TempDir::new("ev2"); + let store = Store::new(t.path()); + let r = build_receipt(json!({"gate": "G"}), json!({})); + let a = store.put_receipt(&r).unwrap(); + let b = store.put_receipt(&r).unwrap(); + assert_eq!(a, b); + } + + #[test] + fn receipt_overwrite_is_refused() { + let t = TempDir::new("ev3"); + let store = Store::new(t.path()); + let r = build_receipt(json!({"gate": "G"}), json!({})); + let (_, path) = store.put_receipt(&r).unwrap(); + // Tamper with the stored file, then try to write the same receipt again. + fs::set_permissions(&path, fs::Permissions::from_mode(0o644)).unwrap(); + fs::write(&path, b"tampered").unwrap(); + match store.put_receipt(&r) { + Err(StoreError::Collision(_)) => {} + other => panic!("expected collision, got {other:?}"), + } + assert_eq!(fs::read(&path).unwrap(), b"tampered"); + } + + #[test] + fn blob_is_content_addressed_and_idempotent() { + let t = TempDir::new("ev4"); + let store = Store::new(t.path()); + let sha = store.put_blob(b"hello\n").unwrap(); + assert_eq!(sha, sha256_hex(b"hello\n")); + let p = t.path().join("blobs").join(format!("{sha}.log")); + assert_eq!(fs::read(&p).unwrap(), b"hello\n"); + assert_eq!( + fs::metadata(&p).unwrap().permissions().mode() & 0o777, + 0o444 + ); + assert_eq!(store.put_blob(b"hello\n").unwrap(), sha); + } + + #[test] + fn blob_collision_detected() { + let t = TempDir::new("ev5"); + let store = Store::new(t.path()); + let sha = store.put_blob(b"hello\n").unwrap(); + let p = t.path().join("blobs").join(format!("{sha}.log")); + fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap(); + fs::write(&p, b"evil").unwrap(); + match store.put_blob(b"hello\n") { + Err(StoreError::Collision(_)) => {} + other => panic!("expected collision, got {other:?}"), + } + } +} diff --git a/tools/aien-test/src/lib.rs b/tools/aien-test/src/lib.rs new file mode 100644 index 00000000..955423af --- /dev/null +++ b/tools/aien-test/src/lib.rs @@ -0,0 +1,15 @@ +//! AIEN-TEST Slice A (ADR 0028): one gate, host pool, serial. +//! +//! Tests report observations; this crate derives the verdict and writes an +//! immutable, content-addressed receipt. See `manifest`, `verdict`, +//! `evidence`, `process`, `runner`. + +pub mod cli; +pub mod evidence; +pub mod manifest; +pub mod process; +pub mod runner; +pub mod verdict; + +#[cfg(test)] +pub mod testutil; diff --git a/tools/aien-test/src/main.rs b/tools/aien-test/src/main.rs new file mode 100644 index 00000000..6f1e775f --- /dev/null +++ b/tools/aien-test/src/main.rs @@ -0,0 +1,92 @@ +//! `aien-test run GATE_FILE_OR_NAME`: run one gate, print the verdict, exit +//! non-zero unless PASS (0 PASS, 1 FAIL or BAD_MANIFEST, 2 NOT_RUN or usage, +//! 3 BLOCKED_HARDWARE, 4 BLOCKED_OPERATOR, 5 MISSING_IMPLEMENTATION). + +use aien_test::cli::{parse_args, USAGE}; +use aien_test::runner::{self, Options, RunError}; +use aien_test::verdict::Verdict; +use std::path::PathBuf; + +fn main() { + std::process::exit(real_main()); +} + +fn real_main() -> i32 { + let argv: Vec = std::env::args().skip(1).collect(); + let cli = match parse_args(&argv) { + Ok(c) => c, + Err(e) => { + eprintln!("aien-test: {e}"); + eprintln!("{USAGE}"); + return 2; + } + }; + let cwd = match std::env::current_dir() { + Ok(d) => d, + Err(e) => { + eprintln!("aien-test: cannot read current directory: {e}"); + return 2; + } + }; + let manifest_path = match runner::locate_gate(&cwd, &cli.gate) { + Ok(p) => p, + Err(e) => { + println!("AIEN_TEST: BAD_MANIFEST {e}"); + return 1; + } + }; + let parent = manifest_path.parent().unwrap_or(&cwd).to_path_buf(); + let root = match runner::repo_root(&parent) { + Ok(r) => r, + Err(e) => { + println!("AIEN_TEST: FAIL {e}"); + return 1; + } + }; + let evidence_dir = match cli.evidence_dir { + Some(d) => d, + None => match std::env::var_os("HOME") { + Some(h) => { + let name = root + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_else(|| "repo".to_string()); + PathBuf::from(h) + .join("workspace") + .join("evidence-out") + .join(name) + } + None => { + eprintln!("aien-test: HOME is not set and no --evidence-dir given"); + return 2; + } + }, + }; + let mut opts = Options::new(evidence_dir); + opts.allow_dirty = cli.allow_dirty; + opts.args_override = cli.args; + match runner::run_gate(&root, &manifest_path, &opts) { + Ok(o) => { + if o.verdict == Verdict::NotRun && !o.reason.is_empty() { + println!("REFUSED: {}", o.reason); + } + if let Some(p) = &o.receipt_path { + println!("RECEIPT {}", p.display()); + } + if o.reason.is_empty() { + println!("AIEN_TEST: {}", o.verdict.as_str()); + } else { + println!("AIEN_TEST: {} {}", o.verdict.as_str(), o.reason); + } + o.verdict.exit_code() + } + Err(RunError::BadManifest(m)) => { + println!("AIEN_TEST: BAD_MANIFEST {m}"); + 1 + } + Err(RunError::Fatal(m)) => { + println!("AIEN_TEST: FAIL {m}"); + 1 + } + } +} diff --git a/tools/aien-test/src/manifest.rs b/tools/aien-test/src/manifest.rs new file mode 100644 index 00000000..0af65ad6 --- /dev/null +++ b/tools/aien-test/src/manifest.rs @@ -0,0 +1,765 @@ +//! Gate manifest v1 parser (ADR 0028 Decision 3). Strict: unknown keys, +//! duplicate keys, tabs, CRLF, BOM, deep indentation and trailing garbage are +//! all errors. +//! +//! Slice A deviation (recorded): the ADR's full example nests the `observe` +//! list one level deeper than the normative grammar allows. The grammar wins: +//! `observe` is a one-line JSON list, for example +//! ` observe: ["sqrt_max_ulp <= 1", "chip_verdict == \"PASS\""]`. +//! The `adapter` key is not part of Slice A and is rejected as unknown. + +use crate::evidence::sha256_hex; +use serde_json::Value; +use std::fmt; + +pub const MAX_LINES: usize = 200; +pub const MAX_BYTES: usize = 16 * 1024; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ManifestError(pub String); + +impl fmt::Display for ManifestError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +fn err(line: usize, msg: &str) -> Result { + Err(ManifestError(format!("line {line}: {msg}"))) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Op { + Eq, + Ne, + Lt, + Le, + Gt, + Ge, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Quant { + Last, + All, + Any, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Rule { + pub text: String, + pub quant: Quant, + pub name: String, + pub op: Op, + pub value: Value, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Build { + pub target: String, + pub tool: String, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Manifest { + pub gate: String, + pub owner: String, + pub requires: Vec, + pub depends_on: Vec, + pub inputs: Vec, + pub build: Option, + pub exec: String, + pub args: Vec, + pub expect_exit: i64, + pub rules: Vec, + pub timeout_ms: u64, + pub mutants: Vec, + pub checks: Vec, + pub cache_allowed: bool, + /// sha256 of the exact manifest file bytes (P7). + pub digest: String, +} + +impl Manifest { + /// The scarcest listed pool: gb10 > qemu > host. + pub fn pool(&self) -> &'static str { + if self.requires.iter().any(|r| r == "gb10") { + "gb10" + } else if self.requires.iter().any(|r| r == "qemu") { + "qemu" + } else { + "host" + } + } +} + +#[derive(Debug, Clone)] +enum Val { + Str(String), + List(Vec), +} + +struct Entry { + key: String, + line: usize, + scalar: Option, + items: Vec, + children: Vec<(String, Val, usize)>, +} + +pub fn valid_key(k: &str) -> bool { + let mut chars = k.chars(); + match chars.next() { + Some(c) if c.is_ascii_lowercase() => {} + _ => return false, + } + chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_') +} + +pub fn valid_gate_id(s: &str) -> bool { + !s.is_empty() + && s.len() <= 64 + && s.chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '.' || c == '-') +} + +/// Observation NAME: [a-z][a-z0-9_.-]* +pub fn valid_obs_name(s: &str) -> bool { + let mut chars = s.chars(); + match chars.next() { + Some(c) if c.is_ascii_lowercase() => {} + _ => return false, + } + chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '.' || c == '-') +} + +fn valid_rel_path(s: &str) -> bool { + !s.is_empty() && !s.starts_with('/') && !s.contains('\0') && !s.split('/').any(|c| c == "..") +} + +fn parse_val(s: &str, line: usize) -> Result { + if s.starts_with('"') { + let mut it = serde_json::Deserializer::from_str(s).into_iter::(); + let v = match it.next() { + Some(Ok(v)) => v, + _ => return err(line, "bad quoted string"), + }; + if !s[it.byte_offset()..].is_empty() { + return err(line, "trailing garbage after quoted string"); + } + return Ok(Val::Str(v)); + } + if s.starts_with('[') { + return match serde_json::from_str::>(s) { + Ok(v) => Ok(Val::List(v)), + Err(_) => err(line, "list must be a one-line JSON array of strings"), + }; + } + let cut = match s.find(" #") { + Some(i) => &s[..i], + None => s, + }; + let t = cut.trim_end(); + if t.is_empty() { + return err(line, "empty value"); + } + Ok(Val::Str(t.to_string())) +} + +/// Split `KEY: VALUE` (value optional). +fn split_key(s: &str, line: usize) -> Result<(String, Option), ManifestError> { + let i = match s.find(':') { + Some(i) => i, + None => return err(line, "expected KEY: or an item line"), + }; + let key = &s[..i]; + if !valid_key(key) { + return err(line, "invalid key"); + } + let rest = &s[i + 1..]; + if rest.is_empty() { + return Ok((key.to_string(), None)); + } + if !rest.starts_with(' ') { + return err(line, "space required after colon"); + } + let v = &rest[1..]; + if v.starts_with(' ') { + return err(line, "extra space after colon"); + } + Ok((key.to_string(), Some(parse_val(v, line)?))) +} + +fn parse_entries(text: &str) -> Result, ManifestError> { + let mut entries: Vec = Vec::new(); + for (i, raw) in text.lines().enumerate() { + let n = i + 1; + let raw = raw.trim_end_matches(' '); + let trimmed = raw.trim_start_matches(' '); + if trimmed.is_empty() || trimmed.starts_with('#') { + continue; + } + if let Some(rest) = raw.strip_prefix(" - ") { + if rest.starts_with(' ') { + return err(n, "extra space after dash"); + } + let v = match parse_val(rest, n)? { + Val::Str(s) => s, + Val::List(_) => return err(n, "list item must be a scalar"), + }; + match entries.last_mut() { + Some(e) => e.items.push(v), + None => return err(n, "item line before any key"), + } + } else if let Some(rest) = raw.strip_prefix(" ") { + if rest.starts_with(' ') { + return err(n, "indentation deeper than two spaces"); + } + let (k, v) = split_key(rest, n)?; + let v = match v { + Some(v) => v, + None => return err(n, "child key needs a value"), + }; + match entries.last_mut() { + Some(e) => { + if e.children.iter().any(|c| c.0 == k) { + return err(n, "duplicate child key"); + } + e.children.push((k, v, n)); + } + None => return err(n, "child line before any key"), + } + } else if raw.starts_with(' ') { + return err(n, "one-space indentation"); + } else { + let (k, v) = split_key(raw, n)?; + if entries.iter().any(|e| e.key == k) { + return err(n, &format!("duplicate key {k}")); + } + entries.push(Entry { + key: k, + line: n, + scalar: v, + items: Vec::new(), + children: Vec::new(), + }); + } + } + for e in &entries { + let shapes = (e.scalar.is_some() as u8) + + (!e.items.is_empty() as u8) + + (!e.children.is_empty() as u8); + if shapes > 1 { + return err(e.line, &format!("key {} mixes value shapes", e.key)); + } + } + Ok(entries) +} + +fn scalar(e: &Entry) -> Result { + match (&e.scalar, e.items.is_empty(), e.children.is_empty()) { + (Some(Val::Str(s)), true, true) => Ok(s.clone()), + _ => err(e.line, &format!("key {} needs a scalar value", e.key)), + } +} + +fn list(e: &Entry) -> Result, ManifestError> { + match (&e.scalar, e.children.is_empty()) { + (Some(Val::List(l)), true) if e.items.is_empty() => Ok(l.clone()), + (None, true) => Ok(e.items.clone()), + _ => err(e.line, &format!("key {} needs a list", e.key)), + } +} + +fn map<'a>(e: &'a Entry, allowed: &[&str]) -> Result<&'a Vec<(String, Val, usize)>, ManifestError> { + if e.scalar.is_some() || !e.items.is_empty() || e.children.is_empty() { + return err(e.line, &format!("key {} needs child keys", e.key)); + } + for (k, _, n) in &e.children { + if !allowed.contains(&k.as_str()) { + return err(*n, &format!("unknown child key {k} under {}", e.key)); + } + } + Ok(&e.children) +} + +fn child<'a>(c: &'a [(String, Val, usize)], k: &str) -> Option<&'a (String, Val, usize)> { + c.iter().find(|x| x.0 == k) +} + +fn child_str(c: &[(String, Val, usize)], k: &str) -> Result, ManifestError> { + match child(c, k) { + None => Ok(None), + Some((_, Val::Str(s), _)) => Ok(Some(s.clone())), + Some((_, Val::List(_), n)) => err(*n, &format!("{k} must be a scalar")), + } +} + +pub fn parse_duration_ms(s: &str) -> Option { + let (num, mult) = if let Some(n) = s.strip_suffix("ms") { + (n, 1u64) + } else if let Some(n) = s.strip_suffix('s') { + (n, 1000) + } else if let Some(n) = s.strip_suffix('m') { + (n, 60_000) + } else if let Some(n) = s.strip_suffix('h') { + (n, 3_600_000) + } else { + return None; + }; + if num.is_empty() || !num.chars().all(|c| c.is_ascii_digit()) { + return None; + } + let v: u64 = num.parse().ok()?; + if v == 0 { + return None; + } + v.checked_mul(mult) +} + +pub fn parse_rule(text: &str) -> Result { + let (quant, rest) = if let Some(r) = text.strip_prefix("all ") { + (Quant::All, r) + } else if let Some(r) = text.strip_prefix("any ") { + (Quant::Any, r) + } else { + (Quant::Last, text) + }; + let mut it = rest.splitn(3, ' '); + let name = it.next().unwrap_or(""); + let op = it.next().unwrap_or(""); + let val = it.next().unwrap_or(""); + if !valid_obs_name(name) { + return Err(format!("bad observation name in rule {text:?}")); + } + let op = match op { + "==" => Op::Eq, + "!=" => Op::Ne, + "<" => Op::Lt, + "<=" => Op::Le, + ">" => Op::Gt, + ">=" => Op::Ge, + _ => return Err(format!("bad operator in rule {text:?}")), + }; + let value = + parse_json_scalar(val.trim()).ok_or_else(|| format!("bad value in rule {text:?}"))?; + Ok(Rule { + text: text.to_string(), + quant, + name: name.to_string(), + op, + value, + }) +} + +/// JSON string, integer (no floats), true/false/null. +pub fn parse_json_scalar(s: &str) -> Option { + let v: Value = serde_json::from_str(s).ok()?; + let ok = match &v { + Value::String(_) | Value::Bool(_) | Value::Null => true, + Value::Number(n) => n.is_i64(), + _ => false, + }; + if ok { + Some(v) + } else { + None + } +} + +pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() > MAX_BYTES { + return Err(ManifestError("manifest larger than 16 KiB".into())); + } + if bytes.starts_with(&[0xEF, 0xBB, 0xBF]) { + return Err(ManifestError("BOM not allowed".into())); + } + let text = std::str::from_utf8(bytes) + .map_err(|_| ManifestError("manifest is not valid UTF-8".into()))?; + if text.contains('\r') { + return Err(ManifestError( + "CR not allowed (Unix line endings only)".into(), + )); + } + if text.contains('\t') { + return Err(ManifestError("tab not allowed".into())); + } + if text.lines().count() > MAX_LINES { + return Err(ManifestError("manifest longer than 200 lines".into())); + } + let entries = parse_entries(text)?; + + const KNOWN: [&str; 13] = [ + "gate", + "manifest_version", + "owner", + "requires", + "depends_on", + "inputs", + "build", + "run", + "expects", + "timeout", + "mutants", + "checks", + "cache", + ]; + for e in &entries { + if !KNOWN.contains(&e.key.as_str()) { + return err(e.line, &format!("unknown key {}", e.key)); + } + } + let get = |k: &str| entries.iter().find(|e| e.key == k); + let need = |k: &str| match get(k) { + Some(e) => Ok(e), + None => Err(ManifestError(format!("missing required key {k}"))), + }; + + let gate = scalar(need("gate")?)?; + if !valid_gate_id(&gate) { + return Err(ManifestError(format!("invalid gate id {gate:?}"))); + } + if scalar(need("manifest_version")?)? != "1" { + return Err(ManifestError( + "unsupported manifest_version (only 1)".into(), + )); + } + let owner = scalar(need("owner")?)?; + + let requires = list(need("requires")?)?; + for r in &requires { + if !["host", "qemu", "gb10", "operator"].contains(&r.as_str()) { + return Err(ManifestError(format!("unknown requires entry {r:?}"))); + } + } + if !requires + .iter() + .any(|r| r == "host" || r == "qemu" || r == "gb10") + { + return Err(ManifestError( + "requires must list one of host, qemu, gb10".into(), + )); + } + + let depends_on = match get("depends_on") { + Some(e) => list(e)?, + None => Vec::new(), + }; + for d in &depends_on { + if !valid_gate_id(d) { + return Err(ManifestError(format!("invalid depends_on id {d:?}"))); + } + } + let inputs = match get("inputs") { + Some(e) => list(e)?, + None => Vec::new(), + }; + for i in &inputs { + if !valid_rel_path(i) { + return Err(ManifestError(format!( + "inputs path must be repo-relative: {i:?}" + ))); + } + } + + let build = match get("build") { + None => None, + Some(e) => { + let c = map(e, &["target", "tool"])?; + let tool = + child_str(c, "tool")?.ok_or_else(|| ManifestError("build.tool missing".into()))?; + let target = child_str(c, "target")? + .ok_or_else(|| ManifestError("build.target missing".into()))?; + if !["make", "cargo", "none"].contains(&tool.as_str()) { + return Err(ManifestError(format!("unknown build.tool {tool:?}"))); + } + Some(Build { target, tool }) + } + }; + + let (exec, args) = { + let c = map(need("run")?, &["exec", "args"])?; + let exec = child_str(c, "exec")?.ok_or_else(|| ManifestError("run.exec missing".into()))?; + if !valid_rel_path(&exec) { + return Err(ManifestError( + "run.exec must be a repo-relative path".into(), + )); + } + let args = match child(c, "args") { + None => Vec::new(), + Some((_, Val::List(l), _)) => l.clone(), + Some((_, Val::Str(_), n)) => return err(*n, "run.args must be a one-line list"), + }; + (exec, args) + }; + + let (expect_exit, rules) = { + let c = map(need("expects")?, &["exit", "observe", "verdict"])?; + match child_str(c, "verdict")? { + Some(v) if v == "PASS" => {} + _ => return Err(ManifestError("expects.verdict must be PASS in v1".into())), + } + let exit = match child_str(c, "exit")? { + None => 0, + Some(s) => s + .parse::() + .map_err(|_| ManifestError("expects.exit must be an integer".into()))?, + }; + let texts: Vec = match child(c, "observe") { + None => Vec::new(), + Some((_, Val::List(l), _)) => l.clone(), + Some((_, Val::Str(s), _)) => vec![s.clone()], + }; + let mut rules = Vec::new(); + for t in &texts { + rules.push(parse_rule(t).map_err(ManifestError)?); + } + (exit, rules) + }; + + let timeout_s = scalar(need("timeout")?)?; + let timeout_ms = parse_duration_ms(&timeout_s) + .ok_or_else(|| ManifestError(format!("bad timeout {timeout_s:?}")))?; + + let mutants = match get("mutants") { + Some(e) => list(e)?, + None => Vec::new(), + }; + for m in &mutants { + if m.is_empty() + || !m + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-') + { + return Err(ManifestError(format!("bad mutant name {m:?}"))); + } + } + let checks = match get("checks") { + Some(e) => list(e)?, + None => Vec::new(), + }; + for c in &checks { + if !["no_libm_symbols", "no_cuda_symbols", "clean_tree_after"].contains(&c.as_str()) { + return Err(ManifestError(format!("unknown check {c:?}"))); + } + } + let cache_allowed = match get("cache") { + None => true, + Some(e) => match scalar(e)?.as_str() { + "allow" => true, + "never" => false, + other => { + return Err(ManifestError(format!( + "cache must be allow or never, got {other:?}" + ))) + } + }, + }; + + Ok(Manifest { + gate, + owner, + requires, + depends_on, + inputs, + build, + exec, + args, + expect_exit, + rules, + timeout_ms, + mutants, + checks, + cache_allowed, + digest: sha256_hex(bytes), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + pub const GOOD: &str = concat!( + "# comment\n", + "gate: G-1\n", + "manifest_version: 1\n", + "owner: omega\n", + "requires:\n", + " - host\n", + "run:\n", + " exec: tools/run.sh\n", + " args: [\"--a\", \"b c\"]\n", + "expects:\n", + " exit: 0\n", + " observe: [\"n == 3\", \"all x <= 2\", \"s == \\\"ok\\\"\"]\n", + " verdict: PASS\n", + "timeout: 5s\n", + ); + + fn with(extra: &str) -> String { + format!("{GOOD}{extra}") + } + + #[test] + fn good_manifest_parses() { + let m = parse(GOOD.as_bytes()).unwrap(); + assert_eq!(m.gate, "G-1"); + assert_eq!(m.owner, "omega"); + assert_eq!(m.pool(), "host"); + assert_eq!(m.exec, "tools/run.sh"); + assert_eq!(m.args, vec!["--a".to_string(), "b c".to_string()]); + assert_eq!(m.timeout_ms, 5000); + assert_eq!(m.rules.len(), 3); + assert_eq!(m.rules[1].quant, Quant::All); + assert_eq!(m.digest, sha256_hex(GOOD.as_bytes())); + assert!(m.cache_allowed); + } + + #[test] + fn digest_covers_comments() { + let a = parse(GOOD.as_bytes()).unwrap(); + let b = parse(with("# more\n").as_bytes()).unwrap(); + assert_ne!(a.digest, b.digest); + } + + #[test] + fn duplicate_top_level_key_rejected() { + assert!(parse(with("owner: x\n").as_bytes()).is_err()); + } + + #[test] + fn duplicate_child_key_rejected() { + let t = GOOD.replace(" exit: 0\n", " exit: 0\n exit: 1\n"); + assert!(parse(t.as_bytes()).is_err()); + } + + #[test] + fn unknown_top_level_key_rejected() { + assert!(parse(with("surprise: 1\n").as_bytes()).is_err()); + } + + #[test] + fn unknown_child_key_rejected() { + let t = GOOD.replace( + " exec: tools/run.sh\n", + " exec: tools/run.sh\n shell: sh\n", + ); + assert!(parse(t.as_bytes()).is_err()); + } + + #[test] + fn tab_crlf_bom_rejected() { + assert!(parse(GOOD.replace("owner: omega", "owner:\tomega").as_bytes()).is_err()); + assert!(parse(GOOD.replace('\n', "\r\n").as_bytes()).is_err()); + let mut b = vec![0xEF, 0xBB, 0xBF]; + b.extend_from_slice(GOOD.as_bytes()); + assert!(parse(&b).is_err()); + assert!(parse(&[0xFF, 0xFE, b'\n']).is_err()); + } + + #[test] + fn deep_indent_rejected() { + let t = GOOD.replace( + " exec: tools/run.sh\n", + " exec: tools/run.sh\n deeper: 1\n", + ); + assert!(parse(t.as_bytes()).is_err()); + } + + #[test] + fn mixed_shapes_rejected() { + let t = GOOD.replace("requires:\n - host\n", "requires: [\"host\"]\n - host\n"); + assert!(parse(t.as_bytes()).is_err()); + } + + #[test] + fn trailing_garbage_rejected() { + assert!(parse( + GOOD.replace("owner: omega", "owner: \"omega\" x") + .as_bytes() + ) + .is_err()); + } + + #[test] + fn size_limits() { + let mut big = String::from(GOOD); + for _ in 0..200 { + big.push_str("# pad\n"); + } + assert!(parse(big.as_bytes()).is_err()); + let huge = format!("{GOOD}# {}\n", "x".repeat(MAX_BYTES)); + assert!(parse(huge.as_bytes()).is_err()); + } + + #[test] + fn missing_required_and_bad_version() { + assert!(parse(GOOD.replace("timeout: 5s\n", "").as_bytes()).is_err()); + assert!(parse( + GOOD.replace("manifest_version: 1", "manifest_version: 2") + .as_bytes() + ) + .is_err()); + assert!(parse( + GOOD.replace(" verdict: PASS\n", " verdict: FAIL\n") + .as_bytes() + ) + .is_err()); + } + + #[test] + fn requires_needs_a_pool() { + assert!(parse(GOOD.replace(" - host\n", " - operator\n").as_bytes()).is_err()); + assert!(parse(GOOD.replace(" - host\n", " - moon\n").as_bytes()).is_err()); + } + + #[test] + fn pool_is_scarcest() { + let t = GOOD.replace(" - host\n", " - host\n - gb10\n"); + assert_eq!(parse(t.as_bytes()).unwrap().pool(), "gb10"); + } + + #[test] + fn paths_must_be_relative() { + assert!(parse(GOOD.replace("tools/run.sh", "/bin/sh").as_bytes()).is_err()); + assert!(parse(GOOD.replace("tools/run.sh", "../x").as_bytes()).is_err()); + } + + #[test] + fn durations() { + assert_eq!(parse_duration_ms("250ms"), Some(250)); + assert_eq!(parse_duration_ms("2m"), Some(120_000)); + assert_eq!(parse_duration_ms("1h"), Some(3_600_000)); + assert_eq!(parse_duration_ms("0s"), None); + assert_eq!(parse_duration_ms("5"), None); + assert_eq!(parse_duration_ms("s"), None); + } + + #[test] + fn rules_parse_and_reject_floats() { + let r = parse_rule("fence_count == 3").unwrap(); + assert_eq!(r.op, Op::Eq); + assert_eq!(r.value, Value::from(3)); + assert!(parse_rule("x <= 1.5").is_err()); + assert!(parse_rule("X == 1").is_err()); + assert!(parse_rule("x ~ 1").is_err()); + assert!(parse_rule("x ==").is_err()); + assert_eq!(parse_rule("any v > 2").unwrap().quant, Quant::Any); + assert_eq!( + parse_rule("s == \"a b\"").unwrap().value, + Value::from("a b") + ); + } + + #[test] + fn comment_inside_bare_value() { + let m = parse( + GOOD.replace("owner: omega", "owner: omega # note") + .as_bytes(), + ) + .unwrap(); + assert_eq!(m.owner, "omega"); + let m = parse(GOOD.replace("owner: omega", "owner: a#b").as_bytes()).unwrap(); + assert_eq!(m.owner, "a#b"); + } +} diff --git a/tools/aien-test/src/process.rs b/tools/aien-test/src/process.rs new file mode 100644 index 00000000..823b714e --- /dev/null +++ b/tools/aien-test/src/process.rs @@ -0,0 +1,192 @@ +//! Spawn a command without a shell, capture stdout and stderr, enforce a +//! wall-clock timeout by killing the whole process group (SIGTERM, then +//! SIGKILL after a grace period). No async: one waiter thread and two reader +//! threads per child. + +use std::io::{self, Read}; +use std::os::unix::process::{CommandExt, ExitStatusExt}; +use std::path::PathBuf; +use std::process::{Child, Command, ExitStatus, Stdio}; +use std::sync::mpsc; +use std::thread; +use std::time::{Duration, Instant}; + +pub struct RunSpec { + pub program: PathBuf, + pub args: Vec, + pub cwd: PathBuf, + pub timeout: Duration, + /// Time between SIGTERM and SIGKILL (ADR 0028 Decision 6 says 10 s). + pub kill_grace: Duration, +} + +#[derive(Debug)] +pub struct RunOutput { + /// Exit code; None if the child was killed by a signal. + pub exit_code: Option, + pub signal: Option, + pub stdout: Vec, + pub stderr: Vec, + pub timed_out: bool, + pub duration_ms: u64, +} + +type Waited = io::Result; + +fn signal_group(pid: i32, sig: i32) { + if pid > 0 { + // SAFETY: plain syscall; a stale group id yields ESRCH, ignored. + unsafe { + libc::kill(-pid, sig); + } + } +} + +fn lost() -> io::Error { + io::Error::other("waiter thread lost") +} + +fn spawn(spec: &RunSpec) -> io::Result { + let mut cmd = Command::new(&spec.program); + cmd.args(&spec.args) + .current_dir(&spec.cwd) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .process_group(0); + let mut attempt = 0; + loop { + match cmd.spawn() { + Ok(c) => return Ok(c), + // A script written moments ago can be briefly busy when another + // thread forks while its write descriptor is still open. + Err(e) if e.raw_os_error() == Some(libc::ETXTBSY) && attempt < 40 => { + attempt += 1; + thread::sleep(Duration::from_millis(50)); + } + Err(e) => return Err(e), + } + } +} + +fn terminate(pid: i32, rx: &mpsc::Receiver, grace: Duration) -> io::Result { + signal_group(pid, libc::SIGTERM); + match rx.recv_timeout(grace) { + Ok(r) => Ok(r), + Err(mpsc::RecvTimeoutError::Timeout) => { + signal_group(pid, libc::SIGKILL); + rx.recv().map_err(|_| lost()) + } + Err(mpsc::RecvTimeoutError::Disconnected) => Err(lost()), + } +} + +fn reader(src: Option) -> thread::JoinHandle> { + thread::spawn(move || { + let mut buf = Vec::new(); + if let Some(mut s) = src { + let _ = s.read_to_end(&mut buf); + } + buf + }) +} + +pub fn run(spec: &RunSpec) -> io::Result { + let start = Instant::now(); + let mut child = spawn(spec)?; + let pid = child.id() as i32; + let h_out = reader(child.stdout.take()); + let h_err = reader(child.stderr.take()); + let (tx, rx) = mpsc::channel::(); + thread::spawn(move || { + let r = child.wait(); + let _ = tx.send(r); + }); + + let mut timed_out = false; + let waited: Waited = match rx.recv_timeout(spec.timeout) { + Ok(r) => r, + Err(mpsc::RecvTimeoutError::Timeout) => { + timed_out = true; + terminate(pid, &rx, spec.kill_grace)? + } + Err(mpsc::RecvTimeoutError::Disconnected) => return Err(lost()), + }; + // Whatever the leader did, nothing it started may outlive the run. + signal_group(pid, libc::SIGKILL); + let status = waited?; + let stdout = h_out.join().unwrap_or_default(); + let stderr = h_err.join().unwrap_or_default(); + Ok(RunOutput { + exit_code: status.code(), + signal: status.signal(), + stdout, + stderr, + timed_out, + duration_ms: start.elapsed().as_millis() as u64, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn sh(script: &str, timeout_ms: u64) -> RunSpec { + RunSpec { + program: PathBuf::from("/bin/sh"), + args: vec!["-c".to_string(), script.to_string()], + cwd: PathBuf::from("/"), + timeout: Duration::from_millis(timeout_ms), + kill_grace: Duration::from_millis(500), + } + } + + #[test] + fn captures_output_and_exit_code() { + let o = run(&sh("echo out; echo err 1>&2; exit 3", 10_000)).unwrap(); + assert_eq!(o.exit_code, Some(3)); + assert_eq!(o.stdout, b"out\n"); + assert_eq!(o.stderr, b"err\n"); + assert!(!o.timed_out); + } + + #[test] + fn timeout_kills_and_flags() { + let o = run(&sh("sleep 20", 300)).unwrap(); + assert!(o.timed_out); + assert_eq!(o.exit_code, None); + assert!(o.signal.is_some()); + assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms); + } + + #[test] + fn timeout_kills_the_whole_group() { + // The grandchild inherits stdout; if only the leader were killed the + // reader threads would block until the grandchild's sleep ends. + let o = run(&sh("sleep 20 & wait", 300)).unwrap(); + assert!(o.timed_out); + assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms); + } + + #[test] + fn term_ignored_gets_killed_after_grace() { + let o = run(&sh("trap '' TERM; sleep 20", 200)).unwrap(); + assert!(o.timed_out); + assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms); + } + + #[test] + fn orphans_do_not_outlive_a_normal_exit() { + let o = run(&sh("sleep 20 & echo done", 10_000)).unwrap(); + assert_eq!(o.exit_code, Some(0)); + assert!(!o.timed_out); + assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms); + } + + #[test] + fn missing_program_is_an_error() { + let mut s = sh("true", 1000); + s.program = PathBuf::from("/nonexistent/aien-test-nope"); + assert!(run(&s).is_err()); + } +} diff --git a/tools/aien-test/src/runner.rs b/tools/aien-test/src/runner.rs new file mode 100644 index 00000000..667ddf30 --- /dev/null +++ b/tools/aien-test/src/runner.rs @@ -0,0 +1,946 @@ +//! Serial, host-pool runner for one gate (ADR 0028, Slice A). +//! +//! Order: parse manifest (BAD_MANIFEST means no receipt), pin the commit, +//! record whether the tree is clean, decide refusals, run, measure what +//! changed, derive the verdict, write blobs and an immutable receipt. +//! +//! Slice A choices where the ADR is silent (recorded in the PR): +//! - A dirty tree is refused unless the operator passes `--allow-dirty` (the +//! manifest grammar has no key for it and P4 forbids adding one here). A +//! run allowed this way is recorded with `tree_clean_before = false`. +//! - "Tree changed after the run" means `git status --porcelain` differs from +//! the pre-run output, so it also catches a run that dirties an already +//! allowed-dirty tree further. +//! - `pins` is always empty and `dependencies` is always empty. +//! - `gb10_present` is a heuristic: `/dev/nvidiactl` exists (UNVERIFIED). + +use crate::evidence::{build_receipt, canonical_digest, sha256_hex, utc_string, Store, SCHEMA}; +use crate::manifest::{self, Manifest}; +use crate::process::{self, RunSpec}; +use crate::verdict::{self, derive, parse_observations, Facts, Verdict}; +use serde_json::{json, Map, Value}; +use std::collections::BTreeSet; +use std::fmt; +use std::fs; +use std::path::{Component, Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +pub struct Options { + pub evidence_dir: PathBuf, + pub allow_dirty: bool, + pub args_override: Option>, + pub kill_grace: Duration, +} + +impl Options { + pub fn new(evidence_dir: PathBuf) -> Options { + Options { + evidence_dir, + allow_dirty: false, + args_override: None, + kill_grace: Duration::from_secs(10), + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum RunError { + /// Manifest invalid: no receipt (P8). + BadManifest(String), + /// Could not bind or write evidence (CR-004 style fatal). + Fatal(String), +} + +impl fmt::Display for RunError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + RunError::BadManifest(m) => write!(f, "BAD_MANIFEST {m}"), + RunError::Fatal(m) => write!(f, "FATAL {m}"), + } + } +} + +#[derive(Debug, Clone)] +pub struct Outcome { + pub verdict: Verdict, + pub reason: String, + pub receipt_path: Option, + pub receipt_digest: Option, +} + +fn git_out(root: &Path, args: &[&str]) -> Result { + let out = Command::new("git") + .arg("-C") + .arg(root) + .args(args) + .output() + .map_err(|e| format!("cannot run git: {e}"))?; + if !out.status.success() { + return Err(format!( + "git {:?} failed: {}", + args, + String::from_utf8_lossy(&out.stderr).trim() + )); + } + Ok(String::from_utf8_lossy(&out.stdout).into_owned()) +} + +pub fn repo_root(dir: &Path) -> Result { + let s = git_out(dir, &["rev-parse", "--show-toplevel"])?; + Ok(PathBuf::from(s.trim())) +} + +fn head(root: &Path) -> Result { + let s = git_out(root, &["rev-parse", "HEAD"])?.trim().to_string(); + if s.len() == 40 + && s.chars() + .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)) + { + Ok(s) + } else { + Err(format!("HEAD is not a 40-hex commit: {s:?}")) + } +} + +fn porcelain(root: &Path) -> Result { + git_out(root, &["status", "--porcelain"]) +} + +/// Absolute, lexically normalized path whose deepest existing ancestor is +/// canonicalized, so a not-yet-created evidence dir can still be compared. +fn resolve(p: &Path) -> PathBuf { + let abs = if p.is_absolute() { + p.to_path_buf() + } else { + std::env::current_dir().unwrap_or_default().join(p) + }; + let mut norm = PathBuf::new(); + for c in abs.components() { + match c { + Component::ParentDir => { + norm.pop(); + } + Component::CurDir => {} + other => norm.push(other.as_os_str()), + } + } + let mut existing = norm.clone(); + let mut tail = Vec::new(); + while !existing.exists() { + match existing.file_name().map(|s| s.to_os_string()) { + Some(n) => { + tail.push(n); + existing.pop(); + } + None => break, + } + } + let mut base = fs::canonicalize(&existing).unwrap_or(existing); + for n in tail.iter().rev() { + base.push(n); + } + base +} + +const SKIP_DIRS: [&str; 5] = [".git", "target", "build", "vendor", "node_modules"]; + +/// D1: every `*.gate` file under `root`, skipping the usual build dirs and any +/// directory holding `.aien-test-ignore`. Sorted. +pub fn discover(root: &Path) -> Vec { + fn walk(dir: &Path, out: &mut Vec) { + if dir.join(".aien-test-ignore").exists() { + return; + } + let rd = match fs::read_dir(dir) { + Ok(r) => r, + Err(_) => return, + }; + for e in rd.flatten() { + let path = e.path(); + let ft = match e.file_type() { + Ok(t) => t, + Err(_) => continue, + }; + let name = e.file_name().to_string_lossy().into_owned(); + if ft.is_dir() { + if !SKIP_DIRS.contains(&name.as_str()) { + walk(&path, out); + } + } else if ft.is_file() && name.ends_with(".gate") { + out.push(path); + } + } + } + let mut out = Vec::new(); + walk(root, &mut out); + out.sort(); + out +} + +/// Resolve `GATE_FILE_OR_NAME`: an existing file path, else the unique +/// `.gate` file under the repository whose `gate:` equals the name (D2). +pub fn locate_gate(cwd: &Path, name: &str) -> Result { + let p = Path::new(name); + let direct = if p.is_absolute() { + p.to_path_buf() + } else { + cwd.join(p) + }; + if direct.is_file() { + return fs::canonicalize(&direct).map_err(|e| format!("cannot resolve {name}: {e}")); + } + let root = repo_root(cwd)?; + let mut found: Vec = Vec::new(); + let mut unparsable = 0; + for path in discover(&root) { + match fs::read(&path) { + Ok(bytes) => match manifest::parse(&bytes) { + Ok(m) if m.gate == name => found.push(path), + Ok(_) => {} + Err(_) => unparsable += 1, + }, + Err(_) => unparsable += 1, + } + } + match found.len() { + 1 => Ok(found.remove(0)), + 0 => Err(format!( + "no gate named {name} ({unparsable} unparsable gate files skipped)" + )), + _ => Err(format!( + "duplicate gate id {name} in: {}", + found + .iter() + .map(|f| f.display().to_string()) + .collect::>() + .join(", ") + )), + } +} + +fn collect_files(root: &Path, rel: &str, out: &mut BTreeSet) { + let path = root.join(rel.trim_end_matches('/')); + let md = match fs::symlink_metadata(&path) { + Ok(m) => m, + Err(_) => { + out.insert(rel.trim_end_matches('/').to_string()); + return; + } + }; + if md.is_dir() { + if let Ok(rd) = fs::read_dir(&path) { + for e in rd.flatten() { + let name = e.file_name().to_string_lossy().into_owned(); + if name == ".git" { + continue; + } + let child = format!("{}/{}", rel.trim_end_matches('/'), name); + collect_files(root, &child, out); + } + } + } else if md.is_file() { + out.insert(rel.trim_end_matches('/').to_string()); + } +} + +/// sha256 over the canonical list of (path, file sha256) for the explicit +/// `inputs` plus the D3 convention-implied inputs of `tests//.gate`. +/// A listed path that does not exist is recorded with a null digest. Compiler +/// identity is not included in Slice A because Slice A does not build. +pub fn build_inputs_digest(root: &Path, manifest_rel: Option<&Path>, m: &Manifest) -> String { + let mut paths: BTreeSet = BTreeSet::new(); + for i in &m.inputs { + collect_files(root, i, &mut paths); + } + if let Some(rel) = manifest_rel { + let dir = rel.parent().unwrap_or(Path::new("")); + let stem = rel + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + if let Ok(sub) = dir.strip_prefix("tests") { + let sub = sub.to_string_lossy().into_owned(); + let join = |base: &str| { + if sub.is_empty() { + base.to_string() + } else { + format!("{base}/{sub}") + } + }; + for (base, want) in [ + (join("src"), stem.clone()), + (join("tests"), format!("{stem}_test")), + ] { + if let Ok(rd) = fs::read_dir(root.join(&base)) { + for e in rd.flatten() { + let p = e.path(); + let fstem = p + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_default(); + if p.is_file() && fstem == want { + paths.insert(format!("{base}/{}", e.file_name().to_string_lossy())); + } + } + } + } + } + } + let entries: Vec = paths + .iter() + .map(|p| { + let digest = fs::read(root.join(p)).ok().map(|b| sha256_hex(&b)); + json!({ "path": p, "sha256": digest }) + }) + .collect(); + canonical_digest(&json!({ "inputs": entries })).unwrap_or_default() +} + +fn which(name: &str) -> bool { + match std::env::var_os("PATH") { + Some(p) => std::env::split_paths(&p).any(|d| d.join(name).is_file()), + None => false, + } +} + +fn machine() -> Value { + let kernel = fs::read_to_string("/proc/sys/kernel/osrelease") + .map(|s| s.trim().to_string()) + .unwrap_or_default(); + let cpuinfo = fs::read_to_string("/proc/cpuinfo").unwrap_or_default(); + let cpu_model = cpuinfo + .lines() + .find(|l| l.starts_with("model name")) + .and_then(|l| l.split_once(':')) + .map(|p| p.1.trim().to_string()) + .unwrap_or_default(); + let cpus = std::thread::available_parallelism() + .map(|n| n.get() as u64) + .unwrap_or(0); + let meminfo = fs::read_to_string("/proc/meminfo").unwrap_or_default(); + let mem_kib = meminfo + .lines() + .find(|l| l.starts_with("MemTotal:")) + .and_then(|l| l.split_whitespace().nth(1)) + .and_then(|v| v.parse::().ok()) + .unwrap_or(0); + let gb10 = Path::new("/dev/nvidiactl").exists(); + let qemu = which("qemu-system-aarch64") || which("qemu-system-x86_64"); + json!({ + "arch": std::env::consts::ARCH, + "kernel_release": kernel, + "cpu_model": cpu_model, + "cpu_count": cpus, + "mem_total_kib": mem_kib, + "gb10_present": gb10, + "qemu_available": qemu, + }) +} + +fn captured_env() -> Value { + let mut m = Map::new(); + for k in [ + "AIEN_PROOF_OFF", + "CC", + "CFLAGS", + "CHIPRUN_SELFTEST", + "LANG", + "LC_ALL", + "RUSTFLAGS", + "TZ", + ] { + if let Ok(v) = std::env::var(k) { + m.insert(k.to_string(), Value::String(v)); + } + } + Value::Object(m) +} + +fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +fn fatal(e: E) -> RunError { + RunError::Fatal(e.to_string()) +} + +pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result { + let bytes = fs::read(manifest_path) + .map_err(|e| RunError::Fatal(format!("cannot read manifest: {e}")))?; + let m = manifest::parse(&bytes).map_err(|e| RunError::BadManifest(e.0))?; + let started = now_secs(); + let t0 = Instant::now(); + + let commit = head(root).map_err(RunError::Fatal)?; + let before = porcelain(root).map_err(RunError::Fatal)?; + let evidence_inside = resolve(&opts.evidence_dir).starts_with(resolve(root)); + let refusal: Option = if evidence_inside { + Some("evidence_inside".to_string()) + } else if !before.is_empty() && !opts.allow_dirty { + Some("dirty_tree".to_string()) + } else { + None + }; + + let exec_path = root.join(&m.exec); + let exec_exists = exec_path.is_file(); + let will_run = verdict::pre_run(&m, &refusal, exec_exists).is_none(); + + let mut facts = Facts { + refusal, + exec_exists, + ..Facts::default() + }; + let mut stdout: Vec = Vec::new(); + let mut stderr: Vec = Vec::new(); + let mut after = before.clone(); + if will_run { + let spec = RunSpec { + program: exec_path.clone(), + args: opts.args_override.clone().unwrap_or_else(|| m.args.clone()), + cwd: root.to_path_buf(), + timeout: Duration::from_millis(m.timeout_ms), + kill_grace: opts.kill_grace, + }; + match process::run(&spec) { + Ok(o) => { + facts.exit_status = o.exit_code.map(i64::from); + facts.timed_out = o.timed_out; + stdout = o.stdout; + stderr = o.stderr; + } + Err(e) => { + stderr = format!("aien-test: cannot run {}: {e}\n", m.exec).into_bytes(); + } + } + after = porcelain(root).map_err(RunError::Fatal)?; + let head_after = head(root).unwrap_or_default(); + facts.tree_changed_after = after != before; + facts.head_moved = head_after != commit; + facts.observations = parse_observations(&stdout); + } + let derived = derive(&m, &facts); + + if evidence_inside { + return Ok(Outcome { + verdict: derived.verdict, + reason: derived.reason, + receipt_path: None, + receipt_digest: None, + }); + } + + let store = Store::new(&opts.evidence_dir); + let stdout_sha = store.put_blob(&stdout).map_err(fatal)?; + let stderr_sha = store.put_blob(&stderr).map_err(fatal)?; + let binary_sha = if exec_exists { + fs::read(&exec_path).ok().map(|b| sha256_hex(&b)) + } else { + None + }; + let manifest_rel = manifest_path + .strip_prefix(root) + .ok() + .map(|p| p.to_path_buf()); + let inputs_digest = build_inputs_digest(root, manifest_rel.as_deref(), &m); + let machine_v = machine(); + let machine_digest = canonical_digest(&machine_v).map_err(fatal)?; + + let observations: Vec = facts + .observations + .iter() + .map(|o| json!({ "name": o.name, "value": o.value })) + .collect(); + let rules: Vec = derived + .rules + .iter() + .map(|(t, h)| json!({ "rule": t, "held": h })) + .collect(); + let checks: Vec = m + .checks + .iter() + .map(|c| { + let passed = will_run && c == "clean_tree_after" && !facts.tree_changed_after; + json!({ "name": c, "passed": passed }) + }) + .collect(); + + let mut core = Map::new(); + core.insert("gate".into(), json!(m.gate)); + core.insert("owner".into(), json!(m.owner)); + core.insert("manifest_digest".into(), json!(m.digest)); + core.insert("commit".into(), json!(commit)); + core.insert("pins".into(), json!([])); + core.insert("tree_clean_before".into(), json!(before.is_empty())); + core.insert("tree_clean_after".into(), json!(after.is_empty())); + core.insert("commit_unchanged_after".into(), json!(!facts.head_moved)); + if let Some(b) = &binary_sha { + core.insert("binary_sha256".into(), json!(b)); + } + core.insert("build_inputs_digest".into(), json!(inputs_digest)); + core.insert("env".into(), captured_env()); + core.insert("machine".into(), machine_v); + core.insert("machine_digest".into(), json!(machine_digest)); + core.insert("exit_status".into(), json!(facts.exit_status)); + core.insert("stdout_sha256".into(), json!(stdout_sha)); + core.insert("stderr_sha256".into(), json!(stderr_sha)); + core.insert("observations".into(), Value::Array(observations)); + core.insert("rules".into(), Value::Array(rules)); + core.insert("derived_verdict".into(), json!(derived.verdict.as_str())); + core.insert("reason".into(), json!(derived.reason)); + core.insert("mutants".into(), json!([])); + core.insert("checks".into(), Value::Array(checks)); + core.insert("dependencies".into(), json!([])); + + let cache_key = canonical_digest(&json!({ + "manifest_digest": m.digest, + "binary_sha256": binary_sha, + "build_inputs_digest": inputs_digest, + "machine_digest": machine_digest, + "dependencies": [], + "runner_schema": SCHEMA, + "pins": [], + })) + .map_err(fatal)?; + + let volatile = json!({ + "started_utc": utc_string(started), + "finished_utc": utc_string(now_secs()), + "duration_ms": t0.elapsed().as_millis() as u64, + "pool": "host", + "pool_wait_ms": 0, + "runner": { "name": "aien-test", "version": env!("CARGO_PKG_VERSION"), "impl": "rust" }, + "cache": { "key": cache_key, "reused": false, "reused_from": null, "mode": "disabled" }, + "timeout_exceeded": facts.timed_out, + }); + + let receipt = build_receipt(Value::Object(core), volatile); + let (digest, path) = store.put_receipt(&receipt).map_err(fatal)?; + Ok(Outcome { + verdict: derived.verdict, + reason: derived.reason, + receipt_path: Some(path), + receipt_digest: Some(digest), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::testutil::{git, init_repo, write_file, TempDir}; + use std::os::unix::fs::PermissionsExt; + + const OK_SCRIPT: &str = "#!/bin/sh\ntouch \"$1\"\necho \"AIEN-OBS n 3\"\necho PASS\n"; + + fn gate_text( + exec: &str, + args: &[&str], + exit: i32, + observe: &[&str], + timeout: &str, + extra: &str, + ) -> String { + format!( + "gate: T-1\nmanifest_version: 1\nowner: t\nrequires:\n - host\nrun:\n exec: {exec}\n args: {}\nexpects:\n exit: {exit}\n observe: {}\n verdict: PASS\ntimeout: {timeout}\n{extra}", + serde_json::to_string(args).unwrap(), + serde_json::to_string(observe).unwrap(), + ) + } + + struct Fx { + repo: TempDir, + ev: TempDir, + scratch: TempDir, + } + + impl Fx { + fn marker(&self) -> PathBuf { + self.scratch.path().join("marker") + } + fn manifest(&self) -> PathBuf { + self.repo.path().join("tests/t.gate") + } + fn opts(&self) -> Options { + let mut o = Options::new(self.ev.path().join("out")); + o.kill_grace = Duration::from_millis(300); + o + } + } + + /// A repo with `tools/run.sh` = script and a gate whose args are the + /// marker path. + fn fixture(script: &str, exit: i32, observe: &[&str], timeout: &str, extra: &str) -> Fx { + let scratch = TempDir::new("scratch"); + let marker = scratch.path().join("marker"); + let gate = gate_text( + "tools/run.sh", + &[marker.to_str().unwrap()], + exit, + observe, + timeout, + extra, + ); + let repo = init_repo( + "repo", + &[ + ("tools/run.sh", script, true), + ("tests/t.gate", gate.as_str(), false), + ("README", "hello\n", false), + ], + ); + Fx { + repo, + ev: TempDir::new("ev"), + scratch, + } + } + + fn ok_fixture() -> Fx { + fixture(OK_SCRIPT, 0, &["n == 3"], "20s", "") + } + + fn read_json(p: &Path) -> Value { + serde_json::from_slice(&fs::read(p).unwrap()).unwrap() + } + + fn run(fx: &Fx, opts: &Options) -> Outcome { + run_gate(fx.repo.path(), &fx.manifest(), opts).unwrap() + } + + #[test] + fn pass_writes_a_bound_receipt() { + let fx = ok_fixture(); + let o = run(&fx, &fx.opts()); + assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); + assert!(fx.marker().exists(), "script must have run"); + let path = o.receipt_path.unwrap(); + let r = read_json(&path); + assert_eq!(r["schema"], "aien-test/EvidenceReceiptV1"); + let core = &r["core"]; + let head_now = git_out(fx.repo.path(), &["rev-parse", "HEAD"]).unwrap(); + assert_eq!(core["commit"], head_now.trim()); + assert_eq!(core["gate"], "T-1"); + assert_eq!(core["derived_verdict"], "PASS"); + assert_eq!(core["reason"], ""); + assert_eq!(core["exit_status"], 0); + assert_eq!(core["tree_clean_before"], true); + assert_eq!(core["tree_clean_after"], true); + assert_eq!(core["commit_unchanged_after"], true); + assert_eq!(core["observations"][0]["name"], "n"); + assert_eq!(core["observations"][0]["value"], 3); + assert_eq!(core["rules"][0]["held"], true); + let script_bytes = fs::read(fx.repo.path().join("tools/run.sh")).unwrap(); + assert_eq!(core["binary_sha256"], sha256_hex(&script_bytes)); + let gate_bytes = fs::read(fx.manifest()).unwrap(); + assert_eq!(core["manifest_digest"], sha256_hex(&gate_bytes)); + assert_eq!(r["volatile"]["pool"], "host"); + assert_eq!(r["volatile"]["timeout_exceeded"], false); + // Receipt is read-only and named by its digest. + assert_eq!( + fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o444 + ); + assert_eq!( + path.file_name().unwrap().to_string_lossy(), + format!("{}.json", o.receipt_digest.unwrap()) + ); + // stdout blob holds the script output verbatim. + let sha = core["stdout_sha256"].as_str().unwrap(); + let blob = fx.ev.path().join("out/blobs").join(format!("{sha}.log")); + assert_eq!(fs::read(blob).unwrap(), b"AIEN-OBS n 3\nPASS\n"); + } + + #[test] + fn dirty_tree_is_refused_and_nothing_runs() { + let fx = ok_fixture(); + write_file(fx.repo.path(), "README", "changed\n", false); + let o = run(&fx, &fx.opts()); + assert_eq!(o.verdict, Verdict::NotRun); + assert_eq!(o.reason, "dirty_tree"); + assert!(!fx.marker().exists(), "script must not run on a dirty tree"); + let r = read_json(&o.receipt_path.unwrap()); + assert_eq!(r["core"]["tree_clean_before"], false); + assert_eq!(r["core"]["exit_status"], Value::Null); + } + + #[test] + fn untracked_file_counts_as_dirty() { + let fx = ok_fixture(); + write_file(fx.repo.path(), "stray.txt", "x", false); + let o = run(&fx, &fx.opts()); + assert_eq!( + (o.verdict, o.reason.as_str()), + (Verdict::NotRun, "dirty_tree") + ); + assert!(!fx.marker().exists()); + } + + #[test] + fn allow_dirty_runs_and_records_it() { + let fx = ok_fixture(); + write_file(fx.repo.path(), "README", "changed\n", false); + let mut opts = fx.opts(); + opts.allow_dirty = true; + let o = run(&fx, &opts); + assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); + assert!(fx.marker().exists()); + let r = read_json(&o.receipt_path.unwrap()); + assert_eq!(r["core"]["tree_clean_before"], false); + } + + #[test] + fn timeout_is_enforced_with_fail() { + let fx = fixture("#!/bin/sh\nsleep 20\n", 0, &[], "300ms", ""); + let t = Instant::now(); + let o = run(&fx, &fx.opts()); + assert!(t.elapsed() < Duration::from_secs(10)); + assert_eq!((o.verdict, o.reason.as_str()), (Verdict::Fail, "timeout")); + let r = read_json(&o.receipt_path.unwrap()); + assert_eq!(r["volatile"]["timeout_exceeded"], true); + } + + #[test] + fn rule_mismatch_fails_even_if_the_script_prints_pass() { + let fx = fixture( + "#!/bin/sh\necho \"AIEN-OBS n 4\"\necho PASS\necho 'AIEN-OBS verdict \"PASS\"'\n", + 0, + &["n == 3"], + "20s", + "", + ); + let o = run(&fx, &fx.opts()); + assert_eq!((o.verdict, o.reason.as_str()), (Verdict::Fail, "rule:0")); + let r = read_json(&o.receipt_path.unwrap()); + assert_eq!(r["core"]["rules"][0]["held"], false); + } + + #[test] + fn exit_status_must_match() { + let fx = fixture( + "#!/bin/sh\necho \"AIEN-OBS n 3\"\nexit 2\n", + 0, + &["n == 3"], + "20s", + "", + ); + let o = run(&fx, &fx.opts()); + assert_eq!( + (o.verdict, o.reason.as_str()), + (Verdict::Fail, "rc_nonzero") + ); + let r = read_json(&o.receipt_path.unwrap()); + assert_eq!(r["core"]["exit_status"], 2); + } + + #[test] + fn nonzero_expected_exit_passes() { + let fx = fixture("#!/bin/sh\nexit 7\n", 7, &[], "20s", ""); + assert_eq!(run(&fx, &fx.opts()).verdict, Verdict::Pass); + } + + #[test] + fn missing_exec_is_missing_implementation() { + let fx = ok_fixture(); + fs::remove_file(fx.repo.path().join("tools/run.sh")).unwrap(); + git(fx.repo.path(), &["add", "-A"]); + git(fx.repo.path(), &["commit", "-q", "-m", "rm"]); + let o = run(&fx, &fx.opts()); + assert_eq!(o.verdict, Verdict::MissingImplementation); + assert_eq!(o.reason, "NO_RUN_EXEC"); + let r = read_json(&o.receipt_path.unwrap()); + assert!(r["core"].get("binary_sha256").is_none()); + } + + #[test] + fn evidence_dir_inside_repo_is_refused() { + let fx = ok_fixture(); + let mut opts = fx.opts(); + opts.evidence_dir = fx.repo.path().join("evidence"); + let o = run(&fx, &opts); + assert_eq!( + (o.verdict, o.reason.as_str()), + (Verdict::NotRun, "evidence_inside") + ); + assert!(o.receipt_path.is_none()); + assert!(!fx.repo.path().join("evidence").exists()); + assert!(!fx.marker().exists()); + } + + #[test] + fn tree_dirtied_by_the_run_fails() { + let fx = fixture("#!/bin/sh\necho more >> README\n", 0, &[], "20s", ""); + let o = run(&fx, &fx.opts()); + assert_eq!( + (o.verdict, o.reason.as_str()), + (Verdict::Fail, "dirty_after") + ); + let r = read_json(&o.receipt_path.unwrap()); + assert_eq!(r["core"]["tree_clean_after"], false); + } + + #[test] + fn head_moving_during_the_run_fails() { + let fx = fixture( + "#!/bin/sh\ngit -c user.name=t -c user.email=t@example.invalid -c commit.gpgsign=false commit -q --allow-empty -m moved\n", + 0, + &[], + "20s", + "", + ); + let o = run(&fx, &fx.opts()); + assert_eq!( + (o.verdict, o.reason.as_str()), + (Verdict::Fail, "head_moved") + ); + let r = read_json(&o.receipt_path.unwrap()); + assert_eq!(r["core"]["commit_unchanged_after"], false); + } + + #[test] + fn args_after_double_dash_replace_manifest_args() { + let fx = ok_fixture(); + let other = fx.scratch.path().join("other"); + let mut opts = fx.opts(); + opts.args_override = Some(vec![other.to_str().unwrap().to_string()]); + let o = run(&fx, &opts); + assert_eq!(o.verdict, Verdict::Pass); + assert!(other.exists()); + assert!(!fx.marker().exists()); + } + + #[test] + fn bad_manifest_writes_no_receipt() { + let fx = ok_fixture(); + write_file(fx.repo.path(), "tests/t.gate", "gate: X\nbogus: 1\n", false); + match run_gate(fx.repo.path(), &fx.manifest(), &fx.opts()) { + Err(RunError::BadManifest(_)) => {} + other => panic!("expected BadManifest, got {other:?}"), + } + assert!(!fx.ev.path().join("out").exists()); + } + + #[test] + fn operator_and_other_pool_gates_do_not_run() { + let fx = ok_fixture(); + let gate = fs::read_to_string(fx.manifest()).unwrap(); + write_file( + fx.repo.path(), + "tests/t.gate", + &gate.replace(" - host\n", " - host\n - operator\n"), + false, + ); + git(fx.repo.path(), &["add", "-A"]); + git(fx.repo.path(), &["commit", "-q", "-m", "op"]); + let o = run(&fx, &fx.opts()); + assert_eq!(o.verdict, Verdict::BlockedOperator); + assert!(!fx.marker().exists()); + write_file( + fx.repo.path(), + "tests/t.gate", + &gate.replace(" - host\n", " - gb10\n"), + false, + ); + git(fx.repo.path(), &["add", "-A"]); + git(fx.repo.path(), &["commit", "-q", "-m", "gb10"]); + let o = run(&fx, &fx.opts()); + assert_eq!( + (o.verdict, o.reason.as_str()), + (Verdict::NotRun, "pool_unsupported:gb10") + ); + assert!(!fx.marker().exists()); + } + + #[test] + fn unfinished_receipts_are_never_modified_by_a_second_run() { + let fx = ok_fixture(); + let first = run(&fx, &fx.opts()).receipt_path.unwrap(); + let before = fs::read(&first).unwrap(); + let second = run(&fx, &fx.opts()); + assert_eq!(second.verdict, Verdict::Pass); + assert_eq!(fs::read(&first).unwrap(), before); + } + + #[test] + fn inputs_digest_tracks_input_bytes() { + let fx = ok_fixture(); + let m = manifest::parse(&fs::read(fx.manifest()).unwrap()).unwrap(); + let mut m2 = m.clone(); + m2.inputs = vec!["README".to_string()]; + let a = build_inputs_digest(fx.repo.path(), None, &m2); + assert_eq!(a, build_inputs_digest(fx.repo.path(), None, &m2)); + write_file(fx.repo.path(), "README", "different\n", false); + let b = build_inputs_digest(fx.repo.path(), None, &m2); + assert_ne!(a, b); + } + + #[test] + fn convention_inputs_are_found() { + let repo = init_repo( + "conv", + &[ + ("src/rt/world.c", "int x;", false), + ("tests/rt/world_test.c", "int t;", false), + ("tests/rt/other.c", "int o;", false), + ], + ); + let m = manifest::parse(gate_text("tools/x.sh", &[], 0, &[], "5s", "").as_bytes()).unwrap(); + let rel = Path::new("tests/rt/world.gate"); + let a = build_inputs_digest(repo.path(), Some(rel), &m); + write_file(repo.path(), "src/rt/world.c", "int y;", false); + let b = build_inputs_digest(repo.path(), Some(rel), &m); + assert_ne!(a, b, "implied src input must feed the digest"); + write_file(repo.path(), "tests/rt/other.c", "int p;", false); + let c = build_inputs_digest(repo.path(), Some(rel), &m); + assert_eq!(b, c, "unrelated file must not feed the digest"); + } + + #[test] + fn locate_by_path_name_and_duplicates() { + let g1 = gate_text("tools/x.sh", &[], 0, &[], "5s", "").replace("T-1", "ONE"); + let g2 = gate_text("tools/x.sh", &[], 0, &[], "5s", "").replace("T-1", "TWO"); + let repo = init_repo( + "loc", + &[ + ("tests/a/one.gate", g1.as_str(), false), + ("tests/b/two.gate", g2.as_str(), false), + ("target/skipped.gate", g1.as_str(), false), + ("tests/bad.gate", "nonsense\n", false), + ], + ); + let p = locate_gate(repo.path(), "ONE").unwrap(); + assert!(p.ends_with("tests/a/one.gate"), "{p:?}"); + let p = locate_gate(repo.path(), "tests/b/two.gate").unwrap(); + assert!(p.ends_with("tests/b/two.gate")); + assert!(locate_gate(repo.path(), "NOPE").is_err()); + write_file(repo.path(), "tests/c/dup.gate", g1.as_str(), false); + let e = locate_gate(repo.path(), "ONE").unwrap_err(); + assert!(e.contains("duplicate"), "{e}"); + } + + #[test] + fn ignore_marker_hides_a_directory() { + let g = gate_text("tools/x.sh", &[], 0, &[], "5s", ""); + let repo = init_repo( + "ign", + &[ + ("tests/a.gate", g.as_str(), false), + ("tests/skip/b.gate", g.as_str(), false), + ("tests/skip/.aien-test-ignore", "", false), + ], + ); + let found = discover(repo.path()); + assert_eq!(found.len(), 1); + assert!(found[0].ends_with("tests/a.gate")); + } + + #[test] + fn resolve_handles_missing_dirs_and_dotdot() { + let t = TempDir::new("res"); + let p = resolve(&t.path().join("a/b/../c")); + assert_eq!(p, t.path().join("a/c")); + } +} diff --git a/tools/aien-test/src/testutil.rs b/tools/aien-test/src/testutil.rs new file mode 100644 index 00000000..8099aaf8 --- /dev/null +++ b/tools/aien-test/src/testutil.rs @@ -0,0 +1,87 @@ +//! Test helpers: unique temp dirs and throwaway git repositories. + +use std::fs; +use std::os::unix::fs::PermissionsExt; +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::sync::atomic::{AtomicU64, Ordering}; + +static COUNTER: AtomicU64 = AtomicU64::new(0); + +pub struct TempDir { + path: PathBuf, +} + +impl TempDir { + pub fn new(tag: &str) -> TempDir { + let n = COUNTER.fetch_add(1, Ordering::SeqCst); + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.subsec_nanos()) + .unwrap_or(0); + let path = std::env::temp_dir().join(format!( + "aien-test-{tag}-{}-{n}-{nanos}", + std::process::id() + )); + fs::create_dir_all(&path).expect("create temp dir"); + let path = fs::canonicalize(&path).expect("canonicalize temp dir"); + TempDir { path } + } + + pub fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.path); + } +} + +pub fn git(dir: &Path, args: &[&str]) { + let out = Command::new("git") + .arg("-C") + .arg(dir) + .args([ + "-c", + "user.name=test", + "-c", + "user.email=test@example.invalid", + "-c", + "commit.gpgsign=false", + ]) + .args(args) + .output() + .expect("run git"); + assert!( + out.status.success(), + "git {:?} failed: {}", + args, + String::from_utf8_lossy(&out.stderr) + ); +} + +pub fn write_file(dir: &Path, rel: &str, content: &str, executable: bool) { + let p = dir.join(rel); + if let Some(parent) = p.parent() { + fs::create_dir_all(parent).expect("create parent"); + } + fs::write(&p, content).expect("write file"); + if executable { + fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).expect("chmod"); + } +} + +/// A fresh git repository with one commit containing whatever `files` lists +/// as (relative path, content, executable). +pub fn init_repo(tag: &str, files: &[(&str, &str, bool)]) -> TempDir { + let t = TempDir::new(tag); + git(t.path(), &["init", "-q"]); + for (rel, content, exec) in files { + write_file(t.path(), rel, content, *exec); + } + git(t.path(), &["add", "-A"]); + git(t.path(), &["commit", "-q", "-m", "init"]); + t +} diff --git a/tools/aien-test/src/verdict.rs b/tools/aien-test/src/verdict.rs new file mode 100644 index 00000000..e92a20bb --- /dev/null +++ b/tools/aien-test/src/verdict.rs @@ -0,0 +1,439 @@ +//! Verdict set and derivation (ADR 0028 Decision 5). A test program only +//! reports observations; the verdict is derived here from the manifest's +//! expectations and facts the runner measured. Only the last row can yield +//! PASS. +//! +//! Slice A scope (host pool, serial, one gate): rows 2 to 15 are implemented +//! as below. Where Slice A cannot do what a row presumes (dependencies, other +//! pools, build, symbol checks, operator attestations) it refuses with NOT_RUN +//! or BLOCKED_OPERATOR and a reason code; it never guesses a PASS. +//! +//! Deviation from the ADR table order (recorded): timeout (row 14) is tested +//! before the exit status (row 10), because a killed process has no exit code +//! and would otherwise always be reported as rc_nonzero. + +use crate::manifest::{parse_json_scalar, valid_obs_name, Manifest, Op, Quant, Rule}; +use serde_json::Value; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Verdict { + Pass, + Fail, + NotRun, + BlockedHardware, + BlockedOperator, + MissingImplementation, +} + +impl Verdict { + pub fn as_str(self) -> &'static str { + match self { + Verdict::Pass => "PASS", + Verdict::Fail => "FAIL", + Verdict::NotRun => "NOT_RUN", + Verdict::BlockedHardware => "BLOCKED_HARDWARE", + Verdict::BlockedOperator => "BLOCKED_OPERATOR", + Verdict::MissingImplementation => "MISSING_IMPLEMENTATION", + } + } + + /// CLI exit code: 0 PASS, 1 FAIL, 2 NOT_RUN, 3 BLOCKED_HARDWARE, + /// 4 BLOCKED_OPERATOR, 5 MISSING_IMPLEMENTATION. + pub fn exit_code(self) -> i32 { + match self { + Verdict::Pass => 0, + Verdict::Fail => 1, + Verdict::NotRun => 2, + Verdict::BlockedHardware => 3, + Verdict::BlockedOperator => 4, + Verdict::MissingImplementation => 5, + } + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Observation { + pub name: String, + pub value: Value, +} + +/// Parse `AIEN-OBS ` lines. Anything else, including a +/// malformed AIEN-OBS line (bad name, bad JSON, float), is ordinary log text. +pub fn parse_observations(stdout: &[u8]) -> Vec { + let text = String::from_utf8_lossy(stdout); + let mut out = Vec::new(); + for line in text.lines() { + let rest = match line.strip_prefix("AIEN-OBS ") { + Some(r) => r, + None => continue, + }; + let (name, json) = match rest.split_once(' ') { + Some(p) => p, + None => continue, + }; + if !valid_obs_name(name) { + continue; + } + if let Some(value) = parse_json_scalar(json.trim()) { + out.push(Observation { + name: name.to_string(), + value, + }); + } + } + out +} + +fn compare(op: Op, a: &Value, b: &Value) -> bool { + match op { + Op::Eq => a == b, + Op::Ne => a != b, + _ => match (a.as_i64(), b.as_i64()) { + (Some(x), Some(y)) => match op { + Op::Lt => x < y, + Op::Le => x <= y, + Op::Gt => x > y, + _ => x >= y, + }, + _ => false, + }, + } +} + +pub fn eval_rule(rule: &Rule, obs: &[Observation]) -> bool { + let vals: Vec<&Value> = obs + .iter() + .filter(|o| o.name == rule.name) + .map(|o| &o.value) + .collect(); + if vals.is_empty() { + return false; + } + match rule.quant { + Quant::Last => compare(rule.op, vals[vals.len() - 1], &rule.value), + Quant::All => vals.iter().all(|v| compare(rule.op, v, &rule.value)), + Quant::Any => vals.iter().any(|v| compare(rule.op, v, &rule.value)), + } +} + +/// Facts the runner measured. For a gate that did not run, `exit_status` is +/// None and `observations` is empty. +#[derive(Debug, Clone, Default)] +pub struct Facts { + /// Refusal id decided before running (dirty_tree, evidence_inside, ...). + pub refusal: Option, + pub exec_exists: bool, + pub exit_status: Option, + pub observations: Vec, + pub timed_out: bool, + /// `git status --porcelain` differed after the run. + pub tree_changed_after: bool, + pub head_moved: bool, +} + +#[derive(Debug, Clone, PartialEq)] +pub struct Derived { + pub verdict: Verdict, + pub reason: String, + /// Each `expects.observe` rule and whether it held. + pub rules: Vec<(String, bool)>, +} + +/// Rows 2 to 7: decided before anything runs. Some(..) means do not run. +pub fn pre_run( + m: &Manifest, + refusal: &Option, + exec_exists: bool, +) -> Option<(Verdict, String)> { + if m.requires.iter().any(|r| r == "operator") { + // Slice A has no operator attestation files, so this is always pending. + return Some(( + Verdict::BlockedOperator, + "OPERATOR_STEP_PENDING".to_string(), + )); + } + if let Some(d) = m.depends_on.first() { + // Slice A has no dependency graph; it cannot show the dependency passed. + return Some((Verdict::NotRun, format!("DEP_NOT_PASS:{d}"))); + } + if m.pool() != "host" { + return Some((Verdict::NotRun, format!("pool_unsupported:{}", m.pool()))); + } + if let Some(b) = &m.build { + if b.tool != "none" { + return Some((Verdict::NotRun, "build_unsupported".to_string())); + } + } + if let Some(c) = m.checks.iter().find(|c| c.as_str() != "clean_tree_after") { + return Some((Verdict::NotRun, format!("check_unsupported:{c}"))); + } + if let Some(r) = refusal { + return Some((Verdict::NotRun, r.clone())); + } + if !exec_exists { + return Some((Verdict::MissingImplementation, "NO_RUN_EXEC".to_string())); + } + None +} + +pub fn derive(m: &Manifest, f: &Facts) -> Derived { + if let Some((verdict, reason)) = pre_run(m, &f.refusal, f.exec_exists) { + return Derived { + verdict, + reason, + rules: m.rules.iter().map(|r| (r.text.clone(), false)).collect(), + }; + } + let rules: Vec<(String, bool)> = m + .rules + .iter() + .map(|r| (r.text.clone(), eval_rule(r, &f.observations))) + .collect(); + let (verdict, reason) = if f.timed_out { + (Verdict::Fail, "timeout".to_string()) + } else if f.exit_status != Some(m.expect_exit) { + (Verdict::Fail, "rc_nonzero".to_string()) + } else if let Some(idx) = rules.iter().position(|r| !r.1) { + (Verdict::Fail, format!("rule:{idx}")) + } else if f.tree_changed_after { + (Verdict::Fail, "dirty_after".to_string()) + } else if f.head_moved { + (Verdict::Fail, "head_moved".to_string()) + } else { + (Verdict::Pass, String::new()) + }; + Derived { + verdict, + reason, + rules, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::manifest; + use serde_json::json; + + fn m(extra_replace: Option<(&str, &str)>) -> Manifest { + let mut t = String::from( + "gate: G\nmanifest_version: 1\nowner: o\nrequires:\n - host\nrun:\n exec: x.sh\nexpects:\n exit: 0\n observe: [\"n == 3\", \"all k <= 2\"]\n verdict: PASS\ntimeout: 5s\n", + ); + if let Some((a, b)) = extra_replace { + assert!(t.contains(a), "replace target missing: {a}"); + t = t.replace(a, b); + } + manifest::parse(t.as_bytes()).unwrap() + } + + fn obs(name: &str, v: Value) -> Observation { + Observation { + name: name.to_string(), + value: v, + } + } + + fn good_facts() -> Facts { + Facts { + refusal: None, + exec_exists: true, + exit_status: Some(0), + observations: vec![obs("n", json!(3)), obs("k", json!(1)), obs("k", json!(2))], + timed_out: false, + tree_changed_after: false, + head_moved: false, + } + } + + #[test] + fn exit_codes_and_names_are_fixed() { + let all = [ + (Verdict::Pass, "PASS", 0), + (Verdict::Fail, "FAIL", 1), + (Verdict::NotRun, "NOT_RUN", 2), + (Verdict::BlockedHardware, "BLOCKED_HARDWARE", 3), + (Verdict::BlockedOperator, "BLOCKED_OPERATOR", 4), + (Verdict::MissingImplementation, "MISSING_IMPLEMENTATION", 5), + ]; + for (v, name, code) in all { + assert_eq!(v.as_str(), name); + assert_eq!(v.exit_code(), code); + } + } + + #[test] + fn all_expectations_met_is_pass() { + let d = derive(&m(None), &good_facts()); + assert_eq!(d.verdict, Verdict::Pass); + assert_eq!(d.reason, ""); + assert!(d.rules.iter().all(|r| r.1)); + } + + #[test] + fn rule_mismatch_is_fail_with_index() { + let mut f = good_facts(); + f.observations[0] = obs("n", json!(4)); + let d = derive(&m(None), &f); + assert_eq!(d.verdict, Verdict::Fail); + assert_eq!(d.reason, "rule:0"); + assert!(!d.rules[0].1); + assert!(d.rules[1].1); + } + + #[test] + fn printing_pass_cannot_make_a_pass() { + let mut f = good_facts(); + f.observations = parse_observations(b"PASS\nAIEN-OBS verdict \"PASS\"\n"); + let d = derive(&m(None), &f); + assert_eq!(d.verdict, Verdict::Fail); + } + + #[test] + fn missing_observation_does_not_hold() { + let mut f = good_facts(); + f.observations.retain(|o| o.name != "n"); + assert_eq!(derive(&m(None), &f).reason, "rule:0"); + } + + #[test] + fn exit_status_must_match_expectation() { + let mut f = good_facts(); + f.exit_status = Some(1); + let d = derive(&m(None), &f); + assert_eq!( + (d.verdict, d.reason.as_str()), + (Verdict::Fail, "rc_nonzero") + ); + f.exit_status = None; + assert_eq!(derive(&m(None), &f).reason, "rc_nonzero"); + // A manifest that expects exit 7 passes on 7 and fails on 0. + let m7 = m(Some(("exit: 0", "exit: 7"))); + f.exit_status = Some(7); + assert_eq!(derive(&m7, &f).verdict, Verdict::Pass); + f.exit_status = Some(0); + assert_eq!(derive(&m7, &f).verdict, Verdict::Fail); + } + + #[test] + fn timeout_beats_everything_after_run() { + let mut f = good_facts(); + f.timed_out = true; + f.exit_status = None; + let d = derive(&m(None), &f); + assert_eq!((d.verdict, d.reason.as_str()), (Verdict::Fail, "timeout")); + } + + #[test] + fn tree_and_head_changes_fail() { + let mut f = good_facts(); + f.tree_changed_after = true; + assert_eq!(derive(&m(None), &f).reason, "dirty_after"); + f.tree_changed_after = false; + f.head_moved = true; + assert_eq!(derive(&m(None), &f).reason, "head_moved"); + } + + #[test] + fn first_reason_wins() { + let mut f = good_facts(); + f.exit_status = Some(9); + f.observations.clear(); + f.tree_changed_after = true; + assert_eq!(derive(&m(None), &f).reason, "rc_nonzero"); + } + + #[test] + fn refusal_is_not_run() { + let mut f = good_facts(); + f.refusal = Some("dirty_tree".to_string()); + let d = derive(&m(None), &f); + assert_eq!( + (d.verdict, d.reason.as_str()), + (Verdict::NotRun, "dirty_tree") + ); + } + + #[test] + fn missing_exec_is_missing_implementation() { + let mut f = good_facts(); + f.exec_exists = false; + let d = derive(&m(None), &f); + assert_eq!(d.verdict, Verdict::MissingImplementation); + assert_eq!(d.reason, "NO_RUN_EXEC"); + } + + #[test] + fn operator_gate_is_blocked_operator() { + let mo = m(Some((" - host\n", " - host\n - operator\n"))); + let d = derive(&mo, &good_facts()); + assert_eq!(d.verdict, Verdict::BlockedOperator); + assert_eq!(d.reason, "OPERATOR_STEP_PENDING"); + } + + #[test] + fn other_pools_dependencies_build_and_checks_are_not_run() { + let g = m(Some((" - host\n", " - gb10\n"))); + assert_eq!(derive(&g, &good_facts()).reason, "pool_unsupported:gb10"); + let q = m(Some((" - host\n", " - qemu\n"))); + assert_eq!(derive(&q, &good_facts()).reason, "pool_unsupported:qemu"); + let d = m(Some(( + "timeout: 5s\n", + "timeout: 5s\ndepends_on:\n - OTHER\n", + ))); + let r = derive(&d, &good_facts()); + assert_eq!( + (r.verdict, r.reason.as_str()), + (Verdict::NotRun, "DEP_NOT_PASS:OTHER") + ); + let b = m(Some(( + "timeout: 5s\n", + "timeout: 5s\nbuild:\n target: t\n tool: make\n", + ))); + assert_eq!(derive(&b, &good_facts()).reason, "build_unsupported"); + let c = m(Some(( + "timeout: 5s\n", + "timeout: 5s\nchecks:\n - no_libm_symbols\n", + ))); + assert_eq!( + derive(&c, &good_facts()).reason, + "check_unsupported:no_libm_symbols" + ); + } + + #[test] + fn build_none_and_clean_tree_check_are_fine() { + let b = m(Some(( + "timeout: 5s\n", + "timeout: 5s\nbuild:\n target: t\n tool: none\nchecks:\n - clean_tree_after\n", + ))); + assert_eq!(derive(&b, &good_facts()).verdict, Verdict::Pass); + } + + #[test] + fn observation_parsing() { + let o = parse_observations( + b"noise\nAIEN-OBS a 1\nAIEN-OBS b \"x y\"\nAIEN-OBS c 1.5\nAIEN-OBS BAD 1\nAIEN-OBS d\nAIEN-OBS a 2\nAIEN-OBS e true\nAIEN-OBS f nope\n", + ); + let names: Vec<&str> = o.iter().map(|x| x.name.as_str()).collect(); + assert_eq!(names, vec!["a", "b", "a", "e"]); + assert_eq!(o[1].value, json!("x y")); + } + + #[test] + fn quantifiers_and_ordering() { + let r = manifest::parse_rule("any k > 5").unwrap(); + let o = vec![obs("k", json!(1)), obs("k", json!(9))]; + assert!(eval_rule(&r, &o)); + let r = manifest::parse_rule("k > 5").unwrap(); + assert!(eval_rule(&r, &o), "last value 9 > 5"); + let r = manifest::parse_rule("all k > 5").unwrap(); + assert!(!eval_rule(&r, &o)); + let r = manifest::parse_rule("k < 5").unwrap(); + assert!(!eval_rule(&r, &o)); + // Ordering over strings never holds. + let r = manifest::parse_rule("s < 5").unwrap(); + assert!(!eval_rule(&r, &[obs("s", json!("a"))])); + let r = manifest::parse_rule("s != \"a\"").unwrap(); + assert!(eval_rule(&r, &[obs("s", json!("b"))])); + } +} From 28564d5e9b3099f080169564d91623c1f2f74ba1 Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Fri, 2 Oct 2026 01:09:38 -0500 Subject: [PATCH 2/2] aien-test: satisfy clippy question_mark in parse_duration_ms Rewrite the final strip_suffix('h') branch to use ? so cargo clippy -D warnings passes (CI Cargo Clippy Invariant failed at 5c6a6e14; same lint failed the forge clippy line). Behaviour is unchanged: no recognised suffix returns None. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01DsjWa6csUe4NxndCTmugHu --- tools/aien-test/src/manifest.rs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tools/aien-test/src/manifest.rs b/tools/aien-test/src/manifest.rs index 0af65ad6..6fff3d8e 100644 --- a/tools/aien-test/src/manifest.rs +++ b/tools/aien-test/src/manifest.rs @@ -302,10 +302,9 @@ pub fn parse_duration_ms(s: &str) -> Option { (n, 1000) } else if let Some(n) = s.strip_suffix('m') { (n, 60_000) - } else if let Some(n) = s.strip_suffix('h') { - (n, 3_600_000) } else { - return None; + let n = s.strip_suffix('h')?; + (n, 3_600_000) }; if num.is_empty() || !num.chars().all(|c| c.is_ascii_digit()) { return None;