Skip to content

perf(editor,source-control): batch closed-tab model sweeps, drop 40 store subscriptions - #18144

Merged
nwparker merged 1 commit into
mainfrom
perf/tab-close-model-sweep-and-source-control-subscriptions
Sep 2, 2026
Merged

nwparker merged 1 commit into
mainfrom
perf/tab-close-model-sweep-and-source-control-subscriptions

Conversation

@nwparker

@nwparker nwparker commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​406 $\color{#cf222e}{\Huge{\mathbf{−}}}$​5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​401
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​248 $\color{#cf222e}{\Huge{\mathbf{−}}}$​175 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​73

ELI5

Two separate bits of bookkeeping were doing far more work than they needed to.

  1. Closing tabs. Orca keeps a single global list of every document Monaco is holding on to. When you closed a diff tab, Orca walked that entire list looking for the two documents belonging to that one tab — and it built a fresh text copy of every document's identifier while it looked. Close a batch of tabs (a "close all", a worktree switch) and it re-walked the whole list once per closed tab. 100 tabs closed against 764 held documents meant 200 full walks and ~306,000 throwaway strings, all inside one synchronous React effect. Now it collects everything being closed and walks the list once.

  2. The Source Control panel. One hook asked the app store to notify it 42 separate times about every single change anywhere in the app. 40 of those 42 were watching functions that are created once when the store is built and can never change, so those notifications could never do anything. Now the panel asks the store to notify it about the 2 things that actually vary, and reads the 40 fixed functions directly.

Same behaviour, same documents disposed, same panel.

Corrections to the reported issue

Two details in the report were wrong; verified against the code:

  • The hook has 42 useAppStore calls, not ~50 — 40 actions + 2 record maps. So it was ~40 removable subscribers, not 48.
  • The scrollTopCache / editorSelectionCache sweep was not a real hotspot. Every write into those maps goes through setWithLRU (src/renderer/src/lib/scroll-cache.ts), which caps them at CACHE_MAX_ENTRIES = 20. The per-tab walk was therefore over at most 20 keys, and batching it changes N x 20 comparisons into N x 20 comparisons — identical work. I did the single-pass change anyway (it now probes :: boundaries against a Set, so it really is O(cache) rather than O(tabs x cache)), but the measurable win there is zero and the honest justification is simplicity, not speed. The Monaco registry is the only unbounded collection in this path, and that is where all of the measured win comes from.

The rest of the report checks out: disposeUnattachedMonacoModelsByPathPrefix did scan the whole registry and call both uri.toString(true) and uri.toString() per model, twice per closed diff tab (original + modified prefix), with the cleanup effect processing every removal in one synchronous pass.

Fix 1 — one registry scan per removal batch

useClosedEditorTabCleanup now collects the whole removal batch and hands it to a new
disposeClosedEditorTabs() (closed-editor-tab-disposal.ts), which:

  • calls disposeUnattachedMonacoModelsByPathPrefixes(monaco, allOwnedPrefixes) — one getModels() scan;
  • renders each model's URI at most twice (decoded first, encoded only if the decoded form did not already match), instead of twice per prefix;
  • matches prefixes by probing the URI's own : boundaries against a Set, which is provably the same predicate as uri === prefix || uri.startsWith(prefix + ':') but costs O(segments) instead of O(prefixes) per model.

The isAttachedToEditor() guard, the exact-path edit-model dispose, and every cache key touched are unchanged. disposeUnattachedMonacoModelsByPathPrefix is kept as a one-element wrapper for its other callers.

Taking the monaco namespace as an argument also means the logic is now unit-testable without importing monaco-editor, which is why the sweep helper was split out in the first place.

Fix 2 — 42 store subscriptions become 2

useSourceControlStoreActions now subscribes only to pullRequestGenerationRecords and commitMessageGenerationRecords (the two entries that are state and carry re-render semantics), and reads the other 40 through useAppStore.getState() inside a useMemo keyed on those two maps.

I verified the "actions are stable" premise rather than assuming it, two ways:

  • Statically: each of the 40 names appears exactly twice in src/renderer/src/store — once in a slice contract type, once as a property of the object a slice creator returns. None appears inside a set() payload. pullRequestGenerationRecords and commitMessageGenerationRecords are the only two that do, which is exactly why they stay subscribed.
  • At runtime: a test snapshots every function-valued key on the real store, drives writes through the UI / PR-generation / commit-message slices, and asserts no identity moved.

All 40 are genuine actions; none turned out to be a derived value.

Reference stability is preserved and is now stronger than the doc comment promised. Each action keeps the single identity it was created with (asserted against getState() in a test). The returned object was previously a fresh literal on every render — the pre-fix hook fails the new stability test — and is now stable until one of the two subscribed maps changes.

Measurements

Measured in this repo on this machine, at the reported real scale (382 open diff tabs → 764 retained models), closing 100 diff tabs. Pre-fix numbers come from running the original per-prefix loop against the identical fixture.

Fix 1 — closing 100 diff tabs, 764 retained models

before after
getModels() registry scans 200 1
uri.toString() calls 305,600 1,328
sweep duration 44.17 ms 0.21 ms
models disposed 200 200 (identical set)

That 44 ms was one synchronous block inside a useEffect — i.e. a dropped-frames hitch on "close all" / worktree switch. The 1,328 figure is 764 + 564: the 200 matching models short-circuit after the decoded form, the rest render both.

The regression test asserts the pre-fix shape costs 2N scans and 2N x M x 2 toString calls, the new one costs exactly 1 scan and at most 2M calls, and — separately — that both dispose the same set of model paths, with attached models and still-open tabs untouched in both.

Fix 2 — Source Control store subscriptions

before after
live store subscribers from this hook 42 2
selector evaluations per store write (panel mounted) 42 2
2,000 store writes with the hook mounted (happy-dom, dev React) 1,771 ms 702 ms

The 42 → 2 subscriber count is exact and comes from the existing readStoreListenerCount() census; the pre-fix hook fails that assertion with expected 42 to be 2.

Caveat on the third row, stated plainly: it is a happy-dom + development-React microbenchmark and the absolute milliseconds are not production figures. The ratio (~2.5x, reproduced across runs) is the useful part, and the cost it removes is React's useSyncExternalStore bookkeeping per subscription, not zustand's Set iteration — I also measured 42 vs 2 vanilla useAppStore.subscribe listeners over 2,000 writes and the difference was below the noise floor of the store's own write path, so I am not claiming a zustand-notify win. I could not verify the reported app-wide totals (~1,200 subscribers / ~24,700 selector evaluations per second) from a test process; those come from the live instance.

Negative user-facing trade-offs

None.

  • Fix 1: the prefix predicate is a mechanical rewrite of the same boolean, and the parity test asserts the two implementations dispose an identical set of models over a 320-model fixture that mixes attached models, large-diff generation suffixes, colon-adjacent sibling ids (tab-1 vs tab-10), still-open tabs and plain file models. The isAttachedToEditor() guard is untouched, so nothing can be disposed out from under a live editor. Deletes are order-independent and idempotent, so hoisting the sweeps out of the per-tab loop cannot change the outcome.
  • Fix 2: the returned object has byte-identical keys (verified programmatically against the pre-fix version), every action is the same function object the old selectors returned, and the only two entries with re-render semantics keep their own subscriptions. Object identity is strictly more stable than before, so no downstream memo dep can start missing.

Known gap, deliberately not addressed

There is still no eviction over retained Monaco models. At 382 open tabs the ceiling is one model per activated edit tab plus two per diff tab, released only on tab close (MonacoEditor.tsx passes keepCurrentModel). Adding an LRU here would silently discard undo history and view state for evicted tabs — a product decision, not a perf patch. Left as a bounded-cache gap.

Verification

  • pnpm tc — clean
  • npx oxlint <changed files> — clean
  • npx vitest run --config config/vitest.config.ts src/renderer/src/components/editor src/renderer/src/components/right-sidebar — 3,240 passed, 1 failed

The single failure is right-sidebar/ai-vault-session-worktree-map.test.tsx > builds the map at scale without re-normalizing paths per session, a wall-clock-bounded perf assertion (expect(elapsedMs).toBeLessThan(150)). It fails identically on the base commit aa3ae6f56ec with this branch checked out nowhere near it, and this change touches nothing it imports — it is a pre-existing flake on a loaded machine.

…tore subscriptions

Closing N diff tabs scanned the global Monaco model registry 2N times and
rendered both URI forms for every retained model on each scan. The Source
Control panel opened 42 store subscriptions from one hook, 40 of which watched
action identities that are fixed at store construction and can never change.
@coderabbitai

coderabbitai Bot commented Sep 2, 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: Team

Run ID: 4260da25-f1fd-41f6-a350-d899cc581019

📥 Commits

Reviewing files that changed from the base of the PR and between f37d2fe and e386eb0.

📒 Files selected for processing (8)
  • src/renderer/src/components/editor/closed-editor-tab-cache-sweep.test.ts
  • src/renderer/src/components/editor/closed-editor-tab-cache-sweep.ts
  • src/renderer/src/components/editor/closed-editor-tab-disposal.test.ts
  • src/renderer/src/components/editor/closed-editor-tab-disposal.ts
  • src/renderer/src/components/editor/diff-monaco-model-disposal.ts
  • src/renderer/src/components/editor/useClosedEditorTabCleanup.ts
  • src/renderer/src/components/right-sidebar/source-control/listing/use-store-actions.store-subscriptions.test.tsx
  • src/renderer/src/components/right-sidebar/source-control/listing/use-store-actions.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The change batches closed-editor tab cleanup across Monaco models and editor caches. It adds multi-owner cache sweeping, multi-prefix model disposal, and a centralized closed-tab disposal API. The cleanup hook now processes all closed tabs in one call. Tests cover disposal parity, cache behavior, registry scans, and no-op cases. The source-control actions hook now subscribes only to generation-record maps and memoizes store action references. New tests verify subscriptions, identity stability, live references, and updates.

Merge Risk: ⚪ Minimal · up to e386e

The PR reduces editor cleanup work and source-control subscriptions while preserving model disposal and panel behavior; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 39.13% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes both primary changes: batching closed-tab editor cleanup and reducing Source Control subscriptions.
Description check ✅ Passed The description is detailed and explains the change, rationale, performance measurements, trade-offs, and verification results. The required Linked Issue is still empty, and the template sections for …
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.
Full details: Description check

Explanation

The description is detailed and explains the change, rationale, performance measurements, trade-offs, and verification results. The required Linked Issue is still empty, and the template sections for Visual Proof, Testing checkboxes, Review, Notes, and Checklist are not explicitly completed.

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

@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

  • Batched Monaco model disposal — useClosedEditorTabCleanup now collects the full removal batch into disposeClosedEditorTabs, running one getModels() scan (disposeUnattachedMonacoModelsByPathPrefixes) and one pass per cache instead of one scan/prefix per closed diff tab. Prefix matching was rewritten as a colon-boundary probe against a Set (isOwnedByPathPrefix), provably equivalent to the old uri === prefix || uri.startsWith(prefix + ':') predicate with decoded/encoded short-circuiting preserved.
  • Cache sweep helpers — closed-editor-tab-cache-sweep.ts gains deletePaneScopedCacheEntries (a ::-boundary probe replacing per-owner startsWith), and sweepClosedPdfViewPositions now takes an array. Per-mode disposal parity (edit / markdown-preview / diff / no-op cases) is preserved.
  • Source Control store subscriptions — useSourceControlStoreActions drops 40 subscriptions by reading the stable action references through useAppStore.getState() inside a useMemo keyed on the two record maps, leaving only pullRequestGenerationRecords and commitMessageGenerationRecords subscribed.

Verification

I traced the prefix predicate and ::-probe equivalence (including colon-adjacent sibling ids and the bounds optimization), confirmed the decoded/encoded toString forms are still checked identically, and confirmed no remaining production callers rely on the old single-path signatures. The parity and subscriber-count tests are meaningful (exact counters, > 0 disposed-set guard, listenerCount() - baseline delta) and would fail on a regression.

The one load-bearing invariant — that store actions are never reassigned inside a set() payload — is documented, statically checked by the author, and covered by the never reassigns a store action test. If a future slice ever makes one of these actions stateful, the memo would silently serve stale references, but that risk is deliberately accepted and guarded; no change needed now.

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

@nwparker
nwparker merged commit 3d67f2b into main Sep 2, 2026
29 checks passed
nwparker added a commit that referenced this pull request Sep 2, 2026
… dead export (#18240)

Readiness-review follow-ups to #18144.

The parity test in closed-editor-tab-disposal.test.ts cannot see prefix bleed:
buildScenario closes tab-0..tab-99, so tab-10 is in the closed batch too and the
per-tab oracle disposes its models via tab-10's own prefix. Batched and oracle
agree and the assertion passes even with a bleeding predicate. Verified by
mutation: replacing the boundary probe with a naive startsWith leaves all five
of that file's tests green.

Adds a test through the batched disposeClosedEditorTabs entry point with a
still-OPEN tab-10 alongside a closed tab-1, which does fail under that mutation.

Also records the `boundary + 1` advance in hasPaneScopeOwner as load-bearing for
`:::` runs, with a test that fails under a `+ 2` "tidy-up", and removes
disposeUnattachedMonacoModelsByPathPrefix, which #18144 left with zero production
callers and a comment claiming it was kept for callers that do not exist.

Finally, documents why title-derived rows carry `startedAt: 0`, which is the sole
reason their `now` stamps cannot move a dashboard bucket.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tore subscriptions (stablyai#18144)

Closing N diff tabs scanned the global Monaco model registry 2N times and
rendered both URI forms for every retained model on each scan. The Source
Control panel opened 42 store subscriptions from one hook, 40 of which watched
action identities that are fixed at store construction and can never change.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… dead export (stablyai#18240)

Readiness-review follow-ups to stablyai#18144.

The parity test in closed-editor-tab-disposal.test.ts cannot see prefix bleed:
buildScenario closes tab-0..tab-99, so tab-10 is in the closed batch too and the
per-tab oracle disposes its models via tab-10's own prefix. Batched and oracle
agree and the assertion passes even with a bleeding predicate. Verified by
mutation: replacing the boundary probe with a naive startsWith leaves all five
of that file's tests green.

Adds a test through the batched disposeClosedEditorTabs entry point with a
still-OPEN tab-10 alongside a closed tab-1, which does fail under that mutation.

Also records the `boundary + 1` advance in hasPaneScopeOwner as load-bearing for
`:::` runs, with a test that fails under a `+ 2` "tidy-up", and removes
disposeUnattachedMonacoModelsByPathPrefix, which stablyai#18144 left with zero production
callers and a comment claiming it was kept for callers that do not exist.

Finally, documents why title-derived rows carry `startedAt: 0`, which is the sole
reason their `now` stamps cannot move a dashboard bucket.
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