Skip to content

fix(streaming): surface mid-stream errors when iterating buffered streams - #2047

Merged
HAYDEN-OAI merged 3 commits into
openai:mainfrom
pouyashahrdami:fix/stream-iterator-swallows-errors
Aug 12, 2026
Merged

HAYDEN-OAI merged 3 commits into
openai:mainfrom
pouyashahrdami:fix/stream-iterator-swallows-errors

Conversation

@pouyashahrdami

@pouyashahrdami pouyashahrdami commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor
  • I understand that this repository is auto-generated and my pull request may not be merged

Summary

Fixes #2046.

Streaming consumers could silently treat a failed request as successful when chunks or events were already buffered before a terminal error arrived. Chat Completions, Assistants, and streaming tool-runner readable-stream bridges each retained their own lossy iterator implementation; Responses streaming now also uses the same shared implementation consistently.

Extract the existing retained-failure behavior into a shared, documented EventStream iterator. Every handwritten streaming adapter now drains queued values, rejects exactly once with the original terminal error or abort, removes producer and lifecycle listeners, and cancels its underlying request when iteration stops early. Assistant events remain cloned when queued, and tool-runner chunk/tool-message listeners remain eager and ordered.

The implementation preserves current Responses API nested/flat SSE error normalization, provider error metadata, structured-output parsing, and GPT-5 custom-tool support. All modified SDK source lives under the handwritten src/lib/ tree.

Regression coverage

  • Buffered and pending failures across Chat Completion, Assistant, and Responses iterators.
  • Buffered failures crossing ChatCompletionStreamingRunner.toReadableStream().
  • Exact-once terminal failure delivery, cancellation, completed-stream iteration, listener cleanup, and cloned Assistant snapshots.
  • Explicit iteration over error and abort events without changing their existing semantics.

Verification

  • Full handwritten Vitest suite: 66 files, 1,727 tests passed.
  • Repository lint and formatting checks passed.
  • Exact repository breaking-change workflow passed against current main.
  • Package build and CommonJS/ESM smoke checks passed.
  • Current TypeScript and TypeScript 4.9 both successfully type-check the published package.
  • Generated-file lint and Node version policy checks passed.

…eams

The `[Symbol.asyncIterator]()` implementations in ChatCompletionStream and
ResponseStream buffer events in `pushQueue` when the producer is ahead of the
consumer. The error/abort handlers only rejected readers waiting at that moment
and never stored the error, so an error that fired while events were buffered
(no reader waiting) was lost: the consumer drained the buffer and `next()`
returned done without throwing.

Capture the terminal error and re-throw it once the buffer drains, mirroring the
existing EventStream.events() pattern. Behavior when a reader is already waiting
is unchanged. Adds a regression test to each stream.

Closes openai#2046

@jbeckwith-oai jbeckwith-oai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Blocking: the same buffered-terminal-error loss remains in two public handwritten streaming paths. ChatCompletionStreamingRunner.toReadableStream() overrides the fixed base conversion with its own pushQueue/readQueue/error handlers, and AssistantStreamSymbol.asyncIterator has the same old pattern. I reproduced both on this exact head: enqueue two items with no reader waiting, emit OpenAIError('boom'), then consume; each returned both items and ended normally with thrown=null. This means tool-runner readable-stream bridges and Assistants iteration can still report a failed response as successful. Please apply the retained-failure semantics (preferably via a shared/EventStream.events-based adapter so these copies cannot drift), including listener/queue cleanup on return/end, to every buffered adapter, and add regressions for these two paths. The two paths changed here otherwise behave correctly: their 17 targeted tests, TypeScript, ESLint, Prettier, build, and diff checks pass. Please also make the new tests deterministic by waiting for the stream's terminal error/done signal instead of a fixed 10 ms sleep, and assert the exact error/message rather than any Error.

…s survive in every stream bridge

Address review: the retained-failure fix previously covered only
ChatCompletionStream and ResponseStream, while
ChatCompletionStreamingRunner.toReadableStream() and
AssistantStream[Symbol.asyncIterator]() kept their own copies of the
buffering logic and still dropped terminal errors once events were
buffered with no reader waiting.

- extract EventStream#_createIterator, a shared buffered async-iterator
  adapter (the events() logic, generalized); events() now delegates to it
- rebuild all four duplicated adapters on the shared helper: chunk/event
  iterators keep their break-aborts semantics via onReturn, the runner
  bridge keeps eager listener registration, AssistantStream keeps
  structuredClone-at-push
- remove listeners and drain queues on end/return (previously leaked);
  mark the terminal promise handled when the consumer explicitly ends
  iteration so the self-inflicted abort no longer surfaces as an
  unhandled rejection
- add regression tests for the runner bridge and AssistantStream paths,
  plus edge-case tests for abort retention, exactly-once failure
  delivery, break-aborts, post-end iteration, and events('error')
- make the buffered-error tests deterministic by awaiting the stream's
  terminal signal and asserting the exact error class and message
@pouyashahrdami

Copy link
Copy Markdown
Contributor Author

@jbeckwith-oai Thanks for the thorough review — all points addressed in 5f98601.

Shared adapter: Went with your suggestion: extracted the events() logic into a shared EventStream#_createIterator and rebuilt every buffered adapter on it — both Symbol.asyncIterator implementations, AssistantStream's iterator, and ChatCompletionStreamingRunner.toReadableStream(). events() itself now delegates to it too, so there's exactly one copy of the queue/retained-failure logic left. Per-path semantics are preserved: break-out-of-loop still aborts, the runner bridge still registers listeners eagerly (pre-pull message deltas aren't dropped), and AssistantStream still clones at push time.

Cleanup: Listeners are removed and queues drained on end/return. This surfaced one subtlety worth flagging: the old leaked listeners incidentally suppressed the intentional unhandled-rejection warning when a consumer breaks out of iteration (the self-triggered abort found no listeners after cleanup). return() now marks the terminal promise handled before invoking the abort hook, so existing consumer behavior is unchanged; events() doesn't use that hook, so its "don't suppress after cleanup" contract still holds (covered by the existing test).

Tests: Added regressions for both paths you flagged (both fail on the previous head), plus edge cases: abort retention through a full buffer, exactly-once failure delivery with a pending reader, break-aborts, and post-end iteration returning done instead of hanging. The buffered-error tests now await the stream's terminal done() signal instead of sleeping, and assert the exact error class and message.

Full suite, type check, lint, format, and build are green locally. Ready for another look.

…ffered-stream-errors

# Conflicts:
#	src/lib/EventStream.ts
#	src/lib/responses/ResponseStream.ts
#	tests/lib/ChatCompletionStream.test.ts
#	tests/lib/EventStream.test.ts
#	tests/lib/ResponseStream.test.ts
@HAYDEN-OAI
HAYDEN-OAI dismissed jbeckwith-oai’s stale review August 12, 2026 15:33

Superseded by verified head 03a2cb1: all buffered adapters now share retained-error handling, deterministic regressions cover Chat, Assistants, Responses, and runner serialization, and 1,727 tests plus build and compatibility checks pass.

@HAYDEN-OAI HAYDEN-OAI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verified against actual buffered provider failures across Chat Completions, Assistants, Responses, and tool-runner readable streams. Shared iterator preserves exact-once errors, cancellation, listener cleanup, Assistant snapshots, and existing SSE/custom-tool fixes. Full handwritten suite: 1,727 passing; lint, breaking-change check, package build, and TypeScript 4.9/current checks all pass.

@HAYDEN-OAI
HAYDEN-OAI enabled auto-merge August 12, 2026 15:34
@HAYDEN-OAI
HAYDEN-OAI added this pull request to the merge queue Aug 12, 2026
Merged via the queue into openai:main with commit 8cc6cac Aug 12, 2026
10 checks passed
@openai-sdks openai-sdks Bot mentioned this pull request Aug 12, 2026
@pouyashahrdami

Copy link
Copy Markdown
Contributor Author

Appreciate your feedback!

This branch was previously deployed

1 inactive deployment
ci — 03a2cb12 Deployed Aug 12, 2026 by HAYDEN-OAI via examples #7253
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ChatCompletionStream/ResponseStream: mid-stream errors are silently swallowed when iterating with for await

3 participants