Skip to content

fix(streaming): make fragmented line decoding amortized linear - #2336

Merged
HAYDEN-OAI merged 5 commits into
mainfrom
agent/fix-line-decoder-linear-20260814-mst5e1tw
Aug 15, 2026
Merged

HAYDEN-OAI merged 5 commits into
mainfrom
agent/fix-line-decoder-linear-20260814-mst5e1tw

Conversation

@HAYDEN-OAI

@HAYDEN-OAI HAYDEN-OAI commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

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

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.

@openai-sdks

openai-sdks Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

OkTest Summary

✅ 237/237 SDK tests passed in 10.194s for Node SDK PR #2336.

Test results — 42 files
Test Result Time
tests/chat-completions-complex-body.test.ts ✅ Passed 132ms
tests/chat-completions-create.test.ts ✅ Passed 228ms
tests/chat-completions-stream.test.ts ✅ Passed 206ms
tests/files-content-binary.test.ts ✅ Passed 131ms
tests/files-create-multipart.test.ts ✅ Passed 140ms
tests/files-list-pagination.test.ts ✅ Passed 193ms
tests/initialize-config.test.ts ✅ Passed 194ms
tests/instance-isolation.test.ts ✅ Passed 100ms
tests/models-list.test.ts ✅ Passed 129ms
tests/responses-background-lifecycle.test.ts ✅ Passed 223ms
tests/responses-body-method-errors.test.ts ✅ Passed 347ms
tests/responses-cancel-timeout.test.ts ✅ Passed 230ms
tests/responses-cancel.test.ts ✅ Passed 221ms
tests/responses-compact-retries.test.ts ✅ Passed 272ms
tests/responses-compact.test.ts ✅ Passed 232ms
tests/responses-create-advanced-stream.test.ts ✅ Passed 121ms
tests/responses-create-advanced.test.ts ✅ Passed 179ms
tests/responses-create-disconnect.test.ts ✅ Passed 1.065s
tests/responses-create-errors.test.ts ✅ Passed 179ms
tests/responses-create-malformed-api-responses.test.ts ✅ Passed 143ms
tests/responses-create-retries.test.ts ✅ Passed 222ms
tests/responses-create-stream-failures.test.ts ✅ Passed 226ms
tests/responses-create-stream-timeout.test.ts ✅ Passed 2.149s
tests/responses-create-stream-wire.test.ts ✅ Passed 2.636s
tests/responses-create-stream.test.ts ✅ Passed 76ms
tests/responses-create-terminal-states.test.ts ✅ Passed 195ms
tests/responses-create-timeout.test.ts ✅ Passed 214ms
tests/responses-create.test.ts ✅ Passed 145ms
tests/responses-delete.test.ts ✅ Passed 216ms
tests/responses-input-items-errors.test.ts ✅ Passed 246ms
tests/responses-input-items-list.test.ts ✅ Passed 180ms
tests/responses-input-items-options.test.ts ✅ Passed 145ms
tests/responses-input-tokens-count-timeout.test.ts ✅ Passed 229ms
tests/responses-input-tokens-count.test.ts ✅ Passed 244ms
tests/responses-malformed-inputs.test.ts ✅ Passed 2.18s
tests/responses-not-found-errors.test.ts ✅ Passed 252ms
tests/responses-parse.test.ts ✅ Passed 208ms
tests/responses-retrieve-retries.test.ts ✅ Passed 245ms
tests/responses-retrieve.test.ts ✅ Passed 217ms
tests/responses-stored-method-errors.test.ts ✅ Passed 525ms
tests/retry-behavior.test.ts ✅ Passed 2.853s
tests/sdk-error-shape.test.ts ✅ Passed 230ms

View OkTest run #31824965607

SDK merge (94f7a07d20ce) · head (0b70bb5b7e0e) · base (53dd7236e807) · OkTest (a845fa206fa4)

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

[Medium] Bound the decoder buffer retained after a large completed line.

At src/internal/decoders/line.ts:94-99, consuming the active range resets only the cursors; the geometric backing buffer remains at the remotely influenced high-water capacity for the rest of the long-lived stream. Capacity can approach twice the anomalous line size. The previous implementation replaced that allocation on the next nonempty append, so this is a material retention regression across concurrent streams.

Please replace oversized empty buffers with a baseline or documented modest retention threshold (for example 64 KiB) once #start === #end, preserving geometric reuse for normal lines. Add a large-line → newline → small-line regression that proves the high-water allocation is released or bounded.

The amortized-linear decoding logic, boundary semantics, tests, and exact-head CI otherwise look correct.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 644bd82739

ℹ️ 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".

Comment thread src/internal/decoders/line.ts Resolved

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

Exact-head re-review at 644bd82.

The new 64 KiB reset only runs when every buffered byte has been consumed. A chunk containing a very large completed line followed by one unfinished byte still retains the entire high-water allocation for the remaining stream lifetime: #start < #end skips the reset, and later compaction uses copyWithin on the same oversized array.

Please compact a small active remainder into a fresh bounded buffer when capacity exceeds the retention limit, normalize the cursors, and add a same-chunk large-line + newline + one-byte-tail regression. The amortized-linear decoder behavior, protocol handling, test structure, and exact-head CI otherwise look good.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c346e21321

ℹ️ 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".

Comment thread src/internal/decoders/line.ts Resolved

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

Exact-head re-review at c346e21.

The prior tiny-tail case is fixed, but the retention policy still has a one-byte cliff: any live suffix above 64 KiB disables shrinking entirely. A huge completed line followed by a 65,537-byte unterminated suffix can therefore retain the arbitrarily large high-water allocation while the stream idles; the current over-threshold test actually permits a 65,553-byte suffix to keep a 524,288-byte buffer.

Please shrink whenever capacity is disproportionately larger than the live suffix, using a bounded/geometric ratio such as capacity > max(64 KiB, liveLength * 2), and update the >64 KiB regression to assert that ratio while preserving bytes/UTF-8. Decoder correctness, performance, thermo, and exact CI otherwise look good.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f32c8936d5

ℹ️ 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".

Comment thread tests/internal/decoders/line.test.ts Resolved

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

Re-reviewed exact head f32c893. The prior retention blocker is resolved: completed-line suffix storage is now bounded for empty, small, and >64 KiB live suffixes without reintroducing full rescans or quadratic copying. Cursor rebasing, CR/LF and split-UTF-8 handling, flush behavior, and repeated-cycle performance remain sound; focused regressions cover the former threshold cliff. Strict thermo is clean and all exact-head CI is green. No remaining findings.

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

Re-reviewed exact head 0b70bb5. The latest delta is a test-only consolidation that preserves the important capacity boundaries, reuse, scan/copy linearity, compaction, UTF-8/CRLF, and flush regressions while substantially reducing duplication. Production remains amortized-linear with bounded retained capacity across every suffix size; public streaming behavior remains covered by adjacent suites. Strict thermo is improved, no suppressions or unsuitable doubles were added, and all exact-head CI is green. No findings.

@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 exact head 0b70bb5. The LineDecoder cursor/compaction design is amortized linear, releases oversized historical storage for both small and large suffixes, and preserves CR/LF, UTF-8, and flush semantics. Focused coverage and exact-head CI are green; no findings.

@HAYDEN-OAI
HAYDEN-OAI added this pull request to the merge queue Aug 15, 2026
Merged via the queue into main with commit f32e2df Aug 15, 2026
27 checks passed
@HAYDEN-OAI
HAYDEN-OAI deleted the agent/fix-line-decoder-linear-20260814-mst5e1tw branch August 15, 2026 02:15
@openai-sdks openai-sdks Bot mentioned this pull request Aug 15, 2026

This branch was previously deployed

1 inactive deployment
ci — 0b70bb5b Deployed Aug 14, 2026 by HAYDEN-OAI via ecosystem tests #7614
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