Skip to content
Skills Library
Programming · Review & audit

memory-leak-audit

/memory-leak-audit

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.

Repository
vscode ↗
Licence
MIT
Last repository change
27.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
0
Deprecation

No signals detected. Repository changed on 27.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

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.

Original author 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.

How it works

  1. When to Use
  2. Audit Checklist
  3. Quick Reference
  4. Verification
Original SKILL.md headings · 145 lines, 697 words
SKILL.md preview
---
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.

Versions

The database has no other skills named memory-leak-audit.

Identical content appears in 1 other GitHub folders. We show one copy with the highest score.

Database snapshot: 13.11.2026 · package version 25b0e857dc88 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100axiom-audit-memory
    Use when the user mentions memory leak prevention, code review for memory issues, or proactive leak checking — retain cycles, leaks, and Timer/observer patterns.
  • 95memory-leak-debugging
    Diagnoses and resolves memory leaks in JavaScript/Node.js applications. Use when a user reports high memory usage, OOM errors, or wants to analyze heapsnapshots or run memory leak detection tools like memlab.
  • 100detecting-memory-leaks
    Detect potential memory leaks and analyze memory usage patterns in code. Use when troubleshooting performance issues related to memory growth or identifying leak sources. Trigger with phrases like "detect memory leaks", "analyze memory usage", or "find memory issues".
  • 100detecting-memory-leaks
    Detect potential memory leaks and analyze memory usage patterns in code. Use when troubleshooting performance issues related to memory growth or identifying leak sources. Trigger with phrases like "detect memory leaks", "analyze memory usage", or "find memory issues".
  • 100memory-leaks
    Use when reviewing scripts, client components, bundles, or runtime behavior related to Prevent common memory leak patterns. Inspect both source code and the browser execution path so fixes target the real bottleneck or bug.
  • 100mobiai-review-code
    Use when reviewing mobile code changes — check for lifecycle issues, memory leaks, thread safety, and platform-specific pitfalls.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.