Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 134548c889d7eca7db133b69d350c45e4f55e135
parent bfcfb20c27bb22b2b05e16af1ed98cafec8cfc27
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 16:58:30 -0400

common, editor, scripts: a retry of a corrupt full source refetches it (release 30 lane Q1) — the kept container made the corruptFullSource bucket's retry a no-op ("Prefilter: 0 missing destination files, 7 already complete … Nothing to fetch"); the retry-bucket prefilter now asks again for a corrupt-full-source video (destinationExists refetchCorruptFullSource), and every managed download of one goes through ytdlp/corruptRefetch.ts: the kept file is moved aside (audio.mp4.corrupt-kept, through its tier link — mediaTier-server renameMediaFile; the name is media-tier scratch), a clean result removes it, a malformed one keeps whichever copy decodes longer (lib/salvageAudio-server scanDecodable, one tolerant ffmpeg decode), and anything else (a 429, the network, a filter, a cancel) moves it back and keeps the sidecar corrupt-full-source with the failed attempts appended, while the caller still sees the failure so the platform backs off; every retry is recorded in download-outcome.json's corruptRefetches; a run cut short is settled by the next; corruptFullSource is a replayable bucket with a Retry card on the channel's download stage, and the bucket's sentences say a retry downloads again; synthetic damaged-audio kit in testing/audio; ops help and COMMANDS.md

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2+-
Mcommon/controller/channelSnapshot.ts | 7++++---
Mcommon/jobs/jobSpec.test.ts | 1+
Mcommon/jobs/jobSpec.ts | 3+++
Mcommon/lib/downloadOutcome.ts | 40++++++++++++++++++++++++++++++++++++----
Mcommon/lib/mediaTier-server.test.ts | 50++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/mediaTier-server.ts | 42++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/mediaTier.test.ts | 6++++++
Mcommon/lib/mediaTier.ts | 7+++++++
Acommon/lib/salvageAudio-server.test.ts | 146+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/salvageAudio-server.ts | 333+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/testing/audio/corruptAudio.d.mts | 18++++++++++++++++++
Acommon/testing/audio/corruptAudio.mjs | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/views/pipeline/channelFlow.ts | 2+-
Acommon/ytdlp/corruptRefetch.test.ts | 304+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/ytdlp/corruptRefetch.ts | 297+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 27++++++++++++++++++++++++---
Mcommon/ytdlp/runYtdlp.ts | 32+++++++++++++++++++++++++++-----
Meditor/app/channels/[slug]/components/VideoListPane.tsx | 2+-
Meditor/app/channels/[slug]/components/stages/DownloadStage.tsx | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/lib/videoRows.ts | 4++--
Meditor/app/channels/[slug]/page.tsx | 1+
Meditor/app/channels/[slug]/videos/[id]/components/cards/DownloadOutcomeBadge.tsx | 2+-
Mscripts/archilyzer-ops.mjs | 2++
24 files changed, 1465 insertions(+), 21 deletions(-)

diff --git a/COMMANDS.md b/COMMANDS.md @@ -110,7 +110,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` | | `sync` | sync lists a channel and downloads what is new, as its Sync button does: {"slug"}. "full": true runs the periodic whole-listing sweep now (else the configured cadence decides); "queueKey" picks another queue. On the channel's platform queue, paced like its downloads. | `pnpm ops sync --json '{"slug":"the-quartering"}' --wait` | | `download-missing` | download-missing downloads every listed video the channel does not hold: {"slug"}. "ignoreArchive": true drops the download archive so listed videos it names are fetched again (recovery from a stale archive); "abortOnError": false carries on past a failure (default: stop at the first that is not one video's own). Paced on the platform's queue. | | -| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. | | +| `retry-bucket` | retry-bucket runs one bucket of a channel's report as one job, past any lane hold: {"slug", "bucket"}. "ids": \[...\] runs only those videos, and every one must be in the bucket (a stray id is refused, named); a job run with ids is not replayable, as a checkbox selection in the UI is not. "corruptFullSource" downloads again: the kept file is set aside, and comes back if the download fails; malformed again, the longer decode stays. | | | `transcribe-bucket` | transcribe-bucket transcribes a channel's "downloaded, not transcribed" bucket on the transcription queue, as the channel page's Transcribe button does: {"slug"}. "ids": \[...\] narrows it the same way as on retry-bucket. | | | `fetch-posts` | fetch-posts fetches a social channel's new posts: {"slug"}. "full": true re-walks the whole timeline; "older": true walks back from the oldest archived post through search (X; needs a login), saving its place for the next run, down to "floor": "YYYY-MM-DD" when given; "from": "YYYY-MM-DD" starts the walk afresh there, replacing its saved place (and a "complete") — for a gap above one surviving old post. "limit": N caps the posts one run reads; "pages": N caps the pages (a forum thread: its latest N pages). "full" and "older" together are refused. An older walk over an account that shows no posts (nothing archived, and the last timeline fetch read none) is refused unless "force": true. A drained fetch stops at its next resume point and the next run resumes. | | | `capture-posts` | capture-posts captures archived posts of a social channel (X, forum, Bluesky): a screenshot of each through the connected X profile (a forum thread: its host's forum profile; Bluesky: a headless browser with no login on bsky.app, the shot cropped to the post), and its attached media through gallery-dl (a forum thread: the same profile; Bluesky: its images from the CDN), into the channel's posts-media/&lt;id&gt;/: {"slug", "ids": \[...\]}. Every id must be in the channel's posts archive. "shots": false or "media": false skips that half; posts already captured are skipped unless "force": true. A post that links to an X Article also gets the article (article.json, .md, .png and its images) unless "articles": false; both halves off with "articles": true reads only the articles. Paced like a post fetch, on its queue. | | diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -190,9 +190,10 @@ export type ChannelSnapshot = { // Videos whose download COMPLETED (yt-dlp exit 0, all bytes) but whose final // audio integrity probe stayed malformed even after one re-download // (download-outcome.json "corrupt-full-source"). The downloaded container is - // KEPT on disk for inspection; re-downloading is futile, so this is terminal - // and informational — NOT counted as a failed transcription and NOT re-queued - // for download. Optional: older snapshots lack it; readers default to []. + // KEPT on disk. NOT counted as a failed transcription and NOT re-queued for + // download by a lane; a retry of the bucket refetches it (release 30, lane Q + // — ytdlp/corruptRefetch.ts). Optional: older snapshots lack it; readers + // default to []. corruptFullSource: string[]; // Videos whose transcript rides on a non-canonical VTT name (e.g. only // transcript.en-US.vtt, or a foreign-only transcript.<lang>.vtt) instead of diff --git a/common/jobs/jobSpec.test.ts b/common/jobs/jobSpec.test.ts @@ -23,6 +23,7 @@ test("accepts every replay bucket, including the auto-caption lane", () => { "incompleteTranscript", "shortAudio", "needsCookies", + "corruptFullSource", "autoSubsOnly", "downloadedAutoSubsOnly", "supersededAutoSubs", diff --git a/common/jobs/jobSpec.ts b/common/jobs/jobSpec.ts @@ -23,6 +23,8 @@ export type ReplayBucket = | "incompleteTranscript" | "shortAudio" | "needsCookies" + // Release 30 lane Q: a retry of this bucket refetches (ytdlp/corruptRefetch.ts). + | "corruptFullSource" // Replace-auto-captions lane: ASR-only without audio (fetch audio), ASR-only // with audio (transcribe), and the kept-VTT backups (manual purge). | "autoSubsOnly" @@ -48,6 +50,7 @@ const REPLAY_BUCKETS: ReadonlySet<string> = new Set<ReplayBucket>([ "incompleteTranscript", "shortAudio", "needsCookies", + "corruptFullSource", "autoSubsOnly", "downloadedAutoSubsOnly", "supersededAutoSubs", diff --git a/common/lib/downloadOutcome.ts b/common/lib/downloadOutcome.ts @@ -12,10 +12,14 @@ export type DownloadOutcomeStatus = | "failed" | "failed-corrupt-source" // A download that COMPLETED (yt-dlp exit 0, all bytes) but whose final audio - // integrity probe is malformed even after one re-download. Terminal and - // NOT retried: re-downloading a complete file yields identical bytes. The - // downloaded container is KEPT on disk for inspection. Distinct from - // failed-corrupt-source, which means the download never finished. + // integrity probe is malformed even after one re-download. The downloaded + // container is KEPT on disk (it mostly decodes: a salvage transcription reads + // it, controller/transcribeOne.ts). Never re-queued by a lane, but a RETRY + // refetches it (release 30, lane Q — ytdlp/corruptRefetch.ts): a source that + // serves malformed audio intermittently (Odysee's AAC) can come back clean. + // The retry moves the kept file aside, and a failed retry moves it back and + // keeps this status. Distinct from failed-corrupt-source, which means the + // download never finished. | "corrupt-full-source" // A download that COMPLETED (yt-dlp exit 0) but whose audio is far shorter // than the video's metadata duration — the source served a truncated stream @@ -100,6 +104,31 @@ export type DownloadAttempt = { audioCheck?: AudioCheckAttemptStats; }; +// ONE RETRY OF A corrupt-full-source VIDEO (release 30, lane Q), appended to +// the record's `corruptRefetches` — on the record the retry leaves, whatever +// it ended as, so the history survives the status changing. +// clean the new download is clean; the kept file was removed. +// still-malformed the new download is malformed too; whichever copy decodes +// LONGER was kept (`kept`), the other removed. +// failed the new download did not complete (a 429, the network, a +// filter, a cancel); the kept file was moved back and the +// status stays corrupt-full-source. +export type CorruptRefetchResult = "clean" | "still-malformed" | "failed"; + +export type CorruptRefetch = { + startedAt: string; + finishedAt: string; + result: CorruptRefetchResult; + // What the retry's own download ended as. + status: DownloadOutcomeStatus; + failureClass?: DownloadFailureClass; + error?: string; + // still-malformed: which copy stayed, and how many seconds of each decode + // (null: it could not be measured). + kept?: "new" | "previous"; + decodedSeconds?: { previous: number | null; new: number | null }; +}; + export type DownloadOutcomeRecord = { videoId: string; webpageUrl?: string; @@ -134,6 +163,9 @@ export type DownloadOutcomeRecord = { // video. Writing the verdict here would mean editing a regex has to find and // rewrite ~1,800 sidecars before the change takes effect. filter?: { name: string; reason: string }; + // Every retry of this video while it was corrupt-full-source, oldest first + // (see CorruptRefetch). Carried from record to record by the refetch. + corruptRefetches?: CorruptRefetch[]; }; export const DOWNLOAD_OUTCOME_FILENAME = "download-outcome.json"; diff --git a/common/lib/mediaTier-server.test.ts b/common/lib/mediaTier-server.test.ts @@ -23,6 +23,7 @@ import { relocatedMediaDir, removeMediaFile, removeVideoDirMedia, + renameMediaFile, tierChannelMedia, tierLinkTarget, tierMediaFile, @@ -338,3 +339,52 @@ test("a dead process's half-placed bytes in media/<id>/ are swept with the video ); await rm(f.root, { recursive: true, force: true }); }); + +// Release 30 lane Q: the corrupt-source refetch's set-aside and move-back. +test("renameMediaFile renames a real file where it is", async () => { + const f = await fixture(); + await renameMediaFile(f.videoDir, "audio.mp3", "audio.mp3.corrupt-kept"); + assert.equal(existsSync(path.join(f.videoDir, "audio.mp3")), false); + const st = await lstat(path.join(f.videoDir, "audio.mp3.corrupt-kept")); + assert.ok(st.isFile()); + await renameMediaFile(f.videoDir, "audio.mp3.corrupt-kept", "audio.mp3"); + assert.equal(await readFile(path.join(f.videoDir, "audio.mp3"), "utf8"), "AUDIO"); + await rm(f.root, { recursive: true, force: true }); +}); + +test("renameMediaFile moves a tier link's bytes beside themselves and re-points the name", async () => { + const f = await fixture(); + await mkdir(channelMediaLink(f.paths, f.slug)); + assert.equal(await tierMediaFile(f.videoDir, "audio.mp3"), "tiered"); + const mediaVid = path.join(f.channelsDir, f.slug, "media", "vid1"); + await renameMediaFile(f.videoDir, "audio.mp3", "audio.mp3.corrupt-kept"); + assert.equal(existsSync(path.join(f.videoDir, "audio.mp3")), false); + assert.equal(existsSync(path.join(mediaVid, "audio.mp3")), false); + const aside = path.join(f.videoDir, "audio.mp3.corrupt-kept"); + assert.ok((await lstat(aside)).isSymbolicLink()); + assert.equal(await readlink(aside), "../../media/vid1/audio.mp3.corrupt-kept"); + assert.equal(await readFile(aside, "utf8"), "AUDIO"); + // The set-aside name is not tierable: the hook leaves it as it is. + await tierVideoDir(f.videoDir); + assert.equal(await readlink(aside), "../../media/vid1/audio.mp3.corrupt-kept"); + // And back, as a link to the original name. + await renameMediaFile(f.videoDir, "audio.mp3.corrupt-kept", "audio.mp3"); + assert.equal(await readlink(path.join(f.videoDir, "audio.mp3")), "../../media/vid1/audio.mp3"); + assert.equal(await readFile(path.join(mediaVid, "audio.mp3"), "utf8"), "AUDIO"); + assert.equal(existsSync(path.join(mediaVid, "audio.mp3.corrupt-kept")), false); + assert.deepEqual( + (await readdir(f.videoDir)).filter((n) => n.includes("tierlink") || n.includes("corrupt-kept")), + [], + ); + // removeMediaFile still takes a set-aside link's bytes with it. + await renameMediaFile(f.videoDir, "audio.mp3", "audio.mp3.corrupt-kept"); + await removeMediaFile(f.videoDir, "audio.mp3.corrupt-kept"); + assert.equal(existsSync(path.join(mediaVid, "audio.mp3.corrupt-kept")), false); + await rm(f.root, { recursive: true, force: true }); +}); + +test("renameMediaFile of a missing name throws ENOENT", async () => { + const f = await fixture(); + await assert.rejects(() => renameMediaFile(f.videoDir, "audio.m4a", "x"), { code: "ENOENT" }); + await rm(f.root, { recursive: true, force: true }); +}); diff --git a/common/lib/mediaTier-server.ts b/common/lib/mediaTier-server.ts @@ -394,6 +394,48 @@ export async function removeMediaFile(videoDir: string, name: string): Promise<v await rm(file, { force: true }); } +// RENAME ONE FILE IN A VIDEO DIR, through its link when it is one (release 30, +// lane Q: the corrupt-source refetch moves a kept container aside and back). +// A tier link's bytes are renamed beside themselves in `media/<id>/` and the +// name in `data/<id>/` becomes a link to the new name; a real file (or a link +// that points anywhere but this channel's `media/`) is renamed where it is. +// `to` is replaced if it exists, as `rename` replaces. A missing `from` throws +// ENOENT, as `rename` does. +// +// Order: the bytes first, then the new link (made beside and renamed into +// place), then the old link goes. A process killed between the steps leaves +// the bytes under the new name and, at worst, a dangling old link — never a +// name whose bytes are gone. +export async function renameMediaFile( + videoDir: string, + from: string, + to: string, +): Promise<void> { + const file = path.join(videoDir, from); + const st = await lstat(file); + if (st.isSymbolicLink()) { + const mediaRoot = path.dirname(mediaDirOfVideoDir(videoDir)); + let target = ""; + try { + target = path.resolve(videoDir, await readlink(file)); + } catch { + /* unreadable link: renamed as a link below */ + } + if (target && path.dirname(path.dirname(target)) === mediaRoot) { + const newTarget = path.join(path.dirname(target), to); + await rename(target, newTarget); + const tmpLink = path.join(videoDir, `.${to}.tierlink-${process.pid}`); + await rm(tmpLink, { force: true }); + await symlink(path.relative(videoDir, newTarget), tmpLink); + await lutimes(tmpLink, st.atime, st.mtime).catch(() => {}); + await rename(tmpLink, path.join(videoDir, to)); + await rm(file, { force: true }); + return; + } + } + await rename(file, path.join(videoDir, to)); +} + // Before a whole video dir is deleted: every link's target in it, then the // video's own `media/<id>/` (whatever else is left there — the migration's // platter copies before a `--reclaim`). The caller removes the dir itself. diff --git a/common/lib/mediaTier.test.ts b/common/lib/mediaTier.test.ts @@ -46,6 +46,12 @@ const TABLE: ReadonlyArray<[string, "media" | "text" | "scratch", boolean]> = [ [".audio.mp3.tierlink-4242", "scratch", false], [".audio.mp3.tiering-4242", "scratch", false], [".syncthing.audio.mp3.tmp", "scratch", false], + // Release 30 lane Q: a kept container set aside by the corrupt-source + // refetch, and the salvage transcription's WAV (with parakeet's window dir + // beside it, already scratch by its own rule). + ["audio.mp4.corrupt-kept", "scratch", false], + ["audio.salvage.wav", "scratch", false], + [".audio.salvage.wav.parakeet", "scratch", false], // The hot text. ["transcript.json", "text", false], ["transcript.en.vtt", "text", false], diff --git a/common/lib/mediaTier.ts b/common/lib/mediaTier.ts @@ -66,6 +66,13 @@ const SCRATCH_PATTERNS: ReadonlyArray<RegExp> = [ // Syncthing's in-flight temp (`.syncthing.audio.mp3.tmp`): a transfer the // sync tool never finished. /^\.syncthing\..*\.tmp$/, + // The corrupt-source refetch's kept container, moved aside while the source + // is asked again (`audio.mp4.corrupt-kept`, ytdlp/corruptRefetch.ts): the + // refetch moves it back or removes it when the download ends. + /\.corrupt-kept$/, + // The salvage transcription's decoded WAV (`audio.salvage.wav`, + // lib/salvageAudio-server.ts): removed when the transcription ends. + /^audio\.salvage\.wav$/, ]; export function isScratchEntry(name: string): boolean { diff --git a/common/lib/salvageAudio-server.test.ts b/common/lib/salvageAudio-server.test.ts @@ -0,0 +1,146 @@ +// The salvage decode (release 30, lane Q): a damaged file decoded for what it +// still holds, ON THE SOURCE'S CLOCK — every burst after the damage at its +// source time, the damage silence of its own length, the gap recorded. Real +// ffmpeg over a synthetic tone-burst recording with a deterministic run of +// bytes overwritten (testing/audio/corruptAudio.mjs). +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test lib/salvageAudio-server.test.ts + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { + frameAccumulator, + gapSeconds, + mergeGaps, + salvageDecode, + scanDecodable, +} from "./salvageAudio-server"; +import { + burstTimes, + corruptBytes, + hasFfmpeg, + makeToneFile, + readWavMono16, + toneOnsets, +} from "../testing/audio/corruptAudio.mjs"; + +const tools = hasFfmpeg(); +const deps = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" }; +let ROOT = ""; +let CLEAN = ""; +let DAMAGED = ""; + +before(async () => { + ROOT = await mkdtemp(path.join(tmpdir(), "salvage-audio-")); + if (!tools) return; + CLEAN = makeToneFile(path.join(ROOT, "clean.mp4")); + DAMAGED = corruptBytes(CLEAN, path.join(ROOT, "damaged.mp4")); +}); +after(() => rm(ROOT, { recursive: true, force: true })); + +const near = (a: number, b: number, tol = 0.05) => Math.abs(a - b) <= tol; + +test("mergeGaps sorts, merges holes closer than a second, drops the short ones", () => { + assert.deepEqual( + mergeGaps([ + [10, 10.2], + [3, 4], + [4.5, 6], + [20, 20.3], + [30, 29], + ]), + [[3, 6]], + ); + assert.deepEqual(mergeGaps([[1, 2], [5, 7.5]]), [[1, 2], [5, 7.5]]); + assert.equal(gapSeconds([[1, 2], [5, 7.5]]), 3.5); +}); + +test("frameAccumulator reads framecrc: a jump in pts is a hole, the tail to the container's end is one", () => { + const acc = frameAccumulator(); + for (const line of [ + "#tb 0: 1/16000", + "#stream#, dts, pts, duration, size, hash", + "0, 0, 0, 16000, 32000, 0x00000000", + "0, 16000, 16000, 16000, 32000, 0x00000000", + // 3 s missing (48000 ticks), then two more seconds + "0, 80000, 80000, 32000, 64000, 0x00000000", + ]) { + acc.feed(line); + } + const done = acc.finish(10); + assert.equal(done.decodedSeconds, 4); + assert.equal(done.end, 10); + assert.deepEqual(done.gaps, [[2, 5], [7, 10]]); +}); + +test("a clean file decodes whole, with no gaps", { skip: !tools && "ffmpeg/ffprobe not installed" }, async () => { + const scan = await scanDecodable(CLEAN, deps); + assert.ok(scan); + assert.ok(near(scan.totalSeconds, 30), `total ${scan.totalSeconds}`); + assert.ok(near(scan.decodedSeconds, 30, 0.1), `decoded ${scan.decodedSeconds}`); + assert.deepEqual(scan.gaps, []); +}); + +test("a damaged file: the scan finds the hole and counts only what decodes", { skip: !tools && "ffmpeg/ffprobe not installed" }, async () => { + const scan = await scanDecodable(DAMAGED, deps); + assert.ok(scan); + assert.ok(near(scan.totalSeconds, 30), `total ${scan.totalSeconds}`); + assert.equal(scan.gaps.length, 1, JSON.stringify(scan.gaps)); + const [from, to] = scan.gaps[0]; + assert.ok(to - from > 1, `gap ${from}-${to}`); + // What decodes is the runtime less the hole (within one AAC frame or so). + assert.ok(near(scan.decodedSeconds, 30 - (to - from), 0.1), `decoded ${scan.decodedSeconds}`); +}); + +test("salvageDecode keeps the source's clock: bursts after the damage are at their source times", { skip: !tools && "ffmpeg/ffprobe not installed" }, async () => { + const wav = path.join(ROOT, "salvage.wav"); + const r = await salvageDecode(DAMAGED, wav, deps); + assert.equal(r.gaps.length, 1); + const [from, to] = r.gaps[0]; + const { samples, rate, seconds } = readWavMono16(wav); + assert.equal(rate, 16000); + // Padded out to the container's runtime. + assert.ok(near(seconds, 30), `wav ${seconds}s`); + const onsets = toneOnsets(samples, rate); + // Every burst wholly outside the damage is where the source has it. + const expected = burstTimes().filter((t) => t + 0.3 < from || t > to); + assert.ok(expected.some((t) => t > to), "a burst after the damage is checked"); + for (const t of expected) { + assert.ok( + onsets.some((o) => near(o, t)), + `burst at ${t}s missing from the salvage (onsets ${onsets.join(", ")})`, + ); + } + // No burst inside the damage: it is silence, not audio from later on. + for (const o of onsets) { + assert.ok(!(o > from + 0.05 && o < to - 0.05), `onset ${o} inside the gap ${from}-${to}`); + } +}); + +test("the control: a plain decode closes the damage up, and every later burst lands early", { skip: !tools && "ffmpeg/ffprobe not installed" }, async () => { + // Without this, the test above could pass on a file whose damage cost no + // time at all. The plain decode the salvage replaces shifts the clock. + const naive = path.join(ROOT, "naive.wav"); + execFileSync("ffmpeg", ["-nostdin", "-v", "quiet", "-y", "-err_detect", "ignore_err", "-i", DAMAGED, "-ac", "1", "-ar", "16000", "-c:a", "pcm_s16le", naive]); + const scan = await scanDecodable(DAMAGED, deps); + assert.ok(scan); + const [from, to] = scan.gaps[0]; + const { samples, rate, seconds } = readWavMono16(naive); + assert.ok(seconds < 30 - (to - from) + 0.1, `naive ${seconds}s`); + const late = burstTimes().filter((t) => t > to); + const onsets = toneOnsets(samples, rate); + for (const t of late) { + assert.ok(!onsets.some((o) => near(o, t)), `naive decode kept ${t}s on the clock`); + assert.ok(onsets.some((o) => near(o, t - (to - from), 0.1)), `burst ${t}s not shifted by the gap`); + } +}); + +test("salvageDecode refuses a file nothing in which decodes", { skip: !tools && "ffmpeg/ffprobe not installed" }, async () => { + const junk = path.join(ROOT, "junk.mp4"); + corruptBytes(CLEAN, junk, { fromFrac: 0, toFrac: 1 }); + await assert.rejects(() => salvageDecode(junk, path.join(ROOT, "junk.wav"), deps), /nothing in junk\.mp4 decodes/); +}); diff --git a/common/lib/salvageAudio-server.ts b/common/lib/salvageAudio-server.ts @@ -0,0 +1,333 @@ +// DECODING A DAMAGED AUDIO FILE FOR WHAT IT STILL HOLDS (release 30, lane Q). +// +// A source that served malformed audio mid-stream (Odysee's AAC, CHANNEL.md +// `audioCheck`) leaves a container that is mostly decodable: thousands of +// "Invalid data found when processing input" lines, and either the whole +// runtime or a long prefix of it in between. Two questions are asked of such a +// file, with ONE ffmpeg decode each: +// +// scanDecodable how much of it decodes — the sum of the decoded frames' +// durations, and where the decoded timeline jumps (a gap). +// The corrupt-source refetch keeps whichever of two copies +// decodes LONGER (ytdlp/corruptRefetch.ts). +// salvageDecode the same scan, and beside it a 16 kHz mono WAV of the +// file ON THE SOURCE'S CLOCK: every undecodable span is +// silence of the same length, so a cue at 41:07 in the +// transcript is at 41:07 in the recording. A plain decode +// drops the bad frames and closes up the gap, and every cue +// after the first one lands early by the gap's length. +// +// THE CLOCK COMES FROM THE CONTAINER. Each packet carries its own timestamp +// (an MP4's sample table, not the bytes of the frame), so a frame the decoder +// refuses leaves a hole in the decoded frames' timestamps exactly where the +// frame was. `aresample=async=1:first_pts=0` fills such holes with silence +// (any jump over its `min_hard_comp`, 0.1 s), `apad=whole_dur` pads the tail +// out to the container's duration, and `framecrc` on the unpadded output says +// where the holes were. Verified with a synthetic corrupted file in +// salvageAudio-server.test.ts: tone bursts after the damage keep their times. + +import { spawn } from "node:child_process"; +import { rm } from "node:fs/promises"; +import path from "node:path"; + +// The sample rate both outputs are decoded at: what parakeet and whisper.cpp +// read anyway (parakeet-stitch slices 16 kHz mono windows). +export const SALVAGE_SAMPLE_RATE = 16_000; + +// The salvage WAV's name in the video dir. Not a real audio file +// (`isRealAudioFile` anchors on ONE segment after `audio.`), scratch to the +// media tier (lib/mediaTier.ts), and stable — so parakeet's resumable window +// cache (`.audio.salvage.wav.parakeet`, scratch too) survives a pause: the +// decode is deterministic, the duration the cache is keyed on the same. +export const SALVAGE_WAV_FILENAME = "audio.salvage.wav"; + +// A hole shorter than this is counted (in `decodedSeconds`) but not listed: +// one dropped AAC frame is 23 ms, and a file with 6,557 decode errors would +// otherwise list thousands of them. +export const SALVAGE_GAP_MIN_SECONDS = 0.5; +// Two listed holes with less decoded audio than this between them are one gap. +export const SALVAGE_GAP_MERGE_SECONDS = 1; + +export type SalvageGap = [from: number, to: number]; + +export type DecodeScan = { + // Seconds of audio that decoded (the frames' durations, summed). + decodedSeconds: number; + // The container's duration (ffprobe), or the decoded timeline's end when the + // container does not say. + totalSeconds: number; + // Spans of the source's timeline with no decoded audio, merged and sorted. + gaps: SalvageGap[]; + // ffmpeg's exit code. A tolerant decode exits 0 on a damaged file; non-zero + // means it stopped (an unreadable header, a demuxer that gave up). + exitCode: number | null; +}; + +export type SalvageResult = DecodeScan & { + // The WAV written (absolute path). + wavFile: string; +}; + +export type DecodeDeps = { + ffmpegBin: string; + ffprobeBin: string; + signal?: AbortSignal; + onLog?: (line: string) => void; +}; + +const round3 = (n: number) => Math.round(n * 1000) / 1000; + +// The decoder's tolerance: keep decoding past a refused frame, and let the +// demuxer drop packets it flags as corrupt rather than hand them on. +const TOLERANT_INPUT_ARGS = ["-err_detect", "ignore_err", "-fflags", "+discardcorrupt"]; + +// The unpadded scan output: 16 kHz mono PCM, one framecrc line per frame +// (`stream, dts, pts, duration, size, crc`), on stdout. +function scanOutputArgs(): string[] { + return [ + "-map", + "0:a:0", + "-vn", + "-ac", + "1", + "-ar", + String(SALVAGE_SAMPLE_RATE), + "-c:a", + "pcm_s16le", + "-f", + "framecrc", + "pipe:1", + ]; +} + +// Parsed framecrc frames, accumulated into decoded seconds and holes. +type FrameAccumulator = { + feed: (line: string) => void; + finish: (totalSeconds: number | null) => { decodedSeconds: number; end: number; gaps: SalvageGap[] }; +}; + +// PURE: framecrc lines in, decoded seconds and gaps out. Exported for tests. +export function frameAccumulator(): FrameAccumulator { + let tbNum = 1; + let tbDen = SALVAGE_SAMPLE_RATE; + let decodedTicks = 0; + let expectedEnd: number | null = null; + const raw: SalvageGap[] = []; + const toSec = (ticks: number) => (ticks * tbNum) / tbDen; + return { + feed(line: string) { + const s = line.trim(); + if (!s) return; + if (s.startsWith("#")) { + const tb = /^#tb\s+0:\s*(\d+)\/(\d+)/.exec(s); + if (tb) { + tbNum = Number(tb[1]) || 1; + tbDen = Number(tb[2]) || SALVAGE_SAMPLE_RATE; + } + return; + } + const cols = s.split(",").map((c) => c.trim()); + if (cols.length < 4 || cols[0] !== "0") return; + const pts = Number(cols[2]); + const dur = Number(cols[3]); + if (!Number.isFinite(pts) || !Number.isFinite(dur)) return; + const prevEnd = expectedEnd ?? 0; + if (pts > prevEnd) raw.push([toSec(prevEnd), toSec(pts)]); + decodedTicks += Math.max(0, dur); + expectedEnd = Math.max(prevEnd, pts + dur); + }, + finish(totalSeconds: number | null) { + const end = expectedEnd === null ? 0 : toSec(expectedEnd); + const total = totalSeconds !== null && totalSeconds > end ? totalSeconds : end; + if (total > end) raw.push([end, total]); + return { + decodedSeconds: round3(Math.min(toSec(decodedTicks), total)), + end: round3(total), + gaps: mergeGaps(raw), + }; + }, + }; +} + +// PURE: sort, merge (holes closer than SALVAGE_GAP_MERGE_SECONDS are one), and +// drop what is shorter than SALVAGE_GAP_MIN_SECONDS. Exported for tests and for +// transcribeOne, which adds the windows an engine could not transcribe. +export function mergeGaps(gaps: ReadonlyArray<SalvageGap>): SalvageGap[] { + const sorted = gaps + .filter(([a, b]) => Number.isFinite(a) && Number.isFinite(b) && b > a) + .map(([a, b]) => [a, b] as SalvageGap) + .sort((x, y) => x[0] - y[0]); + const merged: SalvageGap[] = []; + for (const [a, b] of sorted) { + const last = merged.at(-1); + if (last && a - last[1] < SALVAGE_GAP_MERGE_SECONDS) { + last[1] = Math.max(last[1], b); + } else { + merged.push([a, b]); + } + } + return merged + .filter(([a, b]) => b - a >= SALVAGE_GAP_MIN_SECONDS) + .map(([a, b]) => [round3(a), round3(b)] as SalvageGap); +} + +// Seconds covered by a list of (merged, non-overlapping) gaps. +export function gapSeconds(gaps: ReadonlyArray<SalvageGap>): number { + return round3(gaps.reduce((sum, [a, b]) => sum + Math.max(0, b - a), 0)); +} + +// The container's duration, or null when ffprobe cannot say. +export async function containerDurationSec( + ffprobeBin: string, + file: string, + signal?: AbortSignal, +): Promise<number | null> { + const out = await run( + ffprobeBin, + ["-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", file], + { signal }, + ); + if (out.exitCode !== 0) return null; + const sec = Number.parseFloat(out.stdout.trim()); + return Number.isFinite(sec) && sec > 0 ? sec : null; +} + +// HOW MUCH OF A FILE DECODES, with the same tolerance the salvage decode uses. +// One decode, no file written. Null when ffmpeg could not be run at all. +export async function scanDecodable(file: string, deps: DecodeDeps): Promise<DecodeScan | null> { + const total = await containerDurationSec(deps.ffprobeBin, file, deps.signal); + const acc = frameAccumulator(); + const res = await run( + deps.ffmpegBin, + ["-nostdin", "-hide_banner", "-v", "error", ...TOLERANT_INPUT_ARGS, "-i", file, ...scanOutputArgs()], + { signal: deps.signal, onStdoutLine: acc.feed }, + ); + if (res.spawnError) { + deps.onLog?.(`ffmpeg could not be run on ${path.basename(file)}: ${res.spawnError}\n`); + return null; + } + const done = acc.finish(total); + return { decodedSeconds: done.decodedSeconds, totalSeconds: done.end, gaps: done.gaps, exitCode: res.exitCode }; +} + +// DECODE A DAMAGED FILE INTO A WAV ON THE SOURCE'S CLOCK, and say what is +// missing from it. One ffmpeg run, two outputs: the unpadded framecrc scan on +// stdout, and the padded WAV. Throws when nothing decoded at all. +export async function salvageDecode( + input: string, + wavFile: string, + deps: DecodeDeps, +): Promise<SalvageResult> { + const total = await containerDurationSec(deps.ffprobeBin, input, deps.signal); + const acc = frameAccumulator(); + const pad = total !== null ? `,apad=whole_dur=${total}` : ""; + await rm(wavFile, { force: true }); + const res = await run( + deps.ffmpegBin, + [ + "-nostdin", + "-hide_banner", + "-v", + "error", + ...TOLERANT_INPUT_ARGS, + "-i", + input, + ...scanOutputArgs(), + "-map", + "0:a:0", + "-vn", + "-af", + `aresample=${SALVAGE_SAMPLE_RATE}:async=1:first_pts=0${pad}`, + "-ac", + "1", + "-c:a", + "pcm_s16le", + "-f", + "wav", + "-y", + wavFile, + ], + { signal: deps.signal, onStdoutLine: acc.feed }, + ); + if (res.spawnError) throw new Error(`ffmpeg could not be run: ${res.spawnError}`); + const done = acc.finish(total); + if (done.decodedSeconds <= 0) { + await rm(wavFile, { force: true }); + throw new Error( + `nothing in ${path.basename(input)} decodes (ffmpeg exit ${res.exitCode}): ${res.stderrTail.trim().split("\n").slice(-2).join(" | ")}`, + ); + } + return { + decodedSeconds: done.decodedSeconds, + totalSeconds: done.end, + gaps: done.gaps, + exitCode: res.exitCode, + wavFile, + }; +} + +// A one-line summary for a job log. +export function describeSalvage(r: Pick<DecodeScan, "decodedSeconds" | "totalSeconds" | "gaps">): string { + const pct = r.totalSeconds > 0 ? Math.round((r.decodedSeconds / r.totalSeconds) * 1000) / 10 : 0; + return `${r.decodedSeconds}s of ${r.totalSeconds}s decode (${pct}%), ${r.gaps.length} gap${r.gaps.length === 1 ? "" : "s"} (${gapSeconds(r.gaps)}s)`; +} + +type RunResult = { + exitCode: number | null; + stdout: string; + stderrTail: string; + spawnError?: string; +}; + +// spawn, line-streamed stdout (a framecrc scan of a long file is ~15 MB), +// stderr kept to its tail (a damaged file prints a line per refused frame). +function run( + bin: string, + args: string[], + opts: { signal?: AbortSignal; onStdoutLine?: (line: string) => void }, +): Promise<RunResult> { + return new Promise((resolve) => { + let child; + try { + child = spawn(bin, args, { stdio: ["ignore", "pipe", "pipe"], signal: opts.signal }); + } catch (err) { + resolve({ exitCode: null, stdout: "", stderrTail: "", spawnError: (err as Error).message }); + return; + } + let stdout = ""; + let carry = ""; + let stderrTail = ""; + child.stdout.setEncoding("utf8"); + child.stdout.on("data", (chunk: string) => { + if (!opts.onStdoutLine) { + stdout += chunk; + return; + } + carry += chunk; + let nl = carry.indexOf("\n"); + while (nl >= 0) { + opts.onStdoutLine(carry.slice(0, nl)); + carry = carry.slice(nl + 1); + nl = carry.indexOf("\n"); + } + }); + child.stderr.setEncoding("utf8"); + child.stderr.on("data", (chunk: string) => { + stderrTail = (stderrTail + chunk).slice(-4096); + }); + let spawnError: string | undefined; + let settled = false; + const settle = (code: number | null) => { + if (settled) return; + settled = true; + if (carry && opts.onStdoutLine) opts.onStdoutLine(carry); + resolve({ exitCode: code, stdout, stderrTail, ...(spawnError ? { spawnError } : {}) }); + }; + child.on("error", (err) => { + spawnError = err.message; + // A binary that is not there never emits "close" on some Node versions. + if (child.pid === undefined) settle(null); + }); + child.on("close", (code) => settle(code)); + }); +} diff --git a/common/testing/audio/corruptAudio.d.mts b/common/testing/audio/corruptAudio.d.mts @@ -0,0 +1,18 @@ +export const TONE_RATE: number; +export function hasFfmpeg(): boolean; +export function burstTimes(opts?: { duration?: number; first?: number; every?: number }): number[]; +export function makeToneFile( + file: string, + opts?: { duration?: number; first?: number; every?: number }, +): string; +export function corruptBytes( + src: string, + out: string, + opts?: { fromFrac?: number; toFrac?: number; seed?: number }, +): string; +export function readWavMono16(file: string): { rate: number; samples: Int16Array; seconds: number }; +export function toneOnsets( + samples: Int16Array, + rate: number, + opts?: { threshold?: number; quietSec?: number }, +): number[]; diff --git a/common/testing/audio/corruptAudio.mjs b/common/testing/audio/corruptAudio.mjs @@ -0,0 +1,99 @@ +// SYNTHETIC DAMAGED AUDIO (release 30, lane Q) — a tone-burst recording, the +// same recording with a deterministic run of its bytes overwritten (the way a +// source that serves malformed AAC mid-stream damages a file), and the readers +// a test needs to say WHERE the bursts are in a decoded WAV. +// +// The bursts are the clock: a 0.3 s 1 kHz tone every `every` seconds from +// `first`, silence between. A decode that keeps the source's timeline has every +// surviving burst at its source time; one that closes up the damage has every +// burst after it early by the damage's length. +// +// Needs ffmpeg on PATH (the tests that use it skip without it). + +import { execFileSync } from "node:child_process"; +import { readFileSync, writeFileSync } from "node:fs"; + +export const TONE_RATE = 44100; + +export function hasFfmpeg() { + try { + execFileSync("ffmpeg", ["-version"], { stdio: "ignore" }); + execFileSync("ffprobe", ["-version"], { stdio: "ignore" }); + return true; + } catch { + return false; + } +} + +// Where the bursts start, in seconds. +export function burstTimes({ duration = 30, first = 2, every = 4 } = {}) { + const out = []; + for (let t = first; t < duration; t += every) out.push(t); + return out; +} + +// An AAC-in-MP4 tone-burst recording at `file`. +export function makeToneFile(file, { duration = 30, first = 2, every = 4 } = {}) { + const expr = `if(gte(t,${first})*lt(mod(t-${first},${every}),0.3),0.5*sin(2*PI*1000*t),0)`; + execFileSync("ffmpeg", [ + "-nostdin", "-v", "error", "-y", + "-f", "lavfi", "-i", `aevalsrc='${expr}':s=${TONE_RATE}:d=${duration}`, + "-c:a", "aac", "-b:a", "64k", + file, + ]); + return file; +} + +// `src` copied to `out` with the bytes from `fromFrac` to `toFrac` of its +// length overwritten by a seeded LCG — the same bytes every run. With the +// MP4's index at the END (ffmpeg's default, no faststart) the range falls in +// the sample data: the frames there fail to decode, their timestamps survive. +export function corruptBytes(src, out, { fromFrac = 0.4, toFrac = 0.55, seed = 12345 } = {}) { + const buf = readFileSync(src); + let s = seed; + const a = Math.floor(buf.length * fromFrac); + const z = Math.floor(buf.length * toFrac); + for (let k = a; k < z; k += 1) { + s = (s * 1103515245 + 12345) & 0x7fffffff; + buf[k] = s & 0xff; + } + writeFileSync(out, buf); + return out; +} + +// A 16-bit mono PCM WAV's samples and rate, read off its `fmt ` and `data` +// chunks (ffmpeg writes a LIST chunk too, so the header is not 44 bytes). +export function readWavMono16(file) { + const b = readFileSync(file); + let rate = 16000; + let off = 12; + while (off + 8 <= b.length) { + const id = b.toString("ascii", off, off + 4); + let size = b.readUInt32LE(off + 4); + if (id === "fmt ") rate = b.readUInt32LE(off + 12); + if (id === "data") { + // A streamed WAV may carry a 0 or 0xFFFFFFFF size: read to the end. + if (size === 0 || off + 8 + size > b.length) size = b.length - off - 8; + const n = Math.floor(size / 2); + const samples = new Int16Array(n); + for (let i = 0; i < n; i += 1) samples[i] = b.readInt16LE(off + 8 + i * 2); + return { rate, samples, seconds: n / rate }; + } + off += 8 + size + (size % 2); + } + throw new Error(`no data chunk in ${file}`); +} + +// Burst onsets (seconds) in decoded samples: the first loud sample after at +// least `quietSec` of quiet. AAC's own start-up click is not loud enough. +export function toneOnsets(samples, rate, { threshold = 3000, quietSec = 0.5 } = {}) { + const out = []; + const quiet = Math.round(quietSec * rate); + let lastLoud = -Infinity; + for (let i = 0; i < samples.length; i += 1) { + if (Math.abs(samples[i]) <= threshold) continue; + if (i - lastLoud > quiet) out.push(Math.round((i / rate) * 1000) / 1000); + lastLoud = i; + } + return out; +} diff --git a/common/views/pipeline/channelFlow.ts b/common/views/pipeline/channelFlow.ts @@ -442,7 +442,7 @@ export function computeChannelFlow( "corrupt full source", buckets.corruptFullSource.length, "download", - "Download completed but the audio stayed malformed. File kept for inspection; re-downloading is futile.", + "Download completed but the audio stayed malformed; the file is kept. A retry downloads again — a source that is only sometimes malformed can come back clean.", ), ], transcribe: [ diff --git a/common/ytdlp/corruptRefetch.test.ts b/common/ytdlp/corruptRefetch.test.ts @@ -0,0 +1,304 @@ +// 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"; + +const ID = "H64QQZuw-aA"; +const PATHS = { ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" }; + +function cfsRecord(over: Partial<DownloadOutcomeRecord> = {}): 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>): 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<DownloadOutcomeRecord> => + JSON.parse(await readFile(path.join(videoDir, "download-outcome.json"), "utf8")); + +function ctx(measure?: Record<string, number | null>) { + 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 }); +}); diff --git a/common/ytdlp/corruptRefetch.ts b/common/ytdlp/corruptRefetch.ts @@ -0,0 +1,297 @@ +// 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. + +import path from "node:path"; +import { readdir } 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"; + +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<number | null>; + now?: () => Date; +}; + +export type CorruptRefetchPlan = { + videoDir: string; + // The corrupt-full-source record the retry started from. + previous: DownloadOutcomeRecord; + // The original names moved aside (each now `<name>.corrupt-kept`). + asides: string[]; + startedAt: string; +}; + +type Ctx = { + paths: Pick<Paths, "ffmpegBin" | "ffprobeBin">; + onLog: (line: string) => void; + signal?: AbortSignal; + deps?: CorruptRefetchDeps; +}; + +function measureWith(ctx: Ctx): (file: string) => Promise<number | null> { + 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<void> { + const leftovers = entries.filter(isCorruptKeptName); + if (leftovers.length === 0) return; + const record = await loadDownloadOutcome(videoDir); + const clean = record?.status.startsWith("ok") === true; + for (const aside of leftovers) { + const name = originalName(aside); + 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. + if (record && !clean && record.status !== "corrupt-full-source") { + await writeDownloadOutcome(videoDir, { ...record, status: "corrupt-full-source" }); + } +} + +// 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<CorruptRefetchPlan | null> { + const first = await readdir(videoDir).catch(() => [] as string[]); + await resolveLeftovers(videoDir, first, ctx); + const previous = await loadDownloadOutcome(videoDir); + if (previous?.status !== "corrupt-full-source") return null; + const entries = await readdir(videoDir).catch(() => [] as string[]); + 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( + 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, + previous, + 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<DownloadOutcomeRecord> { + const { videoDir, previous, asides } = plan; + 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 } : {}), + }; + const history = previous.corruptRefetches ?? []; + const removeAsides = async () => { + for (const name of asides) await removeMediaFile(videoDir, name + CORRUPT_KEPT_SUFFIX); + }; + + // CLEAN: the new file stands, the kept one goes. + if (outcome.status.startsWith("ok") && fresh.length > 0) { + await removeAsides(); + const record: DownloadOutcomeRecord = { + ...outcome, + corruptRefetches: [...history, { ...base, result: "clean" }], + }; + await writeDownloadOutcome(videoDir, record); + ctx.onLog( + `Corrupt full source: the refetch is clean${asides.length ? `; removed the kept ${asides.join(", ")}` : ""}.\n`, + ); + 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( + `Corrupt full source: the refetch is malformed too; kept the ${kept === "new" ? "new" : "earlier"} copy` + + (decoded ? ` (${decoded.new ?? "?"}s vs ${decoded.previous ?? "?"}s decode)` : "") + + ".\n", + ); + 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); + } + const record: DownloadOutcomeRecord = { + ...previous, + finishedAt: outcome.finishedAt, + attempts: [...previous.attempts, ...outcome.attempts], + corruptRefetches: [ + ...history, + { ...base, ...(lastError ? { error: lastError } : {}) }, + ], + }; + await writeDownloadOutcome(videoDir, record); + await tierVideoDir(videoDir, { onLog: ctx.onLog }); + ctx.onLog( + `Corrupt full source: the refetch ended ${outcome.status}${outcome.failureClass ? ` (${outcome.failureClass})` : ""}; ` + + (asides.length ? `moved the kept ${asides.join(", ")} back; ` : "") + + `the video stays corrupt-full-source.\n`, + ); + return { ...outcome, corruptRefetches: record.corruptRefetches }; +} diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -47,6 +47,11 @@ import { type DownloadOutcomeStatus, } from "../lib/downloadOutcome"; import { writeDownloadOutcome } from "../lib/downloadOutcome-server"; +import { + prepareCorruptRefetch, + settleCorruptRefetch, + type CorruptRefetchDeps, +} from "./corruptRefetch"; import { formatBytes } from "../lib/format"; import { recordAvailability } from "../lib/availability-server"; import { withMetadataHistory } from "../lib/metadataHistory-server"; @@ -194,6 +199,9 @@ export type ManagedDownloadOpts = { // Test seam: what the archive.org download (controller/archiveOrgDownload.ts) // talks to. Every production caller passes none. archiveOrgDeps?: ArchiveOrgDownloadDeps; + // Test seam: how the corrupt-source refetch measures a file's decodable + // seconds (ytdlp/corruptRefetch.ts). Every production caller passes none. + corruptRefetchDeps?: CorruptRefetchDeps; }; // When `reuseInfoJson` is true, the real download reuses the metadata the @@ -658,7 +666,20 @@ export async function downloadOneManaged( if (detectPlatform(opts.videoUrl) === "archiveorg") { return await downloadArchiveOrgManaged(opts, opts.archiveOrgDeps); } - const outcome = await runManagedDownload(opts, channelDir, startedAt, canonicalId); + // A corrupt-full-source video is REFETCHED (release 30, lane Q): its kept + // container goes aside for the download and the result decides which + // copy stays — ytdlp/corruptRefetch.ts. Null for every other video. + const refetchCtx = { + paths: opts.paths, + onLog: opts.onLog, + signal: opts.signal, + deps: opts.corruptRefetchDeps, + }; + const refetch = canonicalId + ? await prepareCorruptRefetch(path.join(channelDir, "data", canonicalId), refetchCtx) + : null; + let outcome = await runManagedDownload(opts, channelDir, startedAt, canonicalId); + if (refetch) outcome = await settleCorruptRefetch(refetch, outcome, refetchCtx); await recordWaybackProvenance(opts, channelDir, canonicalId); return outcome; } finally { @@ -1332,8 +1353,8 @@ async function runManagedDownload( } else if (audioCheckCorruptSource) { status = "failed-corrupt-source"; } else if (audioCheckCorruptFullSource) { - // Kept file, terminal: not "ok" (no usable audio), not a failure (the - // bytes are on disk; re-downloading is futile). Drops into its own bucket. + // Kept file: not "ok" (no usable audio), not a failure (the bytes are on + // disk). Drops into its own bucket; a retry refetches it (corruptRefetch.ts). status = "corrupt-full-source"; } diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -31,7 +31,11 @@ import { classifyDownloadFailure, type Availability, } from "../lib/availability"; -import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; +import { + DOWNLOAD_OUTCOME_FILENAME, + type DownloadOutcomeRecord, +} from "../lib/downloadOutcome"; +import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; import { alwaysCookies, resolveCookiePolicy, @@ -297,6 +301,11 @@ async function retryBucket(opts: RunYtdlpOpts): Promise<void> { prefilter: "destination-exists", idAllowList: opts.bucketIds, handlingOverride: opts.handlingOverride, + // A RETRY REFETCHES A CORRUPT FULL SOURCE (release 30, lane Q): its kept + // file is not a destination that makes the video complete, or the + // corruptFullSource bucket's retry would prefilter every id away + // ("Nothing to fetch"). downloadOneManaged moves the file aside and back. + refetchCorruptFullSource: true, }); } @@ -726,6 +735,7 @@ async function downloadPlaylistManaged( prefilter: PrefilterMode; idAllowList?: ReadonlyArray<string>; handlingOverride?: ChannelHandling; + refetchCorruptFullSource?: boolean; }, ): Promise<void> { const { prefilter, idAllowList, handlingOverride } = cfg; @@ -822,6 +832,7 @@ async function downloadPlaylistManaged( if ( await destinationExists(dataDir, dirId, effectiveHandling, { replaceAutoSubs: opts.replaceAutoSubs, + refetchCorruptFullSource: cfg.refetchCorruptFullSource, }) ) { alreadyComplete++; @@ -1183,9 +1194,10 @@ export async function runManagedDownloads( // and the report's own chatOnly bucket is where it is counted. skippedCount++; } else if (outcome.status === "corrupt-full-source") { - // Completed but stayed malformed after one re-download: terminal and - // kept on disk, but not a usable download. Count as skipped (not ok, - // not a retryable failure) so the batch summary stays honest. + // Completed but stayed malformed after one re-download (or a retry's + // refetch came back malformed too): kept on disk, but not a usable + // download. Count as skipped (not ok, not a failure that backs the + // platform off) so the batch summary stays honest. skippedCount++; } else if (outcome.status === "failed") { failedCount++; @@ -1600,10 +1612,20 @@ export async function destinationExists( dataDir: string, id: string, handling: ChannelHandling, - opts: { replaceAutoSubs?: boolean } = {}, + opts: { replaceAutoSubs?: boolean; refetchCorruptFullSource?: boolean } = {}, ): Promise<boolean> { const dir = path.join(dataDir, id); const entries = await readdir(dir).catch(() => [] as string[]); + // A retry of a corrupt full source asks the source again whatever is on + // disk — the kept container, or a salvage transcript made from it (release + // 30, lane Q). Only the retry asks; a sweep still counts it as there. + if ( + opts.refetchCorruptFullSource === true && + entries.includes(DOWNLOAD_OUTCOME_FILENAME) && + (await loadDownloadOutcome(dir))?.status === "corrupt-full-source" + ) { + return false; + } // Our own transcript always counts as "already done". if (entries.includes("transcript.json")) return true; // A VTT normally counts too — channels can be hybrid. The replace-auto-captions diff --git a/editor/app/channels/[slug]/components/VideoListPane.tsx b/editor/app/channels/[slug]/components/VideoListPane.tsx @@ -879,7 +879,7 @@ function StatusGlyphs({ row }: { row: VideoRow }) { row.corruptSource ? "corrupt source (needs re-download)" : row.corruptFullSource - ? "corrupt full source (download completed but audio is malformed; file kept for inspection)" + ? "corrupt full source (download completed but audio is malformed; file kept — a retry downloads again)" : "downloaded" } className={`w-2 h-2 rounded-full ${dlColor}`} diff --git a/editor/app/channels/[slug]/components/stages/DownloadStage.tsx b/editor/app/channels/[slug]/components/stages/DownloadStage.tsx @@ -29,6 +29,8 @@ type Props = { noTranscriptIds: string[]; partialDownloadIds: string[]; needsCookiesIds: string[]; + // Release 30 lane Q: complete downloads whose audio stayed malformed. + corruptFullSourceIds: string[]; missingShard: ShardConfigSummary | null; }; @@ -42,6 +44,7 @@ export function DownloadStage({ noTranscriptIds, partialDownloadIds, needsCookiesIds, + corruptFullSourceIds, missingShard, }: Props) { const [downloadQueue, setDownloadQueue] = useState(defaultQueueKey); @@ -229,6 +232,12 @@ export function DownloadStage({ defaultQueueKey={defaultQueueKey} existingQueues={existingQueues} /> + <CorruptFullSourceList + slug={slug} + ids={corruptFullSourceIds} + defaultQueueKey={defaultQueueKey} + existingQueues={existingQueues} + /> </div> ); } @@ -488,6 +497,56 @@ function NeedsCookiesList({ ); } +// A RETRY REFETCHES (release 30, lane Q): the kept file is set aside while +// the source is asked again, and comes back if the download fails. +function CorruptFullSourceList({ + slug, + ids, + defaultQueueKey, + existingQueues, +}: { + slug: string; + ids: string[]; + defaultQueueKey: string; + existingQueues: string[]; +}) { + // Stays mounted once its retry has run (RetryBucketControl says why). + const [ranHere, setRanHere] = useState(false); + if (ids.length === 0 && !ranHere) return null; + return ( + <div className="flex flex-col gap-2 rounded border border-border p-3"> + <div> + <h4 className="text-sm font-semibold"> + Corrupt full sources ({ids.length}) + </h4> + <p className="text-xs text-muted-foreground"> + Downloads that completed with malformed audio; the file is kept. A + retry downloads again — a source that is only sometimes malformed can + come back clean. If it is malformed again, the copy that decodes + longer stays; if the download fails, the kept file stays. + </p> + </div> + <VideoIdList + slug={slug} + ids={ids} + ariaLabel="corrupt full sources list" + emptyAriaLabel="corrupt full sources empty" + emptyMessage="None" + itemAriaLabel={(id) => `corrupt full source ${id}`} + /> + <RetryBucketControl + slug={slug} + ids={ids} + actionLabel="corrupt full sources" + defaultQueueKey={defaultQueueKey} + existingQueues={existingQueues} + bucketKey="corruptFullSource" + onRun={() => setRanHere(true)} + /> + </div> + ); +} + function Heading({ title, desc }: { title: string; desc: string }) { return ( <div> diff --git a/editor/app/channels/[slug]/lib/videoRows.ts b/editor/app/channels/[slug]/lib/videoRows.ts @@ -26,8 +26,8 @@ export type VideoRow = { corruptSource: boolean; // The download COMPLETED but its audio stream stayed malformed after one // re-download (download-outcome "corrupt-full-source"). The raw container is - // kept on disk for inspection; re-downloading is futile. Terminal and distinct - // from corruptSource (which never finished) and from a failed transcription. + // kept on disk; a retry refetches it (release 30, lane Q). Distinct from + // corruptSource (which never finished) and from a failed transcription. corruptFullSource: boolean; failedTranscription: boolean; // Has at least one finalized audio file not in the channel's target format — diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -494,6 +494,7 @@ export default async function ChannelDetailPage({ noTranscriptIds={actionableNoTranscriptIds} partialDownloadIds={buckets.partialDownloads} needsCookiesIds={buckets.needsCookies} + corruptFullSourceIds={buckets.corruptFullSource} missingShard={await shard("download-missing")} /> ); diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/DownloadOutcomeBadge.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/DownloadOutcomeBadge.tsx @@ -26,7 +26,7 @@ export function DownloadOutcomeBadge({ case "failed-corrupt-source": return "Corrupt source — download couldn't finish"; case "corrupt-full-source": - return "Corrupt full source — download completed but audio is malformed (file kept)"; + return "Corrupt full source — download completed but audio is malformed (file kept; a retry downloads again)"; case "failed-short-audio": return "Truncated download — audio far shorter than the video (file kept)"; case "skipped-filtered": { diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1079,6 +1079,8 @@ export function usage() { ' lane hold: {"slug", "bucket"}. "ids": [...] runs only those videos, and', " every one must be in the bucket (a stray id is refused, named); a job run", " with ids is not replayable, as a checkbox selection in the UI is not.", + ' "corruptFullSource" downloads again: the kept file is set aside, and comes', + " back if the download fails; malformed again, the longer decode stays.", "", 'transcribe-bucket transcribes a channel\'s "downloaded, not transcribed"', ' bucket on the transcription queue, as the channel page\'s Transcribe button',