Skip to main content

onerig_core/
process.rs

1//! The subprocess driver. It runs one described call to its end and knows
2//! nothing about harnesses or runs: it starts the child in its own process
3//! group, streams its output, and kills the whole group when a limit is hit,
4//! the stop flag is set, or the child is done.
5
6use std::ffi::OsStr;
7use std::io::{BufRead, BufReader, Read, Write};
8use std::os::unix::process::CommandExt;
9use std::path::Path;
10use std::process::{Child, Command, ExitStatus, Stdio};
11use std::sync::mpsc::{self, Receiver, RecvTimeoutError, Sender};
12use std::thread;
13use std::time::{Duration, Instant};
14
15use crate::adapter::{Output, Spawn};
16use crate::halt::Halt;
17
18/// How long a child gets to leave after SIGTERM, and how long its pipes may
19/// stay open after it has exited.
20const GRACE: Duration = Duration::from_secs(2);
21/// How often limits and the stop flag are checked.
22const TICK: Duration = Duration::from_millis(20);
23/// How long output is still collected after the process group is killed.
24const DRAIN: Duration = Duration::from_millis(500);
25const STDERR_TAIL: usize = 16 * 1024;
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28pub struct Limits {
29    /// Longest time without a new stdout line.
30    pub idle: Duration,
31    /// Longest time the job may run.
32    pub total: Duration,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub enum Ended {
37    Exited(Output),
38    IdleTimeout(Output),
39    JobTimeout(Output),
40    /// The stop flag was set.
41    Stopped(Output),
42    SpawnFailed(String),
43}
44
45pub fn run(
46    spawn: &Spawn,
47    cwd: &Path,
48    limits: Limits,
49    stop: &Halt,
50    on_spawn: &mut dyn FnMut(i32),
51    on_line: &mut dyn FnMut(&str),
52) -> Ended {
53    if let Err(message) = write_files(spawn, cwd) {
54        return Ended::SpawnFailed(message);
55    }
56    let mut job = match Job::start(spawn, cwd) {
57        Ok(job) => job,
58        Err(message) => return Ended::SpawnFailed(message),
59    };
60    on_spawn(job.pgid);
61    let reason = job.wait_for_end(limits, stop, on_line);
62    finish(job, reason, on_line)
63}
64
65fn finish(mut job: Job, reason: Reason, on_line: &mut dyn FnMut(&str)) -> Ended {
66    if reason == Reason::Exited {
67        signal_group(job.pgid, libc::SIGKILL);
68    } else {
69        job.terminate(on_line);
70    }
71    job.drain(on_line);
72    let output = job.output();
73    match reason {
74        Reason::Exited => Ended::Exited(output),
75        Reason::Idle => Ended::IdleTimeout(output),
76        Reason::Total => Ended::JobTimeout(output),
77        Reason::Stopped => Ended::Stopped(output),
78    }
79}
80
81/// Relative paths are taken from `cwd`.
82fn write_files(spawn: &Spawn, cwd: &Path) -> Result<(), String> {
83    for (path, text) in &spawn.files {
84        let full = cwd.join(path);
85        let write = || -> std::io::Result<()> {
86            if let Some(parent) = full.parent() {
87                std::fs::create_dir_all(parent)?;
88            }
89            std::fs::write(&full, text)
90        };
91        write().map_err(|e| format!("cannot write {}: {e}", path.display()))?;
92    }
93    Ok(())
94}
95
96/// An exact variable name, or a prefix followed by `*`.
97fn is_removed(name: &OsStr, patterns: &[String]) -> bool {
98    let Some(name) = name.to_str() else {
99        return false;
100    };
101    patterns
102        .iter()
103        .any(|pattern| match pattern.strip_suffix('*') {
104            Some(prefix) => name.starts_with(prefix),
105            None => name == pattern,
106        })
107}
108
109fn signal_group(pgid: i32, signal: i32) {
110    // SAFETY: killpg only sends a signal; a group that is gone gives ESRCH,
111    // which needs no handling.
112    unsafe {
113        libc::killpg(pgid, signal);
114    }
115}
116
117#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118enum Reason {
119    Exited,
120    Idle,
121    Total,
122    Stopped,
123}
124
125enum Piece {
126    Line(String),
127    Stderr(Vec<u8>),
128    Closed,
129}
130
131struct Job {
132    child: Child,
133    pgid: i32,
134    pieces: Receiver<Piece>,
135    open_pipes: u8,
136    stdout: Vec<String>,
137    stderr: Vec<u8>,
138    status: Option<ExitStatus>,
139    started: Instant,
140    last_line: Instant,
141    exited_at: Option<Instant>,
142}
143
144impl Job {
145    fn start(spawn: &Spawn, cwd: &Path) -> Result<Job, String> {
146        let mut command = Command::new(&spawn.program);
147        command
148            .args(&spawn.args)
149            .current_dir(cwd)
150            .stdin(Stdio::piped())
151            .stdout(Stdio::piped())
152            .stderr(Stdio::piped())
153            .process_group(0);
154        for (name, _) in std::env::vars_os() {
155            if is_removed(&name, &spawn.env_remove) {
156                command.env_remove(&name);
157            }
158        }
159        command.envs(spawn.env_set.iter().map(|(k, v)| (k, v)));
160        let mut child = command
161            .spawn()
162            .map_err(|e| format!("cannot start {}: {e}", spawn.program.display()))?;
163        feed_stdin(&mut child, spawn.stdin.clone());
164        let pieces = read_pipes(&mut child);
165        let now = Instant::now();
166        Ok(Job {
167            pgid: child.id() as i32,
168            child,
169            pieces,
170            open_pipes: 2,
171            stdout: Vec::new(),
172            stderr: Vec::new(),
173            status: None,
174            started: now,
175            last_line: now,
176            exited_at: None,
177        })
178    }
179
180    fn wait_for_end(
181        &mut self,
182        limits: Limits,
183        stop: &Halt,
184        on_line: &mut dyn FnMut(&str),
185    ) -> Reason {
186        loop {
187            self.step(on_line);
188            if let Some(reason) = self.reason(limits, stop) {
189                return reason;
190            }
191        }
192    }
193
194    fn step(&mut self, on_line: &mut dyn FnMut(&str)) {
195        match self.pieces.recv_timeout(TICK) {
196            Ok(piece) => self.take(piece, on_line),
197            Err(RecvTimeoutError::Disconnected) => thread::sleep(TICK),
198            Err(RecvTimeoutError::Timeout) => {}
199        }
200        self.poll_exit();
201    }
202
203    fn take(&mut self, piece: Piece, on_line: &mut dyn FnMut(&str)) {
204        match piece {
205            Piece::Line(line) => {
206                on_line(&line);
207                self.stdout.push(line);
208                self.last_line = Instant::now();
209            }
210            Piece::Stderr(bytes) => {
211                self.stderr.extend(bytes);
212                let excess = self.stderr.len().saturating_sub(STDERR_TAIL);
213                self.stderr.drain(..excess);
214            }
215            Piece::Closed => self.open_pipes = self.open_pipes.saturating_sub(1),
216        }
217    }
218
219    fn poll_exit(&mut self) {
220        if self.status.is_none()
221            && let Ok(Some(status)) = self.child.try_wait()
222        {
223            self.status = Some(status);
224            self.exited_at = Some(Instant::now());
225        }
226    }
227
228    fn reason(&self, limits: Limits, stop: &Halt) -> Option<Reason> {
229        let done = |at: Instant| self.open_pipes == 0 || at.elapsed() >= GRACE;
230        if self.exited_at.is_some_and(done) {
231            Some(Reason::Exited)
232        } else if stop.is_set() {
233            Some(Reason::Stopped)
234        } else if self.last_line.elapsed() >= limits.idle {
235            Some(Reason::Idle)
236        } else if self.started.elapsed() >= limits.total {
237            Some(Reason::Total)
238        } else {
239            None
240        }
241    }
242
243    /// SIGTERM to the group, SIGKILL after the grace period; the group is
244    /// killed in any case so no descendant outlives the job.
245    fn terminate(&mut self, on_line: &mut dyn FnMut(&str)) {
246        signal_group(self.pgid, libc::SIGTERM);
247        let deadline = Instant::now() + GRACE;
248        while self.status.is_none() && Instant::now() < deadline {
249            self.step(on_line);
250        }
251        signal_group(self.pgid, libc::SIGKILL);
252        if self.status.is_none() {
253            self.status = self.child.wait().ok();
254        }
255    }
256
257    fn drain(&mut self, on_line: &mut dyn FnMut(&str)) {
258        let deadline = Instant::now() + DRAIN;
259        while self.open_pipes > 0 {
260            let left = deadline.saturating_duration_since(Instant::now());
261            match self.pieces.recv_timeout(left) {
262                Ok(piece) => self.take(piece, on_line),
263                Err(_) => break,
264            }
265        }
266    }
267
268    fn output(self) -> Output {
269        Output {
270            exit_code: self.status.and_then(|status| status.code()),
271            stdout: self.stdout,
272            stderr_tail: String::from_utf8_lossy(&self.stderr).into_owned(),
273        }
274    }
275}
276
277/// Writes stdin from its own thread, so a child that never reads it cannot
278/// block the job, and closes it.
279fn feed_stdin(child: &mut Child, text: Option<String>) {
280    let Some(mut stdin) = child.stdin.take() else {
281        return;
282    };
283    if let Some(text) = text {
284        // A child that exits without reading makes this fail with a broken
285        // pipe, which is not an error of the job.
286        thread::spawn(move || stdin.write_all(text.as_bytes()));
287    }
288}
289
290fn read_pipes(child: &mut Child) -> Receiver<Piece> {
291    let (sender, receiver) = mpsc::channel();
292    if let Some(stdout) = child.stdout.take() {
293        let sender = sender.clone();
294        thread::spawn(move || read_lines(stdout, &sender));
295    }
296    if let Some(stderr) = child.stderr.take() {
297        thread::spawn(move || read_chunks(stderr, &sender));
298    }
299    receiver
300}
301
302fn read_lines(pipe: impl Read, sender: &Sender<Piece>) {
303    let mut reader = BufReader::new(pipe);
304    let mut buffer = Vec::new();
305    while matches!(reader.read_until(b'\n', &mut buffer), Ok(n) if n > 0) {
306        let line = buffer.strip_suffix(b"\n").unwrap_or(&buffer);
307        let line = line.strip_suffix(b"\r").unwrap_or(line);
308        let _ = sender.send(Piece::Line(String::from_utf8_lossy(line).into_owned()));
309        buffer.clear();
310    }
311    let _ = sender.send(Piece::Closed);
312}
313
314fn read_chunks(mut pipe: impl Read, sender: &Sender<Piece>) {
315    let mut chunk = [0u8; 4096];
316    while let Ok(n @ 1..) = pipe.read(&mut chunk) {
317        let _ = sender.send(Piece::Stderr(chunk[..n].to_vec()));
318    }
319    let _ = sender.send(Piece::Closed);
320}
321
322#[cfg(test)]
323mod tests {
324    use super::*;
325    use std::process::{Command, Stdio};
326    use std::thread;
327    use std::time::Instant;
328
329    /// Limits no passing test comes near; a regression fails instead of hanging.
330    const ROOMY: Limits = Limits {
331        idle: Duration::from_secs(10),
332        total: Duration::from_secs(10),
333    };
334
335    struct Seen {
336        ended: Ended,
337        pgids: Vec<i32>,
338        lines: Vec<String>,
339        took: Duration,
340    }
341
342    fn sh(script: &str) -> Spawn {
343        Spawn {
344            program: "/bin/sh".into(),
345            args: vec!["-c".into(), script.into()],
346            ..Spawn::default()
347        }
348    }
349
350    fn drive(spawn: &Spawn, cwd: &Path, limits: Limits, stop: &Halt) -> Seen {
351        let (mut pgids, mut lines) = (Vec::new(), Vec::new());
352        let started = Instant::now();
353        let ended = run(
354            spawn,
355            cwd,
356            limits,
357            stop,
358            &mut |pgid| pgids.push(pgid),
359            &mut |line| lines.push(line.to_owned()),
360        );
361        Seen {
362            ended,
363            pgids,
364            lines,
365            took: started.elapsed(),
366        }
367    }
368
369    fn drive_here(spawn: &Spawn, limits: Limits) -> Seen {
370        drive(spawn, Path::new("."), limits, &Halt::new())
371    }
372
373    fn exited(ended: Ended) -> Output {
374        match ended {
375            Ended::Exited(output) => output,
376            other => panic!("expected an exit, got {other:?}"),
377        }
378    }
379
380    /// Whether a process disappears within a second.
381    fn is_gone(pid: &str) -> bool {
382        (0..100).any(|_| {
383            thread::sleep(Duration::from_millis(10));
384            !Command::new("/bin/kill")
385                .args(["-0", pid])
386                .stderr(Stdio::null())
387                .status()
388                .unwrap()
389                .success()
390        })
391    }
392
393    #[test]
394    fn a_child_that_exits_reports_its_lines_its_exit_code_and_its_stderr() {
395        let spawn = sh("echo one; echo two; echo oops >&2; exit 3");
396
397        let seen = drive_here(&spawn, ROOMY);
398
399        assert_eq!(
400            seen.ended,
401            Ended::Exited(Output {
402                exit_code: Some(3),
403                stdout: vec!["one".into(), "two".into()],
404                stderr_tail: "oops\n".into(),
405            })
406        );
407        assert!(seen.took < DRAIN, "took {:?}", seen.took);
408    }
409
410    #[test]
411    fn empty_lines_are_kept() {
412        let spawn = sh("printf 'a\\n\\nb\\n'");
413
414        let seen = drive_here(&spawn, ROOMY);
415
416        assert_eq!(seen.lines, ["a", "", "b"]);
417    }
418
419    #[test]
420    fn a_variable_name_that_is_not_utf8_is_never_removed() {
421        use std::os::unix::ffi::OsStrExt;
422
423        let removed = is_removed(OsStr::from_bytes(b"\xffNAME"), &["*".to_owned()]);
424
425        assert!(!removed);
426    }
427
428    #[test]
429    fn every_stdout_line_reaches_on_line_without_its_newline() {
430        let spawn = sh("echo first; printf 'no newline at the end'");
431
432        let seen = drive_here(&spawn, ROOMY);
433
434        assert_eq!(seen.lines, ["first", "no newline at the end"]);
435    }
436
437    #[test]
438    fn stdin_is_delivered_to_the_child_and_closed() {
439        let spawn = Spawn {
440            stdin: Some("alpha\nbeta\n".into()),
441            ..sh("cat; echo end")
442        };
443
444        let seen = drive_here(&spawn, ROOMY);
445
446        assert_eq!(exited(seen.ended).stdout, ["alpha", "beta", "end"]);
447    }
448
449    #[test]
450    fn without_stdin_the_child_reads_end_of_file() {
451        let spawn = sh("cat; echo end");
452
453        let seen = drive_here(&spawn, ROOMY);
454
455        assert_eq!(exited(seen.ended).stdout, ["end"]);
456    }
457
458    #[test]
459    fn stdin_the_child_never_reads_does_not_block_the_job() {
460        let spawn = Spawn {
461            stdin: Some("x".repeat(1 << 20)),
462            ..sh("exit 0")
463        };
464
465        let seen = drive_here(&spawn, ROOMY);
466
467        assert_eq!(exited(seen.ended).exit_code, Some(0));
468    }
469
470    #[test]
471    fn env_remove_drops_a_prefix_from_the_inherited_environment_and_env_set_is_applied_last() {
472        assert!(
473            std::env::var_os("CARGO_PKG_NAME").is_some(),
474            "this test needs the variables cargo sets for a test run"
475        );
476        let spawn = Spawn {
477            env_remove: vec!["CARGO_PKG_*".into()],
478            env_set: vec![("CARGO_PKG_VERSION".into(), "set".into())],
479            ..sh(
480                r#"echo "${CARGO_PKG_NAME-removed} ${CARGO_PKG_VERSION-removed} ${CARGO_MANIFEST_DIR:+kept}""#,
481            )
482        };
483
484        let seen = drive_here(&spawn, ROOMY);
485
486        assert_eq!(seen.lines, ["removed set kept"]);
487    }
488
489    #[test]
490    fn env_remove_matches_an_exact_name_or_the_prefix_before_a_star() {
491        let patterns = ["CLAUDE_*".to_owned(), "ANTHROPIC_API_KEY".to_owned()];
492
493        let removed = |name: &str| is_removed(OsStr::new(name), &patterns);
494
495        assert!(removed("CLAUDE_CODE_ENTRYPOINT"));
496        assert!(removed("ANTHROPIC_API_KEY"));
497        assert!(!removed("ANTHROPIC_API_KEY_FILE"));
498        assert!(!removed("MY_CLAUDE_HOME"));
499        assert!(!removed("PATH"));
500    }
501
502    #[test]
503    fn files_are_written_with_their_parent_directories_before_the_child_starts() {
504        let dir = tempfile::tempdir().unwrap();
505        let spawn = Spawn {
506            files: vec![
507                (dir.path().join("a/b/absolute.txt"), "absolute".into()),
508                ("c/relative.txt".into(), "relative".into()),
509            ],
510            ..sh("cat a/b/absolute.txt; echo; cat c/relative.txt")
511        };
512
513        let seen = drive(&spawn, dir.path(), ROOMY, &Halt::new());
514
515        assert_eq!(seen.lines, ["absolute", "relative"]);
516    }
517
518    #[test]
519    fn a_file_that_cannot_be_written_fails_the_spawn_before_anything_starts() {
520        let dir = tempfile::tempdir().unwrap();
521        std::fs::write(dir.path().join("blocker"), "").unwrap();
522        let spawn = Spawn {
523            files: vec![("blocker/prompt.txt".into(), "x".into())],
524            ..sh("exit 0")
525        };
526
527        let seen = drive(&spawn, dir.path(), ROOMY, &Halt::new());
528
529        assert!(
530            matches!(&seen.ended, Ended::SpawnFailed(message) if message.contains("blocker/prompt.txt")),
531            "{:?}",
532            seen.ended
533        );
534        assert!(seen.pgids.is_empty());
535    }
536
537    #[test]
538    fn a_missing_program_is_a_spawn_failure_that_names_the_program() {
539        let spawn = Spawn {
540            program: "/nonexistent/onerig-harness".into(),
541            ..Spawn::default()
542        };
543
544        let seen = drive_here(&spawn, ROOMY);
545
546        assert!(
547            matches!(&seen.ended, Ended::SpawnFailed(message) if message.contains("/nonexistent/onerig-harness")),
548            "{:?}",
549            seen.ended
550        );
551        assert!(seen.pgids.is_empty());
552    }
553
554    #[test]
555    fn on_spawn_receives_the_process_group_the_child_leads() {
556        let spawn = sh("ps -o pgid= -p $$");
557
558        let seen = drive_here(&spawn, ROOMY);
559
560        assert_eq!(seen.pgids.len(), 1);
561        assert!(seen.pgids[0] > 0);
562        assert_eq!(seen.lines[0].trim(), seen.pgids[0].to_string());
563    }
564
565    #[test]
566    fn a_child_with_no_new_stdout_line_ends_as_an_idle_timeout() {
567        let limits = Limits {
568            idle: Duration::from_millis(300),
569            ..ROOMY
570        };
571        let spawn = sh("echo one; while :; do echo noise >&2; sleep 0.05; done");
572
573        let seen = drive_here(&spawn, limits);
574
575        let Ended::IdleTimeout(output) = seen.ended else {
576            panic!("expected an idle timeout, got {:?}", seen.ended);
577        };
578        assert_eq!(output.stdout, ["one"]);
579        assert_eq!(output.exit_code, None);
580        assert!(output.stderr_tail.contains("noise"));
581        assert!(
582            seen.took < GRACE,
583            "SIGTERM alone should end it: {:?}",
584            seen.took
585        );
586    }
587
588    #[test]
589    fn a_child_that_keeps_talking_past_the_total_limit_ends_as_a_job_timeout() {
590        let limits = Limits {
591            idle: Duration::from_millis(500),
592            total: Duration::from_secs(1),
593        };
594        let spawn = sh("while :; do echo tick; sleep 0.05; done");
595
596        let seen = drive_here(&spawn, limits);
597
598        let Ended::JobTimeout(output) = seen.ended else {
599            panic!("expected a job timeout, got {:?}", seen.ended);
600        };
601        assert!(output.stdout.len() > 1);
602        assert!(output.stdout.iter().all(|line| line == "tick"));
603        assert!(seen.took >= limits.total);
604    }
605
606    #[test]
607    fn a_child_that_ignores_sigterm_is_killed_with_its_descendants_after_the_grace_period() {
608        let limits = Limits {
609            idle: Duration::from_millis(300),
610            ..ROOMY
611        };
612        let spawn = sh("trap '' TERM; sleep 30 & echo $!; wait");
613
614        let seen = drive_here(&spawn, limits);
615
616        let Ended::IdleTimeout(output) = seen.ended else {
617            panic!("expected an idle timeout, got {:?}", seen.ended);
618        };
619        assert_eq!(output.exit_code, None);
620        assert!(seen.took >= GRACE, "took {:?}", seen.took);
621        assert!(seen.took < 2 * GRACE, "took {:?}", seen.took);
622        assert!(is_gone(&output.stdout[0]));
623    }
624
625    #[test]
626    fn a_descendant_that_keeps_stdout_open_does_not_hang_the_job_and_is_killed() {
627        let spawn = sh("sleep 30 & echo $!");
628
629        let seen = drive_here(&spawn, ROOMY);
630
631        let output = exited(seen.ended);
632        assert_eq!(output.exit_code, Some(0));
633        assert!(seen.took >= GRACE, "took {:?}", seen.took);
634        assert!(seen.took < 2 * GRACE, "took {:?}", seen.took);
635        assert!(is_gone(&output.stdout[0]));
636    }
637
638    #[test]
639    fn the_stop_flag_set_from_another_thread_ends_the_job_as_stopped() {
640        let stop = Halt::new();
641        let spawn = sh("echo started; sleep 30");
642
643        let seen = thread::scope(|scope| {
644            scope.spawn(|| {
645                thread::sleep(Duration::from_millis(300));
646                stop.stop();
647            });
648            drive(&spawn, Path::new("."), ROOMY, &stop)
649        });
650
651        assert!(
652            matches!(&seen.ended, Ended::Stopped(output) if output.stdout == ["started"]),
653            "{:?}",
654            seen.ended
655        );
656        assert!(seen.took < GRACE, "took {:?}", seen.took);
657    }
658
659    #[test]
660    fn output_that_is_not_utf8_is_decoded_lossily() {
661        let spawn = sh(r"printf '\377 out\n'; printf '\377 err' >&2");
662
663        let seen = drive_here(&spawn, ROOMY);
664
665        let output = exited(seen.ended);
666        assert_eq!(output.stdout, ["\u{fffd} out"]);
667        assert_eq!(output.stderr_tail, "\u{fffd} err");
668    }
669
670    #[test]
671    fn only_the_last_16_kib_of_stderr_are_kept() {
672        let spawn = sh("yes 0123456789 | head -n 3000 >&2; echo last >&2");
673
674        let seen = drive_here(&spawn, ROOMY);
675
676        let tail = exited(seen.ended).stderr_tail;
677        assert_eq!(tail.len(), 16 * 1024);
678        assert!(tail.ends_with("0123456789\nlast\n"));
679    }
680
681    #[test]
682    fn a_child_killed_by_a_signal_has_no_exit_code() {
683        let spawn = sh("kill -KILL $$");
684
685        let seen = drive_here(&spawn, ROOMY);
686
687        assert_eq!(exited(seen.ended).exit_code, None);
688    }
689
690    #[test]
691    fn a_child_that_closes_its_pipes_and_runs_on_still_reports_its_exit_code() {
692        let spawn = sh("exec >&- 2>&-; sleep 0.4; exit 7");
693
694        let seen = drive_here(&spawn, ROOMY);
695
696        assert_eq!(exited(seen.ended).exit_code, Some(7));
697    }
698}