// A RETRY OF A corrupt-full-source VIDEO REFETCHES IT (release 30, lane Q). // // corrupt-full-source is a download that completed but whose audio stayed // malformed after the audio check's one re-download; the container is KEPT. // For a source that serves malformed audio intermittently (Odysee's AAC) the // next request can come back clean, but the kept file made every retry a // no-op: the batch prefilter read it as "already complete" ("Prefilter: 0 // missing destination files, 7 already complete … Nothing to fetch", observed // 2026-10-15). So every managed download of a video whose outcome is // corrupt-full-source goes through here (downloadOneManaged): // // prepare the kept media file(s) are moved ASIDE in the same dir // (`audio.mp4` → `audio.mp4.corrupt-kept`, through the tier link // when it is one — lib/mediaTier-server.ts renameMediaFile), so // the download writes a fresh file. // settle after the download, by what it ended as: // clean the aside file is removed; // still malformed whichever copy decodes LONGER is kept, the // other removed (lib/salvageAudio-server.ts); // anything else (a 429, the network, a filter, a cancel) the // new file, if any, is removed, the aside file // moved BACK, and the sidecar keeps saying // corrupt-full-source — with the failed // attempts appended, so the bucket and its // history survive a failed retry. // Every retry is recorded in the sidecar's `corruptRefetches`. // // THE CALLER STILL SEES THE FAILURE. On the "anything else" path the record // returned is the download's own (status `failed`, its failureClass): a batch // backs the platform off on a 429 exactly as for any other video. Only the // sidecar on disk keeps the corrupt-full-source status — the snapshot reads // that, and it is the single classifier (controller/channelSnapshot.ts). // // A RUN CUT SHORT (killed between moving the file aside and settling) leaves // an `.corrupt-kept` file behind; the next prepare resolves it first. // // HELD AUDIO THE AUDIT FOUND DAMAGED IS REFETCHED THE SAME WAY (release 31, // lane A). A video whose `audio-integrity.json` (controller/audioAudit.ts) // still speaks for a real audio file it holds — same name, size and mtime — // and judges it damaged is the second trigger: the same aside, the same // settle, with three differences. // - Its outcome may be anything (`ok` from before the audio check, or no // sidecar at all); a failed refetch restores THAT record (or, with none, // keeps the download's own), never a corrupt-full-source status it never // had. The file is renamed back with its mtime, so the audit's record // speaks for it again and the video stays in corruptHeldAudio. // - downloadOneManaged turns the audio check ON for the refetch on a // transcribe-handling channel that has it off: a refetch that cannot tell // clean from malformed would be a coin toss. // - After a clean or still-malformed refetch the kept file is decoded again // and `audio-integrity.json` rewritten (`by: "refetch"`) — also for a // corrupt full source that carries one. // Its CorruptRefetch entries carry `trigger: "damaged-held-audio"`. import path from "node:path"; import { readdir, stat } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import type { CorruptRefetch, DownloadOutcomeRecord, } from "../lib/downloadOutcome"; import { loadDownloadOutcome, writeDownloadOutcome, } from "../lib/downloadOutcome-server"; import { isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles"; import { removeMediaFile, renameMediaFile, tierVideoDir, } from "../lib/mediaTier-server"; import { scanDecodable } from "../lib/salvageAudio-server"; import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server"; import { TRANSCRIBE_OUTCOME_FILENAME, type TranscriptSalvage, } from "../lib/transcribeOutcome"; import { CUES_JSON_FILENAME, WHISPER_FILENAME } from "../lib/videoStatus"; import { AUDIO_INTEGRITY_FILENAME, describeIntegrity, type AudioIntegrityRecord, } from "../lib/audioIntegrity"; import { heldAudioDamage, loadAudioIntegrity, measureAndRecordIntegrity, } from "../lib/audioIntegrity-server"; export const CORRUPT_KEPT_SUFFIX = ".corrupt-kept"; export function isCorruptKeptName(name: string): boolean { return name.endsWith(CORRUPT_KEPT_SUFFIX) && name.length > CORRUPT_KEPT_SUFFIX.length; } function originalName(aside: string): string { return aside.slice(0, -CORRUPT_KEPT_SUFFIX.length); } export type CorruptRefetchDeps = { // Seconds of a file that decode (null: not measurable). Default: one // tolerant ffmpeg decode (scanDecodable). measure?: (file: string) => Promise; // The re-audit after a clean or still-malformed refetch (release 31, lane // A). Default: one tolerant decode, written to audio-integrity.json. audit?: (videoDir: string, file: string) => Promise; now?: () => Date; }; // Why a download is a refetch. export type CorruptRefetchTrigger = "corrupt-full-source" | "damaged-held-audio"; export type CorruptRefetchPlan = { videoDir: string; trigger: CorruptRefetchTrigger; // The record the retry started from: corrupt-full-source for that trigger; // for damaged held audio whatever was there, or null. previous: DownloadOutcomeRecord | null; // damaged-held-audio: the audit's record that made it one. damage?: AudioIntegrityRecord; // The original names moved aside (each now `.corrupt-kept`). asides: string[]; startedAt: string; }; type Ctx = { paths: Pick; onLog: (line: string) => void; signal?: AbortSignal; deps?: CorruptRefetchDeps; }; function measureWith(ctx: Ctx): (file: string) => Promise { if (ctx.deps?.measure) return ctx.deps.measure; return async (file) => { const scan = await scanDecodable(file, { ffmpegBin: ctx.paths.ffmpegBin, ffprobeBin: ctx.paths.ffprobeBin, signal: ctx.signal, onLog: ctx.onLog, }); return scan ? scan.decodedSeconds : null; }; } // Of two copies of a recording, keep the one that decodes longer. `current` // is the file under its own name, `aside` a set-aside copy that goes back to // `restoreAs` when it wins (its own original name — an earlier download may // have had another extension). Afterwards only the kept copy remains. // Unmeasurable counts as nothing; a tie keeps the current (newer) copy; when // NEITHER can be measured the aside copy (the one already known to mostly // decode) is kept. async function keepLonger( videoDir: string, current: string, aside: string, restoreAs: string, ctx: Ctx, ): Promise<{ kept: "new" | "previous"; current: number | null; aside: number | null }> { const measure = measureWith(ctx); const cur = await measure(path.join(videoDir, current)); const old = await measure(path.join(videoDir, aside)); const keepCurrent = cur !== null && (old === null || cur >= old); if (keepCurrent) { await removeMediaFile(videoDir, aside); } else { await removeMediaFile(videoDir, current); await renameMediaFile(videoDir, aside, restoreAs); } return { kept: keepCurrent ? "new" : "previous", current: cur, aside: old }; } // What an earlier run left set aside: settle it before anything else. With // the sidecar still corrupt-full-source (or a failure the run never settled) // the kept file goes back — or, when a new file is there too, the longer // decode stays; after a clean download it is simply removed. async function resolveLeftovers(videoDir: string, entries: string[], ctx: Ctx): Promise { const leftovers = entries.filter(isCorruptKeptName); if (leftovers.length === 0) return; const record = await loadDownloadOutcome(videoDir); const finished = record ? Date.parse(record.finishedAt) : Number.NaN; for (const aside of leftovers) { const name = originalName(aside); // "The download since was clean" needs a clean record written AFTER the // file was set aside (its ctime is the rename's). Damaged held audio's // own record is often an old `ok` (release 31, lane A) — removing the // aside on that would lose the only copy of a run cut mid-download. const asideAt = await stat(path.join(videoDir, aside)) .then((st) => st.ctimeMs) .catch(() => Number.NaN); const clean = record?.status.startsWith("ok") === true && Number.isFinite(finished) && Number.isFinite(asideAt) && finished >= asideAt; if (clean) { ctx.onLog(`Removing ${aside} left by an earlier refetch: the download since was clean.\n`); await removeMediaFile(videoDir, aside); } else if (!entries.includes(name)) { ctx.onLog(`Moving ${aside}, left by an interrupted refetch, back to ${name}.\n`); await renameMediaFile(videoDir, aside, name); } else { const r = await keepLonger(videoDir, name, aside, name, ctx); ctx.onLog( `An interrupted refetch left two copies of ${name}; kept the ${r.kept === "new" ? "newer" : "earlier"} one ` + `(${r.current ?? "?"}s vs ${r.aside ?? "?"}s decode).\n`, ); } } // A failure written but never settled: the video is still the corrupt // source it was, and its bucket says so. Not when the aside was damaged // held audio (release 31, lane A) — the audit's record names it: that // video never was a corrupt full source, and its bucket is the audit // record, which the restored file matches again. const audited = entries.includes(AUDIO_INTEGRITY_FILENAME) ? (await loadAudioIntegrity(videoDir))?.file : undefined; const heldTrigger = audited !== undefined && leftovers.some((a) => originalName(a) === audited); if ( record && !heldTrigger && !record.status.startsWith("ok") && record.status !== "corrupt-full-source" ) { await writeDownloadOutcome(videoDir, { ...record, status: "corrupt-full-source" }); } } // A SALVAGE TRANSCRIPT OUTLIVES ITS FILE (operator ruling, 2026-10-15): when a // refetch comes back clean and the video's transcript is a salvage // (transcribe-outcome.json `salvaged`), the transcript, its cues and its // outcome go — through removeMediaFile, the one remover of a video-dir entry — // and the video is downloaded-not-transcribed again, for the lane to redo from // the clean audio. What was retired is returned for the refetch's record. // Any other transcript (a clean one, a caption track) is left alone. async function retireSalvagedTranscript( videoDir: string, onLog: (line: string) => void, ): Promise<(TranscriptSalvage & { transcribedAt: string }) | null> { const entries = await readdir(videoDir).catch(() => [] as string[]); if (!entries.includes(WHISPER_FILENAME) || !entries.includes(TRANSCRIBE_OUTCOME_FILENAME)) { return null; } const record = await loadTranscribeOutcome(videoDir); const salvaged = record?.salvaged; if (!record || !salvaged) return null; for (const name of [WHISPER_FILENAME, CUES_JSON_FILENAME, TRANSCRIBE_OUTCOME_FILENAME]) { await removeMediaFile(videoDir, name); } onLog( `Retired the salvage transcript (${salvaged.decodedSeconds}s of ${salvaged.totalSeconds}s, ` + `${salvaged.gaps.length} gap(s)): the clean audio is transcribed again in full.\n`, ); return { ...salvaged, transcribedAt: record.transcribedAt }; } // Before a managed download: when this video's outcome is corrupt-full-source, // move its kept media aside and say so. Null when the video is anything else // (or has no outcome) — the download is then an ordinary one. Throws when the // kept file cannot be moved aside: downloading over it could leave the // malformed bytes under a status that calls them clean. export async function prepareCorruptRefetch( videoDir: string, ctx: Ctx, ): Promise { const first = await readdir(videoDir).catch(() => [] as string[]); await resolveLeftovers(videoDir, first, ctx); const previous = await loadDownloadOutcome(videoDir); const entries = await readdir(videoDir).catch(() => [] as string[]); let trigger: CorruptRefetchTrigger; let damage: AudioIntegrityRecord | undefined; if (previous?.status === "corrupt-full-source") { trigger = "corrupt-full-source"; } else { const held = await heldAudioDamage(videoDir, entries); if (!held) return null; trigger = "damaged-held-audio"; damage = held.record; } const kept = entries.filter(isRealAudioFile); const asides: string[] = []; try { for (const name of kept) { await renameMediaFile(videoDir, name, name + CORRUPT_KEPT_SUFFIX); asides.push(name); } } catch (err) { for (const name of asides) { await renameMediaFile(videoDir, name + CORRUPT_KEPT_SUFFIX, name).catch(() => {}); } throw new Error( `could not move the kept file aside for a refetch: ${(err as Error).message}`, ); } ctx.onLog( trigger === "damaged-held-audio" ? `Damaged held audio: refetching (the audit: ${describeIntegrity(damage!)}). The kept ${kept.join(", ")} is set aside until the download ends.\n` : kept.length > 0 ? `Corrupt full source: refetching. The kept ${kept.join(", ")} is set aside until the download ends.\n` : `Corrupt full source: refetching (no kept file on disk).\n`, ); return { videoDir, trigger, previous, ...(damage ? { damage } : {}), asides, startedAt: (ctx.deps?.now?.() ?? new Date()).toISOString(), }; } // After the managed download: decide which file stays and write the sidecar. // Returns the record the CALLER should see (see the header). export async function settleCorruptRefetch( plan: CorruptRefetchPlan, outcome: DownloadOutcomeRecord, ctx: Ctx, ): Promise { const { videoDir, previous, asides } = plan; const held = plan.trigger === "damaged-held-audio"; const who = held ? "Damaged held audio" : "Corrupt full source"; const entries = await readdir(videoDir).catch(() => [] as string[]); const fresh = entries.filter(isRealAudioFile); const lastError = outcome.attempts.at(-1)?.error; const base: CorruptRefetch = { startedAt: plan.startedAt, finishedAt: outcome.finishedAt, result: "failed", status: outcome.status, ...(outcome.failureClass ? { failureClass: outcome.failureClass } : {}), ...(held ? { trigger: "damaged-held-audio" as const } : {}), }; const history = previous?.corruptRefetches ?? []; // The kept file decoded again, its audit record rewritten: always for // damaged held audio, and for a corrupt full source that carries a record // (a stale one would otherwise linger beside a new file). const reaudit = async () => { const now = await readdir(videoDir).catch(() => [] as string[]); if (!held && !now.includes(AUDIO_INTEGRITY_FILENAME)) return; const file = pickPreferredAudio(now.filter(isRealAudioFile)); if (!file) return; const audit = ctx.deps?.audit ?? ((dir: string, name: string) => measureAndRecordIntegrity( dir, name, { ffmpegBin: ctx.paths.ffmpegBin, ffprobeBin: ctx.paths.ffprobeBin, signal: ctx.signal, onLog: ctx.onLog }, { by: "refetch" }, )); try { const r = await audit(videoDir, file); ctx.onLog(r ? `Audio audit of ${file}: ${describeIntegrity(r)}.\n` : `Audio audit of ${file}: not measured.\n`); } catch (err) { ctx.onLog(`Audio audit of ${file} failed: ${(err as Error).message}\n`); } }; const removeAsides = async () => { for (const name of asides) await removeMediaFile(videoDir, name + CORRUPT_KEPT_SUFFIX); }; // CLEAN: the new file stands, the kept one goes — and a salvage transcript // made from it is retired, so the transcription lane makes a full one. if (outcome.status.startsWith("ok") && fresh.length > 0) { await removeAsides(); const retiredSalvage = await retireSalvagedTranscript(videoDir, ctx.onLog); const record: DownloadOutcomeRecord = { ...outcome, corruptRefetches: [ ...history, { ...base, result: "clean", ...(retiredSalvage ? { retiredSalvage } : {}) }, ], }; await writeDownloadOutcome(videoDir, record); ctx.onLog( `${who}: the refetch is clean${asides.length ? `; removed the kept ${asides.join(", ")}` : ""}.\n`, ); await reaudit(); return record; } // STILL MALFORMED: the longer decode stays. if (outcome.status === "corrupt-full-source" && fresh.length > 0) { const current = pickPreferredAudio(fresh) ?? fresh[0]; // The previous copy of the same name, else of any name set aside. const asideFor = asides.includes(current) ? current : asides[0]; let kept: "new" | "previous" = "new"; let decoded: { previous: number | null; new: number | null } | undefined; if (asideFor !== undefined) { const r = await keepLonger(videoDir, current, asideFor + CORRUPT_KEPT_SUFFIX, asideFor, ctx); kept = r.kept; decoded = { previous: r.aside, new: r.current }; // Any further copies set aside: the comparison above decided. for (const name of asides) { if (name === asideFor) continue; await removeMediaFile(videoDir, name + CORRUPT_KEPT_SUFFIX); } } const record: DownloadOutcomeRecord = { ...outcome, attempts: [...(previous?.attempts ?? []), ...outcome.attempts], corruptRefetches: [ ...history, { ...base, result: "still-malformed", kept, ...(decoded ? { decodedSeconds: decoded } : {}) }, ], }; await writeDownloadOutcome(videoDir, record); await tierVideoDir(videoDir, { onLog: ctx.onLog }); ctx.onLog( `${who}: the refetch is malformed too; kept the ${kept === "new" ? "new" : "earlier"} copy` + (decoded ? ` (${decoded.new ?? "?"}s vs ${decoded.previous ?? "?"}s decode)` : "") + (held ? "; the video is a corrupt full source now" : "") + ".\n", ); await reaudit(); return record; } // ANYTHING ELSE: the kept file goes back, the status stays. if (asides.length > 0) { for (const name of fresh) await removeMediaFile(videoDir, name); for (const name of asides) await renameMediaFile(videoDir, name + CORRUPT_KEPT_SUFFIX, name); } // The record the retry started from, with this retry appended — or, for // damaged held audio that had none, the download's own. const failed: CorruptRefetch = { ...base, ...(lastError ? { error: lastError } : {}) }; const record: DownloadOutcomeRecord = previous ? { ...previous, finishedAt: outcome.finishedAt, attempts: [...previous.attempts, ...outcome.attempts], corruptRefetches: [...history, failed], } : { ...outcome, corruptRefetches: [failed] }; await writeDownloadOutcome(videoDir, record); await tierVideoDir(videoDir, { onLog: ctx.onLog }); ctx.onLog( `${who}: the refetch ended ${outcome.status}${outcome.failureClass ? ` (${outcome.failureClass})` : ""}; ` + (asides.length ? `moved the kept ${asides.join(", ")} back; ` : "") + (held ? `the held audio stays as it was.\n` : `the video stays corrupt-full-source.\n`), ); return { ...outcome, corruptRefetches: record.corruptRefetches }; }