T-191: M2.1u — Real Node/Bun adapters for the notebook snapshot exporter: createNodeNotebookCommandRunner() + createNodeNotebookSnapshotFs() in libs/research/src/notebook-snapshot-node.ts (argv-only node:child_process.spawn, kill-then-settle ETIMEDOUT, O_EXCL create, real-subprocess + temp-dir tests with a fake marimo script; no new deps, no real marimo, no bin)

This commit is contained in:
Studio 2026-12-03 00:15:54 -05:00
commit b51ce9b22b
5 changed files with 1513 additions and 0 deletions

View file

@ -345,6 +345,28 @@ Exported from `@stock-bot/research` (`libs/research/src/notebook-snapshot.ts`).
- **Fail-closed error codes (`NotebookSnapshotError`)** — `INVALID_OPTION`, `INVALID_PATH`, `NOTEBOOK_NOT_FOUND`, `CHECK_FAILED` (nonzero check exit, `summary.errored === true`, `type: 'error'`, or `severity: 'breaking'`), `CHECK_OUTPUT_INVALID` (non-JSON stdout on exit `0` or malformed `{ issues, summary }` / `summary.total_files !== 1`), `EXPORT_FAILED`, `EXPORT_EMPTY`, and `TIMEOUT`. Formatting and runtime advisories may accompany a clean check.
- **Lexical roots & execution notice:** `allowedNotebookRoot` and `allowedOutputRoot` enforce lexical POSIX path-component containment (blocking `..` traversal and same-prefix sibling escapes); callers must supply trusted directories and keep the notebook file stable between check and export. Note that `marimo export html` **executes notebook cells**.
### Node/Bun Adapters (`@stock-bot/research/notebook-snapshot-node`)
Server-only adapters backed by `node:child_process` and `node:fs/promises` are exported exclusively from the `@stock-bot/research/notebook-snapshot-node` subpath (`libs/research/src/notebook-snapshot-node.ts`) so the default `@stock-bot/research` entrypoint remains browser-bundleable:
- **`createNodeNotebookCommandRunner(options?)`** — Implements `NotebookCommandRunner` via `spawn(command, [...args], { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'] })`. Captures stdout and stderr independently up to `NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES` (`16 MiB` by default, configurable via `options.maxOutputBytes`), kills with `SIGKILL` on timeout (`ETIMEDOUT`) or overflow (`EOUTPUTLIMIT`), and settles only after `close`.
- **`createNodeNotebookSnapshotFs()`** — Implements `NotebookSnapshotFs` over `node:fs/promises` (`stat` mapping only `ENOENT` to `null`, `open(..., 'wx')` exclusive create, binary `readFile`, atomic `rename`, and non-recursive `rm(..., { force: true })`).
```ts
import { exportNotebookSnapshot } from '@stock-bot/research';
import {
createNodeNotebookCommandRunner,
createNodeNotebookSnapshotFs,
} from '@stock-bot/research/notebook-snapshot-node';
const receipt = await exportNotebookSnapshot({
notebookPath: '/abs/path/to/study.py',
outputPath: '/abs/path/to/study.html',
runner: createNodeNotebookCommandRunner(),
fs: createNodeNotebookSnapshotFs(),
});
```
### Manual Host Smoke Check (Director / Host Only)
Automated tests use fakes and never spawn `marimo`. On a host with the pinned `python/` `uv` environment (`marimo 0.26.0`):

View file

@ -17,6 +17,7 @@
"./market-data-store-questdb": "./src/market-data-store-questdb.ts",
"./market-data-store-routed": "./src/market-data-store-routed.ts",
"./mcp": "./src/mcp/index.ts",
"./notebook-snapshot-node": "./src/notebook-snapshot-node.ts",
"./results": "./src/results.ts",
"./signal-panel": "./src/signal-panel.ts",
"./signal-study": "./src/signal-study.ts",

View file

@ -0,0 +1,293 @@
/**
* Node/Bun subprocess and filesystem adapters for {@link exportNotebookSnapshot}.
*
* Intentionally exposed only via the `@stock-bot/research/notebook-snapshot-node`
* subpath (never re-exported from `@stock-bot/research`) so the root package
* stays browser-bundleable.
*/
import { spawn } from 'node:child_process';
import { rename as fsRename, stat as fsStat, open, readFile, rm } from 'node:fs/promises';
import { basename } from 'node:path';
import type {
NotebookCommandResult,
NotebookCommandRunner,
NotebookCommandRunOptions,
NotebookSnapshotFileStat,
NotebookSnapshotFs,
} from './notebook-snapshot';
/** Default per-stream (stdout / stderr) capture cap in bytes (16 MiB). */
export const NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
/** Maximum single-call delay supported by Node/Bun `setTimeout` (2^31 - 1 ms). */
const MAX_TIMER_DELAY_MS = 2_147_483_647;
export interface NodeNotebookCommandRunnerOptions {
/** Maximum captured bytes per stream (stdout and stderr independently). */
readonly maxOutputBytes?: number;
}
interface CodedError extends Error {
code: string;
}
function createCodedError(code: string, message: string): CodedError {
const err = new Error(message) as CodedError;
err.code = code;
return err;
}
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;
}
function assertPositiveSafeInteger(value: unknown, label: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
throw new RangeError(`${label} must be a positive finite integer.`);
}
return value;
}
/**
* Creates a real {@link NotebookCommandRunner} backed by `node:child_process.spawn`.
*
* - Always invokes `command` directly with `args` as argv (`shell: false`).
* - Resolves any numeric exit code on `close`; rejects on spawn errors, signal
* termination, timeout (`ETIMEDOUT`), or per-stream output overflow (`EOUTPUTLIMIT`).
* - On timeout or output overflow, sends `SIGKILL` once and rejects only after
* the child's `close` event has fired.
*/
export function createNodeNotebookCommandRunner(
runnerOptions?: NodeNotebookCommandRunnerOptions
): NotebookCommandRunner {
const maxOutputBytes =
runnerOptions?.maxOutputBytes === undefined
? NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES
: assertPositiveSafeInteger(runnerOptions.maxOutputBytes, 'maxOutputBytes');
return {
run(
command: string,
args: readonly string[],
options: NotebookCommandRunOptions
): Promise<NotebookCommandResult> {
let timeoutMs: number;
try {
timeoutMs = assertPositiveSafeInteger(options.timeoutMs, 'timeoutMs');
} catch (err) {
return Promise.reject(err);
}
const commandName = basename(command) || command;
return new Promise<NotebookCommandResult>((resolve, reject) => {
let settled = false;
let terminalFailure: CodedError | null = null;
let killSent = false;
let timeoutHandle: ReturnType<typeof setTimeout> | undefined;
const stdoutChunks: Buffer[] = [];
let stdoutBytes = 0;
const stderrChunks: Buffer[] = [];
let stderrBytes = 0;
const clearTimeoutHandle = (): void => {
if (timeoutHandle !== undefined) {
clearTimeout(timeoutHandle);
timeoutHandle = undefined;
}
};
let child: ReturnType<typeof spawn>;
try {
child = spawn(command, [...args], {
...(options.cwd !== undefined ? { cwd: options.cwd } : {}),
shell: false,
stdio: ['ignore', 'pipe', 'pipe'],
});
} catch (err) {
settled = true;
reject(err);
return;
}
const triggerTerminalFailure = (err: CodedError): void => {
if (settled || terminalFailure !== null) {
return;
}
terminalFailure = err;
clearTimeoutHandle();
stdoutChunks.length = 0;
stderrChunks.length = 0;
if (!killSent) {
killSent = true;
try {
child.kill('SIGKILL');
} catch {
// Child may have already exited before kill was delivered.
}
}
// Tear down our read ends of stdout/stderr so a descendant that
// inherited either pipe cannot prevent `child`'s `close` event from
// firing once the direct child exits.
child.stdout?.destroy();
child.stderr?.destroy();
};
const attachStreamCollector = (
stream: NodeJS.ReadableStream | null,
streamName: 'stdout' | 'stderr',
chunks: Buffer[],
getBytes: () => number,
setBytes: (next: number) => void
): void => {
if (!stream) {
return;
}
stream.on('error', () => {
// Drain/ignore pipe errors once the child is terminating.
});
stream.on('data', (chunk: Buffer | string) => {
if (terminalFailure !== null || settled) {
// Keep draining so a killed/exiting child never blocks on a full pipe.
return;
}
const buf = typeof chunk === 'string' ? Buffer.from(chunk, 'utf8') : chunk;
const nextBytes = getBytes() + buf.byteLength;
if (nextBytes > maxOutputBytes) {
triggerTerminalFailure(
createCodedError(
'EOUTPUTLIMIT',
`Command '${commandName}' exceeded ${streamName} output limit of ${maxOutputBytes} bytes.`
)
);
return;
}
setBytes(nextBytes);
chunks.push(buf);
});
};
attachStreamCollector(
child.stdout,
'stdout',
stdoutChunks,
() => stdoutBytes,
next => {
stdoutBytes = next;
}
);
attachStreamCollector(
child.stderr,
'stderr',
stderrChunks,
() => stderrBytes,
next => {
stderrBytes = next;
}
);
const deadlineMs = performance.now() + timeoutMs;
const scheduleTimeout = (): void => {
if (settled || terminalFailure !== null) {
return;
}
const remainingMs = deadlineMs - performance.now();
if (remainingMs <= 0) {
triggerTerminalFailure(
createCodedError(
'ETIMEDOUT',
`Command '${commandName}' timed out after ${timeoutMs}ms.`
)
);
return;
}
const delayMs = Math.min(Math.ceil(remainingMs), MAX_TIMER_DELAY_MS);
timeoutHandle = setTimeout(scheduleTimeout, delayMs);
};
scheduleTimeout();
child.once('error', err => {
clearTimeoutHandle();
if (settled) {
return;
}
settled = true;
reject(err);
});
child.once('close', (code, signal) => {
clearTimeoutHandle();
if (settled) {
return;
}
settled = true;
if (terminalFailure !== null) {
reject(terminalFailure);
return;
}
if (code === null) {
reject(
new Error(
signal
? `Command '${commandName}' terminated by signal ${signal}.`
: `Command '${commandName}' terminated without an exit code.`
)
);
return;
}
const stdout = Buffer.concat(stdoutChunks, stdoutBytes).toString('utf8');
const stderr = Buffer.concat(stderrChunks, stderrBytes).toString('utf8');
resolve({ exitCode: code, stdout, stderr });
});
});
},
};
}
/**
* Creates a real {@link NotebookSnapshotFs} backed by `node:fs/promises`.
*/
export function createNodeNotebookSnapshotFs(): NotebookSnapshotFs {
return {
async stat(path: string): Promise<NotebookSnapshotFileStat | null> {
try {
const info = await fsStat(path);
return { isFile: info.isFile(), size: info.size };
} catch (err) {
if (getErrorCode(err) === 'ENOENT') {
return null;
}
throw err;
}
},
async createExclusive(path: string): Promise<void> {
const handle = await open(path, 'wx');
await handle.close();
},
async readBytes(path: string): Promise<Uint8Array> {
const data = await readFile(path);
return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
},
async rename(sourcePath: string, destinationPath: string): Promise<void> {
await fsRename(sourcePath, destinationPath);
},
async remove(path: string): Promise<void> {
await rm(path, { force: true });
},
};
}

View file

@ -0,0 +1,521 @@
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<unknown>): Promise<unknown> {
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<unknown> | undefined;
expect(() => {
returned = runner.run(process.execPath, ['a\0b'], { timeoutMs: 10_000 });
}).not.toThrow();
const err = await expectReject(returned as Promise<unknown>);
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 = '<html>previous published snapshot</html>\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, "<html>half-written", "utf8");',
' process.stderr.write("NameError in cell 3");',
' process.exit(1);',
'}',
'if (mode === "export_empty") process.exit(0);',
'writeFileSync(outPath, "<html>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<string, string> };
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);
});
});
});

View file

@ -0,0 +1,676 @@
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import {
chmod,
mkdir,
mkdtemp,
readdir,
readFile,
realpath,
rm,
writeFile,
} from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, test } from 'bun:test';
import {
createNodeNotebookCommandRunner,
createNodeNotebookSnapshotFs,
NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES,
} from '@stock-bot/research/notebook-snapshot-node';
import { exportNotebookSnapshot, NotebookSnapshotError } from '../src/notebook-snapshot';
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<unknown>): Promise<unknown> {
try {
await promise;
} catch (err) {
return err;
}
throw new Error('Expected promise to reject, but it resolved.');
}
describe('notebook-snapshot-node adapters', () => {
let workDir = '';
beforeEach(async () => {
const rawDir = await mkdtemp(join(tmpdir(), 'notebook-snapshot-node-'));
workDir = await realpath(rawDir);
});
afterEach(async () => {
if (workDir) {
await rm(workDir, { recursive: true, force: true });
workDir = '';
}
});
describe('createNodeNotebookCommandRunner', () => {
test('passes argv verbatim without shell interpretation (spaces, quotes, $(...), ;, *)', async () => {
const scriptPath = join(workDir, 'echo-argv.js');
await writeFile(
scriptPath,
'process.stdout.write(JSON.stringify(process.argv.slice(2)));\n',
'utf8'
);
const runner = createNodeNotebookCommandRunner();
const args = [
scriptPath,
'hello world',
`"double" and 'single' quotes`,
'$(echo pwned)',
'a;b',
'*.ts',
];
const result = await runner.run(process.execPath, args, { timeoutMs: 10_000 });
expect(result.exitCode).toBe(0);
expect(result.stderr).toBe('');
expect(JSON.parse(result.stdout)).toEqual(args.slice(1));
});
test('honours cwd, separates stdout/stderr with split multi-byte UTF-8, and resolves non-zero exit codes', async () => {
const subDir = join(workDir, 'child-cwd');
await mkdir(subDir);
const scriptPath = join(workDir, 'streams-and-exit.js');
await writeFile(
scriptPath,
[
// Split a 3-byte UTF-8 character ('€' = E2 82 AC) and a 4-byte emoji ('🚀' = F0 9F 9A 80) across writes.
'process.stdout.write(Buffer.from([0x63, 0x77, 0x64, 0x3d]));',
'process.stdout.write(process.cwd() + "\\n");',
'process.stdout.write(Buffer.from([0xe2, 0x82]));',
'process.stdout.write(Buffer.from([0xac, 0x0a]));',
'process.stderr.write(Buffer.from([0xf0, 0x9f]));',
'process.stderr.write(Buffer.from([0x9a, 0x80]));',
'process.exit(42);',
].join('\n'),
'utf8'
);
const runner = createNodeNotebookCommandRunner();
const result = await runner.run(process.execPath, [scriptPath], {
cwd: subDir,
timeoutMs: 10_000,
});
expect(result.exitCode).toBe(42);
expect(result.stdout).toBe(`cwd=${subDir}\n€\n`);
expect(result.stderr).toBe('🚀');
});
test('rejects with ENOENT when executable does not exist', async () => {
const runner = createNodeNotebookCommandRunner();
const missingPath = join(workDir, 'does-not-exist-binary');
const err = await expectReject(runner.run(missingPath, ['--version'], { timeoutMs: 10_000 }));
expect(err).toBeInstanceOf(Error);
expect(getErrorCode(err)).toBe('ENOENT');
});
test('rejects signal exit with only command basename (no full path, argv, or env values)', async () => {
const secretArg = 'SECRET_ARG_TOKEN_987654';
const shimPath = join(workDir, 'signal-self.js');
await writeFile(
shimPath,
[
'#!/usr/bin/env bun',
"process.kill(process.pid, 'SIGKILL');",
'setInterval(() => {}, 10_000);',
].join('\n'),
'utf8'
);
await chmod(shimPath, 0o755);
const runner = createNodeNotebookCommandRunner();
const err = await expectReject(runner.run(shimPath, [secretArg], { timeoutMs: 10_000 }));
expect(err).toBeInstanceOf(Error);
const message = (err as Error).message;
expect(message).toContain('signal-self.js');
expect(message).toContain('SIGKILL');
expect(message).not.toContain(workDir);
expect(message).not.toContain(secretArg);
expect(message).not.toContain(process.env.PATH ?? '__no_path__');
});
test('kills timed-out child with SIGKILL and rejects ETIMEDOUT only after child is dead (ESRCH)', async () => {
const pidFile = join(workDir, 'sleeper.pid');
const scriptPath = join(workDir, 'sleep-forever.js');
await writeFile(
scriptPath,
[
"import { writeFileSync } from 'node:fs';",
'writeFileSync(process.argv[2], String(process.pid), "utf8");',
'setInterval(() => {}, 10_000);',
].join('\n'),
'utf8'
);
const runner = createNodeNotebookCommandRunner();
const err = await expectReject(
runner.run(process.execPath, [scriptPath, pidFile], { timeoutMs: 800 })
);
// Read the PID synchronously with no intervening await so the liveness
// probe checks the process state immediately upon settlement.
const pidText = readFileSync(pidFile, 'utf8');
const pid = Number.parseInt(pidText.trim(), 10);
let probeError: unknown;
try {
process.kill(pid, 0);
} catch (killErr) {
probeError = killErr;
}
expect(err).toBeInstanceOf(Error);
expect(getErrorCode(err)).toBe('ETIMEDOUT');
expect(Number.isInteger(pid) && pid > 0).toBe(true);
expect(getErrorCode(probeError)).toBe('ESRCH');
});
test('settles ETIMEDOUT after direct child dies even when a descendant inherits stdout/stderr', async () => {
const childPidFile = join(workDir, 'parent.pid');
const grandchildPidFile = join(workDir, 'grandchild.pid');
const grandchildScript = join(workDir, 'grandchild-sleeper.js');
const parentScript = join(workDir, 'spawn-grandchild.js');
// Bounded lifetime well beyond the runner's 800ms deadline 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 grandchild = spawn(process.execPath, [process.argv[4]], { stdio: "inherit" });',
'writeFileSync(process.argv[2], String(process.pid), "utf8");',
'writeFileSync(process.argv[3], String(grandchild.pid), "utf8");',
'setInterval(() => {}, 10_000);',
].join('\n'),
'utf8'
);
let grandchildPid: number | undefined;
try {
const runner = createNodeNotebookCommandRunner();
const err = await expectReject(
runner.run(
process.execPath,
[parentScript, childPidFile, grandchildPidFile, grandchildScript],
{ timeoutMs: 800 }
)
);
const childPid = Number.parseInt(readFileSync(childPidFile, 'utf8').trim(), 10);
grandchildPid = Number.parseInt(readFileSync(grandchildPidFile, 'utf8').trim(), 10);
let childProbeError: unknown;
try {
process.kill(childPid, 0);
} catch (killErr) {
childProbeError = killErr;
}
// Grandchild still holds the inherited stdout/stderr pipes open while alive.
let grandchildAlive = true;
try {
process.kill(grandchildPid, 0);
} catch {
grandchildAlive = false;
}
expect(err).toBeInstanceOf(Error);
expect(getErrorCode(err)).toBe('ETIMEDOUT');
expect(Number.isInteger(childPid) && childPid > 0).toBe(true);
expect(Number.isInteger(grandchildPid) && grandchildPid > 0).toBe(true);
expect(getErrorCode(childProbeError)).toBe('ESRCH');
expect(grandchildAlive).toBe(true);
} finally {
if (grandchildPid === undefined) {
try {
grandchildPid = Number.parseInt(readFileSync(grandchildPidFile, 'utf8').trim(), 10);
} catch {
// Grandchild never wrote its PID file.
}
}
if (grandchildPid !== undefined && Number.isInteger(grandchildPid) && grandchildPid > 0) {
try {
process.kill(grandchildPid, 'SIGKILL');
} catch {
// Already exited.
}
}
}
});
test('handles timeoutMs beyond 32-bit setTimeout limit without firing immediately', async () => {
const scriptPath = join(workDir, 'fast-ok.js');
await writeFile(scriptPath, 'process.stdout.write("ok");\n', 'utf8');
const runner = createNodeNotebookCommandRunner();
const result = await runner.run(process.execPath, [scriptPath], {
timeoutMs: 3_000_000_000,
});
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('ok');
expect(result.stderr).toBe('');
});
test('enforces NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES independently on stdout and stderr', async () => {
const scriptPath = join(workDir, 'emit-bytes.js');
await writeFile(
scriptPath,
[
'const streamName = process.argv[2];',
'const totalBytes = Number.parseInt(process.argv[3], 10);',
'const chunkSize = 65536;',
'const chunk = Buffer.alloc(chunkSize, 0x61);',
'const target = streamName === "stderr" ? process.stderr : process.stdout;',
'let remaining = totalBytes;',
'function pump() {',
' while (remaining > 0) {',
' const size = Math.min(remaining, chunkSize);',
' remaining -= size;',
' const ok = target.write(size === chunkSize ? chunk : chunk.subarray(0, size));',
' if (!ok) {',
' target.once("drain", pump);',
' return;',
' }',
' }',
'}',
'pump();',
].join('\n'),
'utf8'
);
const runner = createNodeNotebookCommandRunner();
// Exact cap on stdout succeeds.
const stdoutExact = await runner.run(
process.execPath,
[scriptPath, 'stdout', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES)],
{ timeoutMs: 30_000 }
);
expect(stdoutExact.exitCode).toBe(0);
expect(stdoutExact.stdout.length).toBe(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES);
expect(stdoutExact.stderr).toBe('');
// One byte over cap on stdout rejects with EOUTPUTLIMIT.
const stdoutOverflow = await expectReject(
runner.run(
process.execPath,
[scriptPath, 'stdout', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES + 1)],
{ timeoutMs: 30_000 }
)
);
expect(getErrorCode(stdoutOverflow)).toBe('EOUTPUTLIMIT');
// Exact cap on stderr succeeds.
const stderrExact = await runner.run(
process.execPath,
[scriptPath, 'stderr', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES)],
{ timeoutMs: 30_000 }
);
expect(stderrExact.exitCode).toBe(0);
expect(stderrExact.stdout).toBe('');
expect(stderrExact.stderr.length).toBe(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES);
// One byte over cap on stderr rejects with EOUTPUTLIMIT.
const stderrOverflow = await expectReject(
runner.run(
process.execPath,
[scriptPath, 'stderr', String(NODE_NOTEBOOK_RUNNER_MAX_OUTPUT_BYTES + 1)],
{ timeoutMs: 30_000 }
)
);
expect(getErrorCode(stderrOverflow)).toBe('EOUTPUTLIMIT');
});
test('supports custom per-stream maxOutputBytes without sharing cap across streams', async () => {
const scriptPath = join(workDir, 'both-streams.js');
await writeFile(
scriptPath,
[
'const n = Number.parseInt(process.argv[2], 10);',
'process.stdout.write("a".repeat(n));',
'process.stderr.write("b".repeat(n));',
].join('\n'),
'utf8'
);
const runner = createNodeNotebookCommandRunner({ maxOutputBytes: 128 });
const exactBoth = await runner.run(process.execPath, [scriptPath, '128'], {
timeoutMs: 10_000,
});
expect(exactBoth.exitCode).toBe(0);
expect(exactBoth.stdout.length).toBe(128);
expect(exactBoth.stderr.length).toBe(128);
const overCap = await expectReject(
runner.run(process.execPath, [scriptPath, '129'], { timeoutMs: 10_000 })
);
expect(getErrorCode(overCap)).toBe('EOUTPUTLIMIT');
});
test('rejects invalid timeoutMs with RangeError before spawning and invalid maxOutputBytes on construction', async () => {
const runner = createNodeNotebookCommandRunner();
const invalidTimeouts = [
0,
-1,
Number.NaN,
Number.POSITIVE_INFINITY,
Number.NEGATIVE_INFINITY,
1.5,
];
for (const timeoutMs of invalidTimeouts) {
const err = await expectReject(
runner.run(join(workDir, 'never-spawned'), [], { timeoutMs })
);
expect(err).toBeInstanceOf(RangeError);
}
expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: 0 })).toThrow(RangeError);
expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: -5 })).toThrow(RangeError);
expect(() => createNodeNotebookCommandRunner({ maxOutputBytes: 1.5 })).toThrow(RangeError);
});
});
describe('createNodeNotebookSnapshotFs', () => {
test('stat returns null for missing, { isFile, size } for file/dir, and propagates ENOTDIR', async () => {
const fs = createNodeNotebookSnapshotFs();
const missingPath = join(workDir, 'missing.txt');
const filePath = join(workDir, 'sample.bin');
const dirPath = join(workDir, 'nested-dir');
await writeFile(filePath, new Uint8Array([1, 2, 3, 4, 5]));
await mkdir(dirPath);
expect(await fs.stat(missingPath)).toBeNull();
expect(await fs.stat(filePath)).toEqual({ isFile: true, size: 5 });
const dirStat = await fs.stat(dirPath);
expect(dirStat).not.toBeNull();
expect(dirStat?.isFile).toBe(false);
const enotdirErr = await expectReject(fs.stat(join(filePath, 'child')));
expect(getErrorCode(enotdirErr)).toBe('ENOTDIR');
});
test('createExclusive creates an empty file and rejects EEXIST on collision', async () => {
const fs = createNodeNotebookSnapshotFs();
const target = join(workDir, 'exclusive.tmp');
await fs.createExclusive(target);
expect(await fs.stat(target)).toEqual({ isFile: true, size: 0 });
const err = await expectReject(fs.createExclusive(target));
expect(getErrorCode(err)).toBe('EEXIST');
});
test('readBytes round-trips arbitrary binary bytes including 0x00 and 0xff', async () => {
const fs = createNodeNotebookSnapshotFs();
const target = join(workDir, 'binary.dat');
const payload = new Uint8Array([0x00, 0x01, 0x7f, 0x80, 0xfe, 0xff, 0x00, 0x42]);
await writeFile(target, payload);
const actual = await fs.readBytes(target);
expect(actual).toBeInstanceOf(Uint8Array);
expect(Array.from(actual)).toEqual(Array.from(payload));
});
test('rename atomically replaces an existing destination file', async () => {
const fs = createNodeNotebookSnapshotFs();
const src = join(workDir, 'new.html');
const dst = join(workDir, 'published.html');
await writeFile(dst, 'old content', 'utf8');
await writeFile(src, 'new content', 'utf8');
await fs.rename(src, dst);
expect(await fs.stat(src)).toBeNull();
expect(await readFile(dst, 'utf8')).toBe('new content');
});
test('remove is a no-op when absent and rejects non-recursively on a non-empty directory', async () => {
const fs = createNodeNotebookSnapshotFs();
await fs.remove(join(workDir, 'absent.tmp'));
const regularFile = join(workDir, 'deletable.tmp');
await writeFile(regularFile, 'bye', 'utf8');
await fs.remove(regularFile);
expect(await fs.stat(regularFile)).toBeNull();
const nonEmptyDir = join(workDir, 'keep-dir');
const innerFile = join(nonEmptyDir, 'inside.txt');
await mkdir(nonEmptyDir);
await writeFile(innerFile, 'precious', 'utf8');
const err = await expectReject(fs.remove(nonEmptyDir));
expect(err).toBeInstanceOf(Error);
expect(await readFile(innerFile, 'utf8')).toBe('precious');
});
});
describe('end-to-end exportNotebookSnapshot with real adapters and fake marimo shim', () => {
async function writeFakeMarimoShim(
name: string,
mode: 'clean' | 'check_error' | 'hang_export',
logPath: string,
extra?: { readonly htmlContent?: string; readonly pidPath?: string }
): Promise<string> {
const shimPath = join(workDir, name);
const htmlContent = extra?.htmlContent ?? '<!doctype html><html><body>OK</body></html>\n';
const pidPath = extra?.pidPath ?? '';
const script = [
'#!/usr/bin/env bun',
"import { appendFileSync, writeFileSync } from 'node:fs';",
'const args = process.argv.slice(2);',
`const mode = ${JSON.stringify(mode)};`,
`const logPath = ${JSON.stringify(logPath)};`,
`const htmlContent = ${JSON.stringify(htmlContent)};`,
`const pidPath = ${JSON.stringify(pidPath)};`,
'appendFileSync(logPath, JSON.stringify({ args, pid: process.pid }) + "\\n", "utf8");',
'if (args[0] === "check") {',
' if (args[1] !== "--format=json" || args.length !== 3) {',
' process.stderr.write("unexpected check argv: " + JSON.stringify(args));',
' process.exit(2);',
' }',
' if (mode === "check_error") {',
' process.stdout.write(JSON.stringify({',
' issues: [{ type: "error", severity: "breaking", message: "undefined name" }],',
' summary: { errored: true, total_files: 1 },',
' }));',
' process.exit(0);',
' }',
' process.stdout.write(JSON.stringify({',
' issues: [],',
' summary: { errored: false, total_files: 1 },',
' }));',
' process.exit(0);',
'}',
'if (args[0] === "export" && args[1] === "html") {',
' if (args.length !== 6 || args[3] !== "-o" || args[5] !== "--force") {',
' process.stderr.write("unexpected export argv: " + JSON.stringify(args));',
' process.exit(2);',
' }',
' const outPath = args[4];',
' if (mode === "hang_export") {',
' writeFileSync(outPath, "<html>partial", "utf8");',
' if (pidPath) writeFileSync(pidPath, String(process.pid), "utf8");',
' setInterval(() => {}, 10_000);',
' } else {',
' writeFileSync(outPath, htmlContent, "utf8");',
' process.exit(0);',
' }',
'} else {',
' process.stderr.write("unknown command: " + JSON.stringify(args));',
' process.exit(2);',
'}',
].join('\n');
await writeFile(shimPath, `${script}\n`, 'utf8');
await chmod(shimPath, 0o755);
return shimPath;
}
test('clean check publishes HTML whose bytes and sha256 match the receipt with no leftover temp files', async () => {
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');
const logPath = join(workDir, 'clean.log.jsonl');
const expectedHtml = '<!doctype html><html><body><h1>CA Shorts Study €</h1></body></html>\n';
const expectedBytes = Buffer.from(expectedHtml, 'utf8');
const expectedSha256 = createHash('sha256').update(expectedBytes).digest('hex');
await writeFile(notebookPath, '# marimo notebook fixture\n', 'utf8');
const shimPath = await writeFakeMarimoShim('fake-marimo-clean', 'clean', logPath, {
htmlContent: expectedHtml,
});
const receipt = await exportNotebookSnapshot({
notebookPath,
outputPath,
runner: createNodeNotebookCommandRunner(),
fs: createNodeNotebookSnapshotFs(),
marimoCommand: shimPath,
timeoutMs: 10_000,
allowedNotebookRoot: notebookDir,
allowedOutputRoot: outputDir,
});
expect(receipt.notebookPath).toBe(notebookPath);
expect(receipt.outputPath).toBe(outputPath);
expect(receipt.bytes).toBe(expectedBytes.byteLength);
expect(receipt.sha256).toBe(expectedSha256);
expect(receipt.checkDiagnostics).toEqual({
issues: [],
summary: { errored: false, total_files: 1 },
});
const published = await readFile(outputPath);
expect(published.byteLength).toBe(receipt.bytes);
expect(createHash('sha256').update(published).digest('hex')).toBe(receipt.sha256);
expect(await readdir(outputDir)).toEqual(['study.html']);
const invocations = (await readFile(logPath, 'utf8'))
.trim()
.split('\n')
.map(line => JSON.parse(line) as { args: string[] });
expect(invocations).toHaveLength(2);
expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]);
expect(invocations[1]?.args[0]).toBe('export');
expect(invocations[1]?.args[1]).toBe('html');
expect(invocations[1]?.args[2]).toBe(notebookPath);
expect(invocations[1]?.args[3]).toBe('-o');
expect(invocations[1]?.args[5]).toBe('--force');
});
test('blocking check report on exit 0 rejects CHECK_FAILED, skips export, and writes no output or temp files', async () => {
const notebookDir = join(workDir, 'notebooks');
const outputDir = join(workDir, 'out');
await mkdir(notebookDir);
await mkdir(outputDir);
const notebookPath = join(notebookDir, 'broken.py');
const outputPath = join(outputDir, 'broken.html');
const logPath = join(workDir, 'check-error.log.jsonl');
await writeFile(notebookPath, '# broken marimo notebook fixture\n', 'utf8');
const shimPath = await writeFakeMarimoShim('fake-marimo-check-error', 'check_error', logPath);
const err = await expectReject(
exportNotebookSnapshot({
notebookPath,
outputPath,
runner: createNodeNotebookCommandRunner(),
fs: createNodeNotebookSnapshotFs(),
marimoCommand: shimPath,
timeoutMs: 10_000,
})
);
expect(err).toBeInstanceOf(NotebookSnapshotError);
expect((err as NotebookSnapshotError).code).toBe('CHECK_FAILED');
expect(await readdir(outputDir)).toEqual([]);
const invocations = (await readFile(logPath, 'utf8'))
.trim()
.split('\n')
.map(line => JSON.parse(line) as { args: string[] });
expect(invocations).toHaveLength(1);
expect(invocations[0]?.args).toEqual(['check', '--format=json', notebookPath]);
});
test('hanging export rejects TIMEOUT, kills export child, and leaves no output or partial temp file', async () => {
const notebookDir = join(workDir, 'notebooks');
const outputDir = join(workDir, 'out');
await mkdir(notebookDir);
await mkdir(outputDir);
const notebookPath = join(notebookDir, 'hang.py');
const outputPath = join(outputDir, 'hang.html');
const logPath = join(workDir, 'hang.log.jsonl');
const pidPath = join(workDir, 'hang-export.pid');
await writeFile(notebookPath, '# hanging export fixture\n', 'utf8');
const shimPath = await writeFakeMarimoShim('fake-marimo-hang', 'hang_export', logPath, {
pidPath,
});
const err = await expectReject(
exportNotebookSnapshot({
notebookPath,
outputPath,
runner: createNodeNotebookCommandRunner(),
fs: createNodeNotebookSnapshotFs(),
marimoCommand: shimPath,
timeoutMs: 800,
})
);
const pid = Number.parseInt(readFileSync(pidPath, 'utf8').trim(), 10);
let probeError: unknown;
try {
process.kill(pid, 0);
} catch (killErr) {
probeError = killErr;
}
expect(err).toBeInstanceOf(NotebookSnapshotError);
expect((err as NotebookSnapshotError).code).toBe('TIMEOUT');
expect(Number.isInteger(pid) && pid > 0).toBe(true);
expect(getErrorCode(probeError)).toBe('ESRCH');
expect(await readdir(outputDir)).toEqual([]);
const invocations = (await readFile(logPath, 'utf8'))
.trim()
.split('\n')
.map(line => JSON.parse(line) as { args: string[]; pid: number });
expect(invocations).toHaveLength(2);
expect(invocations[0]?.args[0]).toBe('check');
expect(invocations[1]?.args[0]).toBe('export');
});
});
});