Repository navigation
fix(streaming): eliminate quadratic SSE buffer copying - #2324
Conversation
HAYDEN-OAI
left a comment
There was a problem hiding this comment.
Reviewed the complete two-file change at this head. The geometric growth, offset rebasing during compaction, three-byte delimiter overlap, and defensive frame copies preserve the existing SSE framing semantics while removing repeated prefix copies. The focused tests exercise the linear-copy bound, retained-frame isolation, and both compaction choices. I found no actionable issues.
jbeckwith-oai
left a comment
There was a problem hiding this comment.
Reviewed the complete SSE buffering change at this exact head. The offset bookkeeping remains correct through geometric growth and half-capacity compaction, the three-byte overlap preserves every LF/CR/CRLF delimiter split, and yielded frames are copied before later buffer reuse. EOF, fragmented UTF-8, null/empty chunks, cancellation, and cleanup retain existing behavior.
The one-byte fragmentation regression decisively distinguishes the new amortized-linear copying from the prior quadratic prefix copying; focused tests pass 45/45. Formatting, lint, build, breaking-change detection, ecosystem, Node 22/24/26, test matrix, and CodeQL are all green. Files remain focused at 455/576 lines.
…i#2336) ## Summary - replace repeated whole-line concatenation with an amortized-linear, geometrically growing byte buffer - retain active-buffer and newline-search cursors so previously inspected bytes are never rescanned - compact substantially consumed prefixes without losing incomplete UTF-8 sequences or changing CR, LF, split CRLF, flush, or chunk-input semantics - add independent regression tests for copied bytes and inspected bytes, plus fragmented public NDJSON streaming and mixed-input/UTF-8 coverage ## Why `LineDecoder.decode()` previously concatenated its entire unfinished line with every incoming chunk and then searched that entire line again from byte zero. `Stream.fromReadableStream()` passes each raw NDJSON fragment directly to this decoder, so adversarial or naturally fragmented transports could turn a 32 KiB response line into more than 512 MiB of byte copying plus quadratic scanning and CPU consumption. The earlier SSE event-framing fix in openai#2324 changed `src/core/streaming.ts`; it did not address this independent handwritten line decoder. This change touches only the handwritten decoder and its handwritten unit tests. It introduces no maximum line size and does not change the public API. ## Regression-first verification Before the implementation changed, the new focused suite failed independently in both dimensions: ```text copies a linear number of bytes for a line fragmented into single bytes expected 134225920 to be less than or equal to 65536 only scans newly appended bytes while a fragmented line remains unfinished Error: LineDecoder rescanned more than 8192 bytes ``` The first test feeds 16,384 one-byte fragments and instruments `Uint8Array.prototype.set`. The second independently tracks indexed typed-array reads and fails as soon as scanning exceeds a linear bound. ## Measured before / after Measurements use the real SDK implementation, one-byte fragments, and the same Node.js v26.7.0 remote devbox. Copied-byte totals were measured with `Uint8Array.prototype.set`; timings are illustrative wall-clock measurements from the same instrumented runs. | One-byte fragments | Bytes copied before | Bytes copied after | Direct decode before | Direct decode after | Public `Stream.fromReadableStream` before | Public stream after | | ---: | ---: | ---: | ---: | ---: | ---: | ---: | | 4,096 | 8,390,656 | 7,936 | 19.338 ms | 4.292 ms | 43.750 ms | 21.625 ms | | 8,192 | 33,558,528 | 16,128 | 75.942 ms | 7.305 ms | 97.445 ms | 22.393 ms | | 16,384 | 134,225,920 | 32,512 | 251.991 ms | 5.390 ms | 266.465 ms | 36.141 ms | | 32,768 | 536,887,296 | 65,280 | 938.084 ms | 13.756 ms | 964.227 ms | 68.280 ms | At 32 KiB this is approximately **8,224× fewer copied bytes**, **68× faster direct decoding**, and **14× faster public NDJSON streaming**. Independent indexed-byte instrumentation also verifies the scan improvement separately from copying: | One-byte fragments | Indexed byte reads before | Indexed byte reads after | | ---: | ---: | ---: | | 1,024 | 1,049,600 | 2,048 | | 2,048 | 4,196,352 | 4,096 | The fixed decoder performs exactly two indexed comparisons per unfinished input byte instead of repeatedly revisiting the entire accumulated line. ## Validation - `./scripts/test tests/internal/decoders/line.test.ts tests/lib/streaming-core.test.ts` — **74 passed** - `PATH="/tmp/openai-node-line-decoder-bin-mst5e1tw:$PATH" ./node_modules/.bin/vitest run --config vitest.config.mts --update=none` — **2,094 passed across 70 files** - `./scripts/lint` - `./node_modules/.bin/tsc --noEmit` - `./scripts/build` - `./node_modules/typescript-4-9/bin/tsc --project dist/src/tsconfig.json --noEmit` - `./node_modules/.bin/tsc --project dist/src/tsconfig.json --noEmit` - Differential fuzzing against the untouched upstream decoder: **8,500 deterministic scenarios / 467,444 operations**, including invalid and split UTF-8, random flushes, mixed chunk types, CRLF boundaries, and 2,500 compaction/capacity-boundary cases The temporary `PATH` entry supplies the repository's existing pnpm command in the sandbox; no package-manager, lockfile, generated-file, or public-API changes are included.
Production impact
Merged #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
iterSSEChunksappend path still allocated an exact-sizeUint8Arrayand recopied every previously buffered byte for every transport fragment.For
none-byte fragments, copying the existing prefix alone costsn(n - 1) / 2bytes: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 #1913.
Change
Uint8Arrayand track its active start/end plus the absolute delimiter scan cursor.ArrayBuffer/Uint8Array, and trailing incomplete events.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 below8n = 32,832.Before this change, the focused test failed with:
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 #2317 sentinel/cancellation regressions continue to pass.
Existing repository benchmarks
Medians from the existing
tests/benchmarks/streaming.bench.tsfixtures 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: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.