Repository navigation
fix(runtime): skip unchanged worktrees when publishing mobile session snapshots - #12207
Conversation
buildMobileSessionTabSnapshots consults its per-worktree cache after building the content, so a republish saves the fanout but none of the work. With 300 worktrees, an unchanged republish still does 601 units of per-worktree work, and a single changed worktree does 602. Publication is keyed on agentStatusByPaneKey/agentStatusEpoch, so this runs on every agent status tick. On a multi-client runtime host with 381 worktrees this allocated ~350 MB/min and rode the renderer into repeated 4 GB OOMs. Tests are marked it.fails so the branch stays green; drop .fails when the build loop skips worktrees whose inputs are unchanged.
…orktree Every per-worktree builder in buildMobileSessionTabSnapshots took the whole AppState, so a worktree's real input set was the transitive closure of seven helpers and could not be memoized safely. Introduce MobileSessionWorktreeInputs — built once per worktree — and thread it through the group projection and the terminal/markdown/file/browser tab builders so the compiler proves the input set. Tab- and pane-keyed slices are narrowed to this worktree's tab ids, file ids, browser workspace/page ids, and pane keys; agent statuses are bucketed per worktree once per publication via a tab-id index. No behavior change. Dropping AppState from the projection path also removes the second per-worktree read of browserTabsByWorktree, so the publication-cost counter falls from 601 to 1 per publication and its two cases now pass.
… content buildMobileSessionTabSnapshots consulted its per-worktree cache only after building that worktree's three Maps, group projection, and full tab array, so the cache suppressed the fanout but none of the computation. Every agent-status tick therefore rebuilt every worktree, which drove sustained 4 GB renderer working sets on a host holding 381 worktrees. Cache MobileSessionWorktreeInputs alongside each snapshot and reuse the snapshot when every input field is reference-equal, before any intermediate structure is allocated. Worktrees with a mounted TerminalPane always rebuild: their live DOM/PaneManager state is invisible to store references. Absent per-worktree slices now resolve to shared empty values so an empty worktree can compare equal to its last publication. jsonContentEquals stays as the backstop on the rebuild path for inputs that churn by reference without changing output. With 300 worktrees, per-worktree content builds go from 300 to 0 on an unchanged republish and from 300 to 1 when one worktree changes.
📝 WalkthroughWalkthroughMobile session snapshot generation now prepares scoped per-worktree inputs instead of passing global 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1🛠️ Fix failing CI checks 💡
📝 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
🧹 Nitpick comments (1)
src/renderer/src/runtime/sync-runtime-graph.ts (1)
997-1038: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMake the exhaustiveness claim compiler-enforced, or correct the docstring.
The
&&chain covers all 24 fields ofMobileSessionWorktreeInputstoday, so there is no current defect. But the docstring states that a missed input is a compile error. Nothing enforces that. A field added toMobileSessionWorktreeInputslater compiles cleanly here and publishes a stale snapshot to paired clients.Key the comparison by field so the type system rejects an omission.
♻️ Proposed refactor for compiler-enforced field coverage
function canReuseMobileSessionSnapshot( previous: MobileSessionWorktreeInputs, next: MobileSessionWorktreeInputs ): boolean { - return ( - // Why: live DOM/PaneManager state is invisible to store references, so a mounted surface always rebuilds. - !previous.hasMountedTerminalSurface && - !next.hasMountedTerminalSurface && - previous.worktreeId === next.worktreeId && - previous.terminalTabs === next.terminalTabs && - previous.browserWorkspaces === next.browserWorkspaces && - previous.unifiedTabs === next.unifiedTabs && - previous.groups === next.groups && - previous.tabBarOrder === next.tabBarOrder && - previous.activeGroupId === next.activeGroupId && - previous.tabGroupLayout === next.tabGroupLayout && - previous.openFilesById === next.openFilesById && - previous.openFileIds === next.openFileIds && - previous.activeEditorFileId === next.activeEditorFileId && - previous.activeEditorTabType === next.activeEditorTabType && - previous.activeTerminalTabId === next.activeTerminalTabId && - previous.activeBrowserWorkspaceId === next.activeBrowserWorkspaceId && - previous.generatedTitlesEnabled === next.generatedTitlesEnabled && - previous.terminalTheme === next.terminalTheme && - narrowedEntriesEqual(previous.terminalLayoutByTabId, next.terminalLayoutByTabId) && - narrowedEntriesEqual(previous.paneTitlesByTabId, next.paneTitlesByTabId) && - narrowedEntriesEqual(previous.launchDraftByTabId, next.launchDraftByTabId) && - narrowedEntriesEqual(previous.agentStatusByPaneKey, next.agentStatusByPaneKey) && - narrowedEntriesEqual(previous.editorDraftVersionByFileId, next.editorDraftVersionByFileId) && - narrowedEntriesEqual(previous.pagesByBrowserWorkspaceId, next.pagesByBrowserWorkspaceId) && - narrowedEntriesEqual( - previous.certificateFailureByBrowserPageId, - next.certificateFailureByBrowserPageId - ) - ) + // A missing key here is a compile error, so a new input cannot silently reuse a stale snapshot. + const equalByField: Record<keyof MobileSessionWorktreeInputs, boolean> = { + // Why: live DOM/PaneManager state is invisible to store references, so a mounted surface always rebuilds. + hasMountedTerminalSurface: !previous.hasMountedTerminalSurface && !next.hasMountedTerminalSurface, + worktreeId: previous.worktreeId === next.worktreeId, + terminalTabs: previous.terminalTabs === next.terminalTabs, + browserWorkspaces: previous.browserWorkspaces === next.browserWorkspaces, + unifiedTabs: previous.unifiedTabs === next.unifiedTabs, + groups: previous.groups === next.groups, + tabBarOrder: previous.tabBarOrder === next.tabBarOrder, + activeGroupId: previous.activeGroupId === next.activeGroupId, + tabGroupLayout: previous.tabGroupLayout === next.tabGroupLayout, + openFilesById: previous.openFilesById === next.openFilesById, + openFileIds: previous.openFileIds === next.openFileIds, + activeEditorFileId: previous.activeEditorFileId === next.activeEditorFileId, + activeEditorTabType: previous.activeEditorTabType === next.activeEditorTabType, + activeTerminalTabId: previous.activeTerminalTabId === next.activeTerminalTabId, + activeBrowserWorkspaceId: previous.activeBrowserWorkspaceId === next.activeBrowserWorkspaceId, + generatedTitlesEnabled: previous.generatedTitlesEnabled === next.generatedTitlesEnabled, + terminalTheme: previous.terminalTheme === next.terminalTheme, + terminalLayoutByTabId: narrowedEntriesEqual( + previous.terminalLayoutByTabId, + next.terminalLayoutByTabId + ), + paneTitlesByTabId: narrowedEntriesEqual(previous.paneTitlesByTabId, next.paneTitlesByTabId), + launchDraftByTabId: narrowedEntriesEqual(previous.launchDraftByTabId, next.launchDraftByTabId), + agentStatusByPaneKey: narrowedEntriesEqual( + previous.agentStatusByPaneKey, + next.agentStatusByPaneKey + ), + editorDraftVersionByFileId: narrowedEntriesEqual( + previous.editorDraftVersionByFileId, + next.editorDraftVersionByFileId + ), + pagesByBrowserWorkspaceId: narrowedEntriesEqual( + previous.pagesByBrowserWorkspaceId, + next.pagesByBrowserWorkspaceId + ), + certificateFailureByBrowserPageId: narrowedEntriesEqual( + previous.certificateFailureByBrowserPageId, + next.certificateFailureByBrowserPageId + ) + } + return Object.values(equalByField).every(Boolean) }
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 4ce81134-24dd-407c-9532-cde591bd4906
📒 Files selected for processing (2)
src/renderer/src/runtime/sync-runtime-graph-publication-cost.test.tssrc/renderer/src/runtime/sync-runtime-graph.ts
| it('rebuilds only the worktrees whose inputs changed', () => { | ||
| const WORKTREES = 300 | ||
| const { state, reads, resetReads } = makeCountingState(WORKTREES) | ||
|
|
||
| buildMobileSessionTabSnapshots(state) | ||
| resetReads() | ||
|
|
||
| // One worktree's tabs change — the other 299 are untouched. | ||
| const next = { | ||
| ...state, | ||
| tabsByWorktree: { | ||
| ...state.tabsByWorktree, | ||
| 'repo::/wt-7': [ | ||
| { id: 'term-7', title: 'Agent 7 (done)', customTitle: null, type: 'terminal' } | ||
| ] | ||
| }, | ||
| get browserTabsByWorktree() { | ||
| return (state as unknown as { browserTabsByWorktree: unknown }).browserTabsByWorktree | ||
| } | ||
| } as unknown as AppState | ||
|
|
||
| buildMobileSessionTabSnapshots(next) | ||
|
|
||
| expect(reads()).toBeLessThan(WORKTREES / 10) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Measure tab-change rebuilds directly.
browserTabsByWorktree is read once before the worktree loop. Line 169 therefore passes even if a tab change rebuilds all 300 worktree snapshots.
Add a per-tab content-read counter and snapshot-reference assertions, as in the agent-status test. Verify that only repo::/wt-7 rebuilds after the tab change.
#12383) The per-worktree rebuild memo from #12207 refused to skip any worktree with a registered TerminalPane, because builders read live PaneManager/DOM state the memo could not witness. Hidden worktrees stay mounted (8 parked + 12 retained by default, unbounded with terminalHiddenViewParking off), so that set rebuilt on every publication — on the always-on hosts the memo targeted, ~20 worktrees paid the full content build plus the new inputs build and deep compare every tick. Capture the live reads instead: snapshot pane leaf ids, the live active leaf, the serialized pane tree, and per-pane numeric/pty bindings once per publication into MountedTerminalSurfaceCapture, compare captures by value in the memo, and have the builders read only the capture. Live state outside the capture is now unrepresentable in a builder, so the skip stays provably complete — and a mounted worktree whose panes did not change reuses its snapshot like any other.
… snapshots (stablyai#12207) * test(runtime): prove mobile session publication rebuilds every worktree buildMobileSessionTabSnapshots consults its per-worktree cache after building the content, so a republish saves the fanout but none of the work. With 300 worktrees, an unchanged republish still does 601 units of per-worktree work, and a single changed worktree does 602. Publication is keyed on agentStatusByPaneKey/agentStatusEpoch, so this runs on every agent status tick. On a multi-client runtime host with 381 worktrees this allocated ~350 MB/min and rode the renderer into repeated 4 GB OOMs. Tests are marked it.fails so the branch stays green; drop .fails when the build loop skips worktrees whose inputs are unchanged. * refactor(runtime): make mobile session snapshot inputs explicit per worktree Every per-worktree builder in buildMobileSessionTabSnapshots took the whole AppState, so a worktree's real input set was the transitive closure of seven helpers and could not be memoized safely. Introduce MobileSessionWorktreeInputs — built once per worktree — and thread it through the group projection and the terminal/markdown/file/browser tab builders so the compiler proves the input set. Tab- and pane-keyed slices are narrowed to this worktree's tab ids, file ids, browser workspace/page ids, and pane keys; agent statuses are bucketed per worktree once per publication via a tab-id index. No behavior change. Dropping AppState from the projection path also removes the second per-worktree read of browserTabsByWorktree, so the publication-cost counter falls from 601 to 1 per publication and its two cases now pass. * fix(runtime): skip unchanged worktrees before building mobile session content buildMobileSessionTabSnapshots consulted its per-worktree cache only after building that worktree's three Maps, group projection, and full tab array, so the cache suppressed the fanout but none of the computation. Every agent-status tick therefore rebuilt every worktree, which drove sustained 4 GB renderer working sets on a host holding 381 worktrees. Cache MobileSessionWorktreeInputs alongside each snapshot and reuse the snapshot when every input field is reference-equal, before any intermediate structure is allocated. Worktrees with a mounted TerminalPane always rebuild: their live DOM/PaneManager state is invisible to store references. Absent per-worktree slices now resolve to shared empty values so an empty worktree can compare equal to its last publication. jsonContentEquals stays as the backstop on the rebuild path for inputs that churn by reference without changing output. With 300 worktrees, per-worktree content builds go from 300 to 0 on an unchanged republish and from 300 to 1 when one worktree changes. * test(runtime): cover agent status publication cost --------- Co-authored-by: Brennan Benson <[email protected]>
stablyai#12383) The per-worktree rebuild memo from stablyai#12207 refused to skip any worktree with a registered TerminalPane, because builders read live PaneManager/DOM state the memo could not witness. Hidden worktrees stay mounted (8 parked + 12 retained by default, unbounded with terminalHiddenViewParking off), so that set rebuilt on every publication — on the always-on hosts the memo targeted, ~20 worktrees paid the full content build plus the new inputs build and deep compare every tick. Capture the live reads instead: snapshot pane leaf ids, the live active leaf, the serialized pane tree, and per-pane numeric/pty bindings once per publication into MountedTerminalSurfaceCapture, compare captures by value in the memo, and have the builders read only the capture. Live state outside the capture is now unrepresentable in a builder, so the skip stays provably complete — and a mounted worktree whose panes did not change reuses its snapshot like any other.
Fixes a renderer OOM on always-on runtime hosts with paired clients.
Defect
buildMobileSessionTabSnapshotsrebuilt per-worktree content for every worktree on every publication, and consulted its per-worktree cache only after the content was built:The cache suppressed fanout and one allocation. It saved none of the work. Publication is triggered by a sync key including
agentStatusByPaneKey, so this ran on every agent-status tick.An agent tick legitimately changes exactly one worktree's snapshot. Pre-fix the renderer rebuilt all 222 to discover that — 221 of 222 rebuilds were redundant.
Fix
Two commits, reviewable independently.
68a7017c36— refactor: make inputs explicit. IntroducesMobileSessionWorktreeInputs(24 fields) built once per worktree and threaded through the seven per-worktree builders, replacing wholesaleAppState. Pure refactor, no behavior change. This is the enabling step: withAppStateout of those signatures the compiler proves the input set is complete, which is what makes the skip safe.9180807746— fix: skip unchanged worktrees. Reference-compares those explicit inputs and skips before building any intermediates.jsonContentEqualsretained as a backstop on the non-skipped path.Measured —
buildMobileSessionTabSnapshotsin isolation, N=222, 897 tabs, 54 live agent statusesMedian of 3 runs, before
922268af10vs after9180807746:Output is preserved: exactly 1 of 220 snapshots differs before and after. The fix removes work, not results.
At a realistic 20-30 pub/s this path drops from 24-36% of one core to 3.5-5.3%. At the 16 ms coalescing ceiling (~62.5 pub/s) gross allocation drops from ~7.2 GB/min to ~2.0 GB/min.
Field impact
Always-on Windows runtime host, 4 paired clients. Four renderer OOMs in two days across
v1.4.163andv1.4.164-rc.3. Renderer store at the OOM:tabsByWorktree 222,unifiedTabsByWorktree 224,terminalLayoutsByTabId 787,agentStatusByPaneKey 54.Pre-crash
usedHeapMBoscillated3795 -> 3858against a 4,192 MB limit — 91-92% occupancy for the final 8 minutes. That is allocation outrunning GC, not retention: ~95% of the churn is reclaimed, leaving a slow net climb that parks the heap near its ceiling, where near-continuous mark-compact on V8's GC threads converts allocation pressure into >100% of one core. The reported lag is those GC pauses.What this does NOT claim
usedHeapMB / heapLimitMBfrom therenderer_memorybreadcrumb.pr_refresh_queue(~100 coalesced events/min, main-process) is an independent contributor this does not touch.syncRuntimeGraphwith astructuredClone-backed IPC mock, same scale, 3 runs: 21.3 ms -> 12.0 ms. The split after this PR is ~2 ms content build and ~4-7.5 ms structured clone of a 374-906 KB payload (see below) that is byte-identical before and after — this PR reuses cached snapshot objects but does not shrink what gets published. So the payload, not the build, is now the bottleneck; there is almost no headroom left inside this function. At 20-30 pub/s the path goes from 43-64% of one core to 24-36%.agentStatuswith a 20-entrystateHistoryand alastAssistantMessagethe code notes can reach ~8 KB), and the larger is the more realistic. At the coalescer ceiling of 62.5 pub/s that is ~23-57 MB/s, i.e. ~1.4-3.4 GB/min — smaller than the ~7 GB/min this PR removes from the build side, so the payload is not the larger allocation contributor. The case for the follow-up rests on the end-to-end timing instead: after this PR the clone is 4.1 ms of a ~12 ms publication, and Electron pays it on both serialize and deserialize. A follow-up PR (perf(runtime): withhold unchanged mobile snapshots from the graph payload #12245) withholds unchanged snapshots, cutting an unchanged republish from 374 KB / 5.08 ms to 3.4 KB / 0.02 ms. It depends on this one — the partition is an object-identity check that only works once unchanged worktrees return reference-identical snapshots, and merging it first would silently degrade to "everything always changed". Note a graph-level equality check would NOT help: the sync-key gate atApp.tsx:1213-1241already suppresses no-op publications, and on an agent tick the graph genuinely differs by 1 of 220.Known fallback
A worktree with a mounted
TerminalPanealways rebuilds:buildMobileTerminalSurfaceTabsreads livePaneManager/DOM state that no store reference can witness.canReuseMobileSessionSnapshotrefuses to skip when either the previous or current publication saw a registered tab for that worktree (theprevioushalf covers unmount). Only a handful are mounted at real scale. The benchmark fixture registers none, so the measured post-fix figure is mildly optimistic.Correctness notes for review
agentStatusByPaneKeyis read inside the build loop (buildMobileTerminalSurfaceTabs, via a localpaneKey), so it is a genuine per-worktree input and is bucketed through atabId -> worktreeIdindex. A grep for the bare identifier misses this site. Skipping on it would have pinned stale agent statuses on paired clients silently.[]per worktree, which would have defeated reference equality and produced a ~0% skip rate. Now sharedEMPTY_WORKTREE_*constants.browserTabsByWorktree[K]haveworktreeId === K; and anagentStatusByPaneKeykey rejected byparsePaneKeycan never be looked up, since every lookup key ismakePaneKeyoutput.Tests
sync-runtime-graph-publication-cost.test.tscounts per-worktree work via a slice read once per worktree;.failsmarkers removed. Note that metric is satisfied by the refactor alone, so the fix commit adds tests countingtab.titlereads, which observe content builds directly: at 300 worktrees, unchanged republish 1200 -> 0 build units, one worktree changed 1200 -> 4. Both verified failing without the skip.Validation
typecheck:web,typecheck:node,oxlintPASSNote: the
pnpm testwrapper cannot run in this environment (windows-native-registrynode-gyp rebuild needs Visual Studio);pnpm exec vitest run --config config/vitest.config.tsis the repo-correct direct invocation.Final merge-readiness review — 2026-08-03
Reviewed exact head
27d470c2ac645cbcd4cf75c087ce6b3dc771a49d. The final independent review returned CLEAN. GitHub reports a clean merge state and 42 completed checks with zero failures, including Windows packaging.Review fix
27d470c2corrected the publication-cost regression so it mutates one realagentStatusByPaneKeyentry and proves exactly one of 300 worktree snapshots changes identity. The earlier test only changed the top-level map identity and therefore did not exercise the claimed behavior. The temporary incident document was also removed from the PR.Statistical benchmark
Identical SHA-256-verified uncommitted harness at baseline
3658165119, this PR27d470c2ac, and the combined stack through #12245 at5081a12ac2. Each target used three independently started, rotated rounds with 50 warmups and 150 measured samples per round: 450 measured samples per target per metric. Values aremedian / p95 [bootstrap 95% CI for median].structuredCloneThis PR reduces median direct-build time 90.2% versus baseline. The combined stack reduces median scheduled-publication time 90.5% and payload size 94.7% versus baseline; compared with this PR alone, #12245 reduces scheduled time 82.5%, clone time 96.5%, and payload 94.7%. Its 0.003 ms direct-build bookkeeping overhead is dwarfed by the transport reduction.
Every measured iteration changed exactly one status. Baseline and this PR published all 222 snapshots; the combined stack published the changed worktree and withheld the other 221. Payload content preserved the changed status, and there were zero measured publication failures.
Raw local artifacts remain uncommitted in the dedicated benchmark worktree under
.benchmarks/mobile-session-publication/(report.md,summary.json,execution.json, andraw/*.json). Absolute wall times should be treated cautiously because an unrelated two-day-old Node/Vite repro remained at approximately one logical CPU throughout; rotated commit order, independent processes, warmups, and confidence intervals reduce but cannot eliminate that host-load noise. The relative effects are large and consistent.Validation gaps and merge order
low spec windowsenvironment was unavailable:remote_runtime_unavailable: Could not connect to the remote Orca runtime.Windows packaging CI passed.$electron,$perf, and$orca-mobile-emulator-qawere unavailable. This is not a visual change, so no screenshots were fabricated and no prohibited OS-level UI automation was substituted.