import { createHash } from 'node:crypto'; import { describe, expect, test } from 'bun:test'; import { exportNotebookSnapshot, NotebookSnapshotError, type ExportNotebookSnapshotOptions, type NotebookCommandResult, type NotebookCommandRunner, type NotebookSnapshotFileStat, type NotebookSnapshotFs, } from '../src/notebook-snapshot'; // QA coverage for T-177 beyond the programmer's unit tests: fail-at-call-N fault // injection across every port call, realistic marimo 0.26.0 report payloads // (shapes taken from marimo/_lint/formatters/json.py, _lint/linter.py and // _cli/cli.py `check`, which echoes JSON with a trailing newline), temp-name // collisions, path normalization, and option validation. Fakes only; no real // marimo process is ever spawned. const NOTEBOOK = '/work/notebooks/study.py'; const OUTPUT = '/work/out/study.html'; const ORIGINAL_SNAPSHOT = 'original-snapshot'; const NEW_SNAPSHOT = 'new-snapshot — €'; const TEMP_MARKER = '.marimo-snapshot-'; type PortOp = | 'fs.stat' | 'fs.createExclusive' | 'fs.readBytes' | 'fs.rename' | 'fs.remove' | 'runner.check' | 'runner.export'; function errWithCode(code: string, message = code): Error & { code: string } { const err = new Error(message) as Error & { code: string }; err.code = code; return err; } /** * In-memory fs + runner pair sharing one ordered port-call log. `failAt` makes * the Nth port call throw EIO; `failPersistently` makes every later call throw too. */ class FaultyPorts { readonly files = new Map(); readonly ops: PortOp[] = []; readonly runnerArgs: string[][] = []; failAt = 0; failPersistently = false; checkStdout = ''; exportBytes: Uint8Array = new TextEncoder().encode(NEW_SNAPSHOT); createExclusiveHook: ((path: string, attempt: number) => void) | null = null; private createAttempts = 0; constructor() { this.files.set(NOTEBOOK, { isFile: true, bytes: new TextEncoder().encode('import marimo\n') }); this.files.set(OUTPUT, { isFile: true, bytes: new TextEncoder().encode(ORIGINAL_SNAPSHOT) }); } private tick(op: PortOp): void { this.ops.push(op); const n = this.ops.length; if (this.failAt > 0 && (n === this.failAt || (this.failPersistently && n > this.failAt))) { throw errWithCode('EIO', `injected EIO at port call ${n} (${op})`); } } text(path: string): string | undefined { const entry = this.files.get(path); return entry ? new TextDecoder().decode(entry.bytes) : undefined; } tempPaths(): string[] { return [...this.files.keys()].filter(p => p.includes(TEMP_MARKER)); } readonly fs: NotebookSnapshotFs = { stat: async (path): Promise => { this.tick('fs.stat'); const entry = this.files.get(path); return entry ? { isFile: entry.isFile, size: entry.bytes.byteLength } : null; }, createExclusive: async path => { this.tick('fs.createExclusive'); this.createAttempts += 1; this.createExclusiveHook?.(path, this.createAttempts); if (this.files.has(path)) { throw errWithCode('EEXIST'); } this.files.set(path, { isFile: true, bytes: new Uint8Array(0) }); }, readBytes: async path => { this.tick('fs.readBytes'); const entry = this.files.get(path); if (!entry) { throw errWithCode('ENOENT'); } return new Uint8Array(entry.bytes); }, rename: async (from, to) => { this.tick('fs.rename'); const entry = this.files.get(from); if (!entry) { throw errWithCode('ENOENT'); } this.files.delete(from); this.files.set(to, entry); }, remove: async path => { this.tick('fs.remove'); this.files.delete(path); }, }; readonly runner: NotebookCommandRunner = { run: async (_command, args): Promise => { this.runnerArgs.push([...args]); if (args[0] === 'check') { this.tick('runner.check'); return { exitCode: 0, stdout: this.checkStdout, stderr: '' }; } this.tick('runner.export'); const tempPath = args[args.indexOf('-o') + 1] as string; this.files.set(tempPath, { isFile: true, bytes: this.exportBytes }); return { exitCode: 0, stdout: '', stderr: '' }; }, }; options(extra: Partial = {}): ExportNotebookSnapshotOptions { return { notebookPath: NOTEBOOK, outputPath: OUTPUT, runner: this.runner, fs: this.fs, ...extra }; } } async function captureSnapshotError(promise: Promise): Promise { try { await promise; } catch (err) { expect(err).toBeInstanceOf(NotebookSnapshotError); return err as NotebookSnapshotError; } throw new Error('Expected NotebookSnapshotError, but the export resolved.'); } function stubRunner(result: unknown): { runner: NotebookCommandRunner; calls: string[][] } { const calls: string[][] = []; return { calls, runner: { run: async (_c, args) => { calls.push([...args]); return result as NotebookCommandResult; }, }, }; } // Realistic marimo 0.26.0 `check --format=json` stdout (click.echo appends '\n'). function marimoCheckStdout( issues: readonly Record[], errored: boolean, totalFiles = 1 ): string { return `${JSON.stringify({ issues, summary: { total_files: totalFiles, files_with_issues: issues.length > 0 ? 1 : 0, total_issues: issues.length, fixed_issues: 0, errored, }, })}\n`; } describe('exportNotebookSnapshot QA: fail-at-call-N fault injection', () => { const expectedByStep: ReadonlyArray<{ op: PortOp; code: NotebookSnapshotError['code'] }> = [ { op: 'fs.stat', code: 'NOTEBOOK_NOT_FOUND' }, { op: 'runner.check', code: 'CHECK_FAILED' }, { op: 'fs.createExclusive', code: 'EXPORT_FAILED' }, { op: 'runner.export', code: 'EXPORT_FAILED' }, { op: 'fs.stat', code: 'EXPORT_FAILED' }, { op: 'fs.readBytes', code: 'EXPORT_FAILED' }, { op: 'fs.rename', code: 'EXPORT_FAILED' }, ]; test('happy path issues exactly the expected ordered port calls', async () => { const ports = new FaultyPorts(); await exportNotebookSnapshot(ports.options()); expect(ports.ops).toEqual(expectedByStep.map(s => s.op)); }); for (const persistent of [false, true]) { test(`failing port call N (${persistent ? 'and every later call' : 'only'}) fails closed with the mapped code, keeps the old snapshot, and a retry succeeds`, async () => { for (let n = 1; n <= expectedByStep.length; n += 1) { const ports = new FaultyPorts(); ports.failAt = n; ports.failPersistently = persistent; const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); const step = expectedByStep[n - 1]!; expect({ n, op: ports.ops[n - 1], code: err.code }).toEqual({ n, op: step.op, code: step.code }); expect(err.cause).toBeDefined(); expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); // Export must never run once the check phase (or anything before it) failed. if (n <= 2) { expect(ports.runnerArgs.filter(a => a[0] === 'export')).toHaveLength(0); expect(ports.ops).not.toContain('fs.createExclusive'); } if (!persistent) { // Cleanup succeeded: no owned temp file survives any injected fault. expect(ports.tempPaths()).toEqual([]); if (n >= 4) { expect(ports.ops.at(-1)).toBe('fs.remove'); } } // Retry once the fault clears publishes the new snapshot. ports.failAt = 0; const receipt = await exportNotebookSnapshot(ports.options()); expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); expect(receipt.bytes).toBe(ports.exportBytes.byteLength); if (!persistent) { expect(ports.tempPaths()).toEqual([]); } } }); } test('an extra fault index past the last port call means the export succeeds (no hidden fault points)', async () => { const ports = new FaultyPorts(); ports.failAt = expectedByStep.length + 1; const receipt = await exportNotebookSnapshot(ports.options()); expect(receipt.sha256).toBe(createHash('sha256').update(ports.exportBytes).digest('hex')); expect(ports.tempPaths()).toEqual([]); }); }); describe('exportNotebookSnapshot QA: realistic marimo 0.26.0 check reports', () => { test('accepts the real report shape with trailing newline and formatting/runtime diagnostics', async () => { const ports = new FaultyPorts(); const issues = [ { type: 'diagnostic', message: 'Cell is not formatted', filename: NOTEBOOK, line: 3, column: 1, severity: 'formatting', name: 'general-formatting', code: 'MF001', fixable: true, cell_id: ['Hbol'], }, { type: 'diagnostic', message: 'Self import', filename: NOTEBOOK, line: 7, column: 1, severity: 'runtime', name: 'self-import', code: 'MR001', fixable: false, }, ]; ports.checkStdout = marimoCheckStdout(issues, false); const receipt = await exportNotebookSnapshot(ports.options()); expect(receipt.checkDiagnostics).toEqual(JSON.parse(ports.checkStdout)); expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); }); test('blocks export for a file-level error issue even when exit is 0 and summary.errored is false', async () => { // marimo marks `status == "invalid"` notebooks failed without necessarily // setting errored first; the gate must not rely on summary.errored alone. const ports = new FaultyPorts(); ports.checkStdout = marimoCheckStdout( [{ type: 'error', filename: NOTEBOOK, error: `Failed to parse: ${NOTEBOOK} (not a valid notebook)` }], false ); const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); expect(err.code).toBe('CHECK_FAILED'); expect(ports.runnerArgs).toHaveLength(1); expect(ports.ops).not.toContain('fs.createExclusive'); expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); }); test('blocks export for a breaking diagnostic (MB rule) on exit 0', async () => { const ports = new FaultyPorts(); ports.checkStdout = marimoCheckStdout( [ { type: 'diagnostic', message: "Variable 'x' is defined in multiple cells", filename: NOTEBOOK, line: 4, column: 1, severity: 'breaking', name: 'multiple-definitions', code: 'MB002', fixable: false, }, ], false ); const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); expect(err.code).toBe('CHECK_FAILED'); expect(ports.runnerArgs).toHaveLength(1); }); test('rejects a report that checked zero files (e.g. notebook vanished before check) as CHECK_OUTPUT_INVALID', async () => { const ports = new FaultyPorts(); ports.checkStdout = marimoCheckStdout([], false, 0); const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); expect(err.code).toBe('CHECK_OUTPUT_INVALID'); expect(ports.runnerArgs).toHaveLength(1); }); test('blocks a nested diagnostics entry with type "error"', async () => { const ports = new FaultyPorts(); ports.checkStdout = marimoCheckStdout( [{ filename: NOTEBOOK, diagnostics: [{ type: 'error', message: 'boom' }] }], false ); const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); expect(err.code).toBe('CHECK_FAILED'); expect(ports.runnerArgs).toHaveLength(1); }); test('rejects non-string severity in an issue as CHECK_OUTPUT_INVALID', async () => { const ports = new FaultyPorts(); ports.checkStdout = marimoCheckStdout([{ type: 'diagnostic', severity: 3 }], false); const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); expect(err.code).toBe('CHECK_OUTPUT_INVALID'); expect(ports.runnerArgs).toHaveLength(1); }); test('receipt diagnostics are deeply frozen and detached from later mutation attempts', async () => { const ports = new FaultyPorts(); ports.checkStdout = marimoCheckStdout( [{ type: 'diagnostic', severity: 'formatting', code: 'MF001', cell_id: ['a'] }], false ); const receipt = await exportNotebookSnapshot(ports.options()); const diagnostics = receipt.checkDiagnostics!; expect(() => { (diagnostics.summary as { errored: boolean }).errored = true; }).toThrow(TypeError); expect(() => { (diagnostics.issues as unknown[]).push({}); }).toThrow(TypeError); expect(() => { (receipt as { sha256: string }).sha256 = 'x'; }).toThrow(TypeError); expect(diagnostics.summary.errored).toBe(false); }); }); describe('exportNotebookSnapshot QA: runner contract violations', () => { test('non-timeout runner rejection in check maps to CHECK_FAILED with cause and never exports', async () => { const spawnError = errWithCode('ENOENT', 'spawn marimo ENOENT'); const calls: string[][] = []; const ports = new FaultyPorts(); const runner: NotebookCommandRunner = { run: async (_c, args) => { calls.push([...args]); throw spawnError; }, }; const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); expect(err.code).toBe('CHECK_FAILED'); expect(err.cause).toBe(spawnError); expect(calls).toHaveLength(1); expect(ports.tempPaths()).toEqual([]); }); test('malformed runner results in check map to CHECK_FAILED and never export', async () => { const malformed: unknown[] = [ null, 'exit 0', { exitCode: '0', stdout: '', stderr: '' }, { exitCode: Number.NaN, stdout: '', stderr: '' }, { exitCode: 0.5, stdout: '', stderr: '' }, { exitCode: 0, stderr: '' }, { exitCode: 0, stdout: '', stderr: null }, ]; for (const result of malformed) { const ports = new FaultyPorts(); const { runner, calls } = stubRunner(result); const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); expect(err.code).toBe('CHECK_FAILED'); expect(calls).toHaveLength(1); expect(ports.tempPaths()).toEqual([]); } }); test('malformed runner result in export maps to EXPORT_FAILED, removes temp, and keeps destination', async () => { const ports = new FaultyPorts(); const runner: NotebookCommandRunner = { run: async (_c, args) => (args[0] === 'check' ? { exitCode: 0, stdout: '', stderr: '' } : { exitCode: 0, stdout: undefined, stderr: '' }) as unknown as NotebookCommandResult, }; const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ runner }))); expect(err.code).toBe('EXPORT_FAILED'); expect(ports.tempPaths()).toEqual([]); expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); }); test('readBytes returning zero bytes despite a nonzero stat size is EXPORT_EMPTY and cleans up', async () => { const ports = new FaultyPorts(); const fs: NotebookSnapshotFs = { ...ports.fs, readBytes: async () => new Uint8Array(0) }; const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); expect(err.code).toBe('EXPORT_EMPTY'); expect(ports.tempPaths()).toEqual([]); expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); }); test('temp file vanishing between stat and read (ENOENT) is EXPORT_EMPTY', async () => { const ports = new FaultyPorts(); const fs: NotebookSnapshotFs = { ...ports.fs, readBytes: async () => { throw errWithCode('ENOENT'); }, }; const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); expect(err.code).toBe('EXPORT_EMPTY'); expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); }); test('notebook stat throwing ENOENT is NOTEBOOK_NOT_FOUND with zero runner calls', async () => { const ports = new FaultyPorts(); const fs: NotebookSnapshotFs = { ...ports.fs, stat: async () => { throw errWithCode('ENOENT'); }, }; const err = await captureSnapshotError(exportNotebookSnapshot(ports.options({ fs }))); expect(err.code).toBe('NOTEBOOK_NOT_FOUND'); expect(ports.runnerArgs).toHaveLength(0); }); }); describe('exportNotebookSnapshot QA: temp reservation', () => { test('retries on EEXIST collisions and exports to the first free sibling', async () => { const ports = new FaultyPorts(); ports.createExclusiveHook = (path, attempt) => { if (attempt <= 3) { ports.files.set(path, { isFile: true, bytes: new TextEncoder().encode('foreign') }); } }; await exportNotebookSnapshot(ports.options()); const exportArgs = ports.runnerArgs.find(a => a[0] === 'export')!; const usedTemp = exportArgs[exportArgs.indexOf('-o') + 1]!; expect(ports.ops.filter(op => op === 'fs.createExclusive')).toHaveLength(4); expect(usedTemp.startsWith('/work/out/')).toBe(true); // The three foreign colliding files are not owned and must be left alone. expect(ports.tempPaths()).toHaveLength(3); expect(ports.tempPaths()).not.toContain(usedTemp); expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); }); test('gives up with EXPORT_FAILED after bounded EEXIST collisions, never exports, and never removes foreign files', async () => { const ports = new FaultyPorts(); ports.createExclusiveHook = path => { ports.files.set(path, { isFile: true, bytes: new TextEncoder().encode('foreign') }); }; const err = await captureSnapshotError(exportNotebookSnapshot(ports.options())); expect(err.code).toBe('EXPORT_FAILED'); expect(ports.ops.filter(op => op === 'fs.createExclusive')).toHaveLength(16); expect(ports.runnerArgs.filter(a => a[0] === 'export')).toHaveLength(0); expect(ports.ops).not.toContain('fs.remove'); expect(ports.text(OUTPUT)).toBe(ORIGINAL_SNAPSHOT); }); test('a destination directly under / reserves its temp under / without a double slash', async () => { const ports = new FaultyPorts(); ports.files.set('/nb.py', { isFile: true, bytes: new TextEncoder().encode('x') }); await exportNotebookSnapshot(ports.options({ notebookPath: '/nb.py', outputPath: '/snap.html' })); const exportArgs = ports.runnerArgs.find(a => a[0] === 'export')!; const temp = exportArgs[exportArgs.indexOf('-o') + 1]!; expect(temp).toMatch(/^\/\.marimo-snapshot-[^/]+\.tmp\.html$/); expect(ports.text('/snap.html')).toBe(NEW_SNAPSHOT); }); }); describe('exportNotebookSnapshot QA: path normalization and roots', () => { test('passes and reports normalized paths (dot segments, duplicate slashes) to runner, fs, and receipt', async () => { const ports = new FaultyPorts(); const receipt = await exportNotebookSnapshot( ports.options({ notebookPath: '/work//notebooks/./sub/../study.py', outputPath: '/work/out/./x/../study.html', allowedNotebookRoot: '/work/notebooks/', allowedOutputRoot: '/work/out', }) ); expect(ports.runnerArgs[0]).toEqual(['check', '--format=json', NOTEBOOK]); expect(ports.runnerArgs[1]?.[2]).toBe(NOTEBOOK); expect(receipt.notebookPath).toBe(NOTEBOOK); expect(receipt.outputPath).toBe(OUTPUT); expect(ports.text(OUTPUT)).toBe(NEW_SNAPSHOT); }); test('a basename starting with "-" inside an absolute path is passed as one argv element', async () => { const ports = new FaultyPorts(); ports.files.set('/work/notebooks/-rf.py', { isFile: true, bytes: new TextEncoder().encode('x') }); await exportNotebookSnapshot(ports.options({ notebookPath: '/work/notebooks/-rf.py' })); expect(ports.runnerArgs[0]).toEqual(['check', '--format=json', '/work/notebooks/-rf.py']); }); test('root "/" accepts any absolute path; relative or NUL roots and relative cwd are rejected before any port call', async () => { const ok = new FaultyPorts(); await exportNotebookSnapshot(ok.options({ allowedNotebookRoot: '/', allowedOutputRoot: '/' })); expect(ok.text(OUTPUT)).toBe(NEW_SNAPSHOT); const badExtras: Array> = [ { allowedNotebookRoot: 'work/notebooks' }, { allowedOutputRoot: './out' }, { allowedOutputRoot: '/work/out\0' }, { allowedNotebookRoot: '' }, { cwd: 'work' }, // Path equal to the root itself is not "inside" it. { allowedNotebookRoot: NOTEBOOK }, // `..` that climbs above the root after normalization. { notebookPath: '/work/notebooks/../../work/notebooks/../x.py', allowedNotebookRoot: '/work/notebooks' }, ]; for (const extra of badExtras) { const ports = new FaultyPorts(); const err = await captureSnapshotError(exportNotebookSnapshot(ports.options(extra))); expect(err.code).toBe('INVALID_PATH'); expect(ports.ops).toEqual([]); expect(ports.runnerArgs).toEqual([]); } }); test('".." above filesystem root clamps to "/" and is still contained by roots', async () => { const ports = new FaultyPorts(); const err = await captureSnapshotError( exportNotebookSnapshot( ports.options({ notebookPath: '/../../etc/x.py', allowedNotebookRoot: '/work/notebooks' }) ) ); expect(err.code).toBe('INVALID_PATH'); expect(ports.runnerArgs).toEqual([]); }); }); describe('exportNotebookSnapshot QA: option validation', () => { test('rejects malformed ports and options with INVALID_OPTION before any port call', async () => { const ports = new FaultyPorts(); const bad: Array | null> = [ null, { runner: undefined as unknown as NotebookCommandRunner }, { runner: {} as NotebookCommandRunner }, { fs: { ...ports.fs, rename: undefined } as unknown as NotebookSnapshotFs }, { fs: { ...ports.fs, createExclusive: 'x' } as unknown as NotebookSnapshotFs }, { timeoutMs: -1 }, { timeoutMs: 1.5 }, { timeoutMs: Number.NaN }, { timeoutMs: Number.POSITIVE_INFINITY }, { timeoutMs: '1000' as unknown as number }, { marimoCommand: '' }, { marimoCommand: ' ' }, { marimoCommand: 'mar\0imo' }, { marimoCommand: 42 as unknown as string }, ]; for (const extra of bad) { const options = extra === null ? (null as unknown as ExportNotebookSnapshotOptions) : ports.options(extra); const err = await captureSnapshotError(exportNotebookSnapshot(options)); expect(err.code).toBe('INVALID_OPTION'); } expect(ports.ops).toEqual([]); expect(ports.runnerArgs).toEqual([]); }); test('non-string notebookPath/outputPath are INVALID_PATH', async () => { for (const extra of [ { notebookPath: undefined as unknown as string }, { outputPath: 7 as unknown as string }, { notebookPath: '' }, ]) { const ports = new FaultyPorts(); const err = await captureSnapshotError(exportNotebookSnapshot(ports.options(extra))); expect(err.code).toBe('INVALID_PATH'); expect(ports.ops).toEqual([]); } }); test('NotebookSnapshotError is a real Error subclass with stable name and code', () => { const err = new NotebookSnapshotError('TIMEOUT', 'm', { details: { a: 1 } }); expect(err).toBeInstanceOf(Error); expect(err.name).toBe('NotebookSnapshotError'); expect(err.code).toBe('TIMEOUT'); expect(err.details).toEqual({ a: 1 }); expect('cause' in err && err.cause !== undefined).toBe(false); }); });