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