Skip to content

perf(ipc): index worktree owners instead of rescanning the repo list per lookup - #18416

Merged
nwparker merged 1 commit into
mainfrom
perf/repo-worktree-owner-index
Sep 4, 2026
Merged

nwparker merged 1 commit into
mainfrom
perf/repo-worktree-owner-index

Conversation

@nwparker

@nwparker nwparker commented Sep 3, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​208 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​207
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​36 $\color{#cf222e}{\Huge{\mathbf{−}}}$​13 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​23

ELI5

Two little "who owns this folder?" questions had a bad habit. Instead of reading the address book once and remembering it, they re-read the whole book from the start for every single name they checked. With one address book of 1,334 entries and 20 names to check, that's 20 full readings of the book — for one question the app asks on every keystroke in Quick Open and every time you expand a folder in the File Explorer.

This PR reads the book once. Same answers, same order of preference, just not re-read 20 times.

Why it matters

Finding 1 — getLocalRepoForRegisteredWorktree (src/main/ipc/local-worktree-runtime-options.ts)

hasRegisteredWorktreeMetaForRepo ran per repo inside repos.find(...), and each run did Object.keys(store.getAllWorktreeMeta()) — a fresh array allocation over the whole table — plus a splitWorktreeId (two substring allocations + an object) per row. That is R full table walks per call.

There are 59 call sites, including src/main/ipc/filesystem-search-file-paths.ts:49 (once per Quick Open keystroke) and src/main/ipc/filesystem-list-files.ts:41 (every File Explorer expand), plus git:status / git:diff / git:index.

At the reported real scale (1,334 metadata rows, 20 repos, worst case = worktree owned by the last repo), on this machine under load:

current (O(R*M)) : 8.739 ms/call
indexed (O(M+R)) : 1.697 ms/call   (5.1x)

Correction to the original report: the brief attributed the R x M term to path.resolve. It isn't — the original short-circuits on parsed?.repoId === repoId before calling comparableLocalPath, so path.resolve was already ~O(M) in total. The genuine R x M terms are the per-repo Object.keys() snapshot and the R x M splitWorktreeId calls (26,680 vs 1,334 at the reported scale). The regression guard counts those instead, which is why it is a real guard rather than one that passes either way.

Finding 2 — createRepoRowExecutionHostLookup (src/shared/worktree-execution-host-resolution.ts)

rowsFor was repos.filter(...): a fresh O(repos) scan plus an array allocation on every byId/byHost call, plus a Set allocation inside byId. It is called once per worktree key per target by the remote-workspace export path, and by the renderer's copy of the same resolution.

filter-per-call  : 0.2593 ms per 200-key pass   (20 repos)
grouped-once     : 0.0792 ms per 200-key pass   (3.3x)

Measurement

Benchmarks: nice -n 10 node on a loaded machine, 2,000 iterations after a 200-iteration warmup (finding 1) and 5,000 iterations after 500 (finding 2). Absolute numbers run high because the box is loaded; the ratio is the signal and it reproduced across runs (5.1x / 6.1x, 3.3x / 11.8x).

Regression guards fail without the change

Both source files reverted (git stash), tests kept:

 FAIL  src/shared/worktree-execution-host-resolution.test.ts > createRepoRowExecutionHostLookup > scans the repo list once for the factory, never again per lookup
AssertionError: expected 450 to be +0 // Object.is equality

- Expected
+ Received

- 0
+ 450

 ❯ src/shared/worktree-execution-host-resolution.test.ts:202:23
    200|       lookup.byHost('b', 'ssh:m4air')
    201|     }
    202|     expect(idReads()).toBe(afterBuild)
       |                       ^
    203|   })

 FAIL  src/main/ipc/local-worktree-runtime-options.test.ts > getLocalRepoForRegisteredWorktree > walks the worktree meta table once, not once per repo
AssertionError: expected 10 to be 1 // Object.is equality

- Expected
+ Received

- 1
+ 10

 ❯ src/main/ipc/local-worktree-runtime-options.test.ts:63:25
     61|
     62|     expect(getLocalRepoForRegisteredWorktree(store, target, target)?.i…
     63|     expect(metaScans()).toBe(1)
       |                         ^
     64|     expect(counter.splitCalls).toBe(rowCount)
     65|   })

 Test Files  2 failed (2)
      Tests  2 failed | 23 passed (25)

The 23 passing tests in that run are the equivalence cases — they pass against the original implementation too, which is the point: they pin behaviour, the two counters pin the complexity.

After the change:

 Test Files  2 passed (2)
      Tests  25 passed (25)

Correctness

Finding 1. The predicate is unchanged and side-effect free; only evaluation order moves. hasRegisteredWorktreeMetaForRepo(store, repo.id, paths) asked "is there a row with this repoId whose path is a candidate?"; collectRepoIdsWithRegisteredWorktreeMeta(store, paths).has(repo.id) asks the same question of a set built from exactly the rows satisfying the path half. Iteration is still Object.keys (own enumerable keys only — not for...in, which would also walk the prototype chain).

  • getRepos() precedence is preserved. The original short-circuits on the first matching repo in getRepos() order, and so does this one — repos.find(...) is untouched; only the body of the second disjunct changed. Explicitly tested with two repos that both own the path: middle wins over last because middle comes first in getRepos(), regardless of meta-table insertion order.
  • Laziness is preserved exactly. The set is built on first need via ??=, so a store where every candidate repo matches by path still never calls getAllWorktreeMeta — same trigger condition as before, just memoised. Tested (metaScans() === 0).
  • Invalidation: the set is a local, built and discarded inside one call. There is no cache across calls, so no staleness window and nothing to invalidate. A getRepos()/getAllWorktreeMeta() change between two IPC calls is seen immediately, as before.
  • SSH: !repo.connectionId still gates the whole predicate, so an SSH repo is excluded even when it owns the registered worktree. Tested both ways — with a local rival present (local repo wins) and alone (undefined, not the SSH repo).
  • Folder workspaces: unchanged. A folder workspace that is not a registered worktree still resolves to undefined; the meta table is the same table, keyed the same way, and splitWorktreeId is unchanged (in particular the ::workspace:<uuid> suffix is still not stripped here, exactly as before).
  • Windows: path comparison still goes through the same comparableLocalPath (resolve + toLowerCase on win32). Nothing was moved out of that helper.
  • Empty/missing state: the typeof store.getRepos !== 'function' and typeof store.getAllWorktreeMeta !== 'function' guards are both preserved and tested.

Finding 2. Map preserves insertion order and the groups are built by iterating repos in order and pushing, so each group is the same array repos.filter(...) produced — same members, same order. rows[0] therefore selects the same owner.

Scope: src/main/ipc/remote-workspace.ts is deliberately untouched — this is the complementary fix inside the factory and stacks cleanly on #18410.

Negative user-facing trade-offs

None. No cap, cadence, debounce, threshold, sampling, or staleness window was introduced; both indexes are built and discarded within a single call/factory lifetime, so every lookup still sees the current store state and returns the identical repo.

Test plan

nice -n 10 node_modules/.bin/vitest run --config config/vitest.config.ts \
  src/shared/worktree-execution-host-resolution.test.ts \
  src/main/ipc/local-worktree-runtime-options.test.ts \
  src/main/runtime/worktree-launch-host-repo.test.ts \
  src/main/ipc/filesystem-list-files.test.ts \
  src/main/ipc/filesystem-search-file-paths.test.ts
# Test Files 5 passed (5) | Tests 63 passed (63)

nice -n 10 node_modules/.bin/tsc --noEmit -p config/tsconfig.node.json --composite false   # clean
nice -n 10 node_modules/.bin/tsc --noEmit -p config/tsconfig.tc.web.json --composite false # clean (finding 2 is shared code the renderer imports)
node_modules/.bin/oxlint <changed files>                                                   # clean

New tests:

  • src/main/ipc/local-worktree-runtime-options.test.ts (new file) — counter guard (200 meta rows, 10 repos, owner is the last repo: exactly 1 getAllWorktreeMeta call and exactly 200 splitWorktreeId calls), a "never touches the meta table when a repo path matches" guard, and equivalence for: owner is the first repo, owner is the last repo, no owner, two repos owning the same path (getRepos precedence), an SSH repo that owns the worktree (excluded, with and without a local rival), the resolved-path spelling, a folder workspace that is not a registered worktree, and a store missing getRepos / getAllWorktreeMeta.
  • src/shared/worktree-execution-host-resolution.test.ts — counter guard (150 lookups against one factory read the repo rows zero additional times), plus missing / ambiguous / resolved-with-agreeing-rows (still rows[0]) and byHost hit/miss/order.

Linked Issue

No tracked issue — this came out of a performance audit of the IPC hot paths (Quick Open keystrokes, File Explorer expand, git:status/git:diff/git:index), not a filed bug.

Visual Proof

N/A — no UI, layout, or interaction change. Both edits are pure lookup-internals in main/shared code; every call returns the identical repo it returned before, so there is nothing to show a before/after of.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated

Verified locally (see the Test plan section above for the exact commands): 5 test files / 63 tests pass, tsc --noEmit clean for both the node and web projects, oxlint clean on the changed files. Both regression guards were confirmed to fail against the pre-change implementations. Platform: macOS; the changed code is platform-independent apart from comparableLocalPath, which is untouched and still applies the win32 toLowerCase branch.

Review

Two behaviour-preserving index builds, both scoped to a single call/factory lifetime. The equivalence argument for each is spelled out in the Correctness section: the Set membership predicate is the same question the old per-repo path check asked, and rows.some(hostId !== rows[0].hostId) is the same predicate as new Set(hostIds).size > 1. getRepos() precedence, laziness, SSH exclusion, and folder-workspace behaviour are each pinned by a test.

Agent skill upstream boundary

  • Not applicable — no skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation is copied or translated here.

Notes

  • Security: no new input surface; both indexes are built from data the callers already hold.
  • Cross-platform: path comparison still goes through the unchanged comparableLocalPath (resolve + toLowerCase on win32); no separator assumptions were added.
  • Remote SSH: !repo.connectionId still gates the whole predicate, so an SSH repo is never returned as the local owner — tested with and without a competing local repo. Nothing here reports on, stops, or lists remote work, so the live/unverifiable/exited vocabulary does not apply.
  • Mobile: untouched.
  • Backwards compatibility / remote wire: nothing crosses the wire; no RPC params, stream frames, or published content change, so a mixed-version client/host pair sees exactly what it saw before.
  • Folder workspaces: a folder workspace that is not a registered worktree still resolves to undefined; the ::workspace:<uuid> suffix is still not stripped here, exactly as before.
  • Git provider: no provider-specific code paths involved.
  • Performance: the point of the PR — O(R*M) to O(M+R) for finding 1, and O(repos) per lookup to O(1) for finding 2.

Checklist

  • This PR is small and focused (2 prod files, +36/-13)
  • I explained what changed and why (including ELI5)
  • N/A with reason for visual proof — no UI or interaction change
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • Typecheck, targeted tests, and lint pass locally; CI covers the rest

…per lookup

Two hot lookups rescanned a whole table once per repo.

`getLocalRepoForRegisteredWorktree` (59 IPC call sites, including Quick Open
keystrokes and every File Explorer expand) walked the entire worktree-meta table
once per repo. One pass now collects the owning repo ids, built lazily so a repo
whose own path matches still never touches the table.

`createRepoRowExecutionHostLookup` re-filtered the repo array on every `byId` /
`byHost` call. Rows are grouped into a Map once at construction, preserving
repo-list order so `rows[0]` still picks the same owner.
@coderabbitai

coderabbitai Bot commented Sep 3, 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: Team

Run ID: a6ddbde1-a683-4543-8032-2427d4bbef0c

📥 Commits

Reviewing files that changed from the base of the PR and between 4cc0b8d and 90b5a42.

📒 Files selected for processing (4)
  • src/main/ipc/local-worktree-runtime-options.test.ts
  • src/main/ipc/local-worktree-runtime-options.ts
  • src/shared/worktree-execution-host-resolution.test.ts
  • src/shared/worktree-execution-host-resolution.ts

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


📝 Walkthrough

Walkthrough

The change reduces repeated repository scans in two lookup paths. Local worktree resolution scans worktree metadata at most once per call and reuses the matching repository IDs. Execution host resolution groups repository rows by ID when the lookup is created, then reuses the groups for byId and byHost queries. Tests verify scan counts and preserve existing lookup results across missing, ambiguous, resolved, path, SSH, and ordering scenarios.

Merge Risk: ⚪ Minimal · up to 90b5a

This change optimizes worktree and execution-host lookups while preserving existing resolution behavior and ordering. No current merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 5 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description is detailed and covers the change, rationale, testing, correctness, scope, risks, and checklist. However, the required Linked Issue entry is missing, despite the template stating that … Add a tracked issue reference under Linked Issue, using the required Fixes #<issue-number> format.
✅ Passed checks (3 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly and concisely describes the primary performance change: indexing worktree owners instead of rescanning repository data for each lookup.
Full details: Description check

Explanation

The description is detailed and covers the change, rationale, testing, correctness, scope, risks, and checklist. However, the required Linked Issue entry is missing, despite the template stating that an issue must always be provided.

  • Fix all pre-merge checks with AI
✨ 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

  • Meta-table owner index — getLocalRepoForRegisteredWorktree now walks getAllWorktreeMeta() once (built lazily via ??= inside the .find predicate) and collects matching repo ids into a Set, replacing the per-repo Object.keys snapshot + splitWorktreeId rescan.
  • Repo-row lookup grouping — createRepoRowExecutionHostLookup groups repos into a Map<string, T[]> once at construction, so byId/byHost no longer re-filter the list per call; row order is preserved so rows[0] still selects the same owner.
  • Regression-guard tests — counter-based tests pin the single-pass behavior (metaScans, splitWorktreeId calls, id getter reads) and cover equivalence: getRepos precedence, laziness (zero scans on a direct path match), SSH exclusion both ways, resolved-path spelling, folder workspaces, and ambiguous/missing/resolved/byHost semantics.

The two transformations are behavior-preserving: the Set membership predicate is identical to the old per-repo path check, and the ambiguity check (rows.some(hostId !== rows[0].hostId)) is equivalent to the old new Set(hostIds).size > 1. Both indexes are built and discarded within a single call/factory lifetime, so there is no cross-call staleness surface, and nothing crosses the wire.

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

@nwparker

nwparker commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Bot review triage:

  • pullfrog — "No new issues found." Nothing to action.
  • coderabbitai review — "No actionable comments were generated", merge risk minimal. Nothing to action.
  • coderabbitai pre-merge check "Description check" (⚠️) — fixed. The body now carries the missing template sections: Linked Issue, Visual Proof (N/A with reason — no UI or interaction change), Testing, Review, Agent skill upstream boundary, Notes, and Checklist.
  • coderabbitai pre-merge check "Docstring Coverage" (⚠️, 40% vs an 80% threshold, 5 functions) — declined. This repo's AGENTS.md explicitly requires "Concise/Brief Non-obvious Comments ONLY … DO NOT be verbose, explain the obvious, walk through the code", so blanket docstrings on every touched function are against house style. The two functions where the why is non-obvious already carry a one-line doc comment (collectRepoIdsWithRegisteredWorktreeMeta in src/main/ipc/local-worktree-runtime-options.ts and createRepoRowExecutionHostLookup in src/shared/worktree-execution-host-resolution.ts, the latter explaining why the grouping is hoisted to construction). The remainder are the test-local counter helpers and the unchanged getLocalRepoForRegisteredWorktree, where a docstring would only restate the name.

CI is green on 90b5a429 (static analysis, typecheck, all 8 test shards, both package jobs), and the two touched source files are byte-identical between the PR base and current main, so the 47-commit drift carries no conflict — textual or semantic. No code changed in this pass, so the measured win (5.1x on getLocalRepoForRegisteredWorktree, 3.3x on the byId/byHost lookup) stands as reported.

@nwparker
nwparker merged commit 7ed86a9 into main Sep 4, 2026
29 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…per lookup (stablyai#18416)

Two hot lookups rescanned a whole table once per repo.

`getLocalRepoForRegisteredWorktree` (59 IPC call sites, including Quick Open
keystrokes and every File Explorer expand) walked the entire worktree-meta table
once per repo. One pass now collects the owning repo ids, built lazily so a repo
whose own path matches still never touches the table.

`createRepoRowExecutionHostLookup` re-filtered the repo array on every `byId` /
`byHost` call. Rows are grouped into a Map once at construction, preserving
repo-list order so `rows[0]` still picks the same owner.
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