use std::fmt;
use std::path::Path;
use std::process::ExitStatus;
use std::time::{Duration, Instant};
use tokio::process::Command;
use tracing::{Instrument, Span, debug, field, info_span};
use crate::Codex;
use crate::error::{Error, OutputStream, Result, ShutdownAction};
pub(crate) fn command_span(name: &'static str, codex: &Codex, args: &[String]) -> Span {
info_span!(
parent: Span::current(),
"codex",
otel.name = name,
subcommand = trace_subcommand(args),
arg_count = args.len(),
working_dir_set = codex.working_dir.is_some(),
outcome = field::Empty,
exit_code = field::Empty,
duration_ms = field::Empty,
)
}
fn trace_subcommand(args: &[String]) -> &'static str {
match args.first().map(String::as_str) {
None => "(none)",
Some("exec") => "exec",
Some("archive") => "archive",
Some("delete") => "delete",
Some("unarchive") => "unarchive",
Some("--version" | "-V") => "version",
Some("review") => "review",
Some("login") => "login",
Some("logout") => "logout",
Some("mcp") => "mcp",
Some("mcp-server") => "mcp-server",
Some("app-server") => "app-server",
Some("completion") => "completion",
Some("sandbox") => "sandbox",
Some("apply") => "apply",
Some("resume") => "resume",
Some("fork") => "fork",
Some("features") => "features",
Some("plugin") => "plugin",
Some("doctor") => "doctor",
Some("update") => "update",
Some(_) => "other",
}
}
pub(crate) struct SpanOutcome {
span: Span,
started: Instant,
settled: bool,
}
impl SpanOutcome {
pub(crate) fn start(span: Span) -> Self {
Self {
span,
started: Instant::now(),
settled: false,
}
}
pub(crate) fn settle(&mut self, outcome: &'static str, exit_code: Option<i32>) {
self.settled = true;
self.span.record("outcome", outcome);
self.span
.record("duration_ms", self.started.elapsed().as_millis() as u64);
if let Some(code) = exit_code {
self.span.record("exit_code", code);
}
}
fn settle_from_ref(&mut self, result: &Result<CommandOutput>) {
self.settle_from(result);
}
fn settle_from(&mut self, result: &Result<CommandOutput>) {
match result {
Ok(output) => self.settle("ok", Some(output.exit_code)),
Err(Error::Timeout { .. }) => self.settle("timeout", None),
Err(Error::CleanupFailed { .. }) => self.settle("cleanup_failed", None),
Err(e) => match e.exit_code() {
Some(code) => self.settle("failed", Some(code)),
None => self.settle("error", None),
},
}
}
}
impl Drop for SpanOutcome {
fn drop(&mut self) {
if !self.settled {
self.settle("cancelled", None);
}
}
}
#[cfg(unix)]
fn own_process_group(cmd: &mut Command, enabled: bool) {
if enabled {
cmd.process_group(0);
}
}
#[cfg(not(unix))]
fn own_process_group(_cmd: &mut Command, _enabled: bool) {}
#[must_use]
pub const fn die_with_parent_supported() -> bool {
cfg!(target_os = "linux")
}
#[cfg(unix)]
fn pdeathsig_hook() -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static {
let parent = std::process::id();
move || {
#[cfg(target_os = "linux")]
{
unsafe {
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
return Err(std::io::Error::last_os_error());
}
if libc::getppid() as u32 != parent {
libc::_exit(1);
}
}
}
#[cfg(not(target_os = "linux"))]
{
let _ = parent;
}
Ok(())
}
}
fn apply_die_with_parent(cmd: &mut Command, enabled: bool) {
#[cfg(unix)]
if enabled {
unsafe {
cmd.pre_exec(pdeathsig_hook());
}
}
#[cfg(not(unix))]
{
let _ = (cmd, enabled);
}
}
pub(crate) fn child_command(binary: &Path, process_group: bool, die_with_parent: bool) -> Command {
let mut cmd = Command::new(binary);
cmd.kill_on_drop(true);
own_process_group(&mut cmd, process_group);
apply_die_with_parent(&mut cmd, die_with_parent);
#[cfg(any(target_os = "macos", target_os = "ios"))]
mark_inherited_fds_close_on_exec(&mut cmd);
cmd
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
fn mark_inherited_fds_close_on_exec(cmd: &mut Command) {
const FD_SCAN_LIMIT: libc::c_int = 65_536;
let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
let end = unsafe {
if libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) == 0 {
limit
.assume_init()
.rlim_cur
.min(FD_SCAN_LIMIT as libc::rlim_t) as libc::c_int
} else {
FD_SCAN_LIMIT
}
};
unsafe {
cmd.pre_exec(move || {
for fd in 3..end {
libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
}
Ok(())
});
}
}
pub(crate) fn arm_and_notify(
process_group: bool,
termination_signal: crate::TerminationSignal,
pid: Option<u32>,
on_spawn: Option<&crate::SpawnObserver>,
) -> GroupKillGuard {
if let (Some(pid), Some(observer)) = (pid, on_spawn) {
observer(crate::SpawnInfo {
pid,
pgid: process_group.then_some(pid),
});
}
GroupKillGuard::new(process_group.then_some(pid).flatten(), termination_signal)
}
#[cfg(unix)]
pub(crate) fn signal_group(pid: u32, signal: i32) -> bool {
let Ok(pid) = i32::try_from(pid) else {
return false;
};
unsafe { libc::kill(-pid, signal) == 0 }
}
#[cfg(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd",
target_os = "illumos",
target_os = "solaris",
))]
fn group_leader_running(pid: u32) -> std::io::Result<bool> {
loop {
let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
let result = unsafe {
libc::waitid(
libc::P_PID,
pid as libc::id_t,
info.as_mut_ptr(),
libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
)
};
if result == 0 {
return Ok(unsafe { info.assume_init().si_pid() } == 0);
}
let error = std::io::Error::last_os_error();
if error.kind() != std::io::ErrorKind::Interrupted {
return Err(error);
}
}
}
#[cfg(all(
unix,
not(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd",
target_os = "illumos",
target_os = "solaris",
))
))]
fn group_leader_running(_pid: u32) -> std::io::Result<bool> {
Ok(true)
}
#[cfg(test)]
mod group_leader_probe_tests {
#[cfg(any(
target_os = "linux",
target_os = "android",
target_vendor = "apple",
target_os = "freebsd",
target_os = "dragonfly",
target_os = "netbsd",
target_os = "openbsd",
target_os = "illumos",
target_os = "solaris",
))]
mod waitid {
use super::super::*;
use std::os::unix::process::ExitStatusExt;
#[tokio::test]
async fn reports_exit_without_reaping() {
let mut child = Command::new("sleep")
.arg("60")
.kill_on_drop(true)
.spawn()
.unwrap();
let pid = child.id().unwrap();
assert!(group_leader_running(pid).unwrap());
child.start_kill().unwrap();
tokio::time::timeout(Duration::from_secs(5), async {
while group_leader_running(pid).unwrap() {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("the probe did not see the child exit");
assert!(!group_leader_running(pid).unwrap());
let status = child
.try_wait()
.unwrap()
.expect("the child is still waitable");
assert_eq!(status.signal(), Some(libc::SIGKILL));
}
#[tokio::test]
async fn disarms_when_the_leader_is_reaped_during_the_grace_period() {
let mut command = Command::new("sleep");
command.arg("60").kill_on_drop(true);
own_process_group(&mut command, true);
let mut child = command.spawn().unwrap();
let mut group = GroupKillGuard::new(child.id(), crate::TerminationSignal::Terminate);
let mut stop = Box::pin(group.terminate(Duration::from_millis(500)));
tokio::select! {
biased;
result = &mut stop => panic!("termination finished before the grace period: {result:?}"),
() = std::future::ready(()) => {}
}
let status = tokio::time::timeout(Duration::from_secs(5), child.wait())
.await
.expect("the leader did not exit")
.unwrap();
assert_eq!(status.signal(), Some(libc::SIGTERM));
let error = stop.await.unwrap_err();
assert_eq!(error.raw_os_error(), Some(libc::ECHILD));
assert!(group.pid.is_none());
}
}
}
pub(crate) struct GroupKillGuard {
pid: Option<u32>,
signal: crate::TerminationSignal,
}
impl GroupKillGuard {
pub(crate) fn new(pid: Option<u32>, signal: crate::TerminationSignal) -> Self {
Self { pid, signal }
}
pub(crate) fn disarm(&mut self) {
self.pid = None;
}
#[cfg(unix)]
fn leader_running(&mut self, pid: u32) -> std::io::Result<bool> {
match group_leader_running(pid) {
Ok(running) => Ok(running),
Err(error) if error.raw_os_error() == Some(libc::ECHILD) => {
self.disarm();
Err(error)
}
Err(_) => Ok(true),
}
}
async fn terminate(
&mut self,
grace: Duration,
) -> std::io::Result<(Option<ShutdownAction>, bool)> {
#[cfg(unix)]
if let Some(pid) = self.pid {
let running = self.leader_running(pid)?;
let soft = (signal_group(pid, self.signal.as_raw()) && running)
.then_some(ShutdownAction::Signal(self.signal));
tokio::time::sleep(grace).await;
let running = self.leader_running(pid)?;
let hard = signal_group(pid, libc::SIGKILL) && running;
self.disarm();
return Ok((soft, hard));
}
#[cfg(not(unix))]
let _ = (self.pid.take(), self.signal, grace);
Ok((None, false))
}
}
impl Drop for GroupKillGuard {
fn drop(&mut self) {
if let Some(pid) = self.pid.take() {
#[cfg(unix)]
signal_group(pid, libc::SIGKILL);
#[cfg(not(unix))]
let _ = pid;
}
}
}
#[derive(Clone)]
pub struct CommandOutput {
pub stdout: String,
pub stderr: String,
pub exit_code: i32,
pub success: bool,
}
const DEBUG_TRUNCATE_LEN: usize = 200;
fn truncate_for_debug(s: &str) -> String {
if s.len() > DEBUG_TRUNCATE_LEN {
format!("{}... ({} bytes total)", &s[..DEBUG_TRUNCATE_LEN], s.len())
} else {
s.to_string()
}
}
impl fmt::Debug for CommandOutput {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CommandOutput")
.field("stdout", &truncate_for_debug(&self.stdout))
.field("stderr", &truncate_for_debug(&self.stderr))
.field("exit_code", &self.exit_code)
.field("success", &self.success)
.finish()
}
}
pub async fn run_codex(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
run_codex_with_retry(codex, args, None).await
}
pub async fn run_codex_with_retry(
codex: &Codex,
args: Vec<String>,
retry_override: Option<&crate::retry::RetryPolicy>,
) -> Result<CommandOutput> {
let policy = retry_override.or(codex.retry_policy.as_ref());
match policy {
Some(policy) => {
let span = info_span!(
"codex.retry",
subcommand = trace_subcommand(&args),
max_attempts = policy.max_attempts,
);
crate::retry::with_retry(policy, || run_codex_once(codex, args.clone()))
.instrument(span)
.await
}
None => run_codex_once(codex, args).await,
}
}
pub(crate) fn assemble_args(codex: &Codex, args: Vec<String>) -> Vec<String> {
let mut command_args = Vec::with_capacity(codex.global_args.len() + args.len());
let protects_rollout_budget = args
.windows(2)
.any(|pair| pair[0] == "-c" && crate::RolloutBudgetConfig::is_config_override(&pair[1]));
let mut global_args = codex.global_args.iter().peekable();
while let Some(arg) = global_args.next() {
if protects_rollout_budget
&& matches!(arg.as_str(), "--enable" | "--disable")
&& global_args
.peek()
.is_some_and(|feature| feature.as_str() == "rollout_budget")
{
global_args.next();
continue;
}
if protects_rollout_budget
&& matches!(
arg.as_str(),
"--enable=rollout_budget" | "--disable=rollout_budget"
)
{
continue;
}
command_args.push(arg.clone());
}
command_args.extend(args);
command_args
}
pub(crate) fn command_string(codex: &Codex, args: Vec<String>) -> String {
let mut out = shell_quote(&codex.binary.display().to_string());
for arg in assemble_args(codex, args) {
out.push(' ');
out.push_str(&shell_quote(&arg));
}
out
}
pub(crate) fn shell_quote(arg: &str) -> String {
if arg.is_empty() {
return "''".to_string();
}
if arg.contains(|c: char| c.is_whitespace() || "\"'$\\`|;<>&()[]{}*?!~#".contains(c)) {
return format!("'{}'", arg.replace('\'', r"'\''"));
}
arg.to_string()
}
async fn run_codex_once(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
let span = command_span("codex.exec", codex, &args);
let outcome_span = span.clone();
let command_args = assemble_args(codex, args);
async move {
debug!(arg_count = command_args.len(), "executing codex command");
let mut outcome = SpanOutcome::start(outcome_span);
let result = match codex.timeout {
Some(timeout) => {
run_internal_inner(
SpawnSpec {
binary: &codex.binary,
args: &command_args,
env: &codex.env,
clear_env: codex.clear_env,
working_dir: codex.working_dir.as_deref(),
stdin_prompt: None,
process_group: codex.process_group,
termination_signal: codex.termination_signal,
output_limit: codex.output_limit,
die_with_parent: codex.die_with_parent,
on_spawn: codex.on_spawn.as_ref(),
},
Some(timeout_stop(timeout)),
codex.termination_grace,
)
.await
}
None => {
run_internal_inner(
SpawnSpec {
binary: &codex.binary,
args: &command_args,
env: &codex.env,
clear_env: codex.clear_env,
working_dir: codex.working_dir.as_deref(),
stdin_prompt: None,
process_group: codex.process_group,
termination_signal: codex.termination_signal,
output_limit: codex.output_limit,
die_with_parent: codex.die_with_parent,
on_spawn: codex.on_spawn.as_ref(),
},
None,
Duration::ZERO,
)
.await
}
};
outcome.settle_from(&result);
result
}
.instrument(span)
.await
}
pub async fn run_codex_cancellable<C>(
codex: &Codex,
args: Vec<String>,
cancel: C,
) -> Result<CommandOutput>
where
C: std::future::Future<Output = ()> + Send,
{
let span = command_span("codex.exec", codex, &args);
let outcome_span = span.clone();
let command_args = assemble_args(codex, args);
async move {
debug!(
arg_count = command_args.len(),
"executing cancellable codex command"
);
let mut outcome = SpanOutcome::start(outcome_span);
let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
let result = run_internal_inner(
SpawnSpec {
binary: &codex.binary,
args: &command_args,
env: &codex.env,
clear_env: codex.clear_env,
working_dir: codex.working_dir.as_deref(),
stdin_prompt: None,
process_group: codex.process_group,
termination_signal: codex.termination_signal,
output_limit: codex.output_limit,
die_with_parent: codex.die_with_parent,
on_spawn: codex.on_spawn.as_ref(),
},
Some(stop),
codex.termination_grace,
)
.await;
match &result {
Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
other => outcome.settle_from_ref(other),
}
result
}
.instrument(span)
.await
}
pub async fn run_codex_allow_exit_codes(
codex: &Codex,
args: Vec<String>,
allowed_codes: &[i32],
) -> Result<CommandOutput> {
let output = run_codex(codex, args).await;
match output {
Err(e)
if e.exit_code()
.is_some_and(|code| allowed_codes.contains(&code)) =>
{
let exit_code = e.exit_code().unwrap_or(-1);
let (stdout, stderr) = match &e {
Error::CommandFailed { stdout, stderr, .. } => (stdout.clone(), stderr.clone()),
Error::Auth { message, .. }
| Error::Config { message, .. }
| Error::NotTrustedDirectory { message, .. }
| Error::SessionNotFound { message, .. } => (String::new(), message.clone()),
_ => (String::new(), String::new()),
};
Ok(CommandOutput {
stdout,
stderr,
exit_code,
success: false,
})
}
other => other,
}
}
pub async fn run_codex_with_stdin_prompt(
codex: &Codex,
args: Vec<String>,
prompt: &str,
) -> Result<CommandOutput> {
let span = command_span("codex.exec", codex, &args);
let outcome_span = span.clone();
let command_args = assemble_args(codex, args);
async move {
debug!(
arg_count = command_args.len(),
prompt_bytes = prompt.len(),
"executing codex command with a stdin prompt"
);
let mut outcome = SpanOutcome::start(outcome_span);
let stop = codex.timeout.map(timeout_stop);
let result = run_internal_inner(
SpawnSpec {
binary: &codex.binary,
args: &command_args,
env: &codex.env,
clear_env: codex.clear_env,
working_dir: codex.working_dir.as_deref(),
stdin_prompt: Some(prompt),
process_group: codex.process_group,
termination_signal: codex.termination_signal,
output_limit: codex.output_limit,
die_with_parent: codex.die_with_parent,
on_spawn: codex.on_spawn.as_ref(),
},
stop,
codex.termination_grace,
)
.await;
outcome.settle_from(&result);
result
}
.instrument(span)
.await
}
pub async fn run_codex_with_stdin_prompt_cancellable<C>(
codex: &Codex,
args: Vec<String>,
prompt: &str,
cancel: C,
) -> Result<CommandOutput>
where
C: std::future::Future<Output = ()> + Send,
{
let span = command_span("codex.exec", codex, &args);
let outcome_span = span.clone();
let command_args = assemble_args(codex, args);
async move {
debug!(
arg_count = command_args.len(),
prompt_bytes = prompt.len(),
"executing cancellable codex command with a stdin prompt"
);
let mut outcome = SpanOutcome::start(outcome_span);
let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
let result = run_internal_inner(
SpawnSpec {
binary: &codex.binary,
args: &command_args,
env: &codex.env,
clear_env: codex.clear_env,
working_dir: codex.working_dir.as_deref(),
stdin_prompt: Some(prompt),
process_group: codex.process_group,
termination_signal: codex.termination_signal,
output_limit: codex.output_limit,
die_with_parent: codex.die_with_parent,
on_spawn: codex.on_spawn.as_ref(),
},
Some(stop),
codex.termination_grace,
)
.await;
match &result {
Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
other => outcome.settle_from_ref(other),
}
result
}
.instrument(span)
.await
}
#[derive(Clone, Copy, Debug)]
enum StopReason {
Cancelled { grace_seconds: u64 },
Timeout { timeout_seconds: u64 },
}
impl StopReason {
fn into_error(self) -> Error {
match self {
Self::Cancelled { grace_seconds } => Error::Cancelled { grace_seconds },
Self::Timeout { timeout_seconds } => Error::Timeout { timeout_seconds },
}
}
}
type StopFuture<'a> = std::pin::Pin<Box<dyn std::future::Future<Output = StopReason> + Send + 'a>>;
fn timeout_stop(timeout: Duration) -> StopFuture<'static> {
Box::pin(async move {
tokio::time::sleep(timeout).await;
StopReason::Timeout {
timeout_seconds: timeout.as_secs(),
}
})
}
fn cancellation_or_timeout<'a, C>(
cancel: C,
timeout: Option<Duration>,
grace: Duration,
) -> StopFuture<'a>
where
C: std::future::Future<Output = ()> + Send + 'a,
{
Box::pin(async move {
match timeout {
Some(timeout) => tokio::select! {
() = cancel => StopReason::Cancelled {
grace_seconds: grace.as_secs(),
},
() = tokio::time::sleep(timeout) => StopReason::Timeout {
timeout_seconds: timeout.as_secs(),
},
},
None => {
cancel.await;
StopReason::Cancelled {
grace_seconds: grace.as_secs(),
}
}
}
})
}
struct SpawnSpec<'a> {
binary: &'a std::path::Path,
args: &'a [String],
env: &'a std::collections::HashMap<String, String>,
clear_env: bool,
working_dir: Option<&'a std::path::Path>,
stdin_prompt: Option<&'a str>,
process_group: bool,
termination_signal: crate::TerminationSignal,
output_limit: Option<usize>,
die_with_parent: bool,
on_spawn: Option<&'a crate::SpawnObserver>,
}
async fn capture<R>(
reader: &mut R,
limit: Option<usize>,
stream: OutputStream,
working_dir: Option<&std::path::Path>,
) -> Result<Vec<u8>>
where
R: tokio::io::AsyncRead + Unpin,
{
use tokio::io::AsyncReadExt;
let io_error = |e: std::io::Error| Error::Io {
message: format!("failed to read codex {stream}: {e}"),
source: e,
working_dir: working_dir.map(std::path::Path::to_path_buf),
};
let Some(limit) = limit else {
let mut bytes = Vec::new();
reader.read_to_end(&mut bytes).await.map_err(io_error)?;
return Ok(bytes);
};
let mut bytes = Vec::new();
let mut chunk = [0u8; CAPTURE_CHUNK];
loop {
let read = reader.read(&mut chunk).await.map_err(io_error)?;
if read == 0 {
return Ok(bytes);
}
if bytes.len() + read > limit {
tracing::warn!(
%stream,
limit_bytes = limit,
captured_bytes = bytes.len(),
"codex output exceeded its capture limit; stopping the run"
);
return Err(Error::OutputLimitExceeded {
stream,
limit_bytes: limit,
});
}
bytes.extend_from_slice(&chunk[..read]);
}
}
const CAPTURE_CHUNK: usize = 8 * 1024;
async fn run_internal_inner(
spec: SpawnSpec<'_>,
stop: Option<StopFuture<'_>>,
grace: Duration,
) -> Result<CommandOutput> {
let SpawnSpec {
binary,
args,
env,
clear_env,
working_dir,
stdin_prompt,
process_group,
termination_signal,
output_limit,
die_with_parent,
on_spawn,
} = spec;
let mut cmd = child_command(binary, process_group, die_with_parent);
cmd.args(args);
if stdin_prompt.is_some() {
cmd.stdin(std::process::Stdio::piped());
} else {
cmd.stdin(std::process::Stdio::null());
}
if let Some(dir) = working_dir {
cmd.current_dir(dir);
}
apply_child_environment(&mut cmd, clear_env, env);
cmd.stdout(std::process::Stdio::piped());
cmd.stderr(std::process::Stdio::piped());
let mut child = cmd.spawn().map_err(|e| Error::Io {
message: format!("failed to spawn codex: {e}"),
source: e,
working_dir: working_dir.map(|p| p.to_path_buf()),
})?;
let mut group = arm_and_notify(process_group, termination_signal, child.id(), on_spawn);
let child_stdin = child.stdin.take();
let mut child_stdout = child.stdout.take().expect("stdout was configured as piped");
let mut child_stderr = child.stderr.take().expect("stderr was configured as piped");
let write = async move {
let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
return Ok(());
};
use tokio::io::AsyncWriteExt;
stdin
.write_all(prompt.as_bytes())
.await
.map_err(|e| Error::Io {
message: format!("failed to write the prompt to codex stdin: {e}"),
source: e,
working_dir: working_dir.map(|p| p.to_path_buf()),
})?;
stdin.shutdown().await.map_err(|e| Error::Io {
message: format!("failed to close codex stdin: {e}"),
source: e,
working_dir: working_dir.map(|p| p.to_path_buf()),
})
};
let read_stdout = async {
capture(
&mut child_stdout,
output_limit,
OutputStream::Stdout,
working_dir,
)
.await
};
let read_stderr = async {
capture(
&mut child_stderr,
output_limit,
OutputStream::Stderr,
working_dir,
)
.await
};
let run = async {
let ((), stdout, stderr) = tokio::try_join!(write, read_stdout, read_stderr)?;
let status = child.wait().await.map_err(|e| wait_error(e, working_dir))?;
Ok::<_, Error>((stdout, stderr, status))
};
let finished = match stop {
None => Ok(run.await),
Some(stop) => tokio::select! {
outcome = run => Ok(outcome),
reason = stop => Err(reason),
},
};
let (stdout, stderr, status) = match finished {
Ok(Ok(finished)) => finished,
Ok(Err(error)) => {
let cleanup = terminate_and_reap_draining(
&mut child,
&mut group,
grace,
working_dir,
&mut child_stdout,
&mut child_stderr,
)
.await;
return Err(Error::after_cleanup(error, cleanup));
}
Err(reason) => {
let cleanup = terminate_and_reap_draining(
&mut child,
&mut group,
grace,
working_dir,
&mut child_stdout,
&mut child_stderr,
)
.await;
return Err(Error::after_cleanup(reason.into_error(), cleanup));
}
};
group.disarm();
let stdout = String::from_utf8_lossy(&stdout).to_string();
let stderr = String::from_utf8_lossy(&stderr).to_string();
let exit_code = status.code().unwrap_or(-1);
if !status.success() {
return Err(Error::from_command_failure(
format!("{} {}", binary.display(), args.join(" ")),
exit_code,
stdout,
stderr,
working_dir.map(|p| p.to_path_buf()),
));
}
Ok(CommandOutput {
stdout,
stderr,
exit_code,
success: true,
})
}
pub(crate) async fn terminate_and_reap_draining<O, E>(
child: &mut tokio::process::Child,
group: &mut GroupKillGuard,
grace: Duration,
working_dir: Option<&std::path::Path>,
stdout: &mut O,
stderr: &mut E,
) -> Result<()>
where
O: tokio::io::AsyncRead + Unpin,
E: tokio::io::AsyncRead + Unpin,
{
let drain = async {
let mut stdout_sink = tokio::io::sink();
let mut stderr_sink = tokio::io::sink();
let _ = tokio::join!(
tokio::io::copy(stdout, &mut stdout_sink),
tokio::io::copy(stderr, &mut stderr_sink),
);
std::future::pending::<()>().await;
};
let result = tokio::select! {
result = terminate_and_reap(child, group, grace) => {
result.map(|_| ()).map_err(|e| wait_error(e, working_dir))
},
() = drain => unreachable!("the drain waits until shutdown finishes"),
};
#[cfg(test)]
let result = result.and_then(|()| injected_cleanup_failure(working_dir));
if result.is_err() {
tracing::warn!("codex cleanup failed; the child may not have been reaped");
}
result
}
#[cfg(test)]
thread_local! {
static INJECT_CLEANUP_FAILURE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[cfg(test)]
#[cfg_attr(not(unix), allow(dead_code))]
pub(crate) struct CleanupFailureInjection(std::marker::PhantomData<std::rc::Rc<()>>);
#[cfg(test)]
#[cfg_attr(not(unix), allow(dead_code))]
impl CleanupFailureInjection {
pub(crate) fn arm() -> Self {
INJECT_CLEANUP_FAILURE.with(|armed| armed.set(true));
Self(std::marker::PhantomData)
}
}
#[cfg(test)]
impl Drop for CleanupFailureInjection {
fn drop(&mut self) {
INJECT_CLEANUP_FAILURE.with(|armed| armed.set(false));
}
}
#[cfg(test)]
fn injected_cleanup_failure(working_dir: Option<&std::path::Path>) -> Result<()> {
if INJECT_CLEANUP_FAILURE.with(std::cell::Cell::get) {
return Err(wait_error(
std::io::Error::other("injected cleanup failure"),
working_dir,
));
}
Ok(())
}
pub(crate) async fn terminate_and_reap(
child: &mut tokio::process::Child,
group: &mut GroupKillGuard,
grace: Duration,
) -> std::io::Result<(ExitStatus, Option<ShutdownAction>)> {
let (soft, mut hard) = group.terminate(grace).await?;
let status = if let Some(status) = child.try_wait()? {
status
} else {
match child.start_kill() {
Ok(()) => hard = true,
Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => {}
Err(error) => return Err(error),
}
child.wait().await?
};
let action = if hard && hard_kill_matches(status) {
Some(ShutdownAction::Kill)
} else {
soft
};
Ok((status, action))
}
pub(crate) fn hard_kill_matches(status: ExitStatus) -> bool {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
status.signal() == Some(libc::SIGKILL)
}
#[cfg(windows)]
{
status.code() == Some(1)
}
#[cfg(not(any(unix, windows)))]
{
let _ = status;
true
}
}
fn wait_error(error: std::io::Error, working_dir: Option<&std::path::Path>) -> Error {
Error::Io {
message: format!("failed to wait on codex: {error}"),
source: error,
working_dir: working_dir.map(|p| p.to_path_buf()),
}
}
pub(crate) fn apply_child_environment(
cmd: &mut Command,
clear_env: bool,
env: &std::collections::HashMap<String, String>,
) {
if clear_env {
cmd.env_clear();
}
cmd.envs(env);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::CodexCommand;
#[test]
fn production_commands_use_child_command() {
fn check_directory(dir: &Path) {
for entry in std::fs::read_dir(dir).unwrap() {
let entry = entry.unwrap();
let path = entry.path();
if entry.file_type().unwrap().is_dir() {
check_directory(&path);
continue;
}
if path.extension().and_then(|ext| ext.to_str()) != Some("rs")
|| entry.file_name() == "test_support.rs"
{
continue;
}
let source = std::fs::read_to_string(&path).unwrap();
let mut test_item = false;
let mut skip_body = false;
for (index, line) in source.lines().enumerate() {
if skip_body {
skip_body = line != "}";
continue;
}
test_item |= line == "#[cfg(test)]" || line.starts_with("#[cfg(all(test,");
if line.is_empty()
|| line.starts_with("#[")
|| line.trim_start().starts_with("//")
{
continue;
}
let shared_constructor = entry.file_name() == "exec.rs"
&& line.starts_with("pub(crate) fn child_command(");
skip_body = (std::mem::take(&mut test_item) || shared_constructor)
&& line.ends_with('{');
if skip_body {
continue;
}
assert!(
line.match_indices("Command::new(").all(|(offset, _)| {
line[..offset].ends_with(|ch: char| ch.is_alphanumeric() || ch == '_')
}),
"{}:{}: use crate::exec::child_command for production spawns",
path.display(),
index + 1
);
}
}
}
check_directory(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"));
}
#[cfg(all(unix, not(target_os = "fuchsia")))]
async fn buffered_descriptor_probe(expected: &str) {
use crate::test_support::{inheritable_pipe_writer, stdin_echo_codex};
use std::os::fd::AsRawFd;
let writer = inheritable_pipe_writer();
let codex = stdin_echo_codex()
.env("CODEX_WRAPPER_TEST_FD", writer.as_raw_fd().to_string())
.build()
.unwrap();
let output = crate::ExecCommand::new("probe")
.execute(&codex)
.await
.unwrap();
assert!(
output.stdout.contains(&format!(r#""text":"{expected}""#)),
"{output:?}"
);
}
#[cfg(any(target_os = "macos", target_os = "ios"))]
#[tokio::test]
async fn buffered_exec_marks_inherited_descriptors_close_on_exec() {
buffered_descriptor_probe("fd-closed").await;
}
#[cfg(all(
unix,
not(any(target_os = "macos", target_os = "ios", target_os = "fuchsia"))
))]
#[tokio::test]
async fn buffered_exec_preserves_inheritable_descriptors() {
buffered_descriptor_probe("fd-open").await;
}
#[cfg(unix)]
#[tokio::test]
async fn spawn_reports_missing_and_non_executable_binaries() {
use std::os::unix::fs::OpenOptionsExt;
let binary = crate::test_support::PidFile::new("unlaunchable-binary");
let codex = Codex::builder().binary(binary.path()).build().unwrap();
for errno in [libc::ENOENT, libc::EACCES] {
if errno == libc::EACCES {
std::fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.open(binary.path())
.unwrap();
}
let error = crate::VersionCommand::new()
.execute(&codex)
.await
.unwrap_err();
assert!(
matches!(&error, Error::Io { message, source, working_dir: None }
if message == &format!("failed to spawn codex: {source}")
&& source.raw_os_error() == Some(errno)),
"expected spawn errno {errno}, got {error:?}"
);
}
}
#[test]
fn typed_rollout_budget_suppresses_conflicting_client_global_toggles() {
let codex = Codex::builder()
.binary("/bin/echo")
.config("features.rollout_budget=false")
.enable("rollout_budget")
.disable("rollout_budget")
.arg("--enable=rollout_budget")
.arg("--disable=rollout_budget")
.arg("--disable")
.arg("rollout_budget")
.enable("keep-enabled")
.disable("keep-disabled")
.build()
.expect("echo must exist");
let budget = crate::RolloutBudgetConfig::builder(10_000)
.build()
.expect("valid budget");
let expected = budget.config_override();
let opening = crate::ExecCommand::new("hi")
.rollout_budget(budget.clone())
.args();
let resumed = crate::ExecResumeCommand::new()
.session_id("thread")
.rollout_budget(budget)
.args();
for args in [opening, resumed] {
let assembled = assemble_args(&codex, args);
assert!(assembled.iter().any(|arg| arg == &expected));
assert!(
!assembled.windows(2).any(|pair| {
matches!(pair[0].as_str(), "--enable" | "--disable")
&& pair[1] == "rollout_budget"
}),
"typed budget must suppress paired client toggles: {assembled:?}"
);
assert!(
!assembled.iter().any(|arg| {
matches!(
arg.as_str(),
"--enable=rollout_budget" | "--disable=rollout_budget"
)
}),
"typed budget must suppress equals-form client toggles: {assembled:?}"
);
assert!(
assembled
.windows(2)
.any(|pair| pair == ["--enable", "keep-enabled"])
);
assert!(
assembled
.windows(2)
.any(|pair| pair == ["--disable", "keep-disabled"])
);
}
}
fn make_output(stdout: &str, stderr: &str) -> CommandOutput {
CommandOutput {
stdout: stdout.to_string(),
stderr: stderr.to_string(),
exit_code: 0,
success: true,
}
}
#[test]
fn shell_quote_leaves_plain_words_alone() {
assert_eq!(shell_quote("exec"), "exec");
assert_eq!(shell_quote("--ephemeral"), "--ephemeral");
assert_eq!(shell_quote("model=gpt-5"), "model=gpt-5");
}
#[test]
fn shell_quote_wraps_anything_a_shell_would_read() {
assert_eq!(shell_quote("fix the tests"), "'fix the tests'");
assert_eq!(shell_quote("$HOME"), "'$HOME'");
assert_eq!(shell_quote("a;b"), "'a;b'");
assert_eq!(shell_quote("*.rs"), "'*.rs'");
assert_eq!(shell_quote("it's"), r"'it'\''s'");
}
#[test]
fn shell_quote_keeps_the_empty_argument_visible() {
assert_eq!(shell_quote(""), "''");
}
#[test]
fn debug_short_output_not_truncated() {
let output = make_output("hello", "world");
let debug = format!("{output:?}");
assert!(debug.contains("hello"));
assert!(debug.contains("world"));
assert!(!debug.contains("bytes total"));
}
#[test]
fn debug_long_output_truncated() {
let long = "x".repeat(300);
let output = make_output(&long, &long);
let debug = format!("{output:?}");
assert!(debug.contains("... (300 bytes total)"));
assert!(!debug.contains(&long));
}
#[cfg(unix)]
#[tokio::test]
async fn child_environment_is_inherited_by_default() {
let capture = crate::test_support::EnvCapture::new("env-default");
let codex = crate::test_support::env_capturing_codex(&capture)
.build()
.expect("bash must exist");
crate::ExecCommand::new("probe")
.execute(&codex)
.await
.unwrap();
let environment = capture.read();
assert_eq!(
environment.get("PATH"),
Some(&std::env::var("PATH").expect("test process must have PATH"))
);
}
#[cfg(unix)]
#[tokio::test]
async fn cleared_environment_reaches_buffered_open_and_resume() {
let capture = crate::test_support::EnvCapture::new("env-buffered");
let opening_client = crate::test_support::env_capturing_codex(&capture)
.clear_env()
.env("CODEX_WRAPPER_EXPLICIT", "opening")
.timeout(Duration::from_secs(2))
.build()
.expect("bash must exist");
crate::ExecCommand::new("probe")
.execute(&opening_client)
.await
.unwrap();
let opening_environment = capture.read();
assert!(!opening_environment.contains_key("PATH"));
assert_eq!(
opening_environment
.get("CODEX_WRAPPER_EXPLICIT")
.map(String::as_str),
Some("opening")
);
assert!(opening_environment.contains_key("CODEX_WRAPPER_ENV_CAPTURE"));
let resume_client = crate::test_support::env_capturing_codex(&capture)
.clear_env()
.env("CODEX_WRAPPER_EXPLICIT", "resume")
.build()
.expect("bash must exist");
crate::ExecResumeCommand::new()
.last()
.execute(&resume_client)
.await
.unwrap();
let resume_environment = capture.read();
assert!(!resume_environment.contains_key("PATH"));
assert_eq!(
resume_environment
.get("CODEX_WRAPPER_EXPLICIT")
.map(String::as_str),
Some("resume")
);
}
#[cfg(unix)]
#[tokio::test]
async fn cleared_environment_reaches_stdin_and_cancellable_runs() {
let capture = crate::test_support::EnvCapture::new("env-specialized");
let codex = crate::test_support::env_capturing_codex(&capture)
.env("CODEX_WRAPPER_EXPLICIT", "specialized")
.clear_env()
.build()
.expect("bash must exist");
crate::ExecCommand::new("stdin prompt")
.prompt_via_stdin()
.execute(&codex)
.await
.unwrap();
let stdin_environment = capture.read();
assert!(!stdin_environment.contains_key("PATH"));
assert_eq!(
stdin_environment
.get("CODEX_WRAPPER_EXPLICIT")
.map(String::as_str),
Some("specialized")
);
let never = std::future::pending::<()>();
run_codex_cancellable(&codex, crate::ExecCommand::new("cancellable").args(), never)
.await
.unwrap();
let cancellable_environment = capture.read();
assert!(!cancellable_environment.contains_key("PATH"));
assert_eq!(
cancellable_environment
.get("CODEX_WRAPPER_EXPLICIT")
.map(String::as_str),
Some("specialized")
);
}
#[cfg(unix)]
#[tokio::test]
async fn environment_values_do_not_leak_into_spawn_errors() {
let secret = "spawn-error-must-not-leak-this";
let codex = Codex::builder()
.binary("/codex-wrapper/this-binary-does-not-exist")
.clear_env()
.env("CODEX_WRAPPER_SECRET", secret)
.build()
.unwrap();
let error = run_codex(&codex, vec!["exec".into()])
.await
.expect_err("the fake path must not spawn");
assert!(!error.to_string().contains(secret));
assert!(!format!("{error:?}").contains(secret));
}
#[cfg(unix)]
#[tokio::test]
async fn timeout_kills_the_spawned_process() {
use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
let pid_file = PidFile::new("exec-timeout");
let codex = blocking_codex(&pid_file)
.timeout(Duration::from_millis(500))
.build()
.expect("bash must exist");
let result = run_codex(&codex, vec!["exec".into(), "probe".into()]).await;
assert!(
matches!(result, Err(Error::Timeout { .. })),
"expected timeout error, got: {result:?}"
);
let pid = pid_file.read_pid().await;
assert!(
!is_running_for_test(pid),
"codex ({pid}) survived the timeout"
);
}
#[cfg(unix)]
#[tokio::test]
async fn cancellation_kills_the_spawned_process() {
use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
let pid_file = PidFile::new("exec-cancel");
let codex = blocking_codex(&pid_file).build().expect("bash must exist");
let cancelled = tokio::time::timeout(
Duration::from_millis(500),
run_codex(&codex, vec!["exec".into(), "probe".into()]),
)
.await;
assert!(
cancelled.is_err(),
"fake codex should still have been running, got: {cancelled:?}"
);
let pid = pid_file.read_pid().await;
assert!(
wait_until_gone(pid).await,
"codex ({pid}) survived the dropped future"
);
}
#[cfg(unix)]
mod recorder {
use std::cell::RefCell;
use std::sync::{Arc, Mutex, Once};
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing::{Event, Metadata, Subscriber};
type Sink = Arc<Mutex<Vec<(String, String)>>>;
thread_local! {
static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
}
struct Global;
impl Global {
fn collect(f: impl FnOnce(&mut Vec<(String, String)>)) {
SINK.with(|sink| {
if let Some(sink) = sink.borrow().as_ref() {
f(&mut sink.lock().unwrap());
}
});
}
}
impl Subscriber for Global {
fn enabled(&self, _: &Metadata<'_>) -> bool {
true
}
fn new_span(&self, attrs: &Attributes<'_>) -> Id {
Self::collect(|fields| attrs.record(&mut Collect(fields)));
Id::from_u64(1)
}
fn record(&self, _: &Id, values: &Record<'_>) {
Self::collect(|fields| values.record(&mut Collect(fields)));
}
fn record_follows_from(&self, _: &Id, _: &Id) {}
fn event(&self, event: &Event<'_>) {
Self::collect(|fields| event.record(&mut Collect(fields)));
}
fn enter(&self, _: &Id) {}
fn exit(&self, _: &Id) {}
}
struct Collect<'a>(&'a mut Vec<(String, String)>);
impl Visit for Collect<'_> {
fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
self.0.push((field.name().into(), format!("{value:?}")));
}
fn record_str(&mut self, field: &Field, value: &str) {
self.0.push((field.name().into(), value.into()));
}
fn record_i64(&mut self, field: &Field, value: i64) {
self.0.push((field.name().into(), value.to_string()));
}
fn record_u64(&mut self, field: &Field, value: u64) {
self.0.push((field.name().into(), value.to_string()));
}
}
pub(super) struct Recorder(Sink);
impl Recorder {
pub(super) fn install() -> Self {
static INIT: Once = Once::new();
INIT.call_once(|| {
let _ = tracing::subscriber::set_global_default(Global);
});
let sink: Sink = Arc::new(Mutex::new(Vec::new()));
SINK.with(|slot| *slot.borrow_mut() = Some(Arc::clone(&sink)));
Self(sink)
}
pub(super) fn dump(&self) -> String {
format!("{:?}", self.0.lock().unwrap())
}
pub(super) fn value(&self, field: &str) -> Option<String> {
self.0
.lock()
.unwrap()
.iter()
.rev()
.find(|(name, _)| name == field)
.map(|(_, value)| value.clone())
}
}
impl Drop for Recorder {
fn drop(&mut self) {
SINK.with(|slot| *slot.borrow_mut() = None);
}
}
}
#[cfg(unix)]
#[tokio::test]
async fn span_records_the_subcommand_and_a_clean_outcome() {
let recorder = recorder::Recorder::install();
let codex = Codex::builder()
.binary("/bin/echo")
.build()
.expect("echo must exist");
run_codex(&codex, vec!["exec".into()]).await.unwrap();
assert_eq!(recorder.value("subcommand").as_deref(), Some("exec"));
assert_eq!(recorder.value("outcome").as_deref(), Some("ok"));
assert_eq!(recorder.value("exit_code").as_deref(), Some("0"));
assert!(recorder.value("duration_ms").is_some());
}
#[cfg(unix)]
#[tokio::test]
async fn span_does_not_carry_the_prompt() {
let recorder = recorder::Recorder::install();
let codex = Codex::builder()
.binary("/bin/echo")
.build()
.expect("echo must exist");
run_codex(&codex, vec!["exec".into(), "a very secret prompt".into()])
.await
.unwrap();
assert!(!recorder.dump().contains("secret"), "{}", recorder.dump());
assert!(recorder.value("binary").is_none());
assert!(recorder.value("working_dir").is_none());
}
#[cfg(unix)]
#[tokio::test]
async fn a_cancelled_run_is_recorded_as_cancelled() {
let recorder = recorder::Recorder::install();
let pid_file = crate::test_support::PidFile::new("span-cancel");
let codex = crate::test_support::blocking_codex(&pid_file)
.build()
.expect("bash must exist");
let cancelled = tokio::time::timeout(
Duration::from_millis(300),
run_codex(&codex, vec!["exec".into()]),
)
.await;
assert!(cancelled.is_err(), "the run should still have been going");
assert_eq!(
recorder.value("outcome").as_deref(),
Some("cancelled"),
"recorded: {}",
recorder.dump()
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_timed_out_run_is_recorded_as_timeout() {
let recorder = recorder::Recorder::install();
let pid_file = crate::test_support::PidFile::new("span-timeout");
let codex = crate::test_support::blocking_codex(&pid_file)
.timeout(Duration::from_millis(300))
.build()
.expect("bash must exist");
let result = run_codex(&codex, vec!["exec".into()]).await;
assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
assert_eq!(recorder.value("outcome").as_deref(), Some("timeout"));
}
#[cfg(unix)]
fn flooding_codex(stream: &str, limit: Option<usize>) -> Codex {
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-floods.sh");
let mut builder = Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap())
.env("CODEX_WRAPPER_TEST_FLOOD_STREAM", stream);
if let Some(max_bytes) = limit {
builder = builder.output_limit(max_bytes);
}
builder.build().expect("bash must exist")
}
#[cfg(unix)]
#[tokio::test]
async fn a_stream_past_the_ceiling_fails_without_carrying_its_bytes() {
for stream in ["stdout", "stderr"] {
let codex = flooding_codex(stream, Some(64 * 1024));
let error = crate::ExecCommand::new("hello")
.execute(&codex)
.await
.expect_err("the flood exceeds the ceiling");
let Error::OutputLimitExceeded {
stream: reported,
limit_bytes,
} = error
else {
panic!("expected OutputLimitExceeded for {stream}, got {error:?}");
};
assert_eq!(reported.to_string(), stream);
assert_eq!(limit_bytes, 64 * 1024);
let error = Error::OutputLimitExceeded {
stream: reported,
limit_bytes,
};
let rendered = format!("{error} {error:?}");
assert!(!rendered.contains("xxxxxxxx"), "{rendered}");
assert!(rendered.len() < 512, "error text grew with the output");
}
}
#[cfg(unix)]
#[tokio::test]
async fn without_a_ceiling_the_whole_flood_is_captured() {
let codex = flooding_codex("stdout", None);
let result = crate::ExecCommand::new("hello")
.execute(&codex)
.await
.expect("an unbounded capture succeeds, however large");
assert_eq!(result.stdout.len(), 128 * 8192);
}
#[cfg(unix)]
#[tokio::test]
async fn output_within_the_ceiling_is_returned_whole() {
let codex = crate::test_support::stdin_echo_codex()
.output_limit(64 * 1024)
.build()
.expect("bash must exist");
let result = crate::ExecCommand::new("a short prompt")
.execute(&codex)
.await
.expect("well under the ceiling");
assert!(
result.stdout.contains("thread.started"),
"{}",
result.stdout
);
assert!(
result.stdout.contains("turn.completed"),
"{}",
result.stdout
);
}
#[cfg(unix)]
fn failing_codex(case: &str) -> Codex {
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-failure.sh");
Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap())
.env("CODEX_WRAPPER_TEST_FAILURE", case)
.build()
.expect("bash must exist")
}
#[cfg(unix)]
#[tokio::test]
async fn a_real_spawn_returns_a_classified_error() {
use crate::error::FailureKind;
for (case, expected) in [
("auth", FailureKind::Auth),
("not-trusted", FailureKind::NotTrustedDirectory),
("config", FailureKind::Config),
("session", FailureKind::SessionNotFound),
("mystery", FailureKind::Unclassified),
] {
let codex = failing_codex(case);
let err = run_codex(&codex, vec!["exec".into()]).await.unwrap_err();
assert_eq!(err.failure_kind(), Some(expected), "case {case}: {err}");
}
}
#[cfg(unix)]
#[tokio::test]
async fn a_classified_failure_is_not_retried() {
let policy = crate::retry::RetryPolicy::new()
.max_attempts(3)
.initial_backoff(Duration::from_millis(1))
.retry_on_exit_codes([1]);
let started = Instant::now();
let codex = failing_codex("auth");
let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
.await
.unwrap_err();
assert!(matches!(err, Error::Auth { .. }), "{err}");
assert!(
started.elapsed() < Duration::from_secs(2),
"looks like it retried: {:?}",
started.elapsed()
);
}
#[cfg(unix)]
#[tokio::test]
async fn an_unclassified_failure_still_retries() {
let policy = crate::retry::RetryPolicy::new()
.max_attempts(2)
.initial_backoff(Duration::from_millis(1))
.retry_on_exit_codes([1]);
let codex = failing_codex("mystery");
let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
.await
.unwrap_err();
assert!(matches!(err, Error::CommandFailed { .. }), "{err}");
}
#[cfg(unix)]
#[tokio::test]
async fn allowed_exit_codes_still_apply_to_a_classified_failure() {
let codex = failing_codex("auth");
let output = run_codex_allow_exit_codes(&codex, vec!["exec".into()], &[1])
.await
.expect("exit code 1 was allowed");
assert_eq!(output.exit_code, 1);
assert!(!output.success);
assert!(
output.stderr.contains("401 Unauthorized"),
"{}",
output.stderr
);
}
#[cfg(unix)]
fn spawning_codex(label: &str) -> (Codex, crate::test_support::PidFile) {
let pid_file = crate::test_support::PidFile::new(label);
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-spawns-child.sh");
let codex = Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap())
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().unwrap(),
)
.build()
.expect("bash must exist");
(codex, pid_file)
}
#[cfg(unix)]
async fn read_pids(pid_file: &crate::test_support::PidFile) -> (u32, u32) {
for _ in 0..200 {
if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
let parse = |prefix: &str| -> Option<u32> {
contents
.lines()
.find_map(|l| l.strip_prefix(prefix))
.and_then(|v| v.trim().parse().ok())
};
if let (Some(parent), Some(child)) = (parse("parent="), parse("child=")) {
return (parent, child);
}
}
tokio::time::sleep(Duration::from_millis(10)).await;
}
panic!("the fake codex never recorded both pids");
}
#[cfg(unix)]
#[tokio::test]
async fn cancelling_kills_the_whole_process_group() {
use crate::test_support::wait_until_gone;
let (codex, pid_file) = spawning_codex("group-drop");
let cancelled = tokio::time::timeout(
Duration::from_millis(400),
run_codex(&codex, vec!["exec".into()]),
)
.await;
assert!(cancelled.is_err(), "the run should still have been going");
let (parent, child) = read_pids(&pid_file).await;
assert!(wait_until_gone(parent).await, "codex ({parent}) survived");
assert!(
wait_until_gone(child).await,
"the subprocess ({child}) survived the cancelled run"
);
}
#[cfg(unix)]
#[tokio::test]
async fn run_codex_cancellable_stops_the_group_gracefully() {
use crate::test_support::is_running_for_test;
let (codex, pid_file) = spawning_codex("group-cancel");
let codex = Codex::builder()
.binary(codex.binary())
.arg(
std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-spawns-child.sh")
.to_str()
.unwrap(),
)
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().unwrap(),
)
.termination_grace(Duration::from_millis(50))
.build()
.unwrap();
let cancel = async {
tokio::time::sleep(Duration::from_millis(300)).await;
};
let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel).await;
assert!(
matches!(result, Err(Error::Cancelled { .. })),
"expected a cancellation, got: {result:?}"
);
let (parent, child) = read_pids(&pid_file).await;
assert!(!is_running_for_test(parent), "codex ({parent}) survived");
assert!(
!is_running_for_test(child),
"the subprocess ({child}) survived cancellation"
);
}
#[cfg(unix)]
#[tokio::test]
async fn dropping_during_cancellation_grace_kills_the_group() {
let fixture = crate::test_support::GracePeriodFixture::new("buffered-cancel-grace-drop");
let codex = fixture.builder().build().unwrap();
fixture
.assert_drop_during_grace(run_codex_cancellable(
&codex,
vec!["exec".into()],
fixture.ready(),
))
.await;
}
#[cfg(unix)]
#[tokio::test]
async fn dropping_during_timeout_grace_kills_the_group() {
let fixture = crate::test_support::GracePeriodFixture::new("buffered-timeout-grace-drop");
let codex = fixture
.builder()
.timeout(Duration::from_secs(2))
.build()
.unwrap();
fixture
.assert_drop_during_grace(run_codex(&codex, vec!["exec".into()]))
.await;
}
#[cfg(unix)]
#[tokio::test]
async fn default_shutdown_still_sends_term_and_drains_both_pipes() {
let fixture = crate::test_support::InterruptFixture::new("default-term-drain");
let codex = fixture.builder().build().unwrap();
let result =
run_codex_cancellable(&codex, vec!["exec".into()], fixture.detached_ready()).await;
assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
assert!(fixture.marker(".term").exists());
assert!(!fixture.marker(".int").exists());
assert!(
fixture.marker(".cleaned").exists(),
"shutdown output blocked cleanup"
);
fixture.assert_stopped().await;
}
#[cfg(unix)]
#[tokio::test]
async fn interrupt_cancellation_drains_large_shutdown_output_and_cleans_detached_tool() {
let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-drain");
let codex = fixture
.builder()
.termination_signal(crate::TerminationSignal::Interrupt)
.output_limit(64)
.build()
.unwrap();
let result = run_codex_with_stdin_prompt_cancellable(
&codex,
vec!["exec".into(), "-".into()],
"prompt",
fixture.detached_ready(),
)
.await;
assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
assert!(fixture.marker(".int").exists());
assert!(!fixture.marker(".term").exists());
assert!(
fixture.marker(".cleaned").exists(),
"shutdown output blocked cleanup"
);
fixture.assert_stopped().await;
}
#[cfg(unix)]
#[tokio::test]
async fn interrupt_timeout_keeps_timeout_error_after_cooperative_exit() {
let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-timeout");
let codex = fixture
.builder()
.termination_signal(crate::TerminationSignal::Interrupt)
.timeout(Duration::from_secs(1))
.build()
.unwrap();
let run = run_codex(&codex, vec!["exec".into()]);
tokio::pin!(run);
tokio::select! {
result = &mut run => panic!("run ended before readiness: {result:?}"),
() = fixture.detached_ready() => {}
}
let result = run.await;
assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
assert!(fixture.marker(".int").exists());
assert!(fixture.marker(".cleaned").exists());
fixture.assert_stopped().await;
}
#[cfg(unix)]
#[tokio::test]
async fn interrupt_ignored_uses_bounded_hard_fallback() {
let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-ignored");
let codex = fixture
.builder()
.env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
.termination_signal(crate::TerminationSignal::Interrupt)
.termination_grace(Duration::from_millis(100))
.build()
.unwrap();
let result = tokio::time::timeout(
Duration::from_secs(3),
run_codex_cancellable(&codex, vec!["exec".into()], fixture.ready()),
)
.await
.expect("hard fallback exceeded the grace budget");
assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
assert!(fixture.marker(".int").exists());
assert!(!fixture.marker(".cleaned").exists());
fixture.assert_stopped().await;
}
#[cfg(unix)]
#[tokio::test]
async fn dropping_during_interrupt_grace_kills_immediately() {
let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-drop");
let codex = fixture
.builder()
.env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
.termination_signal(crate::TerminationSignal::Interrupt)
.termination_grace(Duration::from_secs(30))
.build()
.unwrap();
let mut run = Box::pin(run_codex_cancellable(
&codex,
vec!["exec".into()],
fixture.ready(),
));
tokio::select! {
result = &mut run => panic!("run ended before its grace period: {result:?}"),
() = fixture.wait_for(".int") => {}
}
drop(run);
fixture.assert_stopped().await;
}
#[cfg(unix)]
#[tokio::test]
async fn process_group_optout_skips_interrupt_and_grace() {
let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-optout");
let codex = fixture
.builder()
.process_group(false)
.termination_signal(crate::TerminationSignal::Interrupt)
.termination_grace(Duration::from_secs(30))
.build()
.unwrap();
let result = tokio::time::timeout(
Duration::from_secs(3),
run_codex_cancellable(&codex, vec!["exec".into()], fixture.detached_ready()),
)
.await
.expect("optout must not wait through the grace period");
assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
assert!(!fixture.marker(".int").exists());
assert!(!fixture.marker(".term").exists());
let (parent, child) = fixture.pids().unwrap();
assert!(crate::test_support::wait_until_gone(parent).await);
assert!(crate::test_support::is_running_for_test(child));
}
#[cfg(unix)]
#[tokio::test]
async fn timeout_stops_the_group_before_returning() {
use crate::test_support::is_running_for_test;
let pid_file = crate::test_support::PidFile::new("group-timeout-settled");
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-spawns-child.sh");
let codex = Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap())
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().unwrap(),
)
.timeout(Duration::from_millis(300))
.termination_grace(Duration::from_millis(10))
.build()
.unwrap();
let result = run_codex(&codex, vec!["exec".into()]).await;
assert!(
matches!(result, Err(Error::Timeout { .. })),
"expected a timeout, got: {result:?}"
);
let (parent, child) = read_pids(&pid_file).await;
assert!(!is_running_for_test(parent), "codex ({parent}) survived");
assert!(
!is_running_for_test(child),
"the subprocess ({child}) survived the timeout"
);
}
#[cfg(unix)]
#[tokio::test]
async fn stdin_write_failure_stops_and_reaps_before_returning() {
use crate::test_support::is_running_for_test;
let pid_file = crate::test_support::PidFile::new("stdin-write-failure");
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-closes-stdin-spawns-child.sh");
let codex = Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap())
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().unwrap(),
)
.termination_grace(Duration::from_millis(10))
.build()
.unwrap();
let prompt = "x".repeat(4 * 1024 * 1024);
let result = run_codex_with_stdin_prompt(
&codex,
crate::ExecCommand::from_stdin(&prompt).args(),
&prompt,
)
.await;
assert!(
matches!(result, Err(Error::Io { ref message, .. }) if message.contains("stdin")),
"expected a stdin error, got: {result:?}"
);
let (parent, child) = read_pids(&pid_file).await;
assert!(!is_running_for_test(parent), "codex ({parent}) survived");
assert!(
!is_running_for_test(child),
"the subprocess ({child}) survived the stdin failure"
);
}
#[cfg(unix)]
fn injected_cleanup_reason(result: Result<CommandOutput>) -> Error {
match result {
Err(Error::CleanupFailed { reason, cleanup }) => {
assert!(
cleanup.to_string().contains("injected cleanup failure"),
"{cleanup:?}"
);
*reason
}
other => panic!("expected CleanupFailed, got {other:?}"),
}
}
#[cfg(unix)]
#[tokio::test]
async fn failed_cleanup_after_cancellation_is_not_a_bare_cancel() {
let pid_file = crate::test_support::PidFile::new("cleanup-failed-cancel");
let codex = crate::test_support::blocking_codex(&pid_file)
.termination_grace(Duration::from_millis(10))
.build()
.unwrap();
let cancel_soon = || tokio::time::sleep(Duration::from_millis(100));
let injection = CleanupFailureInjection::arm();
let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel_soon()).await;
let reason = injected_cleanup_reason(result);
assert!(matches!(reason, Error::Cancelled { .. }), "{reason:?}");
drop(injection);
let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel_soon()).await;
assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
}
#[cfg(unix)]
#[tokio::test]
async fn failed_cleanup_after_timeout_is_recorded_and_not_retried() {
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
let recorder = recorder::Recorder::install();
let spawns = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&spawns);
let pid_file = crate::test_support::PidFile::new("cleanup-failed-timeout");
let codex = crate::test_support::blocking_codex(&pid_file)
.timeout(Duration::from_millis(200))
.termination_grace(Duration::from_millis(10))
.on_spawn(Arc::new(move |_| {
counted.fetch_add(1, Ordering::SeqCst);
}))
.build()
.unwrap();
let policy = crate::retry::RetryPolicy::new()
.max_attempts(3)
.initial_backoff(Duration::from_millis(1))
.retry_on_timeout(true);
let _injection = CleanupFailureInjection::arm();
let result = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy)).await;
let reason = injected_cleanup_reason(result);
assert!(matches!(reason, Error::Timeout { .. }), "{reason:?}");
assert_eq!(spawns.load(Ordering::SeqCst), 1, "a timeout was retried");
assert_eq!(
recorder.value("outcome").as_deref(),
Some("cleanup_failed"),
"recorded: {}",
recorder.dump()
);
}
#[cfg(unix)]
#[tokio::test]
async fn failed_cleanup_after_an_output_limit_keeps_the_limit_as_reason() {
let codex = flooding_codex("stdout", Some(64 * 1024));
let injection = CleanupFailureInjection::arm();
let result = run_codex(&codex, vec!["exec".into()]).await;
let reason = injected_cleanup_reason(result);
assert!(
matches!(
reason,
Error::OutputLimitExceeded {
stream: OutputStream::Stdout,
limit_bytes: 65_536,
}
),
"{reason:?}"
);
drop(injection);
let result = run_codex(&codex, vec!["exec".into()]).await;
assert!(
matches!(result, Err(Error::OutputLimitExceeded { .. })),
"{result:?}"
);
}
#[cfg(unix)]
#[tokio::test]
async fn a_run_that_finishes_first_is_not_cancelled() {
let codex = Codex::builder()
.binary("/bin/echo")
.build()
.expect("echo must exist");
let never = std::future::pending::<()>();
let output = run_codex_cancellable(&codex, vec!["exec".into()], never)
.await
.unwrap();
assert!(output.success);
}
#[cfg(unix)]
#[tokio::test]
async fn spawn_observer_reports_each_buffered_child_before_returning() {
use std::sync::{Arc, Mutex};
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&seen);
let codex = Codex::builder()
.binary("/bin/echo")
.on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
.build()
.expect("echo must exist");
let output = run_codex(&codex, vec!["probe".into()]).await.unwrap();
let seen = seen.lock().unwrap();
assert_eq!(seen.len(), 1);
assert!(seen[0].pid > 0);
assert_eq!(seen[0].pgid, Some(seen[0].pid));
assert!(output.stdout.contains("probe"));
}
#[cfg(unix)]
#[tokio::test]
async fn spawn_receipt_never_claims_a_shared_group() {
use std::sync::{Arc, Mutex};
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&seen);
let codex = Codex::builder()
.binary("/bin/echo")
.process_group(false)
.on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
.build()
.expect("echo must exist");
run_codex(&codex, vec!["probe".into()]).await.unwrap();
assert_eq!(seen.lock().unwrap()[0].pgid, None);
}
#[test]
fn parent_death_support_matches_the_target() {
assert_eq!(die_with_parent_supported(), cfg!(target_os = "linux"));
}
#[cfg(unix)]
#[tokio::test]
async fn parent_death_policy_composes_with_spawn_observation() {
use std::sync::{Arc, Mutex};
let seen = Arc::new(Mutex::new(Vec::new()));
let sink = Arc::clone(&seen);
let codex = Codex::builder()
.binary("/bin/echo")
.die_with_parent(true)
.on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
.build()
.expect("echo must exist");
run_codex(&codex, vec!["probe".into()]).await.unwrap();
assert_eq!(seen.lock().unwrap().len(), 1);
}
const PDEATHSIG_HELPER_ENV: &str = "CODEX_WRAPPER_PDEATHSIG_HELPER";
#[test]
fn pdeathsig_helper_process() {
if std::env::var(PDEATHSIG_HELPER_ENV).is_err() {
return;
}
use std::io::Write;
use std::sync::Arc;
let codex = Codex::builder()
.binary("/bin/sleep")
.die_with_parent(true)
.on_spawn(Arc::new(|info| {
println!("PID {}", info.pid);
let _ = std::io::stdout().flush();
}))
.build()
.unwrap();
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let _ = runtime.block_on(run_codex(&codex, vec!["300".into()]));
}
#[cfg(target_os = "linux")]
#[test]
fn child_dies_when_its_parent_is_sigkilled() {
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
let executable = std::env::current_exe().expect("test binary path");
let mut helper = Command::new(executable)
.args([
"--exact",
"exec::tests::pdeathsig_helper_process",
"--nocapture",
])
.env(PDEATHSIG_HELPER_ENV, "1")
.stdout(Stdio::piped())
.spawn()
.expect("spawn helper");
let stdout = helper.stdout.take().expect("piped stdout");
let pid = BufReader::new(stdout)
.lines()
.map_while(std::result::Result::ok)
.find_map(|line| line.strip_prefix("PID ").and_then(|pid| pid.parse().ok()))
.expect("helper reported child pid");
unsafe { libc::kill(helper.id() as i32, libc::SIGKILL) };
let _ = helper.wait();
for _ in 0..50 {
if !crate::test_support::is_running_for_test(pid) {
return;
}
std::thread::sleep(Duration::from_millis(100));
}
panic!("child {pid} survived its SIGKILLed parent");
}
#[cfg(unix)]
#[tokio::test]
async fn opting_out_of_process_groups_leaves_the_subprocess() {
use crate::test_support::wait_until_gone;
let pid_file = crate::test_support::PidFile::new("group-optout");
let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests")
.join("fake-codex-spawns-child.sh");
let codex = Codex::builder()
.binary("/bin/bash")
.arg(script.to_str().unwrap())
.env(
"CODEX_WRAPPER_TEST_PIDFILE",
pid_file.path().to_str().unwrap(),
)
.process_group(false)
.build()
.expect("bash must exist");
let cancelled = tokio::time::timeout(
Duration::from_millis(400),
run_codex(&codex, vec!["exec".into()]),
)
.await;
assert!(cancelled.is_err(), "the run should still have been going");
let (parent, child) = read_pids(&pid_file).await;
assert!(
wait_until_gone(parent).await,
"kill_on_drop still reaps the direct child ({parent})"
);
assert!(
crate::test_support::is_running_for_test(child),
"with groups off, the subprocess ({child}) is expected to survive"
);
signal_group(child, libc::SIGKILL);
unsafe { libc::kill(i32::try_from(child).unwrap_or(0), libc::SIGKILL) };
}
#[cfg(unix)]
struct PrivateTraceDir(std::path::PathBuf);
#[cfg(unix)]
impl Drop for PrivateTraceDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
#[cfg(unix)]
fn private_trace_client(body: &str) -> (PrivateTraceDir, Codex) {
use std::os::unix::fs::symlink;
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let name = format!(
"TRACE_PRIVATE_path-{}-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos(),
NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
);
let dir = PrivateTraceDir(std::env::temp_dir().join(name));
std::fs::create_dir(&dir.0).unwrap();
let binary = dir.0.join("TRACE_PRIVATE_binary");
symlink("/bin/bash", &binary).unwrap();
let script = dir.0.join("TRACE_PRIVATE_script");
std::fs::write(&script, body).unwrap();
let codex = Codex::builder()
.binary(binary)
.arg(script.to_string_lossy())
.arg("TRACE_PRIVATE_config")
.working_dir(&dir.0)
.termination_grace(Duration::ZERO)
.build()
.unwrap();
(dir, codex)
}
#[cfg(unix)]
#[tokio::test]
async fn invocation_traces_exclude_private_content_at_every_level() {
let recorder = recorder::Recorder::install();
let body = concat!(
"cat >/dev/null\n",
"printf 'TRACE_PRIVATE_output'\n",
"printf 'TRACE_PRIVATE_stderr' >&2\n"
);
let (_dir, codex) = private_trace_client(body);
let args = vec![
"exec".into(),
"TRACE_PRIVATE_prompt".into(),
"--resume".into(),
"TRACE_PRIVATE_resume".into(),
];
assert!(
run_codex(&codex, args.clone())
.await
.unwrap()
.stdout
.contains("TRACE_PRIVATE")
);
run_codex_cancellable(&codex, args.clone(), std::future::pending())
.await
.unwrap();
run_codex_with_stdin_prompt(&codex, args.clone(), "TRACE_PRIVATE_stdin")
.await
.unwrap();
run_codex_with_stdin_prompt_cancellable(
&codex,
args,
"TRACE_PRIVATE_stdin",
std::future::pending(),
)
.await
.unwrap();
run_codex(&codex, vec!["TRACE_PRIVATE_unknown_command".into()])
.await
.unwrap();
assert!(
recorder.value("outcome").is_some(),
"subscriber must observe outcomes"
);
assert!(
!recorder.dump().contains("TRACE_PRIVATE"),
"{}",
recorder.dump()
);
assert!(
recorder.value("arg_count").is_some(),
"useful argument count remains available"
);
}
#[cfg(all(unix, feature = "json"))]
#[tokio::test]
async fn stream_and_resume_traces_exclude_private_content() {
use crate::{CodexCommand, ExecCommand, ExecResumeCommand};
let recorder = recorder::Recorder::install();
let body = format!(
"cat >/dev/null\n{}",
include_str!("../tests/fake-codex.sh")
.replace("thread_test", "TRACE_PRIVATE_thread")
.replace("hello", "TRACE_PRIVATE_output")
);
let (_dir, codex) = private_trace_client(&body);
let cmd = ExecCommand::new("TRACE_PRIVATE_prompt");
let mut observed = 0;
crate::streaming::stream_exec(&codex, &cmd, |_| observed += 1)
.await
.unwrap();
crate::streaming::stream_exec_cancellable(&codex, &cmd, std::future::pending(), |_| {})
.await
.unwrap();
let stdin_cmd = ExecCommand::new("TRACE_PRIVATE_stdin").prompt_via_stdin();
crate::streaming::stream_exec(&codex, &stdin_cmd, |_| {})
.await
.unwrap();
let resume = ExecResumeCommand::new()
.session_id("TRACE_PRIVATE_resume")
.prompt("TRACE_PRIVATE_prompt");
crate::streaming::stream_exec_resume(&codex, &resume, |_| {})
.await
.unwrap();
crate::streaming::stream_exec_resume_cancellable(
&codex,
&resume,
std::future::pending(),
|_| {},
)
.await
.unwrap();
assert!(observed > 0, "protocol delivery remains intact");
assert!(
cmd.to_command_string(&codex).contains("TRACE_PRIVATE"),
"explicit preview stays caller-controlled"
);
assert!(
!recorder.dump().contains("TRACE_PRIVATE"),
"{}",
recorder.dump()
);
}
#[cfg(unix)]
#[tokio::test]
async fn failure_and_retry_traces_exclude_rendered_errors_and_output() {
let recorder = recorder::Recorder::install();
let (_dir, mut codex) = private_trace_client(
"printf 'TRACE_PRIVATE_output'; printf 'TRACE_PRIVATE_stderr' >&2; exit 7",
);
codex.retry_policy = Some(
crate::RetryPolicy::new()
.max_attempts(2)
.initial_backoff(Duration::ZERO)
.retry_on_exit_codes([7]),
);
let error = run_codex(&codex, vec!["exec".into(), "TRACE_PRIVATE_prompt".into()])
.await
.unwrap_err();
assert!(
error.to_string().contains("TRACE_PRIVATE"),
"explicit error retains diagnostics"
);
codex.retry_policy = None;
codex.output_limit = Some(8);
assert!(matches!(
run_codex(&codex, vec!["exec".into()]).await,
Err(Error::OutputLimitExceeded { .. })
));
assert!(
!recorder.dump().contains("TRACE_PRIVATE"),
"{}",
recorder.dump()
);
assert!(
recorder.value("attempt").is_some(),
"retry event must be captured"
);
}
#[cfg(all(unix, feature = "app-server"))]
#[tokio::test]
async fn app_server_startup_trace_excludes_private_arguments() {
let recorder = recorder::Recorder::install();
let codex = Codex::builder()
.binary("/bin/false")
.arg("TRACE_PRIVATE_configuration")
.build()
.unwrap();
assert!(
crate::app_server::AppServer::builder(&codex)
.start()
.await
.is_err()
);
assert!(
!recorder.dump().contains("TRACE_PRIVATE"),
"{}",
recorder.dump()
);
assert!(
recorder.value("arg_count").is_some(),
"startup event must be captured"
);
}
#[cfg(unix)]
#[tokio::test]
async fn output_limit_trace_omits_captured_prefix() {
let recorder = recorder::Recorder::install();
let (_dir, mut codex) = private_trace_client(
"printf 'TRACE_PRIVATE_output'; sleep 0.05; head -c 4096 /dev/zero",
);
codex.output_limit = Some(64);
assert!(matches!(
run_codex(&codex, vec!["exec".into()]).await,
Err(Error::OutputLimitExceeded { .. })
));
assert!(
recorder.value("captured_bytes").is_some(),
"capture warning was observed"
);
assert!(
!recorder.dump().contains("TRACE_PRIVATE"),
"{}",
recorder.dump()
);
}
}