import { test } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; // Run with: pnpm -C common exec tsx --test lib/childKillGuard.test.ts // // A kill on a child whose spawn FAILED signals the caller's own process group // on Node (lib/childKillGuard.ts): the guard makes it a no-op. Each case runs // in a detached fixture — a group of its own, so a signal to "the group" // reaches the fixture and its canary, never this test runner. const HERE = path.dirname(fileURLToPath(import.meta.url)); const COMMON = path.resolve(HERE, ".."); const FIXTURE = path.join(HERE, "childKillGuard.fixture.ts"); type Report = { selfSigterm: number; canarySignal: string | null; pid?: number | null; killed?: boolean; signal?: string; outcome?: unknown }; function detached(guard: "guard" | "noguard", mode: string): Promise { return new Promise((resolve, reject) => { const child = spawn(process.execPath, [...process.execArgv, FIXTURE, guard, mode], { cwd: COMMON, detached: true, stdio: ["ignore", "pipe", "pipe"] }); let out = ""; let err = ""; child.stdout.on("data", (c: Buffer) => (out += c.toString("utf8"))); child.stderr.on("data", (c: Buffer) => (err += c.toString("utf8"))); const timer = setTimeout(() => { try { process.kill(-child.pid!, "SIGKILL"); } catch { /* gone */ } }, 60_000); child.on("exit", (code, signal) => { clearTimeout(timer); const line = out.trim().split("\n").pop() ?? ""; try { resolve(JSON.parse(line) as Report); } catch { reject(new Error(`fixture ${guard} ${mode} ended ${code ?? signal} with nothing readable: ${out}\n${err}`)); } }); }); } for (const mode of ["spawn-kill", "execa-aborted", "execa-kill", "launcher-abort-after"]) { test(`a failed spawn followed by a kill signals nothing: ${mode}`, async () => { const r = await detached("guard", mode); assert.equal(r.selfSigterm, 0, `the caller was signalled: ${JSON.stringify(r)}`); assert.equal(r.canarySignal, null, `a sibling in the caller's group was signalled: ${JSON.stringify(r)}`); if ("pid" in r) assert.equal(r.pid, null, "the spawn failed: no pid"); if ("killed" in r) assert.equal(r.killed, false, "the kill says it did nothing"); }); } // The launcher's own rule, WITHOUT the guard: yt-dlp is never launched for a // run that is already cancelled, so execa is never handed an aborted signal. for (const mode of ["launcher-aborted-before", "launcher-aborted-by-log"]) { test(`a cancelled run launches nothing, guard or no guard: ${mode}`, async () => { const r = (await detached("noguard", mode)) as Report & { said?: number }; assert.equal(r.selfSigterm, 0, JSON.stringify(r)); assert.equal(r.canarySignal, null, JSON.stringify(r)); assert.deepEqual(r.outcome, { exitCode: null, stderrTail: "", archiveLine: null, formatLine: null }); if (mode === "launcher-aborted-before") assert.equal(r.said, 0, "not even the launch line is logged"); }); } test("the hazard the guard is for, on this Node: without it the same kill reaches the caller's group", async (t) => { const r = await detached("noguard", "spawn-kill"); // Informational when a later Node guards it itself: the guard is then idle, not wrong. if (r.selfSigterm === 0 && r.canarySignal === null) { t.diagnostic(`Node ${process.version} no longer signals the group for an unspawned child`); return; } assert.ok(r.selfSigterm > 0 || r.canarySignal === "SIGTERM", JSON.stringify(r)); }); test("a child that started is killed as before", async () => { const r = await detached("guard", "started-child"); assert.equal(r.killed, true); assert.equal(r.signal, "SIGTERM"); assert.equal(r.selfSigterm, 0); assert.equal(r.canarySignal, null); }); // Every module of common/ that hands a child a `cancelSignal` or calls // `.kill()` on one installs the guard by importing it. jobs/registry.ts is the // one exception: it carries no node import (Next analyses it for the edge // bundle) and checks the pid at its three kills instead. const EXEMPT = new Set(["jobs/registry.ts", "lib/childKillGuard.ts", "lib/childKillGuard.fixture.ts"]); async function sources(dir: string, out: string[] = []): Promise { for (const e of await readdir(dir, { withFileTypes: true })) { if (e.name === "node_modules" || e.name.startsWith(".")) continue; const p = path.join(dir, e.name); if (e.isDirectory()) await sources(p, out); else if (/\.(ts|tsx|mts)$/.test(e.name) && !/\.test\.|\.d\.ts$/.test(e.name)) out.push(p); } return out; } test("every module of common/ that cancels or kills a child imports the guard", async () => { const missing: string[] = []; let spawners = 0; for (const file of await sources(COMMON)) { const rel = path.relative(COMMON, file); const text = await readFile(file, "utf8"); const code = text .split("\n") .filter((l) => !/^\s*(\/\/|\*|\/\*)/.test(l)) .join("\n") .replace(/process\.kill\(/g, ""); if (!/cancelSignal\s*[:,}]|\w\??\.kill\(/.test(code)) continue; spawners++; if (EXEMPT.has(rel)) continue; if (!/^import "(\.\.?\/)+(lib\/)?childKillGuard";$/m.test(text)) missing.push(rel); } assert.ok(spawners > 30, `the scan found the spawning modules (${spawners})`); assert.deepEqual(missing, [], "import \"…/lib/childKillGuard\" in each"); }); test("jobs/registry.ts checks the pid at every kill (it cannot import the guard)", async () => { const text = await readFile(path.join(COMMON, "jobs/registry.ts"), "utf8"); const kills = text.split("\n").filter((l) => /job\.child\.kill\(/.test(l) && !/^\s*\/\//.test(l)); assert.equal(kills.length, 3); // Each kill is on a line, or inside a block, that names the pid check. const guarded = text.match(/job\.child\.pid !== undefined/g) ?? []; assert.equal(guarded.length, 3); });