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-02 21:51:03 -05:00 • committed by Boki
parent 309f442d5e
commit 5d238ce32c
2 changed files with 116 additions and 37 deletions

View file

@ -134,28 +134,13 @@ export function createNodeNotebookCommandRunner(
// 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 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();
const attachStreamCollector = (
stream: NodeJS.ReadableStream | null,
streamName: 'stdout' | 'stderr',
@ -209,6 +194,26 @@ export function createNodeNotebookCommandRunner(
}
);
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) {

View file

@ -1,4 +1,5 @@
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import {
chmod,
mkdir,
@ -162,22 +163,96 @@ describe('notebook-snapshot-node adapters', () => {
runner.run(process.execPath, [scriptPath, pidFile], { timeoutMs: 800 })
);
expect(err).toBeInstanceOf(Error);
expect(getErrorCode(err)).toBe('ETIMEDOUT');
const pidText = await readFile(pidFile, 'utf8');
// 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);
expect(Number.isInteger(pid) && pid > 0).toBe(true);
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');
await writeFile(grandchildScript, 'setInterval(() => {}, 10_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');
@ -573,8 +648,18 @@ describe('notebook-snapshot-node adapters', () => {
})
);
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'))
@ -584,17 +669,6 @@ describe('notebook-snapshot-node adapters', () => {
expect(invocations).toHaveLength(2);
expect(invocations[0]?.args[0]).toBe('check');
expect(invocations[1]?.args[0]).toBe('export');
const pid = Number.parseInt((await readFile(pidPath, 'utf8')).trim(), 10);
expect(Number.isInteger(pid) && pid > 0).toBe(true);
let probeError: unknown;
try {
process.kill(pid, 0);
} catch (killErr) {
probeError = killErr;
}
expect(getErrorCode(probeError)).toBe('ESRCH');
});
});
});