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, 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 die_with_parent: codex.die_with_parent,
413 on_spawn: codex.on_spawn.as_ref(),
414 },
415 Some(timeout_stop(timeout)),
416 codex.termination_grace,
417 )
418 .await
419 }
420 None => {
421 run_internal_inner(
422 SpawnSpec {
423 binary: &codex.binary,
424 args: &command_args,
425 env: &codex.env,
426 clear_env: codex.clear_env,
427 working_dir: codex.working_dir.as_deref(),
428 stdin_prompt: None,
429 process_group: codex.process_group,
430 die_with_parent: codex.die_with_parent,
431 on_spawn: codex.on_spawn.as_ref(),
432 },
433 None,
434 Duration::ZERO,
435 )
436 .await
437 }
438 };
439 outcome.settle_from(&result);
440 result
441 }
442 .instrument(span)
443 .await
444}
445
446pub async fn run_codex_cancellable<C>(
462 codex: &Codex,
463 args: Vec<String>,
464 cancel: C,
465) -> Result<CommandOutput>
466where
467 C: std::future::Future<Output = ()> + Send,
468{
469 let span = command_span("codex.exec", codex, &args);
470 let outcome_span = span.clone();
471 let command_args = assemble_args(codex, args);
472
473 async move {
474 debug!(binary = %codex.binary.display(), args = ?command_args, "executing cancellable codex command");
475
476 let mut outcome = SpanOutcome::start(outcome_span);
477 let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
478 let result = run_internal_inner(
479 SpawnSpec {
480 binary: &codex.binary,
481 args: &command_args,
482 env: &codex.env,
483 clear_env: codex.clear_env,
484 working_dir: codex.working_dir.as_deref(),
485 stdin_prompt: None,
486 process_group: codex.process_group,
487 die_with_parent: codex.die_with_parent,
488 on_spawn: codex.on_spawn.as_ref(),
489 },
490 Some(stop),
491 codex.termination_grace,
492 )
493 .await;
494
495 match &result {
496 Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
497 other => outcome.settle_from_ref(other),
498 }
499 result
500 }
501 .instrument(span)
502 .await
503}
504
505pub async fn run_codex_allow_exit_codes(
507 codex: &Codex,
508 args: Vec<String>,
509 allowed_codes: &[i32],
510) -> Result<CommandOutput> {
511 let output = run_codex(codex, args).await;
512
513 match output {
514 Err(e)
518 if e.exit_code()
519 .is_some_and(|code| allowed_codes.contains(&code)) =>
520 {
521 let exit_code = e.exit_code().unwrap_or(-1);
522 let (stdout, stderr) = match &e {
523 Error::CommandFailed { stdout, stderr, .. } => (stdout.clone(), stderr.clone()),
524 Error::Auth { message, .. }
525 | Error::Config { message, .. }
526 | Error::NotTrustedDirectory { message, .. }
527 | Error::SessionNotFound { message, .. } => (String::new(), message.clone()),
528 _ => (String::new(), String::new()),
529 };
530 Ok(CommandOutput {
531 stdout,
532 stderr,
533 exit_code,
534 success: false,
535 })
536 }
537 other => other,
538 }
539}
540
541pub async fn run_codex_with_stdin_prompt(
553 codex: &Codex,
554 args: Vec<String>,
555 prompt: &str,
556) -> Result<CommandOutput> {
557 let span = command_span("codex.exec", codex, &args);
558 let outcome_span = span.clone();
559 let command_args = assemble_args(codex, args);
560
561 async move {
562 debug!(
563 binary = %codex.binary.display(),
564 args = ?command_args,
565 prompt_bytes = prompt.len(),
566 "executing codex command with a stdin prompt"
567 );
568
569 let mut outcome = SpanOutcome::start(outcome_span);
570 let stop = codex.timeout.map(timeout_stop);
571 let result = run_internal_inner(
572 SpawnSpec {
573 binary: &codex.binary,
574 args: &command_args,
575 env: &codex.env,
576 clear_env: codex.clear_env,
577 working_dir: codex.working_dir.as_deref(),
578 stdin_prompt: Some(prompt),
579 process_group: codex.process_group,
580 die_with_parent: codex.die_with_parent,
581 on_spawn: codex.on_spawn.as_ref(),
582 },
583 stop,
584 codex.termination_grace,
585 )
586 .await;
587 outcome.settle_from(&result);
588 result
589 }
590 .instrument(span)
591 .await
592}
593
594pub async fn run_codex_with_stdin_prompt_cancellable<C>(
599 codex: &Codex,
600 args: Vec<String>,
601 prompt: &str,
602 cancel: C,
603) -> Result<CommandOutput>
604where
605 C: std::future::Future<Output = ()> + Send,
606{
607 let span = command_span("codex.exec", codex, &args);
608 let outcome_span = span.clone();
609 let command_args = assemble_args(codex, args);
610
611 async move {
612 debug!(
613 binary = %codex.binary.display(),
614 args = ?command_args,
615 prompt_bytes = prompt.len(),
616 "executing cancellable codex command with a stdin prompt"
617 );
618
619 let mut outcome = SpanOutcome::start(outcome_span);
620 let stop = cancellation_or_timeout(cancel, codex.timeout, codex.termination_grace);
621 let result = run_internal_inner(
622 SpawnSpec {
623 binary: &codex.binary,
624 args: &command_args,
625 env: &codex.env,
626 clear_env: codex.clear_env,
627 working_dir: codex.working_dir.as_deref(),
628 stdin_prompt: Some(prompt),
629 process_group: codex.process_group,
630 die_with_parent: codex.die_with_parent,
631 on_spawn: codex.on_spawn.as_ref(),
632 },
633 Some(stop),
634 codex.termination_grace,
635 )
636 .await;
637
638 match &result {
639 Err(Error::Cancelled { .. }) => outcome.settle("cancelled", None),
640 other => outcome.settle_from_ref(other),
641 }
642 result
643 }
644 .instrument(span)
645 .await
646}
647
648#[derive(Clone, Copy, Debug)]
649enum StopReason {
650 Cancelled { grace_seconds: u64 },
651 Timeout { timeout_seconds: u64 },
652}
653
654impl StopReason {
655 fn into_error(self) -> Error {
656 match self {
657 Self::Cancelled { grace_seconds } => Error::Cancelled { grace_seconds },
658 Self::Timeout { timeout_seconds } => Error::Timeout { timeout_seconds },
659 }
660 }
661}
662
663type StopFuture<'a> = std::pin::Pin<Box<dyn std::future::Future<Output = StopReason> + Send + 'a>>;
664
665fn timeout_stop(timeout: Duration) -> StopFuture<'static> {
666 Box::pin(async move {
667 tokio::time::sleep(timeout).await;
668 StopReason::Timeout {
669 timeout_seconds: timeout.as_secs(),
670 }
671 })
672}
673
674fn cancellation_or_timeout<'a, C>(
675 cancel: C,
676 timeout: Option<Duration>,
677 grace: Duration,
678) -> StopFuture<'a>
679where
680 C: std::future::Future<Output = ()> + Send + 'a,
681{
682 Box::pin(async move {
683 match timeout {
684 Some(timeout) => tokio::select! {
685 () = cancel => StopReason::Cancelled {
686 grace_seconds: grace.as_secs(),
687 },
688 () = tokio::time::sleep(timeout) => StopReason::Timeout {
689 timeout_seconds: timeout.as_secs(),
690 },
691 },
692 None => {
693 cancel.await;
694 StopReason::Cancelled {
695 grace_seconds: grace.as_secs(),
696 }
697 }
698 }
699 })
700}
701
702struct SpawnSpec<'a> {
704 binary: &'a std::path::Path,
705 args: &'a [String],
706 env: &'a std::collections::HashMap<String, String>,
707 clear_env: bool,
709 working_dir: Option<&'a std::path::Path>,
710 stdin_prompt: Option<&'a str>,
712 process_group: bool,
714 die_with_parent: bool,
716 on_spawn: Option<&'a crate::SpawnObserver>,
718}
719
720async fn run_internal_inner(
721 spec: SpawnSpec<'_>,
722 stop: Option<StopFuture<'_>>,
723 grace: Duration,
724) -> Result<CommandOutput> {
725 let SpawnSpec {
726 binary,
727 args,
728 env,
729 clear_env,
730 working_dir,
731 stdin_prompt,
732 process_group,
733 die_with_parent,
734 on_spawn,
735 } = spec;
736 let mut cmd = Command::new(binary);
737 cmd.args(args);
738
739 if stdin_prompt.is_some() {
742 cmd.stdin(std::process::Stdio::piped());
743 } else {
744 cmd.stdin(std::process::Stdio::null());
745 }
746
747 cmd.kill_on_drop(true);
751 own_process_group(&mut cmd, process_group);
752 apply_die_with_parent(&mut cmd, die_with_parent);
753
754 if let Some(dir) = working_dir {
755 cmd.current_dir(dir);
756 }
757
758 apply_child_environment(&mut cmd, clear_env, env);
759
760 cmd.stdout(std::process::Stdio::piped());
764 cmd.stderr(std::process::Stdio::piped());
765
766 let mut child = cmd.spawn().map_err(|e| Error::Io {
767 message: format!("failed to spawn codex: {e}"),
768 source: e,
769 working_dir: working_dir.map(|p| p.to_path_buf()),
770 })?;
771
772 let mut group = arm_and_notify(process_group, child.id(), on_spawn);
777 let child_stdin = child.stdin.take();
778 let mut child_stdout = child.stdout.take().expect("stdout was configured as piped");
779 let mut child_stderr = child.stderr.take().expect("stderr was configured as piped");
780
781 let write = async move {
782 let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
783 return Ok(());
784 };
785 use tokio::io::AsyncWriteExt;
786 stdin
787 .write_all(prompt.as_bytes())
788 .await
789 .map_err(|e| Error::Io {
790 message: format!("failed to write the prompt to codex stdin: {e}"),
791 source: e,
792 working_dir: working_dir.map(|p| p.to_path_buf()),
793 })?;
794 stdin.shutdown().await.map_err(|e| Error::Io {
797 message: format!("failed to close codex stdin: {e}"),
798 source: e,
799 working_dir: working_dir.map(|p| p.to_path_buf()),
800 })
801 };
802
803 let read_stdout = async move {
808 use tokio::io::AsyncReadExt;
809 let mut bytes = Vec::new();
810 child_stdout
811 .read_to_end(&mut bytes)
812 .await
813 .map(|_| bytes)
814 .map_err(|e| Error::Io {
815 message: format!("failed to read codex stdout: {e}"),
816 source: e,
817 working_dir: working_dir.map(|p| p.to_path_buf()),
818 })
819 };
820 let read_stderr = async move {
821 use tokio::io::AsyncReadExt;
822 let mut bytes = Vec::new();
823 child_stderr
824 .read_to_end(&mut bytes)
825 .await
826 .map(|_| bytes)
827 .map_err(|e| Error::Io {
828 message: format!("failed to read codex stderr: {e}"),
829 source: e,
830 working_dir: working_dir.map(|p| p.to_path_buf()),
831 })
832 };
833 let wait = async { child.wait().await.map_err(|e| wait_error(e, working_dir)) };
834 let run = async {
835 let ((), stdout, stderr, status) = tokio::try_join!(write, read_stdout, read_stderr, wait)?;
836 Ok::<_, Error>((stdout, stderr, status))
837 };
838
839 let finished = match stop {
840 None => Ok(run.await),
841 Some(stop) => tokio::select! {
845 outcome = run => Ok(outcome),
846 reason = stop => Err(reason),
847 },
848 };
849
850 let (stdout, stderr, status) = match finished {
851 Ok(Ok(finished)) => finished,
852 Ok(Err(error)) => {
853 terminate_and_reap(&mut child, &mut group, grace, working_dir).await?;
857 return Err(error);
858 }
859 Err(reason) => {
860 terminate_and_reap(&mut child, &mut group, grace, working_dir).await?;
866 return Err(reason.into_error());
867 }
868 };
869
870 group.disarm();
872
873 let stdout = String::from_utf8_lossy(&stdout).to_string();
874 let stderr = String::from_utf8_lossy(&stderr).to_string();
875 let exit_code = status.code().unwrap_or(-1);
876
877 if !status.success() {
878 return Err(Error::from_command_failure(
879 format!("{} {}", binary.display(), args.join(" ")),
880 exit_code,
881 stdout,
882 stderr,
883 working_dir.map(|p| p.to_path_buf()),
884 ));
885 }
886
887 Ok(CommandOutput {
888 stdout,
889 stderr,
890 exit_code,
891 success: true,
892 })
893}
894
895async fn terminate_and_reap(
896 child: &mut tokio::process::Child,
897 group: &mut GroupKillGuard,
898 grace: Duration,
899 working_dir: Option<&std::path::Path>,
900) -> Result<()> {
901 group.terminate(grace).await;
902 if child
903 .try_wait()
904 .map_err(|e| wait_error(e, working_dir))?
905 .is_none()
906 && let Err(error) = child.start_kill()
907 && error.kind() != std::io::ErrorKind::InvalidInput
908 {
909 return Err(wait_error(error, working_dir));
910 }
911 child.wait().await.map_err(|e| wait_error(e, working_dir))?;
912 Ok(())
913}
914
915fn wait_error(error: std::io::Error, working_dir: Option<&std::path::Path>) -> Error {
916 Error::Io {
917 message: format!("failed to wait on codex: {error}"),
918 source: error,
919 working_dir: working_dir.map(|p| p.to_path_buf()),
920 }
921}
922
923pub(crate) fn apply_child_environment(
928 cmd: &mut Command,
929 clear_env: bool,
930 env: &std::collections::HashMap<String, String>,
931) {
932 if clear_env {
933 cmd.env_clear();
934 }
935 cmd.envs(env);
936}
937
938#[cfg(test)]
939mod tests {
940 use super::*;
941 use crate::CodexCommand;
942
943 #[test]
944 fn typed_rollout_budget_suppresses_conflicting_client_global_toggles() {
945 let codex = Codex::builder()
946 .binary("/bin/echo")
947 .config("features.rollout_budget=false")
948 .enable("rollout_budget")
949 .disable("rollout_budget")
950 .arg("--enable=rollout_budget")
951 .arg("--disable=rollout_budget")
952 .arg("--disable")
953 .arg("rollout_budget")
954 .enable("keep-enabled")
955 .disable("keep-disabled")
956 .build()
957 .expect("echo must exist");
958 let budget = crate::RolloutBudgetConfig::builder(10_000)
959 .build()
960 .expect("valid budget");
961 let expected = budget.config_override();
962 let opening = crate::ExecCommand::new("hi")
963 .rollout_budget(budget.clone())
964 .args();
965 let resumed = crate::ExecResumeCommand::new()
966 .session_id("thread")
967 .rollout_budget(budget)
968 .args();
969
970 for args in [opening, resumed] {
971 let assembled = assemble_args(&codex, args);
972 assert!(assembled.iter().any(|arg| arg == &expected));
973 assert!(
974 !assembled.windows(2).any(|pair| {
975 matches!(pair[0].as_str(), "--enable" | "--disable")
976 && pair[1] == "rollout_budget"
977 }),
978 "typed budget must suppress paired client toggles: {assembled:?}"
979 );
980 assert!(
981 !assembled.iter().any(|arg| {
982 matches!(
983 arg.as_str(),
984 "--enable=rollout_budget" | "--disable=rollout_budget"
985 )
986 }),
987 "typed budget must suppress equals-form client toggles: {assembled:?}"
988 );
989 assert!(
990 assembled
991 .windows(2)
992 .any(|pair| pair == ["--enable", "keep-enabled"])
993 );
994 assert!(
995 assembled
996 .windows(2)
997 .any(|pair| pair == ["--disable", "keep-disabled"])
998 );
999 }
1000 }
1001
1002 fn make_output(stdout: &str, stderr: &str) -> CommandOutput {
1003 CommandOutput {
1004 stdout: stdout.to_string(),
1005 stderr: stderr.to_string(),
1006 exit_code: 0,
1007 success: true,
1008 }
1009 }
1010
1011 #[test]
1012 fn shell_quote_leaves_plain_words_alone() {
1013 assert_eq!(shell_quote("exec"), "exec");
1014 assert_eq!(shell_quote("--ephemeral"), "--ephemeral");
1015 assert_eq!(shell_quote("model=gpt-5"), "model=gpt-5");
1016 }
1017
1018 #[test]
1019 fn shell_quote_wraps_anything_a_shell_would_read() {
1020 assert_eq!(shell_quote("fix the tests"), "'fix the tests'");
1021 assert_eq!(shell_quote("$HOME"), "'$HOME'");
1022 assert_eq!(shell_quote("a;b"), "'a;b'");
1023 assert_eq!(shell_quote("*.rs"), "'*.rs'");
1024 assert_eq!(shell_quote("it's"), r"'it'\''s'");
1025 }
1026
1027 #[test]
1030 fn shell_quote_keeps_the_empty_argument_visible() {
1031 assert_eq!(shell_quote(""), "''");
1032 }
1033
1034 #[test]
1035 fn debug_short_output_not_truncated() {
1036 let output = make_output("hello", "world");
1037 let debug = format!("{output:?}");
1038 assert!(debug.contains("hello"));
1039 assert!(debug.contains("world"));
1040 assert!(!debug.contains("bytes total"));
1041 }
1042
1043 #[test]
1044 fn debug_long_output_truncated() {
1045 let long = "x".repeat(300);
1046 let output = make_output(&long, &long);
1047 let debug = format!("{output:?}");
1048 assert!(debug.contains("... (300 bytes total)"));
1049 assert!(!debug.contains(&long));
1050 }
1051
1052 #[cfg(unix)]
1055 #[tokio::test]
1056 async fn child_environment_is_inherited_by_default() {
1057 let capture = crate::test_support::EnvCapture::new("env-default");
1058 let codex = crate::test_support::env_capturing_codex(&capture)
1059 .build()
1060 .expect("bash must exist");
1061
1062 crate::ExecCommand::new("probe")
1063 .execute(&codex)
1064 .await
1065 .unwrap();
1066
1067 let environment = capture.read();
1068 assert_eq!(
1069 environment.get("PATH"),
1070 Some(&std::env::var("PATH").expect("test process must have PATH"))
1071 );
1072 }
1073
1074 #[cfg(unix)]
1078 #[tokio::test]
1079 async fn cleared_environment_reaches_buffered_open_and_resume() {
1080 let capture = crate::test_support::EnvCapture::new("env-buffered");
1081 let opening_client = crate::test_support::env_capturing_codex(&capture)
1082 .clear_env()
1083 .env("CODEX_WRAPPER_EXPLICIT", "opening")
1084 .timeout(Duration::from_secs(2))
1085 .build()
1086 .expect("bash must exist");
1087
1088 crate::ExecCommand::new("probe")
1089 .execute(&opening_client)
1090 .await
1091 .unwrap();
1092 let opening_environment = capture.read();
1093 assert!(!opening_environment.contains_key("PATH"));
1094 assert_eq!(
1095 opening_environment
1096 .get("CODEX_WRAPPER_EXPLICIT")
1097 .map(String::as_str),
1098 Some("opening")
1099 );
1100 assert!(opening_environment.contains_key("CODEX_WRAPPER_ENV_CAPTURE"));
1101
1102 let resume_client = crate::test_support::env_capturing_codex(&capture)
1103 .clear_env()
1104 .env("CODEX_WRAPPER_EXPLICIT", "resume")
1105 .build()
1106 .expect("bash must exist");
1107 crate::ExecResumeCommand::new()
1108 .last()
1109 .execute(&resume_client)
1110 .await
1111 .unwrap();
1112 let resume_environment = capture.read();
1113 assert!(!resume_environment.contains_key("PATH"));
1114 assert_eq!(
1115 resume_environment
1116 .get("CODEX_WRAPPER_EXPLICIT")
1117 .map(String::as_str),
1118 Some("resume")
1119 );
1120 }
1121
1122 #[cfg(unix)]
1126 #[tokio::test]
1127 async fn cleared_environment_reaches_stdin_and_cancellable_runs() {
1128 let capture = crate::test_support::EnvCapture::new("env-specialized");
1129 let codex = crate::test_support::env_capturing_codex(&capture)
1130 .env("CODEX_WRAPPER_EXPLICIT", "specialized")
1131 .clear_env()
1132 .build()
1133 .expect("bash must exist");
1134
1135 crate::ExecCommand::new("stdin prompt")
1136 .prompt_via_stdin()
1137 .execute(&codex)
1138 .await
1139 .unwrap();
1140 let stdin_environment = capture.read();
1141 assert!(!stdin_environment.contains_key("PATH"));
1142 assert_eq!(
1143 stdin_environment
1144 .get("CODEX_WRAPPER_EXPLICIT")
1145 .map(String::as_str),
1146 Some("specialized")
1147 );
1148
1149 let never = std::future::pending::<()>();
1150 run_codex_cancellable(&codex, crate::ExecCommand::new("cancellable").args(), never)
1151 .await
1152 .unwrap();
1153 let cancellable_environment = capture.read();
1154 assert!(!cancellable_environment.contains_key("PATH"));
1155 assert_eq!(
1156 cancellable_environment
1157 .get("CODEX_WRAPPER_EXPLICIT")
1158 .map(String::as_str),
1159 Some("specialized")
1160 );
1161 }
1162
1163 #[cfg(unix)]
1164 #[tokio::test]
1165 async fn environment_values_do_not_leak_into_spawn_errors() {
1166 let secret = "spawn-error-must-not-leak-this";
1167 let codex = Codex::builder()
1168 .binary("/codex-wrapper/this-binary-does-not-exist")
1169 .clear_env()
1170 .env("CODEX_WRAPPER_SECRET", secret)
1171 .build()
1172 .unwrap();
1173
1174 let error = run_codex(&codex, vec!["exec".into()])
1175 .await
1176 .expect_err("the fake path must not spawn");
1177 assert!(!error.to_string().contains(secret));
1178 assert!(!format!("{error:?}").contains(secret));
1179 }
1180
1181 #[cfg(unix)]
1183 #[tokio::test]
1184 async fn timeout_kills_the_spawned_process() {
1185 use crate::test_support::{PidFile, blocking_codex, is_running_for_test};
1186
1187 let pid_file = PidFile::new("exec-timeout");
1188 let codex = blocking_codex(&pid_file)
1189 .timeout(Duration::from_millis(500))
1190 .build()
1191 .expect("bash must exist");
1192
1193 let result = run_codex(&codex, vec!["exec".into(), "probe".into()]).await;
1194 assert!(
1195 matches!(result, Err(Error::Timeout { .. })),
1196 "expected timeout error, got: {result:?}"
1197 );
1198
1199 let pid = pid_file.read_pid().await;
1200 assert!(
1201 !is_running_for_test(pid),
1202 "codex ({pid}) survived the timeout"
1203 );
1204 }
1205
1206 #[cfg(unix)]
1209 #[tokio::test]
1210 async fn cancellation_kills_the_spawned_process() {
1211 use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
1212
1213 let pid_file = PidFile::new("exec-cancel");
1214 let codex = blocking_codex(&pid_file).build().expect("bash must exist");
1215
1216 let cancelled = tokio::time::timeout(
1217 Duration::from_millis(500),
1218 run_codex(&codex, vec!["exec".into(), "probe".into()]),
1219 )
1220 .await;
1221 assert!(
1222 cancelled.is_err(),
1223 "fake codex should still have been running, got: {cancelled:?}"
1224 );
1225
1226 let pid = pid_file.read_pid().await;
1227 assert!(
1228 wait_until_gone(pid).await,
1229 "codex ({pid}) survived the dropped future"
1230 );
1231 }
1232
1233 #[cfg(unix)]
1244 mod recorder {
1245 use std::cell::RefCell;
1246 use std::sync::{Arc, Mutex, Once};
1247
1248 use tracing::field::{Field, Visit};
1249 use tracing::span::{Attributes, Id, Record};
1250 use tracing::{Event, Metadata, Subscriber};
1251
1252 type Sink = Arc<Mutex<Vec<(String, String)>>>;
1253
1254 thread_local! {
1255 static SINK: RefCell<Option<Sink>> = const { RefCell::new(None) };
1256 }
1257
1258 struct Global;
1259
1260 impl Global {
1261 fn collect(f: impl FnOnce(&mut Vec<(String, String)>)) {
1262 SINK.with(|sink| {
1263 if let Some(sink) = sink.borrow().as_ref() {
1264 f(&mut sink.lock().unwrap());
1265 }
1266 });
1267 }
1268 }
1269
1270 impl Subscriber for Global {
1271 fn enabled(&self, _: &Metadata<'_>) -> bool {
1273 true
1274 }
1275 fn new_span(&self, attrs: &Attributes<'_>) -> Id {
1276 Self::collect(|fields| attrs.record(&mut Collect(fields)));
1277 Id::from_u64(1)
1278 }
1279 fn record(&self, _: &Id, values: &Record<'_>) {
1280 Self::collect(|fields| values.record(&mut Collect(fields)));
1281 }
1282 fn record_follows_from(&self, _: &Id, _: &Id) {}
1283 fn event(&self, _: &Event<'_>) {}
1284 fn enter(&self, _: &Id) {}
1285 fn exit(&self, _: &Id) {}
1286 }
1287
1288 struct Collect<'a>(&'a mut Vec<(String, String)>);
1289
1290 impl Visit for Collect<'_> {
1291 fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) {
1292 self.0.push((field.name().into(), format!("{value:?}")));
1293 }
1294 fn record_str(&mut self, field: &Field, value: &str) {
1295 self.0.push((field.name().into(), value.into()));
1296 }
1297 fn record_i64(&mut self, field: &Field, value: i64) {
1298 self.0.push((field.name().into(), value.to_string()));
1299 }
1300 fn record_u64(&mut self, field: &Field, value: u64) {
1301 self.0.push((field.name().into(), value.to_string()));
1302 }
1303 }
1304
1305 pub(super) struct Recorder(Sink);
1306
1307 impl Recorder {
1308 pub(super) fn install() -> Self {
1310 static INIT: Once = Once::new();
1311 INIT.call_once(|| {
1312 let _ = tracing::subscriber::set_global_default(Global);
1313 });
1314 let sink: Sink = Arc::new(Mutex::new(Vec::new()));
1315 SINK.with(|slot| *slot.borrow_mut() = Some(Arc::clone(&sink)));
1316 Self(sink)
1317 }
1318
1319 pub(super) fn dump(&self) -> String {
1320 format!("{:?}", self.0.lock().unwrap())
1321 }
1322
1323 pub(super) fn value(&self, field: &str) -> Option<String> {
1324 self.0
1325 .lock()
1326 .unwrap()
1327 .iter()
1328 .rev()
1329 .find(|(name, _)| name == field)
1330 .map(|(_, value)| value.clone())
1331 }
1332 }
1333
1334 impl Drop for Recorder {
1335 fn drop(&mut self) {
1336 SINK.with(|slot| *slot.borrow_mut() = None);
1337 }
1338 }
1339 }
1340
1341 #[cfg(unix)]
1342 #[tokio::test]
1343 async fn span_records_the_subcommand_and_a_clean_outcome() {
1344 let recorder = recorder::Recorder::install();
1345
1346 let codex = Codex::builder()
1347 .binary("/bin/echo")
1348 .build()
1349 .expect("echo must exist");
1350 run_codex(&codex, vec!["exec".into()]).await.unwrap();
1351
1352 assert_eq!(recorder.value("subcommand").as_deref(), Some("exec"));
1353 assert_eq!(recorder.value("outcome").as_deref(), Some("ok"));
1354 assert_eq!(recorder.value("exit_code").as_deref(), Some("0"));
1355 assert!(recorder.value("duration_ms").is_some());
1356 }
1357
1358 #[cfg(unix)]
1361 #[tokio::test]
1362 async fn span_does_not_carry_the_prompt() {
1363 let recorder = recorder::Recorder::install();
1364
1365 let codex = Codex::builder()
1366 .binary("/bin/echo")
1367 .build()
1368 .expect("echo must exist");
1369 run_codex(&codex, vec!["exec".into(), "a very secret prompt".into()])
1370 .await
1371 .unwrap();
1372
1373 let recorded = format!("{:?}", recorder.value("subcommand"));
1374 assert!(!recorded.contains("secret"));
1375 for field in ["binary", "working_dir", "outcome", "exit_code"] {
1376 let value = recorder.value(field).unwrap_or_default();
1377 assert!(
1378 !value.contains("secret"),
1379 "{field} leaked the prompt: {value}"
1380 );
1381 }
1382 }
1383
1384 #[cfg(unix)]
1387 #[tokio::test]
1388 async fn a_cancelled_run_is_recorded_as_cancelled() {
1389 let recorder = recorder::Recorder::install();
1390
1391 let pid_file = crate::test_support::PidFile::new("span-cancel");
1392 let codex = crate::test_support::blocking_codex(&pid_file)
1393 .build()
1394 .expect("bash must exist");
1395
1396 let cancelled = tokio::time::timeout(
1397 Duration::from_millis(300),
1398 run_codex(&codex, vec!["exec".into()]),
1399 )
1400 .await;
1401 assert!(cancelled.is_err(), "the run should still have been going");
1402
1403 assert_eq!(
1404 recorder.value("outcome").as_deref(),
1405 Some("cancelled"),
1406 "recorded: {}",
1407 recorder.dump()
1408 );
1409 }
1410
1411 #[cfg(unix)]
1414 #[tokio::test]
1415 async fn a_timed_out_run_is_recorded_as_timeout() {
1416 let recorder = recorder::Recorder::install();
1417
1418 let pid_file = crate::test_support::PidFile::new("span-timeout");
1419 let codex = crate::test_support::blocking_codex(&pid_file)
1420 .timeout(Duration::from_millis(300))
1421 .build()
1422 .expect("bash must exist");
1423
1424 let result = run_codex(&codex, vec!["exec".into()]).await;
1425 assert!(matches!(result, Err(Error::Timeout { .. })), "{result:?}");
1426
1427 assert_eq!(recorder.value("outcome").as_deref(), Some("timeout"));
1428 }
1429
1430 #[cfg(unix)]
1435 fn failing_codex(case: &str) -> Codex {
1436 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1437 .join("tests")
1438 .join("fake-codex-failure.sh");
1439 Codex::builder()
1440 .binary("/bin/bash")
1441 .arg(script.to_str().unwrap())
1442 .env("CODEX_WRAPPER_TEST_FAILURE", case)
1443 .build()
1444 .expect("bash must exist")
1445 }
1446
1447 #[cfg(unix)]
1450 #[tokio::test]
1451 async fn a_real_spawn_returns_a_classified_error() {
1452 use crate::error::FailureKind;
1453
1454 for (case, expected) in [
1455 ("auth", FailureKind::Auth),
1456 ("not-trusted", FailureKind::NotTrustedDirectory),
1457 ("config", FailureKind::Config),
1458 ("session", FailureKind::SessionNotFound),
1459 ("mystery", FailureKind::Unclassified),
1460 ] {
1461 let codex = failing_codex(case);
1462 let err = run_codex(&codex, vec!["exec".into()]).await.unwrap_err();
1463 assert_eq!(err.failure_kind(), Some(expected), "case {case}: {err}");
1464 }
1465 }
1466
1467 #[cfg(unix)]
1471 #[tokio::test]
1472 async fn a_classified_failure_is_not_retried() {
1473 let policy = crate::retry::RetryPolicy::new()
1474 .max_attempts(3)
1475 .initial_backoff(Duration::from_millis(1))
1476 .retry_on_exit_codes([1]);
1477
1478 let started = Instant::now();
1479 let codex = failing_codex("auth");
1480 let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
1481 .await
1482 .unwrap_err();
1483
1484 assert!(matches!(err, Error::Auth { .. }), "{err}");
1485 assert!(
1488 started.elapsed() < Duration::from_secs(2),
1489 "looks like it retried: {:?}",
1490 started.elapsed()
1491 );
1492 }
1493
1494 #[cfg(unix)]
1496 #[tokio::test]
1497 async fn an_unclassified_failure_still_retries() {
1498 let policy = crate::retry::RetryPolicy::new()
1499 .max_attempts(2)
1500 .initial_backoff(Duration::from_millis(1))
1501 .retry_on_exit_codes([1]);
1502
1503 let codex = failing_codex("mystery");
1504 let err = run_codex_with_retry(&codex, vec!["exec".into()], Some(&policy))
1505 .await
1506 .unwrap_err();
1507
1508 assert!(matches!(err, Error::CommandFailed { .. }), "{err}");
1509 }
1510
1511 #[cfg(unix)]
1514 #[tokio::test]
1515 async fn allowed_exit_codes_still_apply_to_a_classified_failure() {
1516 let codex = failing_codex("auth");
1517 let output = run_codex_allow_exit_codes(&codex, vec!["exec".into()], &[1])
1518 .await
1519 .expect("exit code 1 was allowed");
1520
1521 assert_eq!(output.exit_code, 1);
1522 assert!(!output.success);
1523 assert!(
1524 output.stderr.contains("401 Unauthorized"),
1525 "{}",
1526 output.stderr
1527 );
1528 }
1529
1530 #[cfg(unix)]
1537 fn spawning_codex(label: &str) -> (Codex, crate::test_support::PidFile) {
1538 let pid_file = crate::test_support::PidFile::new(label);
1539 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1540 .join("tests")
1541 .join("fake-codex-spawns-child.sh");
1542 let codex = Codex::builder()
1543 .binary("/bin/bash")
1544 .arg(script.to_str().unwrap())
1545 .env(
1546 "CODEX_WRAPPER_TEST_PIDFILE",
1547 pid_file.path().to_str().unwrap(),
1548 )
1549 .build()
1550 .expect("bash must exist");
1551 (codex, pid_file)
1552 }
1553
1554 #[cfg(unix)]
1555 async fn read_pids(pid_file: &crate::test_support::PidFile) -> (u32, u32) {
1556 for _ in 0..200 {
1557 if let Ok(contents) = std::fs::read_to_string(pid_file.path()) {
1558 let parse = |prefix: &str| -> Option<u32> {
1559 contents
1560 .lines()
1561 .find_map(|l| l.strip_prefix(prefix))
1562 .and_then(|v| v.trim().parse().ok())
1563 };
1564 if let (Some(parent), Some(child)) = (parse("parent="), parse("child=")) {
1565 return (parent, child);
1566 }
1567 }
1568 tokio::time::sleep(Duration::from_millis(10)).await;
1569 }
1570 panic!("the fake codex never recorded both pids");
1571 }
1572
1573 #[cfg(unix)]
1576 #[tokio::test]
1577 async fn cancelling_kills_the_whole_process_group() {
1578 use crate::test_support::wait_until_gone;
1579
1580 let (codex, pid_file) = spawning_codex("group-drop");
1581
1582 let cancelled = tokio::time::timeout(
1583 Duration::from_millis(400),
1584 run_codex(&codex, vec!["exec".into()]),
1585 )
1586 .await;
1587 assert!(cancelled.is_err(), "the run should still have been going");
1588
1589 let (parent, child) = read_pids(&pid_file).await;
1590 assert!(wait_until_gone(parent).await, "codex ({parent}) survived");
1591 assert!(
1592 wait_until_gone(child).await,
1593 "the subprocess ({child}) survived the cancelled run"
1594 );
1595 }
1596
1597 #[cfg(unix)]
1600 #[tokio::test]
1601 async fn run_codex_cancellable_stops_the_group_gracefully() {
1602 use crate::test_support::is_running_for_test;
1603
1604 let (codex, pid_file) = spawning_codex("group-cancel");
1605 let codex = Codex::builder()
1606 .binary(codex.binary())
1607 .arg(
1608 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1609 .join("tests")
1610 .join("fake-codex-spawns-child.sh")
1611 .to_str()
1612 .unwrap(),
1613 )
1614 .env(
1615 "CODEX_WRAPPER_TEST_PIDFILE",
1616 pid_file.path().to_str().unwrap(),
1617 )
1618 .termination_grace(Duration::from_millis(50))
1619 .build()
1620 .unwrap();
1621
1622 let cancel = async {
1623 tokio::time::sleep(Duration::from_millis(300)).await;
1624 };
1625 let result = run_codex_cancellable(&codex, vec!["exec".into()], cancel).await;
1626
1627 assert!(
1628 matches!(result, Err(Error::Cancelled { .. })),
1629 "expected a cancellation, got: {result:?}"
1630 );
1631
1632 let (parent, child) = read_pids(&pid_file).await;
1633 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1634 assert!(
1635 !is_running_for_test(child),
1636 "the subprocess ({child}) survived cancellation"
1637 );
1638 }
1639
1640 #[cfg(unix)]
1643 #[tokio::test]
1644 async fn timeout_stops_the_group_before_returning() {
1645 use crate::test_support::is_running_for_test;
1646
1647 let pid_file = crate::test_support::PidFile::new("group-timeout-settled");
1648 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1649 .join("tests")
1650 .join("fake-codex-spawns-child.sh");
1651 let codex = Codex::builder()
1652 .binary("/bin/bash")
1653 .arg(script.to_str().unwrap())
1654 .env(
1655 "CODEX_WRAPPER_TEST_PIDFILE",
1656 pid_file.path().to_str().unwrap(),
1657 )
1658 .timeout(Duration::from_millis(300))
1659 .termination_grace(Duration::from_millis(10))
1660 .build()
1661 .unwrap();
1662
1663 let result = run_codex(&codex, vec!["exec".into()]).await;
1664 assert!(
1665 matches!(result, Err(Error::Timeout { .. })),
1666 "expected a timeout, got: {result:?}"
1667 );
1668
1669 let (parent, child) = read_pids(&pid_file).await;
1670 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1671 assert!(
1672 !is_running_for_test(child),
1673 "the subprocess ({child}) survived the timeout"
1674 );
1675 }
1676
1677 #[cfg(unix)]
1681 #[tokio::test]
1682 async fn stdin_write_failure_stops_and_reaps_before_returning() {
1683 use crate::test_support::is_running_for_test;
1684
1685 let pid_file = crate::test_support::PidFile::new("stdin-write-failure");
1686 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1687 .join("tests")
1688 .join("fake-codex-closes-stdin-spawns-child.sh");
1689 let codex = Codex::builder()
1690 .binary("/bin/bash")
1691 .arg(script.to_str().unwrap())
1692 .env(
1693 "CODEX_WRAPPER_TEST_PIDFILE",
1694 pid_file.path().to_str().unwrap(),
1695 )
1696 .termination_grace(Duration::from_millis(10))
1697 .build()
1698 .unwrap();
1699
1700 let prompt = "x".repeat(4 * 1024 * 1024);
1701 let result = run_codex_with_stdin_prompt(
1702 &codex,
1703 crate::ExecCommand::from_stdin(&prompt).args(),
1704 &prompt,
1705 )
1706 .await;
1707 assert!(
1708 matches!(result, Err(Error::Io { ref message, .. }) if message.contains("stdin")),
1709 "expected a stdin error, got: {result:?}"
1710 );
1711
1712 let (parent, child) = read_pids(&pid_file).await;
1713 assert!(!is_running_for_test(parent), "codex ({parent}) survived");
1714 assert!(
1715 !is_running_for_test(child),
1716 "the subprocess ({child}) survived the stdin failure"
1717 );
1718 }
1719
1720 #[cfg(unix)]
1723 #[tokio::test]
1724 async fn a_run_that_finishes_first_is_not_cancelled() {
1725 let codex = Codex::builder()
1726 .binary("/bin/echo")
1727 .build()
1728 .expect("echo must exist");
1729
1730 let never = std::future::pending::<()>();
1731 let output = run_codex_cancellable(&codex, vec!["exec".into()], never)
1732 .await
1733 .unwrap();
1734 assert!(output.success);
1735 }
1736
1737 #[cfg(unix)]
1738 #[tokio::test]
1739 async fn spawn_observer_reports_each_buffered_child_before_returning() {
1740 use std::sync::{Arc, Mutex};
1741
1742 let seen = Arc::new(Mutex::new(Vec::new()));
1743 let sink = Arc::clone(&seen);
1744 let codex = Codex::builder()
1745 .binary("/bin/echo")
1746 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1747 .build()
1748 .expect("echo must exist");
1749
1750 let output = run_codex(&codex, vec!["probe".into()]).await.unwrap();
1751 let seen = seen.lock().unwrap();
1752 assert_eq!(seen.len(), 1);
1753 assert!(seen[0].pid > 0);
1754 assert_eq!(seen[0].pgid, Some(seen[0].pid));
1755 assert!(output.stdout.contains("probe"));
1756 }
1757
1758 #[cfg(unix)]
1759 #[tokio::test]
1760 async fn spawn_receipt_never_claims_a_shared_group() {
1761 use std::sync::{Arc, Mutex};
1762
1763 let seen = Arc::new(Mutex::new(Vec::new()));
1764 let sink = Arc::clone(&seen);
1765 let codex = Codex::builder()
1766 .binary("/bin/echo")
1767 .process_group(false)
1768 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1769 .build()
1770 .expect("echo must exist");
1771
1772 run_codex(&codex, vec!["probe".into()]).await.unwrap();
1773 assert_eq!(seen.lock().unwrap()[0].pgid, None);
1774 }
1775
1776 #[test]
1777 fn parent_death_support_matches_the_target() {
1778 assert_eq!(die_with_parent_supported(), cfg!(target_os = "linux"));
1779 }
1780
1781 #[cfg(unix)]
1782 #[tokio::test]
1783 async fn parent_death_policy_composes_with_spawn_observation() {
1784 use std::sync::{Arc, Mutex};
1785
1786 let seen = Arc::new(Mutex::new(Vec::new()));
1787 let sink = Arc::clone(&seen);
1788 let codex = Codex::builder()
1789 .binary("/bin/echo")
1790 .die_with_parent(true)
1791 .on_spawn(Arc::new(move |info| sink.lock().unwrap().push(info)))
1792 .build()
1793 .expect("echo must exist");
1794
1795 run_codex(&codex, vec!["probe".into()]).await.unwrap();
1796 assert_eq!(seen.lock().unwrap().len(), 1);
1797 }
1798
1799 const PDEATHSIG_HELPER_ENV: &str = "CODEX_WRAPPER_PDEATHSIG_HELPER";
1800
1801 #[test]
1802 fn pdeathsig_helper_process() {
1803 if std::env::var(PDEATHSIG_HELPER_ENV).is_err() {
1804 return;
1805 }
1806 use std::io::Write;
1807 use std::sync::Arc;
1808
1809 let codex = Codex::builder()
1810 .binary("/bin/sleep")
1811 .die_with_parent(true)
1812 .on_spawn(Arc::new(|info| {
1813 println!("PID {}", info.pid);
1814 let _ = std::io::stdout().flush();
1815 }))
1816 .build()
1817 .unwrap();
1818 let runtime = tokio::runtime::Builder::new_current_thread()
1819 .enable_all()
1820 .build()
1821 .unwrap();
1822 let _ = runtime.block_on(run_codex(&codex, vec!["300".into()]));
1823 }
1824
1825 #[cfg(target_os = "linux")]
1826 #[test]
1827 fn child_dies_when_its_parent_is_sigkilled() {
1828 use std::io::{BufRead, BufReader};
1829 use std::process::{Command, Stdio};
1830
1831 let executable = std::env::current_exe().expect("test binary path");
1832 let mut helper = Command::new(executable)
1833 .args([
1834 "--exact",
1835 "exec::tests::pdeathsig_helper_process",
1836 "--nocapture",
1837 ])
1838 .env(PDEATHSIG_HELPER_ENV, "1")
1839 .stdout(Stdio::piped())
1840 .spawn()
1841 .expect("spawn helper");
1842 let stdout = helper.stdout.take().expect("piped stdout");
1843 let pid = BufReader::new(stdout)
1844 .lines()
1845 .map_while(std::result::Result::ok)
1846 .find_map(|line| line.strip_prefix("PID ").and_then(|pid| pid.parse().ok()))
1847 .expect("helper reported child pid");
1848
1849 unsafe { libc::kill(helper.id() as i32, libc::SIGKILL) };
1851 let _ = helper.wait();
1852
1853 for _ in 0..50 {
1854 if !crate::test_support::is_running_for_test(pid) {
1855 return;
1856 }
1857 std::thread::sleep(Duration::from_millis(100));
1858 }
1859 panic!("child {pid} survived its SIGKILLed parent");
1860 }
1861
1862 #[cfg(unix)]
1867 #[tokio::test]
1868 async fn opting_out_of_process_groups_leaves_the_subprocess() {
1869 use crate::test_support::wait_until_gone;
1870
1871 let pid_file = crate::test_support::PidFile::new("group-optout");
1872 let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1873 .join("tests")
1874 .join("fake-codex-spawns-child.sh");
1875 let codex = Codex::builder()
1876 .binary("/bin/bash")
1877 .arg(script.to_str().unwrap())
1878 .env(
1879 "CODEX_WRAPPER_TEST_PIDFILE",
1880 pid_file.path().to_str().unwrap(),
1881 )
1882 .process_group(false)
1883 .build()
1884 .expect("bash must exist");
1885
1886 let cancelled = tokio::time::timeout(
1887 Duration::from_millis(400),
1888 run_codex(&codex, vec!["exec".into()]),
1889 )
1890 .await;
1891 assert!(cancelled.is_err(), "the run should still have been going");
1892
1893 let (parent, child) = read_pids(&pid_file).await;
1894 assert!(
1895 wait_until_gone(parent).await,
1896 "kill_on_drop still reaps the direct child ({parent})"
1897 );
1898 assert!(
1901 crate::test_support::is_running_for_test(child),
1902 "with groups off, the subprocess ({child}) is expected to survive"
1903 );
1904 signal_group(child, libc::SIGKILL);
1906 unsafe { libc::kill(i32::try_from(child).unwrap_or(0), libc::SIGKILL) };
1907 }
1908}