Skip to content

perf(terminal): serialize checkpoints with one payload walk - #11422

Merged
nwparker merged 5 commits into
mainfrom
perf/single-pass-terminal-checkpoint-byte-length
Jul 30, 2026
Merged

nwparker merged 5 commits into
mainfrom
perf/single-pass-terminal-checkpoint-byte-length

Conversation

@nwparker

@nwparker nwparker commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Serialize terminal checkpoints with a bounded JSON writer that accounts for exact UTF-8 bytes while emitting output. Passing candidates avoid a full-object JSON.stringify followed by Buffer.byteLength; over-cap JSON emission stops once the byte limit is exceeded and discards its bounded partial output. If the initial checkpoint is rejected, the existing fallback deliberately replays the full checkpoint so it can produce and size a trimmed candidate.

Warmed 100 MiB measurements were 253.7–330.2 ms before and 247.4–253.6 ms after. This is not presented as a dramatic speedup; the change primarily bounds JSON emission and removes the extra full-string byte scan for fitting candidates.

ELI5

Orca now stops building checkpoint JSON when it reaches the size limit instead of building an oversized JSON string. If that first attempt is too large, Orca still reads the full terminal history on purpose so it can create a smaller checkpoint that fits.

Review remediation

What changed

  • Replaced the false-positive total-code-unit assertion with a direct proof that an oversized checkpoint object is never handed to full-object JSON.stringify.
  • Kept the exactness-parity tests and passing-path test unchanged.
  • Clarified that JSON emission is bounded, while the rejection fallback intentionally performs a full checkpoint replay.
  • Replaced implied dramatic performance claims with the measured warmed 100 MiB ranges: 253.7–330.2 ms before and 247.4–253.6 ms after.

ELI5

The size-limited JSON builder stops once its bucket is full, so it never creates the giant JSON result. Orca may still reread the terminal data afterward because that replay is how it makes a smaller checkpoint worth saving.

Proof of fix

RED phase: archived pre-fix production (d0ce3c7ec3) with the new test copied in.

temp_dir=$(mktemp -d /tmp/orca-pr11422-red.XXXXXX) && git -C /Users/nwparker/orca/workspaces/orca/prod-scan-07-29 archive d0ce3c7ec3 | tar -x -C "$temp_dir" && cp /Users/nwparker/orca/workspaces/orca/prod-scan-07-29/src/main/daemon/terminal-checkpoint-serializer.test.ts "$temp_dir/src/main/daemon/terminal-checkpoint-serializer.test.ts" && ln -s /Users/nwparker/orca/workspaces/orca/prod-scan-07-29/node_modules "$temp_dir/node_modules" && printf 'RED_TEMP=%s\n' "$temp_dir" && cd "$temp_dir" && pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-checkpoint-serializer.test.ts -t 'rejects an oversized escaped candidate without materializing it'

Result: 1 test file failed; 1 test failed, 2 skipped. The intended assertion failed because pre-fix production passed the oversized checkpoint object to JSON.stringify (expected true to be false).

GREEN phase on pushed head 88ca338811:

pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-checkpoint-serializer.test.ts src/main/daemon/json-utf8-byte-length.test.ts src/main/daemon/terminal-checkpoint-writer-bounds.test.ts

Result: 3 test files passed; 9 tests passed.

Proof of no regression

The green command covers the serializer, exact UTF-8 byte estimator, and checkpoint writer fallback suites. The existing exactness-parity tests and passing-path test remain intact.

pnpm run typecheck

Result: passed across config/tsconfig.node.json, config/tsconfig.tc.cli.json, and config/tsconfig.tc.web.json.

pnpm exec oxlint src/main/daemon/terminal-checkpoint-serializer.test.ts

Result: passed with 0 diagnostics.

No user-visible UI change; screenshots are not applicable.

Final review objections

What changed

  • Added an over-limit multibyte serializer case where the complete JSON is 99 UTF-8 bytes over the cap while its UTF-16 code-unit length is one unit under the cap.
  • Confirmed repo-wide that json-utf8-byte-length was imported only by its own test, then deleted both the dead module and its test.

ELI5

Some characters take more bytes to save than their JavaScript string length suggests, so the new test makes sure Orca measures the real saved size. The old measuring module was no longer connected to Orca, so it and its isolated test were removed.

Proof of fix

RED phase: archived head 88ca338811, copied in the new test, and mutated BoundedJsonWriter.append in the temporary copy to compare and accumulate value.length instead of UTF-8 bytes.

temp_dir=$(mktemp -d /tmp/orca-pr11422-code-unit-red.XXXXXX) && git -C /Users/nwparker/orca/workspaces/orca/prod-scan-07-29 archive HEAD | tar -x -C "$temp_dir" && cp /Users/nwparker/orca/workspaces/orca/prod-scan-07-29/src/main/daemon/terminal-checkpoint-serializer.test.ts "$temp_dir/src/main/daemon/terminal-checkpoint-serializer.test.ts" && ln -s /Users/nwparker/orca/workspaces/orca/prod-scan-07-29/node_modules "$temp_dir/node_modules" && python3 -c 'from pathlib import Path; p=Path("'$temp_dir'/src/main/daemon/terminal-checkpoint-serializer.ts"); s=p.read_text(); s=s.replace("if (this.bytes + bytes > this.maxBytes)", "if (this.bytes + value.length > this.maxBytes)").replace("this.bytes += bytes", "this.bytes += value.length"); p.write_text(s)' && pnpm --dir "$temp_dir" exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-checkpoint-serializer.test.ts -t 'rejects multibyte input whose code-unit length fits under the byte cap'

Result: 1 test file failed; 1 test failed, 3 skipped. The mutation wrongly accepted and returned the direct over-byte-cap JSON, so expect(serialized).not.toBe(expected) failed.

GREEN phase on 4f28318842:

pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/terminal-checkpoint-serializer.test.ts

Result: 1 test file passed; 4 tests passed.

Proof of no regression

pnpm exec vitest run --config config/vitest.config.ts src/main/daemon/history-manager.test.ts src/main/daemon/history-reader.test.ts src/main/daemon/terminal-history-incremental-restore.test.ts src/main/daemon/terminal-checkpoint-writer-bounds.test.ts

Result: 4 test files passed; 95 tests passed.

pnpm run typecheck

Result: passed across all 3 configured projects: node, tc.cli, and tc.web.

pnpm exec oxlint src/main/daemon/terminal-checkpoint-serializer.test.ts

Result: passed with 0 diagnostics.

Repo-wide import confirmation at 88ca338811:

rg -n --hidden --glob '!node_modules' --glob '!.git' "(?:from|import\\()\\s*['\\\"][^'\\\"]*json-utf8-byte-length['\\\"]|jsonUtf8ByteLength" /Users/nwparker/orca/workspaces/orca/prod-scan-07-29

Result: the only import was src/main/daemon/json-utf8-byte-length.test.ts:2; all other matches were declarations or calls inside that same module/test pair. After deletion, a repo-wide search returned no matches.

Scan provenance

Finding: P2 — Terminal checkpoint serializer walks the full payload three times synchronously. Severity: P2. Introduced by #10647 (ca5a821600).

Made with Orca

Comment on lines 1 to 4
import type { TerminalCheckpointFile, TerminalSnapshot } from './types'
import { ColdRestoreReplayWriter } from './cold-restore-replay-writer'
import { HeadlessEmulator } from './headless-emulator'
import { jsonUtf8ByteLength } from './json-utf8-byte-length'

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 Orphaned module left behind

json-utf8-byte-length.ts was the sole production consumer of jsonUtf8ByteLength, and the only remaining import is in json-utf8-byte-length.test.ts. With this PR removing the import, both json-utf8-byte-length.ts and its test file are dead code that no longer have a production caller. They can be deleted to keep the codebase clean.

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 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR replaces the terminal checkpoint serializer's previous two-pass approach (full JSON.stringify + Buffer.byteLength scan) with a single-pass BoundedJsonWriter that tracks UTF-8 bytes inline while emitting output, abandoning the write as soon as the cap is exceeded. Dead code (json-utf8-byte-length.ts and its test) is removed after confirming no remaining production imports.

  • BoundedJsonWriter + appendJsonString/appendJsonValue: UTF-8 byte counting handles ASCII (1 byte), multi-byte BMP (2–3 bytes), valid surrogate pairs (4 bytes), lone surrogates (escaped as \uXXXX, 6 bytes), and control character escapes correctly. Spans are flushed in 16 KiB chunks to limit string concatenation overhead.
  • Binary search fallback: when the direct attempt exceeds the limit, the serializer replays the snapshot, takes a visible-only base, then binary-searches scrollback row count to find the largest fitting checkpoint — unchanged from the previous implementation.
  • Tests: four new cases cover exactness parity at the UTF-8 boundary, multibyte rejection where code-unit length is under the cap but byte length is over, the no-JSON.stringify/no-Buffer.byteLength fast path for passing candidates, and the no-materialize guarantee for oversized inputs.

Confidence Score: 5/5

Safe to merge — the change is well-scoped to the serializer, does not touch callers, and is fully covered by parity and behavioural tests.

The byte accounting in appendJsonString correctly handles every Unicode case. The BoundedJsonWriter invariant — discard and return null on first overflow — is straightforward and the test suite directly verifies no full-object JSON.stringify or Buffer.byteLength call is made on the passing path. Deleting json-utf8-byte-length.ts is safe as it had no remaining production callers.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/main/daemon/terminal-checkpoint-serializer.ts Core rewrite: replaces two-pass (measure + stringify) with a single-pass BoundedJsonWriter that counts UTF-8 bytes inline and abandons output once the cap is hit. Byte accounting for surrogates, escapes, and multibyte BMP characters looks correct.
src/main/daemon/terminal-checkpoint-serializer.test.ts New test suite covering exactness parity at the UTF-8 byte limit, multibyte rejection, no-materialize fast path, and oversized candidate short-circuit. Comprehensive spy-based verification of the key performance invariants.
src/main/daemon/json-utf8-byte-length.ts Deleted — its only production consumer was removed when the inline BoundedJsonWriter took over byte tracking.
src/main/daemon/json-utf8-byte-length.test.ts Deleted alongside its module — no remaining production import after the serializer change.

Reviews (5): Last reviewed commit: "Merge branch 'main' into perf/single-pas..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 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: 60a5ea76-5764-4bb1-8cef-1b7de9241ec9

📥 Commits

Reviewing files that changed from the base of the PR and between 88ca338 and 4f28318.

📒 Files selected for processing (3)
  • src/main/daemon/json-utf8-byte-length.test.ts
  • src/main/daemon/json-utf8-byte-length.ts
  • src/main/daemon/terminal-checkpoint-serializer.test.ts
💤 Files with no reviewable changes (2)
  • src/main/daemon/json-utf8-byte-length.test.ts
  • src/main/daemon/json-utf8-byte-length.ts

📝 Walkthrough

Walkthrough

The terminal checkpoint serializer now incrementally writes JSON while tracking UTF-8 bytes, returning null when the limit is exceeded. It handles JSON escaping, omitted values, circular structures, and unsupported BigInt values. Tests cover exact-limit serialization, multibyte byte limits, single getter traversal without rescanning, and early rejection of oversized escaped content.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is informative, but it doesn't follow the repo's required template sections or include the requested screenshots, testing, and review/audit notes. Rewrite it using the template's Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes sections, and add the cross-platform review details.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: checkpoint serialization now walks the payload once while staying terminal-specific and performance-focused.
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 💡 1
📝 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-checkpoint-serializer.test.ts (1)

44-58: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise a multibyte UTF-8 boundary.

The fixture uses only ASCII, so it would not catch a regression that counts JavaScript characters instead of UTF-8 bytes. Add a case with multibyte characters and a limit near the serialized size (including an over-limit case) to verify the byte-cap branch directly.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c0960f97-c1b7-4846-9db6-2b17dca3b7b8

📥 Commits

Reviewing files that changed from the base of the PR and between 5c8013a and d0ce3c7.

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

@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-checkpoint-serializer.ts (1)

157-205: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

No toJSON()/boxed-primitive support in the generic object path.

Unlike native JSON.stringify, this falls straight to Object.keys(value) for any object, so a Date (or other value with toJSON(), or a boxed Number/String/Boolean) would silently serialize as {} instead of its proper JSON representation. Not triggered by the current TerminalCheckpointFile shape (plain strings/numbers/arrays/objects only), but worth guarding against since this function is meant to be a byte-exact stand-in for JSON.stringify.

♻️ Optional guard for toJSON-bearing values
   if (activeObjects.has(value)) {
     throw new TypeError('Converting circular structure to JSON')
   }
+  if (typeof (value as { toJSON?: unknown }).toJSON === 'function') {
+    return appendJsonValue(writer, (value as { toJSON: () => unknown }).toJSON(), activeObjects)
+  }
   activeObjects.add(value)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 972ffb4a-8a4b-471c-9834-783424551754

📥 Commits

Reviewing files that changed from the base of the PR and between d0ce3c7 and fa33c09.

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

@nwparker
nwparker merged commit ab2b517 into main Jul 30, 2026
52 of 53 checks passed
@nwparker

Copy link
Copy Markdown
Contributor Author

Post-merge follow-up: #11535.

The correctness of BoundedJsonWriter holds up — I differential-fuzzed the extracted implementation against JSON.stringify over 60,096 cases (randomized nested values plus targeted 16 KiB span-boundary cases across ASCII, 2/3-byte UTF-8, surrogate pairs, lone surrogates and control chars) and found zero divergence in output, in acceptance at exactly the byte cap, or in rejection at cap−1.

The performance claim is where it comes apart. Benchmarking the deleted jsonUtf8ByteLength + JSON.stringify path against the merged writer on SGR-styled scrollback (Node 24, median of 9 warmed runs, --expose-gc):

content 5MB scrollback before #11422 after #11422
plain ASCII 12.9ms 17.0ms (1.3x slower)
light ANSI 13.5ms 25.4ms (1.9x slower)
agent-TUI ANSI 20.2ms 86.2ms (4.3x slower)
over-cap reject 10MB, 256KiB cap 16.4ms 1.7ms (10x faster ✓)

The over-cap win is real. But the passing path — which runs on every checkpoint tick — got slower, and it degrades with ANSI escape density because each escape flushes the writer's 16 KiB span and appends separately. Claude Code / Codex TUI scrollback is the densest case, so the regression lands hardest on Orca's primary workload.

The measured range in the description (253.7–330.2ms before, 247.4–253.6ms after) is at 100 MiB, where the emulator replay dominates and masks the serializer delta.

#11535 keeps the bounded walk for sizing only and hands emission back to JSON.stringify: parity with pre-#11422 on the passing path, and 0.3ms on the reject path (better than both). It also closes the appendJsonValue non-exceed-false hole that could return a truncated non-null string, and restores the estimator cross-check.

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…#11422)

* perf(terminal): serialize checkpoints with one payload walk

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

* fix(terminal): bound checkpoint serialization

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

* test(terminal): correct bounded serialization proof

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

* test(terminal): cover over-limit multibyte checkpoints

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

---------

Co-authored-by: Orca <[email protected]>
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