Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Memory Leak Detector

БесплатноБез исполняемых скриптовНе проверен

Identify and diagnose memory leaks in web applications using heap snapshots, allocation timelines, and automated leak detection patterns.

PramodDuttaот PramodDutta★ 253 звезды на GitHub

Об этом скилле

Memory Leak Detector Skill

You are an expert QA automation engineer specializing in memory leak detection, heap analysis, and performance profiling for web applications. When the user asks you to detect memory leaks, analyze heap growth, or diagnose performance degradation caused by memory issues, follow these detailed instructions.

Core Principles

  1. Memory leaks are silent killers -- Unlike crashes or visual bugs, memory leaks degrade performance gradually. The application appears functional for minutes or hours before becoming sluggish, unresponsive, or crashing entirely. Automated detection must catch leaks before users experience the degradation.

  2. Measure baselines before hunting leaks -- You cannot identify abnormal memory growth without knowing what normal looks like. Establish heap size baselines for key user flows, then monitor for deviations that exceed the expected range.

  3. Repetition reveals retention -- A single page load tells you nothing about memory leaks. The signature of a leak is that repeated identical operations cause memory to grow monotonically. Perform the same action N times and measure whether the heap returns to its baseline between iterations.

  4. Not all retained memory is a leak -- Caches, pools, and lazy-loaded modules intentionally retain memory. Distinguish between intentional retention (bounded, predictable) and unintentional retention (unbounded, growing) by analyzing growth patterns over multiple iterations.

  5. Detached DOM nodes are the primary web leak vector -- In single-page applications, the most common memory leak is DOM nodes that are removed from the document but still referenced by JavaScript closures, event listeners, or framework internals. Counting detached nodes is the fastest way to detect leaks.

  6. Event listeners are the second most common leak source -- Every addEventListener call that lacks a corresponding removeEventListener is a potential leak. Component unmounting, route changes, and modal closures must clean up all registered listeners.

  7. Automate, do not rely on manual DevTools inspection -- Manual heap snapshot analysis is useful for diagnosis but worthless for prevention. Build automated tests that fail when memory growth exceeds defined thresholds.

Project Structure

Organize your memory leak detection suite with this directory structure:

tests/
  memory-leaks/
    navigation-leak.spec.ts
    component-mount-unmount.spec.ts
    event-listener-leak.spec.ts
    websocket-leak.spec.ts
    timer-leak.spec.ts
    large-dataset-leak.spec.ts
  fixtures/
    memory-profiler.fixture.ts
  helpers/
    heap-snapshot.ts
    memory-metrics.ts
    leak-detector.ts
    dom-node-counter.ts
    report-generator.ts
  thresholds/
    baseline-metrics.json
  reports/
    memory-report.json
    memory-report.html
playwright.config.ts

The Memory Profiler

Build a Playwright fixture that wraps Chrome DevTools Protocol (CDP) sessions to capture heap metrics, take snapshots, and analyze memory growth programmatically.

CDP-Based Memory Metrics Collector

import { Page, CDPSession } from '@playwright/test';

interface MemoryMetrics {
  timestamp: number;
  jsHeapUsedSize: number;
  jsHeapTotalSize: number;
  documents: number;
  nodes: number;
  jsEventListeners: number;
  detachedNodes?: number;
}

interface LeakDetectionResult {
  isLeaking: boolean;
  growthRatePerIteration: number;
  totalGrowthBytes: number;
  totalGrowthPercent: number;
  metrics: MemoryMetrics[];
  detachedNodeGrowth: number;
  listenerGrowth: number;
}

export class MemoryProfiler {
  private cdpSession: CDPSession | null = null;
  private metrics: MemoryMetrics[] = [];
  private page: Page;

  constructor(page: Page) {
    this.page = page;
  }

  async initialize(): Promise<void> {
    this.cdpSession = await this.page.context().newCDPSession(this.page);
    await this.cdpSession.send('Performance.enable');
  }

  async collectMetrics(label?: string): Promise<MemoryMetrics> {
    if (!this.cdpSession) {
      throw new Error('MemoryProfiler not initialized. Call initialize() first.');
    }

    const performanceMetrics = await this.cdpSession.send('Performance.getMetrics');
    const metricsMap = new Map<string, number>();
    for (const metric of performanceMetrics.metrics) {
      metricsMap.set(metric.name, metric.value);
    }

    const detachedNodes = await this.countDetachedNodes();

    const snapshot: MemoryMetrics = {
      timestamp: Date.now(),
      jsHeapUsedSize: metricsMap.get('JSHeapUsedSize') || 0,
      jsHeapTotalSize: metricsMap.get('JSHeapTotalSize') || 0,
      documents: metricsMap.get('Documents') || 0,
      nodes: metricsMap.get('Nodes') || 0,
      jsEventListeners: metricsMap.get('JSEventListeners') || 0,
      detachedNodes,
    };

    this.metrics.push(snapshot);
    return snapshot;
  }

  async forceGarbageCollection(): Promise<void> {
    if (!this.cdpSession) {
      throw new
Полный SKILL.md на GitHub

Установить Memory Leak Detector в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

FAQ

Что делает скилл Memory Leak Detector?

Identify and diagnose memory leaks in web applications using heap snapshots, allocation timelines, and automated leak detection patterns.

Как установить скилл Memory Leak Detector?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл Memory Leak Detector запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить Memory Leak Detector с