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/plan.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 / plan.rs` 2098 lines ยท 75250 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 planner (ADR 0033 Decision 12; local pipeline amendments A1 and A4). 17 //! 18 //! `aien-test plan [--base REF]` reads two commits of the repository through 19 //! git objects, never through the working tree, so the same plan can be 20 //! recomputed later for a commit that is not checked out (`verify COMMIT` 21 //! does that to check the bundle's `graph_digest`). Only `plan` on a tree 22 //! with uncommitted changes adds those paths, and only with `--allow-dirty`. 23 //! 24 //! What selects a gate at HEAD: 25 //! - a changed path under one of its `inputs`, under a D3 implied input 26 //! (`tests//.gate` implies `src//.*` and 27 //! `tests//_test.*`), its own manifest file, or its golden file; 28 //! - a changed pin (`*.lock` whose content is one 40-hex line) in its inputs; 29 //! - crumb ancestry: the `.crumb` of every directory above a changed path is 30 //! read at HEAD, and the paths named by its `related` or `links` members 31 //! (if the file has them; today's schema has neither) count as changed; 32 //! - the always set (`.aien/always` at BASE, trust anchor A1): one gate id per 33 //! line, selected whatever changed, never excluded by path filtering. 34 //! 35 //! The selection is closed over `depends_on` (a dependency is never dropped) 36 //! and over dependents (a gate whose dependency changed gets a new check id 37 //! and must run again). 38 //! 39 //! Rules that stop a commit from passing: 40 //! - a changed path that no gate's inputs cover and that `.aien/unmapped-ok` 41 //! at BASE does not allow is UNMAPPED: the commit verdict is NOT_RUN with 42 //! reason UNMAPPED_PATH. Manifest files, `.crumb` files and the pipeline's 43 //! own configuration are always mapped (the next rule covers the latter); 44 //! - a change under `.aien/`, `tests/gates/`, `.github/workflows/`, 45 //! `.forgejo/` or `tools/aien-test/` blocks the commit (BLOCKED_OPERATOR, 46 //! PIPELINE_CONFIG_CHANGED) unless the operator passes `--operator`; 47 //! - a gate with `requires: operator` is Blocked (OPERATOR_STEP_PENDING) in 48 //! an automatic run and takes its normal section under `--operator`: the 49 //! operator starting the run by hand is what the manifest asks for; 50 //! - every gate that exists at BASE must exist at HEAD; a deleted gate gives 51 //! NOT_RUN with reason GATE_REMOVED. 52 //! 53 //! The commit verdict algebra (`judge`) is Decision 7 applied to the plan: a 54 //! required gate whose dependency has no receipt is NOT_RUN 55 //! (UNVERIFIED_DEPENDENCY), a FAIL propagates (DEPENDENCY_FAILED), and 56 //! nothing promotes NOT_RUN to PASS. ADVISORY gates never count. 57 //! 58 //! Full scope (`--full`, an Alpha qualification of a commit already on 59 //! main): every gate at HEAD is selected, exactly what `test ./...` runs, so 60 //! every non-advisory gate is required, gb10 and Spark gates included. What 61 //! changed still labels the entries but selects nothing, and UNMAPPED_PATH 62 //! and GATE_REMOVED do not apply. PIPELINE_CONFIG_CHANGED and operator gates 63 //! keep their rules. The bundle signs the scope as `plan.scope`. 64 //! 65 //! Hardware identity: `cache_scope: hardware` gates need one and the ADR does 66 //! not define its content. When none is given the machine digest stands in, 67 //! and the plan says so. 68 69 use crate::bundle::{SCOPE_CHANGED, SCOPE_FULL}; 70 use crate::evidence::{canonical_digest, sha256_hex}; 71 use crate::graph::{self, Graph}; 72 use crate::identity::{self, Binding}; 73 use crate::manifest::{self, Exactness, Manifest}; 74 use crate::process; 75 use crate::verdict::Verdict; 76 use serde_json::{json, Value}; 77 use std::collections::{BTreeMap, BTreeSet}; 78 use std::path::{Path, PathBuf}; 79 use std::process::Command; 80 81 /// Paths whose change blocks a commit unless the operator says otherwise. 82 pub const PIPELINE_CONFIG: [&str; 7] = [ 83 ".aien/", 84 "tests/gates/", 85 ".github/workflows/", 86 ".forgejo/", 87 "tools/aien-test/", 88 "crumb.lock", 89 "tools/crumb/", 90 ]; 91 pub const ALWAYS_FILE: &str = ".aien/always"; 92 pub const UNMAPPED_OK_FILE: &str = ".aien/unmapped-ok"; 93 const SKIP_DIRS: [&str; 5] = [".git", "target", "build", "vendor", "node_modules"]; 94 95 /// What to plan. 96 #[derive(Debug, Clone)] 97 pub struct Request { 98 /// Any revision git resolves (`origin/main`, a sha, `HEAD~1`). 99 pub base: String, 100 pub head: String, 101 /// Uncommitted changes to add to the changed set (`plan --allow-dirty` 102 /// only; `verify` never sets them). 103 pub dirty: Vec, 104 /// `--operator`: a pipeline configuration change is allowed. 105 pub operator: bool, 106 /// `--full`: full scope (an Alpha qualification). Every gate at HEAD is 107 /// selected whatever changed, and the diff-only refusals (UNMAPPED_PATH, 108 /// GATE_REMOVED) do not apply. 109 pub full: bool, 110 pub compiler_identity: String, 111 pub flags: Vec, 112 /// Empty: the machine digest stands in (recorded in the plan). 113 pub hardware_identity: String, 114 /// Gates known to have a reusable receipt (filled by `probe_cached`). 115 pub cached: BTreeSet, 116 } 117 118 impl Request { 119 pub fn new(base: &str, head: &str) -> Request { 120 Request { 121 base: base.to_string(), 122 head: head.to_string(), 123 dirty: Vec::new(), 124 operator: false, 125 full: false, 126 compiler_identity: String::new(), 127 flags: Vec::new(), 128 hardware_identity: String::new(), 129 cached: BTreeSet::new(), 130 } 131 } 132 } 133 134 #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 135 pub enum Section { 136 Required, 137 Cached, 138 NeedsSpark, 139 NeedsGb10, 140 Advisory, 141 Blocked, 142 } 143 144 impl Section { 145 pub fn title(self) -> &'static str { 146 match self { 147 Section::Required => "Required", 148 Section::Cached => "Cached", 149 Section::NeedsSpark => "Needs Spark", 150 Section::NeedsGb10 => "Needs GB10", 151 Section::Advisory => "Advisory", 152 Section::Blocked => "Blocked", 153 } 154 } 155 156 pub const ALL: [Section; 6] = [ 157 Section::Required, 158 Section::Cached, 159 Section::NeedsSpark, 160 Section::NeedsGb10, 161 Section::Advisory, 162 Section::Blocked, 163 ]; 164 } 165 166 /// One selected gate. 167 #[derive(Debug, Clone, PartialEq, Eq)] 168 pub struct Entry { 169 pub gate: String, 170 pub check_id: String, 171 pub pool: String, 172 pub exactness: Exactness, 173 pub cache_scope: manifest::CacheScope, 174 /// False only for ADVISORY gates. 175 pub required: bool, 176 pub section: Section, 177 /// Why it is Blocked (empty otherwise). 178 pub reason: String, 179 pub depends_on: Vec, 180 pub always: bool, 181 /// Why it was selected: the first matching path, `always`, `dependency` 182 /// or `dependent`. 183 pub because: String, 184 } 185 186 #[derive(Debug, Clone)] 187 pub struct Plan { 188 pub base: String, 189 pub head: String, 190 pub changed: Vec, 191 /// Paths added by crumb ancestry (not themselves checked for mapping). 192 pub crumb_paths: Vec, 193 pub pins: Vec, 194 pub unmapped: Vec, 195 /// Gates at BASE that are gone at HEAD. 196 pub removed: Vec, 197 pub config_changed: Vec, 198 /// Set when the whole plan is blocked (PIPELINE_CONFIG_CHANGED). 199 pub blocked: Option, 200 /// Selected gates, dependencies first. 201 pub entries: Vec, 202 /// sha256 over the canonical `[{gate, check_id, depends_on}]` of the 203 /// selected gates, sorted by gate. 204 pub graph_digest: String, 205 pub notes: Vec, 206 /// The graph at HEAD (every gate, not only the selected ones). 207 pub graph: Graph, 208 /// Full scope (`Request::full`): signed into the bundle as 209 /// `plan.scope: "full"`, else `"changed"`. 210 pub full: bool, 211 } 212 213 impl Plan { 214 /// The bundle's `plan.scope` for this plan. 215 pub fn scope(&self) -> &'static str { 216 if self.full { 217 SCOPE_FULL 218 } else { 219 SCOPE_CHANGED 220 } 221 } 222 } 223 224 // ---------------------------------------------------------------- git 225 226 fn git(root: &Path, args: &[&str]) -> Result, String> { 227 let mut cmd = process::git_command(); 228 cmd.env("GIT_OPTIONAL_LOCKS", "0") 229 .arg("-C") 230 .arg(root) 231 .args(args); 232 let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run git: {e}"))?; 233 if !out.status.success() { 234 return Err(format!( 235 "git {} failed: {}", 236 args.join(" "), 237 String::from_utf8_lossy(&out.stderr).trim() 238 )); 239 } 240 Ok(out.stdout) 241 } 242 243 fn git_text(root: &Path, args: &[&str]) -> Result { 244 Ok(String::from_utf8_lossy(&git(root, args)?).into_owned()) 245 } 246 247 /// The 40-hex commit id of `rev`. 248 pub fn resolve(root: &Path, rev: &str) -> Result { 249 let s = git_text( 250 root, 251 &[ 252 "rev-parse", 253 "--verify", 254 "--quiet", 255 &format!("{rev}^{{commit}}"), 256 ], 257 ) 258 .map_err(|_| format!("cannot resolve {rev:?} to a commit"))?; 259 let s = s.trim().to_string(); 260 if is_hex(&s, 40) { 261 Ok(s) 262 } else { 263 Err(format!("{rev:?} is not a commit")) 264 } 265 } 266 267 /// The first of `candidates` that resolves. 268 pub fn resolve_first(root: &Path, candidates: &[&str]) -> Result { 269 for c in candidates { 270 if let Ok(s) = resolve(root, c) { 271 return Ok(s); 272 } 273 } 274 Err(format!("none of {candidates:?} resolves to a commit")) 275 } 276 277 /// The BASE the worker and `verify` plan `head` against: `base_ref` (then 278 /// `main`); when `head` is already on that line (the tip of main or an older 279 /// main commit) its first parent, so a push to main verifies what it changed 280 /// and both sides compute the same plan. The flag says whether `head` is on 281 /// the base line (the `main` trust class). 282 pub fn base_for(root: &Path, base_ref: &str, head: &str) -> Result<(String, bool), String> { 283 let first_parent = format!("{head}~1"); 284 let base = resolve_first(root, &[base_ref, "main", &first_parent])?; 285 let on_base = base == head || git(root, &["merge-base", "--is-ancestor", head, &base]).is_ok(); 286 if on_base { 287 Ok((resolve(root, &first_parent)?, true)) 288 } else { 289 Ok((base, false)) 290 } 291 } 292 293 fn is_hex(s: &str, n: usize) -> bool { 294 s.len() == n 295 && s.bytes() 296 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) 297 } 298 299 /// Every tracked file of `commit`: path to blob id. 300 pub fn tree_rows(root: &Path, commit: &str) -> Result, String> { 301 let out = git(root, &["ls-tree", "-r", "-z", commit])?; 302 let text = String::from_utf8(out).map_err(|_| "git ls-tree output is not UTF-8".to_string())?; 303 let mut rows = BTreeMap::new(); 304 for rec in text.split('\0').filter(|r| !r.is_empty()) { 305 let (meta, path) = rec 306 .split_once('\t') 307 .ok_or_else(|| format!("unparsable ls-tree record {rec:?}"))?; 308 let f: Vec<&str> = meta.split(' ').collect(); 309 if f.len() != 3 || f[2].len() != 40 { 310 return Err(format!("unparsable ls-tree record {rec:?}")); 311 } 312 if f[1] == "blob" { 313 rows.insert(path.to_string(), f[2].to_string()); 314 } 315 } 316 Ok(rows) 317 } 318 319 /// The bytes of `path` at `commit`, None when it does not exist there. 320 pub fn show(root: &Path, commit: &str, path: &str) -> Option> { 321 git(root, &["show", &format!("{commit}:{path}")]).ok() 322 } 323 324 /// `git diff --name-only BASE...HEAD`: paths changed on HEAD's side since the 325 /// merge base. 326 pub fn changed_between(root: &Path, base: &str, head: &str) -> Result, String> { 327 let out = git( 328 root, 329 &["diff", "--name-only", "-z", &format!("{base}...{head}")], 330 )?; 331 let text = String::from_utf8_lossy(&out); 332 let mut v: Vec = text 333 .split('\0') 334 .filter(|s| !s.is_empty()) 335 .map(|s| s.to_string()) 336 .collect(); 337 v.sort(); 338 v.dedup(); 339 Ok(v) 340 } 341 342 /// Paths with uncommitted changes, untracked files included. 343 pub fn uncommitted(root: &Path) -> Result, String> { 344 let out = git( 345 root, 346 &["status", "--porcelain=v1", "-z", "--untracked-files=all"], 347 )?; 348 let text = String::from_utf8_lossy(&out); 349 let mut v = Vec::new(); 350 let mut it = text.split('\0').filter(|s| !s.is_empty()); 351 while let Some(rec) = it.next() { 352 if rec.len() < 4 { 353 continue; 354 } 355 let xy = &rec[..2]; 356 v.push(rec[3..].to_string()); 357 if xy.starts_with('R') || xy.starts_with('C') { 358 // The original name follows as its own record. 359 if let Some(orig) = it.next() { 360 v.push(orig.to_string()); 361 } 362 } 363 } 364 v.sort(); 365 v.dedup(); 366 Ok(v) 367 } 368 369 fn lines_at(root: &Path, commit: &str, path: &str) -> Vec { 370 match show(root, commit, path) { 371 Some(bytes) => String::from_utf8_lossy(&bytes) 372 .lines() 373 .map(|l| l.trim().to_string()) 374 .filter(|l| !l.is_empty() && !l.starts_with('#')) 375 .collect(), 376 None => Vec::new(), 377 } 378 } 379 380 /// `.aien/always` at `commit` (A1: read from BASE, never the working tree). 381 pub fn always_set(root: &Path, commit: &str) -> Vec { 382 lines_at(root, commit, ALWAYS_FILE) 383 } 384 385 /// `.aien/unmapped-ok` at `commit`. 386 pub fn unmapped_ok(root: &Path, commit: &str) -> Vec { 387 lines_at(root, commit, UNMAPPED_OK_FILE) 388 } 389 390 // ---------------------------------------------------------------- gates at a commit 391 392 fn skipped(path: &str, rows: &BTreeMap) -> bool { 393 let parts: Vec<&str> = path.split('/').collect(); 394 let mut prefix = String::new(); 395 for dir in &parts[..parts.len() - 1] { 396 if SKIP_DIRS.contains(dir) { 397 return true; 398 } 399 if !prefix.is_empty() { 400 prefix.push('/'); 401 } 402 prefix.push_str(dir); 403 if rows.contains_key(&format!("{prefix}/.aien-test-ignore")) { 404 return true; 405 } 406 } 407 rows.contains_key(".aien-test-ignore") 408 } 409 410 /// The gate graph of `commit`, read from git objects, plus each gate's 411 /// manifest path relative to the root. 412 pub fn graph_at( 413 root: &Path, 414 commit: &str, 415 rows: &BTreeMap, 416 ) -> Result<(Graph, BTreeMap), String> { 417 let mut entries: Vec<(PathBuf, Manifest)> = Vec::new(); 418 let mut rel_of: BTreeMap = BTreeMap::new(); 419 for path in rows.keys() { 420 if !path.ends_with(".gate") || skipped(path, rows) { 421 continue; 422 } 423 let bytes = 424 show(root, commit, path).ok_or_else(|| format!("cannot read {path} at {commit}"))?; 425 let m = manifest::parse(&bytes).map_err(|e| format!("BAD_MANIFEST {path}: {}", e.0))?; 426 rel_of.insert(m.gate.clone(), path.clone()); 427 entries.push((root.join(path), m)); 428 } 429 let g = graph::build(entries).map_err(|e| e.to_string())?; 430 Ok((g, rel_of)) 431 } 432 433 /// Gate ids at `commit`, tolerating manifests that no longer parse (a broken 434 /// manifest at BASE is still a gate that must not vanish). 435 fn gate_ids_at(root: &Path, commit: &str, rows: &BTreeMap) -> BTreeSet { 436 let mut ids = BTreeSet::new(); 437 for path in rows.keys() { 438 if !path.ends_with(".gate") || skipped(path, rows) { 439 continue; 440 } 441 if let Some(bytes) = show(root, commit, path) { 442 if let Ok(m) = manifest::parse(&bytes) { 443 ids.insert(m.gate); 444 } else if let Some(id) = String::from_utf8_lossy(&bytes) 445 .lines() 446 .find_map(|l| l.strip_prefix("gate:").map(|v| v.trim().to_string())) 447 { 448 ids.insert(id); 449 } 450 } 451 } 452 ids 453 } 454 455 fn stem_of(path: &str) -> &str { 456 let name = path.rsplit('/').next().unwrap_or(path); 457 match name.rfind('.') { 458 Some(i) if i > 0 => &name[..i], 459 _ => name, 460 } 461 } 462 463 /// D3 implied inputs of a manifest at `rel`, from the tree rows. 464 pub fn implied_inputs(rel: &str, rows: &BTreeMap) -> Vec { 465 let mut out = Vec::new(); 466 let (dir, _) = rel.rsplit_once('/').unwrap_or(("", rel)); 467 let stem = stem_of(rel).to_string(); 468 let sub = match dir.strip_prefix("tests") { 469 Some(s) => s.trim_start_matches('/').to_string(), 470 None => return out, 471 }; 472 let join = |base: &str| { 473 if sub.is_empty() { 474 base.to_string() 475 } else { 476 format!("{base}/{sub}") 477 } 478 }; 479 for (base, want) in [ 480 (join("src"), stem.clone()), 481 (join("tests"), format!("{stem}_test")), 482 ] { 483 let prefix = format!("{base}/"); 484 for path in rows.keys() { 485 if let Some(name) = path.strip_prefix(&prefix) { 486 if !name.contains('/') && stem_of(name) == want { 487 out.push(path.clone()); 488 } 489 } 490 } 491 } 492 out 493 } 494 495 /// Every path a gate watches: explicit inputs, implied inputs, its manifest 496 /// and its golden file. 497 pub fn watched(m: &Manifest, rel: &str, rows: &BTreeMap) -> Vec { 498 let mut v: Vec = m 499 .inputs 500 .iter() 501 .map(|i| i.trim_end_matches('/').to_string()) 502 .collect(); 503 v.extend(implied_inputs(rel, rows)); 504 v.push(rel.to_string()); 505 if let Some(g) = &m.oracle.golden { 506 v.push(g.trim_end_matches('/').to_string()); 507 } 508 v.sort(); 509 v.dedup(); 510 v 511 } 512 513 /// `input` is `path` or a directory above it. 514 pub fn covers(input: &str, path: &str) -> bool { 515 let input = input.trim_end_matches('/'); 516 input.is_empty() || path == input || path.starts_with(&format!("{input}/")) 517 } 518 519 /// `*` matches any run of characters (slashes included); a pattern ending in 520 /// `/` matches everything under that directory; anything else is exact. 521 pub fn glob_match(pattern: &str, path: &str) -> bool { 522 if let Some(dir) = pattern.strip_suffix('/') { 523 return covers(dir, path); 524 } 525 fn walk(p: &[u8], s: &[u8]) -> bool { 526 match p.first() { 527 None => s.is_empty(), 528 Some(b'*') => (0..=s.len()).any(|i| walk(&p[1..], &s[i..])), 529 Some(c) => s.first() == Some(c) && walk(&p[1..], &s[1..]), 530 } 531 } 532 walk(pattern.as_bytes(), path.as_bytes()) 533 } 534 535 /// A pin: a `*.lock` file holding exactly one 40-hex commit id. 536 pub fn is_pin(path: &str, bytes: &[u8]) -> bool { 537 path.ends_with(".lock") && is_hex(String::from_utf8_lossy(bytes).trim(), 40) 538 } 539 540 fn strings_of(v: &Value) -> Vec { 541 let mut out = Vec::new(); 542 if let Some(arr) = v.as_array() { 543 for item in arr { 544 if let Some(s) = item.as_str() { 545 out.push(s.to_string()); 546 } else if let Some(o) = item.as_object() { 547 for k in ["path", "target", "dir", "id"] { 548 if let Some(s) = o.get(k).and_then(Value::as_str) { 549 out.push(s.to_string()); 550 break; 551 } 552 } 553 } 554 } 555 } 556 out 557 } 558 559 /// Crumb ancestry: for every directory above a changed path (the root 560 /// included), the paths its `.crumb` at `commit` names under `related` or 561 /// `links`. Today's crumb schema has neither member, so this is empty until 562 /// one appears; the hook is here so a change under a directory can pull in 563 /// what its crumb says belongs with it. 564 pub fn crumb_paths( 565 root: &Path, 566 commit: &str, 567 changed: &[String], 568 rows: &BTreeMap, 569 ) -> Vec { 570 let mut dirs: BTreeSet = BTreeSet::new(); 571 for p in changed { 572 let mut cur = p.as_str(); 573 dirs.insert(String::new()); 574 while let Some((parent, _)) = cur.rsplit_once('/') { 575 dirs.insert(parent.to_string()); 576 cur = parent; 577 } 578 } 579 let mut out: BTreeSet = BTreeSet::new(); 580 for dir in dirs { 581 let file = if dir.is_empty() { 582 ".crumb".to_string() 583 } else { 584 format!("{dir}/.crumb") 585 }; 586 if !rows.contains_key(&file) { 587 continue; 588 } 589 let Some(bytes) = show(root, commit, &file) else { 590 continue; 591 }; 592 let Ok(v) = serde_json::from_slice::(&bytes) else { 593 continue; 594 }; 595 for key in ["related", "links"] { 596 for s in strings_of(&v[key]) { 597 let s = s.trim_matches('/').to_string(); 598 if !s.is_empty() { 599 out.insert(s); 600 } 601 } 602 } 603 } 604 out.into_iter().collect() 605 } 606 607 fn under_config(path: &str) -> bool { 608 PIPELINE_CONFIG.iter().any(|c| covers(c, path)) 609 } 610 611 fn is_crumb_file(path: &str) -> bool { 612 path == ".crumb" 613 || path.ends_with("/.crumb") 614 || path == ".crumb.local" 615 || path.ends_with("/.crumb.local") 616 } 617 618 // ---------------------------------------------------------------- the plan 619 620 /// Compute the plan for `req` in the repository at `root`. 621 pub fn compute(root: &Path, req: &Request) -> Result { 622 let base = resolve(root, &req.base)?; 623 let head = resolve(root, &req.head)?; 624 let mut notes: Vec = Vec::new(); 625 626 let mut changed = changed_between(root, &base, &head)?; 627 changed.extend(req.dirty.iter().cloned()); 628 changed.sort(); 629 changed.dedup(); 630 631 let rows_head = tree_rows(root, &head)?; 632 let rows_base = tree_rows(root, &base)?; 633 let (graph, rel_of) = graph_at(root, &head, &rows_head)?; 634 let ids_base = gate_ids_at(root, &base, &rows_base); 635 let removed: Vec = ids_base 636 .iter() 637 .filter(|id| graph.index_of(id).is_none()) 638 .cloned() 639 .collect(); 640 641 let config_changed: Vec = changed 642 .iter() 643 .filter(|p| under_config(p)) 644 .cloned() 645 .collect(); 646 let blocked = if !config_changed.is_empty() && !req.operator { 647 Some("PIPELINE_CONFIG_CHANGED".to_string()) 648 } else { 649 None 650 }; 651 if !config_changed.is_empty() && req.operator { 652 notes.push("pipeline configuration changed; allowed by --operator".to_string()); 653 } 654 655 let crumb = crumb_paths(root, &head, &changed, &rows_head); 656 let pins: Vec = changed 657 .iter() 658 .filter(|p| { 659 show(root, &head, p) 660 .or_else(|| show(root, &base, p)) 661 .is_some_and(|b| is_pin(p, &b)) 662 }) 663 .cloned() 664 .collect(); 665 let always = always_set(root, &base); 666 let ok_patterns = unmapped_ok(root, &base); 667 668 // What each gate watches, and which changed path (if any) touches it. 669 let mut watched_of: Vec> = Vec::with_capacity(graph.len()); 670 for i in 0..graph.len() { 671 let node = graph.node(i); 672 let rel = rel_of.get(&node.id).cloned().unwrap_or_default(); 673 watched_of.push(watched(&node.manifest, &rel, &rows_head)); 674 } 675 let mut all_changed: Vec = changed.clone(); 676 all_changed.extend(crumb.iter().cloned()); 677 let mut because: BTreeMap = BTreeMap::new(); 678 for (i, w) in watched_of.iter().enumerate() { 679 if let Some(p) = all_changed 680 .iter() 681 .find(|p| w.iter().any(|input| covers(input, p))) 682 { 683 because.insert(i, p.clone()); 684 } 685 } 686 687 let mut unmapped: Vec = changed 688 .iter() 689 .filter(|p| { 690 let mapped = p.ends_with(".gate") 691 || is_crumb_file(p) 692 || under_config(p) 693 || watched_of 694 .iter() 695 .any(|w| w.iter().any(|input| covers(input, p))) 696 || ok_patterns.iter().any(|pat| glob_match(pat, p)); 697 !mapped 698 }) 699 .cloned() 700 .collect(); 701 702 let mut seeds: BTreeSet = because.keys().copied().collect(); 703 let mut always_idx: BTreeSet = BTreeSet::new(); 704 let mut removed = removed; 705 for g in &always { 706 match graph.index_of(g) { 707 Some(i) => { 708 always_idx.insert(i); 709 seeds.insert(i); 710 } 711 None => { 712 if !removed.contains(g) { 713 removed.push(g.clone()); 714 } 715 notes.push(format!("always-set gate {g} does not exist at HEAD")); 716 } 717 } 718 } 719 let mut with_dependents: BTreeSet = seeds.clone(); 720 for &s in &seeds { 721 with_dependents.extend(graph.transitive_dependents(s)); 722 } 723 let targets: Vec = with_dependents.iter().copied().collect(); 724 // Full scope (an Alpha qualification) selects exactly what `test ./...` 725 // runs; what changed still says why a gate is listed, but decides 726 // nothing, so the diff-only refusals do not apply. 727 let selected = if req.full { 728 unmapped.clear(); 729 removed.clear(); 730 notes.push( 731 "full scope: every gate at HEAD is selected; UNMAPPED_PATH and GATE_REMOVED do not apply" 732 .to_string(), 733 ); 734 graph.all() 735 } else { 736 graph.with_dependencies(&targets) 737 }; 738 739 // Check ids for every gate at HEAD, dependencies first. 740 let mut binding = identity::local_binding(&req.hardware_identity)?; 741 if binding.hardware_identity.is_empty() { 742 binding.hardware_identity = binding.machine_digest.clone(); 743 if graph 744 .nodes() 745 .iter() 746 .any(|n| n.manifest.cache_scope == manifest::CacheScope::Hardware) 747 { 748 notes.push("hardware identity not given; the machine digest stands in for cache_scope: hardware".to_string()); 749 } 750 } 751 let ids = check_ids( 752 root, 753 &head, 754 &graph, 755 &rows_head, 756 &req.compiler_identity, 757 &req.flags, 758 &binding, 759 )?; 760 761 let mut entries: Vec = Vec::new(); 762 for &i in graph.order() { 763 if !selected.contains(&i) { 764 continue; 765 } 766 let node = graph.node(i); 767 let m = &node.manifest; 768 let is_always = always_idx.contains(&i); 769 let required = m.exactness != Exactness::Advisory; 770 // A `requires: operator` gate is never scheduled automatically; the 771 // operator starting the run by hand (`--operator`) is what lets it 772 // run, exactly as for a pipeline configuration change (ADR 0033 773 // Decision 2 and amendment A4; sc #614). 774 let operator_gate = m.requires.iter().any(|r| r == "operator"); 775 if operator_gate && req.operator && blocked.is_none() { 776 notes.push(format!("operator gate {}: started by --operator", node.id)); 777 } 778 let (section, reason) = if let Some(b) = &blocked { 779 (Section::Blocked, b.clone()) 780 } else if operator_gate && !req.operator { 781 (Section::Blocked, "OPERATOR_STEP_PENDING".to_string()) 782 } else if !required { 783 (Section::Advisory, String::new()) 784 } else if m.pool() == "gb10" { 785 (Section::NeedsGb10, String::new()) 786 } else if m.pool() == "qemu" 787 || m.requires 788 .iter() 789 .any(|r| r == "aarch64" || r == "bare_metal") 790 { 791 (Section::NeedsSpark, String::new()) 792 } else if req.cached.contains(&node.id) { 793 (Section::Cached, String::new()) 794 } else { 795 (Section::Required, String::new()) 796 }; 797 let why = if is_always { 798 "always".to_string() 799 } else if let Some(p) = because.get(&i) { 800 p.clone() 801 } else if seeds 802 .iter() 803 .any(|s| graph.transitive_dependents(*s).contains(&i)) 804 { 805 "dependent".to_string() 806 } else if req.full { 807 "full".to_string() 808 } else { 809 "dependency".to_string() 810 }; 811 entries.push(Entry { 812 gate: node.id.clone(), 813 check_id: ids.get(&node.id).cloned().unwrap_or_default(), 814 pool: m.pool().to_string(), 815 exactness: m.exactness, 816 cache_scope: m.cache_scope, 817 required, 818 section, 819 reason, 820 depends_on: identity::declared_dependencies(m), 821 always: is_always, 822 because: why, 823 }); 824 } 825 let graph_digest = digest_of(&entries)?; 826 Ok(Plan { 827 base, 828 head, 829 changed, 830 crumb_paths: crumb, 831 pins, 832 unmapped, 833 removed, 834 config_changed, 835 blocked, 836 entries, 837 graph_digest, 838 notes, 839 graph, 840 full: req.full, 841 }) 842 } 843 844 /// sha256 over the canonical `[{gate, check_id, depends_on}]`, sorted by gate. 845 pub fn digest_of(entries: &[Entry]) -> Result { 846 let mut rows: Vec<&Entry> = entries.iter().collect(); 847 rows.sort_by(|a, b| a.gate.cmp(&b.gate)); 848 let v: Vec = rows 849 .iter() 850 .map(|e| json!({ "gate": e.gate, "check_id": e.check_id, "depends_on": e.depends_on })) 851 .collect(); 852 canonical_digest(&json!(v)).map_err(|e| e.to_string()) 853 } 854 855 /// Check ids of every gate of `graph` at `commit`, computed from the tree 856 /// rows (no working tree), dependencies first. 857 pub fn check_ids( 858 root: &Path, 859 commit: &str, 860 graph: &Graph, 861 rows: &BTreeMap, 862 compiler_identity: &str, 863 flags: &[String], 864 binding: &Binding, 865 ) -> Result, String> { 866 let mut done: BTreeMap = BTreeMap::new(); 867 for &i in graph.order() { 868 let m = &graph.node(i).manifest; 869 let mut dep_ids = Vec::new(); 870 for d in identity::declared_dependencies(m) { 871 match done.get(&d) { 872 Some(id) => dep_ids.push(id.clone()), 873 None => return Err(format!("gate {} declares unknown dependency {d}", m.gate)), 874 } 875 } 876 let golden = match &m.oracle.golden { 877 Some(g) => show(root, commit, g), 878 None => None, 879 }; 880 let obj = identity::identity_object_from_parts( 881 m, 882 identity::input_blob_ids_from_rows(m, rows), 883 golden.as_deref(), 884 compiler_identity, 885 flags, 886 &dep_ids, 887 binding, 888 )?; 889 done.insert(m.gate.clone(), identity::id_of(&obj)?); 890 } 891 Ok(done) 892 } 893 894 /// Gates with a reusable receipt right now, for the Cached section. Only 895 /// meaningful when `head` is the checked-out commit and the tree is clean; 896 /// the caller checks that. A gate counts as cached only when every gate it 897 /// depends on would be reused too. 898 pub fn probe_cached(root: &Path, graph: &Graph, opts: &crate::runner::Options) -> BTreeSet { 899 use crate::cache::{self, Lookup}; 900 use crate::evidence::{Index, Store}; 901 let store = Store::new(&opts.evidence_dir); 902 let index = Index::load(&store); 903 let env = crate::runner::captured_env(); 904 let mut stands_on: BTreeMap> = BTreeMap::new(); 905 let mut out = BTreeSet::new(); 906 for &i in graph.order() { 907 let node = graph.node(i); 908 let m = &node.manifest; 909 let mut reuse: Option = None; 910 let deps_ok = m.depends_on.iter().all(|d| { 911 graph 912 .index_of(d) 913 .and_then(|di| stands_on.get(&di).cloned().flatten()) 914 .is_some() 915 }); 916 if cache::policy(m.cache_allowed, opts.no_cache || opts.release) == cache::Mode::Allow 917 && deps_ok 918 { 919 if let Ok(id) = 920 crate::runner::identity(root, &node.path, m, &opts.hardware, opts.sandbox) 921 { 922 let deps: Vec<(String, String)> = m 923 .depends_on 924 .iter() 925 .filter_map(|d| { 926 let di = graph.index_of(d)?; 927 Some((d.clone(), stands_on.get(&di)?.clone()?)) 928 }) 929 .collect(); 930 let now = cache::Experiment { 931 manifest_digest: m.digest.clone(), 932 binary_sha256: id.binary_sha.clone(), 933 build_inputs_digest: id.inputs_digest.clone(), 934 machine_digest: id.machine_digest.clone(), 935 dependencies: deps, 936 pins: opts.pins.clone(), 937 args_override: None, 938 }; 939 if let Ok(k) = cache::key(&now, &index) { 940 if let Lookup::Hit(src) = cache::lookup(&index, &store, &k, &env) { 941 if src.verdict() == Some(Verdict::Pass) { 942 reuse = Some(src.digest.clone()); 943 out.insert(node.id.clone()); 944 } 945 } 946 } 947 } 948 } 949 stands_on.insert(i, reuse); 950 } 951 out 952 } 953 954 // ---------------------------------------------------------------- the verdict algebra 955 956 /// What is known about one gate after a run (or from receipts). 957 #[derive(Debug, Clone, PartialEq, Eq)] 958 pub struct Known { 959 pub verdict: Verdict, 960 pub reason: String, 961 /// The receipt digest, when one was written. 962 pub receipt: Option, 963 } 964 965 /// The commit verdict and the effective per-gate verdicts (Decision 7). 966 #[derive(Debug, Clone, PartialEq, Eq)] 967 pub struct Judged { 968 pub verdict: Verdict, 969 pub reason: String, 970 pub gates: BTreeMap, 971 } 972 973 fn worse(a: Verdict, b: Verdict) -> Verdict { 974 if b.exit_code() > a.exit_code() { 975 b 976 } else { 977 a 978 } 979 } 980 981 /// Apply the algebra to a plan and what is known about its gates. Unknown 982 /// gates are NOT_RUN (no receipt). A required gate is NOT_RUN with 983 /// UNVERIFIED_DEPENDENCY when a dependency has no PASS receipt, and FAIL with 984 /// DEPENDENCY_FAILED when a dependency failed. Advisory gates are judged but 985 /// never move the commit verdict. NOT_RUN is never promoted. 986 pub fn judge(plan: &Plan, known: &BTreeMap) -> Judged { 987 let mut gates: BTreeMap = BTreeMap::new(); 988 for e in &plan.entries { 989 let mut v = match known.get(&e.gate) { 990 Some(k) => (k.verdict, k.reason.clone()), 991 None => (Verdict::NotRun, "NO_RECEIPT".to_string()), 992 }; 993 if e.section == Section::Blocked { 994 v = (Verdict::BlockedOperator, e.reason.clone()); 995 } 996 if known 997 .get(&e.gate) 998 .is_some_and(|k| k.verdict == Verdict::Pass && k.receipt.is_none()) 999 { 1000 v = (Verdict::NotRun, "NO_RECEIPT".to_string()); 1001 } 1002 for d in &e.depends_on { 1003 let dep = gates.get(d).cloned().or_else(|| { 1004 known 1005 .get(d) 1006 .filter(|k| k.receipt.is_some() || k.verdict != Verdict::Pass) 1007 .map(|k| (k.verdict, k.reason.clone())) 1008 }); 1009 match dep { 1010 Some((Verdict::Pass, _)) => {} 1011 Some((Verdict::Fail, _)) => { 1012 v = (Verdict::Fail, format!("DEPENDENCY_FAILED:{d}")); 1013 break; 1014 } 1015 Some((other, _)) if other != Verdict::NotRun => { 1016 v = (other, format!("DEP_BLOCKED:{d}")); 1017 break; 1018 } 1019 _ => { 1020 v = (Verdict::NotRun, format!("UNVERIFIED_DEPENDENCY:{d}")); 1021 break; 1022 } 1023 } 1024 } 1025 gates.insert(e.gate.clone(), v); 1026 } 1027 let (verdict, reason) = if let Some(b) = &plan.blocked { 1028 (Verdict::BlockedOperator, b.clone()) 1029 } else if !plan.unmapped.is_empty() { 1030 (Verdict::NotRun, "UNMAPPED_PATH".to_string()) 1031 } else if !plan.removed.is_empty() { 1032 (Verdict::NotRun, "GATE_REMOVED".to_string()) 1033 } else { 1034 let required: Vec<&Entry> = plan.entries.iter().filter(|e| e.required).collect(); 1035 if required.is_empty() { 1036 (Verdict::NotRun, "NO_REQUIRED_GATES".to_string()) 1037 } else { 1038 let mut worst = Verdict::Pass; 1039 let mut reason = String::new(); 1040 let mut any_fail = false; 1041 for e in &required { 1042 let (v, r) = &gates[&e.gate]; 1043 if *v == Verdict::Fail { 1044 any_fail = true; 1045 } 1046 if v.exit_code() > worst.exit_code() { 1047 worst = worse(worst, *v); 1048 reason = format!("{}:{}", e.gate, r); 1049 } 1050 } 1051 if any_fail { 1052 let first = required 1053 .iter() 1054 .find(|e| gates[&e.gate].0 == Verdict::Fail) 1055 .map(|e| format!("{}:{}", e.gate, gates[&e.gate].1)) 1056 .unwrap_or_default(); 1057 (Verdict::Fail, first) 1058 } else { 1059 (worst, reason) 1060 } 1061 } 1062 }; 1063 Judged { 1064 verdict, 1065 reason, 1066 gates, 1067 } 1068 } 1069 1070 // ---------------------------------------------------------------- crate selection 1071 1072 /// Directories of workspace crate `name` and of every workspace crate that 1073 /// depends on it (transitively), relative to the root, from `cargo metadata`. 1074 pub fn crate_dirs(root: &Path, name: &str) -> Result, String> { 1075 let mut cmd = Command::new("cargo"); 1076 cmd.arg("metadata") 1077 .args(["--format-version", "1", "--no-deps"]) 1078 .current_dir(root); 1079 let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run cargo: {e}"))?; 1080 if !out.status.success() { 1081 return Err(format!( 1082 "cargo metadata failed: {}", 1083 String::from_utf8_lossy(&out.stderr).trim() 1084 )); 1085 } 1086 let v: Value = serde_json::from_slice(&out.stdout) 1087 .map_err(|e| format!("cargo metadata is not JSON: {e}"))?; 1088 crate_dirs_from(&v, root, name) 1089 } 1090 1091 /// `crate_dirs` on metadata already read (for tests). 1092 pub fn crate_dirs_from(meta: &Value, root: &Path, name: &str) -> Result, String> { 1093 let packages = meta["packages"] 1094 .as_array() 1095 .ok_or("cargo metadata has no packages")?; 1096 let mut dir_of: BTreeMap = BTreeMap::new(); 1097 let mut deps_of: BTreeMap> = BTreeMap::new(); 1098 let root_s = root.display().to_string(); 1099 for p in packages { 1100 let n = p["name"].as_str().unwrap_or("").to_string(); 1101 let mp = p["manifest_path"].as_str().unwrap_or(""); 1102 let dir = Path::new(mp) 1103 .parent() 1104 .map(|d| d.display().to_string()) 1105 .unwrap_or_default(); 1106 let rel = dir 1107 .strip_prefix(&format!("{root_s}/")) 1108 .map(|s| s.to_string()) 1109 .unwrap_or_else(|| { 1110 if dir == root_s { 1111 String::new() 1112 } else { 1113 dir.clone() 1114 } 1115 }); 1116 dir_of.insert(n.clone(), rel); 1117 let deps: Vec = p["dependencies"] 1118 .as_array() 1119 .map(|a| { 1120 a.iter() 1121 .filter(|d| d["path"].is_string()) 1122 .filter_map(|d| d["name"].as_str().map(|s| s.to_string())) 1123 .collect() 1124 }) 1125 .unwrap_or_default(); 1126 deps_of.insert(n, deps); 1127 } 1128 if !dir_of.contains_key(name) { 1129 return Err(format!("no workspace crate named {name}")); 1130 } 1131 let mut wanted: BTreeSet = BTreeSet::new(); 1132 let mut todo = vec![name.to_string()]; 1133 while let Some(n) = todo.pop() { 1134 if !wanted.insert(n.clone()) { 1135 continue; 1136 } 1137 for (other, deps) in &deps_of { 1138 if deps.contains(&n) { 1139 todo.push(other.clone()); 1140 } 1141 } 1142 } 1143 let mut dirs: Vec = wanted 1144 .iter() 1145 .filter_map(|n| dir_of.get(n).cloned()) 1146 .collect(); 1147 dirs.sort(); 1148 dirs.dedup(); 1149 Ok(dirs) 1150 } 1151 1152 /// Gates whose inputs cover one of `dirs`, or sit under one of them, plus 1153 /// everything they depend on. 1154 pub fn select_for_dirs(graph: &Graph, dirs: &[String]) -> BTreeSet { 1155 let seeds: Vec = (0..graph.len()) 1156 .filter(|&i| { 1157 graph.node(i).manifest.inputs.iter().any(|input| { 1158 dirs.iter() 1159 .any(|d| covers(input, d) || covers(d, input.trim_end_matches('/'))) 1160 }) 1161 }) 1162 .collect(); 1163 graph.with_dependencies(&seeds) 1164 } 1165 1166 // ---------------------------------------------------------------- rendering 1167 1168 fn short(s: &str) -> String { 1169 s.chars().take(12).collect() 1170 } 1171 1172 /// The plan as the operator sees it: exactly the sections Required, Cached, 1173 /// Needs Spark, Needs GB10, Advisory, Blocked, then UNMAPPED. A full-scope 1174 /// plan says so under `Head:`. 1175 pub fn render(repository: &str, plan: &Plan) -> Vec { 1176 let mut out = vec![ 1177 "AIEN PLAN".to_string(), 1178 format!("Repository: {repository}"), 1179 format!("Base: {}", plan.base), 1180 format!("Head: {}", plan.head), 1181 format!("Changed files: {}", plan.changed.len()), 1182 ]; 1183 if plan.full { 1184 out.insert(4, "Scope: full (every gate at HEAD)".to_string()); 1185 } 1186 for p in &plan.changed { 1187 out.push(format!(" {p}")); 1188 } 1189 if !plan.crumb_paths.is_empty() { 1190 out.push(format!("Crumb paths: {}", plan.crumb_paths.join(" "))); 1191 } 1192 if !plan.pins.is_empty() { 1193 out.push(format!("Pins: {}", plan.pins.join(" "))); 1194 } 1195 out.push(format!("Graph digest: {}", plan.graph_digest)); 1196 for s in Section::ALL { 1197 out.push(format!("{}:", s.title())); 1198 let mut any = false; 1199 for e in plan.entries.iter().filter(|e| e.section == s) { 1200 any = true; 1201 let mut line = format!( 1202 " {} pool={} exactness={} check={} because={}", 1203 e.gate, 1204 e.pool, 1205 e.exactness.as_str(), 1206 short(&e.check_id), 1207 e.because 1208 ); 1209 if !e.reason.is_empty() { 1210 line.push(' '); 1211 line.push_str(&e.reason); 1212 } 1213 out.push(line); 1214 } 1215 if !any { 1216 out.push(" (none)".to_string()); 1217 } 1218 } 1219 out.push("UNMAPPED:".to_string()); 1220 if plan.unmapped.is_empty() { 1221 out.push(" (none)".to_string()); 1222 } 1223 for p in &plan.unmapped { 1224 out.push(format!(" {p}")); 1225 } 1226 if !plan.removed.is_empty() { 1227 out.push(format!("Removed gates: {}", plan.removed.join(" "))); 1228 } 1229 for n in &plan.notes { 1230 out.push(format!("Note: {n}")); 1231 } 1232 let j = judge(plan, &BTreeMap::new()); 1233 let verdict = if let Some(b) = &plan.blocked { 1234 format!("BLOCKED_OPERATOR {b}") 1235 } else if !plan.unmapped.is_empty() { 1236 "NOT_RUN UNMAPPED_PATH".to_string() 1237 } else if !plan.removed.is_empty() { 1238 "NOT_RUN GATE_REMOVED".to_string() 1239 } else if plan.entries.is_empty() { 1240 "NOTHING_SELECTED".to_string() 1241 } else { 1242 let _ = j; 1243 "RUNNABLE".to_string() 1244 }; 1245 out.push(format!("Plan verdict: {verdict}")); 1246 out 1247 } 1248 1249 /// Exit code of `aien-test plan`: 0 runnable (or nothing selected), 2 1250 /// NOT_RUN, 4 BLOCKED_OPERATOR. 1251 pub fn exit_code(plan: &Plan) -> i32 { 1252 if plan.blocked.is_some() { 1253 4 1254 } else if !plan.unmapped.is_empty() || !plan.removed.is_empty() { 1255 2 1256 } else { 1257 0 1258 } 1259 } 1260 1261 /// The repository name a bundle carries: `--repo`, else the `origin` remote 1262 /// normalised to `github.com/OWNER/REPO`, else `github.com/aien-dev/`. 1263 pub fn repository_name(root: &Path, explicit: Option<&str>) -> String { 1264 if let Some(r) = explicit { 1265 return r.to_string(); 1266 } 1267 if let Ok(url) = git_text(root, &["remote", "get-url", "origin"]) { 1268 if let Some(n) = normalise_remote(url.trim()) { 1269 return n; 1270 } 1271 } 1272 let dir = root 1273 .file_name() 1274 .map(|n| n.to_string_lossy().into_owned()) 1275 .unwrap_or_else(|| "repo".to_string()); 1276 format!("github.com/aien-dev/{dir}") 1277 } 1278 1279 /// `git@github.com:o/r.git`, `https://github.com/o/r`, `ssh://git@github.com/o/r.git` 1280 /// all give `github.com/o/r`. Other hosts keep their host name. 1281 pub fn normalise_remote(url: &str) -> Option { 1282 let s = url.trim_end_matches('/'); 1283 let s = s.strip_suffix(".git").unwrap_or(s); 1284 let rest = match s.strip_prefix("git@") { 1285 Some(r) => r.replacen(':', "/", 1), 1286 None => ["ssh://git@", "https://", "http://"] 1287 .iter() 1288 .find_map(|p| s.strip_prefix(p))? 1289 .to_string(), 1290 }; 1291 let parts: Vec<&str> = rest.split('/').filter(|p| !p.is_empty()).collect(); 1292 if parts.len() < 3 { 1293 return None; 1294 } 1295 Some(format!( 1296 "{}/{}/{}", 1297 parts[0], 1298 parts[parts.len() - 2], 1299 parts[parts.len() - 1] 1300 )) 1301 } 1302 1303 /// Short helper for the worker and verify: sha256 of a string. 1304 pub fn sha_of(s: &str) -> String { 1305 sha256_hex(s.as_bytes()) 1306 } 1307 1308 #[cfg(test)] 1309 mod tests { 1310 use super::*; 1311 use crate::testutil::{git, init_repo, write_file, TempDir}; 1312 1313 fn gate(id: &str, inputs: &[&str], extra: &str) -> String { 1314 let mut s = format!("gate: {id}\nmanifest_version: 2\nowner: t\nrequires:\n - host\n"); 1315 if !inputs.is_empty() { 1316 s.push_str("inputs:\n"); 1317 for i in inputs { 1318 s.push_str(&format!(" - {i}\n")); 1319 } 1320 } 1321 s.push_str("run:\n exec: run.sh\nexpects:\n exit: 0\n verdict: PASS\ntimeout: 5s\n"); 1322 s.push_str(extra); 1323 s 1324 } 1325 1326 /// A: inputs a/; B: inputs b/, depends on A; C: inputs c/ and shared/; 1327 /// A also watches shared/. S (security) watches sec/. 1328 fn repo() -> TempDir { 1329 let a = gate("A", &["a/", "shared/"], ""); 1330 let b = gate("B", &["b/"], "depends_on:\n - A\n"); 1331 let c = gate("C", &["c/", "shared/"], ""); 1332 let s = gate("S", &["sec/"], ""); 1333 init_repo( 1334 "plan", 1335 &[ 1336 ("gates/a.gate", a.as_str(), false), 1337 ("gates/b.gate", b.as_str(), false), 1338 ("gates/c.gate", c.as_str(), false), 1339 ("gates/s.gate", s.as_str(), false), 1340 ("run.sh", "#!/bin/sh\nexit 0\n", true), 1341 ("a/a.txt", "a\n", false), 1342 ("b/b.txt", "b\n", false), 1343 ("c/c.txt", "c\n", false), 1344 ("sec/s.txt", "s\n", false), 1345 ("shared/iface.txt", "v1\n", false), 1346 ("README.md", "hi\n", false), 1347 (".aien/always", "S\n", false), 1348 (".aien/unmapped-ok", "*.md\ndocs/\n", false), 1349 ], 1350 ) 1351 } 1352 1353 fn commit(t: &TempDir, files: &[(&str, &str)]) { 1354 for (rel, content) in files { 1355 write_file(t.path(), rel, content, false); 1356 } 1357 git(t.path(), &["add", "-A"]); 1358 git(t.path(), &["commit", "-q", "-m", "change"]); 1359 } 1360 1361 fn plan_of(t: &TempDir) -> Plan { 1362 compute(t.path(), &Request::new("HEAD~1", "HEAD")).unwrap() 1363 } 1364 1365 fn gates(p: &Plan, s: Section) -> Vec<&str> { 1366 p.entries 1367 .iter() 1368 .filter(|e| e.section == s) 1369 .map(|e| e.gate.as_str()) 1370 .collect() 1371 } 1372 1373 fn all_gates(p: &Plan) -> Vec<&str> { 1374 p.entries.iter().map(|e| e.gate.as_str()).collect() 1375 } 1376 1377 #[test] 1378 fn m7_a_small_change_selects_only_the_affected_gates_plus_the_always_set() { 1379 let t = repo(); 1380 commit(&t, &[("b/b.txt", "b2\n")]); 1381 let p = plan_of(&t); 1382 // B changed: B and its dependency A run; C is untouched; S is always. 1383 assert_eq!(all_gates(&p), ["A", "B", "S"]); 1384 assert!(p.unmapped.is_empty()); 1385 assert!(p.blocked.is_none()); 1386 assert_eq!(gates(&p, Section::Required), ["A", "B", "S"]); 1387 let b = p.entries.iter().find(|e| e.gate == "B").unwrap(); 1388 assert_eq!(b.because, "b/b.txt"); 1389 let a = p.entries.iter().find(|e| e.gate == "A").unwrap(); 1390 assert_eq!(a.because, "dependency"); 1391 assert!(p.entries.iter().find(|e| e.gate == "S").unwrap().always); 1392 assert_eq!(exit_code(&p), 0); 1393 assert_eq!(p.graph_digest.len(), 64); 1394 } 1395 1396 #[test] 1397 fn m8_a_shared_interface_change_selects_every_gate_that_watches_it_and_their_dependents() { 1398 let t = repo(); 1399 commit(&t, &[("shared/iface.txt", "v2\n")]); 1400 let p = plan_of(&t); 1401 // A and C watch shared/; B depends on A so its check id moves. 1402 assert_eq!(all_gates(&p), ["A", "B", "C", "S"]); 1403 assert_eq!( 1404 p.entries.iter().find(|e| e.gate == "B").unwrap().because, 1405 "dependent" 1406 ); 1407 } 1408 1409 #[test] 1410 fn m12_the_always_set_survives_path_filtering_and_cannot_be_excluded() { 1411 let t = repo(); 1412 commit(&t, &[("README.md", "changed\n")]); 1413 let p = plan_of(&t); 1414 assert_eq!(all_gates(&p), ["S"]); 1415 assert!(p.unmapped.is_empty(), "*.md is allowed by unmapped-ok"); 1416 // The always set is read from BASE: deleting it at HEAD changes nothing. 1417 commit(&t, &[(".aien/always", "")]); 1418 let p = compute( 1419 t.path(), 1420 &Request { 1421 operator: true, 1422 ..Request::new("HEAD~1", "HEAD") 1423 }, 1424 ) 1425 .unwrap(); 1426 assert_eq!(all_gates(&p), ["S"]); 1427 assert!(p.entries[0].always); 1428 } 1429 1430 #[test] 1431 fn an_unmapped_path_gives_not_run_unmapped_path() { 1432 let t = repo(); 1433 commit(&t, &[("stray/file.txt", "x\n")]); 1434 let p = plan_of(&t); 1435 assert_eq!(p.unmapped, ["stray/file.txt"]); 1436 assert_eq!(exit_code(&p), 2); 1437 let j = judge(&p, &BTreeMap::new()); 1438 assert_eq!( 1439 (j.verdict, j.reason.as_str()), 1440 (Verdict::NotRun, "UNMAPPED_PATH") 1441 ); 1442 let text = render("github.com/x/y", &p).join("\n"); 1443 assert!(text.contains("UNMAPPED:\n stray/file.txt")); 1444 assert!(text.contains("Plan verdict: NOT_RUN UNMAPPED_PATH")); 1445 // docs/ is allowed, a gate file is always mapped. 1446 commit( 1447 &t, 1448 &[ 1449 ("docs/x.md", "x\n"), 1450 ("gates/z.gate", &gate("Z", &["z/"], "")), 1451 ], 1452 ); 1453 let p = plan_of(&t); 1454 assert!(p.unmapped.is_empty(), "{:?}", p.unmapped); 1455 assert_eq!(all_gates(&p), ["S", "Z"]); 1456 } 1457 1458 #[test] 1459 fn pipeline_configuration_changes_block_unless_operator() { 1460 let t = repo(); 1461 commit(&t, &[(".aien/always", "S\nA\n"), ("a/a.txt", "a2\n")]); 1462 let p = plan_of(&t); 1463 assert_eq!(p.blocked.as_deref(), Some("PIPELINE_CONFIG_CHANGED")); 1464 assert_eq!(p.config_changed, [".aien/always"]); 1465 assert_eq!(exit_code(&p), 4); 1466 assert!(p.entries.iter().all(|e| e.section == Section::Blocked)); 1467 let j = judge(&p, &BTreeMap::new()); 1468 assert_eq!(j.verdict, Verdict::BlockedOperator); 1469 let p = compute( 1470 t.path(), 1471 &Request { 1472 operator: true, 1473 ..Request::new("HEAD~1", "HEAD") 1474 }, 1475 ) 1476 .unwrap(); 1477 assert!(p.blocked.is_none()); 1478 assert_eq!(gates(&p, Section::Required), ["A", "B", "S"]); 1479 for cfg in [ 1480 "tests/gates/x", 1481 ".github/workflows/ci.yml", 1482 ".forgejo/w.yml", 1483 "tools/aien-test/src/x.rs", 1484 ] { 1485 assert!(under_config(cfg), "{cfg}"); 1486 } 1487 assert!(!under_config("tools/other/x")); 1488 } 1489 1490 #[test] 1491 fn a_gate_deleted_at_head_is_gate_removed() { 1492 let t = repo(); 1493 std::fs::remove_file(t.path().join("gates/c.gate")).unwrap(); 1494 commit(&t, &[("a/a.txt", "a2\n")]); 1495 let p = plan_of(&t); 1496 assert_eq!(p.removed, ["C"]); 1497 assert!(p.unmapped.is_empty()); 1498 assert_eq!(exit_code(&p), 2); 1499 let j = judge(&p, &BTreeMap::new()); 1500 assert_eq!( 1501 (j.verdict, j.reason.as_str()), 1502 (Verdict::NotRun, "GATE_REMOVED") 1503 ); 1504 } 1505 1506 #[test] 1507 fn a_changed_pin_selects_every_gate_listing_it() { 1508 let a = gate("A", &["a/", "deps/x.lock"], ""); 1509 let b = gate("B", &["b/"], ""); 1510 let t = init_repo( 1511 "plan-pin", 1512 &[ 1513 ("gates/a.gate", a.as_str(), false), 1514 ("gates/b.gate", b.as_str(), false), 1515 ("run.sh", "#!/bin/sh\n", true), 1516 ("deps/x.lock", &format!("{}\n", "a".repeat(40)), false), 1517 ], 1518 ); 1519 commit(&t, &[("deps/x.lock", &format!("{}\n", "b".repeat(40)))]); 1520 let p = plan_of(&t); 1521 assert_eq!(p.pins, ["deps/x.lock"]); 1522 assert_eq!(all_gates(&p), ["A"]); 1523 assert!(is_pin( 1524 "x.lock", 1525 b"`0123456789abcdef0123456789abcdef01234567`\n" 1526 )); 1527 assert!(!is_pin("Cargo.lock", b"[[package]]\n")); 1528 assert!(!is_pin( 1529 "x.txt", 1530 b"`0123456789abcdef0123456789abcdef01234567`\n" 1531 )); 1532 } 1533 1534 #[test] 1535 fn d3_implied_inputs_select_a_tests_dir_gate() { 1536 let g = gate("K", &[], ""); 1537 let t = init_repo( 1538 "plan-d3", 1539 &[ 1540 ("tests/kern/boot.gate", g.as_str(), false), 1541 ("run.sh", "#!/bin/sh\n", true), 1542 ("src/kern/boot.rs", "fn a(){}\n", false), 1543 ("tests/kern/boot_test.rs", "fn t(){}\n", false), 1544 ("src/kern/other.rs", "x\n", false), 1545 ], 1546 ); 1547 let rows = tree_rows(t.path(), "HEAD").unwrap(); 1548 let mut implied = implied_inputs("tests/kern/boot.gate", &rows); 1549 implied.sort(); 1550 assert_eq!(implied, ["src/kern/boot.rs", "tests/kern/boot_test.rs"]); 1551 commit(&t, &[("src/kern/boot.rs", "fn b(){}\n")]); 1552 let p = plan_of(&t); 1553 assert_eq!(all_gates(&p), ["K"]); 1554 assert!(p.unmapped.is_empty()); 1555 commit(&t, &[("src/kern/other.rs", "y\n")]); 1556 let p = plan_of(&t); 1557 assert!(p.entries.is_empty()); 1558 assert_eq!(p.unmapped, ["src/kern/other.rs"]); 1559 } 1560 1561 #[test] 1562 fn a_manifest_edit_selects_its_own_gate() { 1563 let t = repo(); 1564 commit( 1565 &t, 1566 &[( 1567 "gates/c.gate", 1568 &gate("C", &["c/", "shared/"], "cache: never\n"), 1569 )], 1570 ); 1571 let p = plan_of(&t); 1572 assert_eq!(all_gates(&p), ["C", "S"]); 1573 } 1574 1575 #[test] 1576 fn crumb_related_paths_count_as_changed() { 1577 let t = repo(); 1578 commit( 1579 &t, 1580 &[("b/.crumb", "{\"dir_name\":\"b\",\"related\":[\"c/\"]}\n")], 1581 ); 1582 commit(&t, &[("b/b.txt", "b3\n")]); 1583 let p = plan_of(&t); 1584 assert_eq!(p.crumb_paths, ["c"]); 1585 assert_eq!(all_gates(&p), ["A", "B", "C", "S"]); 1586 // A crumb file itself is always mapped. 1587 assert!(is_crumb_file("b/.crumb") && is_crumb_file(".crumb.local")); 1588 // A crumb without related/links adds nothing (today's schema). 1589 commit( 1590 &t, 1591 &[ 1592 ("b/.crumb", "{\"dir_name\":\"b\",\"purpose\":\"x\"}\n"), 1593 ("b/b.txt", "b4\n"), 1594 ], 1595 ); 1596 let p = plan_of(&t); 1597 assert!(p.crumb_paths.is_empty()); 1598 assert_eq!(all_gates(&p), ["A", "B", "S"]); 1599 } 1600 1601 #[test] 1602 fn uncommitted_changes_are_listed_only_when_asked() { 1603 let t = repo(); 1604 commit(&t, &[("a/a.txt", "a2\n")]); 1605 write_file(t.path(), "c/new.txt", "n\n", false); 1606 write_file(t.path(), "b/b.txt", "edit\n", false); 1607 let mut dirty = uncommitted(t.path()).unwrap(); 1608 dirty.sort(); 1609 assert_eq!(dirty, ["b/b.txt", "c/new.txt"]); 1610 let p = plan_of(&t); 1611 assert_eq!(all_gates(&p), ["A", "B", "S"]); 1612 let p = compute( 1613 t.path(), 1614 &Request { 1615 dirty, 1616 ..Request::new("HEAD~1", "HEAD") 1617 }, 1618 ) 1619 .unwrap(); 1620 assert_eq!(all_gates(&p), ["A", "B", "C", "S"]); 1621 } 1622 1623 #[test] 1624 fn the_plan_is_the_same_for_a_commit_that_is_not_checked_out() { 1625 let t = repo(); 1626 commit(&t, &[("b/b.txt", "b2\n")]); 1627 let head = resolve(t.path(), "HEAD").unwrap(); 1628 let base = resolve(t.path(), "HEAD~1").unwrap(); 1629 let p1 = compute(t.path(), &Request::new(&base, &head)).unwrap(); 1630 commit( 1631 &t, 1632 &[ 1633 ("c/c.txt", "c2\n"), 1634 ("gates/a.gate", &gate("A", &["a/", "shared/", "x/"], "")), 1635 ], 1636 ); 1637 let p2 = compute(t.path(), &Request::new(&base, &head)).unwrap(); 1638 assert_eq!(p1.graph_digest, p2.graph_digest); 1639 assert_eq!(all_gates(&p1), all_gates(&p2)); 1640 assert_eq!(p1.changed, p2.changed); 1641 // The newest commit's plan differs (A's manifest changed). 1642 let p3 = compute(t.path(), &Request::new(&base, "HEAD")).unwrap(); 1643 assert_ne!(p3.graph_digest, p1.graph_digest); 1644 } 1645 1646 #[test] 1647 fn sections_follow_exactness_pool_and_operator() { 1648 let adv = gate("ADV", &["adv/"], "exactness: ADVISORY\n"); 1649 let gpu = gate("GPU", &["gpu/"], "").replace(" - host\n", " - gb10\n"); 1650 let q = gate("Q", &["q/"], "").replace(" - host\n", " - qemu\n"); 1651 let op = gate("OP", &["op/"], "").replace(" - host\n", " - host\n - operator\n"); 1652 let t = init_repo( 1653 "plan-sections", 1654 &[ 1655 ("gates/adv.gate", adv.as_str(), false), 1656 ("gates/gpu.gate", gpu.as_str(), false), 1657 ("gates/q.gate", q.as_str(), false), 1658 ("gates/op.gate", op.as_str(), false), 1659 ("run.sh", "#!/bin/sh\n", true), 1660 ("adv/x", "1\n", false), 1661 ("gpu/x", "1\n", false), 1662 ("q/x", "1\n", false), 1663 ("op/x", "1\n", false), 1664 ], 1665 ); 1666 commit( 1667 &t, 1668 &[ 1669 ("adv/x", "2\n"), 1670 ("gpu/x", "2\n"), 1671 ("q/x", "2\n"), 1672 ("op/x", "2\n"), 1673 ], 1674 ); 1675 let mut req = Request::new("HEAD~1", "HEAD"); 1676 req.cached.insert("Q".into()); 1677 let p = compute(t.path(), &req).unwrap(); 1678 assert_eq!(gates(&p, Section::Advisory), ["ADV"]); 1679 assert_eq!(gates(&p, Section::NeedsGb10), ["GPU"]); 1680 assert_eq!( 1681 gates(&p, Section::NeedsSpark), 1682 ["Q"], 1683 "qemu needs the Spark even when cached" 1684 ); 1685 assert_eq!(gates(&p, Section::Blocked), ["OP"]); 1686 assert_eq!( 1687 p.entries.iter().find(|e| e.gate == "OP").unwrap().reason, 1688 "OPERATOR_STEP_PENDING" 1689 ); 1690 assert!(!p.entries.iter().find(|e| e.gate == "ADV").unwrap().required); 1691 let text = render("r", &p).join("\n"); 1692 for title in [ 1693 "Required:", 1694 "Cached:", 1695 "Needs Spark:", 1696 "Needs GB10:", 1697 "Advisory:", 1698 "Blocked:", 1699 "UNMAPPED:", 1700 ] { 1701 assert!(text.contains(&format!("\n{title}\n")), "{title}"); 1702 } 1703 } 1704 1705 fn full(t: &TempDir) -> Plan { 1706 compute( 1707 t.path(), 1708 &Request { 1709 full: true, 1710 ..Request::new("HEAD~1", "HEAD") 1711 }, 1712 ) 1713 .unwrap() 1714 } 1715 1716 #[test] 1717 fn full_scope_selects_every_gate_whatever_the_diff_touches() { 1718 let t = repo(); 1719 commit(&t, &[("b/b.txt", "b2\n")]); 1720 // Changed scope: C watches nothing that changed. 1721 let p = plan_of(&t); 1722 assert_eq!(all_gates(&p), ["A", "B", "S"]); 1723 assert!(!p.full); 1724 assert_eq!(p.scope(), "changed"); 1725 // Full scope: C is selected and required although c/ is untouched. 1726 let p = full(&t); 1727 assert!(p.full); 1728 assert_eq!(p.scope(), "full"); 1729 assert_eq!(all_gates(&p), ["A", "B", "C", "S"]); 1730 assert_eq!(gates(&p, Section::Required), ["A", "B", "C", "S"]); 1731 let c = p.entries.iter().find(|e| e.gate == "C").unwrap(); 1732 assert!(c.required); 1733 assert_eq!(c.because, "full"); 1734 // What changed still labels the entries. 1735 let b = p.entries.iter().find(|e| e.gate == "B").unwrap(); 1736 assert_eq!(b.because, "b/b.txt"); 1737 assert_eq!(p.changed, ["b/b.txt"]); 1738 let text = render("r", &p).join("\n"); 1739 assert!( 1740 text.contains("\nScope: full (every gate at HEAD)\n"), 1741 "{text}" 1742 ); 1743 assert!(!render("r", &plan_of(&t)).join("\n").contains("Scope:")); 1744 } 1745 1746 #[test] 1747 fn full_scope_ignores_the_diff_only_refusals() { 1748 let t = repo(); 1749 std::fs::remove_file(t.path().join("gates/c.gate")).unwrap(); 1750 commit(&t, &[("stray/file.txt", "x\n")]); 1751 let p = plan_of(&t); 1752 assert_eq!(p.unmapped, ["stray/file.txt"]); 1753 assert_eq!(p.removed, ["C"]); 1754 let p = full(&t); 1755 assert!(p.unmapped.is_empty(), "{:?}", p.unmapped); 1756 assert!(p.removed.is_empty(), "{:?}", p.removed); 1757 assert_eq!(exit_code(&p), 0); 1758 assert_eq!(all_gates(&p), ["A", "B", "S"]); 1759 let pass = |g: &str| { 1760 ( 1761 g.to_string(), 1762 Known { 1763 verdict: Verdict::Pass, 1764 reason: String::new(), 1765 receipt: Some(format!("r-{g}")), 1766 }, 1767 ) 1768 }; 1769 let known: BTreeMap = ["A", "B", "S"].into_iter().map(pass).collect(); 1770 assert_eq!(judge(&p, &known).verdict, Verdict::Pass); 1771 // A pipeline configuration change still blocks without --operator. 1772 commit(&t, &[(".aien/always", "S\nA\n")]); 1773 assert_eq!(full(&t).blocked.as_deref(), Some("PIPELINE_CONFIG_CHANGED")); 1774 } 1775 1776 #[test] 1777 fn full_scope_requires_the_gb10_and_spark_gates() { 1778 let h = gate("H", &["h/"], ""); 1779 let gpu = gate("GPU", &["gpu/"], "").replace(" - host\n", " - gb10\n"); 1780 let q = gate("Q", &["q/"], "").replace(" - host\n", " - qemu\n"); 1781 let adv = gate("ADV", &["adv/"], "exactness: ADVISORY\n"); 1782 let t = init_repo( 1783 "plan-full-gb10", 1784 &[ 1785 ("gates/h.gate", h.as_str(), false), 1786 ("gates/gpu.gate", gpu.as_str(), false), 1787 ("gates/q.gate", q.as_str(), false), 1788 ("gates/adv.gate", adv.as_str(), false), 1789 ("run.sh", "#!/bin/sh\n", true), 1790 ("h/x", "1\n", false), 1791 ("gpu/x", "1\n", false), 1792 ("q/x", "1\n", false), 1793 ("adv/x", "1\n", false), 1794 ], 1795 ); 1796 commit(&t, &[("h/x", "2\n")]); 1797 assert_eq!(all_gates(&plan_of(&t)), ["H"]); 1798 let p = full(&t); 1799 assert_eq!(all_gates(&p), ["ADV", "GPU", "H", "Q"]); 1800 // The gb10 gate is in the required set and runnable (the worker runs 1801 // every section but Blocked); its section still says it needs the chip. 1802 let g = p.entries.iter().find(|e| e.gate == "GPU").unwrap(); 1803 assert!(g.required); 1804 assert_eq!((g.section, g.pool.as_str()), (Section::NeedsGb10, "gb10")); 1805 assert_eq!(gates(&p, Section::NeedsSpark), ["Q"]); 1806 assert!(!p.entries.iter().find(|e| e.gate == "ADV").unwrap().required); 1807 let required: Vec<&str> = p 1808 .entries 1809 .iter() 1810 .filter(|e| e.required && e.section != Section::Blocked) 1811 .map(|e| e.gate.as_str()) 1812 .collect(); 1813 assert_eq!(required, ["GPU", "H", "Q"]); 1814 // Without a GPU receipt the commit is not qualified. 1815 let pass = |g: &str| { 1816 ( 1817 g.to_string(), 1818 Known { 1819 verdict: Verdict::Pass, 1820 reason: String::new(), 1821 receipt: Some(format!("r-{g}")), 1822 }, 1823 ) 1824 }; 1825 let mut known: BTreeMap = ["H", "Q"].into_iter().map(pass).collect(); 1826 let j = judge(&p, &known); 1827 assert_eq!( 1828 (j.verdict, j.reason.as_str()), 1829 (Verdict::NotRun, "GPU:NO_RECEIPT") 1830 ); 1831 known.extend([pass("GPU")]); 1832 assert_eq!(judge(&p, &known).verdict, Verdict::Pass); 1833 } 1834 1835 #[test] 1836 fn operator_gate_runs_under_operator_and_is_blocked_otherwise() { 1837 // sc #614: a `requires: operator` gate is OPERATOR_STEP_PENDING for an 1838 // automatic run and runs like any other gate when the operator 1839 // started the run by hand with `--operator` (ADR 0033 Decision 2). 1840 let op = gate("OP", &["op/"], "").replace(" - host\n", " - host\n - operator\n"); 1841 let t = init_repo( 1842 "plan-operator-gate", 1843 &[ 1844 ("gates/op.gate", op.as_str(), false), 1845 ("run.sh", "#!/bin/sh\n", true), 1846 ("op/x", "1\n", false), 1847 ], 1848 ); 1849 commit(&t, &[("op/x", "2\n")]); 1850 let pass = |receipt: bool| { 1851 let mut known = BTreeMap::new(); 1852 known.insert( 1853 "OP".to_string(), 1854 Known { 1855 verdict: Verdict::Pass, 1856 reason: "PASS".into(), 1857 receipt: receipt.then(|| "d".repeat(64)), 1858 }, 1859 ); 1860 known 1861 }; 1862 1863 // Automatic run: Blocked, and a PASS receipt does not unblock it. 1864 let p = compute(t.path(), &Request::new("HEAD~1", "HEAD")).unwrap(); 1865 assert_eq!(gates(&p, Section::Blocked), ["OP"]); 1866 assert_eq!( 1867 exit_code(&p), 1868 0, 1869 "a pending operator step is not a config block" 1870 ); 1871 let j = judge(&p, &pass(true)); 1872 assert_eq!( 1873 (j.verdict, j.reason.as_str()), 1874 (Verdict::BlockedOperator, "OP:OPERATOR_STEP_PENDING") 1875 ); 1876 1877 // Operator run: the gate is Required, runs, and its receipt counts. 1878 let p = compute( 1879 t.path(), 1880 &Request { 1881 operator: true, 1882 ..Request::new("HEAD~1", "HEAD") 1883 }, 1884 ) 1885 .unwrap(); 1886 assert_eq!(gates(&p, Section::Required), ["OP"]); 1887 assert!(gates(&p, Section::Blocked).is_empty()); 1888 let e = p.entries.iter().find(|e| e.gate == "OP").unwrap(); 1889 assert!(e.reason.is_empty(), "reason {}", e.reason); 1890 assert!( 1891 p.notes 1892 .iter() 1893 .any(|n| n.contains("OP") && n.contains("--operator")), 1894 "{:?}", 1895 p.notes 1896 ); 1897 let j = judge(&p, &pass(true)); 1898 assert_eq!((j.verdict, j.reason.as_str()), (Verdict::Pass, "")); 1899 // Without a receipt nothing is promoted. 1900 let j = judge(&p, &pass(false)); 1901 assert_eq!(j.verdict, Verdict::NotRun); 1902 let j = judge(&p, &BTreeMap::new()); 1903 assert_eq!(j.verdict, Verdict::NotRun); 1904 } 1905 1906 #[test] 1907 fn cached_section_needs_the_probe() { 1908 let t = repo(); 1909 commit(&t, &[("a/a.txt", "a2\n")]); 1910 let mut req = Request::new("HEAD~1", "HEAD"); 1911 req.cached.insert("A".into()); 1912 let p = compute(t.path(), &req).unwrap(); 1913 assert_eq!(gates(&p, Section::Cached), ["A"]); 1914 assert_eq!(gates(&p, Section::Required), ["B", "S"]); 1915 } 1916 1917 fn known(v: Verdict, receipt: bool) -> Known { 1918 Known { 1919 verdict: v, 1920 reason: String::new(), 1921 receipt: receipt.then(|| "r".repeat(64)), 1922 } 1923 } 1924 1925 #[test] 1926 fn t5_missing_dependency_receipt_is_unverified_dependency() { 1927 let t = repo(); 1928 commit(&t, &[("b/b.txt", "b2\n")]); 1929 let p = plan_of(&t); 1930 let mut k = BTreeMap::new(); 1931 k.insert("B".to_string(), known(Verdict::Pass, true)); 1932 k.insert("S".to_string(), known(Verdict::Pass, true)); 1933 let j = judge(&p, &k); 1934 assert_eq!(j.gates["A"].0, Verdict::NotRun); 1935 assert_eq!( 1936 j.gates["B"], 1937 (Verdict::NotRun, "UNVERIFIED_DEPENDENCY:A".to_string()) 1938 ); 1939 assert_eq!(j.verdict, Verdict::NotRun); 1940 // A PASS without a receipt is not evidence either. 1941 k.insert("A".to_string(), known(Verdict::Pass, false)); 1942 let j = judge(&p, &k); 1943 assert_eq!(j.gates["A"], (Verdict::NotRun, "NO_RECEIPT".to_string())); 1944 assert_eq!(j.gates["B"].1, "UNVERIFIED_DEPENDENCY:A"); 1945 } 1946 1947 #[test] 1948 fn t6_a_failed_dependency_propagates_as_dependency_failed() { 1949 let t = repo(); 1950 commit(&t, &[("b/b.txt", "b2\n")]); 1951 let p = plan_of(&t); 1952 let mut k = BTreeMap::new(); 1953 k.insert("A".to_string(), known(Verdict::Fail, true)); 1954 k.insert("B".to_string(), known(Verdict::Pass, true)); 1955 k.insert("S".to_string(), known(Verdict::Pass, true)); 1956 let j = judge(&p, &k); 1957 assert_eq!( 1958 j.gates["B"], 1959 (Verdict::Fail, "DEPENDENCY_FAILED:A".to_string()) 1960 ); 1961 assert_eq!(j.verdict, Verdict::Fail); 1962 assert!(j.reason.starts_with("A:")); 1963 } 1964 1965 #[test] 1966 fn t7_not_run_is_never_promoted_and_all_pass_is_pass() { 1967 let t = repo(); 1968 commit(&t, &[("b/b.txt", "b2\n")]); 1969 let p = plan_of(&t); 1970 let mut k = BTreeMap::new(); 1971 k.insert("A".to_string(), known(Verdict::Pass, true)); 1972 k.insert("B".to_string(), known(Verdict::Pass, true)); 1973 k.insert("S".to_string(), known(Verdict::Pass, true)); 1974 let j = judge(&p, &k); 1975 assert_eq!(j.verdict, Verdict::Pass); 1976 assert!(j.gates.values().all(|(v, _)| *v == Verdict::Pass)); 1977 // One required gate NOT_RUN: the commit is NOT_RUN however the rest did. 1978 k.insert("S".to_string(), known(Verdict::NotRun, true)); 1979 let j = judge(&p, &k); 1980 assert_eq!(j.verdict, Verdict::NotRun); 1981 assert_eq!(j.reason, "S:"); 1982 // A security gate from the always set cannot be left out: no entry 1983 // for S means no receipt, which is NOT_RUN. 1984 k.remove("S"); 1985 let j = judge(&p, &k); 1986 assert_eq!(j.gates["S"], (Verdict::NotRun, "NO_RECEIPT".to_string())); 1987 assert_eq!(j.verdict, Verdict::NotRun); 1988 // A blocked required gate blocks the commit. 1989 k.insert("S".to_string(), known(Verdict::BlockedHardware, true)); 1990 assert_eq!(judge(&p, &k).verdict, Verdict::BlockedHardware); 1991 } 1992 1993 #[test] 1994 fn advisory_gates_never_move_the_commit_verdict() { 1995 let adv = gate("ADV", &["a/"], "exactness: ADVISORY\n"); 1996 let a = gate("A", &["a/"], ""); 1997 let t = init_repo( 1998 "plan-adv", 1999 &[ 2000 ("gates/adv.gate", adv.as_str(), false), 2001 ("gates/a.gate", a.as_str(), false), 2002 ("run.sh", "#!/bin/sh\n", true), 2003 ("a/x", "1\n", false), 2004 ], 2005 ); 2006 commit(&t, &[("a/x", "2\n")]); 2007 let p = plan_of(&t); 2008 let mut k = BTreeMap::new(); 2009 k.insert("A".to_string(), known(Verdict::Pass, true)); 2010 k.insert("ADV".to_string(), known(Verdict::Fail, true)); 2011 let j = judge(&p, &k); 2012 assert_eq!(j.verdict, Verdict::Pass); 2013 assert_eq!(j.gates["ADV"].0, Verdict::Fail); 2014 } 2015 2016 #[test] 2017 fn glob_and_covers() { 2018 assert!(glob_match("*.md", "docs/a.md")); 2019 assert!(glob_match("docs/", "docs/x/y")); 2020 assert!(!glob_match("docs/", "docsx/y")); 2021 assert!(glob_match("exact.txt", "exact.txt")); 2022 assert!(!glob_match("exact.txt", "exact.txt2")); 2023 assert!(glob_match("a*b*c", "aXXbYc")); 2024 assert!(covers("a", "a/b")); 2025 assert!(covers("a/", "a")); 2026 assert!(!covers("a", "ab/c")); 2027 assert!(covers("", "anything")); 2028 } 2029 2030 #[test] 2031 fn remote_names_normalise() { 2032 for u in [ 2033 "git@github.com:aien-dev/x.git", 2034 "https://github.com/aien-dev/x", 2035 "https://github.com/aien-dev/x.git/", 2036 "ssh://git@github.com/aien-dev/x.git", 2037 ] { 2038 assert_eq!( 2039 normalise_remote(u).as_deref(), 2040 Some("github.com/aien-dev/x"), 2041 "{u}" 2042 ); 2043 } 2044 assert_eq!(normalise_remote("/local/path"), None); 2045 let t = repo(); 2046 assert_eq!( 2047 repository_name(t.path(), Some("github.com/a/b")), 2048 "github.com/a/b" 2049 ); 2050 assert!(repository_name(t.path(), None).starts_with("github.com/aien-dev/")); 2051 } 2052 2053 #[test] 2054 fn crate_dirs_follow_reverse_dependents() { 2055 let meta = json!({ 2056 "packages": [ 2057 {"name": "core", "manifest_path": "/r/crates/core/Cargo.toml", "dependencies": []}, 2058 {"name": "mid", "manifest_path": "/r/crates/mid/Cargo.toml", 2059 "dependencies": [{"name": "core", "path": "/r/crates/core"}]}, 2060 {"name": "top", "manifest_path": "/r/tools/top/Cargo.toml", 2061 "dependencies": [{"name": "mid", "path": "/r/crates/mid"}, {"name": "serde", "path": null}]}, 2062 {"name": "other", "manifest_path": "/r/crates/other/Cargo.toml", 2063 "dependencies": [{"name": "core", "path": null}]} 2064 ] 2065 }); 2066 let root = Path::new("/r"); 2067 assert_eq!( 2068 crate_dirs_from(&meta, root, "core").unwrap(), 2069 ["crates/core", "crates/mid", "tools/top"] 2070 ); 2071 assert_eq!(crate_dirs_from(&meta, root, "top").unwrap(), ["tools/top"]); 2072 assert!(crate_dirs_from(&meta, root, "nope").is_err()); 2073 let t = repo(); 2074 let g = graph::load(t.path()).unwrap(); 2075 let picked = select_for_dirs(&g, &["b".to_string()]); 2076 let names: Vec<&str> = picked.iter().map(|&i| g.node(i).id.as_str()).collect(); 2077 assert_eq!(names, ["A", "B"]); 2078 // A crate directory above an input also selects the gate. 2079 let picked = select_for_dirs(&g, &[String::new()]); 2080 assert_eq!(picked.len(), 4); 2081 } 2082 2083 #[test] 2084 fn resolve_and_rows() { 2085 let t = repo(); 2086 let h = resolve(t.path(), "HEAD").unwrap(); 2087 assert_eq!(h.len(), 40); 2088 assert!(resolve(t.path(), "no-such-ref").is_err()); 2089 assert_eq!(resolve_first(t.path(), &["nope", "HEAD"]).unwrap(), h); 2090 let rows = tree_rows(t.path(), &h).unwrap(); 2091 assert!(rows.contains_key("gates/a.gate")); 2092 assert_eq!(rows["a/a.txt"].len(), 40); 2093 assert_eq!(show(t.path(), &h, "a/a.txt").unwrap(), b"a\n"); 2094 assert!(show(t.path(), &h, "missing").is_none()); 2095 assert_eq!(always_set(t.path(), &h), ["S"]); 2096 assert_eq!(unmapped_ok(t.path(), &h), ["*.md", "docs/"]); 2097 } 2098 }