Repository navigation
perf(persistence): skip redundant whole-state flushes on terminal reattach - #20137
Conversation
f856be1 to
5002758
Compare
|
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:
📝 WalkthroughWalkthroughThe change adds live lag diagnostic scripts and probes for renderer, inspector, persistence, and terminal-render behavior. It also refactors PTY binding persistence to support refusal fences, durable fast-lane checks, rollback, generation tracking, origin metadata, and tracing. Tests cover diagnostic failures, persistence eligibility, durability, ownership, writer boundaries, tracing, and origin propagation. Priority: ➖ Normal Merge Risk: 🔵 Low · up to The persistence behavior is covered by substantial tests, but the writer-boundary guard can miss files when a source subtree is unreadable, and a few persistence metrics and design-document inconsistencies remain open. These are bounded concerns that should be addressed or accepted before merge. 🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
Full details: Docstring CoverageExplanation Docstring coverage is 25.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 35 functions across 31 files. (1 skipped: 1 unsupported.) Full details: Description checkExplanation The description explains the implementation, motivation, testing, measurements, and reliability scope, but it omits most required template sections, including the Linked Issue, Visual Proof, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections. Resolution Add the required template headings and complete each section. Include a real issue reference after “Fixes #”, or explain the applicable issue link. Add
✨ 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: 7
🧹 Nitpick comments (1)
config/scripts/terminal-render-phase-probe.mjs (1)
63-69: 🚀 Performance & Scalability | 🔵 Trivial | 🏗️ Heavy liftReduce repeated parsing in
terminal.write.Large reattach and relay writes can reach 100 KB or more. The synchronous
matchAlland four full-stringreplacepasses can then add material latency to the measured write. HoistingTextDecoderalone does not provide a consistent improvement. Replace the repeated scans with one pass that preserves the current CSI and OSC handling.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 21a4e697-37fa-4ef3-99d0-2c52be3fff90
📒 Files selected for processing (34)
config/scripts/capture-live-input-lag.mjsconfig/scripts/capture-running-orca-lag.mjsconfig/scripts/main-blocking-probe.mjsconfig/scripts/orca-main-inspector-connection.mjsconfig/scripts/persistence-call-probe.mjsconfig/scripts/terminal-render-phase-probe.mjsorca-live-lag-investigation.mdorca-persistence-design-assessment.mdorca-persistence-design-visual.htmlsrc/main/ipc/pty-daemon-spawn-session-identity.test.tssrc/main/ipc/pty-pane-claim-arbitration.test.tssrc/main/ipc/pty-pane-materialization-race.test.tssrc/main/ipc/pty-pane-reservation-settlement.test.tssrc/main/ipc/pty-runtime-ssh-binding-persistence.test.tssrc/main/ipc/pty/ipc/spawn-commit-persist.tssrc/main/ipc/pty/pane/stable-owner.tssrc/main/ipc/pty/runtime/spawn-commit.tssrc/main/persistence-flush-and-save-scheduling.test.tssrc/main/persistence/loading-store/__fixtures__/terminal-binding-writer-allowlist.txtsrc/main/persistence/loading-store/primary-state-writes.tssrc/main/persistence/loading-store/pty-binding-durability-records.test.tssrc/main/persistence/loading-store/pty-binding-durability-records.tssrc/main/persistence/loading-store/pty-binding-fast-lane.test.tssrc/main/persistence/loading-store/pty-binding-fast-lane.tssrc/main/persistence/loading-store/pty-binding-persistence.tssrc/main/persistence/loading-store/pty-binding-refusals.tssrc/main/persistence/loading-store/pty-binding-span.test.tssrc/main/persistence/loading-store/pty-binding-span.tssrc/main/persistence/loading-store/store-runtime-state.tssrc/main/persistence/loading-store/terminal-binding-writer-boundary.test.tssrc/main/persistence/loading-store/terminal-tab-pty-ownership.test.tssrc/main/persistence/loading-store/terminal-tab-pty-ownership.tssrc/main/ssh/ssh-relay-session-reconnect-incarnation.test.tssrc/main/ssh/ssh-relay-session.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.
There was a problem hiding this comment.
Important
The tab-row ownership rule added in terminal-tab-pty-ownership.ts does not actually match the renderer's rule, so the fast lane still never converges for a tab whose row names a dead PTY — details inline.
Reviewed changes
- Fast-lane predicate (
pty-binding-fast-lane.ts) — eleven named misses gate an early return inpersistPtyBindingthat skips the session clone and whole-state flush when the binding already matches memory and disk. - Refusal extraction (
pty-binding-refusals.ts) — the four pre-existing refusal fences moved verbatim and run before the predicate, preserving every existingfalse. - Tab-row ownership (
terminal-tab-pty-ownership.ts) — main stops overwriting a split tab's row when a sibling pane binds. - Per-pane durability records (
pty-binding-durability-records.ts) — replaces the too-coarse global generation comparison, paired with thewriteToDiskSynchash-match counter fix. - Span + origin tagging (
pty-binding-span.ts) — onepersistence.pty-bindingspan per call with a 200/window fast-lane budget; the spawn-commit and relay callers tagorigin. - Diagnostics — five inspector probe scripts under
config/scripts/and two design docs.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Tab-row ownership (
terminal-tab-pty-ownership.ts) — dropped the reclaim branch so main now rewrites the row only on null or replacement, matching the renderer'supdateTabPtyIdexactly; the design doc and ownership test were updated to the corrected rule. - Reattach origin classification (
pty-binding-span.ts,spawn-commit-persist.ts,stable-owner.ts) — an adopted relay session now tagsorigin: 'reattach'even without anisReattachflag, with a new test asserting the label. - Probe robustness (
main-blocking-probe.mjs,orca-main-inspector-connection.mjs) — socket closure now rejects outstanding and subsequent inspector requests, and IPC polls record failures, covered bylag-probe-failures.test.mjs. - Test cleanup (
persistence-flush-and-save-scheduling.test.ts) — added a sharedafterEachreset for the span sampler, dropping a now-redundant inlinemockRestore.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 4
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b5f65f82-6678-4b52-b2df-de920eaca153
📒 Files selected for processing (11)
config/scripts/lag-probe-failures.test.mjsconfig/scripts/main-blocking-probe.mjsconfig/scripts/orca-main-inspector-connection.mjsdocs/reference/orca-live-lag-investigation.mddocs/reference/orca-persistence-design-assessment.mddocs/reference/orca-persistence-design-visual.htmlsrc/main/ipc/pty-runtime-ssh-binding-persistence.test.tssrc/main/persistence-flush-and-save-scheduling.test.tssrc/main/persistence/loading-store/pty-binding-span.tssrc/main/persistence/loading-store/terminal-tab-pty-ownership.test.tssrc/main/persistence/loading-store/terminal-tab-pty-ownership.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- config/scripts/main-blocking-probe.mjs
- src/main/persistence/loading-store/terminal-tab-pty-ownership.ts
- config/scripts/orca-main-inspector-connection.mjs
- src/main/persistence-flush-and-save-scheduling.test.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.
There was a problem hiding this comment.
ℹ️ No critical issues — minor suggestions inline.
Reviewed changes
- Investigation artifacts removed —
3182bf7deletes the three investigation/design docs (orca-live-lag-investigation.md,orca-persistence-design-assessment.md,orca-persistence-design-visual.html) and repoints the ratchet-test and allowlist references off the deleted design doc. No code path changes; the fast lane, durability records, and tab-row ownership are untouched by this delta.
ℹ️ Nitpicks
- The PR description's
Docssection still listsorca-persistence-design-assessment.mdandorca-live-lag-investigation.md, and theSafetysection cites "the design doc's writer table" — all deleted by this commit. Worth editing the PR body so the merged record does not point at non-existent files.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
Some comments are outside the diff and can’t be posted inline due to GitHub limitations.
⚠️ Outside diff range comments (1)
src/main/persistence/loading-store/terminal-binding-writer-boundary.test.ts (1)
41-79: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winFail the scan when a source directory cannot be read.
collectSourceFilesreturns an empty list for areaddirSyncfailure. A nested failure can omit an entire subtree while the> 500assertion still passes. The ratchet can then miss a terminal-binding writer. Fail with the directory path instead of treating the unreadable subtree as empty.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: d50c9015-46b9-4720-98ff-b5fafc2ceef5
📒 Files selected for processing (3)
config/scripts/lag-probe-failures.test.mjssrc/main/persistence/loading-store/__fixtures__/terminal-binding-writer-allowlist.txtsrc/main/persistence/loading-store/terminal-binding-writer-boundary.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/main/persistence/loading-store/fixtures/terminal-binding-writer-allowlist.txt
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 new issues found.
Reviewed changes
- Lag-probe test runner —
config/scripts/lag-probe-failures.test.mjsnow importstestfromvitestinstead ofnode:test, so the repo's Vitest suite (config/vitest.config.tsincludesconfig/scripts/**/*.test.mjs) actually discovers and runs both probes. Verified locally: 2 tests pass, and no workflow invokesnode --teston this file, so no runner is orphaned. - Writer-boundary comments — the ratchet's JSDoc, failure message, and
terminal-binding-writer-allowlist.txtheader no longer point at the deleted "persistence writer audit"; they now describe the scanner as a syntax-only tripwire and namepersistence-flush-and-save-scheduling.test.tsfor behavioral durability coverage. This retires the prior review's dangling-reference nit.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — one minor doc nit inline.
Reviewed changes
- Global durability check replaces per-pane receipts —
persistPtyBinding's fast lane now requires only!quitFlushStarted && lastDurableWriteGeneration >= writeGeneration;pty-binding-durability-records.ts/.test.tsand theStoreRuntimeStatemap are deleted. Strictly more conservative (fewer skips, never less safe), and no dangling references remain. - Dirty-state regression retargeted — the fast-lane test now asserts the first reattachment after unrelated dirt flushes once and lands the dirty repo on disk, then later unchanged reattachments skip, across local/SSH/runtime partitions.
- Hash-match durability retained —
writeToDiskSyncstill advanceslastDurableWriteGenerationon the unforced hash-match return, which the global-only check depends on.
Verified locally: persistence-flush-and-save-scheduling.test.ts + pty-binding-fast-lane.test.ts → 40 passed.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
| * Why a reattach can be ineligible. `not_durable` alone means memory already matched but the | ||
| * binding was still waiting in the debounced save — the bucket that says whether skipping the | ||
| * flush on a durable match is enough, or the autosave itself has to move off the main thread. |
There was a problem hiding this comment.
With the fast lane back on the global durability check, not_durable also fires when unrelated state is unpersisted while the binding itself is unchanged and already on disk — so "the binding was still waiting in the debounced save" no longer describes what the miss means. Worth widening the comment to the state, since this bucket is read to reason about flush-vs-autosave cost.
| * Why a reattach can be ineligible. `not_durable` alone means memory already matched but the | |
| * binding was still waiting in the debounced save — the bucket that says whether skipping the | |
| * flush on a durable match is enough, or the autosave itself has to move off the main thread. | |
| * Why a reattach can be ineligible. `not_durable` alone means memory already matched but the | |
| * state holding the binding still had unflushed mutations — the bucket that says whether | |
| * skipping the flush on a durable match is enough, or the autosave itself has to move off the | |
| * main thread. |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
reconciledfast-lane miss removed — the predicate dropped itsexpectedBindingcross-check; it is unreachable while eligible, because theexpectedBindingrefusal already forces memory to equalexpectedBinding.incarnationIdand theincarnationmiss forces memory to equalargs.incarnationId, so any real mismatch still falls through to the write path.- Writer-boundary scanner deleted —
terminal-binding-writer-boundary.test.tsand its allowlist fixture are removed; both were added by this PR, so the net effect againstmainis zero, and the behavioral durability coverage they named (persistence-flush-and-save-scheduling.test.ts) is untouched. - Fast-lane test trimmed — the reconciled-incarnation case was removed from
pty-binding-fast-lane.test.ts; the matching-incarnation happy path is still covered, andpersistence-flush-and-save-scheduling.test.tsstill exercises the reconciled fence bump end to end.
Verified locally: pty-binding-fast-lane.test.ts + persistence-flush-and-save-scheduling.test.ts → 40 passed.
Approval is withheld only because the prior not_durable JSDoc nit on pty-binding-fast-lane.ts:7-9 remains open and is unchanged by this delta; that thread is the only outstanding item.
openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
Terminal pane reattachment currently clones the session and serializes the entire 9.2 MB app state even when the binding is already in place and durable. Add an early-return fast path that skips this work when all nine predicates hold: no split, binding matches in-memory and on-disk, incarnation matches, no tombstone, and generation counter proves durability. Includes one-line fix in `writeToDiskSync` to record hash-matched sync flushes as durable, so the fast path doesn't stay parked behind a stale generation. Adds `persistence.pty-binding` observability spans (local NDJSON, unsampled for mutations, budgeted for fast-lane hits) to measure eligibility rates before and after. Includes ratchet test to ensure every binding writer bumps the generation. Diagnostic tools and full investigation notes from September 7, 2026 capture that identified the 59–100 ms no-op binds and measured a real terminal keystroke queued 117 ms behind one such call.
Rapid rebinds of already-durable PTY bindings (e.g., remounting panes) were unnecessarily expensive because they cloned and flushed the entire document state every time. Detect when a binding hasn't changed since the last durable write and skip to return immediately, eliminating main-thread cost on that path.
Fresh spawns always flush, so a fast-lane rate over all calls is diluted by however many terminals the user opened. Each caller knows whether it is a spawn, a reattach, a split, or a relay reattach; pass that through as metadata and record it so the reattach hit rate can be read from the trace file. Never branched on.
…ane binds A tab row names one PTY, but a split tab holds several panes. The renderer keeps the row on the first pane and refuses to let later split-pane spawns steal it, since a remount reattaches the tab to whatever the row says. Main overwrote it with whichever pane was binding, and the renderer's next publish put it back, so every sibling reattach was a state change and could never take the fast lane. On the real profile that is 38% of panes. Rewrite the row only when it names nothing useful: null, the PTY this leaf is replacing, or a PTY no leaf holds. The fast-lane predicate compares against the same rule.
The global write generation is held back by any unrelated dirty state, causing bindings unchanged for minutes to appear unpersisted despite being on disk. Track per-pane durability to skip redundant flushes.
The durability section still described the global generation check as the whole story and claimed there was no binding durability cache. Record the measurement that motivated the per-pane record, and why retiring one needs no cooperation from other binding writers.
…e register Folds the findings from all related debug sessions into the live lag investigation: the persistence/main-thread work (P1-P11), host contention (H1-H5), git and subprocess load on main (G1-G8), renderer and terminal rendering (R1-R8), the terminal daemon session leak from the deleted debug-orca-perf-issue worktree (D1-D9), and the Cmd-J palette review (C1-C6). Keeps the measurement behind each claim, records what is fixed versus open, and restates what the 117 ms keystroke delay still does not explain.
47b6a12 to
bf3bf15
Compare

Reattaching a terminal can clone its workspace session and synchronously serialize the whole application state even when the same binding is already on disk. This PR skips that work when tab/leaf membership, PTY identity, incarnation, and whole-state durability already match.
The fast path runs after existing refusal checks and is disabled after final persistence starts. Changed or unpersisted bindings retain the clone, flush, and rollback path. Main's split-tab fallback PTY rule now matches the renderer, preventing sibling reattachments from repeatedly rewriting it. Sync hash-match flushes correctly advance durability bookkeeping; forced writes remain forced during asynchronous write races.
There is no per-pane durability cache. An unrelated dirty write conservatively makes the next binding flush; later unchanged bindings can skip once the whole state is durable. This keeps the optimization independent of cache receipts, session identity invalidation, and eviction. Sampled binding outcome/origin diagnostics and reusable lag probes remain. No new terminal registry or remote wire protocol is introduced. Investigation Markdown/HTML and temporary benchmark probes are excluded from the diff.
Measurements
Correction (September 13): the earlier 32-switch Electron cache A/B timings have been withdrawn. The test read the first ElectronApplication.evaluate argument as the supplied value, but that argument is the Electron module. As a result both variants retained the cache, and requested large-state padding was not installed. The run did observe session replacement invalidate receipts across 24 reattachments, but does not establish the cache's incremental performance benefit. The prior table is removed to prevent reuse of invalid timing claims.
The separate real-Store microbenchmark demonstrated a narrow cache benefit (20–23 ms around 9 MB) when unrelated state changes without replacing the session. Removing the cache deliberately gives up that benefit for simpler durability evidence. A valid app-level with/without-cache performance comparison remains unproven. The final cache-removal implementation passed separate persistence and restart/reveal checks described below.
Historical measurements motivating the overall PR: four unchanged reattachments on a roughly 9 MB profile took 59–100 ms each, including 48–84 ms in synchronous flush. These are historical baseline measurements, not a fresh before/after comparison of this final PR against main.
Validation
Astra medium source review: removed the repository-wide writer-count scanner/allowlist and redundant reconciliation miss. Existing refusal and mutation checks remain. Follow-up: 50 affected tests, node typecheck, lint, and formatting passed.
Broad local persistence/binding run: 93 files passed, 1,002 tests passed; one opt-in test skipped. Covered persistence failure/rollback and ordering, quit handling, refusals, incarnations, pane claims/materialization, and local/SSH/runtime binding partitions.
After extending the dirty-state regression to all three host partitions: scheduling and lag-probe follow-up 38 tests passed. Asserts the first dirty-state reattachment flushes, subsequent unchanged reattachment skips, and the dirty repo is actually on disk.
Rebuilt the final app without temporary instrumentation: 9 Electron E2E tests passed, including eight additional single/split warm/parked reveals, clean-restart input, stalled-daemon input recovery, replacement-daemon input, scrollback/cursor restoration, tab/worktree restore, titles, and idle-save frequency. Inspected the full hidden-renderer screenshot with both split shell panes restored.
Full
pnpm tc, targeted oxlint, formatting, and diff checks passed.Previous pushed head completed all applicable CI successfully; this simplification requires its own fresh CI result.
Reliability scope
Skipping persistence must not acknowledge changed/undurable bindings, bypass refusals, or let split siblings steal another pane's tab fallback.
The simplification changes only local persistence eligibility and removes cache state. Remote messages, field ownership, execution routing, and liveness policy are unchanged. Host-partition contracts are tested; live paired-server mixed-version journeys and Windows/WSL/folder performance were not measured in this local run. Broader ownership/migration assurance remains a separate workstream.