Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/tools/aien-test/tests/local_ci.rs # 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 Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / tools / aien-test / tests / local_ci.rs` 1810 lines ยท 66040 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 //! The local pipeline end to end, and the negative cases the mission lists 17 //! (22 to 27): an altered receipt, a bad signature, a bundle from another 18 //! commit, a missing required check, a hardware-scoped cached result under 19 //! `--release`, and an executor whose key the repository does not trust. 20 //! Each must leave MERGE ELIGIBILITY at BLOCKED; none may print PASS. 21 //! 22 //! The worker runs with `--sandbox none` (development mode, 23 //! `allow_unsandboxed`) here because the exec helper is the INFRA lane's 24 //! file; the sandbox tests at the end run only when 25 //! `/usr/local/sbin/aien-run-exec` exists. 26 27 use aien_test::bundle; 28 use aien_test::evidence::canonical; 29 use aien_test::plan::{self, Request}; 30 use aien_test::runner::{self, Options}; 31 use aien_test::sandbox::Sandbox; 32 use aien_test::verdict::Verdict; 33 use aien_test::verify::{self, Ask}; 34 use aien_test::worker::{self, Config, StateDir}; 35 use serde_json::{json, Value}; 36 use std::fs; 37 use std::os::unix::fs::PermissionsExt; 38 use std::path::{Path, PathBuf}; 39 use std::process::Command; 40 use std::sync::atomic::{AtomicU64, Ordering}; 41 42 static COUNTER: AtomicU64 = AtomicU64::new(0); 43 /// The user-sandbox scenarios share one mirror name under 44 /// `/var/lib/aien-run/mirror` (`aien-test-selftest.git`): they take turns. 45 static USER_SANDBOX: std::sync::Mutex<()> = std::sync::Mutex::new(()); 46 47 struct Tmp(PathBuf); 48 49 impl Tmp { 50 fn new(tag: &str) -> Tmp { 51 let n = COUNTER.fetch_add(1, Ordering::SeqCst); 52 let p = 53 std::env::temp_dir().join(format!("aien-local-ci-{tag}-{}-{n}", std::process::id())); 54 let _ = fs::remove_dir_all(&p); 55 fs::create_dir_all(&p).unwrap(); 56 Tmp(p) 57 } 58 /// A directory the exec helper accepts as `--cwd`: the sandbox shares no 59 /// `/tmp` with the caller, so sandboxed checks run in 60 /// `/var/lib/aien-run/wt/aien-test-selftest/<40 hex>`. 61 fn sandbox_wt() -> Tmp { 62 let n = COUNTER.fetch_add(1, Ordering::SeqCst); 63 let nanos = std::time::SystemTime::now() 64 .duration_since(std::time::UNIX_EPOCH) 65 .unwrap() 66 .as_nanos(); 67 let id = format!( 68 "{:0>40}", 69 format!("{:x}{:x}{n:x}", std::process::id(), nanos) 70 ); 71 let p = Path::new("/var/lib/aien-run/wt/aien-test-selftest").join(&id[id.len() - 40..]); 72 let _ = fs::remove_dir_all(&p); 73 fs::create_dir_all(&p).unwrap(); 74 Tmp(p) 75 } 76 fn path(&self) -> &Path { 77 &self.0 78 } 79 } 80 81 impl Drop for Tmp { 82 fn drop(&mut self) { 83 let _ = fs::remove_dir_all(&self.0); 84 } 85 } 86 87 fn git(dir: &Path, args: &[&str]) -> String { 88 let out = Command::new("git") 89 .arg("-C") 90 .arg(dir) 91 .args(args) 92 .env("GIT_AUTHOR_NAME", "t") 93 .env("GIT_AUTHOR_EMAIL", "t@t") 94 .env("GIT_COMMITTER_NAME", "t") 95 .env("GIT_COMMITTER_EMAIL", "t@t") 96 .output() 97 .expect("git"); 98 assert!( 99 out.status.success(), 100 "git {args:?}: {}", 101 String::from_utf8_lossy(&out.stderr) 102 ); 103 String::from_utf8_lossy(&out.stdout).trim().to_string() 104 } 105 106 fn write(dir: &Path, rel: &str, content: &str, exec: bool) { 107 let p = dir.join(rel); 108 fs::create_dir_all(p.parent().unwrap()).unwrap(); 109 fs::write(&p, content).unwrap(); 110 if exec { 111 fs::set_permissions(&p, fs::Permissions::from_mode(0o755)).unwrap(); 112 } 113 } 114 115 fn gate(id: &str, input: &str, exec: &str, extra: &str) -> String { 116 format!( 117 "gate: {id}\nmanifest_version: 2\nowner: t\nrequires:\n - host\ninputs:\n - {input}\nrun:\n exec: {exec}\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 10s\n{extra}" 118 ) 119 } 120 121 /// Everything one scenario needs: an origin with `main` (base) and `topic` 122 /// (head, changes `a/a.txt`), a trusted clone, a state dir, a signing key 123 /// whose public half is committed in `.aien/verify.pub`, and a fake `crumb` 124 /// that always says OK. 125 struct World { 126 _root: Tmp, 127 origin: PathBuf, 128 clone: PathBuf, 129 state: StateDir, 130 key: PathBuf, 131 other_key: PathBuf, 132 crumb: PathBuf, 133 base: String, 134 head: String, 135 /// A second head that changes `h/h.txt` (gate H, cache_scope hardware). 136 head_h: String, 137 wt_root: PathBuf, 138 } 139 140 const REPO: &str = "aien-test-selftest"; 141 142 fn world() -> World { 143 let root = Tmp::new("world"); 144 let r = root.path(); 145 let key = r.join("verify.key"); 146 let pubkey = bundle::keygen(&key).unwrap(); 147 let other_key = r.join("other.key"); 148 bundle::keygen(&other_key).unwrap(); 149 let crumb = r.join("crumb"); 150 write( 151 r, 152 "crumb", 153 "#!/bin/sh\nif [ \"$1\" = close ]; then case \"$5\" in create|modify|delete|audit|test|build) ;; *) echo \"crumb: action must be create|modify|delete|audit|test|build\" >&2; exit 2;; esac; fi\necho \"crumb $1: OK\"\nexit 0\n", 154 true, 155 ); 156 157 let origin = r.join("origin"); 158 fs::create_dir_all(&origin).unwrap(); 159 git(&origin, &["init", "-q", "-b", "main"]); 160 write(&origin, "tools/a.sh", "#!/bin/sh\necho PASS\n", true); 161 write(&origin, "tools/h.sh", "#!/bin/sh\necho PASS\n", true); 162 write( 163 &origin, 164 "tests/gates/A.gate", 165 &gate("A", "a/", "tools/a.sh", ""), 166 false, 167 ); 168 write( 169 &origin, 170 "tests/gates/H.gate", 171 &gate("H", "h/", "tools/h.sh", "cache_scope: hardware\n"), 172 false, 173 ); 174 write(&origin, "a/a.txt", "1\n", false); 175 write(&origin, "h/h.txt", "1\n", false); 176 write( 177 &origin, 178 ".aien/verify.pub", 179 &format!("# trusted executors\n{pubkey}\n"), 180 false, 181 ); 182 write(&origin, ".crumb", "crumb: 1\n", false); 183 git(&origin, &["add", "-A"]); 184 git(&origin, &["commit", "-q", "-m", "base"]); 185 let base = git(&origin, &["rev-parse", "HEAD"]); 186 git(&origin, &["checkout", "-q", "-b", "topic"]); 187 write(&origin, "a/a.txt", "2\n", false); 188 git(&origin, &["add", "-A"]); 189 git(&origin, &["commit", "-q", "-m", "change a"]); 190 let head = git(&origin, &["rev-parse", "HEAD"]); 191 git(&origin, &["checkout", "-q", "-b", "topic-h", "main"]); 192 write(&origin, "h/h.txt", "2\n", false); 193 git(&origin, &["add", "-A"]); 194 git(&origin, &["commit", "-q", "-m", "change h"]); 195 let head_h = git(&origin, &["rev-parse", "HEAD"]); 196 git(&origin, &["checkout", "-q", "main"]); 197 198 let clones = r.join("clones"); 199 fs::create_dir_all(&clones).unwrap(); 200 let clone = clones.join(REPO); 201 git(&clones, &["clone", "-q", origin.to_str().unwrap(), REPO]); 202 git(&clone, &["fetch", "-q", "--all"]); 203 World { 204 state: StateDir::new(&r.join("state")), 205 wt_root: r.join("wt"), 206 _root: root, 207 origin, 208 clone, 209 key, 210 other_key, 211 crumb, 212 base, 213 head, 214 head_h, 215 } 216 } 217 218 impl World { 219 fn config(&self) -> Config { 220 let mut cfg = Config::new( 221 self.state.clone(), 222 &self.key, 223 self.clone.parent().unwrap(), 224 &self.wt_root, 225 ); 226 cfg.crumb = Some(self.crumb.display().to_string()); 227 cfg.gh = self.crumb.display().to_string(); // never called unless github 228 // These scenarios run without the exec helper (development mode). 229 cfg.allow_unsandboxed = true; 230 cfg 231 } 232 233 fn ask(&self, commit: &str) -> Ask { 234 Ask { 235 state: self.state.clone(), 236 commit: commit.to_string(), 237 base: "origin/main".to_string(), 238 repository: None, 239 release: false, 240 operator: false, 241 hardware_identity: String::new(), 242 crumb: Some(self.crumb.display().to_string()), 243 keys_override: None, 244 } 245 } 246 247 fn verify(&self, ask: &Ask) -> verify::Report { 248 verify::run(&self.clone, ask) 249 } 250 251 fn bundle_path(&self, sha: &str) -> PathBuf { 252 self.state.bundle_path(REPO, sha) 253 } 254 255 fn read_bundle(&self, sha: &str) -> Value { 256 serde_json::from_slice(&fs::read(self.bundle_path(sha)).unwrap()).unwrap() 257 } 258 259 fn write_bundle(&self, sha: &str, v: &Value) { 260 let p = self.bundle_path(sha); 261 fs::create_dir_all(p.parent().unwrap()).unwrap(); 262 fs::write(p, canonical(v).unwrap()).unwrap(); 263 } 264 } 265 266 fn line<'a>(r: &'a verify::Report, prefix: &str) -> &'a str { 267 r.lines 268 .iter() 269 .find(|l| l.starts_with(prefix)) 270 .map(String::as_str) 271 .unwrap_or_else(|| panic!("no line {prefix:?} in {:#?}", r.lines)) 272 } 273 274 fn assert_blocked(r: &verify::Report, why: &str) { 275 assert!(!r.ready, "{why}: {:#?}", r.lines); 276 assert_eq!( 277 line(r, "MERGE ELIGIBILITY:"), 278 "MERGE ELIGIBILITY: BLOCKED", 279 "{why}" 280 ); 281 assert_ne!(line(r, "Final verdict:"), "Final verdict: PASS", "{why}"); 282 } 283 284 /// The happy path once, shared by the negative tests through `verified_world`. 285 fn verified_world() -> World { 286 let w = world(); 287 let s = worker::run_once(&w.config(), REPO, &w.head).expect("worker"); 288 assert_eq!(s.verdict, Verdict::Pass, "{} {:?}", s.reason, s.notes); 289 assert_eq!(s.bundle_verdict, "PASS"); 290 // The fake crumb rejects actions the real tool rejects; no crumb note. 291 assert!( 292 !s.notes.iter().any(|n| n.starts_with("crumb ")), 293 "{:?}", 294 s.notes 295 ); 296 assert!(w.bundle_path(&w.head).exists()); 297 assert_eq!(s.publication, "local"); 298 w 299 } 300 301 #[test] 302 fn worker_then_verify_is_ready() { 303 let w = verified_world(); 304 let r = w.verify(&w.ask(&w.head)); 305 assert_eq!(r.lines[0], "AIEN LOCAL VERIFICATION"); 306 assert_eq!(line(&r, "Evidence status:"), "Evidence status: VERIFIED"); 307 assert_eq!(line(&r, "Crumb status:"), "Crumb status: CURRENT"); 308 assert_eq!( 309 line(&r, "Hardware status:"), 310 "Hardware status: NOT_REQUIRED" 311 ); 312 assert_eq!(line(&r, "Final verdict:"), "Final verdict: PASS"); 313 assert_eq!(line(&r, "Executed gates:"), "Executed gates: 1 (A)"); 314 assert_eq!(line(&r, "Build time:"), "Build time: n/a"); 315 assert_eq!(line(&r, "GPU lock wait:"), "GPU lock wait: n/a"); 316 assert!(line(&r, "Test time:").ends_with(" ms")); 317 assert_eq!( 318 line(&r, "MERGE ELIGIBILITY:"), 319 "MERGE ELIGIBILITY: READY", 320 "{:#?}", 321 r.lines 322 ); 323 assert!(r.ready); 324 // The journal has the head, the worktree is gone, the clone's checkout is untouched. 325 let j = fs::read_to_string(w.state.journal()).unwrap(); 326 assert!(j.contains(&w.head) && j.contains("\"publication\":\"local\"")); 327 assert!(!w.wt_root.join(REPO).join(&w.head).exists()); 328 assert_eq!(git(&w.clone, &["rev-parse", "HEAD"]), w.base); 329 assert_eq!(git(&w.clone, &["status", "--porcelain"]), ""); 330 // Fresh crumb check leaves no worktree behind. 331 assert!(!git(&w.clone, &["worktree", "list"]).contains("aien-verify-")); 332 let _ = &w.origin; 333 } 334 335 /// DRA-97 retired Crumbs from the active workflow: a head whose crumbs are not 336 /// CURRENT (here the crumb check is skipped, which reports STALE) is still READY 337 /// when its evidence and verdict are. 338 #[test] 339 fn stale_crumbs_do_not_block_ready() { 340 let w = verified_world(); 341 let mut ask = w.ask(&w.head); 342 ask.crumb = None; 343 let r = w.verify(&ask); 344 assert_eq!(line(&r, "Crumb status:"), "Crumb status: STALE"); 345 assert_eq!(line(&r, "Evidence status:"), "Evidence status: VERIFIED"); 346 assert_eq!(line(&r, "Final verdict:"), "Final verdict: PASS"); 347 assert_eq!( 348 line(&r, "MERGE ELIGIBILITY:"), 349 "MERGE ELIGIBILITY: READY", 350 "{:#?}", 351 r.lines 352 ); 353 assert!(r.ready); 354 } 355 356 #[test] 357 fn altered_receipt_is_rejected() { 358 let w = verified_world(); 359 let b = w.read_bundle(&w.head); 360 let digest = b["checks"][0]["receipt"].as_str().unwrap().to_string(); 361 let p = w 362 .state 363 .evidence(REPO, &w.head) 364 .join(format!("{digest}.json")); 365 let text = fs::read_to_string(&p).unwrap(); 366 assert!(text.contains("\"derived_verdict\":\"PASS\"")); 367 fs::set_permissions(&p, fs::Permissions::from_mode(0o644)).unwrap(); 368 fs::write( 369 &p, 370 text.replace( 371 "\"derived_verdict\":\"PASS\"", 372 "\"derived_verdict\":\"FAIL\"", 373 ), 374 ) 375 .unwrap(); 376 let r = w.verify(&w.ask(&w.head)); 377 assert_blocked(&r, "altered receipt"); 378 assert!( 379 r.lines.iter().any(|l| l.starts_with("Problem: A: receipt")), 380 "{:#?}", 381 r.lines 382 ); 383 } 384 385 #[test] 386 fn invalid_signature_is_rejected() { 387 let w = verified_world(); 388 let mut b = w.read_bundle(&w.head); 389 let sig = b["signature"]["sig"].as_str().unwrap().to_string(); 390 let flipped = format!( 391 "{}{}", 392 if sig.starts_with('0') { "1" } else { "0" }, 393 &sig[1..] 394 ); 395 b["signature"]["sig"] = json!(flipped); 396 w.write_bundle(&w.head, &b); 397 let r = w.verify(&w.ask(&w.head)); 398 assert_blocked(&r, "bad signature"); 399 assert_eq!(line(&r, "Evidence status:"), "Evidence status: INVALID"); 400 assert!(line(&r, "Evidence note:").contains("BAD_SIGNATURE")); 401 } 402 403 #[test] 404 fn bundle_from_another_commit_is_rejected() { 405 let w = verified_world(); 406 let b = w.read_bundle(&w.head); 407 // Present the head's bundle as the other branch head's. 408 w.write_bundle(&w.head_h, &b); 409 let r = w.verify(&w.ask(&w.head_h)); 410 assert_blocked(&r, "other commit"); 411 assert!( 412 line(&r, "Evidence note:").contains("COMMIT_MISMATCH"), 413 "{:#?}", 414 r.lines 415 ); 416 } 417 418 #[test] 419 fn missing_required_check_never_passes() { 420 let w = verified_world(); 421 let mut b = w.read_bundle(&w.head); 422 b["checks"] = json!([]); 423 b.as_object_mut().unwrap().remove("signature"); 424 // Re-signed by the trusted key: the algebra, not the signature, must refuse it. 425 let key = bundle::load_signing_key(&w.key).unwrap(); 426 let signed = bundle::sign(&b, &key).unwrap(); 427 assert_eq!( 428 signed["verdict"], "PASS", 429 "an empty bundle declares PASS vacuously" 430 ); 431 w.write_bundle(&w.head, &signed); 432 let r = w.verify(&w.ask(&w.head)); 433 assert_blocked(&r, "missing required check"); 434 assert!( 435 line(&r, "Evidence note:").contains("MISSING_REQUIRED_CHECK: A"), 436 "{:#?}", 437 r.lines 438 ); 439 } 440 441 #[test] 442 fn hardware_cached_result_cannot_satisfy_release() { 443 let w = world(); 444 // A hand-made bundle for the H head: H cached (PASS), signed by the trusted key. 445 let wt = w.wt_root.join("h-plan"); 446 git( 447 &w.clone, 448 &[ 449 "worktree", 450 "add", 451 "-q", 452 "--detach", 453 wt.to_str().unwrap(), 454 &w.head_h, 455 ], 456 ); 457 let p = plan::compute(&wt, &Request::new(&w.base, &w.head_h)).unwrap(); 458 git( 459 &w.clone, 460 &["worktree", "remove", "--force", wt.to_str().unwrap()], 461 ); 462 let h = p 463 .entries 464 .iter() 465 .find(|e| e.gate == "H") 466 .expect("H selected"); 467 let key = bundle::load_signing_key(&w.key).unwrap(); 468 let vk = key.verifying_key(); 469 let tree = git(&w.clone, &["rev-parse", &format!("{}^{{tree}}", w.head_h)]); 470 let unsigned = json!({ 471 "schema": bundle::SCHEMA, 472 "repository": plan::repository_name(&w.clone, None), 473 "commit": w.head_h, 474 "tree_digest": aien_test::evidence::sha256_hex(tree.as_bytes()), 475 "graph_digest": p.graph_digest, 476 "receipt_id_scheme": "sha256-canonical-json", 477 "checks": [{ 478 "gate": "H", "check_id": h.check_id, "exactness": "EXACT", "required": true, 479 "status": "cached", "verdict": "PASS", "backend": "host", 480 "resolution": { "resolved_from": "f".repeat(64) } 481 }], 482 "verdict": "PASS", 483 "executor": { "id": bundle::fingerprint(&vk), "class": "spark", "machine_digest": "0".repeat(64) }, 484 "started_utc": "2026-10-11T00:00:00Z", 485 "finished_utc": "2026-10-11T00:00:02Z", 486 }); 487 let signed = bundle::sign(&unsigned, &key).unwrap(); 488 w.write_bundle(&w.head_h, &signed); 489 let plain = w.verify(&w.ask(&w.head_h)); 490 assert_eq!( 491 line(&plain, "Evidence status:"), 492 "Evidence status: VERIFIED", 493 "{:#?}", 494 plain.lines 495 ); 496 assert_eq!(line(&plain, "Cached gates:"), "Cached gates: 1 (H)"); 497 assert_eq!(line(&plain, "Final verdict:"), "Final verdict: PASS"); 498 assert_eq!(line(&plain, "Total time:"), "Total time: 2000 ms"); 499 let mut release = w.ask(&w.head_h); 500 release.release = true; 501 let r = w.verify(&release); 502 assert_blocked(&r, "hardware cache under --release"); 503 assert_eq!(line(&r, "Cached gates:"), "Cached gates: none"); 504 assert!( 505 r.lines 506 .iter() 507 .any(|l| l.contains("cannot satisfy --release")), 508 "{:#?}", 509 r.lines 510 ); 511 } 512 513 #[test] 514 fn executor_not_in_verify_pub_is_rejected() { 515 let w = verified_world(); 516 let mut b = w.read_bundle(&w.head); 517 b.as_object_mut().unwrap().remove("signature"); 518 let other = bundle::load_signing_key(&w.other_key).unwrap(); 519 b["executor"]["id"] = json!(bundle::fingerprint(&other.verifying_key())); 520 let signed = bundle::sign(&b, &other).unwrap(); 521 w.write_bundle(&w.head, &signed); 522 let r = w.verify(&w.ask(&w.head)); 523 assert_blocked(&r, "untrusted executor"); 524 assert!( 525 line(&r, "Evidence note:").contains("UNKNOWN_KEY"), 526 "{:#?}", 527 r.lines 528 ); 529 // And with no trusted keys at all the answer is the same. 530 let mut none = w.ask(&w.head); 531 none.keys_override = Some(Vec::new()); 532 let r = w.verify(&none); 533 assert_blocked(&r, "no keys"); 534 } 535 536 #[test] 537 fn another_uid_cannot_read_the_key() { 538 let w = world(); 539 let probe = Command::new("sudo") 540 .args(["-n", "-u", "nobody", "true"]) 541 .output(); 542 match probe { 543 Ok(o) if o.status.success() => {} 544 _ => { 545 println!("SKIP: sudo -n -u nobody is not available here"); 546 return; 547 } 548 } 549 let mode = fs::metadata(&w.key).unwrap().permissions().mode() & 0o777; 550 assert_eq!(mode, 0o600); 551 let out = Command::new("sudo") 552 .args(["-n", "-u", "nobody", "cat", w.key.to_str().unwrap()]) 553 .output() 554 .unwrap(); 555 assert!( 556 !out.status.success(), 557 "nobody must not read the signing key" 558 ); 559 assert!(out.stdout.is_empty()); 560 } 561 562 #[test] 563 fn github_down_queues_then_flushes() { 564 let w = world(); 565 let fake = w.state.root.join("fake-gh"); 566 let log = w.state.root.join("gh.log"); 567 let down = w.state.root.join("gh.down"); 568 fs::create_dir_all(&w.state.root).unwrap(); 569 fs::write( 570 &fake, 571 format!( 572 "#!/bin/sh\nif [ -e {} ]; then echo 'connect: network unreachable' >&2; exit 1; fi\necho \"$@\" >> {}\nexit 0\n", 573 down.display(), 574 log.display() 575 ), 576 ) 577 .unwrap(); 578 fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap(); 579 fs::write(&down, "").unwrap(); 580 let mut cfg = w.config(); 581 cfg.github = true; 582 cfg.gh = fake.display().to_string(); 583 let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); 584 assert_eq!(s.verdict, Verdict::Pass, "{}", s.reason); 585 assert_eq!(s.publication, "pending"); 586 assert!( 587 s.notes.iter().any(|n| n.starts_with("GitHub unreachable")), 588 "{:?}", 589 s.notes 590 ); 591 let queued: Vec<_> = fs::read_dir(w.state.outbox_dir()) 592 .unwrap() 593 .flatten() 594 .collect(); 595 assert_eq!(queued.len(), 1); 596 assert!(fs::read_to_string(w.state.journal()) 597 .unwrap() 598 .contains("\"publication\":\"pending\"")); 599 // Still down: nothing posted. 600 assert_eq!(worker::flush_outbox(&cfg), (0, 1)); 601 // Back: posted, outbox empty, the status names the bundle and is a success. 602 fs::remove_file(&down).unwrap(); 603 assert_eq!(worker::flush_outbox(&cfg), (1, 0)); 604 assert_eq!( 605 fs::read_dir(w.state.outbox_dir()) 606 .unwrap() 607 .flatten() 608 .count(), 609 0 610 ); 611 let l = fs::read_to_string(&log).unwrap(); 612 assert!(l.contains(&format!("statuses/{}", w.head)), "{l}"); 613 assert!( 614 l.contains("state=success") && l.contains("context=AIEN Verification (Spark)"), 615 "{l}" 616 ); 617 // The description names the bundle; GitHub caps it at 140 characters, so 618 // a long scratch path may cut the file name off (no assertion on ".json"). 619 assert!(l.contains(": bundle /"), "{l}"); 620 assert!(fs::read_to_string(w.state.journal()) 621 .unwrap() 622 .contains("flushed from outbox")); 623 } 624 625 #[test] 626 fn loop_without_github_keeps_the_outbox() { 627 // A status queued while GitHub was down must not be posted by a loop that 628 // was started without --github (`aien-local-ci start`): posting is the 629 // operator's choice, made with --github. 630 let w = world(); 631 let fake = w.state.root.join("fake-gh"); 632 let log = w.state.root.join("gh.log"); 633 let down = w.state.root.join("gh.down"); 634 fs::create_dir_all(&w.state.root).unwrap(); 635 fs::write( 636 &fake, 637 format!( 638 "#!/bin/sh\nif [ -e {} ]; then echo 'connect: network unreachable' >&2; exit 1; fi\necho \"$@\" >> {}\nexit 0\n", 639 down.display(), 640 log.display() 641 ), 642 ) 643 .unwrap(); 644 fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap(); 645 fs::write(&down, "").unwrap(); 646 let mut cfg = w.config(); 647 cfg.github = true; 648 cfg.gh = fake.display().to_string(); 649 let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); 650 assert_eq!(s.publication, "pending"); 651 assert_eq!(worker::outbox_files(&w.state).len(), 1); 652 // GitHub is back, but this loop runs without --github: nothing is posted. 653 fs::remove_file(&down).unwrap(); 654 cfg.github = false; 655 worker::run_loop(&cfg, Some(1)); 656 assert_eq!(worker::outbox_files(&w.state).len(), 1); 657 assert!(!log.exists(), "{:?}", fs::read_to_string(&log)); 658 // With --github the same loop drains it. 659 cfg.github = true; 660 cfg.repos = Vec::new(); 661 worker::run_loop(&cfg, Some(1)); 662 assert!(worker::outbox_files(&w.state).is_empty()); 663 assert!(fs::read_to_string(&log) 664 .unwrap() 665 .contains(&format!("statuses/{}", w.head))); 666 } 667 668 #[test] 669 fn worker_no_cache_reruns_every_gate() { 670 // The same head twice: the second run reuses the receipt; with 671 // `--no-cache` (cfg.no_cache) it runs the gate again. 672 let w = world(); 673 let mut cfg = w.config(); 674 let first = worker::run_once(&cfg, REPO, &w.head).expect("worker"); 675 assert!( 676 first.gates.iter().any(|(g, st, _)| g == "A" && st == "run"), 677 "{:?}", 678 first.gates 679 ); 680 let again = worker::run_once(&cfg, REPO, &w.head).expect("worker"); 681 assert!( 682 again 683 .gates 684 .iter() 685 .any(|(g, st, _)| g == "A" && st == "cached"), 686 "{:?}", 687 again.gates 688 ); 689 cfg.no_cache = true; 690 cfg.jobs = aien_test::resources::JobsSpec { 691 host: Some(1), 692 qemu: None, 693 }; 694 let fresh = worker::run_once(&cfg, REPO, &w.head).expect("worker"); 695 assert!( 696 fresh.gates.iter().any(|(g, st, _)| g == "A" && st == "run"), 697 "{:?}", 698 fresh.gates 699 ); 700 assert_eq!(fresh.verdict, Verdict::Pass, "{}", fresh.reason); 701 } 702 703 #[test] 704 fn trigger_file_is_served_by_the_loop() { 705 let w = world(); 706 let cfg = w.config(); 707 fs::create_dir_all(w.state.trigger_dir()).unwrap(); 708 fs::write(w.state.trigger_dir().join(format!("{REPO}.{}", w.head)), "").unwrap(); 709 let served = worker::run_loop(&cfg, Some(1)); 710 assert_eq!(served, 1); 711 assert!(w.bundle_path(&w.head).exists()); 712 assert_eq!( 713 fs::read_dir(w.state.trigger_dir()) 714 .unwrap() 715 .flatten() 716 .count(), 717 0 718 ); 719 } 720 721 #[test] 722 fn bare_exec_runs_and_escapes_are_refused() { 723 // `exec: true` (bare) runs from the PATH; `exec: ../x` is a manifest reject. 724 let t = Tmp::new("bare"); 725 let r = t.path(); 726 git(r, &["init", "-q", "-b", "main"]); 727 write(r, "tests/gates/T.gate", &gate("T", "a/", "true", ""), false); 728 write(r, "a/a.txt", "1\n", false); 729 git(r, &["add", "-A"]); 730 git(r, &["commit", "-q", "-m", "init"]); 731 let ev = Tmp::new("bare-ev"); 732 let opts = Options::new(ev.path().join("out")); 733 let o = runner::run_gate(r, &r.join("tests/gates/T.gate"), &opts).unwrap(); 734 assert_eq!(o.verdict, Verdict::Pass, "{}", o.reason); 735 for bad in ["../../usr/bin/env", "/usr/bin/env"] { 736 write(r, "tests/gates/T.gate", &gate("T", "a/", bad, ""), false); 737 git(r, &["commit", "-q", "-am", "bad exec"]); 738 match runner::run_gate(r, &r.join("tests/gates/T.gate"), &opts) { 739 Err(runner::RunError::BadManifest(m)) => assert!(m.contains("run.exec"), "{m}"), 740 other => panic!("{bad}: expected a manifest reject, got {other:?}"), 741 } 742 } 743 } 744 745 #[test] 746 fn user_sandbox_when_the_helper_exists() { 747 if nested_in_sandbox("user_sandbox_when_the_helper_exists") { 748 return; 749 } 750 if !Path::new(aien_test::sandbox::EXEC_HELPER).exists() { 751 println!( 752 "SKIP: {} is not installed (INFRA lane)", 753 aien_test::sandbox::EXEC_HELPER 754 ); 755 return; 756 } 757 let t = Tmp::sandbox_wt(); 758 let r = t.path(); 759 git(r, &["init", "-q", "-b", "main"]); 760 write(r, "tools/a.sh", "#!/bin/sh\necho PASS\n", true); 761 write( 762 r, 763 "tests/gates/A.gate", 764 &gate("A", "a/", "tools/a.sh", ""), 765 false, 766 ); 767 write(r, "a/a.txt", "1\n", false); 768 git(r, &["add", "-A"]); 769 git(r, &["commit", "-q", "-m", "init"]); 770 let ev = Tmp::new("sandbox-ev"); 771 let mut opts = Options::new(ev.path().join("out")); 772 opts.sandbox = Sandbox::User; 773 let o = runner::run_gate(r, &r.join("tests/gates/A.gate"), &opts).unwrap(); 774 println!("sandbox user: {} {}", o.verdict.as_str(), o.reason); 775 assert_eq!(o.verdict, Verdict::Pass, "{}", o.reason); 776 } 777 778 // ---------------------------------------------------------------- ENGINE-2 review fixes 779 780 /// A fake `gh` that logs its arguments; `gh.down` makes every call fail and 781 /// `fail-` makes calls about that commit fail. 782 fn fake_gh(w: &World) -> (PathBuf, PathBuf, PathBuf) { 783 let fake = w.state.root.join("fake-gh"); 784 let log = w.state.root.join("gh.log"); 785 let down = w.state.root.join("gh.down"); 786 fs::create_dir_all(&w.state.root).unwrap(); 787 fs::write( 788 &fake, 789 format!( 790 "#!/bin/sh\nroot={}\nif [ -e \"$root/gh.down\" ]; then echo 'connect: network unreachable' >&2; exit 1; fi\nfor a in \"$@\"; do for f in \"$root\"/fail-*; do [ -e \"$f\" ] || continue; s=${{f##*/fail-}}; case \"$a\" in *\"$s\"*) echo 'refused' >&2; exit 1;; esac; done; done\necho \"$@\" >> {}\nexit 0\n", 791 w.state.root.display(), 792 log.display() 793 ), 794 ) 795 .unwrap(); 796 fs::set_permissions(&fake, fs::Permissions::from_mode(0o755)).unwrap(); 797 (fake, log, down) 798 } 799 800 #[test] 801 fn worker_refuses_unsandboxed_runs_and_bad_names() { 802 let w = world(); 803 let mut cfg = w.config(); 804 cfg.allow_unsandboxed = false; 805 let e = worker::run_once(&cfg, REPO, &w.head).unwrap_err(); 806 assert!(e.contains("--dev-unsandboxed"), "{e}"); 807 // Never with GitHub heads, even in development mode (the CLI applies it). 808 cfg.allow_unsandboxed = true; 809 let e = cfg.check_sandbox_policy_for(true).unwrap_err(); 810 assert!(e.contains("--github"), "{e}"); 811 let cfg = w.config(); 812 for (repo, sha) in [ 813 ("..", w.head.as_str()), 814 ("a/b", w.head.as_str()), 815 (".hidden", w.head.as_str()), 816 (REPO, "HEAD"), 817 (REPO, &w.head[..12]), 818 ] { 819 let e = worker::run_once(&cfg, repo, sha).unwrap_err(); 820 assert!(e.starts_with("refusing"), "{repo} {sha}: {e}"); 821 } 822 // Nothing was checked out, signed or journaled. 823 assert!(!w.wt_root.exists()); 824 assert!(!w.bundle_path(&w.head).exists()); 825 assert!(!w.state.journal().exists()); 826 } 827 828 #[test] 829 fn worker_refuses_a_key_others_can_read() { 830 let w = world(); 831 fs::set_permissions(&w.key, fs::Permissions::from_mode(0o644)).unwrap(); 832 let e = worker::run_once(&w.config(), REPO, &w.head).unwrap_err(); 833 assert!(e.contains("mode 644"), "{e}"); 834 assert!(!w.wt_root.exists()); 835 assert!(!w.bundle_path(&w.head).exists()); 836 } 837 838 #[test] 839 fn github_success_needs_a_ready_verify() { 840 let w = world(); 841 let (fake, log, _down) = fake_gh(&w); 842 let mut cfg = w.config(); 843 cfg.github = true; 844 cfg.gh = fake.display().to_string(); 845 // Signed by a key the repository does not list at BASE: the gates pass, 846 // the bundle algebra says PASS, and still no success is posted. 847 cfg.key = w.other_key.clone(); 848 let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); 849 assert_eq!(s.verdict, Verdict::Pass, "{}", s.reason); 850 assert_eq!(s.bundle_verdict, "PASS"); 851 assert!(!s.ready); 852 assert_eq!(s.publication, "posted"); 853 let l = fs::read_to_string(&log).unwrap(); 854 assert!(l.contains("state=error"), "{l}"); 855 assert!(!l.contains("state=success"), "{l}"); 856 let j = fs::read_to_string(w.state.journal()).unwrap(); 857 assert!(j.contains("\"verify\":\"BLOCKED\""), "{j}"); 858 assert!(j.contains("UNKNOWN_KEY"), "{j}"); 859 // With the trusted key the same head is READY and success is posted. 860 let mut cfg = cfg.clone(); 861 cfg.key = w.key.clone(); 862 let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); 863 assert!(s.ready, "{:?}", s.notes); 864 let l = fs::read_to_string(&log).unwrap(); 865 assert!(l.contains("state=success"), "{l}"); 866 } 867 868 #[test] 869 fn outbox_replays_in_queue_order() { 870 let w = world(); 871 let (fake, log, down) = fake_gh(&w); 872 let mut cfg = w.config(); 873 cfg.github = true; 874 cfg.gh = fake.display().to_string(); 875 fs::write(&down, "").unwrap(); 876 // Queue the heads so that queue order differs from name order. 877 let (first, second) = if w.head > w.head_h { 878 (w.head.clone(), w.head_h.clone()) 879 } else { 880 (w.head_h.clone(), w.head.clone()) 881 }; 882 for sha in [&first, &second] { 883 let s = worker::run_once(&cfg, REPO, sha).expect("worker"); 884 assert_eq!(s.publication, "pending"); 885 } 886 let q = worker::outbox_files(&w.state); 887 assert_eq!(q.len(), 2); 888 assert!(q[0].to_string_lossy().contains(&first)); 889 // Still down: nothing posted, both pending. 890 assert_eq!(worker::flush_outbox(&cfg), (0, 2)); 891 // Up, but GitHub refuses the oldest: the replay stops there, the newer 892 // status does not overtake it. 893 fs::remove_file(&down).unwrap(); 894 let block = w.state.root.join(format!("fail-{first}")); 895 fs::write(&block, "").unwrap(); 896 assert_eq!(worker::flush_outbox(&cfg), (0, 2)); 897 assert!(!log.exists() || fs::read_to_string(&log).unwrap().is_empty()); 898 // Fully back: both posted, oldest first. 899 fs::remove_file(&block).unwrap(); 900 assert_eq!(worker::flush_outbox(&cfg), (2, 0)); 901 assert!(worker::outbox_files(&w.state).is_empty()); 902 let l = fs::read_to_string(&log).unwrap(); 903 let a = l.find(&format!("statuses/{first}")).expect("first posted"); 904 let b = l 905 .find(&format!("statuses/{second}")) 906 .expect("second posted"); 907 assert!(a < b, "{l}"); 908 } 909 910 #[test] 911 fn verify_rejects_another_check_id_or_manifest() { 912 let w = verified_world(); 913 let key = bundle::load_signing_key(&w.key).unwrap(); 914 let original = w.read_bundle(&w.head); 915 916 // A re-signed entry naming another check id. 917 let mut b = original.clone(); 918 b.as_object_mut().unwrap().remove("signature"); 919 b["checks"][0]["check_id"] = json!("0".repeat(64)); 920 w.write_bundle(&w.head, &bundle::sign(&b, &key).unwrap()); 921 let r = w.verify(&w.ask(&w.head)); 922 assert_blocked(&r, "check id"); 923 assert!( 924 r.lines.iter().any(|l| l.contains("CHECK_ID_MISMATCH")), 925 "{:#?}", 926 r.lines 927 ); 928 929 // A receipt made from another manifest, stored under its own digest and 930 // named by a re-signed bundle. 931 let digest = original["checks"][0]["receipt"].as_str().unwrap(); 932 let dir = w.state.evidence(REPO, &w.head); 933 let mut receipt: Value = 934 serde_json::from_slice(&fs::read(dir.join(format!("{digest}.json"))).unwrap()).unwrap(); 935 receipt["core"]["manifest_digest"] = json!("1".repeat(64)); 936 let (forged, _) = aien_test::evidence::Store::new(&dir) 937 .put_receipt(&receipt) 938 .unwrap(); 939 let mut b = original.clone(); 940 b.as_object_mut().unwrap().remove("signature"); 941 b["checks"][0]["receipt"] = json!(forged); 942 w.write_bundle(&w.head, &bundle::sign(&b, &key).unwrap()); 943 let r = w.verify(&w.ask(&w.head)); 944 assert_blocked(&r, "manifest"); 945 assert!( 946 r.lines.iter().any(|l| l.contains("MANIFEST_MISMATCH")), 947 "{:#?}", 948 r.lines 949 ); 950 assert_eq!(line(&r, "Executed gates:"), "Executed gates: none"); 951 } 952 953 #[test] 954 fn main_head_is_verified_against_its_first_parent() { 955 let w = world(); 956 // Land the topic on main: the head is now the tip of origin/main. 957 git(&w.origin, &["merge", "-q", "--ff-only", "topic"]); 958 git(&w.clone, &["fetch", "-q", "--all"]); 959 assert_eq!(git(&w.clone, &["rev-parse", "origin/main"]), w.head); 960 let s = worker::run_once(&w.config(), REPO, &w.head).expect("worker"); 961 assert_eq!(s.verdict, Verdict::Pass, "{} {:?}", s.reason, s.notes); 962 assert!(s.ready, "{:?}", s.notes); 963 // `verify` with the default base reaches the same plan and is READY. 964 let r = w.verify(&w.ask(&w.head)); 965 assert_eq!( 966 line(&r, "MERGE ELIGIBILITY:"), 967 "MERGE ELIGIBILITY: READY", 968 "{:#?}", 969 r.lines 970 ); 971 assert_eq!(line(&r, "Executed gates:"), "Executed gates: 1 (A)"); 972 } 973 974 #[test] 975 fn full_scope_worker_qualifies_every_gate_and_signs_the_scope() { 976 // An Alpha: a commit already on main, judged on every gate. H watches 977 // h/, which the commit does not touch. 978 let w = world(); 979 git(&w.origin, &["merge", "-q", "--ff-only", "topic"]); 980 git(&w.clone, &["fetch", "-q", "--all"]); 981 let s = worker::run_once(&w.config(), REPO, &w.head).expect("worker"); 982 assert!(s.ready, "{:?}", s.notes); 983 assert!(!s.gates.iter().any(|g| g.0 == "H"), "{:?}", s.gates); 984 assert_eq!(w.read_bundle(&w.head)["plan"]["scope"], "changed"); 985 986 let mut cfg = w.config(); 987 cfg.full = true; 988 let s = worker::run_once(&cfg, REPO, &w.head).expect("worker --full"); 989 assert_eq!(s.verdict, Verdict::Pass, "{} {:?}", s.reason, s.notes); 990 assert!(s.ready, "{:?}", s.notes); 991 assert_eq!(gate_status(&s, "H"), ("run".to_string(), Verdict::Pass)); 992 let b = w.read_bundle(&w.head); 993 assert_eq!(b["plan"]["scope"], "full", "{}", b["plan"]); 994 // `verify` plans in the signed scope and reaches the same graph. 995 let r = w.verify(&w.ask(&w.head)); 996 assert_eq!( 997 line(&r, "MERGE ELIGIBILITY:"), 998 "MERGE ELIGIBILITY: READY", 999 "{:#?}", 1000 r.lines 1001 ); 1002 assert_eq!(line(&r, "Affected gates:"), "Affected gates: 2 (A H)"); 1003 // verify-bundle --require-full refuses it: this world's gates are all 1004 // backend host, so its full-scope PASS is not an Alpha (NO_GPU_RECEIPT). 1005 // The gb10 receipt itself is covered by bundle.rs's tests. 1006 let vk = bundle::load_signing_key(&w.key).unwrap().verifying_key(); 1007 let expect = bundle::Expect { 1008 repository: b["repository"].as_str().unwrap().to_string(), 1009 commit: w.head.clone(), 1010 pubkey_hex: bundle::hex_encode(vk.as_bytes()), 1011 required: vec!["A".to_string(), "H".to_string()], 1012 require_full: true, 1013 allow_host_only: false, 1014 }; 1015 let err = bundle::verify(&b, &expect).expect_err("no gb10 gate, no Alpha"); 1016 assert_eq!(err.code(), "NO_GPU_RECEIPT", "{err}"); 1017 // The caller reads the repository's gate manifests; this world declares no 1018 // gb10 gate, so it passes --allow-host-only and the same full-scope PASS is 1019 // an Alpha. Without the flag (above) it is not. 1020 let mut host_only = expect.clone(); 1021 host_only.allow_host_only = true; 1022 let v = bundle::verify(&b, &host_only).expect("host-only Alpha when no gate declares gb10"); 1023 assert_eq!(v.gate_verdict(), "PASS"); 1024 } 1025 1026 #[test] 1027 fn symlinked_exec_out_of_the_tree_never_runs() { 1028 let t = Tmp::new("symlink"); 1029 let r = t.path(); 1030 git(r, &["init", "-q", "-b", "main"]); 1031 fs::create_dir_all(r.join("tools")).unwrap(); 1032 std::os::unix::fs::symlink("/bin/true", r.join("tools/run.sh")).unwrap(); 1033 write( 1034 r, 1035 "tests/gates/T.gate", 1036 &gate("T", "a/", "tools/run.sh", ""), 1037 false, 1038 ); 1039 write(r, "a/a.txt", "1\n", false); 1040 git(r, &["add", "-A"]); 1041 git(r, &["commit", "-q", "-m", "init"]); 1042 let ev = Tmp::new("symlink-ev"); 1043 let opts = Options::new(ev.path().join("out")); 1044 let o = runner::run_gate(r, &r.join("tests/gates/T.gate"), &opts).unwrap(); 1045 assert_eq!(o.verdict, Verdict::MissingImplementation, "{}", o.reason); 1046 assert_eq!(runner::exec_path(r, "tools/run.sh"), None); 1047 } 1048 1049 #[test] 1050 fn worker_in_the_user_sandbox_is_ready() { 1051 if nested_in_sandbox("worker_in_the_user_sandbox_is_ready") { 1052 return; 1053 } 1054 let _turn = USER_SANDBOX.lock().unwrap_or_else(|e| e.into_inner()); 1055 if !Path::new(aien_test::sandbox::EXEC_HELPER).exists() { 1056 println!( 1057 "SKIP: {} is not installed (INFRA lane)", 1058 aien_test::sandbox::EXEC_HELPER 1059 ); 1060 return; 1061 } 1062 let w = world(); 1063 let mut cfg = w.config(); 1064 cfg.allow_unsandboxed = false; 1065 cfg.sandbox = Sandbox::User; 1066 if !wt_tool().is_file() { 1067 println!( 1068 "SKIP: {} is not in this tree (INFRA lane)", 1069 wt_tool().display() 1070 ); 1071 return; 1072 } 1073 cfg.wt_root = PathBuf::from("/var/lib/aien-run/wt"); 1074 cfg.wt_tool = Some(wt_tool()); 1075 let mirror = Path::new(worker::MIRROR_ROOT).join(format!("{REPO}.git")); 1076 let _mirror = MirrorCleanup(mirror.clone()); 1077 let s = worker::run_once(&cfg, REPO, &w.head).expect("worker"); 1078 println!( 1079 "worker --sandbox user: {} {} {:?}", 1080 s.verdict.as_str(), 1081 s.reason, 1082 s.notes 1083 ); 1084 // The wt.sh worktree is gone again and no note says otherwise. 1085 assert!( 1086 !Path::new("/var/lib/aien-run/wt") 1087 .join(REPO) 1088 .join(&w.head) 1089 .exists(), 1090 "worktree left behind" 1091 ); 1092 assert!(mirror.join("HEAD").exists(), "wt.sh keeps its mirror"); 1093 assert_eq!(s.verdict, Verdict::Pass, "{} {:?}", s.reason, s.notes); 1094 assert!(s.ready, "{:?}", s.notes); 1095 let r = w.verify(&w.ask(&w.head)); 1096 assert_eq!( 1097 line(&r, "MERGE ELIGIBILITY:"), 1098 "MERGE ELIGIBILITY: READY", 1099 "{:#?}", 1100 r.lines 1101 ); 1102 } 1103 1104 #[test] 1105 fn worker_cli_refuses_unsandboxed_github_and_unflagged_none() { 1106 let bin = env!("CARGO_BIN_EXE_aien-test"); 1107 let t = Tmp::new("cli"); 1108 let state = t.path().join("state"); 1109 let sha = "a".repeat(40); 1110 let run = |extra: &[&str]| { 1111 let mut args = vec![ 1112 "worker", 1113 "--once", 1114 "repo", 1115 sha.as_str(), 1116 "--state-dir", 1117 state.to_str().unwrap(), 1118 "--clones", 1119 t.path().to_str().unwrap(), 1120 ]; 1121 args.extend_from_slice(extra); 1122 Command::new(bin).args(&args).output().unwrap() 1123 }; 1124 let o = run(&["--sandbox", "none"]); 1125 assert_eq!(o.status.code(), Some(2)); 1126 assert!(String::from_utf8_lossy(&o.stderr).contains("--dev-unsandboxed")); 1127 let o = run(&["--sandbox", "none", "--dev-unsandboxed", "--github"]); 1128 assert_eq!(o.status.code(), Some(2)); 1129 assert!(String::from_utf8_lossy(&o.stderr).contains("--github")); 1130 // Nothing ran: no state was written. 1131 assert!(!state.exists()); 1132 } 1133 1134 // ---------------------------------------------------------------- INFRA-2 alignment 1135 1136 /// INFRA's worktree tool, from this repository. 1137 fn wt_tool() -> PathBuf { 1138 Path::new(env!("CARGO_MANIFEST_DIR")).join("../aien-local-ci/wt.sh") 1139 } 1140 1141 /// Removes a test mirror under `/var/lib/aien-run/mirror` when dropped. 1142 struct MirrorCleanup(PathBuf); 1143 1144 impl Drop for MirrorCleanup { 1145 fn drop(&mut self) { 1146 let _ = fs::remove_dir_all(&self.0); 1147 } 1148 } 1149 1150 #[test] 1151 fn worker_refuses_the_user_sandbox_without_the_wt_tool() { 1152 let w = world(); 1153 let mut cfg = w.config(); 1154 cfg.sandbox = Sandbox::User; 1155 cfg.wt_tool = None; 1156 let e = worker::run_once(&cfg, REPO, &w.head).unwrap_err(); 1157 assert!(e.contains("--wt-tool"), "{e}"); 1158 // Nothing was checked out. 1159 assert!(!w.wt_root.join(REPO).join(&w.head).exists()); 1160 } 1161 1162 #[test] 1163 fn only_a_wt_sh_link_is_trusted() { 1164 let t = Tmp::new("wt-link"); 1165 let wt = t.path().join("wt"); 1166 let mirror = t.path().join("m.git"); 1167 fs::create_dir_all(&wt).unwrap(); 1168 // Owned by the test user, not root: refused even with the right target. 1169 fs::write( 1170 wt.join(".git"), 1171 format!("gitdir: {}/worktrees/x\n", mirror.display()), 1172 ) 1173 .unwrap(); 1174 // Mode 0644 as wt.sh leaves it, so only the owner is wrong. 1175 fs::set_permissions(wt.join(".git"), fs::Permissions::from_mode(0o644)).unwrap(); 1176 let e = worker::check_worktree_link(&wt, &mirror).unwrap_err(); 1177 assert!(e.contains("root-owned"), "{e}"); 1178 // A real wt.sh worktree passes when one is present on this host. 1179 let real = Path::new("/var/lib/aien-run/wt/aien-sovereign-core"); 1180 let found = fs::read_dir(real).ok().and_then(|mut rd| { 1181 rd.find_map(|e| { 1182 // The run directory layout (`//`), or the older flat one. 1183 e.ok() 1184 .map(|e| e.path()) 1185 .map(|p| { 1186 let nested = p.join("aien-sovereign-core"); 1187 if nested.join(".git").is_file() { 1188 nested 1189 } else { 1190 p 1191 } 1192 }) 1193 .filter(|p| p.join(".git").is_file()) 1194 }) 1195 }); 1196 if let Some(p) = found { 1197 let m = Path::new(worker::MIRROR_ROOT).join("aien-sovereign-core.git"); 1198 worker::check_worktree_link(&p, &m).expect("wt.sh worktree"); 1199 let other = Path::new(worker::MIRROR_ROOT).join("elsewhere.git"); 1200 assert!(worker::check_worktree_link(&p, &other).is_err()); 1201 } else { 1202 println!("SKIP real wt.sh worktree: none present"); 1203 } 1204 } 1205 1206 #[test] 1207 fn a_wrong_target_dir_is_refused_by_the_helper() { 1208 if nested_in_sandbox("a_wrong_target_dir_is_refused_by_the_helper") { 1209 return; 1210 } 1211 if !Path::new(aien_test::sandbox::EXEC_HELPER).exists() { 1212 println!( 1213 "SKIP: {} is not installed (INFRA lane)", 1214 aien_test::sandbox::EXEC_HELPER 1215 ); 1216 return; 1217 } 1218 // The helper itself: exit 2, its prefix on stderr, nothing ran. 1219 let t = Tmp::sandbox_wt(); 1220 let r = t.path(); 1221 let bad = "/var/lib/aien-run/target/aien-test-selftest/other"; 1222 let (program, args) = aien_test::sandbox::command( 1223 Sandbox::User, 1224 Path::new("/bin/true"), 1225 &[], 1226 r, 1227 10, 1228 "host", 1229 &[("CARGO_TARGET_DIR".to_string(), bad.to_string())], 1230 ); 1231 let out = Command::new(program).args(&args).output().unwrap(); 1232 assert_eq!(out.status.code(), Some(2), "{out:?}"); 1233 assert!(out.stderr.starts_with(b"aien-run-exec:"), "{out:?}"); 1234 assert!(runner::sandbox_refused( 1235 Sandbox::User, 1236 out.status.code(), 1237 &out.stderr 1238 )); 1239 assert!(!runner::sandbox_refused( 1240 Sandbox::None, 1241 out.status.code(), 1242 &out.stderr 1243 )); 1244 assert!(!runner::sandbox_refused( 1245 Sandbox::User, 1246 Some(2), 1247 b"own error\n" 1248 )); 1249 1250 // Through the runner: a gate that expects exit 2 still never passes on 1251 // a refusal, and its receipt has no exit status. 1252 git(r, &["init", "-q", "-b", "main"]); 1253 write( 1254 r, 1255 "tests/gates/R.gate", 1256 &gate("R", "a/", "true", "").replace("exit: 0", "exit: 2"), 1257 false, 1258 ); 1259 write(r, "a/a.txt", "1\n", false); 1260 git(r, &["add", "-A"]); 1261 git(r, &["commit", "-q", "-m", "init"]); 1262 let ev = Tmp::new("refused-ev"); 1263 let mut opts = Options::new(ev.path().join("out")); 1264 opts.sandbox = Sandbox::User; 1265 opts.cargo_target_dir = Some(PathBuf::from(bad)); 1266 let o = runner::run_gate(r, &r.join("tests/gates/R.gate"), &opts).unwrap(); 1267 assert_eq!(o.verdict, Verdict::Fail, "{}", o.reason); 1268 let receipt: serde_json::Value = 1269 serde_json::from_slice(&fs::read(o.receipt_path.unwrap()).unwrap()).unwrap(); 1270 assert_eq!(receipt["core"]["exit_status"], serde_json::Value::Null); 1271 } 1272 1273 // ---------------------------------------------------------------- SANDBOX lane: sibling checkouts 1274 1275 /// The sibling source repository of these scenarios (its trusted clone sits 1276 /// next to the world's clone, its mirror under `/var/lib/aien-run/mirror`). 1277 const SIB: &str = "aien-test-selftest-sib"; 1278 1279 /// A gate S that passes only when `../sib/lib/x.txt` says `hello`; as 1280 /// `aien-run` it also demands that neither the sibling nor the run directory 1281 /// is writable. Returns the head that adds S, the sibling's commit and a 1282 /// sibling map naming it. 1283 fn sibling_world(w: &World) -> (String, String, PathBuf) { 1284 let root = w.origin.parent().unwrap().to_path_buf(); 1285 let so = root.join("sib-origin"); 1286 fs::create_dir_all(&so).unwrap(); 1287 git(&so, &["init", "-q", "-b", "main"]); 1288 write(&so, "lib/x.txt", "hello\n", false); 1289 git(&so, &["add", "-A"]); 1290 git(&so, &["commit", "-q", "-m", "sib"]); 1291 let sib_sha = git(&so, &["rev-parse", "HEAD"]); 1292 let clones = w.clone.parent().unwrap(); 1293 git(clones, &["clone", "-q", so.to_str().unwrap(), SIB]); 1294 1295 git(&w.origin, &["checkout", "-q", "-b", "topic-s", "main"]); 1296 write( 1297 &w.origin, 1298 "tools/s.sh", 1299 "#!/bin/sh\n\ 1300 test \"$(cat ../sib/lib/x.txt)\" = hello || { echo 'no sibling' >&2; exit 1; }\n\ 1301 echo \"AIEN-OBS sibling_commit \\\"$(git -C ../sib rev-parse HEAD)\\\"\"\n\ 1302 if [ \"$(id -un)\" = aien-run ]; then\n\ 1303 [ -w ../sib/lib/x.txt ] && { echo 'sibling writable' >&2; exit 1; }\n\ 1304 [ -w .. ] && { echo 'run directory writable' >&2; exit 1; }\n\ 1305 fi\n\ 1306 echo PASS\n", 1307 true, 1308 ); 1309 write( 1310 &w.origin, 1311 "tests/gates/S.gate", 1312 &gate("S", "tools/", "tools/s.sh", ""), 1313 false, 1314 ); 1315 git(&w.origin, &["add", "-A"]); 1316 git(&w.origin, &["commit", "-q", "-m", "gate S reads ../sib"]); 1317 let head_s = git(&w.origin, &["rev-parse", "HEAD"]); 1318 git(&w.origin, &["checkout", "-q", "main"]); 1319 git(&w.clone, &["fetch", "-q", "--all"]); 1320 1321 let map = root.join("siblings"); 1322 fs::write(&map, format!("# test map\n{REPO} sib {SIB} main\n")).unwrap(); 1323 (head_s, sib_sha, map) 1324 } 1325 1326 fn gate_verdict(s: &worker::Summary, id: &str) -> Verdict { 1327 s.gates 1328 .iter() 1329 .find(|g| g.0 == id) 1330 .map(|g| g.2) 1331 .unwrap_or_else(|| panic!("no gate {id} in {:?}", s.gates)) 1332 } 1333 1334 #[test] 1335 fn worker_provides_a_sibling_checkout_and_removes_it() { 1336 if nested_in_sandbox("worker_provides_a_sibling_checkout_and_removes_it") { 1337 return; 1338 } 1339 let w = world(); 1340 let (head_s, sib_sha, map) = sibling_world(&w); 1341 let mut cfg = w.config(); 1342 cfg.operator = true; // S is a new gate: a pipeline configuration change. 1343 1344 // Negative control: no sibling map, so ../sib is missing and S fails. 1345 let s = worker::run_once(&cfg, REPO, &head_s).expect("worker"); 1346 assert_eq!(gate_verdict(&s, "S"), Verdict::Fail, "{:?}", s.notes); 1347 1348 cfg.siblings = Some(map); 1349 let s = worker::run_once(&cfg, REPO, &head_s).expect("worker"); 1350 assert_eq!( 1351 gate_verdict(&s, "S"), 1352 Verdict::Pass, 1353 "{} {:?}", 1354 s.reason, 1355 s.notes 1356 ); 1357 let want = format!("sibling ../sib: {SIB} origin/main {sib_sha}"); 1358 assert!(s.notes.contains(&want), "{:?}", s.notes); 1359 // The run directory (checkout and sibling) is gone, and neither clone 1360 // still lists a worktree for it. 1361 assert!(!w.wt_root.join(REPO).join(&head_s).exists()); 1362 let sib_clone = w.clone.parent().unwrap().join(SIB); 1363 for c in [&w.clone, &sib_clone] { 1364 let list = git(c, &["worktree", "list"]); 1365 assert_eq!(list.lines().count(), 1, "{list}"); 1366 } 1367 } 1368 1369 #[test] 1370 fn a_broken_sibling_map_refuses_the_run_before_any_checkout() { 1371 let w = world(); 1372 let mut cfg = w.config(); 1373 let map = w.origin.parent().unwrap().join("bad-siblings"); 1374 fs::write(&map, format!("{REPO} ../escape {SIB} main\n")).unwrap(); 1375 cfg.siblings = Some(map.clone()); 1376 let e = worker::run_once(&cfg, REPO, &w.head).unwrap_err(); 1377 assert!(e.contains("sibling map line 1"), "{e}"); 1378 assert!(!w.wt_root.join(REPO).join(&w.head).exists()); 1379 // A map that cannot be read refuses too. 1380 cfg.siblings = Some(map.with_extension("missing")); 1381 let e = worker::run_once(&cfg, REPO, &w.head).unwrap_err(); 1382 assert!(e.contains("cannot read the sibling map"), "{e}"); 1383 } 1384 1385 #[test] 1386 fn worker_in_the_user_sandbox_reads_a_read_only_sibling() { 1387 if nested_in_sandbox("worker_in_the_user_sandbox_reads_a_read_only_sibling") { 1388 return; 1389 } 1390 let _turn = USER_SANDBOX.lock().unwrap_or_else(|e| e.into_inner()); 1391 if !Path::new(aien_test::sandbox::EXEC_HELPER).exists() || !wt_tool().is_file() { 1392 println!("SKIP: exec helper or wt.sh not present (INFRA lane)"); 1393 return; 1394 } 1395 let w = world(); 1396 let (head_s, sib_sha, map) = sibling_world(&w); 1397 let mut cfg = w.config(); 1398 cfg.allow_unsandboxed = false; 1399 cfg.sandbox = Sandbox::User; 1400 cfg.operator = true; 1401 cfg.wt_root = PathBuf::from("/var/lib/aien-run/wt"); 1402 cfg.wt_tool = Some(wt_tool()); 1403 cfg.siblings = Some(map); 1404 let _m1 = MirrorCleanup(Path::new(worker::MIRROR_ROOT).join(format!("{REPO}.git"))); 1405 let _m2 = MirrorCleanup(Path::new(worker::MIRROR_ROOT).join(format!("{SIB}.git"))); 1406 let s = worker::run_once(&cfg, REPO, &head_s).expect("worker"); 1407 assert_eq!( 1408 gate_verdict(&s, "S"), 1409 Verdict::Pass, 1410 "{} {:?}", 1411 s.reason, 1412 s.notes 1413 ); 1414 let want = format!("sibling ../sib: {SIB} origin/main {sib_sha}"); 1415 assert!(s.notes.contains(&want), "{:?}", s.notes); 1416 assert!( 1417 !Path::new("/var/lib/aien-run/wt") 1418 .join(REPO) 1419 .join(&head_s) 1420 .exists(), 1421 "run directory left behind" 1422 ); 1423 } 1424 1425 /// True inside the user sandbox (`AIEN_SANDBOX_NESTED=1`, set by the worker's 1426 /// sandbox wrapper): the five tests that start a sandbox or provision sibling 1427 /// worktrees themselves cannot nest there (aien-run may not call the helper or 1428 /// write `/var/lib/aien-run/wt`), so they skip and say so. They run everywhere 1429 /// else: on GitHub runners and in operator runs. tests/gates/run.sh records 1430 /// the skip as an observation. 1431 fn nested_in_sandbox(test: &str) -> bool { 1432 let nested = std::env::var(aien_test::sandbox::NESTED_MARKER).as_deref() == Ok("1"); 1433 if nested { 1434 println!( 1435 "SKIP-NESTED: {test}: inside the user sandbox ({}=1)", 1436 aien_test::sandbox::NESTED_MARKER 1437 ); 1438 } 1439 nested 1440 } 1441 1442 /// A new commit `name` on `branch` of the world's origin that writes `files`, 1443 /// fetched into the trusted clone. Returns the commit. 1444 fn commit_on(w: &World, branch: &str, files: &[(&str, &str)], name: &str) -> String { 1445 git(&w.origin, &["checkout", "-q", branch]); 1446 for (rel, content) in files { 1447 write(&w.origin, rel, content, false); 1448 } 1449 git(&w.origin, &["add", "-A"]); 1450 git(&w.origin, &["commit", "-q", "-m", name]); 1451 let sha = git(&w.origin, &["rev-parse", "HEAD"]); 1452 git(&w.origin, &["checkout", "-q", "main"]); 1453 git(&w.clone, &["fetch", "-q", "--all"]); 1454 sha 1455 } 1456 1457 fn gate_status(s: &worker::Summary, id: &str) -> (String, Verdict) { 1458 s.gates 1459 .iter() 1460 .find(|g| g.0 == id) 1461 .map(|g| (g.1.clone(), g.2)) 1462 .unwrap_or_else(|| panic!("no gate {id} in {:?}", s.gates)) 1463 } 1464 1465 /// With siblings, the worker reuses a result only for the same commit of 1466 /// the repository and only while every sibling is at the same commit: the 1467 /// sibling commits are in the cache key, and the evidence directory is the 1468 /// head's own. 1469 #[test] 1470 fn worker_reuses_only_the_same_commit_while_its_sibling_commits_match() { 1471 if nested_in_sandbox("worker_reuses_only_the_same_commit_while_its_sibling_commits_match") { 1472 return; 1473 } 1474 let w = world(); 1475 let (head_s, sib_sha, map) = sibling_world(&w); 1476 let mut cfg = w.config(); 1477 cfg.operator = true; // S is a new gate: a pipeline configuration change. 1478 cfg.siblings = Some(map); 1479 let pass = |st: &str| (st.to_string(), Verdict::Pass); 1480 1481 let r1 = worker::run_once(&cfg, REPO, &head_s).expect("worker r1"); 1482 assert_eq!(gate_status(&r1, "S"), pass("run"), "{:?}", r1.notes); 1483 assert!( 1484 r1.notes.iter().any(|n| n.contains(&sib_sha)), 1485 "{:?}", 1486 r1.notes 1487 ); 1488 1489 // The same head again, sibling unchanged: reused. 1490 let r2 = worker::run_once(&cfg, REPO, &head_s).expect("worker r2"); 1491 assert_eq!(gate_status(&r2, "S"), pass("cached"), "{:?}", r2.gates); 1492 1493 // A new commit that leaves S's declared inputs (tools/) alone still runs 1494 // S: results never cross commits. 1495 let head_s2 = commit_on(&w, "topic-s", &[("h/h.txt", "s2\n")], "change h"); 1496 let r3 = worker::run_once(&cfg, REPO, &head_s2).expect("worker r3"); 1497 assert_eq!(gate_status(&r3, "S"), pass("run"), "{:?}", r3.gates); 1498 1499 // The sibling moves to a new commit: the same head runs S again. 1500 let so = w.origin.parent().unwrap().join("sib-origin"); 1501 write(&so, "lib/extra.txt", "world\n", false); 1502 git(&so, &["add", "-A"]); 1503 git(&so, &["commit", "-q", "-m", "sib v2"]); 1504 let sib_sha2 = git(&so, &["rev-parse", "HEAD"]); 1505 assert_ne!(sib_sha, sib_sha2); 1506 git( 1507 &w.clone.parent().unwrap().join(SIB), 1508 &["fetch", "-q", "--all"], 1509 ); 1510 let r4 = worker::run_once(&cfg, REPO, &head_s).expect("worker r4"); 1511 assert_eq!(gate_status(&r4, "S"), pass("run"), "{:?}", r4.gates); 1512 assert!( 1513 r4.notes.iter().any(|n| n.contains(&sib_sha2)), 1514 "{:?}", 1515 r4.notes 1516 ); 1517 1518 // Same head, sibling still at its new commit: reused again. 1519 let r5 = worker::run_once(&cfg, REPO, &head_s).expect("worker r5"); 1520 assert_eq!(gate_status(&r5, "S"), pass("cached"), "{:?}", r5.gates); 1521 } 1522 1523 /// Cache safety across commits: gate U declares only `u/` as its input but 1524 /// its program also reads the root `README.md`, as SC-TEST's 1525 /// `tier2_boundary` tests read the root `README.md` and `COVENANT.md`. A 1526 /// later commit that changes only `README.md` makes U fail when it really 1527 /// runs, so the worker must run U again, never hand it the earlier PASS. 1528 #[test] 1529 fn worker_never_reuses_a_pass_when_an_undeclared_file_changed_across_commits() { 1530 if nested_in_sandbox( 1531 "worker_never_reuses_a_pass_when_an_undeclared_file_changed_across_commits", 1532 ) { 1533 return; 1534 } 1535 let w = world(); 1536 let mut cfg = w.config(); 1537 cfg.operator = true; // U is a new gate: a pipeline configuration change. 1538 1539 git(&w.origin, &["checkout", "-q", "-b", "topic-u", "main"]); 1540 write( 1541 &w.origin, 1542 "tools/u.sh", 1543 "#!/bin/sh\ngrep -q 'AGPL-3.0' README.md || { echo 'README.md lost its licence' >&2; exit 1; }\necho PASS\n", 1544 true, 1545 ); 1546 git(&w.origin, &["checkout", "-q", "main"]); 1547 let head_u1 = commit_on( 1548 &w, 1549 "topic-u", 1550 &[ 1551 ("u/u.txt", "1\n"), 1552 ("README.md", "Licence: AGPL-3.0\n"), 1553 ("tests/gates/U.gate", &gate("U", "u/", "tools/u.sh", "")), 1554 ], 1555 "gate U reads README.md", 1556 ); 1557 let head_u2 = commit_on( 1558 &w, 1559 "topic-u", 1560 &[("README.md", "Licence: none\n")], 1561 "README.md loses its licence", 1562 ); 1563 1564 let r1 = worker::run_once(&cfg, REPO, &head_u1).expect("worker u1"); 1565 assert_eq!( 1566 gate_status(&r1, "U"), 1567 ("run".to_string(), Verdict::Pass), 1568 "{:?}", 1569 r1.notes 1570 ); 1571 let r2 = worker::run_once(&cfg, REPO, &head_u2).expect("worker u2"); 1572 assert_eq!( 1573 gate_status(&r2, "U"), 1574 ("run".to_string(), Verdict::Fail), 1575 "a PASS from {head_u1} must not be handed to {head_u2}: {:?}", 1576 r2.gates 1577 ); 1578 } 1579 1580 /// An operator run of a pipeline configuration change (a head that adds a 1581 /// gate under `tests/gates/`) is checked with the operator's permission too: 1582 /// the independent check recomputes the plan with `operator` set, so a 1583 /// passing operator run is READY and posts success. Without the operator the 1584 /// same head stays BLOCKED_OPERATOR and never posts success. 1585 #[test] 1586 fn worker_operator_run_of_a_config_change_is_ready_and_posts_success() { 1587 if nested_in_sandbox("worker_operator_run_of_a_config_change_is_ready_and_posts_success") { 1588 return; 1589 } 1590 let w = world(); 1591 let (fake, log, _down) = fake_gh(&w); 1592 let mut cfg = w.config(); 1593 cfg.github = true; 1594 cfg.gh = fake.display().to_string(); 1595 git(&w.origin, &["checkout", "-q", "-b", "topic-op", "main"]); 1596 write(&w.origin, "op/op.sh", "#!/bin/sh\necho PASS\n", true); 1597 git(&w.origin, &["checkout", "-q", "main"]); 1598 let head = commit_on( 1599 &w, 1600 "topic-op", 1601 &[ 1602 ("op/op.txt", "1\n"), 1603 ("tests/gates/OP.gate", &gate("OP", "op/", "op/op.sh", "")), 1604 ], 1605 "new gate OP", 1606 ); 1607 1608 // Not the operator: blocked, never success. 1609 let s = worker::run_once(&cfg, REPO, &head).expect("worker (no operator)"); 1610 assert!(!s.ready, "{:?}", s.notes); 1611 let l = fs::read_to_string(&log).unwrap(); 1612 assert!(!l.contains("state=success"), "{l}"); 1613 1614 // The operator: the gate runs and passes, the check agrees, success. 1615 cfg.operator = true; 1616 let s = worker::run_once(&cfg, REPO, &head).expect("worker (operator)"); 1617 assert_eq!(gate_verdict(&s, "OP"), Verdict::Pass, "{:?}", s.notes); 1618 assert_eq!(s.bundle_verdict, "PASS"); 1619 assert!(s.ready, "{:?}", s.notes); 1620 let l = fs::read_to_string(&log).unwrap(); 1621 assert!(l.contains("state=success"), "{l}"); 1622 let j = fs::read_to_string(w.state.journal()).unwrap(); 1623 assert!( 1624 j.lines().last().unwrap().contains("\"verify\":\"READY\""), 1625 "{j}" 1626 ); 1627 1628 // Permission must never be inherited from an earlier authorized run 1629 // of this exact head. A later non-operator run must publish a refusal. 1630 let prior_statuses = l; 1631 cfg.operator = false; 1632 let s = worker::run_once(&cfg, REPO, &head).expect("worker (operator revoked)"); 1633 assert!(!s.ready, "operator authorization leaked into a later run"); 1634 let statuses = fs::read_to_string(&log).unwrap(); 1635 let new_statuses = statuses 1636 .strip_prefix(&prior_statuses) 1637 .expect("the worker must append to the existing status log"); 1638 assert!(new_statuses.contains("state=error"), "{new_statuses}"); 1639 assert!(!new_statuses.contains("state=success"), "{new_statuses}"); 1640 let journal = fs::read_to_string(w.state.journal()).unwrap(); 1641 assert!( 1642 journal 1643 .lines() 1644 .last() 1645 .unwrap() 1646 .contains("\"verify\":\"BLOCKED\""), 1647 "{journal}" 1648 ); 1649 } 1650 1651 /// A new commit of `branch` with the very same tree (a re-push, a squash 1652 /// merge of an up-to-date PR). 1653 fn same_tree_commit_on(w: &World, branch: &str) -> String { 1654 git(&w.origin, &["checkout", "-q", branch]); 1655 git( 1656 &w.origin, 1657 &["commit", "-q", "--allow-empty", "-m", "same tree"], 1658 ); 1659 let sha = git(&w.origin, &["rev-parse", "HEAD"]); 1660 git(&w.origin, &["checkout", "-q", "main"]); 1661 git(&w.clone, &["fetch", "-q", "--all"]); 1662 sha 1663 } 1664 1665 fn bundle_check(s: &worker::Summary, id: &str) -> serde_json::Value { 1666 let b: serde_json::Value = serde_json::from_slice(&fs::read(&s.bundle_path).unwrap()).unwrap(); 1667 b["checks"] 1668 .as_array() 1669 .unwrap() 1670 .iter() 1671 .find(|c| c["gate"] == id) 1672 .cloned() 1673 .unwrap_or_else(|| panic!("no check {id} in {b}")) 1674 } 1675 1676 /// Judge once (Drake 2026-10-20): a second head with the same tree reuses 1677 /// the first head's result through the shared store, the signed bundle says 1678 /// which receipt and which head it came from, and verify still says READY. 1679 #[test] 1680 fn another_head_reuses_through_the_shared_store_and_the_bundle_says_so() { 1681 let w = world(); 1682 let cfg = w.config(); 1683 let r1 = worker::run_once(&cfg, REPO, &w.head).expect("worker r1"); 1684 assert_eq!(gate_status(&r1, "A"), ("run".to_string(), Verdict::Pass)); 1685 let receipt = bundle_check(&r1, "A")["receipt"] 1686 .as_str() 1687 .unwrap() 1688 .to_string(); 1689 1690 let head2 = same_tree_commit_on(&w, "topic"); 1691 let r2 = worker::run_once(&cfg, REPO, &head2).expect("worker r2"); 1692 assert_eq!(gate_status(&r2, "A"), ("cached".to_string(), Verdict::Pass)); 1693 let c = bundle_check(&r2, "A"); 1694 assert_eq!(c["resolution"]["resolved_from"], receipt.as_str()); 1695 assert_eq!(c["resolution"]["resolved_from_commit"], w.head.as_str()); 1696 assert!(r2.ready, "{:?}", r2.notes); 1697 assert_eq!(r2.verdict, Verdict::Pass, "{}", r2.reason); 1698 1699 // A head one declared byte away runs A again. 1700 let head3 = commit_on(&w, "topic", &[("a/a.txt", "a3\n")], "change a"); 1701 let r3 = worker::run_once(&cfg, REPO, &head3).expect("worker r3"); 1702 assert_eq!(gate_status(&r3, "A"), ("run".to_string(), Verdict::Pass)); 1703 } 1704 1705 /// A batch of two heads with one tree runs each shared gate once: one head 1706 /// runs it, the other reuses it, and both bundles are READY. 1707 #[test] 1708 fn a_batch_runs_a_shared_gate_once_for_all_its_heads() { 1709 let w = world(); 1710 let mut cfg = w.config(); 1711 cfg.batch_host = Some(2); 1712 let head2 = same_tree_commit_on(&w, "topic"); 1713 let out = worker::run_batch(&cfg, REPO, &[w.head.clone(), head2.clone()]); 1714 assert_eq!(out.len(), 2); 1715 let mut statuses = Vec::new(); 1716 for (sha, r) in &out { 1717 let s = r.as_ref().unwrap_or_else(|e| panic!("{sha}: {e}")); 1718 assert!(s.ready, "{sha}: {:?}", s.notes); 1719 assert_eq!(s.verdict, Verdict::Pass, "{sha}: {}", s.reason); 1720 statuses.push(gate_status(s, "A").0); 1721 } 1722 statuses.sort(); 1723 assert_eq!(statuses, vec!["cached".to_string(), "run".to_string()]); 1724 } 1725 1726 /// One judge per head: a second judge of a head that is being judged is 1727 /// refused at once, before any checkout. 1728 #[test] 1729 fn a_head_being_judged_is_refused_to_a_second_judge() { 1730 let w = world(); 1731 let cfg = w.config(); 1732 let held = worker::claim_head(&w.state, REPO, &w.head) 1733 .unwrap() 1734 .expect("free"); 1735 let e = worker::run_once(&cfg, REPO, &w.head).expect_err("refused"); 1736 assert!(e.contains("already being judged"), "{e}"); 1737 drop(held); 1738 assert!(worker::run_once(&cfg, REPO, &w.head).is_ok()); 1739 } 1740 1741 #[test] 1742 fn loop_leaves_triggers_of_other_repos_alone() { 1743 // One trigger file is visible to every poller; a poller started with 1744 // --repos takes only its own repositories and leaves the file in place. 1745 let w = world(); 1746 let mut cfg = w.config(); 1747 cfg.repos = vec!["some-other-repo".to_string()]; 1748 let trigger = w.state.trigger_dir().join(format!("{REPO}.{}", w.head)); 1749 fs::create_dir_all(w.state.trigger_dir()).unwrap(); 1750 fs::write(&trigger, "").unwrap(); 1751 assert_eq!(worker::run_loop(&cfg, Some(1)), 0); 1752 assert!(trigger.exists()); 1753 assert!(!w.bundle_path(&w.head).exists()); 1754 cfg.repos = vec![REPO.to_string()]; 1755 assert_eq!(worker::run_loop(&cfg, Some(1)), 1); 1756 assert!(!trigger.exists()); 1757 assert!(w.bundle_path(&w.head).exists()); 1758 } 1759 1760 #[test] 1761 fn loop_skips_a_head_another_process_is_judging() { 1762 // A head already being judged is not judged again, and its trigger file 1763 // stays for the holder (or the next round) to deal with. 1764 let w = world(); 1765 let cfg = w.config(); 1766 let trigger = w.state.trigger_dir().join(format!("{REPO}.{}", w.head)); 1767 fs::create_dir_all(w.state.trigger_dir()).unwrap(); 1768 fs::write(&trigger, "").unwrap(); 1769 let held = worker::claim_head(&w.state, REPO, &w.head) 1770 .unwrap() 1771 .expect("claim"); 1772 assert_eq!(worker::run_loop(&cfg, Some(1)), 0); 1773 assert!(trigger.exists()); 1774 assert!(!w.bundle_path(&w.head).exists()); 1775 drop(held); 1776 assert_eq!(worker::run_loop(&cfg, Some(1)), 1); 1777 assert!(!trigger.exists()); 1778 } 1779 1780 #[test] 1781 fn worker_once_skips_a_head_another_process_is_judging() { 1782 // `worker --once` for a head a poller holds does nothing and says so. 1783 let bin = env!("CARGO_BIN_EXE_aien-test"); 1784 let t = Tmp::new("once-held"); 1785 let state = StateDir::new(&t.path().join("state")); 1786 let sha = "a".repeat(40); 1787 let held = worker::claim_head(&state, "repo", &sha) 1788 .unwrap() 1789 .expect("claim"); 1790 let o = Command::new(bin) 1791 .args(["worker", "--once", "repo", sha.as_str(), "--state-dir"]) 1792 .arg(&state.root) 1793 .arg("--clones") 1794 .arg(t.path()) 1795 .args(["--sandbox", "none", "--dev-unsandboxed"]) 1796 .output() 1797 .unwrap(); 1798 let out = String::from_utf8_lossy(&o.stdout); 1799 assert_eq!(o.status.code(), Some(75), "{out}"); 1800 assert!( 1801 out.contains(&format!( 1802 "already being judged by pid {}", 1803 std::process::id() 1804 )), 1805 "{out}" 1806 ); 1807 // Nothing was fetched, journaled or run. 1808 assert!(!state.journal().exists()); 1809 drop(held); 1810 }