MemLab Documentation

repository·main·Indexed 26 days ago

https://github.com/facebook/memlab

An end-to-end testing and analysis framework for identifying JavaScript memory leaks and optimization opportunities in browsers, Node.js, Electron, and Hermes. It includes a core library for heap snapshot parsing, a CLI for leak detection, an E2E testing framework for Chromium, and MemLens for interactive React memory scanning. Additionally, it provides an MCP server (@memlab/mcp-server) allowing AI assistants to interact with heap analysis APIs for tasks like sequence analysis, property distribution, and growth signal detection.

Tokens
81.8K
Snippets
171
Records
498
Agent score
84%

What's inside MemLab

  1. Overview of memlab E2E

    main
    The memlab E2E package is a testing framework designed for headless or headful Chromium browsers. It provides the core functionality for controlling and interacting with the browser, recording heap snapshots, and logging execution metadata during memory leak investigations.
  2. Overview of Memlab features

    main

    Memlab is a memory testing framework for JavaScript designed to automate the process of finding and analyzing memory leaks in Single-Page Applications (SPAs).

    Key capabilities include:

    • Automated Testing: Define a IScenario using the Puppeteer API to interact with your application. Memlab automatically handles browser interaction, heap snapshotting, leak filtering, aggregation, and retainer trace generation.
    • Object-oriented Heap Traversal: Provides a programmatic API for analyzing JS heap snapshots from Chromium-based browsers, Node.js, Electron.js, and Hermes. This includes support for custom memory leak detectors via ILeakFilter.
    • Memory CLI Toolbox: Includes built-in CLI commands and APIs (like BaseAnalysis) to identify memory optimization opportunities.
    • Memory Assertions in Node.js: Allows Node.js programs or unit tests to take heap snapshots of their own state and perform self-checks using methods like hasobjectwithclassname on IHeapSnapshot.
  3. Overview of memlab Core Library

    main

    The memlab core library provides the fundamental building blocks for memory leak detection and analysis. It includes:

    • V8/Hermes heap snapshot parsers
    • Core memory analysis algorithms
    • Leak trace clustering
    • Utilities and configuration management
  4. Understand memlab execution breadcrumbs

    main

    During execution, memlab displays a live-updating breadcrumb showing its progress. After completion, the terminal displays the JavaScript heap size at each step and groups leaked objects by potential root causes.

    Each step in the breadcrumb represents a specific state:

    • page-load (baseline): The starting point showing memory allocated when the page initially loaded.
    • action-on-page (target): The memory state after the action function has been executed.
    • revert (final): The memory state after the back function has been executed to return to the baseline state.

    Example output format: page-load[23MB](baseline)[s1] > action-on-page[37.3MB](target)[s2] > revert[35.9MB](final)[s3]

  5. How MemLab calculates leaked objects

    main

    MemLab uses set theory to isolate potential memory leaks from heap snapshots. The logic follows this formula:

    (STP \ SBP) ∩ SFP

    1. Subtraction (STP \ SBP): It identifies objects allocated during the target interaction by taking the target heap snapshot (STP) and removing all objects that existed in the baseline heap snapshot (SBP).
    2. Intersection (∩ SFP): It then intersects that set with the objects remaining in the final heap snapshot (SFP).

    This process isolates objects that were allocated during the target interaction but are still alive when they should have been released. MemLab further refines this list using heuristics for specific leak types, such as detached DOM elements, error stack traces, and unmounted React Fiber nodes.

  6. Explore Memlab Modules

    main

    Memlab is organized into several core modules that provide different levels of interaction for memory leak detection and analysis:

    • @memlab/api: The primary API for programmatic interaction with Memlab.
    • @memlab/core: The core library containing the main logic and engine.
    • @memlab/heap-analysis: Specialized tools for performing deep heap analysis and investigating memory usage.
  7. Use the Memlab API for memory leak detection

    main

    The @memlab/api package provides programmatic access to Memlab's core capabilities, allowing you to automate memory leak detection, run browser interactions, and take heap snapshots within your own scripts or CI pipelines.

    Key functional areas include:

    • Leak Detection: Using findLeaks or findLeaksBySnapshotFilePaths to identify memory growth.
    • Execution Control: Using run to execute a full Memlab session or takeSnapshots to capture specific heap states.
    • Analysis: Using analyze to process results or specialized ResultReader classes to parse browser interactions and snapshots.
  8. Understand MemLens Core Functionality

    main

    MemLens is a memory diagnostic and debugging tool designed for React applications. It focuses on detecting and visualizing memory leaks, specifically identifying detached components that persist in memory despite being removed from the DOM.

    It achieves this through:

    • DOM Scanning: Mapping all elements in the DOM.
    • React Fiber Analysis: Tracking the React fiber tree to understand component hierarchy.
    • Leak Detection: Identifying components that are detached from the main DOM tree but still reside in memory.
    • Dual Monitoring: Using both periodic scanning and real-time mutation observers to detect changes.
  9. Use the memlab CLI

    main
    The memlab CLI library provides access to all MemLab commands, command-line options, and command-line interfaces. It is the primary entry point for running memory leak detection tasks from the terminal and supports extensibility for adding new commands.
  10. Investigate String Waste (duplicated/large strings)

    main

    Use this path when triage indicates high string duplication or strings consuming >30% of the heap.

    Investigation Steps:

    1. memlab_duplicated_strings: Identify top duplicated strings by total retained size and per-entry savings. Use include_node_ids: true if you plan to use memlab_retainer_summary later.
    2. memlab_intern_opportunities: Recommended starting point for interning. Groups duplicated strings by property name and parent object shape. Shows total savings per (property × shape) combination. Use summary_only: true for a compact view when screening many snapshots.
    3. memlab_string_patterns: Group strings by prefix to find families (e.g., API responses, IDs, URLs).
    4. memlab_sliced_strings: Check if small substrings are keeping massive parent strings alive.
    5. memlab_retainer_summary: For the top duplicated string, use this with class_name: "string" or specific node_ids to cluster retainer patterns. Use compact: true and framework_filter: true to reduce token usage.

    Common Fixes:

    • Use string interning with a Map<string, string> pool for JSON/API responses.
    • For sliced strings, use Buffer.from(str).toString() or concatenation to create an independent copy instead of str.slice() to allow the parent to be GC'd.
  11. Deploy the Memlab website

    main

    You can deploy the website using either SSH or GitHub Pages.

    Using SSH: Set the USE_SSH environment variable to true.

    Using GitHub Pages: Set the GIT_USER environment variable to your GitHub username. This will build the website and push it to the gh-pages branch.