Repository navigation
perf(ipc): index worktree owners instead of rescanning the repo list per lookup - #18416
Conversation
…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.
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (4)
Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe 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 Merge Risk: ⚪ Minimal · up to 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)
✅ Passed checks (3 passed)
Full details: Description checkExplanation 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.
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
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. Comment |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- Meta-table owner index —
getLocalRepoForRegisteredWorktreenow walksgetAllWorktreeMeta()once (built lazily via??=inside the.findpredicate) and collects matching repo ids into aSet, replacing the per-repoObject.keyssnapshot +splitWorktreeIdrescan. - Repo-row lookup grouping —
createRepoRowExecutionHostLookupgroupsreposinto aMap<string, T[]>once at construction, sobyId/byHostno longer re-filterthe list per call; row order is preserved sorows[0]still selects the same owner. - Regression-guard tests — counter-based tests pin the single-pass behavior (
metaScans,splitWorktreeIdcalls,idgetter reads) and cover equivalence:getReposprecedence, laziness (zero scans on a direct path match), SSH exclusion both ways, resolved-path spelling, folder workspaces, andambiguous/missing/resolved/byHostsemantics.
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.
DeepSeek Pro (free via Pullfrog for OSS) | 𝕏
|
Bot review triage:
CI is green on |
…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.

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)hasRegisteredWorktreeMetaForReporan per repo insiderepos.find(...), and each run didObject.keys(store.getAllWorktreeMeta())— a fresh array allocation over the whole table — plus asplitWorktreeId(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) andsrc/main/ipc/filesystem-list-files.ts:41(every File Explorer expand), plusgit: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:
Correction to the original report: the brief attributed the R x M term to
path.resolve. It isn't — the original short-circuits onparsed?.repoId === repoIdbefore callingcomparableLocalPath, sopath.resolvewas already ~O(M) in total. The genuine R x M terms are the per-repoObject.keys()snapshot and the R x MsplitWorktreeIdcalls (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)rowsForwasrepos.filter(...): a fresh O(repos) scan plus an array allocation on everybyId/byHostcall, plus aSetallocation insidebyId. 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.Measurement
Benchmarks:
nice -n 10 nodeon 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: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:
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 stillObject.keys(own enumerable keys only — notfor...in, which would also walk the prototype chain).getRepos()precedence is preserved. The original short-circuits on the first matching repo ingetRepos()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:middlewins overlastbecausemiddlecomes first ingetRepos(), regardless of meta-table insertion order.??=, so a store where every candidate repo matches by path still never callsgetAllWorktreeMeta— same trigger condition as before, just memoised. Tested (metaScans() === 0).getRepos()/getAllWorktreeMeta()change between two IPC calls is seen immediately, as before.!repo.connectionIdstill 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).undefined; the meta table is the same table, keyed the same way, andsplitWorktreeIdis unchanged (in particular the::workspace:<uuid>suffix is still not stripped here, exactly as before).comparableLocalPath(resolve+toLowerCaseonwin32). Nothing was moved out of that helper.typeof store.getRepos !== 'function'andtypeof store.getAllWorktreeMeta !== 'function'guards are both preserved and tested.Finding 2.
Mappreserves insertion order and the groups are built by iteratingreposin order and pushing, so each group is the same arrayrepos.filter(...)produced — same members, same order.rows[0]therefore selects the same owner.rows.length === 0 -> missingbecomes!rows[0] -> missing. These differ only if index 0 of a non-empty group were nullish, which cannot happen: building the group already dereferencedrepo.id.new Set(rows.map(hostId)).size > 1becomesrows.some(hostId !== rows[0].hostId). Identical predicate (a set of size > 1 means some element differs from the first), one fewer array and one fewer Set allocated, and it short-circuits.|| !owner -> ambiguousarm of the original was unreachable for a non-empty group; it is now folded intomissing. Same observable outcomes.ambiguous/missing/resolvedandbyHosthit/miss are all covered by new tests, and the 14 existingresolveWorktreeExecutionHosttests — which drive the real cross-host leak cases from [Bug]: SSH worktree/terminal operations are validated locally instead of routing to the connected SSH target (DaemonProtocolError: working directory does not exist) #11163 / [Bug]: Remote host attempting to view a file results in error #6648 / Host-blind connectionId resolution can hand a client-owned SSH connection to a runtime (duplicate repo rows) #17799 — pass unchanged.byIdusessomeandbyHostusesfind, neither mutates, so sharing them across calls is safe.Scope:
src/main/ipc/remote-workspace.tsis 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
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 1getAllWorktreeMetacall and exactly 200splitWorktreeIdcalls), 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 (getReposprecedence), 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 missinggetRepos/getAllWorktreeMeta.src/shared/worktree-execution-host-resolution.test.ts— counter guard (150 lookups against one factory read the repo rows zero additional times), plusmissing/ambiguous/resolved-with-agreeing-rows (stillrows[0]) andbyHosthit/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
Verified locally (see the Test plan section above for the exact commands): 5 test files / 63 tests pass,
tsc --noEmitclean for both the node and web projects,oxlintclean 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 fromcomparableLocalPath, which is untouched and still applies thewin32toLowerCasebranch.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
Setmembership predicate is the same question the old per-repo path check asked, androws.some(hostId !== rows[0].hostId)is the same predicate asnew Set(hostIds).size > 1.getRepos()precedence, laziness, SSH exclusion, and folder-workspace behaviour are each pinned by a test.Agent skill upstream boundary
Notes
comparableLocalPath(resolve+toLowerCaseonwin32); no separator assumptions were added.!repo.connectionIdstill 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 thelive/unverifiable/exitedvocabulary does not apply.undefined; the::workspace:<uuid>suffix is still not stripped here, exactly as before.Checklist
N/Awith reason for visual proof — no UI or interaction change