/** * 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 session-record upload trigger (`MEMLAB_RECORD_UPLOAD_CMD`): * debounce, one run at a time, retry with backoff, and the final attempt on * shutdown. The command is a stub that appends a line to a file. * * npm run build-pkg && node scripts/check-record-upload.mjs * * Runs against the BUILT dist/. */ import './test-isolation.mjs'; import assert from 'assert/strict'; import {spawn} from 'child_process'; import fs from 'fs'; import {after, beforeEach, 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, 'record-upload.js'))) { console.error( 'check-record-upload: dist/record-upload.js is missing; build first.', ); process.exit(1); } const load = rel => import(pathToFileURL(path.join(dist, rel)).href); const {noteRecord} = await load('session-record.js'); const {recordUploadLine, recordUploadState, resetRecordUploadForTests} = await load('record-upload.js'); const ENV = [ 'MEMLAB_RECORD_FILE', 'MEMLAB_RECORD_UPLOAD_CMD', 'MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS', 'MEMLAB_RECORD_UPLOAD_BACKOFF_MS', 'MEMLAB_RECORD_UPLOAD_TIMEOUT_MS', 'MEMLAB_RECORDS_DIR', 'MEMLAB_UPLOAD_RUNS', 'PATH', ]; const saved = Object.fromEntries(ENV.map(k => [k, process.env[k]])); const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'memlab-record-upload-')); const calls = path.join(tmp, 'calls'); const quote = s => `'${s.replace(/'/g, "'\\''")}'`; const sleep = ms => new Promise(r => setTimeout(r, ms)); const lines = () => fs.existsSync(calls) ? fs.readFileSync(calls, 'utf8').split('\n').filter(Boolean) : []; async function waitFor(pred, ms = 3000) { const end = Date.now() + ms; while (Date.now() < end) { if (pred()) { return true; } // eslint-disable-next-line no-await-in-loop await sleep(10); } return pred(); } beforeEach(() => { resetRecordUploadForTests(); for (const k of ENV) { if (k !== 'PATH') delete process.env[k]; } process.env.PATH = saved.PATH; fs.rmSync(calls, {force: true}); process.env.MEMLAB_RECORD_FILE = path.join(tmp, 'records.jsonl'); process.env.MEMLAB_RECORD_UPLOAD_CMD = `echo x >> ${quote(calls)}`; process.env.MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS = '30'; }); after(() => { resetRecordUploadForTests(); for (const k of ENV) { if (saved[k] == null) { delete process.env[k]; } else { process.env[k] = saved[k]; } } fs.rmSync(tmp, {recursive: true, force: true}); }); test('two reports inside the debounce window run the command once', async () => { noteRecord('memlab_leak_report', 'leak_report', {}); noteRecord('memlab_round_audit', 'round_audit', {}); assert.equal(lines().length, 0, 'debounced, not run at once'); assert.ok(await waitFor(() => lines().length === 1)); await sleep(150); assert.equal(lines().length, 1); assert.ok(await waitFor(() => recordUploadState().last != null)); assert.match(recordUploadLine(), /^1 run\(s\), last \d+ s ago \(exit 0\)$/); }); test('tool_call records alone run nothing, and with no command and no uploader on the PATH nothing runs', async () => { noteRecord('memlab_eval', 'tool_call', {}); delete process.env.MEMLAB_RECORD_UPLOAD_CMD; process.env.PATH = path.join(tmp, 'empty-bin'); noteRecord('memlab_leak_report', 'leak_report', {}); assert.equal(recordUploadState(), null); await sleep(150); assert.equal(lines().length, 0); }); test('MEMLAB_UPLOAD_RUNS=0 no longer turns uploads off', async () => { process.env.MEMLAB_UPLOAD_RUNS = '0'; noteRecord('memlab_leak_report', 'leak_report', {}); assert.ok(await waitFor(() => lines().length === 1)); }); test('with no command, a meta on the PATH uploads the records directory', async () => { const bin = path.join(tmp, 'bin'); fs.mkdirSync(bin, {recursive: true}); const fake = path.join(bin, 'meta'); fs.writeFileSync(fake, `#!/bin/sh\necho "$*" >> ${quote(calls)}\n`); fs.chmodSync(fake, 0o755); delete process.env.MEMLAB_RECORD_UPLOAD_CMD; process.env.PATH = `${bin}${path.delimiter}/bin${path.delimiter}/usr/bin`; process.env.MEMLAB_RECORDS_DIR = path.join(tmp, "it's records"); noteRecord('memlab_leak_report', 'leak_report', {}); assert.ok(await waitFor(() => lines().length === 1)); assert.equal( lines()[0], `memlab.run upload --dir=${path.join(tmp, "it's records")} -o json`, ); assert.match(recordUploadState().command, /^meta memlab\.run upload --dir=/); }); test('a `meta` that is a directory or a Node script is not taken for the uploader', async () => { delete process.env.MEMLAB_RECORD_UPLOAD_CMD; const dirBin = path.join(tmp, 'dir-bin'); fs.mkdirSync(path.join(dirBin, 'meta'), {recursive: true}); const nodeBin = path.join(tmp, 'node-bin'); fs.mkdirSync(nodeBin, {recursive: true}); const npmMeta = path.join(nodeBin, 'meta'); fs.writeFileSync(npmMeta, `#!/usr/bin/env node\nrequire('fs');\n`); fs.chmodSync(npmMeta, 0o755); const shimBin = path.join(tmp, 'shim-bin'); fs.mkdirSync(shimBin, {recursive: true}); const shim = path.join(shimBin, 'meta'); fs.writeFileSync( shim, [ '#!/bin/sh', `basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")`, 'if [ -x "$basedir/node" ]; then', ' exec "$basedir/node" "$basedir/../meta/bin/meta" "$@"', 'else', ' exec node "$basedir/../meta/bin/meta" "$@"', 'fi', '', ].join('\n'), ); fs.chmodSync(shim, 0o755); for (const bin of [dirBin, nodeBin, shimBin]) { resetRecordUploadForTests(); process.env.PATH = `${bin}${path.delimiter}/bin${path.delimiter}/usr/bin`; assert.equal(recordUploadState(), null, bin); } // A directory named `meta` is skipped, as `sh` skips it, for the next one. const realBin = path.join(tmp, 'real-bin'); fs.mkdirSync(realBin, {recursive: true}); const fake = path.join(realBin, 'meta'); fs.writeFileSync(fake, '#!/bin/sh\nexit 0\n'); fs.chmodSync(fake, 0o755); resetRecordUploadForTests(); process.env.PATH = [dirBin, realBin, '/bin', '/usr/bin'].join(path.delimiter); assert.match(recordUploadState().command, /^meta memlab\.run upload --dir=/); }); test('a failing command is retried after each backoff delay, then left alone', async () => { process.env.MEMLAB_RECORD_UPLOAD_CMD = `echo f >> ${quote(calls)}; exit 3`; process.env.MEMLAB_RECORD_UPLOAD_BACKOFF_MS = '20,40'; noteRecord('memlab_leak_report', 'leak_report', {}); assert.ok(await waitFor(() => lines().length === 1)); assert.ok(await waitFor(() => recordUploadState().next_at != null)); assert.match(recordUploadLine(), /\(exit 3\); retry 1 in \d+ s/); assert.ok(await waitFor(() => recordUploadState().gave_up)); await sleep(150); assert.equal(lines().length, 3, '1 run + 2 retries'); assert.match(recordUploadLine(), /^3 run\(s\).*gave up after the last retry/); process.env.MEMLAB_RECORD_UPLOAD_CMD = `echo x >> ${quote(calls)}`; noteRecord('memlab_leak_report', 'leak_report', {}); assert.ok(await waitFor(() => lines().length === 4)); assert.ok(await waitFor(() => recordUploadState().last?.exit === 0)); assert.doesNotMatch(recordUploadLine(), /gave up/); }); test('a report written while a run is in flight gets its own run afterwards', async () => { process.env.MEMLAB_RECORD_UPLOAD_CMD = `sleep 0.2; echo x >> ${quote(calls)}`; noteRecord('memlab_leak_report', 'leak_report', {}); assert.ok(await waitFor(() => recordUploadState().running)); noteRecord('memlab_round_audit', 'round_audit', {}); assert.ok(await waitFor(() => lines().length === 2)); assert.equal(recordUploadState().runs, 2); }); test('a run past its time limit is stopped and counts as failed, so later reports upload', async () => { process.env.MEMLAB_RECORD_UPLOAD_CMD = `echo start >> ${quote(calls)}; sleep 5; echo end >> ${quote(calls)}`; process.env.MEMLAB_RECORD_UPLOAD_TIMEOUT_MS = '200'; process.env.MEMLAB_RECORD_UPLOAD_BACKOFF_MS = '600000'; noteRecord('memlab_leak_report', 'leak_report', {}); assert.ok( await waitFor(() => /timed out/.test(recordUploadState().last?.error ?? ''), ), ); assert.equal(recordUploadState().running, false); assert.match(recordUploadLine(), /failed: timed out after 0 s/); await sleep(300); assert.deepEqual(lines(), ['start'], 'the hung run was killed'); process.env.MEMLAB_RECORD_UPLOAD_CMD = `echo x >> ${quote(calls)}`; noteRecord('memlab_leak_report', 'leak_report', {}); assert.ok(await waitFor(() => lines().length === 2)); assert.ok(await waitFor(() => recordUploadState().last?.exit === 0)); }); test('a timed-out run that ignores SIGTERM stays in flight until its group is killed', async () => { resetRecordUploadForTests({killGraceMs: 1500}); process.env.MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS = '30'; process.env.MEMLAB_RECORD_UPLOAD_CMD = `trap '' TERM; echo start >> ${quote(calls)}; sleep 5; echo end >> ${quote(calls)}`; process.env.MEMLAB_RECORD_UPLOAD_TIMEOUT_MS = '200'; process.env.MEMLAB_RECORD_UPLOAD_BACKOFF_MS = '600000'; noteRecord('memlab_leak_report', 'leak_report', {}); assert.ok(await waitFor(() => lines().length === 1)); await sleep(700); assert.equal(recordUploadState().running, true, 'released before the kill'); process.env.MEMLAB_RECORD_UPLOAD_CMD = `echo again >> ${quote(calls)}`; noteRecord('memlab_leak_report', 'leak_report', {}); await sleep(100); assert.deepEqual(lines(), ['start'], 'a second run started beside it'); assert.ok(await waitFor(() => lines().length === 2, 3000), lines().join()); assert.deepEqual(lines(), ['start', 'again']); await sleep(200); assert.ok(!lines().includes('end'), 'the hung run was not killed'); }); test('a steady stream of reports still runs within 5 debounce windows', async () => { const end = Date.now() + 300; while (Date.now() < end && lines().length === 0) { noteRecord('memlab_leak_report', 'leak_report', {}); // eslint-disable-next-line no-await-in-loop await sleep(15); } assert.ok(lines().length >= 1, 'no run while reports kept arriving'); }); test('the final attempt waits for the run in flight, not beside it', async () => { const script = ` const {noteRecord} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'session-record.js')).href)}); const {recordUploadState} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'record-upload.js')).href)}); noteRecord('memlab_leak_report', 'leak_report', {}); while (!recordUploadState().running) await new Promise(r => setTimeout(r, 5)); noteRecord('memlab_round_audit', 'round_audit', {}); `; const proc = spawn(process.execPath, ['--input-type=module', '-e', script], { env: { ...process.env, MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS: '0', MEMLAB_RECORD_UPLOAD_CMD: `echo start >> ${quote(calls)}; sleep 0.3; echo end >> ${quote(calls)}`, }, stdio: ['pipe', 'ignore', 'inherit'], }); await new Promise(resolve => proc.on('exit', resolve)); assert.ok(await waitFor(() => lines().length === 4, 5000), lines().join()); assert.deepEqual(lines(), ['start', 'end', 'start', 'end']); }); test('a run in flight at shutdown gets one more run after it, so a late failure is not stranded', async () => { const script = ` const {noteRecord} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'session-record.js')).href)}); const {recordUploadState} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'record-upload.js')).href)}); noteRecord('memlab_leak_report', 'leak_report', {}); while (!recordUploadState().running) await new Promise(r => setTimeout(r, 5)); `; const proc = spawn(process.execPath, ['--input-type=module', '-e', script], { env: { ...process.env, MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS: '0', MEMLAB_RECORD_UPLOAD_CMD: `echo start >> ${quote(calls)}; sleep 0.3; echo end >> ${quote(calls)}; exit 1`, }, stdio: ['pipe', 'ignore', 'inherit'], }); await new Promise(resolve => proc.on('exit', resolve)); assert.ok(await waitFor(() => lines().length === 4, 5000), lines().join()); assert.deepEqual(lines(), ['start', 'end', 'start', 'end']); }); test('the final attempt stops a hung run at its time limit instead of waiting forever', async () => { const hung = path.join(tmp, 'hung-once'); const script = ` const {noteRecord} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'session-record.js')).href)}); const {recordUploadState} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'record-upload.js')).href)}); noteRecord('memlab_leak_report', 'leak_report', {}); while (!recordUploadState().running) await new Promise(r => setTimeout(r, 5)); `; const proc = spawn(process.execPath, ['--input-type=module', '-e', script], { env: { ...process.env, MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS: '0', MEMLAB_RECORD_UPLOAD_TIMEOUT_MS: '1000', // Only the first run hangs, so nothing writes after this test. MEMLAB_RECORD_UPLOAD_CMD: `if [ -e ${quote(hung)} ]; then echo again >> ${quote(calls)}; else touch ${quote(hung)}; echo start >> ${quote(calls)}; sleep 4; echo end >> ${quote(calls)}; fi`, }, stdio: ['pipe', 'ignore', 'inherit'], }); await new Promise(resolve => proc.on('exit', resolve)); assert.ok(await waitFor(() => lines().length === 2, 3500), lines().join()); assert.deepEqual(lines(), ['start', 'again']); await sleep(3500); assert.deepEqual(lines(), ['start', 'again'], 'the hung run was stopped'); }); test('the final attempt kills a hung run that ignores SIGTERM before it uploads', async () => { const hung = path.join(tmp, 'hung-term-once'); const script = ` const {noteRecord} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'session-record.js')).href)}); const {recordUploadState, resetRecordUploadForTests} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'record-upload.js')).href)}); resetRecordUploadForTests({killGraceMs: 2000}); noteRecord('memlab_leak_report', 'leak_report', {}); while (!recordUploadState().running) await new Promise(r => setTimeout(r, 5)); `; const proc = spawn(process.execPath, ['--input-type=module', '-e', script], { env: { ...process.env, MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS: '0', MEMLAB_RECORD_UPLOAD_TIMEOUT_MS: '1000', MEMLAB_RECORD_UPLOAD_CMD: `if [ -e ${quote(hung)} ]; then echo again >> ${quote(calls)}; else touch ${quote(hung)}; trap '' TERM; echo start >> ${quote(calls)}; sleep 6; echo end >> ${quote(calls)}; fi`, }, stdio: ['pipe', 'ignore', 'inherit'], }); await new Promise(resolve => proc.on('exit', resolve)); await sleep(1800); assert.deepEqual(lines(), ['start'], 'the final upload ran beside the run'); assert.ok(await waitFor(() => lines().length === 2, 4000), lines().join()); assert.deepEqual(lines(), ['start', 'again']); await sleep(3500); assert.deepEqual(lines(), ['start', 'again'], 'the hung run was not killed'); }); test('a final attempt whose spawn fails asynchronously does not crash the exit', async () => { const script = ` const {noteRecord} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'session-record.js')).href)}); noteRecord('memlab_leak_report', 'leak_report', {}); `; const proc = spawn(process.execPath, ['--input-type=module', '-e', script], { env: { ...process.env, MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS: '600000', PATH: path.join(tmp, 'no-such-dir'), }, stdio: ['pipe', 'ignore', 'pipe'], }); let stderr = ''; proc.stderr.on('data', d => (stderr += d)); const code = await new Promise(resolve => proc.on('exit', resolve)); assert.equal(code, 0, stderr); }); /** A server process that writes one report and is then stopped. */ function child(stop) { const script = ` const {noteRecord} = await import(${JSON.stringify(pathToFileURL(path.join(dist, 'session-record.js')).href)}); noteRecord('memlab_leak_report', 'leak_report', {}); ${stop} `; const proc = spawn(process.execPath, ['--input-type=module', '-e', script], { env: {...process.env, MEMLAB_RECORD_UPLOAD_DEBOUNCE_MS: '600000'}, stdio: ['pipe', 'ignore', 'inherit'], }); return new Promise(resolve => proc.on('exit', (code, signal) => resolve({code, signal})), ); } test('shutdown sends the owed upload once: SIGTERM keeps its default exit, and an empty event loop', async () => { const term = await child( `process.kill(process.pid, 'SIGTERM'); setTimeout(() => {}, 5000);`, ); assert.equal(term.signal, 'SIGTERM'); assert.ok( await waitFor(() => lines().length === 1), 'final attempt after SIGTERM', ); const idle = await child(''); assert.equal(idle.code, 0); assert.ok( await waitFor(() => lines().length === 2), 'final attempt at beforeExit', ); await sleep(150); assert.equal(lines().length, 2, 'one final attempt each'); }); test('nothing owed at shutdown, nothing sent', async () => { delete process.env.MEMLAB_RECORD_UPLOAD_CMD; const idle = await child(''); assert.equal(idle.code, 0); await sleep(150); assert.equal(lines().length, 0); });