Skip to content

perf(sidebar): stop re-allocating 423 workspace descriptors and 193 bucket projections per recompute - #18241

Merged
nwparker merged 3 commits into
mainfrom
nwparker/sidebar-bucket-count-alloc
Sep 2, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/sidebar-bucket-count-alloc

Conversation

@nwparker

@nwparker nwparker commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​781 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​780
Prod 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​242 $\color{#cf222e}{\Huge{\mathbf{−}}}$​98 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​144

Salvages the still-valid parts of #18141, rebuilt on the row-cache design #18222 landed. #18141 is closed as superseded; its count-cache design (a per-worktree validUntil clock boundary) is not reintroduced — main's row cache wins.

ELI5

The sidebar shows four numbers: how many agents are waiting on you, working, done, or idle. To get them, Orca walks every workspace you have open and sorts each agent into one of the four piles.

#18222 made the expensive middle step — rebuilding each workspace's agent list — reuse its previous answer when nothing about that workspace changed. But two cheaper steps around it were still redone from scratch on every single recompute:

  1. Building the list of workspaces to walk. With 423 worktrees, that's 423 freshly allocated descriptor objects, thrown away microseconds later. The list only depends on four things (repos, worktreesByRepo, folderWorkspaces, projectGroups), none of which change when an agent sends a status ping.
  2. Sorting each workspace's agents into piles. Even when a workspace's agent list was handed back unchanged by reference, we re-sorted it. 193 pile-sorts per recompute to reach the same four numbers.

This PR memoizes both, plus swaps the store subscription's useShallow comparison — which allocated two arrays, 28 tuples and two Maps on every store write in the app just to conclude nothing moved — for a direct 14-way ===. Finally, when the four numbers come out the same as last time, the same object is handed back, so nothing downstream re-renders.

Zero change to what the numbers say.

Measurements

Baseline is current main (c0e5b189aa0), not #18141's numbers, which measured against a pre-#18222 main and are invalid.

Method: main's buildDashboardBucketCounts vendored side-by-side with this branch's, both driven over the same fixture (10 repos / 423 worktrees / 193 with tabs / 386 tabs) for 100 calls through one warm cache. Deterministic operation counts, because wall-clock swung ~2x between runs on a loaded machine. Wall times are best-of-5 runs.

Scenario A — ordinary agent status ping (agentStatusEpoch unchanged; dominant idle-app traffic)

per call main this branch
row-pipeline recomputes 1 1
bucket projections 193 1
workspace descriptors allocated 423 0
wall (best of 5) 0.33 ms 0.24 ms

Scenario B — retention-relevant change (agentStatusEpoch bumps)

per call main this branch
row-pipeline recomputes 423 423
bucket projections 193 193
workspace descriptors allocated 423 0
wall (best of 5) 0.57 ms 0.50 ms

Store-subscription selector, 200k writes, best of 8, all 14 slices unchanged:

useShallow module gate
ns per store write 1122 10
Object.entries calls per write 2 0
Map allocations per write 2 0

What this does not fix, and what it would cost

Scenario B's 423 → 423 row recomputes is untouched, and it is the bigger remaining prize. agentStatusEpoch is a coarse invalidation token: main's worktree-agent-rows-cache compares it for equality and discards every worktree's rows when it moves. The epoch bumps on retention-relevant changes, migration changes, orphan eviction, and the freshness scheduler's stale-boundary tick — not rare.

#18141 solved this with a per-worktree validUntil: the minimum future agentStatusEvidenceObservedAt(entry) + AGENT_STATUS_STALE_AFTER_MS over that worktree's entries, so a worktree with no entry near its freshness boundary survives an epoch bump. I traced the clock consumers to confirm the idea is still sound on today's pipeline — only worktree-agent-rows.ts:176 and :221 read now in a way that can move a bucket; title-derived rows stamp updatedAt: now but carry startedAt: 0, which dashboardRowBucketProjection short-circuits.

Assessment: feasible, but out of scope here. worktree-agent-rows-cache.ts has three other consumers — build-dashboard-snapshot.ts, useDashboardPopoutBridge.ts, useLiveDashboardSnapshot.ts — so the token cannot simply be swapped. It would need:

  • a per-entry freshness boundary computed alongside the rows and stored on the cache entry, with the gate becoming now >= computedAt && now <= validUntil in addition to (not instead of) the existing input-identity checks, since the epoch also signals non-clock changes;
  • restoredUnconfirmed and done entries excluded from the boundary (they are never fresh / never decay), which errs toward extra rebuilds and never toward a stale count;
  • the three other consumers audited for whether they can supply a monotonic now — the pop-out bridge in particular passes a now from a different tick source;
  • test coverage for a worktree straddling the boundary while another does not, which is the case a coarse token cannot express.

Prize, from the table above: 423 → ~1 row-pipeline recomputes per call in Scenario B, and it would speed up the pop-out dashboard too, since it shares the cache. That is a real win but it is a redesign of code that landed after #18141 was written, so it belongs to whoever owns the dashboard cache rather than to a rebase.

Correctness

  • useShallow → module gate. The gate compares the same 14 slice identities shallow() compared, and returns the previous object when they all hold. The returned object doubles as the DashboardSnapshotState handed to the builder, so the object is built once per real change instead of once per store write. The gate is module-level rather than per-hook because it is a pure function of the store state — one gate correctly serves every mounted consumer.
  • Workspace descriptor memo. Re-verified the read set on current main, since a wrong key here silently serves a stale workspace list. With includeMapMetadata: false, resolveHostLabel is unreachable (both call sites are gated), so buildHostLabelLookup never runs and sshTargetLabels / runtimeEnvironments / settings are never read; isFolderRepo and remoteHostKind are short-circuited. What remains is repos, worktreesByRepo, folderWorkspaces and projectGroups — exactly the key. Graduate Agents activity view with filtering, persistence, and performance improvements #18222 did not change this, and the read set is now documented on DashboardWorkspaceState so widening it flags the key.
  • Per-worktree tally memo. dashboardRowBucketProjection reads only the row and acknowledgedAgentsByPaneKey[row.paneKey], so those two identities are the complete input. Keying on the ack slice rather than folding it into the row cache preserves main's property that an acknowledgement recounts without rebuilding any rows. Tallies are evicted in the same pass that evicts rows, so the map stays bounded.
  • The no-cache path (buildDashboardBucketCounts(state, now)) is unchanged, which is what makes it usable as the test oracle.

Tests

  • build-dashboard-bucket-counts.equivalence.test.ts — an unmemoized reference walk composed from the same shared primitives, run against the memoized builder over 8 mutations x 5 clock steps, both independently and cumulatively through one shared cache.
    • Closes the boundary gap the reviewer found in perf(sidebar): stop recounting every workspace's agents for four sidebar numbers #18141. Its matrix covered NOW, NOW + STALE + 1 and NOW + STALE * 4 but never exactly NOW + STALE — the last instant an entry is fresh (now - observedAt <= STALE) and the only point where a cache hit, not a recompute, has to return a freshness verdict. That step is now in the matrix and has a dedicated case asserting working: 1 on a cache hit at NOW + STALE and working: 0 one millisecond later, so the case is not vacuous.
  • build-dashboard-bucket-counts.allocation.test.ts — fails on main: asserts 1 descriptor collection (400, not 2000) across 5 recomputes, 5 bucket projections instead of 2000, re-collection when each of the four keyed slices moves, and that an acknowledgement write still recounts every worktree without rebuilding a single row.
  • useAgentBucketCounts.gate.test.ts — fails on main: counts Object.entries calls and Map constructions across 2000 store writes for the gate (0 and 0) against an unwrapped useShallow baseline (4000 and 4000).
  • agent-dashboard-performance-isolation.test.ts still passes — no new eager import reaches the sidebar.

Negative user-facing trade-offs

None.

  • The three memos are keyed on identities that are strict supersets of what the memoized computation reads, so every state that produced different numbers before still produces different numbers now — verified by the equivalence matrix, which includes the idle-decay transitions driven by agentStatusEpoch.
  • Identity reuse of the counts object can only reduce renders, and only when all four numbers are literally equal; it cannot suppress a visible change.
  • Memory: three bounded additions — one workspace-descriptor array (already allocated every pass today, now retained between passes), one 4-number tally per active worktree evicted in the same pass as its rows, and one 15-field object of slice references held by the module gate.
  • The module-level gate holds references to one snapshot of 14 store slices even with no consumer mounted. Those slices are the live store's own, so this retains nothing the store does not already hold; resetAgentBucketCountStateForTests exists for deterministic tests.

Closes #18141.

…ucket projections per recompute

Layers three identity memos onto the row cache #18222 landed, without changing
what the four sidebar numbers say in any state.

- The active-workspace descriptor list is memoized on the four slices
  `collectActiveDashboardWorkspaces(state, false)` actually reads.
- Each worktree's bucket tally is memoized on its rows plus the acknowledgement
  map, so a ping that rebuilds one worktree no longer re-projects the board.
- The `useShallow` selector becomes a module-level 14-identity gate, which
  allocates nothing on the unchanged path.
- The counts object is reused by identity when all four totals hold.
@coderabbitai

coderabbitai Bot commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The dashboard bucket count hook now uses an identity-preserving selector for tracked state slices. The bucket count builder memoizes active workspace descriptors and per-worktree tallies, prunes removed worktrees, and reuses unchanged count objects. New tests cover allocation behavior, selective recomputation, cache invalidation, staleness boundaries, mutation sequences, and equivalence with an unmemoized oracle.

Merge Risk: ⚪ Minimal · up to d9905

The PR reuses existing dashboard data to reduce repeated in-memory allocations without changing displayed counts. One test subcase could exercise cache hits more precisely, but the relevant boundary remains covered and no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.09% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 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 summarizes the primary performance change: avoiding repeated workspace descriptor allocation and bucket projection work in the sidebar.
Description check ✅ Passed The description provides detailed ELI5, rationale, implementation, measurements, scope, correctness, linked issue, and testing information. It omits some template headings and checklist items, includi…
Linked Issues check ✅ Passed The PR satisfies the relevant objective for #18141 by preventing repeated sidebar workspace and bucket-count work while preserving the four totals. It documents the replacement memoization design, its…
Out of Scope Changes check ✅ Passed The production changes, exported type, selector reset helper, and added tests all support the stated sidebar performance objective. No unrelated code changes are evident.
Full details: Description check

Explanation

The description provides detailed ELI5, rationale, implementation, measurements, scope, correctness, linked issue, and testing information. It omits some template headings and checklist items, including an explicit Visual Proof N/A statement, but the core information is complete.

Full details: Linked Issues check

Explanation

The PR satisfies the relevant objective for #18141 by preventing repeated sidebar workspace and bucket-count work while preserving the four totals. It documents the replacement memoization design, its correctness, and the intentionally out-of-scope epoch-driven row recomputation.

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

@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

A performance-only refactor that memoizes three allocation hot-spots in the sidebar's bucket-count path, leaving the computed numbers identical while cutting per-recompute allocations. Tests assert the memoized builder stays equivalent to an unmemoized reference walk, and all new/changed tests plus the pre-existing cache tests pass.

  • Workspace descriptor memo — selectActiveDashboardWorkspaces reuses the workspace list while repos / worktreesByRepo / folderWorkspaces / projectGroups identities hold. I traced collectActiveDashboardWorkspaces(state, false) and confirmed the metadata-free read set is exactly those four slices: resolveHostLabel, buildHostLabelLookup, isFolderRepo, and remoteHostKind are all gated behind includeMapMetadata.
  • Per-worktree tally memo — tallyWorktreeRows caches each worktree's bucket tally keyed on its rows + acknowledgedAgentsByPaneKey identities, matching dashboardRowBucketProjection's read set (row + ack[panexistKey]), so an acknowledgement recount never rebuilds rows. Tally eviction runs against seenWorktreeIds before finishWorktreeAgentRowsCachePass, so the map stays bounded.
  • Store-selector gate — selectAgentBucketCountState replaces zustand's useShallow with a module-level 14-way === gate; since the slice set is unchanged from the old selector and it is a pure function of the singleton store, one gate correctly serves the single AgentDashboardSidebarEntry consumer. The lastCounts identity reuse can only suppress re-renders when all four totals are actually equal.

The equivalence matrix closes the NOW + STALE boundary the earlier #18141 matrix missed and asserts a non-vacuous working: 1 → working: 0 decay across a cache hit. I verified the memo keys against the store's immutable-update convention (worktrees/folder workspaces are replaced by identity, never mutated in place).

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…/sidebar-bucket-count-alloc

# Conflicts:
#	src/renderer/src/components/dashboard/useAgentBucketCounts.ts

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

🧹 Nitpick comments (1)
src/renderer/src/components/dashboard/build-dashboard-bucket-counts.equivalence.test.ts (1)

303-303: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Hoist state out of the clock loop so this test exercises cache hits.

baseState() allocates new repos, worktreesByRepo, folderWorkspaces, and projectGroups objects on each call. Because it runs inside the CLOCK_WALK loop, every step changes those slice identities and misses the workspace memo and the tally memo. This test therefore repeats cold-cache equivalence and never reaches the BASE + STALE cache hit that the CLOCK_WALK comment describes.

The boundary is still covered by the cumulative test and by the explicit boundary test, so this is a precision improvement only.

♻️ Proposed change to hold state identity across the clock walk
     for (const mutation of MUTATIONS) {
       const cache = createDashboardBucketCountsCache()
+      const state = mutation.apply(baseState())
       for (const step of CLOCK_WALK) {
-        const state = mutation.apply(baseState())
         expect(

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 6c7c7bdc-eb46-43d2-9f62-3055a3c06108

📥 Commits

Reviewing files that changed from the base of the PR and between 0886db2 and 28119d1.

📒 Files selected for processing (7)
  • src/renderer/src/components/dashboard/build-dashboard-bucket-counts.allocation.test.ts
  • src/renderer/src/components/dashboard/build-dashboard-bucket-counts.equivalence.test.ts
  • src/renderer/src/components/dashboard/build-dashboard-bucket-counts.ts
  • src/renderer/src/components/dashboard/dashboard-snapshot-workspaces.ts
  • src/renderer/src/components/dashboard/useAgentBucketCounts.gate.test.ts
  • src/renderer/src/components/dashboard/useAgentBucketCounts.test.tsx
  • src/renderer/src/components/dashboard/useAgentBucketCounts.ts

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

@nwparker
nwparker merged commit 4376154 into main Sep 2, 2026
28 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…ucket projections per recompute (stablyai#18241)

Layers three identity memos onto the row cache stablyai#18222 landed, without changing
what the four sidebar numbers say in any state.

- The active-workspace descriptor list is memoized on the four slices
  `collectActiveDashboardWorkspaces(state, false)` actually reads.
- Each worktree's bucket tally is memoized on its rows plus the acknowledgement
  map, so a ping that rebuilds one worktree no longer re-projects the board.
- The `useShallow` selector becomes a module-level 14-identity gate, which
  allocates nothing on the unchanged path.
- The counts object is reused by identity when all four totals hold.
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