The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(process): await stopped descendants before cancellation acknowledgement
Steven Enamakelf5ec62f9d202
diff --git a/crates/openhuman-core/src/tools/timeout/group_exit.rs b/crates/openhuman-core/src/tools/timeout/group_exit.rsnew file mode 100644index 0000000000..983a7dfd61--- /dev/null+++ b/crates/openhuman-core/src/tools/timeout/group_exit.rs@@ -0,0 +1,59 @@+//! Wait for signalled Linux process-group members to stop executing.+//!+//! The caller keeps the group leader unreaped during this check, reserving+//! its PID and preventing a new process group from reusing the identifier.++/// Wait until the reserved group contains no executing Linux processes.+#[cfg(target_os = "linux")]+pub(super) async fn wait(pid: u32) -> std::io::Result<()> {+ loop {+ let active = tokio::task::spawn_blocking(move || active_members(pid))+ .await+ .map_err(std::io::Error::other)??;+ if !active {+ return Ok(());+ }+ tokio::time::sleep(std::time::Duration::from_millis(1)).await;+ }+}++/// Other platforms retain their existing direct-child acknowledgement.+#[cfg(not(target_os = "linux"))]+pub(super) async fn wait(_: u32) -> std::io::Result<()> {+ Ok(())+}++/// Inspect kernel process states without reaping the reserved group leader.+#[cfg(target_os = "linux")]+fn active_members(group: u32) -> std::io::Result<bool> {+ for entry in std::fs::read_dir("/proc")? {+ let entry = entry?;+ if entry.file_name().to_string_lossy().parse::<u32>().is_err() {+ continue;+ }+ // Process entries can disappear or become unreadable between+ // enumeration and reading.+ if let Ok(stat) = std::fs::read_to_string(entry.path().join("stat")) {+ if is_active_member(&stat, group) {+ return Ok(true);+ }+ }+ }+ Ok(false)+}++/// Zombies and dead tasks cannot execute further side effects.+#[cfg(target_os = "linux")]+fn is_active_member(stat: &str, group: u32) -> bool {+ let Some((_, fields)) = stat.rsplit_once(") ") else {+ return false;+ };+ let mut fields = fields.split_whitespace();+ let state = fields.next();+ let process_group = fields.nth(1).and_then(|value| value.parse::<u32>().ok());+ process_group == Some(group) && !matches!(state, Some("Z" | "X" | "x"))+}++#[cfg(all(test, target_os = "linux"))]+#[path = "group_exit_tests.rs"]+mod tests;diff --git a/crates/openhuman-core/src/tools/timeout/group_exit_tests.rs b/crates/openhuman-core/src/tools/timeout/group_exit_tests.rsnew file mode 100644index 0000000000..4dd36b59f0--- /dev/null+++ b/crates/openhuman-core/src/tools/timeout/group_exit_tests.rs@@ -0,0 +1,19 @@+use super::*;++#[test]+fn exited_members_do_not_block_cleanup_but_running_members_do() {+ for state in ["R", "S", "D", "T", "I"] {+ assert!(is_active_member(+ &format!("12 (name with ) spaces) {state} 1 42 42"),+ 42+ ));+ }+ for state in ["Z", "X", "x"] {+ assert!(!is_active_member(+ &format!("12 (sleep) {state} 1 42 42"),+ 42+ ));+ }+ assert!(!is_active_member("12 (sleep) R 1 43 43", 42));+ assert!(!is_active_member("malformed", 42));+}diff --git a/crates/openhuman-core/src/tools/timeout/mod.rs b/crates/openhuman-core/src/tools/timeout/mod.rsindex c1378afc32..c689a71972 100644--- a/crates/openhuman-core/src/tools/timeout/mod.rs+++ b/crates/openhuman-core/src/tools/timeout/mod.rs@@ -20,6 +20,7 @@ use tinytools::ToolTimeout;mod command_environment;pub use command_environment::CommandEnvironment;+mod group_exit;mod process_cleanup;pub use process_cleanup::ProcessCleanup;@@ -344,7 +345,18 @@ async fn collect_command_output(_ = async { let _ = cancellation.wait_for(|cancelled| *cancelled).await; } => {group.kill();child.start_kill()?;- child.wait().await?+ // Pipe EOF and the shell's exit can precede a descendant's exit.+ // Keep the leader unreaped while checking the reserved group.+ let stopped = match group.0 {+ Some(pid) => group_exit::wait(pid).await,+ None => Ok(()),+ };+ let status = child.wait().await?;+ // Disarm before propagating a check error after reaping: its PID+ // could now be reused, including while unwinding this function.+ group.0 = None;+ stopped?;+ status}result = child.wait() => result?,};diff --git a/crates/openhuman-embed/tests/process_cancellation.rs b/crates/openhuman-embed/tests/process_cancellation.rsindex 479c9e4214..f5d79a2ed8 100644--- a/crates/openhuman-embed/tests/process_cancellation.rs+++ b/crates/openhuman-embed/tests/process_cancellation.rs@@ -259,3 +259,50 @@ async fn cancellation_reaps_the_leader_when_an_escaped_descendant_holds_its_pipe"escaped descendant blocked cancellation acknowledgement");}++/// Closed output pipes do not prove that a signalled descendant has exited.+#[tokio::test]+async fn cleanup_acknowledgement_waits_for_descendants_that_closed_their_output() {+ for _ in 0..16 {+ let scratch = tempfile::tempdir().unwrap();+ let pidfile = scratch.path().join("closed-output.pid");+ let mut cmd = tokio::process::Command::new("/bin/sh");+ cmd.args(["-c", &format!(+ "pids=''; for i in 1 2 3 4 5 6 7 8; do sleep 30 >/dev/null 2>&1 & pids=\"$pids $!\"; done; echo \"$pids\" > {}; wait", pidfile.display()+ )]);+ let cleanup = ProcessCleanup::default();+ let mut run = Box::pin(cleanup.scope(output_unbounded(&mut cmd)));+ let pids = tokio::time::timeout(Duration::from_secs(5), async {+ loop {+ tokio::select! {+ result = &mut run => panic!("command ended before cancellation: {result:?}"),+ _ = tokio::time::sleep(Duration::from_millis(1)) => {}+ }+ if let Ok(text) = std::fs::read_to_string(&pidfile) {+ let pids: Vec<u32> = text+ .split_whitespace()+ .filter_map(|pid| pid.parse().ok())+ .collect();+ if pids.len() == 8 {+ break pids;+ }+ }+ }+ })+ .await+ .unwrap();+ drop(run);+ tokio::time::timeout(Duration::from_secs(5), cleanup.wait())+ .await+ .unwrap();+ for pid in pids {+ if let Ok(stat) = std::fs::read_to_string(format!("/proc/{pid}/stat")) {+ let (_, fields) = stat.rsplit_once(") ").unwrap();+ assert!(+ fields.starts_with('Z') || fields.starts_with('X'),+ "descendant still active after cleanup acknowledgement: {stat}"+ );+ }+ }+ }+}