/** * 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 the "Applicable tools not run this session" line * (steering.ts) and its use at the end of `memlab_round_digest` and * `memlab_leak_report`: the applicable calls whose tool the session's call * log does not have, at most three, in compact mode too. * * npm run build-pkg && npm run test-units * * Runs against the BUILT dist/. */ import './test-isolation.mjs'; import assert from 'assert/strict'; import fs from 'fs'; import {after, test} from 'node:test'; import os from 'os'; import path from 'path'; import v8 from 'v8'; 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, 'steering.js'))) { console.error('check-steering: dist/steering.js is missing; build first.'); process.exit(1); } const load = rel => import(pathToFileURL(path.join(dist, rel)).href); const {z} = await import('zod'); const {notRunThisSession, steeringFromRoutes, steeringLine} = await load('steering.js'); const {routesFor} = await load('specialist-routes.js'); const {calledTools, recordCall} = await load('perf-stats.js'); const {terseText} = await load('terse-output.js'); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'steering-')); after(() => fs.rmSync(tmp, {recursive: true, force: true})); async function toolFrom(file, register, name) { const mod = await load(file); let shape = null; let handler = null; mod[register]({ tool: (...a) => { if (a[0] === name) { shape = a.find((x, i) => i > 0 && x != null && typeof x === 'object'); handler = a.at(-1); } }, }); return async args => { const res = await handler(z.object(shape).parse(args), {}); return res.content.map(c => c.text).join('\n'); }; } const ctx = {runDir: '/r/r1', paths: ['/r/a', '/r/b']}; test('one item per route, keyed by its main tool, with the growth', () => { const items = steeringFromRoutes( routesFor( [ {name: 'V8EventListener', type: 'native', perCycle: 62}, {name: 'Detached HTMLDivElement', type: 'native', netCount: 40}, {name: 'DOMTimer', type: 'native'}, {name: 'NoSuchFamily', type: 'object'}, ], ctx, ), ); assert.deepEqual( items.map(i => i.tool), ['memlab_duplicate_subscriptions', 'memlab_detached_dom', 'memlab_timers'], ); assert.equal(items[0].why, 'dom listeners: V8EventListener +62/cycle'); assert.match(items[0].text, /^`memlab_duplicate_subscriptions\(\{paths: /); // A route that loads a snapshot first keeps the whole chain. assert.match( items[2].text, /`memlab_load_snapshot\(.*\)` → `memlab_timers\(\{\}\)`/, ); }); test('called tools drop out; at most three; null when nothing is left', () => { const item = (tool, why = tool) => ({tool, text: `\`${tool}()\``, why}); const items = ['a', 'b', 'c', 'd', 'b'].map(t => item(`memlab_${t}`)); assert.deepEqual( notRunThisSession(items, new Set(['memlab_a'])).map(i => i.tool), ['memlab_b', 'memlab_c', 'memlab_d'], ); assert.equal( steeringLine(notRunThisSession([item('memlab_x', 'why x')], new Set())), '**Applicable tools not run this session:** `memlab_x()` (why x).', ); assert.equal(steeringLine([]), null); // A terse session drops it with the other next-step blocks. const line = steeringLine([item('memlab_x')]); assert.equal( terseText(`## Report\n\n| a |\n|---|\n| 1 |\n\n${line}`).includes(line), false, ); recordCall('memlab_steering_probe', 1); assert.ok(calledTools().has('memlab_steering_probe')); assert.equal(notRunThisSession([item('memlab_steering_probe')]).length, 0); }); function makeRound(name, leakRows) { const dir = path.join(tmp, name); fs.mkdirSync(path.join(dir, 'analysis'), {recursive: true}); fs.writeFileSync( path.join(dir, 'run.json'), JSON.stringify({ run_id: name, rungs: [0, 50].map((c, i) => ({ index: i, path: path.join(dir, `rung_0${i}_c${c}.heapsnapshot`), cycles: c, post_gc_heap_mb: 200 + i, })), totals: {cycles: 50, ok: 50, fail: 0}, caveats: ['A caveat.'], }), ); if (leakRows != null) { fs.writeFileSync( path.join(dir, 'analysis', 'memlab_leak_report.txt'), [ '| Class | Type | Δ count | Verdict hint |', '|---|---|--:|---|', ...leakRows, '', ].join('\n'), ); } return dir; } test('round_digest ends with the line, in full and compact form', async () => { const digest = await toolFrom( 'tools/round-digest.js', 'registerRoundDigest', 'memlab_round_digest', ); const dir = makeRound('r1', [ '| EventListener | native | +620 | ↑ every step — LEAK candidate |', '| Promise | object | +300 | ↑ every step — LEAK candidate |', ]); const full = await digest({run_dir: dir}); const last = full.trimEnd().split('\n').at(-1); assert.match(last, /^\*\*Applicable tools not run this session:\*\* /); assert.match(last, /memlab_duplicate_subscriptions/); assert.match(last, /memlab_pending_promises\(\{run_dir: /); assert.match(last, /memlab_growth_atlas\(\{run_dir: /); assert.doesNotMatch(last, /memlab_leak_report/); const compact = await digest({run_dir: dir, compact: true}); assert.equal(compact.trimEnd().split('\n').at(-1), last); // Once run, a tool is no longer named. recordCall('memlab_pending_promises', 1); recordCall('memlab_duplicate_subscriptions', 1); const after = await digest({run_dir: dir, compact: false}); const tail = after.trimEnd().split('\n').at(-1); assert.doesNotMatch(tail, /pending_promises|duplicate_subscriptions/); assert.match(tail, /memlab_growth_atlas/); // No leak report on disk: the report itself is named. const bare = await digest({run_dir: makeRound('r2', null)}); assert.match( bare.trimEnd().split('\n').at(-1), /memlab_leak_report\(\{run_dir: /, ); }); test('leak_report ends with the line, not in JSON', async () => { const report = await toolFrom( 'tools/leak-report.js', 'registerLeakReport', 'memlab_leak_report', ); globalThis.__steeringGrowth = []; const paths = [0, 1, 2].map(i => { for (let k = 0; k < 2000; k++) globalThis.__steeringGrowth.push(new Map()); return v8.writeHeapSnapshot(path.join(tmp, `st_${i}.heapsnapshot`)); }); const text = await report({paths, compact: false}); assert.match( text.trimEnd().split('\n').at(-1), /^\*\*Applicable tools not run this session:\*\* `memlab_collection_diff\(\{paths: /, ); const compact = await report({paths, compact: true}); assert.match(compact, /\*\*Applicable tools not run this session:\*\*/); const json = await report({paths, format: 'json'}); assert.doesNotMatch(json, /Applicable tools not run/); // With a run_dir: growth_atlas is named until the round has one on disk. const run = path.join(tmp, 'r-atlas'); fs.mkdirSync(path.join(run, 'analysis'), {recursive: true}); fs.writeFileSync( path.join(run, 'run.json'), JSON.stringify({ rungs: paths.map((p, i) => ({index: i, path: p, cycles: i * 10})), totals: {cycles: 20}, }), ); const steer = t => t.trimEnd().split('\n').at(-1); assert.match(steer(await report({run_dir: run})), /memlab_growth_atlas/); fs.writeFileSync(path.join(run, 'analysis', 'growth_atlas.md'), '# atlas\n'); assert.doesNotMatch( await report({run_dir: run, compact: false}), /memlab_growth_atlas\(/, ); });