import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, 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 { SavedVideoPointer } from "../lib/savedVideo"; import { savedAlternatesLine } from "../lib/savedVideo"; import { dropSavedVideo, loadSavedVideo, persistSourceVideo, resolveSavedVideo, unpersistSavedVideo, } from "../lib/savedVideo-server"; import { findSourceMedia, isSourceMediaFile } from "../lib/mediaFiles"; import { wholeContainersOf } from "../lib/evidenceClip.mjs"; import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; import { mediaImportSidecar } from "../lib/mediaImport-server"; import { listSavedAlternates, savedVideoTotals } from "../controller/savedVideoInventory"; import { pruneSavedVideos } from "../controller/pruneSavedVideos"; import { finalizeAppExtraction } from "./finalizeAppExtraction"; import { alternateName, persistOverExisting, planSavedContainer, type SavedAlternatesDeps } from "./savedAlternates"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/savedAlternates.test.ts // // A download over a container already in the saved-video store keeps BOTH // (ytdlp/savedAlternates.ts): which is active, what the pointer flags, that no // reader takes the alternate for a source, and that nothing deletes one // silently. A temp corpus; a "container" is a text file whose content names // its length and height, read by injected measure/height deps. const CONFIG = { handling: "transcribe", platform: "rumble", url: "https://rumble.com/c/Synth" } as ChannelConfig; const SLUG = "synth-rumble"; const NOW = new Date("2026-10-23T17:23:12.000Z"); async function withCorpus(fn: (paths: Paths) => Promise): Promise { const dir = await mkdtemp(path.join(tmpdir(), "saved-alternates-")); const paths = { transcriptsDir: dir, channelsDir: path.join(dir, "channels"), savedVideosDir: path.join(dir, "saved-videos"), ffprobeBin: "/nonexistent/ffprobe", ffmpegBin: "/nonexistent/ffmpeg", } as Paths; try { await fn(paths); } finally { await rm(dir, { recursive: true, force: true }); } } function fakeMedia(tag: string, seconds: number, height: number): string { return `${tag};seconds=${seconds};height=${height}`; } const deps: SavedAlternatesDeps = { measure: async (f) => { const m = /seconds=([\d.]+)/.exec(await readFile(f, "utf8").catch(() => "")); return m ? Number(m[1]) : null; }, height: async (f) => { const m = /height=(\d+)/.exec(await readFile(f, "utf8").catch(() => "")); return m ? Number(m[1]) : null; }, now: () => NOW, }; function videoDirOf(paths: Paths, id: string): string { return path.join(paths.channelsDir, SLUG, "data", id); } // A video whose container is already in the store: landed (import-media, a // pin, with media-import.json) or an ordinary download. async function seed( paths: Paths, id: string, opts: { landed?: boolean; seconds?: number; height?: number; keepReason?: "pin" | "keep-latest"; requestedBy?: string } = {}, ): Promise { const dir = videoDirOf(paths, id); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("old", opts.seconds ?? 4696.629777, opts.height ?? 360)); await persistSourceVideo({ videoDir: dir, sourceFilename: "source-media.mp4", storeDir: path.join(paths.savedVideosDir, SLUG, id), keepReason: opts.keepReason ?? (opts.landed ? "pin" : "keep-latest"), ...(opts.landed ? { origin: { requestedBy: "import-media", kind: "local-archive" as const, archive: "/x/cap.zip", entry: "cap.mp4" } } : opts.requestedBy ? { origin: { requestedBy: opts.requestedBy } } : {}), ...(opts.landed ? {} : { format: { preset: "original" as const, height: opts.height ?? 360 } }), }); if (opts.landed) { await mediaImportSidecar.write(dir, { entries: [ { at: "2026-10-22T00:00:00.000Z", via: "import-media", source: { path: "/x/cap.mp4", name: "cap.mp4", bytes: 10 }, finalized: "copied", container: { file: "source-media.mp4", seconds: 4696.629777, bytes: 10 }, kept: "new", audio: "skipped", }, ], }); } return dir; } // The download's container, as yt-dlp leaves it in data//, finalized as a // forced persist over a transcript (no audio extracted). async function download( paths: Paths, dir: string, opts: { explicit: boolean; seconds?: number; height?: number; oldCopyAsProxy?: boolean }, ): Promise { await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("new", opts.seconds ?? 4696.479777, opts.height ?? 720)); const log: string[] = []; await finalizeAppExtraction({ paths, channelSlug: SLUG, channelConfig: CONFIG, videoDir: dir, videoId: path.basename(dir), fmt: "mp3", persist: true, category: "override", extractAudio: false, format: { preset: "video_720", height: opts.height ?? 720, vcodec: "avc1" }, explicitPersist: opts.explicit, ...(opts.oldCopyAsProxy ? { oldCopyAsProxy: true } : {}), alternatesDeps: deps, onLog: (s) => void log.push(s), signal: new AbortController().signal, }); return log.join(""); } const ALT_360 = "source-media.alt-360p-20261023172312.mp4"; const ALT_720 = "source-media.alt-720p-20261023172312.mp4"; async function storeFiles(p: SavedVideoPointer): Promise { return (await readdir(p.dir)).sort(); } test("an explicit persist over a landed copy: both kept, the download active, the landed one flagged; the pin stays", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "v7h6xzw", { landed: true }); await setDoNotClean(dir, true, { by: "operator", via: "toggle", note: "keep" }); const log = await download(paths, dir, { explicit: true }); assert.match( log, /Kept both copies: the download \(720p, 4696\.5 s\) is now the active source; the landed one \(360p, 4696\.6 s\) stays as source-media\.alt-360p-20261023172312\.mp4\. Flagged for a check\.\n/, ); const p = (await loadSavedVideo(dir))!; assert.equal(p.file, "source-media.mp4"); assert.match(await readFile(path.join(p.dir, p.file), "utf8"), /^new/); assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]); assert.match(await readFile(path.join(p.dir, ALT_360), "utf8"), /^old/); // A pin stays a pin; the do-not-clean marker is untouched. assert.equal(p.keepReason, "pin"); assert.ok(await isDoNotClean(dir)); // The landed provenance moved to the alternate; the active one is a download. assert.equal(p.origin, undefined); assert.equal(p.format?.height, 720); assert.deepEqual(p.probed, { seconds: 4696.479777, height: 720 }); assert.equal(p.alternates?.length, 1); const alt = p.alternates![0]!; assert.equal(alt.file, ALT_360); assert.equal(alt.height, 360); assert.equal(alt.seconds, 4696.629777); assert.equal(alt.origin?.requestedBy, "import-media"); assert.equal(alt.origin?.kind, "local-archive"); assert.equal(alt.setAsideAt, NOW.toISOString()); // The flag in the landing's own history. const c = (await mediaImportSidecar.load(dir))?.challenges?.at(-1); assert.equal(c?.kept, "download"); assert.equal(c?.alternate, ALT_360); assert.equal(c?.explicit, true); assert.equal( savedAlternatesLine(p), "2 saved copies: active 720p, 4696.5 s (download); alternate 360p, 4696.6 s (import-media, source-media.alt-360p-20261023172312.mp4)", ); }); }); test("an explicit persist much shorter than the landed copy still becomes active; nothing is deleted", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vshort", { landed: true }); const log = await download(paths, dir, { explicit: true, seconds: 4696.629777 - 300 }); assert.match(log, /the download \(720p, 4396\.6 s\) is now the active source/); const p = (await loadSavedVideo(dir))!; assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]); // A second one: the first download joins the alternates, which accumulate. await download(paths, dir, { explicit: true, height: 1080 }); const p2 = (await loadSavedVideo(dir))!; assert.deepEqual(p2.alternates?.map((a) => a.file), [ALT_360, ALT_720]); assert.deepEqual(await storeFiles(p2), [ALT_360, ALT_720, "source-media.mp4"]); assert.equal(p2.keepReason, "pin"); }); }); test("an automatic download over a landed copy of the same length: both kept, the landed one stays active", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vauto", { landed: true }); await setDoNotClean(dir, true, { by: "operator", via: "toggle" }); const log = await download(paths, dir, { explicit: false }); assert.match( log, /Kept both copies: the landed one \(360p, 4696\.6 s\) stays the active source \(an automatic download takes over only when it is longer\); the download \(720p, 4696\.5 s\) is kept as source-media\.alt-720p-20261023172312\.mp4\. Flagged for a check\.\n/, ); const p = (await loadSavedVideo(dir))!; assert.equal(p.file, "source-media.mp4"); assert.match(await readFile(path.join(p.dir, p.file), "utf8"), /^old/); assert.match(await readFile(path.join(p.dir, ALT_720), "utf8"), /^new/); assert.equal(p.origin?.requestedBy, "import-media", "the active copy keeps its own provenance"); assert.equal(p.keepReason, "pin"); assert.ok(await isDoNotClean(dir)); assert.deepEqual(p.alternates?.map((a) => [a.file, a.height, a.preset, a.vcodec]), [[ALT_720, 720, "video_720", "avc1"]]); assert.ok(!(await readdir(dir)).includes("source-media.mp4"), "the download left the data dir"); assert.equal((await mediaImportSidecar.load(dir))?.challenges?.at(-1)?.kept, "landed"); }); }); test("an automatic download longer than the copy in the store becomes active; the other is kept", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vlong", { requestedBy: "umtool" }); const log = await download(paths, dir, { explicit: false, seconds: 5000 }); assert.match(log, /the download \(720p, 5000\.0 s\) is now the active source \(it is longer\); the saved one \(360p, 4696\.6 s\) stays as source-media\.alt-360p-20261023172312\.mp4/); const p = (await loadSavedVideo(dir))!; // An ordinary copy's requester and keep-latest class carry over. assert.equal(p.keepReason, "keep-latest"); assert.equal(p.origin?.requestedBy, "umtool"); assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]); }); }); test("no copy in the store: an ordinary persist, no alternates", async () => { await withCorpus(async (paths) => { const dir = videoDirOf(paths, "vfresh"); await mkdir(dir, { recursive: true }); const log = await download(paths, dir, { explicit: true }); assert.doesNotMatch(log, /Kept both/); const p = (await loadSavedVideo(dir))!; assert.equal(p.alternates, undefined); assert.equal(p.keepReason, "override"); }); }); test("readers never take an alternate for the source", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vread", { landed: true }); await download(paths, dir, { explicit: true }); const p = (await loadSavedVideo(dir))!; assert.equal(await resolveSavedVideo(dir), path.join(p.dir, "source-media.mp4")); for (const name of [ALT_360, "source-media.alt-20261023172312.webm", "source-media.alt-720p-20261023172312-2.mkv"]) { assert.equal(isSourceMediaFile(name), false, name); } assert.equal(findSourceMedia([ALT_360]), null); // Even in the data dir (where unpersist puts it back), the clip tier's // whole-container list does not name it. await writeFile(path.join(dir, ALT_360), "x"); assert.deepEqual((await wholeContainersOf(dir)).map((c) => c.name), ["source-media.mp4"]); }); }); test("the inventory counts and lists alternates; the prune never removes one; drop and unpersist take them along", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vprune", { keepReason: "keep-latest" }); await download(paths, dir, { explicit: true }); const p = (await loadSavedVideo(dir))!; assert.equal(p.keepReason, "keep-latest"); const totals = await savedVideoTotals({ paths, channelSlug: SLUG }); assert.equal(totals.bytes, p.bytes + p.alternates![0]!.bytes); assert.deepEqual((await listSavedAlternates({ paths })).map((e) => e.videoId), ["vprune"]); // Rolled out of a keep-latest window of 0: kept, with a line saying why. await writeFile(path.join(paths.channelsDir, SLUG, "config.json"), JSON.stringify(CONFIG)); const lines: string[] = []; const r = await pruneSavedVideos({ paths, channelSlug: SLUG, onLog: (l) => void lines.push(l) }); assert.equal(r.pruned, 0); assert.match(lines.join("\n"), /Kept saved video vprune .* 1 alternate copy flagged for a check/); assert.deepEqual(await storeFiles(p), [ALT_360, "source-media.mp4"]); // Unpersist brings both back to the data dir. assert.equal(await unpersistSavedVideo(dir), true); const back = (await readdir(dir)).sort(); assert.ok(back.includes(ALT_360) && back.includes("source-media.mp4")); // Drop (a deliberate whole-video delete) removes both and counts both. const dir2 = await seed(paths, "vdrop", {}); await download(paths, dir2, { explicit: true }); const p2 = (await loadSavedVideo(dir2))!; assert.equal(await dropSavedVideo(dir2), p2.bytes + p2.alternates![0]!.bytes); assert.deepEqual(await readdir(p2.dir).catch(() => []), []); }); }); test("the prune keeps a video holding a proxy and names it as one (wording only)", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vproxyp", { keepReason: "keep-latest" }); await download(paths, dir, { explicit: true, height: 1080, oldCopyAsProxy: true }); await writeFile(path.join(paths.channelsDir, SLUG, "config.json"), JSON.stringify(CONFIG)); const lines: string[] = []; const r = await pruneSavedVideos({ paths, channelSlug: SLUG, onLog: (l) => void lines.push(l) }); assert.equal(r.pruned, 0); assert.match( lines.join("\n"), /Kept saved video vproxyp .*: it holds 1 alternate copy \(1 kept on purpose as the lower-quality proxy\)\./, ); assert.doesNotMatch(lines.join("\n"), /flagged for a check/); }); }); test("a persist that fails after the rename puts the old name back", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vfail", { landed: true }); await writeFile(path.join(dir, "source-media.mp4"), fakeMedia("new", 4696, 720)); const plan = (await planSavedContainer({ videoDir: dir, newContainer: path.join(dir, "source-media.mp4"), explicit: true, deps }))!; await rm(path.join(dir, "source-media.mp4")); await assert.rejects( persistOverExisting(plan, { sourceFilename: "source-media.mp4", deps, onLog: () => {} }), ); const p = (await loadSavedVideo(dir))!; assert.deepEqual(await storeFiles(p), ["source-media.mp4"]); assert.equal(p.alternates, undefined); }); }); // persist-videos "below-height": the old copy is marked the proxy in the SAME // pointer write that lists it — never by a second write that a crash or a // throw could leave undone. test("oldCopyAsProxy: a taller download marks the old copy keptAs proxy in the one pointer write; not taller, no mark", async () => { await withCorpus(async (paths) => { const dir = await seed(paths, "vprox01", { landed: true }); const log = await download(paths, dir, { explicit: true, height: 1080, oldCopyAsProxy: true }); assert.match(log, /stays as source-media\.alt-360p-20261023172312\.mp4\. Kept on purpose as the lower-quality proxy\.\n/); const p = (await loadSavedVideo(dir))!; assert.equal(p.alternates?.length, 1); assert.equal(p.alternates![0]!.keptAs, "proxy"); assert.equal(p.alternates![0]!.height, 360); assert.equal(p.keepReason, "pin"); // The download is not taller: both kept, no mark, flagged for a check. const dir2 = await seed(paths, "vprox02", { height: 720, requestedBy: "umtool" }); const log2 = await download(paths, dir2, { explicit: true, height: 720, oldCopyAsProxy: true }); assert.match(log2, /Not marked as a proxy \(the download is not measured taller\); flagged for a check\.\n/); const p2 = (await loadSavedVideo(dir2))!; assert.equal(p2.alternates?.[0]?.keptAs, undefined); // Without the option (any other explicit persist): never a proxy. const dir3 = await seed(paths, "vprox03", { landed: true }); await download(paths, dir3, { explicit: true, height: 1080 }); assert.equal((await loadSavedVideo(dir3))!.alternates?.[0]?.keptAs, undefined); }); }); test("alternate names: height when known, a numbered suffix on a clash", () => { assert.equal(alternateName("source-media.webm", null, NOW), "source-media.alt-20261023172312.webm"); assert.equal( alternateName("source-media.mp4", 720, NOW, [ALT_720]), "source-media.alt-720p-20261023172312-2.mp4", ); });