T-177: M2.1o — marimo check-gated static HTML snapshot exporter for research notebooks: exportNotebookSnapshot over an injected command-runner port in libs/research/src/notebook-snapshot.ts (check must pass before marimo export html, fail-closed, atomic output, no new deps, no real marimo in tests)

This commit is contained in:
Studio 2026-12-02 15:56:45 -05:00
parent b23722f151
commit be9ae5a7c9
2 changed files with 95 additions and 14 deletions

View file

@ -255,14 +255,9 @@ function assertWithinRoot(
} }
} }
function splitDirAndBase(normalizedFilePath: string): { function dirnamePosix(normalizedFilePath: string): string {
readonly dir: string;
readonly base: string;
} {
const lastSlash = normalizedFilePath.lastIndexOf('/'); const lastSlash = normalizedFilePath.lastIndexOf('/');
const dir = lastSlash <= 0 ? '/' : normalizedFilePath.slice(0, lastSlash); return lastSlash <= 0 ? '/' : normalizedFilePath.slice(0, lastSlash);
const base = normalizedFilePath.slice(lastSlash + 1);
return { dir, base };
} }
function validatePortsAndOptions(options: ExportNotebookSnapshotOptions): { function validatePortsAndOptions(options: ExportNotebookSnapshotOptions): {
@ -530,11 +525,11 @@ function generateTempToken(): string {
} }
async function reserveSiblingTempHtml(fs: NotebookSnapshotFs, outputPath: string): Promise<string> { async function reserveSiblingTempHtml(fs: NotebookSnapshotFs, outputPath: string): Promise<string> {
const { dir, base } = splitDirAndBase(outputPath); const dir = dirnamePosix(outputPath);
const dirPrefix = dir === '/' ? '' : dir; const dirPrefix = dir === '/' ? '' : dir;
for (let attempt = 0; attempt < MAX_TEMP_RESERVATION_ATTEMPTS; attempt += 1) { for (let attempt = 0; attempt < MAX_TEMP_RESERVATION_ATTEMPTS; attempt += 1) {
const candidate = `${dirPrefix}/.${base}.${generateTempToken()}.tmp.html`; const candidate = `${dirPrefix}/.marimo-snapshot-${generateTempToken()}.tmp.html`;
try { try {
await fs.createExclusive(candidate); await fs.createExclusive(candidate);
return candidate; return candidate;
@ -636,12 +631,12 @@ export async function exportNotebookSnapshot(
'check' 'check'
); );
const trimmedCheckStdout = checkResult.stdout.trim(); const hasCheckStdout = checkResult.stdout.length > 0;
let parsedCheckJson: unknown = undefined; let parsedCheckJson: unknown = undefined;
let checkJsonParseError: unknown = undefined; let checkJsonParseError: unknown = undefined;
if (trimmedCheckStdout.length > 0) { if (hasCheckStdout) {
try { try {
parsedCheckJson = JSON.parse(trimmedCheckStdout); parsedCheckJson = JSON.parse(checkResult.stdout);
} catch (err) { } catch (err) {
checkJsonParseError = err; checkJsonParseError = err;
} }
@ -665,7 +660,7 @@ export async function exportNotebookSnapshot(
} }
let checkDiagnostics: MarimoCheckReport | null = null; let checkDiagnostics: MarimoCheckReport | null = null;
if (trimmedCheckStdout.length > 0) { if (hasCheckStdout) {
if (checkJsonParseError !== undefined) { if (checkJsonParseError !== undefined) {
throw new NotebookSnapshotError( throw new NotebookSnapshotError(
'CHECK_OUTPUT_INVALID', 'CHECK_OUTPUT_INVALID',

View file

@ -335,6 +335,33 @@ describe('exportNotebookSnapshot', () => {
expect(calls).toHaveLength(1); expect(calls).toHaveLength(1);
}); });
test('never invokes export when check exits 0 with whitespace-only stdout', async () => {
for (const stdout of ['\n', ' \t\r\n']) {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>existing-snapshot</html>');
const { runner, calls } = createRecordingRunner(async () => ({
exitCode: 0,
stdout,
stderr: '',
}));
await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'CHECK_OUTPUT_INVALID'
);
expect(calls).toHaveLength(1);
expect(calls[0]?.args[0]).toBe('check');
expect(fs.createdTempPaths).toHaveLength(0);
expect(fs.getText('/work/out.html')).toBe('<html>existing-snapshot</html>');
}
});
test('never invokes export when check exits 0 with malformed JSON or invalid report shape', async () => { test('never invokes export when check exits 0 with malformed JSON or invalid report shape', async () => {
const badOutputs = [ const badOutputs = [
'{not-valid-json', '{not-valid-json',
@ -538,7 +565,39 @@ describe('exportNotebookSnapshot', () => {
expect(fs.getText('/work/out.html')).toBe('<html>keep-original</html>'); expect(fs.getText('/work/out.html')).toBe('<html>keep-original</html>');
}); });
test('fail-closed export: rename failure throws EXPORT_FAILED, removes temp, preserves destination, and preserves primary error if cleanup fails', async () => { test('fail-closed export: rename failure throws EXPORT_FAILED, removes temp, and preserves destination', async () => {
const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>prior-snapshot</html>');
fs.failRenameError = new Error('EXDEV: cross-device link not permitted');
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>new-snapshot</html>');
return { exitCode: 0, stdout: '', stderr: '' };
});
const err = await expectSnapshotError(
exportNotebookSnapshot({
notebookPath: '/work/nb.py',
outputPath: '/work/out.html',
runner,
fs,
}),
'EXPORT_FAILED'
);
const tempPath = fs.createdTempPaths[0] as string;
expect(err.cause).toBe(fs.failRenameError);
expect(fs.removedPaths).toContain(tempPath);
expect(fs.getBytes(tempPath)).toBeUndefined();
expect(fs.getText('/work/out.html')).toBe('<html>prior-snapshot</html>');
});
test('fail-closed export: rename failure preserves primary error if temp cleanup also fails', async () => {
const fs = new InMemoryNotebookFs(); const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n'); fs.putFile('/work/nb.py', 'import marimo\n');
fs.putFile('/work/out.html', '<html>prior-snapshot</html>'); fs.putFile('/work/out.html', '<html>prior-snapshot</html>');
@ -569,6 +628,33 @@ describe('exportNotebookSnapshot', () => {
expect(fs.getText('/work/out.html')).toBe('<html>prior-snapshot</html>'); expect(fs.getText('/work/out.html')).toBe('<html>prior-snapshot</html>');
}); });
test('uses a short sibling temp filename even when output basename is near POSIX NAME_MAX', async () => {
const fs = new InMemoryNotebookFs();
const notebookPath = '/work/nb.py';
const longBasename = `${'a'.repeat(250)}.html`;
const outputPath = `/work/${longBasename}`;
fs.putFile(notebookPath, 'import marimo\n');
const { runner } = createRecordingRunner(async (_cmd, args) => {
if (args[0] === 'check') {
return { exitCode: 0, stdout: '', stderr: '' };
}
const tempPath = args[args.indexOf('-o') + 1] as string;
fs.putFile(tempPath, '<html>long-name-ok</html>');
return { exitCode: 0, stdout: '', stderr: '' };
});
await exportNotebookSnapshot({ notebookPath, outputPath, runner, fs });
expect(fs.createdTempPaths).toHaveLength(1);
const tempPath = fs.createdTempPaths[0] as string;
const tempBasename = tempPath.slice(tempPath.lastIndexOf('/') + 1);
expect(tempPath.startsWith('/work/')).toBe(true);
expect(tempBasename.endsWith('.html')).toBe(true);
expect(tempBasename.length).toBeLessThan(128);
expect(fs.getText(outputPath)).toBe('<html>long-name-ok</html>');
});
test('overlapping exports to the same outputPath reserve separate temp files without partial publication', async () => { test('overlapping exports to the same outputPath reserve separate temp files without partial publication', async () => {
const fs = new InMemoryNotebookFs(); const fs = new InMemoryNotebookFs();
fs.putFile('/work/nb.py', 'import marimo\n'); fs.putFile('/work/nb.py', 'import marimo\n');