Repository navigation
perf(terminal): serialize checkpoints with one payload walk - #11422
Conversation
Co-authored-by: Orca <[email protected]>
| 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' | ||
|
|
There was a problem hiding this comment.
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 SummaryThis PR replaces the terminal checkpoint serializer's previous two-pass approach (full
Confidence Score: 5/5Safe 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.
|
| 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
|
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 (3)
💤 Files with no reviewable changes (2)
📝 WalkthroughWalkthroughThe terminal checkpoint serializer now incrementally writes JSON while tracking UTF-8 bytes, returning 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 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-checkpoint-serializer.test.ts (1)
44-58: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winExercise 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
📒 Files selected for processing (2)
src/main/daemon/terminal-checkpoint-serializer.test.tssrc/main/daemon/terminal-checkpoint-serializer.ts
Co-authored-by: Orca <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/main/daemon/terminal-checkpoint-serializer.ts (1)
157-205: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winNo
toJSON()/boxed-primitive support in the generic object path.Unlike native
JSON.stringify, this falls straight toObject.keys(value)for any object, so aDate(or other value withtoJSON(), or a boxedNumber/String/Boolean) would silently serialize as{}instead of its proper JSON representation. Not triggered by the currentTerminalCheckpointFileshape (plain strings/numbers/arrays/objects only), but worth guarding against since this function is meant to be a byte-exact stand-in forJSON.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
📒 Files selected for processing (2)
src/main/daemon/terminal-checkpoint-serializer.test.tssrc/main/daemon/terminal-checkpoint-serializer.ts
Co-authored-by: Orca <[email protected]>
Co-authored-by: Orca <[email protected]>
|
Post-merge follow-up: #11535. The correctness of The performance claim is where it comes apart. Benchmarking the deleted
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 |
…#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]>
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.stringifyfollowed byBuffer.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
JSON.stringify.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.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.tsResult: 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.
Result: passed across
config/tsconfig.node.json,config/tsconfig.tc.cli.json, andconfig/tsconfig.tc.web.json.pnpm exec oxlint src/main/daemon/terminal-checkpoint-serializer.test.tsResult: passed with 0 diagnostics.
No user-visible UI change; screenshots are not applicable.
Final review objections
What changed
json-utf8-byte-lengthwas 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 mutatedBoundedJsonWriter.appendin the temporary copy to compare and accumulatevalue.lengthinstead of UTF-8bytes.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.tsResult: 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.tsResult: 4 test files passed; 95 tests passed.
Result: passed across all 3 configured projects: node, tc.cli, and tc.web.
pnpm exec oxlint src/main/daemon/terminal-checkpoint-serializer.test.tsResult: passed with 0 diagnostics.
Repo-wide import confirmation at
88ca338811: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