Repository navigation
perf(terminal): drop the JSON structural pre-scan from the history read path - #10499
Conversation
…ad path readTerminalHistoryJson/Async walked every character of checkpoint.json in interpreted JS before handing the same string to native JSON.parse. On a 26.8MB checkpoint that scan measured 63-330ms — 2.7-12x the JSON.parse it guards, and 57% of the whole read path — all of it synchronous main-thread work. readTerminalHistoryJsonAsync exists so cold-restore reads do not block the main thread; running the scan inline right after the async read defeated its own stated purpose. The scan also had a correctness cost: TERMINAL_HISTORY_JSON_MAX_STRUCTURAL_TOKENS was 1_000_000, and oscLinks is unbounded at ~10 structural tokens per link, so roughly 100k OSC-8 hyperlinks tripped the assert, history-reader swallowed the throw to a null checkpoint, and the terminal restored blank — the same user-visible loss #10479 just fixed for the byte cap. checkpoint.json and meta.json are our own SerializeAddon output, not untrusted input: the byte cap still bounds the read, and a corrupt file fails JSON.parse into the same catch. The shared helper stays for the call sites that do handle untrusted JSON.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughTerminal history JSON readers no longer pre-validate structural token counts or nesting depth before parsing. The synchronous and asynchronous readers now directly parse loaded text with 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/daemon/terminal-history-file-reader.ts (1)
14-19: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCondense the explanatory comments.
Keep the durable rationale, but reduce each to one focused “Why” comment; benchmark and failure-history detail belongs in the PR description.
src/main/daemon/terminal-history-file-reader.ts#L14-L19: replace the six-line implementation narrative with one concise reason for bypassing the pre-scan.src/main/daemon/history-reader-memory.test.ts#L120-L122: summarize the regression being covered in one line.src/main/daemon/history-reader-memory.test.ts#L138-L139: summarize why direct-reader coverage is needed in one line.As per coding guidelines, comments must be concise, limited to non-obvious information, and preferably one line.
Source: Coding guidelines
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f3cc8691-0e5e-4047-820e-b0950ebdc20e
📒 Files selected for processing (2)
src/main/daemon/history-reader-memory.test.tssrc/main/daemon/terminal-history-file-reader.ts
…h cap The retired pre-scan enforced two limits; the new tests only covered the structural-token half. Dropping the 128-level nesting cap is safe solely because V8 parses JSON iteratively — depth costs heap, not stack — so a deeply nested checkpoint parses instead of overflowing. Verified: 10M-deep arrays and objects parse without throwing on V8 14.6. That property is an engine guarantee this code now silently depends on, and a recursive parser would abort the daemon outright rather than throw into the callers' catch. The test fails on main with "JSON nesting exceeds 128 levels" and costs 4ms.
…omment Keeps the durable rationale for skipping the pre-scan (self-authored input, byte cap still bounds the read, corrupt files land in the callers' existing catch) and moves the "~57% of the read path" measurement to the PR body, where it cannot go stale against a later change to this path. Addresses the CodeRabbit comment-length nitpick against the repo's one-line-if-possible comment guideline.
|
@coderabbitai Partially actioned in Actioned — Declined — the two test comments (
The guideline says concise and non-obvious, preferably one line; these are 2-3 lines each and are carrying non-obvious rationale, which is the case the guideline exists to protect. Multi-line For the record, the review also added a third test in |
|
Tip For best results, initiate chat on the files or code changes.
I agree the two test comments protect non-obvious coverage intent—especially the direct-reader assertion given 🐇💭 ✏️ Learnings added
|
…ad path (stablyai#10499) * perf(terminal): drop the JSON structural pre-scan from the history read path readTerminalHistoryJson/Async walked every character of checkpoint.json in interpreted JS before handing the same string to native JSON.parse. On a 26.8MB checkpoint that scan measured 63-330ms — 2.7-12x the JSON.parse it guards, and 57% of the whole read path — all of it synchronous main-thread work. readTerminalHistoryJsonAsync exists so cold-restore reads do not block the main thread; running the scan inline right after the async read defeated its own stated purpose. The scan also had a correctness cost: TERMINAL_HISTORY_JSON_MAX_STRUCTURAL_TOKENS was 1_000_000, and oscLinks is unbounded at ~10 structural tokens per link, so roughly 100k OSC-8 hyperlinks tripped the assert, history-reader swallowed the throw to a null checkpoint, and the terminal restored blank — the same user-visible loss stablyai#10479 just fixed for the byte cap. checkpoint.json and meta.json are our own SerializeAddon output, not untrusted input: the byte cap still bounds the read, and a corrupt file fails JSON.parse into the same catch. The shared helper stays for the call sites that do handle untrusted JSON. * test(terminal): pin iterative JSON.parse for the dropped nesting-depth cap The retired pre-scan enforced two limits; the new tests only covered the structural-token half. Dropping the 128-level nesting cap is safe solely because V8 parses JSON iteratively — depth costs heap, not stack — so a deeply nested checkpoint parses instead of overflowing. Verified: 10M-deep arrays and objects parse without throwing on V8 14.6. That property is an engine guarantee this code now silently depends on, and a recursive parser would abort the daemon outright rather than throw into the callers' catch. The test fails on main with "JSON nesting exceeds 128 levels" and costs 4ms. * docs(terminal): drop the rot-prone benchmark figure from the reader comment Keeps the durable rationale for skipping the pre-scan (self-authored input, byte cap still bounds the read, corrupt files land in the callers' existing catch) and moves the "~57% of the read path" measurement to the PR body, where it cannot go stale against a later change to this path. Addresses the CodeRabbit comment-length nitpick against the repo's one-line-if-possible comment guideline.
Summary
Cold restore of a large terminal checkpoint ran a per-character JSON scan in interpreted JS in front of native
JSON.parse, on the main thread. It cost ~57% of the checkpoint read path, and its structural-token cap was low enough that a link-dense terminal restored blank. This drops the scan from the two terminal-history readers only.The defect
readTerminalHistoryJson/readTerminalHistoryJsonAsynccalledassertJsonTextStructureWithinLimits(text, ...)beforeJSON.parse. That helper walks the JSON character by character in interpreted JS (content[index]+ string comparisons) — on a 20MB+ checkpoint that is ~25M iterations run in front of a native parser, entirely on the main thread.The sharpest version:
readTerminalHistoryJsonAsyncexists specifically so cold-restore reads do not block the main thread — its own comment said "cold-restore payload reads must not block the main thread". The file I/O was async, and then a synchronous CPU scan ran inline immediately after. The function defeated its own stated purpose.This is a regression against v1.4.155, where the read was
JSON.parse(readFileSync(path, 'utf-8')); neitherterminal-history-file-reader.tsnorjson-text-structure-limit.tsexisted. Both arrived with #10179 and survived revert #10255 (which could not reclaim them because #9990 had landed onhistory-reader.ts).Measured, not inferred
Node v26.5.0, 26.8MB checkpoint (20MB of realistic ANSI scrollback with powerline/box-drawing/emoji glyphs), timing the real
terminal-history-file-readerexports:Broken down across the whole read path (
readFileSync→toString('utf8')→ scan →JSON.parse): read 2ms, decode 19ms, scan 63ms, parse 27ms — the scan alone was 57% of the checkpoint read path and 2.4x theJSON.parseit was guarding.JSON.parsestays flat at ~30ms across runs; the scan is the part whose cost balloons under GC pressure (run3), which is exactly the condition a big cold restore creates.To state it plainly: in isolation I measured ~63-330ms for the scan, not the ~900ms of synchronous main-thread work seen in live restore testing. The scan is a real and dominant share of the read path, but I did not reproduce it as the sole cause of a ~950ms restore — the rest of that budget is elsewhere (decode, replay), and is not addressed here.
Also fixed: a silent-blank-restore path
TERMINAL_HISTORY_JSON_MAX_STRUCTURAL_TOKENS = 1_000_000was itself reachable by ordinary terminal content.daemon-checkpoint-file.tshas an unboundedoscLinksarray; each{"row":n,"startCol":n,"endCol":n,"uri":"..."}entry costs ~10 structural tokens, so roughly 100k OSC-8 hyperlinks crossed the limit. The assert threw,history-reader.ts:84-86swallowed it tocheckpoint = null, and the terminal restored blank — identical user-visible loss to the bug just fixed by #10479. Raising the byte cap did nothing for this.The fix, and why this option
Option 1 of three considered:
checkpoint.jsonandmeta.jsonare Orca's ownSerializeAddonoutput, not untrusted input. The byte cap (TERMINAL_HISTORY_CHECKPOINT_MAX_BYTES) already bounds the read, and a corrupt file failsJSON.parseinto the samecatchthe callers already have. The DoS threat model the scan defends against does not apply to a file we wrote ourselves. It also makes the oscLinks silent-drop disappear rather than re-tuning a limit that would need re-tuning again.charCodeAt+ numeric comparisons). I benchmarked this: 47-58ms vs 57-86ms — meaningfully faster, but still adds tens of ms of pure main-thread overhead to guard a file we authored, and does nothing about the oscLinks blank restore.Scoped deliberately. The shared
assertJsonTextStructureWithinLimitshelper is untouched and still guards the ~18 call sites that do handle untrusted input —agent-hook-listener.ts,browser-screencast-protocol.ts,relay-json-admission.ts,fetch-response-body.ts,text-search.ts, and others. Only the terminal-history readers change.Tests
Both new tests fail on
mainand pass here:restores a checkpoint carrying more OSC links than the retired structural-token cap— 150koscLinks. Before:expected undefined to be 'safe checkpoint'(the blank restore, reproduced end-to-end throughdetectColdRestore). After: full restore with all 150k links.parses link-dense checkpoints without a structural pre-scan budget— asserts the reader directly, becausedetectColdRestorehides any reader throw as a null checkpoint and would stay green if the pre-scan came back.The replaced test (
rejects structurally amplified checkpoints before parsing) asserted the behavior this PR removes.```
npx vitest run --config config/vitest.config.ts src/main/daemon/
Test Files 68 passed | 2 skipped (70)
Tests 1035 passed | 5 skipped (1040)
```
pnpm typecheck:node,oxlint,oxfmt --check, max-lines ratchet and reliability gates all clean.Follow-up left out of scope
The shared helper is still
content[index]-based for every other consumer; thecharCodeAtrewrite is a free several-fold win there and belongs in its own PR.Screenshots
No visual change. The user-visible effect is behavioral: a checkpoint carrying ~100k+ OSC-8 hyperlinks now restores its scrollback instead of coming back blank.
Testing
pnpm lint(oxlint,oxfmt --check) — cleanpnpm typecheck(typecheck:node) — cleanpnpm test—src/main/daemon/: 68 files passed, 1036 passed | 5 skippedpnpm buildAll three added tests were verified to fail on
mainby reverting onlyterminal-history-file-reader.tsand keeping the new test file:mainexpected undefined to be 'safe checkpoint'(the blank restore)JsonTextStructureCapacityError: JSON structure exceeds 1000000 tokensJsonTextStructureCapacityError: JSON nesting exceeds 128 levelsCombined cost of the three: ~93ms.
AI Review Report
Reviewed with Claude (Opus) subagents. Main risks checked:
The retired pre-scan enforced two caps, not one. The PR body originally
justified only the structural-token half; the 128-level nesting-depth cap
was dropped with no coverage. That is the one way this change could have been
wrong: if
JSON.parserecursed, a deeply nested checkpoint would abort theprocess outright rather than throw into the callers'
catch. Verifiedempirically on V8 14.6 — arrays and objects nested 10,000,000 deep parse in
~1.2s without throwing and without crashing; V8's JSON parser is iterative,
so depth costs heap, not stack. Commit
28f6d68085adds a regression testpinning that property, since the read path now silently depends on it.
Caller safety. Both
readTerminalHistoryJsoncall sites(
history-reader.ts:79-86and:293-297) wrap the read intry/catchanddegrade to "no history", so any parse failure is no worse than the pre-scan
throw it replaces. No caller of either reader is left unguarded, and the async
variant's rejection cannot escape as an unhandled rejection.
Trusted-input claim.
HistoryReader'sbasePathis alwaysgetHistoryDir()— a fixed app-data directory.checkpoint.jsonis writtenonly by
history-manager.tsand read only byhistory-reader.ts; nothingtransfers one across a trust boundary. Under SSH the daemon runs on the remote
host and reads its own local history dir, so no checkpoint crosses the relay.
Blast radius.
src/shared/json-text-structure-limit.tsis byte-for-byteunchanged (empty diff) and its own tests still pass; the ~18 untrusted-input
call sites are unaffected. The two deleted constants have zero remaining
references repo-wide.
Cross-platform. No platform-dependent behavior touched — no shortcuts,
labels, shell invocation, or path construction changed. Path handling still
goes through
join. Behavior is identical on macOS, Linux, and Windows, andidentical for local, WSL, SSH, and folder-workspace sessions.
Security Audit
This PR removes an input-validation guard, so the audit centers there.
checkpoint.json/meta.jsonare self-authored, andreadNodeFileSyncWithinLimitstill enforces the byte cap(
TERMINAL_HISTORY_CHECKPOINT_MAX_BYTES,TERMINAL_HISTORY_META_MAX_BYTES),so the read stays bounded. The DoS threat model the scan defended against
needs an untrusted producer, which this path does not have. For reference,
v1.4.155 ran
JSON.parse(readFileSync(path, 'utf-8'))here with no cap atall — this PR is strictly more bounded than the last shipped release.
JSON.parseoutput is bounded by a small constant factor of thebyte cap, and the writer never emits structurally amplified payloads.
secrets, dependencies, IPC. No new dependency, no new IPC surface.
Notes
charCodeAtrewrite of the shared helper (a free several-fold win forits other ~18 consumers) is deliberately out of scope and belongs in its
own PR.
was 57% of the checkpoint read path. It was not reproduced as the sole
cause of the ~950ms live restore; the remainder (decode, replay) is elsewhere
and is not addressed here.