Skip to content

perf(renderer): scope batched open-file reconciliation by worktree - #13748

Merged
nwparker merged 1 commit into
mainfrom
nwparker/perf-batch-open-files
Aug 11, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/perf-batch-open-files

Conversation

@nwparker

@nwparker nwparker commented Aug 11, 2026 •

Copy link
Copy Markdown
Contributor

What this is

The follow-up flagged while reviewing #13676. That PR made batched snapshot reconciliation linear for terminals and agents, but left openFiles rebuilt per snapshot.

The cost

Every snapshot in a batch scanned the whole openFiles array three times (cull set, retained filter, equality check) and did a linear find per editor tab. openFiles is 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:

Fixture Before After
no workspace has editors, 3,000 open files 99.7 ms 3.1 ms 32×
5% of workspaces have editors, 3,000 open files 105.3 ms 7.7 ms 13.7×
every workspace has editors, 3,000 open files 113.9 ms 84.2 ms 1.35×
every workspace has editors, no bystanders 69.9 ms 53.1 ms 1.3×

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

  • Bucket open files by worktree for the life of a batch. A snapshot only reconciles its own worktree, so the cull set, the surviving-id set, and the existingFile lookup all answer from that bucket.
  • Skip the global rebuild when a snapshot has nothing to drop and nothing to mirror — the rebuild would reproduce the array exactly and the existing equality check would discard it.
  • Retarget the index at the array each snapshot produced, re-bucketing only the worktree that changed.
  • The per-editor-tab openFiles.find() becomes a map lookup, so the O(editors x files) term is gone everywhere, batch or not.

Semantics are unchanged, deliberately

openFiles still flows through each snapshot's patch, so the sameOpenFiles bail 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 openFileEqual compares 15 of OpenFile's ~35 fields, so "equal" does not mean "same object". Two cases fell out:

  1. A batch that closes and reopens a file has a net effect that is openFileEqual to 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.
  2. With two entries sharing (worktreeId, id) and differing in runtimeEnvironmentId, 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 passed
  • Typecheck, oxlint, oxfmt, and the max-lines ratchet all clean. No max-lines suppression added.
  • New: a 400-case seeded differential suite asserting the batch path matches repeated single-snapshot reconciliation, over duplicate ids, mixed runtimeEnvironmentId (string / null / undefined), markdown-preview and edit modes, repeated worktrees, and bystander worktrees.
  • New unit tests for both divergences above, the duplicate first-wins lookup, cross-environment culling, and active-editor focus survival.

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.openFiles identity check turns a stale index into a rebuild.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the implementation, semantics, benchmarks, and testing, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add the required template sections, state “No visual change,” document the AI cross-platform review, provide a security audit, and record platform-specific risks or follow-up.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main performance change: scoping batched open-file reconciliation by worktree.
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.

@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: 3


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 20e06459-663e-4e4b-ac98-7049b494f4eb

📥 Commits

Reviewing files that changed from the base of the PR and between 1928ca5 and 82add84.

📒 Files selected for processing (3)
  • src/renderer/src/runtime/web-session-open-files-batch-equivalence.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.test.ts
  • src/renderer/src/runtime/web-session-tabs-sync.ts

Comment on lines +1 to +3
/* 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. */

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.

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

Suggested change
/* 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

Comment on lines +2583 to +2597
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)
}

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.

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

Suggested change
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)
}

Comment on lines 2856 to 2859
const currentActiveEditorStillValid =
state.activeFileId &&
nextOpenFiles.some((file) => file.worktreeId === worktreeId && file.id === state.activeFileId)
state.activeFileId && nextWorktreeOpenFileIds.has(state.activeFileId)
? state.activeFileId
: null

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 | 🟡 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/store

Repository: 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]>
@nwparker
nwparker force-pushed the nwparker/perf-batch-open-files branch from 82add84 to 3d0ca96 Compare August 11, 2026 05:17
@nwparker
nwparker merged commit 23c803a into main Aug 11, 2026
44 checks passed
@nwparker
nwparker deleted the nwparker/perf-batch-open-files branch August 11, 2026 05:21
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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]>
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