Skip to content

perf(renderer): stop one pane title update from scanning the global sleeping-record inventory - #21292

Merged
Jinwoo-H merged 9 commits into
mainfrom
perf/store-fanout-keyed-subscriptions
Sep 17, 2026
Merged

Jinwoo-H merged 9 commits into
mainfrom
perf/store-fanout-keyed-subscriptions

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​454 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​451
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​53 $\color{#cf222e}{\Huge{\mathbf{−}}}$​34 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​19

Problem

A pane title update writes runtimePaneTitlesByTabId and nothing else. But zustand notifies every subscriber synchronously on every set, and each subscriber re-runs its selector. useShallow suppresses the re-render, never the scan.

selectSleepingRecordParkExemptTabIds (sleeping-record-park-exemption.ts, consumed by use-terminal-tab-cold-parking.ts) had no identity gate, so every retained worktree walked the entire global sleeping-agent inventory on every store write to conclude nothing changed for it — on the keystroke path.

Reproduction

src/renderer/src/components/terminal-pane/pane-title-update-global-scan-budget.test.tsx, committed first as it.fails so the before-state is in history (4a02d97).

It seeds the real store at the captured scale — 870 workspaces, 1,408 terminal tabs, 857 sleeping records, 177 agent-status rows — and mounts the real components: 870 WorktreeCardStatusSlot sidebar rows (the list is not virtualised, and each row's useWorktreeActivityStatus opens ~6 subscriptions) plus 20 retained workspaces through useTerminalTabColdParking / selectTabBarAgentProjections. That mount opens 5,500 zustand listeners, inside the capture's 5,462–7,478, so the fanout being measured is the real one.

Instrumentation is test-only: counting accessors on the state maps, vi.mock wrappers for per-module selector executions, render counters in the row components, and a subscriber that counts notifications. No production instrumentation.

ONE setRuntimePaneTitle at that scale:

metric before after
zustand listeners 5,500 5,500
store notifications 1 1
listener invocations 5,500 5,500
selector runs — worktree activity summary 896 896
selector runs — worktree card status inputs 2,688 2,688
selector runs — sleeping-record exemption 23 23
selector runs — tab-bar agent projections 23 23
React commits — sidebar rows 0 0
React commits — retained panes 1 1
sleeping-agent records read 19,711 0
agent-status rows read 0 0
workspace tab buckets read 1,394 1,394

The three read counters sit on the state maps themselves, so a 0 is an absence proof across all 5,500 subscribers, not only the four instrumented modules. 1,394 bucket reads is roughly one keyed lookup per workspace consumer — a full-inventory walk would be that number times 870.

Fix

selectSleepingRecordParkExemptTabIds now goes through the existing createWorktreeRecordSelector generation cache, keyed on the sleepingAgentSessionsByPaneKey identity. The walk happens once per worktree per real inventory change instead of once per store write. The build body is unchanged.

Two supporting changes:

  • worktree-record-selector-cache.ts moves from components/sidebar/ to store/, since terminal-pane/ now shares it. Pure rename plus two import lines.
  • It gains an optional isEmpty override so a Set-valued selector can use it (Object.keys(set).length is always 0).

What remains — and why no keyed subscriptions here

The ticket's premise is that a pane update should notify only affected consumers. The numbers say notification work is still O(mounted workspaces): 5,500 listener invocations and ~3,630 instrumented selector executions per title update, unchanged by this PR. That is inherent to one shared store — zustand visits every listener.

But every one of those visits is now a cheap identity check. Zero records scanned, zero unrelated re-renders, zero allocation in the measured selectors. Measurement also showed the other four files the ticket names were not on the title path at all: tab-agent-types-by-tab-id.ts and worktree-agent-activity-summary.ts already have source-identity caches and read 0 rows; the store-side getTerminalTabOwnerWorktreeId is already an incrementally maintained index; workspace-delete-lineage.ts is a delete-action path, not a subscriber.

So the keyed per-pane/per-workspace subscription work STA-7552 proposes is not justified by this measurement and is not attempted here. Building it would add a second subscription mechanism and per-worktree registries with their own lifecycle, to replace ~5,500 identity-comparison closure calls per update. Whether that residue is material is a question for the packaged trace, not for a guess — if it turns out to matter, the right follow-up is to cut the ~6 subscriptions per sidebar row down to one, which reduces listeners at the source rather than adding a parallel path. I would rather land the measured 19,711 → 0 and let the packaged trace rank what is next.

What is preserved

  • Presentation semantics, host-status authority, and the no-op / decorative-title gates in setRuntimePaneTitle are untouched — no store action changed.
  • The exemption rule is byte-identical: same passive-completed-hibernation carve-out, same persisted-tabId-over-pane-key precedence, same refusal to invent an owner for a delimiter-less pane key. The existing selector tests cover all three and still pass.
  • Lifecycle: no new subscriber, no new global mutable cache, no feature flag. The memo is generation-scoped — a source change allocates a fresh map, so at most two generations are retained and entries for worktrees that stop asking are dropped. Two new cases in sleeping-record-park-exemption.test.ts prove a rebuild on inventory change and that an exemption is dropped once the workspace's records leave the map; terminal-pane-store-subscription-budget.test.tsx still proves unmount returns the listener count to baseline.
  • Folder workspaces and git worktrees are treated identically; nothing here is platform- or host-dependent.

Risk

Low. One selector gains a memo whose key is the exact slice it reads. The failure mode of a wrong key would be a stale park exemption, covered by the two new lifecycle cases. The file move is a rename with two import updates and no behavior change.

Not verified

  • No packaged before/after trace. The parent issue's acceptance asks for a packaged build at ~870 workspaces with typing tail latency. That needs Jinjing's machine and profile; this PR carries only deterministic renderer counts.
  • ORCA_TYPING_BENCH=1 typing-latency e2e was not run — it needs a fresh out/ build this worktree could not produce. No p50/p95/p99 is claimed.
  • The residual ~5,500 identity checks per update are counted but not ranked against a keystroke budget; see "What remains".
  • Runtime-graph publication and persistence (STA-7553) and the ~817 ms of React rendering in the capture are untouched.

Refs STA-7552, STA-7551.

One setRuntimePaneTitle at Jinjing's scale (~870 workspaces, 1,408 terminal
tabs, 857 sleeping records, 20 mounted worktrees) reads 19,711 sleeping-agent
records: 23 executions of selectSleepingRecordParkExemptTabIds x 857. The two
budget cases are it.fails so the before-state lands in history.

Refs STA-7552, STA-7551
…dentity

A pane title update writes runtimePaneTitlesByTabId, but zustand re-runs every
mounted subscriber's selector, so each retained worktree walked the whole
sleeping-agent inventory to conclude nothing changed for it. useShallow
suppressed the re-render, never the scan.

selectSleepingRecordParkExemptTabIds now goes through the existing
createWorktreeRecordSelector generation cache, keyed on the record-map
identity, so the walk happens once per worktree per real inventory change
instead of once per store write. The cache moves from components/sidebar to
store/ now that terminal-pane shares it, and takes an isEmpty override so a
Set-valued selector can use it.

19,711 sleeping-record reads -> 0 for one title update at capture scale.

Refs STA-7552, STA-7551
@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2f57caed-f002-41a5-83e5-76cf150df252

📥 Commits

Reviewing files that changed from the base of the PR and between f026f24 and 8fdb9c8.

📒 Files selected for processing (2)
  • src/renderer/src/components/terminal-pane/pane-title-update-global-scan-budget.test.tsx
  • src/renderer/src/store/worktree-record-selector-cache.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/renderer/src/components/terminal-pane/pane-title-update-global-scan-budget.test.tsx
  • src/renderer/src/store/worktree-record-selector-cache.ts

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


📝 Walkthrough

Walkthrough

The sleeping-record selector now accepts full store state and uses shared empty-value handling for Set and Map results. The cold-parking hook and focused tests use the new state shape. The capture-scale suite measures selector runs, notifications, reads, renders, and committed sidebar rows during pane-title updates. Two sidebar imports now use the @/store alias.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 8fdb9

This change memoizes an internal selector so that unrelated pane-title updates no longer rescan the full sleeping-agent inventory, while still correctly recomputing when the underlying record set changes, including removals. Verification of the core caching logic did not surface any correctness gaps, so this appears safe to merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 29.41% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 17 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main performance change: preventing pane-title updates from scanning the global sleeping-record inventory.
Description check ✅ Passed The description is detailed and directly covers the problem, implementation, measurements, preserved behavior, risks, testing, and out-of-scope work. It does not fully follow the repository template: …
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

The first repro mounted 20 retained workspaces (~60 subscribers) and counted
record reads only, which under-models the capture. The sidebar worktree list is
not virtualised, so all 870 rows mount and each WorktreeCardStatusSlot opens
~6 subscriptions. Mounting the real row component brings the harness to 5,500
zustand listeners, inside the capture's 5,462-7,478.

One setRuntimePaneTitle now reports listener invocations, per-module selector
executions, React commits, and records scanned. Before/after the memo, only
records scanned moves: 19,711 -> 0. Notification work stays O(mounted
workspaces) by construction; each visit is now an identity check.

Refs STA-7552, STA-7551

@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: Advanced

Run ID: 97b9e815-e4a2-4316-b3dc-d03b52a69fb5

📥 Commits

Reviewing files that changed from the base of the PR and between 2ceb85c and 9c083c5.

📒 Files selected for processing (1)
  • src/renderer/src/components/terminal-pane/pane-title-update-global-scan-budget.test.tsx

Included review availability: Your plan provides up to 10 included reviews per hour; 1 remains 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

  • Memoize the park-exemption selector — selectSleepingRecordParkExemptTabIds is now built through createWorktreeRecordSelector, keyed on the sleepingAgentSessionsByPaneKey identity, so an unrelated store write no longer walks the global record map once per retained worktree.
  • Set-aware emptiness override — createWorktreeRecordSelector gains an optional isEmpty, since Object.keys(set).length is always 0 for the new ReadonlySet<string> value type.
  • Cache module relocation — worktree-record-selector-cache.ts moves from components/sidebar/ to store/, with the two sidebar import paths updated; no stale references remain.
  • Deterministic scan-budget test — a new capture-scale test seeds the real store (870 workspaces / 1,408 tabs / 857 records) and asserts zero sleeping-record reads for one setRuntimePaneTitle, flat counts across repeated updates, and a rebuild on inventory change.
  • Exemption lifecycle cases — the selector test now proves a rebuild on record-map change and that an exemption is dropped once the workspace's records leave the map.

I verified the budget test is falsifiable: temporarily defeating the memoization (readSources: () => [{}]) reproduces exactly 19,711 record reads and fails the test, matching the documented before-state. I also confirmed zustand v5's shallow compares Set iterables correctly (so the carried-generation identity carry is sound for this value type), and that every producer of sleepingAgentSessionsByPaneKey allocates a new map on content change rather than mutating in place, so the identity key cannot serve a stale exemption. pnpm tc:web and pnpm run check:code-quality:changed are clean, and the two touched test files pass 9/9.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Flash (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 (incremental — delta since the prior pullfrog review at 2ceb85c1c8)

  • Only the scan-budget test changed. 9c083c5d8f expands pane-title-update-global-scan-budget.test.tsx from 3 to 5 tests: it mounts the real, unvirtualised WorktreeCardStatusSlot sidebar rows (all 870) inside a TooltipProvider, wraps four production selectors with counting vi.mock shims that call through to the real implementations, reads the pre-existing store listener census, and asserts all four fanout axes — listeners/notifications, per-module selector runs, React commits, and records read.
  • No production code changed in this commit. The memoized selectSleepingRecordParkExemptTabIds, the isEmpty override, and the worktree-record-selector-cache.ts relocation are byte-identical to the previously reviewed 2ceb85c1c8.
  • The new assertions pin the measured shape rather than a tautology: reads.sleepingRecords/agentStatusRows must stay 0, sidebar-row renders must stay 0, and the selector-run floors (>= 870 summary, >= 2610 card-status inputs) only hold if the mocks actually intercept — so a broken mock or a reintroduced global walk fails the test.

I re-ran the suite (11/11 passing) and pnpm tc:web (clean). The reads.sleepingRecords === 0 assertion remains falsifiable: defeating the memo still reproduces exactly 19,711 reads. The listener census is pre-existing production code installed at src/renderer/src/store/index.ts:75, not added here.

Pullfrog  | View workflow run | Using DeepSeek Flash (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 critical issues — one stale comment inline.

Reviewed changes

Incremental review of the five commits since the prior pullfrog review at 9c083c5d8f (535c1ba679, bd2fd8215e, 4784efb825, f026f24542, c0c6b4bd54).

  • Generic emptiness in the selector cache — createWorktreeRecordSelector no longer takes an isEmpty option; an internal isEmptyValue recognizes Set/Map by .size and falls back to Object.keys for records, so record-valued callers are unchanged and a Set-valued caller no longer needs a per-call hook.
  • Park-exemption selector tightened — the explicit isEmpty override is gone, build destructures its state argument, and SleepingRecordParkExemptionState is no longer exported (no external consumers).
  • Scan-budget test counts real row commits — each sidebar row is wrapped in React.Profiler, and the assertion now pins exactly TARGET_WORKTREE_ID, which is stronger than the old wrapper-level counter; duplicate/unasserted tests and the tabBarAgentProjections counter/mock were removed.
  • Exemption lifecycle cases — still prove a rebuild on inventory change and a dropped exemption once a workspace's records leave the map.

I re-ran the two touched files (9/9 passing), pnpm tc:web (clean), and pnpm run check:code-quality:changed (0 findings / 7 files). The isEmptyValue refactor is semantically equivalent for the one prior isEmpty caller, and the Object.keys path is byte-for-byte unchanged for the other four selectors. The one open review thread (the React.Profiler commit-counting gap) is addressed by 535c1ba679 and now resolved.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@Jinwoo-H
Jinwoo-H merged commit 0371418 into main Sep 17, 2026
34 checks passed
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
…leeping-record inventory (stablyai#21292)

* test(perf): pin the pane-title global-scan repro at live-capture scale

One setRuntimePaneTitle at Jinjing's scale (~870 workspaces, 1,408 terminal
tabs, 857 sleeping records, 20 mounted worktrees) reads 19,711 sleeping-agent
records: 23 executions of selectSleepingRecordParkExemptTabIds x 857. The two
budget cases are it.fails so the before-state lands in history.

Refs STA-7552, STA-7551

* perf(renderer): memoize the sleeping-record park exemption on slice identity

A pane title update writes runtimePaneTitlesByTabId, but zustand re-runs every
mounted subscriber's selector, so each retained worktree walked the whole
sleeping-agent inventory to conclude nothing changed for it. useShallow
suppressed the re-render, never the scan.

selectSleepingRecordParkExemptTabIds now goes through the existing
createWorktreeRecordSelector generation cache, keyed on the record-map
identity, so the walk happens once per worktree per real inventory change
instead of once per store write. The cache moves from components/sidebar to
store/ now that terminal-pane shares it, and takes an isEmpty override so a
Set-valued selector can use it.

19,711 sleeping-record reads -> 0 for one title update at capture scale.

Refs STA-7552, STA-7551

* test(perf): model the full sidebar fanout and count all four axes

The first repro mounted 20 retained workspaces (~60 subscribers) and counted
record reads only, which under-models the capture. The sidebar worktree list is
not virtualised, so all 870 rows mount and each WorktreeCardStatusSlot opens
~6 subscriptions. Mounting the real row component brings the harness to 5,500
zustand listeners, inside the capture's 5,462-7,478.

One setRuntimePaneTitle now reports listener invocations, per-module selector
executions, React commits, and records scanned. Before/after the memo, only
records scanned moves: 19,711 -> 0. Notification work stays O(mounted
workspaces) by construction; each visit is now an identity check.

Refs STA-7552, STA-7551

* test(perf): count sidebar-row commits inside the row subtree

* refactor(store): teach the selector cache Set/Map emptiness instead of an option

* test(perf): drop the duplicate mounts and unasserted counters

* refactor(terminal-pane): tighten the park-exemption selector's shape and why

* refactor(store): keep the emptiness check off the broad object type

* test(renderer): count the three instrumented selector modules in the fanout comment
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