Repository navigation
perf(renderer): scope batched open-file reconciliation by worktree - #13748
Conversation
📝 WalkthroughWalkthroughBatch web-session reconciliation now maintains an open-file index grouped by worktree and preserves first-match duplicate behavior. Mirrored editor updates, stale-file removal, active-file validation, and active-editor preservation use the current worktree’s indexed files. Tests cover deterministic batched-versus-sequential equivalence, editor state, duplicate entries, environment scoping, close-and-reopen sequences, no-op patches, ordering, and input immutability. 🚥 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 |
There was a problem hiding this comment.
Actionable comments posted: 3
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 20e06459-663e-4e4b-ac98-7049b494f4eb
📒 Files selected for processing (3)
src/renderer/src/runtime/web-session-open-files-batch-equivalence.test.tssrc/renderer/src/runtime/web-session-tabs-sync.test.tssrc/renderer/src/runtime/web-session-tabs-sync.ts
| /* Why: the batched open-file path reconciles against a slot-keyed draft instead of | ||
| * rebuilding the global array per snapshot. These seeded cases assert it stays | ||
| * indistinguishable from repeated single-snapshot reconciliation. */ |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Correct the design description in the header comment.
The implementation buckets open files by worktree in WebSessionOpenFilesIndex and still rebuilds the array per snapshot, except on the no-op fast path at web-session-tabs-sync.ts Lines 2192-2197. It does not reconcile against a "slot-keyed draft". Align the comment with the shipped design.
📝 Proposed comment fix
-/* Why: the batched open-file path reconciles against a slot-keyed draft instead of
- * rebuilding the global array per snapshot. These seeded cases assert it stays
- * indistinguishable from repeated single-snapshot reconciliation. */
+/* Why: the batched open-file path reconciles against a worktree-bucketed index and
+ * skips the global rebuild when a snapshot changes nothing. These seeded cases assert
+ * it stays indistinguishable from repeated single-snapshot reconciliation. */📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| /* Why: the batched open-file path reconciles against a slot-keyed draft instead of | |
| * rebuilding the global array per snapshot. These seeded cases assert it stays | |
| * indistinguishable from repeated single-snapshot reconciliation. */ | |
| /* Why: the batched open-file path reconciles against a worktree-bucketed index and | |
| * skips the global rebuild when a snapshot changes nothing. These seeded cases assert | |
| * it stays indistinguishable from repeated single-snapshot reconciliation. */ |
Source: Coding guidelines
| const initialCopy = structuredClone(initial) | ||
|
|
||
| let sequential = initial | ||
| for (const snapshot of snapshots) { | ||
| const patch = applyWebSessionTabsSnapshot(sequential, snapshot, ENV, NOW) | ||
| if (patch !== sequential) { | ||
| sequential = { ...sequential, ...patch } | ||
| } | ||
| } | ||
|
|
||
| resetWebSessionTabsSnapshotFreshnessForTests() | ||
| const batched = { | ||
| ...initial, | ||
| ...applyWebSessionTabsSnapshots(initial, snapshots, ENV, NOW) | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Reset module freshness state before the sequential run.
The test resets freshness only before the batched run at Line 2593. The sequential loop at Lines 2585-2591 inherits whatever module state the previous test left behind. The other added tests reset before both runs, for example Lines 2771 and 2780. Add the same reset here so the two paths start from identical module state.
💚 Proposed fix
const initialCopy = structuredClone(initial)
+ resetWebSessionTabsSnapshotFreshnessForTests()
let sequential = initial
for (const snapshot of snapshots) {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const initialCopy = structuredClone(initial) | |
| let sequential = initial | |
| for (const snapshot of snapshots) { | |
| const patch = applyWebSessionTabsSnapshot(sequential, snapshot, ENV, NOW) | |
| if (patch !== sequential) { | |
| sequential = { ...sequential, ...patch } | |
| } | |
| } | |
| resetWebSessionTabsSnapshotFreshnessForTests() | |
| const batched = { | |
| ...initial, | |
| ...applyWebSessionTabsSnapshots(initial, snapshots, ENV, NOW) | |
| } | |
| const initialCopy = structuredClone(initial) | |
| resetWebSessionTabsSnapshotFreshnessForTests() | |
| let sequential = initial | |
| for (const snapshot of snapshots) { | |
| const patch = applyWebSessionTabsSnapshot(sequential, snapshot, ENV, NOW) | |
| if (patch !== sequential) { | |
| sequential = { ...sequential, ...patch } | |
| } | |
| } | |
| resetWebSessionTabsSnapshotFreshnessForTests() | |
| const batched = { | |
| ...initial, | |
| ...applyWebSessionTabsSnapshots(initial, snapshots, ENV, NOW) | |
| } |
| const currentActiveEditorStillValid = | ||
| state.activeFileId && | ||
| nextOpenFiles.some((file) => file.worktreeId === worktreeId && file.id === state.activeFileId) | ||
| state.activeFileId && nextWorktreeOpenFileIds.has(state.activeFileId) | ||
| ? state.activeFileId | ||
| : null |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Inspect writers of activeFileId and activeWorktreeId to confirm they stay in the same worktree.
set -euo pipefail
fd -e ts -e tsx . src/renderer/src/store --exec rg -n -C 4 'activeFileId\s*:' {} \;
rg -n -C 4 'activeWorktreeId\s*:' --type=ts --type=tsx src/renderer/src/storeRepository: stablyai/orca
Length of output: 23403
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- relevant consumer ---'
sed -n '2825,2880p' src/renderer/src/runtime/web-session-tabs-sync.ts
printf '%s\n' '--- active state declarations and action implementations ---'
rg -n -C 8 'activeWorktreeId\s*[:=]|activeFileId\s*[:=]' src/renderer/src/store --glob '*.ts' --glob '*.tsx' \
| sed -n '1,260p'
printf '%s\n' '--- direct active worktree setters and editor activation actions ---'
rg -n -C 10 'setActiveWorktree|activate.*Worktree|setActiveFile|activate.*File|activeFileIdByWorktree' \
src/renderer/src/store --glob '*.ts' --glob '*.tsx' | sed -n '1,320p'Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- setActiveWorktree implementation ---'
sed -n '5580,5715p' src/renderer/src/store/slices/worktrees.ts
sed -n '5928,6035p' src/renderer/src/store/slices/worktrees.ts
printf '%s\n' '--- production assignments of activeWorktreeId ---'
rg -n -C 5 'activeWorktreeId\s*:' src/renderer/src/store --glob '*.ts' --glob '!*.test.ts' --glob '!*.test.tsx'
printf '%s\n' '--- production assignments of activeFileId ---'
rg -n -C 3 'activeFileId\s*:' src/renderer/src/store --glob '*.ts' --glob '!*.test.ts' --glob '!*.test.tsx' \
| sed -n '1,420p'Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- completion of setActiveWorktree ---'
sed -n '5710,5850p' src/renderer/src/store/slices/worktrees.ts
printf '%s\n' '--- editor close and activation paths ---'
sed -n '2180,2320p' src/renderer/src/store/slices/editor.ts
sed -n '2528,2560p' src/renderer/src/store/slices/editor.ts
printf '%s\n' '--- all non-test activeFileId writes, reduced to file and line ---'
rg -n 'activeFileId\s*:' src/renderer/src/store --glob '*.ts' --glob '!*.test.ts' --glob '!*.test.tsx'
printf '%s\n' '--- sync worktree identity and map selection ---'
rg -n -C 8 'isActiveWorktree|nextWorktreeOpenFileIds|activeFileIdByWorktree' \
src/renderer/src/runtime/web-session-tabs-sync.ts | sed -n '1,260p'Repository: stablyai/orca
Length of output: 25850
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- setActiveFile call sites ---'
rg -n -C 6 '\.setActiveFile\(|setActiveFile\s*:' src --glob '*.ts' --glob '*.tsx' \
| sed -n '1,260p'
printf '%s\n' '--- editor-state test cases for cross-worktree active files ---'
rg -n -C 8 'setActiveFile|activeFileId:.*(wt|source|target)|activeWorktreeId:.*(wt|source|target)' \
src/renderer/src/store/slices/editor.test.ts src/renderer/src/store/slices/*.test.ts \
| sed -n '1,320p'Repository: stablyai/orca
Length of output: 50369
Use the worktree-scoped active file. setActiveFile can update activeFileId without changing activeWorktreeId. Use activeEditorFileIdForWorktree for this validation instead of the global state.activeFileId.
Every snapshot in a batch scanned the whole openFiles array three times and did a linear find per editor tab, so a reconnect paid for open files those snapshots never touched. Bucket open files by worktree for the duration of a batch, skip the global rebuild when a snapshot has nothing to drop or mirror, and retarget the index at the array each snapshot produced. Per-snapshot semantics are unchanged: openFiles still flows through each patch, so the equality bail is still evaluated per snapshot against the current array. An earlier draft deferred that bail to the end of the batch, which let the batch keep pre-batch file objects that sequential reconciliation rebuilds; the two regression tests here pin both cases. 1,200 workspaces, 3,000 unrelated open files: no workspace with editors 99.7ms -> 3.1ms, 5% with editors 105.3ms -> 7.7ms. Where every workspace has editors the array genuinely changes each snapshot, so the rebuild remains (113.9ms -> 84.2ms). Co-authored-by: Orca <[email protected]>
82add84 to
3d0ca96
Compare
…tablyai#13748) Every snapshot in a batch scanned the whole openFiles array three times and did a linear find per editor tab, so a reconnect paid for open files those snapshots never touched. Bucket open files by worktree for the duration of a batch, skip the global rebuild when a snapshot has nothing to drop or mirror, and retarget the index at the array each snapshot produced. Per-snapshot semantics are unchanged: openFiles still flows through each patch, so the equality bail is still evaluated per snapshot against the current array. An earlier draft deferred that bail to the end of the batch, which let the batch keep pre-batch file objects that sequential reconciliation rebuilds; the two regression tests here pin both cases. 1,200 workspaces, 3,000 unrelated open files: no workspace with editors 99.7ms -> 3.1ms, 5% with editors 105.3ms -> 7.7ms. Where every workspace has editors the array genuinely changes each snapshot, so the rebuild remains (113.9ms -> 84.2ms). Co-authored-by: Orca <[email protected]>
What this is
The follow-up flagged while reviewing #13676. That PR made batched snapshot reconciliation linear for terminals and agents, but left
openFilesrebuilt per snapshot.The cost
Every snapshot in a batch scanned the whole
openFilesarray three times (cull set, retained filter, equality check) and did a linearfindper editor tab.openFilesis global, so a snapshot for workspace 900 paid for files belonging to workspaces it never touches — including files whose worktree isn't in the batch at all.Measured on a synthetic reconnect, 1,200 workspaces, same fixture before and after:
The first row is the point: 99.7 ms spent entirely on files no snapshot in the batch touches.
The last two rows are honest about the limit. When every workspace owns editors, each snapshot legitimately produces a different array — the mirrored files move to the end — so sequential reconciliation genuinely emits N distinct arrays. That rebuild is the specified behavior, not an implementation artifact, and it stays.
How
existingFilelookup all answer from that bucket.openFiles.find()becomes a map lookup, so the O(editors x files) term is gone everywhere, batch or not.Semantics are unchanged, deliberately
openFilesstill flows through each snapshot's patch, so thesameOpenFilesbail is still evaluated per snapshot against the current array.An earlier draft of this change deferred that bail to the end of the batch and kept a slot-keyed draft. That was fully linear in every fixture — but it diverged from sequential reconciliation, because
openFileEqualcompares 15 ofOpenFile's ~35 fields, so "equal" does not mean "same object". Two cases fell out:openFileEqualto its input, so the end-of-batch check suppressed the patch and kept the pre-batch object — retaining per-file state (lastKnownDiskSignature, autosave gates) that sequential rebuilds away.(worktreeId, id)and differing inruntimeEnvironmentId, the rebuilt file is seeded from the first match but replaces the environment-matching one. When sequential bails, the original survives; the deferred draft had already swapped it for a clone of the other environment's entry.Both are pinned as regression tests here, and both fail against that draft.
Testing
pnpm vitest src/renderer/src/runtime/ src/renderer/src/store/— 227 files, 3,078 tests passedmax-linessuppression added.runtimeEnvironmentId(string/null/undefined), markdown-preview and edit modes, repeated worktrees, and bystander worktrees.The tests were validated by mutation testing rather than assumed: 6 deliberate faults injected into the implementation (last-wins lookup, dropped environment scoping, unconditional early-out, dropped mirrored/removed id handling, wrong-worktree re-bucketing, ignored mirror flag) — all 6 caught. Two earlier gaps that mutation testing exposed are now covered; one surviving mutant (never advancing the index) is perf-only by construction, since the
source !== state.openFilesidentity check turns a stale index into a rebuild.Made with Orca 🐋