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