// fetchWindows (the batch) and THE HEIGHT TIER (lib/clipWindow.ts): a tall ask // over a lower held window cuts a taller one beside it from the saved copy, // or uses the window as it is and says why — never a network fetch for height; // a tall ask with nothing held fetches into its own tier; no ask is exactly as // before; the ceiling clamps. Every network and media dependency is stubbed. // // Run with: pnpm --filter yt-dlp-transcript-common exec tsx --test controller/fetchWindowsTier.test.ts import { test } from "node:test"; import assert from "node:assert/strict"; import { mkdir, mkdtemp, readFile, readdir, rm, stat, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { fetchWindows, type FetchWindowsDeps, type FetchWindowsItem } from "./fetchWindows"; import { evictClipWindows } from "./evictClipWindows"; import type { Paths } from "../lib/paths"; import type { ChannelConfig } from "../lib/channelConfig"; import type { SiteSettings } from "../lib/settings"; import type { SavedWindowSource } from "../lib/savedVideoWindow-server"; import type { FetchWindowOpts } from "../ytdlp/fetchWindowManaged"; const CONFIG = { url: "https://www.youtube.com/@x", platform: "youtube" } as unknown as ChannelConfig; async function withCorpus(fn: (o: { paths: Paths; videoDir: string; clips: string }) => Promise) { const root = await mkdtemp(path.join(os.tmpdir(), "fetchwindows-tier-")); const channelsDir = path.join(root, "channels"); const videoDir = path.join(channelsDir, "c", "data", "v1"); const clips = path.join(videoDir, "clips"); await mkdir(clips, { recursive: true }); const paths = { transcriptsDir: root, channelsDir, savedVideosDir: path.join(root, "saved") } as unknown as Paths; try { await fn({ paths, videoDir, clips }); } finally { await rm(root, { recursive: true, force: true }); } } const covers = (height: number): SavedWindowSource => ({ kind: "covers", pointer: { storedAt: "", dir: "/s", file: "source-media.mp4", bytes: 1 }, container: "/s/source-media.mp4", durationSec: 100, probe: { durationSec: 100, width: Math.round((height * 16) / 9), height, hasVideo: true, hasAudio: true }, }) as SavedWindowSource; function harness(o: { saved?: SavedWindowSource; windowMaxHeight?: number; renderHeld?: () => string | null } = {}) { const fetches: FetchWindowOpts[] = []; const cuts: { maxHeight?: number; from: number; to: number }[] = []; const derived: { from: string; to: number }[] = []; const sleeps: number[] = []; const deps: Partial = { sleep: async (ms) => { sleeps.push(ms); }, renderHeld: o.renderHeld ?? (() => null), cutPlainFromTiered: async (c) => { derived.push({ from: c.tiered.file, to: c.to }); const file = `${c.from.toFixed(2)}-${c.to.toFixed(2)}.mp4`; return { file, path: path.join(c.videoDir, "clips", file), from: c.from, to: c.to, bytes: 1, provenance: null }; }, getSettings: () => ({ sleepBetweenDownloadsSeconds: 0, clips: { wholeRecordingPlatforms: [], ...(o.windowMaxHeight ? { windowMaxHeight: o.windowMaxHeight } : {}) }, }) as unknown as SiteSettings, readChannelConfig: async () => CONFIG, findVideoSourceUrl: async () => "https://www.youtube.com/watch?v=v1", assertTextReadable: async () => undefined, cooldownRemainingMs: async () => 0, heldRefusal: async () => null, recordBackoff: async () => {}, recordClean: async () => null, gapRemainingMs: () => 0, noteGap: () => {}, probeWindow: async () => null, probeHeight: async () => null, savedWindowSource: async () => o.saved ?? { kind: "none" }, cutSavedWindow: async (c) => { cuts.push({ maxHeight: c.tier, from: c.from, to: c.to }); const tier = c.tier; const file = `${c.from.toFixed(2)}-${c.to.toFixed(2)}${tier ? `.h${tier}` : ""}.mp4`; return { file, path: path.join(c.videoDir, "clips", file), from: c.from, to: c.to, bytes: 1, provenance: null, ...(tier ? { tier, height: tier } : {}) }; }, fetchWindow: async (f) => { fetches.push(f); return { file: "/x", from: f.from, to: f.to, bytes: 1, cached: false, provenance: null } as never; }, }; return { deps, fetches, cuts, derived, sleeps }; } const item: FetchWindowsItem = { slug: "c", id: "v1", from: 10, to: 20 }; const run = (paths: Paths, deps: Partial, maxHeight?: number, lines: string[] = []) => fetchWindows({ paths, items: [item], provenance: { requestedBy: "umtool" }, maxHeight, gapMs: 0, onLog: (l) => lines.push(l), deps }); async function plainWindow(clips: string, height?: number) { await writeFile(path.join(clips, "10.00-20.00.mp4"), "the 720 window"); await writeFile(path.join(clips, "10.00-20.00.json"), JSON.stringify({ requestedBy: "reports", ...(height ? { height } : {}) })); } test("a tall ask over a 720 window with a 1080 saved copy cuts the 1080 beside it; the 720 one is not touched", async () => { await withCorpus(async ({ paths, videoDir, clips }) => { await plainWindow(clips, 720); await writeFile( path.join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "2026-11-13T00:00:00.000Z", dir: "/s", file: "source-media.mp4", bytes: 1, format: { preset: "original", height: 1080 } }), ); const before = await stat(path.join(clips, "10.00-20.00.mp4")); const h = harness({ saved: covers(1080) }); const lines: string[] = []; const r = await run(paths, h.deps, 1080, lines); assert.deepEqual(h.cuts, [{ maxHeight: 1080, from: 10, to: 20 }]); assert.equal(h.fetches.length, 0); assert.equal(r.cut.length, 1); assert.equal(r.lower, undefined); assert.match(lines.join(""), /cut from the saved video into clips\/10\.00-20\.00\.h1080\.mp4 \(1080p, beside clips\/10\.00-20\.00\.mp4, which stays as it is\)/); const after = await stat(path.join(clips, "10.00-20.00.mp4")); assert.equal(after.mtimeMs, before.mtimeMs); assert.equal(await readFile(path.join(clips, "10.00-20.00.mp4"), "utf8"), "the 720 window"); }); }); test("a tall ask over a 720 window with no saved copy uses it as it is, says why, and fetches nothing", async () => { await withCorpus(async ({ paths, clips }) => { await plainWindow(clips, 720); const h = harness(); const lines: string[] = []; const r = await run(paths, h.deps, 1080, lines); assert.equal(h.fetches.length, 0); assert.equal(h.cuts.length, 0); assert.equal(r.cached.length, 1); assert.equal(r.lower?.length, 1); assert.equal(r.lower![0].file, "10.00-20.00.mp4"); assert.equal(r.lower![0].height, 720); assert.equal(r.lower![0].asked, 1080); assert.match(r.lower![0].why, /no saved copy/); assert.match(lines.join(""), /cached in clips\/10\.00-20\.00\.mp4 at 720p, below the 1080p asked — no saved copy/); }); }); test("an old window with no recorded height is probed once on its first tall ask, and recorded", async () => { await withCorpus(async ({ paths, clips }) => { await plainWindow(clips); const h = harness(); let probes = 0; h.deps.probeHeight = async () => { probes += 1; return 1080; }; const r = await run(paths, h.deps, 1080); assert.equal(r.cached.length, 1); assert.equal(r.lower, undefined, "a 1080 window is not lower than a 1080 ask"); assert.equal(probes, 1); assert.equal(JSON.parse(await readFile(path.join(clips, "10.00-20.00.json"), "utf8")).height, 1080); await run(paths, h.deps, 1080); assert.equal(probes, 1, "the second ask reads the record"); }); }); test("a tall ask with nothing held fetches into its own tier at its height; no ask fetches as before", async () => { await withCorpus(async ({ paths }) => { const tall = harness(); await run(paths, tall.deps, 1080); assert.equal(tall.fetches.length, 1); assert.equal(tall.fetches[0].maxHeight, 1080); assert.equal(tall.fetches[0].tier, 1080); const plain = harness(); await run(paths, plain.deps); assert.equal(plain.fetches[0].maxHeight, undefined); assert.equal(plain.fetches[0].tier, undefined); const at480 = harness(); await run(paths, at480.deps, 480); assert.equal(at480.fetches[0].maxHeight, 480); assert.equal(at480.fetches[0].tier, undefined); }); }); test("an ask above clips.windowMaxHeight is clamped to it, and said", async () => { await withCorpus(async ({ paths }) => { const h = harness({ windowMaxHeight: 1080 }); const lines: string[] = []; const r = await run(paths, h.deps, 2160, lines); assert.equal(r.clampedFrom, 2160); assert.equal(h.fetches[0].maxHeight, 1080); assert.equal(h.fetches[0].tier, 1080); assert.match(lines.join(""), /2160p was asked; clips\.windowMaxHeight caps a window at 1080p/); }); }); test("with no ask, a held 720 window answers as always, unprobed, whatever the saved copy holds", async () => { await withCorpus(async ({ paths, clips }) => { await plainWindow(clips); const h = harness({ saved: covers(1080) }); let probes = 0; h.deps.probeHeight = async () => { probes += 1; return 720; }; const r = await run(paths, h.deps); assert.equal(r.cached.length, 1); assert.equal(h.cuts.length, 0); assert.equal(probes, 0); assert.equal(r.lower, undefined); }); }); // EVICTION sees a tiered window as a window of its span: named, covered and by // age, each with its own `.h.json` (and a set-aside tiered one too). test("eviction sees a tiered window as a window of its span: named, covered and by age, with its sidecar", async () => { await withCorpus(async ({ paths, clips }) => { await writeFile(path.join(paths.channelsDir, "c", "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube" })); for (const n of ["10.00-20.00.mp4", "10.00-20.00.json", "10.00-20.00.h1080.mp4", "10.00-20.00.h1080.json", "30.00-40.00.h1080.desynced.mp4", "30.00-40.00.h1080.desynced.json", "50.00-60.00.mp4"]) { await writeFile(path.join(clips, n), "media"); } const old = new Date(Date.now() - 400 * 86_400_000); await utimes(path.join(clips, "30.00-40.00.h1080.desynced.mp4"), old, old); const named = await evictClipWindows({ paths, slug: "c", id: "v1", windows: [{ from: 10, to: 20 }], olderThanDays: 0 }); assert.equal(named.windows, 2); assert.deepEqual((await readdir(clips)).sort(), [ "30.00-40.00.h1080.desynced.json", "30.00-40.00.h1080.desynced.mp4", "50.00-60.00.mp4", ]); const aged = await evictClipWindows({ paths, slug: "c", id: "v1", olderThanDays: 30 }); assert.equal(aged.windows, 1); assert.deepEqual(await readdir(clips), ["50.00-60.00.mp4"]); }); }); // C: the tier filter — what a refetch asks. "tiered" leaves the 720 window a // site reads; "plain" leaves the taller cuts; a named tiered window is that one. test("eviction's tier filter: covering with tiers tiered or plain removes only that kind", async () => { await withCorpus(async ({ paths, clips }) => { await writeFile(path.join(paths.channelsDir, "c", "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube" })); const seed = async () => { for (const n of ["10.00-20.00.mp4", "10.00-20.00.json", "10.00-20.00.h1080.mp4", "10.00-20.00.h1080.json", "10.00-20.00.h1440.mp4"]) { await writeFile(path.join(clips, n), "media"); } }; await seed(); const tall = await evictClipWindows({ paths, slug: "c", id: "v1", covering: [{ from: 12, to: 18 }], tiers: "tiered" }); assert.equal(tall.windows, 2); assert.deepEqual((await readdir(clips)).sort(), ["10.00-20.00.json", "10.00-20.00.mp4"]); await seed(); const plain = await evictClipWindows({ paths, slug: "c", id: "v1", covering: [{ from: 12, to: 18 }], tiers: "plain" }); assert.equal(plain.windows, 1); assert.deepEqual((await readdir(clips)).sort(), ["10.00-20.00.h1080.json", "10.00-20.00.h1080.mp4", "10.00-20.00.h1440.mp4"]); await seed(); const one = await evictClipWindows({ paths, slug: "c", id: "v1", windows: [{ from: 10, to: 20, tier: 1080 }] }); assert.equal(one.windows, 1); assert.ok(!(await readdir(clips)).includes("10.00-20.00.h1080.mp4")); assert.ok((await readdir(clips)).includes("10.00-20.00.mp4")); }); }); // G: THE LADDER. Asks of 900, 1000 and 1080 share the 1080 file; a Retry's // tier (its spec) wins over today's settings. test("tiers snap to the ladder, held to the ceiling; a given tier wins over the settings", async () => { await withCorpus(async ({ paths }) => { for (const ask of [900, 1000, 1080]) { const h = harness(); await run(paths, h.deps, ask); assert.equal(h.fetches[0].tier, 1080, String(ask)); assert.equal(h.fetches[0].maxHeight, 1080, String(ask)); } const over = harness({ windowMaxHeight: 2160 }); await run(paths, over.deps, 1200); assert.equal(over.fetches[0].tier, 1440); const held = harness({ windowMaxHeight: 1200 }); await run(paths, held.deps, 1200); assert.equal(held.fetches[0].tier, 1200, "a rung above the ceiling is held to it"); // A Retry: the spec's 1440, though today's ceiling is 1080. const retry = harness({ windowMaxHeight: 1080 }); await fetchWindows({ paths, items: [item], provenance: { requestedBy: "umtool" }, maxHeight: 1440, tier: 1440, gapMs: 0, deps: retry.deps }); assert.equal(retry.fetches[0].tier, 1440); }); }); // D: a PLAIN miss a tiered window holds is cut locally from it, never fetched. test("a plain ask that misses, over a span a tiered window holds, is cut from that window; nothing is fetched", async () => { await withCorpus(async ({ paths, clips }) => { await writeFile(path.join(clips, "0.00-30.00.h1080.mp4"), "taller"); await writeFile(path.join(clips, "0.00-30.00.h1080.json"), JSON.stringify({ requestedBy: "umtool", height: 1080 })); const h = harness(); const lines: string[] = []; const r = await run(paths, h.deps, undefined, lines); assert.deepEqual(h.derived, [{ from: "0.00-30.00.h1080.mp4", to: 20 }]); assert.equal(h.fetches.length, 0); assert.equal(r.cut.length, 1); assert.match(lines.join(""), /cut from clips\/0\.00-30\.00\.h1080\.mp4 into clips\/10\.00-20\.00\.mp4/); // A cut that fails fails the item, as a saved-copy cut does: nothing is fetched. await rm(path.join(clips, "10.00-20.00.mp4"), { force: true }); const bad = harness(); bad.deps.cutPlainFromTiered = async () => { throw new Error("ffmpeg refused"); }; const failed = await run(paths, bad.deps); assert.equal(bad.fetches.length, 0); assert.equal(failed.failed[0]?.class, "cut-failed"); assert.match(failed.failed[0]?.message ?? "", /cutting it from clips\/0\.00-30\.00\.h1080\.mp4 failed: ffmpeg refused/); }); }); // H: a tall cut from the saved copy waits while render mode holds the machine. test("a tall cut from the saved copy waits out render mode, and says so", async () => { await withCorpus(async ({ paths }) => { let polls = 0; const h = harness({ saved: covers(1080), renderHeld: () => (polls++ < 2 ? "umtool take p --id t, since 13:31" : null) }); const lines: string[] = []; const r = await run(paths, h.deps, 1080, lines); assert.equal(h.cuts.length, 1); assert.equal(r.cut.length, 1); assert.equal(h.sleeps.length, 2); const text = lines.join(""); assert.match(text, /the 1080p cut\): render mode holds the machine \(umtool take p --id t, since 13:31\) — waiting/); assert.match(text, /render mode ended — waited \d+s/); // A plain cut does not wait. let asked = 0; const plain = harness({ saved: covers(1080), renderHeld: () => (asked++, "held") }); await run(paths, plain.deps); assert.equal(asked, 0); assert.equal(plain.cuts.length, 1); }); }); // 4: a tiered window that is not in sync is no source: set aside, and the plain // ask goes on as if it were not there (here: the network). test("a desynced tiered window is set aside, not cut from; the plain ask is fetched", async () => { await withCorpus(async ({ paths, clips }) => { await writeFile(path.join(clips, "0.00-30.00.h1080.mp4"), "taller"); await writeFile(path.join(clips, "0.00-30.00.h1080.json"), JSON.stringify({ requestedBy: "umtool", height: 1080 })); const h = harness(); h.deps.probeWindow = async () => [ { codec_type: "video", start_time: "3.200000", duration: "93.733000" }, { codec_type: "audio", start_time: "3.140000", duration: "90.580000" }, ]; const r = await run(paths, h.deps); assert.deepEqual(h.derived, []); assert.equal(h.fetches.length, 1); assert.equal(h.fetches[0].tier, undefined); assert.deepEqual(r.setAside, ["c/v1/clips/0.00-30.00.h1080.desynced.mp4"]); assert.ok((await readdir(clips)).includes("0.00-30.00.h1080.desynced.mp4")); }); }); // 1: a REFETCH on a tall ask is not answered by the lower 720 window. test("a tall refetch over a 720 window: cut at its tier from the saved copy; with none, fetched at its tier", async () => { await withCorpus(async ({ paths, videoDir, clips }) => { await plainWindow(clips, 720); const refetch: FetchWindowsItem = { ...item, refetch: true }; // No saved copy: the network, at the tier. const h = harness(); const lines: string[] = []; const r = await fetchWindows({ paths, items: [refetch], provenance: { requestedBy: "umtool" }, maxHeight: 1080, gapMs: 0, onLog: (l) => lines.push(l), deps: h.deps }); assert.equal(r.cached.length, 0); assert.equal(r.lower, undefined); assert.equal(h.fetches.length, 1); assert.equal(h.fetches[0].tier, 1080); assert.match(lines.join(""), /a refetch — clips\/10\.00-20\.00\.mp4 \(720p\) does not answer it/); // A saved copy (even one no taller): cut again at the tier from it. await writeFile( path.join(videoDir, "saved-video.json"), JSON.stringify({ storedAt: "", dir: "/s", file: "source-media.mp4", bytes: 1, format: { preset: "original", height: 720 } }), ); const s = harness({ saved: covers(720) }); await fetchWindows({ paths, items: [refetch], provenance: { requestedBy: "umtool" }, maxHeight: 1080, gapMs: 0, deps: s.deps }); assert.deepEqual(s.cuts, [{ maxHeight: 1080, from: 10, to: 20 }]); assert.equal(s.fetches.length, 0); // Without the flag the same ask is the 720 window, listed lower. const plain = harness({ saved: covers(720) }); const p = await run(paths, plain.deps, 1080); assert.equal(p.cached.length, 1); assert.equal(plain.cuts.length, 0); }); });