Skip to content

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

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

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

Conversation

@nwparker

@nwparker nwparker commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

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

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. A monotonic escape cursor keeps that skip O(n) overall rather
than rescanning for backslashes on every string.

Same input, same verdict: 20,000 randomized strings over a structural /
escape / unicode alphabet and a set of hand-picked adversarial cases (odd and
even backslash runs, unterminated strings, astral-plane characters, limit
boundaries at +/-1) produce identical results before and after.

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

Copy link
Copy Markdown
Contributor Author

Closed accidentally; GitHub refuses to reopen a PR whose branch was force-pushed after closing. Recreated as #10874 — same branch (oom-slice-3-daemon-wire), same four commits, no content change.

kunsanglee added a commit to kunsanglee/orca that referenced this pull request Jul 28, 2026
The guard hand-rolled path normalization that `cross-platform-path.ts`
already provides. Two of this branch's earlier commits fixed bugs the
reuse never had, and the copy missed NFC folding, so a non-ASCII
workspace path dropped every status from that workspace (stablyai#10832).

Delegate to `resolveRuntimePath` and `isPathInsideOrEqual`, keep the
notation bails as guard policy, and drop `readHookPayloadCwd` in favour
of `readBoundedString` — which also restores the 4096 cwd bound the
hand-rolled reader lost. Stop persisting `sourceCwd`, a transport-only
field the hydrate whitelist drops.
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.

1 participant