Repository navigation
perf(persistence): skip rewriting unchanged terminal scrollback snapshots - #18764
Conversation
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Digest-guarded snapshot writes —
terminal-scrollback-snapshots.tsnow tracks a per-process SHA-256 of what it last wrote at each path and short-circuits both the sync and async writers when the buffer is byte-identical, dropping the entry on delete and on write failure. - New unit tests —
terminal-scrollback-snapshot-write-skip.test.tspins the no-op republish via unchangedino/mtimeMs, the rewrite-on-content-change path, and the rewrite-after-delete path. - Benchmark harness —
bench:scrollback-snapshot-write-skipruns the production writer with and without the write memory reset.
The core invariant holds: the digest is computed on the full source buffer, and the bytes written to disk are a deterministic function of that buffer, so digest equality implies the on-disk content is already correct — a skip can never leave stale bytes. The delete and write-failure paths both clear the map entry first, and every deletion in the codebase flows through these helpers, so the documented "external writer" case is not reachable within Orca.
ℹ️ Async writer has no direct coverage
The new test file exercises only the sync writer. writeTerminalScrollbackSnapshot (the deferSnapshotFiles path) duplicates the skip/remember logic against the same shared map but isn't asserted directly; a regression there (e.g. a dropped rememberWrittenSnapshotDigest) wouldn't be caught. Non-blocking — consider a matching async test.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between e95026d1b17ac67650c20b72efa07d9ef42586ac and 3a6a11601d9b79f9dd01fd5104ec9978041a594a. 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review. 📝 WalkthroughWalkthroughThe change adds process-local SHA-256 digest caching to terminal scrollback snapshot writers. Unchanged snapshots skip encoding and file writes. Failed writes and deleted snapshots clear cached state. Tests cover unchanged writes, changed content, file replacement, and cache eviction. A benchmark measures baseline and republish timings, validates output files, reports avoided disk writes, and is exposed through package scripts. Merge Risk: ⚪ Minimal · up to Terminal scrollback snapshots now avoid rewriting verified unchanged files, reducing disk I/O while retaining rewrites when snapshots change or are no longer valid. Current merge-readiness risk is minimal. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description explains the change, motivation, implementation, measurements, testing, platform considerations, and checklist status. However, the required Linked Issue section contains "N/A", while the template states that an issue must always be linked. ✨ 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.
Actionable comments posted: 4
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: bffc54a8-61e6-4540-a052-6d259a9e748f
📒 Files selected for processing (4)
config/scripts/scrollback-snapshot-write-skip-benchmark.mjspackage.jsonsrc/main/terminal-scrollback-snapshot-write-skip.test.tssrc/main/terminal-scrollback-snapshots.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
5a5c42c to
8a0b89c
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Extracted the write memory into
terminal-scrollback-snapshot-write-memory.ts— the per-process digest map became a disk-verified identity{ digest, size, mtimeMs, ino }, still capped at 256 with least-recently-republished eviction. - Added on-disk verification before skipping — both writers now stat the temp file before rename (rename preserves inode and mtime) and, on republish, only skip when
isWrittenSnapshotStillOnDiskconfirms the file at the path still matches that identity. A vanished, replaced, or modified-in-place file forces a rewrite. - Closed the "external writer" caveat by construction — the previous digest-only skip assumed the directory was Orca-owned; the new stat check makes a stale skip require same size + inode + mtime to the millisecond.
- Added direct async-writer coverage — resolving the prior review's only note, plus delete-with-fallback-root, vanished/replaced/modified-in-place, and the 256-cap eviction tests.
The identity check (ino + mtimeMs + size) matches the codebase's established file-identity idiom (secure-file.ts, relay/terminal-history.ts), and the tests implicitly verify that rename preserves inode on every platform the suite runs.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Hoisted the sync writer's digest guard out of its
tryblock —snapshotDigest,statSnapshotSync, and theisWrittenSnapshotStillOnDiskcheck now run before thetryinwriteTerminalScrollbackSnapshotSync, mirroring the async writer and scoping thecatch/forgetWrittenSnapshotpath to the actual disk write.
The change is behaviorally neutral in practice: snapshotDigest hashes an already-validated non-empty string, statSnapshotSync swallows its own errors, and isWrittenSnapshotStillOnDisk only does map lookups and numeric comparisons — none can throw. The prior placement was a latent wart, where any throw from the guard would have hit the catch, spuriously forgetWrittenSnapshot-ing a valid entry and returning null (treating a pure memory/read failure as a write failure). The real write path (trailingUtf8Bytes, mkdirSync, writeFileSync, renameSync) stays inside the try, so disk failures are still caught and logged as before.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
41c6495 to
e95026d
Compare
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Proved the skip instead of inferring it — the benchmark now stats every snapshot before and after an unchanged republish and fails if any file's
inoormtimeMsmoved; the previous size-based check read identical whether or not a rewrite happened, so it could not actually detect a regression. - Fail-loudly guards — a
nullreturn fromwriteTerminalScrollbackSnapshotSyncnow throws, andORCA_SNAPSHOT_BENCH_LEAVESabove the writer's 256-entry digest capacity is rejected up front so silent LRU eviction can't mask the skip the benchmark claims to measure.
The verification is sound: writtenFiles is captured once, so both stat passes walk the same name order, and a real rewrite always produces a fresh inode (temp file + rename), so the inode comparison can't false-negative. No production code changed in this delta.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
54c70fe to
ce8b420
Compare
There was a problem hiding this comment.
Important
package.json defines bench:terminal-partial-escape-tail twice — the second entry shadows the first and silently drops its --disable-warning=MODULE_TYPELESS_PACKAGE_JSON flag, so the benchmark emits a module-type warning on every run. Delete the duplicate entry. The optimization itself is correct and thoroughly tested.
Reviewed changes
- Added an ESC-free fast path to
advancePartialEscapeTail— when the tracked tail is empty and the chunk has no ESC byte, return''instead of concatenating and walking the chunk. - Added differential fuzz and unit coverage — the gate is proven byte-identical to the unguarded fold over a ~593k-case corpus (exhaustive at symbol depth, every split point of known sequences, and the tail-cap boundary), plus a fold-property check.
- Added a benchmark —
bench:terminal-partial-escape-tailverifies equivalence over a corpus, then reports ~583x faster on ESC-free chunks and 1.0x (no-op) on SGR-coloured output.
ℹ️ PR title and description describe a different change
The branch now holds the terminal partial-escape-tail optimization, but the title (perf(persistence): skip rewriting unchanged terminal scrollback snapshots) and the full description still describe the scrollback-snapshot work this branch previously contained. Update them to match — or split this into its own PR — so reviewers and the merge history stay coherent.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
| "bench:terminal-partial-escape-tail": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON config/scripts/terminal-partial-escape-tail-benchmark.mjs", | ||
| "bench:terminal-partial-escape-tail": "node config/scripts/terminal-partial-escape-tail-benchmark.mjs", |
There was a problem hiding this comment.
Duplicate key: this second bench:terminal-partial-escape-tail entry shadows the one above and drops its --disable-warning=MODULE_TYPELESS_PACKAGE_JSON flag, so the benchmark emits a module-type warning on every run (I confirmed by running it). Delete this line and keep the flagged entry, matching the sibling bench:worktree-refresh-churn script.
| "bench:terminal-partial-escape-tail": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON config/scripts/terminal-partial-escape-tail-benchmark.mjs", | |
| "bench:terminal-partial-escape-tail": "node config/scripts/terminal-partial-escape-tail-benchmark.mjs", | |
| "bench:terminal-partial-escape-tail": "node --disable-warning=MODULE_TYPELESS_PACKAGE_JSON config/scripts/terminal-partial-escape-tail-benchmark.mjs", |
…te against the unguarded fold
… and cap the fold expectation
Two review findings on the differential fuzz, both about the test faithfully modelling the
function it guards.
The odometer generated strings by symbol depth but the caller filtered on `chunk.length`, which
is the UTF-16 code-unit count. An astral symbol is two code units, so every depth-4 string
containing one was silently skipped and the corpus was not exhaustive at depth 4 the way the
test name claimed. The generator now yields `{ depth, text }` and the caller filters on depth.
That restores the missing strings and takes the pinned corpus from 516,566 to 593,468 - exactly
the count CodeRabbit derived for the intended corpus.
The pairing assertion in the sibling suite compared the capped `advancePartialEscapeTail`
against an uncapped `extractPartialEscapeTail(pending + chunk)`. It passed only because no
pairing in that corpus crosses MAX_PARTIAL_ESCAPE_TAIL_LENGTH; it would have stopped modelling
the function the moment one did. The cap now lives in the expectation, matching the fuzz
oracle.
Re-verified the fuzz still fails on a wrong guard: mutating the gate to a bracket check fails
all four tests with a `gate diverged` assertion on a lone ESC chunk.
Reported by CodeRabbit and pullfrog on #18748.
ce8b420 to
f57744e
Compare
There was a problem hiding this comment.
ℹ️ No new issues in this delta. The changes since the last review are clean and well-tested; the only reason this isn't an approval is that the previously-raised duplicate
bench:terminal-partial-escape-tailkey inpackage.jsonis still present (open thread), and the PR title/description still describe the earlier scrollback work.
Reviewed changes
- Simplified the benchmark —
terminal-partial-escape-tail-benchmark.mjsdrops thespawnSyncre-exec andnodeModule.registerHooks.ts-resolution shim in favor of a direct staticimportof the.tssource, matching the siblingbench:worktree-refresh-churnscript (native type stripping +--disable-warning=MODULE_TYPELESS_PACKAGE_JSON). - Added exhaustive differential fuzz coverage —
terminal-partial-escape-tail.fuzz.test.tschecks the gate against the unguarded fold oracle (plus a fold-property check) across an exhaustive symbol-depth corpus, every split point of known sequences, and the tail-cap boundary, ratcheting the case count to593_468(I verified the count is correct). - Spelled the ESC gate consistently —
advancePartialEscapeTailnow writes the ESC byte as'\x1b', matching the sibling ingest gates; behaviorally identical to the prior'\u001b'. - Expanded the unit-test corpus — richer pending-tail/chunk pairings and
JSON.stringifyfailure messages.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
…hots (stablyai#18764) * perf(terminal): tighten the partial-escape-tail benchmark and equivalence test * perf(terminal): spell the ESC gate the same way as the sibling ingest gates * test(terminal): differential-fuzz the ESC-free partial-escape-tail gate against the unguarded fold * test(terminal): make the escape-tail fuzz exhaustive at symbol depth, and cap the fold expectation Two review findings on the differential fuzz, both about the test faithfully modelling the function it guards. The odometer generated strings by symbol depth but the caller filtered on `chunk.length`, which is the UTF-16 code-unit count. An astral symbol is two code units, so every depth-4 string containing one was silently skipped and the corpus was not exhaustive at depth 4 the way the test name claimed. The generator now yields `{ depth, text }` and the caller filters on depth. That restores the missing strings and takes the pinned corpus from 516,566 to 593,468 - exactly the count CodeRabbit derived for the intended corpus. The pairing assertion in the sibling suite compared the capped `advancePartialEscapeTail` against an uncapped `extractPartialEscapeTail(pending + chunk)`. It passed only because no pairing in that corpus crosses MAX_PARTIAL_ESCAPE_TAIL_LENGTH; it would have stopped modelling the function the moment one did. The cap now lives in the expectation, matching the fuzz oracle. Re-verified the fuzz still fails on a wrong guard: mutating the gate to a bracket check fails all four tests with a `gate diverged` assertion on a lone ESC chunk. Reported by CodeRabbit and pullfrog on stablyai#18748.

ELI5
Every time you click from one terminal split pane to another, Orca saves your session. As part of that save it rewrote your terminal scrollback files to disk — all of them, every time — even though not a single byte had changed. At 8 sleeping terminals that's 4 MB of synchronous disk writes per pane click, on the main thread.
This PR makes the writer remember what it last put at each path and skip the write when the content is identical. Same files on disk, just without rewriting them.
Split out of #18739 because this is the one change in that series that keeps state between calls (a small digest map), so it deserves its own review and its own revert button.
What Changed
terminal-scrollback-snapshot-write-memory.ts(new) — a per-process map from snapshot path to{ digest, size, mtimeMs, ino }of the file the last rename produced (stat taken on the temp file before the rename, which preserves inode and mtime). Capped at 256 entries, evicting the least recently republished path.terminal-scrollback-snapshots.ts— both writers (writeTerminalScrollbackSnapshotSyncand the async variant) compute a SHA-256 of the buffer; on a digest match theystatthe path and return the existing ref only if size, mtime and inode still match the file this process wrote. Anything else — file missing, replaced, or modified in place — drops the entry and writes. The entry is also dropped by both delete helpers and on write failure. A fresh process always writes at least once.config/scripts/scrollback-snapshot-write-skip-benchmark.mjs(pnpm bench:scrollback-snapshot-write-skip) — runs the production writer in both modes: with the memory reset each round (every leaf reaches disk, the pre-change behaviour) and with it retained.The memory is a hint, not the source of truth. The on-disk check is what makes the skip safe; the map only decides whether the check is worth running.
Why
The main thread is what serves file-explorer, editor and git IPC, so this is disk time those requests spent queued behind a pane click.
Measurements
pnpm bench:scrollback-snapshot-write-skip, 8 retained scrollback leaves at the 512 KB cap, median of 9 rounds, M4 Max, 5 runs each. The baseline is disk-bound and noisy run to run (4–10 ms); the after number is stable.The 8
statcalls on a hit are lost in the SHA-256 cost of hashing 4 MB; the remaining 1.5 ms is the hash, not disk.Linked Issue
N/A — perf follow-up found while profiling the session write path.
Visual Proof
N/A — no UI or interaction change; the bytes on disk are identical.
Negative user-facing trade-offs
None identified. Specifically:
Two things worth stating explicitly rather than hiding:
The earlier "external writers" caveat is gone: the on-disk check closes it by construction rather than by audit. The only way to get a stale skip is a writer that replaces the file with the same size, same inode and same mtime to the millisecond, which is not something a file replace produces.
Testing
pnpm tc✅pnpm test src/main/terminal-scrollback-snapshot-write-skip.test.ts src/main/persistence— 901 passed ✅pnpm run check:code-quality:changed✅New:
src/main/terminal-scrollback-snapshot-write-skip.test.ts(10 tests): republish is a no-op on the same inode and mtime for both the sync and async writer, and the memory is shared between them; content change rewrites; sync delete and async delete (with a legacy fallback root, which the write never targets) then republish rewrites; the file vanishing, being replaced, or being modified in place with the same size and inode behind the memory all rewrite; the 256 cap holds and evicts the least recently republished path, never a hot one.I manually tested these changes locally (macOS)
Automated tests added/updated
Review
Agent skill upstream boundary
Notes
Cross-platform: paths come from
snapshotPath, which already usespath.join; the map is keyed by that resolved string. SSH: snapshot files live on the host that owns the store, and the memory is per-process on that host. Folder workspaces and worktrees take the same path.Checklist
N/Awith reason for visual proofpnpm tc,pnpm test(touched paths), andcheck:code-quality:changedpass locally; CI covers the rest