Skip to content

fix(daemon): bound NDJSON and binary-frame ingress - #10874

Draft
nwparker wants to merge 6 commits into
oom-slice-2-clifrom
oom-slice-3-daemon-wire
Draft

nwparker wants to merge 6 commits into
oom-slice-2-clifrom
oom-slice-3-daemon-wire

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Slice 3 of the re-landed OOM work. Stacked on #10828 — review only the two commits above it.

Recreated from #10832, which was closed accidentally. Same branch, same commits, no content change.

ELI5

The daemon talks to the app over a socket. Two things it reads can be made to
eat far more memory than they look like they should.

  1. Binary frames start with a header saying "here comes N bytes." The
    parser trusted that number and waited. Say 4 GiB and the parser keeps
    everything you send while waiting for a frame that never completes.
    Now it checks N against the existing size cap and rejects immediately —
    nothing to wait for.

  2. JSON lines were capped at 16 MiB on the wire, but a small line can
    expand into a huge object once parsed. [[[[[...]]]]] is mostly brackets.
    4 MiB of that becomes ~109 MiB of memory. Now we look at the line's shape
    before parsing it and reject the amplified ones.

Why this matters

The wire cap was measuring the wrong thing. It bounded what a message costs
to receive, not what it costs to hold. At the shipped 16 MiB line cap, a
single admitted line could turn into ~437 MiB of heap — repeatedly.

Proof the OOM is fixed

Measured against origin/main's real parsers, not reimplementations:

case main this PR
frame declaring 4 GiB, 256 MiB trickled 256 MiB retained, still growing rejected at the header, 0 retained
4 MiB structurally amplified line 109.2 MiB retained (27.3x) rejected before parse, ~0 retained

Proof of no regressions

Behavior parity. The second commit rewrites the structure scanner for
speed. It is differential-tested against the char-by-char implementation it
replaces, over 505,720 cases with zero divergence — 240,000 randomized
over a structural/escape/unicode alphabet under four limit sets, plus
exhaustive enumeration of every string up to length 5 over
{ } [ ] , : " \\ a. Verdicts are compared including the thrown resource
and limit, not just throw/no-throw. Hand-picked adversarial cases (odd/even
backslash runs, unterminated strings, astral-plane characters, limit
boundaries at ±1) are now permanent tests.

The coverage is not vacuous: dropping the closing-quote refresh reintroduces
mismatches in that harness, and the failures are spurious rejections —
inputs the reference accepts that the mutant throws on — i.e. exactly the
"OOM fix that drops valid data" regression class. Reverting to the naive
rescan fails the linear-time test at 2349ms against a 500ms budget.

Throughput. The guard runs on the daemon's hot receive path, so cost
matters. First measurement showed a real 2.95x slowdown — the scan cost 4x
more than JSON.parse itself. That's the "OOM fix that degrades UX" failure
mode, so it got fixed rather than accepted:

  • 20k scans of a 2 KiB message: 286ms → 5.3ms
  • realistic daemon PTY traffic (20k messages, 40.6 MiB, 646 socket reads):
    main 35.4ms vs 51.0ms here — 795 MiB/s, far above real load

Skipping a string body in one indexOf is only linear if the closing-quote
index is reused across escapes. Deriving it inside the escape loop rescans the
tail once per escape, which is quadratic on a payload carrying escaped text
(a serialized file, or JSON inside JSON). Both cursors are therefore
monotonic, and the escape-dense shape is covered by a timing test:

4 MiB body char-by-char (before) naive skip this PR
escape-dense \n 14.0ms 2330.1ms 0.9ms
quote-dense \" 12.2ms 1.5ms 2.0ms
unescaped 11.2ms 0.1ms 0.1ms

Tests. 20,118 passing across shared + main + cli + relay.
Two failures in src/relay/agent-exec-handler.test.ts are pre-existing:
clean origin/main reproduces them identically with none of this branch's
code. terminal-history-incremental-restore also flakes under load
independently of this branch: interleaved A/B runs (alternating commits to
control for machine-load drift) give 2/14 failures on this PR's base vs
0/14 on its tip
, and the two timing-sensitive cases fail no more often with
this commit than without it. Typecheck and lint clean; the 6 tsconfig.web
errors reproduce identically on clean origin/main.

User-facing changes

None. No behavior changes for any input a real peer sends; the new rejections
apply only to input that would previously have exhausted memory.

Made with Orca 🐋

nwparker and others added 4 commits July 26, 2026 19:37
The daemon's two wire parsers each accept peer-controlled input without a
ceiling on what a single message can turn into.

Binary frames: the parser reads a 32-bit declared payload length and waits
for that many bytes. A peer that declares 4 GiB makes the parser buffer every
byte it sends, unbounded, with no frame ever completing. FRAME_MAX_PAYLOAD
existed but was only enforced on the send path. Reject from the header
instead: a declared length over the cap is unsatisfiable, so there is nothing
to wait for.

NDJSON: a line under the 16 MiB cap can still expand into an object graph
far larger than its wire size. 4 MiB of nested arrays parses into ~109 MiB of
heap — 27x amplification, and the cap admits that per line, repeatedly.
Scan the line's structure before JSON.parse and reject amplified input on
token count and nesting depth, so the ceiling covers what the message costs
in memory rather than only what it costs on the wire.

The parser also accumulates into a byte buffer rather than a JS string, which
lets it report the admitted byte count without re-serializing the parsed value.

Verified: 1,123 daemon tests pass; 4,782 across shared + daemon + cli, three
consecutive runs. Realistic daemon PTY traffic (20k messages, 40 MiB, 64 KiB
socket reads) parses at 795 MiB/s, well above real load.
The structure scan added to the daemon's receive path cost 4x more than the
JSON.parse it guards: it indexed the string per character, allocating a
one-character string for every byte, and walked string bodies one byte at a
time even though a string's contents carry no structure.

Read char codes instead, and skip each string body to its closing quote in
one indexOf. Two cursors keep that skip linear: a monotonic escape cursor so
backslash lookups never rescan, and a hoisted closing-quote index that is
re-derived only when the escape cursor passes it. Deriving the closing quote
inside the escape loop instead would rescan the tail once per escape, which
is quadratic on a payload carrying escaped text -- 2.3s on a 4 MB body.

Same input, same verdict: 505,720 differential cases against the previous
char-by-char implementation -- 240,000 randomized over a structural / escape /
unicode alphabet under four limit sets, plus every string up to length 5 over
{ } [ ] , : " \ a -- produce identical results, including the thrown
resource and limit. Dropping the closing-quote refresh reintroduces
mismatches, so the coverage is not vacuous.

20k scans of a 2 KiB message: 286ms -> 5.3ms. The guard now costs less than
the parse it protects, which takes the daemon's fragmented-feed overhead from
2.95x down to 1.44x. On a 4 MB escape-dense body: 14.0ms -> 0.9ms.

Co-authored-by: Orca <[email protected]>
…ndaries

Accumulating the line as UTF-8 bytes encodes each fed segment on its own. A
chunk boundary landing between a surrogate pair encoded each half separately,
so one astral character (emoji, math script, flags) became two replacement
characters. The previous string accumulator concatenated before encoding and
never had this. Hold a trailing high surrogate back until its low half arrives,
and drop it on reset.

Not reachable from today's callers: all seven feed a StringDecoder, which
withholds partial sequences and never emits a lone half. This closes the gap
before a caller that does not — a relay hop, a test double, a future non-socket
source — makes it reachable.

Adds a differential harness that runs this parser and the previous one over the
same randomized terminal-like traffic (ANSI, CJK, astral, quotes, backslashes,
embedded newlines) split at random boundaries, asserting identical output.
6,000 cases across three seeds. Verified in both directions: without the fix, 4
of 5 tests fail; with it, 1,128 daemon tests pass.
@OrcaWin
OrcaWin marked this pull request as draft October 27, 2026 09:44
@OrcaWin

OrcaWin commented Oct 27, 2026

Copy link
Copy Markdown
Collaborator

Moving this PR to draft because it has been untouched for more than 80 days (latest recorded PR activity or commit timestamp: 2026-07-28T03:18:05Z; checked on 2026-10-27). This keeps the review queue focused on active work while preserving the proposal. Please mark it ready for review when work resumes.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants