1use std::fmt;
5use std::time::{Duration, Instant};
6
7use tokio::process::Command;
8use tracing::{Instrument, Span, debug, field, info_span};
9
10use crate::Codex;
11use crate::error::{Error, OutputStream, Result};
12
13pub(crate) fn command_span(name: &'static str, codex: &Codex, args: &[String]) -> Span {
19 let working_dir = codex
20 .working_dir
21 .as_ref()
22 .map_or_else(|| "(inherited)".to_string(), |p| p.display().to_string());
23
24 info_span!(
25 parent: Span::current(),
26 "codex",
27 otel.name = name,
28 subcommand = args.first().map_or("(none)", String::as_str),
29 binary = %codex.binary.display(),
30 working_dir = %working_dir,
31 outcome = field::Empty,
32 exit_code = field::Empty,
33 duration_ms = field::Empty,
34 )
35}
36
37pub(crate) struct SpanOutcome {
47 span: Span,
48 started: Instant,
49 settled: bool,
50}
51
52impl SpanOutcome {
53 pub(crate) fn start(span: Span) -> Self {
54 Self {
55 span,
56 started: Instant::now(),
57 settled: false,
58 }
59 }
60
61 pub(crate) fn settle(&mut self, outcome: &'static str, exit_code: Option<i32>) {
62 self.settled = true;
63 self.span.record("outcome", outcome);
64 self.span
65 .record("duration_ms", self.started.elapsed().as_millis() as u64);
66 if let Some(code) = exit_code {
67 self.span.record("exit_code", code);
68 }
69 }
70
71 fn settle_from_ref(&mut self, result: &Result<CommandOutput>) {
72 self.settle_from(result);
73 }
74
75 fn settle_from(&mut self, result: &Result<CommandOutput>) {
76 match result {
77 Ok(output) => self.settle("ok", Some(output.exit_code)),
78 Err(Error::Timeout { .. }) => self.settle("timeout", None),
79 Err(e) => match e.exit_code() {
82 Some(code) => self.settle("failed", Some(code)),
83 None => self.settle("error", None),
84 },
85 }
86 }
87}
88
89impl Drop for SpanOutcome {
90 fn drop(&mut self) {
91 if !self.settled {
92 self.settle("cancelled", None);
93 }
94 }
95}
96
97#[cfg(unix)]
104pub(crate) fn own_process_group(cmd: &mut Command, enabled: bool) {
105 if enabled {
106 cmd.process_group(0);
107 }
108}
109
110#[cfg(not(unix))]
111pub(crate) fn own_process_group(_cmd: &mut Command, _enabled: bool) {}
112
113#[must_use]
121pub const fn die_with_parent_supported() -> bool {
122 cfg!(target_os = "linux")
123}
124
125#[cfg(unix)]
132fn pdeathsig_hook() -> impl FnMut() -> std::io::Result<()> + Send + Sync + 'static {
133 let parent = std::process::id();
134 move || {
135 #[cfg(target_os = "linux")]
136 {
137 unsafe {
139 if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) != 0 {
140 return Err(std::io::Error::last_os_error());
141 }
142 if libc::getppid() as u32 != parent {
143 libc::_exit(1);
144 }
145 }
146 }
147 #[cfg(not(target_os = "linux"))]
148 {
149 let _ = parent;
150 }
151 Ok(())
152 }
153}
154
155pub(crate) fn apply_die_with_parent(cmd: &mut Command, enabled: bool) {
157 #[cfg(unix)]
158 if enabled {
159 unsafe {
161 cmd.pre_exec(pdeathsig_hook());
162 }
163 }
164 #[cfg(not(unix))]
165 {
166 let _ = (cmd, enabled);
167 }
168}
169
170pub(crate) fn arm_and_notify(
172 process_group: bool,
173 pid: Option<u32>,
174 on_spawn: Option<&crate::SpawnObserver>,
175) -> GroupKillGuard {
176 if let (Some(pid), Some(observer)) = (pid, on_spawn) {
177 observer(crate::SpawnInfo {
178 pid,
179 pgid: process_group.then_some(pid),
180 });
181 }
182 GroupKillGuard::new(process_group.then_some(pid).flatten())
183}
184
185#[cfg(unix)]
194pub(crate) fn signal_group(pid: u32, signal: i32) {
195 let Ok(pid) = i32::try_from(pid) else {
196 return;
197 };
198 unsafe {
201 libc::kill(-pid, signal);
202 }
203}
204
205pub(crate) struct GroupKillGuard {
212 pid: Option<u32>,
213}
214
215impl GroupKillGuard {
216 pub(crate) fn new(pid: Option<u32>) -> Self {
217 Self { pid }
218 }
219
220 pub(crate) fn disarm(&mut self) {
222 self.pid = None;
223 }
224
225 #[cfg(unix)]
229 pub(crate) async fn terminate(&mut self, grace: Duration) {
230 let Some(pid) = self.pid.take() else {
231 return;
232 };
233 signal_group(pid, libc::SIGTERM);
234 tokio::time::sleep(grace).await;
235 signal_group(pid, libc::SIGKILL);
236 }
237
238 #[cfg(not(unix))]
241 pub(crate) async fn terminate(&mut self, _grace: Duration) {
242 let _ = self.pid.take();
243 }
244}
245
246impl Drop for GroupKillGuard {
247 fn drop(&mut self) {
248 if let Some(pid) = self.pid.take() {
251 #[cfg(unix)]
252 signal_group(pid, libc::SIGKILL);
253 #[cfg(not(unix))]
254 let _ = pid;
255 }
256 }
257}
258
259#[derive(Clone)]
264pub struct CommandOutput {
265 pub stdout: String,
267 pub stderr: String,
269 pub exit_code: i32,
271 pub success: bool,
273}
274
275const DEBUG_TRUNCATE_LEN: usize = 200;
276
277fn truncate_for_debug(s: &str) -> String {
278 if s.len() > DEBUG_TRUNCATE_LEN {
279 format!("{}... ({} bytes total)", &s[..DEBUG_TRUNCATE_LEN], s.len())
280 } else {
281 s.to_string()
282 }
283}
284
285impl fmt::Debug for CommandOutput {
286 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
287 f.debug_struct("CommandOutput")
288 .field("stdout", &truncate_for_debug(&self.stdout))
289 .field("stderr", &truncate_for_debug(&self.stderr))
290 .field("exit_code", &self.exit_code)
291 .field("success", &self.success)
292 .finish()
293 }
294}
295
296pub async fn run_codex(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
302 run_codex_with_retry(codex, args, None).await
303}
304
305pub async fn run_codex_with_retry(
307 codex: &Codex,
308 args: Vec<String>,
309 retry_override: Option<&crate::retry::RetryPolicy>,
310) -> Result<CommandOutput> {
311 let policy = retry_override.or(codex.retry_policy.as_ref());
312
313 match policy {
314 Some(policy) => {
315 let span = info_span!(
318 "codex.retry",
319 subcommand = args.first().map_or("(none)", String::as_str),
320 max_attempts = policy.max_attempts,
321 );
322 crate::retry::with_retry(policy, || run_codex_once(codex, args.clone()))
323 .instrument(span)
324 .await
325 }
326 None => run_codex_once(codex, args).await,
327 }
328}
329
330pub(crate) fn assemble_args(codex: &Codex, args: Vec<String>) -> Vec<String> {
338 let mut command_args = Vec::with_capacity(codex.global_args.len() + args.len());
339 let protects_rollout_budget = args
340 .windows(2)
341 .any(|pair| pair[0] == "-c" && crate::RolloutBudgetConfig::is_config_override(&pair[1]));
342 let mut global_args = codex.global_args.iter().peekable();
343 while let Some(arg) = global_args.next() {
344 if protects_rollout_budget
345 && matches!(arg.as_str(), "--enable" | "--disable")
346 && global_args
347 .peek()
348 .is_some_and(|feature| feature.as_str() == "rollout_budget")
349 {
350 global_args.next();
351 continue;
352 }
353 if protects_rollout_budget
354 && matches!(
355 arg.as_str(),
356 "--enable=rollout_budget" | "--disable=rollout_budget"
357 )
358 {
359 continue;
360 }
361 command_args.push(arg.clone());
362 }
363 command_args.extend(args);
364 command_args
365}
366
367pub(crate) fn command_string(codex: &Codex, args: Vec<String>) -> String {
369 let mut out = shell_quote(&codex.binary.display().to_string());
370 for arg in assemble_args(codex, args) {
371 out.push(' ');
372 out.push_str(&shell_quote(&arg));
373 }
374 out
375}
376
377pub(crate) fn shell_quote(arg: &str) -> String {
383 if arg.is_empty() {
384 return "''".to_string();
385 }
386 if arg.contains(|c: char| c.is_whitespace() || "\"'$\\`|;<>&()[]{}*?!~#".contains(c)) {
387 return format!("'{}'", arg.replace('\'', r"'\''"));
388 }
389 arg.to_string()
390}
391
392async fn run_codex_once(codex: &Codex, args: Vec<String>) -> Result<CommandOutput> {
393 let span = command_span("codex.exec", codex, &args);
394 let outcome_span = span.clone();
395 let command_args = assemble_args(codex, args);
396
397 async move {
398 debug!(binary = %codex.binary.display(), args = ?command_args, "executing codex command");
399
400 let mut outcome = SpanOutcome::start(outcome_span);
401 let result = match codex.timeout {
402 Some(timeout) => {
403 run_internal_inner(
404 SpawnSpec {
405 binary: &codex.binary,
406 args: &command_args,
407 env: &codex.env,
408 clear_env: codex.clear_env,
409 working_dir: codex.working_dir.as_deref(),
410 stdin_prompt: None,
411 process_group: codex.process_group,
412 output_limit: codex.output_limit,
413 die_with_parent: codex.die_with_parent,
414 on_spawn: codex.on_spawn.as_ref(),
415 },
416 Some(timeout_stop(timeout)),
417 codex.termination_grace,
418 )
419 .await
420 }
421 None => {
422 run_internal_inner(
423 SpawnSpec {
424 binary: &codex.binary,
425 args: &command_args,
426 env: &codex.env,
427 clear_env: codex.clear_env,
428 working_dir: codex.working_dir.as_deref(),
429 stdin_prompt: None,
430 process_group: codex.process_group,
431 output_limit: codex.output_limit,
432 die_with_parent: codex.die_with_parent,
433 on_spawn: codex.on_spawn.as_ref(),
434 },
435 None,
436 Duration::ZERO,
437 )
438 .await
439 }
440 };
441 outcome.settle_from(&result);
442 result
443 }
444 .instrument(span)
445 .await
446}
447
448pub async fn run_codex_cancellable<C>(
464 codex: &Codex,
465 args: Vec<String>,
466 cancel: C,
467) -> Result<CommandOutput>
468where
469 C: std::future::Future<Output = ()> + Send,
470{
471 let span = command_span("codex.exec", codex, &args);
472 let outcome_span = span.clone();
473 let command_args = assemble_args(codex, args);
474
475 async move {
476 debug!(binary = %codex.binary.display(), args = ?command_args, "executing cancellable codex command");
477
478 let mut outcome = SpanOutcome::start(outcome_span);
479 let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
480 let result = run_internal_inner(
481 SpawnSpec {
482 binary: &codex.binary,
483 args: &command_args,
484 env: &codex.env,
485 clear_env: codex.clear_env,
486 working_dir: codex.working_dir.as_deref(),
487 stdin_prompt: None,
488 process_group: codex.process_group,
489 output_limit: codex.output_limit,
490 die_with_parent: codex.die_with_parent,
491 on_spawn: codex.on_spawn.as_ref(),
492 },
493 Some(stop),
494 codex.termination_grace,
495 )
496 .await;
497
498 match &result {
499 Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
500 other => outcome.settle_from_ref(other),
501 }
502 result
503 }
504 .instrument(span)
505 .await
506}
507
508pub async fn run_codex_allow_exit_codes(
510 codex: &Codex,
511 args: Vec<String>,
512 allowed_codes: &[i32],
513) -> Result<CommandOutput> {
514 let output = run_codex(codex, args).await;
515
516 match output {
517 Err(e)
521 if e.exit_code()
522 .is_some_and(|code| allowed_codes.contains(&code)) =>
523 {
524 let exit_code = e.exit_code().unwrap_or(-1);
525 let (stdout, stderr) = match &e {
526 Error::CommandFailed { stdout, stderr, .. } => (stdout.clone(), stderr.clone()),
527 Error::Auth { message, .. }
528 | Error::Config { message, .. }
529 | Error::NotTrustedDirectory { message, .. }
530 | Error::SessionNotFound { message, .. } => (String::new(), message.clone()),
531 _ => (String::new(), String::new()),
532 };
533 Ok(CommandOutput {
534 stdout,
535 stderr,
536 exit_code,
537 success: false,
538 })
539 }
540 other => other,
541 }
542}
543
544pub async fn run_codex_with_stdin_prompt(
556 codex: &Codex,
557 args: Vec<String>,
558 prompt: &str,
559) -> Result<CommandOutput> {
560 let span = command_span("codex.exec", codex, &args);
561 let outcome_span = span.clone();
562 let command_args = assemble_args(codex, args);
563
564 async move {
565 debug!(
566 binary = %codex.binary.display(),
567 args = ?command_args,
568 prompt_bytes = prompt.len(),
569 "executing codex command with a stdin prompt"
570 );
571
572 let mut outcome = SpanOutcome::start(outcome_span);
573 let stop = codex.timeout.map(timeout_stop);
574 let result = run_internal_inner(
575 SpawnSpec {
576 binary: &codex.binary,
577 args: &command_args,
578 env: &codex.env,
579 clear_env: codex.clear_env,
580 working_dir: codex.working_dir.as_deref(),
581 stdin_prompt: Some(prompt),
582 process_group: codex.process_group,
583 output_limit: codex.output_limit,
584 die_with_parent: codex.die_with_parent,
585 on_spawn: codex.on_spawn.as_ref(),
586 },
587 stop,
588 codex.termination_grace,
589 )
590 .await;
591 outcome.settle_from(&result);
592 result
593 }
594 .instrument(span)
595 .await
596}
597
598pub async fn run_codex_with_stdin_prompt_cancellable<C>(
603 codex: &Codex,
604 args: Vec<String>,
605 prompt: &str,
606 cancel: C,
607) -> Result<CommandOutput>
608where
609 C: std::future::Future<Output = ()> + Send,
610{
611 let span = command_span("codex.exec", codex, &args);
612 let outcome_span = span.clone();
613 let command_args = assemble_args(codex, args);
614
615 async move {
616 debug!(
617 binary = %codex.binary.display(),
618 args = ?command_args,
619 prompt_bytes = prompt.len(),
620 "executing cancellable codex command with a stdin prompt"
621 );
622
623 let mut outcome = SpanOutcome::start(outcome_span);
624 let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
625 let result = 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: Some(prompt),
633 process_group: codex.process_group,
634 output_limit: codex.output_limit,
635 die_with_parent: codex.die_with_parent,
636 on_spawn: codex.on_spawn.as_ref(),
637 },
638 Some(stop),
639 codex.termination_grace,
640 )
641 .await;
642
643 match &result {
644 Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
645 other => outcome.settle_from_ref(other),
646 }
647 result
648 }
649 .instrument(span)
650 .await
651}
652
653#[derive(Clone, Copy, Debug)]
654enum StopReason {
655 Cancelled { grace_seconds: u64 },
656 Timeout { timeout_seconds: u64 },
657}
658
659impl StopReason {
660 fn into_error(self) -> Error {
661 match self {
662 Self::Cancelled { grace_seconds } => Error::Cancelled { grace_seconds },
663 Self::Timeout { timeout_seconds } => Error::Timeout { timeout_seconds },
664 }
665 }
666}
667
668type StopFuture<'a> = std::pin::Pin<Box<dyn std::future::Future<Output = StopReason> + Send + 'a>>;
669
670fn timeout_stop(timeout: Duration) -> StopFuture<'static> {
671 Box::pin(async move {
672 tokio::time::sleep(timeout).await;
673 StopReason::Timeout {
674 timeout_seconds: timeout.as_secs(),
675 }
676 })
677}
678
679fn cancellation_or_timeout<'a, C>(
680 cancel: C,
681 timeout: Option<Duration>,
682 grace: Duration,
683) -> StopFuture<'a>
684where
685 C: std::future::Future<Output = ()> + Send + 'a,
686{
687 Box::pin(async move {
688 match timeout {
689 Some(timeout) => tokio::select! {
690 () = cancel => StopReason::Cancelled {
691 grace_seconds: grace.as_secs(),
692 },
693 () = tokio::time::sleep(timeout) => StopReason::Timeout {
694 timeout_seconds: timeout.as_secs(),
695 },
696 },
697 None => {
698 cancel.await;
699 StopReason::Cancelled {
700 grace_seconds: grace.as_secs(),
701 }
702 }
703 }
704 })
705}
706
707struct SpawnSpec<'a> {
709 binary: &'a std::path::Path,
710 args: &'a [String],
711 env: &'a std::collections::HashMap<String, String>,
712 clear_env: bool,
714 working_dir: Option<&'a std::path::Path>,
715 stdin_prompt: Option<&'a str>,
717 process_group: bool,
719 output_limit: Option<usize>,
721 die_with_parent: bool,
723 on_spawn: Option<&'a crate::SpawnObserver>,
725}
726
727async fn capture<R>(
738 reader: &mut R,
739 limit: Option<usize>,
740 stream: OutputStream,
741 working_dir: Option<&std::path::Path>,
742) -> Result<Vec<u8>>
743where
744 R: tokio::io::AsyncRead + Unpin,
745{
746 use tokio::io::AsyncReadExt;
747
748 let io_error = |e: std::io::Error| Error::Io {
749 message: format!("failed to read codex {stream}: {e}"),
750 source: e,
751 working_dir: working_dir.map(std::path::Path::to_path_buf),
752 };
753
754 let Some(limit) = limit else {
755 let mut bytes = Vec::new();
756 reader.read_to_end(&mut bytes).await.map_err(io_error)?;
757 return Ok(bytes);
758 };
759
760 let mut bytes = Vec::new();
761 let mut chunk = [0u8; CAPTURE_CHUNK];
762 loop {
763 let read = reader.read(&mut chunk).await.map_err(io_error)?;
764 if read == 0 {
765 return Ok(bytes);
766 }
767 if bytes.len() + read > limit {
768 bytes.truncate(BREACH_LOG_BYTES.min(bytes.len()));
769 tracing::warn!(
770 %stream,
771 limit_bytes = limit,
772 head = %String::from_utf8_lossy(&bytes),
773 "codex output exceeded its capture limit; stopping the run"
774 );
775 return Err(Error::OutputLimitExceeded {
776 stream,
777 limit_bytes: limit,
778 });
779 }
780 bytes.extend_from_slice(&chunk[..read]);
781 }
782}
783
784const CAPTURE_CHUNK: usize = 8 * 1024;
787
788const BREACH_LOG_BYTES: usize = 2 * 1024;
792
793async fn run_internal_inner(
794 spec: SpawnSpec<'_>,
795 stop: Option<StopFuture<'_>>,
796 grace: Duration,
797) -> Result<CommandOutput> {
798 let SpawnSpec {
799 binary,
800 args,
801 env,
802 clear_env,
803 working_dir,
804 stdin_prompt,
805 process_group,
806 output_limit,
807 die_with_parent,
808 on_spawn,
809 } = spec;
810 let mut cmd = Command::new(binary);
811 cmd.args(args);
812
813 if stdin_prompt.is_some() {
816 cmd.stdin(std::process::Stdio::piped());
817 } else {
818 cmd.stdin(std::process::Stdio::null());
819 }
820
821 cmd.kill_on_drop(true);
825 own_process_group(&mut cmd, process_group);
826 apply_die_with_parent(&mut cmd, die_with_parent);
827
828 if let Some(dir) = working_dir {
829 cmd.current_dir(dir);
830 }
831
832 apply_child_environment(&mut cmd, clear_env, env);
833
834 cmd.stdout(std::process::Stdio::piped());
838 cmd.stderr(std::process::Stdio::piped());
839
840 let mut child = cmd.spawn().map_err(|e| Error::Io {
841 message: format!("failed to spawn codex: {e}"),
842 source: e,
843 working_dir: working_dir.map(|p| p.to_path_buf()),
844 })?;
845
846 let mut group = arm_and_notify(process_group, child.id(), on_spawn);
851 let child_stdin = child.stdin.take();
852 let mut child_stdout = child.stdout.take().expect("stdout was configured as piped");
853 let mut child_stderr = child.stderr.take().expect("stderr was configured as piped");
854
855 let write = async move {
856 let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
857 return Ok(());
858 };
859 use tokio::io::AsyncWriteExt;
860 stdin
861 .write_all(prompt.as_bytes())
862 .await
863 .map_err(|e| Error::Io {
864 message: format!("failed to write the prompt to codex stdin: {e}"),
865 source: e,
866 working_dir: working_dir.map(|p| p.to_path_buf()),
867 })?;
868 stdin.shutdown().await.map_err(|e| Error::Io {
871 message: format!("failed to close codex stdin: {e}"),
872 source: e,
873 working_dir: working_dir.map(|p| p.to_path_buf()),
874 })
875 };
876
877 let read_stdout = async move {
882 capture(
883 &mut child_stdout,
884 output_limit,
885 OutputStream::Stdout,
886 working_dir,
887 )
888 .await
889 };
890 let read_stderr = async move {
891 capture(
892 &mut child_stderr,
893 output_limit,
894 OutputStream::Stderr,
895 working_dir,
896 )
897 .await
898 };
899 let wait = async { child.wait().await.map_err(|e| wait_error(e, working_dir)) };
900 let run = async {
901 let ((), stdout, stderr, status) = tokio::try_join!(write, read_stdout, read_stderr, wait)?;
902 Ok::<_, Error>((stdout, stderr, status))
903 };
904
905 let finished = match stop {
906 None => Ok(run.await),
907 Some(stop) => tokio::select! {
911 outcome = run => Ok(outcome),
912 reason = stop => Err(reason),
913 },
914 };
915
916 let (stdout, stderr, status) = match finished {
917 Ok(Ok(finished)) => finished,
918 Ok(Err(error)) => {
919 terminate_and_reap(&mut child, &mut group, grace, working_dir).await?;
923 return Err(error);
924 }
925 Err(reason) => {
926 terminate_and_reap(&mut child, &mut group, grace, working_dir).await?;
932 return Err(reason.into_error());
933 }
934 };
935
936 group.disarm();
938
939 let stdout = String::from_utf8_lossy(&stdout).to_string();
940 let stderr = String::from_utf8_lossy(&stderr).to_string();
941 let exit_code = status.code().unwrap_or(-1);
942
943 if !status.success() {
944 return Err(Error::from_command_failure(
945 format!("{} {}", binary.display(), args.join(" ")),
946 exit_code,
947 stdout,
948 stderr,
949 working_dir.map(|p| p.to_path_buf()),
950 ));
951 }
952
953 Ok(CommandOutput {
954 stdout,
955 stderr,
956 exit_code,
957 success: true,
958 })
959}
960
961pub(crate) async fn terminate_and_reap(
962 child: &mut tokio::process::Child,
963 group: &mut GroupKillGuard,
964 grace: Duration,
965 working_dir: Option<&std::path::Path>,
966) -> Result<()> {
967 group.terminate(grace).await;
968 if child
969 .try_wait()
970 .map_err(|e| wait_error(e, working_dir))?
971 .is_none()
972 && let Err(error) = child.start_kill()
973 && error.kind() != std::io::ErrorKind::InvalidInput
974 {
975 return Err(wait_error(error, working_dir));
976 }
977 child.wait().await.map_err(|e| wait_error(e, working_dir))?;
978 Ok(())
979}
980
981fn wait_error(error: std::io::Error, working_dir: Option<&std::path::Path>) -> Error {
982 Error::Io {
983 message: format!("failed to wait on codex: {error}"),
984 source: error,
985 working_dir: working_dir.map(|p| p.to_path_buf()),
986 }
987}
988
989pub(crate) fn apply_child_environment(
994 cmd: &mut Command,
995 clear_env: bool,
996 env: &std::collections::HashMap<String, String>,
997) {
998 if clear_env {
999 cmd.env_clear();
1000 }
1001 cmd.envs(env);
1002}
1003
1004#[cfg(test)]
1005mod tests {
1006 use super::*;
1007 use crate::CodexCommand;
1008
1009 #[test]
1010 fn typed_rollout_budget_suppresses_conflicting_client_global_toggles() {
1011 let codex = Codex::builder()
1012 .binary("/bin/echo")
1013 .config("features.rollout_budget=false")
1014 .enable("rollout_budget")
1015 .disable("rollout_budget")
1016 .arg("--enable=rollout_budget")
1017 .arg("--disable=rollout_budget")
1018 .arg("--disable")
1019 .arg("rollout_budget")
1020 .enable("keep-enabled")
1021 .disable("keep-disabled")
1022 .build()
1023 .expect("echo must exist");
1024 let budget = crate::RolloutBudgetConfig::builder(10_000)
1025 .build()
1026 .expect("valid budget");
1027 let expected = budget.config_override();
1028 let opening = crate::ExecCommand::new("hi")
1029 .rollout_budget(budget.clone())
1030 .args();
1031 let resumed = crate::ExecResumeCommand::new()
1032 .session_id("thread")
1033 .rollout_budget(budget)
1034 .args();
1035
1036 for args in [opening, resumed] {
1037 let assembled = assemble_args(&codex, args);
1038 assert!(assembled.iter().any(|arg| arg == &expected));
1039 assert!(
1040 !assembled.windows(2).any(|pair| {
1041 matches!(pair[0].as_str(), "--enable" | "--disable")
1042 && pair[1] == "rollout_budget"
1043 }),
1044 "typed budget must suppress paired client toggles: {assembled:?}"
1045 );
1046 assert!(
1047 !assembled.iter().any(|arg| {
1048 matches!(
1049 arg.as_str(),
1050 "--enable=rollout_budget" | "--disable=rollout_budget"
1051 )
1052 }),
1053 "typed budget must suppress equals-form client toggles: {assembled:?}"
1054 );
1055 assert!(
1056 assembled
1057 .windows(2)
1058 .any(|pair| pair == ["--enable", "keep-enabled"])
1059 );
1060 assert!(
1061 assembled
1062 .windows(2)
1063 .any(|pair| pair == ["--disable", "keep-disabled"])
1064 );
1065 }
1066 }
1067
1068 fn make_output(stdout: &str, stderr: &str) -> CommandOutput {
1069 CommandOutput {
1070 stdout: stdout.to_string(),
1071 stderr: stderr.to_string(),
1072 exit_code: 0,
1073 success: true,
1074 }
1075 }
1076
1077 #[test]
1078 fn shell_quote_leaves_plain_words_alone() {
1079 assert_eq!(shell_quote("exec"), "exec");
1080 assert_eq!(shell_quote("--ephemeral"), "--ephemeral");
1081 assert_eq!(shell_quote("model=gpt-5"), "model=gpt-5");
1082 }
1083
1084 #[test]
1085 fn shell_quote_wraps_anything_a_shell_would_read() {
1086 assert_eq!(shell_quote("fix the tests"), "'fix the tests'");
1087 assert_eq!(shell_quote("$HOME"), "'$HOME'");
1088 assert_eq!(shell_quote("a;b"), "'a;b'");
1089 assert_eq!(shell_quote("*.rs"), "'*.rs'");
1090 assert_eq!(shell_quote("it's"), r"'it'\''s'");
1091 }
1092
1093 #[test]
1096 fn shell_quote_keeps_the_empty_argument_visible() {
1097 assert_eq!(shell_quote(""), "''");
1098 }
1099
1100 #[test]
1101 fn debug_short_output_not_truncated() {
1102 let output = make_output("hello", "world");
1103 let debug = format!("{output:?}");
1104 assert!(debug.contains("hello"));
1105 assert!(debug.contains("world"));
1106 assert!(!debug.contains("bytes total"));
1107 }
1108
1109 #[test]
1110 fn debug_long_output_truncated() {
1111 let long = "x".repeat(300);
1112 let output = make_output(&long, &long);
1113 let debug = format!("{output:?}");
1114 assert!(debug.contains("... (300 bytes total)"));
1115 assert!(!debug.contains(&long));
1116 }
1117
1118 #[cfg(unix)]
1121 #[tokio::test]
1122 async fn child_environment_is_inherited_by_default() {
1123 let capture = crate::test_support::EnvCapture::new("env-default");
1124 let codex = crate::test_support::env_capturing_codex(&capture)
1125 .build()
1126 .expect("bash must exist");
1127
1128 crate::ExecCommand::new("probe")
1129 .execute(&codex)
1130 .await
1131 .unwrap();
1132
1133 let environment = capture.read();
1134 assert_eq!(
1135 environment.get("PATH"),
1136 Some(&std::env::var("PATH").expect("test process must have PATH"))
1137 );
1138 }
1139
1140 #[cfg(unix)]
1144 #[tokio::test]
1145 async fn cleared_environment_reaches_buffered_open_and_resume() {
1146 let capture = crate::test_support::EnvCapture::new("env-buffered");
1147 let opening_client = crate::test_support::env_capturing_codex(&capture)
1148 .clear_env()
1149 .env("CODEX_WRAPPER_EXPLICIT", "opening")
1150 .timeout(Duration::from_secs(2))
1151 .build()
1152 .expect("bash must exist");
1153
1154 crate::ExecCommand::new("probe")
1155 .execute(&opening_client)
1156 .await
1157 .unwrap();
1158 let opening_environment = capture.read();
1159 assert!(!opening_environment.contains_key("PATH"));
1160 assert_eq!(
1161 opening_environment
1162 .get("CODEX_WRAPPER_EXPLICIT")
1163 .map(String::as_str),
1164 Some("opening")
1165 );
1166 assert!(opening_environment.contains_key("CODEX_WRAPPER_ENV_CAPTURE"));
1167
1168 let resume_client = crate::test_support::env_capturing_codex(&capture)
1169 .clear_env()
1170 .env("CODEX_WRAPPER_EXPLICIT", "resume")
1171 .build()
1172 .expect("bash must exist");
1173 crate::ExecResumeCommand::new()
1174 .last()
1175 .execute(&resume_client)
1176 .await
1177 .unwrap();
1178 let resume_environment = capture.read();
1179 assert!(!resume_environment.contains_key("PATH"));
1180 assert_eq!(
1181 resume_environment
1182 .get("CODEX_WRAPPER_EXPLICIT")
1183 .map(String::as_str),
1184 Some("resume")
1185 );
1186 }
1187
1188 #[cfg(unix)]
1192 #[tokio::test]
1193 async fn cleared_environment_reaches_stdin_and_cancellable_runs() {
1194 let capture = crate::test_support::EnvCapture::new("env-specialized");
1195 let codex = crate::test_support::env_capturing_codex(&capture)
1196 .env("CODEX_WRAPPER_EXPLICIT", "specialized")
1197 .clear_env()
1198 .build()
1199 .expect("bash must exist");
1200
1201 crate::ExecCommand::new("stdin prompt")
1202 .prompt_via_stdin()
1203 .execute(&codex)
1204 .await
1205 .unwrap();
1206 let stdin_environment = capture.read();
1207 assert!(!stdin_environment.contains_key("PATH"));
1208 assert_eq!(
1209 stdin_environment
1210 .get("CODEX_WRAPPER_EXPLICIT")
1211 .map(String::as_str),
1212 Some("specialized")
1213 );
1214
1215 let never = std::future::pending::<()>();
1216 run_codex_cancellable(&codex, crate::ExecCommand::new("cancellable").args(), never)
1217 .await
1218 .unwrap();
1219 let cancellable_environment = capture.read();
1220 assert!(!cancellable_environment.contains_key("PATH"));
1221 assert_eq!(
1222 cancellable_environment
1223 .get("CODEX_WRAPPER_EXPLICIT")
1224 .map(String::as_str),
1225 Some("specialized")
1226 );
1227 }
1228
1229 #[cfg(unix)]
1230 #[tokio::test]
1231 async fn environment_values_do_not_leak_into_spawn_errors() {
1232 let secret = "spawn-error-must-not-leak-this";
1233 let codex = Codex::builder()
1234 .binary("/codex-wrapper/this-binary-does-not-exist")
1235 .clear_env()
1236 .env("CODEX_WRAPPER_SECRET", secret)
1237 .build()
1238 .unwrap();
1239
1240 let error = run_codex(&codex, vec!["exec".into()])
1241 .await
1242 .expect_err("the fake path must not spawn");
1243 assert!(!error.to_string().contains(secret));
1244 assert!(!format!("{error:?}").contains(secret));
1245 }
1246
1247 #[cfg(unix)]
1249 #[tokio::test]
1250 async fn timeout_kills_the_spawned_process() {
1251 use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
1252
1253 let pid_file = PidFile::new("exec-timeout");
1254 let codex = blocking_codex(&pid_file)
1255 .timeout(Duration::from_millis(500))
1256 .build()
1257 .expect("bash must exist");
1258
1259 let result = run_codex(&codex, vec!["exec".into(), "probe".into()]).await;
1260 assert!(
1261 matches!(result, Err(Error::Timeout { .. })),
1262 "expected timeout error, got: {result:?}"
1263 );
1264
1265 let pid = pid_file.read_pid().await;
1266 assert!(
1267 !is_running_for_test(pid),
1268 "codex ({pid}) survived the timeout"
1269 );
1270 }
1271
1272 #[cfg(unix)]
1275 #[tokio::test]
1276 async fn cancellation_kills_the_spawned_process() {
1277 use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
1278
1279 let pid_file = PidFile::new("exec-cancel");
1280 let codex = blocking_codex(&pid_file).build().expect("bash must exist");
1281
1282 let cancelled = tokio::time::timeout(
1283 Duration::from_millis(500),
1284 run_codex(&codex, vec!["exec".into(), "probe".into()]),
1285 )
1286 .await;
1287 assert!(
1288 cancelled.is_err(),
1289 "fake codex should still have been running, got: {cancelled:?}"
1290 );
1291
1292 let pid = pid_file.read_pid().await;
1293 assert!(
1294 wait_until_gone(pid).await,
1295 "codex ({pid}) survived the dropped future"
1296 );
1297 }
1298
1299 #[cfg(unix)]
1310 mod recorder {
1311 use std::cell::RefCell;
1312 use std::sync::{Arc, Mutex, Once};
1313
1314 use tracing::field::{Field, Visit};
1315 use tracing::span::{Attributes, Id, Record};
1316 use tracing::{Event, Metadata, Subscriber};
1317
1318 type Sink = Arc<Mutex<Vec<(String, String)>>>;
1319
1320 thread_local! {
1321 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
1322 }
1323
1324 struct Global;
1325
1326 impl Global {
1327 fn collect(f: impl FnOnce(&mut Vec<(String, String)>)) {
1328 SINK.with(|sink| {
1329 if let Some(sink) = sink.borrow().as_ref() {
1330 f(&mut sink.lock().unwrap());
1331 }
1332 });
1333 }
1334 }
1335
1336 impl Subscriber for Global {
1337 fn enabled(&self, _: &Metadata<'_>) -> bool {
1339 true
1340 }
1341 fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1342 Self::collect(|fields| attrs.record(&mut Collect(fields)));
1343 Id::from_u64(1)
1344 }
1345 fn record(&self, _: &Id, values: &Record<'_>) {
1346 Self::collect(|fields| values.record(&mut Collect(fields)));
1347 }
1348 fn record_follows_from(&self, _: &Id, _: &Id) {}
1349 fn event(&self, _: &Event<'_>) {}
1350 fn enter(&self, _: &Id) {}
1351 fn exit(&self, _: &Id) {}
1352 }
1353
1354 struct Collect<'a>(&'a mut Vec<(String, String)>);
1355
1356 impl Visit for Collect<'_> {
1357 fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
1358 self.0.push((field.name().into(), format!("{value:?}")));
1359 }
1360 fn record_str(&mut self, field: &Field, value: &str) {
1361 self.0.push((field.name().into(), value.into()));
1362 }
1363 fn record_i64(&mut self, field: &Field, value: i64) {
1364 self.0.push((field.name().into(), value.to_string()));
1365 }
1366 fn record_u64(&mut self, field: &Field, value: u64) {
1367 self.0.push((field.name().into(), value.to_string()));
1368 }
1369 }
1370
1371 pub(super) struct Recorder(Sink);
1372
1373 impl Recorder {
1374 pub(super) fn install() -> Self {
1376 static INIT: Once = Once::new();
1377 INIT.call_once(|| {
1378 let _ = tracing::subscriber::set_global_default(Global);
1379 });
1380 let sink: Sink = Arc::new(Mutex::new(Vec::new()));
1381 SINK.with(|slot| *slot.borrow_mut() = Some(Arc::clone(&sink)));
1382 Self(sink)
1383 }
1384
1385 pub(super) fn dump(&self) -> String {
1386 format!("{:?}", self.0.lock().unwrap())
1387 }
1388
1389 pub(super) fn value(&self, field: &str) -> Option<String> {
1390 self.0
1391 .lock()
1392 .unwrap()
1393 .iter()
1394 .rev()
1395 .find(|(name, _)| name == field)
1396 .map(|(_, value)| value.clone())
1397 }
1398 }
1399
1400 impl Drop for Recorder {
1401 fn drop(&mut self) {
1402 SINK.with(|slot| *slot.borrow_mut() = None);
1403 }
1404 }
1405 }
1406
1407 #[cfg(unix)]
1408 #[tokio::test]
1409 async fn span_records_the_subcommand_and_a_clean_outcome() {
1410 let recorder = recorder::Recorder::install();
1411
1412 let codex = Codex::builder()
1413 .binary("/bin/echo")
1414 .build()
1415 .expect("echo must exist");
1416 run_codex(&codex, vec!["exec".into()]).await.unwrap();
1417
1418 assert_eq!(recorder.value("subcommand").as_deref(), Some("exec"));
1419 assert_eq!(recorder.value("outcome").as_deref(), Some("ok"));
1420 assert_eq!(recorder.value("exit_code").as_deref(), Some("0"));
1421 assert!(recorder.value("duration_ms").is_some());
1422 }
1423
1424 #[cfg(unix)]
1427 #[tokio::test]
1428 async fn span_does_not_carry_the_prompt() {
1429 let recorder = recorder::Recorder::install();
1430
1431 let codex = Codex::builder()
1432 .binary("/bin/echo")
1433 .build()
1434 .expect("echo must exist");
1435 run_codex(&codex, vec!["exec".into(), "a very secret prompt".into()])
1436 .await
1437 .unwrap();
1438
1439 let recorded = format!("{:?}", recorder.value("subcommand"));
1440 assert!(!recorded.contains("secret"));
1441 for field in ["binary", "working_dir", "outcome", "exit_code"] {
1442 let value = recorder.value(field).unwrap_or_default();
1443 assert!(
1444 !value.contains("secret"),
1445 "{field} leaked the prompt: {value}"
1446 );
1447 }
1448 }
1449
1450 #[cfg(unix)]
1453 #[tokio::test]
1454 async fn a_cancelled_run_is_recorded_as_cancelled() {
1455 let recorder = recorder::Recorder::install();
1456
1457 let pid_file = crate::test_support::PidFile::new("span-cancel");
1458 let codex = crate::test_support::blocking_codex(&pid_file)
1459 .build()
1460 .expect("bash must exist");
1461
1462 let cancelled = tokio::time::timeout(
1463 Duration::from_millis(300),
1464 run_codex(&codex, vec!["exec".into()]),
1465 )
1466 .await;
1467 assert!(cancelled.is_err(), "the run should still have been going");
1468
1469 assert_eq!(
1470 recorder.value("outcome").as_deref(),
1471 Some("cancelled"),
1472 "recorded: {}",
1473 recorder.dump()
1474 );
1475 }
1476
1477 #[cfg(unix)]
1480 #[tokio::test]
1481 async fn a_timed_out_run_is_recorded_as_timeout() {
1482 let recorder = recorder::Recorder::install();
1483
1484 let pid_file = crate::test_support::PidFile::new("span-timeout");
1485 let codex = crate::test_support::blocking_codex(&pid_file)
1486 .timeout(Duration::from_millis(300))
1487 .build()
1488 .expect("bash must exist");
1489
1490 let result = run_codex(&codex, vec!["exec".into()]).await;
1491 assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
1492
1493 assert_eq!(recorder.value("outcome").as_deref(), Some("timeout"));
1494 }
1495
1496 #[cfg(unix)]
1501 fn flooding_codex(stream: &str, limit: Option<usize>) -> Codex {
1502 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1503 .join("tests")
1504 .join("fake-codex-floods.sh");
1505 let mut builder = Codex::builder()
1506 .binary("/bin/bash")
1507 .arg(script.to_str().unwrap())
1508 .env("CODEX_WRAPPER_TEST_FLOOD_STREAM", stream);
1509 if let Some(max_bytes) = limit {
1510 builder = builder.output_limit(max_bytes);
1511 }
1512 builder.build().expect("bash must exist")
1513 }
1514
1515 #[cfg(unix)]
1518 #[tokio::test]
1519 async fn a_stream_past_the_ceiling_fails_without_carrying_its_bytes() {
1520 for stream in ["stdout", "stderr"] {
1521 let codex = flooding_codex(stream, Some(64 * 1024));
1522 let error = crate::ExecCommand::new("hello")
1523 .execute(&codex)
1524 .await
1525 .expect_err("the flood exceeds the ceiling");
1526
1527 let Error::OutputLimitExceeded {
1528 stream: reported,
1529 limit_bytes,
1530 } = error
1531 else {
1532 panic!("expected OutputLimitExceeded for {stream}, got {error:?}");
1533 };
1534 assert_eq!(reported.to_string(), stream);
1535 assert_eq!(limit_bytes, 64 * 1024);
1536
1537 let error = Error::OutputLimitExceeded {
1540 stream: reported,
1541 limit_bytes,
1542 };
1543 let rendered = format!("{error} {error:?}");
1544 assert!(!rendered.contains("xxxxxxxx"), "{rendered}");
1545 assert!(rendered.len() < 512, "error text grew with the output");
1546 }
1547 }
1548
1549 #[cfg(unix)]
1553 #[tokio::test]
1554 async fn without_a_ceiling_the_whole_flood_is_captured() {
1555 let codex = flooding_codex("stdout", None);
1556 let result = crate::ExecCommand::new("hello")
1557 .execute(&codex)
1558 .await
1559 .expect("an unbounded capture succeeds, however large");
1560 assert_eq!(result.stdout.len(), 128 * 8192);
1561 }
1562
1563 #[cfg(unix)]
1565 #[tokio::test]
1566 async fn output_within_the_ceiling_is_returned_whole() {
1567 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1568 .join("tests")
1569 .join("fake-codex-echo-stdin.sh");
1570 let codex = Codex::builder()
1571 .binary("/bin/bash")
1572 .arg(script.to_str().unwrap())
1573 .output_limit(64 * 1024)
1574 .build()
1575 .expect("bash must exist");
1576 let result = crate::ExecCommand::new("a short prompt")
1577 .execute(&codex)
1578 .await
1579 .expect("well under the ceiling");
1580 assert!(
1583 result.stdout.contains("thread.started"),
1584 "{}",
1585 result.stdout
1586 );
1587 assert!(
1588 result.stdout.contains("turn.completed"),
1589 "{}",
1590 result.stdout
1591 );
1592 }
1593
1594 #[cfg(unix)]
1599 fn failing_codex(case: &str) -> Codex {
1600 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1601 .join("tests")
1602 .join("fake-codex-failure.sh");
1603 Codex::builder()
1604 .binary("/bin/bash")
1605 .arg(script.to_str().unwrap())
1606 .env("CODEX_WRAPPER_TEST_FAILURE", case)
1607 .build()
1608 .expect("bash must exist")
1609 }
1610
1611 #[cfg(unix)]
1614 #[tokio::test]
1615 async fn a_real_spawn_returns_a_classified_error() {
1616 use crate::error::FailureKind;
1617
1618 for (case, expected) in [
1619 ("auth", FailureKind::Auth),
1620 ("not-trusted", FailureKind::NotTrustedDirectory),
1621 ("config", FailureKind::Config),
1622 ("session", FailureKind::SessionNotFound),
1623 ("mystery", FailureKind::Unclassified),
1624 ] {
1625 let codex = failing_codex(case);
1626 let err = run_codex(&codex, vec!["exec".into()]).await.unwrap_err();
1627 assert_eq!(err.failure_kind(), Some(expected), "case {case}: {err}");
1628 }
1629 }
1630
1631 #[cfg(unix)]
1635 #[tokio::test]
1636 async fn a_classified_failure_is_not_retried() {
1637 let policy = crate::retry::RetryPolicy::new()
1638 .max_attempts(3)
1639 .initial_backoff(Duration::from_millis(1))
1640 .retry_on_exit_codes([1]);
1641
1642 let started = Instant::now();
1643 let codex = failing_codex("auth");
1644 let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
1645 .await
1646 .unwrap_err();
1647
1648 assert!(matches!(err, Error::Auth { .. }), "{err}");
1649 assert!(
1652 started.elapsed() < Duration::from_secs(2),
1653 "looks like it retried: {:?}",
1654 started.elapsed()
1655 );
1656 }
1657
1658 #[cfg(unix)]
1660 #[tokio::test]
1661 async fn an_unclassified_failure_still_retries() {
1662 let policy = crate::retry::RetryPolicy::new()
1663 .max_attempts(2)
1664 .initial_backoff(Duration::from_millis(1))
1665 .retry_on_exit_codes([1]);
1666
1667 let codex = failing_codex("mystery");
1668 let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
1669 .await
1670 .unwrap_err();
1671
1672 assert!(matches!(err, Error::CommandFailed { .. }), "{err}");
1673 }
1674
1675 #[cfg(unix)]
1678 #[tokio::test]
1679 async fn allowed_exit_codes_still_apply_to_a_classified_failure() {
1680 let codex = failing_codex("auth");
1681 let output = run_codex_allow_exit_codes(&codex, vec!["exec".into()], &[1])
1682 .await
1683 .expect("exit code 1 was allowed");
1684
1685 assert_eq!(output.exit_code, 1);
1686 assert!(!output.success);
1687 assert!(
1688 output.stderr.contains("401 Unauthorized"),
1689 "{}",
1690 output.stderr
1691 );
1692 }
1693
1694 #[cfg(unix)]
1701 fn spawning_codex(label: &str) -> (Codex, crate::test_support::PidFile) {
1702 let pid_file = crate::test_support::PidFile::new(label);
1703 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1704 .join("tests")
1705 .join("fake-codex-spawns-child.sh");
1706 let codex = Codex::builder()
1707 .binary("/bin/bash")
1708 .arg(script.to_str().unwrap())
1709 .env(
1710 "CODEX_WRAPPER_TEST_PIDFILE",
1711 pid_file.path().to_str().unwrap(),
1712 )
1713 .build()
1714 .expect("bash must exist");
1715 (codex, pid_file)
1716 }
1717
1718 #[cfg(unix)]
1719 async fn read_pids(pid_file: &crate::test_support::PidFile) -> (u32, u32) {
1720 for _ in 0..200 {
1721 if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
1722 let parse = |prefix: &str| -> Option<u32> {
1723 contents
1724 .lines()
1725 .find_map(|l| l.strip_prefix(prefix))
1726 .and_then(|v| v.trim().parse().ok())
1727 };
1728 if let (Some(parent), Some(child)) = (parse("parent="), parse("child=")) {
1729 return (parent, child);
1730 }
1731 }
1732 tokio::time::sleep(Duration::from_millis(10)).await;
1733 }
1734 panic!("the fake codex never recorded both pids");
1735 }
1736
1737 #[cfg(unix)]
1740 #[tokio::test]
1741 async fn cancelling_kills_the_whole_process_group() {
1742 use crate::test_support::wait_until_gone;
1743
1744 let (codex, pid_file) = spawning_codex("group-drop");
1745
1746 let cancelled = tokio::time::timeout(
1747 Duration::from_millis(400),
1748 run_codex(&codex, vec!["exec".into()]),
1749 )
1750 .await;
1751 assert!(cancelled.is_err(), "the run should still have been going");
1752
1753 let (parent, child) = read_pids(&pid_file).await;
1754 assert!(wait_until_gone(parent).await, "codex ({parent}) survived");
1755 assert!(
1756 wait_until_gone(child).await,
1757 "the subprocess ({child}) survived the cancelled run"
1758 );
1759 }
1760
1761 #[cfg(unix)]
1764 #[tokio::test]
1765 async fn run_codex_cancellable_stops_the_group_gracefully() {
1766 use crate::test_support::is_running_for_test;
1767
1768 let (codex, pid_file) = spawning_codex("group-cancel");
1769 let codex = Codex::builder()
1770 .binary(codex.binary())
1771 .arg(
1772 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1773 .join("tests")
1774 .join("fake-codex-spawns-child.sh")
1775 .to_str()
1776 .unwrap(),
1777 )
1778 .env(
1779 "CODEX_WRAPPER_TEST_PIDFILE",
1780 pid_file.path().to_str().unwrap(),
1781 )
1782 .termination_grace(Duration::from_millis(50))
1783 .build()
1784 .unwrap();
1785
1786 let cancel = async {
1787 tokio::time::sleep(Duration::from_millis(300)).await;
1788 };
1789 let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel).await;
1790
1791 assert!(
1792 matches!(result, Err(Error::Cancelled { .. })),
1793 "expected a cancellation, got: {result:?}"
1794 );
1795
1796 let (parent, child) = read_pids(&pid_file).await;
1797 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1798 assert!(
1799 !is_running_for_test(child),
1800 "the subprocess ({child}) survived cancellation"
1801 );
1802 }
1803
1804 #[cfg(unix)]
1807 #[tokio::test]
1808 async fn timeout_stops_the_group_before_returning() {
1809 use crate::test_support::is_running_for_test;
1810
1811 let pid_file = crate::test_support::PidFile::new("group-timeout-settled");
1812 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1813 .join("tests")
1814 .join("fake-codex-spawns-child.sh");
1815 let codex = Codex::builder()
1816 .binary("/bin/bash")
1817 .arg(script.to_str().unwrap())
1818 .env(
1819 "CODEX_WRAPPER_TEST_PIDFILE",
1820 pid_file.path().to_str().unwrap(),
1821 )
1822 .timeout(Duration::from_millis(300))
1823 .termination_grace(Duration::from_millis(10))
1824 .build()
1825 .unwrap();
1826
1827 let result = run_codex(&codex, vec!["exec".into()]).await;
1828 assert!(
1829 matches!(result, Err(Error::Timeout { .. })),
1830 "expected a timeout, got: {result:?}"
1831 );
1832
1833 let (parent, child) = read_pids(&pid_file).await;
1834 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1835 assert!(
1836 !is_running_for_test(child),
1837 "the subprocess ({child}) survived the timeout"
1838 );
1839 }
1840
1841 #[cfg(unix)]
1845 #[tokio::test]
1846 async fn stdin_write_failure_stops_and_reaps_before_returning() {
1847 use crate::test_support::is_running_for_test;
1848
1849 let pid_file = crate::test_support::PidFile::new("stdin-write-failure");
1850 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1851 .join("tests")
1852 .join("fake-codex-closes-stdin-spawns-child.sh");
1853 let codex = Codex::builder()
1854 .binary("/bin/bash")
1855 .arg(script.to_str().unwrap())
1856 .env(
1857 "CODEX_WRAPPER_TEST_PIDFILE",
1858 pid_file.path().to_str().unwrap(),
1859 )
1860 .termination_grace(Duration::from_millis(10))
1861 .build()
1862 .unwrap();
1863
1864 let prompt = "x".repeat(4 * 1024 * 1024);
1865 let result = run_codex_with_stdin_prompt(
1866 &codex,
1867 crate::ExecCommand::from_stdin(&prompt).args(),
1868 &prompt,
1869 )
1870 .await;
1871 assert!(
1872 matches!(result, Err(Error::Io { ref message, .. }) if message.contains("stdin")),
1873 "expected a stdin error, got: {result:?}"
1874 );
1875
1876 let (parent, child) = read_pids(&pid_file).await;
1877 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1878 assert!(
1879 !is_running_for_test(child),
1880 "the subprocess ({child}) survived the stdin failure"
1881 );
1882 }
1883
1884 #[cfg(unix)]
1887 #[tokio::test]
1888 async fn a_run_that_finishes_first_is_not_cancelled() {
1889 let codex = Codex::builder()
1890 .binary("/bin/echo")
1891 .build()
1892 .expect("echo must exist");
1893
1894 let never = std::future::pending::<()>();
1895 let output = run_codex_cancellable(&codex, vec!["exec".into()], never)
1896 .await
1897 .unwrap();
1898 assert!(output.success);
1899 }
1900
1901 #[cfg(unix)]
1902 #[tokio::test]
1903 async fn spawn_observer_reports_each_buffered_child_before_returning() {
1904 use std::sync::{Arc, Mutex};
1905
1906 let seen = Arc::new(Mutex::new(Vec::new()));
1907 let sink = Arc::clone(&seen);
1908 let codex = Codex::builder()
1909 .binary("/bin/echo")
1910 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1911 .build()
1912 .expect("echo must exist");
1913
1914 let output = run_codex(&codex, vec!["probe".into()]).await.unwrap();
1915 let seen = seen.lock().unwrap();
1916 assert_eq!(seen.len(), 1);
1917 assert!(seen[0].pid > 0);
1918 assert_eq!(seen[0].pgid, Some(seen[0].pid));
1919 assert!(output.stdout.contains("probe"));
1920 }
1921
1922 #[cfg(unix)]
1923 #[tokio::test]
1924 async fn spawn_receipt_never_claims_a_shared_group() {
1925 use std::sync::{Arc, Mutex};
1926
1927 let seen = Arc::new(Mutex::new(Vec::new()));
1928 let sink = Arc::clone(&seen);
1929 let codex = Codex::builder()
1930 .binary("/bin/echo")
1931 .process_group(false)
1932 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1933 .build()
1934 .expect("echo must exist");
1935
1936 run_codex(&codex, vec!["probe".into()]).await.unwrap();
1937 assert_eq!(seen.lock().unwrap()[0].pgid, None);
1938 }
1939
1940 #[test]
1941 fn parent_death_support_matches_the_target() {
1942 assert_eq!(die_with_parent_supported(), cfg!(target_os = "linux"));
1943 }
1944
1945 #[cfg(unix)]
1946 #[tokio::test]
1947 async fn parent_death_policy_composes_with_spawn_observation() {
1948 use std::sync::{Arc, Mutex};
1949
1950 let seen = Arc::new(Mutex::new(Vec::new()));
1951 let sink = Arc::clone(&seen);
1952 let codex = Codex::builder()
1953 .binary("/bin/echo")
1954 .die_with_parent(true)
1955 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1956 .build()
1957 .expect("echo must exist");
1958
1959 run_codex(&codex, vec!["probe".into()]).await.unwrap();
1960 assert_eq!(seen.lock().unwrap().len(), 1);
1961 }
1962
1963 const PDEATHSIG_HELPER_ENV: &str = "CODEX_WRAPPER_PDEATHSIG_HELPER";
1964
1965 #[test]
1966 fn pdeathsig_helper_process() {
1967 if std::env::var(PDEATHSIG_HELPER_ENV).is_err() {
1968 return;
1969 }
1970 use std::io::Write;
1971 use std::sync::Arc;
1972
1973 let codex = Codex::builder()
1974 .binary("/bin/sleep")
1975 .die_with_parent(true)
1976 .on_spawn(Arc::new(|info| {
1977 println!("PID {}", info.pid);
1978 let _ = std::io::stdout().flush();
1979 }))
1980 .build()
1981 .unwrap();
1982 let runtime = tokio::runtime::Builder::new_current_thread()
1983 .enable_all()
1984 .build()
1985 .unwrap();
1986 let _ = runtime.block_on(run_codex(&codex, vec!["300".into()]));
1987 }
1988
1989 #[cfg(target_os = "linux")]
1990 #[test]
1991 fn child_dies_when_its_parent_is_sigkilled() {
1992 use std::io::{BufRead, BufReader};
1993 use std::process::{Command, Stdio};
1994
1995 let executable = std::env::current_exe().expect("test binary path");
1996 let mut helper = Command::new(executable)
1997 .args([
1998 "--exact",
1999 "exec::tests::pdeathsig_helper_process",
2000 "--nocapture",
2001 ])
2002 .env(PDEATHSIG_HELPER_ENV, "1")
2003 .stdout(Stdio::piped())
2004 .spawn()
2005 .expect("spawn helper");
2006 let stdout = helper.stdout.take().expect("piped stdout");
2007 let pid = BufReader::new(stdout)
2008 .lines()
2009 .map_while(std::result::Result::ok)
2010 .find_map(|line| line.strip_prefix("PID ").and_then(|pid| pid.parse().ok()))
2011 .expect("helper reported child pid");
2012
2013 unsafe { libc::kill(helper.id() as i32, libc::SIGKILL) };
2015 let _ = helper.wait();
2016
2017 for _ in 0..50 {
2018 if !crate::test_support::is_running_for_test(pid) {
2019 return;
2020 }
2021 std::thread::sleep(Duration::from_millis(100));
2022 }
2023 panic!("child {pid} survived its SIGKILLed parent");
2024 }
2025
2026 #[cfg(unix)]
2031 #[tokio::test]
2032 async fn opting_out_of_process_groups_leaves_the_subprocess() {
2033 use crate::test_support::wait_until_gone;
2034
2035 let pid_file = crate::test_support::PidFile::new("group-optout");
2036 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2037 .join("tests")
2038 .join("fake-codex-spawns-child.sh");
2039 let codex = Codex::builder()
2040 .binary("/bin/bash")
2041 .arg(script.to_str().unwrap())
2042 .env(
2043 "CODEX_WRAPPER_TEST_PIDFILE",
2044 pid_file.path().to_str().unwrap(),
2045 )
2046 .process_group(false)
2047 .build()
2048 .expect("bash must exist");
2049
2050 let cancelled = tokio::time::timeout(
2051 Duration::from_millis(400),
2052 run_codex(&codex, vec!["exec".into()]),
2053 )
2054 .await;
2055 assert!(cancelled.is_err(), "the run should still have been going");
2056
2057 let (parent, child) = read_pids(&pid_file).await;
2058 assert!(
2059 wait_until_gone(parent).await,
2060 "kill_on_drop still reaps the direct child ({parent})"
2061 );
2062 assert!(
2065 crate::test_support::is_running_for_test(child),
2066 "with groups off, the subprocess ({child}) is expected to survive"
2067 );
2068 signal_group(child, libc::SIGKILL);
2070 unsafe { libc::kill(i32::try_from(child).unwrap_or(0), libc::SIGKILL) };
2071 }
2072}