Skip to content

perf(terminal): drop the JSON structural pre-scan from the history read path - #10499

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/fix-history-json-scan-cost
Jul 25, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/fix-history-json-scan-cost

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

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 / readTerminalHistoryJsonAsync called assertJsonTextStructureWithinLimits(text, ...) before JSON.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: readTerminalHistoryJsonAsync exists 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')); neither terminal-history-file-reader.ts nor json-text-structure-limit.ts existed. Both arrived with #10179 and survived revert #10255 (which could not reclaim them because #9990 had landed on history-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-reader exports:

before (scan + parse) after (parse only) saved
run0 135.1ms 49.5ms 85.6ms (2.7x)
run1 94.7ms 34.9ms 59.8ms (2.7x)
run2 174.4ms 30.3ms 144.1ms (5.7x)
run3 363.4ms 29.9ms 333.4ms (12.1x)

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 the JSON.parse it was guarding. JSON.parse stays 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_000 was itself reachable by ordinary terminal content. daemon-checkpoint-file.ts has an unbounded oscLinks array; 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-86 swallowed it to checkpoint = 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:

  1. Drop the scan for this call site (chosen). checkpoint.json and meta.json are Orca's own SerializeAddon output, not untrusted input. The byte cap (TERMINAL_HISTORY_CHECKPOINT_MAX_BYTES) already bounds the read, and a corrupt file fails JSON.parse into the same catch the 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.
  2. Make the scan cheap (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.
  3. Move it off the main thread. Real work (worker thread / streaming) for zero security benefit on a self-authored file.

Scoped deliberately. The shared assertJsonTextStructureWithinLimits helper 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 main and pass here:

  • restores a checkpoint carrying more OSC links than the retired structural-token cap — 150k oscLinks. Before: expected undefined to be 'safe checkpoint' (the blank restore, reproduced end-to-end through detectColdRestore). After: full restore with all 150k links.
  • parses link-dense checkpoints without a structural pre-scan budget — asserts the reader directly, because detectColdRestore hides 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; the charCodeAt rewrite 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) — clean
  • pnpm typecheck (typecheck:node) — clean
  • pnpm test — src/main/daemon/: 68 files passed, 1036 passed | 5 skipped
  • pnpm build
  • Added or updated high-quality tests that would catch regressions

All three added tests were verified to fail on main by reverting only
terminal-history-file-reader.ts and keeping the new test file:

test failure on main
restores a checkpoint carrying more OSC links than the retired structural-token cap expected undefined to be 'safe checkpoint' (the blank restore)
parses link-dense checkpoints without a structural pre-scan budget JsonTextStructureCapacityError: JSON structure exceeds 1000000 tokens
parses deeply nested checkpoints without the retired nesting-depth cap JsonTextStructureCapacityError: JSON nesting exceeds 128 levels

Combined 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.parse recursed, a deeply nested checkpoint would abort the
process outright rather than throw into the callers' catch. Verified
empirically 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 28f6d68085 adds a regression test
pinning that property, since the read path now silently depends on it.

Caller safety. Both readTerminalHistoryJson call sites
(history-reader.ts:79-86 and :293-297) wrap the read in try/catch and
degrade 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's basePath is always
getHistoryDir() — a fixed app-data directory. checkpoint.json is written
only by history-manager.ts and read only by history-reader.ts; nothing
transfers 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.ts is byte-for-byte
unchanged (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, and
identical for local, WSL, SSH, and folder-workspace sessions.

Security Audit

This PR removes an input-validation guard, so the audit centers there.

  • Input handling: checkpoint.json / meta.json are self-authored, and
    readNodeFileSyncWithinLimit still 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 at
    all
    — this PR is strictly more bounded than the last shipped release.
  • Memory: JSON.parse output is bounded by a small constant factor of the
    byte cap, and the writer never emits structurally amplified payloads.
  • Stack safety: confirmed above — no uncatchable overflow path.
  • Not applicable / unchanged: command execution, path handling, auth,
    secrets, dependencies, IPC. No new dependency, no new IPC surface.
  • Follow-up: none blocking.

Notes

  • The charCodeAt rewrite of the shared helper (a free several-fold win for
    its other ~18 consumers) is deliberately out of scope and belongs in its
    own PR.
  • Honest scoping on the perf claim: the scan measured 63-330ms in isolation and
    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.

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

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: e907ea2d-f376-4c32-9d61-cae2dd43c51e

📥 Commits

Reviewing files that changed from the base of the PR and between 28f6d68 and 526da00.

📒 Files selected for processing (1)
  • src/main/daemon/terminal-history-file-reader.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/daemon/terminal-history-file-reader.ts

📝 Walkthrough

Walkthrough

Terminal 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 JSON.parse. The exported structural-limit constants and validation import were removed. Tests now cover restoration and parsing of checkpoints containing many OSC-8 hyperlink entries and deeply nested JSON.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: removing the JSON pre-scan from terminal history reads.
Description check ✅ Passed The description follows the template with Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes, including cross-platform review and test status.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/main/daemon/terminal-history-file-reader.ts (1)

14-19: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Condense 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

📥 Commits

Reviewing files that changed from the base of the PR and between 6c03ecf and 66c1ee6.

📒 Files selected for processing (2)
  • src/main/daemon/history-reader-memory.test.ts
  • src/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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

@coderabbitai Partially actioned in 526da00c27.

Actioned — terminal-history-file-reader.ts:14-19. Trimmed 6 lines to 4. The specific problem was not length but rot: "cost ~57% of this read path" is a benchmark pinned to a particular checkpoint on particular hardware, and it silently becomes wrong the moment anything else in this path changes. That number now lives in the PR description. What stayed is the durable rationale a future reader actually needs at the call site — self-authored input, byte cap still bounds the read, corrupt files land in the callers' existing catch.

Declined — the two test comments (history-reader-memory.test.ts:120-122, :138-139). Both encode non-obvious information that is not recoverable from the code:

  • 120-122 records why the number 150,000 is there. Without it the constant looks arbitrary; with it, it is "just past the retired 1M-structural-token cap, which ordinary OSC-8 link density reached." Someone tuning that constant down needs that sentence.
  • 138-139 explains why the file asserts the reader directly when the test above it already covers the same path end-to-end. The answer — detectColdRestore swallows any reader throw into a null checkpoint, so a reinstated pre-scan would leave the end-to-end test green — is precisely the kind of thing that gets "simplified away" as redundant coverage without the note.

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 Why: comments are established style in this directory (terminal-history-file-limits.ts:3-7, history-reader.ts:66-69, :89-92). Compressing either to one line would drop the causal chain, not the verbosity.

For the record, the review also added a third test in 28f6d68085. The retired pre-scan enforced two caps and the original tests covered only the structural-token half; the 128-level nesting-depth cap was dropped with no coverage. That is safe only because V8 parses JSON iteratively — verified empirically, 10M-deep arrays and objects parse without throwing or crashing — and the read path now silently depends on that engine property, so it is pinned.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@brennanb2025 Thanks for the detailed context. The call-site rationale is now appropriately durable without retaining a benchmark-specific performance claim.

I agree the two test comments protect non-obvious coverage intent—especially the direct-reader assertion given detectColdRestore’s error swallowing—and the added deep-nesting test closes the previously untested retired limit. I’m withdrawing the remaining comment-reduction concerns.

🐇💭


✏️ Learnings added
Learnt from: brennanb2025
URL: https://github.com/stablyai/orca/pull/10499

Timestamp: 2026-07-25T07:26:59.958Z
Learning: In `src/main/daemon/history-reader-memory.test.ts`, the OSC-8 checkpoint test’s 150,000-link value intentionally exceeds the retired 1,000,000 structural-token cap at ordinary OSC-8 link density. The direct `readTerminalHistoryJson` test must remain separate from the `HistoryReader.detectColdRestore` integration test because `detectColdRestore` converts reader failures to a null checkpoint, which could otherwise hide restoration of the retired JSON structural pre-scan.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@brennanb2025
brennanb2025 merged commit d9aa919 into main Jul 25, 2026
8 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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