import { afterEach, expect, test } from 'bun:test'; import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { tmpdir } from 'node:os'; import { executeWorkflowFile } from '../src/runtime/exec.js'; const dirs: string[] = []; afterEach(async () => { // Windows keeps a just-terminated process's cwd busy for ~200ms after the // async taskkill (EBUSY). Retry instead of failing a test that passed; a // genuinely leaked process would still hold the directory after 5s and fail. // Explicit loop: Bun's rm does not honor maxRetries. for (const dir of dirs.splice(0)) { for (let attempt = 0; ; attempt++) { try { await rm(dir, { recursive: true, force: true }); break; } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EBUSY' || attempt >= 50) throw error; await new Promise((resolve) => setTimeout(resolve, 100)); } } } }); async function script(source: string) { const cwd = await mkdtemp(join(tmpdir(), 'wf-process-')); dirs.push(cwd); await writeFile(join(cwd, 'script.mjs'), source); return { cwd, workflowDir: cwd }; } test('timeout forcibly finishes a process ignoring SIGTERM', async () => { const runtime = await script( "process.on('SIGTERM',()=>{}); console.log('ready'); setInterval(()=>{}, 100);", ); const start = Date.now(); const result = await executeWorkflowFile( 'script.mjs', [], { timeoutMs: 500 }, runtime, ); expect(result.timedOut).toBe(true); expect(result.exitCode).toBe(124); expect(result.stdout).toContain('ready'); expect(Date.now() - start).toBeLessThan(3000); }); test('cancellation rejects, never masquerades as an ordinary failed command', async () => { const runtime = await script( "process.on('SIGTERM',()=>{}); setInterval(()=>{},100);", ); const controller = new AbortController(); const run = executeWorkflowFile( 'script.mjs', [], {}, { ...runtime, signal: controller.signal }, ); const timer = setTimeout(() => controller.abort(), 100); try { await expect(run).rejects.toMatchObject({ name: 'AbortError' }); } finally { clearTimeout(timer); } }); test('normal nonzero exit differs from timeout', async () => { const runtime = await script( "process.stderr.write('bad input'); process.exitCode=7;", ); const result = await executeWorkflowFile( 'script.mjs', [], { timeoutMs: 3000 }, runtime, ); expect(result).toMatchObject({ exitCode: 7, timedOut: false, stderr: 'bad input', }); }); test('exited leader with descendant-held pipes cannot keep the node waiting', async () => { const runtime = await script( "import {spawn} from 'node:child_process'; spawn(process.execPath,['-e','setInterval(()=>{},100)'],{stdio:'inherit'}).unref();", ); const start = Date.now(); const result = await executeWorkflowFile( 'script.mjs', [], { timeoutMs: 3000 }, runtime, ); expect(result.timedOut).toBe(false); expect(Date.now() - start).toBeLessThan(2000); });