// fetch-copies (release 31, lane C): each gone video's whole audio from the // copy find-copy found, into its own record — the copy's provenance and a // `fetched` attempt written, a source-side failure recorded (never ours), a // rate limit stopping the run with the backoff recorded, a video that holds // media by its turn skipped, the gap between fetches — and the transcription // lane then sees the audio: the snapshot moves the video from noTranscript // (where a gone video's download never comes) to downloadedNoTranscript. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchCopies.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { ClipCopy } from "../lib/clipWindow"; import { loadCopyAttempts } from "../lib/copyAttempts-server"; import { loadArchiveOrgProvenance } from "../lib/archiveOrg-server"; import { ArchiveOrgClient } from "../lib/archiveOrgClient"; import { GONE_AVAILABILITY } from "../testing/draft/corpus.mjs"; import { startFakeArchiveOrg } from "../testing/archiveOrg/fakeArchiveOrg.mjs"; import { FetchWindowError } from "../ytdlp/fetchWindowManaged"; import type { FetchCopyOpts } from "../ytdlp/fetchCopyManaged"; import { copyAttemptFields, fetchCopies, writeCopyProvenance, type FetchCopiesDeps, type FetchCopyItem } from "./fetchCopies"; import { generateChannelSnapshot } from "./channelSnapshot"; const SLUG = "alpha"; const GONE_A = "goneAAAAAA1"; const GONE_B = "goneBBBBBB2"; const GONE_C = "goneCCCCCC3"; const watch = (id: string) => `https://www.youtube.com/watch?v=${id}`; const wayback = (id: string): ClipCopy => ({ from: "wayback", url: `https://web.archive.org/web/20240102030405/${watch(id)}` }); const mirror = (id: string): ClipCopy => ({ from: "archive.org", url: `https://archive.org/download/youtube-${id}/An%20upload-${id}.mp4` }); async function corpus() { const dir = await mkdtemp(path.join(os.tmpdir(), "fetch-copies-")); const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, savedVideosDir: path.join(dir, "saved-videos"), ytdlpBin: "/nonexistent/yt-dlp", } as Paths; const channelDir = path.join(paths.channelsDir, SLUG); await mkdir(path.join(channelDir, "data"), { recursive: true }); await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube", url: "https://www.youtube.com/@alpha/videos", audioFormat: "mp3" })); await writeFile(path.join(channelDir, "playlist"), [GONE_A, GONE_B, GONE_C].map(watch).join("\n")); for (const id of [GONE_A, GONE_B, GONE_C]) { const v = path.join(channelDir, "data", id); await mkdir(v, { recursive: true }); await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, title: `Original ${id}`, webpage_url: watch(id), duration: 300, extractor_key: "Youtube" })); await writeFile(path.join(v, "availability.json"), JSON.stringify({ ...GONE_AVAILABILITY, webpageUrl: watch(id) })); } return { dir, paths, dataDir: path.join(channelDir, "data"), close: () => rm(dir, { recursive: true, force: true }) }; } // A fetch that writes the audio (as fetchCopyManaged would), or fails as told. function fakeFetch(fail: Record = {}) { const calls: FetchCopyOpts[] = []; return { calls, fetchCopy: async (o: FetchCopyOpts) => { calls.push(o); const e = fail[o.videoId]; if (e) throw e; await writeFile(path.join(o.videoDir, "audio.mp3"), "audio"); return { audioFile: "audio.mp3", bytes: 5, args: [] }; }, }; } function deps(over: Partial = {}) { const events: string[] = []; const d: Partial = { assertMediaReachable: async () => undefined, sleep: async (ms) => void events.push(`sleep ${ms}`), cooldownRemainingMs: async () => 0, heldRefusal: async () => null, recordBackoff: async (p, _paths, cls) => void events.push(`backoff ${p} ${cls}`), recordClean: async () => null, // Wayback's sidecar is built from the URL alone (no request); archive.org's // would ask the item — the test's own fake is given where it is needed. writeProvenance: async (dir, copy, o) => (copy.from === "wayback" ? writeCopyProvenance(dir, copy, o) : undefined), now: () => new Date("2026-10-16T00:00:00.000Z"), ...over, }; return { d, events }; } test("each copy's audio into its own record: wayback.json, a fetched attempt, the original's metadata kept; the gap between fetches", async () => { const c = await corpus(); try { const f = fakeFetch(); const { d, events } = deps({ fetchCopy: f.fetchCopy }); const items: FetchCopyItem[] = [ { slug: SLUG, id: GONE_A, copy: wayback(GONE_A) }, { slug: SLUG, id: GONE_B, copy: wayback(GONE_B) }, { slug: SLUG, id: GONE_A, copy: mirror(GONE_A) }, // the same recording again: dropped ]; const r = await fetchCopies({ paths: c.paths, items, gapMs: 1234, deps: d }); assert.deepEqual(r.fetched.map((x) => x.id), [GONE_A, GONE_B]); assert.deepEqual(events, ["sleep 1234"], "one gap, between the two fetches"); const dirA = path.join(c.dataDir, GONE_A); assert.equal(f.calls[0]!.videoDir, dirA, "the ORIGINAL record's dir"); const wb = JSON.parse(await readFile(path.join(dirA, "wayback.json"), "utf8")); assert.equal(wb.originalUrl, watch(GONE_A)); assert.equal(wb.captureTs, "20240102030405"); const attempts = (await loadCopyAttempts(dirA))?.attempts ?? []; assert.deepEqual(attempts.map((a) => [a.outcome, a.source, a.captureTs, a.audioFile]), [["fetched", "wayback", "20240102030405", "audio.mp3"]]); assert.equal(JSON.parse(await readFile(path.join(dirA, "metadata.info.json"), "utf8")).title, `Original ${GONE_A}`); } finally { await c.close(); } }); test("archive.org copy: archiveorg.json from the item (the fake), the attempt names its identifier and file", async () => { const c = await corpus(); const ia = await startFakeArchiveOrg({ items: [ { metadata: { identifier: `youtube-${GONE_C}`, title: `An upload ${GONE_C}`, mediatype: "movies", originalurl: watch(GONE_C) }, files: [{ name: `An upload-${GONE_C}.mp4`, source: "original", format: "MPEG4", size: "3000", length: "300" }], }, ], }); try { const client = new ArchiveOrgClient({ fetch: ia.fetch }, { minGapMs: 0 }); const f = fakeFetch(); const { d } = deps({ fetchCopy: f.fetchCopy, writeProvenance: (dir, copy, o) => writeCopyProvenance(dir, copy, { ...o, client }) }); const r = await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_C, copy: mirror(GONE_C) }], deps: d }); assert.equal(r.fetched.length, 1); const dir = path.join(c.dataDir, GONE_C); const prov = await loadArchiveOrgProvenance(dir); assert.equal(prov?.identifier, `youtube-${GONE_C}`); assert.equal(prov?.file, `An upload-${GONE_C}.mp4`); const a = (await loadCopyAttempts(dir))?.attempts?.[0]; assert.deepEqual([a?.outcome, a?.source, a?.identifier, a?.file], ["fetched", "archive.org", `youtube-${GONE_C}`, `An upload-${GONE_C}.mp4`]); assert.equal(JSON.parse(await readFile(path.join(dir, "metadata.info.json"), "utf8")).title, `Original ${GONE_C}`, "the metadata is not the mirror's"); } finally { await ia.close(); await c.close(); } }); test("a copy that failed at its source is recorded (failed + attempt); our own failure is not; a 429 stops the run and backs archive.org off", async () => { const c = await corpus(); try { const f = fakeFetch({ [GONE_A]: new FetchWindowError("ERROR: HTTP Error 404: Not Found", "unknown", "error"), [GONE_B]: new FetchWindowError("ERROR: ffmpeg exited with code 1", "unknown", "error"), [GONE_C]: new FetchWindowError("ERROR: HTTP Error 429: Too Many Requests", "rate_limit", "error"), }); const { d, events } = deps({ fetchCopy: f.fetchCopy }); const items = [GONE_A, GONE_B, GONE_C].map((id) => ({ slug: SLUG, id, copy: wayback(id) })); const r = await fetchCopies({ paths: c.paths, items: [...items, { slug: SLUG, id: "afterStop01", copy: wayback("afterStop01") }], gapMs: 0, deps: d }); assert.deepEqual(r.failed.map((x) => [x.item.id, x.class]), [[GONE_A, "unknown"], [GONE_B, "unknown"], [GONE_C, "rate_limit"]]); assert.equal(r.stopped, "rate-limit"); assert.deepEqual(r.notAttempted.map((x) => x.id), ["afterStop01"]); assert.ok(events.includes("backoff archiveorg rate_limit")); const a = await loadCopyAttempts(path.join(c.dataDir, GONE_A)); assert.deepEqual(a?.failed.map((x) => x.url), [wayback(GONE_A).url]); assert.deepEqual(a?.attempts?.map((x) => x.outcome), ["failed"]); assert.equal(await loadCopyAttempts(path.join(c.dataDir, GONE_B)), null, "ffmpeg is ours: nothing held against the copy"); assert.equal(await loadCopyAttempts(path.join(c.dataDir, GONE_C)), null, "a rate limit says nothing about the copy"); } finally { await c.close(); } }); test("a video holding media by its turn is skipped; an unreachable channel fails its items; a cooldown stops before any request", async () => { const c = await corpus(); try { await writeFile(path.join(c.dataDir, GONE_A, "source-media.mp4"), "x"); const f = fakeFetch(); const r1 = await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_A, copy: wayback(GONE_A) }], deps: deps({ fetchCopy: f.fetchCopy }).d }); assert.deepEqual(r1.skipped.map((s) => s.id), [GONE_A]); const r2 = await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_B, copy: wayback(GONE_B) }], deps: deps({ fetchCopy: f.fetchCopy, assertMediaReachable: async () => Promise.reject(new Error("the drive is not mounted")) }).d, }); assert.deepEqual(r2.failed.map((x) => x.class), ["unreachable"]); const r3 = await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_B, copy: wayback(GONE_B) }], deps: deps({ fetchCopy: f.fetchCopy, cooldownRemainingMs: async () => 60_000 }).d, }); assert.equal(r3.stopped, "cooldown"); assert.equal(f.calls.length, 0, "nothing was fetched"); } finally { await c.close(); } }); test("copyAttemptFields: an archive.org copy's item and file, a Wayback copy's capture", () => { assert.deepEqual(copyAttemptFields(mirror("x0000000001")), { source: "archive.org", url: mirror("x0000000001").url, identifier: "youtube-x0000000001", file: "An upload-x0000000001.mp4", }); assert.equal(copyAttemptFields(wayback("x0000000001")).captureTs, "20240102030405"); assert.equal(copyAttemptFields({ from: "wayback", url: `https://web.archive.org/web/${watch("x")}` }).captureTs, undefined); }); test("the transcription lane picks the audio up: the snapshot moves a gone video from noTranscript to downloadedNoTranscript", async () => { const c = await corpus(); try { const before = await generateChannelSnapshot(c.paths, SLUG); assert.ok(before.buckets.noTranscript.includes(GONE_A)); assert.ok(before.excludedFromDownload?.deleted.includes(GONE_A), "gone: out of the download lane"); assert.ok(!before.undownloadedIds.includes(GONE_A)); const f = fakeFetch(); await fetchCopies({ paths: c.paths, items: [{ slug: SLUG, id: GONE_A, copy: wayback(GONE_A) }], deps: deps({ fetchCopy: f.fetchCopy }).d }); const after = await generateChannelSnapshot(c.paths, SLUG); assert.ok(!after.buckets.noTranscript.includes(GONE_A)); assert.ok(after.buckets.downloadedNoTranscript.includes(GONE_A), "the transcription lane's first bucket"); assert.ok(after.backfill?.transcription?.ids.includes(GONE_A), "and its work list"); assert.ok(after.excludedFromDownload?.deleted.includes(GONE_A), "still gone on its platform"); } finally { await c.close(); } }); // Review 3 S5: fetch-copies passes X's queue rule because it asks archive.org // (lib/xJobRule.ts xJobAsksX). A "copy" whose address is X's is therefore // never fetched here: it fails before any request, and the run goes on. test("review 3 S5: a copy whose address is X's is refused before any request; the others are fetched", async () => { const c = await corpus(); try { const f = fakeFetch(); const { d } = deps({ fetchCopy: f.fetchCopy }); const items: FetchCopyItem[] = [ { slug: SLUG, id: GONE_A, copy: { from: "wayback", url: "https://x.com/example/status/1900000000000003001" } }, { slug: SLUG, id: GONE_B, copy: { from: "archive.org", url: "https://t.co/AbCdEf123" } }, { slug: SLUG, id: GONE_C, copy: wayback(GONE_C) }, ]; const r = await fetchCopies({ paths: c.paths, items, gapMs: 0, deps: d }); assert.deepEqual(r.failed.map((x) => [x.item.id, x.class]), [[GONE_A, "not-a-copy"], [GONE_B, "not-a-copy"]]); for (const x of r.failed) assert.match(x.message, /is X's: a copy is archive\.org's .* nothing was asked of X/); assert.deepEqual(f.calls.map((x) => x.videoId), [GONE_C], "only the archive.org copy was fetched"); } finally { await c.close(); } });