/** * 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 `composeQueries` (tools/eval.ts): `memlab_eval({queries})`. * * 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 os from 'os'; import path from 'path'; import vm from 'vm'; import {test} from 'node:test'; import {fileURLToPath, pathToFileURL} from 'url'; const here = path.dirname(fileURLToPath(import.meta.url)); const built = path.join(here, '..', 'dist', 'tools', 'eval.js'); if (!fs.existsSync(built)) { console.error( 'check-eval-queries: dist/tools/eval.js is missing; build first.', ); process.exit(1); } const { arrayMethodMisuse, composeQueries, protoKeyTrap, jsonSafeResult, describeThrown, implausibleByteFields, SANDBOX_JSON, savedIds, shrinkResult, } = await import(pathToFileURL(built).href); const {setSavedResult} = await import( pathToFileURL(path.join(here, '..', 'dist', 'heap-state.js')).href ); const {spillResult} = await import( pathToFileURL(path.join(here, '..', 'dist', 'result-spill.js')).href ); const run = queries => { const ctx = {result: undefined}; vm.runInNewContext(composeQueries(queries), ctx); // A plain copy: the sandbox realm has its own Object prototype. return JSON.parse(JSON.stringify(ctx.result)); }; test('each query answers by `result =` or `return`, keyed by name', () => { assert.deepEqual( run([ {name: 'a', code: 'result = 1 + 1;'}, {name: 'b', code: 'return [1, 2, 3].length;'}, {name: 'c', code: 'const x = 5; result = x * 2;'}, ]), {a: 2, b: 3, c: 10}, ); }); test('a throwing query reports its error and the rest still run', () => { const out = run([ {name: 'bad', code: 'null.x;'}, {name: 'good', code: 'return "ok";'}, ]); assert.match(out.bad.error, /Cannot read properties of null/); assert.equal(out.good, 'ok'); }); test("queries do not see each other's locals", () => { const out = run([ {name: 'a', code: 'const shared = 1; return shared;'}, {name: 'b', code: 'return typeof shared;'}, ]); assert.deepEqual(out, {a: 1, b: 'undefined'}); }); test("lint: an object helper's own field is not array misuse", () => { assert.deepEqual( arrayMethodMisuse("result = helpers.walkChain(id, 'next').length;"), [], ); assert.equal( arrayMethodMisuse("result = helpers.walkChain(id, 'next').map(f);").length, 1, ); assert.equal( arrayMethodMisuse('result = helpers.pathAll(id).length;').length, 1, ); }); test('lint: a plain {} keyed by heap names is flagged, a literal key is not', () => { assert.equal( protoKeyTrap( 'const by = {}; snapshot.nodes.forEach(n => { (by[n.name] ??= []).push(n.id); });', ).length, 1, ); assert.deepEqual(protoKeyTrap("const by = {}; by['a'] = 1; by[0] = 2;"), []); assert.deepEqual( protoKeyTrap('const by = Object.create(null); by[k] = 1;'), [], ); assert.equal(protoKeyTrap('let $c = {}; $c[k] = 1;').length, 1); assert.deepEqual( protoKeyTrap('const counts = {}; counts.a = 1; m.counts[k] = 2;'), [], ); assert.equal(protoKeyTrap('const by = {}; by[`${n.name}`] = 1;').length, 1); assert.equal(protoKeyTrap("const by = {}; by['x' + k] = 1;").length, 1); assert.deepEqual(protoKeyTrap('const by = {}; by[`x`] = 1;'), []); assert.equal(protoKeyTrap('const a = {}, b = {}; b[k] = 1;').length, 1); assert.equal( protoKeyTrap('const by = {}; for (const n of ns) out.push(...by[n.name]);') .length, 1, ); assert.deepEqual(protoKeyTrap('const by = {}; x = m?.by[k];'), []); }); test('a query that does not parse gets {error}; the others still answer', () => { const out = run([ {name: 'a', code: 'return 1;'}, {name: 'b', code: 'return 1 +;'}, {name: 'c', code: 'result = 3;'}, ]); assert.equal(out.a, 1); assert.match(out.b.error, /SyntaxError/); assert.equal(out.c, 3); }); test('duplicate or __proto__ query names are refused', () => { const q = name => ({name, code: 'return 1;'}); assert.throws(() => composeQueries([q('x'), q('x')]), /unique/); assert.throws(() => composeQueries([q('__proto__')]), /unique/); }); test('a max_nodes abort stops the batch and keeps the partial answers', () => { const ctx = { result: undefined, boom() { const e = new Error('max_nodes budget of 10 exhausted'); e.name = 'BudgetExceeded'; throw e; }, }; const code = composeQueries([ {name: 'a', code: 'return 1;'}, {name: 'b', code: 'result = 5; boom(); result = 6;'}, {name: 'c', code: 'return 3;'}, ]); assert.throws(() => vm.runInNewContext(code, ctx), /max_nodes/); assert.deepEqual(JSON.parse(JSON.stringify(ctx.result)), {a: 1, b: 5}); }); test('an abort in the first query with nothing assigned leaves no result', () => { const ctx = { result: undefined, boom() { const e = new Error('exhausted'); e.name = 'BudgetExceeded'; throw e; }, }; const code = composeQueries([{name: 'a', code: 'boom(); result = 1;'}]); assert.throws(() => vm.runInNewContext(code, ctx)); assert.equal(ctx.result, undefined); }); test('a timeout in a later query keeps the answers already made', () => { const ctx = {result: undefined}; const code = composeQueries([ {name: 'a', code: 'return 1;'}, {name: 'b', code: 'for (;;) {}'}, ]); assert.throws(() => vm.runInNewContext(code, ctx, {timeout: 200})); assert.deepEqual(JSON.parse(JSON.stringify(ctx.result)), {a: 1}); }); /** The shape of memlab's HeapLocation: getters over the whole snapshot. */ class FakeHeapLocation { constructor() { this.heapSnapshot = {big: 1n, nodes: new Uint32Array(8)}; this.idx = 0; } get script_id() { return 7; } get line() { return 12; } get column() { return 3; } } test('a heap location serializes as script_id/line/column, never the snapshot', () => { const loc = new FakeHeapLocation(); assert.throws(() => JSON.stringify(loc), /BigInt/); assert.deepEqual(jsonSafeResult({loc}), { loc: {script_id: 7, line: 12, column: 3}, }); assert.equal( SANDBOX_JSON.stringify({loc}), '{"loc":{"script_id":7,"line":12,"column":3}}', ); }); test('the sandbox JSON turns a BigInt into its string under any replacer', () => { assert.equal(SANDBOX_JSON.stringify({a: 1n}), '{"a":"1"}'); assert.equal(SANDBOX_JSON.stringify({a: 1n, b: 2}, ['a']), '{"a":"1"}'); assert.equal( SANDBOX_JSON.stringify([1n, {c: 2n}], null, 1), '[\n "1",\n {\n "c": "2"\n }\n]', ); assert.equal(SANDBOX_JSON.parse('{"x":1}').x, 1); }); test('the implausible-total check never walks into a heap node', () => { // A node's fields lead into the parsed snapshot: its id maps and typed // arrays. Walking them hung the server on a real rung, and on a small one // flagged the snapshot's own store size as a byte total. const heapSnapshot = { _nodeId2NodeIdx: {fastStoreSize: 5e9}, nodes: new Float64Array(4).fill(5e9), }; const node = {id: 1, type: 'closure', self_size: 32, references: []}; Object.defineProperty(node, 'heapSnapshot', { value: heapSnapshot, enumerable: true, }); const result = {nodes: [node], totalBytes: 10}; assert.deepEqual(implausibleByteFields(result, 1e6), []); assert.deepEqual(implausibleByteFields(jsonSafeResult(result), 1e6), []); // A real over-the-heap total is still flagged. assert.deepEqual(implausibleByteFields({totalBytes: 2e6}, 1e6), [ {path: 'totalBytes', bytes: 2e6}, ]); }); test("a value's toJSON output is walked too", () => { assert.deepEqual(jsonSafeResult({x: {toJSON: () => ({b: 1n})}}), { x: {b: '1'}, }); const d = new Date(0); assert.deepEqual(jsonSafeResult({d}), {d: d.toJSON()}); }); test('a toJSON that returns a fresh object with toJSON is called once', () => { const spread = { a: 1, toJSON() { return {...this, extra: 2}; }, }; assert.deepEqual( JSON.parse(JSON.stringify(jsonSafeResult(spread))), JSON.parse(JSON.stringify(spread)), ); class X { toJSON() { return new X(); } } assert.deepEqual(jsonSafeResult({x: new X()}), {x: {}}); // A nested value's own toJSON still runs. assert.deepEqual( jsonSafeResult({toJSON: () => ({inner: {toJSON: () => 7}})}), {inner: 7}, ); }); test('a toJSON nesting a fresh instance of its class ends instead of overflowing', () => { class Nest { toJSON() { return {inner: new Nest()}; } } let out = jsonSafeResult(new Nest()); let depth = 0; while (out != null && typeof out === 'object') { out = out.inner; depth++; } assert.equal(out, '[Too deep]'); assert.ok(depth > 100, `stopped after ${depth} levels`); class Fan { toJSON() { return {a: new Fan(), b: new Fan()}; } } const started = Date.now(); assert.equal(typeof jsonSafeResult(new Fan()), 'object'); assert.ok(Date.now() - started < 30_000); }); test('getters that each return a fresh object end instead of branching forever', () => { const mk = () => ({ get a() { return mk(); }, get b() { return mk(); }, }); const started = Date.now(); const out = JSON.stringify(jsonSafeResult(mk())); assert.ok(out.includes('[Too many objects]')); assert.ok(Date.now() - started < 30_000); }); test('a thrown value with no string conversion is still described', () => { assert.equal(describeThrown(new Error('boom')), 'boom'); assert.equal(describeThrown(Object.create(null)), '[object Object]'); assert.equal(describeThrown(7), '7'); const hostile = { [Symbol.toPrimitive]() { throw 1; }, get [Symbol.toStringTag]() { throw 2; }, }; assert.equal(describeThrown(hostile), '[unprintable thrown object]'); const trap = () => { throw 3; }; const proxy = new Proxy({}, {getPrototypeOf: trap, get: trap}); assert.equal(describeThrown(proxy), '[unprintable thrown object]'); }); test('summarize: an over-budget array keeps its count, top rows and leading rows', () => { const rows = Array.from({length: 20000}, (_, i) => ({ name: `c${i}`, retainedSize: (i * 7919) % 10007, })); const out = shrinkResult(rows, 8192, {summarize: true}); assert.equal(out.truncated, true); assert.equal(out.summary.count, 20000); assert.equal(out.summary.topBy, 'retainedSize'); assert.equal(out.value.__count, 20000); assert.equal(out.value.__top.length, 10); assert.equal(out.value.__top[0].retainedSize, 10006); assert.ok(out.value.__sample.length > 5); assert.deepEqual(out.value.__sample[0], rows[0]); assert.ok(Buffer.byteLength(JSON.stringify(out.value, null, 2)) <= 8192); // Without `summarize`, the leading entries as before. const plain = shrinkResult(rows, 8192); assert.ok(Array.isArray(plain.value)); assert.equal(plain.summary, undefined); }); test('summarize: a result under budget compact but over it printed is summarized', () => { const rows = Array.from({length: 300}, (_, i) => ({a: i, b: {c: i}})); assert.ok(Buffer.byteLength(JSON.stringify(rows)) <= 8192); assert.ok(Buffer.byteLength(JSON.stringify(rows, null, 2)) > 8192); const out = shrinkResult(rows, 8192, {summarize: true}); assert.equal(out.truncated, true); assert.equal(out.summary.count, 300); assert.ok(Buffer.byteLength(JSON.stringify(out.value, null, 2)) <= 8192); // Without `summarize`, the compact size decides, as before. assert.equal(shrinkResult(rows, 8192).truncated, false); }); test('summarize: a very long result is summarized to the same budget', () => { const rows = Array.from({length: 1_000_000}, (_, i) => ({ name: `c${i}`, retainedSize: i % 9973, })); const out = shrinkResult(rows, 8192, {summarize: true}); assert.equal(out.summary.count, 1_000_000); assert.ok(out.value.__sample.length > 5); assert.ok(Buffer.byteLength(JSON.stringify(out.value, null, 2)) <= 8192); }); test('summarize: a census map ranks by value; sorted leading rows need no top', () => { const census = Object.fromEntries( Array.from({length: 5000}, (_, i) => [`Class${i}`, i]), ); const out = shrinkResult(census, 4096, {summarize: true}); assert.equal(out.value.__top_by, 'value'); assert.deepEqual(Object.keys(out.value.__top).slice(0, 2), [ 'Class4999', 'Class4998', ]); const sorted = Array.from({length: 5000}, (_, i) => ({count: 5000 - i})); const s = shrinkResult(sorted, 4096, {summarize: true}); assert.equal(s.value.__top, undefined); assert.equal(s.value.__sample[0].count, 5000); }); test('summarize: a census keyed by integers keeps its top largest-first', () => { const census = Object.fromEntries( Array.from({length: 5000}, (_, i) => [String(i), (i * 7919) % 5003]), ); const out = shrinkResult(census, 4096, {summarize: true}); assert.equal(out.value.__top_by, 'value'); const values = out.value.__top.map(([, v]) => v); assert.deepEqual( values, [...values].sort((a, b) => b - a), ); assert.equal(values[0], Math.max(...Object.values(census))); }); test('summarize: NaN is left out of the top and Infinity ranks first', () => { const census = Object.fromEntries( Array.from({length: 5000}, (_, i) => [ `Class${i}`, i % 3 === 0 ? NaN : (i * 7919) % 5003, ]), ); census.Class1 = Infinity; const out = shrinkResult(census, 4096, {summarize: true}); assert.equal(out.value.__top_by, 'value'); const values = Object.values(out.value.__top); assert.equal(values[0], Infinity); assert.ok( values.every(v => !Number.isNaN(v)), String(values), ); const rest = values.slice(1); assert.deepEqual( rest, [...rest].sort((a, b) => b - a), ); const finite = Object.values(census).filter(Number.isFinite); assert.equal(rest[0], Math.max(...finite)); }); test('summarize: deep entries are cut at depth 2', () => { const deep = Array.from({length: 50}, () => ({ a: {b: {c: {d: 'x'.repeat(500)}}}, })); const out = shrinkResult(deep, 2048, {summarize: true}); assert.deepEqual(out.value.__sample[0], {a: {b: '[object with 1 keys]'}}); }); test('summarize: a clipped nested list or object says how much it left out', () => { const rows = Array.from({length: 40}, (_, i) => ({ i, ids: Array.from({length: 150}, (_, j) => j), m: Object.fromEntries(Array.from({length: 25}, (_, j) => [`k${j}`, j])), })); const out = shrinkResult(rows, 4096, {summarize: true}); const [first] = out.value.__sample; assert.equal(first.ids.length, 21); assert.equal(first.ids[20], '… 130 more'); assert.equal(first.m['…'], '5 more keys'); }); test('spillResult writes the whole value under MEMLAB_STATE_DIR/results', () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'memlab-spill-')); const prev = process.env.MEMLAB_STATE_DIR; process.env.MEMLAB_STATE_DIR = dir; try { const value = Array.from({length: 20000}, (_, i) => i); const res = spillResult('eval', value); assert.ok(res.path.startsWith(path.join(dir, 'results')), res.path); assert.match(path.basename(res.path), /-eval-[0-9a-f]{8}\.json$/); assert.deepEqual(JSON.parse(fs.readFileSync(res.path, 'utf8')), value); assert.equal(res.bytes, fs.statSync(res.path).size); // Heap-derived text: this user only. assert.equal(fs.statSync(res.path).mode & 0o777, 0o600); assert.equal(fs.statSync(path.dirname(res.path)).mode & 0o777, 0o700); } finally { if (prev == null) delete process.env.MEMLAB_STATE_DIR; else process.env.MEMLAB_STATE_DIR = prev; fs.rmSync(dir, {recursive: true, force: true}); } }); test('savedIds: ids or {id} rows saved on this snapshot; anything else says why', () => { setSavedResult('mixedIds', [1, {id: 2, name: 'x'}, 'skip', 3.5], 'h1'); assert.deepEqual(savedIds('mixedIds', 'h1'), {ids: [1, 2]}); assert.match(savedIds('mixedIds', 'h2').error, /saved against snapshot "h1"/); assert.match(savedIds('nope', 'h1').error, /No saved result named "nope"/); setSavedResult('counts', {a: 1}, 'h1'); assert.match(savedIds('counts', 'h1').error, /not a list of node ids/); setSavedResult('words', ['a', 'b'], 'h1'); assert.match(savedIds('words', 'h1').error, /holds no node ids/); setSavedResult('idSet', new Set([7, 8]), 'h1'); assert.deepEqual(savedIds('idSet', 'h1'), {ids: [7, 8]}); });