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/worker.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 / worker.rs` 2853 lines ยท 111743 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 trusted worker (ADR 0033 Decision 9; local pipeline contracts C1 to 17 //! C7) and the state directory every local-CI command shares. 18 //! 19 //! State lives under `~/.local/state/aien-local-ci/`: 20 //! 21 //! ```text 22 //! evidence/// receipts and blobs of that commit's run 23 //! bundles///bundle.json the signed VerificationBundleV1 24 //! trigger/. a file whose presence asks for a run 25 //! locks/judging/. held (flock) by the one process judging that head 26 //! outbox/..json a GitHub status that could not be posted yet 27 //! journal.jsonl one line per finished head 28 //! worker.heartbeat what the worker is doing right now 29 //! ``` 30 //! 31 //! For one head: fetch into the trusted clone `/` (its checkout 32 //! is never touched), add a detached worktree `//`, 33 //! `crumb claim` it, plan, run the selected gates with the sandbox and the 34 //! pools, write receipts, build and sign the bundle with `~/.aien/verify.key`, 35 //! write it, journal it, `crumb close`, remove the worktree. With `--github` 36 //! the commit status `AIEN Verification (Spark)` is posted: success only on 37 //! PASS, failure on FAIL, error otherwise. When GitHub cannot be reached the 38 //! status goes to the outbox, the journal says `publication: pending`, and the 39 //! next round of a loop started with `--github` flushes it (a loop without 40 //! `--github` leaves it queued). GitHub being down is never a local 41 //! failure. 42 43 use crate::bundle; 44 use crate::evidence::{canonical, canonical_digest, sha256_hex, utc_string}; 45 use crate::graph; 46 use crate::plan::{self, Known, Section}; 47 use crate::process; 48 use crate::resources::{self, GpuWait, Hardware, JobsSpec, DEFAULT_GPU_WAIT}; 49 use crate::runner::{self, CacheNote, Options}; 50 use crate::sandbox::Sandbox; 51 use crate::verdict::Verdict; 52 use crate::verify; 53 use serde_json::{json, Value}; 54 use std::collections::{BTreeMap, BTreeSet}; 55 use std::fs; 56 use std::io::Write; 57 use std::os::unix::fs::MetadataExt; 58 use std::path::{Path, PathBuf}; 59 use std::process::Command; 60 use std::time::{Duration, SystemTime, UNIX_EPOCH}; 61 62 pub const CONTEXT: &str = "AIEN Verification (Spark)"; 63 pub const EXECUTOR_CLASS: &str = "spark"; 64 /// Where INFRA keeps the per-repository cargo target dirs (A2). 65 pub const TARGET_ROOT: &str = "/var/lib/aien-run/target"; 66 /// Where INFRA's `wt.sh` keeps the bare mirrors its worktrees point into. 67 pub const MIRROR_ROOT: &str = "/var/lib/aien-run/mirror"; 68 69 /// A repository directory key the worker accepts: letters, digits, `.`, `_` 70 /// and `-`, not starting with a dot (so never `.` or `..`). 71 pub fn valid_repo_key(repo: &str) -> bool { 72 !repo.is_empty() 73 && repo.len() <= 100 74 && !repo.starts_with('.') 75 && repo 76 .bytes() 77 .all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'_' || b == b'-') 78 } 79 80 /// A full lowercase 40-hex commit id. 81 pub fn valid_sha(sha: &str) -> bool { 82 sha.len() == 40 83 && sha 84 .bytes() 85 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b)) 86 } 87 88 /// The signing key must be a regular file only its owner can read or write 89 /// (mode 0600 or stricter): a key the `aien-run` user could read would let a 90 /// gate sign its own bundle. 91 pub fn check_key_private(path: &Path) -> Result<(), String> { 92 use std::os::unix::fs::PermissionsExt; 93 let meta = fs::symlink_metadata(path) 94 .map_err(|e| format!("cannot stat signing key {}: {e}", path.display()))?; 95 if !meta.file_type().is_file() { 96 return Err(format!( 97 "signing key {} is not a regular file", 98 path.display() 99 )); 100 } 101 let mode = meta.permissions().mode() & 0o777; 102 if mode & 0o077 != 0 { 103 return Err(format!( 104 "signing key {} has mode {mode:o}; it must be 0600 (no group or other access)", 105 path.display() 106 )); 107 } 108 Ok(()) 109 } 110 111 /// The local-CI state directory. 112 #[derive(Debug, Clone, PartialEq, Eq)] 113 pub struct StateDir { 114 pub root: PathBuf, 115 } 116 117 impl StateDir { 118 pub fn new(root: &Path) -> StateDir { 119 StateDir { 120 root: root.to_path_buf(), 121 } 122 } 123 124 /// `~/.local/state/aien-local-ci`; None without HOME. 125 pub fn default_dir() -> Option { 126 let home = std::env::var_os("HOME")?; 127 Some(StateDir::new( 128 &PathBuf::from(home).join(".local/state/aien-local-ci"), 129 )) 130 } 131 132 /// The directory key of a repository name: its last path segment. 133 pub fn repo_key(repository: &str) -> String { 134 repository 135 .trim_end_matches('/') 136 .rsplit('/') 137 .next() 138 .unwrap_or(repository) 139 .to_string() 140 } 141 142 pub fn evidence(&self, repo: &str, sha: &str) -> PathBuf { 143 self.root.join("evidence").join(repo).join(sha) 144 } 145 146 /// `/gate-cache/`: the cross-head store (`cache::Shared`) 147 /// every head of one repository reads and publishes to. 148 pub fn gate_cache(&self, repo: &str) -> PathBuf { 149 self.root.join("gate-cache").join(repo) 150 } 151 152 /// `/locks/target`: the per-target-dir lock files 153 /// (`resources::target_lock_path`). Every holder of a cargo target dir, 154 /// a gate run by this worker or the worker's own priming of 155 /// `target//pr`, takes its lock from here. 156 pub fn target_lock_dir(&self) -> PathBuf { 157 self.root.join("locks").join("target") 158 } 159 160 /// `/locks/judging/.`: held by the process judging that 161 /// head (`claim_head`). 162 pub fn head_lock(&self, repo: &str, sha: &str) -> PathBuf { 163 self.root 164 .join("locks") 165 .join("judging") 166 .join(format!("{repo}.{sha}")) 167 } 168 169 pub fn bundle_path(&self, repo: &str, sha: &str) -> PathBuf { 170 self.root 171 .join("bundles") 172 .join(repo) 173 .join(sha) 174 .join("bundle.json") 175 } 176 177 pub fn trigger_dir(&self) -> PathBuf { 178 self.root.join("trigger") 179 } 180 181 pub fn outbox_dir(&self) -> PathBuf { 182 self.root.join("outbox") 183 } 184 185 pub fn journal(&self) -> PathBuf { 186 self.root.join("journal.jsonl") 187 } 188 189 pub fn heartbeat(&self) -> PathBuf { 190 self.root.join("worker.heartbeat") 191 } 192 193 /// Append one JSON line to the journal. 194 pub fn journal_append(&self, entry: &Value) -> Result<(), String> { 195 fs::create_dir_all(&self.root).map_err(|e| format!("cannot create state dir: {e}"))?; 196 let mut f = fs::OpenOptions::new() 197 .append(true) 198 .create(true) 199 .open(self.journal()) 200 .map_err(|e| format!("cannot open journal: {e}"))?; 201 let mut line = serde_json::to_string(entry).map_err(|e| e.to_string())?; 202 line.push('\n'); 203 f.write_all(line.as_bytes()) 204 .map_err(|e| format!("cannot write journal: {e}")) 205 } 206 207 /// Overwrite the heartbeat file (atomic rename). 208 pub fn beat(&self, repo: &str, sha: &str, phase: &str) { 209 let v = json!({ 210 "utc": utc_string(now_secs()), 211 "pid": std::process::id(), 212 "repo": repo, 213 "sha": sha, 214 "phase": phase, 215 }); 216 let _ = fs::create_dir_all(&self.root); 217 // One temp name per thread: heads of a batch beat at the same time. 218 let tmp = self.root.join(format!( 219 "worker.heartbeat.tmp.{}.{:?}", 220 std::process::id(), 221 std::thread::current().id() 222 )); 223 if fs::write(&tmp, serde_json::to_string(&v).unwrap_or_default()).is_ok() { 224 let _ = fs::rename(&tmp, self.heartbeat()); 225 } 226 } 227 } 228 229 fn now_secs() -> u64 { 230 SystemTime::now() 231 .duration_since(UNIX_EPOCH) 232 .map(|d| d.as_secs()) 233 .unwrap_or(0) 234 } 235 236 /// How the worker is set up. 237 #[derive(Debug, Clone)] 238 pub struct Config { 239 pub state: StateDir, 240 pub key: PathBuf, 241 /// Where the trusted clones live: `/`. 242 pub clones: PathBuf, 243 pub wt_root: PathBuf, 244 pub sandbox: Sandbox, 245 pub github: bool, 246 pub poll: Duration, 247 pub repos: Vec, 248 /// The ref the plan is based on (`origin/main`); a head that *is* that 249 /// ref is planned against its first parent. 250 pub base_ref: String, 251 pub operator: bool, 252 /// `--full`: plan every head in full scope (an Alpha qualification: 253 /// every gate at HEAD, signed as `plan.scope: "full"`). 254 pub full: bool, 255 /// The crumb command (`crumb`); None skips crumb claim/close. 256 pub crumb: Option, 257 /// The GitHub CLI (`gh`), looked up on PATH. 258 pub gh: String, 259 pub hardware_identity: String, 260 /// Allow `Sandbox::None` (development only: gates then run as the 261 /// worker user, who can read the signing key). Never with `github`. 262 pub allow_unsandboxed: bool, 263 /// Per-repository cargo target directories by trust class 264 /// (`//main|pr/`, one per head), used under 265 /// `Sandbox::User`. 266 pub target_root: PathBuf, 267 /// INFRA's worktree tool (`tools/aien-local-ci/wt.sh`). Under 268 /// `Sandbox::User` every checkout is made and removed with it; without it 269 /// the worker refuses to run. 270 pub wt_tool: Option, 271 /// The mirrors `wt_tool` keeps (`/.git`). 272 pub mirror_root: PathBuf, 273 /// The operator's sibling map (`tools/aien-local-ci/siblings`): which 274 /// read-only sibling checkouts a repository's gates reach as `../`. 275 /// None: no siblings. 276 pub siblings: Option, 277 /// `--jobs host=N,qemu=M` for the runs this worker starts (None: the 278 /// machine defaults). An operator run of a repository whose gates share 279 /// one checkout uses `--jobs host=1`. 280 pub jobs: JobsSpec, 281 /// `--no-cache`: run every selected gate, reuse no receipt. 282 pub no_cache: bool, 283 /// How a gb10 gate waits for a held GPU lock (`--gpu-wait`, `--wait-gpu`; 284 /// default the bounded `resources::DEFAULT_GPU_WAIT`). 285 pub gpu_wait: GpuWait, 286 /// `--batch-host N`: host slots the heads of one batch share (None: half 287 /// the CPUs, `resources::BatchShare::default_host`). 288 pub batch_host: Option, 289 /// `--batch-heads N`: how many heads of one repository the loop checks 290 /// out and judges together (default 6; 1 judges one head at a time). 291 pub batch_heads: usize, 292 } 293 294 impl Config { 295 pub fn new(state: StateDir, key: &Path, clones: &Path, wt_root: &Path) -> Config { 296 Config { 297 state, 298 key: key.to_path_buf(), 299 clones: clones.to_path_buf(), 300 wt_root: wt_root.to_path_buf(), 301 sandbox: Sandbox::None, 302 github: false, 303 poll: Duration::from_secs(30), 304 repos: Vec::new(), 305 base_ref: "origin/main".to_string(), 306 operator: false, 307 full: false, 308 crumb: Some("crumb".to_string()), 309 gh: "gh".to_string(), 310 hardware_identity: String::new(), 311 allow_unsandboxed: false, 312 target_root: PathBuf::from(TARGET_ROOT), 313 wt_tool: None, 314 mirror_root: PathBuf::from(MIRROR_ROOT), 315 siblings: None, 316 jobs: JobsSpec::default(), 317 no_cache: false, 318 gpu_wait: GpuWait::Bounded(DEFAULT_GPU_WAIT), 319 batch_host: None, 320 batch_heads: 6, 321 } 322 } 323 324 /// The sandbox rule: `Sandbox::User` always; `Sandbox::None` only when 325 /// `allow_unsandboxed` (development) and never when serving GitHub heads. 326 pub fn check_sandbox_policy_for(&self, github: bool) -> Result<(), String> { 327 if self.sandbox == Sandbox::User { 328 return Ok(()); 329 } 330 if github { 331 return Err("--sandbox none is refused with --github: pull request code must run as the aien-run user".to_string()); 332 } 333 if !self.allow_unsandboxed { 334 return Err("--sandbox none runs gates as the worker user, who can read the signing key; it needs --dev-unsandboxed (development only)".to_string()); 335 } 336 Ok(()) 337 } 338 } 339 340 /// What one head produced. 341 #[derive(Debug, Clone)] 342 pub struct Summary { 343 pub repo: String, 344 pub sha: String, 345 pub repository: String, 346 pub verdict: Verdict, 347 pub reason: String, 348 pub bundle_verdict: String, 349 pub bundle_path: PathBuf, 350 pub bundle_digest: String, 351 pub gates: Vec<(String, String, Verdict)>, 352 pub publication: String, 353 /// What the independent check (`verify`) said about the bundle. 354 pub ready: bool, 355 pub notes: Vec, 356 } 357 358 fn run_cmd(cwd: &Path, program: &str, args: &[&str]) -> Result { 359 let mut cmd = Command::new(program); 360 cmd.args(args).current_dir(cwd); 361 // git and crumb (which runs git) may open a trusted wt.sh worktree. 362 process::apply_git_trust(&mut cmd); 363 if program == "git" { 364 cmd.env("GIT_OPTIONAL_LOCKS", "0"); 365 } 366 let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {program}: {e}"))?; 367 if !out.status.success() { 368 return Err(format!( 369 "{program} {} failed: {}", 370 args.join(" "), 371 String::from_utf8_lossy(&out.stderr).trim() 372 )); 373 } 374 Ok(String::from_utf8_lossy(&out.stdout).into_owned()) 375 } 376 377 fn git(cwd: &Path, args: &[&str]) -> Result { 378 run_cmd(cwd, "git", args) 379 } 380 381 /// One sibling checkout a repository's gates reach as `../`: a 382 /// read-only checkout of `/` at `refs/remotes/origin/` 383 /// as that trusted clone has it when the run starts (never fetched for the 384 /// run, never the network). 385 #[derive(Debug, Clone, PartialEq, Eq)] 386 pub struct Sibling { 387 pub dir: String, 388 pub source: String, 389 pub git_ref: String, 390 } 391 392 /// A branch name the sibling map accepts: letters, digits, `.`, `_`, `-` and 393 /// `/` between non-empty parts that do not start with a dot (so no `..`, no 394 /// leading `-`, nothing git would read as an option or a path escape). 395 pub fn valid_ref(r: &str) -> bool { 396 !r.is_empty() 397 && r.len() <= 200 398 && !r.starts_with('-') 399 && r.split('/').all(|p| !p.is_empty() && !p.starts_with('.')) 400 && r.bytes() 401 .all(|b| b.is_ascii_alphanumeric() || b"._-/".contains(&b)) 402 } 403 404 /// Parse the sibling map (` ` per line, `#` 405 /// comments) and return the siblings of `repo`. Every line is checked, not 406 /// only `repo`'s: a malformed map is refused as a whole. 407 pub fn parse_siblings(text: &str, repo: &str) -> Result, String> { 408 let mut out: Vec = Vec::new(); 409 let mut seen = std::collections::BTreeSet::new(); 410 for (n, raw) in text.lines().enumerate() { 411 let line = raw.split('#').next().unwrap_or("").trim(); 412 if line.is_empty() { 413 continue; 414 } 415 let f: Vec<&str> = line.split_whitespace().collect(); 416 let bad = |why: &str| format!("sibling map line {}: {why}: {raw:?}", n + 1); 417 if f.len() != 4 { 418 return Err(bad("needs ")); 419 } 420 if !valid_repo_key(f[0]) || !valid_repo_key(f[1]) || !valid_repo_key(f[2]) { 421 return Err(bad("repo, dir and source must be plain names")); 422 } 423 if !valid_ref(f[3]) { 424 return Err(bad("bad ref")); 425 } 426 if f[1] == f[0] { 427 return Err(bad("a sibling cannot take the checkout's own name")); 428 } 429 if !seen.insert((f[0], f[1])) { 430 return Err(bad("the same dir twice for one repository")); 431 } 432 if f[0] != repo { 433 continue; 434 } 435 out.push(Sibling { 436 dir: f[1].to_string(), 437 source: f[2].to_string(), 438 git_ref: f[3].to_string(), 439 }); 440 } 441 Ok(out) 442 } 443 444 /// The siblings of `repo` from `cfg.siblings` (none without a map). A map 445 /// that cannot be read or parsed refuses the run: a gate must never run 446 /// against a half-provided neighbourhood without anyone noticing. 447 fn siblings_for(cfg: &Config, repo: &str) -> Result, String> { 448 let Some(path) = &cfg.siblings else { 449 return Ok(Vec::new()); 450 }; 451 let text = fs::read_to_string(path) 452 .map_err(|e| format!("cannot read the sibling map {}: {e}", path.display()))?; 453 parse_siblings(&text, repo) 454 } 455 456 /// One commit a repository's gates check out from a sibling (`pin` in its 457 /// `tests/gates/run.sh`): the sibling's source repository and the commit. 458 #[derive(Debug, Clone, PartialEq, Eq)] 459 pub struct Pin { 460 pub source: String, 461 pub sha: String, 462 } 463 464 /// Parse the pin list (`tools/aien-local-ci/pins` beside the sibling map; 465 /// ` ` per line, `#` comments) and return the 466 /// pins of `repo`. Every line is checked, as in the sibling map. 467 pub fn parse_pins(text: &str, repo: &str) -> Result, String> { 468 let mut out = Vec::new(); 469 for (n, raw) in text.lines().enumerate() { 470 let line = raw.split('#').next().unwrap_or("").trim(); 471 if line.is_empty() { 472 continue; 473 } 474 let f: Vec<&str> = line.split_whitespace().collect(); 475 let bad = |why: &str| format!("pin list line {}: {why}: {raw:?}", n + 1); 476 if f.len() != 3 { 477 return Err(bad("needs ")); 478 } 479 if !valid_repo_key(f[0]) || !valid_repo_key(f[1]) { 480 return Err(bad("repo and source must be plain names")); 481 } 482 if !valid_sha(f[2]) { 483 return Err(bad("the commit must be a full lowercase sha")); 484 } 485 if f[0] == repo { 486 out.push(Pin { 487 source: f[1].to_string(), 488 sha: f[2].to_string(), 489 }); 490 } 491 } 492 Ok(out) 493 } 494 495 /// The pins of `repo` from the `pins` file beside the sibling map (none 496 /// without a map or without the file). A file that exists but cannot be read 497 /// or parsed refuses the run, like a broken sibling map. 498 fn pins_for(cfg: &Config, repo: &str) -> Result, String> { 499 let Some(map) = &cfg.siblings else { 500 return Ok(Vec::new()); 501 }; 502 let path = map.with_file_name("pins"); 503 if !path.exists() { 504 return Ok(Vec::new()); 505 } 506 let text = fs::read_to_string(&path) 507 .map_err(|e| format!("cannot read the pin list {}: {e}", path.display()))?; 508 parse_pins(&text, repo) 509 } 510 511 /// Make every pinned commit of a sibling present in that sibling's trusted 512 /// clone before the siblings are made, so the sandbox (which has no network) 513 /// finds it. Runs on the trusted side at provisioning time only: a missing 514 /// commit is fetched by its sha from the clone's own `origin`, then held by 515 /// `refs/remotes/aien-pins/` so `wt.sh sync` copies it into the mirror and 516 /// `git gc` keeps it. A pin that cannot be made present is a note; the gate 517 /// that needs it then fails on the missing commit, never PASS. 518 pub fn ensure_pins(clones: &Path, pins: &[Pin], sibs: &[Sibling], notes: &mut Vec) { 519 for p in pins { 520 if !sibs.iter().any(|s| s.source == p.source) { 521 notes.push(format!( 522 "pin {}@{}: {} is not a sibling of this repository; not provided", 523 p.source, p.sha, p.source 524 )); 525 continue; 526 } 527 let src = clones.join(&p.source); 528 let want = format!("{}^{{commit}}", p.sha); 529 let present = |src: &Path| git(src, &["cat-file", "-e", &want]).is_ok(); 530 if !present(&src) { 531 match git(&src, &["fetch", "--quiet", "origin", &p.sha]) { 532 Ok(_) if present(&src) => { 533 notes.push(format!("pin {}@{}: fetched from origin", p.source, p.sha)) 534 } 535 Ok(_) => { 536 notes.push(format!( 537 "pin {}@{}: fetch gave no such commit; not provided", 538 p.source, p.sha 539 )); 540 continue; 541 } 542 Err(e) => { 543 notes.push(format!("pin {}@{}: not provided: {e}", p.source, p.sha)); 544 continue; 545 } 546 } 547 } 548 let r = format!("refs/remotes/aien-pins/{}", p.sha); 549 if let Err(e) = git(&src, &["update-ref", &r, &p.sha]) { 550 notes.push(format!( 551 "pin {}@{}: cannot hold it in {r}: {e}", 552 p.source, p.sha 553 )); 554 } 555 } 556 } 557 558 /// Where a head runs: `///` holds the checkout under test 559 /// at `/` and its siblings beside it, so `../` in the checkout is 560 /// the sibling. `nested` is false only for an older `wt.sh` that still makes 561 /// the checkout at the run directory itself (then no siblings are possible). 562 struct Checkout { 563 clone: PathBuf, 564 wt: PathBuf, 565 run_dir: PathBuf, 566 nested: bool, 567 } 568 569 /// Make the read-only sibling checkouts of one head, each from its trusted 570 /// clone at the clone's `origin/`. A sibling that cannot be made is a 571 /// note (its gates then fail on the missing directory, never PASS); every 572 /// sibling made is journaled with its commit. Returns what to remove later 573 /// under `Sandbox::None`, and the receipt `pins` (ADR 0028: `{name, commit}` 574 /// sorted by `name`): each sibling made, named by its `dir`, and each operator 575 /// pin, named `pin:`. They enter `core.pins` and `cache.key`, so a 576 /// result is reused only while every sibling is at the same commit. 577 fn provision_siblings( 578 cfg: &Config, 579 repo: &str, 580 sha: &str, 581 co: &Checkout, 582 sibs: &[Sibling], 583 pins: &[Pin], 584 notes: &mut Vec, 585 ) -> (Vec<(PathBuf, PathBuf)>, Value) { 586 let mut made = Vec::new(); 587 let mut pin_entries: Vec<(String, String)> = Vec::new(); 588 if !sibs.is_empty() && !co.nested { 589 notes.push(format!( 590 "siblings not provided: the worktree tool makes the old flat layout (update {})", 591 cfg.wt_tool 592 .as_ref() 593 .map(|t| t.display().to_string()) 594 .unwrap_or_default() 595 )); 596 return (made, json!([])); 597 } 598 for s in sibs { 599 let src = cfg.clones.join(&s.source); 600 let want = format!("refs/remotes/origin/{}^{{commit}}", s.git_ref); 601 let sib_sha = match git(&src, &["rev-parse", "--verify", "--quiet", &want]) { 602 Ok(o) if valid_sha(o.trim()) => o.trim().to_string(), 603 _ => { 604 notes.push(format!( 605 "sibling ../{}: {} has no origin/{}; not provided", 606 s.dir, 607 src.display(), 608 s.git_ref 609 )); 610 continue; 611 } 612 }; 613 let path = co.run_dir.join(&s.dir); 614 let res = if cfg.sandbox == Sandbox::User { 615 let tool = cfg 616 .wt_tool 617 .as_ref() 618 .map(|t| t.display().to_string()) 619 .unwrap_or_default(); 620 let src_s = src.display().to_string(); 621 run_cmd(&src, &tool, &["sync", &s.source, &src_s]).and_then(|_| { 622 run_cmd( 623 &src, 624 &tool, 625 &["sibling", repo, sha, &s.dir, &s.source, &sib_sha], 626 ) 627 }) 628 } else { 629 let _ = git(&src, &["worktree", "prune"]); 630 git( 631 &src, 632 &[ 633 "worktree", 634 "add", 635 "--detach", 636 "--quiet", 637 &path.display().to_string(), 638 &sib_sha, 639 ], 640 ) 641 }; 642 match res { 643 Ok(_) => { 644 notes.push(format!( 645 "sibling ../{}: {} origin/{} {}", 646 s.dir, s.source, s.git_ref, sib_sha 647 )); 648 made.push((src, path)); 649 pin_entries.push((s.dir.clone(), sib_sha)); 650 } 651 Err(e) => notes.push(format!("sibling ../{}: not provided: {e}", s.dir)), 652 } 653 } 654 for p in pins { 655 pin_entries.push((format!("pin:{}", p.source), p.sha.clone())); 656 } 657 // ADR 0028 receipt member `pins`: `{name, commit}` sorted by `name`. 658 pin_entries.sort(); 659 let pin_json: Vec = pin_entries 660 .into_iter() 661 .map(|(name, commit)| json!({ "name": name, "commit": commit })) 662 .collect(); 663 (made, Value::Array(pin_json)) 664 } 665 666 /// Under `Sandbox::User`: make the worktree with INFRA's `wt.sh` (`sync` the 667 /// mirror from the trusted clone, `add` the head), so `aien-run` can read its 668 /// git data and write its files while the `.git` link stays root-owned. An 669 /// older tree for the same head is removed first and never reused (a `main` 670 /// qualification must not inherit what a pull request run left behind). 671 fn checkout_for_sandbox( 672 cfg: &Config, 673 repo: &str, 674 sha: &str, 675 clone: &Path, 676 ) -> Result<(PathBuf, PathBuf, bool), String> { 677 let tool = cfg.wt_tool.as_ref().ok_or_else(|| { 678 "--sandbox user needs INFRA's worktree tool (--wt-tool, tools/aien-local-ci/wt.sh): \ 679 a checkout made from the private clone is unreadable to aien-run" 680 .to_string() 681 })?; 682 let tool = tool.display().to_string(); 683 let clone_s = clone.display().to_string(); 684 run_cmd(clone, &tool, &["sync", repo, &clone_s])?; 685 let mirror = cfg.mirror_root.join(format!("{repo}.git")); 686 let commit = format!("{sha}^{{commit}}"); 687 if git(&mirror, &["cat-file", "-e", &commit]).is_err() { 688 // A head no branch names (a pull request head, a trigger for a 689 // detached commit): fetch that one commit into the mirror. 690 git(&mirror, &["fetch", "--quiet", &clone_s, sha])?; 691 } 692 git(&mirror, &["cat-file", "-e", &commit]) 693 .map_err(|_| format!("commit {sha} is not in {}", mirror.display()))?; 694 let run_dir = cfg.wt_root.join(repo).join(sha); 695 if fs::symlink_metadata(&run_dir).is_ok() { 696 run_cmd(clone, &tool, &["remove", repo, sha])?; 697 } 698 let made = run_cmd(clone, &tool, &["add", repo, sha])?; 699 let made = PathBuf::from(made.trim()); 700 // The run directory holds the checkout at `/` (siblings beside it); 701 // an older wt.sh still makes the checkout at the run directory itself. 702 let nested = made == run_dir.join(repo); 703 if !nested && made != run_dir { 704 return Err(format!( 705 "{tool} made {:?}, expected {}", 706 made, 707 run_dir.join(repo).display() 708 )); 709 } 710 if let Err(e) = check_worktree_link(&made, &mirror) { 711 let _ = run_cmd(clone, &tool, &["remove", repo, sha]); 712 return Err(e); 713 } 714 Ok((made, run_dir, nested)) 715 } 716 717 /// The checks that make a `wt.sh` worktree safe to open with the operator's 718 /// git: the directory is no symlink, its `.git` is a regular root-owned file 719 /// nobody else can write, and it points into `/worktrees/`. 720 pub fn check_worktree_link(wt: &Path, mirror: &Path) -> Result<(), String> { 721 use std::os::unix::fs::MetadataExt; 722 let canon = fs::canonicalize(wt).map_err(|e| format!("{}: {e}", wt.display()))?; 723 if canon != wt { 724 return Err(format!("{} is not a plain directory path", wt.display())); 725 } 726 let link = wt.join(".git"); 727 let md = fs::symlink_metadata(&link).map_err(|e| format!("{}: {e}", link.display()))?; 728 if !md.file_type().is_file() || md.uid() != 0 || md.mode() & 0o022 != 0 { 729 return Err(format!( 730 "{} must be a root-owned file nobody else can write (uid {}, mode {:o})", 731 link.display(), 732 md.uid(), 733 md.mode() & 0o7777 734 )); 735 } 736 let text = fs::read_to_string(&link).map_err(|e| format!("{}: {e}", link.display()))?; 737 let target = text 738 .trim_end_matches('\n') 739 .strip_prefix("gitdir: ") 740 .ok_or_else(|| format!("{} has no gitdir line", link.display()))?; 741 let target = Path::new(target); 742 let want = mirror.join("worktrees"); 743 if target.parent() != Some(want.as_path()) 744 || target 745 .components() 746 .any(|c| c == std::path::Component::ParentDir) 747 { 748 return Err(format!( 749 "{} points to {}, not into {}", 750 link.display(), 751 target.display(), 752 want.display() 753 )); 754 } 755 Ok(()) 756 } 757 758 /// Fetch the clone and add a detached worktree for `sha`. The clone's own 759 /// checkout is never touched. 760 fn checkout( 761 cfg: &Config, 762 repo: &str, 763 sha: &str, 764 notes: &mut Vec, 765 ) -> Result { 766 let clone = cfg.clones.join(repo); 767 if !clone.join(".git").exists() && !clone.join("HEAD").exists() { 768 return Err(format!("no trusted clone at {}", clone.display())); 769 } 770 let present = |c: &Path| git(c, &["cat-file", "-e", &format!("{sha}^{{commit}}")]).is_ok(); 771 if !present(&clone) { 772 if let Err(e) = git(&clone, &["fetch", "--quiet", "--all"]) { 773 notes.push(format!("fetch failed: {e}")); 774 } 775 } else if let Err(e) = git(&clone, &["fetch", "--quiet", "--all"]) { 776 notes.push(format!("fetch failed (commit already present): {e}")); 777 } 778 if !present(&clone) { 779 return Err(format!("commit {sha} is not in {}", clone.display())); 780 } 781 if cfg.sandbox == Sandbox::User { 782 let (wt, run_dir, nested) = checkout_for_sandbox(cfg, repo, sha, &clone)?; 783 return Ok(Checkout { 784 clone, 785 wt, 786 run_dir, 787 nested, 788 }); 789 } 790 let run_dir = cfg.wt_root.join(repo).join(sha); 791 let wt = run_dir.join(repo); 792 if fs::symlink_metadata(&run_dir).is_ok() { 793 let _ = git( 794 &clone, 795 &["worktree", "remove", "--force", &wt.display().to_string()], 796 ); 797 let _ = fs::remove_dir_all(&run_dir); 798 let _ = git(&clone, &["worktree", "prune"]); 799 } 800 fs::create_dir_all(&run_dir) 801 .map_err(|e| format!("cannot create {}: {e}", run_dir.display()))?; 802 git( 803 &clone, 804 &[ 805 "worktree", 806 "add", 807 "--detach", 808 "--quiet", 809 &wt.display().to_string(), 810 sha, 811 ], 812 )?; 813 Ok(Checkout { 814 clone, 815 wt, 816 run_dir, 817 nested: true, 818 }) 819 } 820 821 /// `Sandbox::None`: remove the checkout, every sibling made for it and the 822 /// run directory, and prune each clone's worktree list. 823 fn remove_checkout(co: &Checkout, made: &[(PathBuf, PathBuf)]) { 824 let _ = git( 825 &co.clone, 826 &[ 827 "worktree", 828 "remove", 829 "--force", 830 &co.wt.display().to_string(), 831 ], 832 ); 833 for (src, p) in made { 834 let _ = git( 835 src, 836 &["worktree", "remove", "--force", &p.display().to_string()], 837 ); 838 } 839 let _ = fs::remove_dir_all(&co.run_dir); 840 let _ = git(&co.clone, &["worktree", "prune"]); 841 for (src, _) in made { 842 let _ = git(src, &["worktree", "prune"]); 843 } 844 } 845 846 fn crumb(cfg: &Config, clone: &Path, sha: &str, wt: &Path, args: &[&str], notes: &mut Vec) { 847 let Some(c) = &cfg.crumb else { 848 return; 849 }; 850 if !wt.join(".crumb").exists() { 851 notes.push(format!( 852 "crumb {}: no .crumb at the worktree root, skipped", 853 args[0] 854 )); 855 return; 856 } 857 let base = match plan::base_for(clone, &cfg.base_ref, sha) { 858 Ok((base, _)) => base, 859 Err(e) => { 860 notes.push(format!("crumb {}: no trusted base: {e}", args[0])); 861 return; 862 } 863 }; 864 let tool = match verify::crumb_tool_for(clone, &base, c, &cfg.state.root.join("crumb-tool")) { 865 verify::CrumbTool::Pinned { path, .. } => path, 866 verify::CrumbTool::Unpinned(path) => PathBuf::from(path), 867 verify::CrumbTool::Unavailable(why) => { 868 notes.push(format!( 869 "crumb {}: trusted tool unavailable: {why}", 870 args[0] 871 )); 872 return; 873 } 874 }; 875 match run_cmd(wt, &tool.to_string_lossy(), args) { 876 Ok(_) => {} 877 Err(e) => notes.push(format!("crumb {}: {e}", args[0])), 878 } 879 } 880 881 /// Verify one head end to end. Never panics on GitHub trouble. 882 pub fn run_once(cfg: &Config, repo: &str, sha: &str) -> Result { 883 run_once_in(cfg, repo, sha, None) 884 } 885 886 /// What one head of a batch gets from `run_batch`: the shared budget and the 887 /// gates other heads of the batch also select. 888 pub type Share = ( 889 std::sync::Arc, 890 BTreeSet, 891 ); 892 893 /// `run_once` as one head of a batch (`share`), or alone (None). 894 pub fn run_once_in( 895 cfg: &Config, 896 repo: &str, 897 sha: &str, 898 share: Option<&Share>, 899 ) -> Result { 900 // Refusals first: nothing is fetched, checked out or run before these. 901 if !valid_repo_key(repo) { 902 return Err(format!("refusing repository name {repo:?}")); 903 } 904 if !valid_sha(sha) { 905 return Err(format!( 906 "refusing commit {sha:?}: a lowercase 40-hex id is required" 907 )); 908 } 909 // Development mode needs the explicit opt-in; the CLI also refuses it 910 // with `--github` (tests post to a fake `gh` without the helper). 911 cfg.check_sandbox_policy_for(false)?; 912 check_key_private(&cfg.key)?; 913 if cfg.sandbox == Sandbox::User && cfg.wt_tool.is_none() { 914 return Err( 915 "--sandbox user needs INFRA's worktree tool (--wt-tool, tools/aien-local-ci/wt.sh)" 916 .to_string(), 917 ); 918 } 919 // The sibling map is read before anything is checked out: a broken map 920 // refuses the run instead of leaving a half-made neighbourhood. 921 let sibs = siblings_for(cfg, repo)?; 922 let pins = pins_for(cfg, repo)?; 923 let mut notes: Vec = Vec::new(); 924 // One judge per head at a time, across processes (the batch, `--once`, 925 // the loop): a second one would rewrite the same bundle and evidence. 926 let head_lock = cfg.state.head_lock(repo, sha); 927 // Tried for up to two seconds: a child another thread forks holds a copy 928 // of the descriptor until it execs, so a lock just released can look held 929 // for a moment; a real second judge holds it for the whole run. 930 let deadline = std::time::Instant::now() + Duration::from_secs(2); 931 let _head = loop { 932 match crate::resources::try_lock(&head_lock) { 933 Ok(Some(l)) => break l, 934 Ok(None) if std::time::Instant::now() < deadline => { 935 std::thread::sleep(Duration::from_millis(50)) 936 } 937 Ok(None) => { 938 return Err(format!( 939 "{repo} {sha} is already being judged by another worker" 940 )) 941 } 942 Err(e) => { 943 return Err(format!( 944 "cannot take the head lock {}: {e}", 945 head_lock.display() 946 )) 947 } 948 } 949 }; 950 cfg.state.beat(repo, sha, "checkout"); 951 // Heads of one batch share the clones and mirrors: checkouts, pins and 952 // sibling worktrees are made one head at a time (git's own locks refuse 953 // concurrent `worktree add` on one repository). 954 let prep = lock_prep(); 955 let co = checkout(cfg, repo, sha, &mut notes)?; 956 ensure_pins(&cfg.clones, &pins, &sibs, &mut notes); 957 let (made, pin_values) = provision_siblings(cfg, repo, sha, &co, &sibs, &pins, &mut notes); 958 drop(prep); 959 let (clone, wt) = (co.clone.clone(), co.wt.clone()); 960 // A wt.sh worktree belongs to aien-run; the operator's git opens it only 961 // after `check_worktree_link` (see `process::trust_worktree`). 962 let trust = (cfg.sandbox == Sandbox::User).then(|| process::trust_worktree(&wt)); 963 // Every sibling's commit is in `opts.pins` (`core.pins` and `cache.key`), 964 // and the evidence directory is this head's own (`evidence//`): 965 // a result from another head arrives only through the shared store, for a 966 // gate `cache::cross_head` lets out, with every sibling at the same commit. 967 // A declared sibling that could not be made turns the cache off for the 968 // whole head. 969 let fresh = made.len() < sibs.len(); 970 let result = run_in_worktree( 971 cfg, 972 repo, 973 sha, 974 &co, 975 HeadCache { 976 fresh, 977 pins: pin_values, 978 share, 979 }, 980 &mut notes, 981 ); 982 crumb( 983 cfg, 984 &clone, 985 sha, 986 &wt, 987 &[ 988 "close", 989 "aien-worker", 990 ".", 991 "worker", 992 "test", 993 "local verification finished", 994 ], 995 &mut notes, 996 ); 997 drop(trust); 998 let prep = lock_prep(); 999 if cfg.sandbox == Sandbox::User { 1000 if let Some(tool) = &cfg.wt_tool { 1001 let tool = tool.display().to_string(); 1002 if let Err(e) = run_cmd(&clone, &tool, &["remove", repo, sha]) { 1003 notes.push(format!("worktree not removed: {e}")); 1004 } 1005 } 1006 } else { 1007 remove_checkout(&co, &made); 1008 } 1009 drop(prep); 1010 cfg.state.beat(repo, sha, "idle"); 1011 let mut summary = result?; 1012 summary.notes.append(&mut notes); 1013 Ok(summary) 1014 } 1015 1016 /// What the cache of one head rests on: `fresh` (a declared sibling could not 1017 /// be made, so nothing is reused), the sibling and operator `pins`, and the 1018 /// batch it belongs to, if any. 1019 struct HeadCache<'a> { 1020 fresh: bool, 1021 pins: Value, 1022 share: Option<&'a Share>, 1023 } 1024 1025 fn run_in_worktree( 1026 cfg: &Config, 1027 repo: &str, 1028 sha: &str, 1029 co: &Checkout, 1030 hc: HeadCache<'_>, 1031 notes: &mut Vec, 1032 ) -> Result { 1033 let HeadCache { fresh, pins, share } = hc; 1034 let (clone, wt) = (co.clone.as_path(), co.wt.as_path()); 1035 let started = now_secs(); 1036 let repository = plan::repository_name(clone, None); 1037 1038 // Plan against the base ref; a head already on the base line is planned 1039 // against its first parent so a push to main still verifies what it 1040 // changed (the same rule `verify` uses). 1041 cfg.state.beat(repo, sha, "plan"); 1042 let (base, on_main) = plan::base_for(wt, &cfg.base_ref, sha)?; 1043 let mut req = plan::Request::new(&base, sha); 1044 req.operator = cfg.operator; 1045 req.full = cfg.full; 1046 req.hardware_identity = cfg.hardware_identity.clone(); 1047 let plan = plan::compute(wt, &req)?; 1048 if !plan 1049 .entries 1050 .iter() 1051 .any(|entry| entry.section == plan::Section::Blocked) 1052 { 1053 crumb( 1054 cfg, 1055 clone, 1056 sha, 1057 wt, 1058 &[ 1059 "claim", 1060 "aien-worker", 1061 ".", 1062 "worker", 1063 "local verification", 1064 "7200", 1065 ], 1066 notes, 1067 ); 1068 } 1069 1070 // Run what the plan selects, through the sandbox and the pools. 1071 cfg.state.beat(repo, sha, "run"); 1072 let evidence_dir = cfg.state.evidence(repo, sha); 1073 fs::create_dir_all(&evidence_dir).map_err(|e| format!("cannot create evidence dir: {e}"))?; 1074 let mut opts = Options::new(evidence_dir.clone()); 1075 opts.sandbox = cfg.sandbox; 1076 opts.cargo_target_dir = target_dir_for(cfg, repo, sha, on_main); 1077 opts.target_lock_dir = cfg.state.target_lock_dir(); 1078 opts.pool_sizes = opts.pool_sizes.with(cfg.jobs); 1079 opts.gpu.wait = cfg.gpu_wait; 1080 opts.pins = pins; 1081 // The same operator permission the plan had: an operator gate the plan 1082 // put in Required under `--operator` must not be refused by the runner. 1083 opts.operator = cfg.operator; 1084 if fresh || cfg.no_cache { 1085 opts.no_cache = true; 1086 } 1087 // A result whose key another head of this repository already has is 1088 // reused from there (`cache::Shared`); the bundle entry names that head. 1089 opts.shared_cache = Some(crate::cache::Shared::new(&cfg.state.gate_cache(repo))); 1090 if let Some((budget, first)) = share { 1091 opts.batch = Some(budget.clone()); 1092 opts.first = first.clone(); 1093 } 1094 let mut known: BTreeMap = BTreeMap::new(); 1095 let mut notes_cache: BTreeMap = BTreeMap::new(); 1096 if plan.blocked.is_none() && !plan.entries.is_empty() { 1097 let g = graph::load(wt).map_err(|e| e.to_string())?; 1098 let mut sel = std::collections::BTreeSet::new(); 1099 for e in plan 1100 .entries 1101 .iter() 1102 .filter(|e| e.section != Section::Blocked) 1103 { 1104 match g.index_of(&e.gate) { 1105 Some(i) => { 1106 sel.insert(i); 1107 } 1108 None => notes.push(format!( 1109 "gate {} is in the plan but not in the worktree graph", 1110 e.gate 1111 )), 1112 } 1113 } 1114 let campaign = runner::run_graph(wt, &g, &sel, &opts).map_err(|e| e.to_string())?; 1115 for (id, o) in campaign.results { 1116 known.insert( 1117 id.clone(), 1118 Known { 1119 verdict: o.verdict, 1120 reason: o.reason.clone(), 1121 receipt: o.receipt_digest.clone(), 1122 }, 1123 ); 1124 notes_cache.insert(id, o.cache); 1125 } 1126 } 1127 let judged = plan::judge(&plan, &known); 1128 1129 // The bundle. 1130 cfg.state.beat(repo, sha, "bundle"); 1131 let key = bundle::load_signing_key(&cfg.key)?; 1132 let vk = key.verifying_key(); 1133 let machine = runner::machine(&Hardware::detect()); 1134 let machine_digest = canonical_digest(&machine).map_err(|e| e.to_string())?; 1135 let tree = git(wt, &["rev-parse", &format!("{sha}^{{tree}}")])?; 1136 let mut checks: Vec = Vec::new(); 1137 let mut entries: Vec<(bool, String, String)> = Vec::new(); 1138 let mut gates: Vec<(String, String, Verdict)> = Vec::new(); 1139 for e in &plan.entries { 1140 let (eff, _) = judged 1141 .gates 1142 .get(&e.gate) 1143 .cloned() 1144 .unwrap_or((Verdict::NotRun, String::new())); 1145 let k = known.get(&e.gate); 1146 let (status, verdict, extra): (&str, String, Value) = 1147 match (e.section, k, notes_cache.get(&e.gate)) { 1148 (Section::Blocked, _, _) => ("blocked", bundle_verdict(eff), json!({})), 1149 (_, Some(k), Some(CacheNote::Reused { from, commit })) if k.receipt.is_some() => ( 1150 "cached", 1151 bundle_verdict(eff), 1152 json!({ "resolution": { 1153 "resolved_from": from, 1154 "resolved_from_commit": commit, 1155 "receipt": k.receipt, 1156 } }), 1157 ), 1158 (_, Some(k), _) if k.receipt.is_some() => { 1159 ("run", bundle_verdict(eff), json!({ "receipt": k.receipt })) 1160 } 1161 _ => ( 1162 "not_run", 1163 bundle_verdict(if eff == Verdict::Pass { 1164 Verdict::NotRun 1165 } else { 1166 eff 1167 }), 1168 json!({}), 1169 ), 1170 }; 1171 let mut entry = json!({ 1172 "gate": e.gate, 1173 "check_id": e.check_id, 1174 "exactness": e.exactness.as_str(), 1175 "required": e.required, 1176 "status": status, 1177 "verdict": verdict, 1178 "backend": e.pool, 1179 }); 1180 if let (Some(dst), Some(src)) = (entry.as_object_mut(), extra.as_object()) { 1181 for (k, v) in src { 1182 dst.insert(k.clone(), v.clone()); 1183 } 1184 } 1185 checks.push(entry); 1186 entries.push((e.required, status.to_string(), verdict.clone())); 1187 gates.push((e.gate.clone(), status.to_string(), eff)); 1188 } 1189 let bundle_verdict = bundle::compute_verdict(&entries).to_string(); 1190 let unsigned = json!({ 1191 "schema": bundle::SCHEMA, 1192 "repository": repository, 1193 "commit": sha, 1194 "tree_digest": sha256_hex(tree.trim().as_bytes()), 1195 "graph_digest": plan.graph_digest, 1196 "receipt_id_scheme": "sha256-canonical-json", 1197 "checks": checks, 1198 "verdict": bundle_verdict, 1199 "executor": { "id": bundle::fingerprint(&vk), "class": EXECUTOR_CLASS, "machine_digest": machine_digest }, 1200 "started_utc": utc_string(started), 1201 "finished_utc": utc_string(now_secs()), 1202 // The planner's verdict beside the bundle algebra: a bundle with no 1203 // required checks is PASS by the algebra (nothing required failed) 1204 // while the plan may say NOT_RUN UNMAPPED_PATH or BLOCKED. Readers 1205 // that gate on the plan read this; `verify` recomputes it anyway. 1206 "plan": { 1207 "verdict": judged.verdict.as_str(), 1208 "reason": judged.reason, 1209 "unmapped": plan.unmapped, 1210 "removed": plan.removed, 1211 "blocked": plan.blocked, 1212 // `full` (every gate at HEAD: an Alpha qualification) or 1213 // `changed` (what the diff selects); signed with the rest, and 1214 // `verify` plans in the same scope. No member means `changed`. 1215 "scope": plan.scope(), 1216 }, 1217 }); 1218 let signed = bundle::sign(&unsigned, &key).map_err(|r| format!("cannot sign bundle: {r}"))?; 1219 let bytes = canonical(&signed).map_err(|e| e.to_string())?; 1220 let bundle_digest = sha256_hex(&bytes); 1221 let bundle_path = cfg.state.bundle_path(repo, sha); 1222 fs::create_dir_all(bundle_path.parent().unwrap_or(&cfg.state.root)) 1223 .map_err(|e| format!("cannot create bundle dir: {e}"))?; 1224 fs::write(&bundle_path, &bytes).map_err(|e| format!("cannot write bundle: {e}"))?; 1225 1226 // The independent check of what was just written, exactly as `verify` 1227 // does it: keys at BASE, signature, graph digest, receipts, manifests, 1228 // crumb, with the same operator permission the plan had (a pipeline 1229 // configuration change the operator ran by hand is not BLOCKED here). 1230 // Nothing is published as success unless this says READY. 1231 cfg.state.beat(repo, sha, "verify"); 1232 let check = verify::run( 1233 clone, 1234 &verify::Ask { 1235 state: cfg.state.clone(), 1236 commit: sha.to_string(), 1237 base: plan.base.clone(), 1238 repository: Some(repository.clone()), 1239 release: false, 1240 operator: cfg.operator, 1241 hardware_identity: cfg.hardware_identity.clone(), 1242 crumb: cfg.crumb.clone(), 1243 keys_override: None, 1244 }, 1245 ); 1246 let ready = check.ready; 1247 let check_problems: Vec = check 1248 .lines 1249 .iter() 1250 .filter(|l| { 1251 l.starts_with("Problem: ") 1252 || l.starts_with("Evidence note: ") 1253 || l.starts_with("Crumb note: ") 1254 }) 1255 .cloned() 1256 .collect(); 1257 1258 // Publication, then the journal. 1259 cfg.state.beat(repo, sha, "publish"); 1260 let publication = if cfg.github { 1261 let status = Status { 1262 repository: repository.clone(), 1263 sha: sha.to_string(), 1264 state: publish_state(ready, &bundle_verdict, judged.verdict).to_string(), 1265 description: format!( 1266 "{} {} {}: bundle {}", 1267 if ready { "READY" } else { "BLOCKED" }, 1268 bundle_verdict, 1269 judged.reason, 1270 bundle_path.display() 1271 ) 1272 .chars() 1273 .take(140) 1274 .collect(), 1275 }; 1276 match post_status(&cfg.gh, &status) { 1277 Ok(()) => "posted".to_string(), 1278 Err(e) => { 1279 notes.push(format!("GitHub unreachable, status queued: {e}")); 1280 queue_status(&cfg.state, repo, &status)?; 1281 "pending".to_string() 1282 } 1283 } 1284 } else { 1285 "local".to_string() 1286 }; 1287 let unmapped = plan.unmapped.clone(); 1288 cfg.state.journal_append(&json!({ 1289 "utc": utc_string(now_secs()), 1290 "repo": repo, 1291 "repository": repository, 1292 "sha": sha, 1293 "base": plan.base, 1294 "scope": plan.scope(), 1295 "verdict": judged.verdict.as_str(), 1296 "reason": judged.reason, 1297 "bundle_verdict": bundle_verdict, 1298 "bundle": bundle_path.display().to_string(), 1299 "bundle_digest": bundle_digest, 1300 "graph_digest": plan.graph_digest, 1301 "gates": gates.iter().map(|(g, s, v)| json!({ "gate": g, "status": s, "verdict": v.as_str() })).collect::>(), 1302 "unmapped": unmapped, 1303 "verify": if ready { "READY" } else { "BLOCKED" }, 1304 "verify_notes": check_problems, 1305 "publication": publication, 1306 "notes": notes, 1307 }))?; 1308 Ok(Summary { 1309 repo: repo.to_string(), 1310 sha: sha.to_string(), 1311 repository, 1312 verdict: judged.verdict, 1313 reason: judged.reason, 1314 bundle_verdict, 1315 bundle_path, 1316 bundle_digest, 1317 gates, 1318 publication, 1319 ready, 1320 notes: Vec::new(), 1321 }) 1322 } 1323 1324 /// `CARGO_TARGET_DIR` for the gates of one head. Under the user sandbox it is 1325 /// the head's OWN dir inside its trust class (A2): 1326 /// `//main/` for a head on the base line, 1327 /// `.../pr/` otherwise. Never shared between heads: cargo calls a 1328 /// workspace crate fresh by file times and a path relative to the workspace, 1329 /// so with one dir per class a head that built after this one was checked out 1330 /// had its binaries linked and run here, with its checkout path baked in 1331 /// (sc #605: SC-TEST, SC-AGENT-PREFLIGHT, SC-VERIFY-CLOSURE "No such file" in 1332 /// another head's worktree; #452: PREFILL-E2E-2 running a mutant). The exec 1333 /// helper accepts only this shape, with `` equal to the worktree's, and 1334 /// creates it on demand; `wt.sh remove` deletes it with the worktree. Never 1335 /// the worker's own target dir, which `aien-run` cannot write. Without the 1336 /// sandbox, the worker's own `CARGO_TARGET_DIR`. 1337 fn target_dir_for(cfg: &Config, repo: &str, sha: &str, on_main: bool) -> Option { 1338 match cfg.sandbox { 1339 Sandbox::None => std::env::var_os("CARGO_TARGET_DIR").map(PathBuf::from), 1340 Sandbox::User => { 1341 let class = if on_main { "main" } else { "pr" }; 1342 Some(cfg.target_root.join(repo).join(class).join(sha)) 1343 } 1344 } 1345 } 1346 1347 /// The commit status for a head: `success` only when the independent check 1348 /// of the bundle just written says READY; `failure` when the bundle or the 1349 /// plan says FAIL; `error` otherwise. 1350 pub fn publish_state(ready: bool, bundle_verdict: &str, judged: Verdict) -> &'static str { 1351 match github_state(bundle_verdict, judged) { 1352 "success" if !ready => "error", 1353 s => s, 1354 } 1355 } 1356 1357 fn bundle_verdict(v: Verdict) -> String { 1358 v.as_str().to_string() 1359 } 1360 1361 /// success only on PASS, failure on FAIL, error on anything else. 1362 pub fn github_state(bundle_verdict: &str, judged: Verdict) -> &'static str { 1363 match (bundle_verdict, judged) { 1364 ("PASS", Verdict::Pass) => "success", 1365 ("FAIL", _) | (_, Verdict::Fail) => "failure", 1366 _ => "error", 1367 } 1368 } 1369 1370 /// A commit status to post. 1371 #[derive(Debug, Clone, PartialEq, Eq)] 1372 pub struct Status { 1373 pub repository: String, 1374 pub sha: String, 1375 pub state: String, 1376 pub description: String, 1377 } 1378 1379 fn owner_repo(repository: &str) -> Option { 1380 let parts: Vec<&str> = repository.split('/').filter(|p| !p.is_empty()).collect(); 1381 if parts.len() >= 3 { 1382 Some(format!( 1383 "{}/{}", 1384 parts[parts.len() - 2], 1385 parts[parts.len() - 1] 1386 )) 1387 } else if parts.len() == 2 { 1388 Some(format!("{}/{}", parts[0], parts[1])) 1389 } else { 1390 None 1391 } 1392 } 1393 1394 /// `gh api -X POST repos/O/R/statuses/SHA ...`. 1395 pub fn post_status(gh: &str, s: &Status) -> Result<(), String> { 1396 let or = owner_repo(&s.repository) 1397 .ok_or_else(|| format!("cannot derive owner/repo from {}", s.repository))?; 1398 let mut cmd = Command::new(gh); 1399 cmd.args([ 1400 "api", 1401 "-X", 1402 "POST", 1403 &format!("repos/{or}/statuses/{}", s.sha), 1404 "-f", 1405 &format!("state={}", s.state), 1406 "-f", 1407 &format!("context={CONTEXT}"), 1408 "-f", 1409 &format!("description={}", s.description), 1410 ]); 1411 let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {gh}: {e}"))?; 1412 if out.status.success() { 1413 Ok(()) 1414 } else { 1415 Err(String::from_utf8_lossy(&out.stderr).trim().to_string()) 1416 } 1417 } 1418 1419 /// Queue a status in the outbox. File names start with a strictly increasing 1420 /// 20-digit sequence (nanoseconds since the epoch, bumped past the newest 1421 /// queued file), so the outbox replays in the order statuses were queued. A 1422 /// newer status for the same head replaces the older one and takes its place 1423 /// at the end of the queue: the latest state is what GitHub must end with. 1424 fn queue_status(state: &StateDir, repo: &str, s: &Status) -> Result<(), String> { 1425 let dir = state.outbox_dir(); 1426 fs::create_dir_all(&dir).map_err(|e| format!("cannot create outbox: {e}"))?; 1427 let suffix = format!(".{repo}.{}.json", s.sha); 1428 let mut newest: u128 = 0; 1429 for f in outbox_files(state) { 1430 let name = f 1431 .file_name() 1432 .map(|n| n.to_string_lossy().into_owned()) 1433 .unwrap_or_default(); 1434 if let Some(seq) = name.split('.').next().and_then(|n| n.parse::().ok()) { 1435 newest = newest.max(seq); 1436 } 1437 if name.ends_with(&suffix) || name == suffix.trim_start_matches('.') { 1438 let _ = fs::remove_file(&f); 1439 } 1440 } 1441 let now = SystemTime::now() 1442 .duration_since(UNIX_EPOCH) 1443 .map(|d| d.as_nanos()) 1444 .unwrap_or(0); 1445 let seq = now.max(newest + 1); 1446 let v = json!({ "repository": s.repository, "sha": s.sha, "state": s.state, "description": s.description }); 1447 let tmp = dir.join(format!(".tmp{suffix}")); 1448 fs::write(&tmp, serde_json::to_string(&v).unwrap_or_default()) 1449 .map_err(|e| format!("cannot write outbox: {e}"))?; 1450 fs::rename(&tmp, dir.join(format!("{seq:020}{suffix}"))) 1451 .map_err(|e| format!("cannot write outbox: {e}")) 1452 } 1453 1454 /// The queued status files, in queue order (`*.json`, by name). 1455 pub fn outbox_files(state: &StateDir) -> Vec { 1456 let Ok(rd) = fs::read_dir(state.outbox_dir()) else { 1457 return Vec::new(); 1458 }; 1459 let mut files: Vec = rd 1460 .flatten() 1461 .map(|e| e.path()) 1462 .filter(|p| { 1463 let n = p 1464 .file_name() 1465 .map(|n| n.to_string_lossy().into_owned()) 1466 .unwrap_or_default(); 1467 n.ends_with(".json") && !n.starts_with('.') 1468 }) 1469 .collect(); 1470 files.sort(); 1471 files 1472 } 1473 1474 /// Post the queued statuses in queue order; a success removes the file. The 1475 /// first failure stops the replay so nothing overtakes an older status; the 1476 /// rest stay queued for the next round. A file that is not a status is 1477 /// renamed to `*.bad` (journaled) so it cannot block the queue. Returns 1478 /// (posted, still pending). 1479 pub fn flush_outbox(cfg: &Config) -> (usize, usize) { 1480 let files = outbox_files(&cfg.state); 1481 let mut posted = 0; 1482 for (i, f) in files.iter().enumerate() { 1483 let status = fs::read_to_string(f) 1484 .ok() 1485 .and_then(|t| serde_json::from_str::(&t).ok()) 1486 .and_then(|v| { 1487 let s = Status { 1488 repository: v["repository"].as_str()?.to_string(), 1489 sha: v["sha"].as_str()?.to_string(), 1490 state: v["state"].as_str()?.to_string(), 1491 description: v["description"].as_str().unwrap_or("").to_string(), 1492 }; 1493 (valid_sha(&s.sha) 1494 && ["success", "failure", "error", "pending"].contains(&s.state.as_str())) 1495 .then_some(s) 1496 }); 1497 let Some(s) = status else { 1498 let _ = fs::rename(f, f.with_extension("bad")); 1499 let _ = cfg.state.journal_append(&json!({ 1500 "utc": utc_string(now_secs()), 1501 "publication": "dropped", 1502 "note": format!("outbox file {} is not a status; renamed to .bad", f.display()), 1503 })); 1504 continue; 1505 }; 1506 match post_status(&cfg.gh, &s) { 1507 Ok(()) => { 1508 let _ = fs::remove_file(f); 1509 posted += 1; 1510 let _ = cfg.state.journal_append(&json!({ 1511 "utc": utc_string(now_secs()), 1512 "sha": s.sha, 1513 "repository": s.repository, 1514 "state": s.state, 1515 "publication": "posted", 1516 "note": "flushed from outbox", 1517 })); 1518 } 1519 Err(_) => return (posted, files.len() - i), 1520 } 1521 } 1522 (posted, 0) 1523 } 1524 1525 /// Pending trigger files as (repo, sha), oldest first (modification time, 1526 /// then name). Names that are not `.<40-hex sha>` with a safe repo 1527 /// key are ignored. 1528 pub fn triggers(state: &StateDir) -> Vec<(String, String, PathBuf)> { 1529 let mut out = Vec::new(); 1530 if let Ok(rd) = fs::read_dir(state.trigger_dir()) { 1531 let mut files: Vec = rd.flatten().map(|e| e.path()).collect(); 1532 // Oldest first: by modification time, then by name. 1533 files.sort_by_key(|f| (fs::metadata(f).and_then(|m| m.modified()).ok(), f.clone())); 1534 for f in files { 1535 let name = f 1536 .file_name() 1537 .map(|n| n.to_string_lossy().into_owned()) 1538 .unwrap_or_default(); 1539 if let Some((repo, sha)) = name.rsplit_once('.') { 1540 let sha = sha.to_ascii_lowercase(); 1541 if valid_sha(&sha) && valid_repo_key(repo) { 1542 out.push((repo.to_string(), sha, f.clone())); 1543 } 1544 } 1545 } 1546 } 1547 out 1548 } 1549 1550 /// What the last answer to one GitHub list request said, kept with its ETag so the next poll can ask 1551 /// "has it changed?" (a 304 reply costs nothing against the hourly allowance; L337, G3-ci-judge-7). 1552 /// `next` is the following page path when the 200 that produced this ETag carried `Link: rel="next"`. 1553 /// A 304 omits that header, so the cached path is what the next poll follows. 1554 #[derive(Default)] 1555 pub struct GithubHeadCache { 1556 entries: std::collections::HashMap, 1557 } 1558 1559 struct CachedHeads { 1560 etag: String, 1561 heads: Vec, 1562 next: Option, 1563 } 1564 1565 /// The `rel="next"` target of a GitHub `Link` header, as a path `gh api` accepts. 1566 /// None when this page is the last. Absolute `api.github.com` URLs are stripped to the path. 1567 fn link_next(headers: &str) -> Option { 1568 for line in headers.lines() { 1569 let Some((name, value)) = line.split_once(':') else { 1570 continue; 1571 }; 1572 if !name.eq_ignore_ascii_case("link") { 1573 continue; 1574 } 1575 for part in value.split(',') { 1576 let Some((url, rest)) = part.split_once('>') else { 1577 continue; 1578 }; 1579 let rel = rest.to_ascii_lowercase(); 1580 if !rel.contains("rel=\"next\"") 1581 && !rel.contains("rel='next'") 1582 && !rel.contains("rel=next") 1583 { 1584 continue; 1585 } 1586 let url = url.trim().trim_start_matches('<').trim(); 1587 if url.is_empty() { 1588 continue; 1589 } 1590 return Some(github_api_path(url)); 1591 } 1592 } 1593 None 1594 } 1595 1596 fn github_api_path(url: &str) -> String { 1597 for prefix in ["https://api.github.com/", "http://api.github.com/"] { 1598 if let Some(rest) = url.strip_prefix(prefix) { 1599 return rest.to_string(); 1600 } 1601 } 1602 url.trim_start_matches('/').to_string() 1603 } 1604 1605 /// One list request as a conditional GET. `pick` turns a 200 body into head shas. A 304 returns the shas 1606 /// and the next-page path of the answer the ETag belongs to; any other status is an error carrying gh's 1607 /// message. The next-page path is `None` when the 200 had no `Link: rel="next"`. 1608 fn conditional_heads( 1609 gh: &str, 1610 path: &str, 1611 pick: fn(&Value) -> Vec, 1612 cache: &mut GithubHeadCache, 1613 ) -> Result<(Vec, Option), String> { 1614 let mut cmd = Command::new(gh); 1615 cmd.args(["api", "-i"]); 1616 if let Some(cached) = cache.entries.get(path) { 1617 cmd.args(["-H", &format!("If-None-Match: {}", cached.etag)]); 1618 } 1619 cmd.arg(path); 1620 let out = process::output_gated(&mut cmd).map_err(|e| format!("cannot run {gh}: {e}"))?; 1621 let text = String::from_utf8_lossy(&out.stdout).into_owned(); 1622 let (head, body) = text 1623 .split_once("\r\n\r\n") 1624 .or_else(|| text.split_once("\n\n")) 1625 .unwrap_or((text.as_str(), "")); 1626 let status = head 1627 .lines() 1628 .next() 1629 .and_then(|l| l.split_whitespace().nth(1)) 1630 .unwrap_or(""); 1631 if status == "304" { 1632 if let Some(cached) = cache.entries.get(path) { 1633 return Ok((cached.heads.clone(), cached.next.clone())); 1634 } 1635 } 1636 if status != "200" || !out.status.success() { 1637 cache.entries.remove(path); 1638 let err = String::from_utf8_lossy(&out.stderr).trim().to_string(); 1639 return Err(if err.is_empty() { 1640 head.lines().next().unwrap_or("no answer").to_string() 1641 } else { 1642 err 1643 }); 1644 } 1645 let value: Value = 1646 serde_json::from_str(body).map_err(|e| format!("unreadable answer for {path}: {e}"))?; 1647 let shas: Vec = pick(&value) 1648 .into_iter() 1649 .map(|s| s.trim().to_ascii_lowercase()) 1650 .filter(|s| valid_sha(s)) 1651 .collect(); 1652 let next = link_next(head); 1653 let etag = head 1654 .lines() 1655 .find_map(|l| { 1656 l.split_once(':') 1657 .filter(|(k, _)| k.eq_ignore_ascii_case("etag")) 1658 }) 1659 .map(|(_, v)| v.trim().to_string()); 1660 match etag { 1661 Some(etag) if !etag.is_empty() => { 1662 cache.entries.insert( 1663 path.to_string(), 1664 CachedHeads { 1665 etag, 1666 heads: shas.clone(), 1667 next: next.clone(), 1668 }, 1669 ); 1670 } 1671 _ => { 1672 cache.entries.remove(path); 1673 } 1674 } 1675 Ok((shas, next)) 1676 } 1677 1678 /// `triggers`, limited to the repositories in `repos` (a poller started with 1679 /// `--repos`). An empty list takes every trigger. Files of other repositories 1680 /// are left where they are: they belong to the poller that lists them. 1681 pub fn triggers_for(state: &StateDir, repos: &[String]) -> Vec<(String, String, PathBuf)> { 1682 let mut all = triggers(state); 1683 if !repos.is_empty() { 1684 all.retain(|(repo, _, _)| repos.iter().any(|r| r == repo)); 1685 } 1686 all 1687 } 1688 1689 /// Exclusive right to judge one (repo, sha) on this machine: an `flock(2)` on 1690 /// `/locks/judging/.`. Every judge of a head shares the 1691 /// worktree `//`, and the first to finish removes it, so 1692 /// two processes judging one head (two pollers that both see a trigger file, 1693 /// or a `worker --once` beside a poller) kill each other's run. The lock file 1694 /// holds the holder's pid. The kernel drops the lock when the holder dies, so 1695 /// a crashed worker never blocks the head. 1696 #[derive(Debug)] 1697 pub struct HeadClaim { 1698 file: Option, 1699 path: PathBuf, 1700 } 1701 1702 impl Drop for HeadClaim { 1703 fn drop(&mut self) { 1704 // Unlink while still holding the lock: anyone who opened the old file 1705 // meanwhile sees the path no longer names it and tries again. 1706 let _ = fs::remove_file(&self.path); 1707 let _gate = process::spawn_gate(); 1708 self.file.take(); 1709 } 1710 } 1711 1712 /// Take the right to judge `repo` at `sha`. `Ok(None)`: another process holds 1713 /// it right now (see `head_holder`); the caller skips the head. Never waits. 1714 pub fn claim_head(state: &StateDir, repo: &str, sha: &str) -> Result, String> { 1715 if !valid_repo_key(repo) || !valid_sha(sha) { 1716 return Err(format!("refusing to claim {repo:?} {sha:?}")); 1717 } 1718 let path = state.head_lock(repo, sha); 1719 let err = |what: &str, e: std::io::Error| format!("{what} {}: {e}", path.display()); 1720 if let Some(parent) = path.parent() { 1721 fs::create_dir_all(parent).map_err(|e| err("cannot create", e))?; 1722 } 1723 // A holder that finishes between our open and our flock unlinks the file; 1724 // we would then hold a lock on a name nobody else can see. Check the path 1725 // still names our file and open again when it does not. 1726 for _ in 0..16 { 1727 let file = fs::OpenOptions::new() 1728 .create(true) 1729 .read(true) 1730 .write(true) 1731 .truncate(false) 1732 .open(&path) 1733 .map_err(|e| err("cannot open", e))?; 1734 if !resources::flock_exclusive(&file, false).map_err(|e| err("cannot lock", e))? { 1735 return Ok(None); 1736 } 1737 let named = fs::metadata(&path).ok(); 1738 let ours = file.metadata().map_err(|e| err("cannot stat", e))?; 1739 if !named.is_some_and(|m| m.dev() == ours.dev() && m.ino() == ours.ino()) { 1740 continue; 1741 } 1742 file.set_len(0).map_err(|e| err("cannot write", e))?; 1743 (&file) 1744 .write_all(format!("{}\n", std::process::id()).as_bytes()) 1745 .map_err(|e| err("cannot write", e))?; 1746 return Ok(Some(HeadClaim { 1747 file: Some(file), 1748 path, 1749 })); 1750 } 1751 Err(format!("cannot settle the claim on {}", path.display())) 1752 } 1753 1754 /// The pid that holds the claim on (repo, sha), when it is readable. 1755 pub fn head_holder(state: &StateDir, repo: &str, sha: &str) -> Option { 1756 fs::read_to_string(state.head_lock(repo, sha)) 1757 .ok()? 1758 .trim() 1759 .parse() 1760 .ok() 1761 } 1762 1763 /// The log words for a head another process is judging. 1764 pub fn held_note(state: &StateDir, repo: &str, sha: &str) -> String { 1765 match head_holder(state, repo, sha) { 1766 Some(pid) => format!("SKIP already being judged by pid {pid}"), 1767 None => "SKIP already being judged by another process".to_string(), 1768 } 1769 } 1770 1771 fn pull_heads(v: &Value) -> Vec { 1772 v.as_array() 1773 .map(|a| { 1774 a.iter() 1775 .filter_map(|p| p["head"]["sha"].as_str().map(str::to_string)) 1776 .collect() 1777 }) 1778 .unwrap_or_default() 1779 } 1780 1781 fn main_head(v: &Value) -> Vec { 1782 v["sha"].as_str().map(str::to_string).into_iter().collect() 1783 } 1784 1785 /// GitHub returns at most 100 pull requests per page. Issue #732: a poll that 1786 /// stops at the first page never sees an open PR past that page, so the local 1787 /// judge never runs it. 1788 const OPEN_PULLS_PER_PAGE: usize = 100; 1789 /// Twenty pages is 2000 open PRs. Past that the list is incomplete; say so 1790 /// instead of silently dropping the rest. 1791 const OPEN_PULLS_PAGE_CAP: usize = 20; 1792 1793 /// Whether a next-page path taken from `Link` is another page of a pull list on api.github.com. 1794 /// GitHub writes it as `repositories//pulls?...` (seen on 2026-10-31) and may write 1795 /// `repos///pulls?...`. An absolute URL to another host keeps its scheme after 1796 /// [`github_api_path`] and never matches. 1797 fn is_pulls_page(next: &str, or: &str) -> bool { 1798 let repos = format!("repos/{or}/pulls?"); 1799 if next 1800 .get(..repos.len()) 1801 .is_some_and(|p| p.eq_ignore_ascii_case(&repos)) 1802 { 1803 return true; 1804 } 1805 next.strip_prefix("repositories/") 1806 .and_then(|rest| rest.split_once("/pulls?")) 1807 .is_some_and(|(id, _)| !id.is_empty() && id.bytes().all(|b| b.is_ascii_digit())) 1808 } 1809 1810 /// Every open PR head, following `Link: rel="next"` until the last page. 1811 /// A next link that is not another page of a pull list ([`is_pulls_page`]) is an error: 1812 /// `gh api` follows an absolute URL to any host, so the walk never hands it one. 1813 fn open_pull_heads(gh: &str, or: &str, cache: &mut GithubHeadCache) -> Result, String> { 1814 let mut path = format!("repos/{or}/pulls?state=open&per_page={OPEN_PULLS_PER_PAGE}"); 1815 let mut out = Vec::new(); 1816 for _page in 1..=OPEN_PULLS_PAGE_CAP { 1817 let (shas, next) = conditional_heads(gh, &path, pull_heads, cache)?; 1818 out.extend(shas); 1819 let Some(next) = next.filter(|n| n != &path) else { 1820 return Ok(out); 1821 }; 1822 if !is_pulls_page(&next, or) { 1823 return Err(format!( 1824 "open pull list for {or}: next page link {next:?} is not a page of a pull list" 1825 )); 1826 } 1827 path = next; 1828 } 1829 Err(format!( 1830 "open pull list for {or} still had a next page after {OPEN_PULLS_PAGE_CAP} pages of {OPEN_PULLS_PER_PAGE}" 1831 )) 1832 } 1833 1834 /// Open PR heads and the main head of `repo` from GitHub. Open pulls are read 1835 /// page by page (`Link: rel="next"`, at most [`OPEN_PULLS_PAGE_CAP`] pages). 1836 /// Errors are returned, never fatal to the loop. Unchanged pages answer 304 1837 /// and cost no allowance; a 304 still follows the next page remembered with 1838 /// its ETag. 1839 pub fn github_heads_cached( 1840 gh: &str, 1841 repository: &str, 1842 cache: &mut GithubHeadCache, 1843 ) -> Result, String> { 1844 let or = owner_repo(repository).ok_or("bad repository name")?; 1845 let mut shas = open_pull_heads(gh, &or, cache)?; 1846 let (main, _) = conditional_heads(gh, &format!("repos/{or}/commits/main"), main_head, cache)?; 1847 shas.extend(main); 1848 shas.sort(); 1849 shas.dedup(); 1850 Ok(shas) 1851 } 1852 1853 /// `github_heads_cached` with no memory of earlier polls. 1854 pub fn github_heads(gh: &str, repository: &str) -> Result, String> { 1855 github_heads_cached(gh, repository, &mut GithubHeadCache::default()) 1856 } 1857 1858 /// The loop: flush the outbox, serve trigger files, poll GitHub when asked, 1859 /// sleep. `iterations` bounds the rounds (None: forever). Returns the number 1860 /// of heads served. 1861 /// Checkouts, pins, sibling worktrees and worktree removal touch the shared 1862 /// clones and mirrors; heads of one batch do them one at a time. 1863 fn lock_prep() -> std::sync::MutexGuard<'static, ()> { 1864 static PREP: std::sync::Mutex<()> = std::sync::Mutex::new(()); 1865 PREP.lock().unwrap_or_else(|e| e.into_inner()) 1866 } 1867 1868 /// For each head, the gates whose experiment another head of the batch is 1869 /// likely to share, read from git objects before anything is checked out: a 1870 /// gate whose manifest blob, declared inputs and repository build files have 1871 /// the same blob ids at two heads (and, for a gate without `cache: 1872 /// inputs_complete`, the same tree). Only an ordering hint: whether a result 1873 /// is really reused is decided by the cache key, never by this. 1874 pub fn batch_first(clone: &Path, shas: &[String]) -> BTreeMap> { 1875 let mut prints: BTreeMap> = BTreeMap::new(); 1876 for sha in shas { 1877 let tree = git(clone, &["rev-parse", &format!("{sha}^{{tree}}")]).unwrap_or_default(); 1878 let files = git(clone, &["ls-tree", "-r", "--name-only", sha]).unwrap_or_default(); 1879 let mut mine = Vec::new(); 1880 for path in files.lines().filter(|p| p.ends_with(".gate")) { 1881 let Ok(bytes) = git(clone, &["show", &format!("{sha}:{path}")]) else { 1882 continue; 1883 }; 1884 let Ok(m) = crate::manifest::parse(bytes.as_bytes()) else { 1885 continue; 1886 }; 1887 let Ok(reach) = crate::cache::cross_head(&m) else { 1888 continue; 1889 }; 1890 let mut args: Vec = 1891 vec!["ls-tree".into(), "-r".into(), sha.clone(), "--".into()]; 1892 args.extend(m.inputs.iter().cloned()); 1893 args.extend(runner::IMPLIED_BUILD_FILES.iter().map(|s| s.to_string())); 1894 let argv: Vec<&str> = args.iter().map(String::as_str).collect(); 1895 let listing = git(clone, &argv).unwrap_or_default(); 1896 let scope = match reach { 1897 crate::cache::Reach::Inputs => String::new(), 1898 crate::cache::Reach::Tree => tree.trim().to_string(), 1899 }; 1900 let print = sha256_hex(format!("{}\n{scope}\n{listing}", m.digest).as_bytes()); 1901 mine.push((m.gate.clone(), print)); 1902 } 1903 prints.insert(sha.clone(), mine); 1904 } 1905 let mut count: BTreeMap<&str, usize> = BTreeMap::new(); 1906 for p in prints.values().flatten() { 1907 *count.entry(p.1.as_str()).or_default() += 1; 1908 } 1909 prints 1910 .iter() 1911 .map(|(sha, v)| { 1912 let first = v 1913 .iter() 1914 .filter(|(_, p)| count.get(p.as_str()).copied().unwrap_or(0) > 1) 1915 .map(|(g, _)| g.clone()) 1916 .collect(); 1917 (sha.clone(), first) 1918 }) 1919 .collect() 1920 } 1921 1922 /// Judge several heads of one repository together (Drake 2026-10-20: "do all 1923 /// the similar ones first and then you go to the ones that are unique"). The 1924 /// heads run side by side; their host gates share one budget of 1925 /// `cfg.batch_host` slots (default half the CPUs) in which gates another head 1926 /// also selects go first, and their gb10 gates take one batch slot, one at a 1927 /// time, before `/tmp/aien-gb10.lock`. A gate with a key another head is 1928 /// running waits on that key's lock and then reuses the result. Results come 1929 /// back in the order of `shas`. 1930 pub fn run_batch( 1931 cfg: &Config, 1932 repo: &str, 1933 shas: &[String], 1934 ) -> Vec<(String, Result)> { 1935 let mut seen = BTreeSet::new(); 1936 let shas: Vec = shas 1937 .iter() 1938 .filter(|s| seen.insert((*s).clone())) 1939 .cloned() 1940 .collect(); 1941 let budget = std::sync::Arc::new(crate::resources::BatchShare::new( 1942 cfg.batch_host 1943 .unwrap_or_else(crate::resources::BatchShare::default_host), 1944 )); 1945 let first = if valid_repo_key(repo) { 1946 batch_first(&cfg.clones.join(repo), &shas) 1947 } else { 1948 BTreeMap::new() 1949 }; 1950 let shares: Vec = shas 1951 .iter() 1952 .map(|s| (budget.clone(), first.get(s).cloned().unwrap_or_default())) 1953 .collect(); 1954 std::thread::scope(|scope| { 1955 let handles: Vec<_> = shas 1956 .iter() 1957 .zip(&shares) 1958 .map(|(sha, share)| scope.spawn(move || run_once_in(cfg, repo, sha, Some(share)))) 1959 .collect(); 1960 shas.iter() 1961 .zip(handles) 1962 .map(|(sha, h)| { 1963 let r = h 1964 .join() 1965 .unwrap_or_else(|_| Err(format!("internal error while judging {sha}"))); 1966 (sha.clone(), r) 1967 }) 1968 .collect() 1969 }) 1970 } 1971 1972 pub fn run_loop(cfg: &Config, iterations: Option) -> usize { 1973 let mut served = 0; 1974 let mut round = 0u64; 1975 let mut head_cache = GithubHeadCache::default(); 1976 loop { 1977 round += 1; 1978 cfg.state.beat("-", "-", "poll"); 1979 // Posting is the operator's choice (--github). A loop without it leaves 1980 // queued statuses where they are, so `aien-local-ci start` after an 1981 // offline --github run never posts them behind the operator's back. 1982 let (posted, pending) = if cfg.github { 1983 flush_outbox(cfg) 1984 } else { 1985 (0, outbox_files(&cfg.state).len()) 1986 }; 1987 if posted + pending > 0 { 1988 println!("OUTBOX posted={posted} pending={pending}"); 1989 } 1990 let mut heads: Vec<(String, String, Option)> = 1991 triggers_for(&cfg.state, &cfg.repos) 1992 .into_iter() 1993 .map(|(r, s, f)| (r, s, Some(f))) 1994 .collect(); 1995 if cfg.github { 1996 for repo in &cfg.repos { 1997 let repository = plan::repository_name(&cfg.clones.join(repo), None); 1998 match github_heads_cached(&cfg.gh, &repository, &mut head_cache) { 1999 Ok(shas) => { 2000 for s in shas { 2001 if !cfg.state.bundle_path(repo, &s).exists() { 2002 heads.push((repo.clone(), s, None)); 2003 } 2004 } 2005 } 2006 Err(e) => println!("GITHUB unreachable for {repo}: {e} (will retry)"), 2007 } 2008 } 2009 } 2010 // L307/L309 integration: take the block-first queue once per round, 2011 // then preserve that order within each repository's batches. 2012 let mut queue: std::collections::VecDeque<(String, String, Option)> = heads.into(); 2013 let mut tried = std::collections::HashSet::new(); 2014 let blocks = if cfg.github { 2015 crate::block_first::open_blocks(&cfg.state.root, &cfg.repos, SystemTime::now()) 2016 } else { 2017 Vec::new() 2018 }; 2019 let mut by_repo: BTreeMap)>> = BTreeMap::new(); 2020 while let Some((repo, sha, trigger)) = crate::block_first::next_head( 2021 &mut queue, 2022 &blocks, 2023 &cfg.state.trigger_dir(), 2024 &|r, s| cfg.state.bundle_path(r, s).exists(), 2025 &mut tried, 2026 ) { 2027 by_repo.entry(repo).or_default().push((sha, trigger)); 2028 } 2029 for (repo, list) in by_repo { 2030 let shas: Vec = list.iter().map(|(s, _)| s.clone()).collect(); 2031 // At most `cfg.batch_heads` heads are checked out at once. 2032 let results: Vec<(String, Result)> = shas 2033 .chunks(cfg.batch_heads.max(1)) 2034 .flat_map(|c| { 2035 if c.len() > 1 { 2036 run_batch(cfg, &repo, c) 2037 } else { 2038 c.iter() 2039 .map(|s| (s.clone(), run_once(cfg, &repo, s))) 2040 .collect() 2041 } 2042 }) 2043 .collect(); 2044 for ((sha, result), (_, trigger)) in results.into_iter().zip(list) { 2045 let mut keep_trigger = false; 2046 match result { 2047 Ok(s) => { 2048 println!( 2049 "HEAD {repo} {sha} {} {} bundle {} publication {}", 2050 s.verdict.as_str(), 2051 s.reason, 2052 s.bundle_path.display(), 2053 s.publication 2054 ); 2055 served += 1; 2056 } 2057 Err(e) => { 2058 println!("HEAD {repo} {sha} ERROR {e}"); 2059 if e.contains("already being judged") { 2060 keep_trigger = true; 2061 } 2062 let _ = cfg.state.journal_append(&json!({ 2063 "utc": utc_string(now_secs()), 2064 "repo": repo, 2065 "sha": sha, 2066 "verdict": "NOT_RUN", 2067 "reason": format!("WORKER_ERROR:{e}"), 2068 "publication": "none", 2069 })); 2070 } 2071 } 2072 if !keep_trigger { 2073 if let Some(f) = trigger { 2074 let _ = fs::remove_file(f); 2075 } 2076 } 2077 } 2078 } 2079 if iterations.is_some_and(|n| round >= n) { 2080 break; 2081 } 2082 std::thread::sleep(cfg.poll); 2083 } 2084 served 2085 } 2086 2087 #[cfg(test)] 2088 mod tests { 2089 use super::*; 2090 2091 #[test] 2092 fn every_head_gets_its_own_target_dir_inside_its_trust_class() { 2093 let mut cfg = Config::new( 2094 StateDir::new(Path::new("/s")), 2095 Path::new("/k"), 2096 Path::new("/c"), 2097 Path::new("/w"), 2098 ); 2099 cfg.sandbox = Sandbox::User; 2100 let (a, b) = ("a".repeat(40), "b".repeat(40)); 2101 let pr_a = target_dir_for(&cfg, "aien-sovereign-core", &a, false).unwrap(); 2102 let pr_b = target_dir_for(&cfg, "aien-sovereign-core", &b, false).unwrap(); 2103 let main_a = target_dir_for(&cfg, "aien-sovereign-core", &a, true).unwrap(); 2104 assert_eq!( 2105 pr_a, 2106 Path::new(TARGET_ROOT) 2107 .join("aien-sovereign-core/pr") 2108 .join(&a) 2109 ); 2110 assert_eq!( 2111 main_a, 2112 Path::new(TARGET_ROOT) 2113 .join("aien-sovereign-core/main") 2114 .join(&a) 2115 ); 2116 // Two heads never share a dir (cargo would link one head's build into 2117 // the other, sc #605), and a head's pr dir is never its main dir (A2). 2118 assert_ne!(pr_a, pr_b); 2119 assert_ne!(pr_a, main_a); 2120 } 2121 /// A fake `gh` that answers `gh api -i [-H If-None-Match: E] PATH` from files: `.body` and `.etag` 2122 /// (key = the path with every non-alphanumeric byte as `_`), and logs every call to `log`. 2123 fn fake_gh(dir: &Path) -> PathBuf { 2124 let script = dir.join("gh"); 2125 fs::write( 2126 &script, 2127 r#"#!/bin/bash 2128 d=$(dirname "$0") 2129 echo "$*" >> "$d/log" 2130 path="${@: -1}" 2131 key=$(printf '%s' "$path" | tr -c 'A-Za-z0-9' '_') 2132 if [ ! -f "$d/$key.body" ]; then printf 'HTTP/2.0 404 Not Found\r\n\r\n{}'; echo "gh: Not Found (HTTP 404)" >&2; exit 1; fi 2133 etag=$(cat "$d/$key.etag") 2134 if [[ " $* " == *"If-None-Match: $etag "* ]]; then printf 'HTTP/2.0 304 Not Modified\r\nEtag: %s\r\n\r\n' "$etag"; echo "gh: HTTP 304" >&2; exit 1; fi 2135 linkhdr="" 2136 if [ -f "$d/$key.link" ]; then linkhdr=$(printf 'Link: %s\r\n' "$(cat "$d/$key.link")"); fi 2137 printf 'HTTP/2.0 200 OK\r\nEtag: %s\r\n%sContent-Type: application/json\r\n\r\n' "$etag" "$linkhdr"; cat "$d/$key.body" 2138 "#, 2139 ) 2140 .unwrap(); 2141 use std::os::unix::fs::PermissionsExt; 2142 fs::set_permissions(&script, fs::Permissions::from_mode(0o755)).unwrap(); 2143 script 2144 } 2145 2146 fn fake_answer(dir: &Path, path: &str, etag: &str, body: &str) { 2147 let key: String = path 2148 .chars() 2149 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) 2150 .collect(); 2151 fs::write(dir.join(format!("{key}.etag")), etag).unwrap(); 2152 fs::write(dir.join(format!("{key}.body")), body).unwrap(); 2153 let _ = fs::remove_file(dir.join(format!("{key}.link"))); 2154 } 2155 2156 fn fake_link(dir: &Path, path: &str, link: &str) { 2157 let key: String = path 2158 .chars() 2159 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) 2160 .collect(); 2161 fs::write(dir.join(format!("{key}.link")), link).unwrap(); 2162 } 2163 2164 #[test] 2165 fn an_unchanged_list_is_asked_with_its_etag_and_answered_from_memory() { 2166 let dir = std::env::temp_dir().join(format!("l337-heads-{}", std::process::id())); 2167 fs::create_dir_all(&dir).unwrap(); 2168 let gh = fake_gh(&dir); 2169 let gh = gh.to_str().unwrap(); 2170 let (p1, p2, m1) = ("1".repeat(40), "2".repeat(40), "3".repeat(40)); 2171 let pulls = format!("repos/aien-dev/demo/pulls?state=open&per_page={OPEN_PULLS_PER_PAGE}"); 2172 let main = "repos/aien-dev/demo/commits/main"; 2173 fake_answer( 2174 &dir, 2175 &pulls, 2176 "W/\"a\"", 2177 &format!(r#"[{{"head":{{"sha":"{p2}"}}}},{{"head":{{"sha":"{p1}"}}}}]"#), 2178 ); 2179 fake_answer(&dir, main, "\"m\"", &format!(r#"{{"sha":"{m1}"}}"#)); 2180 let mut cache = GithubHeadCache::default(); 2181 let first = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); 2182 assert_eq!(first, vec![p1.clone(), p2.clone(), m1.clone()]); 2183 let second = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); 2184 assert_eq!(second, first, "a 304 gives back the earlier answer"); 2185 let log = fs::read_to_string(dir.join("log")).unwrap(); 2186 let lines: Vec<&str> = log.lines().collect(); 2187 assert_eq!(lines.len(), 4, "two calls per poll: {log}"); 2188 assert!( 2189 !lines[0].contains("If-None-Match") && !lines[1].contains("If-None-Match"), 2190 "first poll is unconditional: {log}" 2191 ); 2192 assert!( 2193 lines[2].contains("If-None-Match: W/\"a\"") 2194 && lines[3].contains("If-None-Match: \"m\""), 2195 "second poll sends the etags: {log}" 2196 ); 2197 // The list changes: the new etag brings the new answer. 2198 let p3 = "4".repeat(40); 2199 fake_answer( 2200 &dir, 2201 &pulls, 2202 "W/\"b\"", 2203 &format!(r#"[{{"head":{{"sha":"{p3}"}}}}]"#), 2204 ); 2205 let third = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); 2206 assert_eq!(third, vec![m1, p3], "sorted, new list replaces the old"); 2207 // A repository GitHub does not know is an error, and forgets nothing it should not. 2208 let err = github_heads_cached(gh, "github.com/aien-dev/missing", &mut cache).unwrap_err(); 2209 assert!(err.contains("404"), "{err}"); 2210 // With no memory (the old behaviour) every poll is unconditional. 2211 let _ = github_heads(gh, "github.com/aien-dev/demo").unwrap(); 2212 let log = fs::read_to_string(dir.join("log")).unwrap(); 2213 assert!(!log.lines().last().unwrap().contains("If-None-Match")); 2214 let _ = fs::remove_dir_all(&dir); 2215 } 2216 2217 #[test] 2218 fn link_next_reads_the_next_rel_and_strips_the_api_host() { 2219 let headers = "HTTP/2.0 200 OK\r\nLink: ; rel=\"next\", ; rel=\"last\"\r\n"; 2220 assert_eq!( 2221 link_next(headers).as_deref(), 2222 Some("repos/o/r/pulls?state=open&per_page=100&page=2") 2223 ); 2224 assert_eq!(link_next("HTTP/2.0 200 OK\r\nEtag: \"x\"\r\n"), None); 2225 } 2226 2227 /// Issue #732: a first page of 100 is not the whole list. The head on page 2 2228 /// must be judged too. A 304 omits Link, so the remembered next page is what 2229 /// the second poll follows. Dropping the link stops the walk (negative control). 2230 #[test] 2231 fn open_pulls_past_the_first_page_are_polled_and_a_304_still_follows_next() { 2232 let dir = std::env::temp_dir().join(format!("sc732-heads-{}", std::process::id())); 2233 fs::create_dir_all(&dir).unwrap(); 2234 let gh = fake_gh(&dir); 2235 let gh = gh.to_str().unwrap(); 2236 let (p1, p2, m1) = ("a".repeat(40), "b".repeat(40), "c".repeat(40)); 2237 let page1 = format!("repos/aien-dev/demo/pulls?state=open&per_page={OPEN_PULLS_PER_PAGE}"); 2238 let page2 = format!("{page1}&page=2"); 2239 let main = "repos/aien-dev/demo/commits/main"; 2240 fake_answer( 2241 &dir, 2242 &page1, 2243 "W/\"p1\"", 2244 &format!(r#"[{{"head":{{"sha":"{p1}"}}}}]"#), 2245 ); 2246 fake_link( 2247 &dir, 2248 &page1, 2249 &format!("; rel=\"next\""), 2250 ); 2251 fake_answer( 2252 &dir, 2253 &page2, 2254 "W/\"p2\"", 2255 &format!(r#"[{{"head":{{"sha":"{p2}"}}}}]"#), 2256 ); 2257 fake_answer(&dir, main, "\"m\"", &format!(r#"{{"sha":"{m1}"}}"#)); 2258 let mut cache = GithubHeadCache::default(); 2259 let first = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); 2260 assert_eq!(first, vec![p1.clone(), p2.clone(), m1.clone()]); 2261 let second = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); 2262 assert_eq!( 2263 second, first, 2264 "304 on page 1 still walks the remembered page 2" 2265 ); 2266 let log = fs::read_to_string(dir.join("log")).unwrap(); 2267 let page2_calls = log.lines().filter(|l| l.contains("page=2")).count(); 2268 assert_eq!(page2_calls, 2, "both polls ask for page 2: {log}"); 2269 assert!( 2270 log.lines().any(|l| l.contains("If-None-Match: W/\"p2\"")), 2271 "page 2 is conditional on the second poll: {log}" 2272 ); 2273 // Negative control: no next link, so the head that lived only on page 2 disappears 2274 // and that page is not requested again. 2275 fake_answer( 2276 &dir, 2277 &page1, 2278 "W/\"p1b\"", 2279 &format!(r#"[{{"head":{{"sha":"{p1}"}}}}]"#), 2280 ); 2281 let third = github_heads_cached(gh, "github.com/aien-dev/demo", &mut cache).unwrap(); 2282 assert_eq!(third, vec![p1, m1], "no next link stops at page 1"); 2283 let log = fs::read_to_string(dir.join("log")).unwrap(); 2284 assert_eq!( 2285 log.lines().filter(|l| l.contains("page=2")).count(), 2286 2, 2287 "page 2 is not fetched once page 1 no longer links it: {log}" 2288 ); 2289 let _ = fs::remove_dir_all(&dir); 2290 } 2291 2292 /// Issue #732 acceptance: more than 100 open PRs, the last page's head, a 2293 /// duplicate across pages, an unchanged 304, a changed later page, and a 2294 /// failed later page that is an error rather than a short success. 2295 #[test] 2296 fn a_list_longer_than_one_page_keeps_the_last_head_and_a_later_error_is_not_success() { 2297 let dir = std::env::temp_dir().join(format!("sc732-long-{}", std::process::id())); 2298 fs::create_dir_all(&dir).unwrap(); 2299 let gh = fake_gh(&dir); 2300 let gh = gh.to_str().unwrap(); 2301 let sha = |n: u32| format!("{n:040x}"); 2302 let page1 = format!("repos/aien-dev/wide/pulls?state=open&per_page={OPEN_PULLS_PER_PAGE}"); 2303 let page2 = format!("{page1}&page=2"); 2304 let main = "repos/aien-dev/wide/commits/main"; 2305 let m1 = sha(0xffff); 2306 let mut body = String::from("["); 2307 for n in 0..100 { 2308 if n > 0 { 2309 body.push(','); 2310 } 2311 body.push_str(&format!(r#"{{"head":{{"sha":"{}"}}}}"#, sha(n))); 2312 } 2313 body.push(']'); 2314 fake_answer(&dir, &page1, "W/\"wide1\"", &body); 2315 fake_link( 2316 &dir, 2317 &page1, 2318 &format!("; rel=\"next\""), 2319 ); 2320 fake_answer( 2321 &dir, 2322 &page2, 2323 "W/\"wide2\"", 2324 &format!( 2325 r#"[{{"head":{{"sha":"{}"}}}},{{"head":{{"sha":"{}"}}}}]"#, 2326 sha(0), 2327 sha(100) 2328 ), 2329 ); 2330 fake_answer(&dir, main, "\"mw\"", &format!(r#"{{"sha":"{m1}"}}"#)); 2331 let mut cache = GithubHeadCache::default(); 2332 let first = github_heads_cached(gh, "github.com/aien-dev/wide", &mut cache).unwrap(); 2333 let mut expect: Vec = (0..101).map(sha).collect(); 2334 expect.push(m1); 2335 expect.sort(); 2336 expect.dedup(); 2337 assert_eq!( 2338 first, expect, 2339 "100 page-1 heads + last-page head + main, duplicate dropped" 2340 ); 2341 assert!(first.contains(&sha(100)), "last page head is present"); 2342 assert_eq!(first.len(), 102); 2343 2344 let second = github_heads_cached(gh, "github.com/aien-dev/wide", &mut cache).unwrap(); 2345 assert_eq!(second, first, "304 keeps the long list, including page 2"); 2346 2347 fake_answer( 2348 &dir, 2349 &page2, 2350 "W/\"wide2b\"", 2351 &format!(r#"[{{"head":{{"sha":"{}"}}}}]"#, sha(101)), 2352 ); 2353 let third = github_heads_cached(gh, "github.com/aien-dev/wide", &mut cache).unwrap(); 2354 assert!(third.contains(&sha(101)), "a changed later page is read"); 2355 assert!( 2356 !third.contains(&sha(100)), 2357 "the replaced later-page head is gone" 2358 ); 2359 2360 let key: String = page2 2361 .chars() 2362 .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) 2363 .collect(); 2364 fs::remove_file(dir.join(format!("{key}.body"))).unwrap(); 2365 let err = github_heads_cached(gh, "github.com/aien-dev/wide", &mut cache).unwrap_err(); 2366 assert!( 2367 err.contains("404"), 2368 "a failed later page is an error, not a short list: {err}" 2369 ); 2370 let _ = fs::remove_dir_all(&dir); 2371 } 2372 2373 #[test] 2374 fn only_pull_list_pages_count_as_next_pages() { 2375 let or = "aien-dev/demo"; 2376 assert!(is_pulls_page("repositories/42/pulls?page=2", or)); 2377 assert!(is_pulls_page("repos/aien-dev/demo/pulls?page=2", or)); 2378 assert!(is_pulls_page("repos/Aien-Dev/Demo/pulls?page=2", or)); 2379 assert!(!is_pulls_page( 2380 "https://evil.invalid/repositories/42/pulls?page=2", 2381 or 2382 )); 2383 assert!(!is_pulls_page("repositories/42/issues?page=2", or)); 2384 assert!(!is_pulls_page("repositories//pulls?page=2", or)); 2385 assert!(!is_pulls_page("repositories/4x2/pulls?page=2", or)); 2386 assert!(!is_pulls_page("repos/aien-dev/other/pulls?page=2", or)); 2387 assert!(!is_pulls_page("user/repos?page=2", or)); 2388 } 2389 2390 /// GitHub's real `Link` names later pages `repositories//pulls?...` (seen on 2391 /// aien-sovereign-core-mv, 2026-10-31), not the `repos//` path the walk started 2392 /// from; that page is followed. A next link to another host is refused before `gh` is asked 2393 /// for it (negative control). 2394 #[test] 2395 fn next_links_in_the_repositories_id_form_are_followed_and_other_hosts_are_refused() { 2396 let dir = std::env::temp_dir().join(format!("sc732-repoid-{}", std::process::id())); 2397 fs::create_dir_all(&dir).unwrap(); 2398 let gh = fake_gh(&dir); 2399 let gh = gh.to_str().unwrap(); 2400 let (p1, p2, m1) = ("d".repeat(40), "e".repeat(40), "f".repeat(40)); 2401 let page1 = format!("repos/aien-dev/byid/pulls?state=open&per_page={OPEN_PULLS_PER_PAGE}"); 2402 let page2 = format!( 2403 "repositories/`1375978313`/pulls?state=open&per_page={OPEN_PULLS_PER_PAGE}&page=2" 2404 ); 2405 let main = "repos/aien-dev/byid/commits/main"; 2406 fake_answer( 2407 &dir, 2408 &page1, 2409 "W/\"i1\"", 2410 &format!(r#"[{{"head":{{"sha":"{p1}"}}}}]"#), 2411 ); 2412 fake_link( 2413 &dir, 2414 &page1, 2415 &format!( 2416 "; rel=\"next\", ; rel=\"last\"" 2417 ), 2418 ); 2419 fake_answer( 2420 &dir, 2421 &page2, 2422 "W/\"i2\"", 2423 &format!(r#"[{{"head":{{"sha":"{p2}"}}}}]"#), 2424 ); 2425 fake_answer(&dir, main, "\"mi\"", &format!(r#"{{"sha":"{m1}"}}"#)); 2426 let mut cache = GithubHeadCache::default(); 2427 let heads = github_heads_cached(gh, "github.com/aien-dev/byid", &mut cache).unwrap(); 2428 assert_eq!(heads, vec![p1.clone(), p2, m1]); 2429 2430 fake_answer( 2431 &dir, 2432 &page1, 2433 "W/\"i1b\"", 2434 &format!(r#"[{{"head":{{"sha":"{p1}"}}}}]"#), 2435 ); 2436 fake_link( 2437 &dir, 2438 &page1, 2439 "; rel=\"next\"", 2440 ); 2441 let err = github_heads_cached(gh, "github.com/aien-dev/byid", &mut cache).unwrap_err(); 2442 assert!(err.contains("not a page of a pull list"), "{err}"); 2443 let log = fs::read_to_string(dir.join("log")).unwrap(); 2444 assert!( 2445 !log.contains("evil.invalid"), 2446 "the foreign link is never handed to gh: {log}" 2447 ); 2448 let _ = fs::remove_dir_all(&dir); 2449 } 2450 2451 #[test] 2452 fn pin_list_selects_the_repository_and_refuses_bad_lines() { 2453 let sha = "`353b7d4be3f00169545caec1615cffa61f7d311a`"; 2454 let list = 2455 format!("# c\naien-sovereign-core aien-protocols {sha} # t\nomega physics {sha}\n"); 2456 let p = parse_pins(&list, "aien-sovereign-core").unwrap(); 2457 assert_eq!( 2458 p, 2459 vec![Pin { 2460 source: "aien-protocols".into(), 2461 sha: sha.into() 2462 }] 2463 ); 2464 assert!(parse_pins(&list, "physics").unwrap().is_empty()); 2465 for bad in [ 2466 "a b".to_string(), 2467 format!("a b {sha} extra"), 2468 format!("a ../b {sha}"), 2469 "a b `353b7d4`".to_string(), 2470 format!("a b {}", sha.to_uppercase()), 2471 ] { 2472 assert!(parse_pins(&bad, "a").is_err(), "{bad}"); 2473 } 2474 } 2475 2476 fn sh_git(dir: &Path, args: &[&str]) -> String { 2477 git(dir, args).unwrap_or_else(|e| panic!("git {args:?}: {e}")) 2478 } 2479 2480 /// The trusted clone lacks a pinned commit that only its origin has (on a 2481 /// branch the clone never fetched): ensure_pins fetches it by sha and holds 2482 /// it under refs/remotes/aien-pins/. Negative controls: a pin of a 2483 /// repository that is not a sibling, and a commit origin does not have. 2484 #[test] 2485 fn ensure_pins_fetches_a_missing_pinned_commit_from_origin() { 2486 let t = crate::testutil::TempDir::new("pins"); 2487 let origin = t.path().join("origin"); 2488 fs::create_dir_all(&origin).unwrap(); 2489 sh_git(&origin, &["init", "-q", "-b", "main"]); 2490 for (k, v) in [ 2491 ("user.name", "t"), 2492 ("user.email", "t@t"), 2493 ("uploadpack.allowAnySHA1InWant", "true"), 2494 ] { 2495 sh_git(&origin, &["config", k, v]); 2496 } 2497 fs::write(origin.join("f"), "1").unwrap(); 2498 sh_git(&origin, &["add", "-A"]); 2499 sh_git(&origin, &["commit", "-q", "-m", "one"]); 2500 sh_git(&origin, &["checkout", "-q", "-b", "side"]); 2501 fs::write(origin.join("f"), "2").unwrap(); 2502 sh_git(&origin, &["commit", "-q", "-am", "two"]); 2503 let pinned = sh_git(&origin, &["rev-parse", "HEAD"]).trim().to_string(); 2504 sh_git(&origin, &["checkout", "-q", "main"]); 2505 let clones = t.path().join("clones"); 2506 fs::create_dir_all(&clones).unwrap(); 2507 sh_git( 2508 &clones, 2509 &[ 2510 "clone", 2511 "-q", 2512 "--single-branch", 2513 "--no-local", 2514 "-b", 2515 "main", 2516 origin.to_str().unwrap(), 2517 "src", 2518 ], 2519 ); 2520 let src = clones.join("src"); 2521 let want = format!("{pinned}^{{commit}}"); 2522 assert!( 2523 git(&src, &["cat-file", "-e", &want]).is_err(), 2524 "the clone must lack the pin first" 2525 ); 2526 2527 let sibs = vec![Sibling { 2528 dir: "src".into(), 2529 source: "src".into(), 2530 git_ref: "main".into(), 2531 }]; 2532 let absent = "`0123456789abcdef0123456789abcdef01234567`".to_string(); 2533 let pins = vec![ 2534 Pin { 2535 source: "src".into(), 2536 sha: pinned.clone(), 2537 }, 2538 Pin { 2539 source: "other".into(), 2540 sha: pinned.clone(), 2541 }, 2542 Pin { 2543 source: "src".into(), 2544 sha: absent.clone(), 2545 }, 2546 ]; 2547 let mut notes = Vec::new(); 2548 ensure_pins(&clones, &pins, &sibs, &mut notes); 2549 assert!(git(&src, &["cat-file", "-e", &want]).is_ok(), "{notes:?}"); 2550 let held = sh_git( 2551 &src, 2552 &["rev-parse", &format!("refs/remotes/aien-pins/{pinned}")], 2553 ); 2554 assert_eq!(held.trim(), pinned); 2555 assert!( 2556 notes.iter().any(|n| n.contains("fetched from origin")), 2557 "{notes:?}" 2558 ); 2559 assert!( 2560 notes.iter().any(|n| n.contains("other is not a sibling")), 2561 "{notes:?}" 2562 ); 2563 assert!( 2564 notes 2565 .iter() 2566 .any(|n| n.contains(&absent) && n.contains("not provided")), 2567 "{notes:?}" 2568 ); 2569 assert!(git( 2570 &src, 2571 &[ 2572 "rev-parse", 2573 "--verify", 2574 "--quiet", 2575 &format!("refs/remotes/aien-pins/{absent}") 2576 ] 2577 ) 2578 .is_err()); 2579 } 2580 #[test] 2581 fn sibling_map_selects_the_repository_and_refuses_bad_lines() { 2582 let map = "# comment\n\ 2583 aegis-runtime aien-protocols aien-protocols main\n\ 2584 benchmarks canonical-branch-native-runtime aien-sovereign-core feat/canonical-branch-native-runtime # trailing\n\ 2585 physics aien-architecture aien-architecture main\n\ 2586 physics omega omega main\n"; 2587 let p = parse_siblings(map, "physics").unwrap(); 2588 assert_eq!( 2589 p.iter().map(|s| s.dir.as_str()).collect::>(), 2590 ["aien-architecture", "omega"] 2591 ); 2592 let b = parse_siblings(map, "benchmarks").unwrap(); 2593 assert_eq!(b[0].source, "aien-sovereign-core"); 2594 assert_eq!(b[0].git_ref, "feat/canonical-branch-native-runtime"); 2595 assert!(parse_siblings(map, "omega").unwrap().is_empty()); 2596 assert!(parse_siblings("", "omega").unwrap().is_empty()); 2597 // Every line is checked, also lines for other repositories. 2598 for bad in [ 2599 "x y z", 2600 "x y z main extra", 2601 "x .. z main", 2602 "x y/z z main", 2603 "x y ../z main", 2604 ".x y z main", 2605 "x y z -main", 2606 "x y z a/../b", 2607 "x y z a//b", 2608 "x y z .hidden", 2609 "x y z a;b", 2610 "x x z main", 2611 "physics omega omega main\nphysics omega physics main", 2612 ] { 2613 let e = parse_siblings(&format!("ok a b main\n{bad}\n"), "ok"); 2614 assert!(e.is_err(), "accepted {bad:?}"); 2615 } 2616 } 2617 2618 /// The sibling dirs a `tests/gates/run.sh` reaches: `need_sibling ` 2619 /// and `pin ` (its second argument is the `../`). 2620 fn run_sh_sibling_dirs(run_sh: &str) -> std::collections::BTreeSet { 2621 let mut dirs = std::collections::BTreeSet::new(); 2622 for raw in run_sh.lines() { 2623 let line = raw.split('#').next().unwrap_or("").trim(); 2624 let f: Vec<&str> = line.split_whitespace().collect(); 2625 if f.len() >= 4 && f[0] == "pin" { 2626 dirs.insert(f[2].to_string()); 2627 } 2628 for (i, w) in f.iter().enumerate() { 2629 if *w == "need_sibling" { 2630 if let Some(d) = f.get(i + 1) { 2631 dirs.insert(d.trim_end_matches(';').to_string()); 2632 } 2633 } 2634 } 2635 } 2636 dirs 2637 } 2638 2639 #[test] 2640 fn committed_sibling_map_covers_every_sibling_the_core_gates_reach() { 2641 // A gate whose sibling the operator map does not name gets no 2642 // `../` and exits 3 (run.sh pin) on every worker. Read both 2643 // committed files so a new `pin`/`need_sibling` without its map line 2644 // fails here, before a worker journals "not provided". 2645 let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); 2646 let map = fs::read_to_string(root.join("tools/aien-local-ci/siblings")).unwrap(); 2647 let run_sh = fs::read_to_string(root.join("tests/gates/run.sh")).unwrap(); 2648 let have: std::collections::BTreeSet = parse_siblings(&map, "aien-sovereign-core") 2649 .unwrap() 2650 .into_iter() 2651 .map(|s| s.dir) 2652 .collect(); 2653 let need = run_sh_sibling_dirs(&run_sh); 2654 assert!( 2655 need.contains("aien-train"), 2656 "run.sh no longer pins aien-train: {need:?}" 2657 ); 2658 let missing: Vec<&String> = need.difference(&have).collect(); 2659 assert!( 2660 missing.is_empty(), 2661 "sibling map has no aien-sovereign-core line for {missing:?}" 2662 ); 2663 } 2664 2665 #[test] 2666 fn run_sh_sibling_dirs_reads_pin_and_need_sibling() { 2667 let s = "pin() { # pin \n\ 2668 \x20 pin omega-golden omega `bf54b19f`\n\ 2669 \x20 pin aienos aienos \"$(awk 'NF' x)\"\n\ 2670 \x20 need_sibling physics; need_sibling aien-architecture\n\ 2671 # pin not this one\n"; 2672 let d: Vec = run_sh_sibling_dirs(s).into_iter().collect(); 2673 assert_eq!(d, ["aien-architecture", "aienos", "omega", "physics"]); 2674 } 2675 2676 #[test] 2677 fn sibling_refs_are_plain_branch_names() { 2678 for good in ["main", "feat/canonical-branch-native-runtime", "v1.2_x-y"] { 2679 assert!(valid_ref(good), "{good}"); 2680 } 2681 for bad in [ 2682 "", "-x", "/x", "x/", "a//b", "a/../b", ".x", "a/.b", "a b", "a~1", "a^", "a:b", 2683 ] { 2684 assert!(!valid_ref(bad), "{bad:?}"); 2685 } 2686 } 2687 2688 #[test] 2689 fn state_layout() { 2690 let s = StateDir::new(Path::new("/s")); 2691 assert_eq!(s.evidence("r", "abc"), PathBuf::from("/s/evidence/r/abc")); 2692 assert_eq!( 2693 s.bundle_path("r", "abc"), 2694 PathBuf::from("/s/bundles/r/abc/bundle.json") 2695 ); 2696 assert_eq!(s.trigger_dir(), PathBuf::from("/s/trigger")); 2697 assert_eq!(s.journal(), PathBuf::from("/s/journal.jsonl")); 2698 assert_eq!( 2699 StateDir::repo_key("github.com/aien-dev/aien-sovereign-core"), 2700 "aien-sovereign-core" 2701 ); 2702 assert_eq!(StateDir::repo_key("x"), "x"); 2703 } 2704 2705 #[test] 2706 fn github_states() { 2707 assert_eq!(github_state("PASS", Verdict::Pass), "success"); 2708 assert_eq!(github_state("FAIL", Verdict::Fail), "failure"); 2709 assert_eq!(github_state("NOT_RUN", Verdict::NotRun), "error"); 2710 assert_eq!(github_state("NOT_RUN", Verdict::BlockedOperator), "error"); 2711 // A PASS bundle whose plan-level verdict is not PASS is not success. 2712 assert_eq!(github_state("PASS", Verdict::NotRun), "error"); 2713 assert_eq!( 2714 owner_repo("github.com/aien-dev/x").as_deref(), 2715 Some("aien-dev/x") 2716 ); 2717 assert_eq!(owner_repo("aien-dev/x").as_deref(), Some("aien-dev/x")); 2718 assert_eq!(owner_repo("x"), None); 2719 // success needs the independent check too. 2720 assert_eq!(publish_state(true, "PASS", Verdict::Pass), "success"); 2721 assert_eq!(publish_state(false, "PASS", Verdict::Pass), "error"); 2722 assert_eq!(publish_state(false, "FAIL", Verdict::Fail), "failure"); 2723 assert_eq!(publish_state(true, "NOT_RUN", Verdict::NotRun), "error"); 2724 } 2725 2726 #[test] 2727 fn names_and_sandbox_policy() { 2728 assert!(valid_repo_key("aien-sovereign-core")); 2729 assert!(valid_repo_key("a.b_c-1")); 2730 for bad in ["", ".", "..", ".x", "a/b", "a b", "a\0b"] { 2731 assert!(!valid_repo_key(bad), "{bad:?}"); 2732 } 2733 assert!(valid_sha(&"a".repeat(40))); 2734 assert!(!valid_sha(&"A".repeat(40))); 2735 assert!(!valid_sha(&"a".repeat(39))); 2736 assert!(!valid_sha(&"g".repeat(40))); 2737 let mut cfg = Config::new( 2738 StateDir::new(Path::new("/s")), 2739 Path::new("/k"), 2740 Path::new("/c"), 2741 Path::new("/w"), 2742 ); 2743 // The library default is the development sandbox, refused unless allowed. 2744 assert_eq!(cfg.sandbox, Sandbox::None); 2745 assert!(cfg.check_sandbox_policy_for(false).is_err()); 2746 cfg.allow_unsandboxed = true; 2747 assert!(cfg.check_sandbox_policy_for(false).is_ok()); 2748 assert!(cfg.check_sandbox_policy_for(true).is_err()); 2749 cfg.sandbox = Sandbox::User; 2750 assert!(cfg.check_sandbox_policy_for(true).is_ok()); 2751 } 2752 2753 #[test] 2754 fn triggers_and_outbox_files() { 2755 let t = crate::testutil::TempDir::new("worker-state"); 2756 let s = StateDir::new(t.path()); 2757 fs::create_dir_all(s.trigger_dir()).unwrap(); 2758 fs::write(s.trigger_dir().join(format!("repo.{}", "a".repeat(40))), "").unwrap(); 2759 fs::write(s.trigger_dir().join("junk"), "").unwrap(); 2760 fs::write(s.trigger_dir().join("repo.short"), "").unwrap(); 2761 let t3 = triggers(&s); 2762 assert_eq!(t3.len(), 1); 2763 assert_eq!( 2764 (t3[0].0.as_str(), t3[0].1.as_str()), 2765 ("repo", "a".repeat(40).as_str()) 2766 ); 2767 let st = Status { 2768 repository: "github.com/o/r".into(), 2769 sha: "b".repeat(40), 2770 state: "success".into(), 2771 description: "d".into(), 2772 }; 2773 queue_status(&s, "r", &st).unwrap(); 2774 let q = outbox_files(&s); 2775 assert_eq!(q.len(), 1); 2776 let name = q[0].file_name().unwrap().to_string_lossy().into_owned(); 2777 assert!( 2778 name.ends_with(&format!(".r.{}.json", "b".repeat(40))), 2779 "{name}" 2780 ); 2781 assert_eq!(name.split('.').next().unwrap().len(), 20, "{name}"); 2782 // Queue order: c after b; a newer status for b replaces the older one 2783 // and moves to the end. 2784 let c = Status { 2785 sha: "c".repeat(40), 2786 ..st.clone() 2787 }; 2788 queue_status(&s, "r", &c).unwrap(); 2789 let b2 = Status { 2790 state: "failure".into(), 2791 ..st.clone() 2792 }; 2793 queue_status(&s, "r", &b2).unwrap(); 2794 let q = outbox_files(&s); 2795 assert_eq!(q.len(), 2); 2796 assert!(q[0].to_string_lossy().contains(&"c".repeat(40))); 2797 assert!(q[1].to_string_lossy().contains(&"b".repeat(40))); 2798 assert!(fs::read_to_string(&q[1]).unwrap().contains("failure")); 2799 s.journal_append(&json!({"a": 1})).unwrap(); 2800 s.journal_append(&json!({"b": 2})).unwrap(); 2801 let j = fs::read_to_string(s.journal()).unwrap(); 2802 assert_eq!(j.lines().count(), 2); 2803 s.beat("r", "sha", "plan"); 2804 let hb: Value = serde_json::from_str(&fs::read_to_string(s.heartbeat()).unwrap()).unwrap(); 2805 assert_eq!(hb["phase"], "plan"); 2806 } 2807 2808 #[test] 2809 fn triggers_for_takes_only_the_listed_repos() { 2810 let t = crate::testutil::TempDir::new("worker-trig-repos"); 2811 let s = StateDir::new(t.path()); 2812 fs::create_dir_all(s.trigger_dir()).unwrap(); 2813 for repo in ["core", "small", "other"] { 2814 fs::write( 2815 s.trigger_dir().join(format!("{repo}.{}", "a".repeat(40))), 2816 "", 2817 ) 2818 .unwrap(); 2819 } 2820 // No list: every trigger, as before. 2821 assert_eq!(triggers_for(&s, &[]).len(), 3); 2822 let mine = triggers_for(&s, &["core".to_string(), "small".to_string()]); 2823 let mut names: Vec<&str> = mine.iter().map(|t| t.0.as_str()).collect(); 2824 names.sort(); 2825 assert_eq!(names, ["core", "small"]); 2826 // Filtering reads the files, it never removes the ones it skips. 2827 assert!(s 2828 .trigger_dir() 2829 .join(format!("other.{}", "a".repeat(40))) 2830 .exists()); 2831 } 2832 2833 #[test] 2834 fn one_head_is_judged_by_one_process_at_a_time() { 2835 let t = crate::testutil::TempDir::new("worker-claim"); 2836 let s = StateDir::new(t.path()); 2837 let (a, b) = ("a".repeat(40), "b".repeat(40)); 2838 let first = claim_head(&s, "repo", &a).unwrap().expect("first claim"); 2839 let lock = s.head_lock("repo", &a); 2840 assert!(lock.exists()); 2841 // The same (repo, sha) is taken: the second asker is told who holds it. 2842 assert!(claim_head(&s, "repo", &a).unwrap().is_none()); 2843 assert_eq!(head_holder(&s, "repo", &a), Some(std::process::id())); 2844 // Another sha, and another repo with the same sha, are free. 2845 let other_sha = claim_head(&s, "repo", &b).unwrap().expect("other sha"); 2846 let other_repo = claim_head(&s, "repo2", &a).unwrap().expect("other repo"); 2847 drop((other_sha, other_repo)); 2848 // Releasing frees the head and leaves no lock file behind. 2849 drop(first); 2850 assert!(!lock.exists()); 2851 assert!(claim_head(&s, "repo", &a).unwrap().is_some()); 2852 } 2853 }