Repository navigation
Conversation
…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]>
| /** 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 | ||
| }) | ||
| } |
There was a problem hiding this comment.
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.
| /** 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() |
There was a problem hiding this comment.
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 SummarySeparates the sizing and emission concerns that
Confidence Score: 4/5Safe 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.
|
| 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
Reviews (1): Last reviewed commit: "perf(terminal): size checkpoints with a ..." | Re-trigger Greptile
📝 WalkthroughWalkthroughReplaces 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 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 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.
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
📒 Files selected for processing (2)
src/main/daemon/terminal-checkpoint-serializer.test.tssrc/main/daemon/terminal-checkpoint-serializer.ts
| /** 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 | ||
| }) | ||
| } |
There was a problem hiding this comment.
🎯 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.
| /** 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 | |
| }) | |
| } |
|
Superseded by #26177. |
Description
Follow-up to #11422. That PR replaced
jsonUtf8ByteLength+JSON.stringifywithBoundedJsonWriter, 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 toJSON.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
BoundedJsonWriterbatches 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 withESC(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.PREismainbefore #11422,MERGEDismaintoday,FIXEDis this PR.Passing path — checkpoint fits under the cap. This runs on every checkpoint tick.
Reject path — payload over a 256 KiB cap.
At realistic 5MB checkpoints this is at parity with pre-#11422 (0.97x–1.06x) and 1.4x–4.2x faster than
maintoday. 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 thanmain.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
stringifyWithinLimitagainstJSON.stringify— 60,096 cases, zero divergence on all three axes: exact output equality, acceptance at exactly the byte cap, and rejection at cap−1.Test suites:
Two latent issues closed along the way
Truncated-JSON hole.
appendJsonValuereturnedfalsefor two different reasons — budget exceeded, and value not serializable — butstringifyWithinLimitdiscarded the boolean and returnedwriter.result(). The non-exceedfalseyielded a non-null, half-written string that would have been renamed into place ascheckpoint.json. Unreachable today, but now structurally impossible: anyfalsereturnsnull.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 nativeJSON.stringifyagain, 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 candidateassertedfullCandidateStringifies: 0, byteLengthCalls: 0— it pinned the emitter design this PR reverses. Split intoreads 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.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.expectedJson.Background daemon work only; no user-visible UI change, so screenshots are not applicable.
Made with Orca 🐋