diff --git a/.crumb b/.crumb index 08ee53fc..95620828 100644 --- a/.crumb +++ b/.crumb @@ -119,14 +119,14 @@ } ], "children_root": "sha256:7d8cf5937a13dd896fe511aee80a0873f4917a0a5eb07cbe0fe3690c0c878cbb", - "compiled_at": "2026-10-16T10:56:35Z", + "compiled_at": "2026-10-16T12:47:55Z", "compiler": "crumb-compile/1", - "digest": "sha256:465b497c444698ff5ff701c52b5835526c9e7bf1bdb5bf9b3805e3753d369dd8", + "digest": "sha256:3f2b0f344de88bd003c199fa0d9bbeea4b91477ac16669e5a6b4f3d9f8d6b306", "evidence_files": 1578, "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160", "files": 5889, - "generated_at_commit": "a78ee68ab9a1285a7d4e8a983a7738ff2e1b7d4a", - "source_tree": "sha256:d2f1c2a7c6e804ba394685c392e84936afceeee5c6bf795bc5f3903b9113d8e2" + "generated_at_commit": "f5108c7e52ebba9ba355d4c3547011d0d8e23213", + "source_tree": "sha256:26be27c5d01953ee9460da09d6539cf631150890694993b0b4f4ed2bc765155e" } }, "history": [], diff --git a/tools/aien-test/docs/LOCAL_VERIFICATION.md b/tools/aien-test/docs/LOCAL_VERIFICATION.md index 790900cb..e955a369 100644 --- a/tools/aien-test/docs/LOCAL_VERIFICATION.md +++ b/tools/aien-test/docs/LOCAL_VERIFICATION.md @@ -118,6 +118,22 @@ rule (`Config.allow_unsandboxed`, default false). Under `--sandbox user` the worker passes `CARGO_TARGET_DIR=/var/lib/aien-run/target//main` for a head already on the base line and `.../pr` for any other head (A2). +The gates of one head share that target dir, so the runner holds it for one +gate at a time: every gate that runs takes an exclusive `flock` on +`/locks/target/.lock` (the `CARGO_TARGET_DIR` it +is given, or else the worktree's own `target/`) for its whole run, build and +execution, and releases it when its process has exited. Every gate, not only +those whose manifest names cargo inputs: SC-INQUISITOR builds with cargo and +lists no `Cargo.toml`, and the runner cannot see inside a script. The lock is +the worker's, never the gate's. Without it two gates built in one target dir +at once and one relinked a test binary the other was executing (sc fix/521: +SC-AGENT-PREFLIGHT under SC-TEST, `current_exe: NotFound`, a false FAIL). +Gates given different target dirs still run at the same time. The fixed lock +order of one gate is: pool slot, target-dir lock, `/tmp/aien-gb10.lock`, +aien-proof `slots/gpu.lock`; the worker's target priming takes only the +target-dir lock. Known limit: a gb10 gate is never killed on timeout, so a +hung one holds the target dir until it exits on its own. + Under `--sandbox user` every checkout is made with INFRA's worktree tool (`--wt-tool`, default `/aien-sovereign-core/tools/aien-local-ci/wt.sh`; without it the worker refuses to run). `wt.sh sync` refreshes the bare mirror diff --git a/tools/aien-test/src/resources.rs b/tools/aien-test/src/resources.rs index fe55128e..407c6aad 100644 --- a/tools/aien-test/src/resources.rs +++ b/tools/aien-test/src/resources.rs @@ -8,9 +8,17 @@ //! //! Deadlock rule: whenever more than one resource is taken, they are taken in //! one fixed order. Pools are ordered by `Pool`'s derived `Ord` (gb10, then -//! qemu, then host). For a gb10 job the order is: the in-process gb10 slot, -//! then `/tmp/aien-gb10.lock`, then aien-proof's `slots/gpu.lock` when the -//! aien-proof board directory exists. +//! qemu, then host). The full order for one gate is: (1) the in-process pool +//! slot, (2) the target-dir lock (`lock_target_dir`, every gate that runs, +//! on its `CARGO_TARGET_DIR` or else the worktree's `target/`), (3) +//! `/tmp/aien-gb10.lock`, (4) aien-proof's `slots/gpu.lock` when the +//! aien-proof board directory exists. A holder of (2) already has its slot +//! and never waits for one, so a gate blocked on (2) with a slot in hand +//! cannot close a cycle; the worker's target priming takes (2) alone and +//! never (3) or (4). Known limit: a gb10 gate is never killed on timeout, +//! so a hung one holds (2) and (3) until it exits on its own; every other +//! gate of that target dir waits behind it (the receipt says +//! `timeout_exceeded`). //! //! GPU job protocol (CR-028, CR-029, CR-033, CR-052, CR-053): refuse at once //! (never wait, never steal) if the quiet flag file exists or an `est_load` @@ -405,6 +413,68 @@ impl Drop for GpuGuard { } } +/// The default directory of the target-dir lock files for a bare `run` +/// without a worker state dir (the worker uses `/locks/target`). +pub const DEFAULT_TARGET_LOCK_DIR: &str = "/tmp/aien-test-target-locks"; + +/// The lock file for one cargo target dir: `/.lock`, +/// where every character of the target dir path outside `[A-Za-z0-9._-]` +/// becomes `_`. The path is taken as given (no canonicalising), so every +/// holder that names the same target dir names the same lock file. Not +/// inside the target dir itself: under the user sandbox that belongs to +/// `aien-run`, and the lock is the worker's. +pub fn target_lock_path(lock_dir: &Path, target_dir: &Path) -> PathBuf { + let name: String = target_dir + .display() + .to_string() + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') { + c + } else { + '_' + } + }) + .collect(); + lock_dir.join(format!("{name}.lock")) +} + +/// Exclusive hold of one cargo target dir (`flock(LOCK_EX)`, waited for). +/// Held by the runner for a whole cargo gate, build and run, so two gates of +/// one head never build in, or relink a binary under, the same target dir +/// at once (sc fix/521: SC-AGENT-PREFLIGHT relinked a test binary while +/// SC-TEST was executing it). Dropping it closes the descriptor under the +/// spawn gate, like `GpuGuard`. +#[derive(Debug)] +pub struct TargetLock { + file: Option, + path: PathBuf, +} + +impl TargetLock { + pub fn path(&self) -> &Path { + &self.path + } +} + +impl Drop for TargetLock { + fn drop(&mut self) { + let _gate = crate::process::spawn_gate(); + self.file.take(); + } +} + +/// Take the target-dir lock at `path` (see `target_lock_path`), waiting for +/// the holder to finish. The file is created if absent and never deleted. +pub fn lock_target_dir(path: &Path) -> io::Result { + let file = open_lock(path)?; + flock_exclusive(&file, true)?; + Ok(TargetLock { + file: Some(file), + path: path.to_path_buf(), + }) +} + fn open_lock(path: &Path) -> io::Result { if let Some(parent) = path.parent() { if !parent.as_os_str().is_empty() { @@ -516,6 +586,46 @@ mod tests { }); } + #[test] + fn target_lock_path_is_one_file_per_target_dir_under_the_lock_dir() { + let p = target_lock_path( + Path::new("/state/locks/target"), + Path::new("/var/lib/aien-run/target/aien-sovereign-core/pr"), + ); + assert_eq!( + p, + PathBuf::from( + "/state/locks/target/_var_lib_aien-run_target_aien-sovereign-core_pr.lock" + ) + ); + let main = target_lock_path(Path::new("/l"), Path::new("/t/main")); + let pr = target_lock_path(Path::new("/l"), Path::new("/t/pr")); + assert_ne!(main, pr, "main and pr are different target dirs"); + } + + /// Two holders in one process (two `open`s, two file descriptions) and + /// so two threads of the runner exclude each other; the second waits + /// until the first is dropped. + #[test] + fn target_lock_is_exclusive_and_waited_for() { + let dir = TempDir::new("tlock"); + let path = target_lock_path(dir.path(), Path::new("/t/pr")); + let held = lock_target_dir(&path).unwrap(); + assert!(held.path().exists()); + let (tx, rx) = mpsc::channel(); + thread::scope(|s| { + s.spawn(|| { + let _second = lock_target_dir(&path).unwrap(); + tx.send(()).unwrap(); + }); + thread::sleep(Duration::from_millis(200)); + assert!(rx.try_recv().is_err(), "the second holder must wait"); + drop(held); + rx.recv_timeout(Duration::from_secs(20)) + .expect("the waiter takes the lock after the release"); + }); + } + #[test] fn gb10_pool_is_serialized() { let p = Pools::new(PoolSizes { host: 4, qemu: 2 }); diff --git a/tools/aien-test/src/runner.rs b/tools/aien-test/src/runner.rs index 1258b401..0cf0703b 100644 --- a/tools/aien-test/src/runner.rs +++ b/tools/aien-test/src/runner.rs @@ -27,7 +27,7 @@ use crate::graph::Graph; use crate::manifest::{self, Manifest}; use crate::process::{self, RunSpec}; use crate::resources::{ - acquire_gpu, lock, GpuConfig, GpuGuard, Hardware, Permit, Pool, PoolSizes, Pools, + self, acquire_gpu, lock, GpuConfig, GpuGuard, Hardware, Permit, Pool, PoolSizes, Pools, }; use crate::sandbox::{self, Sandbox}; use crate::verdict::{self, campaign_verdict, derive, parse_observations, DepFact, Facts, Verdict}; @@ -60,6 +60,11 @@ pub struct Options { /// `CARGO_TARGET_DIR` as the runner itself was given it; passed through /// the sandbox as the only environment pair. pub cargo_target_dir: Option, + /// Where the per-target-dir lock files live (`resources::target_lock_path`). + /// Every gate that runs holds the lock of its target dir (`cargo_target_dir` + /// or the worktree's `target/`) for its whole run, so two gates never + /// build in one target dir at once. The worker sets `/locks/target`. + pub target_lock_dir: PathBuf, /// `--release`: qualification mode. No cache reuse and the tree must be /// clean even with `--allow-dirty`. pub release: bool, @@ -83,6 +88,7 @@ impl Options { gpu: GpuConfig::detect(), sandbox: Sandbox::None, cargo_target_dir: None, + target_lock_dir: PathBuf::from(crate::resources::DEFAULT_TARGET_LOCK_DIR), release: false, pins: json!([]), } @@ -660,6 +666,31 @@ fn execute_gate(job: &Job<'_>, permit: Option>) -> Result = if verdict::pre_run(m, &facts).is_none() { + let dir = opts + .cargo_target_dir + .clone() + .unwrap_or_else(|| resolve(root).join("target")); + let path = resources::target_lock_path(&opts.target_lock_dir, &dir); + Some(resources::lock_target_dir(&path).map_err(|e| { + RunError::Fatal(format!("cannot lock target dir {}: {e}", path.display())) + })?) + } else { + None + }; + // A gb10 gate takes the GPU locks only when nothing else already stops it. // A refusal (quiet flag, est_load, a held lock) becomes the gate's reason. let gpu: Option = if m.pool() == "gb10" && verdict::pre_run(m, &facts).is_none() { @@ -717,6 +748,7 @@ fn execute_gate(job: &Job<'_>, permit: Option>) -> Result.gate) and script /// (tools/.sh) per entry; `@S@` in a script is the scratch directory. fn gfx(gates: &[GateSpec]) -> Gfx { + gfx_with(gates, "", &[]) + } + + /// `inputs` block of a gate that declares it builds in the target dir. + const CARGO_INPUTS: &str = "inputs:\n - Cargo.lock\n"; + + /// `gfx` with `extra` appended to every manifest and `files` added to + /// the repository (a `Cargo.lock` for the cargo gates). + fn gfx_with(gates: &[GateSpec], extra: &str, more: &[(&str, &str)]) -> Gfx { let scratch = TempDir::new("gscratch"); let s = scratch.path().to_str().unwrap().to_string(); let mut files: Vec<(String, String, bool)> = Vec::new(); @@ -1696,10 +1737,13 @@ mod tests { files.push((format!("tools/{id}.sh"), script.replace("@S@", &s), true)); files.push(( format!("tests/{id}.gate"), - graph_gate_text(id, deps, requires), + format!("{}{extra}", graph_gate_text(id, deps, requires)), false, )); } + for (p, c) in more { + files.push((p.to_string(), c.to_string(), false)); + } let refs: Vec<(&str, &str, bool)> = files .iter() .map(|(p, c, x)| (p.as_str(), c.as_str(), *x)) @@ -1843,14 +1887,130 @@ mod tests { assert_eq!(c.exit_code(), 3); } + /// `log` holds `start-X, end-X` pairs with no interleaving. + fn assert_serial(log: &[String], what: &str) { + assert_eq!(log.len() % 2, 0, "{what}: {log:?}"); + for pair in log.chunks(2) { + let id = pair[0].strip_prefix("start-").unwrap_or("?"); + assert_eq!(pair[1], format!("end-{id}"), "{what} overlapped: {log:?}"); + } + } + + /// Without a `CARGO_TARGET_DIR` the gates of one run still share the + /// worktree's own `target/`, so they are serialised on that path. + #[test] + fn gates_without_a_target_dir_serialise_on_the_worktree_target() { + let fx = gfx(&[ + ("G-A", "", "host", slow("G-A")), + ("G-B", "", "host", slow("G-B")), + ]); + let mut opts = fx.opts(); + opts.target_lock_dir = fx.scratch.path().join("locks"); + let c = fx.campaign(&opts); + assert_eq!(c.exit_code(), 0); + let log = fx.log(); + assert_eq!(log.len(), 4, "{log:?}"); + assert_serial(&log, "gates sharing the worktree target"); + let lock = crate::resources::target_lock_path( + &opts.target_lock_dir, + &resolve(fx.repo.path()).join("target"), + ); + assert!(lock.exists(), "lock {} never taken", lock.display()); + } + + /// A gate may call cargo without naming `Cargo.toml` among its inputs + /// (SC-INQUISITOR builds spark-inquisitor that way), so the rule is not + /// "cargo gates": every gate given a `CARGO_TARGET_DIR` holds it. #[test] - fn independent_gates_run_at_the_same_time_when_the_pool_allows() { + fn every_gate_given_a_target_dir_is_serialised() { + let cargo_user = |id: &str| { + format!( + "#!/bin/sh\necho start-{id} >> \"@S@/log\"\n\"${{CARGO:-cargo}}\" --version >/dev/null\nsleep 0.2\necho end-{id} >> \"@S@/log\"\n" + ) + }; + let fx = gfx(&[ + ("G-A", "", "host", cargo_user("G-A")), + ("G-B", "", "host", cargo_user("G-B")), + ]); + let mut opts = fx.opts(); + opts.cargo_target_dir = Some(fx.scratch.path().join("target")); + opts.target_lock_dir = fx.scratch.path().join("locks"); + let c = fx.campaign(&opts); + assert_eq!(c.exit_code(), 0); + let log = fx.log(); + assert_eq!(log.len(), 4, "{log:?}"); + assert_serial(&log, "undeclared cargo users"); + } + + /// Two cargo gates of one head share `CARGO_TARGET_DIR`. Run at the same + /// time, one relinks a test binary the other is executing (sc fix/521: + /// SC-AGENT-PREFLIGHT relinked `aien_inference_abi-*` under SC-TEST, which + /// then failed with `current_exe: NotFound`). The runner must hold the + /// target dir for one cargo gate at a time, whatever the pool allows. + #[test] + fn cargo_gates_sharing_a_target_dir_never_overlap() { + let fx = gfx_with( + &[ + ("C-A", "", "host", slow("C-A")), + ("C-B", "", "host", slow("C-B")), + ], + CARGO_INPUTS, + &[("Cargo.lock", "# lock\n")], + ); + let mut opts = fx.opts(); + opts.cargo_target_dir = Some(fx.scratch.path().join("target")); + opts.target_lock_dir = fx.scratch.path().join("locks"); + let c = fx.campaign(&opts); + assert_eq!(c.exit_code(), 0); + let log = fx.log(); + assert_eq!(log.len(), 4, "{log:?}"); + let first = log[0].trim_start_matches("start-").to_string(); + let second = if first == "C-A" { "C-B" } else { "C-A" }; + assert_eq!( + log, + vec![ + format!("start-{first}"), + format!("end-{first}"), + format!("start-{second}"), + format!("end-{second}"), + ], + "the two cargo gates overlapped in one target dir" + ); + let lock = crate::resources::target_lock_path( + &opts.target_lock_dir, + &fx.scratch.path().join("target"), + ); + assert!( + lock.exists(), + "the lock file {} was never taken", + lock.display() + ); + } + + /// The lock is per target dir: gates given different target dirs still + /// run at the same time. + #[test] + fn gates_with_different_target_dirs_run_at_the_same_time() { let fx = gfx(&[ ("G-A", "", "host", rendezvous("a", "b")), ("G-B", "", "host", rendezvous("b", "a")), ]); - let c = fx.campaign(&fx.opts()); - assert_eq!(c.exit_code(), 0); + let mut opts = fx.opts(); + opts.target_lock_dir = fx.scratch.path().join("locks"); + let g = fx.graph(); + let (a, b) = (g.index_of("G-A").unwrap(), g.index_of("G-B").unwrap()); + thread::scope(|s| { + for (i, dir) in [(a, "ta"), (b, "tb")] { + let mut o = Options { + cargo_target_dir: Some(fx.scratch.path().join(dir)), + ..fx.opts() + }; + o.target_lock_dir = opts.target_lock_dir.clone(); + let sel: BTreeSet = [i].into_iter().collect(); + let (g, root) = (&g, fx.repo.path()); + s.spawn(move || run_graph(root, g, &sel, &o).unwrap()); + } + }); assert!(fx.scratch.path().join("saw-a").exists(), "A never saw B"); assert!(fx.scratch.path().join("saw-b").exists(), "B never saw A"); } diff --git a/tools/aien-test/src/worker.rs b/tools/aien-test/src/worker.rs index 4736e9dd..39288d3c 100644 --- a/tools/aien-test/src/worker.rs +++ b/tools/aien-test/src/worker.rs @@ -126,6 +126,14 @@ impl StateDir { self.root.join("evidence").join(repo).join(sha) } + /// `/locks/target`: the per-target-dir lock files + /// (`resources::target_lock_path`). Every holder of a cargo target dir, + /// a gate run by this worker or the worker's own priming of + /// `target//pr`, takes its lock from here. + pub fn target_lock_dir(&self) -> PathBuf { + self.root.join("locks").join("target") + } + pub fn bundle_path(&self, repo: &str, sha: &str) -> PathBuf { self.root .join("bundles") @@ -912,6 +920,7 @@ fn run_in_worktree( let mut opts = Options::new(evidence_dir.clone()); opts.sandbox = cfg.sandbox; opts.cargo_target_dir = target_dir_for(cfg, repo, on_main); + opts.target_lock_dir = cfg.state.target_lock_dir(); opts.pool_sizes = opts.pool_sizes.with(cfg.jobs); opts.pins = pins; if fresh || cfg.no_cache {