// A retry of a corrupt-full-source video refetches it (release 30, lane Q): // the kept file is moved aside for the download; a clean result removes it, a // malformed one keeps the longer decode, anything else moves it back and the // sidecar stays corrupt-full-source with the failed attempt appended. Temp // dirs, a fake measure, and (for the whole path) a fake yt-dlp that answers // the metadata prefetch with a 429 — the failure observed live 2026-10-15. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/corruptRefetch.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { existsSync } from "node:fs"; import { chmod, lstat, mkdir, mkdtemp, readFile, readlink, readdir, rm, writeFile, } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; import { tierMediaFile } from "../lib/mediaTier-server"; import { CORRUPT_KEPT_SUFFIX, prepareCorruptRefetch, settleCorruptRefetch, } from "./corruptRefetch"; import { downloadOneManaged } from "./downloadOneManaged"; import { destinationExists } from "./runYtdlp"; import { generateChannelSnapshot } from "../controller/channelSnapshot"; import { fileIdentity, heldAudioDamage, integrityRecord, writeAudioIntegrity, } from "../lib/audioIntegrity-server"; const ID = "H64QQZuw-aA"; const PATHS = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" }; function cfsRecord(over: Partial = {}): DownloadOutcomeRecord { return { videoId: ID, status: "corrupt-full-source", startedAt: "2026-10-01T00:00:00.000Z", finishedAt: "2026-10-01T01:00:00.000Z", attempts: [ { n: 0, kind: "metadata-prefetch", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0 }, { n: 1, kind: "audio-checked-primary", handling: "transcribe", usedCookies: false, ytdlpExitCode: 0, audioCheck: { checkpoints: 9, rollbacks: 2, restarts: 0, finalProbeVerdict: "malformed" }, }, ], ...over, }; } function outcome(over: Partial): DownloadOutcomeRecord { return { videoId: ID, status: "failed", startedAt: "2026-10-15T00:00:00.000Z", finishedAt: "2026-10-15T00:05:00.000Z", attempts: [], ...over, }; } async function fixture(opts: { tiered?: boolean; status?: DownloadOutcomeRecord } = {}) { const root = await mkdtemp(path.join(tmpdir(), "corrupt-refetch-")); const channelsDir = path.join(root, "channels"); const videoDir = path.join(channelsDir, "c", "data", ID); await mkdir(videoDir, { recursive: true }); await writeFile(path.join(videoDir, "audio.mp4"), "OLD-MALFORMED"); await writeFile(path.join(videoDir, "metadata.info.json"), "{}"); await writeFile( path.join(videoDir, "download-outcome.json"), JSON.stringify(opts.status ?? cfsRecord()), ); if (opts.tiered) { await mkdir(path.join(channelsDir, "c", "media")); assert.equal(await tierMediaFile(videoDir, "audio.mp4"), "tiered"); } return { root, channelsDir, videoDir }; } const readOutcome = async (videoDir: string): Promise => JSON.parse(await readFile(path.join(videoDir, "download-outcome.json"), "utf8")); function ctx(measure?: Record) { const log: string[] = []; return { log, ctx: { paths: PATHS, onLog: (l: string) => log.push(l), deps: { measure: async (file: string) => { const body = await readFile(file, "utf8").catch(() => ""); return measure?.[body] ?? null; }, }, }, }; } test("any other video is not a refetch: nothing moves", async () => { const f = await fixture({ status: { ...cfsRecord(), status: "ok-audio-checked" } }); const { ctx: c } = ctx(); assert.equal(await prepareCorruptRefetch(f.videoDir, c), null); assert.ok(existsSync(path.join(f.videoDir, "audio.mp4"))); await rm(f.root, { recursive: true, force: true }); }); test("a clean refetch: the kept file is removed, the history says clean", async () => { const f = await fixture(); const { ctx: c } = ctx(); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); assert.deepEqual(plan.asides, ["audio.mp4"]); assert.equal(existsSync(path.join(f.videoDir, "audio.mp4")), false); assert.equal(await readFile(path.join(f.videoDir, "audio.mp4" + CORRUPT_KEPT_SUFFIX), "utf8"), "OLD-MALFORMED"); // The download lands a clean file. await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-CLEAN"); const rec = await settleCorruptRefetch(plan, outcome({ status: "ok-audio-checked" }), c); assert.equal(rec.status, "ok-audio-checked"); assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "NEW-CLEAN"); assert.deepEqual((await readdir(f.videoDir)).filter((n) => n.endsWith(CORRUPT_KEPT_SUFFIX)), []); const disk = await readOutcome(f.videoDir); assert.equal(disk.status, "ok-audio-checked"); assert.equal(disk.corruptRefetches?.length, 1); assert.equal(disk.corruptRefetches?.[0].result, "clean"); await rm(f.root, { recursive: true, force: true }); }); test("still malformed: the longer decode stays — the earlier copy here", async () => { const f = await fixture(); const { ctx: c } = ctx({ "OLD-MALFORMED": 5700, "NEW-MALFORMED": 2335 }); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-MALFORMED"); const newAttempt = { n: 1, kind: "audio-checked-primary" as const, handling: "transcribe" as const, usedCookies: false, ytdlpExitCode: 0 }; const rec = await settleCorruptRefetch( plan, outcome({ status: "corrupt-full-source", attempts: [newAttempt] }), c, ); assert.equal(rec.status, "corrupt-full-source"); assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "OLD-MALFORMED"); assert.deepEqual((await readdir(f.videoDir)).filter((n) => n.endsWith(CORRUPT_KEPT_SUFFIX)), []); const disk = await readOutcome(f.videoDir); assert.equal(disk.status, "corrupt-full-source"); assert.equal(disk.attempts.length, 3, "the earlier attempts and the refetch's"); assert.deepEqual(disk.corruptRefetches?.[0], { startedAt: plan.startedAt, finishedAt: "2026-10-15T00:05:00.000Z", result: "still-malformed", status: "corrupt-full-source", kept: "previous", decodedSeconds: { previous: 5700, new: 2335 }, }); await rm(f.root, { recursive: true, force: true }); }); test("still malformed: the new copy stays when it decodes longer", async () => { const f = await fixture(); const { ctx: c } = ctx({ "OLD-MALFORMED": 2335, "NEW-MALFORMED": 5760 }); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-MALFORMED"); await settleCorruptRefetch(plan, outcome({ status: "corrupt-full-source" }), c); assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "NEW-MALFORMED"); assert.equal((await readOutcome(f.videoDir)).corruptRefetches?.[0].kept, "new"); await rm(f.root, { recursive: true, force: true }); }); test("a failed refetch moves the kept file back and the status stays (tier link and all)", async () => { const f = await fixture({ tiered: true }); const { ctx: c } = ctx(); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); const aside = path.join(f.videoDir, "audio.mp4" + CORRUPT_KEPT_SUFFIX); assert.ok((await lstat(aside)).isSymbolicLink()); assert.equal(await readlink(aside), `../../media/${ID}/audio.mp4${CORRUPT_KEPT_SUFFIX}`); const failedAttempt = { n: 0, kind: "metadata-prefetch" as const, handling: "transcribe" as const, usedCookies: false, ytdlpExitCode: 1, error: "ERROR: HTTP Error 429: Too Many Requests", }; const rec = await settleCorruptRefetch( plan, outcome({ status: "failed", failureClass: "rate_limit", attempts: [failedAttempt] }), c, ); // The caller still sees the failure, so the batch backs the platform off. assert.equal(rec.status, "failed"); assert.equal(rec.failureClass, "rate_limit"); // The kept file is back under its name, still a link into media/. const link = path.join(f.videoDir, "audio.mp4"); assert.equal(await readlink(link), `../../media/${ID}/audio.mp4`); assert.equal(await readFile(link, "utf8"), "OLD-MALFORMED"); assert.equal(existsSync(path.join(f.channelsDir, "c", "media", ID, "audio.mp4" + CORRUPT_KEPT_SUFFIX)), false); const disk = await readOutcome(f.videoDir); assert.equal(disk.status, "corrupt-full-source"); assert.equal(disk.attempts.length, 3); assert.equal(disk.attempts[1].audioCheck?.finalProbeVerdict, "malformed", "the history is kept"); assert.equal(disk.corruptRefetches?.[0].result, "failed"); assert.equal(disk.corruptRefetches?.[0].failureClass, "rate_limit"); assert.match(disk.corruptRefetches?.[0].error ?? "", /429/); await rm(f.root, { recursive: true, force: true }); }); test("a failed refetch that left a short file: the short file goes, the kept one comes back", async () => { const f = await fixture(); const { ctx: c } = ctx(); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); await writeFile(path.join(f.videoDir, "audio.mp4"), "SHORT"); await settleCorruptRefetch(plan, outcome({ status: "failed-short-audio" }), c); assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "OLD-MALFORMED"); assert.equal((await readOutcome(f.videoDir)).status, "corrupt-full-source"); await rm(f.root, { recursive: true, force: true }); }); test("a refetch cut short is settled by the next one: the kept file comes back first", async () => { const f = await fixture(); const { ctx: c } = ctx(); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); // …killed here. The next retry starts: const { ctx: c2, log } = ctx(); const again = await prepareCorruptRefetch(f.videoDir, c2); assert.ok(again); assert.deepEqual(again.asides, ["audio.mp4"]); assert.match(log.join(""), /left by an interrupted refetch, back to audio\.mp4/); assert.equal( await readFile(path.join(f.videoDir, "audio.mp4" + CORRUPT_KEPT_SUFFIX), "utf8"), "OLD-MALFORMED", ); await rm(f.root, { recursive: true, force: true }); }); test("the retry's prefilter asks again for a corrupt full source; a sweep still counts it as there", async () => { const f = await fixture(); const dataDir = path.dirname(f.videoDir); assert.equal(await destinationExists(dataDir, ID, "transcribe"), true); assert.equal( await destinationExists(dataDir, ID, "transcribe", { refetchCorruptFullSource: true }), false, ); // A salvage transcript does not stop the retry either. await writeFile(path.join(f.videoDir, "transcript.json"), "{}"); assert.equal( await destinationExists(dataDir, ID, "transcribe", { refetchCorruptFullSource: true }), false, ); await rm(f.root, { recursive: true, force: true }); }); test("the whole path: a 429 at the prefetch leaves the video corrupt-full-source, its file in place", async () => { const f = await fixture(); const bin = path.join(f.root, "fake-ytdlp.sh"); await writeFile( bin, `#!/bin/sh\necho "ERROR: [youtube] ${ID}: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2\nexit 1\n`, ); await chmod(bin, 0o755); const paths = { channelsDir: f.channelsDir, ytdlpBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as Paths; let log = ""; const record = await downloadOneManaged({ channelSlug: "c", channelConfig: { handling: "transcribe", url: "https://www.youtube.com/@c/videos", audioCheck: { enabled: true }, } as ChannelConfig, paths, videoUrl: `https://www.youtube.com/watch?v=${ID}`, onLog: (s) => { log += s; }, signal: new AbortController().signal, }); assert.equal(record.status, "failed"); assert.equal(record.failureClass, "rate_limit"); assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "OLD-MALFORMED"); const disk = await readOutcome(f.videoDir); assert.equal(disk.status, "corrupt-full-source"); assert.deepEqual( disk.attempts.map((a) => a.kind), ["metadata-prefetch", "audio-checked-primary", "metadata-prefetch"], ); assert.equal(disk.corruptRefetches?.[0].failureClass, "rate_limit"); assert.match(log, /Corrupt full source: refetching/); assert.match(log, /stays corrupt-full-source/); await rm(f.root, { recursive: true, force: true }); }); test("a clean refetch retires a salvage transcript: the video is downloaded-not-transcribed again", async () => { const f = await fixture(); const channelDir = path.join(f.channelsDir, "c"); await writeFile( path.join(channelDir, "config.json"), JSON.stringify({ handling: "transcribe", url: "https://www.youtube.com/@c/videos" }), ); await writeFile(path.join(channelDir, "playlist"), `https://www.youtube.com/watch?v=${ID}\n`); await writeFile(path.join(f.videoDir, "metadata.info.json"), JSON.stringify({ id: ID, duration: 6000 })); const salvaged = { source: "audio.mp4", decodedSeconds: 2335, totalSeconds: 6000, gaps: [[2335, 6000]] }; await writeFile(path.join(f.videoDir, "transcript.json"), "{}"); await writeFile(path.join(f.videoDir, "transcript.cues.json"), "{}"); await writeFile( path.join(f.videoDir, "transcribe-outcome.json"), JSON.stringify({ videoId: ID, transcribedAt: "2026-10-15T00:00:00.000Z", salvaged }), ); const paths = { channelsDir: f.channelsDir } as Paths; const before = await generateChannelSnapshot(paths, "c"); assert.deepEqual(before.buckets.salvagedTranscript, [ID]); const { ctx: c, log } = ctx(); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-CLEAN"); await settleCorruptRefetch(plan, outcome({ status: "ok-audio-checked" }), c); for (const name of ["transcript.json", "transcript.cues.json", "transcribe-outcome.json"]) { assert.equal(existsSync(path.join(f.videoDir, name)), false, `${name} retired`); } assert.match(log.join(""), /Retired the salvage transcript/); const disk = await readOutcome(f.videoDir); assert.deepEqual(disk.corruptRefetches?.[0].retiredSalvage, { ...salvaged, transcribedAt: "2026-10-15T00:00:00.000Z", }); const after = await generateChannelSnapshot(paths, "c"); assert.deepEqual(after.buckets.downloadedNoTranscript, [ID]); assert.deepEqual(after.buckets.salvagedTranscript, []); assert.deepEqual(after.buckets.corruptFullSource, []); await rm(f.root, { recursive: true, force: true }); }); test("a clean refetch leaves a transcript that is not a salvage alone", async () => { const f = await fixture(); await writeFile(path.join(f.videoDir, "transcript.json"), "{}"); await writeFile( path.join(f.videoDir, "transcribe-outcome.json"), JSON.stringify({ videoId: ID, transcribedAt: "2026-10-15T00:00:00.000Z" }), ); const { ctx: c } = ctx(); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-CLEAN"); await settleCorruptRefetch(plan, outcome({ status: "ok-audio-checked" }), c); assert.ok(existsSync(path.join(f.videoDir, "transcript.json"))); assert.equal((await readOutcome(f.videoDir)).corruptRefetches?.[0].retiredSalvage, undefined); await rm(f.root, { recursive: true, force: true }); }); // --------------------------------------------------------------------------- // Release 31, lane A: held audio the audio audit found damaged is the second // trigger. Its outcome is an old `ok` (or nothing); a failed refetch restores // THAT, never a corrupt-full-source status it never had. // --------------------------------------------------------------------------- async function heldFixture(opts: { status?: DownloadOutcomeRecord | null; verdict?: "damaged" | "clean"; tiered?: boolean } = {}) { const f = await fixture({ tiered: opts.tiered, status: opts.status ?? undefined }); if (opts.status === null) await rm(path.join(f.videoDir, "download-outcome.json")); else if (opts.status === undefined) { await writeFile( path.join(f.videoDir, "download-outcome.json"), JSON.stringify(outcome({ status: "ok", startedAt: "2026-01-01T00:00:00.000Z", finishedAt: "2026-01-01T00:10:00.000Z" })), ); } const id = await fileIdentity(path.join(f.videoDir, "audio.mp4")); await writeAudioIntegrity( f.videoDir, integrityRecord( "audio.mp4", id, opts.verdict === "clean" ? { decodedSeconds: 600, totalSeconds: 600, gaps: [] } : { decodedSeconds: 300, totalSeconds: 600, gaps: [[300, 600]] }, { by: "audit" }, ), ); return f; } function heldCtx(audits: string[]) { const c = ctx(); return { ...c, ctx: { ...c.ctx, deps: { ...c.ctx.deps, audit: async (videoDir: string, file: string) => { audits.push(`${path.basename(videoDir)}/${file}=${await readFile(path.join(videoDir, file), "utf8")}`); return null; }, }, }, }; } test("damaged held audio is a refetch; a clean one is not; a stale record is not", async () => { const f = await heldFixture(); const { ctx: c, log } = heldCtx([]); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); assert.equal(plan.trigger, "damaged-held-audio"); assert.equal(plan.previous?.status, "ok"); assert.deepEqual(plan.asides, ["audio.mp4"]); assert.match(log.join(""), /Damaged held audio: refetching \(the audit: damaged: 5:00 of 10:00 decodes \(50%\), 1 gap\)/); await rm(f.root, { recursive: true, force: true }); const clean = await heldFixture({ verdict: "clean" }); assert.equal(await prepareCorruptRefetch(clean.videoDir, heldCtx([]).ctx), null); await rm(clean.root, { recursive: true, force: true }); const stale = await heldFixture(); await writeFile(path.join(stale.videoDir, "audio.mp4"), "OLD-MALFORMED-BUT-LONGER"); assert.equal(await prepareCorruptRefetch(stale.videoDir, heldCtx([]).ctx), null); await rm(stale.root, { recursive: true, force: true }); }); test("damaged held audio, clean refetch: the kept file goes, the new one is audited, the history says why", async () => { const f = await heldFixture({ tiered: true }); const audits: string[] = []; const { ctx: c, log } = heldCtx(audits); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-CLEAN"); const rec = await settleCorruptRefetch(plan, outcome({ status: "ok-audio-checked" }), c); assert.equal(rec.status, "ok-audio-checked"); assert.deepEqual(rec.corruptRefetches?.map((r) => [r.result, r.trigger]), [["clean", "damaged-held-audio"]]); assert.deepEqual((await readdir(f.videoDir)).filter((n) => n.endsWith(CORRUPT_KEPT_SUFFIX)), []); assert.equal(existsSync(path.join(f.channelsDir, "c", "media", ID, "audio.mp4" + CORRUPT_KEPT_SUFFIX)), false); assert.deepEqual(audits, [`${ID}/audio.mp4=NEW-CLEAN`]); assert.match(log.join(""), /Damaged held audio: the refetch is clean; removed the kept audio\.mp4/); await rm(f.root, { recursive: true, force: true }); }); test("damaged held audio, failed refetch: the file and its OLD ok record come back; the audit record speaks for it again", async () => { const f = await heldFixture({ tiered: true }); const before = await fileIdentity(path.join(f.videoDir, "audio.mp4")); const audits: string[] = []; const { ctx: c, log } = heldCtx(audits); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); const rec = await settleCorruptRefetch(plan, outcome({ status: "failed", failureClass: "rate_limit" }), c); assert.equal(rec.status, "failed", "the caller sees the failure"); const disk = await readOutcome(f.videoDir); assert.equal(disk.status, "ok", "never a corrupt-full-source status it never had"); assert.equal(disk.corruptRefetches?.[0].trigger, "damaged-held-audio"); assert.equal(disk.corruptRefetches?.[0].result, "failed"); assert.deepEqual(await fileIdentity(path.join(f.videoDir, "audio.mp4")), before, "size and mtime kept"); assert.ok(await heldAudioDamage(f.videoDir), "still damaged held audio, so still in the bucket"); assert.deepEqual(audits, [], "nothing new to audit"); assert.match(log.join(""), /the held audio stays as it was/); await rm(f.root, { recursive: true, force: true }); }); test("damaged held audio with no outcome record: a failed refetch keeps the download's own, with the retry", async () => { const f = await heldFixture({ status: null }); const { ctx: c } = heldCtx([]); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); assert.equal(plan.previous, null); await settleCorruptRefetch(plan, outcome({ status: "failed", failureClass: "network" }), c); const disk = await readOutcome(f.videoDir); assert.equal(disk.status, "failed"); assert.equal(disk.corruptRefetches?.length, 1); assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "OLD-MALFORMED"); await rm(f.root, { recursive: true, force: true }); }); test("damaged held audio, malformed again: the longer decode stays, the video is a corrupt full source, re-audited", async () => { const f = await heldFixture(); const audits: string[] = []; const { ctx: c } = heldCtx(audits); c.deps.measure = async (file: string) => ((await readFile(file, "utf8")).startsWith("NEW") ? 500 : 300); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-MALFORMED"); const rec = await settleCorruptRefetch(plan, outcome({ status: "corrupt-full-source" }), c); assert.equal(rec.status, "corrupt-full-source"); assert.equal(rec.corruptRefetches?.[0].kept, "new"); assert.equal(await readFile(path.join(f.videoDir, "audio.mp4"), "utf8"), "NEW-MALFORMED"); assert.deepEqual(audits, [`${ID}/audio.mp4=NEW-MALFORMED`]); await rm(f.root, { recursive: true, force: true }); }); test("a refetch of damaged held audio cut mid-download: the old ok record does not make the kept copy disposable", async () => { const f = await heldFixture(); const { ctx: c } = heldCtx([]); const plan = await prepareCorruptRefetch(f.videoDir, c); assert.ok(plan); // …killed before the download wrote anything. The next refetch starts: const { ctx: c2, log } = heldCtx([]); const again = await prepareCorruptRefetch(f.videoDir, c2); assert.ok(again, "the restored file is still damaged held audio"); assert.match(log.join(""), /back to audio\.mp4/); assert.equal( await readFile(path.join(f.videoDir, "audio.mp4" + CORRUPT_KEPT_SUFFIX), "utf8"), "OLD-MALFORMED", ); assert.equal((await readOutcome(f.videoDir)).status, "ok", "and never rewritten corrupt-full-source"); await rm(f.root, { recursive: true, force: true }); }); test("the retry's prefilter asks again for damaged held audio; a sweep still counts it as there", async () => { const f = await heldFixture(); const dataDir = path.dirname(f.videoDir); assert.equal(await destinationExists(dataDir, ID, "transcribe"), true); assert.equal(await destinationExists(dataDir, ID, "transcribe", { refetchDamagedAudio: true }), false); await rm(f.root, { recursive: true, force: true }); });