/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @oncall memory_lab */ /** * Unit tests for session records (`MEMLAB_RECORD_FILE`, and the records * directory on a host with an uploader). * * npm run build-pkg && npm run test-units * * Runs against the BUILT dist/. */ import './test-isolation.mjs'; import assert from 'assert/strict'; import {execFileSync} from 'child_process'; import {createHash} from 'crypto'; import fs from 'fs'; import {test} from 'node:test'; import os from 'os'; import path from 'path'; import {fileURLToPath, pathToFileURL} from 'url'; const here = path.dirname(fileURLToPath(import.meta.url)); const dist = path.join(here, '..', 'dist'); if (!fs.existsSync(path.join(dist, 'session-record.js'))) { console.error( 'check-session-record: dist/session-record.js is missing; build first.', ); process.exit(1); } const load = rel => import(pathToFileURL(path.join(dist, rel)).href); const { RECORD_CONTRACT_VERSION, noteRecord, resetRecordFilesForTests, withToolCallRecord, } = await load('session-record.js'); const {resetRecordUploadForTests} = await load('record-upload.js'); const {noteSnapshotRead, runWithReadScope} = await load('read-scope.js'); const {SERVER_VERSION} = await load('server-version.js'); const {registerRoundAudit} = await load('tools/round-audit.js'); const {registerLeakReport} = await load('tools/leak-report.js'); const {registerVerifyFix} = await load('tools/verify-fix.js'); const {registerFindingIndex} = await load('tools/finding-index.js'); const {registerLoadSnapshot} = await load('tools/load-snapshot.js'); const {registerDuplicatedStrings} = await load('tools/duplicated-strings.js'); const {registerLargestObjects} = await load('tools/largest-objects.js'); const {getSnapshot, resetEmittedNotes} = await load('heap-state.js'); const {registerRetainerTrace} = await load('tools/retainer-trace.js'); const {recordEdge, recordPath} = await load('session-record.js'); const {resetSuggestionBudget} = await load('utils.js'); const {z} = await import('zod'); /** Call a tool's handler with its zod defaults applied, as the SDK would. */ async function callTool(register, input) { let reg; register({tool: (...args) => (reg = args)}); const shape = reg.find( a => a != null && typeof a === 'object' && Object.values(a).some(v => v?._def != null), ); const res = await reg.at(-1)(z.object(shape ?? {}).parse(input)); return res.content.map(c => c.text).join('\n'); } const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), 'session-record-')); // No real uploader in these tests: a `meta` on the PATH would make every test // session upload its records. The tests that need an uploader name a command. process.env.PATH = (process.env.PATH ?? '') .split(path.delimiter) .filter(dir => dir === '' || !fs.existsSync(path.join(dir, 'meta'))) .join(path.delimiter); delete process.env.MEMLAB_RECORD_UPLOAD_CMD; process.env.MEMLAB_RECORDS_DIR = tmp(); /** Run `fn` on a host whose uploader is `true`, with records under `dir`. */ async function withUploader(dir, fn) { const saved = { cmd: process.env.MEMLAB_RECORD_UPLOAD_CMD, dir: process.env.MEMLAB_RECORDS_DIR, }; process.env.MEMLAB_RECORD_UPLOAD_CMD = 'true'; process.env.MEMLAB_RECORDS_DIR = dir; resetRecordFilesForTests(); try { return await fn(); } finally { resetRecordUploadForTests(); resetRecordFilesForTests(); if (saved.cmd == null) { delete process.env.MEMLAB_RECORD_UPLOAD_CMD; } else { process.env.MEMLAB_RECORD_UPLOAD_CMD = saved.cmd; } process.env.MEMLAB_RECORDS_DIR = saved.dir; } } const jsonlIn = dir => fs.readdirSync(dir).filter(name => name.endsWith('.jsonl')); function readRecords(file) { if (!fs.existsSync(file)) { return []; } return fs .readFileSync(file, 'utf8') .split('\n') .filter(Boolean) .map(l => JSON.parse(l)); } function withRecordFile(file, fn) { const before = process.env.MEMLAB_RECORD_FILE; if (file == null) { delete process.env.MEMLAB_RECORD_FILE; } else { process.env.MEMLAB_RECORD_FILE = file; } return Promise.resolve(fn()).finally(() => { if (before == null) { delete process.env.MEMLAB_RECORD_FILE; } else { process.env.MEMLAB_RECORD_FILE = before; } }); } test('on a host with an uploader, records go to this process file in the records directory, whatever launched the server', async () => { const dir = tmp(); await withUploader(dir, () => withRecordFile(null, () => noteRecord('t', 'leak_report', {a: 1})), ); const files = jsonlIn(dir); assert.equal(files.length, 1); assert.match(files[0], /^\d{8}T\d{6}Z-\d+\.jsonl$/); assert.equal(fs.statSync(path.join(dir, files[0])).mode & 0o777, 0o600); const [record] = readRecords(path.join(dir, files[0])); assert.equal(record.kind, 'leak_report'); assert.deepEqual(record.data, {a: 1}); }); test('a records file that cannot be opened is reported once across retries in later seconds', async () => { const dir = tmp(); fs.chmodSync(dir, 0o500); const errors = []; const consoleError = console.error; console.error = (...a) => errors.push(a.join(' ')); try { await withUploader(dir, async () => { await withRecordFile(null, () => noteRecord('t', 'leak_report', {a: 1})); await new Promise(r => setTimeout(r, 1100)); await withRecordFile(null, () => noteRecord('t', 'leak_report', {a: 2})); }); } finally { console.error = consoleError; fs.chmodSync(dir, 0o700); } const creation = errors.filter(e => /could not create a session-record file/.test(e), ); assert.equal(creation.length, 1, creation.join('\n')); }); test('a records directory that could not be created is retried on the next record', async () => { const parent = tmp(); const dir = path.join(parent, 'records'); // A file where the directory should be: mkdir fails with EEXIST/ENOTDIR. fs.writeFileSync(dir, ''); const errors = []; const consoleError = console.error; console.error = (...a) => errors.push(a.join(' ')); try { await withUploader(dir, async () => { await withRecordFile(null, () => { noteRecord('t', 'leak_report', {a: 1}); noteRecord('t', 'leak_report', {a: 2}); }); fs.rmSync(dir); await withRecordFile(null, () => noteRecord('t', 'leak_report', {a: 3})); }); } finally { console.error = consoleError; } const creation = errors.filter(e => /could not create a session-record file/.test(e), ); assert.equal(creation.length, 1, 'the same failure is reported once'); const files = jsonlIn(dir); assert.equal(files.length, 1); assert.deepEqual( readRecords(path.join(dir, files[0])).map(r => r.data), [{a: 3}], ); }); test('a MEMLAB_RECORD_FILE outside the records directory gets a copy there; one inside gets the only copy', async () => { const dir = tmp(); const outside = path.join(tmp(), 'gate.jsonl'); await withUploader(dir, () => withRecordFile(outside, () => noteRecord('t', 'round_audit', {v: 1})), ); assert.equal(readRecords(outside).length, 1); assert.equal(jsonlIn(dir).length, 1, 'a copy in the records directory'); const dir2 = tmp(); const inside = path.join(dir2, 'named.jsonl'); await withUploader(dir2, () => withRecordFile(inside, () => noteRecord('t', 'round_audit', {v: 2})), ); assert.deepEqual(jsonlIn(dir2), ['named.jsonl']); assert.equal(readRecords(inside).length, 1); }); test('noteRecord writes nothing unless MEMLAB_RECORD_FILE is set', async () => { const dir = tmp(); await withRecordFile(null, () => noteRecord('t', 'leak_report', {a: 1})); assert.deepEqual(fs.readdirSync(dir), []); }); test('noteRecord appends one JSON line per call', async () => { const file = path.join(tmp(), 'records.jsonl'); await withRecordFile(file, () => { noteRecord('memlab_a', 'leak_report', {n: 1}); noteRecord('memlab_b', 'verify_fix', {n: 2}); }); const recs = readRecords(file); assert.equal(recs.length, 2); assert.equal(recs[0].contract, RECORD_CONTRACT_VERSION); assert.equal(recs[0].tool, 'memlab_a'); assert.equal(recs[1].kind, 'verify_fix'); assert.deepEqual(recs[1].data, {n: 2}); assert.ok(!Number.isNaN(Date.parse(recs[0].at))); assert.equal(recs[0].server_version, SERVER_VERSION); assert.equal(recs[0].round, undefined); }); test('noteRecord never throws when the file cannot be written', async () => { const file = path.join(tmp(), 'missing-dir', 'records.jsonl'); const errors = []; const orig = console.error; console.error = m => errors.push(String(m)); try { await withRecordFile(file, () => noteRecord('memlab_a', 'leak_report', {})); } finally { console.error = orig; } assert.equal(errors.length, 1); assert.match(errors[0], /could not write the memlab_a record/); }); /** `//snapshots/rung_0.heapsnapshot`, with `manifest` as the round's run.json. */ function roundWithRung(name, manifest) { const dir = path.join(fs.realpathSync(tmp()), name); fs.mkdirSync(path.join(dir, 'snapshots'), {recursive: true}); if (manifest != null) { fs.writeFileSync(path.join(dir, 'run.json'), JSON.stringify(manifest)); } return {dir, rung: path.join(dir, 'snapshots', 'rung_0.heapsnapshot')}; } const roundKey = dir => createHash('sha256') .update(`${os.hostname()}\0${dir}`) .digest('hex') .slice(0, 16); test('a record names the round of the snapshot the call read last', async () => { const first = roundWithRung('r41', null); const {dir, rung} = roundWithRung('r42 voip/call', { app: 'wa', combos: ['voip call', 7, 'x'.repeat(200)], }); const file = path.join(tmp(), 'records.jsonl'); await withRecordFile(file, () => runWithReadScope(async () => { noteSnapshotRead(first.rung); noteSnapshotRead(rung); noteRecord('memlab_a', 'leak_report', {}); }), ); const [rec] = readRecords(file); assert.deepEqual(rec.round, { key: roundKey(dir), label: 'call', app: 'wa', combos: ['voip_call', 'x'.repeat(128)], }); assert.ok(!JSON.stringify(rec).includes(dir)); }); test("a round's combos come from hunt_runner's config.combos too", async () => { const {dir, rung} = roundWithRung('r45', { app: 'whatsapp-web', config: {combos: ['wa-idle-control']}, }); const file = path.join(tmp(), 'records.jsonl'); await withRecordFile(file, () => runWithReadScope(async () => { noteSnapshotRead(rung); noteRecord('memlab_a', 'leak_report', {}); }), ); const [rec] = readRecords(file); assert.deepEqual(rec.round, { key: roundKey(dir), label: 'r45', app: 'whatsapp-web', combos: ['wa-idle-control'], }); }); test('a read inside a nested scope names the round for the enclosing call', async () => { const {dir, rung} = roundWithRung('r43', null); const file = path.join(tmp(), 'records.jsonl'); await withRecordFile(file, () => runWithReadScope(async () => { await runWithReadScope(async () => noteSnapshotRead(rung)); noteRecord('memlab_battery', 'tool_call', {}); }), ); const [rec] = readRecords(file); assert.deepEqual(rec.round, { key: roundKey(dir), label: 'r43', app: null, combos: [], }); }); test('a call names the round its parameters point at, unless it reads another', async () => { const named = roundWithRung('r44', null); const read = roundWithRung('r45', null); const file = path.join(tmp(), 'records.jsonl'); await withRecordFile(file, () => runWithReadScope(async () => { await withToolCallRecord( 'memlab_leak_report', {paths: [read.rung, named.rung]}, async () => noteRecord('memlab_leak_report', 'leak_report', {}), ); await runWithReadScope(() => withToolCallRecord('memlab_x', {file_path: named.rung}, async () => noteSnapshotRead(read.rung), ), ); await runWithReadScope(() => withToolCallRecord( 'memlab_round_audit', {run_dir: named.dir}, async () => ({}), ), ); }), ); assert.deepEqual( readRecords(file).map(r => [r.tool, r.kind, r.round.label]), [ ['memlab_leak_report', 'leak_report', 'r44'], ['memlab_leak_report', 'tool_call', 'r44'], ['memlab_x', 'tool_call', 'r45'], ['memlab_round_audit', 'tool_call', 'r44'], ], ); }); test('withToolCallRecord records duration and failure, and passes results and errors through', async () => { const file = path.join(tmp(), 'records.jsonl'); const off = await withRecordFile(null, () => withToolCallRecord('memlab_a', {}, async () => 'answer'), ); assert.equal(off, 'answer'); assert.equal(readRecords(file).length, 0); await withRecordFile(file, async () => { assert.deepEqual( await withToolCallRecord('memlab_ok', {}, async () => ({content: []})), {content: []}, ); await withToolCallRecord('memlab_bad', {}, async () => ({ content: [], isError: true, })); await assert.rejects( withToolCallRecord('memlab_throws', {}, async () => { throw new Error('timed out'); }), /timed out/, ); }); const recs = readRecords(file); assert.deepEqual( recs.map(r => [r.tool, r.kind, r.data.is_error]), [ ['memlab_ok', 'tool_call', false], ['memlab_bad', 'tool_call', true], ['memlab_throws', 'tool_call', true], ], ); assert.ok(recs.every(r => Number.isInteger(r.data.ms) && r.data.ms >= 0)); assert.deepEqual(Object.keys(recs[0].data).sort(), ['is_error', 'ms']); }); function roundDir() { const dir = tmp(); fs.writeFileSync( path.join(dir, 'run.json'), JSON.stringify({ run_id: 'r1', totals: {cycles: 60, ok: 58, fail: 2}, rungs: [0, 20, 40, 60].map((c, index) => ({ index, path: `snapshots/rung_${index}_c${c}.heapsnapshot`, })), settle_rung: {path: 'snapshots/rung_99_settle.heapsnapshot'}, environment: {dev_build: false}, config: {combos: ['open_chat']}, positive_controls: [{name: 'p', kind: 'map-size', edge: 'm'}], stop_reason: 'cycles', }), ); return dir; } async function audit(runDir) { let handler; registerRoundAudit({tool: (...args) => (handler = args.at(-1))}); const res = await handler({run_dir: runDir}); return res.content.map(c => c.text).join('\n'); } test('round_audit records its verdict and the run shape, and its answer is unchanged', async () => { const dir = roundDir(); const file = path.join(tmp(), 'records.jsonl'); const plain = await withRecordFile(null, () => audit(dir)); const recorded = await withRecordFile(file, () => runWithReadScope(() => withToolCallRecord('memlab_round_audit', {run_dir: dir}, () => audit(dir), ), ), ); assert.equal(recorded, plain); const recs = readRecords(file); assert.deepEqual( recs.map(r => r.kind), ['round_audit', 'tool_call'], ); const {data, kind, tool, round} = recs[0]; assert.equal(round.key, roundKey(path.resolve(dir))); assert.equal(tool, 'memlab_round_audit'); assert.equal(kind, 'round_audit'); assert.equal(data.run_id, 'r1'); assert.match(plain, new RegExp(`Verdict: ${data.verdict}`)); assert.equal(data.cycles, 60); assert.equal(data.cycles_landed, 58); assert.equal(data.rungs, 4); assert.equal(data.settle, true); assert.equal(data.dev_build, false); assert.deepEqual(data.combos, ['open_chat']); assert.equal(data.positive_controls, 1); assert.ok(data.checks.length > 0); for (const c of data.checks) { assert.deepEqual(Object.keys(c).sort(), ['name', 'status']); } }); test('recordLabel hashes string contents and keeps class names', async () => { const {recordLabel} = await load('session-record.js'); assert.equal(recordLabel('Map', 'object'), 'Map'); const a = recordLabel('secret token value', 'string'); assert.match(a, /^\(string [0-9a-f]{12}\)$/); assert.equal(recordLabel('secret token value', 'concatenated string'), a); assert.ok(!a.includes('secret')); }); test('recordLabel hashes regexp sources, URLs and data-shaped attribute values', async () => { const {recordLabel} = await load('session-record.js'); const re = recordLabel('^thread_15551234567$', 'regexp'); assert.match(re, /^\(regexp [0-9a-f]{12}\)$/); assert.match(recordLabel('Symbol(user 8812)', 'symbol'), /^\(symbol /); assert.match(recordLabel('15551234567', 'number'), /^\(number /); const url = 'https://app.example.com/messages/t/15551234567'; const win = recordLabel(`Window / ${url}`, 'object'); assert.match(win, /^Window \/ \(url [0-9a-f]{12}\)$/); assert.equal( recordLabel(`Window (global*) / ${url}`, 'object').endsWith(win.slice(9)), true, ); const ctx = recordLabel( 'system / NativeContext / blob:https://x.com/abc', 'hidden', ); assert.match(ctx, /^system \/ NativeContext \/ \(url [0-9a-f]{12}\)$/); assert.match( recordLabel('Script / about:blank', 'code'), /^Script \/ \(url /, ); const el = recordLabel( 'Detached
', 'native', ); assert.match( el, /^Detached
$/, ); assert.equal( recordLabel('', 'native').includes( 'x.com', ), false, ); for (const label of [re, win, ctx, el]) { assert.ok(!label.includes('15551234567'), label); assert.ok(!/https?:/.test(label), label); } assert.equal(recordLabel('onMessage', 'closure'), 'onMessage'); assert.equal(recordLabel('system / Context', 'hidden'), 'system / Context'); assert.equal( recordLabel('Detached
', 'native'), 'Detached
', ); }); /** Three snapshots of a node process in which `LeakyThing` grows by `perRung` per rung. */ function growingLadder(perRung = 300) { const dir = tmp(); const script = ` const v8 = require('v8'); class LeakyThing { constructor(i) { this.i = i; } } globalThis.kept = []; for (let i = 0; i < 300; i++) globalThis.kept.push(new LeakyThing(i)); for (let rung = 0; rung < 3; rung++) { for (let i = 0; i < ${perRung}; i++) globalThis.kept.push(new LeakyThing(i)); v8.writeHeapSnapshot(process.argv[1] + '/rung_' + rung + '.heapsnapshot'); }`; execFileSync(process.execPath, ['-e', script, dir]); return [0, 1, 2].map(i => path.join(dir, `rung_${i}.heapsnapshot`)); } async function leakReport(paths) { let handler; registerLeakReport({tool: (...args) => (handler = args.at(-1))}); const res = await handler({ paths, cycles: [0, 10, 20], limit: 10, min_growth_count: 50, monotonic_only: true, include_artifacts: false, auto_baseline: false, compact: false, }); return res.content.map(c => c.text).join('\n'); } test('leak_report records one row per class with its verdict, and its answer is unchanged', async () => { const paths = growingLadder(); const file = path.join(tmp(), 'records.jsonl'); const plain = await withRecordFile(null, () => leakReport(paths)); const recorded = await withRecordFile(file, () => leakReport(paths)); assert.equal( recorded.replace(/\d+(\.\d+)?\s?(ms|s)\b/g, ''), plain.replace(/\d+(\.\d+)?\s?(ms|s)\b/g, ''), ); const recs = readRecords(file); assert.equal(recs.length, 1); const {data, kind, tool} = recs[0]; assert.equal(tool, 'memlab_leak_report'); assert.equal(kind, 'leak_report'); assert.equal(data.rungs, 3); assert.equal(data.cycles, 20); assert.equal(data.min_growth_count, 50); const row = data.rows.find(r => r.class === 'LeakyThing'); assert.ok(row, JSON.stringify(data.rows.map(r => r.class))); assert.equal(row.net_count, 600); assert.equal(row.per_cycle, 30); assert.equal(row.verdict, 'leak_candidate'); assert.equal(row.settled, null); assert.ok(data.leak_candidates >= 1); // The path from a GC root to one of the newest LeakyThings, through the // global `kept` array, with no snapshot path in it. assert.ok(Array.isArray(row.retainer_path), JSON.stringify(row)); assert.equal(row.retainer_path.at(-1).name, 'LeakyThing'); assert.equal(row.retainer_path.at(-1).edge, undefined); assert.ok( row.retainer_path.some(hop => hop.edge === 'kept'), JSON.stringify(row.retainer_path), ); assert.ok(!JSON.stringify(data).includes('.heapsnapshot')); }); test('recordEdge keeps indices and identifiers and hashes dictionary keys', () => { assert.equal(recordEdge(3), '3'); for (const name of ['3', '424242424242']) { const key = recordEdge(name); assert.match(key, /^\(key [0-9a-f]{12}\)$/); assert.equal(recordEdge(name), key); assert.notEqual(key, name); } assert.equal(recordEdge('_listeners'), '_listeners'); assert.equal(recordEdge('$$cache'), '$$cache'); assert.equal(recordEdge('h264'), 'h264'); assert.equal(recordEdge(65_535), '65535'); for (const name of [ 65_536, 123_456_789, 15_551_234_567, 'user_8812', 'a9f3c2e17b4d8e0f1a2b3c4d5e6f7a8b', ]) { assert.match(recordEdge(name), /^\(key [0-9a-f]{12}\)$/, String(name)); } const key = recordEdge('15551234567@c.us'); assert.match(key, /^\(key [0-9a-f]{12}\)$/); assert.equal(recordEdge('15551234567@c.us'), key); assert.ok(!key.includes('15551234567')); }); test('recordPath hashes string names, and keeps both ends of a long chain', () => { const hop = (name, type, edgeName) => ({ node: {name, type}, ...(edgeName != null ? {edgeName, edgeType: 'property'} : {}), }); const short = recordPath([ hop('(GC roots)', 'synthetic', 'next'), hop('secret text', 'string'), ]); assert.equal(short.elided, 0); assert.deepEqual(short.path[0], { name: '(GC roots)', type: 'synthetic', edge: 'next', edge_type: 'property', }); assert.match(short.path[1].name, /^\(string [0-9a-f]{12}\)$/); const pageData = recordPath([ hop('(GC roots)', 'synthetic', 1), hop( 'Window / https://app.example.com/messages/t/15551234567', 'object', 're', ), hop('^chat_15551234567$', 'regexp'), ]); assert.ok( !JSON.stringify(pageData.path).includes('15551234567'), JSON.stringify(pageData.path), ); const long = recordPath( Array.from({length: 30}, (_, i) => hop(`Node${String(i)}`, 'object', i < 29 ? 'next' : undefined), ), ); assert.equal(long.path.length, 16); assert.equal(long.elided, 14); assert.equal(long.path[0].name, 'Node0'); assert.equal(long.path.at(-1).name, 'Node29'); }); test('retainer_trace records the traced path, and its answer is unchanged', async () => { const [, , last] = growingLadder(100); await callTool(registerLoadSnapshot, {file_path: last, quiet: true}); let target = null; getSnapshot().nodes.forEach(node => { if ( target == null && node.name === 'LeakyThing' && node.type === 'object' && node.hasPathEdge ) { target = node.id; } }); assert.ok(target != null); const file = path.join(tmp(), 'records.jsonl'); resetEmittedNotes(); resetSuggestionBudget(); const plain = await withRecordFile(null, () => callTool(registerRetainerTrace, {node_id: target}), ); resetEmittedNotes(); resetSuggestionBudget(); const traced = await withRecordFile(file, () => callTool(registerRetainerTrace, {node_id: target}), ); // The once-per-session snapshot header has nothing to do with recording. const headless = t => t.replace(/^> Snapshot: .*\n\n/, ''); assert.equal(headless(traced), headless(plain)); const recs = readRecords(file); assert.equal(recs.length, 1); const {kind, tool, data} = recs[0]; assert.equal(tool, 'memlab_retainer_trace'); assert.equal(kind, 'retainer_trace'); assert.equal(data.class, 'LeakyThing'); assert.equal(data.type, 'object'); assert.equal(data.path.at(-1).name, 'LeakyThing'); assert.ok(data.path.some(hop => hop.edge === 'kept')); assert.equal(typeof data.production_path, 'boolean'); }); test('retainer_trace hashes digit-string keys and preserves numeric array indices', async () => { const dir = tmp(); execFileSync(process.execPath, [ '-e', `const v8 = require('v8'); class NumericKeyThing {} class IntegerKeyThing {} class ArrayIndexThing {} globalThis.numericKeys = {'424242424242': new NumericKeyThing()}; globalThis.integerKeys = {'123456789': new IntegerKeyThing()}; globalThis.arrayIndices = []; globalThis.arrayIndices[3] = new ArrayIndexThing(); v8.writeHeapSnapshot(process.argv[1]);`, path.join(dir, 'numeric-edges.heapsnapshot'), ]); await callTool(registerLoadSnapshot, { file_path: path.join(dir, 'numeric-edges.heapsnapshot'), quiet: true, }); for (const [name, expected, edgeType] of [ ['NumericKeyThing', recordEdge('424242424242'), 'property'], ['IntegerKeyThing', recordEdge(123456789), 'element'], ['ArrayIndexThing', '3', 'element'], ]) { let target = null; getSnapshot().nodes.forEach(node => { if (node.name === name && node.type === 'object' && node.hasPathEdge) { target = node.id; } }); assert.ok(target != null, name); const file = path.join(tmp(), 'records.jsonl'); await withRecordFile(file, () => callTool(registerRetainerTrace, { node_id: target, raw: true, exclude_dev: false, }), ); const [{data}] = readRecords(file); assert.equal(data.path.at(-1).name, name); assert.equal(data.path.at(-2).edge, expected); assert.equal(data.path.at(-2).edge_type, edgeType); assert.ok(!JSON.stringify(data).includes('424242424242')); assert.ok(!JSON.stringify(data).includes('123456789')); } }); async function verifyFix(before, after) { let handler; registerVerifyFix({tool: (...args) => (handler = args.at(-1))}); const res = await handler({ metric_kind: 'class_count', locator: 'LeakyThing', before_paths: before, after_paths: after, cycles: 10, expected_reduction: 0.9, chain_edge: 'next', max_file_size_mb: 4096, }); return res.content.map(c => c.text).join('\n'); } test('verify_fix records its verdict and rates, and its answer is unchanged', async () => { const before = growingLadder(300); const after = growingLadder(0); const file = path.join(tmp(), 'records.jsonl'); const plain = await withRecordFile(null, () => verifyFix(before, after)); const recorded = await withRecordFile(file, () => verifyFix(before, after)); assert.equal(recorded, plain); const recs = readRecords(file); assert.equal(recs.length, 1); const {data, kind, tool} = recs[0]; assert.equal(tool, 'memlab_verify_fix'); assert.equal(kind, 'verify_fix'); assert.equal(data.verdict, 'FIX_CONFIRMED', plain); assert.match(plain, /FIX CONFIRMED/); assert.equal(data.metric_kind, 'class_count'); assert.equal(data.locator, 'LeakyThing'); assert.equal(data.before_rate, 30); assert.equal(data.after_rate, 0); assert.equal(data.reduction, 1); assert.equal(data.second_pair, false); }); test('verify_fix records INCONCLUSIVE when the before arm does not grow', async () => { const flat = growingLadder(0); const file = path.join(tmp(), 'records.jsonl'); await withRecordFile(file, () => verifyFix(flat, flat)); const [rec] = readRecords(file); assert.equal(rec.data.verdict, 'INCONCLUSIVE'); assert.equal(rec.data.reason, 'before_not_growing'); }); async function findingIndex(args) { let handler; registerFindingIndex({tool: (...a) => (handler = a.at(-1))}); const res = await handler({growing_classes: [], ...args}); return res.content.map(c => c.text).join('\n'); } test('finding_index check records NEW and KNOWN verdicts with fingerprints; record and import write none', async () => { const before = process.env.MEMLAB_FINDINGS_INDEX; process.env.MEMLAB_FINDINGS_INDEX = path.join(tmp(), 'findings.json'); try { const file = path.join(tmp(), 'records.jsonl'); const pathA = 'Window -> cache (property) -> LeakyThing'; await withRecordFile(file, () => findingIndex({ action: 'record', retainer_path: pathA, growing_classes: ['LeakyThing'], round: 'r1', status: 'known', }), ); assert.equal(readRecords(file).length, 0); const known = await withRecordFile(file, () => findingIndex({ action: 'check', retainer_path: pathA, growing_classes: ['LeakyThing'], }), ); const fresh = await withRecordFile(file, () => findingIndex({ action: 'check', retainer_path: 'Window -> other (property) -> Thing', growing_classes: ['Thing'], }), ); const recs = readRecords(file); assert.equal(recs.length, 2); assert.ok( recs.every( r => r.tool === 'memlab_finding_index' && r.kind === 'finding_check', ), ); const [k, n] = recs.map(r => r.data.matches[0]); assert.equal(k.verdict, 'KNOWN'); assert.deepEqual(k.classes, ['LeakyThing']); assert.ok(known.includes(k.fingerprint)); assert.equal(n.verdict, 'NEW'); assert.ok(fresh.includes(n.fingerprint)); assert.notEqual(k.fingerprint, n.fingerprint); } finally { if (before == null) { delete process.env.MEMLAB_FINDINGS_INDEX; } else { process.env.MEMLAB_FINDINGS_INDEX = before; } } }); /** One node snapshot holding 400 copies of one long string and a big array. */ function stringsSnapshot() { const file = path.join(tmp(), 'strings.heapsnapshot'); const script = ` const v8 = require('v8'); class BigHolder { constructor() { this.items = new Array(50000).fill(0).map((_, i) => ({i})); } } globalThis.holder = new BigHolder(); globalThis.copies = []; for (let i = 0; i < 400; i++) globalThis.copies.push(['private-value-', 'x'.repeat(80), String(i % 1)].join('')); v8.writeHeapSnapshot(process.argv[1]);`; execFileSync(process.execPath, ['-e', script, file]); return file; } test('duplicated_strings and largest_objects record optimization items without string contents', async () => { const snap = stringsSnapshot(); await callTool(registerLoadSnapshot, {file_path: snap, quiet: true}); const file = path.join(tmp(), 'records.jsonl'); // Notes and suggestions are rationed per session; reset so both calls see // the same session. resetEmittedNotes(); resetSuggestionBudget(); const plainDup = await withRecordFile(null, () => callTool(registerDuplicatedStrings, {limit: 5}), ); resetEmittedNotes(); resetSuggestionBudget(); const dup = await withRecordFile(file, () => callTool(registerDuplicatedStrings, {limit: 5}), ); const big = await withRecordFile(file, () => callTool(registerLargestObjects, {limit: 5}), ); // The second call is served from the first one's string scan and skips the // once-per-session snapshot header; neither has to do with recording. const uncached = t => t .replace(', which was itself already cached', '') .replace(/^> Snapshot: .*\n\n/, ''); assert.equal(uncached(dup), uncached(plainDup)); const recs = readRecords(file); assert.equal(recs.length, 2); const [d, l] = recs; assert.equal(d.tool, 'memlab_duplicated_strings'); assert.equal(d.kind, 'optimization'); assert.equal(d.data.source, 'duplicated_strings'); assert.ok(d.data.items.length > 0); assert.ok( d.data.items.some(i => i.count >= 400), JSON.stringify(d.data.items), ); assert.ok(d.data.total_bytes > 0); assert.ok(!JSON.stringify(d.data).includes('private-value')); assert.match(dup, /private-value/); assert.equal(l.tool, 'memlab_largest_objects'); assert.equal(l.data.source, 'largest_objects'); assert.ok(l.data.items.length > 0 && l.data.items.length <= 5); assert.ok( l.data.items.every(i => typeof i.bytes === 'number' && i.bytes > 0), ); assert.equal(l.data.total_bytes, null); assert.match(big, /retained size/); });