Repository navigation
fix(sandbox): a CLI run that fails while the stream's consumer waits is no unhandled rejection - #296
Conversation
…hunk of the stream The CLI writes its reply and its result line and exits 1 before the bridge reads its stdout; the consumer awaits a macrotask on each chunk. The failed exit must reach the consumer as the classified error, and must not surface in the host as an unhandled rejection while the consumer waits.
Reviewer's GuideThe PR observes the execa subprocess promise as soon as streaming starts, preventing Node from reporting failures as unhandled while a consumer is processing a chunk, while preserving existing failure classification at stream completion and early-close cleanup. Regression tests simulate an exited CLI with buffered output for both providers, and documentation explains the behavior. File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
PR Summary by Qodotest(providers): cover failed CLI exits while stream consumers wait
AI Description
Diagram
High-Level Assessment
Files changed (1)
|
Code Review by Qodo
1.
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 03dccc3baf
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
execa settles the run once the process has exited and its stdout has ended, and Node ends stdout on the tick after the read that empties it. A run that failed (a non-zero exit, the timeout, the caller's abort) could therefore reject while stream() waited at a yield for a consumer busy with an event of the last read, before the final await attached the only handler, and Node raised it as an uncaught exception. stream() now attaches a handler as soon as execa returns the run; the final await still throws the classified failure, and the early-close path keeps its kill().
There was a problem hiding this comment.
Hey - I've found 2 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts" line_range="496" />
<code_context>
+}
+
+describe.each(STREAM_PROVIDERS)('$name: a consumer that waits on each chunk', ({ binary, model, create, fixture }) => {
+ it('ends with the classified failed exit, which is no unhandled rejection while the consumer waits', async () => {
+ // The CLI wrote its reply and its result line and exited 1 before the
+ // bridge read its stdout.
</code_context>
<issue_to_address>
**Failed CLI run crashes host**
When the CLI exits unsuccessfully after writing output while the consumer waits on work for a yielded chunk, `CLISubprocessBridge.stream()` leaves the subprocess rejection unhandled until stdout drains or the consumer closes the generator. Node reports the rejection, potentially crashing the host instead of delivering the provider’s classified error chunk.
Attach a rejection handler to the subprocess run before yielding stdout, then retain the result for classification after stdout is consumed.
Also at `src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts:499`, `src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts:511`, `src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts:517`.
</issue_to_address>
### Comment 2
<location path="src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts" line_range="519-522" />
<code_context>
+ // so this listener is where it shows.
+ expect(unhandled).not.toHaveBeenCalled();
+ const finals = chunks.filter((chunk) => chunk.isFinal);
+ expect(finals).toHaveLength(1);
+ expect(finals[0].choices).toEqual([]);
+ expect(finals[0].error).toMatchObject({ code: 'CRASHED' });
+ } finally {
+ process.off('unhandledRejection', unhandled);
+ }
</code_context>
<issue_to_address>
**Missing reply chunks bypass the wait**
When the bridge stops yielding parsed reply events while the provider still emits the classified terminal failure, the `finals` assertions at lines 518–521 never require a non-final reply chunk. If the bridges stop yielding parsed reply events but still emit the terminal `CRASHED` chunk, the consumer never pauses before the run settles and this test passes without exercising the unhandled-rejection window.
Assert that `chunks` contains a non-final reply chunk before checking the terminal failure.
</issue_to_address>…d on a reply chunk Without a chunk of the reply the consumer never waits before the run settles, and the test would pass without reaching the case it covers.
## [0.13.48](v0.13.47...v0.13.48) (2026-10-11) ### fix * **sandbox:** a CLI run that fails while the stream's consumer waits is no unhandled rejection (#296) ([babc568](babc568))
Summary
Follow-up to #289 (released in 0.13.45). #289 made
CLISubprocessBridge.stream()handle the run's outcome when its consumer stops reading early. The same unhandled rejection is left open while the consumer is still reading but busy with the previous chunk: the run can fail then, and nothing handles it until the stream reaches its finalawait. This change handles the run's outcome from the moment the process starts.The defect
stream()attaches a handler to the run (execa's subprocess, a native Promise: execa 10.0.1lib/methods/promise.jsL1-2) in only two places: theawait subprocessafter stdout has been read to its end, and thefinallyof #289 when the generator is closed early. Between the start and thatawait, nothing handles it.execa settles the run once the process has exited and its stdio streams have finished. On a failed exit,
waitForSuccessfulExitthrows at the exit (lib/resolve/exit-async.jsL41-49), and the error path then waits for the buffered stdio data (lib/resolve/wait-subprocess.jsL115-125,lib/io/contents.jsL105-111), which waits for the stream to end (lib/resolve/stdio.jsL19-46,lib/resolve/wait-stream.jsL6-21). The timeout and the caller's abort take the same path (lib/terminate/timeout.jsL16-21,lib/terminate/cancel.jsL15-20).Node ends a stream whose EOF has already arrived on the tick after the read that empties it, without waiting for another read (Node v22.23.3
lib/internal/streams/readable.jsL769-778,endReadableL1682-1690,endReadableNTL1692-1698). The bridge reads stdout through the stream's async iterator (createAsyncIterator, L1359-1407), which takes the whole buffer in one read. A consumer slower than the CLI therefore gets the CLI's last lines in one chunk, after the CLI has exited: the stream ends on the next tick, and execa rejects the run a few microtasks later, while the generator waits at ayieldfor the consumer to finish with an event of that chunk.When the consumer awaits I/O there (a socket write, a TTS call, anything that crosses a macrotask), the rejection has no handler when Node checks for one. In Node's default mode (
throw, since Node 15: https://nodejs.org/api/cli.html#--unhandled-rejectionsmode) the host process gets an uncaught exception. The failures that reach this path are the ones the providers already turn into error chunks: a non-zero exit after the result line, an error result the CLI exits non-zero after (the Gemini CLI'shandleError,packages/cli/src/utils/errors.tsL66-93 at google-gemini/gemini-cli 9b6e0265; for Claude Code, @anthropic-ai/claude-agent-sdk 0.3.296 replaces the exit's error with an error result's text, "Replacing exit error with result text" inQuery.readMessages,sdk.mjsL136), the bridge's timeout and the caller's abort.The defect predates #277 and #289: from 5dd1e1b (March 2026) the final
await subprocesswas the stream's only handler. #289 closed it for the consumer that stops reading, and this closes it for the one that keeps reading.The fix
stream()attaches a no-op handler to the run as soon as execa returns it:Promise.resolve(subprocess).catch(() => undefined). For execa's run, a native Promise,Promise.resolvereturns the run itself, so the handler is on the run; any other value a test stubs execa with is taken as the finalawaittakes it. The run is still awaited after stdout has been read to its end, so a consumer that reads to the end gets the classified failure as before; the handler only keeps Node from reporting the rejection in between. Thefinallyof #289 keeps itskill()and no longer needs its own handler.Test
"a consumer that waits on each chunk: ends with the classified failed exit, which is no unhandled rejection while the consumer waits", for both providers, in
src/core/llm/providers/__tests__/cli-providers-subprocess.test.ts. Each provider runs on its real bridge with execa stubbed. stdout is aReadablethat already holds the CLI's reply, its result line and its end, as Node's stream holds them once the CLI has exited, and the run rejects with execa 10's error for exit code 1 when that stream emitsend, as execa settles it after the stdio streams finish. The consumer awaitssetImmediateon each chunk. The test first asserts that the consumer got the reply chunk, so the case under test was reached; then anunhandledRejectionlistener must not have fired, and the stream must end with theCRASHEDchunk. As in #289's early-close test, the run is a plain thenable so thatvi.fn()cannot attach handlers of its own.Docs
docs/features/CLI_ERROR_CODES.md(the bridge paragraph) and the JSDoc ofCLISubprocessBridge.stream().Linked issues
Follows #289.
Type of change
How this was verified
CI only; nothing was run on a workstation. The test commit went up first, on master's code, and the fix after it.
Tests 2 failed | 10043 passed | 64 skipped | 5 todo (10114). The two failures are the new test for each provider; in both, theunhandledRejectionlistener was called once with[Error: Command failed with exit code 1, Promise {}], the run's rejection while the consumer waited.Tests 10045 passed | 64 skipped | 5 todo (10114),cli-providers-subprocess.test.ts34 tests; Batch-1 gated tests, the browser tests and the release dry run green. The run on 4c71093 alone (38133630293) was cancelled when e2e10cd superseded it.catch(CLISubprocessBridge.test.ts,ClaudeCodeCLIBridge.test.ts,GeminiCLIBridge.test.ts);Promise.resolve(subprocess)takes those as the finalawaitdoes, and they pass unchanged in the green run.Migration notes
None. No exported type changes, and a consumer that reads the stream to its end sees the same events and errors.
Checklist
!before the colon for a change that breaks users (feat!:orfeat(api)!:).