commit 4682362d27fdb31aa8a3fdf816cd49aaf0f30672 parent e1894fc174de1e4decc9bd7f1c5231b3bde16e5e Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Thu, 12 Nov 2026 05:07:53 -0500 common: a kill on a child that never started is a no-op, and a cancelled run launches no yt-dlp -- cancelling a download whose channel directory was gone sent SIGTERM to the editor's own process group The editor's e2e server died (pnpm: "Command failed with signal SIGTERM") whenever a test left a download-missing job running and the next test's reset cancelled it while removing the channel tree; a live editor cancelling a download over a directory that is gone would go the same way. VERIFIED (Node 22.23.5, a group leader, a missing cwd; the scratch script and lib/childKillGuard.fixture.ts): ChildProcess.kill() is `this._handle.kill()` with no look at the pid (read from Node's own source); when the spawn failed there is a handle and no pid, and a kill in that tick -- spawn().kill(), execa().kill(), or execa with a cancelSignal that is ALREADY aborted -- delivers SIGTERM to the caller and to a sibling in its group; with the same aborted signal and a cwd that exists, to neither. In the e2e trace the server's kill was on a fake yt-dlp with no pid, 15 ms after the job's metadata child was cancelled. INFERRED: that the kernel call is kill(0) (libuv not read), and which launcher it was -- the trace names the download arguments, which runOneYtdlp and the audio-checked launch share; both are fixed. - lib/childKillGuard.ts: ChildProcess.prototype.kill returns false for a child with no pid. On the prototype because execa kills from inside itself; every module of common/ that passes a cancelSignal or kills a child imports it (37; a test scans for one that does not). jobs/registry.ts keeps no node import and checks the pid at its three kills. - runOneYtdlp, the audio-checked launch (runOneLaunch) and runYtdlp's runChildAndStream return the cancelled outcome before spawning when the signal is aborted -- and again after the launch line is logged, since a log sink may cancel; execa is never handed an aborted signal there. The other cancelSignal launchers (ffmpeg, ffprobe, gallery-dl, ...) still spawn and are killed at once when cancelled first, as before: with the guard that kill cannot reach the group. - runOneLaunch's abort handler read `child` before it was declared when the abort came before the spawn (a ReferenceError): it keeps the pid instead. Tests: a failed spawn followed by a kill signals nothing (four cases, each in a detached fixture with a canary in its group); without the guard the same kill does; a started child is killed as before; a cancelled run launches nothing and logs nothing, guard or no guard; the audio-checked download aborted before launch, over a directory that is gone, and cancelled by the log sink on the launch line. Co-Authored-By: Claude <noreply@anthropic.com> Diffstat:
41 files changed, 407 insertions(+), 11 deletions(-)
diff --git a/common/bin/_spawnBin.ts b/common/bin/_spawnBin.ts @@ -13,6 +13,7 @@ import { spawn } from "node:child_process"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import "../lib/childKillGuard"; const COMMON = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); export const REPO_ROOT = path.resolve(COMMON, ".."); diff --git a/common/bin/evidence-pack.ts b/common/bin/evidence-pack.ts @@ -53,6 +53,7 @@ import type { FlagValue } from "./_parseFlags"; // (social/postCapture.test.ts): a private package, written outside the // corpus, that nothing in the export or publish layer imports. import { CAPTURE_FILENAME, postsMediaDir } from "../social/postCapture"; +import "../lib/childKillGuard"; export const SUMS_FILE = "SHA256SUMS"; export const OTS_FILE = "SHA256SUMS.ots"; diff --git a/common/controller/attachMedia.ts b/common/controller/attachMedia.ts @@ -95,6 +95,7 @@ import { type CopiedEntry, type ZipEntry, } from "../lib/zipReader"; +import "../lib/childKillGuard"; export const ATTACH_MEDIA_REQUESTER = "attach-media"; diff --git a/common/controller/backupSavedVideos.ts b/common/controller/backupSavedVideos.ts @@ -15,6 +15,7 @@ import { } from "../lib/savedVideoBackup"; import { listSavedVideos } from "./savedVideoInventory"; import { updateSavedVideoChecksum } from "../lib/savedVideo-server"; +import "../lib/childKillGuard"; // Backup tooling for the saved-video store (Phase 4 of the video-persistence // feature). `dest` is treated as a local filesystem path (typically a mounted diff --git a/common/controller/checkAvailability.ts b/common/controller/checkAvailability.ts @@ -34,6 +34,7 @@ import { resolveShardItems } from "./shard"; import type { Paths } from "../lib/paths"; import { jitterYtdlpSleeps } from "../lib/jitter"; import { jitterMs } from "../lib/jitter"; +import "../lib/childKillGuard"; export type CheckAvailabilityMode = | "resume" diff --git a/common/controller/diarizeOne.ts b/common/controller/diarizeOne.ts @@ -34,6 +34,7 @@ import { import type { AudioIntegrityVerdict } from "../lib/audioIntegrity"; import { pickPreferredAudio } from "../lib/mediaFiles"; import { resolveSavedVideo } from "../lib/savedVideo-server"; +import "../lib/childKillGuard"; const { readdir } = fs; diff --git a/common/controller/landMedia.ts b/common/controller/landMedia.ts @@ -59,6 +59,7 @@ import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; import { ffmpegRemux } from "./preparePlayable"; import { transcodeAudio } from "./transcode"; +import "../lib/childKillGuard"; // Free space the store's disk keeps beyond the file (attach-media's margin). export const LAND_MEDIA_DISK_MARGIN_BYTES = 2 * 1024 ** 3; diff --git a/common/controller/preparePlayable.ts b/common/controller/preparePlayable.ts @@ -55,6 +55,7 @@ import { type PlayableEntry, type PlayableManifest, } from "../lib/playableMedia"; +import "../lib/childKillGuard"; // The creation date every torrent carries: fixed, so the same copy makes the // same .torrent file byte for byte (the infohash never depended on it). diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -104,6 +104,7 @@ import { findVideoSourceUrl } from "./undownloadedVideos"; import { jitterYtdlpSleeps } from "../lib/jitter"; import { parsePreclipKnob, type PreclipOptions } from "../lib/livePreclip"; import { jitterMs } from "../lib/jitter"; +import "../lib/childKillGuard"; export const RECORD_LIVE_JOB_KIND = "record-live"; export const RECORD_LIVE_RESULT_MARKER = "@@record-live "; diff --git a/common/controller/relocateDir.ts b/common/controller/relocateDir.ts @@ -21,6 +21,7 @@ import type { RelocationMarker, RelocationPhase, } from "../lib/channelMedia"; +import "../lib/childKillGuard"; // MOVING A DIRECTORY TO ANOTHER DRIVE AND LEAVING A SYMLINK — the mechanism, // with no opinion about whose directory it is. diff --git a/common/controller/scanCorruptMedia.ts b/common/controller/scanCorruptMedia.ts @@ -70,6 +70,7 @@ import { type MediaScanReport, type MediaScanVerdict, } from "../lib/mediaScan"; +import "../lib/childKillGuard"; const MEDIA_EXT_SET = new Set(MEDIA_EXTS); diff --git a/common/controller/transcode.ts b/common/controller/transcode.ts @@ -4,6 +4,7 @@ import { execa } from "execa"; import type { Paths } from "../lib/paths"; import type { AudioFormat } from "../lib/channelConfig"; import { tierMediaFile } from "../lib/mediaTier-server"; +import "../lib/childKillGuard"; const CODEC_ARGS: Record<AudioFormat, string[]> = { m4a: ["-c:a", "aac"], diff --git a/common/controller/transcribeFile.ts b/common/controller/transcribeFile.ts @@ -61,6 +61,7 @@ import { type StreamActionResult, } from "../jobs/streamCommand"; import { transcribeWithWorker } from "./transcribeOne"; +import "../lib/childKillGuard"; export const TRANSCRIBE_FILE_JOB_KIND = "transcribe-file"; diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -42,6 +42,7 @@ import { import { writeFileAtomic } from "../lib/jsonFile-server"; import { probeMedia } from "../lib/evidenceClip-server"; import { savedWindowSource } from "../lib/savedVideoWindow-server"; +import "../lib/childKillGuard"; const { pathExists, readdir, rename } = fs; diff --git a/common/controller/ttsFile.ts b/common/controller/ttsFile.ts @@ -61,6 +61,7 @@ import { copyFileAtomic, writeJsonAtomic } from "../lib/jsonFile-server"; import { getSettings } from "../lib/settings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { corpusRootContaining, corpusRoots, realpathDeep } from "./transcribeFile"; +import "../lib/childKillGuard"; export const TTS_FILE_JOB_KIND = "tts-file"; diff --git a/common/controller/ttsServer.ts b/common/controller/ttsServer.ts @@ -27,6 +27,7 @@ import { createWriteStream, existsSync, type WriteStream } from "node:fs"; import net from "node:net"; import path from "node:path"; import type { TtsServerCommand } from "../lib/ttsApps"; +import "../lib/childKillGuard"; export type TtsServerHandle = { url: string; release: () => void }; diff --git a/common/controller/voiceFile.ts b/common/controller/voiceFile.ts @@ -88,6 +88,7 @@ import { getSettings } from "../lib/settings"; import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand"; import { corpusRootContaining, corpusRoots, realpathDeep } from "./transcribeFile"; import { enqueueTtsFile, resolveTtsRequest, ttsCacheKey } from "./ttsFile"; +import "../lib/childKillGuard"; export const VOICE_JOB_KIND: Record<VoiceOp, string> = { enhance: "voice-enhance", convert: "voice-convert" }; diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -402,10 +402,13 @@ class JobRegistry { job.abortController?.abort(); // Also abort the drain signal so any code awaiting a drain unblocks. job.drainController?.abort(); - if (job.child) { + // A child with no pid never started (its spawn failed): Node would + // signal this process's own group (lib/childKillGuard.ts). This module + // stays free of node imports, so the check is made here. + if (job.child && job.child.pid !== undefined) { job.child.kill("SIGTERM"); setTimeout(() => { - if (job.child && !job.child.killed) job.child.kill("SIGKILL"); + if (job.child && job.child.pid !== undefined && !job.child.killed) job.child.kill("SIGKILL"); }, 5_000).unref?.(); } return true; @@ -428,7 +431,7 @@ class JobRegistry { if (job) { job.abortController?.abort(); job.drainController?.abort(); - if (job.child && !job.child.killed) job.child.kill("SIGKILL"); + if (job.child && job.child.pid !== undefined && !job.child.killed) job.child.kill("SIGKILL"); if (job.status === "queued" || job.status === "running") { job.status = "cancelled"; job.endedAt = Date.now(); diff --git a/common/jobs/runChild.ts b/common/jobs/runChild.ts @@ -1,4 +1,5 @@ import { execa, type ResultPromise } from "execa"; +import "../lib/childKillGuard"; export type RunChildOpts = { command: string; diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -2,6 +2,7 @@ import path from "node:path"; import { mkdir } from "node:fs/promises"; import { createWriteStream, type WriteStream } from "node:fs"; import { execa } from "execa"; +import "../lib/childKillGuard"; import { getRegistry, newJobId, diff --git a/common/lib/archiveOrgTorrent-server.ts b/common/lib/archiveOrgTorrent-server.ts @@ -34,6 +34,7 @@ import { type ParsedTorrent, type TorrentFileEntry, } from "./archiveOrgTorrent"; +import "./childKillGuard"; // ─── Is aria2c here? ─── diff --git a/common/lib/childKillGuard.fixture.ts b/common/lib/childKillGuard.fixture.ts @@ -0,0 +1,74 @@ +// The fixture of childKillGuard.test.ts: run DETACHED (a process group of its +// own), it kills a child whose spawn failed and reports who was signalled — +// itself, and a sibling in its group. `guard` or `noguard`, then the case. +import { spawn } from "node:child_process"; +import os from "node:os"; +import path from "node:path"; + +const [guard, mode] = process.argv.slice(2); +if (guard === "guard") await import("./childKillGuard"); +const { execa } = await import("execa"); + +let selfSigterm = 0; +process.on("SIGTERM", () => { + selfSigterm++; +}); +let canarySignal: string | null = null; +const canary = spawn("sleep", ["30"], { stdio: "ignore" }); // same group as this process +canary.on("exit", (_c, s) => { + canarySignal = s; +}); +await new Promise((r) => setTimeout(r, 150)); + +const missing = path.join(os.tmpdir(), `no-such-dir-${process.pid}`, "gone"); +const notes: Record<string, unknown> = {}; +if (mode === "spawn-kill") { + const c = spawn("sleep", ["5"], { cwd: missing }); + c.on("error", () => {}); + notes.pid = c.pid ?? null; + notes.killed = c.kill("SIGTERM"); +} else if (mode === "execa-aborted") { + const ac = new AbortController(); + ac.abort(); + const p = execa("sleep", ["5"], { cwd: missing, cancelSignal: ac.signal, reject: false }); + notes.pid = p.pid ?? null; + const r = await p; + notes.failed = r.failed; +} else if (mode === "execa-kill") { + const p = execa("sleep", ["5"], { cwd: missing, reject: false }); + notes.pid = p.pid ?? null; + notes.killed = p.kill("SIGTERM"); + await p; +} else if (mode === "launcher-abort-after") { + // The download launcher over a channel directory that is gone, cancelled in + // the same tick it launched. + const { runOneYtdlp } = await import("../ytdlp/runOneYtdlp"); + const ac = new AbortController(); + const run = runOneYtdlp({ ytdlpBin: "sleep", onLog: () => {}, signal: ac.signal }, missing, ["5"]); + ac.abort(); + notes.outcome = await run; +} else if (mode === "launcher-aborted-before") { + // Already cancelled when asked to launch: nothing is spawned at all. + const { runOneYtdlp } = await import("../ytdlp/runOneYtdlp"); + const ac = new AbortController(); + ac.abort(); + const said: string[] = []; + notes.outcome = await runOneYtdlp({ ytdlpBin: "sleep", onLog: (l) => said.push(l), signal: ac.signal }, missing, ["5"]); + notes.said = said.length; +} else if (mode === "launcher-aborted-by-log") { + // Cancelled by the log sink, on the launch line itself. + const { runOneYtdlp } = await import("../ytdlp/runOneYtdlp"); + const ac = new AbortController(); + notes.outcome = await runOneYtdlp({ ytdlpBin: "sleep", onLog: () => ac.abort(), signal: ac.signal }, missing, ["5"]); +} else if (mode === "started-child") { + // The guard leaves a real child alone: it is killed as before. + const c = spawn("sleep", ["30"], { stdio: "ignore" }); + await new Promise((r) => setTimeout(r, 100)); + notes.killed = c.kill("SIGTERM"); + notes.signal = await new Promise((r) => c.on("exit", (_c, s) => r(s))); +} +await new Promise((r) => setTimeout(r, 400)); +const out = { selfSigterm, canarySignal, ...notes }; +canary.kill("SIGKILL"); +console.log(JSON.stringify(out)); +process.exit(0); diff --git a/common/lib/childKillGuard.test.ts b/common/lib/childKillGuard.test.ts @@ -0,0 +1,129 @@ +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<Report> { + 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<string[]> { + 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); +}); diff --git a/common/lib/childKillGuard.ts b/common/lib/childKillGuard.ts @@ -0,0 +1,42 @@ +// A KILL ON A CHILD THAT NEVER STARTED IS A NO-OP — process-wide. +// +// Node's ChildProcess.kill() is `this._handle.kill(signal)` with no look at +// `this.pid`. When a spawn FAILS (the binary is not there, the cwd is gone) +// Node keeps the handle until the next tick, with no pid in it, and a kill in +// that window signals pid 0: THE CALLER'S OWN PROCESS GROUP. Verified on Node +// 22.23.5 (12 Nov 2026) with a group leader, a missing cwd and +// · spawn(...).kill("SIGTERM") in the same tick, +// · execa(..., { cancelSignal }) with a signal that is already aborted, +// · execa(...).kill("SIGTERM") in the same tick: +// in each the caller and a sibling in its group received SIGTERM, and with +// the same aborted signal and a cwd that exists, neither did. That is what +// took the editor's test server down (and pnpm with it, "Command failed with +// signal SIGTERM") whenever a download was cancelled while its channel +// directory was being removed — and it would do the same to a live editor. +// +// execa kills from inside itself (cancelSignal, timeout, forceKillAfterDelay), +// so no call site can guard that: the guard is on the prototype. Importing +// this module installs it; every module of common/ that spawns with a +// `cancelSignal` or calls `.kill()` on a child imports it (the test +// lib/childKillGuard.test.ts holds them to it). Idempotent, and per process: +// the mark is on the prototype, which Next's two module graphs share. + +import { ChildProcess } from "node:child_process"; + +const MARK = Symbol.for("archilyzer.childKillGuard"); +type Guarded = { [MARK]?: true; kill: ChildProcess["kill"] }; + +export function installChildKillGuard(): void { + const proto = ChildProcess.prototype as unknown as Guarded; + if (proto[MARK]) return; + const kill = proto.kill; + proto.kill = function guardedKill(this: ChildProcess, signal?: NodeJS.Signals | number): boolean { + // No pid: the spawn failed (or has not happened). There is nothing to + // signal, and the handle would signal the group. + if (this.pid === undefined) return false; + return kill.call(this, signal); + }; + proto[MARK] = true; +} + +installChildKillGuard(); diff --git a/common/lib/clipWindowSync-server.ts b/common/lib/clipWindowSync-server.ts @@ -22,6 +22,7 @@ import { type ProbedWindowStream, type RecordedClipWindowSync, } from "./clipWindowSync"; +import "./childKillGuard"; // A window's streams, or null when they cannot be read. Injectable so tests // decide what a window holds without a real one. diff --git a/common/lib/digestApps.ts b/common/lib/digestApps.ts @@ -27,6 +27,7 @@ import { type DigestAppConfig, type DigestLane, } from "./digest"; +import "./childKillGuard"; // The lane type, the app ids and DigestAppConfig are defined in the client-safe // digest.ts and re-exported here, so settings.ts can consume them without diff --git a/common/lib/evidenceClip-server.ts b/common/lib/evidenceClip-server.ts @@ -57,6 +57,7 @@ import { resolveCorpusSource, } from "./evidenceClip.mjs"; import { resolveVideoDir } from "./videoDir-server.mjs"; +import "./childKillGuard"; // Bumped whenever the arguments below change what a clip looks like: it is in // every hash, so a new profile re-cuts rather than serving an old file. diff --git a/common/lib/livePreclip-server.ts b/common/lib/livePreclip-server.ts @@ -30,6 +30,7 @@ import { clipWindowFile, type ClipProvenance } from "./clipWindow"; import { clipWindowPath, writeClipProvenance, type ClipWindow } from "./clipWindow-server"; import { tmpPathFor } from "./jsonFile-server"; import { decodeSpan } from "./montage/voiceMatch.mjs"; +import "./childKillGuard"; export const liveTranscriptSidecar = sidecar(LIVE_TRANSCRIPT_FILENAME, sidecarField(coerceLiveTranscript), { indent: 0 }); export const livePreclipSidecar = sidecar(LIVE_PRECLIP_FILENAME, sidecarField(coerceLivePreclipState)); diff --git a/common/lib/recordingClock-server.ts b/common/lib/recordingClock-server.ts @@ -46,6 +46,7 @@ import { savedVideoPath, type SavedVideoPointer } from "./savedVideo"; import { coerceMediaImport, MEDIA_IMPORT_FILENAME } from "./mediaImport"; import { readJsonFile } from "./jsonFile-server"; import { loadTranscribeOutcome } from "./transcribeOutcome-server"; +import "./childKillGuard"; export const recordingClockSidecar = sidecar(CLOCK_FILE, sidecarField(coerceRecordingClock), { indent: 2 }); diff --git a/common/lib/savedVideoWindow-server.ts b/common/lib/savedVideoWindow-server.ts @@ -54,6 +54,7 @@ import { isDriveNotAnswering, onDrive } from "./storageHealth"; import type { Paths } from "./paths"; import { clockForContainer } from "./recordingClock-read.mjs"; import { mapSpan, type RecordingClock } from "./recordingClock.mjs"; +import "./childKillGuard"; // A window cut from a container is seconds of re-encoding; a whole container // on a platter seeks once. Generous, so only a wedged ffmpeg reaches it — diff --git a/common/lib/storageVolumes.ts b/common/lib/storageVolumes.ts @@ -18,6 +18,7 @@ import { type LocationHealthState, } from "./storageHealth"; import { counterSampleMinimumMs, secondsText } from "./storageHealthTimings"; +import "./childKillGuard"; // STORAGE VOLUME PROBES — is this location's disk here, and if not, where? // diff --git a/common/publish/reportExports.ts b/common/publish/reportExports.ts @@ -114,6 +114,7 @@ import { storeHistoryGitDir, revisionExports, } from "./reportHistory"; +import "../lib/childKillGuard"; // A still or a screenshot in report.html: at most this wide, recompressed. export const EXPORT_IMAGE_MAX_WIDTH = 1200; diff --git a/common/publish/sourceAudit.ts b/common/publish/sourceAudit.ts @@ -31,6 +31,7 @@ import os from "node:os"; import path from "node:path"; import { gunzipSync } from "node:zlib"; import { runChildIntoLog } from "../jobs/runChild"; +import "../lib/childKillGuard"; /** A refusal: the step stops, publishes nothing, and says why. */ export class SourceRefusal extends Error { diff --git a/common/social/xGalleryDlFetcher.ts b/common/social/xGalleryDlFetcher.ts @@ -70,6 +70,7 @@ import { type OnePostFetchInput, type OnePostFetchResult, } from "./fetchers"; +import "../lib/childKillGuard"; // "Are we still logged in?" — classified line by line in xGalleryDlSignals.ts // (pure, unit-tested on gallery-dl's real messages): a challenge, a login diff --git a/common/ytdlp/abortedBeforeLaunch.test.ts b/common/ytdlp/abortedBeforeLaunch.test.ts @@ -0,0 +1,85 @@ +// A run that is already cancelled launches nothing (lib/childKillGuard.ts says +// why execa must never be handed an aborted signal): the fake yt-dlp below +// leaves a file behind when it runs, and none is left. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/abortedBeforeLaunch.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { chmod, mkdir, mkdtemp, rm, stat, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { runAudioCheckedYtdlp } from "./audioCheckedDownload"; +import { runOneYtdlp } from "./runOneYtdlp"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; + +const ROOT = await mkdtemp(path.join(os.tmpdir(), "aborted-launch-")); +const RAN = path.join(ROOT, "ran"); +const YTDLP = path.join(ROOT, "fake-ytdlp.mjs"); +await writeFile(YTDLP, `#!/usr/bin/env node\nimport { writeFileSync } from "node:fs";\nwriteFileSync(${JSON.stringify(RAN)}, "ran");\n`); +await chmod(YTDLP, 0o755); +const ran = () => stat(RAN).then(() => true, () => false); +const aborted = () => { + const ac = new AbortController(); + ac.abort(); + return ac.signal; +}; + +test("runOneYtdlp: aborted before launch spawns nothing and logs nothing", async () => { + const said: string[] = []; + const out = await runOneYtdlp({ ytdlpBin: YTDLP, onLog: (l) => said.push(l), signal: aborted() }, ROOT, ["--version"]); + assert.deepEqual(out, { exitCode: null, stderrTail: "", archiveLine: null, formatLine: null }); + assert.deepEqual(said, []); + await new Promise((r) => setTimeout(r, 300)); + assert.equal(await ran(), false, "the fake yt-dlp never ran"); +}); + +test("runOneYtdlp: the same launch, not cancelled, does run (the fake is a real control)", async () => { + const out = await runOneYtdlp({ ytdlpBin: YTDLP, onLog: () => {}, signal: new AbortController().signal }, ROOT, ["--version"]); + assert.equal(out.exitCode, 0); + assert.equal(await ran(), true); + await rm(RAN, { force: true }); +}); + +test("the audio-checked download: aborted before launch is `aborted`, and yt-dlp never ran — over a channel directory that is gone, too", async () => { + for (const channelDir of [path.join(ROOT, "channel"), path.join(ROOT, "removed", "channel")]) { + if (channelDir.includes("/channel") && !channelDir.includes("removed")) await mkdir(path.join(channelDir, "data"), { recursive: true }); + const said: string[] = []; + const out = await runAudioCheckedYtdlp({ + paths: { ytdlpBin: YTDLP, ffmpegBin: "ffmpeg" } as unknown as Paths, + channelDir, + channelConfig: {} as ChannelConfig, + ytdlpArgs: ["--version"], + onLog: (l) => said.push(l), + signal: aborted(), + archiveMarker: "DLOM_ARCHIVE", + expectedVideoIdHint: "vid0000001", + }); + assert.equal(out.kind, "aborted"); + assert.ok(!said.some((l) => l.startsWith("$ ")), "no launch line"); + } + await new Promise((r) => setTimeout(r, 300)); + assert.equal(await ran(), false, "the fake yt-dlp never ran"); +}); + +test("the audio-checked download: cancelled by the log sink on the launch line, yt-dlp is not spawned", async () => { + const channelDir = path.join(ROOT, "channel-log"); + await mkdir(path.join(channelDir, "data"), { recursive: true }); + const ac = new AbortController(); + const out = await runAudioCheckedYtdlp({ + paths: { ytdlpBin: YTDLP, ffmpegBin: "ffmpeg" } as unknown as Paths, + channelDir, + channelConfig: {} as ChannelConfig, + ytdlpArgs: ["--version"], + onLog: (l) => { + if (l.startsWith("$ ")) ac.abort(); + }, + signal: ac.signal, + archiveMarker: "DLOM_ARCHIVE", + expectedVideoIdHint: "vid0000001", + }); + assert.equal(out.kind, "aborted"); + await new Promise((r) => setTimeout(r, 300)); + assert.equal(await ran(), false, "the fake yt-dlp never ran"); +}); diff --git a/common/ytdlp/audioCheckedDownload.ts b/common/ytdlp/audioCheckedDownload.ts @@ -53,6 +53,7 @@ import type { StreamVerdict } from "./ffmpegStreamClassify"; import { probeAudioStream } from "./ffmpegStreamProbe"; import { DLOM_PROBE_MARKER } from "../jobs/progressParsers"; import { jitterYtdlpSleeps } from "../lib/jitter"; +import "../lib/childKillGuard"; const STDERR_TAIL_BYTES = 64 * 1024; const DEFAULT_SIZE_GATE_BYTES = 1024 * 1024; // 1 MiB minimum growth between checks @@ -843,23 +844,35 @@ export async function runAudioCheckedYtdlp( // Derived AbortController: when the caller aborts, we first send // SIGCONT (in case the child is suspended) and then forward to execa. const launchAc = new AbortController(); + // The launched child's pid, once there is one: an abort that arrives + // before the spawn (the log sink below may cancel) has nothing to resume. + let launchedPid: number | undefined; const onParentAbort = () => { - if (child?.pid) { + if (launchedPid) { try { - process.kill(child.pid, "SIGCONT"); + process.kill(launchedPid, "SIGCONT"); } catch {} } launchAc.abort(); }; + // Already cancelled: nothing is launched. execa must never be handed a + // signal that is already aborted — it kills the child at once, and a + // child whose spawn failed (the channel directory removed under a + // cancelled job) has no pid: that kill reaches this process's own group + // (lib/childKillGuard.ts). if (opts.signal.aborted) { - launchAc.abort(); - } else { - opts.signal.addEventListener("abort", onParentAbort, { once: true }); + return { kind: "aborted", exitCode: null, stderrTail: "", archiveLine: null, videoDir: resolvedVideoDir }; } + opts.signal.addEventListener("abort", onParentAbort, { once: true }); // The fixed waits drawn once for this run (lib/jitter.mjs). const spawned = jitterYtdlpSleeps(opts.ytdlpArgs); opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`); + // (A log sink may cancel: asked again at the last moment before the spawn.) + if (launchAc.signal.aborted) { + opts.signal.removeEventListener?.("abort", onParentAbort); + return { kind: "aborted", exitCode: null, stderrTail: "", archiveLine: null, videoDir: resolvedVideoDir }; + } const child = execa(opts.paths.ytdlpBin, spawned, { cwd: opts.channelDir, cancelSignal: launchAc.signal, @@ -867,6 +880,7 @@ export async function runAudioCheckedYtdlp( buffer: false, reject: false, }); + launchedPid = child.pid; let stderrTail = ""; child.stderr?.on("data", (c: Buffer) => { @@ -1203,9 +1217,11 @@ export async function runAudioCheckedYtdlp( process.kill(child.pid, "SIGCONT"); } catch {} } - try { - child.kill("SIGTERM"); - } catch {} + if (child.pid) { + try { + child.kill("SIGTERM"); + } catch {} + } try { await exitPromise; } catch {} diff --git a/common/ytdlp/ffmpegStreamProbe.ts b/common/ytdlp/ffmpegStreamProbe.ts @@ -3,6 +3,7 @@ import { classifyFfmpegProbe, type StreamVerdict, } from "./ffmpegStreamClassify"; +import "../lib/childKillGuard"; export type ProbeAudioStreamOptions = { ffmpegBin: string; diff --git a/common/ytdlp/ffprobeDuration.ts b/common/ytdlp/ffprobeDuration.ts @@ -1,4 +1,5 @@ import { execa } from "execa"; +import "../lib/childKillGuard"; export type ProbeMediaDurationOptions = { ffprobeBin: string; diff --git a/common/ytdlp/metadataScan.ts b/common/ytdlp/metadataScan.ts @@ -49,6 +49,7 @@ import { type MetadataScanRun, } from "../controller/metadataScanStore"; import { jitterYtdlpSleeps } from "../lib/jitter"; +import "../lib/childKillGuard"; // yt-dlp's JSON-subset print template: one JSON object per entry, so the scan // parses lines instead of whole info jsons — and so nothing is ever written to diff --git a/common/ytdlp/runOneYtdlp.ts b/common/ytdlp/runOneYtdlp.ts @@ -13,6 +13,7 @@ import { execa } from "execa"; import type { Paths } from "../lib/paths"; import { observeYtdlpServiceOutcome } from "../lib/serviceCookies-server"; import { jitterYtdlpSleeps } from "../lib/jitter"; +import "../lib/childKillGuard"; export const STDERR_TAIL_BYTES = 64 * 1024; @@ -57,9 +58,17 @@ export async function runOneYtdlp( cwd: string, args: string[], ): Promise<AttemptOutcome> { + // Already cancelled: nothing is launched (and no request is made). execa + // handed an aborted signal kills the child at once, and one whose spawn + // failed — `cwd` removed under a cancelled job — has no pid: that kill + // reaches this process's own group (lib/childKillGuard.ts). The outcome is + // the one a child killed at launch gave: no exit code, the signal aborted. + if (opts.signal.aborted) return { exitCode: null, stderrTail: "", archiveLine: null, formatLine: null }; // The fixed waits drawn once for this run (lib/jitter.mjs). const spawned = jitterYtdlpSleeps(args); opts.onLog(`$ ${opts.ytdlpBin} ${spawned.join(" ")}\n`); + // (A log sink may cancel: asked again at the last moment before the spawn.) + if (opts.signal.aborted) return { exitCode: null, stderrTail: "", archiveLine: null, formatLine: null }; const child = execa(opts.ytdlpBin, spawned, { cwd, cancelSignal: opts.signal, diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -112,6 +112,7 @@ import { skippedShortIds, skipsAsShort, } from "../lib/skipShorts"; +import "../lib/childKillGuard"; export type YtdlpMode = | "store-playlist" @@ -2404,6 +2405,10 @@ async function runChildAndStream( cwd: string, args: string[], ): Promise<string> { + // Already cancelled: nothing is launched, no request counted (as + // runOneYtdlp; lib/childKillGuard.ts says why execa is never handed an + // aborted signal). The caller gates on the signal, as after a killed child. + if (opts.signal.aborted) return ""; const spawned = jitterYtdlpSleeps(args); opts.onLog(`$ ${opts.paths.ytdlpBin} ${spawned.join(" ")}\n`); if (opts.requestCounter) opts.requestCounter.n++;