memory-leak-audit

$npx mdskill add microsoft/vscode/memory-leak-audit

Audits code for memory leaks and disposable issues in event listeners and lifecycle callbacks

  • Identifies memory leaks from unmanaged event listeners and disposable resources
  • Analyzes addDisposableListener, Event.once, DisposableStore, and onWillDispose usage
  • Checks for leaked listeners in DOM handlers, lifecycle events, and repeated object creation
  • Provides actionable fixes to prevent listener accumulation and object leaks

SKILL.md

.github/skills/memory-leak-auditView on GitHub ↗
---
name: memory-leak-audit
description: 'Audit code for memory leaks and disposable issues. Use when reviewing event listeners, DOM handlers, lifecycle callbacks, or fixing leak reports. Covers addDisposableListener, Event.once, MutableDisposable, DisposableStore, and onWillDispose patterns.'
---

# Memory Leak Audit

The #1 bug category in VS Code. This skill encodes the patterns that prevent and fix leaks.

## When to Use

- Reviewing code that registers event listeners or DOM handlers
- Fixing reported memory leaks (listener counts growing over time)
- Creating objects in methods that are called repeatedly
- Working with model lifecycle events (onWillDispose, onDidClose)
- Adding event subscriptions in constructors or setup methods

## Audit Checklist

Work through each check in order. A single missed pattern can cause thousands of leaked objects.

### Step 1: DOM Event Listeners

**Rule**: Never use raw `.onload`, `.onclick`, or `addEventListener()` directly. Always use `addDisposableListener()`.

```typescript
// BAD — leaks a listener every call
this.iconElement.onload = () => { ... };

// GOOD — tracked and disposable
this._register(addDisposableListener(this.iconElement, 'load', () => { ... }));
```

**Validated by**: PR #280566 — Extension icon widget leaked 185 listeners after 37 toggles.

### Step 2: One-Time Events

**Rule**: Use `Event.once()` for events that should only fire once (lifecycle events, close events, first-change events).

```typescript
// BAD — listener stays registered forever after first fire
model.onDidDispose(() => store.dispose());

// GOOD — auto-removes after first invocation
Event.once(model.onDidDispose)(() => store.dispose());
```

**Validated by**: PRs #285657, #285661 — Terminal lifecycle hacks replaced with `Event.once()`.

### Step 3: Repeated Method Calls

**Rule**: Objects created in methods called multiple times must NOT be registered to the class `this._register()`. Use `MutableDisposable` or return `IDisposable` to the caller.

```typescript
// BAD — every call adds another listener to the class store
startSearch() {
    this._register(this.model.onResults(() => { ... }));
}

// GOOD — MutableDisposable ensures max 1 listener
private readonly _searchListener = this._register(new MutableDisposable());

startSearch() {
    this._searchListener.value = this.model.onResults(() => { ... });
}
```

When the event should only fire once per method call, combine `Event.once()` with `MutableDisposable` — this auto-removes the listener after the first invocation while still guarding against repeated calls:

```typescript
private readonly _searchListener = this._register(new MutableDisposable());

startSearch() {
    this._searchListener.value = Event.once(this.model.onResults)(() => { ... });
}
```

**Validated by**: PR #283466 — Terminal find widget leaked 1 listener per search.

### Step 4: Model-Tied DisposableStores

**Rule**: When creating a `DisposableStore` tied to a model's lifetime, register `model.onWillDispose(() => store.dispose())` to the store itself.

```typescript
const store = new DisposableStore();
store.add(model.onWillDispose(() => store.dispose()));
store.add(model.onDidChange(() => { ... }));
```

**Validated by**: Pattern used in `chatEditingSession.ts`, `fileBasedRecommendations.ts`, `testingContentProvider.ts`.

### Step 5: Resource Pool Patterns

**Rule**: When using factory methods that create pooled objects (lists, trees), disposables must be registered to the individual item, not the pool class.

```typescript
// BAD — registers to pool, never cleaned per item
createItem() {
    const item = new Item();
    this._register(item.onEvent(() => { ... }));
    return item;
}

// GOOD — wrap with item-scoped disposal
createItem(): IDisposable & Item {
    const store = new DisposableStore();
    const item = new Item();
    store.add(item.onEvent(() => { ... }));
    return { ...item, dispose: () => store.dispose() };
}
```

**Validated by**: PR #290505 — Chat content parts CollapsibleListPool and TreePool leaked disposables.

### Step 6: Test Validation

**Rule**: Every test suite that creates disposable objects must call `ensureNoDisposablesAreLeakedInTestSuite()`.

```typescript
import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../base/test/common/utils.js';

suite('MyFeature', () => {
    ensureNoDisposablesAreLeakedInTestSuite();

    test('does something', () => {
        // test disposables are tracked automatically
    });
});
```

## Quick Reference

| Scenario | Pattern | Anti-Pattern |
|----------|---------|-------------|
| DOM events | `addDisposableListener()` | `.onclick =`, `addEventListener()` |
| One-time events | `Event.once(event)(handler)` | `event(handler)` for lifecycle |
| Repeated methods | `MutableDisposable` or return `IDisposable` | `this._register()` in non-constructor |
| Model lifecycle | `store.add(model.onWillDispose(...))` | Forgetting cleanup |
| Pooled objects | Item-scoped `DisposableStore` | Pool-scoped `this._register()` |
| Tests | `ensureNoDisposablesAreLeakedInTestSuite()` | No leak checking |

## Verification

After fixing leaks, verify by:
1. Checking listener counts before/after repeated operations
2. Running `ensureNoDisposablesAreLeakedInTestSuite()` in tests
3. Confirming object counts stabilize (don't grow linearly with usage)
4. **For chat-specific leaks**: Run the chat memory leak checker via `npm run perf:chat-leak` (see the `chat-perf` skill). It sends N messages in a single session, forces GC between each, and uses linear regression on heap/DOM samples to detect per-message growth. A slope above 2 MB/msg indicates a leak. Use `--messages 20 --verbose` for more accurate results.

More from microsoft/vscode

SkillDescription
accessibilityPrimary accessibility skill for VS Code. REQUIRED for new feature and contribution work, and also applies to updates of existing UI. Covers accessibility help dialogs, accessible views, verbosity settings, signals, ARIA announcements, keyboard navigation, and ARIA labels/roles.
act-on-feedbackAct on user feedback attached to the current session. Use when the user submits feedback on the session's changes via the Submit Feedback button.
agent-customization**WORKFLOW SKILL** — Create, update, review, fix, or debug VS Code agent customization files (.instructions.md, .prompt.md, .agent.md, SKILL.md, copilot-instructions.md, AGENTS.md). USE FOR: saving coding preferences; troubleshooting why instructions/skills/agents are ignored or not invoked; configuring applyTo patterns; defining tool restrictions; creating custom agent modes or specialized workflows; packaging domain knowledge; fixing YAML frontmatter syntax. DO NOT USE FOR: general coding questions (use default agent); runtime debugging or error diagnosis; MCP server configuration (use MCP docs directly); VS Code extension development. INVOKES: file system tools (read/write customization files), ask-questions tool (interview user for requirements), subagents for codebase exploration. FOR SINGLE OPERATIONS: For quick YAML frontmatter fixes or creating a single file from a known pattern, edit the file directly — no skill needed.
agent-host-chat-contributionsBuild and review cross-cutting agent-host chat behavior through lifecycle contributions. Use when adding turn lifecycle side effects, prompt or context injection, restored-history transformation, protocol-action observation, or when reviewing changes that add code to AgentSideEffects or AgentService.
agent-host-e2e-testsUse when writing, recording, updating, validating, or troubleshooting Agent Host end-to-end and real-provider integration tests under src/vs/platform/agentHost/test/node/e2e and providerIntegration. Covers adding a cross-provider test, re-recording fixtures after an SDK bump, required cross-platform Azure validation, gating non-deterministic or platform-specific tests, and diagnosing replay cache misses.
agent-host-logsAnalyze Agent Host debug log exports. Use when given an ah-logs or ahp-logs zip/folder, an Export Agent Host Debug Logs bundle, events.jsonl, AHP JSONL transport logs, Agent Host.log, remote-agenthost.log, or copilot-logs.
author-contributionsIdentify all files a specific author contributed to on a branch vs its upstream, tracing code through renames. Use when asked who edited what, what code an author contributed, or to audit authorship before a merge. This skill should be run as a subagent — it performs many git operations and returns a concise table.
auto-perf-optimizeRun agent-driven VS Code performance or memory investigations. Use when asked to launch Code OSS, automate a VS Code scenario, run the Chat memory smoke runner, capture renderer heap snapshots, take workflow screenshots, compare run summaries, or drive a repeatable scenario before heap-snapshot analysis.
azure-pipelinesUse when validating Azure DevOps pipeline changes for the VS Code build. Covers queueing builds, checking build status, viewing logs, and iterating on pipeline YAML changes without waiting for full CI runs.
build-champ-triageFind out why a build has failed