Archilyzer · Source

archilyzer

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

commit bc527f4c0906ba98966d7418243108a13ccaeb90
parent 4663c3160e50cada0cab3e111e9dc2398dea3e6f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 15 Oct 2026 17:41:17 -0400

Merge r30/corrupt-recovery: a corrupt full source's retry refetches it (the kept file moved aside, kept back on failure), salvage transcription of a damaged recording on its own clock, salvaged transcripts marked in the index, export and MCP

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

Diffstat:
MCOMMANDS.md | 4++--
Mcommon/components/PlayerProvider.tsx | 5+++++
Mcommon/components/TranscriptModal.tsx | 7+++++++
Mcommon/controller/buildIndex.ts | 14++++++++++++++
Acommon/controller/buildIndexSalvaged.test.ts | 117+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/channelSnapshot.test.ts | 56++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/channelSnapshot.ts | 32+++++++++++++++++++++++++++++---
Mcommon/controller/transcribeOne.ts | 128++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Acommon/controller/transcribeSalvage.test.ts | 176+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/jobSpec.test.ts | 1+
Mcommon/jobs/jobSpec.ts | 3+++
Mcommon/lib/downloadOutcome.ts | 44++++++++++++++++++++++++++++++++++++++++----
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/lib/salvageMark.test.ts | 11+++++++++++
Acommon/lib/salvageMark.ts | 23+++++++++++++++++++++++
Mcommon/lib/transcribeOutcome.ts | 18++++++++++++++++++
Mcommon/lib/transcriptionApps.test.ts | 15+++++++++++++++
Mcommon/lib/transcriptionApps.ts | 9++++++++-
Mcommon/lib/transcripts.ts | 6++++++
Mcommon/testing/README.md | 1+
Acommon/testing/audio/corruptAudio.d.mts | 18++++++++++++++++++
Acommon/testing/audio/corruptAudio.mjs | 99+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/views/pipeline/channelFlow.ts | 8+++++++-
Mcommon/views/pipeline/stageStatus.ts | 1+
Acommon/ytdlp/corruptRefetch.test.ts | 363+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/ytdlp/corruptRefetch.ts | 336+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 27++++++++++++++++++++++++---
Mcommon/ytdlp/runYtdlp.ts | 32+++++++++++++++++++++++++++-----
Meditor/CHANGELOG.md | 2++
Meditor/app/api/ops/_writes.test.ts | 4++++
Meditor/app/api/ops/transcribe-one/route.ts | 15++++++++++-----
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+
Aeditor/app/channels/[slug]/videos/[id]/components/SalvagedTranscriptNotice.tsx | 31+++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx | 13+++++++++++--
Meditor/app/channels/[slug]/videos/[id]/components/cards/DownloadOutcomeBadge.tsx | 2+-
Meditor/app/channels/[slug]/videos/[id]/lib/videoChoreCards.ts | 5+++--
Meditor/app/channels/[slug]/videos/[id]/page.tsx | 6++++++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 8++++++++
Meditor/e2e/audio-check-scenarios.spec.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/e2e/fixtures/bin/fake-ytdlp.mjs | 9+++++++++
Mmcp/src/search.test.ts | 30++++++++++++++++++++++++++++++
Mmcp/src/server.ts | 13++++++++++---
Mplans/FACTS.md | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aplans/release-30/q.md | 125+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mscripts/archilyzer-ops.mjs | 7++++++-
Mscripts/parakeet-stitch.mjs | 66+++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mscripts/parakeet-stitch.test.mjs | 75+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
55 files changed, 2687 insertions(+), 49 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. | | @@ -136,7 +136,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `settings` | settings patches settings.json through the editor's one writer: {"patch": {"&lt;top-level key&gt;": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` | | `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | | | `workers` | workers switches transcription workers as /workers does: {"op": "enable" \| "disable" \| "drain", "ids": \[...\]} — the live pool; a restart restores the launch default. An unknown id is named; the others still apply. | `pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}'` | -| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. | | +| `transcribe-one` | transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file" (an audio file in its dir) that file; without, the video page's Transcribe — the audio on disk, or downloaded first through the channel's managed path. A job; --wait follows it. "salvage": true decodes a damaged file with error tolerance and transcribes what decodes, on the recording's clock, its gaps recorded (the transcript is listed as salvaged); a corrupt-full-source video is salvaged unless "salvage": false. | | | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | | `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | diff --git a/common/components/PlayerProvider.tsx b/common/components/PlayerProvider.tsx @@ -93,6 +93,8 @@ export type TranscriptData = { webpageUrl: string; hlsUrl?: string; mediaUrl?: string; + // A salvage transcript (release 30, lane Q): how much of the runtime decoded. + salvaged?: { decodedSeconds: number; totalSeconds: number }; // The cues of the track on show: the primary, or the alternate the viewer // picked (`track`). cues?: Cue[]; @@ -125,6 +127,8 @@ type Detail = { webpageUrl: string; hlsUrl?: string; mediaUrl?: string; + // A salvage transcript (release 30, lane Q): how much of the runtime decoded. + salvaged?: { decodedSeconds: number; totalSeconds: number }; cues?: Cue[]; } & TrackFields; @@ -462,6 +466,7 @@ export function PlayerProvider({ webpageUrl: detail.webpageUrl, hlsUrl: detail.hlsUrl, mediaUrl: detail.mediaUrl, + ...(detail.salvaged ? { salvaged: detail.salvaged } : {}), // A `vt` the record does not hold reads as the primary. cues: cuesOfTrack(detail, urlVt) ?? detail.cues, tracks: recordTracks(detail), diff --git a/common/components/TranscriptModal.tsx b/common/components/TranscriptModal.tsx @@ -37,6 +37,7 @@ import { VirtualRow } from "./VirtualRow"; import { formatTimestamp } from "../lib/vtt"; import { formatDate } from "../lib/format"; import { trackLabels } from "../lib/captionTracks"; +import { partialTranscriptLine } from "../lib/salvageMark"; type DisplayCue = { start: number; @@ -320,6 +321,11 @@ export default function TranscriptModal() { {data.ageRestricted && <AgeRestrictedBadge />} </p> )} + {data?.salvaged && ( + <p role="status" className="text-xs text-amber-200 mt-0.5"> + {partialTranscriptLine(data.salvaged)} + </p> + )} </div> <div className="px-3 sm:px-0 flex flex-wrap items-center gap-x-3 gap-y-1"> @@ -841,3 +847,4 @@ function TrackSwitcher({ </label> ); } + diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -174,6 +174,7 @@ import { } from "./curatedTagsIndex"; import { tagsForSite } from "../lib/curatedTags"; import { compileRecordedDateRule, deriveRecordedDate } from "../lib/recordedDate"; +import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server"; // v10: multi-site build. Shared per-channel transcript/subs pages are written // once; per-site summaries + subs manifests are filtered selections. Bumped to @@ -1114,6 +1115,19 @@ export async function buildIndex({ const recorded = deriveRecordedDate(recordedRe, summary.title, summary.uploadDate); if (recorded) summary.recordedDate = recorded; } + // A SALVAGE transcript says so on its record (release 30, lane Q): + // only a whisper transcript can be one, and only one carrying the + // outcome sidecar pays the small read. Never carried over. + delete summary.salvaged; + if (s.transcriptKind === "whisper") { + const salvaged = (await loadTranscribeOutcome(videoFullDir).catch(() => null))?.salvaged; + if (salvaged) { + summary.salvaged = { + decodedSeconds: salvaged.decodedSeconds, + totalSeconds: salvaged.totalSeconds, + }; + } + } const indexKey: IndexKey = [ summary.uploadDate, s.channelSlug, diff --git a/common/controller/buildIndexSalvaged.test.ts b/common/controller/buildIndexSalvaged.test.ts @@ -0,0 +1,117 @@ +// Integration: a SALVAGE transcript is marked on its index record and its +// published page (release 30, lane Q) — `salvaged: {decodedSeconds, +// totalSeconds}` from transcribe-outcome.json — and only there: every other +// record's page bytes are what they were, and a clean re-transcription drops +// the mark. Synthetic records through the REAL buildIndex over a temp corpus. +// +// Run with: node_modules/.bin/tsx --test common/controller/buildIndexSalvaged.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, utimesSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const ROOT = mkdtempSync(path.join(tmpdir(), "build-index-salvaged-")); +const PINNED: Record<string, string> = { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"), + EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"), + CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"), + SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"), + CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"), + ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), + ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"), +}; +Object.assign(process.env, PINNED); +delete process.env.ARCHILYZER_INDEX_ALLOW_HELD; +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { buildIndex } = await import("./buildIndex"); +const { open } = await import("lmdb"); + +const paths = getPaths(); +const SLUG = "example-salvage"; +const SITE = "testsite"; + +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const dirOf = (id: string) => path.join(paths.channelsDir, SLUG, "data", id); + +function video(id: string, salvaged?: { decodedSeconds: number; totalSeconds: number; gaps: number[][] }) { + const dir = dirOf(id); + writeJson(path.join(dir, "metadata.info.json"), { + id, + title: `Recording ${id}`, + upload_date: "20260105", + duration: 6000, + webpage_url: `https://odysee.com/@example:0/${id}:0`, + extractor_key: "LBRY", + }); + writeJson(path.join(dir, "transcript.json"), { + chunk_data: [{ start_time: 1, end_time: 2, text: "a synthetic line" }], + }); + writeJson(path.join(dir, "transcribe-outcome.json"), { + videoId: id, + transcribedAt: "2026-10-15T00:00:00.000Z", + ...(salvaged ? { salvaged: { source: "audio.mp4", ...salvaged } } : {}), + }); +} + +function pagesOf(slug: string): string { + const dir = path.join(paths.exportSharedTranscriptsDir, slug); + return readdirSync(dir) + .filter((f) => f.startsWith("page-")) + .map((f) => readFileSync(path.join(dir, f), "utf8")) + .join("\n"); +} + +function records(): Record<string, unknown> { + const out: Record<string, unknown> = {}; + for (const page of pagesOf(SLUG).split("\n").filter(Boolean)) { + for (const r of JSON.parse(page) as Array<{ id: string; salvaged?: unknown }>) out[r.id] = r.salvaged; + } + return out; +} + +test("a salvage transcript's record says how much decoded; a clean one says nothing", async () => { + writeFileSync(paths.settingsFile, "{}"); + writeJson(path.join(paths.channelsDir, SLUG, "config.json"), { handling: "transcribe", name: SLUG }); + writeJson(path.join(paths.sitesDir, SITE, "site.json"), { + siteId: SITE, + siteTitle: "Test Site", + siteDescription: "fixture", + headerTitle: "Test Site", + homeTagline: "", + socialLinks: [], + groups: [{ id: "default", name: "All channels", selectedByDefault: true }], + defaultGroupId: "default", + channels: [{ slug: SLUG, groupId: "default" }], + }); + video("SalvagedRec1", { decodedSeconds: 2335, totalSeconds: 6000, gaps: [[2335, 6000]] }); + video("CleanRec0001"); + await buildIndex({ paths, onLog: () => {} }); + assert.deepEqual(records(), { + SalvagedRec1: { decodedSeconds: 2335, totalSeconds: 6000 }, + CleanRec0001: undefined, + }); + // The gaps stay on disk; the record carries the two numbers. + assert.doesNotMatch(pagesOf(SLUG), /gaps/); + + // Transcribed again from clean audio: the mark goes. + video("SalvagedRec1"); + const later = new Date(Date.now() + 5000); + utimesSync(path.join(dirOf("SalvagedRec1"), "transcript.json"), later, later); + await buildIndex({ paths, onLog: () => {} }); + assert.deepEqual(records(), { SalvagedRec1: undefined, CleanRec0001: undefined }); + assert.doesNotMatch(pagesOf(SLUG), /salvaged/); +}); diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts @@ -854,3 +854,59 @@ test("a channel with no clips/ reports 0 clip bytes, not undefined", async () => await rm(dir, { recursive: true, force: true }); } }); + +// Release 30 lane Q: a salvage transcript is listed in salvagedTranscript, and +// a corrupt-full-source video stays in its bucket after one is made from its +// kept file — a retry can still bring a clean copy. +test("a salvage transcript is salvagedTranscript; its corrupt full source stays corruptFullSource", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "ttb-snap-salvage-")); + try { + const paths = { channelsDir: path.join(dir, "channels") } as Paths; + const channelDir = path.join(paths.channelsDir, "alpha"); + const ids = ["aaaa0000001", "bbbb0000002", "cccc0000003", "dddd0000004"]; + for (const id of ids) await mkdir(path.join(channelDir, "data", id), { recursive: true }); + await writeFile( + path.join(channelDir, "config.json"), + JSON.stringify({ handling: "transcribe", url: "https://www.youtube.com/@alpha/videos" }), + ); + await writeFile( + path.join(channelDir, "playlist"), + ids.map((id) => `https://www.youtube.com/watch?v=${id}`).join("\n"), + ); + const put = (id: string, name: string, body: unknown) => + writeFile(path.join(channelDir, "data", id, name), typeof body === "string" ? body : JSON.stringify(body)); + const cfs = { + videoId: "", + status: "corrupt-full-source", + startedAt: "2026-10-01T00:00:00.000Z", + finishedAt: "2026-10-01T00:01:00.000Z", + attempts: [], + }; + const salvaged = { source: "audio.mp4", decodedSeconds: 2335, totalSeconds: 6000, gaps: [[2335, 6000]] }; + for (const id of ids) await put(id, "metadata.info.json", { id, duration: 6000 }); + // a: corrupt full source, kept file, no transcript yet. + await put("aaaa0000001", "audio.mp4", "x"); + await put("aaaa0000001", "download-outcome.json", { ...cfs, videoId: "aaaa0000001" }); + // b: corrupt full source, salvaged. + await put("bbbb0000002", "audio.mp4", "x"); + await put("bbbb0000002", "download-outcome.json", { ...cfs, videoId: "bbbb0000002" }); + await put("bbbb0000002", "transcript.json", "{}"); + await put("bbbb0000002", "transcribe-outcome.json", { videoId: "bbbb0000002", transcribedAt: "2026-10-15T00:00:00.000Z", salvaged }); + // c: a clean download whose transcript was salvaged on request. + await put("cccc0000003", "audio.mp4", "x"); + await put("cccc0000003", "transcript.json", "{}"); + await put("cccc0000003", "transcribe-outcome.json", { videoId: "cccc0000003", transcribedAt: "2026-10-15T00:00:00.000Z", salvaged }); + // d: an ordinary transcript. + await put("dddd0000004", "audio.mp4", "x"); + await put("dddd0000004", "transcript.json", "{}"); + await put("dddd0000004", "transcribe-outcome.json", { videoId: "dddd0000004", transcribedAt: "2026-10-15T00:00:00.000Z" }); + + const snap = await generateChannelSnapshot(paths, "alpha"); + assert.deepEqual(snap.buckets.corruptFullSource, ["aaaa0000001", "bbbb0000002"]); + assert.deepEqual(snap.buckets.salvagedTranscript, ["bbbb0000002", "cccc0000003"]); + // Still transcripts: what is there is real and searchable. + assert.equal(snap.totals.transcribed, 3); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts @@ -53,6 +53,8 @@ import { } from "../jobs/autoQueuePolicy"; import { isExcludedFromTruncatedCheck } from "../lib/excludeTruncatedCheck-server"; import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; +import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server"; +import { TRANSCRIBE_OUTCOME_FILENAME } from "../lib/transcribeOutcome"; import { chatOnlyIdsFrom, loadMetadataScan, @@ -190,9 +192,11 @@ 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). A salvage transcript made from the kept file + // does not take it out of this bucket (it is in salvagedTranscript too). + // 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 @@ -253,6 +257,14 @@ export type ChannelSnapshot = { // the user can re-download/re-transcribe. Optional: older snapshots lack it; // readers must default to []. incompleteTranscript: string[]; + // Videos whose transcript is a SALVAGE (release 30, lane Q): made from a + // damaged file decoded with error tolerance, with gaps where nothing + // decoded (transcribe-outcome.json `salvaged`). Counted as transcribed — + // what is there is real and searchable — but not a clean full transcript. + // A corrupt-full-source video stays in corruptFullSource too: a retry can + // still bring a clean copy. Optional: older snapshots lack it; readers + // default to []. + salvagedTranscript: string[]; // Videos whose download COMPLETED (yt-dlp exit 0) but whose audio is far // shorter than the metadata duration — the source served a truncated stream // (download-outcome.json "failed-short-audio"). Caught at download time by @@ -997,6 +1009,13 @@ export async function generateChannelSnapshot( const excludedFromTruncatedCheck = await isExcludedFromTruncatedCheck(dir); const outcome = await loadDownloadOutcome(dir); + // A salvage transcript says so in its transcribe-outcome.json (release + // 30, lane Q). Only a whisper transcript can be one, so only those + // with the sidecar pay the small read. + const salvaged = + files.hasWhisper && files.entries.includes(TRANSCRIBE_OUTCOME_FILENAME) + ? Boolean((await loadTranscribeOutcome(dir))?.salvaged) + : false; // Only transcribed (non-untranscribable) dirs can have a truncated // transcript; skip the cues.json read for everything else. const coverage = @@ -1055,6 +1074,7 @@ export async function generateChannelSnapshot( doNotClean, excludedFromTruncatedCheck, outcome, + salvaged, coverage, vttProvenance, digest, @@ -1170,6 +1190,7 @@ export async function generateChannelSnapshot( // and the reason this is a bucket rather than a derived count. const chatOnlyPending: string[] = []; const incompleteTranscript: string[] = []; + const salvagedTranscript: string[] = []; const shortAudio: string[] = []; const autoSubsOnly: string[] = []; const downloadedAutoSubsOnly: string[] = []; @@ -1214,6 +1235,7 @@ export async function generateChannelSnapshot( backfill, effectiveAvailability, outcome, + salvaged, coverage, vttProvenance, digest, @@ -1282,6 +1304,9 @@ export async function generateChannelSnapshot( // downloadedNoTranscript (which would transcribe corrupt audio, or offer // the kept file to the wrong-format sweep) or the wrong-format cleanup // estimate (which would delete it). + // A salvage transcript, whatever the download says (before the + // corrupt-full-source short-circuit: most salvages are of those). + if (salvaged) salvagedTranscript.push(id); if (outcome?.status === "corrupt-full-source") { corruptFullSource.push(id); continue; @@ -1668,6 +1693,7 @@ export async function generateChannelSnapshot( chatOnly: chatOnly.sort(), chatOnlyPending: chatOnlyPending.sort(), incompleteTranscript: incompleteTranscript.sort(), + salvagedTranscript: salvagedTranscript.sort(), shortAudio: shortAudio.sort(), autoSubsOnly: autoSubsOnly.sort(), downloadedAutoSubsOnly: downloadedAutoSubsOnly.sort(), diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -21,6 +21,17 @@ import { findSourceMedia, isRealAudioFile } from "../lib/videoStatus"; import { pickPreferredAudio } from "../lib/mediaFiles"; import { resolveSavedVideo } from "../lib/savedVideo-server"; import { writeTranscribeOutcome } from "../lib/transcribeOutcome-server"; +import type { TranscriptSalvage } from "../lib/transcribeOutcome"; +import { loadDownloadOutcome } from "../lib/downloadOutcome-server"; +import { + SALVAGE_WAV_FILENAME, + describeSalvage, + gapSeconds, + mergeGaps, + salvageDecode, + type SalvageGap, + type SalvageResult, +} from "../lib/salvageAudio-server"; import { writeFileAtomic } from "../lib/jsonFile-server"; import { probeMedia } from "../lib/evidenceClip-server"; import { savedWindowSource } from "../lib/savedVideoWindow-server"; @@ -157,6 +168,13 @@ export type TranscribeOneOptions = { // True asks the engine to keep word timestamps in transcript.json (see // TranscribeBuildInput.words). Only the one-off file transcription asks. words?: boolean; + // A SALVAGE transcription (release 30, lane Q): decode the audio with error + // tolerance into a WAV on the source's clock and transcribe that, recording + // what is missing in transcribe-outcome.json's `salvaged`. Asked for by + // `transcribe-one {"salvage": true}`; AUTOMATIC for a video whose download + // outcome is corrupt-full-source (its file is known to be malformed, and a + // plain run fails at the first bad window). False forces a plain run. + salvage?: boolean; }; export type TranscribeOneOutcome = "transcribed" | "already-exists" | "paused"; @@ -200,6 +218,79 @@ export async function transcribeOneVideo( log(`Using ${resolvedAudio} instead of ${opts.audioFilename}`); } + const salvage = await salvageWanted(opts); + try { + return await transcribeResolved(opts, resolvedAudio, salvage, log); + } finally { + // The salvage WAV is scratch: gone whatever the run ended as. A paused + // parakeet run keeps its window cache, keyed on the WAV's duration, and a + // re-run decodes the same WAV again. + if (salvage) await fs.rm(path.join(opts.videoDir, SALVAGE_WAV_FILENAME), { force: true }); + } +} + +// Salvage when asked, or when the video is a corrupt full source and nobody +// said not to. +async function salvageWanted(opts: TranscribeOneOptions): Promise<boolean> { + if (opts.salvage !== undefined) return opts.salvage; + const outcome = await loadDownloadOutcome(opts.videoDir).catch(() => null); + return outcome?.status === "corrupt-full-source"; +} + +// The windows a salvaging engine could not transcribe, from its output +// (parakeet-stitch --salvage: `salvage.failedWindows`). Empty for any other. +async function failedWindowsOf(transcriptPath: string): Promise<SalvageGap[]> { + try { + const doc = JSON.parse(await fs.readFile(transcriptPath, "utf8")) as { + salvage?: { failedWindows?: unknown }; + }; + const w = doc.salvage?.failedWindows; + if (!Array.isArray(w)) return []; + return w.filter( + (g): g is SalvageGap => + Array.isArray(g) && g.length === 2 && typeof g[0] === "number" && typeof g[1] === "number", + ); + } catch { + return []; + } +} + +async function transcribeResolved( + opts: TranscribeOneOptions, + resolvedAudio: string, + salvage: boolean, + log: (msg: string) => void, +): Promise<TranscribeOneOutcome> { + const transcriptPath = path.join(opts.videoDir, "transcript.json"); + // What the engine reads: the resolved audio, or its salvage WAV. + let engineAudio = resolvedAudio; + let scan: SalvageResult | null = null; + if (salvage) { + log( + `Salvage: decoding ${resolvedAudio} with error tolerance — undecodable spans become silence on the recording's clock.`, + ); + try { + scan = await salvageDecode( + path.join(opts.videoDir, resolvedAudio), + path.join(opts.videoDir, SALVAGE_WAV_FILENAME), + { + ffmpegBin: opts.paths.ffmpegBin, + ffprobeBin: opts.paths.ffprobeBin, + signal: opts.signal, + onLog: (l) => log(l.trimEnd()), + }, + ); + } catch (err) { + if (opts.signal?.aborted) throw err; + throw new TranscribeError( + `salvage decode of ${resolvedAudio} failed: ${(err as Error).message}`, + "transcription", + ); + } + log(`Salvage: ${describeSalvage(scan)}.`); + engineAudio = SALVAGE_WAV_FILENAME; + } + const worker = opts.worker; const start = Date.now(); // Each app writes "<outputBase><ext>" relative to cwd (the ext differs: whisper @@ -223,8 +314,8 @@ export async function transcribeOneVideo( try { bytes = await transcribeViaRemote({ worker, - audioPath: path.join(opts.videoDir, resolvedAudio), - audioName: resolvedAudio, + audioPath: path.join(opts.videoDir, engineAudio), + audioName: engineAudio, videoId: opts.videoId, channelSlug: deriveChannelSlug(opts.paths, opts.videoDir) ?? undefined, onLog: (line: string) => log(line), @@ -249,13 +340,14 @@ export async function transcribeOneVideo( const appConfig = worker.config ?? {}; const bin = appConfig.bin?.trim() || app.defaultBin(); log( - `Transcribe ${opts.videoId} start (${resolvedAudio}) via ${app.id} [${worker.id}]`, + `Transcribe ${opts.videoId} start (${engineAudio}) via ${app.id} [${worker.id}]`, ); const build = app.build({ - audioFile: resolvedAudio, + audioFile: engineAudio, outputBase: tmpBase, config: appConfig, ...(opts.words ? { words: true } : {}), + ...(salvage ? { salvage: true } : {}), }); const child = execa(bin, build.argv, { cwd: opts.videoDir, @@ -326,12 +418,37 @@ export async function transcribeOneVideo( // "content added over time" by transcription date. Best-effort: a failed // sidecar write must not fail an otherwise-successful transcription (the build // falls back to the transcript file mtime when the sidecar is absent). + // A salvage's gaps: what did not decode, and any window the engine could + // not transcribe (parakeet --salvage). A file that decoded whole with every + // window transcribed (a corrupt full source whose kept file was replaced by + // a clean one outside the managed download) made a clean transcript, and is + // not recorded as a salvage. Decoded seconds never claim a gap. + let salvaged: TranscriptSalvage | null = null; + if (scan) { + const failed = await failedWindowsOf(transcriptPath); + if (failed.length > 0) { + log(`Salvage: ${failed.length} window(s) could not be transcribed; recorded as gaps.`); + } + const gaps = mergeGaps([...scan.gaps, ...failed]); + if (gaps.length > 0 || scan.decodedSeconds < scan.totalSeconds - 1) { + const covered = Math.max(0, Math.round((scan.totalSeconds - gapSeconds(gaps)) * 1000) / 1000); + salvaged = { + source: resolvedAudio, + decodedSeconds: Math.min(scan.decodedSeconds, covered), + totalSeconds: scan.totalSeconds, + gaps, + }; + } else { + log(`Salvage: ${resolvedAudio} decodes whole; the transcript is a clean one.`); + } + } try { await writeTranscribeOutcome(opts.videoDir, { videoId: opts.videoId, transcribedAt: new Date().toISOString(), worker: { id: worker.id, appId: worker.appId, kind: worker.kind }, durationMs: Date.now() - start, + ...(salvaged ? { salvaged } : {}), }); } catch (err) { log( @@ -444,6 +561,8 @@ export type TranscribeWithWorkerOptions = { skipInlineDiarization?: boolean; // See TranscribeOneOptions.words. words?: boolean; + // See TranscribeOneOptions.salvage. + salvage?: boolean; }; // Acquire a worker from the global pool and transcribe one video through it, @@ -510,6 +629,7 @@ export async function transcribeWithWorker( partialSignal: partialController?.signal, skipInlineDiarization: opts.skipInlineDiarization, words: opts.words, + ...(opts.salvage !== undefined ? { salvage: opts.salvage } : {}), }); pool.markSuccess(worker.id); return outcome; diff --git a/common/controller/transcribeSalvage.test.ts b/common/controller/transcribeSalvage.test.ts @@ -0,0 +1,176 @@ +// A SALVAGE TRANSCRIPTION KEEPS THE RECORDING'S CLOCK (release 30, lane Q). +// +// A corrupt-full-source video's kept file is transcribed with salvage (it is +// automatic for that status): decoded with error tolerance into a WAV whose +// undecodable spans are silence of their own length, then the normal parakeet +// path (the real scripts/parakeet-stitch.mjs, in overlapping windows) over a +// FAKE parakeet-cli that "transcribes" tone bursts — one word per burst, at +// the burst's time in its window. So the cues it produces are where the +// bursts are in the WAV, and the test checks they are where the bursts are in +// the SOURCE. No real ASR; real ffmpeg over a synthetic damaged recording. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/transcribeSalvage.test.ts + +import { after, before, test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; +import { + burstTimes, + corruptBytes, + hasFfmpeg, + makeToneFile, +} from "../testing/audio/corruptAudio.mjs"; + +const tools = hasFfmpeg(); +let ROOT = ""; +let VIDEO_DIR = ""; +let DAMAGED = ""; +let CLEAN = ""; +const SLUG = "tones"; +const ID = "vid1"; + +before(async () => { + ROOT = await mkdtemp(path.join(tmpdir(), "transcribe-salvage-")); + // Before anything reads getPaths(): a scratch corpus, and the fake CLI. + process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts"); + const cli = path.join(ROOT, "fake-parakeet-cli.mjs"); + const kit = pathToFileURL(path.resolve(import.meta.dirname, "../testing/audio/corruptAudio.mjs")).href; + await writeFile( + cli, + `#!/usr/bin/env node +import { readWavMono16, toneOnsets } from ${JSON.stringify(kit)}; +const argv = process.argv.slice(2); +const wav = argv[argv.indexOf("--input") + 1]; +const { samples, rate } = readWavMono16(wav); +const words = toneOnsets(samples, rate).map((t) => ({ w: "beep", start: t, end: t + 0.3 })); +process.stdout.write(JSON.stringify({ words })); +`, + ); + await chmod(cli, 0o755); + process.env.PARAKEET_CLI = cli; + if (!tools) return; + VIDEO_DIR = path.join(process.env.TRANSCRIPTS_DIR, "channels", SLUG, "data", ID); + await mkdir(VIDEO_DIR, { recursive: true }); + CLEAN = makeToneFile(path.join(ROOT, "clean.mp4")); + DAMAGED = corruptBytes(CLEAN, path.join(VIDEO_DIR, "audio.mp4")); + await writeFile( + path.join(VIDEO_DIR, "metadata.info.json"), + JSON.stringify({ id: ID, title: "Tones", duration: 30, upload_date: "20260105", webpage_url: "https://example.invalid/v/vid1" }), + ); + await writeFile( + path.join(VIDEO_DIR, "download-outcome.json"), + JSON.stringify({ + videoId: ID, + status: "corrupt-full-source", + startedAt: "2026-10-01T00:00:00.000Z", + finishedAt: "2026-10-01T00:01:00.000Z", + attempts: [], + }), + ); +}); +after(() => rm(ROOT, { recursive: true, force: true })); + +const near = (a: number, b: number, tol = 0.06) => Math.abs(a - b) <= tol; + +// A model file must exist; the fake CLI never reads it. 20 s windows with the +// default 6 s overlap: the 30 s recording is two windows, so the stitch's +// offsets are exercised too. +const worker = () => ({ + id: "w1", + name: "fake parakeet", + kind: "local" as const, + enabled: true, + priority: 0, + appId: "parakeet", + config: { model: CLEAN, chunkSize: 20 }, +}); + +test( + "a corrupt full source is salvaged: cues on the recording's clock, the gap recorded, the WAV gone", + { skip: !tools && "ffmpeg/ffprobe not installed" }, + async () => { + const { transcribeOneVideo } = await import("./transcribeOne"); + const { getPaths } = await import("../lib/paths"); + const paths = getPaths(); + const lines: string[] = []; + const outcome = await transcribeOneVideo({ + paths, + videoDir: VIDEO_DIR, + videoId: ID, + audioFilename: "audio.mp4", + worker: worker(), + onLog: (l) => lines.push(l), + skipInlineDiarization: true, + }); + assert.equal(outcome, "transcribed", lines.join("\n")); + assert.match(lines.join("\n"), /Salvage: decoding audio\.mp4 with error tolerance/); + + const record = JSON.parse(await readFile(path.join(VIDEO_DIR, "transcribe-outcome.json"), "utf8")); + assert.ok(record.salvaged, "transcribe-outcome.json records the salvage"); + assert.equal(record.salvaged.source, "audio.mp4"); + assert.ok(near(record.salvaged.totalSeconds, 30), `total ${record.salvaged.totalSeconds}`); + assert.equal(record.salvaged.gaps.length, 1, JSON.stringify(record.salvaged.gaps)); + const [from, to] = record.salvaged.gaps[0]; + assert.ok(to - from > 1); + assert.ok(record.salvaged.decodedSeconds < 30 - 1); + + // The cues: one per surviving burst, each at its SOURCE time. + const transcript = JSON.parse(await readFile(path.join(VIDEO_DIR, "transcript.json"), "utf8")); + const starts: number[] = transcript.chunk_data.map((c: { start_time: number }) => c.start_time); + 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(starts.some((s) => near(s, t)), `no cue at ${t}s (cues ${starts.join(", ")})`); + } + for (const s of starts) { + assert.ok(!(s > from + 0.05 && s < to - 0.05), `cue at ${s}s inside the gap ${from}-${to}`); + } + // Normalized, as every transcription is. + assert.ok(existsSync(path.join(VIDEO_DIR, "transcript.cues.json"))); + // The salvage WAV and parakeet's window cache are gone. + assert.equal(existsSync(path.join(VIDEO_DIR, "audio.salvage.wav")), false); + assert.equal(existsSync(path.join(VIDEO_DIR, ".audio.salvage.wav.parakeet")), false); + // The kept file is untouched. + assert.ok(existsSync(path.join(VIDEO_DIR, "audio.mp4"))); + }, +); + +test( + "a file that decodes whole makes a clean transcript: nothing recorded as salvaged", + { skip: !tools && "ffmpeg/ffprobe not installed" }, + async () => { + // The kept file was replaced by a clean one outside the managed download; + // the sidecar still says corrupt-full-source, so salvage runs — and finds + // nothing missing. + const { transcribeOneVideo } = await import("./transcribeOne"); + const { getPaths } = await import("../lib/paths"); + const dir = path.join(path.dirname(VIDEO_DIR), "vid2"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "audio.mp4"), await readFile(CLEAN)); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id: "vid2", title: "Tones", duration: 30 })); + await writeFile( + path.join(dir, "download-outcome.json"), + JSON.stringify({ videoId: "vid2", status: "corrupt-full-source", startedAt: "x", finishedAt: "x", attempts: [] }), + ); + const lines: string[] = []; + const outcome = await transcribeOneVideo({ + paths: getPaths(), + videoDir: dir, + videoId: "vid2", + audioFilename: "audio.mp4", + worker: worker(), + onLog: (l) => lines.push(l), + skipInlineDiarization: true, + }); + assert.equal(outcome, "transcribed", lines.join("\n")); + assert.match(lines.join("\n"), /decodes whole; the transcript is a clean one/); + const record = JSON.parse(await readFile(path.join(dir, "transcribe-outcome.json"), "utf8")); + assert.equal(record.salvaged, undefined); + const transcript = JSON.parse(await readFile(path.join(dir, "transcript.json"), "utf8")); + assert.equal(transcript.chunk_data.length, burstTimes().length); + }, +); 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 @@ -3,6 +3,7 @@ import type { Availability, DownloadFailureClass } from "./availability"; import type { ChannelHandling } from "./channelConfig"; +import type { TranscriptSalvage } from "./transcribeOutcome"; export type DownloadOutcomeStatus = | "ok" @@ -12,10 +13,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 +105,34 @@ 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 }; + // clean: the salvage transcript made from the replaced file, retired so the + // transcription lane makes a full one from the clean audio — what it was. + retiredSalvage?: TranscriptSalvage & { transcribedAt: string }; +}; + export type DownloadOutcomeRecord = { videoId: string; webpageUrl?: string; @@ -134,6 +167,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/lib/salvageMark.test.ts b/common/lib/salvageMark.test.ts @@ -0,0 +1,11 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { partialTranscriptLine, salvageCaveat } from "./salvageMark"; + +// Release 30 lane Q: the salvage mark, as the export and the MCP say it. +test("the status line and the caveat say how much decoded, in minutes", () => { + const mark = { decodedSeconds: 2335, totalSeconds: 6000 }; + assert.equal(partialTranscriptLine(mark), "Partial transcript: 39 of 100 min decoded"); + assert.match(salvageCaveat(mark), /^⚠ PARTIAL TRANSCRIPT — made from a damaged recording: 39 of 100 min decoded/); + assert.match(salvageCaveat(mark), /Do NOT conclude/); +}); diff --git a/common/lib/salvageMark.ts b/common/lib/salvageMark.ts @@ -0,0 +1,23 @@ +// A SALVAGE TRANSCRIPT, SAID IN ONE LINE (release 30, lane Q) — the record's +// `salvaged` mark (TranscriptSummary.salvaged: made from a damaged recording, +// no transcript where it would not decode) as the export's video page and the +// MCP say it. Pure: no fs, client-safe. + +export type SalvageMark = { decodedSeconds: number; totalSeconds: number }; + +const minutes = (sec: number) => Math.max(0, Math.round(sec / 60)); + +// "Partial transcript: 39 of 100 min decoded" +export function partialTranscriptLine(s: SalvageMark): string { + return `Partial transcript: ${minutes(s.decodedSeconds)} of ${minutes(s.totalSeconds)} min decoded`; +} + +// The MCP's caveat, phrased like its coverage warning: a reader must not +// conclude from this transcript that something was never said. +export function salvageCaveat(s: SalvageMark): string { + return ( + `⚠ PARTIAL TRANSCRIPT — made from a damaged recording: ${minutes(s.decodedSeconds)} of ` + + `${minutes(s.totalSeconds)} min decoded, and the rest has no transcript. Do NOT conclude ` + + `from this transcript that something was never said.` + ); +} diff --git a/common/lib/transcribeOutcome.ts b/common/lib/transcribeOutcome.ts @@ -18,6 +18,24 @@ export type TranscribeOutcomeRecord = { worker?: { id: string; appId?: string; kind: "local" | "remote" | "llm" }; // Wall-clock transcription time in milliseconds. durationMs?: number; + // Set when the transcript is a SALVAGE (release 30, lane Q): made from a + // damaged file decoded with error tolerance, its undecodable spans silence + // on the source's clock (lib/salvageAudio-server.ts). Not a clean full + // transcript — the channel report lists it in `salvagedTranscript`, and the + // video page says what is missing. + salvaged?: TranscriptSalvage; +}; + +export type TranscriptSalvage = { + // The file the salvage decoded (a name in the video dir). + source: string; + // Seconds of audio that decoded and were transcribed. + decodedSeconds: number; + // The recording's length (the container's duration). + totalSeconds: number; + // Spans of the recording with no transcript, [from, to] seconds: what did + // not decode, and any window the engine could not transcribe. Sorted, merged. + gaps: Array<[number, number]>; }; export const TRANSCRIBE_OUTCOME_FILENAME = "transcribe-outcome.json"; diff --git a/common/lib/transcriptionApps.test.ts b/common/lib/transcriptionApps.test.ts @@ -25,3 +25,18 @@ test("an engine with no words to give ignores the ask", () => { assert.deepEqual(app.build({ ...input, words: true }).argv, app.build(input).argv); } }); + +// Release 30 lane Q: a salvage run tells parakeet's wrapper that a bad window +// is a gap; the engines with no windows ignore it. +test("parakeet takes --salvage only on a salvage run; whisper.cpp and chough ignore it", () => { + const app = getTranscriptionApp("parakeet"); + assert.ok(!app.build(input).argv.includes("--salvage")); + const salvaging = app.build({ ...input, salvage: true }).argv; + assert.ok(salvaging.includes("--salvage")); + assert.equal(salvaging.at(-1), "audio.wav"); + for (const id of ["whisper-cpp", "chough"]) { + const other = getTranscriptionApp(id); + assert.equal(other.id, id); + assert.deepEqual(other.build({ ...input, salvage: true }).argv, other.build(input).argv); + } +}); diff --git a/common/lib/transcriptionApps.ts b/common/lib/transcriptionApps.ts @@ -78,6 +78,12 @@ export type TranscribeBuildInput = { // them to give; the others ignore it. Off for corpus transcriptions, whose // transcript.json would otherwise carry every word twice. words?: boolean; + // A SALVAGE run (release 30, lane Q): the input is a damaged recording + // decoded on its own clock, and a window the engine cannot transcribe is a + // gap, not a failed file. Only parakeet's wrapper has windows to tolerate + // (--salvage, which records them in the output's `salvage.failedWindows`); + // the others ignore it. + salvage?: boolean; }; export type TranscriptionApp = { @@ -249,11 +255,12 @@ const parakeet: TranscriptionApp = { supportsPartialStop: true, defaultBin: () => getPaths().parakeetBin, resolveModel: (config) => config.model?.trim() || getPaths().parakeetModel, - build({ audioFile, outputBase, config, words }) { + build({ audioFile, outputBase, config, words, salvage }) { const paths = getPaths(); const model = parakeet.resolveModel(config) as string; const argv = ["--model", model, "--output", outputBase]; if (words) argv.push("--words"); + if (salvage) argv.push("--salvage"); if (typeof config.chunkSize === "number" && config.chunkSize > 0) { argv.push("--segment", String(Math.floor(config.chunkSize))); } diff --git a/common/lib/transcripts.ts b/common/lib/transcripts.ts @@ -1,6 +1,7 @@ import path from "node:path"; import type { Cue } from "./vtt"; import type { TrackFields } from "./captionTracks"; +import type { SalvageMark } from "./salvageMark"; import { readFile } from "fs-extra"; import { getPaths } from "./paths"; @@ -43,6 +44,11 @@ export type TranscriptSummary = { // channel has no rule or the title gives no date, so every other channel's // pages stay byte-identical. Coverage reads it first (`coverageDate`). recordedDate?: string; + // The transcript is a SALVAGE (release 30, lane Q): made from a damaged + // recording, with no transcript where it would not decode — how much of the + // runtime decoded (transcribe-outcome.json `salvaged`, whose gaps stay on + // disk). OMITTED for every other record, so their pages stay byte-identical. + salvaged?: SalvageMark; }; export type DisplaySummary = { diff --git a/common/testing/README.md b/common/testing/README.md @@ -23,6 +23,7 @@ transcript, channel or person goes in these fixtures, ever. | `social/fakeBluesky.mjs` | Release 29: a fake Bluesky on loopback — the public AppView (`resolveHandle`, `getPosts` answering only live posts, images as `embed.images[].fullsize`), a bsky.app-shaped post page (`pageUrl(handle, rkey)`: the post in `[data-testid="postThreadItem-by-<handle>"]` inside page chrome, "Post not found" for a deleted one) for a headless screenshot, and PNG images. `bsky.fetch` sends `https://public.api.bsky.app`, `https://bsky.app` and `https://cdn.bsky.app` to it; `busyTimes` answers 429 first. | | `web/fakeWayback.mjs` | Release 29: a fake Wayback Machine — the CDX API (`/cdx/search/cdx`, `output=json` with its header row, `[]` for none, `filter=statuscode:`, `limit`, `matchType=prefix`) and capture pages (`/web/<ts>[id_]/<url>`). `wb.fetch` sends `https://web.archive.org` to it; `busyTimes` 429s, `downTimes` 503s. | | `draft/corpus.mjs` `GONE_RECORD`, `GONE_AVAILABILITY` | Release 29: a recording deleted on its platform (`state: "deleted"`, cues kept; add it with `withRecords`) and the `availability.json` it carries on disk. The fake Wayback has one capture of its watch page. | +| `audio/corruptAudio.mjs` | Release 30 lane Q: damaged audio for the salvage and refetch tests — `makeToneFile` (an AAC-in-MP4 tone-burst recording: a 0.3 s burst every 4 s, the bursts being the clock), `corruptBytes` (the same with a seeded run of its bytes overwritten: the frames there fail to decode, their timestamps survive), `readWavMono16`, `toneOnsets` (burst onsets in decoded samples), `burstTimes`, `hasFfmpeg`. Needs ffmpeg; the tests that use it skip without. | | `draft/runs/*.json` | One recorded run per generation task (release 27 S5): the model side, scripted — `turns` for the fake Anthropic (`sweep-agent`, `revise-report`, `revise-video`, `research`) or the fake ollama (`sweep-pipeline`, `narrate`; release 28's `flips`, `threads` and `youtube`, release 29's `social`, each with a `note` saying what it is run over and why its first answer is refused), with the question, channels or feedback it answers. `mcp/src/draftTasks.test.ts` runs each task over the synthetic corpus against them. | | `draft/derive.ts`, `draft/regenerate.ts` | How the derived files are made. After a converter change: `cd common && pnpm exec tsx testing/draft/regenerate.ts`, review the diff, commit. `fakes.test.ts` fails until they match. | 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: [ @@ -460,6 +460,12 @@ export function computeChannelFlow( "The transcript covers a fraction of the runtime — the audio download truncated silently.", ), ...siding( + "salvaged transcript", + buckets.salvagedTranscript.length, + "transcribe", + "Transcribed from a damaged file: the parts that would not decode are gaps. A retry of the corrupt full source can bring a clean copy.", + ), + ...siding( "short audio", buckets.shortAudio.length, "transcribe", diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts @@ -42,6 +42,7 @@ export function normalizeBuckets( chatOnly: raw?.chatOnly ?? [], chatOnlyPending: raw?.chatOnlyPending ?? [], incompleteTranscript: raw?.incompleteTranscript ?? [], + salvagedTranscript: raw?.salvagedTranscript ?? [], shortAudio: raw?.shortAudio ?? [], autoSubsOnly: raw?.autoSubsOnly ?? [], downloadedAutoSubsOnly: raw?.downloadedAutoSubsOnly ?? [], diff --git a/common/ytdlp/corruptRefetch.test.ts b/common/ytdlp/corruptRefetch.test.ts @@ -0,0 +1,363 @@ +// A retry of a corrupt-full-source video refetches it (release 30, lane Q): +// the kept file is moved aside for the download; a clean result removes it, a +// malformed one keeps the longer decode, anything else moves it back and the +// sidecar stays corrupt-full-source with the failed attempt appended. Temp +// dirs, a fake measure, and (for the whole path) a fake yt-dlp that answers +// the metadata prefetch with a 429 — the failure observed live 2026-10-15. +// +// Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/corruptRefetch.test.ts + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { existsSync } from "node:fs"; +import { + chmod, + lstat, + mkdir, + mkdtemp, + readFile, + readlink, + readdir, + rm, + writeFile, +} from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import type { DownloadOutcomeRecord } from "../lib/downloadOutcome"; +import { tierMediaFile } from "../lib/mediaTier-server"; +import { + CORRUPT_KEPT_SUFFIX, + prepareCorruptRefetch, + settleCorruptRefetch, +} from "./corruptRefetch"; +import { downloadOneManaged } from "./downloadOneManaged"; +import { destinationExists } from "./runYtdlp"; +import { generateChannelSnapshot } from "../controller/channelSnapshot"; + +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 }); +}); + +test("a clean refetch retires a salvage transcript: the video is downloaded-not-transcribed again", async () => { + const f = await fixture(); + const channelDir = path.join(f.channelsDir, "c"); + await writeFile( + path.join(channelDir, "config.json"), + JSON.stringify({ handling: "transcribe", url: "https://www.youtube.com/@c/videos" }), + ); + await writeFile(path.join(channelDir, "playlist"), `https://www.youtube.com/watch?v=${ID}\n`); + await writeFile(path.join(f.videoDir, "metadata.info.json"), JSON.stringify({ id: ID, duration: 6000 })); + const salvaged = { source: "audio.mp4", decodedSeconds: 2335, totalSeconds: 6000, gaps: [[2335, 6000]] }; + await writeFile(path.join(f.videoDir, "transcript.json"), "{}"); + await writeFile(path.join(f.videoDir, "transcript.cues.json"), "{}"); + await writeFile( + path.join(f.videoDir, "transcribe-outcome.json"), + JSON.stringify({ videoId: ID, transcribedAt: "2026-10-15T00:00:00.000Z", salvaged }), + ); + const paths = { channelsDir: f.channelsDir } as Paths; + const before = await generateChannelSnapshot(paths, "c"); + assert.deepEqual(before.buckets.salvagedTranscript, [ID]); + + const { ctx: c, log } = ctx(); + const plan = await prepareCorruptRefetch(f.videoDir, c); + assert.ok(plan); + await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-CLEAN"); + await settleCorruptRefetch(plan, outcome({ status: "ok-audio-checked" }), c); + for (const name of ["transcript.json", "transcript.cues.json", "transcribe-outcome.json"]) { + assert.equal(existsSync(path.join(f.videoDir, name)), false, `${name} retired`); + } + assert.match(log.join(""), /Retired the salvage transcript/); + const disk = await readOutcome(f.videoDir); + assert.deepEqual(disk.corruptRefetches?.[0].retiredSalvage, { + ...salvaged, + transcribedAt: "2026-10-15T00:00:00.000Z", + }); + const after = await generateChannelSnapshot(paths, "c"); + assert.deepEqual(after.buckets.downloadedNoTranscript, [ID]); + assert.deepEqual(after.buckets.salvagedTranscript, []); + assert.deepEqual(after.buckets.corruptFullSource, []); + await rm(f.root, { recursive: true, force: true }); +}); + +test("a clean refetch leaves a transcript that is not a salvage alone", async () => { + const f = await fixture(); + await writeFile(path.join(f.videoDir, "transcript.json"), "{}"); + await writeFile( + path.join(f.videoDir, "transcribe-outcome.json"), + JSON.stringify({ videoId: ID, transcribedAt: "2026-10-15T00:00:00.000Z" }), + ); + const { ctx: c } = ctx(); + const plan = await prepareCorruptRefetch(f.videoDir, c); + assert.ok(plan); + await writeFile(path.join(f.videoDir, "audio.mp4"), "NEW-CLEAN"); + await settleCorruptRefetch(plan, outcome({ status: "ok-audio-checked" }), c); + assert.ok(existsSync(path.join(f.videoDir, "transcript.json"))); + assert.equal((await readOutcome(f.videoDir)).corruptRefetches?.[0].retiredSalvage, undefined); + await rm(f.root, { recursive: true, force: true }); +}); diff --git a/common/ytdlp/corruptRefetch.ts b/common/ytdlp/corruptRefetch.ts @@ -0,0 +1,336 @@ +// 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"; +import { loadTranscribeOutcome } from "../lib/transcribeOutcome-server"; +import { + TRANSCRIBE_OUTCOME_FILENAME, + type TranscriptSalvage, +} from "../lib/transcribeOutcome"; +import { CUES_JSON_FILENAME, WHISPER_FILENAME } from "../lib/videoStatus"; + +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" }); + } +} + +// 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<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 — 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( + `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/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,8 @@ # Changelog ## [Unreleased] +- **Retrying a corrupt full source downloads it again.** A video whose download completed with malformed audio (Odysee's intermittent AAC, on a channel with the audio check) kept its file, and that file made every retry say "Nothing to fetch". A retry of the **corrupt full sources** bucket — the new card on the channel's Download stage, or `pnpm ops retry-bucket --json '{"slug": "<channel>", "bucket": "corruptFullSource"}'` — now sets the kept file aside and downloads again: a clean result replaces it; a malformed one keeps whichever copy decodes longer; a download that fails (a 429, the network) puts the kept file back and the video stays in the bucket, with the attempt recorded. Each retry is recorded in the video's `download-outcome.json`. Needs a restart of the editor. +- **A damaged recording is transcribed for what decodes, instead of not at all.** Transcribing a corrupt full source used to fail at the first bad stretch. It is now decoded with error tolerance, with the stretches that will not decode kept as silence of their own length, so every line of the transcript is at its true time in the recording; with parakeet, a window that still fails is skipped and noted. The transcript is marked **salvaged**: the video page says how much decoded and which stretches have no transcript, and the channel's report lists it under **salvaged transcript**. It happens on its own for a corrupt full source; `pnpm ops transcribe-one --json '{"slug": "<channel>", "id": "<video>", "salvage": true}'` asks for it on any video (`false` turns it off). When a later retry downloads the recording clean, the salvaged transcript is removed so the recording is transcribed again in full. On the sites, a salvaged transcript's video page says "Partial transcript: N of M min decoded", and the MCP's `get_transcript` and `get_video_metadata` say it is partial. Needs a restart of the editor; the sites show it after their next build. - **find-copy can fetch from an archive.org copy that is a single video file.** Such a file's fetch failed with "Requested format is not available" and the copy was then marked as failed. A copy's window is now cut from whatever single file it is, and a copy is marked failed only when the copy itself is gone or refused. `pnpm ops find-copy --json '{"article": "<id>", "retryFailed": true}'` tries copies marked failed again. Needs a restart of the editor. - **A model can propose verdicts for a fact-check's unruled claims, for you to approve or reject.** `pnpm ops report-draft --json '{"task":"verdicts","article":"<id>"}'` asks each claim with no verdict, with the verdict bench's own prompt, and keeps each proposed verdict, its reason, the model and the prompt version in `verdicts.proposed.json` beside the article, never in `report.json`. It runs only on a model you ticked on the verdict bench (`settings.generation.verdicts.models`, empty until you do), and never sets a verdict itself. umtool's Inbox shows "N verdicts proposed" under Review; **Review verdicts** opens the article, where each proposal has **Approve** (the claim gets that verdict) and **Reject** (the claim stays unruled), with an optional note. A claim you have ruled, or whose proposal you have reviewed, is not asked again. `pnpm ops verdict-review` does the same from the command line. Needs a restart of the editor and umtool. - **Draft everything can add the on-screen deck first.** Tick **with the deck** beside **Draft everything** on a cut's Media tab (or `umtool chain <article> <n> --draft-all --deck`): before the flips, a step adds the on-screen deck with every setting at its default to a cut that has none, so the flips and threads are drafted on a cut the converter made. A copy of the cut as it was is kept in its revisions first. A cut that already has a deck is left as it is, and the step says "deck added" or "deck already there". Off by default: without the tick, Draft everything is as it was. Needs a restart of umtool. diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts @@ -115,6 +115,10 @@ test("transcribe-one, delete-file and do-not-clean refuse before anything is tou const noChannel = await callPost(one, { slug: "no-such", id: VIDEO }); assert.equal(noChannel.status, 400); assert.match(String(noChannel.body.error), /no-such/); + // Release 30 lane Q: "salvage" is a boolean, checked at the door. + const badSalvage = await callPost(one, { slug: SLUG, id: VIDEO, salvage: "yes" }); + assert.equal(badSalvage.status, 400); + assert.match(String(badSalvage.body.error), /"salvage" must be a boolean/); const del = await route("delete-file"); const suspicious = await callPost(del, { slug: SLUG, id: VIDEO, file: "../config.json" }); diff --git a/editor/app/api/ops/transcribe-one/route.ts b/editor/app/api/ops/transcribe-one/route.ts @@ -2,11 +2,11 @@ import { transcribeOneAction, whisperVideoAction, } from "../../../channels/[slug]/videos/[id]/videoActions"; -import { jobResponse, ops, opsFail, optString, reqSlug, reqVideoId } from "../_lib"; +import { jobResponse, ops, opsFail, optBool, optString, reqSlug, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, file? } +// POST { slug, id, file?, salvage? } // // One video, transcribed — the video page's two buttons: // - with "file" (an audio file in the video's dir, e.g. "audio.mp3"): that @@ -17,11 +17,16 @@ export const dynamic = "force-dynamic"; // there is none (the disk floor applies to that download only). // A job on the video's platform queue: { ok, jobId }, so --wait follows it. // The file name is one path segment; a refused one is the action's sentence. +// "salvage" (release 30, lane Q): true decodes the audio with error tolerance +// and transcribes what decodes, its gaps recorded (transcribeOne's salvage); +// false forbids it; absent, a corrupt-full-source video is salvaged and any +// other is not. export async function POST(request: Request) { - return ops(request, ["slug", "id", "file"], async (body) => { + return ops(request, ["slug", "id", "file", "salvage"], async (body) => { const slug = reqSlug(body, "slug"); const id = reqVideoId(body, "id"); const file = optString(body, "file"); + const salvage = optBool(body, "salvage"); // One path segment, checked at the door as reqVideoId checks an id: the // name is joined under the video's directory. if (file !== undefined && (file === "" || /[/\\\0]/.test(file) || file.startsWith("."))) { @@ -29,8 +34,8 @@ export async function POST(request: Request) { } return jobResponse( file !== undefined - ? await transcribeOneAction(slug, id, file) - : await whisperVideoAction(slug, id), + ? await transcribeOneAction(slug, id, file, undefined, salvage) + : await whisperVideoAction(slug, id, undefined, salvage), ); }); } 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/SalvagedTranscriptNotice.tsx b/editor/app/channels/[slug]/videos/[id]/components/SalvagedTranscriptNotice.tsx @@ -0,0 +1,31 @@ +import type { TranscriptSalvage } from "yt-dlp-transcript-common/lib/transcribeOutcome"; +import { formatDuration } from "yt-dlp-transcript-common/lib/format"; + +// A SALVAGE TRANSCRIPT SAYS WHAT IT IS MISSING (release 30, lane Q): made +// from a damaged file decoded with error tolerance, so where nothing decoded +// there is no transcript. The times are the recording's own. +const clock = (s: number) => formatDuration(s) || "0:00"; +const MAX_LISTED = 8; + +export function SalvagedTranscriptNotice({ salvaged }: { salvaged: TranscriptSalvage }) { + const listed = salvaged.gaps.slice(0, MAX_LISTED); + const more = salvaged.gaps.length - listed.length; + return ( + <div + role="status" + aria-label="salvaged transcript" + className="rounded border px-3 py-2 text-sm border-warning/30 bg-warning-soft text-warning" + > + Salvaged transcript — {clock(salvaged.decodedSeconds)} of{" "} + {clock(salvaged.totalSeconds)} of {salvaged.source} decoded. + {salvaged.gaps.length > 0 && ( + <> + {" "} + No transcript for{" "} + {listed.map(([a, b]) => `${clock(a)}–${clock(b)}`).join(", ")} + {more > 0 ? ` and ${more} more` : ""}. + </> + )} + </div> + ); +} diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx @@ -13,6 +13,8 @@ import type { ChannelHandling, } from "yt-dlp-transcript-common/lib/channelConfig"; import type { DownloadOutcomeRecord } from "yt-dlp-transcript-common/lib/downloadOutcome"; +import type { TranscriptSalvage } from "yt-dlp-transcript-common/lib/transcribeOutcome"; +import { SalvagedTranscriptNotice } from "./SalvagedTranscriptNotice"; import type { SavedVideoPointer } from "yt-dlp-transcript-common/lib/savedVideo"; import type { SourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFormat"; import type { AvailabilityHistoryEntry } from "yt-dlp-transcript-common/lib/availability"; @@ -65,6 +67,8 @@ type Props = { defaultQueueKey: string; existingQueues: string[]; downloadOutcome: DownloadOutcomeRecord | null; + // The transcript is a salvage (release 30, lane Q): what it is missing. + salvaged?: TranscriptSalvage | null; availabilityHistory: AvailabilityHistoryEntry[]; channelAudioFormat?: AudioFormat; doNotClean?: boolean; @@ -108,6 +112,7 @@ export function VideoPanel({ defaultQueueKey, existingQueues, downloadOutcome, + salvaged = null, availabilityHistory, channelAudioFormat, doNotClean = false, @@ -149,9 +154,12 @@ export function VideoPanel({ ? "No audio on disk — run the pipeline (VTT first, whisper if needed)." : "Audio not yet downloaded." : `${audioFiles.length} audio file${audioFiles.length === 1 ? "" : "s"} on disk.`; + const salvageShown = hasTranscriptJson && salvaged !== null; const transcribeSummary = autoSubsOnly ? "YouTube auto-captions only — can be replaced with an AI transcript." - : hasTranscript + : salvageShown + ? "Salvaged transcript — gaps where the file would not decode." + : hasTranscript ? "Transcript present." : noAudio ? "No audio yet — run the download pipeline (or use Audio + Whisper) to produce a transcript." @@ -191,6 +199,7 @@ export function VideoPanel({ downloadFailed={downloadFailed} /> {downloadOutcome && <DownloadOutcomeBadge outcome={downloadOutcome} />} + {salvageShown && salvaged && <SalvagedTranscriptNotice salvaged={salvaged} />} {/* BOTH BANNERS ARE RENDERED UNCONDITIONALLY, and each decides for itself whether to draw anything. THE RULE (plans/FACTS.md, fae99f1): a component carrying a StreamActionLog must not be UNMOUNTED when the @@ -297,7 +306,7 @@ export function VideoPanel({ summary={transcribeSummary} defaultOpen={true} tone={ - incompleteTranscript + incompleteTranscript || salvageShown ? "attention" : hasTranscript ? "ok" 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/editor/app/channels/[slug]/videos/[id]/lib/videoChoreCards.ts b/editor/app/channels/[slug]/videos/[id]/lib/videoChoreCards.ts @@ -20,8 +20,9 @@ // videoChoreCards.test.ts pins that its render order is exactly this list, so // a card added there without a row here fails a test rather than going unlisted. // Not a card, so not listed: VideoNavStrip, PipelineStatusStrip, the umtool -// link and the one-line "media archived" status, which is the archive-media -// card's marker restated at the top. +// link, the one-line "media archived" status, which is the archive-media +// card's marker restated at the top, and the one-line salvaged-transcript +// status (release 30, lane Q), which runs nothing. // // No directive: a plain data module. Nothing server-side imports it; a server // component that did would get client references for `component`, not values. diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx @@ -4,6 +4,7 @@ import { notFound } from "next/navigation"; import path from "node:path"; import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { loadDownloadOutcome } from "yt-dlp-transcript-common/lib/downloadOutcome-server"; +import { loadTranscribeOutcome } from "yt-dlp-transcript-common/lib/transcribeOutcome-server"; import { loadAvailability } from "yt-dlp-transcript-common/lib/availability-server"; import { loadMetadataHistory } from "yt-dlp-transcript-common/lib/metadataHistory-server"; import { metadataHistoryView } from "yt-dlp-transcript-common/views/metadataHistoryView"; @@ -127,6 +128,8 @@ export default async function VideoDetailPage({ const meta = await loadMeta(slug, id); const videoDir = path.join(getPaths().channelsDir, slug, "data", id); const downloadOutcome = await loadDownloadOutcome(videoDir); + // A salvage transcript's gaps (release 30, lane Q); null for any other. + const salvaged = (await loadTranscribeOutcome(videoDir))?.salvaged ?? null; const availabilityRecord = await loadAvailability(videoDir); const availabilityHistory = availabilityRecord?.history ?? []; // Every rewrite of metadata.info.json that changed its bytes (release 10 @@ -190,6 +193,7 @@ export default async function VideoDetailPage({ meta, videoDir, downloadOutcome, + salvaged, availabilityHistory, metadataHistory, doNotClean, @@ -219,6 +223,7 @@ export default async function VideoDetailPage({ meta, videoDir, downloadOutcome, + salvaged, availabilityHistory, metadataHistory, doNotClean, @@ -335,6 +340,7 @@ export default async function VideoDetailPage({ defaultQueueKey={defaultQueueKey} existingQueues={existingQueues} downloadOutcome={downloadOutcome} + salvaged={salvaged} availabilityHistory={availabilityHistory} channelAudioFormat={config.audioFormat} doNotClean={doNotClean} diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -185,6 +185,10 @@ export async function transcribeOneAction( videoId: string, audioFilename: string, queueKey?: string, + // A salvage transcription (release 30, lane Q — transcribeOne's `salvage`): + // true forces it, false forbids it, undefined leaves it automatic (a + // corrupt-full-source video is salvaged). + salvage?: boolean, ): Promise<StreamActionResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; @@ -205,6 +209,7 @@ export async function transcribeOneAction( tracker: makeTaskTracker(ctx, onLog), onLog, signal, + ...(salvage !== undefined ? { salvage } : {}), }); safeRevalidate([`/channels/${slug}/videos/${videoId}`]); }, @@ -447,6 +452,8 @@ export async function whisperVideoAction( slug: string, videoId: string, queueKey?: string, + // See transcribeOneAction's `salvage`. + salvage?: boolean, ): Promise<StreamActionResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; @@ -524,6 +531,7 @@ export async function whisperVideoAction( tracker: makeTaskTracker(ctx, onLog), onLog, signal, + ...(salvage !== undefined ? { salvage } : {}), }); safeRevalidate([ `/channels/${slug}/videos/${videoId}`, diff --git a/editor/e2e/audio-check-scenarios.spec.ts b/editor/e2e/audio-check-scenarios.spec.ts @@ -323,6 +323,68 @@ test.describe("audio-checked download scenarios", () => { ).toBe(false); }); + test("a retry of a corrupt full source downloads again; a clean result replaces the kept file", async ({ + page, + }) => { + // Release 30 lane Q1. The kept container used to make the bucket's retry + // a no-op ("Nothing to fetch"); an intermittent source can come back + // clean, so the retry sets the kept file aside and downloads again. + await resetData("audio-check-channel"); + // A real-shaped Odysee claim URL: the retry finds a video by the id the + // app reads off its URL (the fixture's bare `/abc123` reads as none), and + // the claim is the same `abc123`, so the dir is the one the others use. + await writeFile( + resolvePath(`${CHANNEL_ROOT}/playlist`), + `https://odysee.com/@example/clip:${VIDEO_ID}\n`, + ); + await writeFakeConfig({ + mode: "corrupt-final", + deterministicCorrupt: true, + totalChunks: 4, + chunkDelayMs: 100, + }); + await triggerDownload(page); + await waitForOutcome( + (o) => o.status === "corrupt-full-source", + "corrupt-full-source outcome", + ); + await expect + .poll( + async () => + ( + await readJson<{ buckets?: { corruptFullSource?: string[] } }>( + `${CHANNEL_ROOT}/snapshot.json`, + ).catch(() => null) + )?.buckets?.corruptFullSource?.length ?? -1, + { timeout: 15_000, message: "the video in the corruptFullSource bucket" }, + ) + .toBe(1); + + // The source serves clean audio now. + await writeFakeConfig({ mode: "happy", totalChunks: 4, chunkDelayMs: 100 }); + await page.goto(channelStage(CHANNEL, "download")); + const bucket = page.getByLabel("retry corrupt full sources bucket"); + await bucket.getByRole("button", { name: /^Retry \(1\)$/ }).click(); + const retryLog = page.getByLabel("Retry corrupt full sources output"); + await expect(retryLog).toContainText("Corrupt full source: refetching", { + timeout: 30_000, + }); + await expect(retryLog).toContainText("the refetch is clean", { + timeout: 60_000, + }); + const outcome = await waitForOutcome( + (o) => o.status === "ok-audio-checked", + "clean refetch outcome", + ); + expect(outcome.corruptRefetches?.[0]?.result).toBe("clean"); + expect( + await pathExists(`${CHANNEL_ROOT}/data/${VIDEO_ID}/audio.mp3`), + ).toBe(true); + expect( + await pathExists(`${CHANNEL_ROOT}/data/${VIDEO_ID}/audio.mp4.corrupt-kept`), + ).toBe(false); + }); + test("deterministic corruption exhausts retry cap and surfaces failed-corrupt-source", async ({ page, }) => { diff --git a/editor/e2e/fixtures/bin/fake-ytdlp.mjs b/editor/e2e/fixtures/bin/fake-ytdlp.mjs @@ -76,6 +76,15 @@ function urlIdYouTube(u) { const parsed = new URL(u); const v = parsed.searchParams.get("v"); if (v) return v; + // An Odysee claim URL (`/@channel/name:<claim>`) is the claim, as the app's + // extractVideoId reads it (lib/videoId.ts) — so a playlist of real-shaped + // Odysee URLs keeps the fake's data/<id>/ and the app's in step. A bare + // `/abc123` (the audio-check fixture) has no colon and is unchanged. + if (parsed.hostname.endsWith("odysee.com")) { + const decoded = decodeURIComponent(parsed.pathname); + const colon = decoded.lastIndexOf(":"); + if (colon > 0) return decoded.slice(colon + 1); + } return parsed.pathname.split("/").filter(Boolean).pop(); } catch { return u; diff --git a/mcp/src/search.test.ts b/mcp/src/search.test.ts @@ -1762,3 +1762,33 @@ test("server: get_transcript reads the primary by default and another track by ` assert.match(batch, /a zeppelin flew over/); await client.close(); }); + +// Release 30 lane Q: a salvage transcript's record carries `salvaged`; both +// readers say it is partial, and a record without it says nothing. +class SalvagedSource extends StubSource { + protected pages(ch: ChannelRef): TranscriptDetail[][] { + return super.pages(ch).map((p) => + p.map((r) => (r.id === "a1" ? { ...r, salvaged: { decodedSeconds: 2335, totalSeconds: 6000 } } : r)), + ); + } +} + +test("server: a salvage transcript is marked partial by get_transcript and get_video_metadata", async () => { + const client = await connectClient(new SalvagedSource()); + const transcript = firstText( + await client.callTool({ name: "get_transcript", arguments: { video_id: "a1" } }), + ); + assert.match(transcript, /PARTIAL TRANSCRIPT — made from a damaged recording: 39 of 100 min decoded/); + assert.match(transcript, /i love coffee/); + const meta = firstText( + await client.callTool({ name: "get_video_metadata", arguments: { video_id: "a1" } }), + ); + const parsed = JSON.parse(meta.slice(0, meta.indexOf("\n}") + 2)); + assert.deepEqual(parsed.salvaged, { decodedSeconds: 2335, totalSeconds: 6000 }); + assert.match(meta, /PARTIAL TRANSCRIPT/); + const other = firstText( + await client.callTool({ name: "get_transcript", arguments: { video_id: "b2" } }), + ); + assert.doesNotMatch(other, /PARTIAL TRANSCRIPT/); + await client.close(); +}); diff --git a/mcp/src/server.ts b/mcp/src/server.ts @@ -4,6 +4,7 @@ import { type ServerOptions, type Tool, } from "@modelcontextprotocol/server"; +import { salvageCaveat } from "yt-dlp-transcript-common/lib/salvageMark"; import { transcriptToMarkdown } from "yt-dlp-transcript-common/lib/transcriptToMarkdown"; import { formatDate, formatDuration } from "yt-dlp-transcript-common/lib/format"; import { manifestHasDigest } from "yt-dlp-transcript-common/lib/digests"; @@ -2312,7 +2313,7 @@ async function handleGetTranscript( ); } const shown = asked || record.track; - const extraMeta = + const trackMeta = tracks.length > 1 && shown ? [ `track: ${shown} (${trackLabel(shown)})${shown === record.track ? " — the primary" : ""}`, @@ -2321,14 +2322,17 @@ async function handleGetTranscript( .map((t) => `${t} (${trackLabel(t)}${t === record.track ? ", the primary" : ""})`) .join(", ")} — pass track to read one`, ] - : undefined; + : []; + // A salvage transcript (release 30, lane Q) says so where a quote is read. + const salvageMeta = record.salvaged && (!asked || asked === record.track) ? [salvageCaveat(record.salvaged)] : []; + const extraMeta = [...trackMeta, ...salvageMeta]; const md = transcriptToMarkdown( { ...record, cues }, { timestamps: args.timestamps !== false, includeTags: true, linkForCue: (seconds) => momentLinkFor(source, link, seconds), - ...(extraMeta ? { extraMeta } : {}), + ...(extraMeta.length > 0 ? { extraMeta } : {}), }, ); return text(md); @@ -2400,6 +2404,9 @@ async function handleGetMetadata( ].filter(Boolean); lines.push(statLines.join("\n")); } + // A salvage transcript (release 30, lane Q): the record's own mark, stated + // as the caveat it is whatever the stats layer says. + if (found.record.salvaged) lines.push(`- ${salvageCaveat(found.record.salvaged)}`); // ── duplicates.json ── lines.push(await describeOtherCopies(source, slug)); diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -9604,3 +9604,62 @@ parsed to 0 cues, indexing the video textless) is CLOSED by `200a3105` (transcri `planArticleDelete` refuses while it is live. `settings.generation.verdicts.window {mode, seconds}` (default seconds, 60) is the window proposals read; umtool's bar form writes the run's. `benchItemsHash` covers the claim's text and its quotes' spans. + +## Release 30 lane Q: corrupt-source recovery (verified 2026-10-15, branch `r30/corrupt-recovery`) + +- **A managed download of a corrupt-full-source video is a refetch** (`common/ytdlp/corruptRefetch.ts`, called by + `downloadOneManaged` around `runManagedDownload` for every URL with a canonical id). `prepareCorruptRefetch` moves + every real audio file aside as `<name>.corrupt-kept` (`CORRUPT_KEPT_SUFFIX`) with `renameMediaFile` + (`lib/mediaTier-server.ts`: a tier link's bytes are renamed beside themselves in `media/<id>/` and the link + re-pointed; a real file renamed in place); `settleCorruptRefetch` decides by the download's own status: `ok*` with + a fresh audio file → the aside is removed; `corrupt-full-source` → whichever copy decodes longer stays + (`scanDecodable`; a tie keeps the new copy, both unmeasurable keeps the old); anything else → a fresh file is + removed, the aside renamed back, and the sidecar rewritten as the PREVIOUS record (status corrupt-full-source) with + the new attempts appended. The record RETURNED to the caller is the download's own (status `failed`, its + `failureClass`), so a batch backs the platform off on a 429; only the sidecar keeps the bucket's status. + `prepare` first settles any `.corrupt-kept` an interrupted run left (restore, or keep the longer of two copies, or + remove after a clean record; a non-ok record it finds is rewritten corrupt-full-source). +- **`download-outcome.json` `corruptRefetches[]`**: one `CorruptRefetch` per retry, oldest first — + `{startedAt, finishedAt, result: "clean" | "still-malformed" | "failed", status, failureClass?, error?, kept?: + "new" | "previous", decodedSeconds?: {previous, new}}`; carried from record to record by the refetch. +- **The retry prefilter**: `retry-bucket` passes `refetchCorruptFullSource` to `destinationExists`, which then answers + false for a video whose outcome is corrupt-full-source whatever is on disk (the kept file, a salvage transcript). + Only the retry: download-missing and sync still count the kept file as there. `corruptFullSource` is a + `ReplayBucket`; the channel's download stage has a Retry card for it (`retry corrupt full sources bucket`). +- **Media-tier scratch**: `*.corrupt-kept` and `audio.salvage.wav` (`lib/mediaTier.ts` SCRATCH_PATTERNS) — never + tiered, never counted as text; neither is a real audio file. +- **Salvage decode** (`common/lib/salvageAudio-server.ts`): `ffmpeg -err_detect ignore_err -fflags +discardcorrupt`, + 16 kHz mono. `scanDecodable` = the framecrc of the unpadded decode (decoded seconds = summed frame durations; a pts + jump is a hole; the tail to ffprobe's container duration is one); `salvageDecode` adds a second output, + `aresample=16000:async=1:first_pts=0,apad=whole_dur=<container>` into a WAV — silence of each hole's length, so + the WAV is on the source's clock (a plain decode closes the holes up and every later cue lands early by the gap; + both pinned by `salvageAudio-server.test.ts` over `common/testing/audio/corruptAudio.mjs`). Listed gaps: holes merged + when less than 1 s of audio lies between them, then those under 0.5 s dropped (still counted in decoded seconds). +- **Salvage transcription** (`controller/transcribeOne.ts`): `salvage` on `transcribeOneVideo`/`transcribeWithWorker` + (true forces, false forbids, undefined = automatic when `download-outcome.json` says corrupt-full-source). The engine + reads `audio.salvage.wav` in the video dir (removed in a `finally`; parakeet's `.audio.salvage.wav.parakeet` cache + survives a pause — the decode is deterministic). Parakeet gets `--salvage` (`TranscribeBuildInput.salvage`): a window + whose slice or parakeet-cli run fails is a gap; its neighbours own their whole reach on that side; the output gains + `salvage.failedWindows` (what no transcribed window reached); every window failing is exit 1. Whisper.cpp and + chough ignore the flag. +- **`transcribe-outcome.json` `salvaged`** = `{source, decodedSeconds, totalSeconds, gaps: [[from, to], …]}` (decode + holes ∪ failed windows, merged), written only when something is missing — a salvage of a file that decodes whole + is a clean transcript with no `salvaged`. +- **Snapshot bucket `salvagedTranscript`**: whisper transcripts whose transcribe-outcome has `salvaged` (one small read + per whisper transcript carrying the sidecar). Classified BEFORE the corrupt-full-source short-circuit, so a + salvaged corrupt full source is in both buckets. Still counted in `totals.transcribed`. Channel flow: a transcribe + siding; the video page: `SalvagedTranscriptNotice` (`salvaged transcript` status). +- **Ops**: `transcribe-one {…, "salvage": bool}`; `retry-bucket {"bucket": "corruptFullSource"}` refetches. +- **A clean refetch retires a salvage transcript** (operator ruling 2026-10-15): when `settleCorruptRefetch` sees a + clean result and `transcribe-outcome.json` has `salvaged`, `transcript.json`, `transcript.cues.json` and + `transcribe-outcome.json` go through `removeMediaFile`; the clean `CorruptRefetch` keeps + `retiredSalvage: {source, decodedSeconds, totalSeconds, gaps, transcribedAt}`; the snapshot then has the video in + `downloadedNoTranscript` for the transcription lane. Any other transcript is left alone. +- **Downstream, the record's `salvaged`** (`TranscriptSummary.salvaged: {decodedSeconds, totalSeconds}` — a + `SalvageMark`, `lib/salvageMark.ts`; NOT the sidecar's `salvaged`, which also has `source` and `gaps`): set by + buildIndex on a whisper record whose transcribe-outcome has a salvage (read only for whisper records; deleted and + re-derived on every derivation; omitted otherwise, so other pages are byte-identical). The index re-derives a record + when its transcript changes — a salvage writes `transcript.json`, a retirement removes it — so the sidecar's mtime + needs no key of its own. Shown by the export's TranscriptModal ("Partial transcript: N of M min decoded", + `partialTranscriptLine`) and by MCP `get_transcript` / `get_video_metadata` (`salvageCaveat`; the metadata JSON + carries the field). Not on `DisplaySummary` (the summaries pages). diff --git a/plans/release-30/q.md b/plans/release-30/q.md @@ -0,0 +1,125 @@ +# Release 30, lane Q — corrupt-source recovery (as shipped) + +Branch `r30/corrupt-recovery` from `main` `59fdc486`. Brief: `r30q-brief.md` (the plan of record for this lane). +FACTS: "Release 30 lane Q: corrupt-source recovery". + +## Q1, as shipped (2026-10-15): a retry of a corrupt full source refetches it + +The kept container made the corruptFullSource bucket's only control a no-op (the retry-bucket prefilter read it as +"already complete"). Built: +- **The retry asks again.** `retry-bucket` passes `refetchCorruptFullSource` to `destinationExists` + (`common/ytdlp/runYtdlp.ts`): a video whose `download-outcome.json` is corrupt-full-source is never "complete" to + the retry, whatever is on disk (the kept file, a salvage transcript). Only the retry: download-missing and sync still + count the kept file, so no sweep re-fetches these. +- **Every managed download of a corrupt-full-source video is a refetch** (`common/ytdlp/corruptRefetch.ts`, around + `runManagedDownload` in `downloadOneManaged` — so retry-bucket, the video page's re-download and any batch that + reaches the video all take it). `prepareCorruptRefetch` moves each real audio file aside as + `<name>.corrupt-kept`, tier-aware (`renameMediaFile`, new in `lib/mediaTier-server.ts`: a tier link's bytes are + renamed beside themselves in `media/<id>/` and the link re-pointed). `settleCorruptRefetch` decides by what the + download ended as: + - `ok*` with a fresh audio file: the aside file is removed (`removeMediaFile`); + - `corrupt-full-source` again: whichever copy decodes longer stays (`scanDecodable`, one tolerant ffmpeg decode), + the other removed; a tie keeps the new copy, both unmeasurable keeps the old; + - anything else (a 429 at the prefetch — the live case — the network, a filter, a cancel, a short file): a fresh + file is removed, the aside file renamed back, and the sidecar rewritten as the previous record (status + corrupt-full-source) with the new attempts appended. **The caller still gets the download's own record** (status + `failed`, its `failureClass`), so a batch backs the platform off as for any 429. + - Each retry is a `CorruptRefetch` in the sidecar's new `corruptRefetches[]` (result, status, failureClass, error, + kept, decoded seconds of each copy). + - A run cut short leaves `.corrupt-kept`; the next `prepare` settles it first (restore; or the longer of two copies; + or remove after a clean record; a non-ok record it finds is rewritten corrupt-full-source). + - A kept file that cannot be moved aside fails that video's download (it is never downloaded over). +- `*.corrupt-kept` and `audio.salvage.wav` are media-tier scratch (`lib/mediaTier.ts`): never tiered, never text. +- **Surfaces.** `corruptFullSource` is a `ReplayBucket`; the channel's Download stage has a **Corrupt full sources** + card with the bucket's Retry (`retry corrupt full sources bucket`); the channel flow's siding, the video list's dot + title, the video page's outcome badge and the snapshot's comments say a retry downloads again (the "futile" sentence + is gone). Ops help for `retry-bucket`; COMMANDS.md. +- Test kit: `common/testing/audio/corruptAudio.mjs` — a synthetic AAC tone-burst recording, the same with a seeded run + of bytes overwritten, a WAV reader and a burst-onset finder (README not touched — a later kit pass can list it). + +## Q2, as shipped (2026-10-15): salvage transcription + +A plain transcription of a corrupt file failed at the first bad window. Built: +- **The decode** (`common/lib/salvageAudio-server.ts`): `-err_detect ignore_err -fflags +discardcorrupt`, 16 kHz mono; + one ffmpeg run with two outputs — the framecrc of the unpadded decode (decoded seconds; a pts jump is a hole; the + tail to the container's duration is one) and a WAV through `aresample=async=1:first_pts=0,apad=whole_dur=<duration>` + (each hole silence of its own length). **The timestamp claim is verified**: over the synthetic damaged recording the + bursts after the damage are at their source times in the salvage WAV (±50 ms) and absent inside the gap, while a + plain decode (the control) puts every later burst early by the gap's length. +- **The transcription** (`controller/transcribeOne.ts`): `salvage` on `transcribeOneVideo` / `transcribeWithWorker` — + true forces, false forbids, absent = **automatic when the download outcome is corrupt-full-source** (my call: the + file is known to be malformed and a plain run fails at the first bad window; nothing else transcribes such a video + automatically, so this only changes an explicit Transcribe). The engine reads `audio.salvage.wav` in the video dir + (removed in a `finally`; parakeet's window cache survives a pause). Recorded in `transcribe-outcome.json` as + `salvaged: {source, decodedSeconds, totalSeconds, gaps}` — only when something is missing; a salvage of a file that + decodes whole is a clean transcript. +- **parakeet-stitch `--salvage`** (passed by the parakeet app on a salvage run; whisper.cpp and chough ignore it): a + window whose slice or parakeet-cli run fails is a gap, not the end of the file; its neighbours own their whole reach + on that side; the output gains `salvage.failedWindows`, which transcribeOne merges into the gaps; every window failing + is still exit 1. +- **Not a clean full transcript**: the snapshot's new `salvagedTranscript` bucket (still counted as transcribed; a + corrupt full source stays in its own bucket — a retry can still bring a clean copy), a transcribe siding in the + channel flow, and on the video page a status line ("Salvaged transcript — 38:55 of 1:40:00 of audio.mp4 decoded. No + transcript for …") with the transcribe card's tone at attention. Not the `incompleteTranscript` bucket: its action + is delete-and-re-download, which is the corrupt-full-source retry's job here. +- **Ops**: `transcribe-one {…, "salvage": bool}` (checked a boolean at the door); help and COMMANDS.md. + +## Q3: the bucket stays honest + +A failed refetch keeps the corrupt-full-source status and its history (Q1's "anything else" path, pinned by the +whole-path test: a fake yt-dlp answering the prefetch with a 429 leaves the sidecar corrupt-full-source with +`["metadata-prefetch", "audio-checked-primary", "metadata-prefetch"]` and the kept file in place). The snapshot stays +the single classifier: it reads the sidecar's status as before; the only addition is `salvagedTranscript`. + +## Follow-ups (2026-10-15, orchestrator's ruling and brief) + +- **A clean refetch retires a salvage transcript** (ruling: yes). In `settleCorruptRefetch`'s clean branch: when + `transcribe-outcome.json` has `salvaged`, `transcript.json`, `transcript.cues.json` and `transcribe-outcome.json` go + through `removeMediaFile` (the one remover of a video-dir entry — the editor's `clearIncompleteTranscriptOne` uses + it too, but also takes the audio, which is the point here to keep); the clean `CorruptRefetch` records + `retiredSalvage` (the salvage and its `transcribedAt`); the snapshot then has the video in `downloadedNoTranscript` + (pinned through the real `generateChannelSnapshot`). A transcript that is not a salvage is left alone. +- **Salvaged transcripts are marked downstream.** The index record gains `salvaged: {decodedSeconds, totalSeconds}` + (`TranscriptSummary.salvaged`, a `SalvageMark`; omitted otherwise so every other page is byte-identical) from the + sidecar, for whisper records only; the published transcript pages carry it (pinned through the real `buildIndex`). + The export's video page (TranscriptModal) shows "Partial transcript: N of M min decoded" under its date line; MCP + `get_transcript` adds a "⚠ PARTIAL TRANSCRIPT … do NOT conclude that something was never said" meta line (primary + track only) and `get_video_metadata` carries the field and the same line. Not on `DisplaySummary`; no e2e (unit + tests; the export suite at merge). + +| Commit | What | +| --- | --- | +| `fc0942e7` | Q1: corruptRefetch.ts, renameMediaFile, the retry prefilter, scanDecodable + the test kit, the replay bucket, the Retry card, the sentences; ops help, COMMANDS.md | +| `72ef936b` | Q2: salvageDecode, transcribeOne salvage, parakeet-stitch --salvage, transcribe-outcome `salvaged`, the `salvagedTranscript` bucket, the video page's status; ops help, COMMANDS.md | +| `1d327f32` | Q2: a salvage that finds nothing missing is a clean transcript | +| `88e03d2f` | editor: the status is not a chore card (videoChoreCards); the e2e retry scenario; CHANGELOG | +| `ebd2d95f` | this record, FACTS | +| `74310acc` | the test kit README lists `testing/audio` | +| `ff9c2c51` | a clean refetch retires a salvage transcript | +| `b606cebe` | the record's `salvaged` mark: buildIndex, the export's status line, the MCP caveat | +| `4c6468ae` | the follow-ups' record, FACTS, CHANGELOG | +| `c932e29f` | e2e: the retry scenario on a real-shaped Odysee claim URL (fake yt-dlp reads its id as the app does) | +| (this commit) | the e2e result | + +Gates (from the worktree root; every tsc and suite behind the shared heavy lock after 16:29): +- tsc: common, editor, mcp package-scoped clean at each commit; `pnpm -r exec tsc --noEmit` clean at the branch tip. +- common: 4253 at the branch's start (1 failing that run — the run overlapped my first edits; not reproduced) → + 4279, all pass. New: `ytdlp/corruptRefetch.test.ts` 9 (one through `downloadOneManaged` with a fake yt-dlp), + `lib/salvageAudio-server.test.ts` 7 (real ffmpeg), `controller/transcribeSalvage.test.ts` 2 (the real stitch + wrapper over a fake parakeet-cli that "transcribes" tone bursts: cues at the source's burst times ±60 ms, none in the + gap), `mediaTier-server` +3, `mediaTier` +3 rows, `channelSnapshot` +1, `transcriptionApps` +1, `jobSpec` +1 bucket. +- test:scripts: 1024 (1021 + 3 skipped) → 1027 (1024 + 3 skipped), none failing (`parakeet-stitch.test.mjs` +3). +- editor unit: 310 → 310, all pass (the transcribe-one door check is inside an existing test). +- mcp: 372/372. +- `docs cli --check`, `docs files --check`, `docs env --check`: clean. +- After the follow-ups (`b606cebe`): `pnpm -r exec tsc --noEmit` clean; common 4283/4283 (+2 corruptRefetch, +1 + buildIndexSalvaged, +1 salvageMark); editor 310/310; mcp 372 → 373/373; test:scripts 1027 (1024 + 3 skipped); + export unit 117/117. +- e2e (after the bus came back, on the orchestrator's word), `audio-check-scenarios.spec.ts`, foreground: run 1 — + 15 passed, 1 failed (the new retry scenario: the fixture's bare `https://odysee.com/abc123` reads as no id to the + app, so the retry's allowlist kept 0 of 1 URLs — a fixture shape, not the refetch); fixed in `c932e29f` (the scenario + uses a real-shaped Odysee claim URL; the fake yt-dlp reads such a URL's id as the app does); run 2 — **16/16 + passed** (1.3 min). + +Not done: no live run (the orchestrator's, after merge); the editor's video page does not list `corruptRefetches` +(the sidecar has them); the summaries pages (`DisplaySummary`) do not carry the mark. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -912,7 +912,10 @@ export function usage() { 'transcribe-one transcribes one video: {"slug", "id", "file"?}. With "file"', ' (an audio file in its dir) that file; without, the video page\'s', ' Transcribe — the audio on disk, or downloaded first through the channel\'s', - ' managed path. A job; --wait follows it.', + ' managed path. A job; --wait follows it. "salvage": true decodes a damaged', + ' file with error tolerance and transcribes what decodes, on the', + ' recording\'s clock, its gaps recorded (the transcript is listed as', + ' salvaged); a corrupt-full-source video is salvaged unless "salvage": false.', "", 'delete-file deletes one file of one video, as its Files list does:', ' {"slug", "id", "file"}. A tiered media file goes with its bytes on the', @@ -1079,6 +1082,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', diff --git a/scripts/parakeet-stitch.mjs b/scripts/parakeet-stitch.mjs @@ -51,6 +51,13 @@ // --words also write the stitched words, as a top-level // `words: [{w, start, end, conf}]` beside chunk_data // (seconds; readers of chunk_data ignore it) +// --salvage a damaged recording (release 30, lane Q): slice with +// ffmpeg's error tolerance, and a window that cannot be +// sliced or transcribed is a GAP, not the end of the +// file. The output gains `salvage: { failedWindows: +// [[from, to], ...] }` (seconds: the span each failed +// window owned). A failed window is not cached, so a +// re-run asks it again. // -h, --help show this help import { execFile } from "node:child_process"; @@ -97,6 +104,7 @@ function parseArgs(argv) { maxCue: 8, keepTemp: false, words: false, + salvage: false, output: undefined, audio: undefined, }; @@ -124,6 +132,7 @@ function parseArgs(argv) { case "-o": case "--output": opts.output = next(); break; case "--keep-temp": opts.keepTemp = true; break; case "--words": opts.words = true; break; + case "--salvage": opts.salvage = true; break; default: if (a.startsWith("-")) fail(`unknown option ${a}`); positional.push(a); @@ -200,8 +209,11 @@ async function probeDuration(ffprobe, audio) { // Slice [start, start+len) of the source into a 16kHz-mono s16 WAV. Input // seeking (-ss before -i) is fast and accurate enough given the overlap. -async function sliceWav(ffmpeg, audio, start, len, outWav) { +async function sliceWav(ffmpeg, audio, start, len, outWav, { salvage = false } = {}) { const args = ["-nostdin", "-v", "error", "-y"]; + // Salvage: keep decoding past a refused frame, drop packets the demuxer + // flags as corrupt (lib/salvageAudio-server.ts decodes the same way). + if (salvage) args.push("-err_detect", "ignore_err", "-fflags", "+discardcorrupt"); if (start > 0) args.push("-ss", String(start)); args.push("-i", audio); if (len !== undefined) args.push("-t", String(len)); @@ -496,6 +508,7 @@ async function main() { let paused = false; const segTimes = []; // measured wall-time (ms) per freshly-transcribed window, for ETA let done = 0; // windows present (cached or freshly done) + const failed = new Set(); // salvage: windows that could not be sliced or transcribed try { for (let i = 0; i < N; i += 1) { const start = offsets[i]; @@ -515,12 +528,24 @@ async function main() { const len = isLast ? undefined : opts.segment; const wav = path.join(tmp, `win-${String(i).padStart(4, "0")}.wav`); const eta = etaSuffix(segTimes, N - i); - progress(`segment ${i + 1}/${N} @${round3(start)}s — slicing${eta}`); - await sliceWav(opts.ffmpeg, opts.audio, start, len, wav); - progress(`segment ${i + 1}/${N} @${round3(start)}s — transcribing${eta}`); - const t0 = Date.now(); - const doc = await transcribeWindow(opts, wav); - segTimes.push(Date.now() - t0); + let doc; + try { + progress(`segment ${i + 1}/${N} @${round3(start)}s — slicing${eta}`); + await sliceWav(opts.ffmpeg, opts.audio, start, len, wav, { salvage: opts.salvage }); + progress(`segment ${i + 1}/${N} @${round3(start)}s — transcribing${eta}`); + const t0 = Date.now(); + doc = await transcribeWindow(opts, wav); + segTimes.push(Date.now() - t0); + } catch (err) { + if (!opts.salvage) throw err; + // SALVAGE: one bad window is a gap, not the end of the file. + const msg = String(err?.message ?? err).split("\n").filter(Boolean).slice(-1)[0] ?? ""; + progress(`segment ${i + 1}/${N} @${round3(start)}s — failed, recorded as a gap (salvage): ${msg}`); + failed.add(i); + done += 1; + if (!opts.keepTemp) await rm(wav, { force: true }); + continue; + } // Persist the raw parakeet-cli payload for this window (the "original json"), // tagged with its absolute start offset. This is the durable, resumable // artifact; stitching happens only at the end. @@ -536,9 +561,16 @@ async function main() { process.exit(PARTIAL_PAUSE_CODE); } + // A salvage with nothing salvaged is a failed transcription, not an empty one. + if (failed.size === N) fail(`every one of ${N} window(s) failed (salvage)`, 1); + // All windows present — load the raw payloads and stitch the final transcript. const windowWords = []; for (let i = 0; i < N; i += 1) { + if (failed.has(i)) { + windowWords.push([]); + continue; + } const { start, doc } = JSON.parse(await readFile(winPath(i), "utf8")); const words = Array.isArray(doc.words) ? doc.words : []; windowWords.push( @@ -558,10 +590,15 @@ async function main() { for (let i = 0; i < N - 1; i += 1) { cuts.push(offsets[i + 1] + overlap / 2); } + // Salvage: a window beside a FAILED one owns its whole reach on that side — + // nothing else will cover the overlap there. + const ok = (i) => i >= 0 && i < N && !failed.has(i); + const reach = (i) => (i === N - 1 ? Infinity : offsets[i] + opts.segment); const stitched = []; for (let i = 0; i < N; i += 1) { - const lo = i > 0 ? cuts[i - 1] : -Infinity; - const hi = i < N - 1 ? cuts[i] : Infinity; + if (!ok(i)) continue; + const lo = i === 0 ? -Infinity : ok(i - 1) ? cuts[i - 1] : offsets[i]; + const hi = i === N - 1 ? Infinity : ok(i + 1) ? cuts[i] : reach(i); for (const w of windowWords[i]) { if (w.start >= lo && w.start < hi) stitched.push(w); } @@ -570,12 +607,23 @@ async function main() { const chunkData = groupCues(stitched, { gap: opts.gap, maxCue: opts.maxCue }); const text = chunkData.map((c) => c.text).join(" "); + // What no transcribed window reached: the gaps the failed windows left. + const failedWindows = []; + let cursor = 0; + for (let i = 0; i < N; i += 1) { + if (!ok(i)) continue; + if (offsets[i] > cursor) failedWindows.push([round3(cursor), round3(offsets[i])]); + cursor = Math.max(cursor, Math.min(reach(i), duration)); + } + if (failed.size > 0 && cursor < duration) failedWindows.push([round3(cursor), round3(duration)]); + if (failedWindows.length) progress(`salvage: ${failedWindows.length} of ${N} window(s) failed and are gaps`); const doc = { duration_seconds: round3(duration), chunks: chunkData.length, text, chunk_data: chunkData, ...(opts.words ? { words: wordsOut(stitched) } : {}), + ...(opts.salvage ? { salvage: { failedWindows } } : {}), }; const json = JSON.stringify(doc); diff --git a/scripts/parakeet-stitch.test.mjs b/scripts/parakeet-stitch.test.mjs @@ -116,3 +116,78 @@ test("the live owner check: this process owns a dir it marked; a dead pid does n rmSync(dir, { recursive: true, force: true }); } }); + +// Release 30 lane Q: --salvage. A window that cannot be sliced or transcribed +// is a gap, recorded in the output; without the flag it is the end of the file. +function salvageFixture(root, { failSlice = false } = {}) { + const bin = path.join(root, "bin"); + const work = path.join(root, "video"); + mkdirSync(bin); + mkdirSync(work); + writeFileSync(path.join(work, "audio.wav"), "not audio"); + writeFileSync(path.join(root, "model.gguf"), "not a model"); + sh(path.join(bin, "ffprobe"), "echo 1000"); + // ffmpeg writes the window wav (its last argument), named for its window; + // with failSlice the second window's slice fails as a damaged file does. + sh( + path.join(bin, "ffmpeg"), + `for a; do last="$a"; done; case "$last" in *win-0001.wav) ${failSlice ? 'echo "Invalid data found when processing input" >&2; exit 1' : "echo wav > \"$last\""};; *) echo wav > "$last";; esac`, + ); + // parakeet-cli: one word 1 s into each window; the second window fails. + sh( + path.join(bin, "parakeet-cli"), + 'for a; do last="$a"; done; case "$last" in *win-0001.wav) echo "parakeet: decode failed" >&2; exit 1;; esac; echo \'{"words":[{"w":"word","start":1,"end":1.5}]}\'', + ); + return { bin, work }; +} + +function runStitch(root, bin, work, extra = []) { + return spawnSync( + process.execPath, + [SCRIPT, "--model", path.join(root, "model.gguf"), "--cli", path.join(bin, "parakeet-cli"), "--ffmpeg", path.join(bin, "ffmpeg"), ...extra, path.join(work, "audio.wav"), path.join(work, "out.json")], + { env: { ...process.env, TMPDIR: path.join(root, "tmp") }, encoding: "utf8", timeout: 30_000 }, + ); +} + +for (const failSlice of [false, true]) { + test(`--salvage: a window whose ${failSlice ? "slice" : "transcription"} fails is a gap, the rest is stitched`, async () => { + const root = mkdtempSync(path.join(os.tmpdir(), "stitch-salvage-")); + try { + mkdirSync(path.join(root, "tmp")); + const { bin, work } = salvageFixture(root, { failSlice }); + // Without the flag: the whole file fails. + const plain = runStitch(root, bin, work); + assert.equal(plain.status, 1); + assert.ok(!existsSync(path.join(work, "out.json"))); + // With it: windows 0 and 2 are transcribed, window 1 is a gap. + const r = runStitch(root, bin, work, ["--salvage"]); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stderr, /segment 2\/3 @474s — failed, recorded as a gap \(salvage\)/); + const doc = JSON.parse((await import("node:fs")).readFileSync(path.join(work, "out.json"), "utf8")); + // 1000 s in 480 s windows with 6 s overlap: starts 0, 474, 948. With the + // middle one gone, its neighbours own their whole reach — 0–480 and + // 948–1000 — and only what neither reaches is a gap. + assert.deepEqual(doc.salvage, { failedWindows: [[480, 948]] }); + assert.deepEqual(doc.chunk_data.map((c) => c.start_time), [1, 949]); + // A failed window is not cached; the next run asks it again. + assert.ok(!existsSync(path.join(work, ".audio.wav.parakeet")), "work dir removed after the stitch"); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +} + +test("--salvage: every window failing is a failed transcription, not an empty one", () => { + const root = mkdtempSync(path.join(os.tmpdir(), "stitch-salvage-all-")); + try { + mkdirSync(path.join(root, "tmp")); + const { bin, work } = salvageFixture(root); + sh(path.join(bin, "parakeet-cli"), "exit 1"); + const r = runStitch(root, bin, work, ["--salvage"]); + assert.equal(r.status, 1); + assert.match(r.stderr, /every one of 3 window\(s\) failed \(salvage\)/); + assert.ok(!existsSync(path.join(work, "out.json"))); + } finally { + rmSync(root, { recursive: true, force: true }); + } +});