Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aien-sovereign-core-mv/blob/main/tools/aien-test/src/process.rs # aien-sovereign-core-mv AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aien-sovereign-core-mv / tools / aien-test / src / process.rs` 355 lines ยท 13091 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 //! Spawn a command without a shell, capture stdout and stderr, enforce a 17 //! wall-clock timeout by killing the whole process group (SIGTERM, then 18 //! SIGKILL after a grace period). No async: one waiter thread and two reader 19 //! threads per child. 20 21 use std::io::{self, Read}; 22 use std::os::unix::process::{CommandExt, ExitStatusExt}; 23 use std::path::{Path, PathBuf}; 24 use std::process::{Child, Command, ExitStatus, Output, Stdio}; 25 use std::sync::{mpsc, Mutex, MutexGuard}; 26 use std::thread; 27 use std::time::{Duration, Instant}; 28 29 pub struct RunSpec { 30 pub program: PathBuf, 31 pub args: Vec, 32 pub cwd: PathBuf, 33 pub timeout: Duration, 34 /// Time between SIGTERM and SIGKILL (ADR 0028 Decision 6 says 10 s). 35 pub kill_grace: Duration, 36 /// false: the job is never signalled and never timed out (ADR 0028 37 /// Decision 6, gb10 jobs). `timeout` is then advisory and only sets 38 /// `timeout_exceeded`. 39 pub enforce_timeout: bool, 40 /// Extra `K=V` pairs for the program's environment, set by the runner 41 /// (never by a manifest). The user sandbox forwards them as `--env`. 42 pub env: Vec<(String, String)>, 43 /// Names removed from the inherited environment before `env` is applied, 44 /// so an operator's shell cannot leak a runner-only marker into a gate. 45 pub env_remove: Vec, 46 } 47 48 #[derive(Debug)] 49 pub struct RunOutput { 50 /// Exit code; None if the child was killed by a signal. 51 pub exit_code: Option, 52 pub signal: Option, 53 pub stdout: Vec, 54 pub stderr: Vec, 55 /// The runner killed the job because `timeout` passed. 56 pub timed_out: bool, 57 /// The job ran longer than `timeout`, whether or not it was killed. 58 pub timeout_exceeded: bool, 59 pub duration_ms: u64, 60 } 61 62 type Waited = io::Result; 63 64 fn signal_group(pid: i32, sig: i32) { 65 if pid > 0 { 66 // SAFETY: plain syscall; a stale group id yields ESRCH, ignored. 67 unsafe { 68 libc::kill(-pid, sig); 69 } 70 } 71 } 72 73 fn lost() -> io::Error { 74 io::Error::other("waiter thread lost") 75 } 76 77 /// Held around every child spawn in this crate and around the release of the 78 /// GPU lock descriptors (`resources::GpuGuard`), so the two never overlap. 79 /// 80 /// Why: `flock(2)` locks belong to the open file description, and a child 81 /// created by fork (or clone) gets its own copy of the descriptor table. The 82 /// lock descriptor is close-on-exec (std opens every file with `O_CLOEXEC`, 83 /// `library/std/src/sys/fs/unix.rs` `open_c`), so a child drops its copy at 84 /// exec. Between the fork and the exec the child still holds the file 85 /// description, and the lock looks held even after the parent closed its own 86 /// descriptor. With several threads (parallel gates in the runner, parallel 87 /// unit tests) another thread's child can sit in that window exactly when a 88 /// guard is dropped, and the next `acquire_gpu` is refused with `LockHeld` 89 /// although nobody holds the lock (an intermittent failure of 90 /// `gpu_lock_is_exclusive_and_released_on_drop` was seen once on the forge). 91 /// 92 /// `Command::spawn` returns only after the child has exec'd or failed (std 93 /// reads the close-on-exec pipe until it closes, `process/unix/unix.rs` 94 /// `spawn`). So a spawn made under this mutex has no child left in the window 95 /// when the mutex is released, and a guard released under it can only be 96 /// copied by spawns that start after the descriptors are already closed. 97 /// A genuinely held lock is still refused at once (ADR 0028 Decision 6). 98 static SPAWN_GATE: Mutex<()> = Mutex::new(()); 99 100 /// Worktrees the operator's git may open although `aien-run` owns their 101 /// files. The worker adds one only after checking that it was made by INFRA's 102 /// `wt.sh`: its `.git` file is root-owned, not writable by anyone else, and 103 /// points into the operator's mirror, so every git setting and hook that git 104 /// reads there is the operator's, never the checked-out code's. 105 static TRUSTED_WORKTREES: Mutex> = Mutex::new(Vec::new()); 106 107 /// Trust `dir` for git (git's `safe.directory`) until the guard is dropped. 108 pub fn trust_worktree(dir: &Path) -> TrustGuard { 109 let mut v = TRUSTED_WORKTREES.lock().unwrap_or_else(|p| p.into_inner()); 110 v.push(dir.to_path_buf()); 111 TrustGuard(dir.to_path_buf()) 112 } 113 114 /// Removes its directory from the trusted list when dropped. 115 pub struct TrustGuard(PathBuf); 116 117 impl Drop for TrustGuard { 118 fn drop(&mut self) { 119 let mut v = TRUSTED_WORKTREES.lock().unwrap_or_else(|p| p.into_inner()); 120 if let Some(i) = v.iter().position(|d| d == &self.0) { 121 v.remove(i); 122 } 123 } 124 } 125 126 /// Give `cmd` the trusted worktrees as `safe.directory` entries through 127 /// git's command-line configuration (`GIT_CONFIG_COUNT`), which git honours 128 /// for that setting. Children that run git themselves (crumb) inherit it. With 129 /// no trusted worktree the command is left exactly as it was. 130 pub fn apply_git_trust(cmd: &mut Command) { 131 let v = TRUSTED_WORKTREES.lock().unwrap_or_else(|p| p.into_inner()); 132 if v.is_empty() { 133 return; 134 } 135 cmd.env("GIT_CONFIG_COUNT", v.len().to_string()); 136 for (i, d) in v.iter().enumerate() { 137 cmd.env(format!("GIT_CONFIG_KEY_{i}"), "safe.directory"); 138 cmd.env(format!("GIT_CONFIG_VALUE_{i}"), d); 139 } 140 } 141 142 /// `git` with the trusted worktrees applied (see [`apply_git_trust`]). 143 pub fn git_command() -> Command { 144 let mut cmd = Command::new("git"); 145 apply_git_trust(&mut cmd); 146 cmd 147 } 148 149 /// Take the spawn gate. It is a leaf lock: nothing else is taken while it is 150 /// held, and a poisoned gate is still usable (it guards no data). 151 pub(crate) fn spawn_gate() -> MutexGuard<'static, ()> { 152 SPAWN_GATE.lock().unwrap_or_else(|e| e.into_inner()) 153 } 154 155 /// `cmd.spawn()` under the spawn gate. Every child this crate starts goes 156 /// through here (or `output_gated`), never through a bare `Command::spawn`. 157 pub(crate) fn spawn_gated(cmd: &mut Command) -> io::Result { 158 let _gate = spawn_gate(); 159 cmd.spawn() 160 } 161 162 /// `cmd.output()` with the spawn under the spawn gate. Waiting for the output 163 /// happens after the gate is released, so a slow child never blocks others. 164 pub(crate) fn output_gated(cmd: &mut Command) -> io::Result { 165 cmd.stdin(Stdio::null()) 166 .stdout(Stdio::piped()) 167 .stderr(Stdio::piped()); 168 spawn_gated(cmd)?.wait_with_output() 169 } 170 171 fn spawn(spec: &RunSpec) -> io::Result { 172 let mut cmd = Command::new(&spec.program); 173 cmd.args(&spec.args) 174 .current_dir(&spec.cwd) 175 .stdin(Stdio::null()) 176 .stdout(Stdio::piped()) 177 .stderr(Stdio::piped()) 178 .process_group(0); 179 for k in &spec.env_remove { 180 cmd.env_remove(k); 181 } 182 for (k, v) in &spec.env { 183 cmd.env(k, v); 184 } 185 let mut attempt = 0; 186 loop { 187 // One attempt per gate hold: the retry sleep below is outside it. 188 match spawn_gated(&mut cmd) { 189 Ok(c) => return Ok(c), 190 // A script written moments ago can be briefly busy when another 191 // thread forks while its write descriptor is still open. 192 Err(e) if e.raw_os_error() == Some(libc::ETXTBSY) && attempt < 40 => { 193 attempt += 1; 194 thread::sleep(Duration::from_millis(50)); 195 } 196 Err(e) => return Err(e), 197 } 198 } 199 } 200 201 fn terminate(pid: i32, rx: &mpsc::Receiver, grace: Duration) -> io::Result { 202 signal_group(pid, libc::SIGTERM); 203 match rx.recv_timeout(grace) { 204 Ok(r) => Ok(r), 205 Err(mpsc::RecvTimeoutError::Timeout) => { 206 signal_group(pid, libc::SIGKILL); 207 rx.recv().map_err(|_| lost()) 208 } 209 Err(mpsc::RecvTimeoutError::Disconnected) => Err(lost()), 210 } 211 } 212 213 fn reader(src: Option) -> thread::JoinHandle> { 214 thread::spawn(move || { 215 let mut buf = Vec::new(); 216 if let Some(mut s) = src { 217 let _ = s.read_to_end(&mut buf); 218 } 219 buf 220 }) 221 } 222 223 pub fn run(spec: &RunSpec) -> io::Result { 224 let start = Instant::now(); 225 let mut child = spawn(spec)?; 226 let pid = child.id() as i32; 227 let h_out = reader(child.stdout.take()); 228 let h_err = reader(child.stderr.take()); 229 let (tx, rx) = mpsc::channel::(); 230 thread::spawn(move || { 231 let r = child.wait(); 232 let _ = tx.send(r); 233 }); 234 235 let mut timed_out = false; 236 let waited: Waited = if !spec.enforce_timeout { 237 // Advisory timeout: wait for the job however long it takes. 238 rx.recv().map_err(|_| lost())? 239 } else { 240 match rx.recv_timeout(spec.timeout) { 241 Ok(r) => r, 242 Err(mpsc::RecvTimeoutError::Timeout) => { 243 timed_out = true; 244 terminate(pid, &rx, spec.kill_grace)? 245 } 246 Err(mpsc::RecvTimeoutError::Disconnected) => return Err(lost()), 247 } 248 }; 249 let waited_for = start.elapsed(); 250 if spec.enforce_timeout { 251 // Whatever the leader did, nothing it started may outlive the run. 252 signal_group(pid, libc::SIGKILL); 253 } 254 let status = waited?; 255 let stdout = h_out.join().unwrap_or_default(); 256 let stderr = h_err.join().unwrap_or_default(); 257 Ok(RunOutput { 258 exit_code: status.code(), 259 signal: status.signal(), 260 stdout, 261 stderr, 262 timed_out, 263 timeout_exceeded: timed_out || (!spec.enforce_timeout && waited_for > spec.timeout), 264 duration_ms: start.elapsed().as_millis() as u64, 265 }) 266 } 267 268 #[cfg(test)] 269 mod tests { 270 use super::*; 271 272 fn sh(script: &str, timeout_ms: u64) -> RunSpec { 273 RunSpec { 274 program: PathBuf::from("/bin/sh"), 275 args: vec!["-c".to_string(), script.to_string()], 276 cwd: PathBuf::from("/"), 277 timeout: Duration::from_millis(timeout_ms), 278 kill_grace: Duration::from_millis(500), 279 enforce_timeout: true, 280 env: Vec::new(), 281 env_remove: Vec::new(), 282 } 283 } 284 285 #[test] 286 fn captures_output_and_exit_code() { 287 let o = run(&sh("echo out; echo err 1>&2; exit 3", 10_000)).unwrap(); 288 assert_eq!(o.exit_code, Some(3)); 289 assert_eq!(o.stdout, b"out\n"); 290 assert_eq!(o.stderr, b"err\n"); 291 assert!(!o.timed_out); 292 } 293 294 #[test] 295 fn timeout_kills_and_flags() { 296 let o = run(&sh("sleep 20", 300)).unwrap(); 297 assert!(o.timed_out); 298 assert_eq!(o.exit_code, None); 299 assert!(o.signal.is_some()); 300 assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms); 301 } 302 303 #[test] 304 fn timeout_kills_the_whole_group() { 305 // The grandchild inherits stdout; if only the leader were killed the 306 // reader threads would block until the grandchild's sleep ends. 307 let o = run(&sh("sleep 20 & wait", 300)).unwrap(); 308 assert!(o.timed_out); 309 assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms); 310 } 311 312 #[test] 313 fn term_ignored_gets_killed_after_grace() { 314 let o = run(&sh("trap '' TERM; sleep 20", 200)).unwrap(); 315 assert!(o.timed_out); 316 assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms); 317 } 318 319 #[test] 320 fn orphans_do_not_outlive_a_normal_exit() { 321 let o = run(&sh("sleep 20 & echo done", 10_000)).unwrap(); 322 assert_eq!(o.exit_code, Some(0)); 323 assert!(!o.timed_out); 324 assert!(o.duration_ms < 10_000, "took {} ms", o.duration_ms); 325 } 326 327 #[test] 328 fn advisory_timeout_never_signals_the_job() { 329 let mut s = sh("sleep 1; echo done", 100); 330 s.enforce_timeout = false; 331 let o = run(&s).unwrap(); 332 assert_eq!(o.exit_code, Some(0)); 333 assert_eq!(o.stdout, b"done\n"); 334 assert!(!o.timed_out, "an advisory timeout must not kill"); 335 assert!(o.timeout_exceeded, "but it must be reported"); 336 assert!(o.signal.is_none()); 337 } 338 339 #[test] 340 fn within_the_limit_is_not_exceeded() { 341 let mut s = sh("echo quick", 20_000); 342 s.enforce_timeout = false; 343 let o = run(&s).unwrap(); 344 assert!(!o.timeout_exceeded); 345 let o = run(&sh("echo quick", 20_000)).unwrap(); 346 assert!(!o.timeout_exceeded && !o.timed_out); 347 } 348 349 #[test] 350 fn missing_program_is_an_error() { 351 let mut s = sh("true", 1000); 352 s.program = PathBuf::from("/nonexistent/aien-test-nope"); 353 assert!(run(&s).is_err()); 354 } 355 }