Skip to content

perf(vault): dedupe scope paths by key instead of rescanning - #11314

Merged
nwparker merged 2 commits into
mainfrom
perf/ai-vault-scope-path-dedupe
Jul 29, 2026
Merged

nwparker merged 2 commits into
mainfrom
perf/ai-vault-scope-path-dedupe

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

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:

const comparisonPath = normalizeRuntimePathForComparison(trimmedPath)
if (paths.some((existingPath) => normalizeRuntimePathForComparison(existingPath) === comparisonPath)) {
  return
}
paths.push(trimmedPath)

Accepting K paths costs O(K²) normalize('NFC') calls — ~632k at 1124 workspaces. normalizeRuntimePathForComparison is the same ICU-backed primitive that made #10841 visible.

Separately, isAiVaultWorkspaceScopePathClaimed rescanned every live worktree once per prior id, and runs twice per switch (via activeWorktreePaths and scopePaths in AiVaultPanel.tsx:114,133).

Fix

  • Carry a Set of comparison keys alongside the paths — one normalize + one lookup per insert.
  • Thread that accumulator from the workspace pass into the project pass, instead of 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 order.

Results

deriveAiVaultScopeSessionPaths on 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:

  • monorepo (all one repo) and real mixed-repo layouts, from a real 1124-workspace profile
  • priors both claimed and unclaimed by other live workspaces, self-owned priors, cross-repo prior ids, bogus ids
  • duplicate paths, trailing slashes, doubled separators
  • NFD/NFC (Hangul and accented), WSL UNC
  • relative and blank paths, empty worktree list, null active worktree
  • 3 host-setup projections × 4 project-key shapes

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

  • 4938 tests pass across right-sidebar/ and shared/
  • tsc --noEmit -p config/tsconfig.tc.web.json clean
  • oxlint clean

Remaining, not in this PR

ai-vault-resume-target.ts:134,161 and ai-vault-session-resume.ts:169 do Object.values(worktreesByRepo).flat().find(...) per visible row (~3ms/render at this scale); getIndexedWorktreeMap already exists for exactly this. And checks-panel-terminal-worktree.ts:97 still normalizes inside a sort comparator — same shape #11303 fixed, different panel.

#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-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

Replaces the O(n²) deduplication in deriveAiVaultScopeSessionPaths and addAiVaultWorkspaceScopePath with a ScopePathAccumulator that carries a Set<string> of comparison keys alongside the accepted paths, and pre-builds a single claimed-path set for the prior-id check by excluding the active worktree by ID. The result is a 190 ms → 0.8 ms improvement on a 1124-workspace profile.

  • ScopePathAccumulator: a { paths, comparisonKeys } pair that makes dedup O(1) per insert and is threaded from collectWorkspaceScopePaths into the project pass so normalization state is never discarded.
  • buildClaimedComparisonPaths: builds the claim set once per call (O(n)) by iterating live worktrees and skipping the active one by ID, fixing the ordering-sensitive edge case from the previous review where a first-writer-wins path→id map could mask a real claimant.
  • New test file: pins workspace-scope and session-scope semantics with 9 behavioral cases plus independent timing guards on both exported functions at 1200-worktree scale.

Confidence Score: 5/5

Safe 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.

Important Files Changed

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
Loading

Reviews (2): Last reviewed commit: "fix(vault): make the claim check indepen..." | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 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: 0df64bdf-1b8c-4f69-8faf-2754274d3378

📥 Commits

Reviewing files that changed from the base of the PR and between d48c7d1 and 624fc12.

📒 Files selected for processing (2)
  • src/renderer/src/components/right-sidebar/ai-vault-scope-paths.test.ts
  • src/renderer/src/components/right-sidebar/ai-vault-scope-paths.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/right-sidebar/ai-vault-scope-paths.test.ts

📝 Walkthrough

Walkthrough

Refactors 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)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the fix and testing, but it does not follow the required template or include several required sections. Rewrite it using the repository template: add Summary, Screenshots, Testing checklist, AI Review Report, Security Audit, and Notes sections.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: faster scope-path deduping by using keys instead of rescanning.
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.

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.
@nwparker

Copy link
Copy Markdown
Contributor Author

Both review comments were valid — fixed in 624fc12.

1. First-writer-wins ordering (P2) — real bug, not just theoretical.

I reproduced it directly:

live = [active(path=/x), claimant(path=/x)], prior -> /x
old some(): claimed = true
new map:    claimed = false   <- diverges

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:

AssertionError: expected [ '/repo/orca-renamed', '/repo/orca' ] to deeply equal [ '/repo/orca-renamed' ]

2. Missing timing guard on deriveAiVaultWorkspaceScopePaths (P2) — correct.

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 deriveAiVaultScopeSessionPaths still measures 0.8ms (from 189.7ms).

On the CodeRabbit description-template warning: this is an internal perf change with no visual surface, so screenshots don't apply.

@nwparker
nwparker merged commit 6cc579a into main Jul 29, 2026
25 checks passed
@nwparker
nwparker deleted the perf/ai-vault-scope-path-dedupe branch July 29, 2026 07:11
nwparker added a commit that referenced this pull request Jul 29, 2026
* 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)
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
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