Advanced Analysis
These features go beyond the everyday tools. Most investigations don't need them, but they answer questions no class count or retainer trace can.
Closures and Scopes
Variables No Live Code Can Read
All closures created in one scope share one V8 Context. A large value used only by a callback that has already run stays alive for as long as any other closure from the same scope does.
memlab_dead_context_variables finds these values. It checks each variable
in each Context against the closures and suspended async functions still on
the heap, and reports the variables that nothing live can read. Rows are grouped
by scope (function and source position) and ranked by the bytes clearing them
would free: a value counts only when that slot is the one thing outside the
value that holds it. A value held only by dead slots, in several Contexts or
twice in one, is listed with how many slots hold it: no one of them frees it,
but clearing them all does. A dead variable whose value something else also
holds, such as the page's Window or Document, frees nothing, so it is
left out unless you pass include_shared: true. Each row gives the ids to pass to
memlab_retainer_trace.
This needs the source scope tree that V8 15.6 (Chrome 156) and later include
in snapshots. For the most accurate results, capture with Chrome 157 or later,
which leaves out script-level let and const. On older snapshots, the tool
says the scope tree is missing.
Scope Chains
A function that captures a closure from its previous call keeps that call's
whole Context alive, and that one keeps the call before it, back to the first
call. Every link is a system / Context, so a chain that grows by one per
interaction never shows up in a class count.
memlab_scope_chains follows these links between Contexts of the same
function. For each function, it reports the longest chain, the variables that
link it, and the id of its head. With a ladder (run_dir or paths), it
gives the longest chain at every rung, so you can tell a chain that keeps
growing from one that stops.
To size a fix, memlab_what_if({scope_of: <head id>}) frees every Context of
that function's scope at once, and reports how many bytes would come back,
without counting any byte twice. cascade: true adds what those Contexts
were the last holder of.
React Compiler development builds
The React Compiler's development build creates scope chains of its own: it
wraps each hook call in a closure that captures the hook's arguments. A chain
linked only through the compiler's temporaries (t0 … tN) is labelled as
this artifact. A production build doesn't create it; to confirm, read the
module from a production capture with memlab_module_source and
compare_to.
Stale React Context Values
Every React fiber that reads a context records the value it read, in
fiber.dependencies.firstContext → {context, memoizedValue, next}. When the
provider's value changes, a consumer that has not rendered since still holds
the old value, and everything that value keeps alive: an old Map, the
closures stored with it, and any detached element those closures captured.
This is neither a provider leak nor a {current} ref, so the ref tools don't
report it.
memlab_stale_context_snapshots compares each consumer's memoizedValue
with what its nearest provider supplies now, or with the context's default
when no provider is above it. A Context.Consumer fiber on the way up is not
taken for the provider. For a consumer in the current tree, "now" is the
memoizedProps.value of the provider's current fiber only: its alternate
fiber keeps the value from before the last change, which is exactly what a
stale consumer holds. A consumer outside the current tree is compared with
both copies. Rows are grouped by context and consumer
component, with how many consumers are still mounted and the bytes only the
stale value keeps alive (its retained size when its dominator chain runs
through the consumer's dependency record: what rendering that consumer again
would free). Run it on a settle rung with snapshot (default: the active
snapshot). Outside a render,
_currentValue holds the context's default, not the provided value, which is
why the tool reads the provider fiber instead.
Served Source
A browser snapshot keeps the source text of every script the page loaded, so you can read the code that actually ran next to the objects it created.
memlab_module_sourceprints a module's source, or the lines that matchgrep.memlab_source_for_node({node_ids, context_lines})prints the function behind a closure, or behind a Context through a closure over it.- In
memlab_eval,helpers.moduleSource(name)returns the same source,helpers.scripts()lists every script with its source text, andhelpers.stringsBySize({minLen})the longest strings, so a search over source text reads a hundred scripts instead of every string.
Custom Queries
When no tool answers your question, memlab_eval runs a JavaScript program
against the snapshot. The program assigns its answer to result, or returns
it.
- A node's
referencesandreferrerswork like arrays (.filter,.map,.find,.length,for…of). - Walk every node with
for (const n of snapshot.nodes),snapshot.nodes.forEach(…)orhelpers.forEachNode(…), and every edge withfor (const e of helpers.edges()). All of them count againstmax_nodes. helpers.ownProps(node)is{name: value}and also iterates as[name, value]pairs;helpers.ownPropNodes(node)returns[name, node].helpers.mapEntryNodes(map)also takes the Map's backing store;helpers.entryNodesis the same helper, and a Map row ofhelpers.mapEntriesorhelpers.entriesalso answers.keyNodeand.valueNode.helpers.help()lists the aliases.node.propsmaps an object's property names, or a Context's variable names, to nodes.node.locationis{script_id, line, column}.- The result prints as JSON: a node as
{id, name, type, self_size}, a Map or Set as an object or array, a BigInt as its decimal string. The program's ownJSON.stringifyturns a BigInt into a string too, instead of throwing. result = helpers.help()lists every helper with its signature and a short purpose;helpers.help("getProp")gives one in full. This is the quickest way to find a helper when you drive the server from a script.helpers.global("clearInterval")reads a page global: a property of the main realm's global object (the browser'sWindow [JSGlobalObject]with the most edges, or Node.js'sglobal);helpers.global()is that object.helpers.getPropon theWindow / <url>proxy reads through to it.helpers.byEdgeName(name)returns the HOLDERS of an edge, so for a page global it returns the global object, not the value.helpers.isArtifact(id)says whymemlab_artifact_budgetdoes not count a node as app memory: a dev or automation family (harnessfor the measurement harness's wrappers,reactFastRefresh,devEdgefor a React DEV edge or a devtools module,console, …) or a known artifact kind (ax,cdp-network, …). It returns null for app memory. Filter an owner tally with it, e.g.ids.filter(id => helpers.isArtifact(id) == null).helpers.prodReachable(id)is true when the node exists in a production build: it is reachable from a GC root or a module's top-level scope once every development edge (React_owner/_debug*, Fast Refresh, devtools, console handles) is cut. It is the same check as the dev-only labels, not "is the shortest path a dev one", which on a development build is true for nearly everything.helpers.prodReachable(id, {path: true})returns{reachable, route, devHop, path}:routeisproduction,production-dev-shortest(the shortest path crossesdevHop, and the productionpathsurvives the cut) ordev-only.- Helpers do common work:
helpers.ctxVars(node)lists a scope's variables,helpers.arrayLen(node)counts a collection's entries, andhelpers.firstRetainer(node)names the object one hop up. - A snapshot records no element for a small integer or a double, so an
array of numbers has no element edges.
helpers.arrayLenreads its length from the backing store's capacity instead of returning 0, andhelpers.arrayInfo(node)says how the length was worked out, with bounds: exact for an array built at its size, an upper bound for one grown bypush, a lower bound for a sparse (dictionary) array. For a sparse arrayhelpers.arrayLengives that same lower bound, not its visible entries, and null when no entry holds an object (its length is unknown). - For React:
helpers.fiberOf(domNode)returns a mounted element's fiber,helpers.componentName(fiber)its component,helpers.hooks(fiber)its hooks with their pending updates, andhelpers.memoCacheSlots(fiber)the React Compiler cache slots that can keep a stale closure alive. helpers.groupByShape(ids),helpers.topRetainers(ids)(who outside a set holds it),helpers.referrerChains(id)andhelpers.edgeWalk(id, names)replace the walks people otherwise write by hand.helpers.walk(id, "timer.context.s.table")follows a path of edges (also["listeners", 0, "callback"], or[n]for an element edge) and never throws on a missing hop: it returns{found, id, at, stoppedAt, missingEdge, available}, whereavailablelists the edges of the node it stopped on.helpers.edgeTarget(id, name, {strict: true})throws with those edges instead of returning null. ChainingedgeTargetcalls fails the whole query at the first missing hop.- A result over 8 KB (
max_result_bytes, ormax_output_chars) prints as a summary:__count(the number of entries),__top(the 10 largest by a numeric field such asretainedSizeorcount, or by value for a{name: count}map, as[key, value]pairs when a key is an integer) and__sample(the first entries that fit), cut at depth 2. The whole result is written to a JSON file under~/.memlab/results(MEMLAB_STATE_DIR, kept 7 days), and the footer gives its path, so you read the rest from the file instead of running the program again.memlab_eval_acrossdoes the same per rung, with the 8 KB shared between the rungs (at least 2 KB each). save_as: "name"keeps a result for later calls in the session.helpers.load("name")reads it back; for a saved list of node ids,restrict_to_ids: "name"runs the next program's node walk over those nodes only, andhelpers.byIds("name")returns the nodes. Ids are per snapshot, so a list saved against another snapshot is refused. A saved list of node ids is also a named population:population: "name"onmemlab_retainer_summary,memlab_trace_all,memlab_what_if,memlab_island_doorsandmemlab_validate_findingreads it without the ids passing through the conversation, and the reply tosave_asprints its count.- To ask several things at once, pass
queries: [{name, code}, ...]instead ofcode. The answers come back keyed by name, and one query failing does not stop the others. memlab_eval({mode: "recipes"})prints worked examples.
Before running a program, the tool checks it for mistakes that would waste a
whole scan: a helper that doesn't exist (it suggests the right one), a
program with no output (no result, return, console or helpers.save),
and an e.type === 'context' filter in code that never reaches a scope (a
closure's link to its scope is an internal reference named context). Pass
skip_lint: true if the check is wrong.
A program stopped by its timeout (timeout_ms) still returns what it had:
the partial result, or, when it had not assigned result yet, its
top-level variables as they stood, with a partial: {edges_visited,
nodes_visited, elapsed_ms} line. Assign the accumulator to result before
the loop (const out = {}; result = out;) so a timeout returns every count
made so far. mode: "lint" (and dry_run) warns about a helpers.stableKey
call inside a loop over one node's edges: each call walks a path, so over a
large dictionary the loop is quadratic. With the snapshot loaded and the node
id written as a literal, it estimates the loop from the node's edge count and
a measured per-call cost.
An error names the line and column in your code (or in the prelude) and
prints that line, for example at code line 3:10: with a caret under the
column. A failing query's error ends with (at query line N:C).
To run one program on every rung of a ladder, use memlab_eval_across (see
Snapshot Ladders).
caution
memlab_eval runs code with the privileges of the server process. See
Tool Permissions and Safety before approving it.
Saved Probes
If you investigate the same app again and again, you measure the same few
populations each time. Save each one once with memlab_probes: a
memlab_eval program that assigns a number to result, optionally with an
expect (flat or bounded) and a cap.
memlab_probes({mode: 'save', set: 'myapp', match: 'myapp.example.com',
name: 'open_dialogs', code: "result = helpers.byClass('Dialog').length",
expect: 'flat'})
Probes are saved in named sets in ~/.memlab/probes.json. When a set's
match is part of the round's URL filter, memlab_ladder_probe,
memlab_ab_compare and memlab_analysis_battery run it without being asked,
and print OK or VIOLATED for every probe with an expect. A set can also save
a run_dir. memlab_eval_across({use: ['myapp']}), with no code, then runs
every probe of the set on every rung of that round and returns one table with a
row per probe and a column per rung. With several sets, rows are named
<set>/<probe>, so probes of the same name in two sets both show. A probe that
throws or does not parse gets an error: … cell, and the other probes on that
rung still run. An unknown set name is an error.
Three helpers cover the counts such probes usually need:
helpers.countShapes({name: [props]}) counts plain objects that have every
listed property, per name. helpers.countStrings(regex, {prefix}) counts
matching strings. helpers.detachedElements() returns detached DOM elements
without the Blink records attached to them. You can also pass
probes: "<set>" to choose a set, or probes: "none" for none. On
memlab_ladder_probe and memlab_ab_compare, passing your own metrics also
turns the automatic choice off.
To test several hypotheses on one load of each rung, give
memlab_ladder_probe metrics of the form {code, expect, cap?}. expect is
flat, bounded (under cap, or slowing down), grows (up at every step),
absent (0 at every rung) or present (above 0 at the last rung), and a
true / false result counts as 1 / 0. The report then opens with a
Hypotheses table of PASS, FAIL or INCONCLUSIVE per hypothesis. A hypothesis is
INCONCLUSIVE when a rung gave no reading, the probe never found its holder, or
its series is all zero while the visibility control saw nothing either.
memlab_ladder_probe({run_dir, metrics: {
dialogs_bounded: {code: "result = helpers.byClass('Dialog').length", expect: 'bounded', cap: 3},
no_detached_frames: {code: "result = helpers.byClass('Detached HTMLIFrameElement').length", expect: 'absent'},
}})
Findings Index
memlab_finding_index remembers what earlier investigations found, so a new
one can check whether a finding is already known before investigating it.
A finding is identified by its retainer path, normalized. Some findings have
no stable path, so they are identified by a kind and its keys instead:
kind | Keys |
|---|---|
update-queue | component, and hook_ordinal or setter |
collection | class (optionally probe) |
probe | probe (optionally set) |
optimization | owner and waste_kind (optionally module): memory a fix gives back at a steady size, not a leak |
memlab_finding_index({action: 'record', kind: 'update-queue', round: 'r12',
keys: {component: 'ChatList', hook_ordinal: 3, setter: 'setMenuOpen'}})
Other useful actions:
listfilters byround,since_round,status,title,kindanddev_only.searchtakes a free-textqueryand looks for its words in each finding's title, note, signature, key values, growing classes and retraction reason. A word of five or more characters also matches a word one edit away, so a typo still finds the finding. Findings that contain at least half of the words are listed best first, with a Score column, up to 20; thelistfilters apply too.dev_only: truemarks a finding that only a development build has (for example dev-only code or a dev-only cache). It is separate fromstatus: "artifact", which means the population belongs to the test harness, not the app.kindis not a category:kind: "artifact"is refused with a pointer tostatus: "artifact".- When a
checkfinds no exact match, it lists likely matches. Attach the new sighting to one withaction: "reconfirm". action: "batch"runs several actions in one call, and returns one line per action.- Pass
run_dirto any action, and the round's name and workstream are read from itsrun.json. verified_by_abrecords the A/B result that verified a fix ({round, metric, off, on}), andrecordandcheckprint it next to the fix. Arecordoramendthat setsstatus: "fixed"without it gets a warning: the fix is a claim, not a result.fixed_by_commitsrecords the commit hashes that carry a fix (for example a local commit before it has a diff id), andexplainera link or id of the write-up.checkprints both.amendchanges any stored field, includingtitle, without counting a sighting.stalealso lists entries with a recorded fix whose status is stillknownorcandidate, since the nextcheckreads them as open findings.coverrecords the combinations of interactions a round drove. Withrun_dir, it also records the served code revision and a hash of the feature-flag values, so two rounds that drove the same combinations against different code can be told apart.
To find the code behind a finding, memlab_source_for_finding({fingerprint})
reads the module and field names off its retainer path, and lists up to three
files with the lines that assign those fields. It needs
MEMLAB_SOURCE_LOOKUP_CMD, a shell command that prints the files for
{module}, and reads the files from MEMLAB_SOURCE_ROOT or the current
directory. It doesn't read a printed path outside that directory, and a
lookup command that fails says why rather than reporting "no file".
To show the status of the code change that fixed each finding, set
MEMLAB_FIX_STATUS_CMD to a shell command containing {diff}. JSON output
is shown as its fields (status=Accepted, is_landed=false), anything else as
its first line.
MEMLAB_FIX_STATUS_TIMEOUT_MS sets its timeout (20 seconds by default).
Answers are cached for ten minutes per change, a lookup that fails says why
(a timeout, the exit code, or the first line of its error output), and
memlab_server_status shows the last lookup's result.
An agent's suggestions for improving memlab are a session record too:
memlab_feedback({text, areas}) writes one memlab_feedback record (the text
scrubbed like a finding note and cut to 32,000 characters, its suggestion
count, the areas it names, the agent runtime and this server's call counts),
with the round of round_dir when given, else as the session's.
memlab_feedback({prompt: true}) returns what to cover. Until one is
recorded, memlab_server_status says so and the first answer of a closing
tool (the leak report, hunt report, round digest, verdict table or report
lint) ends with a one-line pointer to it.
A wrapper that uploads the session records --record writes can report each
attempt in a JSON status file, MEMLAB_UPLOAD_STATUS_FILE:
{at, exit, rounds: [{round_key, label, status, error}], error, fix, log},
plus skipped (and exit: null) when the wrapper chose not to run the upload.
memlab_server_status and memlab-cli doctor then say how many rounds were
not recorded, with the last error and the fix, that the upload was not
attempted and why, or that all were recorded.
To have the server run that upload itself, set MEMLAB_RECORD_UPLOAD_CMD to
a shell command. The server runs it 30 seconds after a report-type record
(MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS), one run at a time and detached from the
server. A run that exits non-zero is retried after 1, 5 and 15 minutes
(MEMLAB_RECORD_UPLOAD_BACKOFF_MS). An upload still owed when the server
exits is attempted once more. MEMLAB_UPLOAD_RUNS=0 turns it off, and
memlab_server_status shows the last run and the next retry.