repositories / smith
smith
There are many coding harnesses - but this one is fast
owned by bugabinga
smith-core/src/bash.rs
RawFile outline
- READ_CHUNK line 17
- GRACE_DRAIN line 18
- POLL_SLICE line 19
- BashResult line 22
- execute line 44
- Stream line 141
- spawn line 147
- kill_tree line 172
- drain_pipes line 186
- spawn_reader line 213
- tests line 241
- run line 252
- completes_and_captures_output line 256
- timeout_kills_silent_child_promptly line 264
- stderr_heavy_child_cannot_deadlock_the_deadline line 273
- cancellation_stops_execution line 281
- output_cap_keeps_fitting_prefix line 298
- high_volume_output_is_not_throttled line 304
- descendant_processes_are_killed_with_the_tree line 316
//! Bounded, cancellable shell execution with owned-process-tree termination
//! (`SMH-SPEC-SPEC0001`, Tools).
//!
//! Pipes are drained by dedicated threads so the deadline loop is never
//! blocked by a silent child; per-stream caps keep the fitting prefix and
//! bound all collection, including post-exit draining.
use smith::error::{Result, SmithError};
use smith::tool::CancelHandle;
use std::io::Read;
use std::process::{Child, Command, ExitStatus, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::time::{Duration, Instant};
const READ_CHUNK: usize = 16 * 1024;
const GRACE_DRAIN: Duration = Duration::from_millis(500);
const POLL_SLICE: Duration = Duration::from_millis(25);
/// Result of a bounded shell execution.
#[derive(Clone, PartialEq, Eq, Debug, serde::Serialize, serde::Deserialize)]
pub struct BashResult {
/// Exit status; `None` when killed by timeout, cancellation, or signal.
pub exit_code: Option<i32>,
/// Stdout, capped with the fitting prefix retained.
pub stdout: String,
/// Stderr, capped with the fitting prefix retained.
pub stderr: String,
/// Cancellation was requested.
pub cancelled: bool,
/// The deadline elapsed and the process tree was killed.
pub timed_out: bool,
/// Wall-clock duration in ms.
pub duration_ms: u64,
}
/// Run `cmd` under `bash -c` in `workdir` with a hard deadline, per-stream
/// output caps, and a shared cancellation handle.
///
/// # Errors
///
/// Returns [`SmithError::Tool`] when the process cannot be spawned.
pub fn execute(
cmd: &str,
workdir: Option<&str>,
timeout_ms: u64,
max_output_bytes: usize,
cancel: &CancelHandle,
) -> Result<BashResult> {
let started = Instant::now();
let deadline = started + Duration::from_millis(timeout_ms.max(1));
let mut child = spawn(cmd, workdir)?;
let (tx, rx) = mpsc::channel::<(Stream, Vec<u8>)>();
let stdout_remaining = Arc::new(AtomicUsize::new(max_output_bytes));
let stderr_remaining = Arc::new(AtomicUsize::new(max_output_bytes));
let handles = drain_pipes(
&mut child,
&tx,
Arc::clone(&stdout_remaining),
Arc::clone(&stderr_remaining),
);
drop(tx); // reader threads hold the only senders
let mut stdout: Vec<u8> = Vec::new();
let mut stderr: Vec<u8> = Vec::new();
let mut status: Option<ExitStatus> = None;
let mut cancelled = false;
let mut timed_out = false;
while status.is_none() {
if cancel.is_cancelled() {
cancelled = true;
kill_tree(&mut child);
status = child.wait().ok();
break;
}
let now = Instant::now();
if now >= deadline {
timed_out = true;
kill_tree(&mut child);
status = child.wait().ok();
break;
}
let wait = POLL_SLICE.min(deadline - now);
match rx.recv_timeout(wait) {
Ok((stream, chunk)) => match stream {
Stream::Stdout => stdout.extend_from_slice(&chunk),
Stream::Stderr => stderr.extend_from_slice(&chunk),
},
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => {
// Both pipes closed: reap without blocking past the deadline.
while status.is_none() && Instant::now() < deadline {
if let Ok(Some(st)) = child.try_wait() {
status = Some(st);
}
}
if status.is_none()
&& let Ok(Some(st)) = child.try_wait()
{
status = Some(st);
}
}
}
if status.is_none()
&& let Ok(Some(st)) = child.try_wait()
{
status = Some(st);
break;
}
}
// Bounded post-exit drain: retain late output until pipes close or the
// grace window expires. Threads only ever send capped prefixes.
let grace_end = Instant::now() + GRACE_DRAIN;
while Instant::now() < grace_end {
match rx.recv_timeout(Duration::from_millis(50)) {
Ok((stream, chunk)) => match stream {
Stream::Stdout => stdout.extend_from_slice(&chunk),
Stream::Stderr => stderr.extend_from_slice(&chunk),
},
Err(RecvTimeoutError::Timeout) => {}
Err(RecvTimeoutError::Disconnected) => break,
}
}
for handle in handles {
let _ = handle.join();
}
Ok(BashResult {
exit_code: status.as_ref().and_then(ExitStatus::code),
stdout: String::from_utf8_lossy(&stdout).into_owned(),
stderr: String::from_utf8_lossy(&stderr).into_owned(),
cancelled,
timed_out,
duration_ms: u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX),
})
}
#[derive(Clone, Copy)]
enum Stream {
Stdout,
Stderr,
}
fn spawn(cmd: &str, workdir: Option<&str>) -> Result<Child> {
let mut command = Command::new("bash");
command
.arg("-c")
.arg(cmd)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
if let Some(dir) = workdir {
command.current_dir(dir);
}
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
// Own the process tree: the child becomes a group leader so the
// deadline path can signal every descendant.
command.process_group(0);
}
command.spawn().map_err(|e| SmithError::Tool {
code: "BASH_SPAWN".to_string(),
message: e.to_string(),
})
}
/// Kill the whole owned process group where the platform supports it,
/// falling back to the direct child.
fn kill_tree(child: &mut Child) {
#[cfg(unix)]
{
use nix::sys::signal::{Signal, killpg};
use nix::unistd::Pid;
let pgid = Pid::from_raw(i32::try_from(child.id()).unwrap_or(i32::MAX));
let _ = killpg(pgid, Signal::SIGKILL);
}
let _ = child.kill();
}
/// Spawn one reader thread per pipe. Each thread forwards capped prefixes
/// (never more than `remaining` permits) and keeps draining to EOF so a
/// chatty descendant can never deadlock the parent.
fn drain_pipes(
child: &mut Child,
tx: &mpsc::Sender<(Stream, Vec<u8>)>,
stdout_remaining: Arc<AtomicUsize>,
stderr_remaining: Arc<AtomicUsize>,
) -> Vec<std::thread::JoinHandle<()>> {
let mut handles = Vec::new();
if let Some(out) = child.stdout.take() {
handles.push(spawn_reader(
out,
tx.clone(),
Stream::Stdout,
stdout_remaining,
));
}
if let Some(err) = child.stderr.take() {
handles.push(spawn_reader(
err,
tx.clone(),
Stream::Stderr,
stderr_remaining,
));
}
handles
}
/// Forward capped prefixes from one pipe until it closes.
fn spawn_reader<R: Read + Send + 'static>(
mut pipe: R,
tx: mpsc::Sender<(Stream, Vec<u8>)>,
stream: Stream,
remaining: Arc<AtomicUsize>,
) -> std::thread::JoinHandle<()> {
std::thread::spawn(move || {
let mut buf = vec![0u8; READ_CHUNK];
loop {
match pipe.read(&mut buf) {
// End of pipe or a read failure both end this reader.
Ok(0) | Err(_) => break,
Ok(n) => {
let keep = n.min(remaining.load(Ordering::Relaxed));
if keep > 0 {
if tx.send((stream, buf[..keep].to_vec())).is_err() {
break;
}
remaining.fetch_sub(keep, Ordering::Relaxed);
}
// Beyond the cap we keep reading (without retaining) so
// the pipe never back-pressures the child indefinitely.
}
}
}
})
}
#[cfg(test)]
#[cfg(unix)]
#[expect(
clippy::unwrap_used,
reason = "tests may panic on invariant violations"
)]
mod tests {
use super::*;
use crate::process_signal::{ProcessSignal, closed};
use std::thread;
fn run(cmd: &str, timeout_ms: u64, cap: usize) -> BashResult {
execute(cmd, None, timeout_ms, cap, &CancelHandle::new()).unwrap()
}
#[test]
fn completes_and_captures_output() {
let res = run("printf 'hello'", 5_000, 1024);
assert_eq!(res.exit_code, Some(0));
assert_eq!(res.stdout, "hello");
assert!(!res.timed_out && !res.cancelled);
}
#[test]
fn timeout_kills_silent_child_promptly() {
let res = run("sleep 30", 400, 1024);
assert!(res.timed_out);
assert_eq!(res.exit_code, None);
// keep-with-deadline: time is the contract; wide margin over the 400ms timeout.
assert!(res.duration_ms < 2_000, "took {}ms", res.duration_ms);
}
#[test]
fn stderr_heavy_child_cannot_deadlock_the_deadline() {
let res = run("while true; do echo noise >&2; done", 400, 4096);
assert!(res.timed_out);
// keep-with-deadline: time is the contract; wide margin over the 400ms timeout.
assert!(res.duration_ms < 2_000, "took {}ms", res.duration_ms);
}
#[test]
fn cancellation_stops_execution() {
let cancel = CancelHandle::new();
let signal = ProcessSignal::new();
let script = format!("{}; sleep 30", signal.raise());
let running = {
let cancel = cancel.clone();
thread::spawn(move || execute(&script, None, 30_000, 1024, &cancel).unwrap())
};
// synchronize: cancel once the command reports it runs, never after a guessed delay.
let mut socket = signal.wait();
cancel.cancel();
let res = running.join().unwrap();
assert!(res.cancelled && !res.timed_out);
assert!(closed(&mut socket), "cancelled command kept running");
}
#[test]
fn output_cap_keeps_fitting_prefix() {
let res = run("printf 'abcdefghij'", 5_000, 5);
assert_eq!(res.stdout, "abcde");
}
#[test]
fn high_volume_output_is_not_throttled() {
// keep-with-deadline: the command's own timeout is the throughput bound.
let res = run("head -c 300000 /dev/zero | tr '\\0' 'x'", 3_000, 1 << 20);
assert!(
!res.timed_out,
"throughput regression: {}ms",
res.duration_ms
);
assert_eq!(res.stdout.len(), 300_000);
}
#[test]
fn descendant_processes_are_killed_with_the_tree() {
let cancel = CancelHandle::new();
let signal = ProcessSignal::new();
// Only the background descendant holds the connection.
let script = format!("({}; sleep 30) & sleep 30", signal.raise());
let running = {
let cancel = cancel.clone();
thread::spawn(move || execute(&script, None, 30_000, 1024, &cancel).unwrap())
};
// synchronize: kill the tree once the descendant reports it runs.
let mut socket = signal.wait();
cancel.cancel();
assert!(running.join().unwrap().cancelled);
assert!(closed(&mut socket), "descendant survived the tree kill");
}
}