Skip to content

fix(ai): long ChatGPT Responses SSE turns fail after 16 MiB of streamed events - #166853

Merged
steipete merged 3 commits into
openclaw:mainfrom
Jackten:fix/chatgpt-responses-sse-pending-buffer-cap
Oct 8, 2026
Merged

steipete merged 3 commits into
openclaw:mainfrom
Jackten:fix/chatgpt-responses-sse-pending-buffer-cap

Conversation

@Jackten

@Jackten Jackten commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: long ChatGPT Responses SSE turns fail after 16 MiB of healthy streamed events, leaving the agent turn unfinished.

Related: #166848. This fixes its cumulative SSE-cap failure; the issue also covers session-sticky WebSocket fallback and failure classification, so it should remain open for those separate concerns.

User Impact

Long SSE turns can finish even when aggregate event traffic exceeds 16 MiB. Individual oversized events still fail and cancel the reader, including completed, unterminated, EOF, and multibyte frames. No configuration change, migration, or new option is required.

Why This Change Was Made

The parser owns framing and retained input. The previous cumulative guard counted events that had already been parsed and discarded. The contributor patch moved the guard to pending text, but completed oversized frames bypassed it and its UTF-16 character threshold changed the unit of protection.

Maintainer decision: retain a 16 MiB byte budget for one buffered frame, and permit longer aggregate streams. The parser now scans byte boundaries incrementally and checks the budget before growing its buffer, decoding, or JSON parsing. Every growing allocation is explicitly capped. It handles multiple frames in a single large read, chunk-split CRLF delimiters, and final EOF frames. Reader cancellation remains non-blocking. This preserves the memory-hardening purpose of #96762 without imposing a total-transfer cap on healthy turns. WebSocket fallback policy is unchanged.

Original fix by @Jackten; maintainer cleanup replaces pending-character checks with bounded byte framing, closes the completed-frame bypass, and adds regression coverage and documentation. The original contributor commit is preserved, with human coauthor credit in the follow-up commit.

Evidence

Verified head: 01fa0f1d390ac6fd96c84b4c5885769352448d20 on fresh secretless AWS lease cbx_96c07c320d80, explicitly pinned to r7a.xlarge (4 vCPU, 32 GiB). All commands ran sequentially. The clean trusted-main bootstrap verified the full SHA and IMDS no-role boundary; networking was public with no Tailscale, hydration was disabled, and only CI was eligible for environment forwarding. No contributor code ran on the host.

Check Result
pnpm tsgo:core Passed, 68 s wall time
pnpm tsgo:core:test packages Passed, 105 s wall time; covering graph 56.3 s
All five ChatGPT Responses test files 94 passed; 7 s command wall time, 5.36 s Vitest
Limit tests alone, --maxWorkers=1 8 passed; 5 s command wall time, 3.26 s Vitest
Production-only negative control Failed as expected after restoring only the parser to the merge base; unchanged long-stream tests reported the original cumulative 16 MiB error
Real Gateway, fixed parser HTTP 200, exact reply LONG_SSE_TURN_COMPLETED, one primary provider request; 20,988,035 bytes across 326 SSE events, 5.014 s turn time
Real Gateway, main-parser control HTTP 500, no completed reply; original cumulative-limit error, 5.457 s turn time
Real Gateway, oversized completed/unterminated frames HTTP 500 with the repaired parser's own 16 MiB frame-limit error
Open-stream cancellation Passed: HTTP 500 with the frame-bound error; all four attempts disconnected before completion, after 18,546,851–19,267,747 wire bytes of a planned 64 MiB stream; 6.337 s turn time

The live setup used the real pnpm openclaw gateway run process with isolated state, workspace, auth, and ephemeral loopback ports. A local HTTP server supplied ChatGPT Responses SSE at /codex/responses; a synthetic token was stored through the normal models auth paste-token CLI. The fixture used provider openai, the explicit ChatGPT adapter, OpenClaw runtime, SSE transport, and a small synthetic utility-model response. This selects the native ChatGPT parser under the real Gateway.

For both negative controls, only packages/ai/src/providers/openai-chatgpt-responses-protocol.ts was restored from merge base eacaa1b64cfa333256769a1b1dc7e8532606bc20 (blob 3c7e4e5197b4ac00e129765d8f368bb1a44b196d). That parser is identical to the inspected main implementation. The same pushed Git HEAD, tests, dependencies, and lease were retained. The baseline Gateway was rebuilt; the fixed file was restored afterward and git diff --exit-code HEAD passed.

Representative excerpts:

fixed: HTTP 200; bytesWritten=20988035; framesWritten=326
fixed: content=LONG_SSE_TURN_COMPLETED; primaryRequests=1
main parser: HTTP 500; no completed reply
main parser: OpenAI ChatGPT Responses success body exceeded 16777216 bytes (received 16839601)
oversized frame: OpenAI ChatGPT Responses SSE frame exceeded 16777216 bytes
open stream: completed=false; disconnected=true on every attempt; plannedBytes=67108864

The cancellation fixture keeps producing toward 64 MiB and asserts actual disconnect before completion. Wire bytes include socket buffering; the parser guard remains 16,777,216 bytes.

The existing agent recovery policy made four attempts for the deliberately failing turns. The successful long turn made one request. WebSocket recovery and failure classification remain separate concerns in #166848.

Exact-head CI and CodeQL passed. Local static formatting, targeted oxlint, and diff checks passed. Independent Codex autoreview was scoped clean through P2; ClawSweeper revision 3 on this head reported no remaining code or security findings. This evidence addresses its outstanding real-transport proof and test-cost requests.

Executed commands and test cost

The trusted bootstrap was launched with CRABBOX_ENV_ALLOW=CI, --provider aws --id cbx_96c07c320d80 --fresh-pr openclaw/openclaw#166853 --no-hydrate, and the full head SHA. The check commands were:

pnpm tsgo:core
pnpm tsgo:core:test packages
pnpm test \
  packages/ai/src/providers/openai-chatgpt-responses-limits.test.ts \
  packages/ai/src/providers/openai-chatgpt-responses-protocol.test.ts \
  packages/ai/src/providers/openai-chatgpt-responses.cache.test.ts \
  packages/ai/src/providers/openai-chatgpt-responses-streaming.test.ts \
  packages/ai/src/providers/openai-chatgpt-responses.test.ts --maxWorkers=1
pnpm test packages/ai/src/providers/openai-chatgpt-responses-limits.test.ts --maxWorkers=1

The limit command was repeated with only the production parser restored to the merge base. It exited 1 in 3 s; the two healthy-stream cases failed with success body exceeded 16777216 bytes (received 16,789,504 and 20,986,880 bytes). Other negative-control failures reflect the deliberately restored old error message; they are not claimed as independent behavior regressions.

The live harness ran these commands on the lease, with the parser switched between them:

node "$proof_dir/gateway-sse-proof.mjs" "$PWD" \
  01fa0f1d390ac6fd96c84b4c5885769352448d20 success head
node "$proof_dir/gateway-sse-proof.mjs" "$PWD" \
  01fa0f1d390ac6fd96c84b4c5885769352448d20 failure main-production

The separate open-stream cancellation cell ran:

node "$proof_dir/gateway-cancellation-proof.mjs" "$PWD" \
  01fa0f1d390ac6fd96c84b4c5885769352448d20 success cancellation pending-only

Each harness invocation starts pnpm openclaw gateway run --port <ephemeral> --bind loopback --allow-unconfigured and sends a normal authenticated /v1/chat/completions request. Both Gateway/fake-server pairs stopped successfully. Paired live gates, including build/startup/auth/cleanup, took 108 s and 172 s.

CI cost: the eight limit cases totaled 1.010 s of reported execution; their 209-test/10-file shard took 3.45 s. The full containing CI job took 131 s including setup and other shards.

Scope, review findings, and recovery notes

Exact numstat against the merge base (touched files were unchanged on inspected main):

Area Added Removed Net
Production 59 53 +6
Tests 103 4 +99
Docs 4 0 +4

Production LOC exception: the six-line increase supplies incremental byte framing and bounds allocation before decoding/parsing. No unrelated or compressed cleanup funds the change.

ClawSweeper's completed-frame bypass and character-based accounting findings are fixed by the byte guard before buffering and parsing. The per-frame resource-policy decision is documented above. The live before/after comparison, oversized-frame rejection, cancellation proof, and measured test cost provide the requested evidence.

Earlier proof attempts hit fleet capacity, inspection timeouts, and an undersized quota fallback; those leases were released. An initial finite-stream test fixture closed before cancellation could be observed; the follow-up switched it to demand-driven reads without weakening assertions. Final-head unit tests passed. Live fixture corrections removed a retired agent-default marker, selected the actual native OpenAI ChatGPT path with synthetic token auth, and supplied the normal utility-model response. These were fixture changes, not product changes; failed attempts are not counted as passing evidence.

The approved replacement remained bound to the same head throughout. Final lease cleanup: crabbox stop --provider aws cbx_96c07c320d80 succeeded; the final crabbox list --provider aws --json contained none of this task's lease IDs.

…ed events

The SSE success-body guard capped the cumulative stream at 16 MiB, so long
reasoning turns that stream many small well-formed events died mid-turn with
"success body exceeded 16777216 bytes". Bound only the unterminated pending
frame instead, matching the Anthropic Messages transport, so a hostile
endpoint that never emits a frame boundary is still cut off.

Related: openclaw#166848

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 8, 2026
@clawsweeper

clawsweeper Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 8, 2026, 5:19 AM ET / 09:19 UTC (Revision 6).

ClawSweeper review

What this changes

The PR replaces ChatGPT Responses’ cumulative 16 MiB streaming limit with a 16 MiB limit on each buffered event, preserving oversized-event cancellation.

Example: An agent receives 20,988,035 bytes across 326 streamed events

  • Before: The turn fails with the cumulative 16777216-byte limit error and returns HTTP 500.
  • After: The turn returns HTTP 200 with LONG_SSE_TURN_COMPLETED after one primary provider request.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Strong Gateway proof and a clean focused patch; the rating reflects partial coverage of the broader linked transport report.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (terminal): Exact-head copied terminal results exercise the changed parser through the real Gateway and HTTP transport: the long turn completes, the parser-only baseline fails, and oversized open streams disconnect before completion. Both previous proof requests are satisfied; no stored-data contract changes.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Partial
User problem: Long ChatGPT agent turns fail before finishing even though the endpoint continues sending healthy events.
Reason: The real failure warrants a focused repair, and the parser-area contributor has recorded the revised resource policy. The PR correctly uses Related for the broader issue because its other transport concerns remain.

Merge readiness

✅ Ready for maintainer review

Keep open: this is a useful repair for an active failure still present on main. The new Gateway evidence satisfies the previous proof requests, and no actionable code or security finding remains.

Priority: P1
Reviewed head: 01fa0f1d390ac6fd96c84b4c5885769352448d20

Before merge

None.

Findings

None.

Agent review details

How this fits together

The ChatGPT Responses provider reads server-sent events, which deliver model output incrementally over HTTP. Its parser turns incoming bytes into events consumed by the agent and cancels responses that exceed its buffering limit.

flowchart TD
  A[Agent model request] --> B[ChatGPT HTTP response]
  B --> C[Incremental byte framing]
  C --> D{Event exceeds 16 MiB?}
  D -->|Yes| E[Cancel response and report error]
  D -->|No| F[Decode and parse event]
  F --> G[Agent receives model output]
  F --> C
Loading

Technical review

Best possible solution:

Land the bounded-frame repair while leaving WebSocket recovery and failure classification tracked in #166848.

Do we have a high-confidence way to reproduce the issue?

Yes: current source proves that healthy aggregate traffic above 16777216 bytes fails, and the supplied real Gateway parser-only negative control observes that error. This read-only review did not execute the reproduction.

Is this the best way to solve the issue?

Yes for the SSE-limit defect: bounding bytes at the canonical framing owner preserves memory protection without limiting already-consumed events. The broader linked transport report remains only partially addressed.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 54bd6ecee189.

Provenance checked

  • ChatGPT Responses SSE resource limit and limit regression tests changes intended behavior with a stated reason (fix(openai-chatgpt-responses): bound streaming success-body SSE reads at 16 MiB #96762: Prevent hostile or malfunctioning endpoints from exhausting memory through unbounded streaming success bodies.)
  • packages/ai/src/providers/openai-chatgpt-responses-protocol.ts canonical parser ownership keeps the original intent (5eebaf9: Internalize framing and resource ownership without restoring a test-only provider export or adding a public package surface.)
  • Final-frame recovery and malformed EOF handling keeps the original intent (924381f: Preserve completion events when endpoints omit the final blank line and retain malformed-fragment guidance.)

Testing

Proof path: shipped entry point. Added test files: 1.

Security

None.

Evidence

What I checked:

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • vincentkoc: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • zenglingbiao: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

PR surface

Source +6, Tests +99, Docs +4. Total +109 across 3 files.

View PR surface stats
Area Files Added Removed Net
Source 1 59 53 +6
Tests 1 103 4 +99
Docs 1 4 0 +4
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 3 166 57 +109

Review metrics

Metric Value Why it matters
Resource-budget policy 16 MiB cumulative transfer limit becomes a 16 MiB per-event byte limit The accepted policy permits long healthy turns while retaining a bounded parser allocation and oversized-event cancellation.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 📣 needs proof: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P1: Reported production agent turns fail mid-task after crossing the cumulative stream cap, and current main retains that mechanism.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only; repair and merge need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (5 earlier review cycles)
  • reviewed 2026-10-08T00:55:00.871Z sha c3cd3cb :: needs real behavior proof before merge. :: [P2] Check completed frame size before parsing it
  • reviewed 2026-10-08T06:10:01.263Z sha f9fc2c1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-08T06:27:36.568Z sha 01fa0f1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-08T07:00:43.483Z sha 01fa0f1 :: needs real behavior proof before merge. :: none
  • reviewed 2026-10-08T08:11:25.962Z sha 01fa0f1 :: needs real behavior proof before merge. :: none

Allow long, well-framed ChatGPT SSE turns to complete without a cumulative
16 MiB transfer cap. Enforce the same byte budget on retained individual
frames before growing the allocation or decoding, including completed,
unterminated, EOF, multibyte, and chunk-split frames. Keep cancellation
non-blocking and preserve consumer-owned failures.

Original fix by @Jackten; maintainer cleanup adds byte-level framing,
completed-frame enforcement, and regression coverage. Addresses the SSE
limit portion of openclaw#166848; WebSocket fallback policy remains separate.

Co-authored-by: Jack Alderson <[email protected]>
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M and removed size: S labels Oct 8, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. label Oct 8, 2026
Disable speculative EOF prefetch in the finite oversized-frame fixture so the cancellation callback stays observable. Preserve rejection, cancellation reason, and reader-lock assertions. Reproduced the four fixture failures in CI and on secretless AWS before changing the fixture.
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Oct 8, 2026
@steipete
steipete merged commit bd23988 into openclaw:main Oct 8, 2026
142 checks passed
@steipete

steipete commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 9, 2026
…ed events (openclaw#166853)

Long ChatGPT Responses SSE turns failed after 16 MiB of cumulative traffic, even when completed events had already been consumed. Bound each retained SSE frame to 16 MiB before buffer growth, decoding, or parsing so legitimate longer streams finish while oversized frames still fail and cancel upstream.

The framing owner preserves EOF and chunk-split CRLF handling and non-blocking cancellation. Provider regression coverage and documentation describe the per-frame byte budget. Original fix by @Jackten; maintainer cleanup closes the completed-frame bypass and preserves byte accounting.

Validation at 01fa0f1: core and package-test types, 94 provider tests, eight standalone one-worker limit cases, production-only negative control, and real Gateway transport proof. A 20,988,035-byte turn across 326 SSE events completed through one request; the main-parser control failed with the original HTTP 500 error. Oversized frames were rejected and the 64 MiB streaming probe disconnected upstream. Exact-head CI and CodeQL passed; ClawSweeper revision 6 is ready for maintainer review with no findings.

Related: openclaw#166848. WebSocket fallback and failure classification remain open.

Co-authored-by: Jack Alderson <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
RomneyDa pushed a commit that referenced this pull request Oct 11, 2026
…ed events (#166853)

Long ChatGPT Responses SSE turns failed after 16 MiB of cumulative traffic, even when completed events had already been consumed. Bound each retained SSE frame to 16 MiB before buffer growth, decoding, or parsing so legitimate longer streams finish while oversized frames still fail and cancel upstream.

The framing owner preserves EOF and chunk-split CRLF handling and non-blocking cancellation. Provider regression coverage and documentation describe the per-frame byte budget. Original fix by @Jackten; maintainer cleanup closes the completed-frame bypass and preserves byte accounting.

Validation at 01fa0f1: core and package-test types, 94 provider tests, eight standalone one-worker limit cases, production-only negative control, and real Gateway transport proof. A 20,988,035-byte turn across 326 SSE events completed through one request; the main-parser control failed with the original HTTP 500 error. Oversized frames were rejected and the 64 MiB streaming probe disconnected upstream. Exact-head CI and CodeQL passed; ClawSweeper revision 6 is ready for maintainer review with no findings.

Related: #166848. WebSocket fallback and failure classification remain open.

Co-authored-by: Jack Alderson <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit bd23988)
wheakerd pushed a commit to wheakerd/clawdbot that referenced this pull request Oct 22, 2026
…ed events (openclaw#166853)

Long ChatGPT Responses SSE turns failed after 16 MiB of cumulative traffic, even when completed events had already been consumed. Bound each retained SSE frame to 16 MiB before buffer growth, decoding, or parsing so legitimate longer streams finish while oversized frames still fail and cancel upstream.

The framing owner preserves EOF and chunk-split CRLF handling and non-blocking cancellation. Provider regression coverage and documentation describe the per-frame byte budget. Original fix by @Jackten; maintainer cleanup closes the completed-frame bypass and preserves byte accounting.

Validation at 01fa0f1: core and package-test types, 94 provider tests, eight standalone one-worker limit cases, production-only negative control, and real Gateway transport proof. A 20,988,035-byte turn across 326 SSE events completed through one request; the main-parser control failed with the original HTTP 500 error. Oversized frames were rejected and the 64 MiB streaming probe disconnected upstream. Exact-head CI and CodeQL passed; ClawSweeper revision 6 is ready for maintainer review with no findings.

Related: openclaw#166848. WebSocket fallback and failure classification remain open.

Co-authored-by: Jack Alderson <[email protected]>
Co-authored-by: Peter Steinberger <[email protected]>
(cherry picked from commit bd23988)
(cherry picked from commit 4ba79d5)
Co-authored-by: RomneyDa <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants