Repository navigation
perf(vault): dedupe scope paths by key instead of rescanning - #11314
Conversation
#11303 took the session maps off the workspace-switch path, but scope path derivation still follows the active worktree and stayed quadratic. addAiVaultWorkspaceScopePath deduped by re-normalizing every already accepted path on each insert, so accepting K paths cost O(K^2) normalize('NFC') calls — ~632k at 1124 workspaces. isAiVaultWorkspaceScopePathClaimed separately rescanned every live worktree per prior id, and runs twice per switch via activeWorktreePaths and scopePaths. - carry a Set of comparison keys alongside the paths, so each insert is one normalize plus one Set lookup - thread that accumulator from the workspace pass into the project pass rather than restarting deduplication against a plain array - build one comparison-path -> worktree id map for the claim check, keeping first-writer-wins to match the previous some() short-circuit deriveAiVaultScopeSessionPaths on a real 1124-workspace profile: 189.7ms -> 0.8ms. Output is unchanged, including ordering: verified against the previous implementation across 117 scenario/option combinations covering monorepo and mixed-repo layouts, priors both claimed and unclaimed, duplicate paths, NFD/NFC, WSL UNC, trailing and doubled separators, relative and blank paths, and four project-key shapes. Adds the first test file for this module: scope semantics (priors, claimed priors, cross-repo rejection, dedupe, NFD/NFC) plus a timing guard. Verified fail-first — the guard reports 220ms on the previous implementation. Path length is chosen deliberately, since normalize() cost scales with it and short synthetic paths understate the old shape.
Greptile SummaryReplaces the O(n²) deduplication in
Confidence Score: 5/5Safe to merge — the refactored dedup logic is semantically equivalent to the original and the ordering-sensitive claim-check edge case from the previous review is explicitly fixed and covered by a new test. Both algorithmic changes (accumulator-based dedup and pre-built claim set) are correct: the accumulator preserves insertion order and first-spelling wins, matching the original; the claim set excludes the active worktree by ID rather than by position, so a claimant that shares the prior path is never masked regardless of list ordering. The new test file covers all semantically meaningful cases — claimed vs unclaimed priors, cross-repo rejection, separator/NFD/NFC normalization, relative/blank paths, and timing regression guards for both exported functions at realistic scale. No pre-existing paths through this logic are left unguarded. Files Needing Attention: No files require special attention.
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/right-sidebar/ai-vault-scope-paths.ts | Replaces O(n²) dedup scan with a ScopePathAccumulator (Set + array), threads the accumulator across workspace and project passes, and pre-builds a claim set that excludes the active worktree by ID — fixing both the quadratic normalize cost and the ordering-dependent claim semantics flagged in the previous review. |
| src/renderer/src/components/right-sidebar/ai-vault-scope-paths.test.ts | New test file covering workspace and session scope semantics: prior paths, claimed/unclaimed priors, ordering-independent claim detection, cross-repo rejection, separator/trailing-slash dedupe, NFD/NFC folding, relative paths, and performance regression guards for both deriveAiVaultWorkspaceScopePaths and deriveAiVaultScopeSessionPaths. |
Flowchart
%%{init: {'theme': 'neutral'}}%%
flowchart TD
A["deriveAiVaultScopeSessionPaths(activeWorktree, liveWorktrees)"] --> B{activeWorktree null?}
B -- yes --> C["return []"]
B -- no --> D["collectWorkspaceScopePaths(activeWorktree, liveWorktrees)"]
D --> E["createScopePathAccumulator()\n{ paths: [], comparisonKeys: Set }"]
E --> F["addAiVaultWorkspaceScopePath(acc, activeWorktree.path)"]
F --> G{priorWorktreeIds\nnon-empty?}
G -- yes --> H["buildClaimedComparisonPaths(liveWorktrees, activeWorktree)\nSkips worktree.id === activeWorktree.id\n→ Set of comparison keys owned by others"]
G -- no --> I["claimedComparisonPaths = null"]
H --> J["For each priorWorktreeId\nparse → repoId check → claim check → addAiVaultWorkspaceScopePath"]
I --> J
D --> K["ScopePathAccumulator (carry forward)"]
K --> L["Project pass: iterate liveWorktrees\naddAiVaultWorkspaceScopePath(acc, worktree.path)"]
L --> M["Setup pass: iterate projection.setups\naddAiVaultWorkspaceScopePath(acc, setup.path)"]
M --> N["return accumulator.paths"]
subgraph addAiVaultWorkspaceScopePath
P["trim + isAbsolute check"] --> Q["normalizeRuntimePathForComparison(trimmedPath)"]
Q --> R{comparisonKeys.has?}
R -- yes --> S["return (skip duplicate)"]
R -- no --> T["comparisonKeys.add(key)\npaths.push(trimmedPath)"]
end
Reviews (2): Last reviewed commit: "fix(vault): make the claim check indepen..." | Re-trigger Greptile
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughRefactors AI Vault scope path derivation around a shared accumulator containing paths and normalized comparison keys. Workspace ownership checks use precomputed claimed normalized paths, while session derivation reuses deduplication state across workspace and project paths and returns no paths without an active worktree. Adds tests covering workspace ownership, renamed paths, repository filtering, separator and Unicode normalization, and performance with 1200 worktrees. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 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 |
Review catch on the first pass: keying claims by comparison path meant a duplicate path had to pick one owner, and picking the active worktree masked a real claimant later in the list. Concretely, with the active worktree also listed at its own prior path, the prior was reported unclaimed where the previous some() reported it claimed. Excludes the active worktree while building the set instead of comparing ids at read time, so any surviving entry is a claim by construction and ordering cannot decide the result. Adds a test over four orderings, verified fail-first against the previous commit. Also adds a timing guard for deriveAiVaultWorkspaceScopePaths, which the session-scope guard did not cover. Equivalence rerun against the pre-optimization implementation: 156 scenario/option combinations, identical paths and ordering.
|
Both review comments were valid — fixed in 624fc12. 1. First-writer-wins ordering (P2) — real bug, not just theoretical. I reproduced it directly: Greptile framed it as reachable only when two live worktrees share a path, which git prevents. But the trigger is narrower and doesn't need two distinct worktrees to collide: it fires when the active worktree itself is listed at its own prior path. My original 117-combination equivalence sweep missed it because none of those datasets had the active worktree occupying the prior path. Fixed by excluding the active worktree while building the set rather than comparing ids at read time — any surviving entry is then a claim by construction, so ordering can't decide the result. That also removes the ordering dependency from the interface entirely, which was the reviewer's underlying point. Worth noting: my first attempt at a regression test for this passed on the buggy code (wrong shape — the claimant differed from the active path, so the map never picked the active worktree as owner). The committed test uses the active worktree listed at the prior path across four orderings, and is verified fail-first against d48c7d1: 2. Missing timing guard on Added, at the same 1200-worktree scale, with 25 priors so the claim check (the other per-call scan in that function) is exercised too. Re-verified after the fix: equivalence extended to 156 scenario/option combinations across 12 datasets, including the ordering cases — identical paths and ordering. 4940 tests pass, tsc and oxlint clean, and On the CodeRabbit description-template warning: this is an internal perf change with no visual surface, so screenshots don't apply. |
* test(vault): guard the workspace-switch regression #11303 fixed (#11311) #11303 removed the O(sessions x roots) path normalization from the session worktree map, but nothing fails if that shape comes back. Adds the two checks that were missing, plus the tool that would have caught it. - timing guard: 1200 worktrees x 400 sessions must build in <150ms. Verified fail-first — restoring the pre-#11303 per-session buildWorktreeCandidates call takes it to 238ms; it is ~15ms as merged. - path boundary: '/repo/alpha-sibling' must not be attributed to '/repo/alpha'. Hoisting the root normalization out of the loop must not degrade containment into a bare startsWith. Also adds tools/benchmarks/workspace-switch-paint-latency.mjs, which attaches over CDP and measures first-paint-after-click and max frame gap. The existing worktree-switch-responsiveness.spec.ts only times the synchronous click task, which stays ~1ms because the highlight is a direct DOM mutation — that is why a ~1s stall could ship without tripping a budget. On the affected build it read maxFrameGap p50=973ms. (cherry picked from commit c5102e1) * perf(vault): dedupe scope paths by key instead of rescanning (#11314) * perf(vault): dedupe scope paths by key instead of rescanning #11303 took the session maps off the workspace-switch path, but scope path derivation still follows the active worktree and stayed quadratic. addAiVaultWorkspaceScopePath deduped by re-normalizing every already accepted path on each insert, so accepting K paths cost O(K^2) normalize('NFC') calls — ~632k at 1124 workspaces. isAiVaultWorkspaceScopePathClaimed separately rescanned every live worktree per prior id, and runs twice per switch via activeWorktreePaths and scopePaths. - carry a Set of comparison keys alongside the paths, so each insert is one normalize plus one Set lookup - thread that accumulator from the workspace pass into the project pass rather than restarting deduplication against a plain array - build one comparison-path -> worktree id map for the claim check, keeping first-writer-wins to match the previous some() short-circuit deriveAiVaultScopeSessionPaths on a real 1124-workspace profile: 189.7ms -> 0.8ms. Output is unchanged, including ordering: verified against the previous implementation across 117 scenario/option combinations covering monorepo and mixed-repo layouts, priors both claimed and unclaimed, duplicate paths, NFD/NFC, WSL UNC, trailing and doubled separators, relative and blank paths, and four project-key shapes. Adds the first test file for this module: scope semantics (priors, claimed priors, cross-repo rejection, dedupe, NFD/NFC) plus a timing guard. Verified fail-first — the guard reports 220ms on the previous implementation. Path length is chosen deliberately, since normalize() cost scales with it and short synthetic paths understate the old shape. * fix(vault): make the claim check independent of worktree ordering Review catch on the first pass: keying claims by comparison path meant a duplicate path had to pick one owner, and picking the active worktree masked a real claimant later in the list. Concretely, with the active worktree also listed at its own prior path, the prior was reported unclaimed where the previous some() reported it claimed. Excludes the active worktree while building the set instead of comparing ids at read time, so any surviving entry is a claim by construction and ordering cannot decide the result. Adds a test over four orderings, verified fail-first against the previous commit. Also adds a timing guard for deriveAiVaultWorkspaceScopePaths, which the session-scope guard did not cover. Equivalence rerun against the pre-optimization implementation: 156 scenario/option combinations, identical paths and ordering. (cherry picked from commit 6cc579a) * perf(vault): look up resume worktrees through the shared index (#11317) Resolving a session's resume target scanned every worktree in every repo: two `Object.values(worktreesByRepo).flat().find(...)` calls, which also allocate a fresh 1124-element array each time, plus an equivalent `some()` walk. All three run per visible session row, so a panel render repeated them ~20 times. `getIndexedWorktreeMap` already exists for this and is WeakMap-cached on `worktreesByRepo`, so the index is built once per store snapshot rather than per call. `connection-owner-resolution.ts` already resolves worktrees this way. ~1.6ms -> ~0.002ms per render pass at 1124 worktrees. Net -4 lines. Behavior is unchanged: the map dedupes by id, which only diverges from `find()` when one id appears twice with different objects. Worktree ids are `repoId::path`, so a duplicate id within a repo array — the documented race the index was built for — refers to the same worktree. (cherry picked from commit b4b3bcd)
…i#11314) * perf(vault): dedupe scope paths by key instead of rescanning stablyai#11303 took the session maps off the workspace-switch path, but scope path derivation still follows the active worktree and stayed quadratic. addAiVaultWorkspaceScopePath deduped by re-normalizing every already accepted path on each insert, so accepting K paths cost O(K^2) normalize('NFC') calls — ~632k at 1124 workspaces. isAiVaultWorkspaceScopePathClaimed separately rescanned every live worktree per prior id, and runs twice per switch via activeWorktreePaths and scopePaths. - carry a Set of comparison keys alongside the paths, so each insert is one normalize plus one Set lookup - thread that accumulator from the workspace pass into the project pass rather than restarting deduplication against a plain array - build one comparison-path -> worktree id map for the claim check, keeping first-writer-wins to match the previous some() short-circuit deriveAiVaultScopeSessionPaths on a real 1124-workspace profile: 189.7ms -> 0.8ms. Output is unchanged, including ordering: verified against the previous implementation across 117 scenario/option combinations covering monorepo and mixed-repo layouts, priors both claimed and unclaimed, duplicate paths, NFD/NFC, WSL UNC, trailing and doubled separators, relative and blank paths, and four project-key shapes. Adds the first test file for this module: scope semantics (priors, claimed priors, cross-repo rejection, dedupe, NFD/NFC) plus a timing guard. Verified fail-first — the guard reports 220ms on the previous implementation. Path length is chosen deliberately, since normalize() cost scales with it and short synthetic paths understate the old shape. * fix(vault): make the claim check independent of worktree ordering Review catch on the first pass: keying claims by comparison path meant a duplicate path had to pick one owner, and picking the active worktree masked a real claimant later in the list. Concretely, with the active worktree also listed at its own prior path, the prior was reported unclaimed where the previous some() reported it claimed. Excludes the active worktree while building the set instead of comparing ids at read time, so any surviving entry is a claim by construction and ordering cannot decide the result. Adds a test over four orderings, verified fail-first against the previous commit. Also adds a timing guard for deriveAiVaultWorkspaceScopePaths, which the session-scope guard did not cover. Equivalence rerun against the pre-optimization implementation: 156 scenario/option combinations, identical paths and ordering.
Follow-up to #11303 and #11311.
#11303 took the two session maps off the workspace-switch path. Scope path derivation still follows the active worktree, and was still quadratic — so it remains on the click path at full cost.
Cause
addAiVaultWorkspaceScopePath(ai-vault-scope-paths.ts:98) deduped by re-normalizing every already-accepted path on every insert:Accepting K paths costs O(K²)
normalize('NFC')calls — ~632k at 1124 workspaces.normalizeRuntimePathForComparisonis the same ICU-backed primitive that made #10841 visible.Separately,
isAiVaultWorkspaceScopePathClaimedrescanned every live worktree once per prior id, and runs twice per switch (viaactiveWorktreePathsandscopePathsinAiVaultPanel.tsx:114,133).Fix
Setof comparison keys alongside the paths — one normalize + one lookup per insert.comparison path → worktree idmap for the claim check, keeping first-writer-wins to match the previoussome()short-circuit order.Results
deriveAiVaultScopeSessionPathson a real 1124-workspace profile: 189.7ms → 0.8ms.Correctness
Output is unchanged including ordering — verified against the previous implementation across 117 scenario/option combinations over 9 datasets:
Tests
This module had no test file. Adds one covering the scope semantics that were previously unpinned — prior paths, priors claimed by a live workspace, cross-repo rejection, separator/trailing-slash dedupe, NFD/NFC folding — plus a timing guard.
The guard is verified fail-first: 220ms on the previous implementation, ~1ms here.
One detail worth flagging: path length matters as much as count, because
normalize()cost scales with it. My first version of the guard used short synthetic paths (/repo/w0) and passed on the broken code at 77ms — a false guard. It now uses ~50-character paths matching the real profile.Verification
right-sidebar/andshared/tsc --noEmit -p config/tsconfig.tc.web.jsoncleanoxlintcleanRemaining, not in this PR
ai-vault-resume-target.ts:134,161andai-vault-session-resume.ts:169doObject.values(worktreesByRepo).flat().find(...)per visible row (~3ms/render at this scale);getIndexedWorktreeMapalready exists for exactly this. Andchecks-panel-terminal-worktree.ts:97still normalizes inside a sort comparator — same shape #11303 fixed, different panel.