Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(codex): oversized app-server messages end the session before they are parsed #18271

Closedonly21mil(GitHub profile, opens in a new tab)wants to merge 5 commits intomain fromrefs/pull/18271/headopened View on GitHub

Problem

The Codex app-server reader buffers a newline-delimited message of any size before joining and parsing it, so one oversized message can exhaust the heap. MAX_BUFFERED_RAW_MESSAGES bounds queue length, not the bytes in one message.

Change

Add a 128 MiB ceiling per incoming message, the top of the maintainer triage's 64 to 128 MiB band. The issue reports Codex diff strings near 49 million characters. That is already about 46.7 MiB before JSON escaping or multi-byte text, so 64 MiB leaves about 1.4x headroom and 128 MiB about 2.7x. ACP's 16 MiB ceiling would reject those diffs.

Count UTF-8 bytes as fragments arrive, before retaining them, joining the line, raw logging or parsing. Keep Stream.decodeText() and count each decoded fragment once with charCodeAt, without allocating an encoded copy or rescanning retained fragments. On Linux x64 with Node v24.18.1, the loop took 270 to 298 ms per 128 Mi code units, about 2 ns per code unit. Buffer.byteLength took 15 to 63 ms on the same input, but it is a Node API; this package's only runtime dependency is effect. The streaming TextDecoder keeps code points intact, so counting each surrogate half as two bytes gives four bytes per pair. Invalid input becomes U+FFFD and counts as three bytes, covered by a boundary test. The ceiling measures the UTF-8 size of the decoded text the reader would retain.

Pack short fragments into flat blocks once their tail reaches 1,024 UTF-16 code units, and retain longer reads directly without copying them. Input that arrives a byte at a time now costs one array entry per block, with a bounded tail, rather than one entry per read. Copy a fragment that follows a newline into its own string, at most once per message, because V8 would otherwise keep it as a view that holds the whole read, including the completed lines before it.

Production reads come through a pipe into the spawner's PassThrough, with Node's default 64 KiB high-water mark, a buffering threshold, not a cap. In the Linux/Node probe, a child wrote 32 MiB in one write, then LF, while the reader slept 2 ms per read; the largest read observed was 153,728 bytes. Without the copy, a pending message also keeps alive the read holding its first fragment. The copy saves at most one such read per pending message and matters most for large reads such as in-memory stdio. Packing bounds entry overhead even if a peer writes a byte at a time.

The limit excludes LF and CRLF terminators, including CRLF split across chunks. Exactly the limit is accepted; one byte over is rejected. An unterminated final message at EOF has the same limit, including a final bare CR.

On overflow, dispatch complete lines that came earlier in the same chunk, clear the unfinished message and end the session. Pending requests fail with a typed CodexAppServerTransportError whose operation is read-input-stream. The error cause carries the limit and bytes seen, never message content. The transport error itself keeps its fixed message. The oversized message is never joined, logged or parsed.

The test-only maxIncomingMessageBytes option allows small regression fixtures. Production callers keep the 128 MiB default.

Scope and approval

Fixes #12884 and follows the design in the maintainer triage: count fragment bytes and terminate with a typed transport error before join, raw logging or decode.

This carries forward #12889 by @cestercian, which was closed during the October 11 cleanup of PRs without model disclosure, with an invitation to rebuild on current main. It keeps the 128 MiB ceiling, maxIncomingMessageBytes option name, transport error and injected-small-limit test shape.

This replaces the pendingCr flag with a trailing-CR adjustment and counts decoded fragments without explicit surrogate pairing or early exit. It packs short fragments into flat blocks instead of repeatedly concatenating them. It omits construction-time validation for the test option, adds bytes seen to the error cause and rewrites tests around shared helpers.

Inherited coverage includes pending requests receiving the same error, no raw or decoded logs for a rejected message, rejection of an unterminated oversized line after a complete line in the same chunk, and a message sent one byte per chunk routing intact.

New assertions cover one termination callback, rejection before a newline and a bare CR at EOF. They check payload exclusion from logs and errors, cause sizes, malformed UTF-8 replacement counting and split three- and four-byte characters. Block-boundary and fragment-copy tests extend the one-byte-per-chunk coverage.

Later heap pressure after decode stays out of scope: activity persistence in #12758 and ingestion queues in #12883. A message under this ceiling can still cause those failures.

Hit every surface: server-side only. ACP providers already cap messages at 16 MiB through ndJsonRpc(); no client, contract or UI change.

Verification

Host: Linux x64; Node v24.21.0 in the vp test workers. The two forced-GC probes, the pipe-read probe and the count-cost probe ran on Node v24.18.1; the first forced-GC probe also ran on v24.21.0.

Focused regression coverage in protocol.test.ts uses in-memory stdio and an injected small limit. Cases cover exact-limit LF and CRLF framing, split CRLF, one-byte overflow, fragmented overflow before a newline and final messages at EOF. Unicode cases split three- and four-byte characters across input chunks and distinguish UTF-8 bytes from UTF-16 length. Invalid UTF-8 counts as its three-byte U+FFFD replacement in counts an invalid UTF-8 byte as the three bytes of its U+FFFD replacement.

Tests check the overflow behaviour above, including the cause's byte count and limit. The existing fragmented 4 MiB notification remains accepted under the default ceiling.

New block-packing and fragment-copy tests:

  • routes a message sent one byte per chunk at the byte limit with LF after several blocks
  • routes a message sent one byte per chunk at the byte limit with CRLF whose \r completes a block
  • keeps one-byte chunks in order around a chunk longer than a block
  • rejects an over-limit message sent one byte per chunk before its newline arrives
  • keeps multi-byte characters intact across remainder blocks with 1-byte input chunks
  • keeps multi-byte characters intact across remainder blocks with 7-byte input chunks
  • routes a message with a short first fragment after complete lines in a large chunk
  • routes a message with a long first fragment after complete lines in a large chunk

These guard content, order and the byte check across block packing and the fragment copy. Seven of these eight also pass on main; the one-byte-per-chunk over-limit test times out there, as shown below. The probes below show the memory properties.

In a forced-GC probe with a 1 MiB injected limit and one-byte reads, this branch retained 1,024 blocks with an empty tail at the limit, freed 1.01 to 1.02 MiB of heap when overflow cleared the buffer, and rejected byte 1,048,577 with the typed transport error. In a second forced-GC probe, one in-memory stdio read of 16 to 64 MiB of completed lines followed by a 64-byte or 1,100-byte unfinished prefix kept the whole read alive without the copy, raising external memory by 16,777,352 to 67,109,096 bytes while 2,112 to 3,148 bytes were buffered; with the copy, external memory grew by 40 bytes in every case, the same as with no completed lines in front. These large reads come from in-memory stdio, not a pipe.

vp test run packages/effect-codex-app-server/src/protocol.test.ts
vp test run packages/effect-codex-app-server/src/client.test.ts

On main, 14 of 46 tests fail: twelve by assertion and two by timeout. rejects an over-limit message from small fragments before its newline arrives and rejects an over-limit message sent one byte per chunk before its newline arrives keep input open to prove rejection before LF or EOF. Each fails on main by the 5-second runner timeout.

Regression output against the unfixed code, excerpt:

FAIL  rejects a message one byte over the limit with LF framing
AssertionError: expected CodexAppServerInputStreamEndedError: Code… { _tag: '…' } to be an instance of CodexAppServerTransportError
FAIL  counts an invalid UTF-8 byte as the three bytes of its U+FFFD replacement
AssertionError: expected CodexAppServerInputStreamEndedError: Code… { _tag: '…' } to be an instance of CodexAppServerTransportError
FAIL  rejects an over-limit message from small fragments before its newline arrives
Error: Test timed out in 5000ms.
FAIL  rejects an over-limit message sent one byte per chunk before its newline arrives
Error: Test timed out in 5000ms.

Test Files  1 failed (1)
Tests  14 failed | 32 passed (46)

Focused test output with the fix:

Test Files  1 passed (1)
Tests  46 passed (46)
Duration  5.80s (import 50%, transform 42%, setup 5%, tests 3%)

Regression tests before and after Regression tests fail 14 times on main, including two 5-second timeouts, and pass 46 times on this branch.

Focused lint, format, package typecheck and knip commands and results:

CommandObserved result
vp test run packages/effect-codex-app-server/src/protocol.test.ts46 passed, exit 0.
vp test run packages/effect-codex-app-server/src/client.test.ts2 passed, exit 0.
vp lint packages/effect-codex-app-server/src/protocol.ts packages/effect-codex-app-server/src/protocol.test.tsExit 0, no diagnostics.
vp fmt --check packages/effect-codex-app-server/src/protocol.ts packages/effect-codex-app-server/src/protocol.test.tsExit 0, both files correctly formatted.
cd packages/effect-codex-app-server && vp run typechecktsc --noEmit passed, exit 0.
vp run knip:checkExit 0; both dependency/file and export checks passed.
Tail-packing mutations before a long fragment, at a newline and at EOF1, 10 and 5 tests failed respectively; each mutation was restored.
Fragment-copy mutation that drops one code unit4 tests failed, including both fragment-copy tests; restored.
Error-cause mutation that reports one extra byte1 test failed; restored.

Oversized message, main against this branch

A temporary test calls the real protocol with makeInMemoryStdio and the default ceiling. It feeds a 129 MiB ASCII JSON notification, exactly 135,266,304 UTF-8 bytes excluding its newline, in 65,536-byte chunks with the newline offered separately, then offers a small reply for an already pending thread/read request.

The same command ran against main's protocol and this branch:

vp test run packages/effect-codex-app-server/src/zz-evidence-oversize.test.ts --silent=false --reporter=verbose

Main:

Node version: v24.21.0
Node heap size limit bytes: 4496293888
NODE_OPTIONS: unset
Protocol options: default byte ceiling; logIncoming=true
Notification UTF-8 bytes, excluding newline: 135266304
Input chunk bytes: 65536; newline offered separately
Log event: incoming/raw; payload bytes: 135266304
Log event: incoming/decoded; payload bytes: 135266304
Probe: valid reply for the pending request offered after the oversized notification
Log event: incoming/raw; payload bytes: 29
Log event: incoming/decoded; payload bytes: 29
Notification reached onNotification: true; count: 1
Log event count: 4
Pending request outcome: success; result: {"ok":true}
Operation: none
Cause message: none
onTermination ran: false; count: 0
Peak memory method: process.memoryUsage() after each offered chunk and newline, after yielding to the reader
Peak sampled RSS bytes: 674459648; MiB: 643.21
Peak sampled heapUsed bytes: 435171264; MiB: 415.01
Elapsed milliseconds: 226.32

This branch:

Node version: v24.21.0
Node heap size limit bytes: 4496293888
NODE_OPTIONS: unset
Protocol options: default byte ceiling; logIncoming=true
Notification UTF-8 bytes, excluding newline: 135266304
Input chunk bytes: 65536; newline offered separately
Probe: valid reply for the pending request offered after the oversized notification
Notification reached onNotification: false; count: 0
Log event count: 0
Pending request outcome: failure; error class: CodexAppServerTransportError
Operation: read-input-stream
Cause message: Incoming message reached 134283264 bytes, over the 134217728-byte limit.
onTermination ran: true; count: 1
Peak memory method: process.memoryUsage() after each offered chunk and newline, after yielding to the reader
Peak sampled RSS bytes: 460570624; MiB: 439.23
Peak sampled heapUsed bytes: 166533168; MiB: 158.82
Elapsed milliseconds: 257.63

Oversized notification before and after The same 129 MiB notification is delivered and logged on main, then rejected with a typed transport error on this branch.

Both runs used Node v24.21.0 with the same heap limit, NODE_OPTIONS unset and the same 60-second timeout. Both probe tests passed without a timeout or out-of-memory failure. The outputs above show the before/after behaviour.

Peak memory was sampled with process.memoryUsage() after each offered chunk and newline, after yielding to the reader. The caller retained the entire 129 MiB input buffer in both runs, and the samples include test-runner overhead. These are per-chunk samples for this probe, not OS or process-lifetime maxima or an isolated protocol-memory benchmark.

Not checked

  • A live Codex session sending a message larger than 128 MiB.
  • A live Codex child process or app-server integration. The pipe-read probe uses a test child; the oversized-message probe uses in-memory stdio.
  • macOS or Windows.
  • JavaScript engines other than V8; the fragment copy and its retention probe were checked on Node.
  • Continuous OS memory monitoring, repeated-run benchmarks, or payloads beyond the 129 MiB probe.
  • Full repository test suite, builds, lint, and type checks.

Model and harness: Claude Opus 5.5 in Claude Code and GPT-6.1 Sol in Codex, run from T3 Code. 🤖 Generated with Claude Code

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:unvouched

    2. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — The production Codex app-server reader now enforces a new 128 MiB default and terminates sessions when messages exceed it, affecting parsing, logging, and pending requests on an existing path. Focused regression coverage is extensive, but the default and session-lifecycle changes warrant human review.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    3. juliusmarminge added labelsmacroscope-review

    4. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      No actionable comments were generated in the recent review. 🎉

      ℹ️ Recent review info
      ⚙️ Run configuration
      • Configuration used: Path: .coderabbit.config.ts
      • Review profile: CHILL
      • Plan: Advanced
      • Run ID: 161edb2e-a957-4662-8487-7abeb3691eb9

      📥 Commits

      Reviewing files that changed from the base of the PR and between 0c53c13dd081f51c35ab84bfee3cff162c60d167 and b35ffeff8eff88bc9a541e17c90fa89b59b3c683.


      📒 Files selected for processing (2)
      • packages/effect-codex-app-server/src/protocol.test.ts
      • packages/effect-codex-app-server/src/protocol.ts

      🚧 Files skipped from review as they are similar to previous changes (1)
      • packages/effect-codex-app-server/src/protocol.ts

      Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.



      📝 Walkthrough
      📝 Walkthrough

      Walkthrough

      The protocol now exposes a configurable per-message byte limit, defaulting to 128 MiB. The input reader counts UTF-8 bytes while buffering JSONL input and rejects oversized messages. It dispatches earlier complete lines before reporting an oversized message. Tests cover framing, fragmentation, end-of-input, and error and log handling.

      Changes

      Incoming message byte limit

      Layer / File(s)Summary
      Limit configuration and fragment accounting
      packages/effect-codex-app-server/src/protocol.ts
      The protocol adds the optional maxIncomingMessageBytes setting, a 128 MiB default, UTF-8 byte counting, and helpers for retaining input fragments.
      Input enforcement and message handling
      packages/effect-codex-app-server/src/protocol.ts, packages/effect-codex-app-server/src/protocol.test.ts
      The reader checks message sizes as it processes chunks and at end-of-input. Tests cover LF and CRLF framing, fragmented and multibyte input, prior complete-line dispatch, and oversized-message errors that omit message contents.

      Priority: ➖ Normal

      Estimated code review effort: 3 (Moderate) | ~25 minutes

      Change: Bug fix · Severity of issue fixed: Medium


      Merge Risk: ⚪ Minimal · up to b35ff

      Oversized Codex app-server messages now end the session with a clear error before they are parsed. Messages under the limit behave as before, and I found no merge-blocking risk.

      Security Architecture Review

      Security architecture risk: 🔵 Low · up to b35ff

      The change limits oversized input and terminates the affected session through existing cleanup behavior. No introduced security issue was established, but deployed memory budgets and custom limit settings were not fully verified.

      Retained concerns No architecture-level concerns identified.

      Security review details

      Security Blast Radius

      • inferred — A peer able to supply oversized data on the existing stdio connection can terminate that protocol session and fail its pending requests. The change replaces previously unbounded message accumulation with explicit session failure; the inspected path does not introduce additional identity or privilege authority. Total process-memory exposure across sessions is not established by this per-message limit.

      Trust Boundaries and Controls

      • observed — The byte ceiling is chosen from caller-supplied protocol construction options, not incoming message contents. It is not validated: NaN or positive Infinity defeats numeric overflow comparisons for direct callers. The inspected higher-level client does not forward this override, and the base had no byte ceiling, so this is not retained as a PR-introduced attacker-controlled bypass.

      Resilience and Maintainability Implications

      • observed — Short fragments are packed into blocks at a 1,024-code-unit threshold rather than retained as one array entry per tiny read. Post-newline remainders are explicitly detached from the preceding chunk contents. These mechanisms reduce fragmentation-related retention alongside the message ceiling, but do not constitute a total heap budget.

      Hardening Proposals

      • proposed — If direct protocol configuration is supported beyond tests, validate the override against a documented finite range at construction time to prevent accidental disabling of the ceiling.

      Pre-merge checks | Passed 4
      ✅ Passed checks (4 passed)
      Check nameStatusExplanation
      Linked Issues checkPassedThe change meets the coding requirements in [#12884]. protocol.ts adds a 128 MiB default ceiling and counts decoded fragment UTF-8 bytes before retaining, joining, logging, or parsing the message. T…
      Out of Scope Changes checkPassedThe changes stay within [#12884]. Production changes are limited to the server-side Codex app-server reader and its test override. The added helpers and tests support byte counting, framing, overflow …
      Title checkPassedThe title is concise, specific, and accurately describes the main change: oversized app-server messages now terminate the session before parsing.
      Description checkPassedThe description fully addresses the required Problem, Change, Scope and approval, and Verification sections. It includes issue links, implementation details, focused test results, observed limitations…

      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create a new PR

      • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Comment `@coderabbitai help` to get the list of available commands.
    5. Note

      Written by gpt-6.1-sol on behalf of Maria

      Thanks for investigating oversized Codex messages. Right now we are only taking focused bug fixes from outside contributors, and this 577-line change exceeds what we can take over from an unvouched contributor under our limited review capacity. For reconsideration, submit a substantially smaller fix centered on the incoming-message limit. Please preserve the heap-exhaustion reproduction in an issue so the problem is not lost.

    6. maria-rcks closed this

Sign in to join this conversation.