Repository navigation
perf(usage): resolve each cwd's worktree once per scan - #21130
Conversation
Codex and OpenCode attribution ran the worktree containment search for every parsed event, so a cold scan cost events x worktrees. On 745 MB of real rollouts (~20k events) that is 1.2s with 0 worktrees, 5.0s with 100, 12.8s with 300 and 39.8s with 1000; a full corpus with hundreds of remembered worktrees is where the STA-7724 reparse burned minutes of main-thread CPU. A scan holds only a few hundred distinct cwds, so both scanners now build one memoized resolver per scan and thread it through parsing instead of passing the worktree list to every event.
`createUsageWorktreeResolver` now takes raw worktree refs and canonicalizes them itself, so each scanner has one entry point and neither keeps a private `buildWorktreesWithCanonicalPaths` or `canonicalizePath`. The resolver unit test counts comparisons through the same `areWorktreePathsEqual` mock the scanner-level test uses instead of a property getter.
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
- New shared memoized resolver —
src/main/usage/usage-worktree-resolver.tsexposescreateUsageWorktreeResolver(worktrees), returning a(cwd) => worktree | nullfunction backed by a per-scanMap<cwd, worktree | null>. The containment helpers moved here verbatim from both providers, so Codex and OpenCode now share one implementation instead of two copies. - Codex scan threads one resolver —
scanCodexUsageFilesbuilds the canonicalized list once, creates the resolver, and passes it throughparseCodexUsageFile→attributeCodexUsageEvent(second parameter changed from the worktree array to a callback). - OpenCode scan threads one resolver — same shape in
scanOpenCodeUsageDatabases/parseOpenCodeUsageDatabase/attributeOpenCodeUsageEvent; the duplicatedfindContainingWorktreeandisContainingPathare deleted. - Tests —
usage-worktree-resolver.test.tspins the memo with a countingcanonicalPathgetter plus the full containment matrix;scanner-attribution-memo.test.tsdrives a realscanCodexUsageFilesover three files (two sharing a cwd) and boundsareWorktreePathsEqualcalls atdistinctCwds × worktrees, which genuinely fails if the memo is only per-file; existing provider tests were updated to construct resolvers.
I verified behavioral equivalence while reading: first-match-wins over the canonicalizer's length-descending order is preserved, normalizeFsPath is still applied inside the resolver, the memo lives only for the scan, and every changed signature has only in-repo callers. Locally, the four touched test files pass (28 tests) and oxlint reports 0 warnings/errors on the changed files.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes (delta since the previous pullfrog review at 1796171)
- Resolver now owns canonicalization —
createUsageWorktreeResolveris async and takes rawUsageScanWorktreeRefs, canonicalizing internally viacanonicalizeUsageWorktreePaths(worktrees, canonicalizePath). The privatecanonicalizePathmoved into the resolver,CanonicalizedUsageWorktreeRefis no longer exported, and both scanners'buildWorktreesWithCanonicalPathshelpers are deleted (call sites are nowawait createUsageWorktreeResolver(worktrees)). - Resolver tests reworked — the old
canonicalPathgetter trick no longer works now that canonicalization is internal, sousage-worktree-resolver.test.tscounts through a mockedareWorktreePathsEqualinstead; the redundant "memoizes each cwd independently" case was folded into the walk-count test. - Codex memo test shrunk —
scanner-attribution-memo.test.tsdrops from 40×25 to 4×4 per the PR body, keeping the same cross-file assertion shape.
I checked the load-bearing equivalence claim for this commit: the new resolver's canonicalizePath is byte-identical to both prior implementations (codex-session-file-discovery.canonicalizePath and the private one that used to live in opencode-usage-worktree-attribution.ts), so consolidating them does not change any canonicalPath. codex-session-file-discovery.canonicalizePath remains in use for file-path keys, and all createUsageWorktreeResolver call sites are in-repo scanners/tests. Re-ran the four touched test files (27 tests pass) and oxlint (0 warnings/errors).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
📝 WalkthroughWalkthroughThe change adds a shared, memoized Priority: ⬇️ Low Merge Risk: 🟡 Moderate · up to On Windows systems where a user has both a POSIX/WSL-style worktree path and a native Windows session pointing at the same drive-anchored location, usage attribution can assign statistics to the wrong worktree or repository. This is a narrow, environment-specific data-integrity edge case rather than a broad functional break, and it predates this PR, but the new shared resolver is now the natural place to fix it and it should be addressed before or shortly after merge. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ 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.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: b127fc89-d37b-49d0-9970-112de1fa2361
📒 Files selected for processing (9)
src/main/codex-usage/codex-usage-event-attribution.tssrc/main/codex-usage/scanner-attribution-memo.test.tssrc/main/codex-usage/scanner.test.tssrc/main/codex-usage/scanner.tssrc/main/opencode-usage/opencode-usage-worktree-attribution.tssrc/main/opencode-usage/scanner.test.tssrc/main/opencode-usage/scanner.tssrc/main/usage/usage-worktree-resolver.test.tssrc/main/usage/usage-worktree-resolver.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 7 remain after this review.
|
|
||
| async function canonicalizePath(pathValue: string): Promise<string> { | ||
| try { | ||
| return normalizeFsPath(await realpath(pathValue)) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
sed -n '1,80p' src/main/usage/usage-path-comparison.ts
echo "-----"
find src/main -iname "*worktree-path-comparison*" -o -iname "*worktree-logic*"
echo "-----"
sed -n '1,80p' src/main/ipc/worktree-path-comparison.ts 2>/dev/null
echo "-----"
sed -n '1,80p' src/main/ipc/worktree-logic.ts 2>/dev/null
echo "-----"
rg -n "areWorktreePathsEqual" -A 30 src/main --type ts | head -150
echo "-----"
node -e "const path=require('path'); console.log(path.win32.resolve('/workspace/repo'));" 2>/dev/null || true
echo "-----"
git log --oneline --all -- src/main/codex-usage/codex-usage-event-attribution.ts | tail -5
git show 1796171d53^:src/main/codex-usage/codex-usage-event-attribution.ts 2>/dev/null | sed -n '1,90p'Repository: stablyai/orca
Length of output: 22925
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- resolver ---'
cat -n src/main/usage/usage-worktree-resolver.ts | sed -n '1,130p'
printf '%s\n' '--- comparison ---'
cat -n src/main/ipc/worktree-path-comparison.ts | sed -n '1,220p'
printf '%s\n' '--- usage callers and helpers ---'
rg -n "findContainingWorktree|normalizeFsPath|canonicalPath|areWorktreePathsEqual|isContainingPath" src/main/usage src/main/codex-usage src/main --glob '*.ts' | head -220
printf '%s\n' '--- relevant history summaries ---'
git log --oneline --all -- src/main/usage/usage-path-comparison.ts src/main/usage/usage-worktree-resolver.ts src/main/codex-usage/codex-usage-event-attribution.ts src/main/ipc/worktree-path-comparison.ts | head -30
printf '%s\n' '--- parent helper candidates ---'
git show 1796171d53^:src/main/codex-usage/codex-usage-event-attribution.ts 2>/dev/null | rg -n -C 18 "normalizeFsPath|findContainingWorktree|isContainingPath|areWorktreePathsEqual"
git show 1796171d53^:src/main/usage/usage-path-comparison.ts 2>/dev/null | cat -n | sed -n '1,140p'Repository: stablyai/orca
Length of output: 39026
🏁 Script executed:
#!/bin/bash
set -e
printf '%s\n' '--- consolidation commit ---'
git show --stat --oneline 980960ab31
printf '%s\n' '--- focused diff ---'
git show --format= --find-renames 980960ab31 -- src/main/usage/usage-worktree-resolver.ts src/main/codex-usage/codex-usage-event-attribution.ts src/main/usage/usage-path-comparison.ts src/main/ipc/worktree-path-comparison.ts | sed -n '1,260p'
printf '%s\n' '--- parent resolver/codex relevant code ---'
git show 980960ab31^:src/main/codex-usage/codex-usage-event-attribution.ts 2>/dev/null | sed -n '1,120p'
printf '%s\n' '--- current canonicalizer ---'
cat -n src/main/usage-worktree-canonicalizer.ts | sed -n '1,180p'Repository: stablyai/orca
Length of output: 7017
Preserve POSIX path identity on Windows.
On Windows, normalizeFsPath applies win32.resolve to /workspace/repo and anchors it to the current drive. findContainingWorktree then passes only the normalized string to areWorktreePathsEqual and isContainingPath. These functions cannot recover the original POSIX flavor, so a POSIX or WSL worktree can match a native Windows path on that drive and receive the wrong repoId and worktreeId.
Preserve path flavor during canonicalization and reject mixed POSIX and Windows paths before equality or containment checks. This behavior existed in the previous local helper, so the consolidation preserves rather than introduces it.
* perf(usage): resolve each cwd's worktree once per scan Codex and OpenCode attribution ran the worktree containment search for every parsed event, so a cold scan cost events x worktrees. On 745 MB of real rollouts (~20k events) that is 1.2s with 0 worktrees, 5.0s with 100, 12.8s with 300 and 39.8s with 1000; a full corpus with hundreds of remembered worktrees is where the STA-7724 reparse burned minutes of main-thread CPU. A scan holds only a few hundred distinct cwds, so both scanners now build one memoized resolver per scan and thread it through parsing instead of passing the worktree list to every event. * refactor(usage): make the worktree resolver own canonicalization `createUsageWorktreeResolver` now takes raw worktree refs and canonicalizes them itself, so each scanner has one entry point and neither keeps a private `buildWorktreesWithCanonicalPaths` or `canonicalizePath`. The resolver unit test counts comparisons through the same `areWorktreePathsEqual` mock the scanner-level test uses instead of a property getter.
* perf(usage): resolve each cwd's worktree once per scan Codex and OpenCode attribution ran the worktree containment search for every parsed event, so a cold scan cost events x worktrees. On 745 MB of real rollouts (~20k events) that is 1.2s with 0 worktrees, 5.0s with 100, 12.8s with 300 and 39.8s with 1000; a full corpus with hundreds of remembered worktrees is where the STA-7724 reparse burned minutes of main-thread CPU. A scan holds only a few hundred distinct cwds, so both scanners now build one memoized resolver per scan and thread it through parsing instead of passing the worktree list to every event. * refactor(usage): make the worktree resolver own canonicalization `createUsageWorktreeResolver` now takes raw worktree refs and canonicalizes them itself, so each scanner has one entry point and neither keeps a private `buildWorktreesWithCanonicalPaths` or `canonicalizePath`. The resolver unit test counts comparisons through the same `areWorktreePathsEqual` mock the scanner-level test uses instead of a property getter.
* perf(usage): resolve each cwd's worktree once per scan Codex and OpenCode attribution ran the worktree containment search for every parsed event, so a cold scan cost events x worktrees. On 745 MB of real rollouts (~20k events) that is 1.2s with 0 worktrees, 5.0s with 100, 12.8s with 300 and 39.8s with 1000; a full corpus with hundreds of remembered worktrees is where the STA-7724 reparse burned minutes of main-thread CPU. A scan holds only a few hundred distinct cwds, so both scanners now build one memoized resolver per scan and thread it through parsing instead of passing the worktree list to every event. * refactor(usage): make the worktree resolver own canonicalization `createUsageWorktreeResolver` now takes raw worktree refs and canonicalizes them itself, so each scanner has one entry point and neither keeps a private `buildWorktreesWithCanonicalPaths` or `canonicalizePath`. The resolver unit test counts comparisons through the same `areWorktreePathsEqual` mock the scanner-level test uses instead of a property getter.

Problem
Codex and OpenCode usage attribution ran the worktree containment search once per parsed event.
findContainingWorktreewalked every known worktree callingareWorktreePathsEqual+ apath.relativecontainment check, so a cold scan costevents × worktrees. The worktree list comes fromloadKnownUsageWorktreesByRepo, which includes every persisted worktree, so hundreds is normal on an automation-heavy machine.Measured on 745 MB of real rollouts (~20k events):
With a per-cwd memo, all of those are ~1.1 s. On a 30 GB corpus (~1.6M events, ~5.8k files) the same slope extrapolates to ~16 minutes of attribution at 300 worktrees — this is what turned a full reparse into the 18-minute main-thread burn in STA-7724. Distinct cwds per corpus are only a few hundred, so nearly all of that work is repeated answers.
Fix
One resolver per scan, memoized by
cwd:src/main/usage/usage-worktree-resolver.tsis the single entry point:await createUsageWorktreeResolver(worktrees)takes rawUsageScanWorktreeRefs, canonicalizes them itself (canonicalizeUsageWorktreePaths+ therealpath/normalizeFsPathfallback that OpenCode used to keep privately), and returns(cwd) => worktree | nullbacked by aMap<cwd, worktree | null>(misses memoize asnull). The containment logic moved here unchanged; it was byte-identical in the Codex and OpenCode modules, so this removes a duplicate too.const resolveWorktree = await createUsageWorktreeResolver(worktrees)— and the privatebuildWorktreesWithCanonicalPathshelpers are gone from both. The resolver is threaded throughparseCodexUsageFile/parseOpenCodeUsageDatabase→attributeCodexUsageEvent/attributeOpenCodeUsageEvent. No module-level cache and no WeakMap keyed on the worktrees array, so the memo lives exactly as long as the scan.cwd:fallback keys.Claude scanner: checked, it does not have the per-event pattern.
attributeClaudeUsageTurnsalready memoizes bycwdfor the batch it is given (one file), so its residual cost isfiles × worktrees, notevents × worktrees— ~1.7M cheap prefix compares on a 5.8k-file corpus. Hoisting that memo to per-scan is a possible follow-up; it is not what caused the incident, so it is not in this PR.Measurement
Vitest micro-benchmark on a synthetic fixture (500 worktrees, 5,000 events, 200 distinct cwds), old unmemoized attribution vs. the resolver, same process, same fixture, results asserted identical:
identicalResults: truefor all 5,000 events. The "after" figure still includes the 5,000awaits and result-object spreads ofattributeCodexUsageEvent, so the attribution search itself is essentially gone. (Benchmark was a scratch file, not committed.)Tests added:
src/main/usage/usage-worktree-resolver.test.ts— counts comparisons through a mockedareWorktreePathsEqualand proves 998 further events after the first two distinct cwds (one hit, one miss) cost zero extra comparisons; plus containment semantics (exact, nested,..namechild,..escape, sibling prefix, cross-drive Windows, empty worktree list).src/main/codex-usage/scanner-attribution-memo.test.ts— fullscanCodexUsageFilesover three rollout files (two sharing a cwd), countingareWorktreePathsEqualcalls:≤ distinctCwds × worktrees, proving the memo survives across files, not just within one.Risk
Low. Behaviour-preserving: the resolver returns exactly what the old loop returned for the same inputs, and worktree canonicalization is unchanged. The memo is created per scan and discarded with it, so a worktree added between scans is picked up by the next scan exactly as before — no staleness window is introduced. The only API change is the second parameter of
parseCodexUsageFile/parseOpenCodeUsageDatabase/ the twoattribute*functions, all internal to the scanners.Landing order
Independent of #21102 and #21114, and should land first — neither of those changes attribution, and this is the change that removes the dominant cold-scan cost. #21102 will need a trivial rebase over
src/main/codex-usage/scanner.ts(parseCodexUsageFilenow takes a resolver instead of the worktree array).