Skip to content

fix(streaming): eliminate quadratic SSE buffer copying - #2324

Merged
HAYDEN-OAI merged 1 commit into
mainfrom
codex/sse-amortized-buffer-019ffdc4
Aug 14, 2026
Merged

HAYDEN-OAI merged 1 commit into
mainfrom
codex/sse-amortized-buffer-019ffdc4

Conversation

@HAYDEN-OAI

Copy link
Copy Markdown
Contributor

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 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 #1913.

Change

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:

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 #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.

@openai-sdks

openai-sdks Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

OkTest Summary

✅ 237/237 SDK tests passed in 8.68s for Node SDK PR #2324.

Test results — 42 files
Test Result Time
tests/chat-completions-complex-body.test.ts ✅ Passed 152ms
tests/chat-completions-create.test.ts ✅ Passed 188ms
tests/chat-completions-stream.test.ts ✅ Passed 162ms
tests/files-content-binary.test.ts ✅ Passed 102ms
tests/files-create-multipart.test.ts ✅ Passed 115ms
tests/files-list-pagination.test.ts ✅ Passed 113ms
tests/initialize-config.test.ts ✅ Passed 158ms
tests/instance-isolation.test.ts ✅ Passed 91ms
tests/models-list.test.ts ✅ Passed 101ms
tests/responses-background-lifecycle.test.ts ✅ Passed 179ms
tests/responses-body-method-errors.test.ts ✅ Passed 204ms
tests/responses-cancel-timeout.test.ts ✅ Passed 199ms
tests/responses-cancel.test.ts ✅ Passed 176ms
tests/responses-compact-retries.test.ts ✅ Passed 184ms
tests/responses-compact.test.ts ✅ Passed 173ms
tests/responses-create-advanced-stream.test.ts ✅ Passed 81ms
tests/responses-create-advanced.test.ts ✅ Passed 126ms
tests/responses-create-disconnect.test.ts ✅ Passed 1.084s
tests/responses-create-errors.test.ts ✅ Passed 289ms
tests/responses-create-malformed-api-responses.test.ts ✅ Passed 138ms
tests/responses-create-retries.test.ts ✅ Passed 118ms
tests/responses-create-stream-failures.test.ts ✅ Passed 155ms
tests/responses-create-stream-timeout.test.ts ✅ Passed 2.129s
tests/responses-create-stream-wire.test.ts ✅ Passed 1.997s
tests/responses-create-stream.test.ts ✅ Passed 62ms
tests/responses-create-terminal-states.test.ts ✅ Passed 150ms
tests/responses-create-timeout.test.ts ✅ Passed 174ms
tests/responses-create.test.ts ✅ Passed 111ms
tests/responses-delete.test.ts ✅ Passed 86ms
tests/responses-input-items-errors.test.ts ✅ Passed 131ms
tests/responses-input-items-list.test.ts ✅ Passed 139ms
tests/responses-input-items-options.test.ts ✅ Passed 90ms
tests/responses-input-tokens-count-timeout.test.ts ✅ Passed 243ms
tests/responses-input-tokens-count.test.ts ✅ Passed 146ms
tests/responses-malformed-inputs.test.ts ✅ Passed 1.638s
tests/responses-not-found-errors.test.ts ✅ Passed 166ms
tests/responses-parse.test.ts ✅ Passed 123ms
tests/responses-retrieve-retries.test.ts ✅ Passed 198ms
tests/responses-retrieve.test.ts ✅ Passed 168ms
tests/responses-stored-method-errors.test.ts ✅ Passed 582ms
tests/retry-behavior.test.ts ✅ Passed 2.898s
tests/sdk-error-shape.test.ts ✅ Passed 202ms

View OkTest run #31759868663

SDK merge (b36ced545ae6) · head (b55a3d495adb) · base (486e1917b013) · OkTest (a845fa206fa4)

@HAYDEN-OAI HAYDEN-OAI left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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 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.

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.

@HAYDEN-OAI
HAYDEN-OAI added this pull request to the merge queue Aug 14, 2026
Merged via the queue into main with commit ebdb296 Aug 14, 2026
27 checks passed
@HAYDEN-OAI
HAYDEN-OAI deleted the codex/sse-amortized-buffer-019ffdc4 branch August 14, 2026 15:16
@openai-sdks openai-sdks Bot mentioned this pull request Aug 14, 2026
virelai2604 pushed a commit to virelai2604/openai-node that referenced this pull request Aug 15, 2026
…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.

This branch was previously deployed

1 inactive deployment
ci — b55a3d49 Deployed Aug 14, 2026 by HAYDEN-OAI via ecosystem tests #7393
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants