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

branch main Branches Tags History

aien-sovereign-core-mv / tools / aien-test / src / resources.rs

1415 lines · 52031 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//! Resource pools and the GPU locks (ADR 0028 Decision 6).
17//!
18//! Three counting semaphores inside one runner process: `host` (default size
19//! is the CPU count), `qemu` (default `min(4, host / 2)`, a guess that is
20//! overridable with `--jobs`), and `gb10` (fixed at 1). A job holds exactly
21//! one pool slot. Semaphores are plain `Mutex` plus `Condvar`; a `Permit` is
22//! an RAII guard that returns its slot when dropped.
23//!
24//! Deadlock rule: whenever more than one resource is taken, they are taken in
25//! one fixed order. Pools are ordered by `Pool`'s derived `Ord` (gb10, then
26//! qemu, then host). The full order for one gate is: (1) the in-process pool
27//! slot, (2) the target-dir lock (`lock_target_dir`, every gate that runs,
28//! on its `CARGO_TARGET_DIR` or else the worktree's `target/`), (3)
29//! `/tmp/aien-gb10.lock`, (4) aien-proof's `slots/gpu.lock` when the
30//! aien-proof board directory exists. A holder of (2) already has its slot
31//! and never waits for one, so a gate blocked on (2) with a slot in hand
32//! cannot close a cycle; the worker's target priming takes (2) alone and
33//! never (3) or (4). Known limit: a gb10 gate is never killed on timeout,
34//! so a hung one holds (2) and (3) until it exits on its own; every other
35//! gate of that target dir waits behind it (the receipt says
36//! `timeout_exceeded`).
37//!
38//! GPU job protocol (CR-028, CR-029, CR-033, CR-052, CR-053): refuse at once
39//! (never wait, never steal) if the quiet flag file exists or an `est_load`
40//! process is running, then take the `flock(2)` locks. A held lock is waited
41//! for up to a bound (`GpuWait`, default `DEFAULT_GPU_WAIT`), then refused:
42//! the live model server takes `/tmp/aien-gb10.lock` around every request
43//! (sc `aien-serve-http`, `GpuLock::acquire_queued_at`), so a single try
44//! loses nearly every time. The wait is a blocking `flock` in the kernel's
45//! queue on a helper thread, the same queue the server's requests and
46//! `flock(1)` jobs wait in, so neither side can starve the other the way a
47//! poller with `LOCK_NB` is starved by queued waiters. `--gpu-wait 0` refuses
48//! at once; `--wait-gpu` waits without a bound. The lock files are created if
49//! absent and never deleted. Dropping a `GpuGuard` closes the descriptors,
50//! and the kernel releases the locks (a dead holder frees them too).
51//!
52//! Fork window: a `flock` lives as long as any copy of the open file
53//! description does, and a child that another thread forks while a lock
54//! descriptor is open holds a copy until it execs (the descriptor is
55//! close-on-exec, so it never survives the exec). The guard therefore closes
56//! its descriptors under `process::spawn_gate`, the mutex every child spawn
57//! in this crate also takes, so no child is in that window at the moment the
58//! lock is released and the next `acquire_gpu` is not refused by a lock
59//! nobody holds.
60
61use std::fmt;
62use std::fs::{self, File, OpenOptions};
63use std::io;
64use std::os::unix::io::AsRawFd;
65use std::path::{Path, PathBuf};
66use std::sync::atomic::{AtomicBool, Ordering};
67use std::sync::{mpsc, Arc, Condvar, Mutex, MutexGuard};
68use std::time::{Duration, Instant};
69
70pub const DEFAULT_GPU_LOCK: &str = "/tmp/aien-gb10.lock";
71
72/// How long a gb10 gate waits for a held GPU lock before NOT_RUN `gpu_lock`.
73/// The server's own upload waits this long for the same lock (sc
74/// `qwen38_engine::LOAD_LOCK_WAIT`, "other jobs' chip runs take minutes");
75/// one server request held it 108 s median and 222 s at most over 323
76/// requests on 2026-10-19 (serve.log), so the bound covers many turns.
77pub const DEFAULT_GPU_WAIT: Duration = Duration::from_secs(30 * 60);
78
79/// MemAvailable (MB) a gb10 gate needs before it starts, checked with the GPU
80/// locks held. Measured on the Spark, 2026-10-20 (omega rx_r14_recovery_silicon
81/// under the GB10 lock, MemAvailable sampled every 0.5 s): baseline drift
82/// 0.8 GB, drop to 1.6 GB below the pre-run baseline during the run. The
83/// omega silicon gates that failed NO_MEMORY at channel create had 3-4 GB
84/// free, so the floor sits about twice that failure point. Replace it with
85/// per-gate peaks from the `volatile.gpu_wait` fields as they accrue.
86pub const DEFAULT_GPU_MEM_MB: u64 = 6 * 1024;
87
88/// How long a gb10 gate waits, holding the GPU locks, for `DEFAULT_GPU_MEM_MB`
89/// to show as free. Short on purpose: a 27B server holds its weights for hours,
90/// and a memory-short gate is NOT_RUN `gpu_mem` (retryable), not FAIL.
91pub const DEFAULT_GPU_MEM_WAIT: Duration = Duration::from_secs(15 * 60);
92
93/// Poll interval of the memory wait.
94const GPU_MEM_POLL: Duration = Duration::from_secs(5);
95
96/// The memory reading (procfs).
97pub const DEFAULT_MEMINFO: &str = "/proc/meminfo";
98
99/// What a gb10 gate does when another holder has a GPU lock.
100#[derive(Debug, Clone, Copy, PartialEq, Eq)]
101pub enum GpuWait {
102 /// Refuse at once (`--gpu-wait 0`, and the scratch configs of tests).
103 Refuse,
104 /// Wait in the kernel's queue up to this long, then refuse.
105 Bounded(Duration),
106 /// `--wait-gpu`: wait as long as it takes.
107 Forever,
108}
109
110impl GpuWait {
111 /// The receipt's `volatile.gpu_wait.mode`.
112 pub fn mode(self) -> &'static str {
113 match self {
114 GpuWait::Refuse => "refuse",
115 GpuWait::Bounded(_) => "bounded",
116 GpuWait::Forever => "forever",
117 }
118 }
119
120 /// The bound in ms (`Refuse` is 0, `Forever` has none).
121 pub fn bound_ms(self) -> Option<u64> {
122 match self {
123 GpuWait::Refuse => Some(0),
124 GpuWait::Bounded(d) => Some(d.as_millis() as u64),
125 GpuWait::Forever => None,
126 }
127 }
128}
129
130/// Set to `1` in a gb10 gate's environment while the runner holds the GPU
131/// locks for it (ADR 0033: gb10 is serialized by the trusted side). A gate
132/// script that also takes `/tmp/aien-gb10.lock` by hand must skip that when
133/// it sees this: under `--sandbox user` it cannot open the worker's lock file
134/// (exit 66, `flock: Permission denied`), and as the same user it would
135/// block forever behind the runner's own exclusive lock.
136pub const GPU_LOCK_HELD_MARKER: &str = "AIEN_GB10_LOCK_HELD";
137
138pub(crate) fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
139 m.lock().unwrap_or_else(|e| e.into_inner())
140}
141
142/// A counting semaphore.
143#[derive(Debug)]
144pub struct Semaphore {
145 size: usize,
146 free: Mutex<usize>,
147 cv: Condvar,
148}
149
150impl Semaphore {
151 /// A semaphore with `size` slots (at least 1).
152 pub fn new(size: usize) -> Semaphore {
153 let size = size.max(1);
154 Semaphore {
155 size,
156 free: Mutex::new(size),
157 cv: Condvar::new(),
158 }
159 }
160
161 pub fn size(&self) -> usize {
162 self.size
163 }
164
165 pub fn available(&self) -> usize {
166 *lock(&self.free)
167 }
168
169 /// Block until a slot is free.
170 pub fn acquire(&self) -> Permit<'_> {
171 let mut free = lock(&self.free);
172 while *free == 0 {
173 free = self.cv.wait(free).unwrap_or_else(|e| e.into_inner());
174 }
175 *free -= 1;
176 Permit { sem: self }
177 }
178
179 /// Take a slot if one is free right now.
180 pub fn try_acquire(&self) -> Option<Permit<'_>> {
181 let mut free = lock(&self.free);
182 if *free == 0 {
183 return None;
184 }
185 *free -= 1;
186 Some(Permit { sem: self })
187 }
188}
189
190/// One held slot. Dropping it frees the slot and wakes one waiter.
191#[derive(Debug)]
192pub struct Permit<'a> {
193 sem: &'a Semaphore,
194}
195
196impl Drop for Permit<'_> {
197 fn drop(&mut self) {
198 let mut free = lock(&self.sem.free);
199 *free += 1;
200 self.sem.cv.notify_one();
201 }
202}
203
204/// The pool a job is scheduled in. The derived `Ord` is the fixed acquire
205/// order: scarcest first.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
207pub enum Pool {
208 Gb10,
209 Qemu,
210 Host,
211}
212
213impl Pool {
214 pub fn name(self) -> &'static str {
215 match self {
216 Pool::Gb10 => "gb10",
217 Pool::Qemu => "qemu",
218 Pool::Host => "host",
219 }
220 }
221
222 pub fn from_name(s: &str) -> Option<Pool> {
223 match s {
224 "gb10" => Some(Pool::Gb10),
225 "qemu" => Some(Pool::Qemu),
226 "host" => Some(Pool::Host),
227 _ => None,
228 }
229 }
230}
231
232/// Sizes of the two resizable pools. The gb10 pool is fixed at 1.
233#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234pub struct PoolSizes {
235 pub host: usize,
236 pub qemu: usize,
237}
238
239/// `--jobs host=N,qemu=M`: only the pools that were named.
240#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
241pub struct JobsSpec {
242 pub host: Option<usize>,
243 pub qemu: Option<usize>,
244}
245
246impl PoolSizes {
247 /// ADR defaults for a machine with `cpus` CPUs: host = cpus, qemu =
248 /// min(4, host / 2), never below 1.
249 pub fn defaults_for(cpus: usize) -> PoolSizes {
250 let host = cpus.max(1);
251 PoolSizes {
252 host,
253 qemu: (host / 2).clamp(1, 4),
254 }
255 }
256
257 pub fn detect() -> PoolSizes {
258 let cpus = std::thread::available_parallelism()
259 .map(|n| n.get())
260 .unwrap_or(1);
261 PoolSizes::defaults_for(cpus)
262 }
263
264 pub fn with(self, jobs: JobsSpec) -> PoolSizes {
265 PoolSizes {
266 host: jobs.host.unwrap_or(self.host),
267 qemu: jobs.qemu.unwrap_or(self.qemu),
268 }
269 }
270}
271
272/// Parse `host=N,qemu=M` (either part may be left out; N, M at least 1).
273pub fn parse_jobs(spec: &str) -> Result<JobsSpec, String> {
274 let mut out = JobsSpec::default();
275 for part in spec.split(',') {
276 let (name, value) = part
277 .split_once('=')
278 .ok_or_else(|| format!("--jobs entry {part:?} must look like host=N or qemu=M"))?;
279 let n: usize = value
280 .parse()
281 .map_err(|_| format!("--jobs {name} needs a whole number, got {value:?}"))?;
282 if n == 0 {
283 return Err(format!("--jobs {name} must be at least 1"));
284 }
285 match name {
286 "host" => out.host = Some(n),
287 "qemu" => out.qemu = Some(n),
288 "gb10" => return Err("the gb10 pool is fixed at 1".to_string()),
289 other => return Err(format!("unknown pool {other:?} in --jobs")),
290 }
291 }
292 Ok(out)
293}
294
295/// The three semaphores of one runner process.
296#[derive(Debug)]
297pub struct Pools {
298 host: Semaphore,
299 qemu: Semaphore,
300 gb10: Semaphore,
301}
302
303impl Pools {
304 pub fn new(sizes: PoolSizes) -> Pools {
305 Pools {
306 host: Semaphore::new(sizes.host),
307 qemu: Semaphore::new(sizes.qemu),
308 gb10: Semaphore::new(1),
309 }
310 }
311
312 pub fn semaphore(&self, pool: Pool) -> &Semaphore {
313 match pool {
314 Pool::Host => &self.host,
315 Pool::Qemu => &self.qemu,
316 Pool::Gb10 => &self.gb10,
317 }
318 }
319
320 pub fn acquire(&self, pool: Pool) -> Permit<'_> {
321 self.semaphore(pool).acquire()
322 }
323
324 pub fn try_acquire(&self, pool: Pool) -> Option<Permit<'_>> {
325 self.semaphore(pool).try_acquire()
326 }
327
328 /// Take several pools in the fixed order (duplicates collapse), so two
329 /// callers asking for the same set can never deadlock each other.
330 pub fn acquire_many(&self, pools: &[Pool]) -> Vec<Permit<'_>> {
331 let mut order: Vec<Pool> = pools.to_vec();
332 order.sort();
333 order.dedup();
334 order.into_iter().map(|p| self.acquire(p)).collect()
335 }
336}
337
338/// Which special hardware this machine has. A heuristic, recorded in the
339/// receipt's `machine` object (UNVERIFIED: `/dev/nvidiactl` for the GB10).
340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341pub struct Hardware {
342 pub gb10_present: bool,
343 pub qemu_available: bool,
344}
345
346fn which(name: &str) -> bool {
347 match std::env::var_os("PATH") {
348 Some(p) => std::env::split_paths(&p).any(|d| d.join(name).is_file()),
349 None => false,
350 }
351}
352
353impl Hardware {
354 pub fn detect() -> Hardware {
355 Hardware {
356 gb10_present: Path::new("/dev/nvidiactl").exists(),
357 qemu_available: which("qemu-system-aarch64") || which("qemu-system-x86_64"),
358 }
359 }
360}
361
362/// Where the GPU lock files and the refusal checks live. Passed in explicitly
363/// (never read from the environment by the lock code), so a test can point
364/// every path at a scratch directory and never touch the real locks.
365#[derive(Debug, Clone)]
366pub struct GpuConfig {
367 /// `/tmp/aien-gb10.lock`, taken first.
368 pub lock_path: PathBuf,
369 /// aien-proof's `slots/gpu.lock`, taken second, only when its board
370 /// directory exists (ADR Decision 6, stopgap until the locks are unified).
371 pub proof_lock_path: Option<PathBuf>,
372 /// `~/workspace/.spark-quiet`; None when HOME is unknown.
373 pub quiet_flag: Option<PathBuf>,
374 /// Where to look for an `est_load` process (`/proc`).
375 pub proc_dir: PathBuf,
376 /// How long to wait for a held lock (`--gpu-wait`, `--wait-gpu`).
377 pub wait: GpuWait,
378 /// The memory reading (`/proc/meminfo`, MemAvailable); a file so a test
379 /// can fake it.
380 pub meminfo: PathBuf,
381 /// MB of MemAvailable a gate needs once it holds the locks; 0 = not checked.
382 pub mem_need_mb: u64,
383 /// How long to wait, holding the locks, for `mem_need_mb` to show as free.
384 pub mem_wait: Duration,
385}
386
387impl GpuConfig {
388 /// The real machine: default lock, HOME-relative quiet flag, aien-proof
389 /// board from `AIEN_PROOF_DIR` or `~/.local/state/aien-proof`.
390 pub fn detect() -> GpuConfig {
391 let home = std::env::var_os("HOME").map(PathBuf::from);
392 let board = match std::env::var_os("AIEN_PROOF_DIR") {
393 Some(d) => Some(PathBuf::from(d)),
394 None => home.as_ref().map(|h| h.join(".local/state/aien-proof")),
395 };
396 GpuConfig {
397 lock_path: PathBuf::from(DEFAULT_GPU_LOCK),
398 proof_lock_path: board
399 .filter(|b| b.is_dir())
400 .map(|b| b.join("slots/gpu.lock")),
401 quiet_flag: home.map(|h| h.join("workspace/.spark-quiet")),
402 proc_dir: PathBuf::from("/proc"),
403 wait: GpuWait::Bounded(DEFAULT_GPU_WAIT),
404 meminfo: PathBuf::from(DEFAULT_MEMINFO),
405 mem_need_mb: DEFAULT_GPU_MEM_MB,
406 mem_wait: DEFAULT_GPU_MEM_WAIT,
407 }
408 }
409
410 /// Every path inside `dir` (a scratch directory): own lock, own quiet
411 /// flag, no aien-proof lock, no `est_load`; a held lock is refused at once.
412 pub fn rooted_at(dir: &Path) -> GpuConfig {
413 GpuConfig {
414 lock_path: dir.join("gb10.lock"),
415 proof_lock_path: None,
416 quiet_flag: Some(dir.join("quiet-flag")),
417 proc_dir: dir.join("proc"),
418 wait: GpuWait::Refuse,
419 meminfo: dir.join("meminfo"),
420 // Not checked unless a test asks: the tests of the lock protocol
421 // do not depend on the machine's memory.
422 mem_need_mb: 0,
423 mem_wait: Duration::ZERO,
424 }
425 }
426}
427
428/// Why a GPU job was refused. `reason()` is the stable code for the receipt.
429#[derive(Debug, Clone, PartialEq, Eq)]
430pub enum GpuRefusal {
431 /// The quiet flag exists; carries its text (CR-028).
432 QuietFlag(String),
433 /// An `est_load` process is running (CR-029).
434 EstLoad,
435 /// A lock file could not be opened (CR-033, `gpu_open`).
436 LockOpen(String),
437 /// Another holder has `/tmp/aien-gb10.lock` (CR-033, `gpu_lock`).
438 LockHeld(PathBuf),
439 /// Another holder has aien-proof's `slots/gpu.lock` (`gpu_lock_proof`).
440 ProofLockHeld(PathBuf),
441 /// The locks were taken but MemAvailable stayed below what the gate needs
442 /// (`gpu_mem`, retryable: nothing ran). `None` = the reading was unreadable.
443 MemShort { free_mb: Option<u64>, need_mb: u64 },
444}
445
446impl GpuRefusal {
447 pub fn reason(&self) -> &'static str {
448 match self {
449 GpuRefusal::QuietFlag(_) => "quiet_flag",
450 GpuRefusal::EstLoad => "est_load",
451 GpuRefusal::LockOpen(_) => "gpu_open",
452 GpuRefusal::LockHeld(_) => "gpu_lock",
453 GpuRefusal::ProofLockHeld(_) => "gpu_lock_proof",
454 GpuRefusal::MemShort { .. } => "gpu_mem",
455 }
456 }
457}
458
459impl fmt::Display for GpuRefusal {
460 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
461 match self {
462 GpuRefusal::QuietFlag(t) => write!(f, "quiet flag is up: {t}"),
463 GpuRefusal::EstLoad => write!(f, "an est_load process is running"),
464 GpuRefusal::LockOpen(m) => write!(f, "cannot open GPU lock: {m}"),
465 GpuRefusal::LockHeld(p) => write!(f, "GPU lock {} is held", p.display()),
466 GpuRefusal::ProofLockHeld(p) => {
467 write!(f, "aien-proof GPU lock {} is held", p.display())
468 }
469 GpuRefusal::MemShort { free_mb, need_mb } => match free_mb {
470 Some(free) => write!(
471 f,
472 "free memory {free} MB, the gate needs {need_mb} MB (MemAvailable)"
473 ),
474 None => write!(
475 f,
476 "free memory unreadable, the gate needs {need_mb} MB (MemAvailable)"
477 ),
478 },
479 }
480 }
481}
482
483/// MemAvailable in MB from a meminfo file; None when it cannot be read.
484pub fn mem_available_mb(meminfo: &Path) -> Option<u64> {
485 let text = fs::read_to_string(meminfo).ok()?;
486 let line = text.lines().find(|l| l.starts_with("MemAvailable:"))?;
487 let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
488 Some(kib / 1024)
489}
490
491/// Wait until MemAvailable reaches `need_mb`, polling every `GPU_MEM_POLL`
492/// and giving up after `bound` (0 = one reading). Ok(free) when it did;
493/// Err(last reading) when it did not.
494pub fn wait_for_memory(meminfo: &Path, need_mb: u64, bound: Duration) -> Result<u64, Option<u64>> {
495 let t0 = Instant::now();
496 loop {
497 let free = mem_available_mb(meminfo);
498 if let Some(f) = free {
499 if f >= need_mb {
500 return Ok(f);
501 }
502 }
503 let left = bound.saturating_sub(t0.elapsed());
504 if left.is_zero() {
505 return Err(free);
506 }
507 std::thread::sleep(GPU_MEM_POLL.min(left));
508 }
509}
510
511/// True if any process under `proc_dir` has a name containing `est_load`
512/// (what `pgrep est_load` matches, CR-029).
513pub fn est_load_running(proc_dir: &Path) -> bool {
514 let rd = match fs::read_dir(proc_dir) {
515 Ok(r) => r,
516 Err(_) => return false,
517 };
518 for e in rd.flatten() {
519 let name = e.file_name();
520 let name = name.to_string_lossy();
521 if name.is_empty() || !name.bytes().all(|b| b.is_ascii_digit()) {
522 continue;
523 }
524 if let Ok(comm) = fs::read_to_string(e.path().join("comm")) {
525 if comm.trim().contains("est_load") {
526 return true;
527 }
528 }
529 }
530 false
531}
532
533/// The cheap refusals that need no lock: quiet flag, then `est_load`. The
534/// flag is never created, changed or removed here (CR-050).
535pub fn preflight(cfg: &GpuConfig) -> Option<GpuRefusal> {
536 if let Some(flag) = &cfg.quiet_flag {
537 if fs::symlink_metadata(flag).is_ok() {
538 let text = fs::read_to_string(flag).unwrap_or_default();
539 return Some(GpuRefusal::QuietFlag(text.trim().to_string()));
540 }
541 }
542 if est_load_running(&cfg.proc_dir) {
543 return Some(GpuRefusal::EstLoad);
544 }
545 None
546}
547
548/// Descriptors holding the GPU locks. Drop releases them, under the spawn
549/// gate (see the module comment, "Fork window").
550#[derive(Debug)]
551pub struct GpuGuard {
552 files: Vec<File>,
553}
554
555impl Drop for GpuGuard {
556 fn drop(&mut self) {
557 let _gate = crate::process::spawn_gate();
558 self.files.clear();
559 }
560}
561
562/// The default directory of the target-dir lock files for a bare `run`
563/// without a worker state dir (the worker uses `<state>/locks/target`).
564pub const DEFAULT_TARGET_LOCK_DIR: &str = "/tmp/aien-test-target-locks";
565
566/// The lock file for one cargo target dir: `<lock_dir>/<sanitised>.lock`,
567/// where every character of the target dir path outside `[A-Za-z0-9._-]`
568/// becomes `_`. The path is taken as given (no canonicalising), so every
569/// holder that names the same target dir names the same lock file. Not
570/// inside the target dir itself: under the user sandbox that belongs to
571/// `aien-run`, and the lock is the worker's.
572pub fn target_lock_path(lock_dir: &Path, target_dir: &Path) -> PathBuf {
573 let name: String = target_dir
574 .display()
575 .to_string()
576 .chars()
577 .map(|c| {
578 if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
579 c
580 } else {
581 '_'
582 }
583 })
584 .collect();
585 lock_dir.join(format!("{name}.lock"))
586}
587
588/// Exclusive hold of one cargo target dir (`flock(LOCK_EX)`, waited for).
589/// Held by the runner for a whole cargo gate, build and run, so two gates of
590/// one head never build in, or relink a binary under, the same target dir
591/// at once (sc fix/521: SC-AGENT-PREFLIGHT relinked a test binary while
592/// SC-TEST was executing it). Dropping it closes the descriptor under the
593/// spawn gate, like `GpuGuard`.
594#[derive(Debug)]
595pub struct TargetLock {
596 file: Option<File>,
597 path: PathBuf,
598}
599
600impl TargetLock {
601 pub fn path(&self) -> &Path {
602 &self.path
603 }
604}
605
606impl Drop for TargetLock {
607 fn drop(&mut self) {
608 let _gate = crate::process::spawn_gate();
609 self.file.take();
610 }
611}
612
613/// The same exclusive lock without waiting: None when someone else holds it.
614pub fn try_lock(path: &Path) -> io::Result<Option<TargetLock>> {
615 let file = open_lock(path)?;
616 Ok(flock_exclusive(&file, false)?.then(|| TargetLock {
617 file: Some(file),
618 path: path.to_path_buf(),
619 }))
620}
621
622/// A counting semaphore shared by every head of one batch (`worker
623/// --batch`), with one rule `Semaphore` lacks: while a priority waiter (a
624/// gate other heads of the batch share) is queued, no plain waiter gets a
625/// slot, so the shared gates of the whole batch run first and the per-head
626/// ones after. Taken after the in-process pool slot and before the target-dir
627/// lock (order (1b) in the module comment); a holder never waits for a pool
628/// slot or a cache entry lock.
629pub struct Budget {
630 size: usize,
631 state: Mutex<(usize, usize)>,
632 cv: Condvar,
633}
634
635/// One slot of a `Budget`, given back when dropped.
636pub struct BudgetPermit<'a> {
637 budget: &'a Budget,
638}
639
640impl Budget {
641 pub fn new(size: usize) -> Budget {
642 let size = size.max(1);
643 Budget {
644 size,
645 state: Mutex::new((size, 0)),
646 cv: Condvar::new(),
647 }
648 }
649
650 pub fn size(&self) -> usize {
651 self.size
652 }
653
654 /// Wait for a slot. `priority`: this gate is shared with other heads.
655 pub fn acquire(&self, priority: bool) -> BudgetPermit<'_> {
656 let mut st = lock(&self.state);
657 if priority {
658 st.1 += 1;
659 }
660 while st.0 == 0 || (!priority && st.1 > 0) {
661 st = self.cv.wait(st).unwrap_or_else(|e| e.into_inner());
662 }
663 st.0 -= 1;
664 if priority {
665 st.1 -= 1;
666 }
667 drop(st);
668 // A plain waiter blocked only by the priority count may go now.
669 self.cv.notify_all();
670 BudgetPermit { budget: self }
671 }
672}
673
674impl Drop for BudgetPermit<'_> {
675 fn drop(&mut self) {
676 lock(&self.budget.state).0 += 1;
677 self.budget.cv.notify_all();
678 }
679}
680
681/// What the heads of one batch share: the host budget (default half the
682/// CPUs) and one gb10 slot, so two heads' GPU gates queue here, one at a
683/// time, instead of spending their bounded wait for `/tmp/aien-gb10.lock` on
684/// each other.
685pub struct BatchShare {
686 pub host: Budget,
687 pub gb10: Budget,
688}
689
690impl BatchShare {
691 pub fn new(host: usize) -> BatchShare {
692 BatchShare {
693 host: Budget::new(host),
694 gb10: Budget::new(1),
695 }
696 }
697
698 /// The default host budget: half the CPUs, at least one.
699 pub fn default_host() -> usize {
700 std::thread::available_parallelism().map_or(1, |n| (n.get() / 2).max(1))
701 }
702}
703
704/// Take the target-dir lock at `path` (see `target_lock_path`), waiting for
705/// the holder to finish. The file is created if absent and never deleted.
706pub fn lock_target_dir(path: &Path) -> io::Result<TargetLock> {
707 let file = open_lock(path)?;
708 flock_exclusive(&file, true)?;
709 Ok(TargetLock {
710 file: Some(file),
711 path: path.to_path_buf(),
712 })
713}
714
715fn open_lock(path: &Path) -> io::Result<File> {
716 if let Some(parent) = path.parent() {
717 if !parent.as_os_str().is_empty() {
718 fs::create_dir_all(parent)?;
719 }
720 }
721 OpenOptions::new().create(true).append(true).open(path)
722}
723
724/// `flock(LOCK_EX)`: Ok(true) when taken, Ok(false) when held by someone else
725/// and `wait` is off.
726pub(crate) fn flock_exclusive(file: &File, wait: bool) -> io::Result<bool> {
727 let op = if wait {
728 libc::LOCK_EX
729 } else {
730 libc::LOCK_EX | libc::LOCK_NB
731 };
732 loop {
733 // SAFETY: flock on a descriptor that `file` keeps open for this call.
734 let rc = unsafe { libc::flock(file.as_raw_fd(), op) };
735 if rc == 0 {
736 return Ok(true);
737 }
738 let err = io::Error::last_os_error();
739 match err.raw_os_error() {
740 Some(libc::EINTR) => {}
741 Some(libc::EWOULDBLOCK) => return Ok(false),
742 _ => return Err(err),
743 }
744 }
745}
746
747/// Wait for `file`'s lock in the kernel's queue until `deadline`. The
748/// blocking `flock` runs on a helper thread; after the deadline the helper is
749/// abandoned and drops the lock (under the spawn gate) the moment the kernel
750/// grants it, so a refused gate never keeps the GPU. An abandoned helper
751/// stays queued until the holder lets go: one per refused gate at most.
752fn flock_queued(file: File, deadline: Instant) -> io::Result<Option<File>> {
753 let (tx, rx) = mpsc::channel();
754 let gave_up = Arc::new(AtomicBool::new(false));
755 let gave_up_t = Arc::clone(&gave_up);
756 std::thread::spawn(move || {
757 let r = flock_exclusive(&file, true).map(|_| file);
758 let lost = |r: io::Result<File>| {
759 if let Ok(f) = r {
760 let _gate = crate::process::spawn_gate();
761 drop(f);
762 }
763 };
764 if gave_up_t.load(Ordering::SeqCst) {
765 return lost(r);
766 }
767 if let Err(mpsc::SendError(r)) = tx.send(r) {
768 lost(r);
769 }
770 });
771 match rx.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
772 Ok(r) => r.map(Some),
773 Err(_) => {
774 gave_up.store(true, Ordering::SeqCst);
775 // The helper may have sent just before the flag: take and drop it.
776 if let Ok(Ok(f)) = rx.try_recv() {
777 let _gate = crate::process::spawn_gate();
778 drop(f);
779 }
780 Ok(None)
781 }
782 }
783}
784
785/// Take the lock at `path`: at once if it is free, else as `wait` says, with
786/// `deadline` the end of a bounded wait. Ok(None) = still held.
787fn take_lock(
788 path: &Path,
789 wait: GpuWait,
790 deadline: Option<Instant>,
791) -> Result<Option<File>, GpuRefusal> {
792 let open_err = |e: io::Error| GpuRefusal::LockOpen(format!("{}: {e}", path.display()));
793 let file = open_lock(path).map_err(open_err)?;
794 if flock_exclusive(&file, false).map_err(open_err)? {
795 return Ok(Some(file));
796 }
797 match (wait, deadline) {
798 (GpuWait::Refuse, _) => Ok(None),
799 (GpuWait::Forever, _) => flock_exclusive(&file, true)
800 .map(|_| Some(file))
801 .map_err(open_err),
802 (GpuWait::Bounded(_), Some(d)) => flock_queued(file, d).map_err(open_err),
803 (GpuWait::Bounded(_), None) => Ok(None),
804 }
805}
806
807/// One `acquire_gpu_timed` call: the result and how long it waited for the
808/// locks (0 when they were free or a preflight refusal came first).
809#[derive(Debug)]
810pub struct GpuAttempt {
811 pub result: Result<GpuGuard, GpuRefusal>,
812 pub waited: Duration,
813 /// MemAvailable (MB) read after the locks were taken; None when the
814 /// memory check is off or the locks were refused first.
815 pub mem_free_mb: Option<u64>,
816 /// `GpuConfig::mem_need_mb` at the time of the attempt (0 = not checked).
817 pub mem_need_mb: u64,
818}
819
820/// The GPU job protocol up to the point of running: refusals first, then the
821/// locks in the fixed order. Call it after taking the in-process gb10 slot.
822pub fn acquire_gpu(cfg: &GpuConfig) -> Result<GpuGuard, GpuRefusal> {
823 acquire_gpu_timed(cfg).result
824}
825
826/// `acquire_gpu`, also reporting the wait. One bound covers both locks. With
827/// a memory need set, the memory is checked once the locks are held; a short
828/// reading waits up to `mem_wait` for it, then refuses as `gpu_mem` and gives
829/// the locks back (the guard drops here, through the spawn gate).
830pub fn acquire_gpu_timed(cfg: &GpuConfig) -> GpuAttempt {
831 let t0 = Instant::now();
832 let (result, mem_free_mb) = match acquire_locks(cfg, t0) {
833 Err(r) => (Err(r), None),
834 Ok(guard) if cfg.mem_need_mb == 0 => (Ok(guard), None),
835 Ok(guard) => match wait_for_memory(&cfg.meminfo, cfg.mem_need_mb, cfg.mem_wait) {
836 Ok(free) => (Ok(guard), Some(free)),
837 Err(free) => {
838 drop(guard);
839 (
840 Err(GpuRefusal::MemShort {
841 free_mb: free,
842 need_mb: cfg.mem_need_mb,
843 }),
844 free,
845 )
846 }
847 },
848 };
849 GpuAttempt {
850 result,
851 waited: t0.elapsed(),
852 mem_free_mb,
853 mem_need_mb: cfg.mem_need_mb,
854 }
855}
856
857fn acquire_locks(cfg: &GpuConfig, t0: Instant) -> Result<GpuGuard, GpuRefusal> {
858 if let Some(r) = preflight(cfg) {
859 return Err(r);
860 }
861 let deadline = match cfg.wait {
862 GpuWait::Bounded(d) => t0.checked_add(d),
863 _ => None,
864 };
865 let primary = match take_lock(&cfg.lock_path, cfg.wait, deadline)? {
866 Some(f) => f,
867 None => return Err(GpuRefusal::LockHeld(cfg.lock_path.clone())),
868 };
869 let mut guard = GpuGuard {
870 files: vec![primary],
871 };
872 if let Some(p) = &cfg.proof_lock_path {
873 match take_lock(p, cfg.wait, deadline)? {
874 Some(f) => guard.files.push(f),
875 // Returning drops `guard`, so the first lock is not left held,
876 // and it is released through the spawn gate like any other.
877 None => return Err(GpuRefusal::ProofLockHeld(p.clone())),
878 }
879 }
880 Ok(guard)
881}
882
883#[cfg(test)]
884mod tests {
885 use super::*;
886 use crate::testutil::{queued_on, write_file, TempDir};
887 use std::sync::mpsc;
888 use std::thread;
889 use std::time::Duration;
890
891 #[test]
892 fn semaphore_counts_slots() {
893 let s = Semaphore::new(2);
894 assert_eq!((s.size(), s.available()), (2, 2));
895 let a = s.try_acquire();
896 let b = s.try_acquire();
897 assert!(a.is_some() && b.is_some());
898 assert_eq!(s.available(), 0);
899 assert!(s.try_acquire().is_none());
900 drop(a);
901 assert_eq!(s.available(), 1);
902 assert!(s.try_acquire().is_some());
903 }
904
905 #[test]
906 fn zero_size_is_one_slot() {
907 assert_eq!(Semaphore::new(0).size(), 1);
908 }
909
910 #[test]
911 fn acquire_waits_for_a_release() {
912 let sem = Semaphore::new(1);
913 let held = sem.acquire();
914 let (tx, rx) = mpsc::channel();
915 thread::scope(|s| {
916 s.spawn(|| {
917 let _p = sem.acquire();
918 tx.send(()).unwrap();
919 });
920 thread::sleep(Duration::from_millis(150));
921 assert!(rx.try_recv().is_err(), "the second acquire must wait");
922 drop(held);
923 rx.recv_timeout(Duration::from_secs(20))
924 .expect("the waiter gets the slot after the release");
925 });
926 }
927
928 #[test]
929 fn target_lock_path_is_one_file_per_target_dir_under_the_lock_dir() {
930 let p = target_lock_path(
931 Path::new("/state/locks/target"),
932 Path::new("/var/lib/aien-run/target/aien-sovereign-core/pr"),
933 );
934 assert_eq!(
935 p,
936 PathBuf::from(
937 "/state/locks/target/_var_lib_aien-run_target_aien-sovereign-core_pr.lock"
938 )
939 );
940 let main = target_lock_path(Path::new("/l"), Path::new("/t/main"));
941 let pr = target_lock_path(Path::new("/l"), Path::new("/t/pr"));
942 assert_ne!(main, pr, "main and pr are different target dirs");
943 }
944
945 /// Two holders in one process (two `open`s, two file descriptions) and
946 /// so two threads of the runner exclude each other; the second waits
947 /// until the first is dropped.
948 #[test]
949 fn target_lock_is_exclusive_and_waited_for() {
950 let dir = TempDir::new("tlock");
951 let path = target_lock_path(dir.path(), Path::new("/t/pr"));
952 let held = lock_target_dir(&path).unwrap();
953 assert!(held.path().exists());
954 let (tx, rx) = mpsc::channel();
955 thread::scope(|s| {
956 s.spawn(|| {
957 let _second = lock_target_dir(&path).unwrap();
958 tx.send(()).unwrap();
959 });
960 thread::sleep(Duration::from_millis(200));
961 assert!(rx.try_recv().is_err(), "the second holder must wait");
962 drop(held);
963 rx.recv_timeout(Duration::from_secs(20))
964 .expect("the waiter takes the lock after the release");
965 });
966 }
967
968 #[test]
969 fn gb10_pool_is_serialized() {
970 let p = Pools::new(PoolSizes { host: 4, qemu: 2 });
971 let first = p.try_acquire(Pool::Gb10);
972 assert!(first.is_some());
973 assert!(p.try_acquire(Pool::Gb10).is_none(), "gb10 has one slot");
974 assert_eq!(p.semaphore(Pool::Gb10).size(), 1);
975 assert_eq!(p.semaphore(Pool::Host).size(), 4);
976 assert_eq!(p.semaphore(Pool::Qemu).size(), 2);
977 drop(first);
978 assert!(p.try_acquire(Pool::Gb10).is_some());
979 }
980
981 #[test]
982 fn pool_names_round_trip() {
983 for pool in [Pool::Gb10, Pool::Qemu, Pool::Host] {
984 assert_eq!(Pool::from_name(pool.name()), Some(pool));
985 }
986 assert_eq!(Pool::from_name("gpu"), None);
987 assert!(Pool::Gb10 < Pool::Qemu && Pool::Qemu < Pool::Host);
988 }
989
990 #[test]
991 fn default_sizes_follow_the_adr() {
992 assert_eq!(PoolSizes::defaults_for(8), PoolSizes { host: 8, qemu: 4 });
993 assert_eq!(PoolSizes::defaults_for(20), PoolSizes { host: 20, qemu: 4 });
994 assert_eq!(PoolSizes::defaults_for(4), PoolSizes { host: 4, qemu: 2 });
995 assert_eq!(PoolSizes::defaults_for(1), PoolSizes { host: 1, qemu: 1 });
996 assert_eq!(PoolSizes::defaults_for(0), PoolSizes { host: 1, qemu: 1 });
997 assert!(PoolSizes::detect().host >= 1);
998 }
999
1000 #[test]
1001 fn jobs_option_parses_and_overrides() {
1002 let j = parse_jobs("host=3,qemu=2").unwrap();
1003 assert_eq!(
1004 j,
1005 JobsSpec {
1006 host: Some(3),
1007 qemu: Some(2)
1008 }
1009 );
1010 let j = parse_jobs("qemu=5").unwrap();
1011 assert_eq!(j.host, None);
1012 let base = PoolSizes { host: 8, qemu: 4 };
1013 assert_eq!(base.with(j), PoolSizes { host: 8, qemu: 5 });
1014 for bad in [
1015 "", "host", "host=", "host=0", "host=x", "gb10=2", "disk=1", "host=1,",
1016 ] {
1017 assert!(parse_jobs(bad).is_err(), "{bad:?} must be rejected");
1018 }
1019 }
1020
1021 #[test]
1022 fn acquire_many_uses_one_order() {
1023 let p = Pools::new(PoolSizes { host: 1, qemu: 1 });
1024 // Opposite orders and repeats: the fixed order keeps them deadlock free.
1025 thread::scope(|s| {
1026 for flip in [false, true] {
1027 let p = &p;
1028 s.spawn(move || {
1029 for _ in 0..100 {
1030 let want = if flip {
1031 [Pool::Host, Pool::Qemu, Pool::Gb10, Pool::Host]
1032 } else {
1033 [Pool::Gb10, Pool::Qemu, Pool::Host, Pool::Gb10]
1034 };
1035 let permits = p.acquire_many(&want);
1036 assert_eq!(permits.len(), 3);
1037 }
1038 });
1039 }
1040 });
1041 for pool in [Pool::Gb10, Pool::Qemu, Pool::Host] {
1042 assert_eq!(p.semaphore(pool).available(), 1, "{pool:?} slot leaked");
1043 }
1044 }
1045
1046 #[test]
1047 fn gpu_lock_is_exclusive_and_released_on_drop() {
1048 let d = TempDir::new("gpu");
1049 let cfg = GpuConfig::rooted_at(d.path());
1050 let g = acquire_gpu(&cfg).expect("free lock");
1051 match acquire_gpu(&cfg) {
1052 Err(GpuRefusal::LockHeld(p)) => assert_eq!(p, cfg.lock_path),
1053 other => panic!("expected LockHeld, got {other:?}"),
1054 }
1055 drop(g);
1056 let again = acquire_gpu(&cfg);
1057 assert!(again.is_ok(), "released by drop: {again:?}");
1058 assert!(cfg.lock_path.exists(), "the lock file is never deleted");
1059 }
1060
1061 /// Regression for the forge flake at e703501c: a child that is between
1062 /// fork and exec holds a copy of the lock's open file description, so the
1063 /// lock looked held after the guard was dropped. The child below stays in
1064 /// that window for 150 ms (its `pre_exec` hook sleeps), the guard is
1065 /// dropped meanwhile, and the next acquire must succeed. The drop waits for
1066 /// the spawn to finish (the spawn gate), so this passes whatever the
1067 /// scheduling; without the gate it fails because the child still holds the
1068 /// lock when the re-acquire runs.
1069 #[test]
1070 fn gpu_lock_release_waits_for_a_child_between_fork_and_exec() {
1071 use std::os::unix::process::CommandExt;
1072 use std::process::Command;
1073
1074 let d = TempDir::new("gpu");
1075 let cfg = GpuConfig::rooted_at(d.path());
1076 let mut fds: [libc::c_int; 2] = [0, 0];
1077 // SAFETY: `fds` has room for the two descriptors pipe2 writes.
1078 let rc = unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) };
1079 assert_eq!(rc, 0, "pipe2");
1080 let (ready_r, ready_w) = (fds[0], fds[1]);
1081
1082 for round in 0..3 {
1083 let g = acquire_gpu(&cfg).unwrap_or_else(|e| panic!("round {round}: {e}"));
1084 thread::scope(|s| {
1085 let spawner = s.spawn(move || {
1086 let mut cmd = Command::new("/bin/true");
1087 // SAFETY: the hook runs between fork and exec and only
1088 // calls write(2) and poll(2), which are async-signal-safe;
1089 // it allocates nothing and touches no lock.
1090 unsafe {
1091 cmd.pre_exec(move || {
1092 let byte = [1u8];
1093 libc::write(ready_w, byte.as_ptr().cast(), 1);
1094 // poll with no descriptors is a sleep: 150 ms.
1095 libc::poll(std::ptr::null_mut(), 0, 150);
1096 Ok(())
1097 });
1098 }
1099 let mut child = crate::process::spawn_gated(&mut cmd).expect("spawn");
1100 child.wait().expect("wait")
1101 });
1102 // The child is now alive and between fork and exec.
1103 let mut pfd = libc::pollfd {
1104 fd: ready_r,
1105 events: libc::POLLIN,
1106 revents: 0,
1107 };
1108 // SAFETY: one valid pollfd.
1109 let n = unsafe { libc::poll(&mut pfd, 1, 20_000) };
1110 assert_eq!(n, 1, "round {round}: the child never reached pre_exec");
1111 let mut byte = [0u8; 1];
1112 // SAFETY: reads at most one byte into a one byte buffer.
1113 let got = unsafe { libc::read(ready_r, byte.as_mut_ptr().cast(), 1) };
1114 assert_eq!(got, 1, "round {round}: ready byte");
1115
1116 drop(g);
1117 let again = acquire_gpu(&cfg);
1118 assert!(
1119 again.is_ok(),
1120 "round {round}: a child between fork and exec kept the lock: {again:?}"
1121 );
1122 drop(again);
1123 let status = spawner.join().expect("spawner thread");
1124 assert!(status.success(), "round {round}: /bin/true failed");
1125 });
1126 }
1127 // SAFETY: both descriptors are ours and no thread is using them now.
1128 unsafe {
1129 libc::close(ready_r);
1130 libc::close(ready_w);
1131 }
1132 }
1133
1134 #[test]
1135 fn held_lock_reason_is_gpu_lock() {
1136 let d = TempDir::new("gpu");
1137 let cfg = GpuConfig::rooted_at(d.path());
1138 let _g = acquire_gpu(&cfg).unwrap();
1139 let e = acquire_gpu(&cfg).unwrap_err();
1140 assert_eq!(e.reason(), "gpu_lock");
1141 assert!(e.to_string().contains("is held"));
1142 }
1143
1144 #[test]
1145 fn bounded_wait_takes_the_lock_when_the_holder_lets_go() {
1146 let d = TempDir::new("gpu");
1147 let mut cfg = GpuConfig::rooted_at(d.path());
1148 let held = acquire_gpu(&cfg).unwrap();
1149 cfg.wait = GpuWait::Bounded(Duration::from_secs(20));
1150 // Let go 300 ms after the waiter shows up in the kernel queue.
1151 let lock = cfg.lock_path.clone();
1152 let holder = thread::spawn(move || {
1153 let t0 = Instant::now();
1154 while !queued_on(&lock) && t0.elapsed() < Duration::from_secs(15) {
1155 thread::sleep(Duration::from_millis(5));
1156 }
1157 let seen = queued_on(&lock);
1158 thread::sleep(Duration::from_millis(300));
1159 drop(held);
1160 seen
1161 });
1162 let a = acquire_gpu_timed(&cfg);
1163 assert!(
1164 holder.join().unwrap(),
1165 "the waiter never queued in the kernel"
1166 );
1167 assert!(a.result.is_ok(), "{:?}", a.result);
1168 assert!(
1169 (Duration::from_millis(250)..Duration::from_secs(20)).contains(&a.waited),
1170 "waited {:?}",
1171 a.waited
1172 );
1173 }
1174
1175 #[test]
1176 fn bounded_wait_gives_up_and_the_abandoned_waiter_hands_the_lock_back() {
1177 let d = TempDir::new("gpu");
1178 let mut cfg = GpuConfig::rooted_at(d.path());
1179 let held = acquire_gpu(&cfg).unwrap();
1180 cfg.wait = GpuWait::Bounded(Duration::from_millis(300));
1181 let a = acquire_gpu_timed(&cfg);
1182 assert_eq!(a.result.unwrap_err().reason(), "gpu_lock");
1183 assert!(a.waited >= Duration::from_millis(300), "{:?}", a.waited);
1184 assert!(a.waited < Duration::from_secs(10), "{:?}", a.waited);
1185 drop(held);
1186 // The helper still queued in the kernel gets the lock and drops it at
1187 // once; a refusing caller then finds it free within moments.
1188 cfg.wait = GpuWait::Refuse;
1189 let t0 = Instant::now();
1190 loop {
1191 if acquire_gpu(&cfg).is_ok() {
1192 break;
1193 }
1194 assert!(
1195 t0.elapsed() < Duration::from_secs(10),
1196 "lock never handed back"
1197 );
1198 thread::sleep(Duration::from_millis(20));
1199 }
1200 }
1201
1202 #[test]
1203 fn bounded_wait_on_a_held_proof_lock_refuses_with_its_reason() {
1204 let d = TempDir::new("gpu");
1205 let mut cfg = GpuConfig::rooted_at(d.path());
1206 cfg.proof_lock_path = Some(d.path().join("slots/gpu.lock"));
1207 let proof_only = GpuConfig {
1208 lock_path: d.path().join("other.lock"),
1209 ..cfg.clone()
1210 };
1211 let held = acquire_gpu(&proof_only).unwrap();
1212 cfg.wait = GpuWait::Bounded(Duration::from_millis(300));
1213 let a = acquire_gpu_timed(&cfg);
1214 assert_eq!(a.result.unwrap_err().reason(), "gpu_lock_proof");
1215 assert!(a.waited >= Duration::from_millis(300), "{:?}", a.waited);
1216 assert!(a.waited < Duration::from_secs(10), "{:?}", a.waited);
1217 drop(held);
1218 }
1219
1220 fn fake_meminfo(dir: &Path, mb: u64) {
1221 write_file(
1222 dir,
1223 "meminfo",
1224 &format!(
1225 "MemTotal: 127598528 kB\nMemAvailable: {} kB\n",
1226 mb * 1024
1227 ),
1228 false,
1229 );
1230 }
1231
1232 #[test]
1233 fn short_memory_is_refused_as_gpu_mem_and_gives_the_locks_back() {
1234 let d = TempDir::new("gpu");
1235 let mut cfg = GpuConfig::rooted_at(d.path());
1236 cfg.mem_need_mb = 100;
1237 cfg.mem_wait = Duration::from_millis(300);
1238 fake_meminfo(d.path(), 40);
1239 let a = acquire_gpu_timed(&cfg);
1240 assert!(
1241 matches!(
1242 a.result,
1243 Err(GpuRefusal::MemShort {
1244 free_mb: Some(40),
1245 need_mb: 100
1246 })
1247 ),
1248 "{:?}",
1249 a.result.as_ref().err()
1250 );
1251 assert_eq!(a.result.as_ref().err().unwrap().reason(), "gpu_mem");
1252 assert_eq!((a.mem_free_mb, a.mem_need_mb), (Some(40), 100));
1253 assert!(a.waited >= Duration::from_millis(300), "{:?}", a.waited);
1254 // The refused gate released the lock: the next job takes it.
1255 cfg.mem_need_mb = 0;
1256 assert!(acquire_gpu(&cfg).is_ok());
1257 }
1258
1259 #[test]
1260 fn enough_memory_runs_and_records_the_reading() {
1261 let d = TempDir::new("gpu");
1262 let mut cfg = GpuConfig::rooted_at(d.path());
1263 cfg.mem_need_mb = 100;
1264 cfg.mem_wait = Duration::from_millis(300);
1265 fake_meminfo(d.path(), 200);
1266 let a = acquire_gpu_timed(&cfg);
1267 assert!(a.result.is_ok(), "{:?}", a.result.as_ref().err());
1268 assert_eq!((a.mem_free_mb, a.mem_need_mb), (Some(200), 100));
1269 }
1270
1271 #[test]
1272 fn memory_that_comes_back_within_the_bound_runs() {
1273 let d = TempDir::new("gpu");
1274 let mut cfg = GpuConfig::rooted_at(d.path());
1275 cfg.mem_need_mb = 100;
1276 cfg.mem_wait = Duration::from_secs(20);
1277 fake_meminfo(d.path(), 40);
1278 let p = d.path().join("meminfo");
1279 let freer = std::thread::spawn(move || {
1280 std::thread::sleep(Duration::from_millis(700));
1281 fs::write(p, "MemTotal: 127598528 kB\nMemAvailable: 204800 kB\n").unwrap();
1282 });
1283 let a = acquire_gpu_timed(&cfg);
1284 freer.join().unwrap();
1285 assert!(a.result.is_ok(), "{:?}", a.result.as_ref().err());
1286 assert_eq!(a.mem_free_mb, Some(200));
1287 assert!(a.waited < Duration::from_secs(20), "{:?}", a.waited);
1288 }
1289
1290 #[test]
1291 fn unreadable_memory_is_refused_not_run() {
1292 let d = TempDir::new("gpu");
1293 let mut cfg = GpuConfig::rooted_at(d.path());
1294 cfg.mem_need_mb = 100;
1295 // No meminfo file in the scratch dir.
1296 let a = acquire_gpu_timed(&cfg);
1297 assert!(matches!(
1298 a.result,
1299 Err(GpuRefusal::MemShort {
1300 free_mb: None,
1301 need_mb: 100
1302 })
1303 ));
1304 assert_eq!(a.mem_free_mb, None);
1305 }
1306
1307 #[test]
1308 fn the_machine_default_checks_the_measured_floor() {
1309 let cfg = GpuConfig::detect();
1310 assert_eq!(cfg.mem_need_mb, DEFAULT_GPU_MEM_MB);
1311 assert_eq!(cfg.meminfo, PathBuf::from(DEFAULT_MEMINFO));
1312 assert_eq!(GpuConfig::rooted_at(Path::new("/x")).mem_need_mb, 0);
1313 }
1314
1315 #[test]
1316 fn open_handle_without_flock_does_not_block() {
1317 // CR-052: only a flock holder blocks; a plain open handle does not.
1318 let d = TempDir::new("gpu");
1319 let cfg = GpuConfig::rooted_at(d.path());
1320 write_file(d.path(), "gb10.lock", "", false);
1321 let _plain = File::open(&cfg.lock_path).unwrap();
1322 assert!(acquire_gpu(&cfg).is_ok());
1323 }
1324
1325 #[test]
1326 fn quiet_flag_refuses_and_is_left_alone() {
1327 let d = TempDir::new("gpu");
1328 let cfg = GpuConfig::rooted_at(d.path());
1329 write_file(d.path(), "quiet-flag", "drake start=now\n", false);
1330 match acquire_gpu(&cfg) {
1331 Err(GpuRefusal::QuietFlag(t)) => assert_eq!(t, "drake start=now"),
1332 other => panic!("expected QuietFlag, got {other:?}"),
1333 }
1334 assert_eq!(
1335 fs::read_to_string(d.path().join("quiet-flag")).unwrap(),
1336 "drake start=now\n",
1337 "the flag must never be changed"
1338 );
1339 assert!(!cfg.lock_path.exists(), "refused before touching the lock");
1340 assert_eq!(preflight(&cfg).unwrap().reason(), "quiet_flag");
1341 }
1342
1343 #[test]
1344 fn est_load_process_refuses() {
1345 let d = TempDir::new("gpu");
1346 let cfg = GpuConfig::rooted_at(d.path());
1347 assert!(preflight(&cfg).is_none(), "no proc dir means no est_load");
1348 write_file(d.path(), "proc/101/comm", "bash\n", false);
1349 write_file(d.path(), "proc/self/comm", "est_load\n", false);
1350 assert!(
1351 !est_load_running(&cfg.proc_dir),
1352 "non-numeric entries are ignored"
1353 );
1354 write_file(d.path(), "proc/202/comm", "est_load\n", false);
1355 assert!(est_load_running(&cfg.proc_dir));
1356 match acquire_gpu(&cfg) {
1357 Err(GpuRefusal::EstLoad) => {}
1358 other => panic!("expected EstLoad, got {other:?}"),
1359 }
1360 }
1361
1362 #[test]
1363 fn proof_lock_is_second_and_blocks_the_whole_acquire() {
1364 let d = TempDir::new("gpu");
1365 let mut cfg = GpuConfig::rooted_at(d.path());
1366 let proof = d.path().join("board/slots/gpu.lock");
1367 cfg.proof_lock_path = Some(proof.clone());
1368 // Someone else (aien-proof) holds its lock. A `GpuGuard` stands in for
1369 // that holder so its release goes through the spawn gate too.
1370 let other = open_lock(&proof).unwrap();
1371 assert!(flock_exclusive(&other, false).unwrap());
1372 let other = GpuGuard { files: vec![other] };
1373 match acquire_gpu(&cfg) {
1374 Err(GpuRefusal::ProofLockHeld(p)) => assert_eq!(p, proof),
1375 got => panic!("expected ProofLockHeld, got {got:?}"),
1376 }
1377 // The failed attempt must not leave the first lock held.
1378 let mut only_first = cfg.clone();
1379 only_first.proof_lock_path = None;
1380 assert!(acquire_gpu(&only_first).is_ok());
1381 drop(other);
1382 let both = acquire_gpu(&cfg).expect("both free now");
1383 // While both are held, each is refused to a second holder.
1384 assert!(matches!(acquire_gpu(&cfg), Err(GpuRefusal::LockHeld(_))));
1385 drop(both);
1386 }
1387
1388 #[test]
1389 fn wait_mode_blocks_until_the_holder_releases() {
1390 let d = TempDir::new("gpu");
1391 let mut cfg = GpuConfig::rooted_at(d.path());
1392 let held = acquire_gpu(&cfg).unwrap();
1393 cfg.wait = GpuWait::Forever;
1394 let (tx, rx) = mpsc::channel();
1395 thread::scope(|s| {
1396 s.spawn(|| {
1397 let g = acquire_gpu(&cfg);
1398 tx.send(g.is_ok()).unwrap();
1399 });
1400 thread::sleep(Duration::from_millis(150));
1401 assert!(rx.try_recv().is_err(), "wait mode must block");
1402 drop(held);
1403 assert!(rx.recv_timeout(Duration::from_secs(20)).unwrap());
1404 });
1405 }
1406
1407 #[test]
1408 fn detect_builds_a_config_without_touching_anything() {
1409 let c = GpuConfig::detect();
1410 assert_eq!(c.lock_path, PathBuf::from(DEFAULT_GPU_LOCK));
1411 assert_eq!(c.wait, GpuWait::Bounded(DEFAULT_GPU_WAIT));
1412 assert_eq!(c.proc_dir, PathBuf::from("/proc"));
1413 let _ = Hardware::detect();
1414 }
1415}