aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
GitHub aien-dev/aien-sovereign-core-mv#190 (code only)
Apply it
git checkout -b patch-7595e4003c0626d4 14126c62f0ac4a89f04ed8b9ea68c17c014b0518 curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/7595e4003c0626d4.patch | git am
Provenance
github-import 1
aien-dev/aien-sovereign-core-mv
190
9b89be97d719b4ca934c24db3e184631d4cda2de
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":190,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/190","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:36:14Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/tools/aien-test/mutations/aien-test.mutants b/tools/aien-test/mutations/aien-test.mutants index b743d208..bee428dd 100644 --- a/tools/aien-test/mutations/aien-test.mutants +++ b/tools/aien-test/mutations/aien-test.mutants @@ -51,3 +51,15 @@ cache_never_ignored cache.rs s#if !cache_allowed {#if false {# a gate that says cache_reuse_keeps_old_commit cache.rs s#core\["commit"\] = json!(commit);#let _ = commit;# a reuse receipt still names the old commit, so the new commit looks unchecked cache_dirty_tree_looks_up runner.rs s#if mode == cache::Mode::Allow \&\& (opts.args_override.is_some() || !tree_clean) {#if false {# a tree with uncommitted changes (or replacement args) still consults the cache cache_no_cache_ignored runner.rs s#cache::policy(m.cache_allowed, opts.no_cache)#cache::policy(m.cache_allowed, false)# --no-cache does not force a fresh run +identity_machine_scope_ignored identity.rs s#CacheScope::Machine => b.machine_digest.clone(),#CacheScope::Machine => String::new(),# a machine-scoped check id no longer depends on the machine, so a result from another machine is reused +identity_dependencies_dropped identity.rs s#"dependency_check_ids": deps,#"dependency_check_ids": Vec::<String>::new(),# a check id ignores the checks it declares it depends on, so a changed dependency leaves it unchanged +identity_compiler_ignored identity.rs s#"compiler_identity": compiler_identity,#"compiler_identity": "",# a different compiler gives the same check id +identity_flags_ignored identity.rs s#"flags": flags,#"flags": Vec::<String>::new(),# different build flags give the same check id +identity_dependency_ids_unsorted identity.rs s#^ deps.sort();# let _ = \&deps;# the order the dependency ids are given in changes the check id +identity_missing_input_dropped identity.rs s#rows.entry(spec.to_string()).or_insert(None);#let _ = spec;# a declared input that matches no tracked file leaves no trace in the identity +identity_golden_not_hashed identity.rs s#goldens.push(sha256_hex(&bytes));#let _ = \&bytes;# editing the golden file does not change the check id +planner_drops_dependencies identity.rs s#graph.with_dependencies(&seeds)#seeds.into_iter().collect()# path filtering selects the changed gate but drops the gates it declares it depends on +v2_tolerance_without_bounded_allowed manifest.rs s#if tolerance.is_some() \&\& exactness != Exactness::Bounded {#if false {# a tolerance is accepted on an EXACT check +v2_analog_eligible_for_exact manifest.rs s#if is_analog(b) \&\& exactness == Exactness::Exact {#if false {# an analog backend may be eligible for an EXACT check +v2_canonical_outside_eligible manifest.rs s#if !eligible.contains(&canonical) {#if false {# a canonical backend that is not eligible is accepted +v1_accepts_v2_keys manifest.rs s#entries.iter().find(|e| V2_KEYS.contains(\&e.key.as_str()))#entries.iter().find(|_e| false)# a v1 manifest may use v2 keys, so it is no longer strictly v1 diff --git a/tools/aien-test/src/cli.rs b/tools/aien-test/src/cli.rs index 92851cbe..7d25d69e 100644 --- a/tools/aien-test/src/cli.rs +++ b/tools/aien-test/src/cli.rs @@ -6,6 +6,7 @@ //! aien-test test ./... | gate:NAME [flags] //! aien-test why GATE_FILE_OR_NAME [flags] //! aien-test list [flags] +//! aien-test identity GATE_FILE_OR_NAME [--compiler-identity S] [--flag F]... [--hardware-identity S] //! ``` //! //! `test changed`, `test crate:NAME`, `--host/--qemu/--gb10`, `--mutants` and @@ -19,6 +20,7 @@ pub const USAGE: &str = "usage: aien-test test ./... | gate:NAME [flags] aien-test why GATE_FILE_OR_NAME [flags] aien-test list [flags] + aien-test identity GATE_FILE_OR_NAME [--compiler-identity S] [--flag F]... [--hardware-identity S] flags: --evidence-dir DIR --allow-dirty --no-cache --jobs host=N,qemu=M --wait-gpu"; /// Which gates `test` runs. @@ -36,6 +38,7 @@ pub enum Command { Test(Selection), Why { gate: String }, List, + Identity { gate: String }, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -51,6 +54,13 @@ pub struct Cli { pub jobs: JobsSpec, /// `--wait-gpu`: wait for a held GPU lock instead of refusing. pub wait_gpu: bool, + /// `identity` only: the compiler identity string (default empty: nothing + /// here builds yet). + pub compiler_identity: String, + /// `identity` only: `--flag F`, repeatable, order kept. + pub flags: Vec<String>, + /// `identity` only: needed for `cache_scope: hardware`. + pub hardware_identity: Option<String>, } fn parse_selection(s: &str) -> Result<Selection, String> { @@ -70,7 +80,7 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { .first() .map(|s| s.as_str()) .ok_or_else(|| "no command".to_string())?; - if !["run", "test", "why", "list"].contains(&name) { + if !["run", "test", "why", "list", "identity"].contains(&name) { return Err(format!("unknown command {name:?}")); } let mut positional: Option<String> = None; @@ -80,6 +90,10 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { let mut args: Option<Vec<String>> = None; let mut jobs = JobsSpec::default(); let mut wait_gpu = false; + let mut compiler_identity = String::new(); + let mut flags: Vec<String> = Vec::new(); + let mut hardware_identity: Option<String> = None; + let mut identity_flags = false; let mut i = 1; while i < argv.len() { let a = argv[i].as_str(); @@ -98,6 +112,18 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { Some(v) => jobs = parse_jobs(v)?, None => return Err("--jobs needs a value".to_string()), } + } else if a == "--compiler-identity" || a == "--flag" || a == "--hardware-identity" { + identity_flags = true; + i += 1; + let v = match argv.get(i) { + Some(v) => v.clone(), + None => return Err(format!("{a} needs a value")), + }; + match a { + "--compiler-identity" => compiler_identity = v, + "--flag" => flags.push(v), + _ => hardware_identity = Some(v), + } } else if a == "--allow-dirty" { allow_dirty = true; } else if a == "--no-cache" { @@ -116,7 +142,16 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { if args.is_some() && name != "run" { return Err("-- ARGS only apply to the run command".to_string()); } + if identity_flags && name != "identity" { + return Err( + "--compiler-identity, --flag and --hardware-identity only apply to identity" + .to_string(), + ); + } let command = match name { + "identity" => Command::Identity { + gate: positional.ok_or("missing GATE_FILE_OR_NAME")?, + }, "run" => Command::Run { gate: positional.ok_or("missing GATE_FILE_OR_NAME")?, }, @@ -142,6 +177,9 @@ pub fn parse_args(argv: &[String]) -> Result<Cli, String> { args, jobs, wait_gpu, + compiler_identity, + flags, + hardware_identity, }) } @@ -268,6 +306,31 @@ mod tests { assert!(parse_args(&v(&["list", "extra"])).is_err()); } + #[test] + fn identity_command_and_its_flags() { + let c = parse_args(&v(&[ + "identity", + "G", + "--compiler-identity", + "rustc 1", + "--flag", + "-O", + "--flag", + "-C", + "--hardware-identity", + "gb10-1", + ])) + .unwrap(); + assert_eq!(c.command, Command::Identity { gate: "G".into() }); + assert_eq!(c.compiler_identity, "rustc 1"); + assert_eq!(c.flags, v(&["-O", "-C"])); + assert_eq!(c.hardware_identity.as_deref(), Some("gb10-1")); + assert!(parse_args(&v(&["identity"])).is_err()); + assert!(parse_args(&v(&["identity", "G", "--flag"])).is_err()); + assert!(parse_args(&v(&["run", "G", "--flag", "x"])).is_err()); + assert!(parse_args(&v(&["list", "--compiler-identity", "x"])).is_err()); + } + #[test] fn override_args_only_for_run() { assert!(parse_args(&v(&["test", "./...", "--", "x"])).is_err()); diff --git a/tools/aien-test/src/identity.rs b/tools/aien-test/src/identity.rs new file mode 100644 index 00000000..5a18c918 --- /dev/null +++ b/tools/aien-test/src/identity.rs @@ -0,0 +1,513 @@ +//! Check identity (ADR 0033 Decision 3). +//! +//! `check_id` is sha256 over the canonical JSON object +//! `{manifest_digest, input_blob_ids, compiler_identity, flags, +//! dependency_check_ids, golden_digests, scope_binding}`. Same inputs give the +//! same id; a different input byte, compiler, flag, declared dependency, +//! golden file, or (for the machine and hardware scopes) machine gives a +//! different id. It is ADR 0028 Decision 7's cache key made explicit about +//! scope. +//! +//! Input identity is the git blob id of every tracked file under each +//! `inputs` entry, read with `git ls-files -s` (no git library). The index is +//! what is read, so an uncommitted edit to a tracked file is not seen: the +//! runner already refuses dirty trees, and `aien-test identity` is meant for +//! clean ones. A declared input that matches no tracked file is recorded with +//! a null blob id rather than dropped, so a typo or a deletion changes the id. + +use crate::evidence::{canonical, sha256_hex}; +use crate::graph::Graph; +use crate::manifest::{CacheScope, Manifest}; +use crate::process; +use serde_json::{json, Value}; +use std::collections::{BTreeMap, BTreeSet}; +use std::fs; +use std::path::Path; +use std::process::Command; + +/// What the `scope_binding` member is built from. Only the part the manifest's +/// `cache_scope` names is used. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Binding { + /// The `arch` string (`std::env::consts::ARCH` on the real machine). + pub arch: String, + /// The ADR 0028 `machine_digest`. + pub machine_digest: String, + /// The hardware identity block for `cache_scope: hardware`. The ADR names + /// it but does not define its content (UNVERIFIED); the caller supplies it. + pub hardware_identity: String, +} + +fn git_ls_files(root: &Path, spec: &str) -> Result<Vec<(String, String)>, String> { + let mut cmd = Command::new("git"); + cmd.env("GIT_OPTIONAL_LOCKS", "0") + .arg("-C") + .arg(root) + .args(["ls-files", "-s", "-z", "--"]) + .arg(format!(":(literal){spec}")); + let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run git: {e}"))?; + if !out.status.success() { + return Err(format!( + "git ls-files failed: {}", + String::from_utf8_lossy(&out.stderr).trim() + )); + } + let text = String::from_utf8(out.stdout).map_err(|_| "git output is not UTF-8".to_string())?; + let mut rows = Vec::new(); + for rec in text.split('\0').filter(|r| !r.is_empty()) { + let (meta, path) = rec + .split_once('\t') + .ok_or_else(|| format!("unparsable ls-files record {rec:?}"))?; + let f: Vec<&str> = meta.split(' ').collect(); + if f.len() != 3 || f[1].len() != 40 { + return Err(format!("unparsable ls-files record {rec:?}")); + } + if f[2] != "0" { + return Err(format!("{path} has an unmerged index entry")); + } + rows.push((path.to_string(), f[1].to_string())); + } + Ok(rows) +} + +/// `[{path, blob_id}]` sorted by path, one row per tracked file under the +/// manifest's `inputs`; a path that matches nothing gets `blob_id: null`. +pub fn input_blob_ids(m: &Manifest, root: &Path) -> Result<Vec<Value>, String> { + let mut rows: BTreeMap<String, Option<String>> = BTreeMap::new(); + for input in &m.inputs { + let spec = input.trim_end_matches('/'); + let found = git_ls_files(root, spec)?; + if found.is_empty() { + rows.entry(spec.to_string()).or_insert(None); + } + for (path, blob) in found { + rows.insert(path, Some(blob)); + } + } + Ok(rows + .into_iter() + .map(|(path, blob)| json!({ "path": path, "blob_id": blob })) + .collect()) +} + +/// The scope binding string for the manifest's `cache_scope`. +pub fn scope_binding(scope: CacheScope, b: &Binding) -> Result<String, String> { + Ok(match scope { + CacheScope::Portable => String::new(), + CacheScope::Arch => b.arch.clone(), + CacheScope::Machine => b.machine_digest.clone(), + CacheScope::Hardware => { + if b.hardware_identity.is_empty() { + return Err("cache_scope hardware needs a hardware identity".into()); + } + format!("{}:{}", b.machine_digest, b.hardware_identity) + } + }) +} + +/// Gates this check declares it rests on: `depends_on` plus an `oracle` +/// `compare` gate, sorted, no repeats. +pub fn declared_dependencies(m: &Manifest) -> Vec<String> { + let mut set: BTreeSet<String> = m.depends_on.iter().cloned().collect(); + if let Some(c) = &m.oracle.compare { + set.insert(c.clone()); + } + set.into_iter().collect() +} + +/// The object that `check_id` hashes. +pub fn identity_object( + m: &Manifest, + root: &Path, + compiler_identity: &str, + flags: &[String], + dependency_check_ids: &[String], + binding: &Binding, +) -> Result<Value, String> { + let mut deps: Vec<String> = dependency_check_ids.to_vec(); + deps.sort(); + let mut goldens: Vec<String> = Vec::new(); + if let Some(g) = &m.oracle.golden { + let bytes = fs::read(root.join(g)).map_err(|e| format!("cannot read golden {g}: {e}"))?; + goldens.push(sha256_hex(&bytes)); + } + goldens.sort(); + Ok(json!({ + "manifest_digest": m.digest, + "input_blob_ids": input_blob_ids(m, root)?, + "compiler_identity": compiler_identity, + "flags": flags, + "dependency_check_ids": deps, + "golden_digests": goldens, + "scope_binding": scope_binding(m.cache_scope, binding)?, + })) +} + +pub fn id_of(object: &Value) -> Result<String, String> { + let bytes = canonical(object).map_err(|e| e.to_string())?; + Ok(sha256_hex(&bytes)) +} + +/// `check_id` (ADR 0033 Decision 3). +pub fn check_id( + m: &Manifest, + root: &Path, + compiler_identity: &str, + flags: &[String], + dependency_check_ids: &[String], + binding: &Binding, +) -> Result<String, String> { + id_of(&identity_object( + m, + root, + compiler_identity, + flags, + dependency_check_ids, + binding, + )?) +} + +/// Ids and hashed objects for gate `target` and everything it rests on, +/// dependencies first. Dependency ids are computed with the same compiler, +/// flags and binding. +pub fn graph_identities( + graph: &Graph, + target: usize, + root: &Path, + compiler_identity: &str, + flags: &[String], + binding: &Binding, +) -> Result<BTreeMap<String, (String, Value)>, String> { + let wanted = graph.with_dependencies(&[target]); + let mut done: BTreeMap<String, (String, Value)> = BTreeMap::new(); + for &i in graph.order() { + if !wanted.contains(&i) { + continue; + } + let m = &graph.node(i).manifest; + let mut dep_ids = Vec::new(); + for d in declared_dependencies(m) { + match done.get(&d) { + Some((id, _)) => dep_ids.push(id.clone()), + None => return Err(format!("gate {} declares unknown dependency {d}", m.gate)), + } + } + let obj = identity_object(m, root, compiler_identity, flags, &dep_ids, binding)?; + let id = id_of(&obj)?; + done.insert(m.gate.clone(), (id, obj)); + } + Ok(done) +} + +/// Planner-style path filter: the gates whose `inputs` contain a changed +/// path, plus everything each of them declares it depends on. A declared +/// dependency is never dropped by path filtering (ADR 0033 test 17). +pub fn select_changed(graph: &Graph, changed: &[String]) -> BTreeSet<usize> { + let touched: Vec<usize> = (0..graph.len()) + .filter(|&i| { + graph.node(i).manifest.inputs.iter().any(|input| { + let dir = input.trim_end_matches('/'); + changed + .iter() + .any(|c| c == dir || c.starts_with(&format!("{dir}/"))) + }) + }) + .collect(); + let mut seeds = touched; + for &i in &seeds.clone() { + if let Some(j) = graph + .node(i) + .manifest + .oracle + .compare + .as_deref() + .and_then(|c| graph.index_of(c)) + { + seeds.push(j); + } + } + graph.with_dependencies(&seeds) +} + +/// The binding for the machine this process runs on. +pub fn local_binding(hardware_identity: &str) -> Result<Binding, String> { + let machine = crate::runner::machine(&crate::resources::Hardware::detect()); + let machine_digest = crate::evidence::canonical_digest(&machine).map_err(|e| e.to_string())?; + Ok(Binding { + arch: std::env::consts::ARCH.to_string(), + machine_digest, + hardware_identity: hardware_identity.to_string(), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::graph; + use crate::manifest; + use crate::testutil::{git, init_repo, write_file, TempDir}; + + fn gate(id: &str, extra: &str) -> String { + format!( + "gate: {id}\nmanifest_version: 2\nowner: t\nrequires:\n - host\ninputs:\n - data_{id}/\nrun:\n exec: tools/run.sh\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 5s\n{extra}" + ) + } + + fn binding(machine: &str) -> Binding { + Binding { + arch: "aarch64".into(), + machine_digest: machine.repeat(64), + hardware_identity: "hw-1".into(), + } + } + + fn repo(extra: &str) -> TempDir { + let g = gate("A", extra); + init_repo( + "ident", + &[ + ("gates/a.gate", g.as_str(), false), + ("tools/run.sh", "#!/bin/sh\nexit 0\n", true), + ("data_A/one.txt", "one\n", false), + ("data_A/sub/two.txt", "two\n", false), + ("elsewhere.txt", "x\n", false), + ], + ) + } + + fn parsed(t: &TempDir) -> Manifest { + manifest::parse(&std::fs::read(t.path().join("gates/a.gate")).unwrap()).unwrap() + } + + fn id(t: &TempDir, compiler: &str, flags: &[&str], deps: &[&str], b: &Binding) -> String { + let flags: Vec<String> = flags.iter().map(|s| s.to_string()).collect(); + let deps: Vec<String> = deps.iter().map(|s| s.to_string()).collect(); + check_id(&parsed(t), t.path(), compiler, &flags, &deps, b).unwrap() + } + + fn commit(t: &TempDir, rel: &str, content: &str) { + write_file(t.path(), rel, content, false); + git(t.path(), &["add", "-A"]); + git(t.path(), &["commit", "-q", "-m", "edit"]); + } + + #[test] + fn t1_same_inputs_twice_give_the_same_id() { + let t = repo(""); + let b = binding("a"); + let first = id(&t, "rustc 1", &["-O"], &[], &b); + assert_eq!(first.len(), 64); + assert_eq!(first, id(&t, "rustc 1", &["-O"], &[], &b)); + // A second repository with byte-identical content has the same id. + let u = repo(""); + assert_eq!(first, id(&u, "rustc 1", &["-O"], &[], &b)); + } + + #[test] + fn t2_one_input_byte_changes_the_id_and_an_unrelated_file_does_not() { + let t = repo(""); + let b = binding("a"); + let before = id(&t, "c", &[], &[], &b); + commit(&t, "elsewhere.txt", "y\n"); + assert_eq!(before, id(&t, "c", &[], &[], &b)); + commit(&t, "data_A/sub/two.txt", "twp\n"); + let after = id(&t, "c", &[], &[], &b); + assert_ne!(before, after); + commit(&t, "data_A/sub/two.txt", "two\n"); + assert_eq!(before, id(&t, "c", &[], &[], &b)); + } + + #[test] + fn input_blob_ids_are_sorted_git_blob_ids_and_missing_inputs_are_kept() { + let t = repo(""); + let rows = input_blob_ids(&parsed(&t), t.path()).unwrap(); + let paths: Vec<&str> = rows.iter().map(|r| r["path"].as_str().unwrap()).collect(); + assert_eq!(paths, ["data_A/one.txt", "data_A/sub/two.txt"]); + // git's own blob id of "one\n". + let mut cmd = Command::new("git"); + cmd.args(["hash-object", "--stdin"]) + .stdin(std::process::Stdio::piped()) + .stdout(std::process::Stdio::piped()); + let mut child = cmd.spawn().unwrap(); + std::io::Write::write_all(child.stdin.as_mut().unwrap(), b"one\n").unwrap(); + let out = child.wait_with_output().unwrap(); + assert_eq!( + rows[0]["blob_id"].as_str().unwrap(), + String::from_utf8_lossy(&out.stdout).trim() + ); + // A declared input that matches no tracked file is a null row. + let g = gate("A", "").replace("data_A/", "nothing_here/"); + let m = manifest::parse(g.as_bytes()).unwrap(); + let rows = input_blob_ids(&m, t.path()).unwrap(); + assert_eq!(rows.len(), 1); + assert!(rows[0]["blob_id"].is_null()); + // An untracked file under an input is not part of the identity. + let before = id(&t, "c", &[], &[], &binding("a")); + write_file(t.path(), "data_A/untracked.txt", "u\n", false); + assert_eq!(before, id(&t, "c", &[], &[], &binding("a"))); + } + + #[test] + fn t3_compiler_identity_and_flags_change_the_id() { + let t = repo(""); + let b = binding("a"); + let base = id(&t, "rustc 1", &["-O"], &[], &b); + assert_ne!(base, id(&t, "rustc 2", &["-O"], &[], &b)); + assert_ne!(base, id(&t, "rustc 1", &["-O3"], &[], &b)); + assert_ne!(base, id(&t, "rustc 1", &[], &[], &b)); + assert_ne!(base, id(&t, "rustc 1", &["-O", "-g"], &[], &b)); + } + + #[test] + fn t4_machine_scope_follows_the_machine_and_portable_does_not() { + let machine = repo("cache_scope: machine\n"); + let portable = repo("cache_scope: portable\n"); + let arch = repo("cache_scope: arch\n"); + let (a, z) = (binding("a"), binding("b")); + assert_ne!( + id(&machine, "c", &[], &[], &a), + id(&machine, "c", &[], &[], &z) + ); + assert_eq!( + id(&portable, "c", &[], &[], &a), + id(&portable, "c", &[], &[], &z) + ); + assert_eq!(id(&arch, "c", &[], &[], &a), id(&arch, "c", &[], &[], &z)); + let mut other_arch = binding("a"); + other_arch.arch = "x86_64".into(); + assert_ne!( + id(&arch, "c", &[], &[], &a), + id(&arch, "c", &[], &[], &other_arch) + ); + // The default scope is machine. + let default = repo(""); + assert_eq!(parsed(&default).cache_scope, CacheScope::Machine); + } + + #[test] + fn hardware_scope_adds_the_hardware_identity_and_refuses_without_it() { + let t = repo("cache_scope: hardware\n"); + let a = binding("a"); + let mut other = a.clone(); + other.hardware_identity = "hw-2".into(); + assert_ne!(id(&t, "c", &[], &[], &a), id(&t, "c", &[], &[], &other)); + let mut none = a.clone(); + none.hardware_identity = String::new(); + assert!(check_id(&parsed(&t), t.path(), "c", &[], &[], &none).is_err()); + // The portable scope binds to nothing at all. + assert_eq!(scope_binding(CacheScope::Portable, &a).unwrap(), ""); + assert_eq!(scope_binding(CacheScope::Arch, &a).unwrap(), "aarch64"); + } + + #[test] + fn golden_file_bytes_enter_the_identity() { + let g = gate("A", "oracle:\n golden: golden.txt\n"); + let t = init_repo( + "ident-golden", + &[ + ("gates/a.gate", g.as_str(), false), + ("tools/run.sh", "#!/bin/sh\n", true), + ("golden.txt", "v1\n", false), + ], + ); + let b = binding("a"); + let first = id(&t, "c", &[], &[], &b); + write_file(t.path(), "golden.txt", "v2\n", false); + assert_ne!(first, id(&t, "c", &[], &[], &b)); + std::fs::remove_file(t.path().join("golden.txt")).unwrap(); + assert!(check_id(&parsed(&t), t.path(), "c", &[], &[], &b).is_err()); + } + + #[test] + fn dependency_ids_are_sorted_and_part_of_the_object() { + let t = repo(""); + let b = binding("a"); + let x = "x".repeat(64); + let y = "y".repeat(64); + let obj = + identity_object(&parsed(&t), t.path(), "c", &[], &[y.clone(), x.clone()], &b).unwrap(); + assert_eq!(obj["dependency_check_ids"], serde_json::json!([x, y])); + assert_eq!( + id(&t, "c", &[], &["x", "y"], &b), + id(&t, "c", &[], &["y", "x"], &b) + ); + assert_ne!(id(&t, "c", &[], &["x"], &b), id(&t, "c", &[], &[], &b)); + for k in [ + "manifest_digest", + "input_blob_ids", + "compiler_identity", + "flags", + "golden_digests", + "scope_binding", + ] { + assert!(obj.get(k).is_some(), "{k}"); + } + assert_eq!(obj.as_object().unwrap().len(), 7); + } + + fn two_gate_repo() -> TempDir { + let a = gate("A", "depends_on:\n - B\n"); + let b = gate("B", ""); + init_repo( + "ident-graph", + &[ + ("gates/a.gate", a.as_str(), false), + ("gates/b.gate", b.as_str(), false), + ("tools/run.sh", "#!/bin/sh\n", true), + ("data_A/a.txt", "a\n", false), + ("data_B/b.txt", "b\n", false), + ], + ) + } + + #[test] + fn t17_a_declared_dependency_is_part_of_the_identity_even_when_no_changed_path_touches_it() { + let t = two_gate_repo(); + let b = binding("a"); + let g = graph::load(t.path()).unwrap(); + let ia = g.index_of("A").unwrap(); + let before = graph_identities(&g, ia, t.path(), "c", &[], &b).unwrap(); + // Only B's input changes. A's own inputs are untouched, but A's id moves. + commit(&t, "data_B/b.txt", "b2\n"); + let g = graph::load(t.path()).unwrap(); + let after = graph_identities(&g, ia, t.path(), "c", &[], &b).unwrap(); + assert_ne!(before["B"].0, after["B"].0); + assert_ne!(before["A"].0, after["A"].0); + assert_eq!( + before["A"].1["input_blob_ids"], + after["A"].1["input_blob_ids"] + ); + // A's recorded dependency id is exactly B's id. + assert_eq!( + after["A"].1["dependency_check_ids"], + serde_json::json!([after["B"].0]) + ); + } + + #[test] + fn t17_path_filtering_keeps_declared_dependencies() { + let t = two_gate_repo(); + let g = graph::load(t.path()).unwrap(); + let (ia, ib) = (g.index_of("A").unwrap(), g.index_of("B").unwrap()); + // Only A's input changed; B is not touched by any changed path, yet + // A cannot be checked without it. + let picked = select_changed(&g, &["data_A/a.txt".to_string()]); + assert!(picked.contains(&ia)); + assert!(picked.contains(&ib)); + // Only B changed: B alone is selected (dependents are not pulled in). + let picked = select_changed(&g, &["data_B/b.txt".to_string()]); + assert!(picked.contains(&ib) && !picked.contains(&ia)); + // Nothing relevant changed: nothing selected. + assert!(select_changed(&g, &["elsewhere.txt".to_string()]).is_empty()); + // A path that merely shares a name prefix with an input does not match. + assert!(select_changed(&g, &["data_A2/a.txt".to_string()]).is_empty()); + } + + #[test] + fn an_oracle_compare_gate_is_a_declared_dependency() { + let m = + manifest::parse(gate("A", "oracle:\n compare: B\ndepends_on:\n - C\n").as_bytes()) + .unwrap(); + assert_eq!(declared_dependencies(&m), ["B", "C"]); + } +} diff --git a/tools/aien-test/src/lib.rs b/tools/aien-test/src/lib.rs index d3db6cbe..d14089ed 100644 --- a/tools/aien-test/src/lib.rs +++ b/tools/aien-test/src/lib.rs @@ -6,11 +6,41 @@ //! Tests report observations; this crate derives the verdict and writes an //! immutable, content-addressed receipt. See `manifest`, `verdict`, //! `evidence`, `process`, `runner`, `graph`, `resources`, `why`, `cache`. +//! +//! # Manifest v2 and check identity (Slice D, ADR 0033 Decisions 2 and 3) +//! +//! `manifest_version: 2` adds optional keys; a v1 manifest parses to the same +//! values as before and may not use them. Defaults in brackets. +//! +//! - `exactness`: `EXACT` [default], `BOUNDED`, `APPROXIMATE`, `ADVISORY`. +//! - `requires`: v1 values plus `portable`, `aarch64`, `nvrm`, `bare_metal`, +//! `analog_eligible` [`host`; optional in v2]. One of host, qemu, gb10, +//! nvrm, portable, aarch64 is needed. +//! - `tolerance` (child lines `metric`, `abs`, `rel_ppm`, integers only): +//! required for `BOUNDED`, refused otherwise. +//! - `backends` (children `eligible: [..]`, `canonical: X`) from `portable, +//! spark, qemu, gb10, analog_sim, analog_device`. [eligible implied by +//! `requires`; canonical is spark, or portable when `requires` is only +//! portable, or the first digital eligible one when spark is not eligible]. +//! - `fallback` [`["spark"]`], `cache_scope`: `portable|arch|machine|hardware` +//! [`machine`], `oracle` (child `golden: PATH` or `compare: GATE`). +//! - Refusals: tolerance without BOUNDED (and BOUNDED without tolerance); +//! `analog_sim`/`analog_device` eligible, or `analog_eligible` required, for +//! an EXACT check; an analog canonical backend for EXACT or BOUNDED; a +//! canonical backend not in `eligible`; any unknown enum value or key. +//! +//! `identity::check_id` is sha256 over the canonical object +//! `{manifest_digest, input_blob_ids, compiler_identity, flags, +//! dependency_check_ids, golden_digests, scope_binding}`. `aien-test identity +//! GATE [--compiler-identity S] [--flag F]... [--hardware-identity S]` prints +//! `CHECK_ID` and the `OBJECT` it hashed (and the ids of the gates it rests +//! on). pub mod cache; pub mod cli; pub mod evidence; pub mod graph; +pub mod identity; pub mod manifest; pub mod process; pub mod resources; diff --git a/tools/aien-test/src/main.rs b/tools/aien-test/src/main.rs index 9172b2aa..709c868c 100644 --- a/tools/aien-test/src/main.rs +++ b/tools/aien-test/src/main.rs @@ -7,10 +7,13 @@ //! campaign verdict: any FAIL gives 1, else the worst of 2 to 5, else 0. //! - `why GATE`: explain a gate's state from the receipts already written. //! - `list`: list the gates and their dependencies. +//! - `identity GATE`: print the check id (ADR 0033 Decision 3) and the object it +//! hashed, for the gate and everything it depends on. use aien_test::cli::{parse_args, Cli, Command, Selection, USAGE}; use aien_test::evidence::{Index, Store}; use aien_test::graph::{self, GraphError}; +use aien_test::identity; use aien_test::runner::{self, CacheNote, Options, RunError}; use aien_test::verdict::Verdict; use aien_test::why; @@ -43,6 +46,7 @@ fn real_main() -> i32 { Command::Test(selection) => cmd_test(&cli, selection, &cwd), Command::Why { gate } => cmd_why(&cli, gate, &cwd), Command::List => cmd_list(&cwd), + Command::Identity { gate } => cmd_identity(&cli, gate, &cwd), } } @@ -226,6 +230,56 @@ fn cmd_why(cli: &Cli, gate: &str, cwd: &Path) -> i32 { 0 } +fn cmd_identity(cli: &Cli, gate: &str, cwd: &Path) -> i32 { + let root = match repo_root_or_report(cwd) { + Ok(r) => r, + Err(code) => return code, + }; + let graph = match graph::load(&root) { + Ok(g) => g, + Err(e) => return graph_error(&e), + }; + let target = match why::resolve_target(&graph, cwd, gate) { + Ok(i) => i, + Err(e) => { + println!("AIEN_TEST: BAD_MANIFEST {e}"); + return 1; + } + }; + let node = graph.node(target); + let binding = match identity::local_binding(cli.hardware_identity.as_deref().unwrap_or("")) { + Ok(b) => b, + Err(e) => { + println!("AIEN_TEST: FAIL {e}"); + return 1; + } + }; + let ids = match identity::graph_identities( + &graph, + target, + &root, + &cli.compiler_identity, + &cli.flags, + &binding, + ) { + Ok(i) => i, + Err(e) => { + println!("AIEN_TEST: FAIL {e}"); + return 1; + } + }; + for (g, (id, _)) in &ids { + if *g != node.id { + println!("DEPENDENCY {g} CHECK_ID {id}"); + } + } + if let Some((id, obj)) = ids.get(&node.id) { + println!("CHECK_ID {id}"); + println!("OBJECT {}", obj); + } + 0 +} + fn cmd_list(cwd: &Path) -> i32 { let root = match repo_root_or_report(cwd) { Ok(r) => r, diff --git a/tools/aien-test/src/manifest.rs b/tools/aien-test/src/manifest.rs index 6fff3d8e..b5a648d9 100644 --- a/tools/aien-test/src/manifest.rs +++ b/tools/aien-test/src/manifest.rs @@ -60,6 +60,84 @@ pub struct Build { pub tool: String, } +/// Epistemic requirement of a check (ADR 0033 Decision 2). v1 manifests are +/// always `Exact`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Exactness { + Exact, + Bounded, + Approximate, + Advisory, +} + +impl Exactness { + pub fn as_str(self) -> &'static str { + match self { + Exactness::Exact => "EXACT", + Exactness::Bounded => "BOUNDED", + Exactness::Approximate => "APPROXIMATE", + Exactness::Advisory => "ADVISORY", + } + } +} + +/// What a check's cache key and identity bind to (ADR 0033 Decision 5). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CacheScope { + Portable, + Arch, + Machine, + Hardware, +} + +impl CacheScope { + pub fn as_str(self) -> &'static str { + match self { + CacheScope::Portable => "portable", + CacheScope::Arch => "arch", + CacheScope::Machine => "machine", + CacheScope::Hardware => "hardware", + } + } +} + +/// `tolerance`: integers only (receipts carry no floats, ADR 0028 C3). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Tolerance { + pub metric: String, + pub abs: u64, + pub rel_ppm: u64, +} + +/// `backends`: where the check may run and which result is authoritative. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Backends { + pub eligible: Vec<String>, + pub canonical: String, +} + +/// `oracle`: explicit pass condition beyond the v1 `exit` + `observe`. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Oracle { + /// Repo-relative golden file; its sha256 enters the check identity. + pub golden: Option<String>, + /// Another gate whose result this check is compared against. + pub compare: Option<String>, +} + +pub const BACKEND_NAMES: [&str; 6] = [ + "portable", + "spark", + "qemu", + "gb10", + "analog_sim", + "analog_device", +]; + +fn is_analog(b: &str) -> bool { + b == "analog_sim" || b == "analog_device" +} + #[derive(Debug, Clone, PartialEq)] pub struct Manifest { pub gate: String, @@ -76,6 +154,15 @@ pub struct Manifest { pub mutants: Vec<String>, pub checks: Vec<String>, pub cache_allowed: bool, + /// `manifest_version` (1 or 2). The fields below are v2 and hold their + /// documented defaults for a v1 manifest. + pub version: u8, + pub exactness: Exactness, + pub tolerance: Option<Tolerance>, + pub backends: Backends, + pub fallback: Vec<String>, + pub cache_scope: CacheScope, + pub oracle: Oracle, /// sha256 of the exact manifest file bytes (P7). pub digest: String, } @@ -83,7 +170,7 @@ pub struct Manifest { impl Manifest { /// The scarcest listed pool: gb10 > qemu > host. pub fn pool(&self) -> &'static str { - if self.requires.iter().any(|r| r == "gb10") { + if self.requires.iter().any(|r| r == "gb10" || r == "nvrm") { "gb10" } else if self.requires.iter().any(|r| r == "qemu") { "qemu" @@ -366,6 +453,233 @@ pub fn parse_json_scalar(s: &str) -> Option<Value> { } } +pub const REQUIRES_V2: [&str; 9] = [ + "portable", + "aarch64", + "host", + "qemu", + "gb10", + "nvrm", + "bare_metal", + "analog_eligible", + "operator", +]; + +const V2_KEYS: [&str; 6] = [ + "exactness", + "tolerance", + "backends", + "fallback", + "cache_scope", + "oracle", +]; + +fn bad<T>(msg: String) -> Result<T, ManifestError> { + Err(ManifestError(msg)) +} + +fn child_u64(c: &[(String, Val, usize)], k: &str) -> Result<u64, ManifestError> { + let s = child_str(c, k)?.ok_or_else(|| ManifestError(format!("tolerance.{k} missing")))?; + if s.is_empty() || !s.chars().all(|ch| ch.is_ascii_digit()) { + return bad(format!( + "tolerance.{k} must be a non-negative integer, got {s:?}" + )); + } + s.parse::<u64>() + .map_err(|_| ManifestError(format!("tolerance.{k} out of range"))) +} + +/// The v2 keys (ADR 0033 Decision 2) with their defaults and refusals. +type V2 = ( + Exactness, + Option<Tolerance>, + Backends, + Vec<String>, + CacheScope, + Oracle, +); + +fn parse_v2(entries: &[Entry], requires: &[String]) -> Result<V2, ManifestError> { + let get = |k: &str| entries.iter().find(|e| e.key == k); + let exactness = match get("exactness") { + None => Exactness::Exact, + Some(e) => match scalar(e)?.as_str() { + "EXACT" => Exactness::Exact, + "BOUNDED" => Exactness::Bounded, + "APPROXIMATE" => Exactness::Approximate, + "ADVISORY" => Exactness::Advisory, + o => return bad(format!("unknown exactness {o:?}")), + }, + }; + let tolerance = match get("tolerance") { + None => None, + Some(e) => { + let c = map(e, &["metric", "abs", "rel_ppm"])?; + let metric = child_str(c, "metric")? + .ok_or_else(|| ManifestError("tolerance.metric missing".into()))?; + if !valid_obs_name(&metric) { + return bad(format!("bad tolerance.metric {metric:?}")); + } + Some(Tolerance { + metric, + abs: child_u64(c, "abs")?, + rel_ppm: child_u64(c, "rel_ppm")?, + }) + } + }; + if tolerance.is_some() && exactness != Exactness::Bounded { + return bad("tolerance is only allowed with exactness BOUNDED".into()); + } + if tolerance.is_none() && exactness == Exactness::Bounded { + return bad("exactness BOUNDED requires a tolerance".into()); + } + let cache_scope = match get("cache_scope") { + None => CacheScope::Machine, + Some(e) => match scalar(e)?.as_str() { + "portable" => CacheScope::Portable, + "arch" => CacheScope::Arch, + "machine" => CacheScope::Machine, + "hardware" => CacheScope::Hardware, + o => return bad(format!("unknown cache_scope {o:?}")), + }, + }; + let analog_ok = exactness != Exactness::Exact; + if requires.iter().any(|r| r == "analog_eligible") && !analog_ok { + return bad("requires analog_eligible is not allowed for an EXACT check".into()); + } + let check_backend = |b: &str| -> Result<(), ManifestError> { + if BACKEND_NAMES.contains(&b) { + Ok(()) + } else { + bad(format!("unknown backend {b:?}")) + } + }; + // Eligible backends implied by `requires` when none are declared. + let mut implied: Vec<String> = Vec::new(); + for r in requires { + let b = match r.as_str() { + "portable" => "portable", + "host" | "aarch64" => "spark", + "qemu" => "qemu", + "gb10" | "nvrm" => "gb10", + "analog_eligible" => "analog_sim", + _ => continue, + }; + if !implied.iter().any(|x| x == b) { + implied.push(b.to_string()); + } + } + let (eligible, declared_canonical) = match get("backends") { + None => (implied, None), + Some(e) => { + let c = map(e, &["eligible", "canonical"])?; + let eligible = match child(c, "eligible") { + None => implied, + Some((_, Val::List(l), _)) => l.clone(), + Some((_, Val::Str(_), n)) => { + return err(*n, "backends.eligible must be a one-line list") + } + }; + (eligible, child_str(c, "canonical")?) + } + }; + if eligible.is_empty() { + return bad("backends.eligible is empty".into()); + } + for b in &eligible { + check_backend(b)?; + if is_analog(b) && exactness == Exactness::Exact { + return bad(format!( + "backend {b} may not be eligible for an EXACT check" + )); + } + } + let canonical = match declared_canonical { + Some(c) => { + check_backend(&c)?; + c + } + None => { + // ADR default: spark, or portable when `requires` is only + // portable. Deviation: when spark is not eligible (a qemu or gb10 + // only check) the first digital eligible backend is canonical. + let only_portable = requires.iter().all(|r| r == "portable"); + if only_portable && eligible.iter().any(|b| b == "portable") { + "portable".to_string() + } else if eligible.iter().any(|b| b == "spark") { + "spark".to_string() + } else { + match eligible.iter().find(|b| !is_analog(b)) { + Some(b) => b.clone(), + None => return bad("no digital backend is eligible".into()), + } + } + } + }; + if !eligible.contains(&canonical) { + return bad(format!( + "canonical backend {canonical} is not in backends.eligible" + )); + } + if is_analog(&canonical) + && exactness != Exactness::Approximate + && exactness != Exactness::Advisory + { + return bad(format!( + "canonical backend {canonical} is only allowed for APPROXIMATE or ADVISORY" + )); + } + let fallback = match get("fallback") { + None => vec!["spark".to_string()], + Some(e) => { + let l = list(e)?; + if l.is_empty() { + return bad("fallback is empty".into()); + } + for b in &l { + check_backend(b)?; + } + l + } + }; + let oracle = match get("oracle") { + None => Oracle::default(), + Some(e) => { + let c = map(e, &["golden", "compare"])?; + let golden = child_str(c, "golden")?; + let compare = child_str(c, "compare")?; + if golden.is_some() && compare.is_some() { + return bad("oracle takes golden or compare, not both".into()); + } + if golden.is_none() && compare.is_none() { + return bad("oracle needs golden or compare".into()); + } + if let Some(g) = &golden { + if !valid_rel_path(g) { + return bad(format!("oracle.golden must be a repo-relative path: {g:?}")); + } + } + if let Some(g) = &compare { + if !valid_gate_id(g) { + return bad(format!("invalid oracle.compare gate id {g:?}")); + } + } + Oracle { golden, compare } + } + }; + Ok(( + exactness, + tolerance, + Backends { + eligible, + canonical, + }, + fallback, + cache_scope, + oracle, + )) +} + pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { if bytes.len() > MAX_BYTES { return Err(ManifestError("manifest larger than 16 KiB".into())); @@ -388,7 +702,7 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { } let entries = parse_entries(text)?; - const KNOWN: [&str; 13] = [ + const KNOWN: [&str; 19] = [ "gate", "manifest_version", "owner", @@ -402,6 +716,12 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { "mutants", "checks", "cache", + "exactness", + "tolerance", + "backends", + "fallback", + "cache_scope", + "oracle", ]; for e in &entries { if !KNOWN.contains(&e.key.as_str()) { @@ -418,26 +738,50 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { 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 version: u8 = match scalar(need("manifest_version")?)?.as_str() { + "1" => 1, + "2" => 2, + _ => { + return Err(ManifestError( + "unsupported manifest_version (only 1 or 2)".into(), + )) + } + }; + if version == 1 { + if let Some(e) = entries.iter().find(|e| V2_KEYS.contains(&e.key.as_str())) { + return err( + e.line, + &format!("key {} requires manifest_version 2", e.key), + ); + } } let owner = scalar(need("owner")?)?; - let requires = list(need("requires")?)?; + let requires = match (version, get("requires")) { + (1, _) => list(need("requires")?)?, + (_, Some(e)) => list(e)?, + (_, None) => vec!["host".to_string()], + }; + let allowed: &[&str] = if version == 1 { + &["host", "qemu", "gb10", "operator"] + } else { + &REQUIRES_V2 + }; for r in &requires { - if !["host", "qemu", "gb10", "operator"].contains(&r.as_str()) { + if !allowed.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 pools: &[&str] = if version == 1 { + &["host", "qemu", "gb10"] + } else { + &["host", "qemu", "gb10", "nvrm", "portable", "aarch64"] + }; + if !requires.iter().any(|r| pools.contains(&r.as_str())) { + return Err(ManifestError(format!( + "requires must list one of {}", + pools.join(", ") + ))); } let depends_on = match get("depends_on") { @@ -555,6 +899,10 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { }, }; + // v1 manifests carry none of the v2 keys, so this yields the defaults. + let (exactness, tolerance, backends, fallback, cache_scope, oracle) = + parse_v2(&entries, &requires)?; + Ok(Manifest { gate, owner, @@ -570,6 +918,13 @@ pub fn parse(bytes: &[u8]) -> Result<Manifest, ManifestError> { mutants, checks, cache_allowed, + version, + exactness, + tolerance, + backends, + fallback, + cache_scope, + oracle, digest: sha256_hex(bytes), }) } @@ -695,7 +1050,7 @@ mod tests { 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") + GOOD.replace("manifest_version: 1", "manifest_version: 3") .as_bytes() ) .is_err()); @@ -750,6 +1105,173 @@ mod tests { ); } + fn v2(extra: &str) -> String { + GOOD.replace("manifest_version: 1", "manifest_version: 2") + extra + } + + fn v2_err(extra: &str) -> String { + parse(v2(extra).as_bytes()).unwrap_err().0 + } + + #[test] + fn v1_fixture_parses_to_the_same_values_as_before_slice_d() { + let m = parse(GOOD.as_bytes()).unwrap(); + let expected = Manifest { + gate: "G-1".into(), + owner: "omega".into(), + requires: vec!["host".into()], + depends_on: vec![], + inputs: vec![], + build: None, + exec: "tools/run.sh".into(), + args: vec!["--a".into(), "b c".into()], + expect_exit: 0, + rules: m.rules.clone(), + timeout_ms: 5000, + mutants: vec![], + checks: vec![], + cache_allowed: true, + version: 1, + exactness: Exactness::Exact, + tolerance: None, + backends: Backends { + eligible: vec!["spark".into()], + canonical: "spark".into(), + }, + fallback: vec!["spark".into()], + cache_scope: CacheScope::Machine, + oracle: Oracle::default(), + digest: sha256_hex(GOOD.as_bytes()), + }; + assert_eq!(m, expected); + assert_eq!(m.rules.len(), 3); + } + + #[test] + fn v1_rejects_every_v2_key() { + for extra in [ + "exactness: EXACT\n", + "cache_scope: portable\n", + "fallback: [\"spark\"]\n", + "backends:\n canonical: spark\n", + "oracle:\n golden: g.txt\n", + "tolerance:\n metric: m\n abs: 1\n rel_ppm: 1\n", + ] { + let e = parse(with(extra).as_bytes()).unwrap_err().0; + assert!(e.contains("requires manifest_version 2"), "{extra}: {e}"); + } + assert!(parse(with("requires: [\"portable\"]\n").as_bytes()).is_err()); + let t = GOOD.replace(" - host\n", " - host\n - nvrm\n"); + assert!(parse(t.as_bytes()).is_err()); + } + + #[test] + fn a_v2_manifest_without_v2_keys_equals_its_v1_twin() { + let a = parse(GOOD.as_bytes()).unwrap(); + let b = parse(v2("").as_bytes()).unwrap(); + assert_eq!(b.version, 2); + let mut b2 = b.clone(); + b2.version = 1; + b2.digest = a.digest.clone(); + assert_eq!(a, b2); + } + + #[test] + fn v2_defaults() { + let m = parse(v2("").as_bytes()).unwrap(); + assert_eq!(m.exactness, Exactness::Exact); + assert_eq!(m.cache_scope, CacheScope::Machine); + assert_eq!(m.fallback, vec!["spark".to_string()]); + assert_eq!(m.backends.canonical, "spark"); + let t = v2("").replace("requires:\n - host\n", ""); + let m = parse(t.as_bytes()).unwrap(); + assert_eq!(m.requires, vec!["host".to_string()]); + let t = v2("").replace(" - host\n", " - portable\n"); + let m = parse(t.as_bytes()).unwrap(); + assert_eq!(m.backends.canonical, "portable"); + let t = v2("").replace(" - host\n", " - gb10\n"); + let m = parse(t.as_bytes()).unwrap(); + assert_eq!(m.backends.canonical, "gb10"); + assert_eq!(m.pool(), "gb10"); + } + + #[test] + fn v2_keys_parse() { + let m = parse( + v2(concat!( + "exactness: BOUNDED\n", + "tolerance:\n metric: max_ulp\n abs: 2\n rel_ppm: 100\n", + "backends:\n eligible: [\"spark\", \"analog_sim\"]\n canonical: spark\n", + "fallback: [\"spark\", \"gb10\"]\n", + "cache_scope: arch\n", + "oracle:\n golden: tests/g.txt\n", + )) + .as_bytes(), + ) + .unwrap(); + assert_eq!(m.exactness, Exactness::Bounded); + let t = m.tolerance.unwrap(); + assert_eq!((t.metric.as_str(), t.abs, t.rel_ppm), ("max_ulp", 2, 100)); + assert_eq!(m.backends.eligible, vec!["spark", "analog_sim"]); + assert_eq!(m.fallback, vec!["spark", "gb10"]); + assert_eq!(m.cache_scope, CacheScope::Arch); + assert_eq!(m.oracle.golden.as_deref(), Some("tests/g.txt")); + let m = parse(v2("oracle:\n compare: G-0\n").as_bytes()).unwrap(); + assert_eq!(m.oracle.compare.as_deref(), Some("G-0")); + } + + #[test] + fn v2_refusals() { + let tol = "tolerance:\n metric: m\n abs: 1\n rel_ppm: 1\n"; + assert!(v2_err(tol).contains("only allowed with exactness BOUNDED")); + assert!(v2_err("exactness: BOUNDED\n").contains("requires a tolerance")); + assert!(v2_err("backends:\n eligible: [\"spark\", \"analog_sim\"]\n").contains("EXACT")); + assert!(v2_err("backends:\n eligible: [\"analog_device\"]\n").contains("EXACT")); + assert!( + v2_err("backends:\n eligible: [\"spark\"]\n canonical: gb10\n") + .contains("not in backends.eligible") + ); + let t = + v2("requires: [\"host\", \"analog_eligible\"]\n").replace("requires:\n - host\n", ""); + assert!(parse(t.as_bytes()).unwrap_err().0.contains("EXACT")); + for bad in [ + "exactness: exact\n", + "cache_scope: galaxy\n", + "backends:\n canonical: moon\n", + "backends:\n eligible: [\"moon\"]\n", + "fallback: [\"moon\"]\n", + "fallback: []\n", + "oracle:\n golden: /abs\n", + "oracle:\n golden: a\n compare: G\n", + "oracle:\n shell: x\n", + "surprise: 1\n", + "exactness: BOUNDED\ntolerance:\n metric: m\n abs: 1.5\n rel_ppm: 1\n", + "exactness: BOUNDED\ntolerance:\n metric: m\n abs: 1\n", + ] { + assert!(parse(v2(bad).as_bytes()).is_err(), "{bad}"); + } + let t = v2("").replace(" - host\n", " - moon\n"); + assert!(parse(t.as_bytes()).is_err()); + } + + #[test] + fn analog_may_scout_bounded_and_run_approximate() { + let b = "exactness: BOUNDED\ntolerance:\n metric: m\n abs: 1\n rel_ppm: 0\nbackends:\n eligible: [\"spark\", \"analog_sim\"]\n"; + assert!(parse(v2(b).as_bytes()).is_ok()); + let bad = format!("{b} canonical: analog_sim\n"); + assert!(v2_err(&bad).contains("APPROXIMATE or ADVISORY")); + let a = "exactness: APPROXIMATE\nbackends:\n eligible: [\"analog_sim\"]\n canonical: analog_sim\n"; + let m = parse(v2(a).as_bytes()).unwrap(); + assert_eq!(m.backends.canonical, "analog_sim"); + let m = parse( + v2("exactness: ADVISORY\nrequires: [\"host\", \"analog_eligible\"]\n") + .replace("requires:\n - host\n", "") + .as_bytes(), + ) + .unwrap(); + assert!(m.backends.eligible.iter().any(|b| b == "analog_sim")); + } + #[test] fn comment_inside_bare_value() { let m = parse( diff --git a/tools/aien-test/src/runner.rs b/tools/aien-test/src/runner.rs index 1b26e405..d06fcc08 100644 --- a/tools/aien-test/src/runner.rs +++ b/tools/aien-test/src/runner.rs @@ -361,7 +361,7 @@ pub fn build_inputs_digest(root: &Path, manifest_rel: Option<&Path>, m: &Manifes canonical_digest(&json!({ "inputs": entries })).unwrap_or_default() } -fn machine(hw: &Hardware) -> Value { +pub(crate) fn machine(hw: &Hardware) -> Value { let kernel = fs::read_to_string("/proc/sys/kernel/osrelease") .map(|s| s.trim().to_string()) .unwrap_or_default();