interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / tools / aien-test / src / main.rs

680 lines · 22705 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! aien-test: run gates and report verdicts (ADR 0028).
17//!
18//! - `run GATE`: run one gate. Exit 0 PASS, 1 FAIL or BAD_MANIFEST, 2 NOT_RUN
19//! or usage, 3 BLOCKED_HARDWARE, 4 BLOCKED_OPERATOR, 5 MISSING_IMPLEMENTATION.
20//! - `test ./...` and `test gate:NAME`: run many gates, dependencies first,
21//! with worker threads that honour the resource pools. The exit code is the
22//! campaign verdict: any FAIL gives 1, else the worst of 2 to 5, else 0.
23//! - `why GATE`: explain a gate's state from the receipts already written.
24//! - `list`: list the gates and their dependencies.
25//! - `identity GATE`: print the check id (ADR 0033 Decision 3) and the object it
26//! hashed, for the gate and everything it depends on.
27//! - `plan`, `test changed`, `test crate:NAME`: the planner (ADR 0033 Decision 12).
28//! - `status`, `verify COMMIT`, `worker`: the local pipeline (Decisions 9, 10).
29
30use aien_test::bundle;
31use aien_test::cli::{parse_args, Cli, Command, Selection, USAGE};
32use aien_test::evidence::{Index, Store};
33use aien_test::graph::{self, GraphError};
34use aien_test::identity;
35use aien_test::plan::{self, Request};
36use aien_test::runner::{self, CacheNote, Options, RunError};
37use aien_test::sandbox::Sandbox;
38use aien_test::status;
39use aien_test::verdict::Verdict;
40use aien_test::verify;
41use aien_test::why;
42use aien_test::worker::{self, StateDir};
43use std::collections::BTreeSet;
44use std::path::{Path, PathBuf};
45use std::time::Duration;
46
47fn main() {
48 std::process::exit(real_main());
49}
50
51fn real_main() -> i32 {
52 let argv: Vec<String> = std::env::args().skip(1).collect();
53 // VerificationBundleV1 commands (ADR 0033 Decision 6) have their own small parser.
54 if argv.first().is_some_and(|c| bundle::is_bundle_command(c)) {
55 return bundle::cli_main(&argv);
56 }
57 let cli = match parse_args(&argv) {
58 Ok(c) => c,
59 Err(e) => {
60 eprintln!("aien-test: {e}");
61 eprintln!("{USAGE}");
62 return 2;
63 }
64 };
65 let cwd = match std::env::current_dir() {
66 Ok(d) => d,
67 Err(e) => {
68 eprintln!("aien-test: cannot read current directory: {e}");
69 return 2;
70 }
71 };
72 match &cli.command {
73 Command::Run { gate } => cmd_run(&cli, gate, &cwd),
74 Command::Test(selection) => cmd_test(&cli, selection, &cwd),
75 Command::Why { gate } => cmd_why(&cli, gate, &cwd),
76 Command::List => cmd_list(&cwd),
77 Command::Identity { gate } => cmd_identity(&cli, gate, &cwd),
78 Command::Plan => cmd_plan(&cli, &cwd),
79 Command::Status => cmd_status(&cli),
80 Command::Verify { commit } => cmd_verify(&cli, commit, &cwd),
81 Command::Worker => cmd_worker(&cli),
82 }
83}
84
85/// Options for the real machine, with the command line applied.
86fn options(cli: &Cli, root: &Path) -> Result<Options, i32> {
87 let evidence_dir = match &cli.evidence_dir {
88 Some(d) => d.clone(),
89 None => match runner::default_evidence_dir(root) {
90 Some(d) => d,
91 None => {
92 eprintln!("aien-test: HOME is not set and no --evidence-dir given");
93 return Err(2);
94 }
95 },
96 };
97 let mut opts = Options::new(evidence_dir);
98 opts.allow_dirty = cli.allow_dirty;
99 opts.no_cache = cli.no_cache;
100 opts.args_override = cli.args.clone();
101 opts.pool_sizes = opts.pool_sizes.with(cli.jobs);
102 if let Some(w) = cli.gpu_wait {
103 opts.gpu.wait = w;
104 }
105 opts.sandbox = cli.sandbox;
106 opts.release = cli.release;
107 // `--operator` is only accepted on plan, test and worker (cli.rs), so a
108 // plain `run` never lifts an operator gate.
109 opts.operator = cli.operator;
110 opts.cargo_target_dir = std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from);
111 // One evidence store serves every commit of this checkout, so the tree is
112 // in every cache key (#517). Without it, no reuse at all.
113 match runner::direct_pins(root) {
114 Ok(p) => opts.pins = p,
115 Err(e) => {
116 eprintln!("aien-test: cache off, cannot read the tree id ({e})");
117 opts.no_cache = true;
118 }
119 }
120 Ok(opts)
121}
122
123fn run_error(e: &RunError) -> i32 {
124 match e {
125 RunError::BadManifest(m) => println!("AIEN_TEST: BAD_MANIFEST {m}"),
126 RunError::Fatal(m) => println!("AIEN_TEST: FAIL {m}"),
127 }
128 1
129}
130
131fn graph_error(e: &GraphError) -> i32 {
132 match e {
133 // The message already starts with BAD_MANIFEST.
134 GraphError::BadManifest { .. } => println!("AIEN_TEST: {e}"),
135 _ => println!("AIEN_TEST: FAIL {e}"),
136 }
137 1
138}
139
140fn repo_root_or_report(cwd: &Path) -> Result<PathBuf, i32> {
141 runner::repo_root(cwd).map_err(|e| {
142 println!("AIEN_TEST: FAIL {e}");
143 1
144 })
145}
146
147/// Say plainly what the cache did. A reused result is never presented as a
148/// fresh run.
149fn print_cache(note: &CacheNote) {
150 match note {
151 CacheNote::Reused { from, commit } => {
152 println!("REUSED {from} (made at commit {commit})");
153 println!(
154 "CACHE reused: an earlier run of exactly this experiment already has this result, so it was not run again (use --no-cache to force a fresh run)"
155 );
156 }
157 CacheNote::Miss(why) => println!("CACHE miss: {why}; the gate was run"),
158 CacheNote::Skipped(why) => println!("CACHE not used: {why}"),
159 }
160}
161
162fn cmd_run(cli: &Cli, gate: &str, cwd: &Path) -> i32 {
163 let manifest_path = match runner::locate_gate(cwd, gate) {
164 Ok(p) => p,
165 Err(e) => {
166 println!("AIEN_TEST: BAD_MANIFEST {e}");
167 return 1;
168 }
169 };
170 let parent = manifest_path.parent().unwrap_or(cwd).to_path_buf();
171 let root = match repo_root_or_report(&parent) {
172 Ok(r) => r,
173 Err(code) => return code,
174 };
175 let mut opts = match options(cli, &root) {
176 Ok(o) => o,
177 Err(code) => return code,
178 };
179 opts.shared_cache = cli
180 .shared_cache
181 .as_deref()
182 .map(aien_test::cache::Shared::new);
183 match runner::run_gate(&root, &manifest_path, &opts) {
184 Ok(o) => {
185 if o.verdict == Verdict::NotRun && !o.reason.is_empty() {
186 println!("REFUSED: {}", o.reason);
187 }
188 if let Some(p) = &o.receipt_path {
189 println!("RECEIPT {}", p.display());
190 }
191 print_cache(&o.cache);
192 if o.reason.is_empty() {
193 println!("AIEN_TEST: {}", o.verdict.as_str());
194 } else {
195 println!("AIEN_TEST: {} {}", o.verdict.as_str(), o.reason);
196 }
197 o.verdict.exit_code()
198 }
199 Err(e) => run_error(&e),
200 }
201}
202
203fn cmd_test(cli: &Cli, selection: &Selection, cwd: &Path) -> i32 {
204 let root = match repo_root_or_report(cwd) {
205 Ok(r) => r,
206 Err(code) => return code,
207 };
208 let graph = match graph::load(&root) {
209 Ok(g) => g,
210 Err(e) => return graph_error(&e),
211 };
212 let chosen: BTreeSet<usize> = match selection {
213 Selection::All => graph.all(),
214 Selection::Gate(name) => match graph.index_of(name) {
215 Some(i) => graph.with_dependencies(&[i]),
216 None => {
217 println!("AIEN_TEST: BAD_MANIFEST no gate named {name}");
218 return 1;
219 }
220 },
221 Selection::Changed => {
222 let p = match plan_for(cli, &root) {
223 Ok(p) => p,
224 Err(code) => return code,
225 };
226 for line in plan::render(&plan::repository_name(&root, cli.repo.as_deref()), &p) {
227 println!("{line}");
228 }
229 let code = plan::exit_code(&p);
230 if code != 0 {
231 println!(
232 "AIEN_TEST: {}",
233 if code == 4 {
234 "BLOCKED_OPERATOR"
235 } else {
236 "NOT_RUN"
237 }
238 );
239 return code;
240 }
241 p.entries
242 .iter()
243 .filter(|e| e.section != plan::Section::Blocked)
244 .filter_map(|e| graph.index_of(&e.gate))
245 .collect()
246 }
247 Selection::Crate(name) => match plan::crate_dirs(&root, name) {
248 Ok(dirs) => {
249 println!("CRATE {name} dirs {}", dirs.join(" "));
250 plan::select_for_dirs(&graph, &dirs)
251 }
252 Err(e) => {
253 println!("AIEN_TEST: FAIL {e}");
254 return 1;
255 }
256 },
257 };
258 if chosen.is_empty() {
259 println!("AIEN_TEST: NOT_RUN no gates found under {}", root.display());
260 return 2;
261 }
262 let opts = match options(cli, &root) {
263 Ok(o) => o,
264 Err(code) => return code,
265 };
266 match runner::run_graph(&root, &graph, &chosen, &opts) {
267 Ok(campaign) => {
268 for (id, o) in &campaign.results {
269 if o.reason.is_empty() {
270 println!("GATE {id} {}", o.verdict.as_str());
271 } else {
272 println!("GATE {id} {} {}", o.verdict.as_str(), o.reason);
273 }
274 if let Some(p) = &o.receipt_path {
275 println!("RECEIPT {}", p.display());
276 }
277 print_cache(&o.cache);
278 }
279 println!("AIEN_TEST: {}", campaign.verdict().as_str());
280 campaign.exit_code()
281 }
282 Err(e) => run_error(&e),
283 }
284}
285
286fn cmd_why(cli: &Cli, gate: &str, cwd: &Path) -> i32 {
287 let root = match repo_root_or_report(cwd) {
288 Ok(r) => r,
289 Err(code) => return code,
290 };
291 let graph = match graph::load(&root) {
292 Ok(g) => g,
293 Err(e) => return graph_error(&e),
294 };
295 let target = match why::resolve_target(&graph, cwd, gate) {
296 Ok(i) => i,
297 Err(e) => {
298 println!("AIEN_TEST: BAD_MANIFEST {e}");
299 return 1;
300 }
301 };
302 let opts = match options(cli, &root) {
303 Ok(o) => o,
304 Err(code) => return code,
305 };
306 let commit = match runner::head(&root) {
307 Ok(c) => c,
308 Err(e) => {
309 println!("AIEN_TEST: FAIL {e}");
310 return 1;
311 }
312 };
313 let index = Index::load(&Store::new(&opts.evidence_dir));
314 let cache_facts =
315 aien_test::cache::explain_chain(&root, &graph, &index, &opts, &commit, target);
316 for line in why::explain(&graph, &index, &commit, target, &cache_facts) {
317 println!("{line}");
318 }
319 0
320}
321
322fn cmd_identity(cli: &Cli, gate: &str, cwd: &Path) -> i32 {
323 let root = match repo_root_or_report(cwd) {
324 Ok(r) => r,
325 Err(code) => return code,
326 };
327 let graph = match graph::load(&root) {
328 Ok(g) => g,
329 Err(e) => return graph_error(&e),
330 };
331 let target = match why::resolve_target(&graph, cwd, gate) {
332 Ok(i) => i,
333 Err(e) => {
334 println!("AIEN_TEST: BAD_MANIFEST {e}");
335 return 1;
336 }
337 };
338 let node = graph.node(target);
339 let binding = match identity::local_binding(cli.hardware_identity.as_deref().unwrap_or("")) {
340 Ok(b) => b,
341 Err(e) => {
342 println!("AIEN_TEST: FAIL {e}");
343 return 1;
344 }
345 };
346 let ids = match identity::graph_identities(
347 &graph,
348 target,
349 &root,
350 &cli.compiler_identity,
351 &cli.flags,
352 &binding,
353 ) {
354 Ok(i) => i,
355 Err(e) => {
356 println!("AIEN_TEST: FAIL {e}");
357 return 1;
358 }
359 };
360 for (g, (id, _)) in &ids {
361 if *g != node.id {
362 println!("DEPENDENCY {g} CHECK_ID {id}");
363 }
364 }
365 if let Some((id, obj)) = ids.get(&node.id) {
366 println!("CHECK_ID {id}");
367 println!("OBJECT {}", obj);
368 }
369 0
370}
371
372fn cmd_list(cwd: &Path) -> i32 {
373 let root = match repo_root_or_report(cwd) {
374 Ok(r) => r,
375 Err(code) => return code,
376 };
377 let graph = match graph::load(&root) {
378 Ok(g) => g,
379 Err(e) => return graph_error(&e),
380 };
381 for &i in graph.order() {
382 let node = graph.node(i);
383 let file = node.path.strip_prefix(&root).unwrap_or(&node.path);
384 let deps: Vec<&str> = node
385 .deps
386 .iter()
387 .map(|&d| graph.node(d).id.as_str())
388 .collect();
389 println!(
390 "{} pool={} depends_on={} file={}",
391 node.id,
392 node.manifest.pool(),
393 if deps.is_empty() {
394 "-".to_string()
395 } else {
396 deps.join(",")
397 },
398 file.display()
399 );
400 }
401 println!("{} gates", graph.len());
402 0
403}
404
405/// The planner request for this checkout: BASE from `--base` (default
406/// `origin/main`, then `main`), HEAD from the checkout; `--allow-dirty` adds
407/// the uncommitted changes.
408fn plan_for(cli: &Cli, root: &Path) -> Result<plan::Plan, i32> {
409 let head = runner::head(root).map_err(|e| {
410 println!("AIEN_TEST: FAIL {e}");
411 1
412 })?;
413 let base = match &cli.base {
414 Some(b) => plan::resolve(root, b),
415 None => plan::resolve_first(root, &["origin/main", "main"]),
416 }
417 .map_err(|e| {
418 println!("AIEN_TEST: FAIL {e}");
419 1
420 })?;
421 let mut req = Request::new(&base, &head);
422 req.operator = cli.operator;
423 req.full = cli.full;
424 req.compiler_identity = cli.compiler_identity.clone();
425 req.flags = cli.flags.clone();
426 req.hardware_identity = cli.hardware_identity.clone().unwrap_or_default();
427 let dirty = plan::uncommitted(root).map_err(|e| {
428 println!("AIEN_TEST: FAIL {e}");
429 1
430 })?;
431 if !dirty.is_empty() {
432 if !cli.allow_dirty {
433 println!(
434 "AIEN_TEST: NOT_RUN dirty_tree ({} uncommitted paths; use --allow-dirty to plan them)",
435 dirty.len()
436 );
437 return Err(2);
438 }
439 req.dirty = dirty;
440 }
441 plan::compute(root, &req).map_err(|e| {
442 println!("AIEN_TEST: FAIL {e}");
443 1
444 })
445}
446
447fn cmd_plan(cli: &Cli, cwd: &Path) -> i32 {
448 let root = match repo_root_or_report(cwd) {
449 Ok(r) => r,
450 Err(code) => return code,
451 };
452 let mut p = match plan_for(cli, &root) {
453 Ok(p) => p,
454 Err(code) => return code,
455 };
456 // Say which selected gates the evidence cache already settles.
457 if let Ok(opts) = options(cli, &root) {
458 let cached = plan::probe_cached(&root, &p.graph, &opts);
459 if !cached.is_empty() {
460 for e in p.entries.iter_mut() {
461 if e.section == plan::Section::Required && cached.contains(&e.gate) {
462 e.section = plan::Section::Cached;
463 }
464 }
465 }
466 }
467 for line in plan::render(&plan::repository_name(&root, cli.repo.as_deref()), &p) {
468 println!("{line}");
469 }
470 plan::exit_code(&p)
471}
472
473fn state_dir(cli: &Cli) -> Result<StateDir, i32> {
474 match &cli.state_dir {
475 Some(d) => Ok(StateDir::new(d)),
476 None => StateDir::default_dir().ok_or_else(|| {
477 eprintln!("aien-test: HOME is not set and no --state-dir given");
478 2
479 }),
480 }
481}
482
483fn cmd_status(cli: &Cli) -> i32 {
484 let state = match state_dir(cli) {
485 Ok(s) => s,
486 Err(code) => return code,
487 };
488 for line in status::lines(&state) {
489 println!("{line}");
490 }
491 0
492}
493
494fn cmd_verify(cli: &Cli, commit: &str, cwd: &Path) -> i32 {
495 let root = match repo_root_or_report(cwd) {
496 Ok(r) => r,
497 Err(code) => return code,
498 };
499 let state = match state_dir(cli) {
500 Ok(s) => s,
501 Err(code) => return code,
502 };
503 let ask = verify::Ask {
504 state,
505 commit: commit.to_string(),
506 // verify applies the worker's rule: a commit on this line is
507 // checked against its first parent.
508 base: cli
509 .base
510 .clone()
511 .unwrap_or_else(|| "origin/main".to_string()),
512 repository: cli.repo.clone(),
513 release: cli.release,
514 operator: cli.operator,
515 hardware_identity: cli.hardware_identity.clone().unwrap_or_default(),
516 crumb: Some("crumb".to_string()),
517 keys_override: None,
518 };
519 let report = verify::run(&root, &ask);
520 for line in &report.lines {
521 println!("{line}");
522 }
523 if report.ready {
524 0
525 } else {
526 1
527 }
528}
529
530/// `worker --once` found its head being judged by another process and did
531/// nothing (EX_TEMPFAIL; the verdict codes are 0 to 5).
532const EXIT_HELD: i32 = 75;
533
534fn cmd_worker(cli: &Cli) -> i32 {
535 let state = match state_dir(cli) {
536 Ok(s) => s,
537 Err(code) => return code,
538 };
539 let home = std::env::var_os("HOME").map(PathBuf::from);
540 let key = match (&cli.key, &home) {
541 (Some(k), _) => k.clone(),
542 (None, Some(h)) => h.join(".aien/verify.key"),
543 (None, None) => {
544 eprintln!("aien-test: HOME is not set and no --key given");
545 return 2;
546 }
547 };
548 let clones = match (&cli.clones, &home) {
549 (Some(c), _) => c.clone(),
550 (None, Some(h)) => h.join("workspace"),
551 (None, None) => {
552 eprintln!("aien-test: HOME is not set and no --clones given");
553 return 2;
554 }
555 };
556 let wt_root = cli
557 .wt_root
558 .clone()
559 .unwrap_or_else(|| PathBuf::from("/var/lib/aien-run/wt"));
560 let mut cfg = worker::Config::new(state, &key, &clones, &wt_root);
561 // INFRA's worktree tool; the default is the copy in the trusted clone of
562 // this repository. A missing tool makes `--sandbox user` refuse to run.
563 cfg.wt_tool = match &cli.wt_tool {
564 Some(t) => Some(t.clone()),
565 None => Some(clones.join("aien-sovereign-core/tools/aien-local-ci/wt.sh"))
566 .filter(|p| p.is_file()),
567 };
568 // The operator's sibling map, from the same trusted clone. A missing default
569 // file means no siblings (the worker journals it); an explicit file that
570 // cannot be read makes every run refuse.
571 cfg.siblings = match &cli.siblings {
572 Some(f) => Some(f.clone()),
573 None => Some(clones.join("aien-sovereign-core/tools/aien-local-ci/siblings"))
574 .filter(|p| p.is_file()),
575 };
576 // The worker runs other people's code: the user sandbox is its default.
577 // `--sandbox none` is a development mode only, needs
578 // `--dev-unsandboxed`, and is never allowed with `--github`.
579 cfg.sandbox = if cli.sandbox_given {
580 cli.sandbox
581 } else {
582 Sandbox::User
583 };
584 cfg.allow_unsandboxed = cli.dev_unsandboxed;
585 if let Err(e) = cfg.check_sandbox_policy_for(cli.github) {
586 eprintln!("aien-test: {e}");
587 return 2;
588 }
589 if let Some(b) = &cli.base {
590 cfg.base_ref = b.clone();
591 }
592 cfg.github = cli.github;
593 cfg.poll = Duration::from_secs(cli.poll.unwrap_or(30));
594 cfg.repos = cli.repos.clone();
595 cfg.operator = cli.operator;
596 cfg.full = cli.full;
597 cfg.jobs = cli.jobs;
598 if let Some(w) = cli.gpu_wait {
599 cfg.gpu_wait = w;
600 }
601 cfg.no_cache = cli.no_cache;
602 cfg.hardware_identity = cli.hardware_identity.clone().unwrap_or_default();
603 cfg.batch_host = cli.batch_host;
604 if let Some(n) = cli.batch_heads {
605 cfg.batch_heads = n;
606 }
607 if let Some((repo, shas)) = &cli.batch {
608 // One line per head, then the worst exit code: 0 only if every head
609 // passed.
610 let t0 = std::time::Instant::now();
611 let mut code = 0;
612 for (sha, r) in worker::run_batch(&cfg, repo, shas) {
613 match r {
614 Ok(s) => {
615 for (g, st, v) in &s.gates {
616 println!("GATE {sha} {g} {st} {}", v.as_str());
617 }
618 println!(
619 "HEAD {repo} {sha} {} {} bundle {} publication {}",
620 s.verdict.as_str(),
621 s.reason,
622 s.bundle_path.display(),
623 s.publication
624 );
625 code = code.max(s.verdict.exit_code());
626 }
627 Err(e) => {
628 println!("HEAD {repo} {sha} ERROR {e}");
629 code = code.max(1);
630 }
631 }
632 }
633 println!(
634 "BATCH {repo} heads={} wall_ms={}",
635 shas.len(),
636 t0.elapsed().as_millis()
637 );
638 return code;
639 }
640 if let Some((repo, sha)) = &cli.once {
641 // run_once owns the head lock; report a holder without taking it twice.
642 if let Some(pid) = worker::head_holder(&cfg.state, repo, sha) {
643 println!("AIEN_TEST: SKIP already being judged by pid {pid}");
644 return EXIT_HELD;
645 }
646 return match worker::run_once(&cfg, repo, sha) {
647 Ok(s) => {
648 for n in &s.notes {
649 println!("NOTE {n}");
650 }
651 for (g, st, v) in &s.gates {
652 println!("GATE {g} {st} {}", v.as_str());
653 }
654 println!("BUNDLE {} {}", s.bundle_path.display(), s.bundle_digest);
655 println!("PUBLICATION {}", s.publication);
656 if s.reason.is_empty() {
657 println!("AIEN_TEST: {}", s.verdict.as_str());
658 } else {
659 println!("AIEN_TEST: {} {}", s.verdict.as_str(), s.reason);
660 }
661 s.verdict.exit_code()
662 }
663 Err(e) if e.contains("already being judged") => {
664 println!("AIEN_TEST: {e}");
665 EXIT_HELD
666 }
667 Err(e) => {
668 println!("AIEN_TEST: FAIL {e}");
669 1
670 }
671 };
672 }
673 let iterations = match cli.iterations {
674 Some(0) | None => None,
675 Some(n) => Some(n),
676 };
677 let served = worker::run_loop(&cfg, iterations);
678 println!("WORKER served {served}");
679 0
680}