1use std::fmt;
5use std::path::Path;
6use std::process::ExitStatus;
7use std::time::{Duration, Instant};
8
9use tokio::process::Command;
10use tracing::{Instrument, Span, debug, field, info_span};
11
12use crate::Codex;
13use crate::error::{Error, OutputStream, Result, ShutdownAction};
14
15pub(crate) fn command_span(name: &'static str, codex: &Codex, args: &[String]) -> Span {
21 info_span!(
22 parent: Span::current(),
23 "codex",
24 otel.name = name,
25 subcommand = trace_subcommand(args),
26 arg_count = args.len(),
27 working_dir_set = codex.working_dir.is_some(),
28 outcome = field::Empty,
29 exit_code = field::Empty,
30 duration_ms = field::Empty,
31 )
32}
33
34fn trace_subcommand(args: &[String]) -> &'static str {
37 match args.first().map(String::as_str) {
38 None => "(none)",
39 Some("exec") => "exec",
40 Some("archive") => "archive",
41 Some("delete") => "delete",
42 Some("unarchive") => "unarchive",
43 Some("--version" | "-V") => "version",
44 Some("review") => "review",
45 Some("login") => "login",
46 Some("logout") => "logout",
47 Some("mcp") => "mcp",
48 Some("mcp-server") => "mcp-server",
49 Some("app-server") => "app-server",
50 Some("completion") => "completion",
51 Some("sandbox") => "sandbox",
52 Some("apply") => "apply",
53 Some("resume") => "resume",
54 Some("fork") => "fork",
55 Some("features") => "features",
56 Some("plugin") => "plugin",
57 Some("doctor") => "doctor",
58 Some("update") => "update",
59 Some(_) => "other",
60 }
61}
62
63pub(crate) struct SpanOutcome {
73 span: Span,
74 started: Instant,
75 settled: bool,
76}
77
78impl SpanOutcome {
79 pub(crate) fn start(span: Span) -> Self {
80 Self {
81 span,
82 started: Instant::now(),
83 settled: false,
84 }
85 }
86
87 pub(crate) fn settle(&mut self, outcome: &'static str, exit_code: Option<i32>) {
88 self.settled = true;
89 self.span.record("outcome", outcome);
90 self.span
91 .record("duration_ms", self.started.elapsed().as_millis() as u64);
92 if let Some(code) = exit_code {
93 self.span.record("exit_code", code);
94 }
95 }
96
97 fn settle_from_ref(&mut self, result: &Result<CommandOutput>) {
98 self.settle_from(result);
99 }
100
101 fn settle_from(&mut self, result: &Result<CommandOutput>) {
102 match result {
103 Ok(output) => self.settle("ok", Some(output.exit_code)),
104 Err(Error::Timeout { .. }) => self.settle("timeout", None),
105 Err(Error::CleanupFailed { .. }) => self.settle("cleanup_failed", None),
108 Err(e) => match e.exit_code() {
111 Some(code) => self.settle("failed", Some(code)),
112 None => self.settle("error", None),
113 },
114 }
115 }
116}
117
118impl Drop for SpanOutcome {
119 fn drop(&mut self) {
120 if !self.settled {
121 self.settle("cancelled", None);
122 }
123 }
124}
125
126#[cfg(unix)]
130fn own_process_group(cmd: &mut Command, enabled: bool) {
131 if enabled {
132 cmd.process_group(0);
133 }
134}
135
136#[cfg(not(unix))]
137fn own_process_group(_cmd: &mut Command, _enabled: bool) {}
138
139#[must_use]
147pub const fn die_with_parent_supported() -> bool {
148 cfg!(target_os = "linux")
149}
150
151#[cfg(unix)]
158fn pdeathsig_hook() -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static {
159 let parent = std::process::id();
160 move || {
161 #[cfg(target_os = "linux")]
162 {
163 unsafe {
165 if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
166 return Err(std::io::Error::last_os_error());
167 }
168 if libc::getppid() as u32 != parent {
169 libc::_exit(1);
170 }
171 }
172 }
173 #[cfg(not(target_os = "linux"))]
174 {
175 let _ = parent;
176 }
177 Ok(())
178 }
179}
180
181fn apply_die_with_parent(cmd: &mut Command, enabled: bool) {
183 #[cfg(unix)]
184 if enabled {
185 unsafe {
187 cmd.pre_exec(pdeathsig_hook());
188 }
189 }
190 #[cfg(not(unix))]
191 {
192 let _ = (cmd, enabled);
193 }
194}
195
196pub(crate) fn child_command(binary: &Path, process_group: bool, die_with_parent: bool) -> Command {
198 let mut cmd = Command::new(binary);
199 cmd.kill_on_drop(true);
201 own_process_group(&mut cmd, process_group);
202 apply_die_with_parent(&mut cmd, die_with_parent);
203 #[cfg(any(target_os = "macos", target_os = "ios"))]
204 mark_inherited_fds_close_on_exec(&mut cmd);
205 cmd
206}
207
208#[cfg(any(target_os = "macos", target_os = "ios"))]
211fn mark_inherited_fds_close_on_exec(cmd: &mut Command) {
212 const FD_SCAN_LIMIT: libc::c_int = 65_536;
215 let mut limit = std::mem::MaybeUninit::<libc::rlimit>::uninit();
216 let end = unsafe {
218 if libc::getrlimit(libc::RLIMIT_NOFILE, limit.as_mut_ptr()) == 0 {
219 limit
220 .assume_init()
221 .rlim_cur
222 .min(FD_SCAN_LIMIT as libc::rlim_t) as libc::c_int
223 } else {
224 FD_SCAN_LIMIT
225 }
226 };
227
228 unsafe {
231 cmd.pre_exec(move || {
232 for fd in 3..end {
233 libc::fcntl(fd, libc::F_SETFD, libc::FD_CLOEXEC);
235 }
236 Ok(())
237 });
238 }
239}
240
241pub(crate) fn arm_and_notify(
243 process_group: bool,
244 termination_signal: crate::TerminationSignal,
245 pid: Option<u32>,
246 on_spawn: Option<&crate::SpawnObserver>,
247) -> GroupKillGuard {
248 if let (Some(pid), Some(observer)) = (pid, on_spawn) {
249 observer(crate::SpawnInfo {
250 pid,
251 pgid: process_group.then_some(pid),
252 });
253 }
254 GroupKillGuard::new(process_group.then_some(pid).flatten(), termination_signal)
255}
256
257#[cfg(unix)]
265pub(crate) fn signal_group(pid: u32, signal: i32) -> bool {
266 let Ok(pid) = i32::try_from(pid) else {
267 return false;
268 };
269 unsafe { libc::kill(-pid, signal) == 0 }
272}
273
274#[cfg(any(
276 target_os = "linux",
277 target_os = "android",
278 target_vendor = "apple",
279 target_os = "freebsd",
280 target_os = "dragonfly",
281 target_os = "netbsd",
282 target_os = "openbsd",
283 target_os = "illumos",
284 target_os = "solaris",
285))]
286fn group_leader_running(pid: u32) -> std::io::Result<bool> {
287 loop {
288 let mut info = std::mem::MaybeUninit::<libc::siginfo_t>::zeroed();
289 let result = unsafe {
292 libc::waitid(
293 libc::P_PID,
294 pid as libc::id_t,
295 info.as_mut_ptr(),
296 libc::WEXITED | libc::WNOHANG | libc::WNOWAIT,
297 )
298 };
299 if result == 0 {
300 return Ok(unsafe { info.assume_init().si_pid() } == 0);
303 }
304 let error = std::io::Error::last_os_error();
305 if error.kind() != std::io::ErrorKind::Interrupted {
306 return Err(error);
307 }
308 }
309}
310
311#[cfg(all(
312 unix,
313 not(any(
314 target_os = "linux",
315 target_os = "android",
316 target_vendor = "apple",
317 target_os = "freebsd",
318 target_os = "dragonfly",
319 target_os = "netbsd",
320 target_os = "openbsd",
321 target_os = "illumos",
322 target_os = "solaris",
323 ))
324))]
325fn group_leader_running(_pid: u32) -> std::io::Result<bool> {
326 Ok(true)
328}
329
330#[cfg(test)]
331mod group_leader_probe_tests {
332 #[cfg(any(
334 target_os = "linux",
335 target_os = "android",
336 target_vendor = "apple",
337 target_os = "freebsd",
338 target_os = "dragonfly",
339 target_os = "netbsd",
340 target_os = "openbsd",
341 target_os = "illumos",
342 target_os = "solaris",
343 ))]
344 mod waitid {
345 use super::super::*;
346 use std::os::unix::process::ExitStatusExt;
347
348 #[tokio::test]
349 async fn reports_exit_without_reaping() {
350 let mut child = Command::new("sleep")
351 .arg("60")
352 .kill_on_drop(true)
353 .spawn()
354 .unwrap();
355 let pid = child.id().unwrap();
356 assert!(group_leader_running(pid).unwrap());
357
358 child.start_kill().unwrap();
359 tokio::time::timeout(Duration::from_secs(5), async {
360 while group_leader_running(pid).unwrap() {
361 tokio::time::sleep(Duration::from_millis(10)).await;
362 }
363 })
364 .await
365 .expect("the probe did not see the child exit");
366 assert!(!group_leader_running(pid).unwrap());
367
368 let status = child
369 .try_wait()
370 .unwrap()
371 .expect("the child is still waitable");
372 assert_eq!(status.signal(), Some(libc::SIGKILL));
373 }
374
375 #[tokio::test]
376 async fn disarms_when_the_leader_is_reaped_during_the_grace_period() {
377 let mut command = Command::new("sleep");
378 command.arg("60").kill_on_drop(true);
379 own_process_group(&mut command, true);
380 let mut child = command.spawn().unwrap();
381 let mut group = GroupKillGuard::new(child.id(), crate::TerminationSignal::Terminate);
382 let mut stop = Box::pin(group.terminate(Duration::from_millis(500)));
383
384 tokio::select! {
387 biased;
388 result = &mut stop => panic!("termination finished before the grace period: {result:?}"),
389 () = std::future::ready(()) => {}
390 }
391 let status = tokio::time::timeout(Duration::from_secs(5), child.wait())
392 .await
393 .expect("the leader did not exit")
394 .unwrap();
395 assert_eq!(status.signal(), Some(libc::SIGTERM));
396
397 let error = stop.await.unwrap_err();
398 assert_eq!(error.raw_os_error(), Some(libc::ECHILD));
399 assert!(group.pid.is_none());
400 }
401 }
402}
403
404pub(crate) struct GroupKillGuard {
412 pid: Option<u32>,
413 signal: crate::TerminationSignal,
414}
415
416impl GroupKillGuard {
417 pub(crate) fn new(pid: Option<u32>, signal: crate::TerminationSignal) -> Self {
418 Self { pid, signal }
419 }
420
421 pub(crate) fn disarm(&mut self) {
423 self.pid = None;
424 }
425
426 #[cfg(unix)]
427 fn leader_running(&mut self, pid: u32) -> std::io::Result<bool> {
428 match group_leader_running(pid) {
429 Ok(running) => Ok(running),
430 Err(error) if error.raw_os_error() == Some(libc::ECHILD) => {
431 self.disarm();
435 Err(error)
436 }
437 Err(_) => Ok(true),
440 }
441 }
442
443 async fn terminate(
447 &mut self,
448 grace: Duration,
449 ) -> std::io::Result<(Option<ShutdownAction>, bool)> {
450 #[cfg(unix)]
451 if let Some(pid) = self.pid {
452 let running = self.leader_running(pid)?;
453 let soft = (signal_group(pid, self.signal.as_raw()) && running)
454 .then_some(ShutdownAction::Signal(self.signal));
455 tokio::time::sleep(grace).await;
457 let running = self.leader_running(pid)?;
458 let hard = signal_group(pid, libc::SIGKILL) && running;
459 self.disarm();
460 return Ok((soft, hard));
461 }
462 #[cfg(not(unix))]
463 let _ = (self.pid.take(), self.signal, grace);
464 Ok((None, false))
465 }
466}
467
468impl Drop for GroupKillGuard {
469 fn drop(&mut self) {
470 if let Some(pid) = self.pid.take() {
473 #[cfg(unix)]
474 signal_group(pid, libc::SIGKILL);
475 #[cfg(not(unix))]
476 let _ = pid;
477 }
478 }
479}
480
481#[derive(Clone)]
486pub struct CommandOutput {
487 pub stdout: String,
489 pub stderr: String,
491 pub exit_code: i32,
493 pub success: bool,
495}
496
497const DEBUG_TRUNCATE_LEN: usize = 200;
498
499fn truncate_for_debug(s: &str) -> String {
500 if s.len() > DEBUG_TRUNCATE_LEN {
501 format!("{}... ({} bytes total)", &s[..DEBUG_TRUNCATE_LEN], s.len())
502 } else {
503 s.to_string()
504 }
505}
506
507impl fmt::Debug for CommandOutput {
508 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
509 f.debug_struct("CommandOutput")
510 .field("stdout", &truncate_for_debug(&self.stdout))
511 .field("stderr", &truncate_for_debug(&self.stderr))
512 .field("exit_code", &self.exit_code)
513 .field("success", &self.success)
514 .finish()
515 }
516}
517
518pub async fn run_codex(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
524 run_codex_with_retry(codex, args, None).await
525}
526
527pub async fn run_codex_with_retry(
529 codex: &Codex,
530 args: Vec<String>,
531 retry_override: Option<&crate::retry::RetryPolicy>,
532) -> Result<CommandOutput> {
533 let policy = retry_override.or(codex.retry_policy.as_ref());
534
535 match policy {
536 Some(policy) => {
537 let span = info_span!(
540 "codex.retry",
541 subcommand = trace_subcommand(&args),
542 max_attempts = policy.max_attempts,
543 );
544 crate::retry::with_retry(policy, || run_codex_once(codex, args.clone()))
545 .instrument(span)
546 .await
547 }
548 None => run_codex_once(codex, args).await,
549 }
550}
551
552pub(crate) fn assemble_args(codex: &Codex, args: Vec<String>) -> Vec<String> {
560 let mut command_args = Vec::with_capacity(codex.global_args.len() + args.len());
561 let protects_rollout_budget = args
562 .windows(2)
563 .any(|pair| pair[0] == "-c" && crate::RolloutBudgetConfig::is_config_override(&pair[1]));
564 let mut global_args = codex.global_args.iter().peekable();
565 while let Some(arg) = global_args.next() {
566 if protects_rollout_budget
567 && matches!(arg.as_str(), "--enable" | "--disable")
568 && global_args
569 .peek()
570 .is_some_and(|feature| feature.as_str() == "rollout_budget")
571 {
572 global_args.next();
573 continue;
574 }
575 if protects_rollout_budget
576 && matches!(
577 arg.as_str(),
578 "--enable=rollout_budget" | "--disable=rollout_budget"
579 )
580 {
581 continue;
582 }
583 command_args.push(arg.clone());
584 }
585 command_args.extend(args);
586 command_args
587}
588
589pub(crate) fn command_string(codex: &Codex, args: Vec<String>) -> String {
591 let mut out = shell_quote(&codex.binary.display().to_string());
592 for arg in assemble_args(codex, args) {
593 out.push(' ');
594 out.push_str(&shell_quote(&arg));
595 }
596 out
597}
598
599pub(crate) fn shell_quote(arg: &str) -> String {
605 if arg.is_empty() {
606 return "''".to_string();
607 }
608 if arg.contains(|c: char| c.is_whitespace() || "\"'$\\`|;<>&()[]{}*?!~#".contains(c)) {
609 return format!("'{}'", arg.replace('\'', r"'\''"));
610 }
611 arg.to_string()
612}
613
614async fn run_codex_once(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
615 let span = command_span("codex.exec", codex, &args);
616 let outcome_span = span.clone();
617 let command_args = assemble_args(codex, args);
618
619 async move {
620 debug!(arg_count = command_args.len(), "executing codex command");
621
622 let mut outcome = SpanOutcome::start(outcome_span);
623 let result = match codex.timeout {
624 Some(timeout) => {
625 run_internal_inner(
626 SpawnSpec {
627 binary: &codex.binary,
628 args: &command_args,
629 env: &codex.env,
630 clear_env: codex.clear_env,
631 working_dir: codex.working_dir.as_deref(),
632 stdin_prompt: None,
633 process_group: codex.process_group,
634 termination_signal: codex.termination_signal,
635 output_limit: codex.output_limit,
636 die_with_parent: codex.die_with_parent,
637 on_spawn: codex.on_spawn.as_ref(),
638 },
639 Some(timeout_stop(timeout)),
640 codex.termination_grace,
641 )
642 .await
643 }
644 None => {
645 run_internal_inner(
646 SpawnSpec {
647 binary: &codex.binary,
648 args: &command_args,
649 env: &codex.env,
650 clear_env: codex.clear_env,
651 working_dir: codex.working_dir.as_deref(),
652 stdin_prompt: None,
653 process_group: codex.process_group,
654 termination_signal: codex.termination_signal,
655 output_limit: codex.output_limit,
656 die_with_parent: codex.die_with_parent,
657 on_spawn: codex.on_spawn.as_ref(),
658 },
659 None,
660 Duration::ZERO,
661 )
662 .await
663 }
664 };
665 outcome.settle_from(&result);
666 result
667 }
668 .instrument(span)
669 .await
670}
671
672pub async fn run_codex_cancellable<C>(
693 codex: &Codex,
694 args: Vec<String>,
695 cancel: C,
696) -> Result<CommandOutput>
697where
698 C: std::future::Future<Output = ()> + Send,
699{
700 let span = command_span("codex.exec", codex, &args);
701 let outcome_span = span.clone();
702 let command_args = assemble_args(codex, args);
703
704 async move {
705 debug!(
706 arg_count = command_args.len(),
707 "executing cancellable codex command"
708 );
709
710 let mut outcome = SpanOutcome::start(outcome_span);
711 let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
712 let result = run_internal_inner(
713 SpawnSpec {
714 binary: &codex.binary,
715 args: &command_args,
716 env: &codex.env,
717 clear_env: codex.clear_env,
718 working_dir: codex.working_dir.as_deref(),
719 stdin_prompt: None,
720 process_group: codex.process_group,
721 termination_signal: codex.termination_signal,
722 output_limit: codex.output_limit,
723 die_with_parent: codex.die_with_parent,
724 on_spawn: codex.on_spawn.as_ref(),
725 },
726 Some(stop),
727 codex.termination_grace,
728 )
729 .await;
730
731 match &result {
732 Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
733 other => outcome.settle_from_ref(other),
734 }
735 result
736 }
737 .instrument(span)
738 .await
739}
740
741pub async fn run_codex_allow_exit_codes(
743 codex: &Codex,
744 args: Vec<String>,
745 allowed_codes: &[i32],
746) -> Result<CommandOutput> {
747 let output = run_codex(codex, args).await;
748
749 match output {
750 Err(e)
754 if e.exit_code()
755 .is_some_and(|code| allowed_codes.contains(&code)) =>
756 {
757 let exit_code = e.exit_code().unwrap_or(-1);
758 let (stdout, stderr) = match &e {
759 Error::CommandFailed { stdout, stderr, .. } => (stdout.clone(), stderr.clone()),
760 Error::Auth { message, .. }
761 | Error::Config { message, .. }
762 | Error::NotTrustedDirectory { message, .. }
763 | Error::SessionNotFound { message, .. } => (String::new(), message.clone()),
764 _ => (String::new(), String::new()),
765 };
766 Ok(CommandOutput {
767 stdout,
768 stderr,
769 exit_code,
770 success: false,
771 })
772 }
773 other => other,
774 }
775}
776
777pub async fn run_codex_with_stdin_prompt(
789 codex: &Codex,
790 args: Vec<String>,
791 prompt: &str,
792) -> Result<CommandOutput> {
793 let span = command_span("codex.exec", codex, &args);
794 let outcome_span = span.clone();
795 let command_args = assemble_args(codex, args);
796
797 async move {
798 debug!(
799 arg_count = command_args.len(),
800 prompt_bytes = prompt.len(),
801 "executing codex command with a stdin prompt"
802 );
803
804 let mut outcome = SpanOutcome::start(outcome_span);
805 let stop = codex.timeout.map(timeout_stop);
806 let result = run_internal_inner(
807 SpawnSpec {
808 binary: &codex.binary,
809 args: &command_args,
810 env: &codex.env,
811 clear_env: codex.clear_env,
812 working_dir: codex.working_dir.as_deref(),
813 stdin_prompt: Some(prompt),
814 process_group: codex.process_group,
815 termination_signal: codex.termination_signal,
816 output_limit: codex.output_limit,
817 die_with_parent: codex.die_with_parent,
818 on_spawn: codex.on_spawn.as_ref(),
819 },
820 stop,
821 codex.termination_grace,
822 )
823 .await;
824 outcome.settle_from(&result);
825 result
826 }
827 .instrument(span)
828 .await
829}
830
831pub async fn run_codex_with_stdin_prompt_cancellable<C>(
836 codex: &Codex,
837 args: Vec<String>,
838 prompt: &str,
839 cancel: C,
840) -> Result<CommandOutput>
841where
842 C: std::future::Future<Output = ()> + Send,
843{
844 let span = command_span("codex.exec", codex, &args);
845 let outcome_span = span.clone();
846 let command_args = assemble_args(codex, args);
847
848 async move {
849 debug!(
850 arg_count = command_args.len(),
851 prompt_bytes = prompt.len(),
852 "executing cancellable codex command with a stdin prompt"
853 );
854
855 let mut outcome = SpanOutcome::start(outcome_span);
856 let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
857 let result = run_internal_inner(
858 SpawnSpec {
859 binary: &codex.binary,
860 args: &command_args,
861 env: &codex.env,
862 clear_env: codex.clear_env,
863 working_dir: codex.working_dir.as_deref(),
864 stdin_prompt: Some(prompt),
865 process_group: codex.process_group,
866 termination_signal: codex.termination_signal,
867 output_limit: codex.output_limit,
868 die_with_parent: codex.die_with_parent,
869 on_spawn: codex.on_spawn.as_ref(),
870 },
871 Some(stop),
872 codex.termination_grace,
873 )
874 .await;
875
876 match &result {
877 Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
878 other => outcome.settle_from_ref(other),
879 }
880 result
881 }
882 .instrument(span)
883 .await
884}
885
886#[derive(Clone, Copy, Debug)]
887enum StopReason {
888 Cancelled { grace_seconds: u64 },
889 Timeout { timeout_seconds: u64 },
890}
891
892impl StopReason {
893 fn into_error(self) -> Error {
894 match self {
895 Self::Cancelled { grace_seconds } => Error::Cancelled { grace_seconds },
896 Self::Timeout { timeout_seconds } => Error::Timeout { timeout_seconds },
897 }
898 }
899}
900
901type StopFuture<'a> = std::pin::Pin<Box<dyn std::future::Future<Output = StopReason> + Send + 'a>>;
902
903fn timeout_stop(timeout: Duration) -> StopFuture<'static> {
904 Box::pin(async move {
905 tokio::time::sleep(timeout).await;
906 StopReason::Timeout {
907 timeout_seconds: timeout.as_secs(),
908 }
909 })
910}
911
912fn cancellation_or_timeout<'a, C>(
913 cancel: C,
914 timeout: Option<Duration>,
915 grace: Duration,
916) -> StopFuture<'a>
917where
918 C: std::future::Future<Output = ()> + Send + 'a,
919{
920 Box::pin(async move {
921 match timeout {
922 Some(timeout) => tokio::select! {
923 () = cancel => StopReason::Cancelled {
924 grace_seconds: grace.as_secs(),
925 },
926 () = tokio::time::sleep(timeout) => StopReason::Timeout {
927 timeout_seconds: timeout.as_secs(),
928 },
929 },
930 None => {
931 cancel.await;
932 StopReason::Cancelled {
933 grace_seconds: grace.as_secs(),
934 }
935 }
936 }
937 })
938}
939
940struct SpawnSpec<'a> {
942 binary: &'a std::path::Path,
943 args: &'a [String],
944 env: &'a std::collections::HashMap<String, String>,
945 clear_env: bool,
947 working_dir: Option<&'a std::path::Path>,
948 stdin_prompt: Option<&'a str>,
950 process_group: bool,
952 termination_signal: crate::TerminationSignal,
953 output_limit: Option<usize>,
955 die_with_parent: bool,
957 on_spawn: Option<&'a crate::SpawnObserver>,
959}
960
961async fn capture<R>(
972 reader: &mut R,
973 limit: Option<usize>,
974 stream: OutputStream,
975 working_dir: Option<&std::path::Path>,
976) -> Result<Vec<u8>>
977where
978 R: tokio::io::AsyncRead + Unpin,
979{
980 use tokio::io::AsyncReadExt;
981
982 let io_error = |e: std::io::Error| Error::Io {
983 message: format!("failed to read codex {stream}: {e}"),
984 source: e,
985 working_dir: working_dir.map(std::path::Path::to_path_buf),
986 };
987
988 let Some(limit) = limit else {
989 let mut bytes = Vec::new();
990 reader.read_to_end(&mut bytes).await.map_err(io_error)?;
991 return Ok(bytes);
992 };
993
994 let mut bytes = Vec::new();
995 let mut chunk = [0u8; CAPTURE_CHUNK];
996 loop {
997 let read = reader.read(&mut chunk).await.map_err(io_error)?;
998 if read == 0 {
999 return Ok(bytes);
1000 }
1001 if bytes.len() + read > limit {
1002 tracing::warn!(
1003 %stream,
1004 limit_bytes = limit,
1005 captured_bytes = bytes.len(),
1006 "codex output exceeded its capture limit; stopping the run"
1007 );
1008 return Err(Error::OutputLimitExceeded {
1009 stream,
1010 limit_bytes: limit,
1011 });
1012 }
1013 bytes.extend_from_slice(&chunk[..read]);
1014 }
1015}
1016
1017const CAPTURE_CHUNK: usize = 8 * 1024;
1020
1021async fn run_internal_inner(
1022 spec: SpawnSpec<'_>,
1023 stop: Option<StopFuture<'_>>,
1024 grace: Duration,
1025) -> Result<CommandOutput> {
1026 let SpawnSpec {
1027 binary,
1028 args,
1029 env,
1030 clear_env,
1031 working_dir,
1032 stdin_prompt,
1033 process_group,
1034 termination_signal,
1035 output_limit,
1036 die_with_parent,
1037 on_spawn,
1038 } = spec;
1039 let mut cmd = child_command(binary, process_group, die_with_parent);
1040 cmd.args(args);
1041
1042 if stdin_prompt.is_some() {
1045 cmd.stdin(std::process::Stdio::piped());
1046 } else {
1047 cmd.stdin(std::process::Stdio::null());
1048 }
1049
1050 if let Some(dir) = working_dir {
1051 cmd.current_dir(dir);
1052 }
1053
1054 apply_child_environment(&mut cmd, clear_env, env);
1055
1056 cmd.stdout(std::process::Stdio::piped());
1060 cmd.stderr(std::process::Stdio::piped());
1061
1062 let mut child = cmd.spawn().map_err(|e| Error::Io {
1063 message: format!("failed to spawn codex: {e}"),
1064 source: e,
1065 working_dir: working_dir.map(|p| p.to_path_buf()),
1066 })?;
1067
1068 let mut group = arm_and_notify(process_group, termination_signal, child.id(), on_spawn);
1073 let child_stdin = child.stdin.take();
1074 let mut child_stdout = child.stdout.take().expect("stdout was configured as piped");
1075 let mut child_stderr = child.stderr.take().expect("stderr was configured as piped");
1076
1077 let write = async move {
1078 let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
1079 return Ok(());
1080 };
1081 use tokio::io::AsyncWriteExt;
1082 stdin
1083 .write_all(prompt.as_bytes())
1084 .await
1085 .map_err(|e| Error::Io {
1086 message: format!("failed to write the prompt to codex stdin: {e}"),
1087 source: e,
1088 working_dir: working_dir.map(|p| p.to_path_buf()),
1089 })?;
1090 stdin.shutdown().await.map_err(|e| Error::Io {
1093 message: format!("failed to close codex stdin: {e}"),
1094 source: e,
1095 working_dir: working_dir.map(|p| p.to_path_buf()),
1096 })
1097 };
1098
1099 let read_stdout = async {
1104 capture(
1105 &mut child_stdout,
1106 output_limit,
1107 OutputStream::Stdout,
1108 working_dir,
1109 )
1110 .await
1111 };
1112 let read_stderr = async {
1113 capture(
1114 &mut child_stderr,
1115 output_limit,
1116 OutputStream::Stderr,
1117 working_dir,
1118 )
1119 .await
1120 };
1121 let run = async {
1122 let ((), stdout, stderr) = tokio::try_join!(write, read_stdout, read_stderr)?;
1123 let status = child.wait().await.map_err(|e| wait_error(e, working_dir))?;
1126 Ok::<_, Error>((stdout, stderr, status))
1127 };
1128
1129 let finished = match stop {
1130 None => Ok(run.await),
1131 Some(stop) => tokio::select! {
1135 outcome = run => Ok(outcome),
1136 reason = stop => Err(reason),
1137 },
1138 };
1139
1140 let (stdout, stderr, status) = match finished {
1141 Ok(Ok(finished)) => finished,
1142 Ok(Err(error)) => {
1143 let cleanup = terminate_and_reap_draining(
1147 &mut child,
1148 &mut group,
1149 grace,
1150 working_dir,
1151 &mut child_stdout,
1152 &mut child_stderr,
1153 )
1154 .await;
1155 return Err(Error::after_cleanup(error, cleanup));
1156 }
1157 Err(reason) => {
1158 let cleanup = terminate_and_reap_draining(
1164 &mut child,
1165 &mut group,
1166 grace,
1167 working_dir,
1168 &mut child_stdout,
1169 &mut child_stderr,
1170 )
1171 .await;
1172 return Err(Error::after_cleanup(reason.into_error(), cleanup));
1173 }
1174 };
1175
1176 group.disarm();
1178
1179 let stdout = String::from_utf8_lossy(&stdout).to_string();
1180 let stderr = String::from_utf8_lossy(&stderr).to_string();
1181 let exit_code = status.code().unwrap_or(-1);
1182
1183 if !status.success() {
1184 return Err(Error::from_command_failure(
1185 format!("{} {}", binary.display(), args.join(" ")),
1186 exit_code,
1187 stdout,
1188 stderr,
1189 working_dir.map(|p| p.to_path_buf()),
1190 ));
1191 }
1192
1193 Ok(CommandOutput {
1194 stdout,
1195 stderr,
1196 exit_code,
1197 success: true,
1198 })
1199}
1200
1201pub(crate) async fn terminate_and_reap_draining<O, E>(
1206 child: &mut tokio::process::Child,
1207 group: &mut GroupKillGuard,
1208 grace: Duration,
1209 working_dir: Option<&std::path::Path>,
1210 stdout: &mut O,
1211 stderr: &mut E,
1212) -> Result<()>
1213where
1214 O: tokio::io::AsyncRead + Unpin,
1215 E: tokio::io::AsyncRead + Unpin,
1216{
1217 let drain = async {
1218 let mut stdout_sink = tokio::io::sink();
1219 let mut stderr_sink = tokio::io::sink();
1220 let _ = tokio::join!(
1221 tokio::io::copy(stdout, &mut stdout_sink),
1222 tokio::io::copy(stderr, &mut stderr_sink),
1223 );
1224 std::future::pending::<()>().await;
1225 };
1226 let result = tokio::select! {
1227 result = terminate_and_reap(child, group, grace) => {
1228 result.map(|_| ()).map_err(|e| wait_error(e, working_dir))
1229 },
1230 () = drain => unreachable!("the drain waits until shutdown finishes"),
1231 };
1232 #[cfg(test)]
1233 let result = result.and_then(|()| injected_cleanup_failure(working_dir));
1234 if result.is_err() {
1235 tracing::warn!("codex cleanup failed; the child may not have been reaped");
1236 }
1237 result
1238}
1239
1240#[cfg(test)]
1241thread_local! {
1242 static INJECT_CLEANUP_FAILURE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1243}
1244
1245#[cfg(test)]
1255#[cfg_attr(not(unix), allow(dead_code))]
1256pub(crate) struct CleanupFailureInjection(std::marker::PhantomData<std::rc::Rc<()>>);
1257
1258#[cfg(test)]
1259#[cfg_attr(not(unix), allow(dead_code))]
1260impl CleanupFailureInjection {
1261 pub(crate) fn arm() -> Self {
1262 INJECT_CLEANUP_FAILURE.with(|armed| armed.set(true));
1263 Self(std::marker::PhantomData)
1265 }
1266}
1267
1268#[cfg(test)]
1269impl Drop for CleanupFailureInjection {
1270 fn drop(&mut self) {
1271 INJECT_CLEANUP_FAILURE.with(|armed| armed.set(false));
1272 }
1273}
1274
1275#[cfg(test)]
1276fn injected_cleanup_failure(working_dir: Option<&std::path::Path>) -> Result<()> {
1277 if INJECT_CLEANUP_FAILURE.with(std::cell::Cell::get) {
1278 return Err(wait_error(
1279 std::io::Error::other("injected cleanup failure"),
1280 working_dir,
1281 ));
1282 }
1283 Ok(())
1284}
1285
1286pub(crate) async fn terminate_and_reap(
1287 child: &mut tokio::process::Child,
1288 group: &mut GroupKillGuard,
1289 grace: Duration,
1290) -> std::io::Result<(ExitStatus, Option<ShutdownAction>)> {
1291 let (soft, mut hard) = group.terminate(grace).await?;
1292 let status = if let Some(status) = child.try_wait()? {
1293 status
1294 } else {
1295 match child.start_kill() {
1296 Ok(()) => hard = true,
1297 Err(error) if error.kind() == std::io::ErrorKind::InvalidInput => {}
1298 Err(error) => return Err(error),
1299 }
1300 child.wait().await?
1301 };
1302 let action = if hard && hard_kill_matches(status) {
1305 Some(ShutdownAction::Kill)
1306 } else {
1307 soft
1308 };
1309 Ok((status, action))
1310}
1311
1312pub(crate) fn hard_kill_matches(status: ExitStatus) -> bool {
1313 #[cfg(unix)]
1314 {
1315 use std::os::unix::process::ExitStatusExt;
1316 status.signal() == Some(libc::SIGKILL)
1317 }
1318 #[cfg(windows)]
1319 {
1320 status.code() == Some(1)
1322 }
1323 #[cfg(not(any(unix, windows)))]
1324 {
1325 let _ = status;
1326 true
1327 }
1328}
1329
1330fn wait_error(error: std::io::Error, working_dir: Option<&std::path::Path>) -> Error {
1331 Error::Io {
1332 message: format!("failed to wait on codex: {error}"),
1333 source: error,
1334 working_dir: working_dir.map(|p| p.to_path_buf()),
1335 }
1336}
1337
1338pub(crate) fn apply_child_environment(
1343 cmd: &mut Command,
1344 clear_env: bool,
1345 env: &std::collections::HashMap<String, String>,
1346) {
1347 if clear_env {
1348 cmd.env_clear();
1349 }
1350 cmd.envs(env);
1351}
1352
1353#[cfg(test)]
1354mod tests {
1355 use super::*;
1356 use crate::CodexCommand;
1357
1358 #[test]
1359 fn production_commands_use_child_command() {
1360 fn check_directory(dir: &Path) {
1361 for entry in std::fs::read_dir(dir).unwrap() {
1362 let entry = entry.unwrap();
1363 let path = entry.path();
1364 if entry.file_type().unwrap().is_dir() {
1365 check_directory(&path);
1366 continue;
1367 }
1368 if path.extension().and_then(|ext| ext.to_str()) != Some("rs")
1369 || entry.file_name() == "test_support.rs"
1370 {
1371 continue;
1372 }
1373 let source = std::fs::read_to_string(&path).unwrap();
1374 let mut test_item = false;
1375 let mut skip_body = false;
1376 for (index, line) in source.lines().enumerate() {
1377 if skip_body {
1378 skip_body = line != "}";
1380 continue;
1381 }
1382 test_item |= line == "#[cfg(test)]" || line.starts_with("#[cfg(all(test,");
1383 if line.is_empty()
1384 || line.starts_with("#[")
1385 || line.trim_start().starts_with("//")
1386 {
1387 continue;
1388 }
1389 let shared_constructor = entry.file_name() == "exec.rs"
1390 && line.starts_with("pub(crate) fn child_command(");
1391 skip_body = (std::mem::take(&mut test_item) || shared_constructor)
1392 && line.ends_with('{');
1393 if skip_body {
1394 continue;
1395 }
1396 assert!(
1399 line.match_indices("Command::new(").all(|(offset, _)| {
1400 line[..offset].ends_with(|ch: char| ch.is_alphanumeric() || ch == '_')
1401 }),
1402 "{}:{}: use crate::exec::child_command for production spawns",
1403 path.display(),
1404 index + 1
1405 );
1406 }
1407 }
1408 }
1409
1410 check_directory(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"));
1411 }
1412
1413 #[cfg(all(unix, not(target_os = "fuchsia")))]
1414 async fn buffered_descriptor_probe(expected: &str) {
1415 use crate::test_support::{inheritable_pipe_writer, stdin_echo_codex};
1416 use std::os::fd::AsRawFd;
1417
1418 let writer = inheritable_pipe_writer();
1419 let codex = stdin_echo_codex()
1420 .env("CODEX_WRAPPER_TEST_FD", writer.as_raw_fd().to_string())
1421 .build()
1422 .unwrap();
1423 let output = crate::ExecCommand::new("probe")
1424 .execute(&codex)
1425 .await
1426 .unwrap();
1427 assert!(
1428 output.stdout.contains(&format!(r#""text":"{expected}""#)),
1429 "{output:?}"
1430 );
1431 }
1432
1433 #[cfg(any(target_os = "macos", target_os = "ios"))]
1434 #[tokio::test]
1435 async fn buffered_exec_marks_inherited_descriptors_close_on_exec() {
1436 buffered_descriptor_probe("fd-closed").await;
1437 }
1438
1439 #[cfg(all(
1441 unix,
1442 not(any(target_os = "macos", target_os = "ios", target_os = "fuchsia"))
1443 ))]
1444 #[tokio::test]
1445 async fn buffered_exec_preserves_inheritable_descriptors() {
1446 buffered_descriptor_probe("fd-open").await;
1447 }
1448
1449 #[cfg(unix)]
1450 #[tokio::test]
1451 async fn spawn_reports_missing_and_non_executable_binaries() {
1452 use std::os::unix::fs::OpenOptionsExt;
1453
1454 let binary = crate::test_support::PidFile::new("unlaunchable-binary");
1455 let codex = Codex::builder().binary(binary.path()).build().unwrap();
1456 for errno in [libc::ENOENT, libc::EACCES] {
1457 if errno == libc::EACCES {
1458 std::fs::OpenOptions::new()
1459 .write(true)
1460 .create_new(true)
1461 .mode(0o600)
1462 .open(binary.path())
1463 .unwrap();
1464 }
1465 let error = crate::VersionCommand::new()
1466 .execute(&codex)
1467 .await
1468 .unwrap_err();
1469 assert!(
1470 matches!(&error, Error::Io { message, source, working_dir: None }
1471 if message == &format!("failed to spawn codex: {source}")
1472 && source.raw_os_error() == Some(errno)),
1473 "expected spawn errno {errno}, got {error:?}"
1474 );
1475 }
1476 }
1477
1478 #[test]
1479 fn typed_rollout_budget_suppresses_conflicting_client_global_toggles() {
1480 let codex = Codex::builder()
1481 .binary("/bin/echo")
1482 .config("features.rollout_budget=false")
1483 .enable("rollout_budget")
1484 .disable("rollout_budget")
1485 .arg("--enable=rollout_budget")
1486 .arg("--disable=rollout_budget")
1487 .arg("--disable")
1488 .arg("rollout_budget")
1489 .enable("keep-enabled")
1490 .disable("keep-disabled")
1491 .build()
1492 .expect("echo must exist");
1493 let budget = crate::RolloutBudgetConfig::builder(10_000)
1494 .build()
1495 .expect("valid budget");
1496 let expected = budget.config_override();
1497 let opening = crate::ExecCommand::new("hi")
1498 .rollout_budget(budget.clone())
1499 .args();
1500 let resumed = crate::ExecResumeCommand::new()
1501 .session_id("thread")
1502 .rollout_budget(budget)
1503 .args();
1504
1505 for args in [opening, resumed] {
1506 let assembled = assemble_args(&codex, args);
1507 assert!(assembled.iter().any(|arg| arg == &expected));
1508 assert!(
1509 !assembled.windows(2).any(|pair| {
1510 matches!(pair[0].as_str(), "--enable" | "--disable")
1511 && pair[1] == "rollout_budget"
1512 }),
1513 "typed budget must suppress paired client toggles: {assembled:?}"
1514 );
1515 assert!(
1516 !assembled.iter().any(|arg| {
1517 matches!(
1518 arg.as_str(),
1519 "--enable=rollout_budget" | "--disable=rollout_budget"
1520 )
1521 }),
1522 "typed budget must suppress equals-form client toggles: {assembled:?}"
1523 );
1524 assert!(
1525 assembled
1526 .windows(2)
1527 .any(|pair| pair == ["--enable", "keep-enabled"])
1528 );
1529 assert!(
1530 assembled
1531 .windows(2)
1532 .any(|pair| pair == ["--disable", "keep-disabled"])
1533 );
1534 }
1535 }
1536
1537 fn make_output(stdout: &str, stderr: &str) -> CommandOutput {
1538 CommandOutput {
1539 stdout: stdout.to_string(),
1540 stderr: stderr.to_string(),
1541 exit_code: 0,
1542 success: true,
1543 }
1544 }
1545
1546 #[test]
1547 fn shell_quote_leaves_plain_words_alone() {
1548 assert_eq!(shell_quote("exec"), "exec");
1549 assert_eq!(shell_quote("--ephemeral"), "--ephemeral");
1550 assert_eq!(shell_quote("model=gpt-5"), "model=gpt-5");
1551 }
1552
1553 #[test]
1554 fn shell_quote_wraps_anything_a_shell_would_read() {
1555 assert_eq!(shell_quote("fix the tests"), "'fix the tests'");
1556 assert_eq!(shell_quote("$HOME"), "'$HOME'");
1557 assert_eq!(shell_quote("a;b"), "'a;b'");
1558 assert_eq!(shell_quote("*.rs"), "'*.rs'");
1559 assert_eq!(shell_quote("it's"), r"'it'\''s'");
1560 }
1561
1562 #[test]
1565 fn shell_quote_keeps_the_empty_argument_visible() {
1566 assert_eq!(shell_quote(""), "''");
1567 }
1568
1569 #[test]
1570 fn debug_short_output_not_truncated() {
1571 let output = make_output("hello", "world");
1572 let debug = format!("{output:?}");
1573 assert!(debug.contains("hello"));
1574 assert!(debug.contains("world"));
1575 assert!(!debug.contains("bytes total"));
1576 }
1577
1578 #[test]
1579 fn debug_long_output_truncated() {
1580 let long = "x".repeat(300);
1581 let output = make_output(&long, &long);
1582 let debug = format!("{output:?}");
1583 assert!(debug.contains("... (300 bytes total)"));
1584 assert!(!debug.contains(&long));
1585 }
1586
1587 #[cfg(unix)]
1590 #[tokio::test]
1591 async fn child_environment_is_inherited_by_default() {
1592 let capture = crate::test_support::EnvCapture::new("env-default");
1593 let codex = crate::test_support::env_capturing_codex(&capture)
1594 .build()
1595 .expect("bash must exist");
1596
1597 crate::ExecCommand::new("probe")
1598 .execute(&codex)
1599 .await
1600 .unwrap();
1601
1602 let environment = capture.read();
1603 assert_eq!(
1604 environment.get("PATH"),
1605 Some(&std::env::var("PATH").expect("test process must have PATH"))
1606 );
1607 }
1608
1609 #[cfg(unix)]
1613 #[tokio::test]
1614 async fn cleared_environment_reaches_buffered_open_and_resume() {
1615 let capture = crate::test_support::EnvCapture::new("env-buffered");
1616 let opening_client = crate::test_support::env_capturing_codex(&capture)
1617 .clear_env()
1618 .env("CODEX_WRAPPER_EXPLICIT", "opening")
1619 .timeout(Duration::from_secs(2))
1620 .build()
1621 .expect("bash must exist");
1622
1623 crate::ExecCommand::new("probe")
1624 .execute(&opening_client)
1625 .await
1626 .unwrap();
1627 let opening_environment = capture.read();
1628 assert!(!opening_environment.contains_key("PATH"));
1629 assert_eq!(
1630 opening_environment
1631 .get("CODEX_WRAPPER_EXPLICIT")
1632 .map(String::as_str),
1633 Some("opening")
1634 );
1635 assert!(opening_environment.contains_key("CODEX_WRAPPER_ENV_CAPTURE"));
1636
1637 let resume_client = crate::test_support::env_capturing_codex(&capture)
1638 .clear_env()
1639 .env("CODEX_WRAPPER_EXPLICIT", "resume")
1640 .build()
1641 .expect("bash must exist");
1642 crate::ExecResumeCommand::new()
1643 .last()
1644 .execute(&resume_client)
1645 .await
1646 .unwrap();
1647 let resume_environment = capture.read();
1648 assert!(!resume_environment.contains_key("PATH"));
1649 assert_eq!(
1650 resume_environment
1651 .get("CODEX_WRAPPER_EXPLICIT")
1652 .map(String::as_str),
1653 Some("resume")
1654 );
1655 }
1656
1657 #[cfg(unix)]
1661 #[tokio::test]
1662 async fn cleared_environment_reaches_stdin_and_cancellable_runs() {
1663 let capture = crate::test_support::EnvCapture::new("env-specialized");
1664 let codex = crate::test_support::env_capturing_codex(&capture)
1665 .env("CODEX_WRAPPER_EXPLICIT", "specialized")
1666 .clear_env()
1667 .build()
1668 .expect("bash must exist");
1669
1670 crate::ExecCommand::new("stdin prompt")
1671 .prompt_via_stdin()
1672 .execute(&codex)
1673 .await
1674 .unwrap();
1675 let stdin_environment = capture.read();
1676 assert!(!stdin_environment.contains_key("PATH"));
1677 assert_eq!(
1678 stdin_environment
1679 .get("CODEX_WRAPPER_EXPLICIT")
1680 .map(String::as_str),
1681 Some("specialized")
1682 );
1683
1684 let never = std::future::pending::<()>();
1685 run_codex_cancellable(&codex, crate::ExecCommand::new("cancellable").args(), never)
1686 .await
1687 .unwrap();
1688 let cancellable_environment = capture.read();
1689 assert!(!cancellable_environment.contains_key("PATH"));
1690 assert_eq!(
1691 cancellable_environment
1692 .get("CODEX_WRAPPER_EXPLICIT")
1693 .map(String::as_str),
1694 Some("specialized")
1695 );
1696 }
1697
1698 #[cfg(unix)]
1699 #[tokio::test]
1700 async fn environment_values_do_not_leak_into_spawn_errors() {
1701 let secret = "spawn-error-must-not-leak-this";
1702 let codex = Codex::builder()
1703 .binary("/codex-wrapper/this-binary-does-not-exist")
1704 .clear_env()
1705 .env("CODEX_WRAPPER_SECRET", secret)
1706 .build()
1707 .unwrap();
1708
1709 let error = run_codex(&codex, vec!["exec".into()])
1710 .await
1711 .expect_err("the fake path must not spawn");
1712 assert!(!error.to_string().contains(secret));
1713 assert!(!format!("{error:?}").contains(secret));
1714 }
1715
1716 #[cfg(unix)]
1718 #[tokio::test]
1719 async fn timeout_kills_the_spawned_process() {
1720 use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
1721
1722 let pid_file = PidFile::new("exec-timeout");
1723 let codex = blocking_codex(&pid_file)
1724 .timeout(Duration::from_millis(500))
1725 .build()
1726 .expect("bash must exist");
1727
1728 let result = run_codex(&codex, vec!["exec".into(), "probe".into()]).await;
1729 assert!(
1730 matches!(result, Err(Error::Timeout { .. })),
1731 "expected timeout error, got: {result:?}"
1732 );
1733
1734 let pid = pid_file.read_pid().await;
1735 assert!(
1736 !is_running_for_test(pid),
1737 "codex ({pid}) survived the timeout"
1738 );
1739 }
1740
1741 #[cfg(unix)]
1744 #[tokio::test]
1745 async fn cancellation_kills_the_spawned_process() {
1746 use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
1747
1748 let pid_file = PidFile::new("exec-cancel");
1749 let codex = blocking_codex(&pid_file).build().expect("bash must exist");
1750
1751 let cancelled = tokio::time::timeout(
1752 Duration::from_millis(500),
1753 run_codex(&codex, vec!["exec".into(), "probe".into()]),
1754 )
1755 .await;
1756 assert!(
1757 cancelled.is_err(),
1758 "fake codex should still have been running, got: {cancelled:?}"
1759 );
1760
1761 let pid = pid_file.read_pid().await;
1762 assert!(
1763 wait_until_gone(pid).await,
1764 "codex ({pid}) survived the dropped future"
1765 );
1766 }
1767
1768 #[cfg(unix)]
1779 mod recorder {
1780 use std::cell::RefCell;
1781 use std::sync::{Arc, Mutex, Once};
1782
1783 use tracing::field::{Field, Visit};
1784 use tracing::span::{Attributes, Id, Record};
1785 use tracing::{Event, Metadata, Subscriber};
1786
1787 type Sink = Arc<Mutex<Vec<(String, String)>>>;
1788
1789 thread_local! {
1790 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
1791 }
1792
1793 struct Global;
1794
1795 impl Global {
1796 fn collect(f: impl FnOnce(&mut Vec<(String, String)>)) {
1797 SINK.with(|sink| {
1798 if let Some(sink) = sink.borrow().as_ref() {
1799 f(&mut sink.lock().unwrap());
1800 }
1801 });
1802 }
1803 }
1804
1805 impl Subscriber for Global {
1806 fn enabled(&self, _: &Metadata<'_>) -> bool {
1808 true
1809 }
1810 fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1811 Self::collect(|fields| attrs.record(&mut Collect(fields)));
1812 Id::from_u64(1)
1813 }
1814 fn record(&self, _: &Id, values: &Record<'_>) {
1815 Self::collect(|fields| values.record(&mut Collect(fields)));
1816 }
1817 fn record_follows_from(&self, _: &Id, _: &Id) {}
1818 fn event(&self, event: &Event<'_>) {
1819 Self::collect(|fields| event.record(&mut Collect(fields)));
1820 }
1821 fn enter(&self, _: &Id) {}
1822 fn exit(&self, _: &Id) {}
1823 }
1824
1825 struct Collect<'a>(&'a mut Vec<(String, String)>);
1826
1827 impl Visit for Collect<'_> {
1828 fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
1829 self.0.push((field.name().into(), format!("{value:?}")));
1830 }
1831 fn record_str(&mut self, field: &Field, value: &str) {
1832 self.0.push((field.name().into(), value.into()));
1833 }
1834 fn record_i64(&mut self, field: &Field, value: i64) {
1835 self.0.push((field.name().into(), value.to_string()));
1836 }
1837 fn record_u64(&mut self, field: &Field, value: u64) {
1838 self.0.push((field.name().into(), value.to_string()));
1839 }
1840 }
1841
1842 pub(super) struct Recorder(Sink);
1843
1844 impl Recorder {
1845 pub(super) fn install() -> Self {
1847 static INIT: Once = Once::new();
1848 INIT.call_once(|| {
1849 let _ = tracing::subscriber::set_global_default(Global);
1850 });
1851 let sink: Sink = Arc::new(Mutex::new(Vec::new()));
1852 SINK.with(|slot| *slot.borrow_mut() = Some(Arc::clone(&sink)));
1853 Self(sink)
1854 }
1855
1856 pub(super) fn dump(&self) -> String {
1857 format!("{:?}", self.0.lock().unwrap())
1858 }
1859
1860 pub(super) fn value(&self, field: &str) -> Option<String> {
1861 self.0
1862 .lock()
1863 .unwrap()
1864 .iter()
1865 .rev()
1866 .find(|(name, _)| name == field)
1867 .map(|(_, value)| value.clone())
1868 }
1869 }
1870
1871 impl Drop for Recorder {
1872 fn drop(&mut self) {
1873 SINK.with(|slot| *slot.borrow_mut() = None);
1874 }
1875 }
1876 }
1877
1878 #[cfg(unix)]
1879 #[tokio::test]
1880 async fn span_records_the_subcommand_and_a_clean_outcome() {
1881 let recorder = recorder::Recorder::install();
1882
1883 let codex = Codex::builder()
1884 .binary("/bin/echo")
1885 .build()
1886 .expect("echo must exist");
1887 run_codex(&codex, vec!["exec".into()]).await.unwrap();
1888
1889 assert_eq!(recorder.value("subcommand").as_deref(), Some("exec"));
1890 assert_eq!(recorder.value("outcome").as_deref(), Some("ok"));
1891 assert_eq!(recorder.value("exit_code").as_deref(), Some("0"));
1892 assert!(recorder.value("duration_ms").is_some());
1893 }
1894
1895 #[cfg(unix)]
1898 #[tokio::test]
1899 async fn span_does_not_carry_the_prompt() {
1900 let recorder = recorder::Recorder::install();
1901
1902 let codex = Codex::builder()
1903 .binary("/bin/echo")
1904 .build()
1905 .expect("echo must exist");
1906 run_codex(&codex, vec!["exec".into(), "a very secret prompt".into()])
1907 .await
1908 .unwrap();
1909
1910 assert!(!recorder.dump().contains("secret"), "{}", recorder.dump());
1911 assert!(recorder.value("binary").is_none());
1912 assert!(recorder.value("working_dir").is_none());
1913 }
1914
1915 #[cfg(unix)]
1918 #[tokio::test]
1919 async fn a_cancelled_run_is_recorded_as_cancelled() {
1920 let recorder = recorder::Recorder::install();
1921
1922 let pid_file = crate::test_support::PidFile::new("span-cancel");
1923 let codex = crate::test_support::blocking_codex(&pid_file)
1924 .build()
1925 .expect("bash must exist");
1926
1927 let cancelled = tokio::time::timeout(
1928 Duration::from_millis(300),
1929 run_codex(&codex, vec!["exec".into()]),
1930 )
1931 .await;
1932 assert!(cancelled.is_err(), "the run should still have been going");
1933
1934 assert_eq!(
1935 recorder.value("outcome").as_deref(),
1936 Some("cancelled"),
1937 "recorded: {}",
1938 recorder.dump()
1939 );
1940 }
1941
1942 #[cfg(unix)]
1945 #[tokio::test]
1946 async fn a_timed_out_run_is_recorded_as_timeout() {
1947 let recorder = recorder::Recorder::install();
1948
1949 let pid_file = crate::test_support::PidFile::new("span-timeout");
1950 let codex = crate::test_support::blocking_codex(&pid_file)
1951 .timeout(Duration::from_millis(300))
1952 .build()
1953 .expect("bash must exist");
1954
1955 let result = run_codex(&codex, vec!["exec".into()]).await;
1956 assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
1957
1958 assert_eq!(recorder.value("outcome").as_deref(), Some("timeout"));
1959 }
1960
1961 #[cfg(unix)]
1966 fn flooding_codex(stream: &str, limit: Option<usize>) -> Codex {
1967 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1968 .join("tests")
1969 .join("fake-codex-floods.sh");
1970 let mut builder = Codex::builder()
1971 .binary("/bin/bash")
1972 .arg(script.to_str().unwrap())
1973 .env("CODEX_WRAPPER_TEST_FLOOD_STREAM", stream);
1974 if let Some(max_bytes) = limit {
1975 builder = builder.output_limit(max_bytes);
1976 }
1977 builder.build().expect("bash must exist")
1978 }
1979
1980 #[cfg(unix)]
1983 #[tokio::test]
1984 async fn a_stream_past_the_ceiling_fails_without_carrying_its_bytes() {
1985 for stream in ["stdout", "stderr"] {
1986 let codex = flooding_codex(stream, Some(64 * 1024));
1987 let error = crate::ExecCommand::new("hello")
1988 .execute(&codex)
1989 .await
1990 .expect_err("the flood exceeds the ceiling");
1991
1992 let Error::OutputLimitExceeded {
1993 stream: reported,
1994 limit_bytes,
1995 } = error
1996 else {
1997 panic!("expected OutputLimitExceeded for {stream}, got {error:?}");
1998 };
1999 assert_eq!(reported.to_string(), stream);
2000 assert_eq!(limit_bytes, 64 * 1024);
2001
2002 let error = Error::OutputLimitExceeded {
2005 stream: reported,
2006 limit_bytes,
2007 };
2008 let rendered = format!("{error} {error:?}");
2009 assert!(!rendered.contains("xxxxxxxx"), "{rendered}");
2010 assert!(rendered.len() < 512, "error text grew with the output");
2011 }
2012 }
2013
2014 #[cfg(unix)]
2018 #[tokio::test]
2019 async fn without_a_ceiling_the_whole_flood_is_captured() {
2020 let codex = flooding_codex("stdout", None);
2021 let result = crate::ExecCommand::new("hello")
2022 .execute(&codex)
2023 .await
2024 .expect("an unbounded capture succeeds, however large");
2025 assert_eq!(result.stdout.len(), 128 * 8192);
2026 }
2027
2028 #[cfg(unix)]
2030 #[tokio::test]
2031 async fn output_within_the_ceiling_is_returned_whole() {
2032 let codex = crate::test_support::stdin_echo_codex()
2033 .output_limit(64 * 1024)
2034 .build()
2035 .expect("bash must exist");
2036 let result = crate::ExecCommand::new("a short prompt")
2037 .execute(&codex)
2038 .await
2039 .expect("well under the ceiling");
2040 assert!(
2043 result.stdout.contains("thread.started"),
2044 "{}",
2045 result.stdout
2046 );
2047 assert!(
2048 result.stdout.contains("turn.completed"),
2049 "{}",
2050 result.stdout
2051 );
2052 }
2053
2054 #[cfg(unix)]
2059 fn failing_codex(case: &str) -> Codex {
2060 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2061 .join("tests")
2062 .join("fake-codex-failure.sh");
2063 Codex::builder()
2064 .binary("/bin/bash")
2065 .arg(script.to_str().unwrap())
2066 .env("CODEX_WRAPPER_TEST_FAILURE", case)
2067 .build()
2068 .expect("bash must exist")
2069 }
2070
2071 #[cfg(unix)]
2074 #[tokio::test]
2075 async fn a_real_spawn_returns_a_classified_error() {
2076 use crate::error::FailureKind;
2077
2078 for (case, expected) in [
2079 ("auth", FailureKind::Auth),
2080 ("not-trusted", FailureKind::NotTrustedDirectory),
2081 ("config", FailureKind::Config),
2082 ("session", FailureKind::SessionNotFound),
2083 ("mystery", FailureKind::Unclassified),
2084 ] {
2085 let codex = failing_codex(case);
2086 let err = run_codex(&codex, vec!["exec".into()]).await.unwrap_err();
2087 assert_eq!(err.failure_kind(), Some(expected), "case {case}: {err}");
2088 }
2089 }
2090
2091 #[cfg(unix)]
2095 #[tokio::test]
2096 async fn a_classified_failure_is_not_retried() {
2097 let policy = crate::retry::RetryPolicy::new()
2098 .max_attempts(3)
2099 .initial_backoff(Duration::from_millis(1))
2100 .retry_on_exit_codes([1]);
2101
2102 let started = Instant::now();
2103 let codex = failing_codex("auth");
2104 let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
2105 .await
2106 .unwrap_err();
2107
2108 assert!(matches!(err, Error::Auth { .. }), "{err}");
2109 assert!(
2112 started.elapsed() < Duration::from_secs(2),
2113 "looks like it retried: {:?}",
2114 started.elapsed()
2115 );
2116 }
2117
2118 #[cfg(unix)]
2120 #[tokio::test]
2121 async fn an_unclassified_failure_still_retries() {
2122 let policy = crate::retry::RetryPolicy::new()
2123 .max_attempts(2)
2124 .initial_backoff(Duration::from_millis(1))
2125 .retry_on_exit_codes([1]);
2126
2127 let codex = failing_codex("mystery");
2128 let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
2129 .await
2130 .unwrap_err();
2131
2132 assert!(matches!(err, Error::CommandFailed { .. }), "{err}");
2133 }
2134
2135 #[cfg(unix)]
2138 #[tokio::test]
2139 async fn allowed_exit_codes_still_apply_to_a_classified_failure() {
2140 let codex = failing_codex("auth");
2141 let output = run_codex_allow_exit_codes(&codex, vec!["exec".into()], &[1])
2142 .await
2143 .expect("exit code 1 was allowed");
2144
2145 assert_eq!(output.exit_code, 1);
2146 assert!(!output.success);
2147 assert!(
2148 output.stderr.contains("401 Unauthorized"),
2149 "{}",
2150 output.stderr
2151 );
2152 }
2153
2154 #[cfg(unix)]
2161 fn spawning_codex(label: &str) -> (Codex, crate::test_support::PidFile) {
2162 let pid_file = crate::test_support::PidFile::new(label);
2163 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2164 .join("tests")
2165 .join("fake-codex-spawns-child.sh");
2166 let codex = Codex::builder()
2167 .binary("/bin/bash")
2168 .arg(script.to_str().unwrap())
2169 .env(
2170 "CODEX_WRAPPER_TEST_PIDFILE",
2171 pid_file.path().to_str().unwrap(),
2172 )
2173 .build()
2174 .expect("bash must exist");
2175 (codex, pid_file)
2176 }
2177
2178 #[cfg(unix)]
2179 async fn read_pids(pid_file: &crate::test_support::PidFile) -> (u32, u32) {
2180 for _ in 0..200 {
2181 if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
2182 let parse = |prefix: &str| -> Option<u32> {
2183 contents
2184 .lines()
2185 .find_map(|l| l.strip_prefix(prefix))
2186 .and_then(|v| v.trim().parse().ok())
2187 };
2188 if let (Some(parent), Some(child)) = (parse("parent="), parse("child=")) {
2189 return (parent, child);
2190 }
2191 }
2192 tokio::time::sleep(Duration::from_millis(10)).await;
2193 }
2194 panic!("the fake codex never recorded both pids");
2195 }
2196
2197 #[cfg(unix)]
2200 #[tokio::test]
2201 async fn cancelling_kills_the_whole_process_group() {
2202 use crate::test_support::wait_until_gone;
2203
2204 let (codex, pid_file) = spawning_codex("group-drop");
2205
2206 let cancelled = tokio::time::timeout(
2207 Duration::from_millis(400),
2208 run_codex(&codex, vec!["exec".into()]),
2209 )
2210 .await;
2211 assert!(cancelled.is_err(), "the run should still have been going");
2212
2213 let (parent, child) = read_pids(&pid_file).await;
2214 assert!(wait_until_gone(parent).await, "codex ({parent}) survived");
2215 assert!(
2216 wait_until_gone(child).await,
2217 "the subprocess ({child}) survived the cancelled run"
2218 );
2219 }
2220
2221 #[cfg(unix)]
2224 #[tokio::test]
2225 async fn run_codex_cancellable_stops_the_group_gracefully() {
2226 use crate::test_support::is_running_for_test;
2227
2228 let (codex, pid_file) = spawning_codex("group-cancel");
2229 let codex = Codex::builder()
2230 .binary(codex.binary())
2231 .arg(
2232 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2233 .join("tests")
2234 .join("fake-codex-spawns-child.sh")
2235 .to_str()
2236 .unwrap(),
2237 )
2238 .env(
2239 "CODEX_WRAPPER_TEST_PIDFILE",
2240 pid_file.path().to_str().unwrap(),
2241 )
2242 .termination_grace(Duration::from_millis(50))
2243 .build()
2244 .unwrap();
2245
2246 let cancel = async {
2247 tokio::time::sleep(Duration::from_millis(300)).await;
2248 };
2249 let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel).await;
2250
2251 assert!(
2252 matches!(result, Err(Error::Cancelled { .. })),
2253 "expected a cancellation, got: {result:?}"
2254 );
2255
2256 let (parent, child) = read_pids(&pid_file).await;
2257 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2258 assert!(
2259 !is_running_for_test(child),
2260 "the subprocess ({child}) survived cancellation"
2261 );
2262 }
2263
2264 #[cfg(unix)]
2265 #[tokio::test]
2266 async fn dropping_during_cancellation_grace_kills_the_group() {
2267 let fixture = crate::test_support::GracePeriodFixture::new("buffered-cancel-grace-drop");
2268 let codex = fixture.builder().build().unwrap();
2269 fixture
2270 .assert_drop_during_grace(run_codex_cancellable(
2271 &codex,
2272 vec!["exec".into()],
2273 fixture.ready(),
2274 ))
2275 .await;
2276 }
2277
2278 #[cfg(unix)]
2279 #[tokio::test]
2280 async fn dropping_during_timeout_grace_kills_the_group() {
2281 let fixture = crate::test_support::GracePeriodFixture::new("buffered-timeout-grace-drop");
2282 let codex = fixture
2283 .builder()
2284 .timeout(Duration::from_secs(2))
2285 .build()
2286 .unwrap();
2287 fixture
2288 .assert_drop_during_grace(run_codex(&codex, vec!["exec".into()]))
2289 .await;
2290 }
2291
2292 #[cfg(unix)]
2293 #[tokio::test]
2294 async fn default_shutdown_still_sends_term_and_drains_both_pipes() {
2295 let fixture = crate::test_support::InterruptFixture::new("default-term-drain");
2296 let codex = fixture.builder().build().unwrap();
2297 let result =
2298 run_codex_cancellable(&codex, vec!["exec".into()], fixture.detached_ready()).await;
2299 assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2300 assert!(fixture.marker(".term").exists());
2301 assert!(!fixture.marker(".int").exists());
2302 assert!(
2303 fixture.marker(".cleaned").exists(),
2304 "shutdown output blocked cleanup"
2305 );
2306 fixture.assert_stopped().await;
2307 }
2308
2309 #[cfg(unix)]
2310 #[tokio::test]
2311 async fn interrupt_cancellation_drains_large_shutdown_output_and_cleans_detached_tool() {
2312 let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-drain");
2313 let codex = fixture
2314 .builder()
2315 .termination_signal(crate::TerminationSignal::Interrupt)
2316 .output_limit(64)
2318 .build()
2319 .unwrap();
2320 let result = run_codex_with_stdin_prompt_cancellable(
2321 &codex,
2322 vec!["exec".into(), "-".into()],
2323 "prompt",
2324 fixture.detached_ready(),
2325 )
2326 .await;
2327 assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2328 assert!(fixture.marker(".int").exists());
2329 assert!(!fixture.marker(".term").exists());
2330 assert!(
2331 fixture.marker(".cleaned").exists(),
2332 "shutdown output blocked cleanup"
2333 );
2334 fixture.assert_stopped().await;
2335 }
2336
2337 #[cfg(unix)]
2338 #[tokio::test]
2339 async fn interrupt_timeout_keeps_timeout_error_after_cooperative_exit() {
2340 let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-timeout");
2341 let codex = fixture
2342 .builder()
2343 .termination_signal(crate::TerminationSignal::Interrupt)
2344 .timeout(Duration::from_secs(1))
2345 .build()
2346 .unwrap();
2347 let run = run_codex(&codex, vec!["exec".into()]);
2348 tokio::pin!(run);
2349 tokio::select! {
2350 result = &mut run => panic!("run ended before readiness: {result:?}"),
2351 () = fixture.detached_ready() => {}
2352 }
2353 let result = run.await;
2354 assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
2355 assert!(fixture.marker(".int").exists());
2356 assert!(fixture.marker(".cleaned").exists());
2357 fixture.assert_stopped().await;
2358 }
2359
2360 #[cfg(unix)]
2361 #[tokio::test]
2362 async fn interrupt_ignored_uses_bounded_hard_fallback() {
2363 let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-ignored");
2364 let codex = fixture
2365 .builder()
2366 .env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
2367 .termination_signal(crate::TerminationSignal::Interrupt)
2368 .termination_grace(Duration::from_millis(100))
2369 .build()
2370 .unwrap();
2371 let result = tokio::time::timeout(
2372 Duration::from_secs(3),
2373 run_codex_cancellable(&codex, vec!["exec".into()], fixture.ready()),
2374 )
2375 .await
2376 .expect("hard fallback exceeded the grace budget");
2377 assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2378 assert!(fixture.marker(".int").exists());
2379 assert!(!fixture.marker(".cleaned").exists());
2380 fixture.assert_stopped().await;
2381 }
2382
2383 #[cfg(unix)]
2384 #[tokio::test]
2385 async fn dropping_during_interrupt_grace_kills_immediately() {
2386 let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-drop");
2387 let codex = fixture
2388 .builder()
2389 .env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
2390 .termination_signal(crate::TerminationSignal::Interrupt)
2391 .termination_grace(Duration::from_secs(30))
2392 .build()
2393 .unwrap();
2394 let mut run = Box::pin(run_codex_cancellable(
2395 &codex,
2396 vec!["exec".into()],
2397 fixture.ready(),
2398 ));
2399 tokio::select! {
2400 result = &mut run => panic!("run ended before its grace period: {result:?}"),
2401 () = fixture.wait_for(".int") => {}
2402 }
2403 drop(run);
2404 fixture.assert_stopped().await;
2405 }
2406
2407 #[cfg(unix)]
2408 #[tokio::test]
2409 async fn process_group_optout_skips_interrupt_and_grace() {
2410 let fixture = crate::test_support::InterruptFixture::new("buffered-interrupt-optout");
2411 let codex = fixture
2412 .builder()
2413 .process_group(false)
2414 .termination_signal(crate::TerminationSignal::Interrupt)
2415 .termination_grace(Duration::from_secs(30))
2416 .build()
2417 .unwrap();
2418 let result = tokio::time::timeout(
2419 Duration::from_secs(3),
2420 run_codex_cancellable(&codex, vec!["exec".into()], fixture.detached_ready()),
2421 )
2422 .await
2423 .expect("optout must not wait through the grace period");
2424 assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2425 assert!(!fixture.marker(".int").exists());
2426 assert!(!fixture.marker(".term").exists());
2427 let (parent, child) = fixture.pids().unwrap();
2428 assert!(crate::test_support::wait_until_gone(parent).await);
2429 assert!(crate::test_support::is_running_for_test(child));
2430 }
2432
2433 #[cfg(unix)]
2436 #[tokio::test]
2437 async fn timeout_stops_the_group_before_returning() {
2438 use crate::test_support::is_running_for_test;
2439
2440 let pid_file = crate::test_support::PidFile::new("group-timeout-settled");
2441 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2442 .join("tests")
2443 .join("fake-codex-spawns-child.sh");
2444 let codex = Codex::builder()
2445 .binary("/bin/bash")
2446 .arg(script.to_str().unwrap())
2447 .env(
2448 "CODEX_WRAPPER_TEST_PIDFILE",
2449 pid_file.path().to_str().unwrap(),
2450 )
2451 .timeout(Duration::from_millis(300))
2452 .termination_grace(Duration::from_millis(10))
2453 .build()
2454 .unwrap();
2455
2456 let result = run_codex(&codex, vec!["exec".into()]).await;
2457 assert!(
2458 matches!(result, Err(Error::Timeout { .. })),
2459 "expected a timeout, got: {result:?}"
2460 );
2461
2462 let (parent, child) = read_pids(&pid_file).await;
2463 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2464 assert!(
2465 !is_running_for_test(child),
2466 "the subprocess ({child}) survived the timeout"
2467 );
2468 }
2469
2470 #[cfg(unix)]
2474 #[tokio::test]
2475 async fn stdin_write_failure_stops_and_reaps_before_returning() {
2476 use crate::test_support::is_running_for_test;
2477
2478 let pid_file = crate::test_support::PidFile::new("stdin-write-failure");
2479 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2480 .join("tests")
2481 .join("fake-codex-closes-stdin-spawns-child.sh");
2482 let codex = Codex::builder()
2483 .binary("/bin/bash")
2484 .arg(script.to_str().unwrap())
2485 .env(
2486 "CODEX_WRAPPER_TEST_PIDFILE",
2487 pid_file.path().to_str().unwrap(),
2488 )
2489 .termination_grace(Duration::from_millis(10))
2490 .build()
2491 .unwrap();
2492
2493 let prompt = "x".repeat(4 * 1024 * 1024);
2494 let result = run_codex_with_stdin_prompt(
2495 &codex,
2496 crate::ExecCommand::from_stdin(&prompt).args(),
2497 &prompt,
2498 )
2499 .await;
2500 assert!(
2501 matches!(result, Err(Error::Io { ref message, .. }) if message.contains("stdin")),
2502 "expected a stdin error, got: {result:?}"
2503 );
2504
2505 let (parent, child) = read_pids(&pid_file).await;
2506 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
2507 assert!(
2508 !is_running_for_test(child),
2509 "the subprocess ({child}) survived the stdin failure"
2510 );
2511 }
2512
2513 #[cfg(unix)]
2524 fn injected_cleanup_reason(result: Result<CommandOutput>) -> Error {
2525 match result {
2526 Err(Error::CleanupFailed { reason, cleanup }) => {
2527 assert!(
2528 cleanup.to_string().contains("injected cleanup failure"),
2529 "{cleanup:?}"
2530 );
2531 *reason
2532 }
2533 other => panic!("expected CleanupFailed, got {other:?}"),
2534 }
2535 }
2536
2537 #[cfg(unix)]
2538 #[tokio::test]
2539 async fn failed_cleanup_after_cancellation_is_not_a_bare_cancel() {
2540 let pid_file = crate::test_support::PidFile::new("cleanup-failed-cancel");
2541 let codex = crate::test_support::blocking_codex(&pid_file)
2542 .termination_grace(Duration::from_millis(10))
2543 .build()
2544 .unwrap();
2545 let cancel_soon = || tokio::time::sleep(Duration::from_millis(100));
2546
2547 let injection = CleanupFailureInjection::arm();
2548 let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel_soon()).await;
2549 let reason = injected_cleanup_reason(result);
2550 assert!(matches!(reason, Error::Cancelled { .. }), "{reason:?}");
2551
2552 drop(injection);
2554 let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel_soon()).await;
2555 assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
2556 }
2557
2558 #[cfg(unix)]
2562 #[tokio::test]
2563 async fn failed_cleanup_after_timeout_is_recorded_and_not_retried() {
2564 use std::sync::Arc;
2565 use std::sync::atomic::{AtomicUsize, Ordering};
2566
2567 let recorder = recorder::Recorder::install();
2568 let spawns = Arc::new(AtomicUsize::new(0));
2569 let counted = Arc::clone(&spawns);
2570 let pid_file = crate::test_support::PidFile::new("cleanup-failed-timeout");
2571 let codex = crate::test_support::blocking_codex(&pid_file)
2572 .timeout(Duration::from_millis(200))
2573 .termination_grace(Duration::from_millis(10))
2574 .on_spawn(Arc::new(move |_| {
2575 counted.fetch_add(1, Ordering::SeqCst);
2576 }))
2577 .build()
2578 .unwrap();
2579 let policy = crate::retry::RetryPolicy::new()
2580 .max_attempts(3)
2581 .initial_backoff(Duration::from_millis(1))
2582 .retry_on_timeout(true);
2583
2584 let _injection = CleanupFailureInjection::arm();
2585 let result = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy)).await;
2586 let reason = injected_cleanup_reason(result);
2587 assert!(matches!(reason, Error::Timeout { .. }), "{reason:?}");
2588 assert_eq!(spawns.load(Ordering::SeqCst), 1, "a timeout was retried");
2589 assert_eq!(
2590 recorder.value("outcome").as_deref(),
2591 Some("cleanup_failed"),
2592 "recorded: {}",
2593 recorder.dump()
2594 );
2595 }
2596
2597 #[cfg(unix)]
2600 #[tokio::test]
2601 async fn failed_cleanup_after_an_output_limit_keeps_the_limit_as_reason() {
2602 let codex = flooding_codex("stdout", Some(64 * 1024));
2603
2604 let injection = CleanupFailureInjection::arm();
2605 let result = run_codex(&codex, vec!["exec".into()]).await;
2606 let reason = injected_cleanup_reason(result);
2607 assert!(
2608 matches!(
2609 reason,
2610 Error::OutputLimitExceeded {
2611 stream: OutputStream::Stdout,
2612 limit_bytes: 65_536,
2613 }
2614 ),
2615 "{reason:?}"
2616 );
2617
2618 drop(injection);
2619 let result = run_codex(&codex, vec!["exec".into()]).await;
2620 assert!(
2621 matches!(result, Err(Error::OutputLimitExceeded { .. })),
2622 "{result:?}"
2623 );
2624 }
2625
2626 #[cfg(unix)]
2629 #[tokio::test]
2630 async fn a_run_that_finishes_first_is_not_cancelled() {
2631 let codex = Codex::builder()
2632 .binary("/bin/echo")
2633 .build()
2634 .expect("echo must exist");
2635
2636 let never = std::future::pending::<()>();
2637 let output = run_codex_cancellable(&codex, vec!["exec".into()], never)
2638 .await
2639 .unwrap();
2640 assert!(output.success);
2641 }
2642
2643 #[cfg(unix)]
2644 #[tokio::test]
2645 async fn spawn_observer_reports_each_buffered_child_before_returning() {
2646 use std::sync::{Arc, Mutex};
2647
2648 let seen = Arc::new(Mutex::new(Vec::new()));
2649 let sink = Arc::clone(&seen);
2650 let codex = Codex::builder()
2651 .binary("/bin/echo")
2652 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2653 .build()
2654 .expect("echo must exist");
2655
2656 let output = run_codex(&codex, vec!["probe".into()]).await.unwrap();
2657 let seen = seen.lock().unwrap();
2658 assert_eq!(seen.len(), 1);
2659 assert!(seen[0].pid > 0);
2660 assert_eq!(seen[0].pgid, Some(seen[0].pid));
2661 assert!(output.stdout.contains("probe"));
2662 }
2663
2664 #[cfg(unix)]
2665 #[tokio::test]
2666 async fn spawn_receipt_never_claims_a_shared_group() {
2667 use std::sync::{Arc, Mutex};
2668
2669 let seen = Arc::new(Mutex::new(Vec::new()));
2670 let sink = Arc::clone(&seen);
2671 let codex = Codex::builder()
2672 .binary("/bin/echo")
2673 .process_group(false)
2674 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2675 .build()
2676 .expect("echo must exist");
2677
2678 run_codex(&codex, vec!["probe".into()]).await.unwrap();
2679 assert_eq!(seen.lock().unwrap()[0].pgid, None);
2680 }
2681
2682 #[test]
2683 fn parent_death_support_matches_the_target() {
2684 assert_eq!(die_with_parent_supported(), cfg!(target_os = "linux"));
2685 }
2686
2687 #[cfg(unix)]
2688 #[tokio::test]
2689 async fn parent_death_policy_composes_with_spawn_observation() {
2690 use std::sync::{Arc, Mutex};
2691
2692 let seen = Arc::new(Mutex::new(Vec::new()));
2693 let sink = Arc::clone(&seen);
2694 let codex = Codex::builder()
2695 .binary("/bin/echo")
2696 .die_with_parent(true)
2697 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
2698 .build()
2699 .expect("echo must exist");
2700
2701 run_codex(&codex, vec!["probe".into()]).await.unwrap();
2702 assert_eq!(seen.lock().unwrap().len(), 1);
2703 }
2704
2705 const PDEATHSIG_HELPER_ENV: &str = "CODEX_WRAPPER_PDEATHSIG_HELPER";
2706
2707 #[test]
2708 fn pdeathsig_helper_process() {
2709 if std::env::var(PDEATHSIG_HELPER_ENV).is_err() {
2710 return;
2711 }
2712 use std::io::Write;
2713 use std::sync::Arc;
2714
2715 let codex = Codex::builder()
2716 .binary("/bin/sleep")
2717 .die_with_parent(true)
2718 .on_spawn(Arc::new(|info| {
2719 println!("PID {}", info.pid);
2720 let _ = std::io::stdout().flush();
2721 }))
2722 .build()
2723 .unwrap();
2724 let runtime = tokio::runtime::Builder::new_current_thread()
2725 .enable_all()
2726 .build()
2727 .unwrap();
2728 let _ = runtime.block_on(run_codex(&codex, vec!["300".into()]));
2729 }
2730
2731 #[cfg(target_os = "linux")]
2732 #[test]
2733 fn child_dies_when_its_parent_is_sigkilled() {
2734 use std::io::{BufRead, BufReader};
2735 use std::process::{Command, Stdio};
2736
2737 let executable = std::env::current_exe().expect("test binary path");
2738 let mut helper = Command::new(executable)
2739 .args([
2740 "--exact",
2741 "exec::tests::pdeathsig_helper_process",
2742 "--nocapture",
2743 ])
2744 .env(PDEATHSIG_HELPER_ENV, "1")
2745 .stdout(Stdio::piped())
2746 .spawn()
2747 .expect("spawn helper");
2748 let stdout = helper.stdout.take().expect("piped stdout");
2749 let pid = BufReader::new(stdout)
2750 .lines()
2751 .map_while(std::result::Result::ok)
2752 .find_map(|line| line.strip_prefix("PID ").and_then(|pid| pid.parse().ok()))
2753 .expect("helper reported child pid");
2754
2755 unsafe { libc::kill(helper.id() as i32, libc::SIGKILL) };
2757 let _ = helper.wait();
2758
2759 for _ in 0..50 {
2760 if !crate::test_support::is_running_for_test(pid) {
2761 return;
2762 }
2763 std::thread::sleep(Duration::from_millis(100));
2764 }
2765 panic!("child {pid} survived its SIGKILLed parent");
2766 }
2767
2768 #[cfg(unix)]
2773 #[tokio::test]
2774 async fn opting_out_of_process_groups_leaves_the_subprocess() {
2775 use crate::test_support::wait_until_gone;
2776
2777 let pid_file = crate::test_support::PidFile::new("group-optout");
2778 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2779 .join("tests")
2780 .join("fake-codex-spawns-child.sh");
2781 let codex = Codex::builder()
2782 .binary("/bin/bash")
2783 .arg(script.to_str().unwrap())
2784 .env(
2785 "CODEX_WRAPPER_TEST_PIDFILE",
2786 pid_file.path().to_str().unwrap(),
2787 )
2788 .process_group(false)
2789 .build()
2790 .expect("bash must exist");
2791
2792 let cancelled = tokio::time::timeout(
2793 Duration::from_millis(400),
2794 run_codex(&codex, vec!["exec".into()]),
2795 )
2796 .await;
2797 assert!(cancelled.is_err(), "the run should still have been going");
2798
2799 let (parent, child) = read_pids(&pid_file).await;
2800 assert!(
2801 wait_until_gone(parent).await,
2802 "kill_on_drop still reaps the direct child ({parent})"
2803 );
2804 assert!(
2807 crate::test_support::is_running_for_test(child),
2808 "with groups off, the subprocess ({child}) is expected to survive"
2809 );
2810 signal_group(child, libc::SIGKILL);
2812 unsafe { libc::kill(i32::try_from(child).unwrap_or(0), libc::SIGKILL) };
2813 }
2814 #[cfg(unix)]
2815 struct PrivateTraceDir(std::path::PathBuf);
2816
2817 #[cfg(unix)]
2818 impl Drop for PrivateTraceDir {
2819 fn drop(&mut self) {
2820 let _ = std::fs::remove_dir_all(&self.0);
2821 }
2822 }
2823
2824 #[cfg(unix)]
2825 fn private_trace_client(body: &str) -> (PrivateTraceDir, Codex) {
2826 use std::os::unix::fs::symlink;
2827 static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2828 let name = format!(
2829 "TRACE_PRIVATE_path-{}-{}-{}",
2830 std::process::id(),
2831 std::time::SystemTime::now()
2832 .duration_since(std::time::UNIX_EPOCH)
2833 .unwrap()
2834 .as_nanos(),
2835 NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
2836 );
2837 let dir = PrivateTraceDir(std::env::temp_dir().join(name));
2838 std::fs::create_dir(&dir.0).unwrap();
2839 let binary = dir.0.join("TRACE_PRIVATE_binary");
2840 symlink("/bin/bash", &binary).unwrap();
2841 let script = dir.0.join("TRACE_PRIVATE_script");
2842 std::fs::write(&script, body).unwrap();
2843 let codex = Codex::builder()
2844 .binary(binary)
2845 .arg(script.to_string_lossy())
2846 .arg("TRACE_PRIVATE_config")
2847 .working_dir(&dir.0)
2848 .termination_grace(Duration::ZERO)
2849 .build()
2850 .unwrap();
2851 (dir, codex)
2852 }
2853
2854 #[cfg(unix)]
2855 #[tokio::test]
2856 async fn invocation_traces_exclude_private_content_at_every_level() {
2857 let recorder = recorder::Recorder::install();
2858 let body = concat!(
2859 "cat >/dev/null\n",
2860 "printf 'TRACE_PRIVATE_output'\n",
2861 "printf 'TRACE_PRIVATE_stderr' >&2\n"
2862 );
2863 let (_dir, codex) = private_trace_client(body);
2864 let args = vec![
2865 "exec".into(),
2866 "TRACE_PRIVATE_prompt".into(),
2867 "--resume".into(),
2868 "TRACE_PRIVATE_resume".into(),
2869 ];
2870 assert!(
2871 run_codex(&codex, args.clone())
2872 .await
2873 .unwrap()
2874 .stdout
2875 .contains("TRACE_PRIVATE")
2876 );
2877 run_codex_cancellable(&codex, args.clone(), std::future::pending())
2878 .await
2879 .unwrap();
2880 run_codex_with_stdin_prompt(&codex, args.clone(), "TRACE_PRIVATE_stdin")
2881 .await
2882 .unwrap();
2883 run_codex_with_stdin_prompt_cancellable(
2884 &codex,
2885 args,
2886 "TRACE_PRIVATE_stdin",
2887 std::future::pending(),
2888 )
2889 .await
2890 .unwrap();
2891 run_codex(&codex, vec!["TRACE_PRIVATE_unknown_command".into()])
2892 .await
2893 .unwrap();
2894 assert!(
2895 recorder.value("outcome").is_some(),
2896 "subscriber must observe outcomes"
2897 );
2898 assert!(
2899 !recorder.dump().contains("TRACE_PRIVATE"),
2900 "{}",
2901 recorder.dump()
2902 );
2903 assert!(
2904 recorder.value("arg_count").is_some(),
2905 "useful argument count remains available"
2906 );
2907 }
2908
2909 #[cfg(all(unix, feature = "json"))]
2910 #[tokio::test]
2911 async fn stream_and_resume_traces_exclude_private_content() {
2912 use crate::{CodexCommand, ExecCommand, ExecResumeCommand};
2913 let recorder = recorder::Recorder::install();
2914 let body = format!(
2916 "cat >/dev/null\n{}",
2917 include_str!("../tests/fake-codex.sh")
2918 .replace("thread_test", "TRACE_PRIVATE_thread")
2919 .replace("hello", "TRACE_PRIVATE_output")
2920 );
2921 let (_dir, codex) = private_trace_client(&body);
2922 let cmd = ExecCommand::new("TRACE_PRIVATE_prompt");
2923 let mut observed = 0;
2924 crate::streaming::stream_exec(&codex, &cmd, |_| observed += 1)
2925 .await
2926 .unwrap();
2927 crate::streaming::stream_exec_cancellable(&codex, &cmd, std::future::pending(), |_| {})
2928 .await
2929 .unwrap();
2930 let stdin_cmd = ExecCommand::new("TRACE_PRIVATE_stdin").prompt_via_stdin();
2931 crate::streaming::stream_exec(&codex, &stdin_cmd, |_| {})
2932 .await
2933 .unwrap();
2934 let resume = ExecResumeCommand::new()
2935 .session_id("TRACE_PRIVATE_resume")
2936 .prompt("TRACE_PRIVATE_prompt");
2937 crate::streaming::stream_exec_resume(&codex, &resume, |_| {})
2938 .await
2939 .unwrap();
2940 crate::streaming::stream_exec_resume_cancellable(
2941 &codex,
2942 &resume,
2943 std::future::pending(),
2944 |_| {},
2945 )
2946 .await
2947 .unwrap();
2948 assert!(observed > 0, "protocol delivery remains intact");
2949 assert!(
2950 cmd.to_command_string(&codex).contains("TRACE_PRIVATE"),
2951 "explicit preview stays caller-controlled"
2952 );
2953 assert!(
2954 !recorder.dump().contains("TRACE_PRIVATE"),
2955 "{}",
2956 recorder.dump()
2957 );
2958 }
2959
2960 #[cfg(unix)]
2961 #[tokio::test]
2962 async fn failure_and_retry_traces_exclude_rendered_errors_and_output() {
2963 let recorder = recorder::Recorder::install();
2964 let (_dir, mut codex) = private_trace_client(
2965 "printf 'TRACE_PRIVATE_output'; printf 'TRACE_PRIVATE_stderr' >&2; exit 7",
2966 );
2967 codex.retry_policy = Some(
2968 crate::RetryPolicy::new()
2969 .max_attempts(2)
2970 .initial_backoff(Duration::ZERO)
2971 .retry_on_exit_codes([7]),
2972 );
2973 let error = run_codex(&codex, vec!["exec".into(), "TRACE_PRIVATE_prompt".into()])
2974 .await
2975 .unwrap_err();
2976 assert!(
2977 error.to_string().contains("TRACE_PRIVATE"),
2978 "explicit error retains diagnostics"
2979 );
2980 codex.retry_policy = None;
2981 codex.output_limit = Some(8);
2982 assert!(matches!(
2983 run_codex(&codex, vec!["exec".into()]).await,
2984 Err(Error::OutputLimitExceeded { .. })
2985 ));
2986 assert!(
2987 !recorder.dump().contains("TRACE_PRIVATE"),
2988 "{}",
2989 recorder.dump()
2990 );
2991 assert!(
2992 recorder.value("attempt").is_some(),
2993 "retry event must be captured"
2994 );
2995 }
2996
2997 #[cfg(all(unix, feature = "app-server"))]
2998 #[tokio::test]
2999 async fn app_server_startup_trace_excludes_private_arguments() {
3000 let recorder = recorder::Recorder::install();
3001 let codex = Codex::builder()
3002 .binary("/bin/false")
3003 .arg("TRACE_PRIVATE_configuration")
3004 .build()
3005 .unwrap();
3006 assert!(
3007 crate::app_server::AppServer::builder(&codex)
3008 .start()
3009 .await
3010 .is_err()
3011 );
3012 assert!(
3013 !recorder.dump().contains("TRACE_PRIVATE"),
3014 "{}",
3015 recorder.dump()
3016 );
3017 assert!(
3018 recorder.value("arg_count").is_some(),
3019 "startup event must be captured"
3020 );
3021 }
3022 #[cfg(unix)]
3023 #[tokio::test]
3024 async fn output_limit_trace_omits_captured_prefix() {
3025 let recorder = recorder::Recorder::install();
3026 let (_dir, mut codex) = private_trace_client(
3028 "printf 'TRACE_PRIVATE_output'; sleep 0.05; head -c 4096 /dev/zero",
3029 );
3030 codex.output_limit = Some(64);
3031 assert!(matches!(
3032 run_codex(&codex, vec!["exec".into()]).await,
3033 Err(Error::OutputLimitExceeded { .. })
3034 ));
3035 assert!(
3036 recorder.value("captured_bytes").is_some(),
3037 "capture warning was observed"
3038 );
3039 assert!(
3040 !recorder.dump().contains("TRACE_PRIVATE"),
3041 "{}",
3042 recorder.dump()
3043 );
3044 }
3045}