Repository navigation
fix(streaming): finish SSE streams immediately after [DONE] - #2317
Conversation
HAYDEN-OAI
left a comment
There was a problem hiding this comment.
Reviewed the complete two-file change. Both files are handwritten (neither has the canonical Castiron/Stainless banner), so I added sdk. Stopping at [DONE] fixes the indefinite wait and the regression covers cancellation, lock release, and controller state. One completion-path error-handling issue remains, noted inline.
jbeckwith-oai
left a comment
There was a problem hiding this comment.
One validated medium-severity cleanup blocker remains.
At src/core/streaming.ts:70-72, the code sets done = true before break. Exiting the for await loop awaits the nested stream iterator's return(); native ReadableStream iterators and the fallback adapter can reject there when cancel() fails. Because done is already true, that rejection reaches the consumer while the outer finally skips controller.abort(). I reproduced this on the exact head: the body lock was released, but cancellation rejected and controller.signal.aborted remained false, so transport termination was no longer guaranteed.
Please remove the inner done = true; the existing post-loop assignment will then mark only successful cleanup, while a rejected cleanup retains the abort fallback. The now-unreachable if (done) continue branch can also be removed. Add a real-ReadableStream regression whose cancel() rejects, asserting the selected error behavior and that the controller is aborted.
The successful-cancellation behavior and its new regression otherwise look strong. Focused tests pass 41/41; TypeScript, lint, diff hygiene, and all exact-head CI are green.
HAYDEN-OAI
left a comment
There was a problem hiding this comment.
Re-reviewed the complete updated two-file diff. The fix now distinguishes protocol completion from successful iterator cleanup: [DONE] remains authoritative when body cancellation rejects, while done stays false so the outer abort fallback runs. The new real-stream regression covers the rejected-cancel branch, cancellation count, lock release, and controller state. No new correctness issues found. The two code-quality warnings are false positives because the flag is observed specifically when awaited async-iterator closing rejects; I replied with that control-flow explanation. Main CI is still running.
jbeckwith-oai
left a comment
There was a problem hiding this comment.
The prior cleanup blocker is resolved. [DONE] now records terminal protocol state without marking cleanup complete; successful nested-iterator cleanup finishes normally, while a rejecting body cancellation is suppressed only after the sentinel and leaves done false so the outer finally aborts the request as fallback. Pre-sentinel parse, API, and transport failures still propagate, and caller-driven early return still aborts.
The new regression uses a real ReadableStream and verifies rejected cancellation, lock release, no read past [DONE], and fallback abort. Focused tests pass 42/42; all exact-head CI is green; both changed files remain below the size threshold with no structural or suppression concern.
## Production impact Merged openai#1913 documented production Node.js event-loop utilization reaching 100% while decoding fragmented SSE responses; roughly 95% of delimiter scans were redundant. That change fixed quadratic delimiter **rescanning**, but the immediately adjacent `iterSSEChunks` append path still allocated an exact-size `Uint8Array` and recopied every previously buffered byte for every transport fragment. For `n` one-byte fragments, copying the existing prefix alone costs `n(n - 1) / 2` bytes: - 16 KiB: **134,209,536 bytes** copied for one 16,384-byte event. - 1 MiB: **549,755,289,600 bytes** copied for one 1,048,576-byte event. Fragmented upstream responses, slow custom transports, or large audio/structured-output events can therefore create avoidable CPU and GC pressure and exhaust the event loop even after openai#1913. ## Change - Keep a geometrically growing `Uint8Array` and track its active start/end plus the absolute delimiter scan cursor. - Compact only when the consumed prefix occupies at least half the capacity **and** the live event plus incoming fragment still fit; otherwise grow geometrically. This avoids repeatedly copying a huge live tail to reclaim a tiny consumed prefix. - Preserve openai#1913's three-byte delimiter overlap, consecutive events, mixed CR/LF separators split across fragments, null chunks, strings/`ArrayBuffer`/`Uint8Array`, and trailing incomplete events. - Yield defensive frame copies so later buffer reuse cannot mutate retained consumer data; do not impose an arbitrary event-size limit. - Leave merged openai#2317 completion-sentinel cancellation and reader-cleanup behavior unchanged. Open openai#2086 and openai#1648 modify separate earlier regions of this file and do not overlap this patch. Only the handwritten streaming implementation and handwritten streaming-core tests are changed; no generated SDK files, resources, types, or benchmarks are modified. ## Regression-first evidence The new deterministic regression feeds a 4,104-byte SSE event one byte at a time and instruments `Uint8Array.prototype.set`; the assertion requires total copied bytes to remain below `8n = 32,832`. Before this change, the focused test failed with: ```text AssertionError: expected 8427564 to be less than 32832 ``` After this change, the same actual decoder copies **16,399 bytes** (~514x less). Additional focused regressions force compaction across a split CRLF delimiter while retaining an earlier frame, and verify that a tiny consumed prefix never compacts a large live event. The existing no-rescan regression and both openai#2317 sentinel/cancellation regressions continue to pass. ## Existing repository benchmarks Medians from the existing `tests/benchmarks/streaming.bench.ts` fixtures on the same remote devbox, Node.js 26.7.0, Vitest 4.1.10, and one-byte transport fragments; each baseline used 10 samples and optimized runs used 10-18 samples: | Fixture | Operation | Before | After | Improvement | | --- | --- | ---: | ---: | ---: | | 8 KiB | Decode SSE frames | 31.43 ms | 6.44 ms | **4.88x** | | 8 KiB | Decode and parse SSE JSON | 36.95 ms | 5.72 ms | **6.46x** | | 16 KiB | Decode SSE frames | 60.47 ms | 11.60 ms | **5.21x** | | 16 KiB | Decode and parse SSE JSON | 62.05 ms | 11.45 ms | **5.42x** | Benchmark measurements are informational; the regression asserts deterministic copied-byte complexity, not wall-clock timing. ## Verification - `pnpm test:unit tests/lib/streaming-core.test.ts` — **45 passed**. - `pnpm test:unit` — **1,941 passed across 68 handwritten test files**. - `pnpm lint` — passed. - `pnpm exec tsc` — passed. - `pnpm build` — passed, including CommonJS/ESM and Bedrock package smoke tests. - `./node_modules/typescript-4-9/bin/tsc --project dist/src/tsconfig.json --noEmit` — passed. - `./node_modules/typescript/bin/tsc --project dist/src/tsconfig.json --noEmit` — passed. - `pnpm bench tests/benchmarks/streaming.bench.ts --testNamePattern='(8|16) KiB event / 1-byte chunks'` — before/after measurements above. - `git diff --check` — passed.
Impact
OpenAI's SSE protocol defines
data: [DONE]as the terminal event, butStream.fromSSEResponsecurrently marks the stream done and then continues reading until the HTTP response reaches physical EOF. If an upstream server, load balancer, or reverse proxy keeps the response open after delivering[DONE], consumers can hang indefinitely even though generation has completed. This affects direct async iteration and higher-level stream aggregation helpers such asfinalChatCompletion(), while retaining the response-body reader and network resources.Root cause and fix
The sentinel branch currently executes
done = true; continue;. Replace only thatcontinuewithbreak:donebefore leaving the loop so successful completion does not spuriously abort the stream'sAbortController.Only handwritten streaming implementation and handwritten unit-test files are changed; no generated SDK files or tests are modified.
Regression-first evidence
The new regression constructs a real
ReadableStreamthat enqueues one JSON event followed bydata: [DONE]\n\nand deliberately never closes its body. AhighWaterMarkof0disables speculative reads, and the source'spull()throws immediately if the SDK requests any bytes beyond the terminal event. This is fully deterministic and uses no sleep or timing-based race.Before the implementation change, the focused suite failed with:
After the fix, the regression verifies that the first item is yielded, the second iterator call immediately resolves as complete while the source remains unclosed, the body is canceled exactly once, the reader lock is released, and the request controller remains unaborted.
Verification
pnpm test:unit tests/lib/streaming-core.test.ts— 41 passedpnpm test:unit— 1,845 passed across 66 test filespnpm lint— passedpnpm exec tsc— passedgit diff --check— passed