import { test } from "node:test"; import assert from "node:assert/strict"; import { access, mkdir, mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { VerifyProbes } from "./verifyBeforeClean"; import { CLEAN_RATE_LIMIT_MAX_RETRIES, CLEAN_RETRY_PAUSE_MS, PLAN_LOST_SENTENCE, cleanAudioRequestFor, cleanReplayFor, REPLAY_UNCHECKED_KEY_OFF, runCleanAudioJob, type CleanRetry, } from "./cleanAudioJob"; import { parseChannelConfig } from "../lib/channelConfig"; import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanAudioJob.test.ts // // A CHECKED CLEAN THE SOURCE RATE-LIMITED (lane clean-unverified, ruling 2): // it cleans nothing it could not verify, ends DEFERRED with one retry // SCHEDULED (off-queue: cleanRetrySchedule.ts) after the pause, at most twice; // the third rate limit in a row gives up for a person. Any other failure to // verify retries nothing. And how the job decides, WHEN IT STARTS, whether it // runs unchecked and what it may remove (review 1, F2, F3, F5). Temp corpus, // stub probes, an injected clock. const ROOT = await mkdtemp(path.join(tmpdir(), "clean-audio-job-")); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true })); const T0 = Date.parse("2026-11-21T03:00:00.000Z"); let n = 0; async function corpus(config: Record = {}, ids = ["a", "b"]) { const dir = path.join(ROOT, `c${n++}`); const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: path.join(dir, "no-ytdlp") } as unknown as Paths; await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); await writeFile( path.join(paths.channelsDir, "ch", "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/example", ...config }), ); for (const id of ids) { const v = path.join(paths.channelsDir, "ch", "data", id); await mkdir(v, { recursive: true }); await writeFile(path.join(v, "transcript.json"), "{}"); await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(100)); } return paths; } const has = (paths: Paths, id: string) => access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false); const audioLeft = async (paths: Paths, ids = ["a", "b"]) => { let left = 0; for (const id of ids) left += (await has(paths, id)) ? 1 : 0; return left; }; function rateLimitedListing() { const calls = { quick: 0, full: 0, backoff: 0 }; const probes: VerifyProbes = { quick: async () => { calls.quick++; throw new EnumerationIncompleteError(1, "rumble", null, 0); }, full: async () => { calls.full++; throw new Error("tier C is not reached"); }, recordBackoff: async () => { calls.backoff++; }, }; return { calls, probes }; } const allListed = () => { const calls = { quick: 0 }; const probes: VerifyProbes = { quick: async () => (calls.quick++, { knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }), }; return { calls, probes }; }; function retryRecorder() { const scheduled: CleanRetry[] = []; return { scheduled, scheduleRetry: async (r: CleanRetry) => { scheduled.push(r); return { ok: true as const, id: `${r.of}.retry${r.attempt}` }; }, }; } const base = (paths: Paths, over: Partial[0]> = {}) => ({ channelSlug: "ch", paths, jobId: "job-1", onLog: () => {}, ...over, }); test("a rate-limited listing: 0 cleaned, a DEFERRED end, exactly one retry scheduled at now + 15 min", async () => { const paths = await corpus(); const { calls, probes } = rateLimitedListing(); const r = retryRecorder(); const out = await runCleanAudioJob({ ...base(paths), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, }); assert.equal(calls.quick, 1); assert.equal(calls.backoff, 1, "the cooldown is recorded once for this step of the chain"); assert.equal(await audioLeft(paths), 2, "nothing unverified was cleaned"); assert.equal(out.end, "deferred"); assert.equal(CLEAN_RETRY_PAUSE_MS, 15 * 60_000); assert.deepEqual(r.scheduled, [{ attempt: 1, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS, platform: "rumble" }]); if (out.end !== "deferred") return; assert.equal(out.until, T0 + CLEAN_RETRY_PAUSE_MS); assert.equal(out.retryId, "job-1.retry1"); assert.match(out.sentence, /rate-limited/i); assert.match(out.sentence, /0 cleaned/); assert.match(out.sentence, /2 left unverified/); assert.match(out.sentence, /Retry 1 of 2 is scheduled/); assert.match(out.sentence, /waits off the queue/); assert.match(out.sentence, /Cancel this job to cancel it/); }); test("the retry never lands inside the platform's cooldown: a longer cooldown moves it later", async () => { const paths = await corpus(); const { probes } = rateLimitedListing(); const r = retryRecorder(); await runCleanAudioJob({ ...base(paths), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 25 * 60_000 }, }); assert.equal(r.scheduled[0]?.notBefore, T0 + 25 * 60_000); }); test("a rate-limited confirmation probe (tier C blocked) defers the same way", async () => { const paths = await corpus(); const r = retryRecorder(); const probes: VerifyProbes = { quick: async () => ({ knownCount: 2, freshCount: 1, maybeMissingCount: 1, ids: ["b"] }), full: async () => ({ attempted: 1, checked: 0, skipped: 1, byStatus: { public: 0, unlisted: 0, private: 0, members_only: 0, needs_auth: 0, deleted: 0, error: 0 }, blocked: true, blockMessage: "HTTP Error 429", probedIds: [], }), }; const out = await runCleanAudioJob({ ...base(paths), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, }); assert.equal(out.end, "deferred"); assert.equal(await audioLeft(paths), 1, "the listed video was cleaned; the unprobed suspect was not"); assert.equal(r.scheduled.length, 1); if (out.end === "deferred") assert.match(out.sentence, /1 cleaned/); }); test("the third rate limit in a row (retry 2 of 2) gives up for a person: no further retry", async () => { const paths = await corpus(); const { probes } = rateLimitedListing(); const r = retryRecorder(); assert.equal(CLEAN_RATE_LIMIT_MAX_RETRIES, 2); const out = await runCleanAudioJob({ ...base(paths, { jobId: "job-3", retry: { attempt: 2, of: "job-1", notBefore: T0 - 1, platform: "rumble" } }), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, }); assert.equal(out.end, "failed"); if (out.end === "failed") assert.match(out.sentence, /^Gave up: rate-limited/); assert.equal(r.scheduled.length, 0); assert.equal(await audioLeft(paths), 2); }); test("a retry that is rate-limited again schedules the next one, keeping the original request's id", async () => { const paths = await corpus(); const { probes } = rateLimitedListing(); const r = retryRecorder(); const out = await runCleanAudioJob({ ...base(paths, { jobId: "job-2", retry: { attempt: 1, of: "job-1", notBefore: T0 - 1, platform: "rumble" } }), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, }); assert.equal(out.end, "deferred"); assert.deepEqual(r.scheduled, [{ attempt: 2, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS, platform: "rumble" }]); }); test("a retry started before its not-before asks nothing and cleans nothing", async () => { const paths = await corpus(); const { calls, probes } = rateLimitedListing(); const r = retryRecorder(); const out = await runCleanAudioJob({ ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 + 60_000, platform: "rumble" } }), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, }); assert.equal(out.end, "failed"); if (out.end === "failed") assert.match(out.sentence, /before its time/); assert.equal(calls.quick, 0); assert.equal(r.scheduled.length, 0); assert.equal(await audioLeft(paths), 2); }); test("a listing that failed for another reason: 'could not verify', nothing scheduled", async () => { const paths = await corpus(); const r = retryRecorder(); const probes: VerifyProbes = { quick: async () => { throw new Error("yt-dlp exited with code 1"); }, }; const out = await runCleanAudioJob({ ...base(paths), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, }); assert.equal(out.end, "failed"); if (out.end === "failed") assert.match(out.sentence, /^Could not verify availability/); assert.equal(r.scheduled.length, 0); assert.equal(await audioLeft(paths), 2); }); test("a verified clean ends plain done and schedules nothing", async () => { const paths = await corpus(); const r = retryRecorder(); const { probes } = allListed(); const out = await runCleanAudioJob({ ...base(paths), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, }); assert.equal(out.end, "done"); assert.equal(r.scheduled.length, 0); assert.equal(await audioLeft(paths), 0); }); test("a confirmed unchecked job ('button') asks nothing and removes its plan only", async () => { const paths = await corpus(); const { calls, probes } = rateLimitedListing(); const r = retryRecorder(); const out = await runCleanAudioJob({ ...base(paths, { unchecked: "button", plan: ["a"] }), deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, }); assert.equal(out.end, "done"); assert.equal(calls.quick, 0); assert.equal(r.scheduled.length, 0); assert.equal(await has(paths, "a"), false); assert.equal(await has(paths, "b"), true, "not in the confirmed plan"); }); test("ruling 5: a 'button' job whose plan is missing removes nothing and ends failed, asking to confirm again", async () => { const paths = await corpus(); const { calls, probes } = rateLimitedListing(); const out = await runCleanAudioJob({ ...base(paths, { unchecked: "button" }), deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, }); assert.deepEqual(out, { end: "failed", sentence: PLAN_LOST_SENTENCE }); assert.match(PLAN_LOST_SENTENCE, /^Confirmed plan lost; confirm again/); assert.equal(calls.quick, 0); assert.equal(await audioLeft(paths), 2); }); test("ruling 3: a key-driven job whose key was turned off after it was queued runs CHECKED and says so", async () => { const paths = await corpus(); // the key is OFF now const { calls, probes } = allListed(); const logs: string[] = []; const out = await runCleanAudioJob({ ...base(paths, { unchecked: "channel-setting", onLog: (m) => logs.push(m) }), deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, }); assert.equal(out.end, "done"); assert.equal(calls.quick, 1, "the source was asked: it ran checked"); assert.ok(logs.some((l) => /turned off after this clean was queued: it runs CHECKED/.test(l)), logs.join("\n")); assert.ok(!logs.some((l) => l.startsWith("Clean without checking:")), logs.join("\n")); }); test("ruling 3: a key-driven job whose key is still on runs unchecked, discovering at start", async () => { const paths = await corpus({ cleanAudioWithoutChecking: true }); const { calls, probes } = rateLimitedListing(); const out = await runCleanAudioJob({ ...base(paths, { unchecked: "channel-setting" }), deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, }); assert.equal(out.end, "done"); assert.equal(calls.quick, 0); assert.equal(await audioLeft(paths), 0); }); test("a retry stays CHECKED even if the channel's key was turned on since (nobody confirmed an unchecked run)", async () => { const paths = await corpus({ cleanAudioWithoutChecking: true }); const { calls, probes } = allListed(); await runCleanAudioJob({ ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 - 1, platform: "rumble" } }), deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, }); assert.equal(calls.quick, 1); }); test("ruling 4: whatever runs after the wait re-asserts the media guard immediately before removing anything", async () => { const paths = await corpus(); const { probes } = allListed(); // A relocation started during the wait: its marker stands. await writeFile( path.join(paths.channelsDir, "ch", ".relocating.json"), JSON.stringify({ target: "/elsewhere/ch/media", direction: "out", startedAt: "now", phase: "copy", scope: "media" }), ); await assert.rejects( runCleanAudioJob({ ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 - 1, platform: "rumble" } }), deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, }), /relocation/, ); assert.equal(await audioLeft(paths), 2, "nothing removed under a relocation"); }); test("what a request queues: kind, unchecked reason and carried plan, from the key and the explicit flag", () => { const off = parseChannelConfig({ handling: "transcribe", name: "a" }); const on = parseChannelConfig({ handling: "transcribe", name: "a", cleanAudioWithoutChecking: true }); assert.deepEqual(cleanAudioRequestFor(off), { kind: "clean-audio-transcribed" }); assert.deepEqual(cleanAudioRequestFor(on), { kind: "clean-audio-unchecked", unchecked: "channel-setting" }); assert.deepEqual(cleanAudioRequestFor(on, { plan: ["x"] }), { kind: "clean-audio-unchecked", unchecked: "channel-setting", plan: ["x"] }); assert.deepEqual(cleanAudioRequestFor(off, { explicit: "button", plan: ["x"] }), { kind: "clean-audio-unchecked", unchecked: "button", plan: ["x"], }); assert.deepEqual(cleanAudioRequestFor(null, { explicit: "button" }), { kind: "clean-audio-unchecked", unchecked: "button" }); }); test("replay: unchecked only with the explicit flag and its carried plan; a retry's replay is a fresh chain", () => { const cleanReplay = (k: string, p: Record) => cleanReplayFor(k, p, true); assert.deepEqual(cleanReplay("clean-audio-transcribed", {}), { ok: true, call: "clean" }); assert.deepEqual(cleanReplay("clean-audio-transcribed", { plan: ["a"] }), { ok: true, call: "clean", plan: ["a"] }); assert.deepEqual( cleanReplay("clean-audio-retry", { retry: { attempt: 1, of: "j", notBefore: 1, platform: "rumble" }, plan: ["a"] }), { ok: true, call: "clean" }, "the retry's chain and count are the schedule's, never a replay's", ); assert.deepEqual(cleanReplay("clean-audio-unchecked", { unchecked: "button", plan: ["a", "b"] }), { ok: true, call: "unchecked", plan: ["a", "b"], }); // No plan: replayed into a job that ends failed (PLAN_LOST_SENTENCE), never an unbounded run. assert.deepEqual(cleanReplay("clean-audio-unchecked", { unchecked: "button" }), { ok: true, call: "unchecked" }); assert.deepEqual(cleanReplay("clean-audio-unchecked", { unchecked: "button", plan: "a" }), { ok: true, call: "unchecked" }); assert.deepEqual(cleanReplay("clean-audio-unchecked", { unchecked: "channel-setting" }), { ok: true, call: "clean" }); assert.equal(cleanReplay("clean-audio-unchecked", {}).ok, false); // Key OFF: a confirmed unchecked run is never replayed unchecked. assert.deepEqual(cleanReplayFor("clean-audio-unchecked", { unchecked: "button", plan: ["a"] }, false), { ok: false, info: true, error: REPLAY_UNCHECKED_KEY_OFF, }); }); test("ops nit: a carried plan's counts are stated in the job's log before anything is removed", async () => { const paths = await corpus(); const { probes } = rateLimitedListing(); const logs: string[] = []; await runCleanAudioJob({ ...base(paths, { unchecked: "button", plan: ["a", "b"], planCounts: { files: 2, bytes: 200, videos: 2, protected: 0, awaitingDiarization: 0, awaitingVoiceprint: 0 }, onLog: (m) => logs.push(m), }), deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, }); const counted = logs.findIndex((l) => l.startsWith("Plan counted when this clean was asked for: 2 audio file(s) (200 bytes) from 2 video(s); kept: 0")); const removed = logs.findIndex((l) => l.startsWith("Removed ")); assert.ok(counted >= 0 && removed > counted, logs.join("\n")); });