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/src/runner.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 / src / runner.rs` 3093 lines ยท 120914 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 runner (ADR 0028, Slices A and B): one gate, or a whole graph of gates 17 //! run by worker threads that honour the resource pools and the dependencies. 18 //! 19 //! Order for one gate: parse manifest (BAD_MANIFEST means no receipt), pin the 20 //! commit, record whether the tree is clean, decide refusals, take the GPU 21 //! locks if it is a gb10 gate, run, measure what changed, derive the verdict, 22 //! write blobs and an immutable receipt. 23 //! 24 //! Choices where the ADR is silent (recorded in the PRs): 25 //! - A dirty tree is refused unless the operator passes `--allow-dirty` (the 26 //! manifest grammar has no key for it and P4 forbids adding one here). A 27 //! run allowed this way is recorded with `tree_clean_before = false`. 28 //! - "Tree changed after the run" means `git status --porcelain` differs from 29 //! the pre-run output, so it also catches a run that dirties an already 30 //! allowed-dirty tree further. In a graph run the check is per job and does 31 //! not know which job wrote a file, so when one gate dirties the tree, gates 32 //! that were running at the same moment fail with it. That is the safe side. 33 //! - `pins` is always empty. 34 //! - `gb10_present` is a heuristic: `/dev/nvidiactl` exists (UNVERIFIED). 35 //! - `run GATE` never starts a gate's dependencies. It looks their receipts 36 //! up in the evidence store, for the current commit, and says NOT_RUN if one 37 //! is not a PASS. `run_graph` starts them. 38 39 use crate::cache; 40 use crate::evidence::{build_receipt, canonical_digest, sha256_hex, utc_string, Index, Store}; 41 use crate::graph::Graph; 42 use crate::manifest::{self, Manifest}; 43 use crate::process::{self, RunSpec}; 44 use crate::resources::{ 45 self, acquire_gpu_timed, lock, GpuConfig, GpuGuard, Hardware, Permit, Pool, PoolSizes, Pools, 46 GPU_LOCK_HELD_MARKER, 47 }; 48 use crate::sandbox::{self, Sandbox}; 49 use crate::verdict::{self, campaign_verdict, derive, parse_observations, DepFact, Facts, Verdict}; 50 use serde_json::{json, Map, Value}; 51 use std::collections::{BTreeMap, BTreeSet}; 52 use std::fmt; 53 use std::fs; 54 use std::panic::{catch_unwind, AssertUnwindSafe}; 55 use std::path::{Component, Path, PathBuf}; 56 use std::sync::{Condvar, Mutex}; 57 use std::thread; 58 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; 59 60 pub struct Options { 61 pub evidence_dir: PathBuf, 62 pub allow_dirty: bool, 63 /// `--no-cache`: never reuse an earlier result; every gate runs fresh. 64 pub no_cache: bool, 65 pub args_override: Option>, 66 pub kill_grace: Duration, 67 /// Sizes of the host and qemu pools (the gb10 pool is always 1). 68 pub pool_sizes: PoolSizes, 69 /// Which special hardware this machine has. 70 pub hardware: Hardware, 71 /// Lock files and refusal checks for gb10 gates. 72 pub gpu: GpuConfig, 73 /// `--sandbox none|user` (contract C8). `None` keeps every earlier 74 /// behaviour unchanged. 75 pub sandbox: Sandbox, 76 /// `CARGO_TARGET_DIR` as the runner itself was given it; passed through 77 /// the sandbox as the only environment pair. 78 pub cargo_target_dir: Option, 79 /// Where the per-target-dir lock files live (`resources::target_lock_path`). 80 /// Every gate that runs holds the lock of its target dir (`cargo_target_dir` 81 /// or the worktree's `target/`) for its whole run, so two gates never 82 /// build in one target dir at once. The worker sets `/locks/target`. 83 pub target_lock_dir: PathBuf, 84 /// `--release`: qualification mode. No cache reuse and the tree must be 85 /// clean even with `--allow-dirty`. 86 pub release: bool, 87 /// `core.pins` and part of `cache.key` (ADR 0028: `{name, commit}` sorted 88 /// by `name`). The worker sets the head's sibling and operator pins. 89 pub pins: Value, 90 /// `--operator`: the operator started this run by hand, so a 91 /// `requires: operator` gate runs instead of staying OPERATOR_STEP_PENDING 92 /// (ADR 0033 Decision 2). Never set by the automatic loop. 93 pub operator: bool, 94 /// The cross-head store (`cache::Shared`, `/gate-cache/`). 95 /// None keeps the cache inside `evidence_dir`, as before. The worker sets 96 /// it; a lone `run` does not. 97 pub shared_cache: Option, 98 /// The budget every head of one `worker --batch` shares (host slots, one 99 /// gb10 slot). None outside a batch: only this run's own pools apply. 100 pub batch: Option>, 101 /// Gates other heads of the batch also select: picked before the others 102 /// and ahead of them for the batch budget (shared first, unique after). 103 pub first: BTreeSet, 104 } 105 106 impl Options { 107 /// Options for the real machine: detected pool sizes, hardware and GPU 108 /// paths. Tests overwrite the last three with scratch values. 109 pub fn new(evidence_dir: PathBuf) -> Options { 110 Options { 111 evidence_dir, 112 allow_dirty: false, 113 no_cache: false, 114 args_override: None, 115 kill_grace: Duration::from_secs(10), 116 pool_sizes: PoolSizes::detect(), 117 hardware: Hardware::detect(), 118 gpu: GpuConfig::detect(), 119 sandbox: Sandbox::None, 120 cargo_target_dir: None, 121 target_lock_dir: PathBuf::from(crate::resources::DEFAULT_TARGET_LOCK_DIR), 122 release: false, 123 pins: json!([]), 124 operator: false, 125 shared_cache: None, 126 batch: None, 127 first: BTreeSet::new(), 128 } 129 } 130 } 131 132 #[derive(Debug, Clone, PartialEq, Eq)] 133 pub enum RunError { 134 /// Manifest invalid: no receipt (P8). 135 BadManifest(String), 136 /// Could not bind or write evidence (CR-004 style fatal). 137 Fatal(String), 138 } 139 140 impl fmt::Display for RunError { 141 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 142 match self { 143 RunError::BadManifest(m) => write!(f, "BAD_MANIFEST {m}"), 144 RunError::Fatal(m) => write!(f, "FATAL {m}"), 145 } 146 } 147 } 148 149 #[derive(Debug, Clone)] 150 pub struct Outcome { 151 pub verdict: Verdict, 152 pub reason: String, 153 pub receipt_path: Option, 154 pub receipt_digest: Option, 155 /// What the digest cache did for this gate. 156 pub cache: CacheNote, 157 } 158 159 /// What the cache did, in words the report prints. 160 #[derive(Debug, Clone, PartialEq, Eq)] 161 pub enum CacheNote { 162 /// The result was reused, not rerun. Holds the digest of the fresh 163 /// receipt it was taken from and the commit that receipt was made for 164 /// (another head when it came through the cross-head store). 165 Reused { from: String, commit: String }, 166 /// The cache was consulted and had nothing usable; the gate ran. 167 Miss(String), 168 /// The cache was not consulted; the gate ran (or was refused). Holds why. 169 Skipped(String), 170 } 171 172 /// The exec helper refused the call: exit 2 and stderr starting with its 173 /// `aien-run-exec:` prefix (INFRA C8). Only under `Sandbox::User`. 174 pub fn sandbox_refused(sandbox: Sandbox, exit: Option, stderr: &[u8]) -> bool { 175 sandbox == Sandbox::User && exit == Some(2) && stderr.starts_with(b"aien-run-exec:") 176 } 177 178 fn git_out(root: &Path, args: &[&str]) -> Result { 179 // Several jobs may ask for the status at once; the status command must 180 // not take the index lock (and fail the other caller) to refresh it. 181 let mut cmd = process::git_command(); 182 cmd.env("GIT_OPTIONAL_LOCKS", "0") 183 .arg("-C") 184 .arg(root) 185 .args(args); 186 // The spawn goes through the spawn gate (see `process::SPAWN_GATE`) so a 187 // git child never holds a GPU lock descriptor past the lock's release. 188 let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run git: {e}"))?; 189 if !out.status.success() { 190 return Err(format!( 191 "git {:?} failed: {}", 192 args, 193 String::from_utf8_lossy(&out.stderr).trim() 194 )); 195 } 196 Ok(String::from_utf8_lossy(&out.stdout).into_owned()) 197 } 198 199 pub fn repo_root(dir: &Path) -> Result { 200 let s = git_out(dir, &["rev-parse", "--show-toplevel"])?; 201 Ok(PathBuf::from(s.trim())) 202 } 203 204 /// The full commit id of HEAD (40 lower-case hex digits). 205 pub fn head(root: &Path) -> Result { 206 let s = git_out(root, &["rev-parse", "HEAD"])?.trim().to_string(); 207 if s.len() == 40 208 && s.chars() 209 .all(|c| c.is_ascii_digit() || ('a'..='f').contains(&c)) 210 { 211 Ok(s) 212 } else { 213 Err(format!("HEAD is not a 40-hex commit: {s:?}")) 214 } 215 } 216 217 /// The tree id of HEAD: equal for two commits whose every file is identical. 218 pub fn head_tree(root: &Path) -> Result { 219 let s = git_out(root, &["rev-parse", "HEAD^{tree}"])? 220 .trim() 221 .to_string(); 222 if s.len() == 40 && s.bytes().all(|c| c.is_ascii_hexdigit()) { 223 Ok(s) 224 } else { 225 Err(format!("HEAD^{{tree}} is not a 40-hex id: {s:?}")) 226 } 227 } 228 229 /// The cache pins of a direct run (`aien-test run`, `test`, `plan`, `why` 230 /// from a checkout). Its evidence store is one per repository 231 /// (`default_evidence_dir`), shared by every commit, and a gate may read 232 /// files it does not declare (SC-TEST reads the root README.md). So the 233 /// checkout's tree is part of every key: a receipt is reused only by a head 234 /// whose files are all identical, a re-push or a squash merge of an 235 /// up-to-date PR (#517). The worker keeps evidence per head and sets its own 236 /// pins; reuse by declared inputs alone is its cross-head store's job 237 /// (`cache::cross_head`). 238 pub fn direct_pins(root: &Path) -> Result { 239 Ok(json!([{ "name": "head-tree", "tree": head_tree(root)? }])) 240 } 241 242 fn porcelain(root: &Path) -> Result { 243 git_out(root, &["status", "--porcelain"]) 244 } 245 246 /// Where receipts go when `--evidence-dir` is not given: 247 /// `$HOME/workspace/evidence-out/`. 248 pub fn default_evidence_dir(root: &Path) -> Option { 249 let home = std::env::var_os("HOME")?; 250 let name = root 251 .file_name() 252 .map(|n| n.to_string_lossy().into_owned()) 253 .unwrap_or_else(|| "repo".to_string()); 254 Some( 255 PathBuf::from(home) 256 .join("workspace") 257 .join("evidence-out") 258 .join(name), 259 ) 260 } 261 262 /// Absolute, lexically normalized path whose deepest existing ancestor is 263 /// canonicalized, so a not-yet-created evidence dir can still be compared. 264 fn resolve(p: &Path) -> PathBuf { 265 let abs = if p.is_absolute() { 266 p.to_path_buf() 267 } else { 268 std::env::current_dir().unwrap_or_default().join(p) 269 }; 270 let mut norm = PathBuf::new(); 271 for c in abs.components() { 272 match c { 273 Component::ParentDir => { 274 norm.pop(); 275 } 276 Component::CurDir => {} 277 other => norm.push(other.as_os_str()), 278 } 279 } 280 let mut existing = norm.clone(); 281 let mut tail = Vec::new(); 282 while !existing.exists() { 283 match existing.file_name().map(|s| s.to_os_string()) { 284 Some(n) => { 285 tail.push(n); 286 existing.pop(); 287 } 288 None => break, 289 } 290 } 291 let mut base = fs::canonicalize(&existing).unwrap_or(existing); 292 for n in tail.iter().rev() { 293 base.push(n); 294 } 295 base 296 } 297 298 const SKIP_DIRS: [&str; 5] = [".git", "target", "build", "vendor", "node_modules"]; 299 300 /// D1: every `*.gate` file under `root`, skipping the usual build dirs and any 301 /// directory holding `.aien-test-ignore`. Sorted. 302 pub fn discover(root: &Path) -> Vec { 303 fn walk(dir: &Path, out: &mut Vec) { 304 if dir.join(".aien-test-ignore").exists() { 305 return; 306 } 307 let rd = match fs::read_dir(dir) { 308 Ok(r) => r, 309 Err(_) => return, 310 }; 311 for e in rd.flatten() { 312 let path = e.path(); 313 let ft = match e.file_type() { 314 Ok(t) => t, 315 Err(_) => continue, 316 }; 317 let name = e.file_name().to_string_lossy().into_owned(); 318 if ft.is_dir() { 319 if !SKIP_DIRS.contains(&name.as_str()) { 320 walk(&path, out); 321 } 322 } else if ft.is_file() && name.ends_with(".gate") { 323 out.push(path); 324 } 325 } 326 } 327 let mut out = Vec::new(); 328 walk(root, &mut out); 329 out.sort(); 330 out 331 } 332 333 /// Resolve `GATE_FILE_OR_NAME`: an existing file path, else the unique 334 /// `.gate` file under the repository whose `gate:` equals the name (D2). 335 pub fn locate_gate(cwd: &Path, name: &str) -> Result { 336 let p = Path::new(name); 337 let direct = if p.is_absolute() { 338 p.to_path_buf() 339 } else { 340 cwd.join(p) 341 }; 342 if direct.is_file() { 343 return fs::canonicalize(&direct).map_err(|e| format!("cannot resolve {name}: {e}")); 344 } 345 let root = repo_root(cwd)?; 346 let mut found: Vec = Vec::new(); 347 let mut unparsable = 0; 348 for path in discover(&root) { 349 match fs::read(&path) { 350 Ok(bytes) => match manifest::parse(&bytes) { 351 Ok(m) if m.gate == name => found.push(path), 352 Ok(_) => {} 353 Err(_) => unparsable += 1, 354 }, 355 Err(_) => unparsable += 1, 356 } 357 } 358 match found.len() { 359 1 => Ok(found.remove(0)), 360 0 => Err(format!( 361 "no gate named {name} ({unparsable} unparsable gate files skipped)" 362 )), 363 _ => Err(format!( 364 "duplicate gate id {name} in: {}", 365 found 366 .iter() 367 .map(|f| f.display().to_string()) 368 .collect::>() 369 .join(", ") 370 )), 371 } 372 } 373 374 fn collect_files(root: &Path, rel: &str, out: &mut BTreeSet) { 375 // A component with `*` (`crates/*/Cargo.toml`) stands for every entry of 376 // its directory whose name matches; `*` matches any run of characters. 377 let parts: Vec<&str> = rel.trim_end_matches('/').split('/').collect(); 378 if let Some(i) = parts.iter().position(|c| c.contains('*')) { 379 let base = parts[..i].join("/"); 380 let rest = parts[i + 1..].join("/"); 381 let mut names: Vec = fs::read_dir(root.join(&base)) 382 .map(|rd| { 383 rd.flatten() 384 .map(|e| e.file_name().to_string_lossy().into_owned()) 385 .filter(|n| n != ".git" && wildcard_match(parts[i], n)) 386 .collect() 387 }) 388 .unwrap_or_default(); 389 names.sort(); 390 for n in names { 391 let mut child = if base.is_empty() { 392 n 393 } else { 394 format!("{base}/{n}") 395 }; 396 if !rest.is_empty() { 397 child = format!("{child}/{rest}"); 398 } 399 collect_files(root, &child, out); 400 } 401 return; 402 } 403 let path = root.join(rel.trim_end_matches('/')); 404 let md = match fs::symlink_metadata(&path) { 405 Ok(m) => m, 406 Err(_) => { 407 out.insert(rel.trim_end_matches('/').to_string()); 408 return; 409 } 410 }; 411 if md.is_dir() { 412 if let Ok(rd) = fs::read_dir(&path) { 413 for e in rd.flatten() { 414 let name = e.file_name().to_string_lossy().into_owned(); 415 if name == ".git" { 416 continue; 417 } 418 let child = format!("{}/{}", rel.trim_end_matches('/'), name); 419 collect_files(root, &child, out); 420 } 421 } 422 } else if md.is_file() { 423 out.insert(rel.trim_end_matches('/').to_string()); 424 } 425 } 426 427 /// The existing directories a `listed` entry names (`*` per component). 428 fn expand_dirs(root: &Path, pat: &str, out: &mut BTreeSet) { 429 let mut cur: Vec = vec![String::new()]; 430 for c in pat.trim_end_matches('/').split('/') { 431 let mut next = Vec::new(); 432 for base in &cur { 433 let join = |n: &str| { 434 if base.is_empty() { 435 n.to_string() 436 } else { 437 format!("{base}/{n}") 438 } 439 }; 440 if c.contains('*') { 441 if let Ok(rd) = fs::read_dir(root.join(base)) { 442 for e in rd.flatten() { 443 let n = e.file_name().to_string_lossy().into_owned(); 444 if n != ".git" && wildcard_match(c, &n) && e.path().is_dir() { 445 next.push(join(&n)); 446 } 447 } 448 } 449 } else if root.join(join(c)).is_dir() { 450 next.push(join(c)); 451 } 452 } 453 cur = next; 454 } 455 out.extend(cur.into_iter().filter(|d| !d.is_empty())); 456 } 457 458 /// `pat` against `name`, where `*` matches any run of characters (none too). 459 pub(crate) fn wildcard_match(pat: &str, name: &str) -> bool { 460 let pieces: Vec<&str> = pat.split('*').collect(); 461 if pieces.len() == 1 { 462 return pat == name; 463 } 464 let (first, last) = (pieces[0], pieces[pieces.len() - 1]); 465 if !name.starts_with(first) || name.len() < first.len() + last.len() || !name.ends_with(last) { 466 return false; 467 } 468 let mut rest = &name[first.len()..name.len() - last.len()]; 469 for p in &pieces[1..pieces.len() - 1] { 470 match rest.find(p) { 471 Some(at) => rest = &rest[at + p.len()..], 472 None => return false, 473 } 474 } 475 true 476 } 477 478 /// `~/REST` against the judge's `HOME`; an absolute path as it is. 479 pub(crate) fn outside_path(entry: &str) -> PathBuf { 480 match entry.strip_prefix("~/") { 481 Some(rest) => std::env::var_os("HOME") 482 .map(PathBuf::from) 483 .unwrap_or_default() 484 .join(rest), 485 None => PathBuf::from(entry), 486 } 487 } 488 489 /// `(name, sha256)` of every file under one `outside_inputs` entry, named by 490 /// the entry as written (`~/models/X/model.safetensors`), so the key does not 491 /// depend on whose home it is. A missing entry is one row with a null digest. 492 /// Digests are remembered per (path, size, mtime, inode) for the life of the 493 /// process: a checkpoint of gigabytes is read once per judge, not per gate. 494 fn outside_rows(entry: &str) -> Vec<(String, Option)> { 495 use std::os::unix::fs::MetadataExt; 496 type Memo = BTreeMap<(PathBuf, u64, i64, i64, u64), String>; 497 static MEMO: std::sync::OnceLock> = std::sync::OnceLock::new(); 498 let shown = entry.trim_end_matches('/').to_string(); 499 let base = outside_path(&shown); 500 let mut walk = vec![(base.clone(), shown.clone())]; 501 let mut rows = Vec::new(); 502 while let Some((p, name)) = walk.pop() { 503 match fs::metadata(&p) { 504 Ok(md) if md.is_dir() => { 505 if let Ok(rd) = fs::read_dir(&p) { 506 for e in rd.flatten() { 507 let n = e.file_name().to_string_lossy().into_owned(); 508 walk.push((e.path(), format!("{name}/{n}"))); 509 } 510 } 511 } 512 Ok(md) if md.is_file() => { 513 let k = (p.clone(), md.len(), md.mtime(), md.mtime_nsec(), md.ino()); 514 let memo = MEMO.get_or_init(|| Mutex::new(BTreeMap::new())); 515 let hit = memo.lock().ok().and_then(|m| m.get(&k).cloned()); 516 let digest = hit.or_else(|| { 517 let d = sha256_file(&p)?; 518 if let Ok(mut m) = memo.lock() { 519 m.insert(k, d.clone()); 520 } 521 Some(d) 522 }); 523 rows.push((name, digest)); 524 } 525 _ => rows.push((name, None)), 526 } 527 } 528 rows.sort(); 529 rows 530 } 531 532 /// sha256 of a file, streamed (a checkpoint does not fit the 16 KiB budget 533 /// of anything else here, and need not sit in memory). 534 fn sha256_file(p: &Path) -> Option { 535 use sha2::{Digest, Sha256}; 536 use std::io::Read; 537 let mut f = fs::File::open(p).ok()?; 538 let mut h = Sha256::new(); 539 let mut buf = vec![0u8; 1 << 20]; 540 loop { 541 let n = f.read(&mut buf).ok()?; 542 if n == 0 { 543 break; 544 } 545 h.update(&buf[..n]); 546 } 547 Some(format!("{:x}", h.finalize())) 548 } 549 550 /// Where `run.exec` is, for a run without the sandbox (the runner's PATH). 551 /// See [`exec_path_for`]. 552 pub fn exec_path(root: &Path, exec: &str) -> Option { 553 exec_path_in(root, exec, std::env::var_os("PATH")) 554 } 555 556 /// Where `run.exec` is for a run under `sandbox`. A name with a slash is 557 /// repo-relative (the manifest already refuses absolute paths and `..`) and 558 /// must still be inside the repository after symlinks are followed. A bare 559 /// name is a program on the PATH, so a shared gate can say `exec: crumb`: 560 /// the runner's PATH without the sandbox, the exec helper's trusted PATH 561 /// ([`sandbox::TRUSTED_PATH`]) under `--sandbox user`, so the program hashed 562 /// into the receipt is the program that runs. None when it is not there. 563 pub fn exec_path_for(root: &Path, exec: &str, sandbox: Sandbox) -> Option { 564 match sandbox { 565 Sandbox::None => exec_path(root, exec), 566 Sandbox::User => exec_path_in(root, exec, Some(sandbox::TRUSTED_PATH.into())), 567 } 568 } 569 570 fn exec_path_in(root: &Path, exec: &str, path: Option) -> Option { 571 if exec.contains('/') { 572 let p = root.join(exec); 573 if !p.is_file() { 574 return None; 575 } 576 // A symlink in the tree must not lead out of it. 577 let inside = match (p.canonicalize(), root.canonicalize()) { 578 (Ok(cp), Ok(cr)) => cp.starts_with(cr), 579 _ => false, 580 }; 581 return inside.then_some(p); 582 } 583 let path = path?; 584 std::env::split_paths(&path) 585 .filter(|d| !d.as_os_str().is_empty()) 586 .map(|d| d.join(exec)) 587 .find(|p| p.is_file()) 588 } 589 590 /// sha256 over the canonical list of (path, file sha256) for the explicit 591 /// `inputs`, the D3 convention-implied inputs of `tests//.gate` and 592 /// the repository build files in [`IMPLIED_BUILD_FILES`] that exist. 593 /// A listed path that does not exist is recorded with a null digest. Compiler 594 /// identity is not included yet because nothing here builds. 595 pub fn build_inputs_digest(root: &Path, manifest_rel: Option<&Path>, m: &Manifest) -> String { 596 let mut paths: BTreeSet = BTreeSet::new(); 597 for i in &m.inputs { 598 collect_files(root, i, &mut paths); 599 } 600 for f in IMPLIED_BUILD_FILES { 601 if root.join(f).is_file() { 602 paths.insert(f.to_string()); 603 } 604 } 605 if let Some(rel) = manifest_rel { 606 let dir = rel.parent().unwrap_or(Path::new("")); 607 let stem = rel 608 .file_stem() 609 .map(|s| s.to_string_lossy().into_owned()) 610 .unwrap_or_default(); 611 if let Ok(sub) = dir.strip_prefix("tests") { 612 let sub = sub.to_string_lossy().into_owned(); 613 let join = |base: &str| { 614 if sub.is_empty() { 615 base.to_string() 616 } else { 617 format!("{base}/{sub}") 618 } 619 }; 620 for (base, want) in [ 621 (join("src"), stem.clone()), 622 (join("tests"), format!("{stem}_test")), 623 ] { 624 if let Ok(rd) = fs::read_dir(root.join(&base)) { 625 for e in rd.flatten() { 626 let p = e.path(); 627 let fstem = p 628 .file_stem() 629 .map(|s| s.to_string_lossy().into_owned()) 630 .unwrap_or_default(); 631 if p.is_file() && fstem == want { 632 paths.insert(format!("{base}/{}", e.file_name().to_string_lossy())); 633 } 634 } 635 } 636 } 637 } 638 } 639 let entries: Vec = paths 640 .iter() 641 .map(|p| { 642 let digest = fs::read(root.join(p)).ok().map(|b| sha256_hex(&b)); 643 json!({ "path": p, "sha256": digest }) 644 }) 645 .collect(); 646 // Outside inputs and listings join under their own members, so a 647 // manifest without them keeps the digest it always had. 648 let mut obj = json!({ "inputs": entries }); 649 if !m.outside_inputs.is_empty() { 650 let outside: Vec = m 651 .outside_inputs 652 .iter() 653 .flat_map(|o| outside_rows(o)) 654 .map(|(p, d)| json!({ "path": p, "sha256": d })) 655 .collect(); 656 obj["outside_inputs"] = json!(outside); 657 } 658 if !m.listed.is_empty() { 659 let mut dirs: BTreeSet = BTreeSet::new(); 660 for l in &m.listed { 661 expand_dirs(root, l, &mut dirs); 662 } 663 let rows: Vec = dirs 664 .iter() 665 .map(|d| { 666 let mut names: Vec = fs::read_dir(root.join(d)) 667 .map(|rd| { 668 rd.flatten() 669 .map(|e| e.file_name().to_string_lossy().into_owned()) 670 .filter(|n| n != ".git") 671 .collect() 672 }) 673 .unwrap_or_default(); 674 names.sort(); 675 json!({ "dir": d, "names": names }) 676 }) 677 .collect(); 678 obj["listed"] = json!(rows); 679 } 680 canonical_digest(&obj).unwrap_or_default() 681 } 682 683 /// sha256 of the running aien-test binary, read once. None when the binary 684 /// cannot be read (then no result made under None matches one made under a 685 /// readable binary). 686 pub fn judge_sha256() -> Option { 687 static SHA: std::sync::OnceLock> = std::sync::OnceLock::new(); 688 SHA.get_or_init(|| { 689 std::env::current_exe() 690 .and_then(fs::read) 691 .ok() 692 .map(|b| sha256_hex(&b)) 693 }) 694 .clone() 695 } 696 697 /// Repository build files that change what any gate builds or runs even when 698 /// its manifest does not list them (the workspace manifest and lock, the 699 /// toolchain pin, cargo's config). Each one that exists joins every gate's 700 /// `build_inputs_digest`: a gate like SC-INQUISITOR builds with cargo and 701 /// lists no Cargo.toml. Adding a file to the key can only turn a hit into a 702 /// miss, never the other way. 703 pub const IMPLIED_BUILD_FILES: [&str; 8] = [ 704 "Cargo.toml", 705 "Cargo.lock", 706 "rust-toolchain", 707 "rust-toolchain.toml", 708 ".cargo/config", 709 ".cargo/config.toml", 710 "native-artifacts.lock", 711 "mojoproject.toml", 712 ]; 713 714 pub(crate) fn machine(hw: &Hardware) -> Value { 715 let kernel = fs::read_to_string("/proc/sys/kernel/osrelease") 716 .map(|s| s.trim().to_string()) 717 .unwrap_or_default(); 718 let cpuinfo = fs::read_to_string("/proc/cpuinfo").unwrap_or_default(); 719 let cpu_model = cpuinfo 720 .lines() 721 .find(|l| l.starts_with("model name")) 722 .and_then(|l| l.split_once(':')) 723 .map(|p| p.1.trim().to_string()) 724 .unwrap_or_default(); 725 let cpus = std::thread::available_parallelism() 726 .map(|n| n.get() as u64) 727 .unwrap_or(0); 728 let meminfo = fs::read_to_string("/proc/meminfo").unwrap_or_default(); 729 let mem_kib = meminfo 730 .lines() 731 .find(|l| l.starts_with("MemTotal:")) 732 .and_then(|l| l.split_whitespace().nth(1)) 733 .and_then(|v| v.parse::().ok()) 734 .unwrap_or(0); 735 json!({ 736 "arch": std::env::consts::ARCH, 737 "kernel_release": kernel, 738 "cpu_model": cpu_model, 739 "cpu_count": cpus, 740 "mem_total_kib": mem_kib, 741 "gb10_present": hw.gb10_present, 742 "qemu_available": hw.qemu_available, 743 }) 744 } 745 746 pub(crate) fn captured_env() -> Value { 747 let mut m = Map::new(); 748 for k in [ 749 "AIEN_PROOF_OFF", 750 "CC", 751 "CFLAGS", 752 "CHIPRUN_SELFTEST", 753 "LANG", 754 "LC_ALL", 755 "RUSTFLAGS", 756 "TZ", 757 ] { 758 if let Ok(v) = std::env::var(k) { 759 m.insert(k.to_string(), Value::String(v)); 760 } 761 } 762 Value::Object(m) 763 } 764 765 /// Whether the working tree has uncommitted changes (including untracked 766 /// files). 767 pub(crate) fn working_tree_dirty(root: &Path) -> Result { 768 porcelain(root).map(|p| !p.is_empty()) 769 } 770 771 /// The digests that identify one experiment besides its manifest and 772 /// dependencies: the program, the declared inputs, the machine. 773 pub(crate) struct Identity { 774 pub binary_sha: Option, 775 pub inputs_digest: String, 776 pub machine: Value, 777 pub machine_digest: String, 778 } 779 780 pub(crate) fn identity( 781 root: &Path, 782 manifest_path: &Path, 783 m: &Manifest, 784 hw: &Hardware, 785 sandbox: Sandbox, 786 ) -> Result { 787 let binary_sha = exec_path_for(root, &m.exec, sandbox) 788 .and_then(|p| fs::read(p).ok()) 789 .map(|b| sha256_hex(&b)); 790 let manifest_rel = manifest_path.strip_prefix(root).ok(); 791 let mut machine = machine(hw); 792 // Under the user sandbox the exec helper is part of the machine a gate 793 // ran on (network, mounts, limits): a result made under another helper 794 // is not reused (SANDBOX lane: a FAIL made while the sandbox had no 795 // loopback was reused after loopback came up). 796 if sandbox == Sandbox::User { 797 machine["sandbox_helper_sha256"] = 798 json!(fs::read(sandbox::EXEC_HELPER).ok().map(|b| sha256_hex(&b))); 799 } 800 // The judge that derives the verdict is part of the machine too: a result 801 // made by another build of aien-test is never reused, inside one head or 802 // across heads (a new rule in the verdict, a new receipt member). 803 machine["judge_sha256"] = json!(judge_sha256()); 804 let machine_digest = canonical_digest(&machine)?; 805 Ok(Identity { 806 binary_sha, 807 inputs_digest: build_inputs_digest(root, manifest_rel, m), 808 machine, 809 machine_digest, 810 }) 811 } 812 fn now_secs() -> u64 { 813 SystemTime::now() 814 .duration_since(UNIX_EPOCH) 815 .map(|d| d.as_secs()) 816 .unwrap_or(0) 817 } 818 819 fn fatal(e: E) -> RunError { 820 RunError::Fatal(e.to_string()) 821 } 822 823 /// `core.dependencies`: gate to receipt digest, sorted by gate, only for the 824 /// dependencies that have a receipt for this commit. 825 fn dependency_rows(deps: &[DepFact]) -> BTreeMap { 826 deps.iter() 827 .filter_map(|d| d.receipt.as_ref().map(|r| (d.gate.clone(), r.clone()))) 828 .collect() 829 } 830 831 /// Everything `execute_gate` needs besides the permit. 832 struct Job<'a> { 833 root: &'a Path, 834 manifest_path: &'a Path, 835 m: &'a Manifest, 836 opts: &'a Options, 837 /// What is known about each `depends_on` gate right now. 838 deps: Vec, 839 /// How long the job waited for a pool slot. 840 pool_wait_ms: u64, 841 } 842 843 /// Run one gate that has been parsed already. `permit` is the pool slot the 844 /// job holds (None for a lone `run`, and for gates that cannot run anyway); it 845 /// is released as soon as the job ends. 846 fn execute_gate(job: &Job<'_>, permit: Option>) -> Result { 847 let (root, m, opts) = (job.root, job.m, job.opts); 848 let started = now_secs(); 849 let t0 = Instant::now(); 850 851 let commit = head(root).map_err(RunError::Fatal)?; 852 let before = porcelain(root).map_err(RunError::Fatal)?; 853 let evidence_inside = resolve(&opts.evidence_dir).starts_with(resolve(root)); 854 let refusal: Option = if evidence_inside { 855 Some("evidence_inside".to_string()) 856 } else if !before.is_empty() && (!opts.allow_dirty || opts.release) { 857 Some("dirty_tree".to_string()) 858 } else { 859 None 860 }; 861 862 // Resolved where it will run: a bare name under the user sandbox on the 863 // helper's trusted PATH. The full path is what runs and what is hashed. 864 let resolved = exec_path_for(root, &m.exec, opts.sandbox); 865 let exec_exists = resolved.is_some(); 866 let exec_path = resolved.unwrap_or_else(|| root.join(&m.exec)); 867 let mut facts = Facts { 868 refusal, 869 exec_exists, 870 deps: job.deps.clone(), 871 gb10_present: opts.hardware.gb10_present, 872 qemu_available: opts.hardware.qemu_available, 873 operator: opts.operator, 874 ..Facts::default() 875 }; 876 877 // Identify the experiment before anything runs, so the cache lookup and 878 // the receipt agree on what was hashed (ADR Decision 7). 879 let id = identity(root, job.manifest_path, m, &opts.hardware, opts.sandbox).map_err(fatal)?; 880 let store = Store::new(&opts.evidence_dir); 881 let tree_clean = before.is_empty(); 882 let mut mode = cache::policy(m.cache_allowed, opts.no_cache || opts.release); 883 let off_reason: &str = if opts.release { 884 "--release" 885 } else if opts.no_cache { 886 "--no-cache" 887 } else if opts.args_override.is_some() { 888 "replacement arguments were given after --" 889 } else { 890 "the tree has uncommitted changes" 891 }; 892 if mode == cache::Mode::Allow && (opts.args_override.is_some() || !tree_clean) { 893 mode = cache::Mode::Disabled; 894 } 895 let dependencies: Vec<(String, String)> = dependency_rows(&facts.deps).into_iter().collect(); 896 // Receipts are read when a lookup may happen, and to follow a reused 897 // dependency back to the receipt it stands for. 898 let mut index = if mode == cache::Mode::Allow || !dependencies.is_empty() { 899 Index::load(&store) 900 } else { 901 Index::default() 902 }; 903 // The cross-head store, only for a gate whose result may leave this head 904 // (`cache::cross_head`); every other gate keeps its cache inside this 905 // head. The reach decides the entry name: the key, or the key and the 906 // tree id when the manifest does not promise complete inputs. 907 let reach = cache::cross_head(m).ok(); 908 let shared: Option<(&cache::Shared, cache::Reach)> = match (opts.shared_cache.as_ref(), reach) { 909 (Some(sh), Some(r)) => Some((sh, r)), 910 _ => None, 911 }; 912 let experiment = cache::Experiment { 913 manifest_digest: m.digest.clone(), 914 binary_sha256: id.binary_sha.clone(), 915 build_inputs_digest: id.inputs_digest.clone(), 916 machine_digest: id.machine_digest.clone(), 917 dependencies, 918 pins: opts.pins.clone(), 919 args_override: opts.args_override.clone(), 920 }; 921 let cache_key = cache::key(&experiment, &index).map_err(fatal)?; 922 let mut note = match mode { 923 cache::Mode::Never => CacheNote::Skipped("the manifest says cache: never".to_string()), 924 cache::Mode::Disabled => CacheNote::Skipped(off_reason.to_string()), 925 cache::Mode::Allow => { 926 CacheNote::Skipped("the gate cannot run now, so there was nothing to reuse".to_string()) 927 } 928 }; 929 // Reuse only when the gate would really have run: a refusal, a blocked 930 // verdict or a dependency that is not PASS is reported as it is, never 931 // hidden behind an old result. 932 // Held from the shared lookup until this head's result is published, so 933 // another judge of the same key waits for it instead of running it too. 934 let mut key_lock: Option = None; 935 let mut shared_note: Option = None; 936 let mut shared_slot: Option = None; 937 if mode == cache::Mode::Allow && !evidence_inside && verdict::pre_run(m, &facts).is_none() { 938 let env = captured_env(); 939 let local_hit = matches!( 940 cache::lookup(&index, &store, &cache_key, &env), 941 cache::Lookup::Hit(_) 942 ); 943 if let (false, Some((sh, reach))) = (local_hit, shared) { 944 // The shared store is an extra: if the tree id or the entry lock 945 // cannot be had, this head decides alone, as before. 946 let named = head_tree(root) 947 .map(|tree| cache::slot(&cache_key, reach, &tree)) 948 .and_then(|name| match sh.lock(&name) { 949 Ok(l) => Ok((name, l)), 950 Err(e) => Err(format!("cannot lock the entry: {e}")), 951 }); 952 match named { 953 Err(e) => shared_note = Some(format!("the cross-head store was not used ({e})")), 954 Ok((name, l)) => { 955 key_lock = Some(l); 956 match sh.import(&name, &cache_key, &store) { 957 Ok(Some(_)) => index = Index::load(&store), 958 Ok(None) => { 959 shared_note = Some(match reach { 960 cache::Reach::Inputs => "no other head has this key yet".to_string(), 961 cache::Reach::Tree => "no other head with this exact tree has this key yet (the manifest does not say cache: inputs_complete)".to_string(), 962 }) 963 } 964 Err(e) => { 965 shared_note = Some(format!("the cross-head entry could not be read ({e})")) 966 } 967 } 968 shared_slot = Some(name); 969 } 970 } 971 } 972 match cache::lookup(&index, &store, &cache_key, &env) { 973 cache::Lookup::Hit(src) => { 974 let reused_verdict = src 975 .verdict() 976 .ok_or_else(|| fatal("a reusable receipt has no verdict"))?; 977 let volatile = json!({ 978 "started_utc": utc_string(started), 979 "finished_utc": utc_string(now_secs()), 980 "duration_ms": t0.elapsed().as_millis() as u64, 981 "pool": m.pool(), 982 "pool_wait_ms": job.pool_wait_ms, 983 "runner": { "name": "aien-test", "version": env!("CARGO_PKG_VERSION"), "impl": "rust" }, 984 "cache": cache::cache_member(&cache_key, Some(&src.digest), mode), 985 "timeout_exceeded": false, 986 }); 987 let mut volatile = volatile; 988 // Which head the result was made for: this one, or another 989 // head whose result came through the cross-head store. 990 volatile["cache"]["reused_from_commit"] = json!(src.commit()); 991 let receipt = build_receipt(cache::reused_core(src, &commit), volatile); 992 let (digest, path) = store.put_receipt(&receipt).map_err(fatal)?; 993 drop(permit); 994 return Ok(Outcome { 995 verdict: reused_verdict, 996 reason: src.reason().to_string(), 997 receipt_path: Some(path), 998 receipt_digest: Some(digest), 999 cache: CacheNote::Reused { 1000 from: src.digest.clone(), 1001 commit: src.commit().to_string(), 1002 }, 1003 }); 1004 } 1005 cache::Lookup::Miss(miss) => { 1006 note = CacheNote::Miss(match &shared_note { 1007 Some(s) => format!("{}; across heads: {s}", miss.text()), 1008 None => miss.text(), 1009 }) 1010 } 1011 } 1012 } 1013 1014 // In a batch, a host gate that will really run takes one slot of the 1015 // batch budget (shared gates ahead of the rest), and a gb10 gate takes 1016 // the batch's one gb10 slot, so heads of the batch never compete for 1017 // `/tmp/aien-gb10.lock` and spend their bounded wait on each other. A 1018 // reused result above never got here, so it costs no slot. 1019 // Both waits below are timed and go into the receipt on their own 1020 // (`batch_wait_ms`, `target_wait_ms`): `duration_ms` starts at `t0`, so 1021 // without them a gate queued behind another head reads as a slow gate. 1022 let runs = verdict::pre_run(m, &facts).is_none(); 1023 let t_batch = Instant::now(); 1024 let _batch_slot = match (&opts.batch, m.pool(), runs) { 1025 (Some(b), "host", true) => Some(b.host.acquire(opts.first.contains(&m.gate))), 1026 (Some(b), "gb10", true) => Some(b.gb10.acquire(true)), 1027 _ => None, 1028 }; 1029 let batch_wait_ms = t_batch.elapsed().as_millis() as u64; 1030 let t_target = Instant::now(); 1031 // A gate that will run holds its target dir for the whole run (build and 1032 // run), so no other gate builds in it or relinks a binary this one is 1033 // executing (sc fix/521). Every gate, not only those whose manifest 1034 // names cargo inputs: SC-INQUISITOR builds with cargo and lists no 1035 // Cargo.toml, and the runner cannot see inside a script. The dir is the 1036 // `CARGO_TARGET_DIR` the gate is given, or else the worktree's own 1037 // `target/`, which cargo uses by default. Taken after the pool slot and 1038 // before the GPU locks: the fixed order in `resources`. Waited for, 1039 // never refused: the holder is another gate or the worker's priming. 1040 // A gb10 gate is never killed on timeout (ADR 0028 Decision 6), so one 1041 // that hangs holds the target dir until it exits; the receipt's 1042 // `timeout_exceeded` is the only sign. 1043 // `target_lock: none` (a grep, a find, `crumb verify`) skips it: such a gate 1044 // queued behind the head's cargo gates for up to the head's whole wall 1045 // (L335, finding G3-ci-judge-2); `aien-test audit-inputs` refuses the 1046 // promise when the traced run starts cargo or rustc. 1047 let target_lock: Option = 1048 if m.target_lock && verdict::pre_run(m, &facts).is_none() { 1049 let dir = opts 1050 .cargo_target_dir 1051 .clone() 1052 .unwrap_or_else(|| resolve(root).join("target")); 1053 let path = resources::target_lock_path(&opts.target_lock_dir, &dir); 1054 Some(resources::lock_target_dir(&path).map_err(|e| { 1055 RunError::Fatal(format!("cannot lock target dir {}: {e}", path.display())) 1056 })?) 1057 } else { 1058 None 1059 }; 1060 let target_wait_ms = t_target.elapsed().as_millis() as u64; 1061 1062 // The manifest's `prepare` step (a build, say) runs before the GPU locks, 1063 // under the host profile with its timeout enforced, so a gb10 gate never 1064 // holds the chip while it compiles. It holds the pool slot and the target 1065 // dir like the run does. A failure fails the gate and nothing else runs. 1066 let mut prepare_note = Value::Null; 1067 let mut prepare_out: Option<(Option, Vec, Vec)> = None; 1068 if let Some(p) = m 1069 .prepare 1070 .as_ref() 1071 .filter(|_| verdict::pre_run(m, &facts).is_none()) 1072 { 1073 let tp = Instant::now(); 1074 let direct = RunSpec { 1075 program: exec_path_for(root, &p.exec, opts.sandbox) 1076 .unwrap_or_else(|| root.join(&p.exec)), 1077 args: p.args.clone(), 1078 cwd: root.to_path_buf(), 1079 timeout: Duration::from_millis(m.timeout_ms), 1080 kill_grace: opts.kill_grace, 1081 enforce_timeout: true, 1082 env: Vec::new(), 1083 env_remove: vec![GPU_LOCK_HELD_MARKER.to_string()], 1084 }; 1085 let spec = sandbox::wrap( 1086 opts.sandbox, 1087 direct, 1088 "host", 1089 &sandbox::env_pairs(opts.cargo_target_dir.as_deref()), 1090 ); 1091 let (code, timed_out, out, err) = match process::run(&spec) { 1092 Ok(o) => { 1093 let code = o.exit_code.map(i64::from); 1094 let code = if sandbox_refused(opts.sandbox, o.exit_code, &o.stderr) { 1095 None 1096 } else { 1097 code 1098 }; 1099 (code, o.timed_out, o.stdout, o.stderr) 1100 } 1101 Err(e) => ( 1102 None, 1103 false, 1104 Vec::new(), 1105 format!("aien-test: cannot run prepare {}: {e}\n", p.exec).into_bytes(), 1106 ), 1107 }; 1108 facts.prepare_failed = code != Some(0) || timed_out; 1109 prepare_note = json!({ 1110 "duration_ms": tp.elapsed().as_millis() as u64, 1111 "exit_status": code, 1112 "timed_out": timed_out, 1113 "stdout_sha256": store.put_blob(&out).map_err(fatal)?, 1114 "stderr_sha256": store.put_blob(&err).map_err(fatal)?, 1115 }); 1116 prepare_out = Some((code, out, err)); 1117 } 1118 1119 // A gb10 gate takes the GPU locks only when nothing else already stops it, 1120 // waiting for a held lock as `opts.gpu.wait` says. A refusal (quiet flag, 1121 // est_load, a lock still held at the bound) becomes the gate's reason; 1122 // the wait goes into the receipt (`volatile.gpu_wait`) either way. 1123 let mut gpu_wait = Value::Null; 1124 let gpu: Option = 1125 if m.pool() == "gb10" && !facts.prepare_failed && verdict::pre_run(m, &facts).is_none() { 1126 let attempt = acquire_gpu_timed(&opts.gpu); 1127 gpu_wait = json!({ 1128 "mode": opts.gpu.wait.mode(), 1129 "bound_ms": opts.gpu.wait.bound_ms(), 1130 "waited_ms": attempt.waited.as_millis() as u64, 1131 "acquired": attempt.result.is_ok(), 1132 // The memory check (gpu_mem): what the gate needed and what was free 1133 // once it held the locks (null when not checked or refused first). 1134 "mem_need_mb": attempt.mem_need_mb, 1135 "mem_free_mb": attempt.mem_free_mb, 1136 }); 1137 match attempt.result { 1138 Ok(g) => Some(g), 1139 Err(r) => { 1140 facts.refusal = Some(r.reason().to_string()); 1141 None 1142 } 1143 } 1144 } else { 1145 None 1146 }; 1147 let gpu_since = Instant::now(); 1148 let mut gpu_held_ms: Option = None; 1149 let will_run = verdict::pre_run(m, &facts).is_none(); 1150 1151 let mut stdout: Vec = Vec::new(); 1152 let mut stderr: Vec = Vec::new(); 1153 let mut after = before.clone(); 1154 let mut timeout_exceeded = false; 1155 if will_run { 1156 if let Some((code, out, err)) = prepare_out.take().filter(|_| facts.prepare_failed) { 1157 // The prepare step failed and run never started: its output is 1158 // the gate's record. 1159 facts.exit_status = code; 1160 stdout = out; 1161 stderr = err; 1162 } else { 1163 let direct = RunSpec { 1164 program: exec_path.clone(), 1165 args: opts.args_override.clone().unwrap_or_else(|| m.args.clone()), 1166 cwd: root.to_path_buf(), 1167 timeout: Duration::from_millis(m.timeout_ms), 1168 kill_grace: opts.kill_grace, 1169 // gb10 jobs are never killed (ADR 0028 Decision 6): the timeout 1170 // only marks the receipt. 1171 enforce_timeout: m.pool() != "gb10", 1172 // Tell the gate the GPU locks are already held for it, so a 1173 // script that would take /tmp/aien-gb10.lock itself skips that. 1174 // Only the runner may say so: an inherited copy (an operator's 1175 // shell) is removed for every gate the guard is not held for. 1176 env: if gpu.is_some() { 1177 vec![(GPU_LOCK_HELD_MARKER.to_string(), "1".to_string())] 1178 } else { 1179 Vec::new() 1180 }, 1181 env_remove: if gpu.is_some() { 1182 Vec::new() 1183 } else { 1184 vec![GPU_LOCK_HELD_MARKER.to_string()] 1185 }, 1186 }; 1187 // The sandbox seam (C8): `none` returns `direct` unchanged. 1188 let spec = sandbox::wrap( 1189 opts.sandbox, 1190 direct, 1191 m.pool(), 1192 &sandbox::env_pairs(opts.cargo_target_dir.as_deref()), 1193 ); 1194 match process::run(&spec) { 1195 Ok(o) => { 1196 facts.exit_status = o.exit_code.map(i64::from); 1197 // Exit 2 with the helper's prefix is the helper refusing the 1198 // call (nothing ran): never a program result, so it can never 1199 // meet `expects.exit`, not even `exit: 2`. 1200 if sandbox_refused(opts.sandbox, o.exit_code, &o.stderr) { 1201 facts.exit_status = None; 1202 } 1203 facts.timed_out = o.timed_out; 1204 timeout_exceeded = o.timeout_exceeded; 1205 stdout = o.stdout; 1206 stderr = o.stderr; 1207 } 1208 Err(e) => { 1209 stderr = format!("aien-test: cannot run {}: {e}\n", m.exec).into_bytes(); 1210 } 1211 } 1212 } 1213 // The job is over: close the lock descriptors at once. 1214 if gpu.is_some() { 1215 gpu_held_ms = Some(gpu_since.elapsed().as_millis() as u64); 1216 } 1217 drop(gpu); 1218 drop(target_lock); 1219 after = porcelain(root).map_err(RunError::Fatal)?; 1220 let head_after = head(root).unwrap_or_default(); 1221 facts.tree_changed_after = after != before; 1222 facts.head_moved = head_after != commit; 1223 facts.observations = parse_observations(&stdout); 1224 } 1225 drop(permit); 1226 let derived = derive(m, &facts); 1227 1228 if evidence_inside { 1229 return Ok(Outcome { 1230 verdict: derived.verdict, 1231 reason: derived.reason, 1232 receipt_path: None, 1233 receipt_digest: None, 1234 cache: note, 1235 }); 1236 } 1237 1238 let stdout_sha = store.put_blob(&stdout).map_err(fatal)?; 1239 let stderr_sha = store.put_blob(&stderr).map_err(fatal)?; 1240 1241 let observations: Vec = facts 1242 .observations 1243 .iter() 1244 .map(|o| json!({ "name": o.name, "value": o.value })) 1245 .collect(); 1246 let rules: Vec = derived 1247 .rules 1248 .iter() 1249 .map(|(t, h)| json!({ "rule": t, "held": h })) 1250 .collect(); 1251 let checks: Vec = m 1252 .checks 1253 .iter() 1254 .map(|c| { 1255 let passed = will_run && c == "clean_tree_after" && !facts.tree_changed_after; 1256 json!({ "name": c, "passed": passed }) 1257 }) 1258 .collect(); 1259 let dependency_values: Vec = experiment 1260 .dependencies 1261 .iter() 1262 .map(|(gate, receipt)| json!({ "gate": gate, "receipt": receipt })) 1263 .collect(); 1264 1265 let mut core = Map::new(); 1266 core.insert("gate".into(), json!(m.gate)); 1267 core.insert("owner".into(), json!(m.owner)); 1268 core.insert("manifest_digest".into(), json!(m.digest)); 1269 core.insert("commit".into(), json!(commit)); 1270 core.insert("pins".into(), opts.pins.clone()); 1271 core.insert("tree_clean_before".into(), json!(before.is_empty())); 1272 core.insert("tree_clean_after".into(), json!(after.is_empty())); 1273 core.insert("commit_unchanged_after".into(), json!(!facts.head_moved)); 1274 if let Some(b) = &id.binary_sha { 1275 core.insert("binary_sha256".into(), json!(b)); 1276 } 1277 core.insert("build_inputs_digest".into(), json!(id.inputs_digest)); 1278 core.insert("env".into(), captured_env()); 1279 core.insert("machine".into(), id.machine.clone()); 1280 core.insert("machine_digest".into(), json!(id.machine_digest)); 1281 core.insert("exit_status".into(), json!(facts.exit_status)); 1282 core.insert("stdout_sha256".into(), json!(stdout_sha)); 1283 core.insert("stderr_sha256".into(), json!(stderr_sha)); 1284 core.insert("observations".into(), Value::Array(observations)); 1285 core.insert("rules".into(), Value::Array(rules)); 1286 core.insert("derived_verdict".into(), json!(derived.verdict.as_str())); 1287 core.insert("reason".into(), json!(derived.reason)); 1288 core.insert("mutants".into(), json!([])); 1289 core.insert("checks".into(), Value::Array(checks)); 1290 core.insert("dependencies".into(), Value::Array(dependency_values)); 1291 1292 let mut volatile = json!({ 1293 "started_utc": utc_string(started), 1294 "finished_utc": utc_string(now_secs()), 1295 "duration_ms": t0.elapsed().as_millis() as u64, 1296 "pool": m.pool(), 1297 "pool_wait_ms": job.pool_wait_ms, 1298 "batch_wait_ms": batch_wait_ms, 1299 "target_wait_ms": target_wait_ms, 1300 "runner": { "name": "aien-test", "version": env!("CARGO_PKG_VERSION"), "impl": "rust" }, 1301 "cache": cache::cache_member(&cache_key, None, mode), 1302 "timeout_exceeded": timeout_exceeded, 1303 "gpu_wait": gpu_wait, 1304 "gpu_held_ms": gpu_held_ms, 1305 }); 1306 if !prepare_note.is_null() { 1307 volatile["prepare"] = prepare_note; 1308 } 1309 1310 let receipt = build_receipt(Value::Object(core), volatile); 1311 let (digest, path) = store.put_receipt(&receipt).map_err(fatal)?; 1312 // Offer the result to other heads only if `lookup` would reuse it here 1313 // (PASS or FAIL, clean tree, in time, key recomputes, logs present): a 1314 // failed publication costs the next head a run, never a wrong verdict. 1315 if let (Some((sh, _)), Some(name), Some(_held)) = 1316 (shared, shared_slot.as_ref(), key_lock.as_ref()) 1317 { 1318 let idx = Index::load(&store); 1319 if let Some(r) = idx.get(&digest) { 1320 if cache::usable(r, &cache_key, &idx, &store, &captured_env()).is_ok() { 1321 if let Err(e) = sh.publish(name, &digest, &store) { 1322 eprintln!("aien-test: {} not shared with other heads: {e}", m.gate); 1323 } 1324 } 1325 } 1326 } 1327 drop(key_lock); 1328 Ok(Outcome { 1329 verdict: derived.verdict, 1330 reason: derived.reason, 1331 receipt_path: Some(path), 1332 receipt_digest: Some(digest), 1333 cache: note, 1334 }) 1335 } 1336 1337 /// Run one gate. Its dependencies are not started: their receipts for the 1338 /// current commit are read from the evidence store, and a dependency without a 1339 /// PASS receipt makes this gate NOT_RUN (ADR row 5). 1340 pub fn run_gate(root: &Path, manifest_path: &Path, opts: &Options) -> Result { 1341 let bytes = fs::read(manifest_path) 1342 .map_err(|e| RunError::Fatal(format!("cannot read manifest: {e}")))?; 1343 let m = manifest::parse(&bytes).map_err(|e| RunError::BadManifest(e.0))?; 1344 let deps = if m.depends_on.is_empty() { 1345 Vec::new() 1346 } else { 1347 let commit = head(root).map_err(RunError::Fatal)?; 1348 Index::load(&Store::new(&opts.evidence_dir)).dep_facts(&m.depends_on, &commit) 1349 }; 1350 let job = Job { 1351 root, 1352 manifest_path, 1353 m: &m, 1354 opts, 1355 deps, 1356 pool_wait_ms: 0, 1357 }; 1358 execute_gate(&job, None) 1359 } 1360 1361 /// The result of a graph run: one outcome per selected gate, in topological 1362 /// order (a gate always comes after the gates it depends on). 1363 #[derive(Debug, Clone)] 1364 pub struct Campaign { 1365 pub results: Vec<(String, Outcome)>, 1366 } 1367 1368 impl Campaign { 1369 /// ADR 0028 exit rule: any FAIL is FAIL, else the worst of the other 1370 /// non-PASS verdicts, else PASS. 1371 pub fn verdict(&self) -> Verdict { 1372 let all: Vec = self.results.iter().map(|(_, o)| o.verdict).collect(); 1373 campaign_verdict(&all) 1374 } 1375 1376 pub fn exit_code(&self) -> i32 { 1377 self.verdict().exit_code() 1378 } 1379 } 1380 1381 /// What the scheduler shares between worker threads. 1382 struct Sched { 1383 /// Selected gates whose dependencies have all finished and that have not 1384 /// started. 1385 ready: BTreeSet, 1386 /// Per gate: selected dependencies that have not finished yet. 1387 waiting_on: Vec, 1388 /// When each gate became ready (for `pool_wait_ms`). 1389 ready_at: Vec>, 1390 results: Vec>, 1391 /// Selected gates that have not finished. 1392 remaining: usize, 1393 /// The first fatal error; it stops the campaign. 1394 error: Option, 1395 } 1396 1397 /// A gate chosen to start, with the facts about its dependencies and the pool 1398 /// slot it holds (None when it cannot run, so it needs no slot). 1399 struct Pick<'a> { 1400 node: usize, 1401 deps: Vec, 1402 permit: Option>, 1403 } 1404 1405 struct GraphRun<'a> { 1406 root: &'a Path, 1407 graph: &'a Graph, 1408 selection: &'a BTreeSet, 1409 opts: &'a Options, 1410 pools: Pools, 1411 state: Mutex, 1412 cv: Condvar, 1413 /// Facts about dependencies outside the selection, read from the store. 1414 outside: BTreeMap, 1415 } 1416 1417 fn pool_of(m: &Manifest) -> Pool { 1418 Pool::from_name(m.pool()).unwrap_or(Pool::Host) 1419 } 1420 1421 impl GraphRun<'_> { 1422 fn dep_facts(&self, results: &[Option], node: usize) -> Vec { 1423 self.graph 1424 .node(node) 1425 .manifest 1426 .depends_on 1427 .iter() 1428 .map(|id| { 1429 let finished = self.graph.index_of(id).and_then(|d| results[d].as_ref()); 1430 match finished { 1431 Some(o) => DepFact { 1432 gate: id.clone(), 1433 verdict: Some(o.verdict), 1434 receipt: o.receipt_digest.clone(), 1435 }, 1436 None => self.outside.get(id).cloned().unwrap_or_else(|| DepFact { 1437 gate: id.clone(), 1438 verdict: None, 1439 receipt: None, 1440 }), 1441 } 1442 }) 1443 .collect() 1444 } 1445 1446 /// Choose a ready gate that can start now. A gate whose dependencies are 1447 /// not all PASS cannot run, so it needs no pool slot and goes first; any 1448 /// other gate needs a free slot in its pool, and if there is none the 1449 /// next ready gate is tried (so a busy gb10 pool never holds up host 1450 /// work). Called with the scheduler lock held. 1451 fn pick(&self, st: &mut Sched) -> Option> { 1452 let mut chosen = None; 1453 // Gates other heads of a batch share go first (`Options::first`). 1454 let shared = |i: &usize| self.opts.first.contains(&self.graph.node(*i).id); 1455 let order: Vec = st 1456 .ready 1457 .iter() 1458 .filter(|i| shared(i)) 1459 .chain(st.ready.iter().filter(|i| !shared(i))) 1460 .copied() 1461 .collect(); 1462 for i in order { 1463 let deps = self.dep_facts(&st.results, i); 1464 if !deps.iter().all(|d| d.verdict == Some(Verdict::Pass)) { 1465 chosen = Some(Pick { 1466 node: i, 1467 deps, 1468 permit: None, 1469 }); 1470 break; 1471 } 1472 let pool = pool_of(&self.graph.node(i).manifest); 1473 if let Some(permit) = self.pools.try_acquire(pool) { 1474 chosen = Some(Pick { 1475 node: i, 1476 deps, 1477 permit: Some(permit), 1478 }); 1479 break; 1480 } 1481 } 1482 if let Some(p) = &chosen { 1483 st.ready.remove(&p.node); 1484 } 1485 chosen 1486 } 1487 1488 fn worker(&self) { 1489 loop { 1490 let (pick, waited_ms) = { 1491 let mut st = lock(&self.state); 1492 let pick = loop { 1493 if st.remaining == 0 || st.error.is_some() { 1494 return; 1495 } 1496 if let Some(p) = self.pick(&mut st) { 1497 break p; 1498 } 1499 st = self.cv.wait(st).unwrap_or_else(|e| e.into_inner()); 1500 }; 1501 let waited = st.ready_at[pick.node].map_or(0, |t| t.elapsed().as_millis() as u64); 1502 (pick, waited) 1503 }; 1504 let i = pick.node; 1505 let node = self.graph.node(i); 1506 let job = Job { 1507 root: self.root, 1508 manifest_path: &node.path, 1509 m: &node.manifest, 1510 opts: self.opts, 1511 deps: pick.deps, 1512 pool_wait_ms: waited_ms, 1513 }; 1514 let permit = pick.permit; 1515 let ran = catch_unwind(AssertUnwindSafe(|| execute_gate(&job, permit))); 1516 let outcome = match ran { 1517 Ok(r) => r, 1518 Err(_) => Err(RunError::Fatal(format!( 1519 "internal error while running gate {}", 1520 node.id 1521 ))), 1522 }; 1523 let mut st = lock(&self.state); 1524 match outcome { 1525 Ok(o) => { 1526 st.results[i] = Some(o); 1527 st.remaining = st.remaining.saturating_sub(1); 1528 for &d in self.graph.direct_dependents(i) { 1529 if self.selection.contains(&d) { 1530 st.waiting_on[d] = st.waiting_on[d].saturating_sub(1); 1531 if st.waiting_on[d] == 0 { 1532 st.ready.insert(d); 1533 st.ready_at[d] = Some(Instant::now()); 1534 } 1535 } 1536 } 1537 } 1538 Err(e) => { 1539 if st.error.is_none() { 1540 st.error = Some(e); 1541 } 1542 } 1543 } 1544 drop(st); 1545 // The permit went back inside `execute_gate`, so waiting workers 1546 // can use the slot as soon as they wake. 1547 self.cv.notify_all(); 1548 } 1549 } 1550 } 1551 1552 /// Run the gates in `selection` (node numbers of `graph`) with worker threads. 1553 /// A gate starts when every selected gate it depends on has finished and its 1554 /// pool has a free slot (host, qemu, or gb10 with the GPU locks). A gate whose 1555 /// dependency did not PASS is not started: it gets a receipt saying NOT_RUN, 1556 /// or the blocked verdict of the dependency (ADR rows 4 and 5). `selection` 1557 /// should include the dependencies of its members; one that is left out is 1558 /// looked up in the evidence store for the current commit. 1559 pub fn run_graph( 1560 root: &Path, 1561 graph: &Graph, 1562 selection: &BTreeSet, 1563 opts: &Options, 1564 ) -> Result { 1565 if selection.is_empty() { 1566 return Ok(Campaign { 1567 results: Vec::new(), 1568 }); 1569 } 1570 let commit = head(root).map_err(RunError::Fatal)?; 1571 let index = Index::load(&Store::new(&opts.evidence_dir)); 1572 let start = Instant::now(); 1573 1574 let mut outside: BTreeMap = BTreeMap::new(); 1575 let mut waiting_on = vec![0usize; graph.len()]; 1576 let mut ready: BTreeSet = BTreeSet::new(); 1577 let mut ready_at: Vec> = vec![None; graph.len()]; 1578 for &i in selection { 1579 for &d in &graph.node(i).deps { 1580 if selection.contains(&d) { 1581 waiting_on[i] += 1; 1582 } else { 1583 let id = graph.node(d).id.clone(); 1584 let facts = index.dep_facts(std::slice::from_ref(&id), &commit); 1585 if let Some(f) = facts.into_iter().next() { 1586 outside.insert(id, f); 1587 } 1588 } 1589 } 1590 if waiting_on[i] == 0 { 1591 ready.insert(i); 1592 ready_at[i] = Some(start); 1593 } 1594 } 1595 1596 let run = GraphRun { 1597 root, 1598 graph, 1599 selection, 1600 opts, 1601 pools: Pools::new(opts.pool_sizes), 1602 state: Mutex::new(Sched { 1603 ready, 1604 waiting_on, 1605 ready_at, 1606 results: vec![None; graph.len()], 1607 remaining: selection.len(), 1608 error: None, 1609 }), 1610 cv: Condvar::new(), 1611 outside, 1612 }; 1613 1614 // Enough workers for every slot of every pool to be busy at once. 1615 let workers = (opts.pool_sizes.host + opts.pool_sizes.qemu + 1) 1616 .min(selection.len()) 1617 .max(1); 1618 thread::scope(|s| { 1619 for _ in 0..workers { 1620 s.spawn(|| run.worker()); 1621 } 1622 }); 1623 1624 let mut st = lock(&run.state); 1625 if let Some(e) = st.error.take() { 1626 return Err(e); 1627 } 1628 let mut results = Vec::with_capacity(selection.len()); 1629 for &i in graph.order() { 1630 if !selection.contains(&i) { 1631 continue; 1632 } 1633 let id = &graph.node(i).id; 1634 match st.results[i].take() { 1635 Some(o) => results.push((id.clone(), o)), 1636 None => return Err(RunError::Fatal(format!("no result for gate {id}"))), 1637 } 1638 } 1639 Ok(Campaign { results }) 1640 } 1641 1642 #[cfg(test)] 1643 mod tests { 1644 use super::*; 1645 use crate::resources::{acquire_gpu, GpuWait}; 1646 use crate::testutil::queued_on; 1647 use crate::testutil::{git, init_repo, write_file, TempDir}; 1648 use std::os::unix::fs::PermissionsExt; 1649 1650 const OK_SCRIPT: &str = "#!/bin/sh\ntouch \"$1\"\necho \"AIEN-OBS n 3\"\necho PASS\n"; 1651 1652 fn gate_text( 1653 exec: &str, 1654 args: &[&str], 1655 exit: i32, 1656 observe: &[&str], 1657 timeout: &str, 1658 extra: &str, 1659 ) -> String { 1660 format!( 1661 "gate: T-1\nmanifest_version: 1\nowner: t\nrequires:\n - host\nrun:\n exec: {exec}\n args: {}\nexpects:\n exit: {exit}\n observe: {}\n verdict: PASS\ntimeout: {timeout}\n{extra}", 1662 serde_json::to_string(args).unwrap(), 1663 serde_json::to_string(observe).unwrap(), 1664 ) 1665 } 1666 1667 struct Fx { 1668 repo: TempDir, 1669 ev: TempDir, 1670 scratch: TempDir, 1671 } 1672 1673 impl Fx { 1674 fn marker(&self) -> PathBuf { 1675 self.scratch.path().join("marker") 1676 } 1677 fn manifest(&self) -> PathBuf { 1678 self.repo.path().join("tests/t.gate") 1679 } 1680 fn opts(&self) -> Options { 1681 let mut o = Options::new(self.ev.path().join("out")); 1682 o.kill_grace = Duration::from_millis(300); 1683 o.hardware = Hardware { 1684 gb10_present: false, 1685 qemu_available: false, 1686 }; 1687 o.gpu = GpuConfig::rooted_at(self.scratch.path()); 1688 o 1689 } 1690 } 1691 1692 /// A repo with `tools/run.sh` = script and a gate whose args are the 1693 /// marker path. 1694 fn fixture(script: &str, exit: i32, observe: &[&str], timeout: &str, extra: &str) -> Fx { 1695 let scratch = TempDir::new("scratch"); 1696 let marker = scratch.path().join("marker"); 1697 let gate = gate_text( 1698 "tools/run.sh", 1699 &[marker.to_str().unwrap()], 1700 exit, 1701 observe, 1702 timeout, 1703 extra, 1704 ); 1705 let repo = init_repo( 1706 "repo", 1707 &[ 1708 ("tools/run.sh", script, true), 1709 ("tests/t.gate", gate.as_str(), false), 1710 ("README", "hello\n", false), 1711 ], 1712 ); 1713 Fx { 1714 repo, 1715 ev: TempDir::new("ev"), 1716 scratch, 1717 } 1718 } 1719 1720 fn ok_fixture() -> Fx { 1721 fixture(OK_SCRIPT, 0, &["n == 3"], "20s", "") 1722 } 1723 1724 fn read_json(p: &Path) -> Value { 1725 serde_json::from_slice(&fs::read(p).unwrap()).unwrap() 1726 } 1727 1728 fn run(fx: &Fx, opts: &Options) -> Outcome { 1729 run_gate(fx.repo.path(), &fx.manifest(), opts).unwrap() 1730 } 1731 1732 #[test] 1733 fn pass_writes_a_bound_receipt() { 1734 let fx = ok_fixture(); 1735 let o = run(&fx, &fx.opts()); 1736 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 1737 assert!(fx.marker().exists(), "script must have run"); 1738 let path = o.receipt_path.unwrap(); 1739 let r = read_json(&path); 1740 assert_eq!(r["schema"], "aien-test/EvidenceReceiptV1"); 1741 let core = &r["core"]; 1742 let head_now = git_out(fx.repo.path(), &["rev-parse", "HEAD"]).unwrap(); 1743 assert_eq!(core["commit"], head_now.trim()); 1744 assert_eq!(core["gate"], "T-1"); 1745 assert_eq!(core["derived_verdict"], "PASS"); 1746 assert_eq!(core["reason"], ""); 1747 assert_eq!(core["exit_status"], 0); 1748 assert_eq!(core["tree_clean_before"], true); 1749 assert_eq!(core["tree_clean_after"], true); 1750 assert_eq!(core["commit_unchanged_after"], true); 1751 assert_eq!(core["observations"][0]["name"], "n"); 1752 assert_eq!(core["observations"][0]["value"], 3); 1753 assert_eq!(core["rules"][0]["held"], true); 1754 let script_bytes = fs::read(fx.repo.path().join("tools/run.sh")).unwrap(); 1755 assert_eq!(core["binary_sha256"], sha256_hex(&script_bytes)); 1756 let gate_bytes = fs::read(fx.manifest()).unwrap(); 1757 assert_eq!(core["manifest_digest"], sha256_hex(&gate_bytes)); 1758 assert_eq!(core["dependencies"], json!([])); 1759 assert_eq!(r["volatile"]["pool"], "host"); 1760 assert_eq!(r["volatile"]["timeout_exceeded"], false); 1761 // Receipt is read-only and named by its digest. 1762 assert_eq!( 1763 fs::metadata(&path).unwrap().permissions().mode() & 0o777, 1764 0o444 1765 ); 1766 assert_eq!( 1767 path.file_name().unwrap().to_string_lossy(), 1768 format!("{}.json", o.receipt_digest.unwrap()) 1769 ); 1770 // stdout blob holds the script output verbatim. 1771 let sha = core["stdout_sha256"].as_str().unwrap(); 1772 let blob = fx.ev.path().join("out/blobs").join(format!("{sha}.log")); 1773 assert_eq!(fs::read(blob).unwrap(), b"AIEN-OBS n 3\nPASS\n"); 1774 } 1775 1776 #[test] 1777 fn dirty_tree_is_refused_and_nothing_runs() { 1778 let fx = ok_fixture(); 1779 write_file(fx.repo.path(), "README", "changed\n", false); 1780 let o = run(&fx, &fx.opts()); 1781 assert_eq!(o.verdict, Verdict::NotRun); 1782 assert_eq!(o.reason, "dirty_tree"); 1783 assert!(!fx.marker().exists(), "script must not run on a dirty tree"); 1784 let r = read_json(&o.receipt_path.unwrap()); 1785 assert_eq!(r["core"]["tree_clean_before"], false); 1786 assert_eq!(r["core"]["exit_status"], Value::Null); 1787 } 1788 1789 #[test] 1790 fn untracked_file_counts_as_dirty() { 1791 let fx = ok_fixture(); 1792 write_file(fx.repo.path(), "stray.txt", "x", false); 1793 let o = run(&fx, &fx.opts()); 1794 assert_eq!( 1795 (o.verdict, o.reason.as_str()), 1796 (Verdict::NotRun, "dirty_tree") 1797 ); 1798 assert!(!fx.marker().exists()); 1799 } 1800 1801 #[test] 1802 fn allow_dirty_runs_and_records_it() { 1803 let fx = ok_fixture(); 1804 write_file(fx.repo.path(), "README", "changed\n", false); 1805 let mut opts = fx.opts(); 1806 opts.allow_dirty = true; 1807 let o = run(&fx, &opts); 1808 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 1809 assert!(fx.marker().exists()); 1810 let r = read_json(&o.receipt_path.unwrap()); 1811 assert_eq!(r["core"]["tree_clean_before"], false); 1812 } 1813 1814 #[test] 1815 fn timeout_is_enforced_with_fail() { 1816 let fx = fixture("#!/bin/sh\nsleep 20\n", 0, &[], "300ms", ""); 1817 let t = Instant::now(); 1818 let o = run(&fx, &fx.opts()); 1819 assert!(t.elapsed() < Duration::from_secs(10)); 1820 assert_eq!((o.verdict, o.reason.as_str()), (Verdict::Fail, "timeout")); 1821 let r = read_json(&o.receipt_path.unwrap()); 1822 assert_eq!(r["volatile"]["timeout_exceeded"], true); 1823 } 1824 1825 #[test] 1826 fn rule_mismatch_fails_even_if_the_script_prints_pass() { 1827 let fx = fixture( 1828 "#!/bin/sh\necho \"AIEN-OBS n 4\"\necho PASS\necho 'AIEN-OBS verdict \"PASS\"'\n", 1829 0, 1830 &["n == 3"], 1831 "20s", 1832 "", 1833 ); 1834 let o = run(&fx, &fx.opts()); 1835 assert_eq!((o.verdict, o.reason.as_str()), (Verdict::Fail, "rule:0")); 1836 let r = read_json(&o.receipt_path.unwrap()); 1837 assert_eq!(r["core"]["rules"][0]["held"], false); 1838 } 1839 1840 #[test] 1841 fn exit_status_must_match() { 1842 let fx = fixture( 1843 "#!/bin/sh\necho \"AIEN-OBS n 3\"\nexit 2\n", 1844 0, 1845 &["n == 3"], 1846 "20s", 1847 "", 1848 ); 1849 let o = run(&fx, &fx.opts()); 1850 assert_eq!( 1851 (o.verdict, o.reason.as_str()), 1852 (Verdict::Fail, "rc_nonzero") 1853 ); 1854 let r = read_json(&o.receipt_path.unwrap()); 1855 assert_eq!(r["core"]["exit_status"], 2); 1856 } 1857 1858 #[test] 1859 fn nonzero_expected_exit_passes() { 1860 let fx = fixture("#!/bin/sh\nexit 7\n", 7, &[], "20s", ""); 1861 assert_eq!(run(&fx, &fx.opts()).verdict, Verdict::Pass); 1862 } 1863 1864 #[test] 1865 fn missing_exec_is_missing_implementation() { 1866 let fx = ok_fixture(); 1867 fs::remove_file(fx.repo.path().join("tools/run.sh")).unwrap(); 1868 git(fx.repo.path(), &["add", "-A"]); 1869 git(fx.repo.path(), &["commit", "-q", "-m", "rm"]); 1870 let o = run(&fx, &fx.opts()); 1871 assert_eq!(o.verdict, Verdict::MissingImplementation); 1872 assert_eq!(o.reason, "NO_RUN_EXEC"); 1873 let r = read_json(&o.receipt_path.unwrap()); 1874 assert!(r["core"].get("binary_sha256").is_none()); 1875 } 1876 1877 #[test] 1878 fn evidence_dir_inside_repo_is_refused() { 1879 let fx = ok_fixture(); 1880 let mut opts = fx.opts(); 1881 opts.evidence_dir = fx.repo.path().join("evidence"); 1882 let o = run(&fx, &opts); 1883 assert_eq!( 1884 (o.verdict, o.reason.as_str()), 1885 (Verdict::NotRun, "evidence_inside") 1886 ); 1887 assert!(o.receipt_path.is_none()); 1888 assert!(!fx.repo.path().join("evidence").exists()); 1889 assert!(!fx.marker().exists()); 1890 } 1891 1892 #[test] 1893 fn tree_dirtied_by_the_run_fails() { 1894 let fx = fixture("#!/bin/sh\necho more >> README\n", 0, &[], "20s", ""); 1895 let o = run(&fx, &fx.opts()); 1896 assert_eq!( 1897 (o.verdict, o.reason.as_str()), 1898 (Verdict::Fail, "dirty_after") 1899 ); 1900 let r = read_json(&o.receipt_path.unwrap()); 1901 assert_eq!(r["core"]["tree_clean_after"], false); 1902 } 1903 1904 #[test] 1905 fn head_moving_during_the_run_fails() { 1906 let fx = fixture( 1907 "#!/bin/sh\ngit -c user.name=t -c user.email=t@example.invalid -c commit.gpgsign=false commit -q --allow-empty -m moved\n", 1908 0, 1909 &[], 1910 "20s", 1911 "", 1912 ); 1913 let o = run(&fx, &fx.opts()); 1914 assert_eq!( 1915 (o.verdict, o.reason.as_str()), 1916 (Verdict::Fail, "head_moved") 1917 ); 1918 let r = read_json(&o.receipt_path.unwrap()); 1919 assert_eq!(r["core"]["commit_unchanged_after"], false); 1920 } 1921 1922 #[test] 1923 fn args_after_double_dash_replace_manifest_args() { 1924 let fx = ok_fixture(); 1925 let other = fx.scratch.path().join("other"); 1926 let mut opts = fx.opts(); 1927 opts.args_override = Some(vec![other.to_str().unwrap().to_string()]); 1928 let o = run(&fx, &opts); 1929 assert_eq!(o.verdict, Verdict::Pass); 1930 assert!(other.exists()); 1931 assert!(!fx.marker().exists()); 1932 } 1933 1934 #[test] 1935 fn bad_manifest_writes_no_receipt() { 1936 let fx = ok_fixture(); 1937 write_file(fx.repo.path(), "tests/t.gate", "gate: X\nbogus: 1\n", false); 1938 match run_gate(fx.repo.path(), &fx.manifest(), &fx.opts()) { 1939 Err(RunError::BadManifest(_)) => {} 1940 other => panic!("expected BadManifest, got {other:?}"), 1941 } 1942 assert!(!fx.ev.path().join("out").exists()); 1943 } 1944 1945 #[test] 1946 fn operator_and_missing_hardware_gates_do_not_run() { 1947 let fx = ok_fixture(); 1948 let gate = fs::read_to_string(fx.manifest()).unwrap(); 1949 write_file( 1950 fx.repo.path(), 1951 "tests/t.gate", 1952 &gate.replace(" - host\n", " - host\n - operator\n"), 1953 false, 1954 ); 1955 git(fx.repo.path(), &["add", "-A"]); 1956 git(fx.repo.path(), &["commit", "-q", "-m", "op"]); 1957 let o = run(&fx, &fx.opts()); 1958 assert_eq!(o.verdict, Verdict::BlockedOperator); 1959 assert!(!fx.marker().exists()); 1960 write_file( 1961 fx.repo.path(), 1962 "tests/t.gate", 1963 &gate.replace(" - host\n", " - gb10\n"), 1964 false, 1965 ); 1966 git(fx.repo.path(), &["add", "-A"]); 1967 git(fx.repo.path(), &["commit", "-q", "-m", "gb10"]); 1968 let o = run(&fx, &fx.opts()); 1969 assert_eq!( 1970 (o.verdict, o.reason.as_str()), 1971 (Verdict::BlockedHardware, "NO_GB10") 1972 ); 1973 assert!(!fx.marker().exists()); 1974 } 1975 1976 #[test] 1977 fn unfinished_receipts_are_never_modified_by_a_second_run() { 1978 let fx = ok_fixture(); 1979 let first = run(&fx, &fx.opts()).receipt_path.unwrap(); 1980 let before = fs::read(&first).unwrap(); 1981 let second = run(&fx, &fx.opts()); 1982 assert_eq!(second.verdict, Verdict::Pass); 1983 assert_eq!(fs::read(&first).unwrap(), before); 1984 } 1985 1986 #[test] 1987 fn the_exec_helper_is_part_of_the_machine_only_under_the_user_sandbox() { 1988 let fx = ok_fixture(); 1989 let m = manifest::parse(&fs::read(fx.manifest()).unwrap()).unwrap(); 1990 let hw = fx.opts().hardware; 1991 let none = identity(fx.repo.path(), &fx.manifest(), &m, &hw, Sandbox::None).unwrap(); 1992 let user = identity(fx.repo.path(), &fx.manifest(), &m, &hw, Sandbox::User).unwrap(); 1993 assert!(none.machine.get("sandbox_helper_sha256").is_none()); 1994 let want = fs::read(sandbox::EXEC_HELPER).ok().map(|b| sha256_hex(&b)); 1995 assert_eq!(user.machine["sandbox_helper_sha256"], json!(want)); 1996 // Another helper is another machine: no cache entry carries over. 1997 assert_ne!(none.machine_digest, user.machine_digest); 1998 } 1999 2000 #[test] 2001 fn inputs_digest_tracks_input_bytes() { 2002 let fx = ok_fixture(); 2003 let m = manifest::parse(&fs::read(fx.manifest()).unwrap()).unwrap(); 2004 let mut m2 = m.clone(); 2005 m2.inputs = vec!["README".to_string()]; 2006 let a = build_inputs_digest(fx.repo.path(), None, &m2); 2007 assert_eq!(a, build_inputs_digest(fx.repo.path(), None, &m2)); 2008 write_file(fx.repo.path(), "README", "different\n", false); 2009 let b = build_inputs_digest(fx.repo.path(), None, &m2); 2010 assert_ne!(a, b); 2011 } 2012 2013 #[test] 2014 fn convention_inputs_are_found() { 2015 let repo = init_repo( 2016 "conv", 2017 &[ 2018 ("src/rt/world.c", "int x;", false), 2019 ("tests/rt/world_test.c", "int t;", false), 2020 ("tests/rt/other.c", "int o;", false), 2021 ], 2022 ); 2023 let m = manifest::parse(gate_text("tools/x.sh", &[], 0, &[], "5s", "").as_bytes()).unwrap(); 2024 let rel = Path::new("tests/rt/world.gate"); 2025 let a = build_inputs_digest(repo.path(), Some(rel), &m); 2026 write_file(repo.path(), "src/rt/world.c", "int y;", false); 2027 let b = build_inputs_digest(repo.path(), Some(rel), &m); 2028 assert_ne!(a, b, "implied src input must feed the digest"); 2029 write_file(repo.path(), "tests/rt/other.c", "int p;", false); 2030 let c = build_inputs_digest(repo.path(), Some(rel), &m); 2031 assert_eq!(b, c, "unrelated file must not feed the digest"); 2032 } 2033 2034 #[test] 2035 fn locate_by_path_name_and_duplicates() { 2036 let g1 = gate_text("tools/x.sh", &[], 0, &[], "5s", "").replace("T-1", "ONE"); 2037 let g2 = gate_text("tools/x.sh", &[], 0, &[], "5s", "").replace("T-1", "TWO"); 2038 let repo = init_repo( 2039 "loc", 2040 &[ 2041 ("tests/a/one.gate", g1.as_str(), false), 2042 ("tests/b/two.gate", g2.as_str(), false), 2043 ("target/skipped.gate", g1.as_str(), false), 2044 ("tests/bad.gate", "nonsense\n", false), 2045 ], 2046 ); 2047 let p = locate_gate(repo.path(), "ONE").unwrap(); 2048 assert!(p.ends_with("tests/a/one.gate"), "{p:?}"); 2049 let p = locate_gate(repo.path(), "tests/b/two.gate").unwrap(); 2050 assert!(p.ends_with("tests/b/two.gate")); 2051 assert!(locate_gate(repo.path(), "NOPE").is_err()); 2052 write_file(repo.path(), "tests/c/dup.gate", g1.as_str(), false); 2053 let e = locate_gate(repo.path(), "ONE").unwrap_err(); 2054 assert!(e.contains("duplicate"), "{e}"); 2055 } 2056 2057 #[test] 2058 fn ignore_marker_hides_a_directory() { 2059 let g = gate_text("tools/x.sh", &[], 0, &[], "5s", ""); 2060 let repo = init_repo( 2061 "ign", 2062 &[ 2063 ("tests/a.gate", g.as_str(), false), 2064 ("tests/skip/b.gate", g.as_str(), false), 2065 ("tests/skip/.aien-test-ignore", "", false), 2066 ], 2067 ); 2068 let found = discover(repo.path()); 2069 assert_eq!(found.len(), 1); 2070 assert!(found[0].ends_with("tests/a.gate")); 2071 } 2072 2073 #[test] 2074 fn resolve_handles_missing_dirs_and_dotdot() { 2075 let t = TempDir::new("res"); 2076 let p = resolve(&t.path().join("a/b/../c")); 2077 assert_eq!(p, t.path().join("a/c")); 2078 } 2079 2080 // ---- Slice B: pools, dependencies, graph runs ---- 2081 2082 fn gb10_fixture(script: &str, timeout: &str) -> Fx { 2083 let fx = fixture(script, 0, &[], timeout, ""); 2084 let gate = fs::read_to_string(fx.manifest()).unwrap(); 2085 write_file( 2086 fx.repo.path(), 2087 "tests/t.gate", 2088 &gate.replace(" - host\n", " - gb10\n"), 2089 false, 2090 ); 2091 git(fx.repo.path(), &["add", "-A"]); 2092 git(fx.repo.path(), &["commit", "-q", "-m", "gb10"]); 2093 fx 2094 } 2095 2096 fn gb10_opts(fx: &Fx) -> Options { 2097 let mut o = fx.opts(); 2098 o.hardware.gb10_present = true; 2099 o 2100 } 2101 2102 const TOUCH_MARKER: &str = "#!/bin/sh\ntouch \"$1\"\n"; 2103 2104 #[test] 2105 fn gb10_gate_runs_under_the_gpu_lock_and_records_its_pool() { 2106 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2107 let opts = gb10_opts(&fx); 2108 let o = run(&fx, &opts); 2109 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2110 assert!(fx.marker().exists()); 2111 let r = read_json(&o.receipt_path.unwrap()); 2112 assert_eq!(r["volatile"]["pool"], "gb10"); 2113 assert_eq!(r["volatile"]["timeout_exceeded"], false); 2114 assert_eq!(r["core"]["machine"]["gb10_present"], true); 2115 assert!(opts.gpu.lock_path.exists(), "the lock file is created"); 2116 assert!( 2117 acquire_gpu(&opts.gpu).is_ok(), 2118 "the lock is released after the job" 2119 ); 2120 } 2121 2122 /// Prints whether the runner told the gate it already holds the GPU lock. 2123 const LOCK_HELD_SCRIPT: &str = 2124 "#!/bin/sh\ntouch \"$1\"\necho \"AIEN-OBS lock_held ${AIEN_GB10_LOCK_HELD:-0}\"\n"; 2125 2126 #[test] 2127 fn gb10_gate_is_told_the_runner_holds_the_gpu_lock() { 2128 // ADR 0033: the trusted side serializes gb10 under /tmp/aien-gb10.lock. 2129 // A gate script that takes the same lock itself would block behind the 2130 // runner (or, as aien-run, fail to open it), so the runner says so. 2131 let fx = gb10_fixture(LOCK_HELD_SCRIPT, "20s"); 2132 let o = run(&fx, &gb10_opts(&fx)); 2133 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2134 let r = read_json(&o.receipt_path.unwrap()); 2135 assert_eq!(r["core"]["observations"][0]["name"], "lock_held"); 2136 assert_eq!(r["core"]["observations"][0]["value"], 1); 2137 } 2138 2139 /// `prep ` records whether the GPU lock is free and 2140 /// whether the runner claims to hold it; `run ` reports 2141 /// whether the lock is free while the run is going. 2142 const PREPARE_SCRIPT: &str = "#!/bin/sh\nfree=0\nflock -n \"$3\" true && free=1\nif [ \"$1\" = prep ]; then\n echo \"held=${AIEN_GB10_LOCK_HELD:-0} free=$free\" > \"$2.prep\"\n exit \"$4\"\nfi\ntouch \"$2\"\necho \"AIEN-OBS lock_free $free\"\n"; 2143 2144 /// A v2 gb10 gate whose `prepare` exits `prep_exit`. 2145 fn prepare_fixture(prep_exit: i32) -> (Fx, Options) { 2146 let fx = gb10_fixture(PREPARE_SCRIPT, "20s"); 2147 let opts = gb10_opts(&fx); 2148 let (marker, lock) = (fx.marker(), opts.gpu.lock_path.clone()); 2149 let (marker, lock) = (marker.to_str().unwrap(), lock.to_str().unwrap()); 2150 let gate = format!( 2151 "gate: T-1\nmanifest_version: 2\nowner: t\nrequires:\n - gb10\nprepare:\n exec: tools/run.sh\n args: {}\nrun:\n exec: tools/run.sh\n args: {}\nexpects:\n exit: 0\n observe: [\"lock_free == 0\"]\n verdict: PASS\ntimeout: 20s\n", 2152 serde_json::to_string(&["prep", marker, lock, &prep_exit.to_string()]).unwrap(), 2153 serde_json::to_string(&["run", marker, lock]).unwrap(), 2154 ); 2155 write_file(fx.repo.path(), "tests/t.gate", &gate, false); 2156 git(fx.repo.path(), &["add", "-A"]); 2157 git(fx.repo.path(), &["commit", "-q", "-m", "prepare"]); 2158 (fx, opts) 2159 } 2160 2161 #[test] 2162 fn prepare_runs_before_the_gpu_lock_and_run_under_it() { 2163 let (fx, opts) = prepare_fixture(0); 2164 let o = run(&fx, &opts); 2165 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2166 // The prepare step saw a free lock and no claim that it was held. 2167 let prep = fs::read_to_string(fx.marker().with_extension("prep")).unwrap(); 2168 assert_eq!(prep.trim(), "held=0 free=1"); 2169 // The run itself was under the lock (rule lock_free == 0 held). 2170 let r = read_json(&o.receipt_path.unwrap()); 2171 assert_eq!(r["volatile"]["prepare"]["exit_status"], 0); 2172 assert!(r["volatile"]["prepare"]["duration_ms"].is_u64()); 2173 assert!(r["volatile"]["gpu_held_ms"].is_u64()); 2174 assert_eq!(r["volatile"]["gpu_wait"]["acquired"], true); 2175 assert!(acquire_gpu(&opts.gpu).is_ok(), "released after the job"); 2176 } 2177 2178 #[test] 2179 fn a_failed_prepare_fails_the_gate_and_never_takes_the_gpu() { 2180 let (fx, opts) = prepare_fixture(3); 2181 let o = run(&fx, &opts); 2182 assert_eq!( 2183 (o.verdict, o.reason.as_str()), 2184 (Verdict::Fail, "prepare_failed") 2185 ); 2186 assert!(!fx.marker().exists(), "run must not start"); 2187 let r = read_json(&o.receipt_path.unwrap()); 2188 assert_eq!(r["core"]["exit_status"], 3); 2189 assert_eq!(r["volatile"]["prepare"]["exit_status"], 3); 2190 assert!( 2191 r["volatile"]["gpu_wait"].is_null(), 2192 "the GPU lock was never asked for" 2193 ); 2194 assert!(r["volatile"]["gpu_held_ms"].is_null()); 2195 } 2196 2197 #[test] 2198 fn host_gate_is_not_told_the_lock_is_held() { 2199 let fx = fixture(LOCK_HELD_SCRIPT, 0, &[], "20s", ""); 2200 let o = run(&fx, &fx.opts()); 2201 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2202 let r = read_json(&o.receipt_path.unwrap()); 2203 assert_eq!(r["core"]["observations"][0]["value"], 0); 2204 } 2205 2206 #[test] 2207 fn host_gate_does_not_inherit_the_marker_from_the_operator() { 2208 // Without a sandbox the gate inherits the runner's environment. An 2209 // operator shell that exported the marker must not make a host gate 2210 // believe the GPU lock is held for it. 2211 std::env::set_var(GPU_LOCK_HELD_MARKER, "1"); 2212 let fx = fixture(LOCK_HELD_SCRIPT, 0, &[], "20s", ""); 2213 let o = run(&fx, &fx.opts()); 2214 std::env::remove_var(GPU_LOCK_HELD_MARKER); 2215 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2216 let r = read_json(&o.receipt_path.unwrap()); 2217 assert_eq!(r["core"]["observations"][0]["value"], 0); 2218 } 2219 2220 #[test] 2221 fn operator_gate_runs_when_the_operator_started_it() { 2222 // sc #614: the same gate the previous test refuses runs under 2223 // `--operator`, writes its receipt and passes on its own facts. 2224 let fx = ok_fixture(); 2225 let gate = fs::read_to_string(fx.manifest()).unwrap(); 2226 write_file( 2227 fx.repo.path(), 2228 "tests/t.gate", 2229 &gate.replace(" - host\n", " - host\n - operator\n"), 2230 false, 2231 ); 2232 git(fx.repo.path(), &["add", "-A"]); 2233 git(fx.repo.path(), &["commit", "-q", "-m", "op"]); 2234 let mut opts = fx.opts(); 2235 opts.operator = true; 2236 let o = run(&fx, &opts); 2237 assert_eq!((o.verdict, o.reason.as_str()), (Verdict::Pass, "")); 2238 assert!(fx.marker().exists(), "the gate ran"); 2239 assert!(o.receipt_digest.is_some(), "a receipt was written"); 2240 } 2241 2242 #[test] 2243 fn gb10_gate_without_the_hardware_is_blocked() { 2244 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2245 let o = run(&fx, &fx.opts()); 2246 assert_eq!( 2247 (o.verdict, o.reason.as_str()), 2248 (Verdict::BlockedHardware, "NO_GB10") 2249 ); 2250 assert!(!fx.marker().exists()); 2251 } 2252 2253 #[test] 2254 fn gb10_gate_is_refused_while_the_quiet_flag_exists() { 2255 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2256 let opts = gb10_opts(&fx); 2257 let flag = opts.gpu.quiet_flag.clone().unwrap(); 2258 fs::write(&flag, "hold: testing\n").unwrap(); 2259 let o = run(&fx, &opts); 2260 assert_eq!( 2261 (o.verdict, o.reason.as_str()), 2262 (Verdict::NotRun, "quiet_flag") 2263 ); 2264 assert!(!fx.marker().exists()); 2265 assert_eq!(fs::read_to_string(&flag).unwrap(), "hold: testing\n"); 2266 let r = read_json(&o.receipt_path.unwrap()); 2267 assert_eq!(r["core"]["reason"], "quiet_flag"); 2268 } 2269 2270 #[test] 2271 fn gb10_gate_is_refused_while_another_holder_has_the_lock() { 2272 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2273 let opts = gb10_opts(&fx); 2274 let held = acquire_gpu(&opts.gpu).unwrap(); 2275 let o = run(&fx, &opts); 2276 assert_eq!( 2277 (o.verdict, o.reason.as_str()), 2278 (Verdict::NotRun, "gpu_lock") 2279 ); 2280 assert!(!fx.marker().exists(), "a refused job must not run"); 2281 drop(held); 2282 let o = run(&fx, &opts); 2283 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2284 assert!(fx.marker().exists()); 2285 } 2286 2287 /// The machine's default GPU options (what `run`, `test` and the worker 2288 /// start from) with the lock paths moved to scratch: a holder that keeps 2289 /// the lock for a moment, as the live model server does around every 2290 /// request, must not make the gate NOT_RUN. Written against fields both 2291 /// the old and the new `GpuConfig` have, so it runs on either. 2292 #[test] 2293 fn gb10_gate_with_the_default_options_waits_out_a_brief_holder() { 2294 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2295 let mut opts = gb10_opts(&fx); 2296 let scratch = opts.gpu.clone(); 2297 opts.gpu = GpuConfig::detect(); 2298 opts.gpu.lock_path = scratch.lock_path; 2299 opts.gpu.proof_lock_path = None; 2300 opts.gpu.quiet_flag = scratch.quiet_flag; 2301 opts.gpu.proc_dir = scratch.proc_dir; 2302 // The memory check has its own tests below; this one is about the lock wait. 2303 opts.gpu.mem_need_mb = 0; 2304 let held = acquire_gpu(&GpuConfig::rooted_at(fx.scratch.path())).unwrap(); 2305 let holder = std::thread::spawn(move || { 2306 std::thread::sleep(Duration::from_millis(1500)); 2307 drop(held); 2308 }); 2309 let o = run(&fx, &opts); 2310 holder.join().unwrap(); 2311 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2312 assert!(fx.marker().exists()); 2313 } 2314 2315 #[test] 2316 fn gb10_gate_records_the_wait_and_runs_when_the_holder_lets_go() { 2317 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2318 let mut opts = gb10_opts(&fx); 2319 opts.gpu.wait = GpuWait::Bounded(Duration::from_secs(20)); 2320 let held = acquire_gpu(&GpuConfig::rooted_at(fx.scratch.path())).unwrap(); 2321 // Let go 300 ms after the kernel shows the gate queued behind us, so 2322 // the wait is real however long the gate takes to reach the lock. 2323 let lock = opts.gpu.lock_path.clone(); 2324 let holder = std::thread::spawn(move || { 2325 let t0 = std::time::Instant::now(); 2326 while !queued_on(&lock) && t0.elapsed() < Duration::from_secs(15) { 2327 std::thread::sleep(Duration::from_millis(5)); 2328 } 2329 let seen = queued_on(&lock); 2330 std::thread::sleep(Duration::from_millis(300)); 2331 drop(held); 2332 seen 2333 }); 2334 let o = run(&fx, &opts); 2335 assert!(holder.join().unwrap(), "the gate never queued on the lock"); 2336 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2337 let r = read_json(&o.receipt_path.unwrap()); 2338 let w = &r["volatile"]["gpu_wait"]; 2339 assert_eq!(w["mode"], "bounded"); 2340 assert_eq!(w["bound_ms"], 20_000); 2341 assert_eq!(w["acquired"], true); 2342 let waited = w["waited_ms"].as_u64().unwrap(); 2343 assert!((250..20_000).contains(&waited), "waited {waited} ms"); 2344 } 2345 2346 #[test] 2347 fn gb10_gate_held_past_the_bound_is_not_run_with_the_wait_recorded() { 2348 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2349 let mut opts = gb10_opts(&fx); 2350 opts.gpu.wait = GpuWait::Bounded(Duration::from_millis(400)); 2351 let held = acquire_gpu(&GpuConfig::rooted_at(fx.scratch.path())).unwrap(); 2352 let o = run(&fx, &opts); 2353 assert_eq!( 2354 (o.verdict, o.reason.as_str()), 2355 (Verdict::NotRun, "gpu_lock") 2356 ); 2357 assert!(!fx.marker().exists(), "a refused job must not run"); 2358 let r = read_json(&o.receipt_path.unwrap()); 2359 assert_eq!(r["core"]["reason"], "gpu_lock"); 2360 let w = &r["volatile"]["gpu_wait"]; 2361 assert_eq!(w["mode"], "bounded"); 2362 assert_eq!(w["bound_ms"], 400); 2363 assert_eq!(w["acquired"], false); 2364 assert!(w["waited_ms"].as_u64().unwrap() >= 400, "{w}"); 2365 // The waiter given up on must hand the lock back once the holder 2366 // lets go, so the next gate gets it. 2367 drop(held); 2368 opts.gpu.wait = GpuWait::Bounded(Duration::from_secs(20)); 2369 let o = run(&fx, &opts); 2370 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2371 } 2372 2373 /// A gb10 gate whose memory reading is short is NOT_RUN `gpu_mem` with the 2374 /// numbers in the receipt, and its job never starts (retryable, nothing judged). 2375 #[test] 2376 fn gb10_gate_short_of_memory_is_not_run_gpu_mem_and_does_not_start() { 2377 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2378 let mut opts = gb10_opts(&fx); 2379 write_file( 2380 fx.scratch.path(), 2381 "meminfo", 2382 "MemAvailable: 40960 kB\n", 2383 false, 2384 ); 2385 opts.gpu.meminfo = fx.scratch.path().join("meminfo"); 2386 opts.gpu.mem_need_mb = 100; 2387 opts.gpu.mem_wait = Duration::from_millis(300); 2388 let o = run(&fx, &opts); 2389 assert_eq!( 2390 (o.verdict, o.reason.as_str()), 2391 (Verdict::NotRun, "gpu_mem"), 2392 "{}", 2393 o.reason 2394 ); 2395 assert!(!fx.marker().exists(), "a memory-short job must not run"); 2396 let r = read_json(&o.receipt_path.unwrap()); 2397 assert_eq!(r["core"]["reason"], "gpu_mem"); 2398 let w = &r["volatile"]["gpu_wait"]; 2399 assert_eq!(w["acquired"], false); 2400 assert_eq!(w["mem_free_mb"], 40); 2401 assert_eq!(w["mem_need_mb"], 100); 2402 // The locks went back: the same gate with enough memory runs. 2403 write_file( 2404 fx.scratch.path(), 2405 "meminfo", 2406 "MemAvailable: 204800 kB\n", 2407 false, 2408 ); 2409 let o = run(&fx, &opts); 2410 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2411 assert!(fx.marker().exists()); 2412 } 2413 2414 #[test] 2415 fn gb10_gate_with_enough_memory_runs_and_records_the_reading() { 2416 let fx = gb10_fixture(TOUCH_MARKER, "20s"); 2417 let mut opts = gb10_opts(&fx); 2418 write_file( 2419 fx.scratch.path(), 2420 "meminfo", 2421 "MemAvailable: 204800 kB\n", 2422 false, 2423 ); 2424 opts.gpu.meminfo = fx.scratch.path().join("meminfo"); 2425 opts.gpu.mem_need_mb = 100; 2426 let o = run(&fx, &opts); 2427 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2428 assert!(fx.marker().exists()); 2429 let r = read_json(&o.receipt_path.unwrap()); 2430 let w = &r["volatile"]["gpu_wait"]; 2431 assert_eq!(w["acquired"], true); 2432 assert_eq!(w["mem_free_mb"], 200); 2433 } 2434 2435 /// A gate that starts with enough memory and then fails is a real FAIL, 2436 /// never NOT_RUN: the memory check only decides whether the job starts. 2437 #[test] 2438 fn gb10_gate_that_fails_after_it_starts_stays_fail() { 2439 let fx = gb10_fixture("#!/bin/sh\nexit 1\n", "20s"); 2440 let mut opts = gb10_opts(&fx); 2441 write_file( 2442 fx.scratch.path(), 2443 "meminfo", 2444 "MemAvailable: 204800 kB\n", 2445 false, 2446 ); 2447 opts.gpu.meminfo = fx.scratch.path().join("meminfo"); 2448 opts.gpu.mem_need_mb = 100; 2449 let o = run(&fx, &opts); 2450 assert_eq!(o.verdict, Verdict::Fail, "reason {}", o.reason); 2451 assert_ne!(o.reason, "gpu_mem"); 2452 } 2453 2454 #[test] 2455 fn host_gate_records_no_gpu_wait() { 2456 let fx = fixture(TOUCH_MARKER, 0, &[], "20s", ""); 2457 let o = run(&fx, &fx.opts()); 2458 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2459 let r = read_json(&o.receipt_path.unwrap()); 2460 assert_eq!(r["volatile"]["gpu_wait"], Value::Null); 2461 } 2462 2463 #[test] 2464 fn gb10_timeout_is_advisory_and_never_kills_the_job() { 2465 let fx = gb10_fixture("#!/bin/sh\nsleep 1\ntouch \"$1\"\n", "300ms"); 2466 let o = run(&fx, &gb10_opts(&fx)); 2467 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2468 assert!(fx.marker().exists(), "the job must be left to finish"); 2469 let r = read_json(&o.receipt_path.unwrap()); 2470 assert_eq!(r["volatile"]["timeout_exceeded"], true); 2471 } 2472 2473 /// `(gate id, depends_on ids separated by spaces, requires, script)`. 2474 type GateSpec = (&'static str, &'static str, &'static str, String); 2475 2476 fn graph_gate_text(id: &str, deps: &str, requires: &str) -> String { 2477 let dep_block = if deps.trim().is_empty() { 2478 String::new() 2479 } else { 2480 format!( 2481 "depends_on:\n{}", 2482 deps.split_whitespace() 2483 .map(|d| format!(" - {d}\n")) 2484 .collect::() 2485 ) 2486 }; 2487 format!( 2488 "gate: {id}\nmanifest_version: 1\nowner: t\nrequires:\n - {requires}\nrun:\n exec: tools/{id}.sh\n args: []\nexpects:\n exit: 0\n observe: []\n verdict: PASS\ntimeout: 20s\n{dep_block}" 2489 ) 2490 } 2491 2492 /// Script that appends `ran-` to the shared log and exits with `exit`. 2493 fn logging(id: &str, exit: i32) -> String { 2494 format!("#!/bin/sh\necho ran-{id} >> \"@S@/log\"\nexit {exit}\n") 2495 } 2496 2497 /// Script that logs `start-`, takes a moment, then logs `end-`. 2498 fn slow(id: &str) -> String { 2499 format!( 2500 "#!/bin/sh\necho start-{id} >> \"@S@/log\"\nsleep 0.2\necho end-{id} >> \"@S@/log\"\n" 2501 ) 2502 } 2503 2504 /// Script that proves another job is running at the same time: it waits 2505 /// (at most about ten seconds) for the other script's start marker. 2506 fn rendezvous(me: &str, other: &str) -> String { 2507 format!( 2508 "#!/bin/sh\ntouch \"@S@/started-{me}\"\ni=0\nwhile [ ! -f \"@S@/started-{other}\" ] && [ $i -lt 100 ]; do sleep 0.1; i=$((i+1)); done\nif [ -f \"@S@/started-{other}\" ]; then touch \"@S@/saw-{me}\"; fi\n" 2509 ) 2510 } 2511 2512 struct Gfx { 2513 repo: TempDir, 2514 ev: TempDir, 2515 scratch: TempDir, 2516 } 2517 2518 /// A repository with one gate (tests/.gate) and script 2519 /// (tools/.sh) per entry; `@S@` in a script is the scratch directory. 2520 fn gfx(gates: &[GateSpec]) -> Gfx { 2521 gfx_with(gates, "", &[]) 2522 } 2523 2524 /// `inputs` block of a gate that declares it builds in the target dir. 2525 const CARGO_INPUTS: &str = "inputs:\n - Cargo.lock\n"; 2526 2527 /// `gfx` with `extra` appended to every manifest and `files` added to 2528 /// the repository (a `Cargo.lock` for the cargo gates). 2529 fn gfx_with(gates: &[GateSpec], extra: &str, more: &[(&str, &str)]) -> Gfx { 2530 let scratch = TempDir::new("gscratch"); 2531 let s = scratch.path().to_str().unwrap().to_string(); 2532 let mut files: Vec<(String, String, bool)> = Vec::new(); 2533 for (id, deps, requires, script) in gates { 2534 files.push((format!("tools/{id}.sh"), script.replace("@S@", &s), true)); 2535 files.push(( 2536 format!("tests/{id}.gate"), 2537 format!("{}{extra}", graph_gate_text(id, deps, requires)), 2538 false, 2539 )); 2540 } 2541 for (p, c) in more { 2542 files.push((p.to_string(), c.to_string(), false)); 2543 } 2544 let refs: Vec<(&str, &str, bool)> = files 2545 .iter() 2546 .map(|(p, c, x)| (p.as_str(), c.as_str(), *x)) 2547 .collect(); 2548 let repo = init_repo("grepo", &refs); 2549 Gfx { 2550 repo, 2551 ev: TempDir::new("gev"), 2552 scratch, 2553 } 2554 } 2555 2556 impl Gfx { 2557 fn gate_path(&self, id: &str) -> PathBuf { 2558 self.repo.path().join(format!("tests/{id}.gate")) 2559 } 2560 2561 fn opts(&self) -> Options { 2562 let mut o = Options::new(self.ev.path().join("out")); 2563 o.kill_grace = Duration::from_millis(300); 2564 o.hardware = Hardware { 2565 gb10_present: false, 2566 qemu_available: false, 2567 }; 2568 o.gpu = GpuConfig::rooted_at(self.scratch.path()); 2569 o.pool_sizes = PoolSizes { host: 2, qemu: 1 }; 2570 o 2571 } 2572 2573 fn graph(&self) -> Graph { 2574 crate::graph::load(self.repo.path()).unwrap() 2575 } 2576 2577 fn campaign(&self, opts: &Options) -> Campaign { 2578 let g = self.graph(); 2579 let all: BTreeSet = (0..g.len()).collect(); 2580 run_graph(self.repo.path(), &g, &all, opts).unwrap() 2581 } 2582 2583 fn log(&self) -> Vec { 2584 fs::read_to_string(self.scratch.path().join("log")) 2585 .unwrap_or_default() 2586 .lines() 2587 .map(|l| l.to_string()) 2588 .collect() 2589 } 2590 } 2591 2592 fn outcome<'a>(c: &'a Campaign, id: &str) -> &'a Outcome { 2593 &c.results 2594 .iter() 2595 .find(|(g, _)| g == id) 2596 .expect("gate is in the campaign") 2597 .1 2598 } 2599 2600 fn verdict_and_reason<'a>(c: &'a Campaign, id: &str) -> (Verdict, &'a str) { 2601 let o = outcome(c, id); 2602 (o.verdict, o.reason.as_str()) 2603 } 2604 2605 #[test] 2606 fn a_chain_runs_in_order_and_each_receipt_names_its_dependencies() { 2607 let fx = gfx(&[ 2608 ("G-A", "", "host", logging("G-A", 0)), 2609 ("G-B", "G-A", "host", logging("G-B", 0)), 2610 ("G-C", "G-B", "host", logging("G-C", 0)), 2611 ]); 2612 let c = fx.campaign(&fx.opts()); 2613 assert_eq!(c.exit_code(), 0); 2614 let ids: Vec<&str> = c.results.iter().map(|(g, _)| g.as_str()).collect(); 2615 assert_eq!(ids, vec!["G-A", "G-B", "G-C"]); 2616 assert!(c.results.iter().all(|(_, o)| o.verdict == Verdict::Pass)); 2617 assert_eq!(fx.log(), vec!["ran-G-A", "ran-G-B", "ran-G-C"]); 2618 let a = outcome(&c, "G-A").receipt_digest.clone().unwrap(); 2619 let ra = read_json(outcome(&c, "G-A").receipt_path.as_ref().unwrap()); 2620 let rb = read_json(outcome(&c, "G-B").receipt_path.as_ref().unwrap()); 2621 assert_eq!(ra["core"]["dependencies"], json!([])); 2622 assert_eq!( 2623 rb["core"]["dependencies"], 2624 json!([{ "gate": "G-A", "receipt": a }]) 2625 ); 2626 assert!(rb["volatile"]["pool_wait_ms"].is_u64()); 2627 } 2628 2629 #[test] 2630 fn a_failed_dependency_makes_dependents_not_run_with_the_reason_recorded() { 2631 let fx = gfx(&[ 2632 ("G-A", "", "host", logging("G-A", 1)), 2633 ("G-B", "G-A", "host", logging("G-B", 0)), 2634 ("G-C", "G-B", "host", logging("G-C", 0)), 2635 ("G-D", "", "host", logging("G-D", 0)), 2636 ]); 2637 let c = fx.campaign(&fx.opts()); 2638 assert_eq!(verdict_and_reason(&c, "G-A"), (Verdict::Fail, "rc_nonzero")); 2639 assert_eq!( 2640 verdict_and_reason(&c, "G-B"), 2641 (Verdict::NotRun, "DEP_NOT_PASS:G-A") 2642 ); 2643 assert_eq!( 2644 verdict_and_reason(&c, "G-C"), 2645 (Verdict::NotRun, "DEP_NOT_PASS:G-B") 2646 ); 2647 assert_eq!(verdict_and_reason(&c, "G-D"), (Verdict::Pass, "")); 2648 assert_eq!(c.exit_code(), 1); 2649 let mut log = fx.log(); 2650 log.sort(); 2651 assert_eq!(log, vec!["ran-G-A", "ran-G-D"], "B and C must not run"); 2652 let a = outcome(&c, "G-A").receipt_digest.clone().unwrap(); 2653 let rb = read_json(outcome(&c, "G-B").receipt_path.as_ref().unwrap()); 2654 assert_eq!(rb["core"]["derived_verdict"], "NOT_RUN"); 2655 assert_eq!(rb["core"]["reason"], "DEP_NOT_PASS:G-A"); 2656 assert_eq!(rb["core"]["exit_status"], Value::Null); 2657 assert_eq!( 2658 rb["core"]["dependencies"], 2659 json!([{ "gate": "G-A", "receipt": a }]) 2660 ); 2661 } 2662 2663 #[test] 2664 fn a_blocked_dependency_blocks_its_dependents_the_same_way() { 2665 let fx = gfx(&[ 2666 ("G-A", "", "gb10", logging("G-A", 0)), 2667 ("G-B", "G-A", "host", logging("G-B", 0)), 2668 ("G-C", "G-B", "host", logging("G-C", 0)), 2669 ]); 2670 let c = fx.campaign(&fx.opts()); 2671 assert_eq!( 2672 verdict_and_reason(&c, "G-A"), 2673 (Verdict::BlockedHardware, "NO_GB10") 2674 ); 2675 assert_eq!( 2676 verdict_and_reason(&c, "G-B"), 2677 (Verdict::BlockedHardware, "DEP_BLOCKED:G-A") 2678 ); 2679 assert_eq!( 2680 verdict_and_reason(&c, "G-C"), 2681 (Verdict::BlockedHardware, "DEP_BLOCKED:G-B") 2682 ); 2683 assert!(fx.log().is_empty(), "nothing may run"); 2684 assert_eq!(c.exit_code(), 3); 2685 } 2686 2687 /// `log` holds `start-X, end-X` pairs with no interleaving. 2688 fn assert_serial(log: &[String], what: &str) { 2689 assert_eq!(log.len() % 2, 0, "{what}: {log:?}"); 2690 for pair in log.chunks(2) { 2691 let id = pair[0].strip_prefix("start-").unwrap_or("?"); 2692 assert_eq!(pair[1], format!("end-{id}"), "{what} overlapped: {log:?}"); 2693 } 2694 } 2695 2696 /// Without a `CARGO_TARGET_DIR` the gates of one run still share the 2697 /// worktree's own `target/`, so they are serialised on that path. 2698 #[test] 2699 fn gates_without_a_target_dir_serialise_on_the_worktree_target() { 2700 let fx = gfx(&[ 2701 ("G-A", "", "host", slow("G-A")), 2702 ("G-B", "", "host", slow("G-B")), 2703 ]); 2704 let mut opts = fx.opts(); 2705 opts.target_lock_dir = fx.scratch.path().join("locks"); 2706 let c = fx.campaign(&opts); 2707 assert_eq!(c.exit_code(), 0); 2708 let log = fx.log(); 2709 assert_eq!(log.len(), 4, "{log:?}"); 2710 assert_serial(&log, "gates sharing the worktree target"); 2711 let lock = crate::resources::target_lock_path( 2712 &opts.target_lock_dir, 2713 &resolve(fx.repo.path()).join("target"), 2714 ); 2715 assert!(lock.exists(), "lock {} never taken", lock.display()); 2716 } 2717 2718 /// The gate that waits for the target dir the other holds says so in its 2719 /// receipt (`target_wait_ms`), so the wait never reads as test time; a 2720 /// run outside a batch takes no batch slot (`batch_wait_ms` 0). 2721 #[test] 2722 fn a_target_dir_wait_is_recorded_apart_from_the_run() { 2723 let fx = gfx(&[ 2724 ("G-A", "", "host", slow("G-A")), 2725 ("G-B", "", "host", slow("G-B")), 2726 ]); 2727 let mut opts = fx.opts(); 2728 opts.target_lock_dir = fx.scratch.path().join("locks"); 2729 let c = fx.campaign(&opts); 2730 assert_eq!(c.exit_code(), 0); 2731 let second = fx.log()[2].trim_start_matches("start-").to_string(); 2732 let v = |id: &str| { 2733 read_json(outcome(&c, id).receipt_path.as_ref().unwrap())["volatile"].clone() 2734 }; 2735 let (late, early) = if second == "G-A" { 2736 (v("G-A"), v("G-B")) 2737 } else { 2738 (v("G-B"), v("G-A")) 2739 }; 2740 let waited = late["target_wait_ms"].as_u64().unwrap(); 2741 assert!( 2742 waited >= 150, 2743 "second gate waited {waited} ms for the target dir" 2744 ); 2745 assert!(late["duration_ms"].as_u64().unwrap() >= waited); 2746 assert!(early["target_wait_ms"].as_u64().unwrap() < 150); 2747 assert_eq!(late["batch_wait_ms"], json!(0)); 2748 } 2749 2750 /// `target_lock: none` (L335, G3-ci-judge-2): two such gates of one head 2751 /// run side by side instead of queueing on the target dir. 2752 #[test] 2753 fn target_lock_none_gates_do_not_queue_on_the_target_dir() { 2754 let fx = gfx_with( 2755 &[ 2756 ("G-A", "", "host", slow("G-A")), 2757 ("G-B", "", "host", slow("G-B")), 2758 ], 2759 "target_lock: none\n", 2760 &[], 2761 ); 2762 let mut opts = fx.opts(); 2763 opts.target_lock_dir = fx.scratch.path().join("locks"); 2764 let c = fx.campaign(&opts); 2765 assert_eq!(c.exit_code(), 0); 2766 let log = fx.log(); 2767 assert!( 2768 log[0].starts_with("start-") && log[1].starts_with("start-"), 2769 "both started before either ended: {log:?}" 2770 ); 2771 for id in ["G-A", "G-B"] { 2772 let v = read_json(outcome(&c, id).receipt_path.as_ref().unwrap())["volatile"].clone(); 2773 assert!( 2774 v["target_wait_ms"].as_u64().unwrap() < 150, 2775 "{id} waited: {v}" 2776 ); 2777 } 2778 } 2779 2780 /// A gate may call cargo without naming `Cargo.toml` among its inputs 2781 /// (SC-INQUISITOR builds spark-inquisitor that way), so the rule is not 2782 /// "cargo gates": every gate given a `CARGO_TARGET_DIR` holds it. 2783 #[test] 2784 fn every_gate_given_a_target_dir_is_serialised() { 2785 let cargo_user = |id: &str| { 2786 format!( 2787 "#!/bin/sh\necho start-{id} >> \"@S@/log\"\n\"${{CARGO:-cargo}}\" --version >/dev/null\nsleep 0.2\necho end-{id} >> \"@S@/log\"\n" 2788 ) 2789 }; 2790 let fx = gfx(&[ 2791 ("G-A", "", "host", cargo_user("G-A")), 2792 ("G-B", "", "host", cargo_user("G-B")), 2793 ]); 2794 let mut opts = fx.opts(); 2795 opts.cargo_target_dir = Some(fx.scratch.path().join("target")); 2796 opts.target_lock_dir = fx.scratch.path().join("locks"); 2797 let c = fx.campaign(&opts); 2798 assert_eq!(c.exit_code(), 0); 2799 let log = fx.log(); 2800 assert_eq!(log.len(), 4, "{log:?}"); 2801 assert_serial(&log, "undeclared cargo users"); 2802 } 2803 2804 /// Two cargo gates of one head share `CARGO_TARGET_DIR`. Run at the same 2805 /// time, one relinks a test binary the other is executing (sc fix/521: 2806 /// SC-AGENT-PREFLIGHT relinked `aien_inference_abi-*` under SC-TEST, which 2807 /// then failed with `current_exe: NotFound`). The runner must hold the 2808 /// target dir for one cargo gate at a time, whatever the pool allows. 2809 #[test] 2810 fn cargo_gates_sharing_a_target_dir_never_overlap() { 2811 let fx = gfx_with( 2812 &[ 2813 ("C-A", "", "host", slow("C-A")), 2814 ("C-B", "", "host", slow("C-B")), 2815 ], 2816 CARGO_INPUTS, 2817 &[("Cargo.lock", "# lock\n")], 2818 ); 2819 let mut opts = fx.opts(); 2820 opts.cargo_target_dir = Some(fx.scratch.path().join("target")); 2821 opts.target_lock_dir = fx.scratch.path().join("locks"); 2822 let c = fx.campaign(&opts); 2823 assert_eq!(c.exit_code(), 0); 2824 let log = fx.log(); 2825 assert_eq!(log.len(), 4, "{log:?}"); 2826 let first = log[0].trim_start_matches("start-").to_string(); 2827 let second = if first == "C-A" { "C-B" } else { "C-A" }; 2828 assert_eq!( 2829 log, 2830 vec![ 2831 format!("start-{first}"), 2832 format!("end-{first}"), 2833 format!("start-{second}"), 2834 format!("end-{second}"), 2835 ], 2836 "the two cargo gates overlapped in one target dir" 2837 ); 2838 let lock = crate::resources::target_lock_path( 2839 &opts.target_lock_dir, 2840 &fx.scratch.path().join("target"), 2841 ); 2842 assert!( 2843 lock.exists(), 2844 "the lock file {} was never taken", 2845 lock.display() 2846 ); 2847 } 2848 2849 /// The lock is per target dir: gates given different target dirs still 2850 /// run at the same time. 2851 #[test] 2852 fn gates_with_different_target_dirs_run_at_the_same_time() { 2853 let fx = gfx(&[ 2854 ("G-A", "", "host", rendezvous("a", "b")), 2855 ("G-B", "", "host", rendezvous("b", "a")), 2856 ]); 2857 let mut opts = fx.opts(); 2858 opts.target_lock_dir = fx.scratch.path().join("locks"); 2859 let g = fx.graph(); 2860 let (a, b) = (g.index_of("G-A").unwrap(), g.index_of("G-B").unwrap()); 2861 thread::scope(|s| { 2862 for (i, dir) in [(a, "ta"), (b, "tb")] { 2863 let mut o = Options { 2864 cargo_target_dir: Some(fx.scratch.path().join(dir)), 2865 ..fx.opts() 2866 }; 2867 o.target_lock_dir = opts.target_lock_dir.clone(); 2868 let sel: BTreeSet = [i].into_iter().collect(); 2869 let (g, root) = (&g, fx.repo.path()); 2870 s.spawn(move || run_graph(root, g, &sel, &o).unwrap()); 2871 } 2872 }); 2873 assert!(fx.scratch.path().join("saw-a").exists(), "A never saw B"); 2874 assert!(fx.scratch.path().join("saw-b").exists(), "B never saw A"); 2875 } 2876 2877 #[test] 2878 fn a_pool_of_one_runs_gates_one_at_a_time() { 2879 let fx = gfx(&[ 2880 ("G-A", "", "host", slow("G-A")), 2881 ("G-B", "", "host", slow("G-B")), 2882 ("G-C", "", "host", slow("G-C")), 2883 ]); 2884 let mut opts = fx.opts(); 2885 opts.pool_sizes = PoolSizes { host: 1, qemu: 1 }; 2886 let c = fx.campaign(&opts); 2887 assert_eq!(c.exit_code(), 0); 2888 let log = fx.log(); 2889 assert_eq!(log.len(), 6, "{log:?}"); 2890 for pair in log.chunks(2) { 2891 assert!(pair[0].starts_with("start-"), "{log:?}"); 2892 assert_eq!(pair[1], pair[0].replacen("start-", "end-", 1), "{log:?}"); 2893 } 2894 } 2895 2896 #[test] 2897 fn gb10_and_host_gates_run_together_and_record_their_pools() { 2898 let fx = gfx(&[ 2899 ("G-A", "", "gb10", logging("G-A", 0)), 2900 ("G-B", "", "host", logging("G-B", 0)), 2901 ]); 2902 let mut opts = fx.opts(); 2903 opts.hardware.gb10_present = true; 2904 let c = fx.campaign(&opts); 2905 assert_eq!(c.exit_code(), 0); 2906 let r = read_json(outcome(&c, "G-A").receipt_path.as_ref().unwrap()); 2907 assert_eq!(r["volatile"]["pool"], "gb10"); 2908 let r = read_json(outcome(&c, "G-B").receipt_path.as_ref().unwrap()); 2909 assert_eq!(r["volatile"]["pool"], "host"); 2910 } 2911 2912 #[test] 2913 fn a_held_gpu_lock_refuses_the_gb10_gate_and_its_dependents_do_not_run() { 2914 let fx = gfx(&[ 2915 ("G-A", "", "gb10", logging("G-A", 0)), 2916 ("G-B", "G-A", "host", logging("G-B", 0)), 2917 ]); 2918 let mut opts = fx.opts(); 2919 opts.hardware.gb10_present = true; 2920 let held = acquire_gpu(&opts.gpu).unwrap(); 2921 let c = fx.campaign(&opts); 2922 drop(held); 2923 assert_eq!(verdict_and_reason(&c, "G-A"), (Verdict::NotRun, "gpu_lock")); 2924 assert_eq!( 2925 verdict_and_reason(&c, "G-B"), 2926 (Verdict::NotRun, "DEP_NOT_PASS:G-A") 2927 ); 2928 assert!(fx.log().is_empty()); 2929 assert_eq!(c.exit_code(), 2); 2930 } 2931 2932 #[test] 2933 fn run_gate_reads_dependency_receipts_from_the_store() { 2934 let fx = gfx(&[ 2935 ("G-A", "", "host", logging("G-A", 0)), 2936 ("G-B", "G-A", "host", logging("G-B", 0)), 2937 ]); 2938 let opts = fx.opts(); 2939 let run_one = |id: &str| run_gate(fx.repo.path(), &fx.gate_path(id), &opts).unwrap(); 2940 let o = run_one("G-B"); 2941 assert_eq!( 2942 (o.verdict, o.reason.as_str()), 2943 (Verdict::NotRun, "DEP_NOT_PASS:G-A") 2944 ); 2945 assert!(fx.log().is_empty(), "no receipt for A, so B must not run"); 2946 assert_eq!(run_one("G-A").verdict, Verdict::Pass); 2947 let o = run_one("G-B"); 2948 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 2949 assert_eq!(fx.log(), vec!["ran-G-A", "ran-G-B"]); 2950 // A receipt for an older commit does not count. 2951 git( 2952 fx.repo.path(), 2953 &["commit", "-q", "--allow-empty", "-m", "next"], 2954 ); 2955 let o = run_one("G-B"); 2956 assert_eq!( 2957 (o.verdict, o.reason.as_str()), 2958 (Verdict::NotRun, "DEP_NOT_PASS:G-A") 2959 ); 2960 assert_eq!(fx.log().len(), 2); 2961 } 2962 2963 #[test] 2964 fn a_dependency_outside_the_selection_comes_from_the_store() { 2965 let fx = gfx(&[ 2966 ("G-A", "", "host", logging("G-A", 0)), 2967 ("G-B", "G-A", "host", logging("G-B", 0)), 2968 ]); 2969 let opts = fx.opts(); 2970 let g = fx.graph(); 2971 let only_b: BTreeSet = [g.index_of("G-B").unwrap()].into_iter().collect(); 2972 let c = run_graph(fx.repo.path(), &g, &only_b, &opts).unwrap(); 2973 assert_eq!(c.results.len(), 1); 2974 assert_eq!( 2975 verdict_and_reason(&c, "G-B"), 2976 (Verdict::NotRun, "DEP_NOT_PASS:G-A") 2977 ); 2978 let a = run_gate(fx.repo.path(), &fx.gate_path("G-A"), &opts).unwrap(); 2979 assert_eq!(a.verdict, Verdict::Pass); 2980 let c = run_graph(fx.repo.path(), &g, &only_b, &opts).unwrap(); 2981 assert_eq!(verdict_and_reason(&c, "G-B"), (Verdict::Pass, "")); 2982 } 2983 2984 #[test] 2985 fn an_empty_selection_is_an_empty_campaign() { 2986 let fx = gfx(&[("G-A", "", "host", logging("G-A", 0))]); 2987 let g = fx.graph(); 2988 let c = run_graph(fx.repo.path(), &g, &BTreeSet::new(), &fx.opts()).unwrap(); 2989 assert!(c.results.is_empty()); 2990 assert_eq!(c.exit_code(), 0); 2991 } 2992 2993 #[test] 2994 fn a_fatal_error_stops_the_campaign_instead_of_hanging() { 2995 let fx = gfx(&[ 2996 ("G-A", "", "host", logging("G-A", 0)), 2997 ("G-B", "G-A", "host", logging("G-B", 0)), 2998 ("G-C", "", "host", logging("G-C", 0)), 2999 ]); 3000 let blocker = fx.scratch.path().join("not-a-directory"); 3001 fs::write(&blocker, "x").unwrap(); 3002 let mut opts = fx.opts(); 3003 opts.evidence_dir = blocker.join("out"); 3004 let g = fx.graph(); 3005 let all: BTreeSet = (0..g.len()).collect(); 3006 match run_graph(fx.repo.path(), &g, &all, &opts) { 3007 Err(RunError::Fatal(_)) => {} 3008 other => panic!("expected a fatal error, got {other:?}"), 3009 } 3010 } 3011 3012 #[test] 3013 fn default_evidence_dir_is_named_after_the_repository() { 3014 let p = default_evidence_dir(Path::new("/some/where/my-repo")); 3015 if let Some(p) = p { 3016 assert!(p.ends_with("workspace/evidence-out/my-repo"), "{p:?}"); 3017 } 3018 } 3019 3020 /// A repo whose gate names a bare program (no slash), resolved on PATH. 3021 fn bare_fixture(exec: &str) -> Fx { 3022 let scratch = TempDir::new("scratch"); 3023 let gate = gate_text(exec, &[], 0, &[], "20s", ""); 3024 let repo = init_repo( 3025 "repo", 3026 &[ 3027 ("tests/t.gate", gate.as_str(), false), 3028 ("README", "hello\n", false), 3029 ], 3030 ); 3031 Fx { 3032 repo, 3033 ev: TempDir::new("ev"), 3034 scratch, 3035 } 3036 } 3037 3038 #[test] 3039 fn exec_path_rules() { 3040 let fx = ok_fixture(); 3041 let root = fx.repo.path(); 3042 // A slash: repo-relative, present or not. 3043 assert_eq!( 3044 exec_path(root, "tools/run.sh"), 3045 Some(root.join("tools/run.sh")) 3046 ); 3047 assert_eq!(exec_path(root, "tools/missing.sh"), None); 3048 // No slash: the PATH, never the repository root. 3049 write_file(root, "true", "#!/bin/sh\nexit 1\n", true); 3050 let p = exec_path(root, "true").expect("true is on PATH"); 3051 assert_ne!(p, root.join("true")); 3052 assert!(p.is_absolute()); 3053 assert_eq!(exec_path(root, "aien-test-no-such-program-x"), None); 3054 } 3055 3056 #[test] 3057 fn bare_exec_runs_from_path() { 3058 let fx = bare_fixture("true"); 3059 let o = run(&fx, &fx.opts()); 3060 assert_eq!(o.verdict, Verdict::Pass, "reason {}", o.reason); 3061 let r = read_json(&o.receipt_path.unwrap()); 3062 assert_eq!(r["core"]["exit_status"], 0); 3063 assert!( 3064 r["core"]["binary_sha256"].is_string(), 3065 "the PATH program is hashed" 3066 ); 3067 } 3068 3069 #[test] 3070 fn bare_exec_not_on_path_is_missing_implementation() { 3071 let fx = bare_fixture("aien-test-no-such-program-x"); 3072 let o = run(&fx, &fx.opts()); 3073 assert_eq!( 3074 o.verdict, 3075 Verdict::MissingImplementation, 3076 "reason {}", 3077 o.reason 3078 ); 3079 } 3080 3081 #[test] 3082 fn escaping_exec_is_rejected_never_not_run() { 3083 for bad in ["../../usr/bin/env", "/usr/bin/env", "tools/../../bin/true"] { 3084 let fx = bare_fixture(bad); 3085 match run_gate(fx.repo.path(), &fx.manifest(), &fx.opts()) { 3086 Err(RunError::BadManifest(m)) => { 3087 assert!(m.contains("run.exec"), "{bad}: {m}") 3088 } 3089 other => panic!("{bad} must be a manifest reject, got {other:?}"), 3090 } 3091 } 3092 } 3093 }