Repository navigation
perf(persistence): stop the session write re-scanning and rebuilding unchanged state - #18739
Conversation
|
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 89d3f09 and df681b06e4c9da3fbfc406c37c74fcddaad87462. 📒 Files selected for processing (3)
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe 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 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)
✅ Passed checks (3 passed)
Full details: Description checkExplanation 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.
✨ 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: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Team
Run ID: 3b53eada-47b4-4516-9705-7d2addd41565
📒 Files selected for processing (9)
config/scripts/session-write-hot-path-benchmark.mjspackage.jsonsrc/main/persistence/restoring-sessions/pane-key-remapping.test.tssrc/main/persistence/restoring-sessions/pane-key-remapping.tssrc/main/terminal-scrollback-snapshot-write-skip.test.tssrc/main/terminal-scrollback-snapshots.tssrc/shared/utf8-byte-limits.test.tssrc/shared/utf8-byte-limits.tssrc/shared/workspace-session-terminal-buffers.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
There was a problem hiding this comment.
ℹ️ No critical issues — two minor suggestions.
Reviewed changes
- UTF-8 byte-limit fast path —
isUtf8ByteLengthWithinLimitroutes bounded limits throughTextEncoder.encodeIntoagainst a reused scratch buffer, with a differential test covering lone surrogates and every limit around the exact byte length. - Pane-key remap classify-first —
remapPaneKeysreturns 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-pathscript measures the three costs against pre-change baselines and runs cleanly.
ℹ️ Nitpicks
- The digest skip in the async
writeTerminalScrollbackSnapshothas 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-optoBe(ref)assertion would close the gap.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
0130277 to
89d3f09
Compare
There was a problem hiding this comment.
✅ 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.tsand 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 sharedresolveRemappedPaneKeyhelper (?? paneKey) instead of re-inlining the classification, andchangedis derived from the classify-first pass (changed: trueonce a remap is known). - Inlined the UTF-8 fast path —
fitsWithinUtf8ScratchLimitwas folded intoisUtf8ByteLengthWithinLimit, dropping the now-unreachablemaxBytes <= 0guard (already covered by thelength === 0/length > maxBytesearly returns). - Trimmed the benchmark — scenario 3 (snapshot republish) was removed, leaving the two CPU costs and a
bench:scrollback-snapshot-write-skipcross-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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
🧹 Nitpick comments (1)
config/scripts/session-write-hot-path-benchmark.mjs (1)
206-206: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winBenchmark the actual parent remap path.
baselineRemapPaneKeysdoes not match the parent implementation. The parent returnsnullfor canonicalmakePaneKeykeys throughparsePaneKey, then returns the original map without allocatingnext. The baseline skips this guard and always performs the nested lookup and rebuildsnext. 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
📒 Files selected for processing (3)
config/scripts/session-write-hot-path-benchmark.mjssrc/main/persistence/restoring-sessions/pane-key-remapping.tssrc/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
df681b0 to
c39e0a4
Compare
There was a problem hiding this comment.
✅ 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 —
baselineCapScrollbackBuffernow calls the unchanged productionmeasureUtf8ByteLength+clampUtf8TextTailinstead of a hand-written scan, andbaselineRemapPaneKeysreproduces the pre-change loop including itsparsePaneKeyguard andmakePaneKeytry/catch (addressing the earlier "baseline does not match the parent" nit). - Removed the dead try/catch in
resolveRemappedPaneKey—makePaneKeycannot throw here:tabIdis non-empty and colon-free (first-colon delimiter), andisTerminalLeafId(remappedLeafId)is checked immediately prior, so both throw conditions are pre-guarded. - Constructed the
TextEncodereagerly —const utf8Encoder = new TextEncoder()replaces the lazy??=plustypeof TextEncoderguard; safe on every target that importssrc/shared(Node 24 main, Chromium renderers, web build) andmobile/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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

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:
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—remapPaneKeysclassifies first and returns the caller's map untouched when no key needs to move. The rewrite path still runs during an actual migration;changedis only evertruewhen at least one key actually moved, so the rewrite loop no longer tracks it separately.utf8-byte-limits.ts—isUtf8ByteLengthWithinLimitanswers the bounded question withTextEncoder.encodeIntoagainst a reused scratch buffer.encodeIntostops at the destination's end, so a short read means "needs more thanmaxBytes" — exactly the predicate. Limits above 1 MB and non-integer limits (NaN,Infinity) still take the original scan.workspace-session-terminal-buffers.ts—capTerminalScrollbackSessionBufferroutes 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 oldcapTerminalScrollbackSessionBufferbody over the unchangedmeasureUtf8ByteLength, and the oldremapPaneKeysincluding itsparsePaneKeypass), so the numbers can't drift away from what production did.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:
remapPaneKeysreturns 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:
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.tsNew: identity assertion in
pane-key-remapping.test.tsI manually tested these changes locally (macOS)
Automated tests added/updated
Review
Agent skill upstream boundary
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.
TextEncoderis a global on every target that importssrc/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
N/Awith reason for visual proofpnpm tc,pnpm test(touched paths), andcheck:code-quality:changedpass locally; CI covers the rest