Skip to content

perf(persistence): skip rewriting unchanged terminal scrollback snapshots - #18764

Merged
nwparker merged 4 commits into
mainfrom
perf/scrollback-snapshot-write-skip
Sep 5, 2026
Merged

nwparker merged 4 commits into
mainfrom
perf/scrollback-snapshot-write-skip

Conversation

@nwparker

@nwparker nwparker commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​178 $\color{#cf222e}{\Huge{\mathbf{−}}}$​29 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​149
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​51 $\color{#cf222e}{\Huge{\mathbf{−}}}$​110 $\color{#cf222e}{\Huge{\mathbf{−}}}$​59

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 (writeTerminalScrollbackSnapshotSync and the async variant) compute a SHA-256 of the buffer; on a digest match they stat the 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.

Per session write Before After (digest only) After (digest + stat check)
scrollback snapshot republish (8 unchanged leaves) 4.2–10.0 ms 1.52–1.55 ms 1.50–1.55 ms 3–6x
synchronous disk writes 4.00 MB 0 MB 0 MB

The 8 stat calls 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:

  • No staleness. The digest guard skips a write only when the bytes are byte-identical to what this process already wrote at that path. Different content always writes.
  • No lost scrollback. A skip requires the file at the path to still have the size, mtime and inode this process gave it. A file that is missing (deleted by us, by a racing async delete, or by anything external), replaced, or modified in place fails that check and is rewritten. Delete paths and write failures drop the entry as well, and the memory is per-process, so a restart always writes at least once.

Two things worth stating explicitly rather than hiding:

  • Cold writes cost ~0.19 ms more per leaf. The SHA-256 is computed on every call, so a first write or a content change pays the digest on top of the encode it already did (measured: 188 µs for a 512 KB string). An actively printing terminal whose buffer changes between session writes pays this each time; eight such leaves add ~1.5 ms to a write that previously cost ~4–10 ms in disk I/O for the same leaves.
  • Memory: the map holds at most 256 entries (digest + three numbers, ~15 KB) and lives for the process. Eviction is least-recently-republished, so a hot pane is never evicted ahead of a cold one.

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

  • Not applicable

Notes

Cross-platform: paths come from snapshotPath, which already uses path.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

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • N/A with reason for visual proof
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • pnpm tc, pnpm test (touched paths), and check:code-quality:changed pass locally; CI covers the rest

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Digest-guarded snapshot writes — terminal-scrollback-snapshots.ts now 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.ts pins the no-op republish via unchanged ino/mtimeMs, the rewrite-on-content-change path, and the rewrite-after-delete path.
  • Benchmark harness — bench:scrollback-snapshot-write-skip runs 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai

coderabbitai Bot commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 178b53ae-a0af-437c-8215-d013355e7ba4

📥 Commits

Reviewing files that changed from the base of the PR and between e95026d1b17ac67650c20b72efa07d9ef42586ac and 3a6a11601d9b79f9dd01fd5104ec9978041a594a.

📒 Files selected for processing (1)
  • config/scripts/scrollback-snapshot-write-skip-benchmark.mjs
🚧 Files skipped from review as they are similar to previous changes (1)
  • config/scripts/scrollback-snapshot-write-skip-benchmark.mjs

Included review availability: Your plan provides up to 10 included reviews per hour; 3 remain after this review.


📝 Walkthrough

Walkthrough

The 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 3a6a1

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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, motivation, implementation, measurements, testing, platform considerations, and checklist status. However, the required Linked Issue section contains "N/A", while … Add a valid linked issue reference in the Linked Issue section, such as "Fixes #12345" or another applicable issue link. If no issue exists, create or associate one before merging.
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 14 functions across 4 files. 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 clearly and concisely describes the primary change: skipping rewrites of unchanged terminal scrollback snapshots.
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.
Full details: Description check

Explanation

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 💡
  • 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: 4


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: bffc54a8-61e6-4540-a052-6d259a9e748f

📥 Commits

Reviewing files that changed from the base of the PR and between 38bde20 and fc25b13.

📒 Files selected for processing (4)
  • config/scripts/scrollback-snapshot-write-skip-benchmark.mjs
  • package.json
  • src/main/terminal-scrollback-snapshot-write-skip.test.ts
  • src/main/terminal-scrollback-snapshots.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.

@pullfrog pullfrog 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.

✅ 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 isWrittenSnapshotStillOnDisk confirms 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Hoisted the sync writer's digest guard out of its try block — snapshotDigest, statSnapshotSync, and the isWrittenSnapshotStillOnDisk check now run before the try in writeTerminalScrollbackSnapshotSync, mirroring the async writer and scoping the catch/forgetWrittenSnapshot path 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the perf/scrollback-snapshot-write-skip branch from 41c6495 to e95026d Compare September 5, 2026 06:42

@pullfrog pullfrog 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.

✅ 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 ino or mtimeMs moved; 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 null return from writeTerminalScrollbackSnapshotSync now throws, and ORCA_SNAPSHOT_BENCH_LEAVES above 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.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker force-pushed the perf/scrollback-snapshot-write-skip branch 2 times, most recently from 54c70fe to ce8b420 Compare September 5, 2026 07:06

@pullfrog pullfrog 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.

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-tail verifies 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.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread package.json
Comment on lines +145 to +146
"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",

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.

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.

Suggested change
"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",

… 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.
@nwparker
nwparker force-pushed the perf/scrollback-snapshot-write-skip branch from ce8b420 to f57744e Compare September 5, 2026 07:18

@pullfrog pullfrog 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.

ℹ️ 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-tail key in package.json is 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.mjs drops the spawnSync re-exec and nodeModule.registerHooks .ts-resolution shim in favor of a direct static import of the .ts source, matching the sibling bench:worktree-refresh-churn script (native type stripping + --disable-warning=MODULE_TYPELESS_PACKAGE_JSON).
  • Added exhaustive differential fuzz coverage — terminal-partial-escape-tail.fuzz.test.ts checks 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 to 593_468 (I verified the count is correct).
  • Spelled the ESC gate consistently — advancePartialEscapeTail now 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.stringify failure messages.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 4c5077d into main Sep 5, 2026
28 checks passed
@nwparker
nwparker deleted the perf/scrollback-snapshot-write-skip branch September 5, 2026 07:34
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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