import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { JobMeta } from "./jobMeta"; import type { JobSpec } from "./jobSpec"; import { INTERRUPTED_REASON, settleRunningJobMetas, type RequeueFn } from "./bootQueuedJobs"; import { getRegistry } from "./registry"; import { runManagedFunction } from "./streamCommand"; import { settleJob } from "../testing/jobs/quiesce"; import { MAX_RESUMES_IN_A_ROW, RESUME_WINDOW_MS, resumeInterruptedJobs, resumeSpecFor, } from "./resumeInterrupted"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/resumeInterrupted.test.ts // // RESUME WHAT A RESTART INTERRUPTED (2026-10-26), over a temp .jobs dir. A // kind that declares `resumeOnBoot` is re-queued through the injected re-queue // (the editor's is runJobSpec), once; everything else is said and left. // Never run against a real corpus. const NOW = 2_000_000_000_000; async function fixture(metas: Partial[]) { const root = await mkdtemp(path.join(tmpdir(), "resume-interrupted-")); const jobsDir = path.join(root, ".jobs"); await mkdir(jobsDir, { recursive: true }); for (const m of metas) { const meta = { queueKey: "platform:archiveorg", status: "cancelled", cancelReason: INTERRUPTED_REASON, queuedAt: NOW - 3_600_000, endedAt: NOW - 60_000, ...m, }; await writeFile(path.join(jobsDir, `${meta.id}.meta.json`), JSON.stringify(meta)); } const paths = { jobsDir } as Paths; return { paths, root, read: async (id: string) => JSON.parse(await readFile(path.join(jobsDir, `${id}.meta.json`), "utf8")) as JobMeta, log: (id: string) => readFile(path.join(jobsDir, `${id}.log`), "utf8").catch(() => ""), }; } function recorder(answer: (spec: JobSpec, n: number) => Awaited> = (_s, n) => ({ ok: true, jobId: `NEW${n}` })) { const calls: JobSpec[] = []; const requeue: RequeueFn = async (spec) => { calls.push(spec); return answer(spec, calls.length); }; return { calls, requeue }; } const importSpec: JobSpec = { kind: "import-archive-org", slug: "h3", params: { item: "h3-episodes", match: "\\.mp3$" } }; test("an interrupted archive.org import is re-queued once, and its meta says by whom", async () => { const fx = await fixture([{ id: "A1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec }]); try { const { calls, requeue } = recorder(); const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["A1"], now: NOW }); assert.deepEqual(out, [{ id: "A1", kind: "import-archive-org", channelSlug: "h3", action: "resumed", newId: "NEW1" }]); assert.deepEqual(calls, [importSpec]); const meta = await fx.read("A1"); assert.equal(meta.resumedAs, "NEW1"); assert.equal(meta.cancelReason, `${INTERRUPTED_REASON}; resumed as NEW1`); assert.match(await fx.log("A1"), /\[resume\] resumed as NEW1/); // Never twice: the second pass finds it resumed. const again = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["A1"], now: NOW }); assert.deepEqual(again, []); assert.equal(calls.length, 1); } finally { await rm(fx.root, { recursive: true, force: true }); } }); test("the resumed job carries the chain, and its log opens with what it resumes", async () => { const fx = await fixture([ { id: "R1", kind: "refresh-report", queueKey: "refresh-report", channelSlug: "h3", spec: { kind: "refresh-report", slug: "h3" } }, ]); try { let newId = ""; const requeue: RequeueFn = async (spec) => { const res = await runManagedFunction({ kind: spec.kind, queueKey: "test-resume-chain", paths: fx.paths, channelSlug: spec.slug, spec, fn: async (onLog) => onLog("walked"), }); if (!res.ok) return { ok: false, error: res.error }; newId = res.jobId; await res.done; return { ok: true, jobId: res.jobId }; }; const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["R1"], now: NOW }); assert.equal(out[0].action, "resumed"); const record = getRegistry().get(newId); assert.equal(record?.resumedFrom, "R1"); assert.equal(record?.resumeCount, 1); const log = await fx.log(newId); assert.match(log.split("\n")[0], /^\[resume\] Resumes refresh-report job R1 on h3, interrupted when the process running it stopped: the channel's report is regenerated\.$/); // On disk too, for the next boot. (`done` settles before the last sidecar // write lands: waited for by the sidecar, not by 50 polls of 20 ms.) await settleJob(newId, { paths: fx.paths }); const m = await fx.read(newId); assert.equal(m?.status, "done"); assert.equal(m?.resumedFrom, "R1"); assert.equal(m?.resumeCount, 1); } finally { await rm(fx.root, { recursive: true, force: true }); } }); test("interrupted twice in a row is not resumed a third time, and says why", async () => { assert.equal(MAX_RESUMES_IN_A_ROW, 1); const fx = await fixture([ { id: "B2", kind: "download-missing", channelSlug: "h3-feed", spec: { kind: "download-missing", slug: "h3-feed" }, resumedFrom: "B1", resumeCount: 1 }, ]); try { const { calls, requeue } = recorder(); const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["B2"], now: NOW }); assert.equal(calls.length, 0); assert.equal(out[0].action, "not-resumed"); assert.equal(out[0].action === "not-resumed" && out[0].category, "repeat"); const meta = await fx.read("B2"); assert.match(meta.cancelReason ?? "", /; not resumed: interrupted twice in a row \(it resumed B1 and was interrupted again\) — Retry it by hand$/); } finally { await rm(fx.root, { recursive: true, force: true }); } }); test("a kind that does not resume is left exactly as the boot closed it", async () => { const fx = await fixture([{ id: "C1", kind: "relocate-channel-media", channelSlug: "h3" }]); try { const { calls, requeue } = recorder(); const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["C1"], now: NOW }); assert.equal(calls.length, 0); assert.equal(out[0].action === "not-resumed" && out[0].category, "kind"); assert.equal((await fx.read("C1")).cancelReason, INTERRUPTED_REASON); } finally { await rm(fx.root, { recursive: true, force: true }); } }); test("a dry run lists and changes nothing", async () => { const fx = await fixture([{ id: "D1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec }]); try { const { calls, requeue } = recorder(); const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, dryRun: true, now: NOW }); assert.deepEqual(out, [{ id: "D1", kind: "import-archive-org", channelSlug: "h3", action: "would-resume" }]); assert.equal(calls.length, 0); assert.equal((await fx.read("D1")).cancelReason, INTERRUPTED_REASON); } finally { await rm(fx.root, { recursive: true, force: true }); } }); test("by hand: only the last 24 h, and never one superseded by a newer job with the same request", async () => { const fx = await fixture([ { id: "E1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec, endedAt: NOW - RESUME_WINDOW_MS - 1 }, { id: "E2", kind: "fetch-posts", channelSlug: "kf", spec: { kind: "fetch-posts", slug: "kf", params: {} } }, // Re-queued by hand after the restart. { id: "E3", kind: "fetch-posts", channelSlug: "kf", status: "done", cancelReason: undefined, queuedAt: NOW - 30_000, spec: { kind: "fetch-posts", slug: "kf", params: {} } }, ]); try { const { calls, requeue } = recorder(); const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, now: NOW }); assert.equal(calls.length, 0); assert.deepEqual( out.map((o) => [o.id, o.action === "not-resumed" ? o.category : o.action]), [["E2", "superseded"]], ); } finally { await rm(fx.root, { recursive: true, force: true }); } }); test("a refused re-queue is said on the meta, and the by-hand command asks again", async () => { const fx = await fixture([{ id: "F1", kind: "persist-videos", channelSlug: "h3", spec: { kind: "persist-videos", slug: "h3", params: { ids: ["a"] } } }]); try { const refused = recorder(() => ({ ok: false, error: "youtube is held" })); const out = await resumeInterruptedJobs({ paths: fx.paths, requeue: refused.requeue, ids: ["F1"], now: NOW }); assert.equal(out[0].action === "not-resumed" && out[0].category, "refused"); assert.match((await fx.read("F1")).cancelReason ?? "", /not resumed: the re-queue was refused: youtube is held/); const later = recorder(); const again = await resumeInterruptedJobs({ paths: fx.paths, requeue: later.requeue, now: NOW }); assert.equal(again[0].action, "resumed"); } finally { await rm(fx.root, { recursive: true, force: true }); } }); test("resumeSpecFor: a dry run and a full posts re-walk are not resumed; an older walk drops its start date", () => { assert.ok("skip" in resumeSpecFor({ kind: "import-archive-org", slug: "x", params: { item: "i", dryRun: true } })); assert.ok("skip" in resumeSpecFor({ kind: "fetch-posts", slug: "x", params: { full: true } })); assert.deepEqual(resumeSpecFor({ kind: "fetch-posts", slug: "x", params: { older: true, from: "2020-01-01" } }), { spec: { kind: "fetch-posts", slug: "x", params: { older: true } }, }); assert.deepEqual(resumeSpecFor(importSpec), { spec: importSpec }); }); test("the boot's running pass then the resume: what it closed is what it resumes", async () => { const fx = await fixture([ { id: "G1", kind: "download-missing", channelSlug: "feed", status: "running", cancelReason: undefined, endedAt: undefined, queuedAt: NOW - 10_000, spec: { kind: "download-missing", slug: "feed" } }, ]); try { const running = await settleRunningJobMetas({ paths: fx.paths, bootedAt: NOW, isProcessAlive: () => false, selfPid: -1 }); assert.deepEqual(running.interrupted.map((j) => j.id), ["G1"]); const { calls, requeue } = recorder(); const lines: string[] = []; const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: running.interrupted.map((j) => j.id), prefix: "[boot]", log: (l) => lines.push(l), }); assert.equal(out[0].action, "resumed"); assert.equal(calls[0].kind, "download-missing"); assert.deepEqual(lines, ["[boot] resumed download-missing feed: G1 -> NEW1"]); } finally { await rm(fx.root, { recursive: true, force: true }); } }); // Lane instagram: a restart never asks Instagram. test("an interrupted Instagram fetch is not re-queued by a boot: it waits for the next scheduled or pressed sync", async () => { const spec: JobSpec = { kind: "fetch-posts", slug: "example-ig", params: {} }; const fx = await fixture([ { id: "IG1", kind: "fetch-posts", queueKey: "platform:instagram", channelSlug: "example-ig", spec }, { id: "X1", kind: "fetch-posts", queueKey: "platform:twitter", channelSlug: "example-x", spec: { kind: "fetch-posts", slug: "example-x", params: {} } }, ]); try { const { calls, requeue } = recorder(); const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["IG1", "X1"], now: NOW }); const ig = out.find((o) => o.id === "IG1")!; assert.equal(ig.action, "not-resumed"); assert.match((ig as { reason: string }).reason, /an Instagram job is not started by a restart/); // X's fetch resumes as it did. assert.equal(out.find((o) => o.id === "X1")!.action, "resumed"); assert.deepEqual(calls.map((c) => c.slug), ["example-x"]); assert.match((await fx.read("IG1")).cancelReason ?? "", /not resumed: an Instagram job is not started by a restart/); } finally { await rm(fx.root, { recursive: true, force: true }); } }); // Review 2, N1: a queue key is only where a job ran. An Instagram channel's // job that ran on another queue is left too. test("an interrupted fetch of an Instagram channel is not re-queued whatever queue it ran on", async () => { const spec: JobSpec = { kind: "fetch-posts", slug: "example-ig", params: { queueKey: "side" } }; const fx = await fixture([ { id: "IG2", kind: "fetch-posts", queueKey: "side", channelSlug: "example-ig", spec }, { id: "X2", kind: "fetch-posts", queueKey: "side", channelSlug: "example-x", spec: { kind: "fetch-posts", slug: "example-x", params: { queueKey: "side" } } }, ]); try { const channelsDir = path.join(fx.root, "channels"); await mkdir(path.join(channelsDir, "example-ig"), { recursive: true }); await mkdir(path.join(channelsDir, "example-x"), { recursive: true }); // Told by its URL alone: no platform in the config. await writeFile(path.join(channelsDir, "example-ig", "config.json"), JSON.stringify({ sourceKind: "social", url: "https://www.instagram.com/example.account/" })); await writeFile(path.join(channelsDir, "example-x", "config.json"), JSON.stringify({ sourceKind: "social", platform: "twitter", url: "https://x.com/example" })); const { calls, requeue } = recorder(); const out = await resumeInterruptedJobs({ paths: { ...fx.paths, channelsDir } as Paths, requeue, ids: ["IG2", "X2"], now: NOW }); assert.equal(out.find((o) => o.id === "IG2")!.action, "not-resumed"); assert.equal(out.find((o) => o.id === "X2")!.action, "resumed"); assert.deepEqual(calls.map((c) => c.slug), ["example-x"]); } finally { await rm(fx.root, { recursive: true, force: true }); } });