mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
## Why On Unix, a caller that stops draining an output pipe can stall `codex exec` in a write, preventing it from interrupting the turn and cleaning up running commands. ## What changed Move human-readable output, JSON events, and `--output-last-message` writes to a dedicated thread for local Unix runs. Handle `SIGTERM` alongside `SIGINT`, and bound the time spent waiting for output after an interrupt. Allow local turn cancellation before the server marks the turn active, and exit with status 1 if output is cut short. ## Testing Add regression tests that send `SIGTERM` with JSON stdout or human stderr blocked and check that the running command and its child exit. Also cover interruption while writing the last message to a blocked pipe. GitOrigin-RevId: fd9a3621d340cefc9af589c605596d2b178aaa9f
127 lines
4.7 KiB
Rust
127 lines
4.7 KiB
Rust
#![cfg(not(target_os = "windows"))]
|
|
#![allow(clippy::unwrap_used)]
|
|
|
|
use core_test_support::responses;
|
|
use core_test_support::test_codex_exec::test_codex_exec;
|
|
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn sigterm_stops_the_command_and_child_with_blocked_json_stdout() -> anyhow::Result<()> {
|
|
check_sigterm_cleanup(BlockedPipe::JsonStdout).await
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
#[tokio::test]
|
|
async fn sigterm_stops_the_command_and_child_with_blocked_human_stderr() -> anyhow::Result<()> {
|
|
check_sigterm_cleanup(BlockedPipe::HumanStderr).await
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
enum BlockedPipe {
|
|
JsonStdout,
|
|
HumanStderr,
|
|
}
|
|
|
|
#[cfg(unix)]
|
|
async fn check_sigterm_cleanup(pipe: BlockedPipe) -> anyhow::Result<()> {
|
|
use pretty_assertions::assert_eq;
|
|
use std::process::Command;
|
|
use tokio::io::AsyncReadExt;
|
|
use tokio::time::timeout_at;
|
|
|
|
core_test_support::skip_if_no_network!(Ok(()));
|
|
core_test_support::skip_if_sandbox!(Ok(()));
|
|
let test = test_codex_exec();
|
|
let server = responses::start_mock_server().await;
|
|
let fifo = test.cwd_path().join("ready");
|
|
assert!(Command::new("mkfifo").arg(&fifo).status()?.success());
|
|
let mut ready = tokio::net::unix::pipe::OpenOptions::new().open_receiver(&fifo)?;
|
|
// The command appears in both the JSON start event and the human log.
|
|
// Keep it larger than a typical pipe but below Linux's 128 KiB argument limit.
|
|
// The FIFO byte signals that sleep has started. EOF requires both processes to exit.
|
|
let padding = "x".repeat(112 * 1024);
|
|
let args = serde_json::json!({
|
|
"cmd": format!("exec > ready; sleep 60 & printf .; wait # {padding}"),
|
|
"shell": "/bin/sh",
|
|
"login": false,
|
|
"yield_time_ms": 60_000,
|
|
});
|
|
responses::mount_sse_once(
|
|
&server,
|
|
responses::sse(vec![
|
|
responses::ev_function_call("wait", "exec_command", &args.to_string()),
|
|
responses::ev_completed("r1"),
|
|
]),
|
|
)
|
|
.await;
|
|
|
|
let mut cmd = test.cmd_with_server(&server);
|
|
#[cfg(target_os = "macos")]
|
|
cmd.args(["--sandbox", "workspace-write"]);
|
|
#[cfg(not(target_os = "macos"))]
|
|
cmd.arg("--dangerously-bypass-approvals-and-sandbox");
|
|
let mut cli = tokio::process::Command::new(cmd.get_program());
|
|
cli.args(cmd.get_args())
|
|
.envs(cmd.get_envs().filter_map(|(k, v)| v.map(|v| (k, v))))
|
|
// Only the event processor should fill the pipe in this test.
|
|
.env("RUST_LOG", "off")
|
|
.current_dir(test.cwd_path())
|
|
.arg("--skip-git-repo-check")
|
|
.stdin(std::process::Stdio::null())
|
|
.kill_on_drop(true);
|
|
match pipe {
|
|
BlockedPipe::JsonStdout => cli.arg("--json").stdout(std::process::Stdio::piped()),
|
|
BlockedPipe::HumanStderr => cli.stderr(std::process::Stdio::piped()),
|
|
};
|
|
let mut cli = cli.arg("wait").spawn()?;
|
|
tokio::select! {
|
|
byte = ready.read_u8() => byte?,
|
|
status = cli.wait() => anyhow::bail!("exec exited before the command started: {status:?}"),
|
|
};
|
|
// Read into the large event, then hold the pipe open without draining it.
|
|
let reader: &mut (dyn tokio::io::AsyncRead + Unpin) = match pipe {
|
|
BlockedPipe::JsonStdout => cli.stdout.as_mut().expect("stdout is piped"),
|
|
BlockedPipe::HumanStderr => cli.stderr.as_mut().expect("stderr is piped"),
|
|
};
|
|
reader.read_exact(&mut [0; 8192]).await?;
|
|
let pid = cli.id().expect("exec is running").to_string();
|
|
assert!(
|
|
Command::new("kill")
|
|
.args(["-TERM", &pid])
|
|
.status()?
|
|
.success()
|
|
);
|
|
let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(30);
|
|
assert_eq!(timeout_at(deadline, cli.wait()).await??.code(), Some(1));
|
|
assert_eq!(timeout_at(deadline, ready.read(&mut [0])).await??, 0);
|
|
Ok(())
|
|
}
|
|
|
|
/// Verify that when the server reports an error, `codex-exec` exits with a
|
|
/// non-zero status code so automation can detect failures.
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn exits_non_zero_when_server_reports_error() -> anyhow::Result<()> {
|
|
let test = test_codex_exec();
|
|
|
|
// Mock a simple Responses API SSE stream that immediately reports a
|
|
// `response.failed` event with an error message.
|
|
let server = responses::start_mock_server().await;
|
|
let body = responses::sse(vec![serde_json::json!({
|
|
"type": "response.failed",
|
|
"response": {
|
|
"id": "resp_err_1",
|
|
"error": {"code": "rate_limit_exceeded", "message": "synthetic server error"}
|
|
}
|
|
})]);
|
|
responses::mount_sse_once(&server, body).await;
|
|
|
|
test.cmd_with_server(&server)
|
|
.arg("--skip-git-repo-check")
|
|
.arg("tell me something")
|
|
.arg("--experimental-json")
|
|
.assert()
|
|
.code(1);
|
|
|
|
Ok(())
|
|
}
|