Skip to content

perf(runtime): stop the expired-SSH-lease sweep from rescanning every tab layout - #18409

Merged
nwparker merged 4 commits into
mainfrom
perf/leaf-tab-index
Sep 4, 2026
Merged

nwparker merged 4 commits into
mainfrom
perf/leaf-tab-index

Conversation

@nwparker

@nwparker nwparker commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​195 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​195
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​76 $\color{#cf222e}{\Huge{\mathbf{−}}}$​30 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​46

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 Set for 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:

  1. Check the cheap thing first. The 30-second freshness gate now runs before the expensive pane hunt.
  2. Ask once per worktree, not once per tab. Same question, same answer — just not asked 800 times.
  3. Stop allocating to answer a lookup. The pane hunt itself is now an allocation-free scan that short-circuits on the first matching leaf, instead of materialising a Set of every leaf in every tab and then testing it.

Why it matters

runtime:syncWindowGraph is 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:

measured
runtime:syncWindowGraph call rate 0.71 calls/sec
main-thread time per call 20.7 ms
share of total wall-clock CPU 1.47%
share of all main-thread JS ~17%
share of that spent in this subtree 76%
findTerminalTabIdForLeaf alone 0.70% self time — the #1 JS function in the main process

Every 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:

scenario main this PR
every expired lease older than the 30 s grace — the reporter's replay 24.86 ms 0.88 ms (28x)
one lease inside the grace (a pane disconnected seconds ago) 24.31 ms 1.04 ms (23x)
all 137 leases inside the grace — synthetic worst case 18.04 ms 4.31 ms (4.2x)

The 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 findTerminalTabIdForLeaf is never reached at all.

An earlier revision of this PR also added a cached leafId → tabId index 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):

scenario cached index allocation-free scan
reporter's replay 0.87 ms 0.88 ms
one lease inside the grace 1.08 ms 1.04 ms
all 137 inside the grace 3.71 ms 4.31 ms

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:

expired-ssh-lease-pane-candidacy.test.ts   counts lease sweeps across 8 tabs
  without fix #2:  AssertionError: expected 8 to be 1
  with fix #2:     1 sweep

terminal-leaf-tab-resolution.test.ts       "reflects a subtree replaced in place
                                            after an earlier read"
  against the cached index:  AssertionError: expected undefined to be 'tab-a'
  against the scan:          passes

Correctness

  • Predicate reordering is safe: every clause is a pure boolean with no side effects, so && order cannot change the result — only the cost. The selected lease is identical.
  • Hoisting is safe: 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.
  • findTerminalTabIdForLeaf keeps its exact semantics: it walks the layouts record in Object.keys order and returns the first tab whose tree holds the leaf, which is what the original Object.entries loop did. The only change is that it delegates the per-tab tree walk to the existing layoutContainsLeafId, which short-circuits instead of collecting every leaf into a Set first.
  • It holds no state between calls, so there is nothing that can go stale. This matters because persistPtyBinding grafts a leaf by assigning into a layout object that is already inside the layouts record (both the empty-layout and split-spawn branches), and rebaseWorkspaceSessionTerminalMembership copies the record while sharing most layout objects — a memoized answer would need a revalidation key covering every one of those shapes. Pinned by terminal-leaf-tab-resolution.test.ts (in-place subtree replacement is visible to the next read) and by persistence-pty-binding-leaf-tab-resolution.test.ts, which drives the real Store.persistPtyBinding graft end to end.
  • Both readers now share one eligibility predicate and one tab resolver, so the qualified and unqualified paths cannot drift apart.

Negative user-facing trade-offs

None. This deletes work; it does not trade freshness, accuracy or coverage for speed.

  • Same leases are selected, in the same priority order (eligible orphan still beats a superseded predecessor — covered by the existing test).
  • Same tabs are reported recoverable, so the paired-viewer recoverTerminalPane affordance is unchanged.
  • No cadence, cap, threshold, sampling or debounce was introduced or altered.
  • Nothing is cached at all. The earlier revision's "the index revalidates on every read" caveat is gone with the index; every lookup reads the layout tree that is there now.

Test plan

  • src/main/runtime/terminal-leaf-tab-resolution.test.ts — 4 tests over findTerminalTabIdForLeaf: 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 real Store.persistPtyBinding graft (empty-layout first root, split spawn) and asserting findTerminalTabIdForLeaf resolves 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.
  • Also green: ssh-reattach-pane-cardinality.test.ts, orca-runtime-terminal-retirement-host-partition.test.ts, orca-runtime-terminal-split-authority.test.ts.
  • pnpm tc clean; oxlint + oxfmt clean on all changed files; check:code-quality:changed reports 0 new findings.

@coderabbitai

coderabbitai Bot commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

Next included review available in 20 minutes.

Check out review usage here.

View limit details

Limit 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.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 605aa668-5235-4111-9556-231ca3bea2eb

📥 Commits

Reviewing files that changed from the base of the PR and between 666ad1ff94b632490888caac312581fc3bb33e7a and f371cb0.

📒 Files selected for processing (1)
  • src/main/runtime/workspace-session-terminal-membership-authority.ts

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: b2751338-e2f7-4d30-b3ab-d9aa475428f9

📥 Commits

Reviewing files that changed from the base of the PR and between 7ed86a9 and 666ad1ff94b632490888caac312581fc3bb33e7a.

📒 Files selected for processing (5)
  • src/main/persistence-pty-binding-leaf-tab-resolution.test.ts
  • src/main/runtime/expired-ssh-lease-pane-candidacy.test.ts
  • src/main/runtime/orca-runtime-reconcile-headless-mobile-session-browser-tabs.ts
  • src/main/runtime/terminal-leaf-tab-resolution.test.ts
  • src/main/runtime/workspace-session-terminal-membership-authority.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/persistence-pty-binding-leaf-tab-resolution.test.ts
  • src/main/runtime/orca-runtime-reconcile-headless-mobile-session-browser-tabs.ts
  • src/main/runtime/expired-ssh-lease-pane-candidacy.test.ts

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


📝 Walkthrough

Walkthrough

The runtime now resolves terminal tab ownership by walking each tab’s layout tree with layoutContainsLeafId. Persistence and runtime tests cover grafted leaves, split trees, duplicate ownership, missing state, and in-place layout changes. Expired SSH lease candidacy now collects eligible tab IDs in one worktree-wide sweep and reuses the set across tabs. Tests cover single-sweep behavior and non-matching leases.

Merge Risk: ⚪ Minimal · up to 666ad

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)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The changes do not address linked issue #1 or #2. They do not change the Linux terminal renderer or font fallbacks, and they do not implement Ctrl+Backspace handling through sendKeyInput. Link this PR to the correct performance issue, or implement the requirements from issues #1 and #2, including Linux renderer and font changes and Ctrl+Backspace handling while preserving Backspace and Ctrl+W behavior.
Out of Scope Changes check ⚠️ Warning 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+Backspa… Remove the unrelated issue links and associate the PR with the appropriate performance issue, or change the implementation to match the scope of linked issues #1 and #2.
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary performance change: preventing the expired SSH lease sweep from rescanning every tab layout.
Description check ✅ Passed The description provides a detailed ELI5 explanation, rationale, implementation summary, performance measurements, correctness notes, and test plan. It does not follow all template headings and omits …
Full details: Out of Scope Changes check

Explanation

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 💡
  • 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: 1e1ed8c6-a838-4555-8285-0fe8222fdbfe

📥 Commits

Reviewing files that changed from the base of the PR and between f70f580 and 344addc.

📒 Files selected for processing (5)
  • src/main/runtime/expired-ssh-lease-pane-candidacy.test.ts
  • src/main/runtime/orca-runtime-reconcile-headless-mobile-session-browser-tabs.ts
  • src/main/runtime/terminal-leaf-membership-index.test.ts
  • src/main/runtime/terminal-leaf-membership-index.ts
  • src/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.

@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

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 — workspaceSessionWorktreeHasRuntimeOwnedPtyCandidate computes the recoverable-tab set once per worktree and applies the 30s freshness gate before resolving leaf locations.
  • Shared eligibility predicate — isRecentExpiredSshLeaseForWorktree and resolveExpiredSshLeaseTabId unify the qualified (leafId/ptyId) and unqualified lease readers so they can't drift apart.
  • Leaf-membership index — a WeakMap-backed leafId → tabId index replaces the per-lookup tree walk in findTerminalTabIdForLeaf.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | 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

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 — builtFrom now stores each layout's root node reference (TerminalPaneLayoutNode | null) instead of the layout object, so isIndexCurrent detects the in-place layout.root graft that persistPtyBinding performs (split spawn and first-durable-root branches).
  • In-place-graft regression tests — new persistence-pty-binding-leaf-membership-index.test.ts drives the real Store.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.

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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: dd022a6d-5012-4a89-bc80-658fbf02a8dd

📥 Commits

Reviewing files that changed from the base of the PR and between 1c23c54 and a6679b9.

📒 Files selected for processing (3)
  • src/main/persistence-pty-binding-leaf-tab-resolution.test.ts
  • src/main/runtime/terminal-leaf-tab-resolution.test.ts
  • src/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.

@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

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 → tabId membership index — terminal-leaf-membership-index.ts and its WeakMap-backed cache are deleted, eliminating the only piece of mutable cross-call state and the entire staleness invariant the prior review flagged.
  • findTerminalTabIdForLeaf is now a pure tree scan — it delegates the per-tab walk to the existing layoutContainsLeafId helper (terminal-layout-normalization.ts), preserving Object.keys record order and first-matching-tab semantics with no allocation.
  • Tests renamed and refocused — the -leaf-membership-index suites became -leaf-tab-resolution suites; 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.

Pullfrog  | View workflow run | Using 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.
@nwparker
nwparker force-pushed the perf/leaf-tab-index branch from a6679b9 to 666ad1f Compare September 4, 2026 03:44
@coderabbitai

coderabbitai Bot commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

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.
@nwparker
nwparker force-pushed the perf/leaf-tab-index branch from 666ad1f to f371cb0 Compare September 4, 2026 03:49
@nwparker
nwparker merged commit 6c4797c into main Sep 4, 2026
27 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… 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.
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