Skip to content

perf(renderer): cut repo-refresh work in the repos slice - #13788

Closed
nwparker wants to merge 3 commits into
mainfrom
nwparker/perf-repo-refresh-churn
Closed

nwparker wants to merge 3 commits into
mainfrom
nwparker/perf-repo-refresh-churn

Conversation

@nwparker

@nwparker nwparker commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Follow-up to #13744. Profiling the leftovers from that PR surfaced something much bigger than the identity work it was chasing: a quadratic merge running synchronously inside a zustand set() on every repo catalog refresh.

Commit What
bb8ca45 Index the compat merge (up to 27.8×) + stop three slices losing array identity
0754aaa Generalize the identity reconciler; widen catalog types to readonly
033d4ac Refresh-identity tests; complete two incomplete fixtures

1. The quadratic merge — the headline

mergeFetchedProjectCompatibilityForHost runs synchronously inside a zustand set() on every repo refresh (fetchRepos, fetchRuntimeEnvironmentRepos, fetchReposForAllHosts). It was O(projects × (setups + repos)):

  • getProjectHostIds / getExplicitProjectHostIds rescanned all setups and repos, once per project
  • mergePreviousProjectMetadata rebuilt a full repo key-set (new Set(reposById.keys())) per project — a hidden quadratic term

At 1200 repos that is ~200 ms of main-thread work — roughly a dozen dropped frames — inside a store write.

The fix precomputes the indexes once and hands each helper only its own project's slice. No ownership logic was reimplemented; the existing helpers are called verbatim with pre-sliced inputs, so the results are provably identical rather than "hopefully equivalent".

Warm refresh (previous state already holds the catalog — the steady-state case):

repos before after speedup
200 7.7 ms 1.0 ms 7.8×
600 33.2 ms 1.2 ms 27.8×
1200 202.2 ms 8.3 ms 24.3×

Growth is now roughly linear rather than quadratic. Absolute numbers are noisy run-to-run (the 1200 baseline ranged 156–473 ms); the ratio was stable.

2. Three slices that lost array identity every refresh

Same class of bug #13744 fixed for repos, in the slices next to it:

  • projects / projectHostSetups — the merge always allocates (sourceRepoIds is rebuilt per project; setups arrive freshly cloned over IPC), so these now reconcile against previous. filterSetupsForPrunedRepoRows also had to stop copying unconditionally — otherwise the reconcile compares against a throwaway copy and achieves nothing.
  • filterRepoIds — returns the input when nothing was pruned. This one has the widest reach of the three: six identity-sensitive subscribers including App.tsx at the root.
  • folderWorkspacePathStatuses — keeps identity when already empty, at all six catalog-fetch sites (useIpcEvents fires fetchRepos + fetchProjectGroups + fetchFolderWorkspaces together, so fixing only the repo sites would leave the sidebar churning).

On that last one I checked whether the reset was load-bearing before touching it. It isn't: entries already self-invalidate via a requestSnapshot check on read (repos.ts:1609) and write (:2377), plus a 10s TTL and a component-level force-refetch on membership change. Two things settled it — fetchRuntimeEnvironmentRepos already mutates repos without clearing this cache (so it would be a live bug if the reset were required), and the only test asserting a clear covers a mutation site, using identity-agnostic toEqual({}).

3. readonly types

Following the RepoSlice['repos'] precedent — returning live store state behind a mutable type is the footgun that PR called out. RepoSlice['projects'], ['projectHostSetups'], UISlice['filterRepoIds'], and ProjectHostSetupProjection are now readonly. Local accumulators are annotated mutable and built from copies. No as casts, as unknown as, or @ts-expect-error added.

At the persisted-UI IPC boundary (App.tsx) I copy rather than widen a shared main-process type — that call is debounced and serializes anyway.

Honest accounting of the payoff

The identity half is not a CPU win. Measured: the projection WeakMap hit saves ~2 µs at 200 repos and ~0 at 1200, because the selector's expensive prologue (normalizeHydratedProjectHostSetupProjection) is uncached and runs before any cache lookup. Reconciliation also makes the write path slightly slower.

What it actually buys is render churn: useProjectHostSetupProjection goes from "new object every refresh" to reference-stable, which stops ~24 component re-renders (mostly per-pane TerminalPane) plus the buildRows sidebar-tree rebuild in WorktreeList, and two spurious effect re-runs (AiVaultPanel scope paths, native-chat skill rescan).

The speedup in §1 is the real win here. I have also posted a correction on #13744, whose cache claims that profiling falsified.

Testing

Refresh-identity cases live in a new repos-refresh-identity.test.ts (repos.test.ts crossed the 800-line limit, and these are a distinct concern — no max-lines disable added).

Every identity assertion was verified to fail against a reverted source. Fixtures are production-shaped on purpose: a scalar-only repo reconciles even when the compare is broken, which is exactly how an earlier version of this work shipped green while being completely inert.

  • 20,504 main-process tests
  • 13,869 component tests
  • 11,264 store / shared / lib / hooks tests
  • tsc web + node + cli — zero errors
  • oxlint, oxfmt, max-lines ratchet

Residual risk

  • Remaining cost in the merge after indexing is getProjectHostSetupOwnerKey (three JSON.stringify calls per setup) and object spreads in mergeProjectCompatibilityProject — together ~40% of what's left. A non-JSON owner key is a cheap follow-up.
  • projectHostSetupProjectionFromRepos sets createdAt: repo.addedAt || now, so a repo with addedAt === 0 would get a drifting timestamp and never reconcile. addedAt is required and real repos have it, so this is no worse than today — but it is why a fixture missing addedAt would make the fix look broken.
  • Removing the folderWorkspacePathStatuses reset entirely (rather than guarding it) is defensible on the evidence above and would close a window where the folder-path guard is briefly un-gated, but that is a real behavior change and deserves its own PR.

Made with Orca 🐋

nwparker and others added 2 commits August 11, 2026 02:22
Two independent costs on every repo catalog refresh, both in repos.ts.

1. mergeFetchedProjectCompatibilityForHost ran synchronously inside a zustand
   set() and was O(projects x (setups + repos)): getProjectHostIds and
   getExplicitProjectHostIds rescanned all setups and repos per project, and
   mergePreviousProjectMetadata rebuilt a full repo key-set per project.
   Precompute the indexes once and hand each helper only its own project's
   slice, rather than reimplementing any ownership logic.

     200 repos    7.7 ms -> 1.0 ms   (7.8x)
     600 repos   33.2 ms -> 1.2 ms  (27.8x)
     1200 repos 202.2 ms -> 8.3 ms  (24.3x)

   Verified against 4,002 differential cases (2 realistic + 4,000 randomized:
   duplicate repo/project ids, dangling sourceRepoIds, empty repoId setups,
   local/SSH/runtime mixes) comparing output element provenance and order, not
   just deep structure.

2. Three slices lost their array identity on every refresh, defeating
   identity-keyed memos and waking subscribers:
   - projects / projectHostSetups: the merge always allocates (sourceRepoIds is
     rebuilt per project, setups arrive freshly cloned over IPC), so reconcile
     against `previous`. filterSetupsForPrunedRepoRows also had to stop copying
     unconditionally, or the reconcile would compare against a throwaway.
   - filterRepoIds: return the input when nothing was pruned. Six
     identity-sensitive subscribers, including App.tsx at the root.
   - folderWorkspacePathStatuses: keep the identity when already empty. Entries
     self-invalidate on requestSnapshot drift and a 10s TTL, so the defensive
     reset was never the correctness mechanism.

Co-authored-by: Orca <[email protected]>
…log types

reconcileFetchedRepos already reused equal entries and the whole array when
nothing moved; projects and projectHostSetups need the same treatment. Extract
reconcileFetchedEntries with an identity-key callback and keep the repo
function as a thin wrapper, rather than adding a near-duplicate module.

The structural value compare matters here for the same reason it did for repos:
Project.sourceRepoIds is a required array and ProjectHostSetup.hookSettings is
two levels deep, so a reference compare would report every entry changed and
the reconcile would never fire.

Widen the arrays these now hand back to readonly, following the RepoSlice
precedent: returning live store state behind a mutable type is the footgun that
change called out. Local accumulators are annotated mutable and built from
copies. No casts added.

Co-authored-by: Orca <[email protected]>
@nwparker nwparker closed this Aug 11, 2026
@nwparker nwparker reopened this Aug 11, 2026
Split the refresh-identity cases out of repos.test.ts into a dedicated file —
repos.test.ts crossed the 800-line limit, and these are a distinct concern.

Fixtures are production-shaped on purpose. A scalar-only repo reconciles even
when the compare is broken, which is exactly how an earlier version of this
work shipped green while being inert. Each identity assertion was verified to
fail against a reverted source.

Also completes the ProjectGroup and FolderWorkspace fixtures in
useAgentDetectionTarget.test.ts so they satisfy their types at the declaration
instead of being laundered through the surrounding state cast.

Co-authored-by: Orca <[email protected]>
@nwparker
nwparker force-pushed the nwparker/perf-repo-refresh-churn branch from 033d4ac to 121ded5 Compare August 11, 2026 09:27
@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: c003fe64-1793-4e6a-9493-fd3f12a5af30

📥 Commits

Reviewing files that changed from the base of the PR and between 3713dd7 and 033d4ac26e8d2581ba4c9fcc90fc1a4fd95a4b99.

📒 Files selected for processing (15)
  • src/renderer/src/App.tsx
  • src/renderer/src/components/automations/AutomationEditorDialog.tsx
  • src/renderer/src/components/automations/AutomationEditorDialogFooter.tsx
  • src/renderer/src/components/right-sidebar/ai-vault-scope-paths.ts
  • src/renderer/src/components/sidebar/add-repo-skip-finalization.ts
  • src/renderer/src/components/sidebar/visible-worktrees.ts
  • src/renderer/src/hooks/useAgentDetectionTarget.test.ts
  • src/renderer/src/lib/http-link-routing.ts
  • src/renderer/src/store/slices/repo-identity-reconcile.ts
  • src/renderer/src/store/slices/repos-refresh-identity.test.ts
  • src/renderer/src/store/slices/repos.test.ts
  • src/renderer/src/store/slices/repos.ts
  • src/renderer/src/store/slices/ui.ts
  • src/renderer/src/store/slices/worktrees.ts
  • src/shared/project-host-setup-projection.ts

📝 Walkthrough

Walkthrough

The change updates project, setup, and repository-filter collections to use readonly array types. Repository refresh logic now performs generic structural reconciliation and preserves unchanged object and array references. Project and setup catalogs use scoped host ownership indexes. Refresh paths conditionally prune filters and clear path-status caches. Tests cover identity preservation, catalog changes, filter pruning, and stale workspace status removal. UI persistence copies readonly filter arrays before serialization.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the performance and identity changes and testing, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the missing template sections, state “No visual change” if applicable, and document AI review, cross-platform checks, security risks, and follow-up notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 42.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the main change: reducing repository refresh work in the renderer repos slice.
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.
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch nwparker/perf-repo-refresh-churn

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.

@nwparker

Copy link
Copy Markdown
Contributor Author

Superseded before review — closing shortly

This branch was written against an older main and is now CONFLICTING, which is also why it never ran CI: GitHub silently skips pull_request workflows on an unmergeable PR, so only the pull_request_target job fired. Reopening and force-pushing changed nothing, because the cause was mergeability, not a dispatch glitch.

The conflict is with #13770 ("keep catalog array identity and path-status cache on no-op refetches"), which landed from a parallel session while this was in flight. Checking this branch against current main:

Change here Status on main now
Indexed compat merge (up to 27.8×) Still missing — per-project rescans remain at repos.ts:820-832
filterRepoIds identity Still missing — unconditional .filter(...) at :2009, :2093, :2175
projects / projectHostSetups reconciliation Still missing — unchangedMergeSource covers only projectGroups and folderWorkspaces
folderWorkspacePathStatuses guard Already landed by #13770 — redundant here
Structural value comparison #13770 added areCatalogEntriesEqual; shipping this branch would leave two parallel deep-equality helpers in the tree

So the headline (the quadratic merge) and two identity fixes are still needed, but roughly a third of this branch is now duplicate work, and landing it as-is would entrench the duplication rather than fix it.

Rather than resolve a conflict into a branch that would add a second structural-equality helper, this is being rebuilt on current main as two focused PRs:

  1. perf — the indexed compat merge, filterRepoIds, and projects/projectHostSetups reconciliation, built on main's existing areCatalogEntriesEqual instead of a parallel helper.
  2. refactor — unify the duplicate deep-equality helpers that perf(renderer): keep the repos array identity across no-op refetches #13744 and perf(renderer): keep catalog array identity and path-status cache on no-op refetches #13770 landed independently (areValuesEqual in repo-identity-reconcile.ts vs areCatalogEntriesEqual + isPlainCatalogObject in repos.ts) into one home.

The benchmark numbers quoted here were measured against the older main and are being re-established from a fresh baseline rather than carried over.

Worth noting for coordination: this is the second collision in this file today. #13744 and #13770 both landed structural-equality helpers within hours of each other from different sessions.

@nwparker

Copy link
Copy Markdown
Contributor Author

Superseded by #13803 (rebuilt on current main) and #13804 (the dedupe). See the analysis above for what was still missing versus already landed by #13770.

@nwparker nwparker closed this Aug 11, 2026
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