import { readFileSync } from 'node:fs'; import { chmod, mkdir, mkdtemp, readdir, readFile, realpath, rm, symlink, writeFile, } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { createNodeNotebookCommandRunner, createNodeNotebookSnapshotFs, } from '@stock-bot/research/notebook-snapshot-node'; import { exportNotebookSnapshot, NotebookSnapshotError } from '../src/notebook-snapshot'; // QA coverage for T-191 beyond the programmer's suite: kill-then-settle on the // EOUTPUTLIMIT path (including a descendant holding inherited pipes), timer // cleanup on every settlement path (a leaked timer keeps the host process // alive), stdin isolation, spawn error-code preservation, error-message // redaction on timeout/overflow, concurrent runner reuse, O_EXCL refusing to // follow a planted symlink, and exporter failure paths with real adapters that // must keep a previously published snapshot intact. No real marimo, network or // database is used: all children are `process.execPath` running temp fixtures. const ADAPTER_MODULE_PATH = resolve(import.meta.dir, '../src/notebook-snapshot-node.ts'); function getErrorCode(err: unknown): string | undefined { if (typeof err === 'object' && err !== null && 'code' in err) { const code = (err as { code?: unknown }).code; if (typeof code === 'string') { return code; } } return undefined; } async function expectReject(promise: Promise): Promise { try { await promise; } catch (err) { return err; } throw new Error('Expected promise to reject, but it resolved.'); } function probePid(pid: number): string | undefined { try { process.kill(pid, 0); return undefined; } catch (err) { return getErrorCode(err); } } function readPid(path: string): number { const pid = Number.parseInt(readFileSync(path, 'utf8').trim(), 10); if (!Number.isInteger(pid) || pid <= 0) { throw new Error(`Invalid pid in ${path}`); } return pid; } describe('notebook-snapshot-node QA', () => { let workDir = ''; beforeEach(async () => { workDir = await realpath(await mkdtemp(join(tmpdir(), 'notebook-snapshot-node-qa-'))); }); afterEach(async () => { if (workDir) { await rm(workDir, { recursive: true, force: true }); workDir = ''; } }); describe('runner: kill-then-settle on output overflow', () => { test('EOUTPUTLIMIT rejects only after the direct child is dead (ESRCH)', async () => { const pidFile = join(workDir, 'flood.pid'); const scriptPath = join(workDir, 'flood.js'); // Writes its pid, then floods stdout forever; it never exits on its own. await writeFile( scriptPath, [ "import { writeFileSync } from 'node:fs';", 'writeFileSync(process.argv[2], String(process.pid), "utf8");', 'const chunk = Buffer.alloc(4096, 0x78);', 'function pump() { while (process.stdout.write(chunk)) {} process.stdout.once("drain", pump); }', 'pump();', ].join('\n'), 'utf8' ); const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 64 * 1024 }); const err = await expectReject( runner.run(process.execPath, [scriptPath, pidFile], { timeoutMs: 20_000 }) ); // No await between settlement and the liveness probe. const probe = probePid(readPid(pidFile)); expect(getErrorCode(err)).toBe('EOUTPUTLIMIT'); expect(probe).toBe('ESRCH'); }); test('EOUTPUTLIMIT settles even when a descendant still holds inherited stdout/stderr', async () => { const childPidFile = join(workDir, 'child.pid'); const grandchildPidFile = join(workDir, 'grandchild.pid'); const grandchildScript = join(workDir, 'grandchild.js'); const parentScript = join(workDir, 'parent.js'); // Bounded lifetime (well beyond the runner timeout) so a regression cannot // leak the fixture process indefinitely. await writeFile(grandchildScript, 'setTimeout(() => process.exit(0), 30_000);\n', 'utf8'); await writeFile( parentScript, [ "import { spawn } from 'node:child_process';", "import { writeFileSync } from 'node:fs';", 'const gc = spawn(process.execPath, [process.argv[4]], { stdio: "inherit" });', 'writeFileSync(process.argv[2], String(process.pid), "utf8");', 'writeFileSync(process.argv[3], String(gc.pid), "utf8");', 'process.stderr.write("x".repeat(4096));', 'setInterval(() => {}, 10_000);', ].join('\n'), 'utf8' ); let grandchildPid: number | undefined; try { const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 1024 }); const err = await expectReject( runner.run( process.execPath, [parentScript, childPidFile, grandchildPidFile, grandchildScript], // Far below the grandchild's 30s lifetime: if the runner waited on // the inherited pipe it would report ETIMEDOUT instead. { timeoutMs: 15_000 } ) ); const childProbe = probePid(readPid(childPidFile)); grandchildPid = readPid(grandchildPidFile); const grandchildProbe = probePid(grandchildPid); expect(getErrorCode(err)).toBe('EOUTPUTLIMIT'); expect(childProbe).toBe('ESRCH'); expect(grandchildProbe).toBeUndefined(); } finally { try { grandchildPid ??= readPid(grandchildPidFile); process.kill(grandchildPid, 'SIGKILL'); } catch { // Never started or already exited. } } }); }); describe('runner: timer cleanup', () => { // A timer left armed after settlement keeps the host event loop alive. Run // the adapter inside a wrapper process with a 2-minute runner timeout; the // wrapper must exit on its own long before the outer 10s guard kills it. for (const scenario of ['success', 'nonzero', 'enoent', 'signal'] as const) { test(`clears the timeout timer after ${scenario} so the host process can exit`, async () => { const fastChild = join(workDir, 'fast-child.js'); await writeFile( fastChild, [ 'const mode = process.argv[2];', 'if (mode === "nonzero") process.exit(3);', 'if (mode === "signal") process.kill(process.pid, "SIGKILL");', 'process.stdout.write("ok");', ].join('\n'), 'utf8' ); const wrapper = join(workDir, 'wrapper.ts'); await writeFile( wrapper, [ `import { createNodeNotebookCommandRunner } from ${JSON.stringify(ADAPTER_MODULE_PATH)};`, 'const [childScript, mode, missing] = process.argv.slice(2);', 'const runner = createNodeNotebookCommandRunner();', 'const command = mode === "enoent" ? missing : process.execPath;', 'try {', ' const r = await runner.run(command, [childScript, mode], { timeoutMs: 120_000 });', ' process.stdout.write(JSON.stringify({ resolved: r.exitCode }));', '} catch (err) {', ' process.stdout.write(JSON.stringify({ rejected: err.code ?? err.message }));', '}', ].join('\n'), 'utf8' ); const outer = createNodeNotebookCommandRunner(); const result = await outer.run( process.execPath, [wrapper, fastChild, scenario, join(workDir, 'missing-binary')], { timeoutMs: 10_000 } ); expect(result.exitCode).toBe(0); const outcome = JSON.parse(result.stdout) as { resolved?: number; rejected?: string }; if (scenario === 'success') { expect(outcome).toEqual({ resolved: 0 }); } if (scenario === 'nonzero') { expect(outcome).toEqual({ resolved: 3 }); } if (scenario === 'enoent') { expect(outcome).toEqual({ rejected: 'ENOENT' }); } if (scenario === 'signal') { expect(outcome.rejected).toContain('SIGKILL'); } }, 30_000); } }); describe('runner: process isolation and error surface', () => { test('child stdin is closed (ignored), so a stdin reader sees EOF instead of hanging', async () => { const scriptPath = join(workDir, 'read-stdin.js'); await writeFile( scriptPath, [ 'let n = 0;', 'process.stdin.on("data", c => { n += c.length; });', 'process.stdin.on("end", () => process.stdout.write(String(n)));', 'process.stdin.resume();', ].join('\n'), 'utf8' ); const runner = createNodeNotebookCommandRunner(); const result = await runner.run(process.execPath, [scriptPath], { timeoutMs: 10_000 }); expect(result.exitCode).toBe(0); expect(result.stdout).toBe('0'); }); test('preserves EACCES for a non-executable file and for a directory used as command', async () => { const notExecutable = join(workDir, 'plain.txt'); await writeFile(notExecutable, 'not a program\n', 'utf8'); await chmod(notExecutable, 0o644); const runner = createNodeNotebookCommandRunner(); const fileErr = await expectReject(runner.run(notExecutable, [], { timeoutMs: 10_000 })); const dirErr = await expectReject(runner.run(workDir, [], { timeoutMs: 10_000 })); expect(getErrorCode(fileErr)).toBe('EACCES'); expect(getErrorCode(dirErr)).toBe('EACCES'); }); test('argv containing a NUL byte rejects asynchronously instead of throwing from run()', async () => { const runner = createNodeNotebookCommandRunner(); let returned: Promise | undefined; expect(() => { returned = runner.run(process.execPath, ['a\0b'], { timeoutMs: 10_000 }); }).not.toThrow(); const err = await expectReject(returned as Promise); expect(err).toBeInstanceOf(Error); }); test('ETIMEDOUT and EOUTPUTLIMIT messages name only the command basename, not path, argv or output', async () => { const secretArg = 'QA_SECRET_ARG_51f0c2'; const secretOutput = 'QA_SECRET_OUTPUT_9a7d'; const shimPath = join(workDir, 'leaky-tool'); await writeFile( shimPath, [ '#!/usr/bin/env bun', 'const mode = process.argv[2];', `process.stdout.write(${JSON.stringify(secretOutput)});`, 'if (mode === "flood") process.stdout.write("y".repeat(4096));', 'setInterval(() => {}, 10_000);', ].join('\n'), 'utf8' ); await chmod(shimPath, 0o755); const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 1024 }); const timeoutErr = await expectReject( runner.run(shimPath, ['sleep', secretArg], { timeoutMs: 800 }) ); const overflowErr = await expectReject( runner.run(shimPath, ['flood', secretArg], { timeoutMs: 15_000 }) ); expect(getErrorCode(timeoutErr)).toBe('ETIMEDOUT'); expect(getErrorCode(overflowErr)).toBe('EOUTPUTLIMIT'); for (const err of [timeoutErr, overflowErr]) { const message = (err as Error).message; expect(message).toContain('leaky-tool'); expect(message).not.toContain(workDir); expect(message).not.toContain(secretArg); expect(message).not.toContain(secretOutput); } }); test('one runner instance handles concurrent runs without mixing streams or exit codes', async () => { const scriptPath = join(workDir, 'tagged.js'); await writeFile( scriptPath, [ 'const tag = process.argv[2];', 'process.stdout.write("out-" + tag);', 'process.stderr.write("err-" + tag);', 'process.exit(Number(tag));', ].join('\n'), 'utf8' ); const runner = createNodeNotebookCommandRunner(); const tags = [0, 1, 2, 3, 4, 5, 6, 7]; const results = await Promise.all( tags.map(tag => runner.run(process.execPath, [scriptPath, String(tag)], { timeoutMs: 15_000 }) ) ); expect(results).toEqual( tags.map(tag => ({ exitCode: tag, stdout: `out-${tag}`, stderr: `err-${tag}` })) ); }); }); describe('fs: failure propagation and symlink safety', () => { test('createExclusive refuses to follow a planted (dangling) symlink and never creates its target', async () => { const fs = createNodeNotebookSnapshotFs(); const victim = join(workDir, 'victim.html'); const link = join(workDir, '.marimo-snapshot-planted.tmp.html'); await symlink(victim, link); const err = await expectReject(fs.createExclusive(link)); expect(getErrorCode(err)).toBe('EEXIST'); expect(await fs.stat(victim)).toBeNull(); }); test('remove on a symlink deletes the link only and leaves the target intact', async () => { const fs = createNodeNotebookSnapshotFs(); const target = join(workDir, 'target.html'); const link = join(workDir, 'link.html'); await writeFile(target, 'keep me', 'utf8'); await symlink(target, link); await fs.remove(link); expect(await readdir(workDir)).toEqual(['target.html']); expect(await readFile(target, 'utf8')).toBe('keep me'); }); test('missing parents/sources propagate ENOENT from createExclusive, readBytes and rename', async () => { const fs = createNodeNotebookSnapshotFs(); const missingDir = join(workDir, 'no-such-dir'); const createErr = await expectReject(fs.createExclusive(join(missingDir, 'x.tmp'))); const readErr = await expectReject(fs.readBytes(join(workDir, 'absent.bin'))); const renameErr = await expectReject( fs.rename(join(workDir, 'absent.bin'), join(workDir, 'dst.bin')) ); expect(getErrorCode(createErr)).toBe('ENOENT'); expect(getErrorCode(readErr)).toBe('ENOENT'); expect(getErrorCode(renameErr)).toBe('ENOENT'); expect(await readdir(workDir)).toEqual([]); }); test('readBytes of an empty file returns a zero-length Uint8Array', async () => { const fs = createNodeNotebookSnapshotFs(); const target = join(workDir, 'empty.html'); await writeFile(target, ''); const bytes = await fs.readBytes(target); expect(bytes).toBeInstanceOf(Uint8Array); expect(bytes.byteLength).toBe(0); }); }); describe('exporter failure paths with real adapters keep the published snapshot intact', () => { const PREVIOUS_SNAPSHOT = 'previous published snapshot\n'; async function writeShim(mode: 'export_nonzero' | 'export_empty' | 'export_flood') { const shimPath = join(workDir, `fake-marimo-${mode}`); const script = [ '#!/usr/bin/env bun', "import { writeFileSync } from 'node:fs';", 'const args = process.argv.slice(2);', `const mode = ${JSON.stringify(mode)};`, 'if (args[0] === "check") {', ' process.stdout.write(JSON.stringify({ issues: [], summary: { errored: false, total_files: 1 } }) + "\\n");', ' process.exit(0);', '}', 'const outPath = args[4];', 'if (mode === "export_nonzero") {', ' writeFileSync(outPath, "half-written", "utf8");', ' process.stderr.write("NameError in cell 3");', ' process.exit(1);', '}', 'if (mode === "export_empty") process.exit(0);', 'writeFileSync(outPath, "partial", "utf8");', 'const chunk = Buffer.alloc(4096, 0x7a);', 'function pump() { while (process.stdout.write(chunk)) {} process.stdout.once("drain", pump); }', 'pump();', ].join('\n'); await writeFile(shimPath, `${script}\n`, 'utf8'); await chmod(shimPath, 0o755); return shimPath; } async function runExport( mode: 'export_nonzero' | 'export_empty' | 'export_flood' ): Promise<{ err: unknown; outputDir: string; outputPath: string }> { const notebookDir = join(workDir, 'notebooks'); const outputDir = join(workDir, 'out'); await mkdir(notebookDir); await mkdir(outputDir); const notebookPath = join(notebookDir, 'study.py'); const outputPath = join(outputDir, 'study.html'); await writeFile(notebookPath, '# fixture\n', 'utf8'); await writeFile(outputPath, PREVIOUS_SNAPSHOT, 'utf8'); const shimPath = await writeShim(mode); const err = await expectReject( exportNotebookSnapshot({ notebookPath, outputPath, runner: createNodeNotebookCommandRunner({ maxOutputBytes: 64 * 1024 }), fs: createNodeNotebookSnapshotFs(), marimoCommand: shimPath, timeoutMs: 15_000, }) ); return { err, outputDir, outputPath }; } test('nonzero export exit → EXPORT_FAILED, half-written temp removed, previous snapshot untouched', async () => { const { err, outputDir, outputPath } = await runExport('export_nonzero'); expect(err).toBeInstanceOf(NotebookSnapshotError); expect((err as NotebookSnapshotError).code).toBe('EXPORT_FAILED'); expect(await readdir(outputDir)).toEqual(['study.html']); expect(await readFile(outputPath, 'utf8')).toBe(PREVIOUS_SNAPSHOT); }); test('export exits 0 without writing → EXPORT_EMPTY, reserved temp removed, previous snapshot untouched', async () => { const { err, outputDir, outputPath } = await runExport('export_empty'); expect(err).toBeInstanceOf(NotebookSnapshotError); expect((err as NotebookSnapshotError).code).toBe('EXPORT_EMPTY'); expect(await readdir(outputDir)).toEqual(['study.html']); expect(await readFile(outputPath, 'utf8')).toBe(PREVIOUS_SNAPSHOT); }); test('export output flood → EXPORT_FAILED via EOUTPUTLIMIT, temp removed, previous snapshot untouched', async () => { const { err, outputDir, outputPath } = await runExport('export_flood'); expect(err).toBeInstanceOf(NotebookSnapshotError); expect((err as NotebookSnapshotError).code).toBe('EXPORT_FAILED'); expect(getErrorCode((err as Error).cause)).toBe('EOUTPUTLIMIT'); expect(await readdir(outputDir)).toEqual(['study.html']); expect(await readFile(outputPath, 'utf8')).toBe(PREVIOUS_SNAPSHOT); }); }); describe('packaging', () => { test('root entrypoint does not reference the node adapter module', async () => { const indexSource = await readFile(resolve(import.meta.dir, '../src/index.ts'), 'utf8'); const pkg = JSON.parse( await readFile(resolve(import.meta.dir, '../package.json'), 'utf8') ) as { exports: Record }; expect(indexSource).not.toContain('notebook-snapshot-node'); expect(pkg.exports['./notebook-snapshot-node']).toBe('./src/notebook-snapshot-node.ts'); }); test('browser bundle of the root entrypoint contains no adapter code or child_process', () => { const entry = resolve(import.meta.dir, '../src/index.ts'); // Run Bun.build in a subprocess so Bun's in-process build/fd cache stays // isolated from other bundling tests in the full workspace suite. const child = Bun.spawnSync( [ process.execPath, '--no-env-file', '-e', ` const result = await Bun.build({ entrypoints: [${JSON.stringify(entry)}], target: 'browser', }); if (!result.success) { console.error(result.logs); process.exit(1); } const code = (await Promise.all(result.outputs.map(o => o.text()))).join('\\n'); for (const forbidden of [ 'createNodeNotebookCommandRunner', 'createNodeNotebookSnapshotFs', 'child_process', ]) { if (code.includes(forbidden)) { console.error('Found forbidden symbol in browser bundle:', forbidden); process.exit(2); } } `, ], { env: { PATH: process.env.PATH } } ); expect(new TextDecoder().decode(child.stderr)).toBe(''); expect(child.exitCode).toBe(0); }); }); });