Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(tools): kill a timed-out command's whole process group, not just abandon it

killbill9a8626dc26c6
diff --git a/crates/openhuman-core/src/agent/platform_shell.rs b/crates/openhuman-core/src/agent/platform_shell.rs
index 36e804b87e..ab3295c4c1 100644
--- a/crates/openhuman-core/src/agent/platform_shell.rs
+++ b/crates/openhuman-core/src/agent/platform_shell.rs
@@ -174,6 +174,12 @@ fn build_tokio_command_with(command: &str, pipefail: PipeFail) -> tokio::process
// `as_std_mut()` so the Windows arm can reach `raw_arg` (only defined on
// `std::process::Command`); the tokio wrapper forwards the raw arg.
configure_shell_args(cmd.as_std_mut(), command, pipefail);
+ // Every shell-family child leads its own process group and dies with the
+ // handle that owns it, so a deadline (see
+ // `crate::tools::timeout::output_or_kill`) or a cancelled future cannot
+ // leave a pipeline running behind the tool that reported it finished.
+ cmd.kill_on_drop(true);
+ crate::tools::timeout::own_process_group(cmd.as_std_mut());
cmd
}
@@ -183,6 +189,10 @@ fn build_tokio_command_with(command: &str, pipefail: PipeFail) -> tokio::process
pub fn build_std_command(command: &str) -> std::process::Command {
let mut cmd = std::process::Command::new(shell_program());
configure_shell_args(&mut cmd, command, PipeFail::Surface);
+ // Same contract as the tokio builder: the child leads its own process
+ // group so a deadline can reach the whole pipeline (see
+ // `crate::tools::timeout::kill_process_group`).
+ crate::tools::timeout::own_process_group(&mut cmd);
cmd
}
diff --git a/crates/openhuman-core/src/sandbox/ops.rs b/crates/openhuman-core/src/sandbox/ops.rs
index 2ca9b0de42..825fbd0d86 100644
--- a/crates/openhuman-core/src/sandbox/ops.rs
+++ b/crates/openhuman-core/src/sandbox/ops.rs
@@ -284,7 +284,7 @@ async fn execute_unsandboxed(
cmd.env(k, v);
}
- let result = tokio::time::timeout(timeout, cmd.output()).await;
+ let result = crate::tools::timeout::output_or_kill(&mut cmd, timeout).await;
match result {
Ok(Ok(output)) => Ok(SandboxExecResult {
exit_code: output.status.code().unwrap_or(-1),
@@ -451,7 +451,13 @@ async fn execute_local_jail(
}
Ok(None) => {
if start.elapsed() > timeout {
+ // The jailed command is a shell with a
+ // pipeline behind it: signal its whole group,
+ // then the child itself, and reap it so the
+ // timeout report is true of every process.
+ crate::tools::timeout::kill_process_group(child.id());
let _ = child.kill();
+ let _ = child.wait();
return Ok((-1, true));
}
std::thread::sleep(Duration::from_millis(50));
diff --git a/crates/openhuman-core/src/tools/impl/system/install_tool.rs b/crates/openhuman-core/src/tools/impl/system/install_tool.rs
index c8feaf2c91..b2a97422a0 100644
--- a/crates/openhuman-core/src/tools/impl/system/install_tool.rs
+++ b/crates/openhuman-core/src/tools/impl/system/install_tool.rs
@@ -18,7 +18,6 @@ use std::sync::Arc;
use std::time::Duration;
use tinytools::{PermissionLevel, Tool, ToolResult};
use tokio::process::Command as TokioCommand;
-use tokio::time::timeout;
use tinytools_std::detect_tools::find_on_path;
@@ -199,7 +198,12 @@ impl Tool for InstallToolTool {
cmd.args(&prefix).arg(package);
cmd.current_dir(&self.security.workspace_dir);
- let output = match timeout(Duration::from_secs(INSTALL_TIMEOUT_SECS), cmd.output()).await {
+ let output = match crate::tools::timeout::output_or_kill(
+ &mut cmd,
+ Duration::from_secs(INSTALL_TIMEOUT_SECS),
+ )
+ .await
+ {
Ok(Ok(out)) => out,
Ok(Err(e)) => {
return Ok(ToolResult::error(format!(
diff --git a/crates/openhuman-core/src/tools/impl/system/node_exec.rs b/crates/openhuman-core/src/tools/impl/system/node_exec.rs
index 22c1f743aa..4de77a566f 100644
--- a/crates/openhuman-core/src/tools/impl/system/node_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/node_exec.rs
@@ -331,7 +331,7 @@ impl NodeExecTool {
// Bounded only when the caller asked for a deadline; otherwise run to
// completion (no harness/tool timeout on long scripts).
let result = match explicit_timeout {
- Some(timeout) => tokio::time::timeout(timeout, cmd.output()).await,
+ Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,
None => Ok(cmd.output().await),
};
diff --git a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs b/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
index c2eb43ccfd..8db736f22d 100644
--- a/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/npm_exec.rs
@@ -323,7 +323,7 @@ impl NpmExecTool {
// Bounded only when the caller asked for a deadline; otherwise run to
// completion (no harness/tool timeout on long installs/builds).
let result = match explicit_timeout {
- Some(timeout) => tokio::time::timeout(timeout, cmd.output()).await,
+ Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,
None => Ok(cmd.output().await),
};
diff --git a/crates/openhuman-core/src/tools/impl/system/python_exec.rs b/crates/openhuman-core/src/tools/impl/system/python_exec.rs
index bb3bc01130..d78261a606 100644
--- a/crates/openhuman-core/src/tools/impl/system/python_exec.rs
+++ b/crates/openhuman-core/src/tools/impl/system/python_exec.rs
@@ -306,7 +306,7 @@ impl PythonExecTool {
}
let result = match explicit_timeout {
- Some(timeout) => tokio::time::timeout(timeout, cmd.output()).await,
+ Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,
None => Ok(cmd.output().await),
};
diff --git a/crates/openhuman-core/src/tools/impl/system/shell.rs b/crates/openhuman-core/src/tools/impl/system/shell.rs
index d27ff62155..0c33925775 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell.rs
@@ -437,7 +437,7 @@ impl ShellTool {
if explicit_timeout.is_some() { "explicit" } else { "no" }
);
let result = match explicit_timeout {
- Some(timeout) => tokio::time::timeout(timeout, cmd.output()).await,
+ Some(timeout) => crate::tools::timeout::output_or_kill(&mut cmd, timeout).await,
None => Ok(cmd.output().await),
};
diff --git a/crates/openhuman-core/src/tools/impl/system/shell_tests_timeout_tests.rs b/crates/openhuman-core/src/tools/impl/system/shell_tests_timeout_tests.rs
index df5d249931..87bb0e6713 100644
--- a/crates/openhuman-core/src/tools/impl/system/shell_tests_timeout_tests.rs
+++ b/crates/openhuman-core/src/tools/impl/system/shell_tests_timeout_tests.rs
@@ -63,3 +63,51 @@ async fn the_tools_own_deadline_says_it_was_timeout_secs() {
"tool timeout not attributed: {out}"
);
}
+
+/// "timed out … and was killed" has to be true of the whole pipeline, not just
+/// the shell: the model acts on that message, and a survivor keeps consuming
+/// the container the model is still working in.
+#[cfg(not(windows))]
+#[tokio::test]
+async fn the_tools_deadline_kills_the_commands_grandchildren_too() {
+ let dir = std::env::temp_dir().join(format!("oh-shell-pgkill-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let pidfile = dir.join("grandchild.pid");
+ let tool = ShellTool::new(
+ test_security(AutonomyLevel::Full),
+ test_runtime(),
+ test_audit(),
+ );
+ let result = tool
+ .execute(json!({
+ "command": format!("sleep 30 & echo $! > {}; wait", pidfile.display()),
+ "timeout_secs": 1
+ }))
+ .await
+ .unwrap();
+ assert!(result.is_error);
+ assert!(
+ result.output().contains("timed out after 1s"),
+ "{}",
+ result.output()
+ );
+
+ let grandchild: i32 = std::fs::read_to_string(&pidfile)
+ .expect("the shell wrote its background child's pid before the deadline")
+ .trim()
+ .parse()
+ .unwrap();
+ let mut gone = false;
+ for _ in 0..100 {
+ if unsafe { libc::kill(grandchild, 0) } != 0 {
+ gone = true;
+ break;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(
+ gone,
+ "grandchild {grandchild} survived the shell tool's deadline"
+ );
+}
diff --git a/crates/openhuman-core/src/tools/timeout/mod.rs b/crates/openhuman-core/src/tools/timeout/mod.rs
index d796bdc595..d5727a125a 100644
--- a/crates/openhuman-core/src/tools/timeout/mod.rs
+++ b/crates/openhuman-core/src/tools/timeout/mod.rs
@@ -174,6 +174,82 @@ const TOOL_TIMEOUT_GRACE_SECS: u64 = 5;
/// Pure core of [`resolve_tool_deadline`]: the inherited timeout is a parameter
/// so tests can table-drive it without touching the process-global.
+/// Run `cmd` to completion with its output captured, or kill it -- and every
+/// process it started -- when `deadline` passes.
+///
+/// `tokio::time::timeout(deadline, cmd.output())` only abandons the future.
+/// Without `kill_on_drop` the child is not even signalled, and a shell's
+/// pipeline (`grep -r … | head`) is a set of grandchildren that no kill of the
+/// direct child reaches anyway. One `grep -rl … /` the shell tool had reported
+/// as "timed out after 600s and was killed" ran on for half an hour at a full
+/// core inside a two-CPU container, starving the agent that had started it.
+///
+/// So the child is spawned as the leader of its own process group and the
+/// whole group is signalled when the deadline fires. The result has the same
+/// shape as `timeout(deadline, cmd.output())`, so a caller's match arms do not
+/// change. Stdio is set the way `output()` sets it: stdin closed, both output
+/// streams captured.
+pub async fn output_or_kill(
+ cmd: &mut tokio::process::Command,
+ deadline: Duration,
+) -> Result<std::io::Result<std::process::Output>, tokio::time::error::Elapsed> {
+ use std::process::Stdio;
+ cmd.stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .kill_on_drop(true);
+ own_process_group(cmd.as_std_mut());
+ let child = match cmd.spawn() {
+ Ok(child) => child,
+ Err(error) => return Ok(Err(error)),
+ };
+ let pid = child.id();
+ match tokio::time::timeout(deadline, child.wait_with_output()).await {
+ Ok(output) => Ok(output),
+ Err(elapsed) => {
+ if let Some(pid) = pid {
+ kill_process_group(pid);
+ }
+ Err(elapsed)
+ }
+ }
+}
+
+/// Make `cmd` the leader of a new process group when it is spawned, so that
+/// [`kill_process_group`] can reach everything it starts. A no-op off Unix.
+pub fn own_process_group(cmd: &mut std::process::Command) {
+ #[cfg(unix)]
+ {
+ use std::os::unix::process::CommandExt;
+ cmd.process_group(0);
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = cmd;
+ }
+}
+
+/// Send SIGKILL to the process group led by `pid` -- a child spawned via
+/// [`own_process_group`] and everything it started. Off Unix the direct child
+/// is what `kill_on_drop` reaches and no group exists to signal.
+pub fn kill_process_group(pid: u32) {
+ #[cfg(unix)]
+ {
+ let Ok(pid) = i32::try_from(pid) else {
+ return;
+ };
+ // SAFETY: a signal to a process group this process created; the kernel
+ // validates the target, and a negative pid addresses the group.
+ unsafe {
+ libc::kill(-pid, libc::SIGKILL);
+ }
+ }
+ #[cfg(not(unix))]
+ {
+ let _ = pid;
+ }
+}
+
#[cfg(test)]
fn resolve_tool_deadline_with(policy: ToolTimeout, inherited_secs: u64) -> (Option<Duration>, u64) {
resolve_with(&build_settings(inherited_secs), policy)
diff --git a/crates/openhuman-core/src/tools/timeout/mod_tests.rs b/crates/openhuman-core/src/tools/timeout/mod_tests.rs
index 256835b63a..149bc4f07d 100644
--- a/crates/openhuman-core/src/tools/timeout/mod_tests.rs
+++ b/crates/openhuman-core/src/tools/timeout/mod_tests.rs
@@ -184,3 +184,77 @@ fn resolve_effective_table() {
);
}
}
+
+/// The deadline must take the command's whole process group with it. A shell
+/// pipeline is grandchildren of the tool's child, and a `grep -rl … /` the tool
+/// had reported as killed ran on for half an hour at a full core.
+#[cfg(unix)]
+#[tokio::test]
+async fn a_timed_out_command_takes_its_whole_process_group_with_it() {
+ let dir = std::env::temp_dir().join(format!("oh-pgkill-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let pidfile = dir.join("grandchild.pid");
+ // `sleep 30 &` is a grandchild in the shell's own process group; `wait`
+ // keeps the shell alive past the deadline.
+ let mut cmd = crate::agent::platform_shell::build_tokio_command(&format!(
+ "sleep 30 & echo $! > {}; wait",
+ pidfile.display()
+ ));
+ let result = output_or_kill(&mut cmd, Duration::from_millis(700)).await;
+ assert!(result.is_err(), "the deadline must fire on a 30s sleep");
+
+ let grandchild: i32 = loop {
+ if let Ok(text) = std::fs::read_to_string(&pidfile) {
+ if let Ok(pid) = text.trim().parse() {
+ break pid;
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ };
+ let mut gone = false;
+ for _ in 0..100 {
+ // kill(pid, 0) succeeds while the process (or its zombie) exists.
+ if unsafe { libc::kill(grandchild, 0) } != 0 {
+ gone = true;
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(gone, "grandchild {grandchild} survived the deadline");
+}
+
+/// Without a deadline the child still dies with the handle: a cancelled tool
+/// future must not leave the command running either.
+#[cfg(unix)]
+#[tokio::test]
+async fn a_shell_family_child_dies_with_a_dropped_future() {
+ let dir = std::env::temp_dir().join(format!("oh-dropkill-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let pidfile = dir.join("child.pid");
+ let mut cmd = crate::agent::platform_shell::build_tokio_command(&format!(
+ "echo $$ > {}; sleep 30",
+ pidfile.display()
+ ));
+ // `timeout` takes the future by value and drops it when the deadline
+ // passes -- exactly the abandoned-future path a cancelled tool call takes.
+ let _ = tokio::time::timeout(Duration::from_millis(300), cmd.output()).await;
+ let shell: i32 = loop {
+ if let Ok(text) = std::fs::read_to_string(&pidfile) {
+ if let Ok(pid) = text.trim().parse() {
+ break pid;
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ };
+ let mut gone = false;
+ for _ in 0..100 {
+ if unsafe { libc::kill(shell, 0) } != 0 {
+ gone = true;
+ break;
+ }
+ tokio::time::sleep(Duration::from_millis(20)).await;
+ }
+ let _ = std::fs::remove_dir_all(&dir);
+ assert!(gone, "shell {shell} survived its dropped future");
+}