interplane.Get Omega
Read in your language

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

fix(aien-test): one judge per head; pollers take only their own repos triggers (L083)

merged 553186460483aa0d #690 · opened 2026-10-19 22:35 UTC · closed 2026-10-24 01:33 UTC · merged 2026-10-24 01:33 UTC

Imported from GitHub aien-dev/aien-sovereign-core-mv#690, by drakestapleton

Base 27b0d670dc996fc7bd4b4570da37bd231816eb28 · Head e3f1577b05ec3af64c10d784793ac5afec89886f

Merged on GitHub as 1a21d9fadc01eab5042b270649d73a5df2033c96; reachable from main 007ac4ac5ee5edc6f79f411b1706752293604044 (observed 2026-11-18T16:35:46Z)

drakestapleton wrote on 2026-10-19 22:35 UTC

Ledger L083.

Symptom: one aien-local-ci trigger aien-sovereign-core c81fce02 file (2026-10-19 20:25Z) was judged by three pollers at once, two of which do not even list aien-sovereign-core in --repos, plus a hand worker --once. All of them share the worktree /var/lib/aien-run/wt/<repo>/<sha>; the first to finish removed it and the others died FATAL git status ... cannot change to .... Duplicate judges also cost 25-50 min of the sc queue each.

Cause (tools/aien-test/src/worker.rs run_loop): triggers() read every file in trigger/, ignored cfg.repos, and nothing stopped two processes judging one (repo, sha).

Fix:

  • triggers_for(state, repos): a poller started with --repos takes only its own repositories' trigger files; the others stay in place for the poller that lists them (empty list = all, as before).
  • claim_head(): non-blocking flock on <state>/locks/judging/<repo>.<sha> (holder pid inside, unlinked on release with an inode recheck, freed by the kernel if the holder dies). Taken by the loop and by worker --once. A held head is skipped: loop logs HEAD <repo> <sha> SKIP already being judged by pid N; --once prints AIEN_TEST: SKIP ... and exits 75.
  • After claiming, the loop skips a head whose trigger file is gone or (GitHub head) whose bundle now exists.
  • Untouched: aien-run-exec, run_once itself. resources::flock_exclusive is now pub(crate).

Tests (red first, then green): 2 unit tests in worker.rs (triggers_for_takes_only_the_listed_repos, one_head_is_judged_by_one_process_at_a_time) and 3 in tests/local_ci.rs (loop_leaves_triggers_of_other_repos_alone, loop_skips_a_head_another_process_is_judging, worker_once_skips_a_head_another_process_is_judging). cargo test -p aien-test: 295 lib + 5 + 33/35 local_ci; the 2 failures (worker_in_the_user_sandbox_is_ready, ..._reads_a_read_only_sibling) fail identically on origin/main outside the judge sandbox. Clippy clean.

Touches tools/aien-test (pipeline configuration, rule A4): needs an operator run, and a redeploy of the live aien-test after merge. Notes: Spark ~/handoffs/2026-10-19-fixer-trigger-claim.md.

Fetch it

A git bundle of the pull request's head, 8859 bytes.

curl -fsSL https://interplane.io/drakestapleton/aien-sovereign-core-mv/patches/553186460483aa0d.bundle -o 553186460483aa0d.bundle
git fetch 553186460483aa0d.bundle refs/pull/690/head

Raw bundle · Diff

Provenance

This proposal is imported from GitHub; it is not signed by its author. Its import statement and source record:

github-import 1
aien-dev/aien-sovereign-core-mv
690
e3f1577b05ec3af64c10d784793ac5afec89886f
{"kind":"github-import","owner":"aien-dev","repo":"aien-sovereign-core-mv","number":690,"url":"https://github.com/aien-dev/aien-sovereign-core-mv/pull/690","export_sha256":"d815604dc795b494a931d4c9d256159461266bed51d6da460421ed1d94dab90f","imported_utc":"2026-11-18T16:35:46Z"}

Changes

diff --git a/.crumb b/.crumb
index 2822ef11..022f89b3 100644
--- a/.crumb
+++ b/.crumb
@@ -83,7 +83,7 @@
         },
         {
           "digest": "1a65d8ae9be7c2e6ccc39d7ed20762dfde808132a3216c8b82d0ce0232233343",
-          "last_commit": "f8eea420",
+          "last_commit": "5ae9d6a3",
           "name": "crates/aien-cli",
           "purpose": ""
         },
@@ -101,7 +101,7 @@
         },
         {
           "digest": "33c59e438bd2f54515b0b4df7c6b28dd9c3b6f450b4e0a0b09bb8d748e18111f",
-          "last_commit": "b5957723",
+          "last_commit": "a1e91e0a",
           "name": "scripts",
           "purpose": ""
         },
@@ -113,20 +113,20 @@
         },
         {
           "digest": "b951ba47410e53fc92bda5b21209433eb70b090d15667de15924c56540b33684",
-          "last_commit": "fe3677c3",
+          "last_commit": "1739b582",
           "name": "tools/aien-local-ci",
           "purpose": "Local CI sandbox exec contract (C8), aien-run user/caches install, Forgejo trigger hook, health "
         }
       ],
       "children_root": "sha256:d920a87712690a7730a0daa545e3245b6c6504f74a87262f1cd66f0d21e9db3f",
-      "compiled_at": "2026-10-24T00:28:20Z",
+      "compiled_at": "2026-10-24T01:15:20Z",
       "compiler": "crumb-compile/1",
-      "digest": "sha256:7d7efbd069a8fb9d2dace78496d565a9ecdcc2c1953209ea2ff4d3e397c2cd28",
+      "digest": "sha256:67a954e3cf16d94b55d768f64cf7dec0d4e03f182363955973df4d7810e69919",
       "evidence_files": 1578,
       "evidence_root": "sha256:135e27a1a0704c4a8371cd2c1eb555f2b5beec61c212949b029a5457418a7160",
       "files": 5895,
-      "generated_at_commit": "4ca62826b4ec6dae1ee92fa7979ad2b8c676ad3c",
-      "source_tree": "sha256:da08a94cee4499bfd6c15d447fb2d1fb17d513fa5f6597b24689a883cb752dba"
+      "generated_at_commit": "e6340a202203e9a22ce6ebefbd8431284d278ff2",
+      "source_tree": "sha256:c2b72b5f685e115981bdb65a8f861afcbe6ba37c409aae600ccc15ca7dc87d91"
     }
   },
   "history": [],
diff --git a/tools/aien-test/docs/LOCAL_VERIFICATION.md b/tools/aien-test/docs/LOCAL_VERIFICATION.md
index f6a39fcb..b51f5b9c 100644
--- a/tools/aien-test/docs/LOCAL_VERIFICATION.md
+++ b/tools/aien-test/docs/LOCAL_VERIFICATION.md
@@ -360,6 +360,13 @@ that has no bundle yet, then sleeps `--poll` seconds. `--iterations N`
 bounds the rounds (tests). Trigger names that are not a plain repository
 name and a 40-hex commit are ignored.
 
+With `--repos`, the loop takes only trigger files of those repositories and
+leaves the others for the poller that lists them. Before judging a head (loop
+or `--once`) the worker takes an `flock` on `locks/judging/<repo>.<sha>`
+(holder pid inside); if another process holds it the head is skipped with
+`SKIP already being judged by pid N` (`--once` exits 75), because every judge
+of a head shares one worktree and the first to finish removes it.
+
 What starts a run, and what does not (checked 2026-10-11 on the Spark):
 
 | trigger | how | covers today |
@@ -448,6 +455,7 @@ unmapped path, no blocked gate, no problem line.
   evidence/<repo>/<sha>/<digest>.json    receipts of that run
   bundles/<repo>/<sha>/bundle.json       the signed bundle
   trigger/<repo>.<sha>                   a run request (removed when served)
+  locks/judging/<repo>.<sha>            held while one process judges that head
   outbox/<seq>.<repo>.<sha>.json         a commit status waiting for GitHub, in queue order
   journal.jsonl                          one line per finished head
   worker.heartbeat                       pid, phase, repo, sha, utc
diff --git a/tools/aien-test/src/main.rs b/tools/aien-test/src/main.rs
index 7805bda5..f658e526 100644
--- a/tools/aien-test/src/main.rs
+++ b/tools/aien-test/src/main.rs
@@ -498,6 +498,10 @@ fn cmd_verify(cli: &Cli, commit: &str, cwd: &Path) -> i32 {
     }
 }
 
+/// `worker --once` found its head being judged by another process and did
+/// nothing (EX_TEMPFAIL; the verdict codes are 0 to 5).
+const EXIT_HELD: i32 = 75;
+
 fn cmd_worker(cli: &Cli) -> i32 {
     let state = match state_dir(cli) {
         Ok(s) => s,
@@ -567,6 +571,18 @@ fn cmd_worker(cli: &Cli) -> i32 {
     cfg.no_cache = cli.no_cache;
     cfg.hardware_identity = cli.hardware_identity.clone().unwrap_or_default();
     if let Some((repo, sha)) = &cli.once {
+        // The same exclusive right the loop takes: a poller may be judging it.
+        let _claim = match worker::claim_head(&cfg.state, repo, sha) {
+            Ok(Some(c)) => c,
+            Ok(None) => {
+                println!("AIEN_TEST: {}", worker::held_note(&cfg.state, repo, sha));
+                return EXIT_HELD;
+            }
+            Err(e) => {
+                println!("AIEN_TEST: FAIL {e}");
+                return 1;
+            }
+        };
         return match worker::run_once(&cfg, repo, sha) {
             Ok(s) => {
                 for n in &s.notes {
diff --git a/tools/aien-test/src/resources.rs b/tools/aien-test/src/resources.rs
index 4ff019f5..b458997b 100644
--- a/tools/aien-test/src/resources.rs
+++ b/tools/aien-test/src/resources.rs
@@ -540,7 +540,7 @@ fn open_lock(path: &Path) -> io::Result<File> {
 
 /// `flock(LOCK_EX)`: Ok(true) when taken, Ok(false) when held by someone else
 /// and `wait` is off.
-fn flock_exclusive(file: &File, wait: bool) -> io::Result<bool> {
+pub(crate) fn flock_exclusive(file: &File, wait: bool) -> io::Result<bool> {
     let op = if wait {
         libc::LOCK_EX
     } else {
diff --git a/tools/aien-test/src/worker.rs b/tools/aien-test/src/worker.rs
index 5b76cd40..b03faa7c 100644
--- a/tools/aien-test/src/worker.rs
+++ b/tools/aien-test/src/worker.rs
@@ -7,6 +7,7 @@
 //! evidence/<repo>/<sha>/   receipts and blobs of that commit's run
 //! bundles/<repo>/<sha>/bundle.json   the signed VerificationBundleV1
 //! trigger/<repo>.<sha>     a file whose presence asks for a run
+//! locks/judging/<repo>.<sha>  held (flock) by the one process judging that head
 //! outbox/<repo>.<sha>.json a GitHub status that could not be posted yet
 //! journal.jsonl            one line per finished head
 //! worker.heartbeat         what the worker is doing right now
@@ -29,7 +30,7 @@ use crate::evidence::{canonical, canonical_digest, sha256_hex, utc_string};
 use crate::graph;
 use crate::plan::{self, Known, Section};
 use crate::process;
-use crate::resources::{GpuWait, Hardware, JobsSpec, DEFAULT_GPU_WAIT};
+use crate::resources::{self, GpuWait, Hardware, JobsSpec, DEFAULT_GPU_WAIT};
 use crate::runner::{self, CacheNote, Options};
 use crate::sandbox::Sandbox;
 use crate::verdict::Verdict;
@@ -38,6 +39,7 @@ use serde_json::{json, Value};
 use std::collections::BTreeMap;
 use std::fs;
 use std::io::Write;
+use std::os::unix::fs::MetadataExt;
 use std::path::{Path, PathBuf};
 use std::process::Command;
 use std::time::{Duration, SystemTime, UNIX_EPOCH};
@@ -134,6 +136,15 @@ impl StateDir {
         self.root.join("locks").join("target")
     }
 
+    /// `<state>/locks/judging/<repo>.<sha>`: held by the process judging that
+    /// head (`claim_head`).
+    pub fn head_lock(&self, repo: &str, sha: &str) -> PathBuf {
+        self.root
+            .join("locks")
+            .join("judging")
+            .join(format!("{repo}.{sha}"))
+    }
+
     pub fn bundle_path(&self, repo: &str, sha: &str) -> PathBuf {
         self.root
             .join("bundles")
@@ -1382,6 +1393,99 @@ pub fn triggers(state: &StateDir) -> Vec<(String, String, PathBuf)> {
     out
 }
 
+/// `triggers`, limited to the repositories in `repos` (a poller started with
+/// `--repos`). An empty list takes every trigger. Files of other repositories
+/// are left where they are: they belong to the poller that lists them.
+pub fn triggers_for(state: &StateDir, repos: &[String]) -> Vec<(String, String, PathBuf)> {
+    let mut all = triggers(state);
+    if !repos.is_empty() {
+        all.retain(|(repo, _, _)| repos.iter().any(|r| r == repo));
+    }
+    all
+}
+
+/// Exclusive right to judge one (repo, sha) on this machine: an `flock(2)` on
+/// `<state>/locks/judging/<repo>.<sha>`. Every judge of a head shares the
+/// worktree `<wt-root>/<repo>/<sha>`, and the first to finish removes it, so
+/// two processes judging one head (two pollers that both see a trigger file,
+/// or a `worker --once` beside a poller) kill each other's run. The lock file
+/// holds the holder's pid. The kernel drops the lock when the holder dies, so
+/// a crashed worker never blocks the head.
+#[derive(Debug)]
+pub struct HeadClaim {
+    file: Option<fs::File>,
+    path: PathBuf,
+}
+
+impl Drop for HeadClaim {
+    fn drop(&mut self) {
+        // Unlink while still holding the lock: anyone who opened the old file
+        // meanwhile sees the path no longer names it and tries again.
+        let _ = fs::remove_file(&self.path);
+        let _gate = process::spawn_gate();
+        self.file.take();
+    }
+}
+
+/// Take the right to judge `repo` at `sha`. `Ok(None)`: another process holds
+/// it right now (see `head_holder`); the caller skips the head. Never waits.
+pub fn claim_head(state: &StateDir, repo: &str, sha: &str) -> Result<Option<HeadClaim>, String> {
+    if !valid_repo_key(repo) || !valid_sha(sha) {
+        return Err(format!("refusing to claim {repo:?} {sha:?}"));
+    }
+    let path = state.head_lock(repo, sha);
+    let err = |what: &str, e: std::io::Error| format!("{what} {}: {e}", path.display());
+    if let Some(parent) = path.parent() {
+        fs::create_dir_all(parent).map_err(|e| err("cannot create", e))?;
+    }
+    // A holder that finishes between our open and our flock unlinks the file;
+    // we would then hold a lock on a name nobody else can see. Check the path
+    // still names our file and open again when it does not.
+    for _ in 0..16 {
+        let file = fs::OpenOptions::new()
+            .create(true)
+            .read(true)
+            .write(true)
+            .truncate(false)
+            .open(&path)
+            .map_err(|e| err("cannot open", e))?;
+        if !resources::flock_exclusive(&file, false).map_err(|e| err("cannot lock", e))? {
+            return Ok(None);
+        }
+        let named = fs::metadata(&path).ok();
+        let ours = file.metadata().map_err(|e| err("cannot stat", e))?;
+        if !named.is_some_and(|m| m.dev() == ours.dev() && m.ino() == ours.ino()) {
+            continue;
+        }
+        file.set_len(0).map_err(|e| err("cannot write", e))?;
+        (&file)
+            .write_all(format!("{}\n", std::process::id()).as_bytes())
+            .map_err(|e| err("cannot write", e))?;
+        return Ok(Some(HeadClaim {
+            file: Some(file),
+            path,
+        }));
+    }
+    Err(format!("cannot settle the claim on {}", path.display()))
+}
+
+/// The pid that holds the claim on (repo, sha), when it is readable.
+pub fn head_holder(state: &StateDir, repo: &str, sha: &str) -> Option<u32> {
+    fs::read_to_string(state.head_lock(repo, sha))
+        .ok()?
+        .trim()
+        .parse()
+        .ok()
+}
+
+/// The log words for a head another process is judging.
+pub fn held_note(state: &StateDir, repo: &str, sha: &str) -> String {
+    match head_holder(state, repo, sha) {
+        Some(pid) => format!("SKIP already being judged by pid {pid}"),
+        None => "SKIP already being judged by another process".to_string(),
+    }
+}
+
 /// Open PR heads and the main head of `repo` from GitHub (bounded: one call
 /// per list). Errors are returned, never fatal to the loop.
 pub fn github_heads(gh: &str, repository: &str) -> Result<Vec<String>, String> {
@@ -1434,10 +1538,11 @@ pub fn run_loop(cfg: &Config, iterations: Option<u64>) -> usize {
         if posted + pending > 0 {
             println!("OUTBOX posted={posted} pending={pending}");
         }
-        let mut heads: Vec<(String, String, Option<PathBuf>)> = triggers(&cfg.state)
-            .into_iter()
-            .map(|(r, s, f)| (r, s, Some(f)))
-            .collect();
+        let mut heads: Vec<(String, String, Option<PathBuf>)> =
+            triggers_for(&cfg.state, &cfg.repos)
+                .into_iter()
+                .map(|(r, s, f)| (r, s, Some(f)))
+                .collect();
         if cfg.github {
             for repo in &cfg.repos {
                 let repository = plan::repository_name(&cfg.clones.join(repo), None);
@@ -1454,6 +1559,27 @@ pub fn run_loop(cfg: &Config, iterations: Option<u64>) -> usize {
             }
         }
         for (repo, sha, trigger) in heads {
+            // One process judges a head at a time: the worktree is shared.
+            let _claim = match claim_head(&cfg.state, &repo, &sha) {
+                Ok(Some(c)) => c,
+                Ok(None) => {
+                    println!("HEAD {repo} {sha} {}", held_note(&cfg.state, &repo, &sha));
+                    continue;
+                }
+                Err(e) => {
+                    println!("HEAD {repo} {sha} ERROR {e}");
+                    continue;
+                }
+            };
+            // The holder we waited behind may have served this head already.
+            let served_meanwhile = match &trigger {
+                Some(f) => !f.exists(),
+                None => cfg.state.bundle_path(&repo, &sha).exists(),
+            };
+            if served_meanwhile {
+                println!("HEAD {repo} {sha} SKIP already judged by another process");
+                continue;
+            }
             match run_once(cfg, &repo, &sha) {
                 Ok(s) => {
                     println!(
@@ -1822,4 +1948,50 @@ mod tests {
         let hb: Value = serde_json::from_str(&fs::read_to_string(s.heartbeat()).unwrap()).unwrap();
         assert_eq!(hb["phase"], "plan");
     }
+
+    #[test]
+    fn triggers_for_takes_only_the_listed_repos() {
+        let t = crate::testutil::TempDir::new("worker-trig-repos");
+        let s = StateDir::new(t.path());
+        fs::create_dir_all(s.trigger_dir()).unwrap();
+        for repo in ["core", "small", "other"] {
+            fs::write(
+                s.trigger_dir().join(format!("{repo}.{}", "a".repeat(40))),
+                "",
+            )
+            .unwrap();
+        }
+        // No list: every trigger, as before.
+        assert_eq!(triggers_for(&s, &[]).len(), 3);
+        let mine = triggers_for(&s, &["core".to_string(), "small".to_string()]);
+        let mut names: Vec<&str> = mine.iter().map(|t| t.0.as_str()).collect();
+        names.sort();
+        assert_eq!(names, ["core", "small"]);
+        // Filtering reads the files, it never removes the ones it skips.
+        assert!(s
+            .trigger_dir()
+            .join(format!("other.{}", "a".repeat(40)))
+            .exists());
+    }
+
+    #[test]
+    fn one_head_is_judged_by_one_process_at_a_time() {
+        let t = crate::testutil::TempDir::new("worker-claim");
+        let s = StateDir::new(t.path());
+        let (a, b) = ("a".repeat(40), "b".repeat(40));
+        let first = claim_head(&s, "repo", &a).unwrap().expect("first claim");
+        let lock = s.head_lock("repo", &a);
+        assert!(lock.exists());
+        // The same (repo, sha) is taken: the second asker is told who holds it.
+        assert!(claim_head(&s, "repo", &a).unwrap().is_none());
+        assert_eq!(head_holder(&s, "repo", &a), Some(std::process::id()));
+        // Another sha, and another repo with the same sha, are free.
+        let other_sha = claim_head(&s, "repo", &b).unwrap().expect("other sha");
+        let other_repo = claim_head(&s, "repo2", &a).unwrap().expect("other repo");
+        drop((other_sha, other_repo));
+        // Releasing frees the head and leaves no lock file behind.
+        drop(first);
+        assert!(!lock.exists());
+        assert!(claim_head(&s, "repo", &a).unwrap().is_some());
+    }
 }
diff --git a/tools/aien-test/tests/local_ci.rs b/tools/aien-test/tests/local_ci.rs
index 398475ae..1a00b840 100644
--- a/tools/aien-test/tests/local_ci.rs
+++ b/tools/aien-test/tests/local_ci.rs
@@ -1559,3 +1559,74 @@ fn worker_operator_run_of_a_config_change_is_ready_and_posts_success() {
         "{journal}"
     );
 }
+
+#[test]
+fn loop_leaves_triggers_of_other_repos_alone() {
+    // One trigger file is visible to every poller; a poller started with
+    // --repos takes only its own repositories and leaves the file in place.
+    let w = world();
+    let mut cfg = w.config();
+    cfg.repos = vec!["some-other-repo".to_string()];
+    let trigger = w.state.trigger_dir().join(format!("{REPO}.{}", w.head));
+    fs::create_dir_all(w.state.trigger_dir()).unwrap();
+    fs::write(&trigger, "").unwrap();
+    assert_eq!(worker::run_loop(&cfg, Some(1)), 0);
+    assert!(trigger.exists());
+    assert!(!w.bundle_path(&w.head).exists());
+    cfg.repos = vec![REPO.to_string()];
+    assert_eq!(worker::run_loop(&cfg, Some(1)), 1);
+    assert!(!trigger.exists());
+    assert!(w.bundle_path(&w.head).exists());
+}
+
+#[test]
+fn loop_skips_a_head_another_process_is_judging() {
+    // A head already being judged is not judged again, and its trigger file
+    // stays for the holder (or the next round) to deal with.
+    let w = world();
+    let cfg = w.config();
+    let trigger = w.state.trigger_dir().join(format!("{REPO}.{}", w.head));
+    fs::create_dir_all(w.state.trigger_dir()).unwrap();
+    fs::write(&trigger, "").unwrap();
+    let held = worker::claim_head(&w.state, REPO, &w.head)
+        .unwrap()
+        .expect("claim");
+    assert_eq!(worker::run_loop(&cfg, Some(1)), 0);
+    assert!(trigger.exists());
+    assert!(!w.bundle_path(&w.head).exists());
+    drop(held);
+    assert_eq!(worker::run_loop(&cfg, Some(1)), 1);
+    assert!(!trigger.exists());
+}
+
+#[test]
+fn worker_once_skips_a_head_another_process_is_judging() {
+    // `worker --once` for a head a poller holds does nothing and says so.
+    let bin = env!("CARGO_BIN_EXE_aien-test");
+    let t = Tmp::new("once-held");
+    let state = StateDir::new(&t.path().join("state"));
+    let sha = "a".repeat(40);
+    let held = worker::claim_head(&state, "repo", &sha)
+        .unwrap()
+        .expect("claim");
+    let o = Command::new(bin)
+        .args(["worker", "--once", "repo", sha.as_str(), "--state-dir"])
+        .arg(&state.root)
+        .arg("--clones")
+        .arg(t.path())
+        .args(["--sandbox", "none", "--dev-unsandboxed"])
+        .output()
+        .unwrap();
+    let out = String::from_utf8_lossy(&o.stdout);
+    assert_eq!(o.status.code(), Some(75), "{out}");
+    assert!(
+        out.contains(&format!(
+            "already being judged by pid {}",
+            std::process::id()
+        )),
+        "{out}"
+    );
+    // Nothing was fetched, journaled or run.
+    assert!(!state.journal().exists());
+    drop(held);
+}