diff --git a/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md b/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md new file mode 100644 index 00000000000..26c0768bcb6 --- /dev/null +++ b/.changes/knowledge/fix-video-digest-watch-signal-cleanup-6920a1c4.md @@ -0,0 +1,7 @@ +--- +bump: patch +--- + +### Fixed + +- `video-digest` `run-watch.js` now removes its temp video, frame and sheet directories when SIGHUP, SIGINT or SIGTERM interrupts a watch before `watch.json` records them, then exits `129`, `130` or `143`. On POSIX the interrupt kills each child's whole process group, so a yt-dlp ffmpeg grandchild ends too; on Windows only direct children are killed. Cleanup runs once, and the handlers are removed when the run ends. diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal-watching.test.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal-watching.test.js new file mode 100644 index 00000000000..751661e3952 --- /dev/null +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal-watching.test.js @@ -0,0 +1,110 @@ +/** + * A signal that lands while frame extraction runs stops the watch before it writes + * anything from the killed work: no watching manifest, and the run reports failure. + * The signal handler is invoked in-process, with process.exit stubbed. + */ + +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +import { createAcquisitionEnvelope } from "../adapters/adapter-contract.js"; +import { acquireMedia } from "../adapters/registry.js"; +import { orchestrateWatching } from "../watching/orchestrate-watching.js"; +import { writeWatchingManifest } from "../watching/write-watching-manifest.js"; +import { runWatchCli } from "./run-watch.js"; + +vi.mock("@melodic/video-digestion/shared/terminal", () => ({ + writeStderr: () => {}, + writeStdout: () => {}, +})); + +vi.mock("../adapters/registry.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, acquireMedia: vi.fn() }; +}); + +vi.mock("../transcript/asr-transcribe.js", async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, detectAsrCapability: vi.fn(async () => ({ available: false })) }; +}); + +vi.mock("../watching/orchestrate-watching.js", () => ({ orchestrateWatching: vi.fn() })); + +vi.mock("../watching/write-watching-manifest.js", () => ({ + writeWatchingManifest: vi.fn(async () => ({ + selectionPath: "selection.json", + coveragePlanPath: "coverage-plan.json", + frameCount: 0, + contactSheetCount: 0, + })), +})); + +const URL = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"; +const ENV_KEYS = ["TMPDIR", "TEMP", "TMP"]; + +/** @type {string} */ +let sandbox; +/** @type {Record} */ +let savedEnv; + +describe("run-watch interrupted during frame extraction", () => { + beforeEach(async () => { + sandbox = await fs.mkdtemp(path.join(os.tmpdir(), "watch-signal-watching-")); + const fakeTmp = path.join(sandbox, "tmp"); + await fs.mkdir(fakeTmp); + savedEnv = Object.fromEntries(ENV_KEYS.map((key) => [key, process.env[key]])); + for (const key of ENV_KEYS) process.env[key] = fakeTmp; + process.env.YOUTUBE_WORK_ROOT = path.join(sandbox, "work"); + vi.mocked(acquireMedia).mockReset(); + vi.mocked(orchestrateWatching).mockReset(); + vi.mocked(writeWatchingManifest).mockClear(); + vi.spyOn(process, "exit").mockImplementation(/** @type {any} */ (() => undefined)); + }); + + afterEach(async () => { + vi.restoreAllMocks(); + for (const [key, value] of Object.entries(savedEnv)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + delete process.env.YOUTUBE_WORK_ROOT; + await fs.rm(sandbox, { recursive: true, force: true }); + }); + + it("writes no watching manifest and returns 1 when SIGTERM lands mid-extraction", async () => { + vi.mocked(acquireMedia).mockImplementation(async (_url, { workDir }) => { + const mediaPath = path.join(workDir, "dQw4w9WgXcQ.mp4"); + const metadataPath = path.join(workDir, "dQw4w9WgXcQ.info.json"); + await fs.writeFile(mediaPath, "binary"); + await fs.writeFile(metadataPath, "{}"); + return { + success: true, + data: createAcquisitionEnvelope({ + entries: [{ mediaPath, captionPaths: [], metadataPath, caption: null }], + metadata: { id: "dQw4w9WgXcQ", title: "Fixture Talk", description: "", chapters: [], comments: [] }, + workDir, + }), + }; + }); + vi.mocked(orchestrateWatching).mockImplementation(async () => { + const handler = /** @type {() => void} */ (process.listeners("SIGTERM").at(-1)); + handler(); + // A killed ffmpeg leaves a degraded result rather than a rejection. + return /** @type {any} */ ({ + selectedFrames: [], + targetMinFrames: 0, + highVolume: false, + candidateCount: 0, + probedDurationSec: null, + densificationWindows: [], + }); + }); + + expect(await runWatchCli(["node", "run-watch.js", URL])).toBe(1); + expect(vi.mocked(orchestrateWatching)).toHaveBeenCalledOnce(); + expect(vi.mocked(writeWatchingManifest)).not.toHaveBeenCalled(); + }); +}); diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js new file mode 100644 index 00000000000..1950802d648 --- /dev/null +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch-signal.test.js @@ -0,0 +1,135 @@ +/** + * A watch killed by SIGHUP, SIGINT or SIGTERM during acquisition removes the temp dirs it + * made and exits with the conventional signal code. A real child run is used: a + * fake `yt-dlp` on PATH blocks the acquisition so the signal lands mid-download. + * POSIX only (the fake yt-dlp is a shell script). + */ + +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import fs from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { afterEach, beforeEach, describe, expect, it } from "vitest"; + +const RUN_WATCH = fileURLToPath(new URL("./run-watch.js", import.meta.url)); +const URL_UNDER_TEST = "https://www.youtube.com/watch?v=dQw4w9WgXcQ"; +const TEMP_PREFIXES = ["video-extraction-", "video-frames-", "video-sheets-"]; + +/** @type {string} */ +let sandbox; +/** @type {string} */ +let fakeTmp; +/** @type {string} */ +let started; + +async function watchTempDirs() { + const names = await fs.readdir(fakeTmp); + return names.filter((name) => TEMP_PREFIXES.some((prefix) => name.startsWith(prefix))); +} + +async function waitFor(predicate, timeoutMs = 20_000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + if (await predicate()) return; + await new Promise((resolve) => setTimeout(resolve, 50)); + } + throw new Error("timed out waiting for the child to reach acquisition"); +} + +describe.skipIf(process.platform === "win32")("run-watch interrupted by a signal", () => { + beforeEach(async () => { + sandbox = await fs.mkdtemp(path.join(os.tmpdir(), "watch-signal-")); + fakeTmp = path.join(sandbox, "tmp"); + const bin = path.join(sandbox, "bin"); + started = path.join(sandbox, "yt-dlp-started"); + await fs.mkdir(fakeTmp); + await fs.mkdir(bin); + await fs.writeFile( + path.join(bin, "yt-dlp"), + // Keeps writing into the work dir, as a real download would, so a signal that + // leaves it running races the cleanup and recreates files after the rm. + `#!/bin/sh\ntouch "${started}"\nwhile :; do\n for d in "$TMPDIR"/video-extraction-*; do\n [ -d "$d" ] && echo x >> "$d/partial.part"\n done\n sleep 0.05\ndone\n`, + { mode: 0o755 }, + ); + }); + + afterEach(async () => { + await fs.rm(sandbox, { recursive: true, force: true }); + }); + + it.each([ + ["SIGTERM", 143], + ["SIGINT", 130], + ])("%s removes the temp dirs and exits %i", async (signal, exitCode) => { + const child = spawn(process.execPath, [RUN_WATCH, URL_UNDER_TEST], { + env: { + ...process.env, + PATH: `${path.join(sandbox, "bin")}${path.delimiter}${process.env.PATH}`, + TMPDIR: fakeTmp, + VIDEO_DIGEST_WORK_ROOT: path.join(sandbox, "work"), + }, + stdio: "ignore", + }); + const exited = new Promise((resolve) => child.on("exit", (code, sig) => resolve({ code, sig }))); + + await waitFor(() => existsSync(started)); + expect(await watchTempDirs()).toHaveLength(3); + + child.kill(signal); + expect(await exited).toEqual({ code: exitCode, sig: null }); + expect(await watchTempDirs()).toEqual([]); + // A surviving fake yt-dlp would recreate the work dir's file within one tick. + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(await watchTempDirs()).toEqual([]); + }); + + it.each([ + ["SIGTERM", 143], + ["SIGHUP", 129], + ])("%s also ends a grandchild the yt-dlp child started", async (signal, exitCode) => { + const grandPid = path.join(sandbox, "grandchild.pid"); + // A real yt-dlp runs ffmpeg as its own child; this one leaves a writer looping + // in the background, which outlives a SIGKILL sent to yt-dlp alone. + await fs.writeFile( + path.join(sandbox, "bin", "yt-dlp"), + `#!/bin/sh\n( while :; do\n for d in "$TMPDIR"/video-extraction-*; do\n [ -d "$d" ] && echo x >> "$d/merge.part"\n done\n sleep 0.05\ndone ) &\necho $! > "${grandPid}"\ntouch "${started}"\nwait\n`, + { mode: 0o755 }, + ); + const child = spawn(process.execPath, [RUN_WATCH, URL_UNDER_TEST], { + env: { + ...process.env, + PATH: `${path.join(sandbox, "bin")}${path.delimiter}${process.env.PATH}`, + TMPDIR: fakeTmp, + VIDEO_DIGEST_WORK_ROOT: path.join(sandbox, "work"), + }, + stdio: "ignore", + }); + const exited = new Promise((resolve) => child.on("exit", (code, sig) => resolve({ code, sig }))); + + await waitFor(() => existsSync(started)); + const pid = Number(await fs.readFile(grandPid, "utf8")); + const alive = () => { + try { + process.kill(pid, 0); + return true; + } catch { + return false; + } + }; + try { + child.kill(signal); + expect(await exited).toEqual({ code: exitCode, sig: null }); + await waitFor(() => !alive(), 2_000).catch(() => {}); + expect(alive()).toBe(false); + await new Promise((resolve) => setTimeout(resolve, 300)); + expect(await watchTempDirs()).toEqual([]); + } finally { + if (alive()) process.kill(pid, "SIGKILL"); + } + // A surviving grandchild holds yt-dlp's pipes open, so the run waits out its + // settle window before exiting; the timeout leaves room for that failure. + }, 30_000); +}); diff --git a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js index df7be4ecc1a..a0f11a9be69 100755 --- a/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js +++ b/plugins/knowledge/skills/video-digest/extraction/watch/run-watch.js @@ -22,7 +22,9 @@ * Vision absorption, research, and synthesis run in the skill session (not this script). */ +import childProcess from "node:child_process"; import fs from "node:fs/promises"; +import { syncBuiltinESMExports } from "node:module"; import os from "node:os"; import path from "node:path"; @@ -139,18 +141,118 @@ export async function runWatchCli(argv) { // Until watch.json records the temp dirs, nothing else points at them, so a // failure removes the ones this run made. Once recorded, --recover needs them. /** @type {TempDirs} */ - const temp = { dirs: {}, recorded: false }; + const temp = { dirs: {}, recorded: false, interrupted: false }; + const children = trackChildren(temp); + // The signal handlers and the finally block share one cleanup, so it runs once. + /** @type {Promise | null} */ + let cleanup = null; + const cleanUpOnce = () => { + cleanup ??= temp.recorded + ? Promise.resolve() + : removeRecordedTempSessionDirs(temp.dirs, "watch"); + return cleanup; + }; + /** @type {Promise | null} */ + let running = null; + const signalHandlers = Object.entries(SIGNAL_EXIT_CODES).map(([signal, code]) => { + const handler = () => { + // Stop the work first: end the yt-dlp/ffmpeg children and flag the run so + // watchUrl creates and records nothing more. The dirs go only once watchUrl + // has settled, so nothing is still writing into them or creating them. + children.interrupt(); + const settled = Promise.race([ + Promise.resolve(running).catch(() => {}), + new Promise((resolve) => setTimeout(resolve, INTERRUPT_SETTLE_MS).unref()), + ]); + settled.then(cleanUpOnce).finally(() => process.exit(code)); + }; + process.on(signal, handler); + return /** @type {const} */ ([signal, handler]); + }); try { - return await watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFrameGapSec, temp }); + running = watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFrameGapSec, temp }); + return await running; + } catch (error) { + if (error instanceof InterruptedError) return 1; + throw error; } finally { - if (!temp.recorded) await removeRecordedTempSessionDirs(temp.dirs, "watch"); + for (const [signal, handler] of signalHandlers) process.off(signal, handler); + children.stop(); + await cleanUpOnce(); + } +} + +/** Conventional exit code (128 + signal number) for each signal the watch cleans up on. */ +const SIGNAL_EXIT_CODES = { SIGHUP: 129, SIGINT: 130, SIGTERM: 143 }; + +/** Longest the signal handler waits for watchUrl to wind down before removing the dirs anyway. */ +const INTERRUPT_SETTLE_MS = 10_000; + +class InterruptedError extends Error { + constructor() { + super("watch interrupted"); + this.name = "InterruptedError"; } } +/** + * Track every child the run spawns (yt-dlp, ffmpeg, ...) so a signal can end them. + * The shared spawn helper keeps no handle on its children, so `spawn` is wrapped + * for the life of the run; once interrupted, a child spawned late is ended at once. + * On POSIX each child leads its own process group and the whole group is killed, + * so yt-dlp's ffmpeg goes with it. On Windows only the direct child is killed, and + * a grandchild can outlive the interrupt. + * + * @param {TempDirs} temp + */ +function trackChildren(temp) { + const originalSpawn = childProcess.spawn; + const groups = process.platform !== "win32"; + /** @type {Set} */ + const live = new Set(); + /** @param {import('node:child_process').ChildProcess} child */ + const kill = (child) => { + if (groups && child.pid) { + try { + process.kill(-child.pid, "SIGKILL"); + return; + } catch { + // The group is already gone; fall through to the direct kill. + } + } + child.kill("SIGKILL"); + }; + childProcess.spawn = /** @type {typeof childProcess.spawn} */ ( + function trackedSpawn(command, ...rest) { + if (groups) { + const at = rest[0] == null || Array.isArray(rest[0]) ? 1 : 0; + rest[at] = { ...rest[at], detached: true }; + } + const child = originalSpawn.call(this, command, ...rest); + live.add(child); + child.once("close", () => live.delete(child)); + if (temp.interrupted) kill(child); + return child; + } + ); + syncBuiltinESMExports(); + return { + interrupt() { + temp.interrupted = true; + for (const child of live) kill(child); + }, + stop() { + childProcess.spawn = originalSpawn; + syncBuiltinESMExports(); + }, + }; +} + /** * @typedef {Object} TempDirs * @property {{ workDir?: string, framesDir?: string, contactSheetsDir?: string }} dirs - created by this run * @property {boolean} recorded - true once watch.json holds them as tempSession + * @property {boolean} interrupted - set by a signal; watchUrl then creates and records nothing more */ /** @@ -165,13 +267,20 @@ export async function runWatchCli(argv) { * }} options */ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFrameGapSec, temp }) { + const throwIfInterrupted = () => { + if (temp.interrupted) throw new InterruptedError(); + }; + throwIfInterrupted(); // Temp dirs retained for vision reads in the same session; regen via run-watch when missing. const workDir = await fs.mkdtemp(path.join(os.tmpdir(), "video-extraction-")); temp.dirs.workDir = workDir; + throwIfInterrupted(); const framesDir = await fs.mkdtemp(path.join(os.tmpdir(), "video-frames-")); temp.dirs.framesDir = framesDir; + throwIfInterrupted(); const sheetsDir = await fs.mkdtemp(path.join(os.tmpdir(), "video-sheets-")); temp.dirs.contactSheetsDir = sheetsDir; + throwIfInterrupted(); /** @type {import('../adapters/adapter-contract.js').AcquireOutcome} */ let acquisition; @@ -185,6 +294,7 @@ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFr } throw error; } + throwIfInterrupted(); if (!acquisition.success || !acquisition.data) { writeStderr(acquisition.error ?? "Acquisition failed"); return 1; @@ -283,6 +393,7 @@ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFr next = markPhaseComplete(next, "research", { skipped: true }); } + throwIfInterrupted(); await writeWatchState(sliceDir, next); temp.recorded = true; const continuationPrompt = await writeContinuationPrompt(sliceDir, next); @@ -360,8 +471,10 @@ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFr // detectRecoverableBootstrap can discover (it requires the file to exist). state.status = "watching"; writeStderr("watch: watching start"); + throwIfInterrupted(); await writeWatchState(sliceDir, state); temp.recorded = true; + throwIfInterrupted(); const watching = await orchestrateWatching({ videoPath: primary.mediaPath, @@ -370,6 +483,8 @@ async function watchUrl({ url, adapter, skipResearch, target, strategyArg, maxFr cues, maxFrameGapSec, }); + // A killed ffmpeg yields a degraded result, not a rejection: write nothing from it. + throwIfInterrupted(); state.status = "vision"; state.frameSelection = {