Skip to content

perf(terminal): size checkpoints with a bounded walk, emit with JSON.stringify - #11535

Closed
nwparker wants to merge 1 commit into
mainfrom
perf/measure-only-checkpoint-byte-budget
Closed

nwparker wants to merge 1 commit into
mainfrom
perf/measure-only-checkpoint-byte-budget

Conversation

@nwparker

@nwparker nwparker commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Description

Follow-up to #11422. That PR replaced jsonUtf8ByteLength + JSON.stringify with BoundedJsonWriter, a hand-rolled JSON emitter that counts UTF-8 bytes while writing. It achieved its goal of bounding the over-cap path, but it also made the path that runs on every checkpoint — the one where the payload fits — measurably slower.

This keeps the bounded walk and uses it only for sizing, then hands emission back to native JSON.stringify. An over-cap checkpoint is still never passed to JSON.stringify, so #11422's win is preserved and improved on.

ELI5

Orca has to check a terminal snapshot isn't too big before saving it. #11422 made Orca write out the save-file by hand while measuring, which turned out to be slow for colorful terminal output. Now Orca measures by hand — that part is fast and can stop early — and lets JavaScript's built-in, much faster writer produce the actual file.

Why the emitter was slow

BoundedJsonWriter batches unescaped runs into 16 KiB spans. Every character needing a JSON escape flushes the current span and appends the escape separately. Terminal ANSI is dense with ESC (0x1b, a control character escaped as �), so on real agent-TUI scrollback the span batching almost never engages and the writer degenerates into two small string appends per escape.

Measurements

Node 24 / macOS, median of 9 warmed runs with --expose-gc, driven by SGR-styled scrollback with multibyte content. PRE is main before #11422, MERGED is main today, FIXED is this PR.

Passing path — checkpoint fits under the cap. This runs on every checkpoint tick.

content size PRE MERGED FIXED vs MERGED
plain ASCII 1MB 2.6ms 4.4ms 3.6ms 0.83x
plain ASCII 5MB 12.9ms 17.0ms 12.6ms 0.74x
light ANSI 1MB 3.0ms 5.5ms 3.8ms 0.69x
light ANSI 5MB 13.5ms 25.4ms 14.4ms 0.57x
agent-TUI ANSI 1MB 4.3ms 10.0ms 5.4ms 0.54x
agent-TUI ANSI 5MB 20.2ms 86.2ms 20.8ms 0.24x

Reject path — payload over a 256 KiB cap.

PRE MERGED FIXED
agent-TUI ANSI, 10MB payload 16.4ms 1.7ms 0.3ms

At realistic 5MB checkpoints this is at parity with pre-#11422 (0.97x–1.06x) and 1.4x–4.2x faster than main today. The 1MB rows carry more run-to-run variance and their absolute deltas are ~1ms. The reject path is ~55x faster than pre-#11422 and ~6x faster than main.

To be clear about the claim: this is not a win over pre-#11422 on the passing path. It restores that path to parity while keeping — and extending — #11422's early-exit benefit on the reject path.

Proof of no regression

Differential fuzz of stringifyWithinLimit against JSON.stringify — 60,096 cases, zero divergence on all three axes: exact output equality, acceptance at exactly the byte cap, and rejection at cap−1.

  • 60,000 randomized nested values drawn from control characters, 1/2/3-byte UTF-8, paired surrogates, and lone high/low surrogates
  • targeted cases straddling the 8 KiB chunk boundary (16382–32769 code units) for ASCII, 2-byte, 3-byte, surrogate-pair, lone-surrogate and control-character fills
checked 60096
{}          # no CONTENT, EXACT_LIMIT_REJECTED, or OVER_LIMIT_ACCEPTED findings

Test suites:

pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/
Test Files  77 passed | 2 skipped (79)
     Tests  1168 passed | 5 skipped (1173)
pnpm run typecheck        # passed: node, tc.cli, tc.web
pnpm run check:code-quality:changed
  code quality: 0 new finding(s) across 2 changed file(s).
  type-aware code quality: 0 new finding(s) across 2 changed file(s).
  React Doctor: 0 new finding(s) across 2 changed file(s).

Two latent issues closed along the way

  1. Truncated-JSON hole. appendJsonValue returned false for two different reasons — budget exceeded, and value not serializable — but stringifyWithinLimit discarded the boolean and returned writer.result(). The non-exceed false yielded a non-null, half-written string that would have been renamed into place as checkpoint.json. Unreachable today, but now structurally impossible: any false returns null.

  2. Restored the estimator cross-check. perf(terminal): serialize checkpoints with one payload walk #11422 dropped throw new Error('Terminal checkpoint size estimator mismatch'). Since output is native JSON.stringify again, the guard is cheap to keep, and it is the only thing that can catch a sizing bug before the bytes reach disk.

Test changes

  • does not materialize and rescan a passing candidate asserted fullCandidateStringifies: 0, byteLengthCalls: 0 — it pinned the emitter design this PR reverses. Split into reads each snapshot field once on the passing path (the part that is still a real invariant) and a boundary test asserting acceptance at exactly the cap and rejection at cap−1.
  • Added sizes lone surrogates as JSON.stringify escapes them. perf(terminal): serialize checkpoints with one payload walk #11422's suite used only paired surrogates, so the 6-byte lone-surrogate cost had no coverage.
  • Factored the duplicated expected-object literal into expectedJson.

Background daemon work only; no user-visible UI change, so screenshots are not applicable.

Made with Orca 🐋

…stringify

#11422 replaced the size estimator with a hand-rolled JSON emitter. That bounded
the over-cap path but made the common path — where the checkpoint fits — 1.3x to
4.8x slower, because every ANSI escape breaks the writer's span batching into
per-escape string appends.

Keep the bounded walk, but only for sizing, and hand emission back to native
JSON.stringify. The over-cap payload is still never stringified.

Made with [Orca](https://github.com/stablyai/orca)

Co-authored-by: Orca <[email protected]>
Comment on lines +30 to +46
/** Mirrors the on-disk field order the serializer emits, so tests can compare against
* real JSON.stringify output rather than a hand-written string. */
function expectedJson(input: TerminalSnapshot): string {
return JSON.stringify({
snapshotAnsi: input.snapshotAnsi,
scrollbackAnsi: input.scrollbackAnsi,
oscLinks: input.oscLinks,
rehydrateSequences: input.rehydrateSequences,
cwd: metadata.cwd,
cols: input.cols,
rows: input.rows,
modes: input.modes,
scrollbackLines: input.scrollbackLines,
generation: metadata.generation,
checkpointedAt: metadata.checkpointedAt
})
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 The expectedJson helper silently omits pendingEscapeTailAnsi and lastTitle, which checkpointFile conditionally includes when those fields are truthy. A test that constructs a snapshot with either field and passes it to expectedJson will produce a JSON object that is missing those properties, so the resolves.toBe(expected) assertion would pass against the wrong string or fail with a confusing mismatch. The comment on the helper says it "mirrors the on-disk field order the serializer emits", so the gap is easy to miss.

Suggested change
/** Mirrors the on-disk field order the serializer emits, so tests can compare against
* real JSON.stringify output rather than a hand-written string. */
function expectedJson(input: TerminalSnapshot): string {
return JSON.stringify({
snapshotAnsi: input.snapshotAnsi,
scrollbackAnsi: input.scrollbackAnsi,
oscLinks: input.oscLinks,
rehydrateSequences: input.rehydrateSequences,
cwd: metadata.cwd,
cols: input.cols,
rows: input.rows,
modes: input.modes,
scrollbackLines: input.scrollbackLines,
generation: metadata.generation,
checkpointedAt: metadata.checkpointedAt
})
}
/** Mirrors the on-disk field order the serializer emits, so tests can compare against
* real JSON.stringify output rather than a hand-written string. */
function expectedJson(input: TerminalSnapshot): string {
return JSON.stringify({
snapshotAnsi: input.snapshotAnsi,
scrollbackAnsi: input.scrollbackAnsi,
oscLinks: input.oscLinks,
rehydrateSequences: input.rehydrateSequences,
...(input.pendingEscapeTailAnsi ? { pendingEscapeTailAnsi: input.pendingEscapeTailAnsi } : {}),
cwd: metadata.cwd,
cols: input.cols,
rows: input.rows,
modes: input.modes,
scrollbackLines: input.scrollbackLines,
...(input.lastTitle ? { lastTitle: input.lastTitle } : {}),
generation: metadata.generation,
checkpointedAt: metadata.checkpointedAt
})
}

spanBytes += 4
index += 1
function measureJsonString(budget: JsonByteBudget, value: string): boolean {
const remaining = budget.remaining()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 remaining snapshot vs. actual budget divergence

remaining captures budget.remaining() once at entry, before the string's own bytes are committed. The per-chunk early-exit bytes > remaining is an optimisation: it fires as soon as this string's local tally alone exceeds the available room, saving the cost of finishing a long string that can't fit. For strings shorter than MEASURE_CHUNK_CODE_UNITS (the common case) the check fires after the single chunk and is equivalent to the final budget.add(bytes). For multi-chunk strings it provides an upper bound of one extra chunk's worth of work on the reject path. This is intentional and correct — just worth a short comment so the next reader doesn't wonder why remaining is never updated inside the loop.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

@greptile-apps

greptile-apps Bot commented Jul 30, 2026

Copy link
Copy Markdown

Greptile Summary

Separates the sizing and emission concerns that BoundedJsonWriter combined: JsonByteBudget now does a bounded walk to count UTF-8 bytes (bailing early on over-cap payloads), and native JSON.stringify handles the actual output once the walk confirms the payload fits. A post-emit Buffer.byteLength cross-check is restored as a safety net against measurement drift.

  • Serializer rewrite (terminal-checkpoint-serializer.ts): BoundedJsonWriter is replaced by JsonByteBudget + measureJsonString/measureJsonValue; byte accounting covers all Unicode cases (lone surrogates, surrogate pairs, control chars, multi-byte BMP). stringifyWithinLimit returns null on any false from the walk, closing the old truncated-JSON hole.
  • Test suite (terminal-checkpoint-serializer.test.ts): adds lone-surrogate sizing coverage, a single-byte boundary test, and an expectedJson helper to reduce duplication; removes emitter-design assertions that no longer apply. The helper omits the two optional fields (pendingEscapeTailAnsi, lastTitle) that checkpointFile conditionally emits, making it incorrect for snapshots that carry those fields.

Confidence Score: 4/5

Safe to merge. The byte-counting walk is correct for all Unicode cases, the cross-check guard catches any measurement drift before bytes reach disk, and 60k fuzz cases confirm measurement matches JSON.stringify output exactly.

The core serializer logic is sound — surrogate handling, control-char escaping, and chunk-boundary edge cases are all correctly accounted for. The one gap is the expectedJson test helper, which omits the two optional checkpoint fields (pendingEscapeTailAnsi and lastTitle); a future test that exercises those fields and reuses the helper would silently compare against the wrong expected string.

Files Needing Attention: terminal-checkpoint-serializer.test.ts — the expectedJson helper needs the two conditional fields added before it can be safely reused for snapshots that carry them.

Important Files Changed

Filename Overview
src/main/daemon/terminal-checkpoint-serializer.ts Replaces BoundedJsonWriter (emitter + sizer) with JsonByteBudget (sizer only) — measurement walks the structure and exits early on over-budget, then native JSON.stringify handles emission with a post-emit cross-check guard. Logic is correct for all Unicode cases including lone surrogates and chunk-boundary surrogate pairs.
src/main/daemon/terminal-checkpoint-serializer.test.ts Test suite updated to match new architecture: removed emitter-design assertions, added lone-surrogate sizing test, added exact-boundary test; introduces expectedJson() helper but it omits the optional pendingEscapeTailAnsi and lastTitle fields, making it incorrect for snapshots that carry those fields.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[serializeTerminalCheckpointWithinLimit] --> B[checkpointFile - build TerminalCheckpointFile]
    B --> C[stringifyWithinLimit]
    C --> D[measureJsonValue via JsonByteBudget]
    D --> E{fits within maxBytes?}
    E -- No --> F[return null]
    E -- Yes --> G[JSON.stringify checkpoint]
    G --> H{Buffer.byteLength > maxBytes?}
    H -- Yes --> I[throw - estimator mismatch]
    H -- No --> J[return json string]
    F --> K[replaySnapshot - HeadlessEmulator]
    K --> L[getSnapshot scrollbackRows=0]
    L --> M[stringifyWithinLimit visibleOnly]
    M --> N{fits?}
    N -- No --> O[throw - metadata exceeds limit]
    N -- Yes --> P[binary search scrollback rows]
    P --> Q[return bestJson]
    J --> R[caller receives json]
    Q --> R
Loading

Reviews (1): Last reviewed commit: "perf(terminal): size checkpoints with a ..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Replaces bounded JSON construction with recursive UTF-8 byte estimation for strings, arrays, objects, omitted values, and circular references. Serialization now estimates against the byte limit, calls JSON.stringify, and verifies the emitted byte length. Tests centralize expected JSON generation and cover exact byte boundaries, escaped payload sizing, and single snapshot-field evaluation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the implementation and testing well but omits the required AI Review Report, Security Audit, Notes, and template headings. Add the required Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections, including cross-platform and security review details.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely summarizes the bounded sizing walk and native JSON.stringify emission changes.
✨ 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4e734b2f-5508-4905-8db9-e840790b70d8

📥 Commits

Reviewing files that changed from the base of the PR and between d0d8695 and fd45d88.

📒 Files selected for processing (2)
  • src/main/daemon/terminal-checkpoint-serializer.test.ts
  • src/main/daemon/terminal-checkpoint-serializer.ts

Comment on lines +30 to +46
/** Mirrors the on-disk field order the serializer emits, so tests can compare against
* real JSON.stringify output rather than a hand-written string. */
function expectedJson(input: TerminalSnapshot): string {
return JSON.stringify({
snapshotAnsi: input.snapshotAnsi,
scrollbackAnsi: input.scrollbackAnsi,
oscLinks: input.oscLinks,
rehydrateSequences: input.rehydrateSequences,
cwd: metadata.cwd,
cols: input.cols,
rows: input.rows,
modes: input.modes,
scrollbackLines: input.scrollbackLines,
generation: metadata.generation,
checkpointedAt: metadata.checkpointedAt
})
}

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

expectedJson doesn't mirror the two optional fields from checkpointFile.

checkpointFile() (terminal-checkpoint-serializer.ts) conditionally includes pendingEscapeTailAnsi and lastTitle when truthy, but this helper never includes them. Any future test that sets either field via snapshot({...}) will get a mismatched expected value, defeating the helper's stated purpose of mirroring "the on-disk field order the serializer emits."

🩹 Proposed fix to mirror the conditional fields
 function expectedJson(input: TerminalSnapshot): string {
   return JSON.stringify({
     snapshotAnsi: input.snapshotAnsi,
     scrollbackAnsi: input.scrollbackAnsi,
     oscLinks: input.oscLinks,
     rehydrateSequences: input.rehydrateSequences,
+    ...(input.pendingEscapeTailAnsi
+      ? { pendingEscapeTailAnsi: input.pendingEscapeTailAnsi }
+      : {}),
     cwd: metadata.cwd,
     cols: input.cols,
     rows: input.rows,
     modes: input.modes,
     scrollbackLines: input.scrollbackLines,
+    ...(input.lastTitle ? { lastTitle: input.lastTitle } : {}),
     generation: metadata.generation,
     checkpointedAt: metadata.checkpointedAt
   })
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
/** Mirrors the on-disk field order the serializer emits, so tests can compare against
* real JSON.stringify output rather than a hand-written string. */
function expectedJson(input: TerminalSnapshot): string {
return JSON.stringify({
snapshotAnsi: input.snapshotAnsi,
scrollbackAnsi: input.scrollbackAnsi,
oscLinks: input.oscLinks,
rehydrateSequences: input.rehydrateSequences,
cwd: metadata.cwd,
cols: input.cols,
rows: input.rows,
modes: input.modes,
scrollbackLines: input.scrollbackLines,
generation: metadata.generation,
checkpointedAt: metadata.checkpointedAt
})
}
/** Mirrors the on-disk field order the serializer emits, so tests can compare against
* real JSON.stringify output rather than a hand-written string. */
function expectedJson(input: TerminalSnapshot): string {
return JSON.stringify({
snapshotAnsi: input.snapshotAnsi,
scrollbackAnsi: input.scrollbackAnsi,
oscLinks: input.oscLinks,
rehydrateSequences: input.rehydrateSequences,
...(input.pendingEscapeTailAnsi
? { pendingEscapeTailAnsi: input.pendingEscapeTailAnsi }
: {}),
cwd: metadata.cwd,
cols: input.cols,
rows: input.rows,
modes: input.modes,
scrollbackLines: input.scrollbackLines,
...(input.lastTitle ? { lastTitle: input.lastTitle } : {}),
generation: metadata.generation,
checkpointedAt: metadata.checkpointedAt
})
}

@nwparker

Copy link
Copy Markdown
Contributor Author

Superseded by #26177.

@nwparker nwparker closed this Oct 14, 2026
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