Repository navigation
perf(runtime): stop the expired-SSH-lease sweep from rescanning every tab layout - #18409
Conversation
|
Warning Review limit reachedNext included review available in 20 minutes. View limit detailsLimit details: You’ve used all 10 included reviews currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📥 CommitsReviewing files that changed from the base of the PR and between 666ad1ff94b632490888caac312581fc3bb33e7a and f371cb0. 📒 Files selected for processing (1)
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 7ed86a9 and 666ad1ff94b632490888caac312581fc3bb33e7a. 📒 Files selected for processing (5)
🚧 Files skipped from review as they are similar to previous changes (3)
Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains after this review. 📝 WalkthroughWalkthroughThe runtime now resolves terminal tab ownership by walking each tab’s layout tree with Merge Risk: ⚪ Minimal · up to This change optimizes expired SSH lease candidacy and terminal leaf-to-tab resolution while preserving the stated recovery behavior. Current coverage supports the changed paths, with no remaining merge-blocking risk identified. 🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (3 warnings)
✅ Passed checks (2 passed)
Full details: Out of Scope Changes checkExplanation The implementation is focused on expired SSH lease performance and terminal leaf lookup, but those changes are unrelated to the two directly linked issues, which require Linux support and Ctrl+Backspace handling. ✨ 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: 1e1ed8c6-a838-4555-8285-0fe8222fdbfe
📒 Files selected for processing (5)
src/main/runtime/expired-ssh-lease-pane-candidacy.test.tssrc/main/runtime/orca-runtime-reconcile-headless-mobile-session-browser-tabs.tssrc/main/runtime/terminal-leaf-membership-index.test.tssrc/main/runtime/terminal-leaf-membership-index.tssrc/main/runtime/workspace-session-terminal-membership-authority.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.
There was a problem hiding this comment.
Important
The new leaf-membership index can serve stale leafId → tabId mappings after a layout is mutated in place. persistPtyBinding grafts a leaf into an existing layout via layout.root = { … } without replacing the layout object, which the reference-equality revalidation does not detect — see the inline comment.
Reviewed changes
- Lease-sweep hoisting + predicate reorder —
workspaceSessionWorktreeHasRuntimeOwnedPtyCandidatecomputes the recoverable-tab set once per worktree and applies the 30s freshness gate before resolving leaf locations. - Shared eligibility predicate —
isRecentExpiredSshLeaseForWorktreeandresolveExpiredSshLeaseTabIdunify the qualified (leafId/ptyId) and unqualified lease readers so they can't drift apart. - Leaf-membership index — a
WeakMap-backedleafId → tabIdindex replaces the per-lookup tree walk infindTerminalTabIdForLeaf.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
This delta reworks the leaf-membership index so it can no longer serve a stale leafId → tabId mapping, resolving the prior review's one finding:
- Root-identity revalidation —
builtFromnow stores each layout'srootnode reference (TerminalPaneLayoutNode | null) instead of the layout object, soisIndexCurrentdetects the in-placelayout.rootgraft thatpersistPtyBindingperforms (split spawn and first-durable-root branches). - In-place-graft regression tests — new
persistence-pty-binding-leaf-membership-index.test.tsdrives the realStore.persistPtyBinding, plus two new index cases (in-place root replacement, empty-layout first root), and the walk-once counter now counts node reads rather than layout reads.
The fix leans on the documented invariant that "no writer mutates a layout node in place". I traced every main-process writer of terminalLayoutsByTabId to confirm it: the only in-place mutation is the layout.root = … reassignment in persistPtyBinding (now detected via root identity), while retirement (retireLeavesFromTerminalLayout, pruneTabGroupLayoutAfterRetirement), rebase (rebaseLayout), and scrollback-snapshot writers all produce new records or node objects that the WeakMap key or per-record Object.keys/size parity check catches.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
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: dd022a6d-5012-4a89-bc80-658fbf02a8dd
📒 Files selected for processing (3)
src/main/persistence-pty-binding-leaf-tab-resolution.test.tssrc/main/runtime/terminal-leaf-tab-resolution.test.tssrc/main/runtime/workspace-session-terminal-membership-authority.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 2 remain after this review.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Since the prior pullfrog review, the PR abandoned the cached leaf-membership index and replaced it with a stateless, allocation-free scan:
- Removed the
leafId → tabIdmembership index —terminal-leaf-membership-index.tsand itsWeakMap-backed cache are deleted, eliminating the only piece of mutable cross-call state and the entire staleness invariant the prior review flagged. findTerminalTabIdForLeafis now a pure tree scan — it delegates the per-tab walk to the existinglayoutContainsLeafIdhelper (terminal-layout-normalization.ts), preservingObject.keysrecord order and first-matching-tab semantics with no allocation.- Tests renamed and refocused — the
-leaf-membership-indexsuites became-leaf-tab-resolutionsuites; the in-place-subtree-replacement guard now asserts the resolver reads the tree as it is now rather than anything memoized.
The pivot is a strictly positive simplification: the index's revalidation already cost O(tabs) per read, so removing it loses nothing measurable while deleting ~200 lines and retiring the staleness question outright. The remaining wins (freshness gate first, per-worktree lease sweep) are pure and stateless.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
… tab layout The `runtime:syncWindowGraph` IPC handler is the most expensive thing the main process does: measured on a real session it costs 20.7 ms per call at 0.71 calls/sec, which is 1.47% of wall and ~17% of all main-thread JS. 76% of that sits in one subtree: `getHydrationTargets` -> `hasRuntimeOwnedPtyCandidate` -> `getRecentExpiredSshLease` -> `findTerminalTabIdForLeaf`. Three pieces of pure waste, none of which change an answer: 1. `getRecentExpiredSshLease` evaluated its cheapest and most selective filter LAST. `SSH_PANE_RECOVERY_GRACE_MS` is 30 s, so nearly every stored expired lease fails it — but only after the predicate had already resolved the lease's leaf to its current tab, which is the expensive part. The freshness and reattach-eligibility gates now run first; the predicate is otherwise identical and side-effect free, so the selected lease is unchanged. 2. The sweep ran once per tab. `workspaceSessionWorktreeHasRuntimeOwnedPtyCandidate` asked "does a recent expired lease name THIS tab" for every tab in a worktree, and each ask re-read and re-filtered the whole lease list. It now resolves the worktree's recoverable tab ids once, lazily, so a worktree whose first tab already owns a serve/SSH pty still never sweeps. 3. `findTerminalTabIdForLeaf` allocated a `Set` and walked a whole pane tree per tab to answer one leaf lookup. It now reads a leafId -> tabId index built once per layouts record and reused until a layout object is replaced, which keeps first-tab-wins ordering identical. Measured by replaying a real 414-worktree / 801-tab / 137-lease session: 2.51 ms -> 0.27 ms per publish for this subtree, a 9.3x cut. No user-facing trade-off: same leases selected, same tabs reported recoverable, same SSH pane recovery affordance.
persistPtyBinding grafts a leaf by assigning `layout.root` on the SAME layout object inside the SAME layouts record, so the layout-identity revalidation kept serving an index blind to the grafted leaf and findTerminalTabIdForLeaf answered `undefined` where the pre-index linear scan answered the tab. That fed the SSH reattach fence (restoreReattachedPtyRuntime) and the expired-lease pane recovery resolver, both of which then fall back to the frozen lease tabId. Membership is a pure function of the root tree and no writer mutates a node in place, so root identity is the exact revalidation key — same O(tabs) pointer compare, no new cap, cadence or staleness window.
…rship index Fix #3 of this PR cached a leafId -> tabId map per layouts record and revalidated it by comparing every root reference on every read. It was the only mutable cross-call state in the change, the only piece carrying a staleness invariant, and it had already needed one follow-up fix (1c23c54) after a layout-identity key turned out to be blind to `persistPtyBinding`'s in-place `layout.root` graft. The index was never what produced the measured win. After fix #1 moves the freshness gate first, the reporter's replay never calls `findTerminalTabIdForLeaf` at all — every stored expired lease is older than the 30 s recovery grace, so the entire 24.9 ms -> 0.9 ms comes from fixes #1 and #2, both of which are unchanged. `findTerminalTabIdForLeaf` is now an allocation-free scan over the existing `layoutContainsLeafId`, which short-circuits on the first matching leaf instead of materialising a Set per tab. Same answers, same first-tab-in-record-order semantics, no revalidation key, nothing for a writer to invalidate. Re-measured on the same 414-worktree / 801-tab / 137-lease replay (process.cpuUsage deltas, median of 3; wall clock is useless on this box): scenario main index scan all leases stale (replay) 24.86 0.87 0.88 ms/publish one lease inside the grace 24.31 1.08 1.04 ms/publish all 137 inside the grace 18.04 3.71 4.31 ms/publish The measured win is unchanged. Only the synthetic worst case — every one of 137 leases expiring inside the same 30 s window — pays for the cache's absence, and even there the two ranges overlap because the index's own revalidation is O(tabs) per lookup. Removes 208 net lines. `terminal-leaf-tab-resolution.test.ts` keeps the parity cases and adds the guard the cache needed: a subtree replaced in place after an earlier read must be visible to the next one. That test fails against the index.
a6679b9 to
666ad1f
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
'Allocation-free' overstated it — Object.keys does allocate one key array. A guarded for...in trades that for a hasOwn call per tab and measures slower, so record the reason the next reader does not re-litigate it.
666ad1f to
f371cb0
Compare
… tab layout (stablyai#18409) * perf(runtime): stop the expired-SSH-lease sweep from rescanning every tab layout The `runtime:syncWindowGraph` IPC handler is the most expensive thing the main process does: measured on a real session it costs 20.7 ms per call at 0.71 calls/sec, which is 1.47% of wall and ~17% of all main-thread JS. 76% of that sits in one subtree: `getHydrationTargets` -> `hasRuntimeOwnedPtyCandidate` -> `getRecentExpiredSshLease` -> `findTerminalTabIdForLeaf`. Three pieces of pure waste, none of which change an answer: 1. `getRecentExpiredSshLease` evaluated its cheapest and most selective filter LAST. `SSH_PANE_RECOVERY_GRACE_MS` is 30 s, so nearly every stored expired lease fails it — but only after the predicate had already resolved the lease's leaf to its current tab, which is the expensive part. The freshness and reattach-eligibility gates now run first; the predicate is otherwise identical and side-effect free, so the selected lease is unchanged. 2. The sweep ran once per tab. `workspaceSessionWorktreeHasRuntimeOwnedPtyCandidate` asked "does a recent expired lease name THIS tab" for every tab in a worktree, and each ask re-read and re-filtered the whole lease list. It now resolves the worktree's recoverable tab ids once, lazily, so a worktree whose first tab already owns a serve/SSH pty still never sweeps. 3. `findTerminalTabIdForLeaf` allocated a `Set` and walked a whole pane tree per tab to answer one leaf lookup. It now reads a leafId -> tabId index built once per layouts record and reused until a layout object is replaced, which keeps first-tab-wins ordering identical. Measured by replaying a real 414-worktree / 801-tab / 137-lease session: 2.51 ms -> 0.27 ms per publish for this subtree, a 9.3x cut. No user-facing trade-off: same leases selected, same tabs reported recoverable, same SSH pane recovery affordance. * fix(runtime): revalidate the leaf membership index on root identity persistPtyBinding grafts a leaf by assigning `layout.root` on the SAME layout object inside the SAME layouts record, so the layout-identity revalidation kept serving an index blind to the grafted leaf and findTerminalTabIdForLeaf answered `undefined` where the pre-index linear scan answered the tab. That fed the SSH reattach fence (restoreReattachedPtyRuntime) and the expired-lease pane recovery resolver, both of which then fall back to the frozen lease tabId. Membership is a pure function of the root tree and no writer mutates a node in place, so root identity is the exact revalidation key — same O(tabs) pointer compare, no new cap, cadence or staleness window. * perf(runtime): resolve a leaf's tab by scan instead of a cached membership index Fix stablyai#3 of this PR cached a leafId -> tabId map per layouts record and revalidated it by comparing every root reference on every read. It was the only mutable cross-call state in the change, the only piece carrying a staleness invariant, and it had already needed one follow-up fix (1c23c54) after a layout-identity key turned out to be blind to `persistPtyBinding`'s in-place `layout.root` graft. The index was never what produced the measured win. After fix stablyai#1 moves the freshness gate first, the reporter's replay never calls `findTerminalTabIdForLeaf` at all — every stored expired lease is older than the 30 s recovery grace, so the entire 24.9 ms -> 0.9 ms comes from fixes stablyai#1 and stablyai#2, both of which are unchanged. `findTerminalTabIdForLeaf` is now an allocation-free scan over the existing `layoutContainsLeafId`, which short-circuits on the first matching leaf instead of materialising a Set per tab. Same answers, same first-tab-in-record-order semantics, no revalidation key, nothing for a writer to invalidate. Re-measured on the same 414-worktree / 801-tab / 137-lease replay (process.cpuUsage deltas, median of 3; wall clock is useless on this box): scenario main index scan all leases stale (replay) 24.86 0.87 0.88 ms/publish one lease inside the grace 24.31 1.08 1.04 ms/publish all 137 inside the grace 18.04 3.71 4.31 ms/publish The measured win is unchanged. Only the synthetic worst case — every one of 137 leases expiring inside the same 30 s window — pays for the cache's absence, and even there the two ranges overlap because the index's own revalidation is O(tabs) per lookup. Removes 208 net lines. `terminal-leaf-tab-resolution.test.ts` keeps the parity cases and adds the guard the cache needed: a subtree replaced in place after an earlier read must be visible to the next one. That test fails against the index. * docs(runtime): say why the leaf scan keeps Object.keys 'Allocation-free' overstated it — Object.keys does allocate one key array. A guarded for...in trades that for a hasOwn call per tab and measures slower, so record the reason the next reader does not re-litigate it.

ELI5
Every time the UI tells the main process "here is my current window layout", the main process asked one question over and over: "is any of these tabs a leftover SSH pane the user could still reconnect to?"
To answer it, it looked at every stored SSH lease, and for each one it went hunting through every single terminal tab's pane tree to work out where that pane lives now — building a throwaway
Setfor each tab along the way. Then, at the very end, it checked "…and is this lease less than 30 seconds old?" — and threw almost all of them away, because they weren't.So it did the expensive search first and the cheap disqualifying check last. And it repeated the whole thing once per tab.
Three fixes, none of which change the answer:
Setof every leaf in every tab and then testing it.Why it matters
runtime:syncWindowGraphis the single most expensive thing Orca's main process does. Measured live on a real session with the Chrome DevTools Protocol profiler attached to the packaged app:runtime:syncWindowGraphcall ratefindTerminalTabIdForLeafaloneEvery one of those 20.7 ms is a millisecond the main process is not answering IPC, spawning a terminal, or servicing a keystroke.
Measurement
Replaying the reporter's real persisted session shape (414 worktrees, 801 terminal tabs, 137 SSH leases) through the before/after predicate. Wall clock is meaningless on the measuring box, so these are
process.cpuUsage()user+system deltas per publish, median of 3 runs:mainThe whole win comes from fixes #1 and #2, both of which are pure and stateless. In the reporter's replay every stored expired lease is minutes old, so once the freshness gate moves first
findTerminalTabIdForLeafis never reached at all.An earlier revision of this PR also added a cached
leafId → tabIdindex behind that lookup. It has been removed: it was the only mutable cross-call state in the change, it carried the only staleness invariant, and it did not pay for itself. Measured against the scan that replaced it (same shape, same method):The first two are indistinguishable, and even the synthetic worst case's ranges overlap across runs — because the index's own revalidation had to compare every root reference on every read, which is O(tabs) per lookup, the same order as the scan it was avoiding. Removing it drops 208 net lines and the entire staleness question.
Deterministic regression guards, not timing assertions:
Correctness
&&order cannot change the result — only the cost. The selected lease is identical.getRecentExpiredSshLease(worktreeId, tabId, undefined)answers "does an eligible lease resolve to this tab". Collecting all such tab ids in one pass and testing membership is the same predicate, and the sweep stays lazy so the early-exit path never pays for it.findTerminalTabIdForLeafkeeps its exact semantics: it walks the layouts record inObject.keysorder and returns the first tab whose tree holds the leaf, which is what the originalObject.entriesloop did. The only change is that it delegates the per-tab tree walk to the existinglayoutContainsLeafId, which short-circuits instead of collecting every leaf into aSetfirst.persistPtyBindinggrafts a leaf by assigning into a layout object that is already inside the layouts record (both the empty-layout and split-spawn branches), andrebaseWorkspaceSessionTerminalMembershipcopies the record while sharing most layout objects — a memoized answer would need a revalidation key covering every one of those shapes. Pinned byterminal-leaf-tab-resolution.test.ts(in-place subtree replacement is visible to the next read) and bypersistence-pty-binding-leaf-tab-resolution.test.ts, which drives the realStore.persistPtyBindinggraft end to end.Negative user-facing trade-offs
None. This deletes work; it does not trade freshness, accuracy or coverage for speed.
recoverTerminalPaneaffordance is unchanged.Test plan
src/main/runtime/terminal-leaf-tab-resolution.test.ts— 4 tests overfindTerminalTabIdForLeaf: split-tree resolution, first-tab-in-record-order on a contested leaf, miss/empty/undefined parity, and the in-place-subtree-replacement guard (verified failing against the cached index).src/main/persistence-pty-binding-leaf-tab-resolution.test.ts— 2 tests driving the realStore.persistPtyBindinggraft (empty-layout first root, split spawn) and assertingfindTerminalTabIdForLeafresolves the grafted leaf.src/main/runtime/expired-ssh-lease-pane-candidacy.test.ts— 2 new tests; verified to fail without fix Fix Ctrl+Backspace not deleting word in terminal #2.ssh-reattach-pane-cardinality.test.ts,orca-runtime-terminal-retirement-host-partition.test.ts,orca-runtime-terminal-split-authority.test.ts.pnpm tcclean;oxlint+oxfmtclean on all changed files;check:code-quality:changedreports 0 new findings.