Skip to content

perf(usage): resolve each cwd's worktree once per scan - #21130

Merged
Jinwoo-H merged 2 commits into
mainfrom
perf/usage-attribution-cwd-memo
Sep 17, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
perf/usage-attribution-cwd-memo

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​286 $\color{#cf222e}{\Huge{\mathbf{−}}}$​38 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​248
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​110 $\color{#cf222e}{\Huge{\mathbf{−}}}$​129 $\color{#cf222e}{\Huge{\mathbf{−}}}$​19

Problem

Codex and OpenCode usage attribution ran the worktree containment search once per parsed event. findContainingWorktree walked every known worktree calling areWorktreePathsEqual + a path.relative containment check, so a cold scan cost events × worktrees. The worktree list comes from loadKnownUsageWorktreesByRepo, which includes every persisted worktree, so hundreds is normal on an automation-heavy machine.

Measured on 745 MB of real rollouts (~20k events):

Worktrees Cold scan
0 1.2 s
100 5.0 s
300 12.8 s
1000 39.8 s

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:

  • New src/main/usage/usage-worktree-resolver.ts is the single entry point: await createUsageWorktreeResolver(worktrees) takes raw UsageScanWorktreeRefs, canonicalizes them itself (canonicalizeUsageWorktreePaths + the realpath/normalizeFsPath fallback that OpenCode used to keep privately), and returns (cwd) => worktree | null backed by a Map<cwd, worktree | null> (misses memoize as null). The containment logic moved here unchanged; it was byte-identical in the Codex and OpenCode modules, so this removes a duplicate too.
  • Each scanner's call site is now one line — const resolveWorktree = await createUsageWorktreeResolver(worktrees) — and the private buildWorktreesWithCanonicalPaths helpers are gone from both. The resolver is threaded through parseCodexUsageFile / 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.
  • Attribution results are unchanged: same comparison order, same first-match-wins semantics, same cwd: fallback keys.

Claude scanner: checked, it does not have the per-event pattern. attributeClaudeUsageTurns already memoizes by cwd for the batch it is given (one file), so its residual cost is files × worktrees, not events × 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:

Wall clock Worktree-list walks
Before 3,570 ms 5,000 (one per event)
After 145 ms 200 (one per distinct cwd)
24.5× faster 25× fewer

identicalResults: true for all 5,000 events. The "after" figure still includes the 5,000 awaits and result-object spreads of attributeCodexUsageEvent, 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 mocked areWorktreePathsEqual and proves 998 further events after the first two distinct cwds (one hit, one miss) cost zero extra comparisons; plus containment semantics (exact, nested, ..name child, .. escape, sibling prefix, cross-drive Windows, empty worktree list).
  • src/main/codex-usage/scanner-attribution-memo.test.ts — full scanCodexUsageFiles over three rollout files (two sharing a cwd), counting areWorktreePathsEqual calls: ≤ 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 two attribute* 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 (parseCodexUsageFile now takes a resolver instead of the worktree array).

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.

@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

  • New shared memoized resolver — src/main/usage/usage-worktree-resolver.ts exposes createUsageWorktreeResolver(worktrees), returning a (cwd) => worktree | null function backed by a per-scan Map<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 — scanCodexUsageFiles builds the canonicalized list once, creates the resolver, and passes it through parseCodexUsageFile → attributeCodexUsageEvent (second parameter changed from the worktree array to a callback).
  • OpenCode scan threads one resolver — same shape in scanOpenCodeUsageDatabases / parseOpenCodeUsageDatabase / attributeOpenCodeUsageEvent; the duplicated findContainingWorktree and isContainingPath are deleted.
  • Tests — usage-worktree-resolver.test.ts pins the memo with a counting canonicalPath getter plus the full containment matrix; scanner-attribution-memo.test.ts drives a real scanCodexUsageFiles over three files (two sharing a cwd) and bounds areWorktreePathsEqual calls at distinctCwds × 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.

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

@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 (delta since the previous pullfrog review at 1796171)

  • Resolver now owns canonicalization — createUsageWorktreeResolver is async and takes raw UsageScanWorktreeRefs, canonicalizing internally via canonicalizeUsageWorktreePaths(worktrees, canonicalizePath). The private canonicalizePath moved into the resolver, CanonicalizedUsageWorktreeRef is no longer exported, and both scanners' buildWorktreesWithCanonicalPaths helpers are deleted (call sites are now await createUsageWorktreeResolver(worktrees)).
  • Resolver tests reworked — the old canonicalPath getter trick no longer works now that canonicalization is internal, so usage-worktree-resolver.test.ts counts through a mocked areWorktreePathsEqual instead; the redundant "memoizes each cwd independently" case was folded into the walk-count test.
  • Codex memo test shrunk — scanner-attribution-memo.test.ts drops 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).

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

@Jinwoo-H
Jinwoo-H merged commit 2c2d068 into main Sep 17, 2026
27 checks passed
@Jinwoo-H
Jinwoo-H deleted the perf/usage-attribution-cwd-memo branch September 17, 2026 02:31
@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change adds a shared, memoized UsageWorktreeResolver for cwd-to-worktree matching. Codex and OpenCode scanners create one resolver per scan and pass it to event attribution. Local canonicalization and containment helpers are removed from both attribution paths. Tests cover path boundaries, Windows drives, cached misses, resolver reuse, and shared memoization across scanned files.

Priority: ⬇️ Low

Merge Risk: 🟡 Moderate · up to 98096

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.26% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 19 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 main change: memoizing worktree resolution for each cwd during a usage scan.
Description check ✅ Passed The description is comprehensive and on-topic. It explains the problem, implementation, performance impact, testing, risks, and landing order. It does not reproduce every template heading and does not…
  • 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.

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: b127fc89-d37b-49d0-9970-112de1fa2361

📥 Commits

Reviewing files that changed from the base of the PR and between 77cd61d and 980960a.

📒 Files selected for processing (9)
  • src/main/codex-usage/codex-usage-event-attribution.ts
  • src/main/codex-usage/scanner-attribution-memo.test.ts
  • src/main/codex-usage/scanner.test.ts
  • src/main/codex-usage/scanner.ts
  • src/main/opencode-usage/opencode-usage-worktree-attribution.ts
  • src/main/opencode-usage/scanner.test.ts
  • src/main/opencode-usage/scanner.ts
  • src/main/usage/usage-worktree-resolver.test.ts
  • src/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))

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.

🗄️ 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.

github-actions Bot pushed a commit to MAYFCHOI/orca that referenced this pull request Sep 17, 2026
* 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.
Him188 pushed a commit to Him188/orca that referenced this pull request Sep 18, 2026
* 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.
ivanvykopal pushed a commit to ivanvykopal/orca that referenced this pull request Sep 20, 2026
* 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.
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