Skip to content

perf(renderer): index GitHub resume lookups - #13698

Merged
nwparker merged 2 commits into
mainfrom
nwparker/perf-index-resume-repo-lookups
Aug 11, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/perf-index-resume-repo-lookups

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Summary

  • skip repo/worktree traversal on window resume when neither PR nor issue decorations are visible
  • share a lazy, first-wins repo ID/path index across GitHub refresh collection and runtime PR/issue follow-on fetches
  • reuse the existing host-aware worktree index across request-head and response handling

ELI5

When Orca came back to the foreground, it repeatedly walked the whole project list to answer questions like “which project owns this workspace?” With many remote projects, it could reread the same list millions of times. This gives Orca a temporary address book: each project/workspace is recorded once, then later lookups go straight to the answer. If no PR or issue badges are visible, Orca skips the walk entirely.

Why

The app calls refreshAllGitHub() whenever the window becomes visible. The old path used nested .find() scans during candidate collection, runtime routing, PR/issue fetch setup, request-head lookup, and response handling. Runtime-owned repos under PR-status grouping process every stale candidate, so 1,200 repos/worktrees produced quadratic renderer work during foreground resume.

Measurement

Node v24.18.0, 1,200 repos + 1,200 worktrees, 15 warmups, median of 31 samples, 5 invocations per sample. The matched synchronous kernel covers candidate collection, runtime-owner routing, fetch repo selection, runtime repo routing, and request-head lookup.

Path Before After
Full runtime PR lookup kernel 8.280 ms 0.197 ms
Identity work 3,603,000 linear comparisons 3,600 identity reads + map lookups

That is about 42.1x faster for the measured lookup work. Deterministic scale tests also wait for all 128 runtime PR/issue responses and enforce linear identity-read bounds. With decorations hidden, the test proves zero repo/worktree identity reads while cache cleanup still runs.

Behavior and safety

  • preserves Array.find first-match behavior for duplicate repo IDs and paths, including ID-or-path precedence across local, SSH, and runtime hosts
  • keeps exact path equality, so Windows/Linux/macOS behavior is unchanged
  • keys caches by Orca's copy-on-write repo/worktree snapshots; WeakMap ownership does not retain superseded snapshots
  • preserves fail-closed handling for non-unique worktree IDs
  • no RPC/wire payload, persistence, dependency, Git command, mobile-facing surface, or provider contract change
  • existing request fanout is unchanged; this removes renderer lookup amplification around it

Validation

  • 214 focused GitHub refresh/owner-routing/leak tests passed
  • isolated refreshAllGitHub describe: 12 passed
  • pinned full suite: 49,432 passed / 97 skipped
  • full TypeScript typecheck passed
  • lint passed
  • full desktop/native build passed
  • changed-code quality and git diff --check passed
  • three adversarial readiness reviewers: no P0/P1/P2 findings

Full-suite command used the intended release baseline:

ORCA_CROSS_VERSION_BASELINE_REF=v1.4.177 pnpm test

Residual risk

The benchmark isolates synchronous renderer lookup work rather than packaged visibility-to-idle latency. No real SSH sleep/resume smoke or heap snapshot was taken; deterministic scaling and copy-on-write invalidation tests cover the changed contract.

@coderabbitai

coderabbitai Bot commented Aug 10, 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: 9ab7f81a-dfa7-40f7-94d5-8403bce41641

📥 Commits

Reviewing files that changed from the base of the PR and between 49ba9c5 and 5408439.

📒 Files selected for processing (2)
  • src/renderer/src/store/slices/github.test.ts
  • src/renderer/src/store/slices/github.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/store/slices/github.ts

📝 Walkthrough

Walkthrough

The change adds a cached GitHub repository lookup index with ID, path, and combined lookup methods. GitHub repository and worktree resolution now uses memoized indexes and supports missing collections. Refresh logic skips unnecessary work, reuses resolved repositories, and uses indexed iteration. Tests cover duplicate IDs, sparse matches, cache behavior, bounded identity reads, runtime dispatch, and inactive refresh views.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely identifies the main renderer performance change for GitHub resume lookups.
Description check ✅ Passed The description clearly covers the change, rationale, performance results, behavior, risks, and extensive validation.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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
📝 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: Pro Plus

Run ID: 1eb6f9c2-5d90-4279-8075-f2da2b007622

📥 Commits

Reviewing files that changed from the base of the PR and between 2ee43bf and 49ba9c5.

📒 Files selected for processing (4)
  • src/renderer/src/store/slices/github-repo-lookup-index.test.ts
  • src/renderer/src/store/slices/github-repo-lookup-index.ts
  • src/renderer/src/store/slices/github.test.ts
  • src/renderer/src/store/slices/github.ts

Comment on lines +5810 to +5827
const duplicateCandidates = mockApi.gh.enqueuePRRefresh.mock.calls
.map(([call]) => call.candidate)
.filter((candidate) => candidate.repoId === repoId)
expect(duplicateCandidates).toHaveLength(2)
expect(duplicateCandidates).toEqual(
expect.arrayContaining([
expect.objectContaining({
repoPath: '/first',
connectionId: 'first',
executionHostId: 'ssh:first'
}),
expect.objectContaining({
repoPath: '/first',
connectionId: 'first',
executionHostId: 'ssh:first'
})
])
)

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does Vitest expect.arrayContaining require duplicate expected elements to match distinct received elements?

💡 Result:

No, Vitest's expect.arrayContaining does not require duplicate expected elements to match distinct received elements [1][2]. The expect.arrayContaining matcher functions by verifying that the received array is a superset of the expected array [1][2]. It checks whether each element in the expected array exists somewhere in the received array; it does not perform a one-to-one mapping or verify counts, nor does it enforce that multiple instances of an element in the expected array must correspond to separate, distinct instances in the received array [1][2]. In practice, if you have an expected array like ['a', 'a'] and a received array like ['a', 'b', 'c'], expect.arrayContaining(['a', 'a']) will evaluate to true because 'a' is present in the received array, satisfying the subset requirement for each expected item individually [1][2]. This behavior is consistent with Jest, upon which Vitest's expect implementation is based [3][4][5]. If you require an exact match that accounts for both quantity and value (i.e., verifying the frequency of elements), expect.arrayContaining is not the appropriate tool, and you should instead use other matchers or a custom validation approach [6][7].

Citations:


🏁 Script executed:

#!/bin/sh
set -eu

file='src/renderer/src/store/slices/github.test.ts'
printf '%s\n' '--- relevant test context ---'
sed -n '5760,5840p' "$file"

printf '%s\n' '--- Vitest references ---'
rg -n '"vitest"|vitest@|expect\.arrayContaining' package.json package-lock.json pnpm-lock.yaml yarn.lock "$file" 2>/dev/null | head -80

Repository: stablyai/orca

Length of output: 2989


Tighten the duplicate-ID assertion so it checks every candidate.

expect.arrayContaining does not require duplicate expected entries to match distinct received elements. With toHaveLength(2), the second candidate could still contain repoPath: '/second' and connectionId: 'second' without failing this test. Assert the expected fields on each candidate.

…changed

Every eviction helper already returns its input reference untouched when it
evicts nothing, so the opening sweep in refreshAllGitHub can compare identities
and return the previous state. Window resume then stops waking every store
subscriber on a no-op sweep.

Folds in the remaining unique optimization from #13711, which this PR
supersedes on the lookup-indexing side.

Co-authored-by: Orca <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor Author

Superseding #13711 — folded in its unique optimization

#13711 and this PR overlap on refreshAllGitHub. I cross-applied each PR's test suite against the other's implementation to find out exactly what each one guarantees that the other does not.

Both carry the identical if (!shouldRefreshPRs && !shouldRefreshIssues) return early exit. Beyond that they fixed disjoint halves:

#13711 #13698
Linear lookups inside refreshAllGitHub ✅ (local Map) ✅ (shared index)
Linear lookups on the dispatch paths (fetchPRForBranch, findRepoForGitHubOwner) ❌ ✅
Skips redundant Zustand publication ✅ ❌ (until now)

The dispatch-path gap is the substantive one. Running #13698's scale tests against #13711 and doubling repoCount 128 → 256 separates constant factor from complexity:

  • keeps runtime PR dispatch identity reads linear: 51,072 → 200,448 reads (3.9x for a 2x input — still quadratic)
  • keeps runtime issue dispatch repo identity reads linear: 25,536 → 100,224 (3.9x — still quadratic)

#13711 only de-duplicated lookups within refreshAllGitHub, leaving each of the N dispatched fetches to re-scan all N repos. So this PR is the right base.

The one thing #13711 had that this PR didn't: it returned the previous state from the opening cache sweep when nothing changed. Every eviction helper already returns its input reference untouched on a no-op (evictStaleEntries github.ts:1643-1645, pruneExpiredPRRefreshStates :1765), so the sweep was allocating a fresh snapshot and waking every subscriber on each resume. Added in 5408439 with #13711's two publication tests ported over.

Correctness review

The highest-risk surface here is findRepoForGitHubOwner (7 call sites — it picks which token/connection a request uses); a divergence would route a request to the wrong host. Verified:

  • findByIdOrPath equivalence with Array.find — fuzzed against Array.find over randomized repo arrays with duplicate ids/paths, empty strings, and randomized interleaved query sequences on a shared partially-built index. No divergence. The !repoId guard matches the original repoId ? truthiness check exactly, so an empty-string repoId behaves identically.
  • WeakMap staleness — state.repos is never mutated in place anywhere in the renderer. reorderRepos (repos.ts:3641) builds a fresh array; the repos.push at :3636 targets a local Map bucket. No repo.id = / repo.path = assignments, and the store has no immer middleware (store/index.ts:57), so draft mutation isn't even reachable. Array identity is a faithful proxy for content identity.
  • buildWorktreeLookupIndex memo key — reads only worktreesByRepo and repos, and getRepoExecutionHostId is pure over the repo object, so the two-field key is sufficient.
  • findWorktreeById → .first — first is set on first-seen in iteration order (github.ts:993), exactly matching the old nested-loop early return.
  • Early return — everything after the opening set() is gated on shouldRefreshPRs/shouldRefreshIssues, and the return sits after the sweep, so cache eviction still runs.

Local: 199 focused tests, 2431 renderer store tests, tsc -p config/tsconfig.tc.web.json, oxlint, max-lines ratchet — all clean.

Follow-up (not blocking)

reconcileFetchedRepos (repo-identity-reconcile.ts:30-43) deliberately returns the previous array reference when nothing changed, which is what lets this WeakMap keep a warm index across no-op repos:changed echoes. But on the fetchRepos path that reference is immediately passed through applyManualRepoOrder (repos.ts:1907, :1992, :2062), which unconditionally allocates a new array — forcing a cold index on every repo fetch. Returning the input when the order is unchanged would materially extend this cache's reach. Orthogonal; worth a separate PR.

@nwparker
nwparker merged commit b44df2e into main Aug 11, 2026
44 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
* perf(renderer): index GitHub resume lookups

* perf(renderer): skip the resume cache sweep publication when nothing changed

Every eviction helper already returns its input reference untouched when it
evicts nothing, so the opening sweep in refreshAllGitHub can compare identities
and return the previous state. Window resume then stops waking every store
subscriber on a no-op sweep.

Folds in the remaining unique optimization from stablyai#13711, which this PR
supersedes on the lookup-indexing side.

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

---------

Co-authored-by: Orca <[email protected]>
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