Skip to main content

codex_wrapper/
streaming.rs

1//! Streaming execution for `codex exec` commands.
2//!
3//! Instead of buffering all JSONL output and returning it at once,
4//! the streaming API pipes stdout from the child process and delivers
5//! each [`JsonLineEvent`] to a caller-supplied callback as soon as it
6//! arrives.
7//!
8//! # Example
9//!
10//! ```no_run
11//! use codex_wrapper::{Codex, ExecCommand, JsonLineEvent};
12//!
13//! # async fn example() -> codex_wrapper::Result<()> {
14//! let codex = Codex::builder().build()?;
15//! let cmd = ExecCommand::new("what is 2+2?").ephemeral();
16//!
17//! cmd.stream(&codex, |event: JsonLineEvent| {
18//!     println!("{}: {:?}", event.event_type, event.extra);
19//! })
20//! .await?;
21//! # Ok(())
22//! # }
23//! ```
24
25use tokio::io::{AsyncBufReadExt, BufReader};
26use tokio::process::Command;
27use tracing::{Instrument, debug};
28
29use crate::Codex;
30use crate::command::CodexCommand;
31use crate::error::{Error, Result};
32use crate::types::JsonLineEvent;
33
34/// Stream JSONL events from `codex exec <prompt>`, invoking `handler` for each
35/// parsed [`JsonLineEvent`].
36///
37/// The child's stderr is drained concurrently and returned in the error if the
38/// process exits with a non-zero status.
39pub async fn stream_exec<F>(
40    codex: &Codex,
41    cmd: &crate::command::exec::ExecCommand,
42    handler: F,
43) -> Result<()>
44where
45    F: FnMut(JsonLineEvent),
46{
47    let args = cmd.clone().json().args();
48    run_streaming(
49        codex,
50        args,
51        cmd.stdin_prompt(),
52        handler,
53        std::future::pending(),
54    )
55    .await
56}
57
58/// Stream JSONL events until the command completes or `cancel` resolves.
59///
60/// Cancellation terminates the owned process group, waits through the
61/// client's configured grace period, and reaps the direct child before
62/// returning [`Error::Cancelled`], or [`Error::CleanupFailed`] wrapping it if
63/// stopping or reaping the child failed. Shutdown output is drained and discarded;
64/// handlers stop receiving events after cancellation. Detached tools require
65/// the CLI's cooperation; see [`crate::CodexBuilder::termination_signal`].
66pub async fn stream_exec_cancellable<C, F>(
67    codex: &Codex,
68    cmd: &crate::command::exec::ExecCommand,
69    cancel: C,
70    handler: F,
71) -> Result<()>
72where
73    C: std::future::Future<Output = ()> + Send,
74    F: FnMut(JsonLineEvent),
75{
76    let args = cmd.clone().json().args();
77    run_streaming(codex, args, cmd.stdin_prompt(), handler, cancel).await
78}
79
80/// Stream JSONL events from `codex exec resume`, invoking `handler` for each
81/// parsed [`JsonLineEvent`].
82pub async fn stream_exec_resume<F>(
83    codex: &Codex,
84    cmd: &crate::command::exec::ExecResumeCommand,
85    handler: F,
86) -> Result<()>
87where
88    F: FnMut(JsonLineEvent),
89{
90    let args = cmd.clone().json().args();
91    run_streaming(
92        codex,
93        args,
94        cmd.stdin_prompt(),
95        handler,
96        std::future::pending(),
97    )
98    .await
99}
100
101/// Stream resumed-turn JSONL events until completion or cancellation.
102///
103/// This has the same settled process-cleanup contract as
104/// [`stream_exec_cancellable`].
105pub async fn stream_exec_resume_cancellable<C, F>(
106    codex: &Codex,
107    cmd: &crate::command::exec::ExecResumeCommand,
108    cancel: C,
109    handler: F,
110) -> Result<()>
111where
112    C: std::future::Future<Output = ()> + Send,
113    F: FnMut(JsonLineEvent),
114{
115    let args = cmd.clone().json().args();
116    run_streaming(codex, args, cmd.stdin_prompt(), handler, cancel).await
117}
118
119/// Core streaming implementation shared by both exec variants.
120///
121/// `stdin_prompt` carries the prompt for a `codex exec -` run, where it is
122/// delivered on stdin rather than in argv.
123async fn run_streaming<C, F>(
124    codex: &Codex,
125    args: Vec<String>,
126    stdin_prompt: Option<&str>,
127    mut handler: F,
128    cancel: C,
129) -> Result<()>
130where
131    C: std::future::Future<Output = ()> + Send,
132    F: FnMut(JsonLineEvent),
133{
134    let span = crate::exec::command_span("codex.stream", codex, &args);
135    let command_args = crate::exec::assemble_args(codex, args);
136    let _span_guard = span.clone().entered();
137
138    debug!(arg_count = command_args.len(), "streaming codex command");
139
140    // Settles on every exit below, and on drop for the one that has no exit:
141    // a cancelled stream, which is the outcome most easily missed.
142    let mut outcome = crate::exec::SpanOutcome::start(span.clone());
143
144    let mut child_cmd = Command::new(&codex.binary);
145    child_cmd.args(&command_args);
146    if stdin_prompt.is_some() {
147        child_cmd.stdin(std::process::Stdio::piped());
148    } else {
149        child_cmd.stdin(std::process::Stdio::null());
150    }
151    child_cmd.stdout(std::process::Stdio::piped());
152    child_cmd.stderr(std::process::Stdio::piped());
153
154    // Kill the child if this future is dropped: on timeout, on caller
155    // cancellation, or on task abort. Without this, tokio detaches the child
156    // and codex keeps running with no handle left to stop it.
157    child_cmd.kill_on_drop(true);
158    crate::exec::own_process_group(&mut child_cmd, codex.process_group);
159    crate::exec::apply_die_with_parent(&mut child_cmd, codex.die_with_parent);
160
161    if let Some(dir) = &codex.working_dir {
162        child_cmd.current_dir(dir);
163    }
164    crate::exec::apply_child_environment(&mut child_cmd, codex.clear_env, &codex.env);
165
166    let mut child = child_cmd.spawn().map_err(|e| Error::Io {
167        message: format!("failed to spawn codex: {e}"),
168        source: e,
169        working_dir: codex.working_dir.clone(),
170    })?;
171
172    // Armed for the whole stream. Dropping this future signals the group,
173    // which reaches descendants still in that group; kill_on_drop alone only
174    // stops the direct child. Detached tools require cooperative cleanup.
175    let mut group = crate::exec::arm_and_notify(
176        codex.process_group,
177        codex.termination_signal,
178        child.id(),
179        codex.on_spawn.as_ref(),
180    );
181
182    let mut stdout = BufReader::new(child.stdout.take().expect("stdout was configured as piped"));
183    let mut stderr = BufReader::new(child.stderr.take().expect("stderr was configured as piped"));
184    // Taken up front so the write does not borrow `child`, which the wait
185    // below needs.
186    let child_stdin = child.stdin.take();
187
188    // Write the prompt and close the handle, so the CLI stops waiting for
189    // more. This runs as part of the streamed future rather than before it,
190    // so a prompt larger than the pipe buffer cannot block the readers.
191    let stdin_task = async {
192        let (Some(prompt), Some(mut stdin)) = (stdin_prompt, child_stdin) else {
193            return Ok(());
194        };
195        use tokio::io::AsyncWriteExt;
196        stdin
197            .write_all(prompt.as_bytes())
198            .await
199            .map_err(|e| Error::Io {
200                message: format!("failed to write the prompt to codex stdin: {e}"),
201                source: e,
202                working_dir: codex.working_dir.clone(),
203            })?;
204        stdin.shutdown().await.map_err(|e| Error::Io {
205            message: format!("failed to close codex stdin: {e}"),
206            source: e,
207            working_dir: codex.working_dir.clone(),
208        })
209    };
210
211    let stdout_task = async {
212        let mut captured_bytes = 0usize;
213        while let Some(line) = read_bounded_line(
214            &mut stdout,
215            &mut captured_bytes,
216            codex.output_limit,
217            crate::OutputStream::Stdout,
218            &codex.working_dir,
219        )
220        .await?
221        {
222            if line.trim_start().starts_with('{') {
223                match serde_json::from_str::<JsonLineEvent>(&line) {
224                    Ok(event) => handler(event),
225                    Err(source) => {
226                        return Err(Error::Json {
227                            message: format!("failed to parse JSONL event: {line}"),
228                            source,
229                        });
230                    }
231                }
232            }
233        }
234        Ok::<(), Error>(())
235    };
236
237    let stderr_task = async {
238        let mut collected = String::new();
239        let mut captured_bytes = 0usize;
240        while let Some(line) = read_bounded_line(
241            &mut stderr,
242            &mut captured_bytes,
243            codex.output_limit,
244            crate::OutputStream::Stderr,
245            &codex.working_dir,
246        )
247        .await?
248        {
249            if !collected.is_empty() {
250                collected.push('\n');
251            }
252            collected.push_str(&line);
253        }
254        Ok::<String, Error>(collected)
255    };
256
257    let stream_future = async {
258        let ((), (), stderr_output) = tokio::try_join!(stdin_task, stdout_task, stderr_task)?;
259        // Keep the leader unreaped until all readers finish so a cancellation
260        // never signals a group whose leader PID could already be reused.
261        let status = child.wait().await.map_err(|e| Error::Io {
262            message: format!("failed to wait on codex process: {e}"),
263            source: e,
264            working_dir: codex.working_dir.clone(),
265        })?;
266        Ok::<_, Error>((stderr_output, status))
267    };
268
269    // Dropped explicitly before awaiting: the guard exists so the span is the
270    // parent of everything above, while the await below must not hold it
271    // across a yield point.
272    drop(_span_guard);
273
274    let stop = async {
275        match codex.timeout {
276            Some(timeout) => tokio::select! {
277                () = cancel => StreamStop::Cancelled,
278                () = tokio::time::sleep(timeout) => StreamStop::Timeout(timeout),
279            },
280            None => {
281                cancel.await;
282                StreamStop::Cancelled
283            }
284        }
285    };
286    let finished = tokio::select! {
287        result = stream_future.instrument(span) => Ok(result),
288        reason = stop => Err(reason),
289    };
290
291    let (stderr_output, status) = match finished {
292        Ok(Ok(finished)) => finished,
293        Ok(Err(error)) => {
294            let cleanup = crate::exec::terminate_and_reap_draining(
295                &mut child,
296                &mut group,
297                codex.termination_grace,
298                codex.working_dir.as_deref(),
299                &mut stdout,
300                &mut stderr,
301            )
302            .await;
303            let label = if cleanup.is_ok() {
304                "failed"
305            } else {
306                "cleanup_failed"
307            };
308            outcome.settle(label, None);
309            return Err(Error::after_cleanup(error, cleanup));
310        }
311        Err(reason) => {
312            let cleanup = crate::exec::terminate_and_reap_draining(
313                &mut child,
314                &mut group,
315                codex.termination_grace,
316                codex.working_dir.as_deref(),
317                &mut stdout,
318                &mut stderr,
319            )
320            .await;
321            let (label, error) = match reason {
322                StreamStop::Cancelled => (
323                    "cancelled",
324                    Error::Cancelled {
325                        grace_seconds: codex.termination_grace.as_secs(),
326                    },
327                ),
328                StreamStop::Timeout(timeout) => (
329                    "timeout",
330                    Error::Timeout {
331                        timeout_seconds: timeout.as_secs(),
332                    },
333                ),
334            };
335            // Matches the buffered path, so a span never reads as a settled
336            // stop when the child may not have been reaped.
337            let label = if cleanup.is_ok() {
338                label
339            } else {
340                "cleanup_failed"
341            };
342            outcome.settle(label, None);
343            return Err(Error::after_cleanup(error, cleanup));
344        }
345    };
346
347    // A nonzero exit is also a completed, reaped run, not a drop cleanup.
348    group.disarm();
349    let exit_code = status.code().unwrap_or(-1);
350    if !status.success() {
351        outcome.settle("failed", Some(exit_code));
352        return Err(Error::from_command_failure(
353            format!("{} {}", codex.binary.display(), command_args.join(" ")),
354            exit_code,
355            String::new(),
356            stderr_output,
357            codex.working_dir.clone(),
358        ));
359    }
360
361    outcome.settle("ok", Some(exit_code));
362    Ok(())
363}
364
365enum StreamStop {
366    Cancelled,
367    Timeout(std::time::Duration),
368}
369
370pub(crate) async fn read_bounded_line<R: tokio::io::AsyncBufRead + Unpin>(
371    reader: &mut R,
372    captured_bytes: &mut usize,
373    output_limit: Option<usize>,
374    stream: crate::OutputStream,
375    working_dir: &Option<std::path::PathBuf>,
376) -> Result<Option<String>> {
377    let mut line = Vec::new();
378    loop {
379        let available = reader.fill_buf().await.map_err(|source| Error::Io {
380            message: format!("failed to read {stream} line: {source}"),
381            source,
382            working_dir: working_dir.clone(),
383        })?;
384        if available.is_empty() {
385            if line.is_empty() {
386                return Ok(None);
387            }
388            break;
389        }
390        let take = available
391            .iter()
392            .position(|byte| *byte == b'\n')
393            .map_or(available.len(), |index| index + 1);
394        if output_limit.is_some_and(|limit| captured_bytes.saturating_add(take) > limit) {
395            return Err(Error::OutputLimitExceeded {
396                stream,
397                limit_bytes: output_limit.unwrap_or_default(),
398            });
399        }
400        line.extend_from_slice(&available[..take]);
401        *captured_bytes = captured_bytes.saturating_add(take);
402        let complete = line.last() == Some(&b'\n');
403        reader.consume(take);
404        if complete {
405            line.pop();
406            break;
407        }
408    }
409    if line.last() == Some(&b'\r') {
410        line.pop();
411    }
412    String::from_utf8(line)
413        .map(Some)
414        .map_err(|source| Error::Io {
415            message: format!("failed to decode {stream} line"),
416            source: std::io::Error::new(std::io::ErrorKind::InvalidData, source),
417            working_dir: working_dir.clone(),
418        })
419}
420
421#[cfg(all(test, unix))]
422mod tests {
423    use super::*;
424    use std::sync::{Arc, Mutex};
425
426    /// Build a [`Codex`] client that uses `bash` to run the fake-codex script.
427    fn fake_codex(script_name: &str) -> Codex {
428        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
429            .join("tests")
430            .join(script_name);
431        Codex::builder()
432            .binary("/bin/bash")
433            .arg(script.to_str().unwrap())
434            .build()
435            .expect("bash must exist")
436    }
437
438    #[tokio::test]
439    async fn stream_exec_delivers_events() {
440        let codex = fake_codex("fake-codex.sh");
441        let cmd = crate::command::exec::ExecCommand::new("test prompt").json();
442        let events = Arc::new(Mutex::new(Vec::new()));
443        let events_clone = Arc::clone(&events);
444
445        stream_exec(&codex, &cmd, move |event| {
446            events_clone.lock().unwrap().push(event);
447        })
448        .await
449        .unwrap();
450
451        let events = events.lock().unwrap();
452        assert!(!events.is_empty(), "expected at least one event");
453
454        let types: Vec<&str> = events.iter().map(|e| e.event_type.as_str()).collect();
455        assert!(
456            types.contains(&"thread.started"),
457            "expected thread.started, got: {types:?}"
458        );
459        assert!(
460            types.contains(&"turn.completed"),
461            "expected turn.completed, got: {types:?}"
462        );
463    }
464
465    /// The API promises delivery as events arrive. Buffering until stdout
466    /// closes loses a thread id when a long-running process or its host dies
467    /// after `thread.started`, which is the durability use case for streaming.
468    #[tokio::test]
469    async fn stream_exec_delivers_an_event_while_the_child_is_still_running() {
470        let codex = Codex::builder()
471            .binary("/bin/bash")
472            .arg("-c")
473            .arg(
474                "printf '%s\\n' '{\"type\":\"thread.started\",\"thread_id\":\"thread-early\"}'; sleep 10",
475            )
476            .build()
477            .expect("bash must exist");
478        let cmd = crate::command::exec::ExecCommand::new("probe").json();
479        let (sent, delivered) = tokio::sync::oneshot::channel();
480        let mut sent = Some(sent);
481
482        let task = tokio::spawn(async move {
483            stream_exec(&codex, &cmd, move |event| {
484                if event.thread_id() == Some("thread-early")
485                    && let Some(sent) = sent.take()
486                {
487                    let _ = sent.send(());
488                }
489            })
490            .await
491        });
492
493        let delivered = tokio::time::timeout(std::time::Duration::from_secs(1), delivered).await;
494        let still_running = !task.is_finished();
495        task.abort();
496        let _ = task.await;
497
498        assert!(delivered.is_ok(), "callback waited for the child to exit");
499        assert!(
500            still_running,
501            "the fixture must still be running when the callback fires"
502        );
503    }
504
505    #[cfg(unix)]
506    #[tokio::test]
507    async fn streaming_interrupt_drains_without_parsing_or_delivering_shutdown_bytes() {
508        let fixture = crate::test_support::InterruptFixture::new("stream-interrupt-drain");
509        let codex = fixture
510            .builder()
511            .termination_signal(crate::TerminationSignal::Interrupt)
512            .output_limit(64)
513            .build()
514            .unwrap();
515        let command = crate::ExecCommand::from_stdin("prompt");
516        let mut calls = 0;
517        let result =
518            stream_exec_cancellable(&codex, &command, fixture.detached_ready(), |_| calls += 1)
519                .await;
520        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
521        assert_eq!(calls, 0, "shutdown bytes must not reach the event handler");
522        assert!(fixture.marker(".int").exists());
523        assert!(
524            fixture.marker(".cleaned").exists(),
525            "shutdown output blocked cleanup"
526        );
527        fixture.assert_stopped().await;
528    }
529
530    #[cfg(unix)]
531    #[tokio::test]
532    async fn streaming_resume_interrupt_ignored_uses_hard_fallback() {
533        let fixture = crate::test_support::InterruptFixture::new("stream-resume-interrupt-ignored");
534        let codex = fixture
535            .builder()
536            .env("CODEX_WRAPPER_TEST_SHUTDOWN_MODE", "ignore")
537            .termination_signal(crate::TerminationSignal::Interrupt)
538            .termination_grace(std::time::Duration::from_millis(100))
539            .build()
540            .unwrap();
541        let command = crate::ExecResumeCommand::new().last();
542        let result = tokio::time::timeout(
543            std::time::Duration::from_secs(3),
544            stream_exec_resume_cancellable(&codex, &command, fixture.ready(), |_| {}),
545        )
546        .await
547        .expect("hard fallback exceeded the grace budget");
548        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
549        assert!(fixture.marker(".int").exists());
550        fixture.assert_stopped().await;
551    }
552
553    #[tokio::test]
554    async fn stream_exec_resume_delivers_events() {
555        let codex = fake_codex("fake-codex.sh");
556        let cmd = crate::command::exec::ExecResumeCommand::new().last().json();
557        let events = Arc::new(Mutex::new(Vec::new()));
558        let events_clone = Arc::clone(&events);
559
560        stream_exec_resume(&codex, &cmd, move |event| {
561            events_clone.lock().unwrap().push(event);
562        })
563        .await
564        .unwrap();
565
566        let events = events.lock().unwrap();
567        assert!(!events.is_empty(), "expected at least one event");
568    }
569
570    #[tokio::test]
571    async fn streaming_reports_the_child_before_events_are_delivered() {
572        let order = Arc::new(Mutex::new(Vec::new()));
573        let spawn_order = Arc::clone(&order);
574        let event_order = Arc::clone(&order);
575        let script = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
576            .join("tests")
577            .join("fake-codex.sh");
578        let codex = Codex::builder()
579            .binary("/bin/bash")
580            .arg(script.to_str().unwrap())
581            .on_spawn(Arc::new(move |_| spawn_order.lock().unwrap().push("spawn")))
582            .build()
583            .expect("bash must exist");
584
585        crate::ExecCommand::new("probe")
586            .json()
587            .stream(&codex, move |_| {
588                let mut order = event_order.lock().unwrap();
589                if !order.contains(&"event") {
590                    order.push("event");
591                }
592            })
593            .await
594            .unwrap();
595
596        assert_eq!(&order.lock().unwrap()[..2], ["spawn", "event"]);
597    }
598
599    /// Streaming owns a separate process builder from buffered execution.
600    /// Cover opening, stdin opening, and resume so none can regress to ambient
601    /// inheritance while the others stay isolated.
602    #[tokio::test]
603    async fn cleared_environment_reaches_every_streaming_variant() {
604        let capture = crate::test_support::EnvCapture::new("env-streaming");
605        let codex = crate::test_support::env_capturing_codex(&capture)
606            .clear_env()
607            .env("CODEX_WRAPPER_EXPLICIT", "streaming")
608            .build()
609            .expect("bash must exist");
610
611        crate::ExecCommand::new("opening")
612            .stream(&codex, |_| {})
613            .await
614            .unwrap();
615        let opening_environment = capture.read();
616        assert!(!opening_environment.contains_key("PATH"));
617        assert_eq!(
618            opening_environment
619                .get("CODEX_WRAPPER_EXPLICIT")
620                .map(String::as_str),
621            Some("streaming")
622        );
623
624        crate::ExecCommand::new("stdin")
625            .prompt_via_stdin()
626            .stream(&codex, |_| {})
627            .await
628            .unwrap();
629        let stdin_environment = capture.read();
630        assert!(!stdin_environment.contains_key("PATH"));
631        assert_eq!(
632            stdin_environment
633                .get("CODEX_WRAPPER_EXPLICIT")
634                .map(String::as_str),
635            Some("streaming")
636        );
637
638        crate::ExecResumeCommand::new()
639            .last()
640            .stream(&codex, |_| {})
641            .await
642            .unwrap();
643        let resume_environment = capture.read();
644        assert!(!resume_environment.contains_key("PATH"));
645        assert_eq!(
646            resume_environment
647                .get("CODEX_WRAPPER_EXPLICIT")
648                .map(String::as_str),
649            Some("streaming")
650        );
651    }
652
653    /// Contract captured from a paid 0.145.0 run: the callback receives the
654    /// typed terminal before the process reports its non-zero exit, including
655    /// an assistant message but no fabricated token counts.
656    #[tokio::test]
657    async fn stream_exec_classifies_native_rollout_budget_exhaustion() {
658        let codex = fake_codex("fake-codex-rollout-budget.sh");
659        let cmd = crate::command::exec::ExecCommand::new("probe").json();
660        let events = Arc::new(Mutex::new(Vec::new()));
661        let collected = Arc::clone(&events);
662
663        let error = stream_exec(&codex, &cmd, move |event| {
664            collected.lock().unwrap().push(event);
665        })
666        .await
667        .expect_err("captured rollout exhaustion exits non-zero");
668
669        assert_eq!(error.exit_code(), Some(1));
670        let events = events.lock().unwrap();
671        let terminal = events
672            .iter()
673            .find(|event| event.is_turn_failed())
674            .expect("turn.failed must be delivered");
675        assert_eq!(
676            terminal.turn_failure_kind(),
677            Some(crate::TurnFailureKind::RolloutBudgetExhausted)
678        );
679        assert_eq!(terminal.usage(), None);
680        assert_eq!(crate::QueryResult::from_events(events.clone()).result, "ok");
681    }
682
683    #[tokio::test]
684    async fn stream_exec_timeout() {
685        let codex = Codex::builder()
686            .binary("/bin/bash")
687            .arg("-c")
688            .arg("sleep 10")
689            .timeout(std::time::Duration::from_millis(50))
690            .build()
691            .unwrap();
692
693        let cmd = crate::command::exec::ExecCommand::new("test").json();
694        let result = stream_exec(&codex, &cmd, |_| {}).await;
695
696        assert!(
697            matches!(result, Err(Error::Timeout { .. })),
698            "expected timeout error, got: {result:?}"
699        );
700    }
701
702    /// The streaming path drops both `stream_future` and the child it borrows.
703    /// Without `kill_on_drop`, the timeout above would leave codex running.
704    #[tokio::test]
705    async fn stream_exec_timeout_kills_the_spawned_process() {
706        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
707
708        let pid_file = PidFile::new("stream-timeout");
709        let codex = blocking_codex(&pid_file)
710            .timeout(std::time::Duration::from_millis(500))
711            .build()
712            .expect("bash must exist");
713
714        let cmd = crate::command::exec::ExecCommand::new("probe").json();
715        let result = stream_exec(&codex, &cmd, |_| {}).await;
716        assert!(
717            matches!(result, Err(Error::Timeout { .. })),
718            "expected timeout error, got: {result:?}"
719        );
720
721        let pid = pid_file.read_pid().await;
722        assert!(
723            wait_until_gone(pid).await,
724            "codex ({pid}) survived the timeout"
725        );
726    }
727
728    /// The caller dropping the stream future, with no wrapper timeout.
729    #[tokio::test]
730    async fn stream_exec_cancellation_kills_the_spawned_process() {
731        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
732
733        let pid_file = PidFile::new("stream-cancel");
734        let codex = blocking_codex(&pid_file).build().expect("bash must exist");
735
736        let cmd = crate::command::exec::ExecCommand::new("probe").json();
737        let cancelled = tokio::time::timeout(
738            std::time::Duration::from_millis(500),
739            stream_exec(&codex, &cmd, |_| {}),
740        )
741        .await;
742        assert!(
743            cancelled.is_err(),
744            "fake codex should still have been running, got: {cancelled:?}"
745        );
746
747        let pid = pid_file.read_pid().await;
748        assert!(
749            wait_until_gone(pid).await,
750            "codex ({pid}) survived the dropped future"
751        );
752    }
753
754    #[tokio::test]
755    async fn explicit_stream_cancellation_reaps_before_returning() {
756        use crate::test_support::{PidFile, blocking_codex, wait_until_gone};
757
758        let pid_file = PidFile::new("stream-explicit-cancel");
759        let codex = blocking_codex(&pid_file).build().expect("bash must exist");
760        let cmd = crate::command::exec::ExecCommand::new("probe").json();
761        let cancel = async {
762            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
763        };
764
765        let result = stream_exec_cancellable(&codex, &cmd, cancel, |_| {}).await;
766        assert!(matches!(result, Err(Error::Cancelled { .. })));
767
768        let pid = pid_file.read_pid().await;
769        assert!(
770            wait_until_gone(pid).await,
771            "codex ({pid}) survived explicit stream cancellation"
772        );
773    }
774
775    #[tokio::test]
776    async fn dropping_during_stream_cancellation_grace_kills_the_group() {
777        let fixture = crate::test_support::GracePeriodFixture::new("stream-cancel-grace-drop");
778        let codex = fixture.builder().build().unwrap();
779        let cmd = crate::ExecCommand::new("probe").json();
780        fixture
781            .assert_drop_during_grace(stream_exec_cancellable(
782                &codex,
783                &cmd,
784                fixture.ready(),
785                |_| {},
786            ))
787            .await;
788    }
789
790    #[tokio::test]
791    async fn stream_exec_parse_error() {
792        let codex = fake_codex("fake-codex-bad-json.sh");
793        let cmd = crate::command::exec::ExecCommand::new("test").json();
794        let result = stream_exec(&codex, &cmd, |_| {}).await;
795
796        assert!(
797            matches!(result, Err(Error::Json { .. })),
798            "expected json parse error, got: {result:?}"
799        );
800    }
801
802    #[tokio::test]
803    async fn streaming_enforces_the_raw_output_ceiling() {
804        let codex = Codex::builder()
805            .binary("/bin/bash")
806            .arg("-c")
807            .arg("for ((i=0; i<4096; i++)); do printf x; done; sleep 3")
808            .output_limit(128)
809            .timeout(std::time::Duration::from_secs(1))
810            .build()
811            .expect("bash must exist");
812        let cmd = crate::command::exec::ExecCommand::new("probe").json();
813
814        let result = stream_exec(&codex, &cmd, |_| {}).await;
815
816        assert!(matches!(
817            result,
818            Err(Error::OutputLimitExceeded {
819                stream: crate::OutputStream::Stdout,
820                limit_bytes: 128,
821            })
822        ));
823    }
824
825    // -----------------------------------------------------------------
826    // Failed cleanup is not reported as a settled stop
827    //
828    // The injection replaces the cleanup result after the real termination
829    // and wait have run, so these cover reporting, not that a syscall fails.
830    // -----------------------------------------------------------------
831
832    /// The stop reason inside a [`Error::CleanupFailed`] whose cleanup half
833    /// is the injected failure, not some other error.
834    fn injected_cleanup_reason(result: Result<()>) -> Error {
835        match result {
836            Err(Error::CleanupFailed { reason, cleanup }) => {
837                assert!(
838                    cleanup.to_string().contains("injected cleanup failure"),
839                    "{cleanup:?}"
840                );
841                *reason
842            }
843            other => panic!("expected CleanupFailed, got {other:?}"),
844        }
845    }
846
847    #[tokio::test]
848    async fn failed_stream_cleanup_after_cancellation_is_not_a_bare_cancel() {
849        let pid_file = crate::test_support::PidFile::new("stream-cleanup-failed-cancel");
850        let codex = crate::test_support::blocking_codex(&pid_file)
851            .termination_grace(std::time::Duration::from_millis(10))
852            .build()
853            .unwrap();
854        let cmd = crate::command::exec::ExecCommand::new("probe").json();
855        let cancel_soon = || tokio::time::sleep(std::time::Duration::from_millis(100));
856
857        let injection = crate::exec::CleanupFailureInjection::arm();
858        let result = stream_exec_cancellable(&codex, &cmd, cancel_soon(), |_| {}).await;
859        let reason = injected_cleanup_reason(result);
860        assert!(matches!(reason, Error::Cancelled { .. }), "{reason:?}");
861
862        drop(injection);
863        let result = stream_exec_cancellable(&codex, &cmd, cancel_soon(), |_| {}).await;
864        assert!(matches!(result, Err(Error::Cancelled { .. })), "{result:?}");
865    }
866
867    #[tokio::test]
868    async fn failed_stream_cleanup_after_timeout_keeps_the_timeout_as_reason() {
869        let pid_file = crate::test_support::PidFile::new("stream-cleanup-failed-timeout");
870        let codex = crate::test_support::blocking_codex(&pid_file)
871            .timeout(std::time::Duration::from_millis(100))
872            .termination_grace(std::time::Duration::from_millis(10))
873            .build()
874            .unwrap();
875        let cmd = crate::command::exec::ExecCommand::new("probe").json();
876
877        let _injection = crate::exec::CleanupFailureInjection::arm();
878        let result = stream_exec(&codex, &cmd, |_| {}).await;
879        let reason = injected_cleanup_reason(result);
880        assert!(matches!(reason, Error::Timeout { .. }), "{reason:?}");
881    }
882
883    /// A parse failure ends the stream through the error branch rather than a
884    /// stop signal, and must report a failed cleanup the same way.
885    #[tokio::test]
886    async fn failed_stream_cleanup_after_a_parse_error_keeps_the_json_error() {
887        let codex = fake_codex("fake-codex-bad-json.sh");
888        let cmd = crate::command::exec::ExecCommand::new("test").json();
889
890        let injection = crate::exec::CleanupFailureInjection::arm();
891        let result = stream_exec(&codex, &cmd, |_| {}).await;
892        let reason = injected_cleanup_reason(result);
893        assert!(matches!(reason, Error::Json { .. }), "{reason:?}");
894
895        drop(injection);
896        let result = stream_exec(&codex, &cmd, |_| {}).await;
897        assert!(matches!(result, Err(Error::Json { .. })), "{result:?}");
898    }
899
900    #[tokio::test]
901    async fn failed_stream_cleanup_after_an_output_limit_keeps_the_limit() {
902        let codex = Codex::builder()
903            .binary("/bin/bash")
904            .arg("-c")
905            .arg("for ((i=0; i<4096; i++)); do printf x; done; sleep 3")
906            .output_limit(128)
907            .timeout(std::time::Duration::from_secs(1))
908            .build()
909            .expect("bash must exist");
910        let cmd = crate::command::exec::ExecCommand::new("probe").json();
911
912        let _injection = crate::exec::CleanupFailureInjection::arm();
913        let result = stream_exec(&codex, &cmd, |_| {}).await;
914        let reason = injected_cleanup_reason(result);
915        assert!(
916            matches!(
917                reason,
918                Error::OutputLimitExceeded {
919                    stream: crate::OutputStream::Stdout,
920                    limit_bytes: 128,
921                }
922            ),
923            "{reason:?}"
924        );
925    }
926}