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 / judge_once_tests.rs

543 lines · 19957 bytes Raw Blame History
1//! Judge once (Drake 2026-10-20): the cross-head store, its key, the rules
2//! for what may leave a head, and the batch budget. Red/green: each reuse
3//! test also shows the miss one byte away.
4
5use crate::cache::{self, Local, Reach, Shared};
6use crate::evidence::{Index, Store};
7use crate::manifest;
8use crate::resources::{Budget, GpuConfig, Hardware};
9use crate::runner::{self, CacheNote, Options, Outcome};
10use crate::testutil::{git, init_repo, write_file, TempDir};
11use crate::verdict::Verdict;
12use serde_json::Value;
13use std::fs;
14use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicUsize, Ordering};
16use std::sync::Arc;
17use std::time::Duration;
18
19const PASS: &str = "#!/bin/sh\necho x >> \"$1\"\necho \"AIEN-OBS n 3\"\necho PASS\n";
20const FAIL: &str = "#!/bin/sh\necho x >> \"$1\"\necho \"AIEN-OBS n 3\"\nexit 1\n";
21
22fn gate(counter: &Path, version: u8, extra: &str) -> String {
23 format!(
24 "gate: J-A\nmanifest_version: {version}\nowner: t\nrequires:\n - host\ninputs:\n - data/\nrun:\n exec: tools/run.sh\n args: [\"{}\"]\nexpects:\n exit: 0\n observe: [\"n == 3\"]\n verdict: PASS\ntimeout: 20s\n{extra}",
25 counter.display()
26 )
27}
28
29/// One repository whose commits stand for different heads; each head gets
30/// its own evidence store, as the worker gives it, and all share one
31/// cross-head store.
32struct Fx {
33 repo: TempDir,
34 ev: TempDir,
35 scratch: TempDir,
36}
37
38impl Fx {
39 fn new(script: &str, version: u8, extra: &str) -> Fx {
40 let scratch = TempDir::new("jo-scratch");
41 let text = gate(&scratch.path().join("a.count"), version, extra);
42 let repo = init_repo(
43 "jo-repo",
44 &[
45 ("tools/run.sh", script, true),
46 ("tests/a.gate", text.as_str(), false),
47 ("data/in.txt", "one\n", false),
48 ("README", "hello\n", false),
49 ],
50 );
51 Fx {
52 repo,
53 ev: TempDir::new("jo-ev"),
54 scratch,
55 }
56 }
57 fn runs(&self) -> usize {
58 fs::read_to_string(self.scratch.path().join("a.count")).map_or(0, |s| s.lines().count())
59 }
60 fn head(&self) -> String {
61 runner::head(self.repo.path()).unwrap()
62 }
63 fn shared_dir(&self) -> PathBuf {
64 self.ev.path().join("gate-cache")
65 }
66 /// The options the worker would give the head now checked out.
67 fn opts(&self) -> Options {
68 let mut o = Options::new(self.ev.path().join("evidence").join(self.head()));
69 o.kill_grace = Duration::from_millis(300);
70 o.hardware = Hardware {
71 gb10_present: false,
72 qemu_available: false,
73 };
74 o.gpu = GpuConfig::rooted_at(self.scratch.path());
75 o.shared_cache = Some(Shared::new(&self.shared_dir()));
76 o
77 }
78 fn run(&self) -> Outcome {
79 runner::run_gate(
80 self.repo.path(),
81 &self.repo.path().join("tests/a.gate"),
82 &self.opts(),
83 )
84 .unwrap()
85 }
86 fn commit(&self, rel: &str, content: &str) -> String {
87 write_file(self.repo.path(), rel, content, false);
88 git(self.repo.path(), &["add", "-A"]);
89 git(self.repo.path(), &["commit", "-q", "-m", rel]);
90 self.head()
91 }
92 /// A new commit with the very same tree (a re-push, a squash merge of an
93 /// up-to-date PR).
94 fn same_tree_commit(&self) -> String {
95 git(
96 self.repo.path(),
97 &["commit", "-q", "--allow-empty", "-m", "same tree"],
98 );
99 self.head()
100 }
101 fn receipt(o: &Outcome) -> Value {
102 serde_json::from_slice(&fs::read(o.receipt_path.as_ref().unwrap()).unwrap()).unwrap()
103 }
104}
105
106fn reused(o: &Outcome) -> Option<(&str, &str)> {
107 match &o.cache {
108 CacheNote::Reused { from, commit } => Some((from, commit)),
109 _ => None,
110 }
111}
112
113fn parsed(text: &str) -> manifest::Manifest {
114 manifest::parse(text.as_bytes()).unwrap_or_else(|e| panic!("{e:?}\n{text}"))
115}
116
117// ---- what may leave a head ----------------------------------------------
118
119#[test]
120fn cross_head_rules_name_what_stays_in_its_head_and_why() {
121 let c = Path::new("/tmp/c");
122 let v2 = |extra: &str| parsed(&gate(c, 2, extra));
123 assert_eq!(cache::cross_head(&v2("")), Ok(Reach::Tree));
124 assert_eq!(
125 cache::cross_head(&v2("cache: inputs_complete\n")),
126 Ok(Reach::Inputs)
127 );
128 assert_eq!(
129 cache::cross_head(&v2("cache: never\n")),
130 Err(Local::CacheNever)
131 );
132 assert_eq!(
133 cache::cross_head(&v2("cache: inputs_complete\ncache_scope: hardware\n")),
134 Err(Local::HardwareScope)
135 );
136 assert_eq!(
137 cache::cross_head(&v2("cache: inputs_complete\nexactness: APPROXIMATE\n")),
138 Err(Local::NotExact)
139 );
140 let swap =
141 |from: &str, to: &str| parsed(&gate(c, 2, "cache: inputs_complete\n").replace(from, to));
142 assert_eq!(
143 cache::cross_head(&swap(" - host\n", " - gb10\n")),
144 Err(Local::ChipState)
145 );
146 assert_eq!(
147 cache::cross_head(&swap(" - host\n", " - host\n - operator\n")),
148 Err(Local::Operator)
149 );
150 // A promise without real inputs is no promise: the tree decides.
151 assert_eq!(
152 cache::cross_head(&swap("inputs:\n - data/\n", "")),
153 Ok(Reach::Tree)
154 );
155 assert_eq!(cache::slot("k", Reach::Inputs, "t"), "k");
156 assert_eq!(cache::slot("k", Reach::Tree, "t"), "k-t");
157}
158
159// ---- the key ---------------------------------------------------------------
160
161#[test]
162fn key_flips_on_any_declared_input_or_build_file_byte_and_not_on_others() {
163 let fx = Fx::new(PASS, 1, "");
164 let m = parsed(&fs::read_to_string(fx.repo.path().join("tests/a.gate")).unwrap());
165 let digest = || runner::build_inputs_digest(fx.repo.path(), None, &m);
166 let d0 = digest();
167 fx.commit("README", "changed\n");
168 assert_eq!(digest(), d0, "an undeclared file is not in the key");
169 fx.commit("data/in.txt", "onf\n");
170 let d1 = digest();
171 assert_ne!(d1, d0, "one declared byte flips the key");
172 fx.commit("Cargo.lock", "# lock\n");
173 let d2 = digest();
174 assert_ne!(d2, d1, "a repository build file joins every key");
175 fx.commit("rust-toolchain.toml", "[toolchain]\n");
176 assert_ne!(digest(), d2, "so does the toolchain pin");
177}
178
179#[test]
180fn the_judge_binary_is_part_of_the_machine_and_so_of_the_key() {
181 let fx = Fx::new(PASS, 1, "");
182 let m = parsed(&fs::read_to_string(fx.repo.path().join("tests/a.gate")).unwrap());
183 let hw = Hardware {
184 gb10_present: false,
185 qemu_available: false,
186 };
187 let path = fx.repo.path().join("tests/a.gate");
188 let id = runner::identity(
189 fx.repo.path(),
190 &path,
191 &m,
192 &hw,
193 crate::sandbox::Sandbox::None,
194 )
195 .unwrap();
196 let sha = runner::judge_sha256().expect("the test binary can be read");
197 assert_eq!(id.machine["judge_sha256"], sha.as_str());
198 let o = fx.run();
199 assert_eq!(
200 Fx::receipt(&o)["core"]["machine"]["judge_sha256"],
201 sha.as_str()
202 );
203}
204
205// ---- reuse across heads, red/green -------------------------------------------
206
207#[test]
208fn a_complete_inputs_result_is_reused_by_another_head_and_not_one_byte_away() {
209 let fx = Fx::new(PASS, 1, "cache: inputs_complete\n");
210 let h1 = fx.head();
211 let first = fx.run();
212 assert_eq!((first.verdict, fx.runs()), (Verdict::Pass, 1));
213 assert_eq!(reused(&first), None);
214
215 // Another head: only an undeclared file differs. Reused, not run.
216 let h2 = fx.commit("README", "other head\n");
217 let second = fx.run();
218 assert_eq!((second.verdict, fx.runs()), (Verdict::Pass, 1));
219 let src = first.receipt_digest.clone().unwrap();
220 assert_eq!(reused(&second), Some((src.as_str(), h1.as_str())));
221 let r = Fx::receipt(&second);
222 assert_eq!(r["core"]["commit"], h2.as_str());
223 assert_eq!(r["volatile"]["cache"]["reused"], true);
224 assert_eq!(r["volatile"]["cache"]["reused_from"], src.as_str());
225 assert_eq!(r["volatile"]["cache"]["reused_from_commit"], h1.as_str());
226 // The source receipt and its logs came along into this head's own store.
227 let store = Store::new(&fx.opts().evidence_dir);
228 let index = Index::load(&store);
229 let copied = index.get(&src).expect("source receipt imported");
230 assert!(store.blob_exists(copied.value["core"]["stdout_sha256"].as_str().unwrap()));
231
232 // One declared byte different: the gate runs again.
233 fx.commit("data/in.txt", "onf\n");
234 let third = fx.run();
235 assert_eq!((third.verdict, fx.runs()), (Verdict::Pass, 2));
236 assert_eq!(reused(&third), None);
237 match &third.cache {
238 CacheNote::Miss(why) => assert!(why.contains("across heads"), "{why}"),
239 other => panic!("{other:?}"),
240 }
241}
242
243#[test]
244fn without_the_promise_only_an_identical_tree_reuses() {
245 // The gate reads nothing undeclared here, but its manifest does not say
246 // so: an undeclared change (README) must run it again (SC-TEST reads the
247 // root README.md), the same tree under a new commit reuses it.
248 let fx = Fx::new(PASS, 1, "");
249 fx.run();
250 assert_eq!(fx.runs(), 1);
251 fx.commit("README", "other head\n");
252 let second = fx.run();
253 assert_eq!((fx.runs(), reused(&second)), (2, None));
254 let h2 = fx.head();
255 fx.same_tree_commit();
256 let third = fx.run();
257 assert_eq!(fx.runs(), 2);
258 assert_eq!(reused(&third).map(|r| r.1), Some(h2.as_str()));
259}
260
261#[test]
262fn a_fail_crosses_heads_as_a_fail_never_as_a_pass() {
263 let fx = Fx::new(FAIL, 1, "cache: inputs_complete\n");
264 let first = fx.run();
265 assert_eq!(first.verdict, Verdict::Fail);
266 fx.commit("README", "other head\n");
267 let second = fx.run();
268 assert_eq!((second.verdict, fx.runs()), (Verdict::Fail, 1));
269 assert!(reused(&second).is_some());
270}
271
272#[test]
273fn a_gate_that_stays_in_its_head_is_never_shared_even_on_the_same_tree() {
274 let fx = Fx::new(PASS, 2, "exactness: APPROXIMATE\n");
275 fx.run();
276 fx.same_tree_commit();
277 let second = fx.run();
278 assert_eq!((fx.runs(), reused(&second)), (2, None));
279 assert!(!fx.shared_dir().join("keys").exists());
280}
281
282#[test]
283fn a_damaged_shared_receipt_is_a_miss_never_a_hit() {
284 let fx = Fx::new(PASS, 1, "cache: inputs_complete\n");
285 let first = fx.run();
286 let src = first.receipt_digest.unwrap();
287 let path = fx.shared_dir().join(format!("{src}.json"));
288 let mut perm = fs::metadata(&path).unwrap().permissions();
289 #[allow(clippy::permissions_set_readonly_false)]
290 perm.set_readonly(false);
291 fs::set_permissions(&path, perm).unwrap();
292 let text = fs::read_to_string(&path).unwrap().replace("PASS", "FAIL");
293 fs::write(&path, text).unwrap();
294 fx.commit("README", "other head\n");
295 let second = fx.run();
296 assert_eq!(
297 (second.verdict, fx.runs(), reused(&second)),
298 (Verdict::Pass, 2, None)
299 );
300}
301
302#[test]
303fn two_heads_racing_for_one_key_run_it_once() {
304 // Two clones at different commits with the same declared inputs, judged
305 // at the same moment: the key lock makes the second wait and reuse.
306 let fx = Fx::new(
307 "#!/bin/sh\necho x >> \"$1\"\nsleep 1\necho \"AIEN-OBS n 3\"\necho PASS\n",
308 1,
309 "cache: inputs_complete\n",
310 );
311 let other = TempDir::new("jo-clone");
312 let dst = other.path().join("r");
313 git(
314 other.path(),
315 &[
316 "clone",
317 "-q",
318 fx.repo.path().to_str().unwrap(),
319 dst.to_str().unwrap(),
320 ],
321 );
322 write_file(&dst, "README", "other head\n", false);
323 git(&dst, &["add", "-A"]);
324 git(&dst, &["commit", "-q", "-m", "other"]);
325 let opts_b = {
326 let mut o = fx.opts();
327 o.evidence_dir = fx.ev.path().join("evidence").join("b");
328 o
329 };
330 let (a, b) = std::thread::scope(|s| {
331 let a = s.spawn(|| fx.run());
332 let b = s.spawn(|| runner::run_gate(&dst, &dst.join("tests/a.gate"), &opts_b).unwrap());
333 (a.join().unwrap(), b.join().unwrap())
334 });
335 assert_eq!(fx.runs(), 1, "one run for both heads");
336 assert_eq!(
337 [reused(&a).is_some(), reused(&b).is_some()]
338 .iter()
339 .filter(|x| **x)
340 .count(),
341 1
342 );
343 assert_eq!((a.verdict, b.verdict), (Verdict::Pass, Verdict::Pass));
344}
345
346// ---- the batch budget ----------------------------------------------------------
347
348#[test]
349fn the_batch_budget_serves_shared_gates_before_the_others() {
350 let budget = Arc::new(Budget::new(1));
351 let held = budget.acquire(false);
352 let order = Arc::new(std::sync::Mutex::new(Vec::new()));
353 let started = Arc::new(AtomicUsize::new(0));
354 std::thread::scope(|s| {
355 let plain = {
356 let (b, o, st) = (budget.clone(), order.clone(), started.clone());
357 s.spawn(move || {
358 st.fetch_add(1, Ordering::SeqCst);
359 let _p = b.acquire(false);
360 o.lock().unwrap().push("unique");
361 })
362 };
363 while started.load(Ordering::SeqCst) < 1 {
364 std::thread::yield_now();
365 }
366 std::thread::sleep(Duration::from_millis(50));
367 let shared = {
368 let (b, o) = (budget.clone(), order.clone());
369 s.spawn(move || {
370 let _p = b.acquire(true);
371 o.lock().unwrap().push("shared");
372 })
373 };
374 std::thread::sleep(Duration::from_millis(50));
375 drop(held);
376 plain.join().unwrap();
377 shared.join().unwrap();
378 });
379 assert_eq!(*order.lock().unwrap(), vec!["shared", "unique"]);
380}
381
382// ---- declared inputs outside the tree and by pattern (L335) ----------------
383
384/// A model checkpoint is not in the repository; `outside_inputs` puts its
385/// bytes in the key. Unchanged checkpoint: another head reuses. One byte of
386/// the checkpoint changed: the gate runs again.
387#[test]
388fn an_outside_input_is_in_the_key_and_one_changed_byte_runs_the_gate_again() {
389 let ckpt = TempDir::new("jo-ckpt");
390 fs::write(ckpt.path().join("model.safetensors"), "weights-1").unwrap();
391 let extra = format!(
392 "outside_inputs:\n - {}/\ncache: inputs_complete\n",
393 ckpt.path().display()
394 );
395 let fx = Fx::new(PASS, 1, &extra);
396 let first = fx.run();
397 assert_eq!((first.verdict, fx.runs()), (Verdict::Pass, 1));
398 fx.commit("README", "other head\n");
399 let second = fx.run();
400 assert_eq!(
401 fx.runs(),
402 1,
403 "same checkpoint, same declared inputs: reused"
404 );
405 assert!(reused(&second).is_some());
406 // Same length, other bytes (the memo is keyed on size, mtime and inode,
407 // so a rewrite is seen).
408 std::thread::sleep(Duration::from_millis(20));
409 fs::write(ckpt.path().join("model.safetensors"), "weights-2").unwrap();
410 fx.commit("README", "third head\n");
411 let third = fx.run();
412 assert_eq!((third.verdict, fx.runs()), (Verdict::Pass, 2));
413 assert_eq!(reused(&third), None);
414}
415
416#[test]
417fn an_outside_input_that_is_missing_is_a_null_row_not_a_match() {
418 let gone = TempDir::new("jo-gone");
419 let text = |p: &str| {
420 parsed(&gate(
421 Path::new("/c"),
422 1,
423 &format!("outside_inputs:\n - {p}/x\n"),
424 ))
425 };
426 let fx = Fx::new(PASS, 1, "");
427 let d_missing = runner::build_inputs_digest(
428 fx.repo.path(),
429 None,
430 &text(&gone.path().display().to_string()),
431 );
432 fs::write(gone.path().join("x"), "").unwrap();
433 let d_empty = runner::build_inputs_digest(
434 fx.repo.path(),
435 None,
436 &text(&gone.path().display().to_string()),
437 );
438 assert_ne!(
439 d_missing, d_empty,
440 "a missing file and an empty file are different keys"
441 );
442 // A manifest without outside_inputs keeps the digest it always had.
443 let plain = parsed(&gate(Path::new("/c"), 1, ""));
444 let before = runner::build_inputs_digest(fx.repo.path(), None, &plain);
445 assert_eq!(
446 before,
447 runner::build_inputs_digest(fx.repo.path(), None, &plain)
448 );
449}
450
451#[test]
452fn outside_inputs_must_be_home_or_absolute_paths_without_dotdot() {
453 for bad in ["models/x", "~/../etc", "/a/../b", "~/", "/"] {
454 let t = gate(Path::new("/c"), 1, &format!("outside_inputs:\n - {bad}\n"));
455 assert!(
456 manifest::parse(t.as_bytes()).is_err(),
457 "{bad} must be refused"
458 );
459 }
460 let t = gate(Path::new("/c"), 1, "outside_inputs:\n - ~/models/T/\n");
461 assert_eq!(parsed(&t).outside_inputs, vec!["~/models/T/".to_string()]);
462}
463
464/// `crates/*/Cargo.toml`: every member manifest is in the key (cargo reads
465/// them all to load the workspace), their sources are not.
466#[test]
467fn a_star_pattern_input_covers_each_match_and_nothing_else() {
468 let fx = Fx::new(PASS, 1, "");
469 fx.commit("crates/b/Cargo.toml", "[package]\n");
470 fx.commit("crates/b/src/lib.rs", "x\n");
471 let m =
472 parsed(&gate(Path::new("/c"), 1, "").replace(" - data/\n", " - crates/*/Cargo.toml\n"));
473 let digest = || runner::build_inputs_digest(fx.repo.path(), None, &m);
474 let d0 = digest();
475 fx.commit("crates/b/src/lib.rs", "y\n");
476 assert_eq!(digest(), d0, "a source file the pattern does not name");
477 fx.commit("crates/b/Cargo.toml", "[package]\nname = \"b\"\n");
478 let d1 = digest();
479 assert_ne!(d1, d0, "a matched member manifest");
480 fx.commit("crates/c/Cargo.toml", "[package]\n");
481 assert_ne!(digest(), d1, "a new member manifest");
482 // A pattern at the top is the whole tree for the cross-head rule.
483 let top = parsed(
484 &gate(Path::new("/c"), 1, "cache: inputs_complete\n")
485 .replace(" - data/\n", " - */Cargo.toml\n"),
486 );
487 assert_eq!(cache::cross_head(&top), Ok(Reach::Tree));
488}
489
490/// `listed`: a file added to a listed directory flips the key; a changed
491/// byte inside it does not (its contents are not declared by the listing).
492#[test]
493fn a_listed_directory_puts_its_names_in_the_key_not_its_bytes() {
494 let fx = Fx::new(PASS, 1, "");
495 fx.commit("crates/b/tests/one.rs", "x\n");
496 let m = parsed(&gate(Path::new("/c"), 1, "listed:\n - crates/*/tests\n"));
497 let digest = || runner::build_inputs_digest(fx.repo.path(), None, &m);
498 let d0 = digest();
499 fx.commit("crates/b/tests/one.rs", "y\n");
500 assert_eq!(digest(), d0, "same names");
501 fx.commit("crates/b/tests/two.rs", "z\n");
502 assert_ne!(digest(), d0, "a new test target");
503}
504
505// ---- direct runs (#517) -------------------------------------------------
506
507/// The options a direct `aien-test run` gives the checkout: one evidence
508/// store for every commit (`default_evidence_dir`), no cross-head store.
509fn direct(fx: &Fx, pins: Value) -> Outcome {
510 let mut o = fx.opts();
511 o.evidence_dir = fx.ev.path().join("direct");
512 o.shared_cache = None;
513 o.pins = pins;
514 runner::run_gate(fx.repo.path(), &fx.repo.path().join("tests/a.gate"), &o).unwrap()
515}
516
517#[test]
518fn a_direct_run_reuses_only_a_receipt_made_for_the_same_tree() {
519 let fx = Fx::new(PASS, 1, "");
520 direct(&fx, runner::direct_pins(fx.repo.path()).unwrap());
521 assert_eq!(fx.runs(), 1);
522 // An undeclared file changes (SC-TEST reads the root README.md): it runs again.
523 fx.commit("README", "other head\n");
524 let second = direct(&fx, runner::direct_pins(fx.repo.path()).unwrap());
525 assert_eq!((fx.runs(), reused(&second)), (2, None));
526 // The same tree under a new commit (a re-push) reuses.
527 let h2 = fx.head();
528 fx.same_tree_commit();
529 let third = direct(&fx, runner::direct_pins(fx.repo.path()).unwrap());
530 assert_eq!(fx.runs(), 2);
531 assert_eq!(reused(&third).map(|r| r.1), Some(h2.as_str()));
532}
533
534#[test]
535fn without_the_tree_a_direct_run_would_reuse_an_older_commit() {
536 // The red half: the key alone (no tree) lets the README change through.
537 let fx = Fx::new(PASS, 1, "");
538 direct(&fx, Value::Array(vec![]));
539 fx.commit("README", "other head\n");
540 let second = direct(&fx, Value::Array(vec![]));
541 assert_eq!(fx.runs(), 1);
542 assert!(reused(&second).is_some());
543}