import { test } from "node:test"; import assert from "node:assert/strict"; import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import { excludedIds, verifyBeforeClean, type VerifyProbes } from "./verifyBeforeClean"; import { cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed"; import { runCleanAudioJob, type CleanRetry } from "./cleanAudioJob"; import { indexListing, isListed } from "./listingMatch"; import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/verifyPartialListing.test.ts // // A LISTING THE SOURCE RATE-LIMITED PART-WAY (lane verify-resume, operator 21 // Nov 2026: "take a partial result and clean files that were found live in // the partial"). The entries printed before the 429 verify the candidates // among them; every other candidate stays unverified and keeps its audio. // Temp corpus, a stub lister that rate-limits after N entries; no yt-dlp. const ROOT = await mkdtemp(path.join(tmpdir(), "verify-partial-")); process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true })); process.on("exit", () => void rm(ROOT, { recursive: true, force: true })); const T0 = Date.parse("2026-11-21T03:00:00.000Z"); let n = 0; // A Rumble channel whose candidates are transcribed and hold audio. `embed` // gives a candidate a metadata.info.json naming its second (embed) id. async function corpus(ids: string[], embed: Record = {}, times: Record = {}): Promise { 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" }), ); 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)); if (embed[id] || times[id] !== undefined) { await writeFile( path.join(v, "metadata.info.json"), JSON.stringify({ id: embed[id] ?? id, title: "t", ...(times[id] !== undefined ? { timestamp: times[id] } : {}) }), ); } } return paths; } const hasAudio = (paths: Paths, id: string) => access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false); const watch = (id: string) => `https://rumble.com/${id}-a-title.html`; // The stub lister: the source returns `urls`, then answers 429. function rateLimitedAfter(urls: string[]) { const calls = { quick: 0, full: 0, backoff: 0 }; const probes: VerifyProbes = { quick: async () => { calls.quick++; throw new EnumerationIncompleteError(1, "rumble", 3, urls.length, urls); }, full: async () => { calls.full++; throw new Error("no per-video probe after a rate-limited listing"); }, recordBackoff: async () => { calls.backoff++; }, }; return { calls, probes }; } test("a partial listing verifies the candidates it returned; the rest stay unverified", async () => { const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc", "v1dddd"]); const { calls, probes } = rateLimitedAfter([watch("v1aaaa"), watch("v9zzzz"), watch("v1cccc")]); const lines: string[] = []; const v = await verifyBeforeClean({ channelSlug: "ch", paths, candidateIds: ["v1aaaa", "v1bbbb", "v1cccc", "v1dddd"], onLog: (m) => lines.push(m), probes, }); assert.equal(calls.quick, 1); assert.equal(calls.full, 0, "no confirmation probe: a candidate the prefix did not reach is not a suspect"); assert.equal(calls.backoff, 1, "the cooldown is recorded"); assert.deepEqual([...v.unverified].sort(), ["v1bbbb", "v1dddd"]); assert.deepEqual([...excludedIds(v)].sort(), ["v1bbbb", "v1dddd"]); assert.equal(v.pinned.size, 0); assert.equal(v.stopped?.kind, "rate-limit"); assert.deepEqual(v.partial, { verified: 2, entries: 3, unverified: 2 }); assert.ok( lines.some((l) => l.includes("verified 2 from a partial listing of 3 entries; 2 unverified remain")), lines.join("\n"), ); }); test("the sweep cleans what the partial listing verified and never a video outside it", async () => { const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc"]); const { probes } = rateLimitedAfter([watch("v1aaaa")]); const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, probes, assertReachable: async () => {} }); assert.equal(await hasAudio(paths, "v1aaaa"), false, "listed in the partial: cleaned"); assert.equal(await hasAudio(paths, "v1bbbb"), true, "not in any listing: kept"); assert.equal(await hasAudio(paths, "v1cccc"), true, "not in any listing: kept"); assert.equal(r.cleanedDirs, 1); assert.equal(r.unverified, 2); assert.deepEqual(r.partial, { verified: 1, entries: 1, unverified: 2 }); assert.equal(r.stopped?.kind, "rate-limit"); }); test("a rate limit before any entry still cleans nothing", async () => { const paths = await corpus(["v1aaaa", "v1bbbb"]); const { probes } = rateLimitedAfter([]); const lines: string[] = []; const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); assert.equal(r.cleanedDirs, 0); assert.equal(r.unverified, 2); assert.equal(r.partial, undefined); assert.ok(lines.some((l) => l.includes("nothing cleaned this run"))); }); test("Rumble's two ids: an embed entry verifies the candidate whose metadata names it, never by a substring or across id kinds", async () => { const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc", "v1dddd"], { v1aaaa: "v8embd1", // listed below by its embed URL v1bbbb: "v8embd2", // its embed id is spelled like another video's SLUG entry below }); const { probes } = rateLimitedAfter([ "https://rumble.com/embed/v8embd1/", // A slug entry spelled like v1bbbb's EMBED id: a different video's page. watch("v8embd2"), // A longer id containing a candidate's id, and a title naming one. watch("v1ccccx"), "https://rumble.com/v2eeee-about-v1dddd-and-more.html", ]); const v = await verifyBeforeClean({ channelSlug: "ch", paths, candidateIds: ["v1aaaa", "v1bbbb", "v1cccc", "v1dddd"], onLog: () => {}, probes }); assert.deepEqual([...v.unverified].sort(), ["v1bbbb", "v1cccc", "v1dddd"]); assert.equal(v.partial?.verified, 1); }); test("isListed matches a directory against page ids and an embed id against embed ids only", () => { const idx = indexListing([watch("v1aaaa"), "https://rumble.com/embed/v8embd1/", "not a url"]); assert.equal(idx.entries, 2); assert.equal(isListed(idx, { dir: "v1aaaa" }), true); assert.equal(isListed(idx, { dir: "v1zzzz", embed: "v8embd1" }), true); assert.equal(isListed(idx, { dir: "v8embd1" }), false, "a directory name is never matched against an embed id"); assert.equal(isListed(idx, { dir: "v1zzzz", embed: "v1aaaa" }), false, "an embed id is never matched against a page id"); assert.equal(isListed(idx, { dir: "v1aaa" }), false, "no prefix match"); }); test("the job: a partial listing ends deferred and says what it verified, cleaned and left", async () => { const paths = await corpus(["v1aaaa", "v1bbbb"]); const { probes } = rateLimitedAfter([watch("v1aaaa"), watch("v5other")]); const scheduled: CleanRetry[] = []; const out = await runCleanAudioJob({ channelSlug: "ch", paths, jobId: "job-1", onLog: () => {}, deps: { probes, assertReachable: async () => {}, now: () => T0, cooldownRemainingMs: async () => 0, scheduleRetry: async (r) => (scheduled.push(r), { ok: true as const, id: "job-1.retry1" }), }, }); assert.equal(out.end, "deferred"); if (out.end !== "deferred") return; assert.match(out.sentence, /verified 1 from a partial listing of 2 entries; 1 unverified remain; 1 cleaned, 1 left unverified/); assert.equal(await hasAudio(paths, "v1aaaa"), false); assert.equal(await hasAudio(paths, "v1bbbb"), true); assert.equal(scheduled.length, 1, "the unverified remainder is retried"); }); test("a retry says how many verdicts it started with and how many it added", async () => { const { recordListing } = await import("./listingEvidence"); // Upload times: v1bbbb newest, v1aaaa a week older. This attempt's partial // listing (newest first) reached v1bbbb only, so it did not cover v1aaaa's // place: the earlier attempt's sighting of v1aaaa still counts. const day = 86_400; const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc"], {}, { v1aaaa: 1_790_000_000 - 7 * day, v1bbbb: 1_790_000_000, v1cccc: 1_790_000_000 - 30 * day }); // The attempt before this one listed v1aaaa before the source stopped it. await recordListing(paths, "ch", { at: new Date(Date.now() - 3_600_000).toISOString(), source: "quick-check", urls: [watch("v1aaaa")], complete: false, platform: "rumble", url: "https://rumble.com/c/example" }); const { calls, probes } = rateLimitedAfter([watch("v1bbbb")]); const lines: string[] = []; const out = await runCleanAudioJob({ channelSlug: "ch", paths, jobId: "job-2", retry: { attempt: 1, of: "job-1", notBefore: T0 - 1, platform: "rumble", id: "job-1.retry1" }, onLog: (m) => lines.push(m), deps: { probes, assertReachable: async () => {}, now: () => T0, cooldownRemainingMs: async () => 0, scheduleRetry: async () => ({ ok: true as const, id: "job-1.retry2" }), }, }); assert.equal(calls.quick, 1); assert.equal(out.end, "deferred"); assert.equal(await hasAudio(paths, "v1aaaa"), false, "verified by the earlier attempt's entries"); assert.equal(await hasAudio(paths, "v1bbbb"), false, "verified by this attempt's"); assert.equal(await hasAudio(paths, "v1cccc"), true); assert.ok( lines.includes("Retry 1 of 2: started with 1 verdict(s) earlier attempts and stored listings had earned, added 1; 1 unverified remain."), lines.join("\n"), ); assert.ok(lines.some((l) => /asking at \d+\.\d\d s between requests \(rumble's current pace\)/.test(l)), lines.join("\n")); });