From ab76bfbe753bfb8fb0f16c12155844035fc03f23 Mon Sep 17 00:00:00 2001 From: Misha Davidov Date: Mon, 4 Aug 2025 15:35:15 -0700 Subject: [PATCH] exec: timeout on grandchildren We were enforcing the 10 s wall-clock limit only on the child process. If that child (bash) spawns grandchildren and we kill it on timeout, those grandchildren still have the original stdout/err pipe open, so the background tasks that are draining the pipes block forever --- codex-rs/core/src/exec.rs | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/codex-rs/core/src/exec.rs b/codex-rs/core/src/exec.rs index dce02cc5e2..c34d84b6ac 100644 --- a/codex-rs/core/src/exec.rs +++ b/codex-rs/core/src/exec.rs @@ -344,8 +344,42 @@ pub(crate) async fn consume_truncated_output( } }; - let stdout = stdout_handle.await??; - let stderr = stderr_handle.await??; + // Wait for the stdout/stderr collection tasks but guard against them + // hanging forever. In the normal case both pipes are closed once the child + // terminates so the tasks exit quickly. However, if the child process + // spawned grandchildren that inherited its stdout/stderr file descriptors + // those pipes may stay open after we `kill` the direct child on timeout. + // That would cause the `read_capped` tasks to block on `read()` + // indefinitely, effectively hanging the whole agent. + + const IO_DRAIN_TIMEOUT_MS: u64 = 2_000; // 2 s should be plenty for local pipes + + // We need mutable bindings so we can `abort()` them on timeout. + use tokio::task::JoinHandle; + + async fn await_with_timeout( + handle: &mut JoinHandle>>, + timeout: Duration, + ) -> std::io::Result> { + tokio::select! { + join_res = &mut *handle => { + match join_res { + Ok(io_res) => io_res, + Err(join_err) => Err(std::io::Error::new(std::io::ErrorKind::Other, join_err)), + } + }, + _ = tokio::time::sleep(timeout) => { + handle.abort(); + Ok(Vec::new()) + } + } + } + + let mut stdout_handle = stdout_handle; + let mut stderr_handle = stderr_handle; + + let stdout = await_with_timeout(&mut stdout_handle, Duration::from_millis(IO_DRAIN_TIMEOUT_MS)).await?; + let stderr = await_with_timeout(&mut stderr_handle, Duration::from_millis(IO_DRAIN_TIMEOUT_MS)).await?; Ok(RawExecToolCallOutput { exit_status,