Skip to content

perf(persistence): stop the session write re-scanning and rebuilding unchanged state - #18739

Merged
nwparker merged 3 commits into
mainfrom
perf/session-write-hot-path
Sep 5, 2026
Merged

nwparker merged 3 commits into
mainfrom
perf/session-write-hot-path

Conversation

@nwparker

@nwparker nwparker commented Sep 4, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​44 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​44
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​272 $\color{#cf222e}{\Huge{\mathbf{−}}}$​42 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​230

ELI5

Every time you click from one terminal split pane to another, Orca saves your session. That save was doing two chunks of pure CPU work that produced exactly the same result as last time:

  1. It rebuilt three internal bookkeeping maps (which pane you'd acknowledged, when you cleared activity, which turns you marked unread) and then threw all three away. These maps grow with every pane you've ever opened, so this got slower the longer you'd used Orca.
  2. It measured the byte size of every saved scrollback buffer with a hand-written character-by-character loop — twice per save, over half-megabyte buffers.

Neither produced a different answer than the previous save. This PR makes each one skip the work when nothing changed. Same maps, same size decisions — just without redoing the work.

Both changes are stateless per call apart from a reused scratch buffer. The third optimization that used to ride along here — skipping the disk rewrite of unchanged scrollback snapshot files — is the only one that keeps memory between calls, so it moved to its own PR (#18764) to be reviewed and reverted independently.

What Changed

  • pane-key-remapping.ts — remapPaneKeys classifies first and returns the caller's map untouched when no key needs to move. The rewrite path still runs during an actual migration; changed is only ever true when at least one key actually moved, so the rewrite loop no longer tracks it separately.
  • utf8-byte-limits.ts — isUtf8ByteLengthWithinLimit answers the bounded question with TextEncoder.encodeInto against a reused scratch buffer. encodeInto stops at the destination's end, so a short read means "needs more than maxBytes" — exactly the predicate. Limits above 1 MB and non-integer limits (NaN, Infinity) still take the original scan.
  • workspace-session-terminal-buffers.ts — capTerminalScrollbackSessionBuffer routes through that bounded check instead of its own scan.

Why

The main thread is what serves file-explorer, editor and git IPC, so this is time those requests spent queued behind a pane click.

Measurements

pnpm bench:session-write-hot-path (new, checked in), 8 retained scrollback leaves / 2000 accumulated pane keys, median of 9 rounds, M4 Max. Each scenario runs the production export against the pre-change function verbatim (the old capTerminalScrollbackSessionBuffer body over the unchanged measureUtf8ByteLength, and the old remapPaneKeys including its parsePaneKey pass), so the numbers can't drift away from what production did.

Per session write Before After
scrollback UTF-8 budget scan (16 calls @ 512 KB) 20.5 ms 3.0 ms 6.8x
pane-key remap (3 maps @ 2000 keys) 1.4 ms 0.6 ms 2.3x
main-thread time ~22 ms ~3.6 ms
discarded map objects 3 per write 0

Linked Issue

N/A — perf follow-up found while profiling the session write path.

Visual Proof

N/A — no UI or interaction change; the persisted maps and byte-limit decisions are identical.

Negative user-facing trade-offs

None identified. Specifically:

  • No changed limits. The native byte-length check is exercised against the scan it replaced across lone surrogates, multi-byte sequences, and every limit around the boundary — added as a differential test.
  • No changed maps. remapPaneKeys returns the same values it built before; only the allocation is gone. Added an identity assertion so a future rebuild-and-discard regression fails the test.

One thing worth stating explicitly rather than hiding:

  • Memory: the UTF-8 scratch buffer is retained and grows to the largest limit requested, capped at 1 MB (512 KB in practice — the scrollback limit). It is the only state in this PR.

Testing

  • pnpm tc ✅

  • pnpm test src/main/persistence src/shared/workspace-session-terminal-buffers.test.ts src/shared/utf8-byte-limits.test.ts — 927 passed ✅

  • pnpm run check:code-quality:changed ✅

  • New: differential test in src/shared/utf8-byte-limits.test.ts

  • New: identity assertion in pane-key-remapping.test.ts

  • I manually tested these changes locally (macOS)

  • Automated tests added/updated

Review

Agent skill upstream boundary

  • Not applicable

Notes

Cross-platform: pure JS/TS, no path or shell work. SSH: the session write runs on whichever host owns the store; nothing here is host-specific. TextEncoder is a global on every target that imports src/shared (Node 24 main, Electron renderers, the relay); mobile/ does not import this module, so the encoder is constructed eagerly with no runtime guard.

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

@coderabbitai

coderabbitai Bot commented Sep 4, 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: Team

Run ID: 09e183a0-e94b-4f06-ac34-1af51d731599

📥 Commits

Reviewing files that changed from the base of the PR and between 89d3f09 and df681b06e4c9da3fbfc406c37c74fcddaad87462.

📒 Files selected for processing (3)
  • config/scripts/session-write-hot-path-benchmark.mjs
  • src/main/persistence/restoring-sessions/pane-key-remapping.ts
  • src/shared/utf8-byte-limits.ts

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


📝 Walkthrough

Walkthrough

The session write path now uses a bounded native UTF-8 encoding check with scanner fallback. Terminal scrollback capping uses the new check. Pane-key remapping preserves stable input maps. Tests cover both behaviors. A Node.js benchmark compares production behavior with pre-change baselines and reports median timings.

Merge Risk: 🟡 Moderate · up to c39e0

This change improves session-write CPU costs and preserves scrollback byte limits and stable pane-key maps, but an open snapshot-write concern remains: unchanged buffers may leave missing or externally replaced scrollback snapshot content unrepaired. Resolve or explicitly accept that risk before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 23.81% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, visual proof, platform considerations, and checklist. However, the required Linked Issue section contains “N/A,” although the tem… Add the actual issue reference to the Linked Issue section, using the required format such as Fixes #1234``. If no issue exists, create or link a tracking issue before merging.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the main performance change: avoiding redundant session-write work.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, visual proof, platform considerations, and checklist. However, the required Linked Issue section contains “N/A,” although the template states that an issue link must always be provided.

  • Fix all pre-merge checks with AI
✨ 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 3b53eada-47b4-4516-9705-7d2addd41565

📥 Commits

Reviewing files that changed from the base of the PR and between 0a821e5 and 0130277.

📒 Files selected for processing (9)
  • config/scripts/session-write-hot-path-benchmark.mjs
  • package.json
  • src/main/persistence/restoring-sessions/pane-key-remapping.test.ts
  • src/main/persistence/restoring-sessions/pane-key-remapping.ts
  • src/main/terminal-scrollback-snapshot-write-skip.test.ts
  • src/main/terminal-scrollback-snapshots.ts
  • src/shared/utf8-byte-limits.test.ts
  • src/shared/utf8-byte-limits.ts
  • src/shared/workspace-session-terminal-buffers.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 7 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 critical issues — two minor suggestions.

Reviewed changes

  • UTF-8 byte-limit fast path — isUtf8ByteLengthWithinLimit routes bounded limits through TextEncoder.encodeInto against a reused scratch buffer, with a differential test covering lone surrogates and every limit around the exact byte length.
  • Pane-key remap classify-first — remapPaneKeys returns the caller's map untouched (same identity) when no key migrates; the rewrite path is unchanged and an identity assertion pins the no-rebuild behavior.
  • Scrollback snapshot write skip — a SHA-256 digest of the buffer, keyed by resolved path, turns unchanged republishes into no-ops; dropped on delete and write failure, capped at 256 entries.
  • Benchmark — new bench:session-write-hot-path script measures the three costs against pre-change baselines and runs cleanly.

ℹ️ Nitpicks

  • The digest skip in the async writeTerminalScrollbackSnapshot has no test coverage — only the sync path is exercised. It backs the deferred/unload flow (migrateWorkspaceSessionTerminalScrollbackSnapshotsAsync), so a future regression in its remember/forget ordering wouldn't be caught. A single no-op toBe(ref) assertion would close the gap.

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

@nwparker
nwparker force-pushed the perf/session-write-hot-path branch from 0130277 to 89d3f09 Compare September 5, 2026 01:05
@nwparker nwparker changed the title perf(persistence): stop the session write re-scanning, rebuilding, and rewriting unchanged state perf(persistence): stop the session write re-scanning and rebuilding unchanged state Sep 5, 2026

@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 — the delta since the prior pullfrog review splits the scrollback-snapshot write-skip out of this PR and cleans up the two remaining optimizations.

  • Split out the scrollback-snapshot write-skip — terminal-scrollback-snapshots.ts and its write-skip test were removed from this PR (now tracked in #18764), along with the benchmark's snapshot-republish scenario.
  • Refactored remapPaneKeys — the rewrite pass now resolves each key through the shared resolveRemappedPaneKey helper (?? paneKey) instead of re-inlining the classification, and changed is derived from the classify-first pass (changed: true once a remap is known).
  • Inlined the UTF-8 fast path — fitsWithinUtf8ScratchLimit was folded into isUtf8ByteLengthWithinLimit, dropping the now-unreachable maxBytes <= 0 guard (already covered by the length === 0 / length > maxBytes early returns).
  • Trimmed the benchmark — scenario 3 (snapshot republish) was removed, leaving the two CPU costs and a bench:scrollback-snapshot-write-skip cross-reference.

ℹ️ PR description still describes the removed snapshot write-skip

The ELI5, "What changed", and "Measurements" sections still list terminal-scrollback-snapshots.ts and the republish numbers, but that optimization now lives in #18764. Worth trimming before merge so the merged description matches the code.

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

@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)
config/scripts/session-write-hot-path-benchmark.mjs (1)

206-206: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Benchmark the actual parent remap path.

baselineRemapPaneKeys does not match the parent implementation. The parent returns null for canonical makePaneKey keys through parsePaneKey, then returns the original map without allocating next. The baseline skips this guard and always performs the nested lookup and rebuilds next. Reproduce the parent loop so the timing measures this change, not an older and more expensive path.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: c2584bbc-713c-4d59-9768-60a933720189

📥 Commits

Reviewing files that changed from the base of the PR and between 0130277 and 89d3f09.

📒 Files selected for processing (3)
  • config/scripts/session-write-hot-path-benchmark.mjs
  • src/main/persistence/restoring-sessions/pane-key-remapping.ts
  • src/shared/utf8-byte-limits.ts

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

…d rewriting unchanged state

`setLocalWorkspaceSession` runs on every `session:set`/`session:patch`, which fires on
something as ordinary as clicking between two terminal split panes. Three costs in that
handler were paid in full even when nothing had changed.

Scrollback snapshots were re-encoded and rewritten to disk on every publication. The
renderer republishes the whole `terminalLayoutsByTabId` map, so each write re-wrote every
slept leaf's 512 KB snapshot file. The writer now remembers the content digest it last put
at each path and returns the existing ref instead. The memory is keyed by resolved path,
dropped on delete and on write failure, and capped at 256 entries, so a missing file is
always rewritten and a restart always writes at least once.

`remapPaneKeys` rebuilt three pane-key maps per write and the caller discarded all three:
post-migration no key is ever rewritten, so `changed` stayed false. It now classifies first
and returns the caller's map untouched when nothing moves. Those maps grow with every pane
ever opened, so the discarded work grew with workspace age.

`capTerminalScrollbackSessionBuffer` measured each retained buffer with a per-code-unit JS
loop, twice per write. It now goes through `isUtf8ByteLengthWithinLimit`, which answers the
bounded question with `TextEncoder.encodeInto` against a reused scratch buffer — the encoder
stops at the destination's end, so a short read is exactly "exceeds the limit". Limits above
1 MB, and any non-integer limit, still take the scan.

Measured by `pnpm bench:session-write-hot-path` at 8 retained leaves / 2000 pane keys:

| per session write | before | after |
| --- | --- | --- |
| scrollback UTF-8 budget scan | 18.8 ms | 2.8 ms (6.8x) |
| pane-key remap | 1.8 ms | 0.7 ms (2.7x) |
| scrollback snapshot republish | 4.4 ms | 1.5 ms (2.9x) |
| synchronous disk writes | 4.00 MB | 0 |

No behavior changes: the bytes written, the maps returned, and the cap decisions are
identical. The new differential test walks the native byte-limit check against the scan it
replaced across lone surrogates and every limit around the boundary.
…unchanged state

Two stateless optimizations on the per-session-write path:

- remapPaneKeys classifies first and returns the caller's map untouched
  when no key needs to move, instead of rebuilding three maps and
  discarding them on every write.
- isUtf8ByteLengthWithinLimit answers the bounded question through
  TextEncoder.encodeInto against a reused scratch buffer; limits above
  1 MB and non-integer limits still take the scan.

The scrollback snapshot write-skip that used to ride along here moved to
its own PR so it can be reviewed and reverted on its own.
… benchmark baselines verbatim

- remapPaneKeys: drop the unreachable makePaneKey try/catch and fold the empty-map guard into the classify pass
- isUtf8ByteLengthWithinLimit: TextEncoder is available on every target, so construct the encoder and scratch eagerly
- benchmark: run the pre-change capTerminalScrollbackSessionBuffer and remapPaneKeys verbatim instead of a hand-rolled approximation
@nwparker
nwparker force-pushed the perf/session-write-hot-path branch from df681b0 to c39e0a4 Compare September 5, 2026 05:24

@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 — the delta since the prior pullfrog review (89d3f09) makes the benchmark baselines verbatim and simplifies the two fast paths.

  • Made the benchmark baselines verbatim — baselineCapScrollbackBuffer now calls the unchanged production measureUtf8ByteLength + clampUtf8TextTail instead of a hand-written scan, and baselineRemapPaneKeys reproduces the pre-change loop including its parsePaneKey guard and makePaneKey try/catch (addressing the earlier "baseline does not match the parent" nit).
  • Removed the dead try/catch in resolveRemappedPaneKey — makePaneKey cannot throw here: tabId is non-empty and colon-free (first-colon delimiter), and isTerminalLeafId(remappedLeafId) is checked immediately prior, so both throw conditions are pre-guarded.
  • Constructed the TextEncoder eagerly — const utf8Encoder = new TextEncoder() replaces the lazy ??= plus typeof TextEncoder guard; safe on every target that imports src/shared (Node 24 main, Chromium renderers, web build) and mobile/ does not import this module.

The PR description now also reflects the two-optimization scope, with the snapshot write-skip correctly referenced as living in #18764.

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

@nwparker
nwparker merged commit 149732d into main Sep 5, 2026
27 checks passed
@nwparker
nwparker deleted the perf/session-write-hot-path branch September 5, 2026 06:39
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
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