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
aien-sovereign-core-mv / crates / aien-proof / src / board.rs
| 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 board: look up the stamp, join an identical run in flight, or claim the |
| 17 | //! job and run it behind the CPU slot, memory, and GPU gates. |
| 18 | //! |
| 19 | //! Board layout (default `~/.local/state/aien-proof`, override `AIEN_PROOF_DIR`): |
| 20 | //! stamps/<key>.json passing runs, reused by every agent and worktree |
| 21 | //! fails/<key>.json latest failing run, shared only with runs that joined it |
| 22 | //! locks/<key>.lock held while a job runs; identical requests block on it |
| 23 | //! slots/cpu-N.lock CPU slots (`AIEN_PROOF_SLOTS`) |
| 24 | //! slots/gpu.lock the GPU key, one GPU job at a time |
| 25 | //! slots/res-<name>.lock other exclusive keys, e.g. `machine-1` |
| 26 | //! slots/<name>.holder who holds a key right now (agent, pid, job, since) |
| 27 | //! holds/<key>.json record of each `hold` run (never reused) |
| 28 | //! logs/<key>.log full output of the latest real run |
| 29 | //! ledger.jsonl hash-chained record of every real run |
| 30 | |
| 31 | use crate::{fingerprint, ledger, lock::FileLock}; |
| 32 | use serde::{Deserialize, Serialize}; |
| 33 | use std::fs; |
| 34 | use std::io::{self, Read, Write}; |
| 35 | use std::path::PathBuf; |
| 36 | use std::process::{Command, Stdio}; |
| 37 | use std::sync::{Arc, Mutex}; |
| 38 | use std::thread; |
| 39 | use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; |
| 40 | |
| 41 | const GIB: u64 = 1024 * 1024 * 1024; |
| 42 | |
| 43 | pub struct Board { |
| 44 | pub root: PathBuf, |
| 45 | pub cpu_slots: usize, |
| 46 | pub min_free_bytes: u64, |
| 47 | /// Longest wait for free memory before running anyway (a gate that never |
| 48 | /// opens would hang the hive). |
| 49 | pub mem_wait: Duration, |
| 50 | pub quiet: bool, |
| 51 | } |
| 52 | |
| 53 | pub struct Job { |
| 54 | pub name: String, |
| 55 | pub agent: String, |
| 56 | /// Directory the command runs in; inputs are relative to it. |
| 57 | pub base: PathBuf, |
| 58 | pub inputs: Vec<PathBuf>, |
| 59 | pub cmd: Vec<String>, |
| 60 | pub gpu: bool, |
| 61 | /// Exclusive keys held for the whole run, e.g. `machine-1`. |
| 62 | pub resources: Vec<String>, |
| 63 | pub toolchain: String, |
| 64 | } |
| 65 | |
| 66 | impl Job { |
| 67 | /// Every exclusive key this job needs, including `gpu` when set. |
| 68 | pub fn resource_names(&self) -> Vec<String> { |
| 69 | let mut names = self.resources.clone(); |
| 70 | if self.gpu { |
| 71 | names.push("gpu".into()); |
| 72 | } |
| 73 | names.sort(); |
| 74 | names.dedup(); |
| 75 | names |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | /// Key names are path components: lowercase letters, digits and dashes only. |
| 80 | pub fn valid_resource(name: &str) -> bool { |
| 81 | !name.is_empty() |
| 82 | && name.len() <= 64 |
| 83 | && name |
| 84 | .bytes() |
| 85 | .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') |
| 86 | } |
| 87 | |
| 88 | /// An exclusive key. The holder file is removed before the lock is released |
| 89 | /// (`Drop` runs before fields are dropped), so a named holder is never stale |
| 90 | /// while the key is free. |
| 91 | pub struct ResourceGuard { |
| 92 | _lock: FileLock, |
| 93 | holder: PathBuf, |
| 94 | } |
| 95 | |
| 96 | impl Drop for ResourceGuard { |
| 97 | fn drop(&mut self) { |
| 98 | let _ = fs::remove_file(&self.holder); |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | #[derive(Debug, Clone, Serialize, Deserialize)] |
| 103 | pub struct Record { |
| 104 | pub key: String, |
| 105 | pub job: String, |
| 106 | pub agent: String, |
| 107 | pub cmd: Vec<String>, |
| 108 | pub exit_code: i32, |
| 109 | pub duration_ms: u64, |
| 110 | pub finished_at: u64, |
| 111 | pub ledger_index: u64, |
| 112 | pub ledger_hash: String, |
| 113 | } |
| 114 | |
| 115 | #[derive(Debug)] |
| 116 | pub enum Outcome { |
| 117 | /// A passing stamp already existed; nothing ran. |
| 118 | Stamped(Record), |
| 119 | /// An identical run was in flight; its result was shared, nothing ran. |
| 120 | Joined(Record), |
| 121 | /// This request ran the job. |
| 122 | Ran(Record), |
| 123 | } |
| 124 | |
| 125 | impl Outcome { |
| 126 | pub fn record(&self) -> &Record { |
| 127 | match self { |
| 128 | Outcome::Stamped(r) | Outcome::Joined(r) | Outcome::Ran(r) => r, |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | pub fn passed(&self) -> bool { |
| 133 | self.record().exit_code == 0 |
| 134 | } |
| 135 | |
| 136 | pub fn label(&self) -> &'static str { |
| 137 | match self { |
| 138 | Outcome::Stamped(_) => "stamped", |
| 139 | Outcome::Joined(_) => "joined", |
| 140 | Outcome::Ran(_) => "ran", |
| 141 | } |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn now() -> u64 { |
| 146 | SystemTime::now() |
| 147 | .duration_since(UNIX_EPOCH) |
| 148 | .map(|d| d.as_secs()) |
| 149 | .unwrap_or(0) |
| 150 | } |
| 151 | |
| 152 | fn env_num(name: &str) -> Option<u64> { |
| 153 | std::env::var(name).ok()?.trim().parse().ok() |
| 154 | } |
| 155 | |
| 156 | /// `MemAvailable` from /proc/meminfo, in bytes. |
| 157 | pub fn mem_available() -> Option<u64> { |
| 158 | let info = fs::read_to_string("/proc/meminfo").ok()?; |
| 159 | let line = info.lines().find(|l| l.starts_with("MemAvailable:"))?; |
| 160 | let kb: u64 = line |
| 161 | .trim_start_matches("MemAvailable:") |
| 162 | .trim() |
| 163 | .trim_end_matches("kB") |
| 164 | .trim() |
| 165 | .parse() |
| 166 | .ok()?; |
| 167 | Some(kb * 1024) |
| 168 | } |
| 169 | |
| 170 | fn tee<R: Read + Send + 'static>( |
| 171 | mut src: R, |
| 172 | log: Arc<Mutex<fs::File>>, |
| 173 | echo: bool, |
| 174 | to_stderr: bool, |
| 175 | ) -> thread::JoinHandle<()> { |
| 176 | thread::spawn(move || { |
| 177 | let mut buf = [0u8; 8192]; |
| 178 | loop { |
| 179 | let n = match src.read(&mut buf) { |
| 180 | Ok(0) | Err(_) => break, |
| 181 | Ok(n) => n, |
| 182 | }; |
| 183 | if let Ok(mut f) = log.lock() { |
| 184 | let _ = f.write_all(&buf[..n]); |
| 185 | } |
| 186 | if echo { |
| 187 | if to_stderr { |
| 188 | let _ = io::stderr().write_all(&buf[..n]); |
| 189 | } else { |
| 190 | let _ = io::stdout().write_all(&buf[..n]); |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | }) |
| 195 | } |
| 196 | |
| 197 | impl Board { |
| 198 | pub fn from_env() -> Self { |
| 199 | let root = std::env::var_os("AIEN_PROOF_DIR") |
| 200 | .map(PathBuf::from) |
| 201 | .unwrap_or_else(|| { |
| 202 | let home = std::env::var_os("HOME") |
| 203 | .map(PathBuf::from) |
| 204 | .unwrap_or_else(|| PathBuf::from(".")); |
| 205 | home.join(".local/state/aien-proof") |
| 206 | }); |
| 207 | let cores = thread::available_parallelism() |
| 208 | .map(|n| n.get()) |
| 209 | .unwrap_or(4); |
| 210 | Self { |
| 211 | root, |
| 212 | cpu_slots: env_num("AIEN_PROOF_SLOTS") |
| 213 | .map(|n| n as usize) |
| 214 | .unwrap_or((cores / 8).max(2)), |
| 215 | min_free_bytes: env_num("AIEN_PROOF_MIN_FREE_GB").unwrap_or(4) * GIB, |
| 216 | mem_wait: Duration::from_secs(env_num("AIEN_PROOF_MEM_WAIT_SECS").unwrap_or(600)), |
| 217 | quiet: false, |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | fn note(&self, msg: &str) { |
| 222 | if !self.quiet { |
| 223 | eprintln!("[aien-proof] {msg}"); |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | fn record_path(&self, kind: &str, key: &str) -> PathBuf { |
| 228 | self.root.join(kind).join(format!("{key}.json")) |
| 229 | } |
| 230 | |
| 231 | fn read_record(&self, kind: &str, key: &str) -> Option<Record> { |
| 232 | serde_json::from_slice(&fs::read(self.record_path(kind, key)).ok()?).ok() |
| 233 | } |
| 234 | |
| 235 | fn write_record(&self, kind: &str, rec: &Record) -> io::Result<()> { |
| 236 | let path = self.record_path(kind, &rec.key); |
| 237 | fs::create_dir_all(path.parent().unwrap())?; |
| 238 | let tmp = path.with_extension(format!("tmp{}", std::process::id())); |
| 239 | fs::write(&tmp, serde_json::to_vec_pretty(rec)?)?; |
| 240 | fs::rename(tmp, path) |
| 241 | } |
| 242 | |
| 243 | fn replay(&self, how: &str, rec: &Record) { |
| 244 | if self.quiet { |
| 245 | return; |
| 246 | } |
| 247 | let verdict = if rec.exit_code == 0 { "pass" } else { "FAIL" }; |
| 248 | eprintln!( |
| 249 | "[aien-proof] {}: {how} {verdict} (ran by {} in {} ms, ledger #{}), replaying output", |
| 250 | rec.job, rec.agent, rec.duration_ms, rec.ledger_index |
| 251 | ); |
| 252 | if let Ok(log) = fs::read(self.root.join("logs").join(format!("{}.log", rec.key))) { |
| 253 | let _ = io::stdout().write_all(&log); |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | fn acquire_cpu_slot(&self) -> io::Result<FileLock> { |
| 258 | let mut noted = false; |
| 259 | loop { |
| 260 | for i in 0..self.cpu_slots.max(1) { |
| 261 | if let Some(slot) = |
| 262 | FileLock::try_acquire(&self.root.join("slots").join(format!("cpu-{i}.lock")))? |
| 263 | { |
| 264 | return Ok(slot); |
| 265 | } |
| 266 | } |
| 267 | if !noted { |
| 268 | self.note(&format!("all {} CPU slots busy, waiting", self.cpu_slots)); |
| 269 | noted = true; |
| 270 | } |
| 271 | thread::sleep(Duration::from_millis(100)); |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | fn resource_lock_path(&self, name: &str) -> PathBuf { |
| 276 | // `gpu` keeps its original path so older binaries still exclude each other. |
| 277 | if name == "gpu" { |
| 278 | self.root.join("slots/gpu.lock") |
| 279 | } else { |
| 280 | self.root.join("slots").join(format!("res-{name}.lock")) |
| 281 | } |
| 282 | } |
| 283 | |
| 284 | /// Acquire keys in sorted order so two jobs can never deadlock. |
| 285 | pub fn acquire_resources( |
| 286 | &self, |
| 287 | names: &[String], |
| 288 | agent: &str, |
| 289 | job: &str, |
| 290 | ) -> io::Result<Vec<ResourceGuard>> { |
| 291 | let mut names: Vec<&String> = names.iter().collect(); |
| 292 | names.sort(); |
| 293 | names.dedup(); |
| 294 | let mut guards = Vec::with_capacity(names.len()); |
| 295 | for name in names { |
| 296 | if !valid_resource(name) { |
| 297 | return Err(io::Error::new( |
| 298 | io::ErrorKind::InvalidInput, |
| 299 | format!( |
| 300 | "invalid resource name {name:?}: use lowercase letters, digits, dashes" |
| 301 | ), |
| 302 | )); |
| 303 | } |
| 304 | let lock_path = self.resource_lock_path(name); |
| 305 | let holder = self.root.join("slots").join(format!("{name}.holder")); |
| 306 | let lock = match FileLock::try_acquire(&lock_path)? { |
| 307 | Some(lock) => lock, |
| 308 | None => { |
| 309 | let who = fs::read_to_string(&holder).unwrap_or_default(); |
| 310 | let who = who.trim(); |
| 311 | self.note(&format!( |
| 312 | "{name} key held by {}, waiting", |
| 313 | if who.is_empty() { "another run" } else { who } |
| 314 | )); |
| 315 | FileLock::acquire(&lock_path)? |
| 316 | } |
| 317 | }; |
| 318 | fs::write( |
| 319 | &holder, |
| 320 | format!( |
| 321 | "agent={agent} pid={} job={job} since={}\n", |
| 322 | std::process::id(), |
| 323 | now() |
| 324 | ), |
| 325 | )?; |
| 326 | guards.push(ResourceGuard { |
| 327 | _lock: lock, |
| 328 | holder, |
| 329 | }); |
| 330 | } |
| 331 | Ok(guards) |
| 332 | } |
| 333 | |
| 334 | /// Run `cmd` in `base`, teeing output to the terminal and `log_path`. |
| 335 | /// Returns the exit code and wall time in milliseconds. |
| 336 | fn execute( |
| 337 | &self, |
| 338 | cmd: &[String], |
| 339 | base: &std::path::Path, |
| 340 | log_path: &std::path::Path, |
| 341 | ) -> io::Result<(i32, u64)> { |
| 342 | fs::create_dir_all(log_path.parent().unwrap())?; |
| 343 | let log = Arc::new(Mutex::new(fs::File::create(log_path)?)); |
| 344 | let started = Instant::now(); |
| 345 | let mut child = Command::new(&cmd[0]) |
| 346 | .args(&cmd[1..]) |
| 347 | .current_dir(base) |
| 348 | .stdin(Stdio::null()) |
| 349 | .stdout(Stdio::piped()) |
| 350 | .stderr(Stdio::piped()) |
| 351 | .spawn()?; |
| 352 | let out = tee( |
| 353 | child.stdout.take().unwrap(), |
| 354 | log.clone(), |
| 355 | !self.quiet, |
| 356 | false, |
| 357 | ); |
| 358 | let err = tee(child.stderr.take().unwrap(), log.clone(), !self.quiet, true); |
| 359 | let status = child.wait()?; |
| 360 | let _ = out.join(); |
| 361 | let _ = err.join(); |
| 362 | Ok(( |
| 363 | status.code().unwrap_or(-1), |
| 364 | started.elapsed().as_millis() as u64, |
| 365 | )) |
| 366 | } |
| 367 | |
| 368 | /// Run `job.cmd` while holding its exclusive keys, with no fingerprint, |
| 369 | /// stamp or reuse: hardware actions such as booting Machine 1 must happen |
| 370 | /// every time they are asked for. Recorded in the ledger as an `audit` |
| 371 | /// event whose payload is the full output. |
| 372 | pub fn hold(&self, job: &Job) -> io::Result<Record> { |
| 373 | if job.cmd.is_empty() { |
| 374 | return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty command")); |
| 375 | } |
| 376 | let names = job.resource_names(); |
| 377 | if names.is_empty() { |
| 378 | return Err(io::Error::new( |
| 379 | io::ErrorKind::InvalidInput, |
| 380 | "hold needs at least one --resource", |
| 381 | )); |
| 382 | } |
| 383 | let _keys = self.acquire_resources(&names, &job.agent, &job.name)?; |
| 384 | let mut id = blake3::Hasher::new(); |
| 385 | id.update(b"AIEN_PROOF_HOLD_V1"); |
| 386 | id.update(job.name.as_bytes()); |
| 387 | id.update(job.agent.as_bytes()); |
| 388 | id.update(&std::process::id().to_be_bytes()); |
| 389 | let nanos = SystemTime::now() |
| 390 | .duration_since(UNIX_EPOCH) |
| 391 | .map(|d| d.as_nanos()) |
| 392 | .unwrap_or(0); |
| 393 | id.update(&nanos.to_be_bytes()); |
| 394 | let key = id.finalize().to_hex().to_string(); |
| 395 | |
| 396 | let log_path = self.root.join("logs").join(format!("{key}.log")); |
| 397 | let (exit_code, duration_ms) = self.execute(&job.cmd, &job.base, &log_path)?; |
| 398 | let payload = fs::read(&log_path)?; |
| 399 | let verdict = if exit_code == 0 { "pass" } else { "fail" }; |
| 400 | let intent = format!("{verdict} exit={exit_code} resources={}", names.join(",")); |
| 401 | let event = ledger::append_action( |
| 402 | &self.root, "audit", &job.agent, &job.name, &intent, &payload, |
| 403 | )?; |
| 404 | let rec = Record { |
| 405 | key, |
| 406 | job: job.name.clone(), |
| 407 | agent: job.agent.clone(), |
| 408 | cmd: job.cmd.clone(), |
| 409 | exit_code, |
| 410 | duration_ms, |
| 411 | finished_at: now(), |
| 412 | ledger_index: event.index, |
| 413 | ledger_hash: ledger::hex(&event.hash), |
| 414 | }; |
| 415 | self.write_record("holds", &rec)?; |
| 416 | Ok(rec) |
| 417 | } |
| 418 | |
| 419 | /// Current key holders as `(name, holder line)`. |
| 420 | pub fn holders(&self) -> Vec<(String, String)> { |
| 421 | let mut out: Vec<(String, String)> = fs::read_dir(self.root.join("slots")) |
| 422 | .into_iter() |
| 423 | .flatten() |
| 424 | .flatten() |
| 425 | .filter_map(|e| { |
| 426 | let name = e.file_name().to_string_lossy().into_owned(); |
| 427 | let name = name.strip_suffix(".holder")?.to_string(); |
| 428 | let who = fs::read_to_string(e.path()).ok()?; |
| 429 | Some((name, who.trim().to_string())) |
| 430 | }) |
| 431 | .collect(); |
| 432 | out.sort(); |
| 433 | out |
| 434 | } |
| 435 | |
| 436 | fn wait_for_memory(&self) { |
| 437 | let start = Instant::now(); |
| 438 | let mut noted = false; |
| 439 | while let Some(free) = mem_available() { |
| 440 | if free >= self.min_free_bytes { |
| 441 | return; |
| 442 | } |
| 443 | if start.elapsed() >= self.mem_wait { |
| 444 | self.note("memory still low after the wait limit, running anyway"); |
| 445 | return; |
| 446 | } |
| 447 | if !noted { |
| 448 | self.note(&format!( |
| 449 | "{} GiB free, below the {} GiB gate, waiting", |
| 450 | free / GIB, |
| 451 | self.min_free_bytes / GIB |
| 452 | )); |
| 453 | noted = true; |
| 454 | } |
| 455 | thread::sleep(Duration::from_millis(500)); |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | pub fn run(&self, job: &Job) -> io::Result<Outcome> { |
| 460 | if job.cmd.is_empty() { |
| 461 | return Err(io::Error::new(io::ErrorKind::InvalidInput, "empty command")); |
| 462 | } |
| 463 | let key = |
| 464 | fingerprint::job_key(&job.base, &job.name, &job.cmd, &job.toolchain, &job.inputs)?; |
| 465 | if let Some(rec) = self.read_record("stamps", &key) { |
| 466 | self.replay("stamped", &rec); |
| 467 | return Ok(Outcome::Stamped(rec)); |
| 468 | } |
| 469 | |
| 470 | let lock_path = self.root.join("locks").join(format!("{key}.lock")); |
| 471 | let _job_lock = match FileLock::try_acquire(&lock_path)? { |
| 472 | Some(lock) => lock, |
| 473 | None => { |
| 474 | let waited_from = now(); |
| 475 | self.note(&format!( |
| 476 | "{}: identical run already in flight, joining it", |
| 477 | job.name |
| 478 | )); |
| 479 | let lock = FileLock::acquire(&lock_path)?; |
| 480 | if let Some(rec) = self.read_record("stamps", &key) { |
| 481 | self.replay("joined", &rec); |
| 482 | return Ok(Outcome::Joined(rec)); |
| 483 | } |
| 484 | if let Some(rec) = self.read_record("fails", &key) { |
| 485 | if rec.finished_at >= waited_from { |
| 486 | self.replay("joined", &rec); |
| 487 | return Ok(Outcome::Joined(rec)); |
| 488 | } |
| 489 | } |
| 490 | lock |
| 491 | } |
| 492 | }; |
| 493 | // A run may have finished between the first lookup and taking the lock. |
| 494 | if let Some(rec) = self.read_record("stamps", &key) { |
| 495 | self.replay("stamped", &rec); |
| 496 | return Ok(Outcome::Stamped(rec)); |
| 497 | } |
| 498 | |
| 499 | let _cpu = self.acquire_cpu_slot()?; |
| 500 | self.wait_for_memory(); |
| 501 | let _keys = self.acquire_resources(&job.resource_names(), &job.agent, &job.name)?; |
| 502 | |
| 503 | let log_path = self.root.join("logs").join(format!("{key}.log")); |
| 504 | let (exit_code, duration_ms) = self.execute(&job.cmd, &job.base, &log_path)?; |
| 505 | |
| 506 | let payload = fs::read(&log_path)?; |
| 507 | let verdict = if exit_code == 0 { "pass" } else { "fail" }; |
| 508 | let intent = format!("{verdict} exit={exit_code} key={key}"); |
| 509 | let event = ledger::append(&self.root, &job.agent, &job.name, &intent, &payload)?; |
| 510 | let rec = Record { |
| 511 | key, |
| 512 | job: job.name.clone(), |
| 513 | agent: job.agent.clone(), |
| 514 | cmd: job.cmd.clone(), |
| 515 | exit_code, |
| 516 | duration_ms, |
| 517 | finished_at: now(), |
| 518 | ledger_index: event.index, |
| 519 | ledger_hash: ledger::hex(&event.hash), |
| 520 | }; |
| 521 | self.write_record(if exit_code == 0 { "stamps" } else { "fails" }, &rec)?; |
| 522 | Ok(Outcome::Ran(rec)) |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | #[cfg(test)] |
| 527 | mod tests { |
| 528 | use super::*; |
| 529 | use crate::testutil::temp_dir; |
| 530 | |
| 531 | fn board(tag: &str) -> Board { |
| 532 | Board { |
| 533 | root: temp_dir(tag), |
| 534 | cpu_slots: 4, |
| 535 | min_free_bytes: 0, |
| 536 | mem_wait: Duration::from_secs(1), |
| 537 | quiet: true, |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | /// A job whose command appends a line to `runs` (outside its inputs), so the |
| 542 | /// number of lines is the number of real executions. |
| 543 | fn job(base: &std::path::Path, name: &str, script: &str) -> Job { |
| 544 | fs::create_dir_all(base.join("src")).unwrap(); |
| 545 | fs::write(base.join("src/lib.rs"), "pub fn a() {}").unwrap(); |
| 546 | Job { |
| 547 | name: name.into(), |
| 548 | agent: "tester".into(), |
| 549 | base: base.to_path_buf(), |
| 550 | inputs: vec![PathBuf::from("src")], |
| 551 | cmd: vec![ |
| 552 | "sh".into(), |
| 553 | "-c".into(), |
| 554 | format!("echo x >> runs; {script}"), |
| 555 | ], |
| 556 | gpu: false, |
| 557 | resources: vec![], |
| 558 | toolchain: "test".into(), |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | fn runs(base: &std::path::Path) -> usize { |
| 563 | fs::read_to_string(base.join("runs")) |
| 564 | .map(|s| s.lines().count()) |
| 565 | .unwrap_or(0) |
| 566 | } |
| 567 | |
| 568 | #[test] |
| 569 | fn pass_is_stamped_then_replayed_without_running() { |
| 570 | let b = board("board-stamp"); |
| 571 | let base = temp_dir("base-stamp"); |
| 572 | let j = job(&base, "unit", "true"); |
| 573 | assert!(matches!(b.run(&j).unwrap(), Outcome::Ran(_))); |
| 574 | let second = b.run(&j).unwrap(); |
| 575 | assert!(matches!(second, Outcome::Stamped(_))); |
| 576 | assert!(second.passed()); |
| 577 | assert_eq!(runs(&base), 1); |
| 578 | assert_eq!( |
| 579 | ledger::verify(&b.root.join(ledger::LEDGER_FILE)).unwrap().0, |
| 580 | 1 |
| 581 | ); |
| 582 | } |
| 583 | |
| 584 | #[test] |
| 585 | fn a_second_worktree_with_the_same_code_reuses_the_stamp() { |
| 586 | let b = board("board-worktree"); |
| 587 | let (wt1, wt2) = (temp_dir("wt1"), temp_dir("wt2")); |
| 588 | assert!(matches!( |
| 589 | b.run(&job(&wt1, "unit", "true")).unwrap(), |
| 590 | Outcome::Ran(_) |
| 591 | )); |
| 592 | assert!(matches!( |
| 593 | b.run(&job(&wt2, "unit", "true")).unwrap(), |
| 594 | Outcome::Stamped(_) |
| 595 | )); |
| 596 | assert_eq!(runs(&wt1) + runs(&wt2), 1); |
| 597 | } |
| 598 | |
| 599 | #[test] |
| 600 | fn identical_concurrent_requests_run_once() { |
| 601 | let b = Arc::new(board("board-join")); |
| 602 | let base = temp_dir("base-join"); |
| 603 | let j = Arc::new(job(&base, "slow", "sleep 1")); |
| 604 | let handles: Vec<_> = (0..5) |
| 605 | .map(|_| { |
| 606 | let (b, j) = (b.clone(), j.clone()); |
| 607 | thread::spawn(move || b.run(&j).unwrap()) |
| 608 | }) |
| 609 | .collect(); |
| 610 | let outcomes: Vec<Outcome> = handles.into_iter().map(|h| h.join().unwrap()).collect(); |
| 611 | assert_eq!(runs(&base), 1); |
| 612 | assert_eq!( |
| 613 | outcomes |
| 614 | .iter() |
| 615 | .filter(|o| matches!(o, Outcome::Ran(_))) |
| 616 | .count(), |
| 617 | 1 |
| 618 | ); |
| 619 | assert!(outcomes.iter().all(Outcome::passed)); |
| 620 | } |
| 621 | |
| 622 | #[test] |
| 623 | fn failures_are_not_stamped_but_are_shared_with_joiners() { |
| 624 | let b = Arc::new(board("board-fail")); |
| 625 | let base = temp_dir("base-fail"); |
| 626 | let j = Arc::new(job(&base, "broken", "sleep 1; exit 3")); |
| 627 | let handles: Vec<_> = (0..3) |
| 628 | .map(|_| { |
| 629 | let (b, j) = (b.clone(), j.clone()); |
| 630 | thread::spawn(move || b.run(&j).unwrap()) |
| 631 | }) |
| 632 | .collect(); |
| 633 | for h in handles { |
| 634 | assert_eq!(h.join().unwrap().record().exit_code, 3); |
| 635 | } |
| 636 | assert_eq!(runs(&base), 1); |
| 637 | // A fresh request after the failure runs again rather than trusting it. |
| 638 | assert!(matches!(b.run(&j).unwrap(), Outcome::Ran(_))); |
| 639 | assert_eq!(runs(&base), 2); |
| 640 | } |
| 641 | |
| 642 | #[test] |
| 643 | fn gpu_jobs_never_overlap() { |
| 644 | let b = Arc::new(board("board-gpu")); |
| 645 | let base = temp_dir("base-gpu"); |
| 646 | let started = Instant::now(); |
| 647 | let handles: Vec<_> = (0..2) |
| 648 | .map(|i| { |
| 649 | let b = b.clone(); |
| 650 | let mut j = job(&base, &format!("gpu-{i}"), "sleep 0.5"); |
| 651 | j.gpu = true; |
| 652 | thread::spawn(move || b.run(&j).unwrap()) |
| 653 | }) |
| 654 | .collect(); |
| 655 | for h in handles { |
| 656 | assert!(h.join().unwrap().passed()); |
| 657 | } |
| 658 | assert!(started.elapsed() >= Duration::from_millis(1000)); |
| 659 | } |
| 660 | |
| 661 | fn hold_job(base: &std::path::Path, resource: &str, script: &str) -> Job { |
| 662 | let mut j = job(base, "boot-machine-1", script); |
| 663 | j.resources = vec![resource.into()]; |
| 664 | j |
| 665 | } |
| 666 | |
| 667 | #[test] |
| 668 | fn holds_on_the_same_key_never_overlap_and_are_never_reused() { |
| 669 | let b = Arc::new(board("hold-same")); |
| 670 | let base = temp_dir("base-hold-same"); |
| 671 | let started = Instant::now(); |
| 672 | let handles: Vec<_> = (0..2) |
| 673 | .map(|_| { |
| 674 | let (b, j) = (b.clone(), hold_job(&base, "machine-1", "sleep 0.5")); |
| 675 | thread::spawn(move || b.hold(&j).unwrap()) |
| 676 | }) |
| 677 | .collect(); |
| 678 | for h in handles { |
| 679 | assert_eq!(h.join().unwrap().exit_code, 0); |
| 680 | } |
| 681 | assert!(started.elapsed() >= Duration::from_millis(1000)); |
| 682 | // Identical commands both ran: hardware actions are not stamped. |
| 683 | assert_eq!(runs(&base), 2); |
| 684 | } |
| 685 | |
| 686 | #[test] |
| 687 | fn different_keys_run_in_parallel() { |
| 688 | let b = Arc::new(board("hold-diff")); |
| 689 | let base = temp_dir("base-hold-diff"); |
| 690 | let started = Instant::now(); |
| 691 | let handles: Vec<_> = ["machine-1", "machine-2"] |
| 692 | .into_iter() |
| 693 | .map(|r| { |
| 694 | let (b, j) = (b.clone(), hold_job(&base, r, "sleep 0.6")); |
| 695 | thread::spawn(move || b.hold(&j).unwrap()) |
| 696 | }) |
| 697 | .collect(); |
| 698 | for h in handles { |
| 699 | h.join().unwrap(); |
| 700 | } |
| 701 | assert!(started.elapsed() < Duration::from_millis(1100)); |
| 702 | } |
| 703 | |
| 704 | #[test] |
| 705 | fn holder_is_visible_during_the_run_and_the_run_is_audited() { |
| 706 | let b = board("hold-audit"); |
| 707 | let base = temp_dir("base-hold-audit"); |
| 708 | let holder = b.root.join("slots/machine-1.holder"); |
| 709 | let rec = b |
| 710 | .hold(&hold_job( |
| 711 | &base, |
| 712 | "machine-1", |
| 713 | &format!("cat {}", holder.display()), |
| 714 | )) |
| 715 | .unwrap(); |
| 716 | assert_eq!(rec.exit_code, 0); |
| 717 | let log = fs::read_to_string(b.root.join("logs").join(format!("{}.log", rec.key))).unwrap(); |
| 718 | assert!( |
| 719 | log.contains("agent=tester") && log.contains("job=boot-machine-1"), |
| 720 | "{log}" |
| 721 | ); |
| 722 | assert!(!holder.exists()); |
| 723 | assert!(b.holders().is_empty()); |
| 724 | |
| 725 | let ledger_text = fs::read_to_string(b.root.join(ledger::LEDGER_FILE)).unwrap(); |
| 726 | let event: ledger::LedgerEvent = |
| 727 | serde_json::from_str(ledger_text.lines().last().unwrap()).unwrap(); |
| 728 | assert_eq!(event.action, "audit"); |
| 729 | assert!(event.intent.contains("resources=machine-1")); |
| 730 | assert_eq!( |
| 731 | ledger::verify(&b.root.join(ledger::LEDGER_FILE)).unwrap().0, |
| 732 | 1 |
| 733 | ); |
| 734 | } |
| 735 | |
| 736 | #[test] |
| 737 | fn run_honors_named_keys() { |
| 738 | let b = Arc::new(board("run-keys")); |
| 739 | let base = temp_dir("base-run-keys"); |
| 740 | let started = Instant::now(); |
| 741 | let handles: Vec<_> = (0..2) |
| 742 | .map(|i| { |
| 743 | let mut j = job(&base, &format!("job-{i}"), "sleep 0.5"); |
| 744 | j.resources = vec!["machine-1".into()]; |
| 745 | let b = b.clone(); |
| 746 | thread::spawn(move || b.run(&j).unwrap()) |
| 747 | }) |
| 748 | .collect(); |
| 749 | for h in handles { |
| 750 | assert!(h.join().unwrap().passed()); |
| 751 | } |
| 752 | assert!(started.elapsed() >= Duration::from_millis(1000)); |
| 753 | } |
| 754 | |
| 755 | #[test] |
| 756 | fn rejects_unsafe_key_names_and_holds_without_a_key() { |
| 757 | let b = board("hold-names"); |
| 758 | let base = temp_dir("base-hold-names"); |
| 759 | for bad in ["", "../etc", "Machine1", "a b", &"x".repeat(65)] { |
| 760 | assert!(!valid_resource(bad), "{bad:?}"); |
| 761 | assert!(b.hold(&hold_job(&base, bad, "true")).is_err()); |
| 762 | } |
| 763 | assert!(valid_resource("machine-1")); |
| 764 | assert!(b.hold(&job(&base, "no-key", "true")).is_err()); |
| 765 | assert_eq!(runs(&base), 0); |
| 766 | } |
| 767 | } |