Skip to content

fix: retire closed editor models from the app shell - #21178

Merged
nwparker merged 6 commits into
mainfrom
np-oom-scan-closed-editor-models
Sep 20, 2026
Merged

nwparker merged 6 commits into
mainfrom
np-oom-scan-closed-editor-models

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 17, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​957 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​957
Prod 30 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​8782 $\color{#cf222e}{\Huge{\mathbf{−}}}$​62 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​8720

ELI5

Closing a file could leave its full editor model in memory for the rest of the app session. This change releases models that no open editor still uses while keeping the small caches that remember where you were looking.

What Changed

Track model ownership through hidden and final editor closes. Wait for attached editors to detach before disposal, preserve live/reopened/shared owners, and keep the existing 20-entry view caches when a model is disposed.

Why

A closed editor should not retain all of its text and editing structures forever. Ownership checks prevent disposing a model another editor still needs. View positions do not require retaining the whole model.

Tradeoff

Undo is not guaranteed for every closed file: large files, raw Windows-drive URIs, and undo-budget eviction can still lose history. VS Code also disposes models and keeps bounded closed-file undo data rather than retaining every edited model forever (modelService.ts, modelUndoRedoParticipant.ts). Complete and test the bounded closed-file undo policy, including Windows URI normalization and large-file behavior, before claiming universal undo preservation; unlimited model retention defeats the memory fix.

Linked Issue

Related to #19831 as memory hardening; incident causality is not established.

Visual Proof

No before/after UI capture is attached; this changes editor lifetime behavior. Automated behavior evidence is linked under Testing.

Testing

Recorded validation includes 75 tests across nine suites and 32 comparative Node/Electron audit cases for ownership, attachment, reentrancy, view-cache preservation, and real Monaco close/reopen controls. Small POSIX/file-URI files retain undo through Monaco's existing closed-file support.

Original audit

Review

Do not merge unchanged if preserving undo is a hard requirement. A bounded detached undo store is the safer final design.

@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

📝 Walkthrough

Walkthrough

The change moves closed-editor cleanup from EditorPanel to an app-level store subscription. A controller now coordinates Monaco model attachment, ownership checks, deferred disposal, cache cleanup, and registry replacement handling. Monaco setup exposes the live registry through a bridge. New tests cover disposal, reentrancy, remounts, shared models, and HMR registration. Audit tooling, source fences, lifecycle results, and validation records document before/fixed behavior across graphs and runtimes.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to e9ee5

The implementation evidence is documented as having passed despite a failing typecheck in an unchanged file. Correct the wording so validation status is clear before merge.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 13.79% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 18 files. (13 skipped… 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 identifies the primary change: retiring closed editor models from the app shell.
Description check ✅ Passed The description is mostly complete and explains the user impact, implementation, motivation, tradeoffs, linked issue, visual-proof status, testing evidence, and review guidance. It omits several templ…
Full details: Docstring Coverage

Explanation

Docstring coverage is 13.79% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 18 files. (13 skipped: 13 unsupported.)

  • 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 critical issues — two informational notes in the body and two inline observations. The core ownership logic holds up.

Reviewed changes

  • App-shell cleanup ownership — useClosedEditorTabCleanup() now takes no args and attaches attachClosedEditorTabCleanup from useAppShellServices, so cleanup no longer dies with the conditionally-mounted EditorPanel.
  • New lifetime controller — closed-editor-tab-controller.ts diffs openFiles, captures candidate models, defers attached models until onDidChangeAttached, and re-checks live ownership (id, or parsed filePath URI for edit) behind a generational fence before every dispose/sweep.
  • Disposal helper rework — disposeClosedEditorTabs takes onAttachedModel/isStillClosed; edit models are disposed only when unattached; diff prefix matching now returns the matched prefix and the sweep accepts an ownership predicate.
  • Lazy registry bridge — new lib/editor-model-registry.ts singleton, registered from monaco-setup.ts with HMR unregistration.
  • Tests and audit evidence — 4 new suites (17 cases) using real Monaco models, plus the docs/audits/closed-editor-model-lifetime/ report tree.

I traced the controller's state machine (store subscription, schedule/flush/clearPending, retainedModels, reentrancy callbacks) and found no reachable path that disposes a model still owned by an open tab, nor one that retains a detached closed model forever. The findings below are the residual rough edges.

ℹ️ The production hook call site is not pinned by a permanent test

The essential wiring is use-app-shell-services.ts:34 — the whole point is that cleanup now attaches somewhere that cannot unmount. But closed-editor-model-shell.test.tsx:52-55 declares its own Shell that calls useClosedEditorTabCleanup() and mocks EditorPanel inert, so it exercises the controller, not that the app shell calls it: deleting line 34 would leave every new assertion green.

Technical details
# App-shell placement has no regression test

## Affected sites
- `src/renderer/src/app-shell/use-app-shell-services.ts:34` — production call site, unasserted.
- `src/renderer/src/components/editor/closed-editor-model-shell.test.tsx:52-55` — supplies its own hook call site, so it cannot detect removal of the production one.
- `src/renderer/src/app-startup-routing.test.ts` — references `use-app-shell-services` for other hooks only; nothing pins the cleanup hook.

## Required outcome
- A regression test that fails if the cleanup hook is not invoked from the app shell (either an assertion that `useAppShellServices` calls `useClosedEditorTabCleanup`, or an integration render of the shell with a real store and a mocked `EditorPanel`).

## Open questions for the human (optional)
- Is the audit suite's static source fence (`docs/audits/.../loader-controls.cjs`) intended to be the only guard on this wiring, or can a unit test own it?

ℹ️ Audit evidence lives under a non-allow-listed docs/audits/ tree

docs/** is gitignored except for an explicit allow-list. This PR adds a new docs/audits/closed-editor-model-lifetime/ subtree (~8.6k lines including two patches and seven JSON reports) with no matching allow-list entry, so those files exist only via force-add and a clean git add would silently skip them.

Technical details
# New docs subtree is not reproducible from a clean `git add`

## Affected sites
- `.gitignore:96-137` — `docs/**` is ignored; the allow-list has no `docs/audits/` entry.
- `docs/audits/closed-editor-model-lifetime/` — 15 tracked files added by this PR.

## Required outcome
- Decide whether this evidence is durable repo content. If yes, add `!docs/audits/` and `!docs/audits/**` (or relocate it under an allow-listed path). If no, the PR body plus the permanent test suites are the better home, and the working artifacts should be dropped.

## Open questions for the human (optional)
- Is committing the audit corpus itself the intended process, or is it normally attached to the PR? There is no prior `docs/audits/` directory on `main` to follow.

ℹ️ Nitpicks

  • src/renderer/src/lib/monaco-setup.ts:95-96 — extra blank line before the registry registration.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Preserve the captured model across registry replacement. · closed-editor-tab-controller.ts:47-55

src/renderer/src/components/editor/closed-editor-tab-controller.ts:47-55
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Preserve the captured model across registry replacement. When a close is queued before supported Monaco registry replacement, the registry notification clears candidateModels before replaying the descriptor. The successor flush then cannot dispose the original model, and no controller retry or other production owner handles it. Retain and dispose that exact captured model through the transition, while keeping the identity fence so a successor model at the same URI is not disposed.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 2a1091c8-637e-4498-bdaf-1e73eb306246

📥 Commits

Reviewing files that changed from the base of the PR and between 082e865 and 29820ed.

📒 Files selected for processing (3)
  • docs/audits/closed-editor-model-lifetime/README.md
  • docs/audits/closed-editor-model-lifetime/validation.json
  • src/renderer/src/components/editor/editor-model-lifetime-fixture.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • docs/audits/closed-editor-model-lifetime/README.md

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

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Preserve captured disposal work across registry… · closed-editor-tab-controller.ts:118-120

src/renderer/src/components/editor/closed-editor-tab-controller.ts:118-120
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Preserve captured disposal work across registry replacement.

If a close queues disposal while registry is available, then the bridge becomes null before flush runs, clearPending removes candidateModels. The registry callback restores only pendingFiles. A later flush therefore cannot re-find the original model through the fenced registry, so the model can remain undisposed.

Retain the captured files and models across the registry transition, then retry them when a registry becomes available. Do not add models created after the close to that snapshot.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 6c7a5708-e102-4b5e-bce9-bb6fbeca692a

📥 Commits

Reviewing files that changed from the base of the PR and between 29820ed and 44fe188.

📒 Files selected for processing (5)
  • src/renderer/src/components/editor/closed-editor-model-lifetime.test.ts
  • src/renderer/src/components/editor/closed-editor-model-registry.test.ts
  • src/renderer/src/components/editor/closed-editor-tab-controller.ts
  • src/renderer/src/components/editor/closed-editor-tab-disposal.ts
  • src/renderer/src/components/editor/closed-editor-view-state-retention.test.ts

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

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

Important

The cache-preservation follow-up changed the checked-out product sources but did not regenerate the committed audit artifacts, so the documented audit reproduction now aborts and the README contradicts the new tests.

Reviewed changes

  • CI fixture correction — editor-model-lifetime-fixture.ts drops Reflect.get/Reflect.apply for a typed attachment-port check and direct receiver-preserving calls.
  • Model retirement split from cache sweeping — disposeClosedEditorModels now owns model disposal; disposeClosedEditorTabs wraps it plus disposeClosedEditorTabCaches, and the controller calls only the model half so closed-tab view caches survive within their 20-entry LRU.
  • View-state retention coverage — new closed-editor-view-state-retention.test.ts (6 cases) pins cache preservation, the 20-entry LRU across 40 closes, and Monaco's closed-file undo limits; lifetime/registry expectations were updated to match.
  • Comment cleanup — the stale "models and view-state cache entries" JSDoc was replaced with a one-line note.

Verified locally: 32 tests across the seven related suites pass, and every production cache write goes through setWithLRU, so preserving the caches does not introduce unbounded growth.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@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: ccb55db0-5dc7-43ba-8883-86bbbaf3b7ea

📥 Commits

Reviewing files that changed from the base of the PR and between 44fe188 and e9ee5f5.

📒 Files selected for processing (17)
  • .gitignore
  • docs/audits/closed-editor-model-lifetime/README.md
  • docs/audits/closed-editor-model-lifetime/fix.patch
  • docs/audits/closed-editor-model-lifetime/loader-results.json
  • docs/audits/closed-editor-model-lifetime/main-before-electron-results.json
  • docs/audits/closed-editor-model-lifetime/main-before-node-results.json
  • docs/audits/closed-editor-model-lifetime/main-fixed-electron-results.json
  • docs/audits/closed-editor-model-lifetime/main-fixed-node-results.json
  • docs/audits/closed-editor-model-lifetime/source-versions.json
  • docs/audits/closed-editor-model-lifetime/validation.json
  • docs/audits/closed-editor-model-lifetime/worktree-before-electron-results.json
  • docs/audits/closed-editor-model-lifetime/worktree-before-node-results.json
  • docs/audits/closed-editor-model-lifetime/worktree-fixed-electron-results.json
  • docs/audits/closed-editor-model-lifetime/worktree-fixed-node-results.json
  • src/renderer/src/app-startup-routing.test.ts
  • src/renderer/src/components/editor/closed-editor-model-registry.test.ts
  • src/renderer/src/components/editor/closed-editor-tab-controller.ts
🚧 Files skipped from review as they are similar to previous changes (6)
  • docs/audits/closed-editor-model-lifetime/worktree-fixed-electron-results.json
  • docs/audits/closed-editor-model-lifetime/main-before-node-results.json
  • docs/audits/closed-editor-model-lifetime/main-before-electron-results.json
  • docs/audits/closed-editor-model-lifetime/worktree-before-node-results.json
  • docs/audits/closed-editor-model-lifetime/worktree-fixed-node-results.json
  • docs/audits/closed-editor-model-lifetime/main-fixed-electron-results.json

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

@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

  • Registry-replacement hardening — flush now keeps captured model custody when the bridge is temporarily null, and the registry subscription invalidates queued callbacks instead of calling clearPending, so a close queued across an unregister/re-register is retried rather than orphaned.
  • Interrupted-batch retry — when disposal itself triggers a registry replacement, the batch's files and still-live models are re-queued behind the generation fence, and the retained-model sweep bails on the same fence.
  • Registry-transition tests — four new cases in closed-editor-model-registry.test.ts cover queued custody, retained attachment custody, successor-URI preservation, and reentrant replacement; the tautological expect(bridge.get()).toBeNull() was removed.
  • App-shell wiring guard — app-startup-routing.test.ts now asserts the cleanup hook is called from use-app-shell-services and is absent from EditorPanel.
  • Audit regeneration — source-versions.json, fix.patch, the comparative reports, README, and validation.json were regenerated, and .gitignore now allow-lists docs/audits/.

Verified locally: loader-controls.cjs exits 0, the audit vitest config passes (4 cases), and 61 tests across the seven related product suites pass. All three prior threads are addressed and resolved.

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

Monaco keys its model registry by `uri.toString()`, and both
`@monaco-editor/react` (via the `path` prop) and the closed-tab disposal
path built that key with `Uri.parse`. On Windows a raw path such as
`C:\repo\a.ts` parses as scheme `c`, which fails the scheme gate in
`modelService._schemaShouldMaintainUndoRedoElements`, so closed-file undo
history was dropped for every file at any size — not only the large files
the tradeoff note covers.

Add `toEditorModelUri`, the one filesystem-path -> model-key function,
built on `Uri.file` so the result always carries the `file:` scheme and
re-parses to itself. Route model creation, disposal lookup and the
still-open ownership comparison through it so all three agree; a
divergence there would dispose a model an open editor is still editing.
@nwparker
nwparker merged commit 9218826 into main Sep 20, 2026
29 of 30 checks passed
@nwparker
nwparker deleted the np-oom-scan-closed-editor-models branch September 20, 2026 00:51
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.

2 participants