import { test } from "node:test"; import assert from "node:assert/strict"; import { access, chmod, mkdir, mkdtemp, 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 { VerifyProbes } from "./verifyBeforeClean"; import { verifyBeforeClean } from "./verifyBeforeClean"; import { cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed"; import { LISTING_EVIDENCE_RETAIN_MS, foldListing, freshCompleteListing, freshListingIndex, listingResumeStart, normalizeListingEvidence, readListingEvidence, recordListing, type ListingEvidence, } from "./listingEvidence"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/listingEvidence.test.ts // // THE PRE-CLEAN CHECK KEEPS WHAT IT LEARNED AND CONTINUES (lane verify-resume, // operator 21 Nov 2026: "retrying from start is horrible because it will just // keep failing"). A fake yt-dlp lists a temp channel and answers 429 after N // entries; it honours `-I :` the way a PagedList extractor does. const ROOT = await mkdtemp(path.join(tmpdir(), "listing-evidence-")); 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 H = 3_600_000; const T0 = Date.parse("2026-11-21T03:00:00.000Z"); const iso = (ms: number) => new Date(ms).toISOString(); const empty = (): ListingEvidence => normalizeListingEvidence(null); const RU = "https://rumble.com/c/example"; const YT = "https://www.youtube.com/@ch/videos"; // --------------------------------------------------------------------------- // The record test("an id is dated to the start of the newest listing that returned it; embed ids are kept apart", () => { let r = foldListing(empty(), { at: iso(T0 - 2 * H), source: "sync-full", urls: ["https://rumble.com/v1aaaa-t.html"], complete: true, platform: "rumble", url: RU }, T0); r = foldListing(r, { at: iso(T0 - H), source: "quick-check", urls: ["https://rumble.com/v1aaaa-t.html", "https://rumble.com/embed/v8embd1/"], complete: false, pagesReached: 2, platform: "rumble", url: RU }, T0); // An older listing folded later does not move a date back. r = foldListing(r, { at: iso(T0 - 5 * H), source: "sync-paged", urls: ["https://rumble.com/v1aaaa-t.html"], complete: false, platform: "rumble", url: RU }, T0); assert.equal(r.seen.v1aaaa, iso(T0 - H)); assert.equal(r.embedSeen.v8embd1, iso(T0 - H)); assert.equal(r.seen.v8embd1, undefined, "an embed id never lands among page ids"); assert.deepEqual(r.attempts.map((a) => [a.source, a.complete, a.count, a.start]), [ ["sync-full", true, 1, 1], ["quick-check", false, 2, 1], ["sync-paged", false, 1, 1], ]); assert.equal(r.attempts[1].pagesReached, 2); }); test("ids not listed for the retention period are dropped, and attempts are capped", () => { let r = foldListing(empty(), { at: iso(T0 - LISTING_EVIDENCE_RETAIN_MS - H), source: "sync-full", urls: ["https://www.youtube.com/watch?v=old00000001"], complete: true, platform: "youtube", url: YT }, T0 - LISTING_EVIDENCE_RETAIN_MS); for (let i = 0; i < 25; i++) { r = foldListing(r, { at: iso(T0), source: "sync-paged", urls: ["https://www.youtube.com/watch?v=new00000001"], complete: false, platform: "youtube", url: YT }, T0); } assert.equal(r.seen.old00000001, undefined); assert.equal(r.seen.new00000001, iso(T0)); assert.equal(r.attempts.length, 20); }); test("only ids listed inside the window are fresh; 0 h uses nothing; a date in the future is not evidence", () => { const r: ListingEvidence = { version: 2, url: RU, absent: {}, lastComplete: null, seen: { fresh: iso(T0 - 23 * H), stale: iso(T0 - 25 * H), future: iso(T0 + 2 * H) }, embedSeen: {}, attempts: [], }; assert.deepEqual([...freshListingIndex(r, T0, 24).ids], ["fresh"]); assert.equal(freshListingIndex(r, T0, 0).entries, 0); }); test("a hand-broken record reads as what is valid in it", () => { const r = normalizeListingEvidence({ seen: { a: iso(T0), b: 3, c: "not a date" }, attempts: [{ at: "x" }, { at: iso(T0), source: "quick-check", complete: false, start: 1, count: 4, platform: "odysee", url: RU }] }); assert.deepEqual(Object.keys(r.seen), ["a"]); assert.equal(r.attempts.length, 1); }); test("the resume start: a continuation only where the extractor pages by offset, after a fresh cut-short attempt", () => { const cut = (platform: string, at = iso(T0 - H)): ListingEvidence => ({ version: 2, url: RU, absent: {}, lastComplete: null, seen: {}, embedSeen: {}, attempts: [{ at, source: "quick-check", complete: false, start: 1, count: 408, platform, url: RU }], }); // Odysee (LBRY OnDemandPagedList, 50 a page): continue 2 pages before the cut. assert.deepEqual( { ...listingResumeStart(cut("odysee"), "odysee", T0, 24), after: null }, { start: 309, after: null, overlap: 100 }, ); assert.equal(listingResumeStart(cut("bitchute"), "bitchute", T0, 24).start, 359); // Rumble, YouTube, Twitch: generators — `-I N:` would fetch pages 1..N anyway. for (const p of ["rumble", "youtube", "twitch", "kick"]) assert.equal(listingResumeStart(cut(p), p, T0, 24).start, 1, p); // Outside the window, or after a complete listing: from the top. assert.equal(listingResumeStart(cut("odysee", iso(T0 - 25 * H)), "odysee", T0, 24).start, 1); const done = cut("odysee"); done.attempts.push({ at: iso(T0 - H / 2), source: "clean-check", complete: true, start: 309, count: 50, platform: "odysee", url: RU }); assert.equal(listingResumeStart(done, "odysee", T0, 24).start, 1); // Sync's paged walk is a prefix by design, not an attempt to continue. const paged = cut("odysee"); paged.attempts[0].source = "sync-paged"; assert.equal(listingResumeStart(paged, "odysee", T0, 24).start, 1); }); test("the newest complete whole listing is kept as lastComplete; a paged walk or a continuation never is one", () => { let r = empty(); r = foldListing(r, { at: iso(T0 - 2 * H), endedAt: iso(T0 - 2 * H + 600_000), source: "sync-full", urls: ["https://rumble.com/v1aaaa-t.html", "https://rumble.com/embed/v8embd1/"], complete: true, platform: "rumble", url: RU }, T0); r = foldListing(r, { at: iso(T0 - H), source: "sync-paged", urls: ["https://rumble.com/v1bbbb-t.html"], complete: true, platform: "rumble", url: RU }, T0); r = foldListing(r, { at: iso(T0 - H), source: "clean-check", urls: ["https://rumble.com/v1cccc-t.html"], complete: true, start: 309, platform: "rumble", url: RU }, T0); const c = freshCompleteListing(r, T0, 24); assert.equal(c?.source, "sync-full"); assert.equal(c?.endedAt, iso(T0 - 2 * H + 600_000)); assert.deepEqual(c?.ids, ["v1aaaa"]); assert.deepEqual(c?.embedIds, ["v8embd1"]); assert.equal(freshCompleteListing(r, T0, 1), null, "outside the window"); }); // --------------------------------------------------------------------------- // The check, over a fake lister let n = 0; type Source = { paths: Paths; dir: string; calls: () => Promise; setListing: (urls: string[]) => Promise; setLimit: (k: number) => Promise; setFail: () => Promise }; // A channel on `channelUrl` whose candidates (`ids`) are transcribed and hold // audio, and a fake yt-dlp that prints the listing file from `-I :` (1 // without it), at most `limit` entries, then a 429 when more remain. async function source(channelUrl: string, ids: string[]): Promise { const dir = path.join(ROOT, `s${n++}`); await mkdir(dir, { recursive: true }); const bin = path.join(dir, "fake-ytdlp.sh"); await writeFile( bin, [ "#!/bin/sh", `d='${dir}'`, "start=1; prev=''", 'for a in "$@"; do if [ "$prev" = "-I" ]; then start="${a%%:*}"; fi; prev="$a"; done', 'echo "$start" >> "$d/calls"', // A listing that prints what it has, then fails for a reason that is not a rate limit. 'if [ -f "$d/fail" ]; then cat "$d/listing.txt" 2>/dev/null; echo "ERROR: [x] x: Unsupported URL" >&2; exit 1; fi', 'lim=$(cat "$d/limit" 2>/dev/null || echo 0)', 'awk -v s="$start" -v lim="$lim" \'NR>=s { if (lim>0 && c>=lim) exit; print; c++ }\' "$d/listing.txt"', 'left=$(awk -v s="$start" \'NR>=s\' "$d/listing.txt" | wc -l)', 'if [ "$lim" -gt 0 ] && [ "$left" -gt "$lim" ]; then echo "ERROR: [x] x: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2; exit 1; fi', "exit 0", "", ].join("\n"), ); await chmod(bin, 0o755); const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: bin, jobsDir: path.join(dir, ".jobs") } 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: channelUrl })); 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(10)); } return { paths, dir, calls: async () => (await readFile(path.join(dir, "calls"), "utf8").catch(() => "")).split("\n").filter(Boolean), setListing: (urls) => writeFile(path.join(dir, "listing.txt"), urls.join("\n") + "\n"), setLimit: (k) => writeFile(path.join(dir, "limit"), String(k)), setFail: () => writeFile(path.join(dir, "fail"), "1"), }; } const hasAudio = (paths: Paths, id: string) => access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false); // No per-video probe in these runs unless a test says so: a suspect is // recorded and left unprobed (so unverified). function probesRecording() { const asked: string[][] = []; const probes: VerifyProbes = { recordBackoff: async () => {}, full: async (opts) => (asked.push([...(opts.onlyIds ?? [])]), { attempted: 0, checked: 0, skipped: 0, byStatus: {} as never, blocked: false, probedIds: [] }), }; return { asked, probes }; } const odysee = (k: number) => `https://odysee.com/@ch:1/video-${k}:od${String(k).padStart(4, "0")}`; const odId = (k: number) => `od${String(k).padStart(4, "0")}`; const rumble = (k: number) => `https://rumble.com/v${(100000 + k).toString(36)}-title-${k}.html`; const ruId = (k: number) => `v${(100000 + k).toString(36)}`; test("Rumble (no offset paging): each attempt starts at entry 1 but keeps what earlier attempts verified, and makes progress", async () => { const ids = [ruId(5), ruId(150), ruId(290)]; const s = await source("https://rumble.com/c/example", ids); await s.setListing(Array.from({ length: 300 }, (_, i) => rumble(i + 1))); const { probes } = probesRecording(); const run = () => cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); let lines: string[] = []; // Attempt 1: the source stops it after 100 entries. await s.setLimit(100); let r = await run(); assert.equal(r.cleanedDirs, 1); assert.equal(await hasAudio(s.paths, ruId(5)), false); assert.equal(r.unverified, 2); // The partial listing is saved as evidence, marked incomplete. const ev = await readListingEvidence(s.paths, "ch"); assert.equal(ev.attempts.at(-1)?.complete, false); assert.equal(ev.attempts.at(-1)?.count, 100); assert.ok(ev.seen[ruId(5)]); // Attempt 2: further this time (200 entries). The pace has risen meanwhile // in production; here the fake simply lets more through. lines = []; await s.setLimit(200); r = await run(); assert.equal(await hasAudio(s.paths, ruId(150)), false, "attempt 2 adds the candidate it reached"); assert.equal(await hasAudio(s.paths, ruId(290)), true, "never listed: kept"); assert.equal(r.unverified, 1); // Rumble's extractor cannot start at an offset: both attempts asked from 1. assert.deepEqual(await s.calls(), ["1", "1"]); assert.ok(lines.some((l) => l.includes("started with 0 of 2 candidate(s) verified by stored evidence")), lines.join("\n")); }); test("Odysee (offset paging): the next attempt continues two pages before the cut, and a complete continuation clears the rest", async () => { const ids = [odId(10), odId(150), odId(280)]; const s = await source("https://odysee.com/@ch:1", ids); await s.setListing(Array.from({ length: 300 }, (_, i) => odysee(i + 1))); const { asked, probes } = probesRecording(); const lines: string[] = []; const run = () => cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); await s.setLimit(200); let r = await run(); assert.equal(r.cleanedDirs, 2, "entries 1–200 verify od0010 and od0150"); assert.equal(await hasAudio(s.paths, odId(280)), true); r = await run(); assert.equal(await hasAudio(s.paths, odId(280)), false, "the continuation (entries 101–300) verified it"); assert.deepEqual(await s.calls(), ["1", "101"]); assert.equal(r.stopped, undefined, "the continuation ran to the end"); assert.deepEqual(asked, [], "nothing missing, nothing to probe"); assert.ok(lines.some((l) => l.includes("from entry 101, 100 entries of overlap")), lines.join("\n")); assert.ok(lines.some((l) => l.includes("overlaps the last attempt by 100 entries")), lines.join("\n")); }); test("a listing that moved by more than the overlap between attempts: what neither attempt returned is never cleaned", async () => { const ids = [odId(10), odId(220)]; const s = await source("https://odysee.com/@ch:1", ids); await s.setListing(Array.from({ length: 400 }, (_, i) => odysee(i + 1))); const { asked, probes } = probesRecording(); const lines: string[] = []; const run = () => cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); await s.setLimit(200); await run(); // entries 1–200: od0010 cleaned assert.equal(await hasAudio(s.paths, odId(10)), false); // 150 videos near the top are removed before the next attempt: entry 220 // moves up to 70, before the continuation's start (101). await s.setListing(Array.from({ length: 400 }, (_, i) => i + 1).filter((k) => k < 11 || k > 160).map(odysee)); await s.setLimit(0); await run(); assert.equal(await hasAudio(s.paths, odId(220)), true, "never returned by either attempt: kept"); assert.deepEqual(asked, [[odId(220)]], "it goes to the per-video confirmation instead"); assert.ok(lines.some((l) => l.includes("moved by more than the overlap")), lines.join("\n")); }); test("stored evidence: fresh Sync listings and fresh probes verify with no request; stale ones, a backfill and an unknown writer do not", async () => { const s = await source("https://rumble.com/c/example", ["v1aaaa", "v1bbbb", "v1cccc", "v1dddd", "v1eeee"]); await s.setListing([]); await s.setFail(); // any listing fails at once, answering nothing const now = Date.now(); await recordListing(s.paths, "ch", { at: iso(now - 2 * H), source: "sync-paged", urls: ["https://rumble.com/v1aaaa-t.html"], complete: false, platform: "rumble", url: RU }); await recordListing(s.paths, "ch", { at: iso(now - 30 * H), source: "sync-full", urls: ["https://rumble.com/v1bbbb-t.html"], complete: true, platform: "rumble", url: RU }); const av = (id: string, rec: Record) => writeFile(path.join(s.paths.channelsDir, "ch", "data", id, "availability.json"), JSON.stringify(rec)); await av("v1cccc", { checkedAt: iso(now - H), checkedBy: "check", availability: "public" }); await av("v1dddd", { checkedAt: iso(now - H), checkedBy: "backfill", availability: "public" }); await av("v1eeee", { checkedAt: iso(now - H), availability: "public" }); const { probes } = probesRecording(); const lines: string[] = []; const v = await verifyBeforeClean({ channelSlug: "ch", paths: s.paths, candidateIds: ["v1aaaa", "v1bbbb", "v1cccc", "v1dddd", "v1eeee"], onLog: (m) => lines.push(m), probes }); assert.deepEqual([...v.unverified].sort(), ["v1bbbb", "v1dddd", "v1eeee"]); assert.equal(v.fromEvidence, 2); assert.ok(lines.some((l) => l.includes("started with 2 of 5 candidate(s) verified by stored evidence (1 listed, 1 probed, within 24 h); 3 to ask the source")), lines.join("\n")); }); test("everything vouched for by stored evidence: nothing is asked at all", async () => { const s = await source("https://rumble.com/c/example", ["v1aaaa"]); await recordListing(s.paths, "ch", { at: iso(Date.now() - H), source: "sync-paged", urls: ["https://rumble.com/v1aaaa-t.html"], complete: false, platform: "rumble", url: RU }); const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: () => {}, probes: probesRecording().probes, assertReachable: async () => {} }); assert.equal(r.cleanedDirs, 1); assert.deepEqual(await s.calls(), [], "no listing spawned"); }); test("a complete listing inside the window sends what it does not name straight to the per-video confirmation", async () => { const s = await source("https://rumble.com/c/example", ["v1aaaa", "v1bbbb"]); await recordListing(s.paths, "ch", { at: iso(Date.now() - H), source: "sync-full", urls: ["https://rumble.com/v1aaaa-t.html"], complete: true, platform: "rumble", url: RU }); const { asked, probes } = probesRecording(); const v = await verifyBeforeClean({ channelSlug: "ch", paths: s.paths, candidateIds: ["v1aaaa", "v1bbbb"], onLog: () => {}, probes }); assert.deepEqual(await s.calls(), [], "no second listing"); assert.deepEqual(asked, [["v1bbbb"]]); assert.deepEqual([...v.unverified], ["v1bbbb"], "unprobed: kept"); }); test("verifyBeforeCleanMaxAgeHours 0: stored evidence is never used", async () => { const s = await source("https://rumble.com/c/example", ["v1aaaa"]); await s.setListing([]); await s.setLimit(1); await recordListing(s.paths, "ch", { at: iso(Date.now() - 60_000), source: "sync-full", urls: ["https://rumble.com/v1aaaa-t.html"], complete: true, platform: "rumble", url: RU }); const v = await verifyBeforeClean({ channelSlug: "ch", paths: s.paths, candidateIds: ["v1aaaa"], onLog: () => {}, probes: probesRecording().probes, maxAgeHours: 0 }); assert.deepEqual(await s.calls(), ["1"], "it listed"); assert.equal(v.fromEvidence, 0); }); // --------------------------------------------------------------------------- // Few candidates: ask each by itself instead of listing test("the few-candidates rule: fewer probes than listing requests; Kick's one-answer listing always lists", async () => { const { preferPerVideo, entriesPerRequest } = await import("./listingEvidence"); assert.deepEqual(preferPerVideo({ candidates: 150, listingSize: 8000, entriesPerRequest: 25 }), { perVideo: true, listingRequests: 320 }); assert.equal(preferPerVideo({ candidates: 350, listingSize: 8000, entriesPerRequest: 25 }).perVideo, false); assert.equal(preferPerVideo({ candidates: 1, listingSize: 30, entriesPerRequest: 30 }).perVideo, false, "one page beats any probe run"); assert.equal(preferPerVideo({ candidates: 2, listingSize: 1000, entriesPerRequest: Number.POSITIVE_INFINITY }).perVideo, false); // A continuation only has the pages after its start left to list. assert.equal(preferPerVideo({ candidates: 30, listingSize: 2000, entriesPerRequest: 50, start: 1001 }).listingRequests, 20); // Measured from a listing that logged its pages. const r = empty(); r.attempts.push({ at: iso(T0), source: "quick-check", complete: false, start: 1, count: 408, pagesReached: 17, platform: "rumble", url: RU }); assert.equal(entriesPerRequest(r, "rumble"), 24); assert.equal(entriesPerRequest(r, "youtube"), 30); }); // A probe stub that answers `public` (as runAvailabilityCheck records it) for // the first `limit` ids it is asked about, then reports the source blocked. function probesAnswering(paths: Paths, limit: number) { const asked: string[][] = []; const probes: VerifyProbes = { recordBackoff: async () => {}, full: async (opts) => { const ids = [...(opts.onlyIds ?? [])]; asked.push(ids); const probed = ids.slice(0, limit); for (const id of probed) { await writeFile( path.join(paths.channelsDir, "ch", "data", id, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), checkedBy: "check", availability: "public" }), ); } const blocked = probed.length < ids.length; return { attempted: probed.length, checked: probed.length, skipped: 0, byStatus: {} as never, blocked, ...(blocked ? { blockMessage: "HTTP Error 429" } : {}), probedIds: probed }; }, }; return { asked, probes }; } async function bigRoster(paths: Paths, size: number): Promise { const entries: Record = {}; for (let i = 0; i < size; i++) entries[`r${i}`] = { url: "", firstSeenAt: iso(T0), lastListedAt: iso(T0), source: "listing" }; await writeFile(path.join(paths.channelsDir, "ch", "roster.json"), JSON.stringify({ version: 1, updatedAt: iso(T0), lastSweep: null, entries })); } async function withUrl(paths: Paths, id: string): Promise { await writeFile(path.join(paths.channelsDir, "ch", "data", id, "metadata.info.json"), JSON.stringify({ id, webpage_url: `https://www.youtube.com/watch?v=${id}` })); } test("few candidates on a big channel: no listing, each asked by itself; a rate limit keeps what was answered and the next run asks only the rest", async () => { const ids = ["yt000000001", "yt000000002", "yt000000003", "yt000000004", "yt000000005"]; const s = await source("https://www.youtube.com/@ch/videos", ids); for (const id of ids) await withUrl(s.paths, id); await bigRoster(s.paths, 3000); // ~100 listing requests at 30 a page const { asked, probes } = probesAnswering(s.paths, 2); const lines: string[] = []; const run = () => cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); let r = await run(); assert.deepEqual(await s.calls(), [], "no listing"); assert.equal(r.cleanedDirs, 2, "the two answered before the rate limit are cleaned"); assert.equal(r.unverified, 3); assert.equal(r.stopped?.kind, "rate-limit"); assert.ok(lines.some((l) => l.includes("asking each one by itself instead (5 requests, paced)")), lines.join("\n")); r = await run(); assert.deepEqual(asked, [ids, ids.slice(2)], "the retry asks only the unverified remainder"); assert.equal(r.cleanedDirs, 2); assert.equal(r.unverified, 1); }); test("few candidates, but one has nothing to probe it by: the listing serves them all", async () => { const ids = ["yt000000001", "yt000000002"]; const s = await source("https://www.youtube.com/@ch/videos", ids); await withUrl(s.paths, ids[0]); // the second has no metadata, so no webpage_url await bigRoster(s.paths, 3000); await s.setListing(ids.map((id) => `https://www.youtube.com/watch?v=${id}`)); const { asked, probes } = probesAnswering(s.paths, 10); const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: () => {}, probes, assertReachable: async () => {} }); assert.deepEqual(await s.calls(), ["1"], "listed"); assert.deepEqual(asked, []); assert.equal(r.cleanedDirs, 2); });