import { test } from "node:test"; import assert from "node:assert/strict"; import { appendFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import path from "node:path"; import type { ChannelConfig } from "../lib/channelConfig"; import type { MediaProbe } from "../lib/mediaImport"; import type { AttemptOutcome } from "../ytdlp/runOneYtdlp"; // Run with: // pnpm --filter yt-dlp-transcript-common exec tsx --test controller/recordLive.test.ts // // Record live (controller/recordLive.ts) over a temp corpus: the recorders, the // browser and the network are stubs that write fake "media" files // (`format=;seconds=`); the landing is the real one with a stub probe. // One case spawns a real child to prove a Cancel reaches it as SIGINT. const ROOT = await mkdtemp(path.join(tmpdir(), "record-live-")); const CORPUS = path.join(ROOT, "transcripts"); process.env.TRANSCRIPTS_DIR = CORPUS; process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); await mkdir(CORPUS, { recursive: true }); await writeFile(process.env.SETTINGS_FILE, "{}"); const { getPaths } = await import("../lib/paths"); const { parseRecordLiveRequest, planForUrl, pollEventPlaylist, recordLiveRun, spawnRecorder, choosePlaylist, hlsFormatOf, } = await import("./recordLive"); const { liveRecordingSidecar } = await import("../lib/mediaImport-server"); const { loadSavedVideo } = await import("../lib/savedVideo-server"); const { isDoNotClean } = await import("../lib/doNotClean-server"); const paths = getPaths(); test.after(() => rm(ROOT, { recursive: true, force: true })); const SLUG = "synth-rumble"; const CONFIG = { handling: "transcribe", url: "https://rumble.com/c/Synth", platform: "rumble", name: "Synth" } as ChannelConfig; await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true }); await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify(CONFIG)); await mkdir(paths.savedVideosDir, { recursive: true }); async function fakeProbe(file: string): Promise { const text = await readFile(file, "utf8").catch(() => ""); const all = [...text.matchAll(/seconds=([\d.]+)/g)].reduce((s, m) => s + Number(m[1]), 0); if (!/format=/.test(text)) return null; // `v=none;` / `a=none;`: a stream with no video / no audio. return { formatName: /format=([^;]+)/.exec(text)![1]!, seconds: all, videoCodec: /v=none;/.test(text) ? null : "h264", audioCodec: /a=none;/.test(text) ? null : "aac", }; } const land = { probe: fakeProbe, remux: async (src: string, dest: string) => { await writeFile(dest, `format=mov,mp4;seconds=${(await fakeProbe(src))!.seconds};`); }, transcode: async (o: { videoDir: string; fmt: string }) => { await writeFile(path.join(o.videoDir, `audio.${o.fmt}`), "format=mp3;seconds=1;"); }, freeBytes: async () => 1e15, }; // The fakes' files are not media: the landing's check (DESIGN-4 4) passes // unless a case says otherwise. const VERIFY_OK = { verifyMerged: async () => ({ ok: true as const }), verifyScan: async () => ({ ok: true as const }) }; const handoff = async () => ({ workersPaused: true, laneEnabled: true, laneHeld: false, ruleCoversChannel: true, channelPaused: false, hasTranscript: false, transcribeJob: false, }); const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const; // A refresh that writes the stream's metadata (live, with one HLS format). // Read after the recording (the stream has ended): a live record then says // `was_live` (the platforms' own word for an ended stream), unless // `stillLive` says it is still live. function refreshWith( meta: Record, opts: { failFirst?: string; stillLive?: () => boolean; failAfterFirst?: string; afterRead?: (n: number) => void; failReads?: number[]; failWith?: string; endedAs?: string } = {}, ) { let n = 0; let wrote = 0; return async (cwd: string, args: string[]): Promise => { n++; if (opts.failFirst && n === 1) return { exitCode: 1, stderrTail: opts.failFirst, archiveLine: null, formatLine: null }; if (opts.failAfterFirst && n > 1) return { exitCode: 1, stderrTail: opts.failAfterFirst, archiveLine: null, formatLine: null }; if (opts.failReads?.includes(n)) return { exitCode: 1, stderrTail: opts.failWith ?? "ERROR: Unable to download webpage: timed out", archiveLine: null, formatLine: null }; const o = args[args.indexOf("-o") + 1]!; const dir = path.join(cwd, path.dirname(o)); wrote++; const ended = wrote > 1 && meta.live_status === "is_live" && !(opts.stillLive?.() ?? false); await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(ended ? { ...meta, live_status: opts.endedAs ?? "was_live" } : meta)); opts.afterRead?.(n); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }; } const RUMBLE_META = { id: "v7embed", extractor: "RumbleEmbed", title: "A live show", live_status: "is_live", timestamp: 1792691875, formats: [ { format_id: "hls-0", protocol: "m3u8_native", height: 360, url: "https://cdn.example/live/chunklist_360p_i0_DVR.m3u8" }, { format_id: "hls-1", protocol: "m3u8_native", height: 720, url: "https://cdn.example/live/chunklist_720p_i0_DVR.m3u8" }, ], }; const DVR = "#EXTM3U\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:1\n#EXTINF:2,\nm_1.ts\n#EXTINF:2,\nm_2.ts\n"; test("which stream: Rumble by URL id, Kick by channel or VOD uuid", () => { assert.deepEqual(planForUrl("https://rumble.com/v7h8pxg-9-thugs.html"), { url: "https://rumble.com/v7h8pxg-9-thugs.html", platform: "rumble", id: "v7h8pxg" }); const ch = planForUrl("https://kick.com/asmongold"); assert.ok(!("error" in ch) && ch.id === null && ch.kickChannel === "asmongold"); const vod = planForUrl("https://kick.com/asmongold/videos/01a164b1-0c18-723a-a785-f9637c989507"); assert.ok(!("error" in vod) && vod.id === "01a164b1-0c18-723a-a785-f9637c989507" && vod.kickChannel === "asmongold"); const canon = planForUrl("https://kick.com/video/01a164b1-0c18-723a-a785-f9637c989507"); assert.ok(!("error" in canon) && canon.id === "01a164b1-0c18-723a-a785-f9637c989507"); assert.ok("error" in parseRecordLiveRequest({ slug: "s" })); assert.ok("error" in parseRecordLiveRequest({ slug: "s", url: "x", maxHeight: 10 })); assert.deepEqual(parseRecordLiveRequest({ slug: "s", url: "https://kick.com/a", maxHeight: null, doNotClean: true }), { slug: "s", url: "https://kick.com/a", maxHeight: null, doNotClean: true, }); assert.equal(hlsFormatOf(RUMBLE_META, 480)?.height, 360); }); test("Rumble path A: yt-dlp --live-from-start into a staging part, then landed; Do not clean; the pause named", async () => { const calls: { bin: string; args: string[] }[] = []; const log: string[] = []; const s = await recordLiveRun({ paths, request: { slug: SLUG, url: "https://rumble.com/v1aaaaa-show.html", doNotClean: true, note: "Huck — keep" }, plan: { url: "https://rumble.com/v1aaaaa-show.html", platform: "rumble", id: "v1aaaaa" }, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: (l) => void log.push(l), signal: new AbortController().signal, deps: { refresh: refreshWith(RUMBLE_META), fetchText: async () => DVR, spawn: async ({ bin, args }) => { calls.push({ bin, args }); await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=7200;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, }, }); assert.equal(calls.length, 1); const args = calls[0]!.args; assert.ok(args.includes("--live-from-start")); assert.ok(args.includes("--impersonate"), "the channel's Rumble args"); assert.match(args[args.indexOf("--downloader-args") + 1]!, /-live_start_index 0/); assert.equal(s.status, "landed"); assert.equal(s.reach?.fromStart, true); assert.equal(s.landed?.seconds, 7200); const dir = path.join(CORPUS, "channels", SLUG, "data", "v1aaaaa"); assert.equal((await loadSavedVideo(dir))?.origin?.requestedBy, "record-live"); assert.ok(await isDoNotClean(dir)); const rec = await liveRecordingSidecar.load(dir); assert.equal(rec?.status, "landed"); assert.equal(rec?.parts[0]?.method, "ytdlp"); assert.ok(log.some((l) => /broadcast from its start/.test(l))); assert.ok(log.some((l) => /waits behind the pause/.test(l))); const slugStore = path.join(paths.savedVideosDir, SLUG); assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".")), [], "no staging left"); }); test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once the first part begins, each part's stem recorded", async () => { const p = parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: { everyMinutes: 5 } }); assert.ok(!("error" in p)); if ("error" in p) return; assert.equal(p.preclip?.everyMinutes, 5); assert.equal(p.preclip?.maxChunkMinutes, 20); assert.equal(p.transcribe, true, "preclip implies the landing's transcription"); const off = parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: true, transcribe: false }); assert.ok(!("error" in off) && off.transcribe === false && off.preclip?.everyMinutes === 10); assert.match((parseRecordLiveRequest({ slug: "s", url: "https://rumble.com/v1x-y.html", preclip: { every: 1 } }) as { error: string }).error, /preclip/); const asked: { slug: string; id: string; every: number }[] = []; const log: string[] = []; await recordLiveRun({ paths, request: { slug: SLUG, url: "https://rumble.com/v3ppppp-show.html", preclip: p.preclip }, plan: { url: "https://rumble.com/v3ppppp-show.html", platform: "rumble", id: "v3ppppp" }, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: (l) => void log.push(l), signal: new AbortController().signal, startPreclip: async (slug, id, options) => { asked.push({ slug, id, every: options.everyMinutes }); return { ok: true, jobId: "job-pre" }; }, deps: { refresh: refreshWith(RUMBLE_META), fetchText: async () => DVR, spawn: async ({ args }) => { // The pre-clip is asked for while the recorder runs. await new Promise((r) => setTimeout(r, 10)); await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=60;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, }, }); assert.deepEqual(asked, [{ slug: SLUG, id: "v3ppppp", every: 5 }]); assert.ok(log.some((l) => /Live pre-clip: job job-pre/.test(l))); const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", SLUG, "data", "v3ppppp")); assert.match(rec?.parts[0]?.stem ?? "", /^\.v3ppppp\.live-.+\.ytdlp$/); }); test("yt-dlp cannot start at the start: --no-live-from-start with ffmpeg at index 0; the longest part lands", async () => { const calls: string[][] = []; const s = await recordLiveRun({ paths, request: { slug: SLUG, url: "https://rumble.com/v2bbbbb-show.html" }, plan: { url: "https://rumble.com/v2bbbbb-show.html", platform: "rumble", id: "v2bbbbb" }, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal, deps: { refresh: refreshWith(RUMBLE_META), fetchText: async () => DVR, spawn: async ({ args }) => { calls.push(args); if (calls.length === 1) { return { exitCode: 1, stderrTail: "ERROR: --live-from-start is passed, but there are no formats that can be downloaded from the start.", signalled: false }; } await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=600;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, }, }); assert.equal(calls.length, 2); assert.ok(calls[1]!.includes("--no-live-from-start")); assert.match(calls[1]![calls[1]!.indexOf("--downloader-args") + 1]!, /-live_start_index 0/); assert.equal(s.landed?.seconds, 600); }); test("Rumble refuses yt-dlp: path B — the page's playlist from a browser, recorded by ffmpeg", async () => { const bins: string[] = []; const s = await recordLiveRun({ paths, request: { slug: SLUG, url: "https://rumble.com/v3ccccc-show.html" }, plan: { url: "https://rumble.com/v3ccccc-show.html", platform: "rumble", id: "v3ccccc" }, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal, deps: { refresh: refreshWith(RUMBLE_META, { failFirst: "ERROR: [RumbleEmbed] v3: Unable to download JSON metadata: HTTP Error 403: Forbidden" }), fetchText: async (url) => /playlist\.m3u8/.test(url) ? "#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=1,RESOLUTION=1280x720\nchunklist_720p_i0_DVR.m3u8\n#EXT-X-STREAM-INF:BANDWIDTH=1,RESOLUTION=640x360\nchunklist_360p_i0_DVR.m3u8\n" : DVR, sniff: async () => ({ ok: true, playlists: ["https://rumble.com/live-hls-dvr/key/playlist.m3u8?level=1"] }), spawn: async ({ bin, args }) => { bins.push(bin); assert.equal(args[args.indexOf("-i") + 1], "https://rumble.com/live-hls-dvr/key/chunklist_720p_i0_DVR.m3u8"); assert.equal(args[args.indexOf("-live_start_index") + 1], "0"); await writeFile(args.at(-1)!, "format=mpegts;seconds=300;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, }, }); assert.deepEqual(bins, [paths.ffmpegBin]); assert.equal(s.parts[0]?.method, "browser"); assert.equal(s.landed?.seconds, 300); }); test("a stream that is not live is refused before anything is recorded", async () => { await assert.rejects( recordLiveRun({ paths, request: { slug: SLUG, url: "https://rumble.com/v4ddddd-show.html" }, plan: { url: "https://rumble.com/v4ddddd-show.html", platform: "rumble", id: "v4ddddd" }, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal, deps: { refresh: refreshWith({ ...RUMBLE_META, live_status: "was_live" }), land, handoff }, }), /is not live \(live_status was_live\)/, ); await assert.rejects(stat(path.join(CORPUS, "channels", SLUG, "data", "v4ddddd")), "the record it made is not left behind"); }); test("Kick: the ongoing VOD polled from segment 0 beside the channel's live stream; the longer lands", async () => { const KICK = { handling: "transcribe", url: "https://kick.com/synth/videos", platform: "kick", name: "Synth Kick" } as ChannelConfig; const slug = "synth-kick"; await mkdir(path.join(CORPUS, "channels", slug, "data"), { recursive: true }); await writeFile(path.join(CORPUS, "channels", slug, "config.json"), JSON.stringify(KICK)); const uuid = "01a164b1-0c18-723a-a785-f9637c989507"; const spawned: string[][] = []; const s = await recordLiveRun({ paths, request: { slug, url: "https://kick.com/synth" }, plan: { url: "https://kick.com/synth", platform: "kick", id: null, kickChannel: "synth" }, channelConfig: KICK, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal, deps: { kickVod: async () => ({ id: uuid, url: `https://kick.com/synth/videos/${uuid}` }), refresh: refreshWith({ id: uuid, extractor: "kick:vod", live_status: "is_live", uploader_id: "synth", formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/x/360p30/playlist.m3u8" }], }), spawn: async ({ args }) => { spawned.push(args); await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=1000;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, poll: async (o) => { assert.equal(o.playlistUrl, "https://stream.kick.com/x/360p30/playlist.m3u8"); await writeFile(o.output, "format=mpegts;seconds=5000;"); return { segments: 500, seconds: 5000, gaps: 0, firstSeq: 0, ended: "the VOD has not grown" }; }, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, }, }); assert.equal(spawned.length, 1); assert.ok(spawned[0]!.includes("--no-live-from-start"), "the channel's live stream has no DVR"); assert.equal(spawned[0]!.at(-1), "https://kick.com/synth"); assert.equal(s.id, uuid); assert.equal(s.landed?.seconds, 5000, "the VOD from its start is the longer"); assert.deepEqual(s.parts.map((p) => p.method).sort(), ["vod-poll", "ytdlp"]); }); test("the VOD poller appends new segments in order, counts a gap, and ends when the stream is over", async () => { const out = path.join(ROOT, "poll.ts"); const snapshots = [ "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT\n#EXT-X-MEDIA-SEQUENCE:0\n#EXTINF:10,\n0.ts\n#EXTINF:10,\n1.ts\n#EXT-X-ENDLIST\n", "#EXTM3U\n#EXT-X-PLAYLIST-TYPE:EVENT\n#EXT-X-MEDIA-SEQUENCE:0\n#EXTINF:10,\n0.ts\n#EXTINF:10,\n1.ts\n#EXTINF:10,\n2.ts\n#EXTINF:10,\n3.ts\n#EXT-X-ENDLIST\n", ]; let reads = 0; let clock = 0; const r = await pollEventPlaylist({ playlistUrl: "https://stream.kick.com/x/playlist.m3u8", output: out, onLog: () => {}, signal: new AbortController().signal, liveEnded: () => reads >= 2, idleEndMs: 1e9, idleAfterLiveEndMs: 30_000, fetchText: async () => snapshots[Math.min(reads++, 1)]!, fetchBytes: async (url) => { if (url.endsWith("/2.ts")) throw new Error("HTTP 404"); return new TextEncoder().encode(`[${url.split("/").pop()}]`); }, now: () => clock, wait: async (ms) => { clock += ms; }, }); assert.equal(await readFile(out, "utf8"), "[0.ts][1.ts][3.ts]"); assert.equal(r.segments, 3); assert.equal(r.gaps, 1); assert.equal(r.firstSeq, 0); assert.match(r.ended, /live stream ended/); }); test("Cancel reaches the recorder as SIGINT, and it gets to finish its file", async () => { const out = path.join(ROOT, "sigint.txt"); // The child says "ready" once its SIGINT handler is armed; the Cancel is // sent then, not after a fixed time (a loaded machine starts node slowly). const script = `process.on("SIGINT", () => { require("fs").writeFileSync(${JSON.stringify(out)}, "finalized"); process.exit(0); }); console.log("frame= 1"); console.log("ready"); setInterval(() => {}, 1000);`; const ac = new AbortController(); const lines: string[] = []; const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: (l) => void lines.push(l), signal: ac.signal, label: "t" }); const readyBy = Date.now() + 60_000; // The child's own line (not the echo of its command, which names it too). while (!lines.some((l) => /^(?:\[t\] )?ready\s*$/.test(l))) { assert.ok(Date.now() < readyBy, "the child never said it was ready"); await new Promise((r) => setTimeout(r, 10)); } ac.abort(); const o = await p; assert.equal(o.signalled, true); assert.equal(o.exitCode, 0); assert.equal(await readFile(out, "utf8"), "finalized"); assert.ok(lines.some((l) => /SIGINT/.test(l))); }); test("a cancelled recording still lands what it has", async () => { const ac = new AbortController(); const s = await recordLiveRun({ paths, request: { slug: SLUG, url: "https://rumble.com/v5eeeee-show.html" }, plan: { url: "https://rumble.com/v5eeeee-show.html", platform: "rumble", id: "v5eeeee" }, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: ac.signal, deps: { refresh: refreshWith(RUMBLE_META), fetchText: async () => DVR, spawn: async ({ args }) => { await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=42;"); ac.abort(); return { exitCode: 255, stderrTail: "", signalled: true }; }, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, }, }); assert.equal(s.status, "cancelled"); assert.equal(s.landed?.seconds, 42); const dir = path.join(CORPUS, "channels", SLUG, "data", "v5eeeee"); await stat(path.join(dir, "saved-video.json")); }); test("choosePlaylist: the master's variant by height, else the page's DVR chunklist", async () => { const sig = new AbortController().signal; const failing = async () => { throw new Error("403"); }; assert.equal( await choosePlaylist(["https://cdn/x/chunklist_i1.m3u8", "https://cdn/x/chunklist_i1_DVR.m3u8"], 720, failing, sig), "https://cdn/x/chunklist_i1_DVR.m3u8", ); }); // --- YouTube: separate video + audio streams (2026-10-26) ---------------------------- // // A YouTube live stream with --live-from-start offers only separate DASH video // and audio, and `-f best` failed at once ("Requested format is not // available"). The recorder here is a FAKE yt-dlp (a real child, through the // real spawnRecorder) that refuses a muxed selector the way YouTube's did and, // for `bv*+ba`, writes the two streams as `.f270.mp4` + `.f234.m4a` // from small real files made by ffmpeg — then merges them (FAKE_YT_MODE=finish) // or waits for the SIGINT and exits without merging (FAKE_YT_MODE=hang, a cancel // or a crash before the merge). The landing is the real one with the real // ffprobe; only the audio extraction is stubbed. Nothing is fetched. const FAKE_YTDLP_SOURCE = `#!/usr/bin/env node import { copyFileSync, rmSync } from "node:fs"; import { execFileSync } from "node:child_process"; const argv = process.argv.slice(2); const f = argv[argv.indexOf("-f") + 1]; const out = argv[argv.indexOf("-o") + 1]; const id = argv.at(-1).split("v=")[1]; if (!f.includes("+ba")) { process.stderr.write("ERROR: [youtube] " + id + ": Requested format is not available. Use --list-formats for a list of available formats\\n"); process.exit(1); } const stem = out.replace(/\\.%\\(ext\\)s$/, ""); const v = stem + ".f270.mp4"; const a = stem + ".f234.m4a"; copyFileSync(process.env.FAKE_YT_VIDEO, v); copyFileSync(process.env.FAKE_YT_AUDIO, a); console.log("[download] Destination: " + v); if (process.env.FAKE_YT_MODE === "hang") { process.on("SIGINT", () => process.exit(130)); setInterval(() => {}, 1000); } else { execFileSync("ffmpeg", ["-v", "error", "-y", "-i", v, "-i", a, "-map", "0:v", "-map", "1:a", "-c", "copy", "-f", "mp4", stem + ".temp.mp4"]); execFileSync("mv", [stem + ".temp.mp4", stem + ".mp4"]); rmSync(v); rmSync(a); console.log('[Merger] Merging formats into "' + stem + '.mp4"'); } `; const YT_SLUG = "synth-youtube"; const YT_CONFIG = { handling: "transcribe", url: "https://www.youtube.com/@Synth", platform: "youtube", name: "Synth YT" } as ChannelConfig; const run = promisify(execFile); const MEDIA = path.join(ROOT, "media"); const VIDEO = path.join(MEDIA, "video-only.mp4"); const AUDIO = path.join(MEDIA, "audio-only.m4a"); const FAKE_YTDLP = path.join(ROOT, "fake-yt-dlp.mjs"); // Fragmented, as a DASH live stream's appended segments are. const FRAG = ["-movflags", "frag_keyframe+empty_moov+default_base_moof"]; let ytReady: Promise | null = null; const ytSetup = () => (ytReady ??= (async () => { await mkdir(path.join(CORPUS, "channels", YT_SLUG, "data"), { recursive: true }); await writeFile(path.join(CORPUS, "channels", YT_SLUG, "config.json"), JSON.stringify(YT_CONFIG)); await mkdir(MEDIA, { recursive: true }); await run("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=320x180:rate=25:duration=3", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-g", "25", ...FRAG, "-f", "mp4", VIDEO]); await run("ffmpeg", ["-v", "error", "-y", "-f", "lavfi", "-i", "sine=frequency=440:duration=3", "-c:a", "aac", ...FRAG, "-f", "mp4", AUDIO]); await writeFile(FAKE_YTDLP, FAKE_YTDLP_SOURCE, { mode: 0o755 }); process.env.FAKE_YT_VIDEO = VIDEO; process.env.FAKE_YT_AUDIO = AUDIO; })()); // No heavy-slot gate in a temp root: the merge runs ffmpeg directly. const ytPaths = { ...paths, ytdlpBin: FAKE_YTDLP, monorepoRoot: ROOT }; const realLand = { transcode: async (o: { videoDir: string; fmt: string }) => { await writeFile(path.join(o.videoDir, `audio.${o.fmt}`), "audio"); }, freeBytes: async () => 1e15, }; // What a real live YouTube record carries (the metadata read passes no // --live-from-start, so no generator formats: HLS only), started two hours ago. const YT_META = (id: string) => ({ id, extractor: "youtube", title: "A YouTube live stream", live_status: "is_live", release_timestamp: Math.floor(Date.now() / 1000) - 7200, formats: [ { format_id: "91", protocol: "m3u8_native", height: 144, vcodec: "avc1.4d400c", acodec: "mp4a.40.5", url: "https://manifest.example/91.m3u8" }, { format_id: "95", protocol: "m3u8_native", height: 720, vcodec: "avc1.4d401f", acodec: "mp4a.40.2", url: "https://manifest.example/95.m3u8" }, ], }); async function streamsOf(file: string): Promise<{ v: string | null; a: string | null; seconds: number }> { const { stdout } = await run("ffprobe", ["-v", "error", "-show_format", "-show_streams", "-of", "json", file]); const j = JSON.parse(stdout) as { format: { duration: string }; streams: { codec_type: string; codec_name: string }[] }; return { v: j.streams.find((s) => s.codec_type === "video")?.codec_name ?? null, a: j.streams.find((s) => s.codec_type === "audio")?.codec_name ?? null, seconds: Number(j.format.duration), }; } async function ytRun(id: string, opts: { mode: "finish" | "hang"; separate?: boolean; log?: string[] }) { await ytSetup(); process.env.FAKE_YT_MODE = opts.mode; const ac = new AbortController(); const slugStore = path.join(paths.savedVideosDir, YT_SLUG); let stopper: NodeJS.Timeout | null = null; if (opts.mode === "hang") { // Cancel once both streams are on disk. stopper = setInterval(async () => { const names = await readdir(slugStore).catch(() => [] as string[]); if (names.some((n) => n.endsWith(".f270.mp4")) && names.some((n) => n.endsWith(".f234.m4a"))) ac.abort(); }, 100); } try { return await recordLiveRun({ paths: ytPaths, request: { slug: YT_SLUG, url: `https://www.youtube.com/watch?v=${id}`, ...(opts.separate !== undefined ? { separate: opts.separate } : {}) }, plan: { url: `https://www.youtube.com/watch?v=${id}`, platform: "youtube", id }, channelConfig: YT_CONFIG, cookiePolicy: NO_COOKIES, onLog: (l) => void opts.log?.push(l), signal: ac.signal, deps: { refresh: refreshWith(YT_META(id)), fetchText: async () => { throw new Error("no playlist read is expected"); }, land: realLand, freeBytes: async () => 1e15, handoff }, }); } finally { if (stopper) clearInterval(stopper); } } test("YouTube, muxed only (the 2026-10-26 failure): the fake refuses `best`, and the log says to record separate streams", async () => { const log: string[] = []; await assert.rejects(ytRun("ytmuxed0001", { mode: "finish", separate: false, log }), /nothing was recorded/); assert.ok(log.some((l) => /Requested format is not available/.test(l))); assert.ok(log.some((l) => /"separate": true/.test(l))); }); test("YouTube: separate video + audio by default, merged by yt-dlp, the merged mp4 lands with its sound", async () => { const log: string[] = []; const s = await ytRun("ytmerged001", { mode: "finish", log }); assert.ok(log.some((l) => /bv\*\[height<=720\]\+ba\/b\[height<=720\]\/bv\*\+ba\/b/.test(l)), "the separate selector at 720p"); assert.ok(log.some((l) => /--merge-output-format mp4\/mkv/.test(l))); assert.equal(s.status, "landed"); const dir = path.join(CORPUS, "channels", YT_SLUG, "data", "ytmerged001"); const pointer = await loadSavedVideo(dir); assert.equal(pointer?.file, "source-media.mp4"); const stored = await streamsOf(s.landed!.container!); assert.deepEqual([stored.v, stored.a], ["h264", "aac"]); assert.ok(Math.abs(stored.seconds - 3) < 0.5, `${stored.seconds} s`); const rec = await liveRecordingSidecar.load(dir); assert.equal(rec?.separate, true); assert.notEqual(rec?.parts[0]?.merged, true, "yt-dlp merged it"); const left = (await readdir(path.join(paths.savedVideosDir, YT_SLUG))).filter((n) => n.startsWith(".ytmerged001")); assert.deepEqual(left, [], "no staging left"); }); test("YouTube cancelled mid-record: the two unmerged streams are merged by record-live, and a playable mp4 with sound lands", async () => { const log: string[] = []; const s = await ytRun("ytcancel001", { mode: "hang", log }); assert.equal(s.status, "cancelled"); assert.ok(log.some((l) => /left unmerged/.test(l)), log.join("")); assert.ok(s.landed && s.landed.seconds !== null && Math.abs(s.landed.seconds - 3) < 0.5, JSON.stringify(s.landed)); const dir = path.join(CORPUS, "channels", YT_SLUG, "data", "ytcancel001"); const pointer = await loadSavedVideo(dir); assert.equal(pointer?.file, "source-media.mp4"); const stored = await streamsOf(s.landed!.container!); assert.deepEqual([stored.v, stored.a], ["h264", "aac"]); const rec = await liveRecordingSidecar.load(dir); assert.equal(rec?.status, "cancelled"); assert.equal(rec?.parts[0]?.merged, true); const left = (await readdir(path.join(paths.savedVideosDir, YT_SLUG))).filter((n) => n.startsWith(".ytcancel001")); assert.deepEqual(left, [], "the streams and the merge are gone from staging"); }); test("an earlier run's unmerged streams are merged and landed by the next run", async () => { await ytSetup(); const slugStore = path.join(paths.savedVideosDir, YT_SLUG); await mkdir(slugStore, { recursive: true }); const stem = path.join(slugStore, ".ytleft00001.live-2026-10-25T01-00-00-000Z.ytdlp"); await run("cp", [VIDEO, `${stem}.f270.mp4`]); await run("cp", [AUDIO, `${stem}.f234.mp4`]); const log: string[] = []; // This run records nothing (muxed only, refused): the leftover is what lands. const s = await ytRun("ytleft00001", { mode: "finish", separate: false, log }); assert.equal(s.status, "landed"); assert.ok(log.some((l) => /An earlier recording left 1 part/.test(l))); assert.equal((await streamsOf(s.landed!.container!)).a, "aac"); assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".ytleft00001")), []); }); // --- THE INCIDENT (20 Nov 2026): a from-start attempt that records nothing ---------- // // A YouTube stream asked for `fromStart`, `doNotClean` and a note; yt-dlp // `--live-from-start` exited 1 after seconds with "The downloaded file is // empty" and wrote nothing; the job failed with no retry, no fallback and no // alert. The recorder here is a stub that does exactly that, every time (or // for the first N attempts); the waits between attempts are recorded, never // slept. The listing (controller/liveRecordings.ts) is what a person and an // agent read afterwards. const EMPTY = "[youtube] Sleeping 1.0 seconds ...\nERROR: The downloaded file is empty\n"; const ytChannel = async () => { await mkdir(path.join(CORPUS, "channels", YT_SLUG, "data"), { recursive: true }); await writeFile(path.join(CORPUS, "channels", YT_SLUG, "config.json"), JSON.stringify(YT_CONFIG)); }; // The stream started two hours ago. const ytLiveMeta = (id: string) => ({ ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 7200 }); const ytUrl = (id: string) => `https://www.youtube.com/watch?v=${id}`; type Attempt = (args: string[], n: number, signal: AbortSignal, onLine?: (l: string) => void) => Promise<{ exitCode: number | null; stderrTail: string; signalled: boolean }>; const writesAfter = (failures: number, stderr = EMPTY): Attempt => async (args, n) => { if (n <= failures) return { exitCode: 1, stderrTail: stderr, signalled: false }; const out = args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, ".mp4"); await writeFile(out, "format=mov,mp4;seconds=600;"); return { exitCode: 0, stderrTail: "", signalled: false }; }; async function incidentRun( id: string, attempt: Attempt, opts: { signal?: AbortSignal; onWait?: (ms: number) => void; request?: Record; meta?: Record; deps?: Record; // Slice 2's tries beside the live edge: their 15 min waits pass at once // ("immediate", recorded in `waits`), or never come before the run ends // (the default: no try is made). // A number: that many pass at once, the rest never come. recovery?: "immediate" | number; refresh?: Parameters[1]; requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>; } = {}, ) { await ytChannel(); const calls: string[][] = []; const waits: number[] = []; const log: string[] = []; let recoveryWaits = 0; const run = recordLiveRun({ paths, // The insurance recorder (slice 4) is off unless a case asks for it. request: { slug: YT_SLUG, url: ytUrl(id), fromStart: true, transcribe: true, doNotClean: true, note: "must not lose", insurance: false, ...(opts.request ?? {}) }, plan: { url: ytUrl(id), platform: "youtube", id }, channelConfig: YT_CONFIG, cookiePolicy: NO_COOKIES, onLog: (l) => void log.push(l), signal: opts.signal ?? new AbortController().signal, jobId: `job-${id}`, ...(opts.requestTranscription ? { requestTranscription: opts.requestTranscription } : {}), deps: { refresh: refreshWith(opts.meta ?? ytLiveMeta(id), opts.refresh ?? {}), fetchText: async () => { throw new Error("no playlist read is expected"); }, spawn: async ({ args, signal, onLine }: { args: string[]; signal: AbortSignal; onLine?: (l: string) => void }) => { calls.push(args); return attempt(args, calls.length, signal, onLine); }, wait: async (ms) => { waits.push(ms); opts.onWait?.(ms); }, recoveryWait: (ms: number, sig: AbortSignal) => { const passes = opts.recovery === "immediate" || (typeof opts.recovery === "number" && recoveryWaits++ < opts.recovery); if (passes) { waits.push(ms); return Promise.resolve(); } return new Promise((r) => (sig.aborted ? r() : sig.addEventListener("abort", () => r(), { once: true }))); }, jitter: (ms) => ms, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, shuttingDown: () => false, // The fakes' files are not media: the check passes unless a case says. verifyMerged: async () => ({ ok: true }), verifyScan: async () => ({ ok: true }), ...(opts.deps ?? {}), }, } as Parameters[0]); return { run, calls, waits, log }; } const fromStartArg = (args: string[]) => args.includes("--live-from-start"); const startIndex0 = (args: string[]) => /-live_start_index 0/.test(args[args.indexOf("--downloader-args") + 1] ?? ""); test("THE INCIDENT: 'downloaded file is empty' every time → 3 from-start tries, 3 live-edge tries, then a durable loud failure in the listing", async () => { const id = "exmplincid1"; const { run, calls, waits, log } = await incidentRun(id, writesAfter(Infinity)); await assert.rejects(run, /The downloaded file is empty/); assert.equal(calls.length, 6, `six recorder attempts, not ${calls.length}`); assert.deepEqual(calls.map(fromStartArg), [true, true, true, false, false, false]); assert.deepEqual(calls.map(startIndex0), [true, true, true, false, false, false], "the live edge asks ffmpeg for no index 0"); assert.deepEqual(waits, [60_000, 180_000, 0, 60_000, 180_000], "paced: 0/+60/+180 s, then the same from the live edge"); assert.ok(log.some((l) => /from its start failed 3 times/.test(l)), "the log says the from-start attempts failed"); // The run made data// and recorded nothing into it: the dir goes (an // enumerator would read it as fetched) — the failure record does NOT. await assert.rejects(stat(path.join(CORPUS, "channels", YT_SLUG, "data", id))); const { listLiveRecordings, acknowledgeLiveRecording } = await import("./liveRecordings"); const rows = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows; assert.equal(rows.length, 1); const row = rows[0]!; assert.equal(row.status, "failed"); assert.equal(row.needsAttention, true); assert.equal(row.mustKeep, true); assert.equal(row.attempts, 6); assert.equal(row.jobId, `job-${id}`); assert.match(row.error ?? "", /The downloaded file is empty/); assert.match(row.error ?? "", /6 attempts/); assert.equal(row.parts.length, 6); assert.match(row.parts[0]!.error ?? "", /The downloaded file is empty/); // Acknowledged: it stays listed, and no longer needs anyone. const ack = await acknowledgeLiveRecording(paths, { slug: YT_SLUG, id, by: "test" }); assert.equal(ack.ok, true); const after = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!; assert.equal(after.needsAttention, false); assert.ok(after.acknowledgedAt); }); test("from its start fails twice, the third try records: landed, 3 attempts, nothing to attend to", async () => { const id = "exmplretry1"; const { run, calls, waits } = await incidentRun(id, writesAfter(2)); const s = await run; assert.equal(s.status, "landed"); assert.equal(calls.length, 3); assert.ok(calls.every(fromStartArg)); assert.deepEqual(waits, [60_000, 180_000]); const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id)); assert.equal(rec?.attempts, 3); assert.equal(rec?.fallback, undefined); const { listLiveRecordings } = await import("./liveRecordings"); const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!; assert.equal(row.status, "landed"); assert.equal(row.needsAttention, false); }); test("from its start fails 3 times, the live edge records: landed, the start said LOST, and it needs a person", async () => { const id = "exmpledge01"; const { run, calls, log } = await incidentRun(id, writesAfter(3)); const s = await run; assert.equal(s.status, "landed"); assert.equal(calls.length, 4); assert.equal(fromStartArg(calls[3]!), false); const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id)); assert.equal(rec?.fallback, "live-edge"); assert.ok(rec?.lost && rec.lost.toSeconds !== null && Math.abs(rec.lost.toSeconds - 7200) < 120, JSON.stringify(rec?.lost)); assert.ok(log.some((l) => /are NOT recorded/.test(l)), "the log says what was lost"); const { listLiveRecordings } = await import("./liveRecordings"); const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!; assert.equal(row.fallback, "live-edge"); assert.equal(row.needsAttention, true, "a lost start is a failure needing attention"); }); test("a stream that has ended is not retried; a cancel during a wait stops at once (a must-keep stream's cancel needs a person, another's is quiet)", async () => { const ended = await incidentRun("exmplended1", writesAfter(Infinity, "ERROR: [youtube] exmplended1: This live event has ended.\n")); await assert.rejects(ended.run, /ended/); assert.equal(ended.calls.length, 1); assert.deepEqual(ended.waits, []); const ac = new AbortController(); const cancelled = await incidentRun("exmplcancl1", writesAfter(Infinity), { signal: ac.signal, onWait: () => ac.abort() }); const s = await cancelled.run; assert.equal(s.status, "cancelled"); assert.equal(cancelled.calls.length, 1, "no attempt after the cancel"); const { listLiveRecordings } = await import("./liveRecordings"); const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id: "exmplcancl1" })).rows[0]!; assert.equal(row.status, "cancelled"); assert.equal(row.stoppedBy, "operator"); assert.equal(row.needsAttention, true, "a must-keep stream cancelled: is that what was wanted?"); const ac2 = new AbortController(); const plain = await incidentRun("exmplcancl2", writesAfter(Infinity), { signal: ac2.signal, onWait: () => ac2.abort(), request: { doNotClean: false, note: undefined }, }); assert.equal((await plain.run).status, "cancelled"); const quiet = (await listLiveRecordings(paths, { slug: YT_SLUG, id: "exmplcancl2" })).rows[0]!; assert.equal(quiet.mustKeep, false); assert.equal(quiet.needsAttention, false, "a person's Cancel of a stream that is not must-keep is quiet"); }); test("a healthy recording is untouched: one spawn, no wait, today's argv byte for byte", async () => { const { ytdlpLiveArgs } = await import("../lib/liveCapture"); const { channelExtraArgs } = await import("../ytdlp/channelArgs"); const id = "exmplhealth"; const { run, calls, waits } = await incidentRun(id, writesAfter(0)); const s = await run; assert.equal(s.status, "landed"); assert.equal(calls.length, 1); assert.deepEqual(waits, []); const out = calls[0]![calls[0]!.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, ""); assert.deepEqual( calls[0], ytdlpLiveArgs({ url: ytUrl(id), output: out, fromStart: true, maxHeight: 720, separate: true, waitForVideo: false, channelArgs: [...channelExtraArgs(YT_CONFIG, undefined), "--downloader-args", "ffmpeg_i:-live_start_index 0 -m3u8_hold_counters 180 -seg_max_retry 10"], }), ); }); test("a later recording of the same stream that lands supersedes the earlier failure", async () => { const id = "exmplsuper1"; const first = await incidentRun(id, writesAfter(Infinity)); await assert.rejects(first.run); // The second run holds the whole stream: 600 s of a stream that started // ~600 s before it ended (by the clock). const second = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); assert.equal((await second.run).status, "landed"); const { listLiveRecordings } = await import("./liveRecordings"); const rows = (await listLiveRecordings(paths, { slug: YT_SLUG, id, all: true })).rows; assert.equal(rows.length, 2); const failed = rows.find((r) => r.status === "failed")!; assert.ok(failed.supersededBy, "the failure names the run that landed"); assert.equal(failed.needsAttention, false); }); test("the recorder's progress thinning also catches yt-dlp's numbered stream lines", async () => { const { isProgressLine } = await import("./recordLive"); assert.equal(isProgressLine("1: [download] 12.3% of ~ 1.20GiB at 2.00MiB/s ETA 10:00 (frag 4453/30299)"), true); assert.equal(isProgressLine("2: [download] Destination: x.f140.m4a"), true); assert.equal(isProgressLine("[download] 50.0% of 10MiB"), true); assert.equal(isProgressLine("ERROR: The downloaded file is empty"), false); // DESIGN-4 3: a missing or failed fragment is never thinned out of the log // (the lines as the installed yt-dlp printed them, LOG.md DESIGN-4). for (const l of [ "[download] fragment not found; Skipping fragment 21 ...", "1: [download] Got error: HTTP Error 503. Retrying fragment 40 (1/10)...", "[download] Skipping fragment 7 ...", "WARNING: .ytdl file is corrupt. Restarting from the beginning ...", "WARNING: Inconsistent state of incomplete fragment download. Restarting from the beginning ...", ]) assert.equal(isProgressLine(l), false, l); }); // --- REVIEW-1 (21 Nov 2026): what the first slice got wrong, pinned ---------------- const store = () => path.join(paths.savedVideosDir, YT_SLUG); const outOf = (args: string[]) => args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, ""); const rowOf = async (id: string) => { const { listLiveRecordings } = await import("./liveRecordings"); return (await listLiveRecordings(paths, { slug: YT_SLUG, id, all: true })).rows; }; test("1.4: a normal stream end where yt-dlp exits 1 but the parts hold bytes lands, unchanged: one spawn, no wait, not failed", async () => { const id = "exmplexit01"; const { run, calls, waits, log } = await incidentRun(id, async (args) => { // Both streams written, yt-dlp's merge never ran (exit 1 at the end). await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=3600;"); await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=3600;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 403\nERROR: unable to download fragment\n", signalled: false }; }); const s = await run; assert.equal(s.status, "landed"); assert.equal(calls.length, 1, "not retried"); assert.deepEqual(waits, []); assert.ok(!log.some((l) => /recorded nothing/.test(l))); const row = (await rowOf(id))[0]!; assert.equal(row.status, "landed"); assert.equal(row.error, undefined); assert.equal(row.failureClass, undefined); // What the recorder said at its end is classified on the part (REVIEW-1 2.1 // of live-guard-2); the run is not failed for it. assert.equal(row.parts[0]!.failureClass, "network"); assert.equal(row.needsAttention, false); }); test("1.1: an earlier run's longer from-start part lands, and this run's live-edge part — the only copy of the stream's end — is KEPT, listed, needing a person", async () => { const id = "exmplkeep01"; await mkdir(store(), { recursive: true }); // Run A (an earlier, interrupted run): 3 h from the start, left in staging. const earlier = path.join(store(), `.${id}.live-2026-11-20T01-00-00-000Z.ytdlp.mp4`); await writeFile(earlier, "format=mov,mp4;seconds=10800;"); // Run B: from its start fails 3 times; the live edge records 1.8 h. const { run, calls } = await incidentRun(id, async (args, n) => { if (n <= 3) return { exitCode: 1, stderrTail: EMPTY, signalled: false }; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=6480;"); return { exitCode: 0, stderrTail: "", signalled: false }; }); const s = await run; assert.equal(calls.length, 4); assert.equal(s.landed?.seconds, 10800, "the longest (run A's) lands"); const left = (await readdir(store())).filter((n) => n.startsWith(`.${id}.`)); assert.equal(left.length, 1, `the live-edge part is still on disk: ${left.join(", ")}`); assert.match(left[0]!, /ytdlp-edge-a4\.mp4$/); const row = (await rowOf(id))[0]!; assert.equal(row.keptParts?.length, 1); const k = row.keptParts![0]!; assert.equal(k.run, "this"); assert.equal(k.fromStart, false); assert.equal(k.seconds, 6480); assert.ok(k.bytes > 0 && k.files[0]!.name === left[0]); assert.equal(row.needsAttention, true); assert.match(row.reason, /kept in staging/); const { acknowledgeLiveRecording } = await import("./liveRecordings"); assert.equal((await acknowledgeLiveRecording(paths, { slug: YT_SLUG, id, by: "test" })).ok, true); assert.equal((await rowOf(id))[0]!.needsAttention, false, "acknowledged"); assert.equal((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).length, 1, "an acknowledgement removes nothing"); }); test("1.1: of this run's own parts, a shorter audio-only from-start part is kept beside the landed one (its sound is not proven inside)", async () => { const id = "exmplkeep02"; // Attempt 1 records audio only for 45 s (one stream missing: retried), // attempt 2 records both from the start. const { run, calls } = await incidentRun(id, async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=45;v=none;"); return { exitCode: 1, stderrTail: "2: ERROR: The downloaded file is empty\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); return { exitCode: 0, stderrTail: "", signalled: false }; }); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2); // The audio-only part is NOT taken as inside the landed one: that file's // own sound may be shorter than its length (REVIEW-LF-2 4) — kept, listed. assert.deepEqual((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).map((n) => /\.f140\.m4a$/.test(n)), [true]); const row = (await rowOf(id))[0]!; assert.equal(row.keptParts?.length, 1); assert.equal(row.missingStream, undefined, "the second attempt has both"); assert.equal(row.parts[0]!.missingStream, "video"); assert.equal(row.parts[0]!.failureClass, "partial"); }); test("1.7: one stream with bytes and the other empty is a failed attempt, retried; when every attempt ends so, the row names the missing stream and keeps the parts", async () => { const id = "exmplpart01"; const videoOnly: Attempt = async (args) => { await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=45;a=none;"); return { exitCode: 1, stderrTail: "1: [download] Destination: x\n2: ERROR: The downloaded file is empty\n", signalled: false }; }; const { run, calls, waits } = await incidentRun(id, videoOnly); await assert.rejects(run, /audio stream recorded nothing/); assert.equal(calls.length, 6, "the schedule, as for nothing at all"); assert.deepEqual(waits, [60_000, 180_000, 0, 60_000, 180_000]); const row = (await rowOf(id))[0]!; assert.equal(row.status, "failed"); assert.equal(row.missingStream, "audio"); assert.equal(row.failureClass, "partial"); assert.equal(row.keptParts?.length, 6, "every video-only part stays on disk"); assert.ok(row.keptParts!.every((k) => k.bytes > 0 && /not landable/.test(k.why))); assert.equal((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).length, 6); assert.equal(row.needsAttention, true); }); test("2.1: an editor shutdown stops a recording as `interrupted`, never `cancelled`, and it needs a person", async () => { const ac = new AbortController(); const { run } = await incidentRun("exmplshut01", writesAfter(Infinity), { signal: ac.signal, onWait: () => ac.abort(), request: { doNotClean: false, note: undefined }, deps: { shuttingDown: () => true }, }); const s = await run; assert.equal(s.status, "interrupted"); const row = (await rowOf("exmplshut01"))[0]!; assert.equal(row.status, "interrupted"); assert.equal(row.stoppedBy, "shutdown"); assert.equal(row.needsAttention, true, "interrupted needs a person, must-keep or not"); assert.match(row.reason, /editor shut down/); // Shut down mid-recording with bytes: what was recorded lands, interrupted. const ac2 = new AbortController(); const mid = await incidentRun("exmplshut02", async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); ac2.abort(); return { exitCode: null, stderrTail: "", signalled: true }; }, { signal: ac2.signal, deps: { shuttingDown: () => true } }); const s2 = await mid.run; assert.equal(s2.status, "interrupted"); assert.equal(s2.landed?.seconds, 300); assert.equal((await rowOf("exmplshut02"))[0]!.needsAttention, true); }); test("2.3: only a landed from-start run that covers the stream supersedes; a live-edge run, a fromStart:false run and a short partial never do", async () => { const id = "exmplcover1"; const first = await incidentRun(id, writesAfter(Infinity)); await assert.rejects(first.run); const stillNeeds = async () => (await rowOf(id)).find((r) => r.status === "failed" && !/not landed/.test(r.error ?? ""))!; // (a) asked not from its start: lands, does not supersede. const edge = await incidentRun(id, writesAfter(0), { request: { fromStart: false } }); assert.equal((await edge.run).status, "landed"); assert.equal((await stillNeeds()).needsAttention, true, "a run from now does not hold the start"); assert.equal((await stillNeeds()).supersededBy, undefined); // (b) from its start, 600 s of a stream that has run two hours: the store // holds (a)'s recording, which this one is not proven to hold — not landed, // kept, needing a person. const short = await incidentRun(id, writesAfter(0)); await assert.rejects(short.run, /not landed/); assert.equal((await stillNeeds()).needsAttention, true, "a short partial does not supersede"); const shortRow = (await rowOf(id)).find((r) => r.status === "failed" && /not landed/.test(r.error ?? ""))!; assert.equal(shortRow.keptParts?.length, 1); assert.equal(shortRow.coverage?.covers, false); assert.equal(shortRow.coverage?.basis, "clock"); // (c) the ended stream's own duration, 710 s, against 700 s captured: covers, // so it replaces the stored live-edge recording. const whole = await incidentRun( id, async (args) => { await writeFile(`${args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, "")}.mp4`, "format=mov,mp4;seconds=700;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, { meta: { ...YT_META(id), live_status: "post_live", duration: 710 } }, ); assert.equal((await whole.run).status, "landed"); const failed = await stillNeeds(); assert.ok(failed.supersededBy, "the whole stream, from its start, supersedes"); assert.equal(failed.needsAttention, false); }); test("3.1: ended, private, members-only and a full disk are not retried; the row records the class", async () => { const cases: [string, string, string][] = [ ["exmplcls001", "ERROR: [youtube] exmplcls001: This live event has ended.\n", "ended"], ["exmplcls002", "ERROR: [youtube] exmplcls002: Private video. Sign in if you've been granted access to this video\n", "private"], ["exmplcls003", "ERROR: [youtube] exmplcls003: Join this channel to get access to members-only content like this video, and other exclusive perks.\n", "members"], ["exmplcls004", "ERROR: unable to write data: [Errno 28] No space left on device\n", "disk"], ]; for (const [id, stderr, cls] of cases) { const r = await incidentRun(id, writesAfter(Infinity, stderr)); await assert.rejects(r.run); assert.equal(r.calls.length, 1, `${cls}: one spawn`); assert.deepEqual(r.waits, []); const row = (await rowOf(id))[0]!; assert.equal(row.failureClass, cls); assert.equal(row.needsAttention, true); } }); test("3.1: a 429 or the bot check gets ONE more try after 15 min, then stops and says so", async () => { for (const [id, stderr] of [ ["exmpl429001", "ERROR: [youtube] exmpl429001: HTTP Error 429: Too Many Requests\n"], ["exmplbot001", "ERROR: [youtube] exmplbot001: Sign in to confirm you're not a bot. Use --cookies-from-browser or --cookies for the authentication.\n"], ] as const) { const r = await incidentRun(id, writesAfter(Infinity, stderr)); await assert.rejects(r.run, /429|not a bot/); assert.equal(r.calls.length, 2, "one retry"); assert.deepEqual(r.waits, [15 * 60_000]); assert.ok(r.calls.every(fromStartArg), "the same mode"); assert.ok(r.log.some((l) => /refused again/.test(l) && /not retried again/.test(l))); assert.equal((await rowOf(id))[0]!.failureClass, "rate-limited"); } // Refused once, then the retry records: landed. const ok = await incidentRun("exmpl429002", writesAfter(1, "ERROR: HTTP Error 429: Too Many Requests\n")); assert.equal((await ok.run).status, "landed"); assert.equal(ok.calls.length, 2); }); test("a network or unknown failure keeps the designed schedule", async () => { const r = await incidentRun("exmplnet001", writesAfter(Infinity, "ERROR: [download] Got error: \nERROR: Unable to download fragment\n")); await assert.rejects(r.run); assert.equal(r.calls.length, 6); assert.equal((await rowOf("exmplnet001"))[0]!.failureClass, "network"); }); test("Record again asks what the run was asked: from the start, quality, transcribe, keep, its note and the pre-clip", async () => { const { recordAgainRequest } = await import("./recordLive"); const preclip = { everyMinutes: 10, maxChunkMinutes: 20, overlapSeconds: 5, scan: true, mine: false }; assert.deepEqual( recordAgainRequest({ slug: "s", url: "u", fromStart: true, maxHeight: 480, transcribe: true, doNotClean: true, note: "keep", preclip } as never), { fromStart: true, maxHeight: 480, transcribe: true, doNotClean: true, note: "keep", preclip }, ); }); // --- Kept only when its footage might not be inside the landed file ---------------- // // When the landed file is from the start (or a platform VOD) and covers the // whole stream (streamCoverage, the 2.3 rule), every other part is inside it // and goes, recorded on the row; otherwise every other part with bytes stays. const leftover = async (id: string, seconds: number) => { await mkdir(store(), { recursive: true }); const f = path.join(store(), `.${id}.live-2026-11-20T01-00-00-000Z.ytdlp.mp4`); await writeFile(f, `format=mov,mp4;seconds=${seconds};`); return f; }; test("covered (b): a from-start landing that covers the stream removes an earlier run's partial, nobody is asked", async () => { const id = "exmplcov0b1"; const earlier = await leftover(id, 300); // Its run's row says it was recorded from the start (a part no row // describes may hold the stream's end, and is kept). const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await ytChannel(); await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt: "2026-11-20T01:00:00.000Z", status: "failed", fromStart: true, attempts: 1, mustKeep: true, parts: [{ method: "ytdlp", url: ytUrl(id), fromStart: true, provenStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem: path.basename(earlier).replace(/\.mp4$/, "") }], }); const { run } = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); assert.equal((await run).status, "landed"); await assert.rejects(stat(earlier), "the earlier partial is inside the landed file"); const row = (await rowOf(id))[0]!; assert.equal(row.coverage?.covers, true); assert.equal(row.keptParts, undefined); assert.equal(row.removedParts?.length, 1); assert.equal(row.needsAttention, false); }); test("not covered (c): a landing shorter than the stream keeps the earlier run's part, and needs a person", async () => { const id = "exmplcov0c1"; const earlier = await leftover(id, 300); const { run } = await incidentRun(id, writesAfter(0)); // 600 s of a stream two hours old assert.equal((await run).status, "landed"); assert.ok((await stat(earlier)).size > 0, "kept"); const row = (await rowOf(id))[0]!; assert.equal(row.coverage?.covers, false); assert.equal(row.keptParts?.length, 1); assert.equal(row.keptParts![0]!.run, "earlier"); assert.equal(row.needsAttention, true); }); test("not covered (d): a stream whose length cannot be established keeps every other part", async () => { const id = "exmplcov0d1"; const earlier = await leftover(id, 300); // No start time and no duration: the stream's length is not known. const { run } = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: undefined } }); assert.equal((await run).status, "landed"); assert.ok((await stat(earlier)).size > 0, "kept"); const row = (await rowOf(id))[0]!; assert.equal(row.coverage?.streamSeconds, null); assert.equal(row.coverage?.covers, false); assert.equal(row.keptParts?.length, 1); assert.equal(row.needsAttention, true); }); test("a landing that fails removes nothing: the covered landing's other part and the part itself stay, listed, and the row needs a person", async () => { const id = "exmplland01"; const earlier = await leftover(id, 300); const { run } = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 }, // The store's disk is full: landMediaFile throws. deps: { land: { ...land, freeBytes: async () => 0 } }, }); await assert.rejects(run, /the landing failed/); assert.ok((await stat(earlier)).size > 0, "the earlier part is still on disk"); const mine = (await readdir(store())).filter((n) => n.startsWith(`.${id}.`) && n !== path.basename(earlier)); assert.equal(mine.length, 1, "this run's part is still on disk"); const row = (await rowOf(id))[0]!; assert.equal(row.status, "failed"); assert.equal(row.removedParts, undefined); assert.equal(row.keptParts?.length, 2); assert.equal(row.needsAttention, true); }); // --- SLICE 2: the start recovered beside a live-edge recording --------------------- // // From its start failed three times, the run records from the live edge, and // BESIDE it — never touching it — tries from its start again every 15 min, one // try at a time, at most 8 times. The waits are recorded, never slept. const RECOVERY_WAIT = 15 * 60_000; const isRecovery = (args: string[]) => /\.ytdlp-recover-r\d+$/.test(outOf(args)); // The live-edge recorder: records 1800 s, and runs until `ended` resolves. const edgeUntil = (ended: Promise, seconds = 30) => async (args: string[]) => { await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`); await ended; return { exitCode: 0, stderrTail: "", signalled: false }; }; const failEmpty = { exitCode: 1, stderrTail: EMPTY, signalled: false }; test("slice 2: the live edge records, a from-start try beside it records from the start; unproven (a recovery part), it lands, the live-edge part is kept for a person", async () => { const id = "exmplrecov1"; let endStream!: () => void; const ended = new Promise((r) => (endStream = r)); let active = 0; let maxActive = 0; const edge = edgeUntil(ended); let recoveries = 0; const { run, calls, waits, log } = await incidentRun(id, async (args) => { if (!fromStartArg(args)) return edge(args); active++; maxActive = Math.max(maxActive, active); try { if (!isRecovery(args)) return failEmpty; recoveries++; if (recoveries === 1) return failEmpty; // The second try catches up and runs to the stream's end. await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); endStream(); await new Promise((r) => setTimeout(r, 30)); return { exitCode: 0, stderrTail: "", signalled: false }; } finally { active--; } // The third 15 min wait never comes: the stream ends first. The ended // stream's own duration proves the live edge's 30 s inside the whole. }, { recovery: 2, meta: { ...ytLiveMeta(id), duration: 7200 } }); const s = await run; assert.equal(s.status, "landed"); assert.equal(recoveries, 2, "two tries: the first failed, the second recorded"); assert.equal(calls.length, 6, "3 from its start, 1 live edge, 2 recovery tries"); assert.equal(maxActive, 1, "never two from-start recorders at once"); assert.equal(waits.filter((w) => w === RECOVERY_WAIT).length, 2, "each try after a 15 min wait"); assert.equal(s.landed?.seconds, 7200, "the from-start try's part, the longest, lands"); assert.ok(log.some((l) => /tried again beside the live edge/.test(l))); const row = (await rowOf(id))[0]!; assert.equal(row.fallback, "live-edge"); assert.equal(row.startRecovery?.tries, 2); // A recovery part never carries the proof of start (main's rule): it lands, // but it is not taken as the whole stream — the live-edge part is kept and // a person decides. assert.equal(row.parts.find((p) => p.recovery && (p.seconds ?? 0) > 0)?.provenStart, undefined); assert.ok(row.parts.filter((p) => !p.fromStart).every((p) => p.provenStart === undefined), "nor a live-edge part"); assert.equal(row.coverage?.covers, false); // "recorded" whichever ends first, the try or the live edge (the loop's // later stop no longer turns a try that recorded into "stopped"). assert.equal(row.startRecovery?.state, "recorded"); assert.ok(row.keptParts?.some((k) => /ytdlp-edge-a4$/.test(k.stem)), "the live-edge part is kept"); assert.equal(row.needsAttention, true); }); test("slice 2: bounded — 8 failed tries beside the live edge, one at a time, then no more; the start stays lost and needs a person", async () => { const id = "exmplrecov2"; let recoveries = 0; let active = 0; let maxActive = 0; const { run, calls } = await incidentRun(id, async (args) => { if (!fromStartArg(args)) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=1800;"); // The stream runs until the tries are spent (or 3 s, whichever first). for (let i = 0; i < 300 && recoveries < 8; i++) await new Promise((r) => setTimeout(r, 10)); await new Promise((r) => setTimeout(r, 50)); return { exitCode: 0, stderrTail: "", signalled: false }; } active++; maxActive = Math.max(maxActive, active); if (isRecovery(args)) recoveries++; await new Promise((r) => setTimeout(r, 2)); active--; return failEmpty; }, { recovery: "immediate" }); const s = await run; assert.equal(s.status, "landed"); assert.equal(recoveries, 8, "at most 8 tries"); assert.equal(calls.length, 3 + 1 + 8); assert.equal(maxActive, 1); const row = (await rowOf(id))[0]!; assert.equal(row.startRecovery?.state, "exhausted"); assert.match(row.startRecovery?.lastError ?? "", /downloaded file is empty/); assert.equal(row.needsAttention, true, "the start is still lost"); }); test("slice 2: a try that says the stream is private stops the tries; the stream ending while a try waits stops them too", async () => { const gone = "exmplrecov3"; let tries = 0; const a = await incidentRun(gone, async (args) => { if (!fromStartArg(args)) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=1800;"); for (let i = 0; i < 100 && tries < 1; i++) await new Promise((r) => setTimeout(r, 10)); await new Promise((r) => setTimeout(r, 100)); return { exitCode: 0, stderrTail: "", signalled: false }; } if (isRecovery(args)) { tries++; return { exitCode: 1, stderrTail: `ERROR: [youtube] ${gone}: Private video\n`, signalled: false }; } return failEmpty; }, { recovery: "immediate" }); await a.run; assert.equal(tries, 1, "not tried again"); const r3 = (await rowOf(gone))[0]!; assert.equal(r3.startRecovery?.state, "gave-up"); assert.equal(r3.startRecovery?.failureClass, "private"); // The stream ends while the first try is still 15 min away: no try. const early = "exmplrecov4"; const b = await incidentRun( early, async (args) => { if (fromStartArg(args)) return failEmpty; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=1800;"); await new Promise((r) => setTimeout(r, 20)); return { exitCode: 0, stderrTail: "", signalled: false }; }, // (the default: the 15 min never comes before the stream ends) ); assert.equal((await b.run).status, "landed"); assert.equal(b.calls.filter(isRecovery).length, 0); const r4 = (await rowOf(early))[0]!; assert.equal(r4.startRecovery?.state, "stopped"); assert.equal(r4.needsAttention, true); }); // --- SLICE 3: the stall watchdog acts, and a recorder that dies is restarted -------- // // The watchdog compares the part's files every `watchMs`; no growth for // `stallMs` stops that recorder alone. Then one metadata read: still live → a // new part (its own stem; the stalled part kept until the landing decides), // bounded; ended → land. const hangAfter = (seconds: number) => async (args: string[], _n: number, signal: AbortSignal) => { await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`); await new Promise((r) => (signal.aborted ? r() : signal.addEventListener("abort", () => r(), { once: true }))); return { exitCode: null, stderrTail: "", signalled: true }; }; const FAST_WATCH = { watchMs: 10, stallMs: 80 }; test("slice 3: a stalled recorder is stopped, the stream still live, a new part records: the stalled part was kept until the landing, the whole lands", async () => { const id = "exmplstall1"; let live = true; const hang = hangAfter(300); const { run, calls, waits, log } = await incidentRun( id, async (args, n, signal) => { if (n === 1) return hang(args, n, signal); // The restart records from its start to the end. assert.ok( (await readdir(store())).some((f) => f.startsWith(`.${id}.`) && f.endsWith(".ytdlp.mp4")), "the stalled part is still on disk while the restart records", ); await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); live = false; return { exitCode: 0, stderrTail: "", signalled: false }; }, // (The stream is as old as the stalled part: it had reached the live edge.) { deps: { ...FAST_WATCH, freshFromStart: false }, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 } }, ); const s = await run; assert.equal(s.status, "landed"); assert.equal(calls.length, 2, "the stalled recorder, then one restart"); assert.ok(!fromStartArg(calls[1]!), "restarted at the live edge: the stalled part holds the past (REVIEW-2)"); assert.match(outOf(calls[1]!), /\.ytdlp-r1$/, "the restart's own stem"); assert.ok(!waits.includes(30_000), "the live edge at once (REVIEW-3)"); assert.ok(log.some((l) => /stalled/.test(l))); const row = (await rowOf(id))[0]!; assert.equal(row.parts[0]!.stalled, true); assert.equal(row.restarts?.count, 1); assert.equal(s.landed?.seconds, 7200); assert.ok(row.keptParts?.some((k) => /\.ytdlp$/.test(k.stem)), "the stalled from-start part is kept: the join or a person decides"); assert.equal(row.needsAttention, true); }); test("slice 3: a recorder that exits with bytes while the stream still reads live (twice, 60 s apart) is restarted; a normal end is not", async () => { const id = "exmplexitl1"; let live = true; const { run, calls, waits } = await incidentRun( id, async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); live = false; return { exitCode: 0, stderrTail: "", signalled: false }; }, { deps: FAST_WATCH, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 }, }, ); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2); assert.ok(waits.includes(60_000), "read again a minute later before restarting"); // A normal end (the stream reads ended at once): one spawn, no restart. const plain = await incidentRun("exmplexitl2", writesAfter(0), { deps: FAST_WATCH }); assert.equal((await plain.run).status, "landed"); assert.equal(plain.calls.length, 1); assert.deepEqual(plain.waits, []); }); test("slice 3: restarts are bounded (6 an hour); past it the run WAITS the hour out and goes on (REVIEW-5 note 3), and every part is accounted for", { timeout: 60_000 }, async () => { const id = "exmplbound1"; // Each recorder writes and then stalls; the stream ends after the 9th. let n0 = 0; const { run, calls, waits } = await incidentRun( id, async (args, n, signal) => { n0 = n; return hangAfter(100 * n)(args, n, signal); }, { deps: FAST_WATCH, refresh: { stillLive: () => n0 < 9 }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 100 }, }, ); const s = await run; assert.equal(s.status, "landed"); assert.ok(calls.length >= 8, `past the hour's 6 restarts: ${calls.length} recorders`); assert.ok(waits.some((w) => w > 60_000 && w <= 3_600_000), "the hour waited out"); const row = (await rowOf(id))[0]!; assert.equal(row.restarts?.refused, undefined); assert.ok((row.restarts?.waited ?? 0) >= 1); assert.ok((row.keptParts?.length ?? 0) + (row.removedParts?.length ?? 0) >= 3, "every part is accounted for"); }); test("slice 3: a stall when the stream has ended lands what was recorded, no restart; a stall with nothing written is a failed attempt on the schedule", async () => { const id = "exmplstall2"; const { run, calls } = await incidentRun(id, hangAfter(600), { deps: FAST_WATCH }); assert.equal((await run).status, "landed"); assert.equal(calls.length, 1); const row = (await rowOf(id))[0]!; assert.equal(row.parts[0]!.stalled, true); assert.equal(row.restarts?.count ?? 0, 0); const id2 = "exmplstall3"; const two = await incidentRun( id2, async (args, n, signal) => { if (n === 1) { await new Promise((r) => signal.addEventListener("abort", () => r(), { once: true })); return { exitCode: null, stderrTail: "", signalled: true }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, { deps: FAST_WATCH }, ); assert.equal((await two.run).status, "landed"); assert.equal(two.calls.length, 2); assert.deepEqual(two.waits, [60_000], "the schedule's second from-start attempt"); const r2 = (await rowOf(id2))[0]!; assert.equal(r2.parts[0]!.failureClass, "stalled"); }); // --- SLICE 3: the run the boot pass starts for an interrupted recording ------------- // // `resumeOf` names the interrupted run (its startedAt). The run's own first // read decides: live → record; ended → land what is in staging, or say there // is nothing; unreadable → nothing at all. const interruptedRow = async (id: string, startedAt: string, parts: { stem: string; fromStart: boolean }[] = []) => { const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await ytChannel(); await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt, endedAt: startedAt, status: "interrupted", stoppedBy: "shutdown", fromStart: true, attempts: 1, mustKeep: true, // (A from-start part recorded by this build carries its proof.) parts: parts.map((p) => ({ method: "ytdlp" as const, url: ytUrl(id), fromStart: p.fromStart, ...(p.fromStart ? { provenStart: true } : {}), startedAt, stem: p.stem })), restart: { at: startedAt, by: "boot", state: "asked", jobId: `job-${id}` }, }); }; const oldRow = async (id: string, startedAt: string) => (await rowOf(id)).find((r) => r.startedAt === startedAt)!; test("slice 3 resume: the stream is still live → it records again; the interrupted row says restarted and no longer needs a person", async () => { const id = "exmplresum1"; const t0 = "2026-11-21T08:00:00.000Z"; await interruptedRow(id, t0); // The new run lands 600 s of a stream that started 590 s ago: the whole. const { run, calls, log } = await incidentRun(id, writesAfter(0), { request: { resumeOf: t0 }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 }, }); assert.equal((await run).status, "landed"); assert.equal(calls.length, 1); assert.ok(log.some((l) => /recording again/.test(l))); const old = await oldRow(id, t0); assert.equal(old.restart?.state, "restarted"); assert.equal(old.restart?.jobId, `job-${id}`); assert.ok(old.supersededBy, "the new run holds the whole stream: it supersedes the interruption"); assert.equal(old.needsAttention, false); // A restarted run that lands short leaves the interruption loud (REVIEW-1 1.3). const id2 = "exmplresum5"; await interruptedRow(id2, t0); const short = await incidentRun(id2, writesAfter(0), { request: { resumeOf: t0 } }); assert.equal((await short.run).status, "landed"); const old2 = await oldRow(id2, t0); assert.equal(old2.restart?.state, "restarted"); assert.equal(old2.needsAttention, true, "600 s of a two-hour stream does not carry the interruption"); assert.match(old2.reason, /without the whole stream/); const fresh = (await rowOf(id)).find((r) => r.startedAt !== t0)!; assert.equal(fresh.resumeOf, t0); }); test("slice 3 resume: the stream has ended → no recorder; the interrupted run's part lands, and covering the stream it clears the row", async () => { const id = "exmplresum2"; const t0 = "2026-11-21T08:00:00.000Z"; const stem = `.${id}.live-2026-11-21T08-00-00-000Z.ytdlp`; await mkdir(store(), { recursive: true }); await writeFile(path.join(store(), `${stem}.mp4`), "format=mov,mp4;seconds=3000;"); await interruptedRow(id, t0, [{ stem, fromStart: true }]); const { run, calls } = await incidentRun(id, writesAfter(0), { request: { resumeOf: t0 }, meta: { ...YT_META(id), live_status: "was_live", duration: 3010 }, }); const s = await run; assert.equal(calls.length, 0, "nothing is recorded"); assert.equal(s.status, "landed"); assert.equal(s.landed?.seconds, 3000); const old = await oldRow(id, t0); // What was done, not what was meant (REVIEW-5 B3). assert.equal(old.restart?.state, "landed"); assert.ok(old.supersededBy, "the landed whole supersedes the interruption"); assert.equal(old.needsAttention, false); }); test("slice 3 resume: ended with nothing left says so and still needs a person; an unreadable state starts nothing and writes no row of its own", async () => { const id = "exmplresum3"; const t0 = "2026-11-21T08:00:00.000Z"; await interruptedRow(id, t0); const ended = await incidentRun(id, writesAfter(0), { request: { resumeOf: t0 }, meta: { ...YT_META(id), live_status: "was_live" } }); assert.equal((await ended.run).status, "interrupted"); assert.equal(ended.calls.length, 0); const rows = await rowOf(id); assert.equal(rows.length, 1, "no row of its own"); assert.equal(rows[0]!.restart?.state, "ended"); assert.equal(rows[0]!.needsAttention, true); assert.match(rows[0]!.reason, /end of the stream is NOT recorded/); const id2 = "exmplresum4"; await interruptedRow(id2, t0); // (Every read fails: three over about ten minutes, then unknown.) const unknown = await incidentRun(id2, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1, 2, 3], failWith: "ERROR: [youtube] exmplresum4: Unable to download webpage: The read operation timed out" }, }); await assert.rejects(unknown.run, /timed out/); assert.equal(unknown.calls.length, 0, "never a recording on a guess"); const rows2 = await rowOf(id2); assert.equal(rows2.length, 1, "no failed row of its own"); assert.equal(rows2[0]!.restart?.state, "unknown"); assert.match(rows2[0]!.restart?.reason ?? "", /timed out/); assert.equal(rows2[0]!.needsAttention, true); }); // --- SLICE 4: the insurance recorder beside a from-start recording catching up ------ // // On by default for a stream marked keep before or when the recording starts; // the request's `insurance` overrides. It records the live edge, its own part, // and stops once the from-start recorder has caught up (yt-dlp's `(frag N/M)` // on every stream) plus a margin — or runs the whole stream when asked. const isInsurance = (args: string[]) => /\.ytdlp-insure(?:-r\d+)?$/.test(outOf(args)); const FAST_INSURE = { insurancePollMs: 5, insuranceMarginMs: 10, insuranceGraceMs: 10 }; function insuranceFake(o: { mainSeconds?: number; edgeSeconds?: number; caughtUp?: boolean } = {}) { // (The insurance's part is 30 s by default: the live edge at the stream's end.) let started!: () => void; const insStarted = new Promise((r) => (started = r)); let stoppedBy: "signal" | null = null; let mainReturned!: () => void; const mainDone = new Promise((r) => (mainReturned = r)); const state = { stoppedBy: () => stoppedBy }; const attempt: Attempt = async (args, _n, signal, onLine) => { if (isInsurance(args)) { assert.equal(fromStartArg(args), false, "the insurance records the live edge"); await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${o.edgeSeconds ?? 30};`); started(); await Promise.race([ new Promise((r) => signal.addEventListener("abort", () => r(), { once: true })), mainDone.then(() => new Promise((r) => setTimeout(r, 200))), ]); if (signal.aborted) { stoppedBy = "signal"; return { exitCode: null, stderrTail: "", signalled: true }; } return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Private video\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${o.mainSeconds ?? 7200};`); onLine?.("1: [download] 10.0% of ~ 1.20GiB at 2.00MiB/s ETA 10:00 (frag 100/3000)"); onLine?.("2: [download] 10.0% of ~ 90.0MiB at 1.00MiB/s ETA 10:00 (frag 300/9000)"); await insStarted; if (o.caughtUp !== false) { onLine?.("1: [download] 99.9% of ~ 1.20GiB at 2.00MiB/s ETA 00:01 (frag 2990/3000)"); await new Promise((r) => setTimeout(r, 60)); assert.equal(stoppedBy, null, "not stopped while the audio stream is still behind"); onLine?.("2: [download] 99.9% of ~ 90.0MiB at 1.00MiB/s ETA 00:01 (frag 8990/9000)"); await new Promise((r) => setTimeout(r, 80)); } mainReturned(); if (o.mainSeconds !== undefined && o.mainSeconds < 7200) { return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Private video\n", signalled: false }; } return { exitCode: 0, stderrTail: "", signalled: false }; }; return { attempt, state }; } test("slice 4: a stream marked keep gets the insurance by default; it stops once every stream has caught up, and covered by the whole it goes at landing", { timeout: 60_000 }, async () => { const id = "exmplinsur1"; const f = insuranceFake(); const { run, calls, waits } = await incidentRun(id, f.attempt, { request: { insurance: undefined }, deps: FAST_INSURE, meta: { ...ytLiveMeta(id), duration: 7200 }, }); const s = await run; assert.equal(s.status, "landed"); assert.equal(calls.length, 2, "the from-start recorder and the insurance"); assert.equal(calls.filter(isInsurance).length, 1); assert.equal(f.state.stoppedBy(), "signal", "stopped after the catch-up"); assert.ok(waits.includes(60_000), "a pause after the from-start part's first bytes"); const row = (await rowOf(id))[0]!; const { startTimes, ...ins } = row.insurance ?? ({} as NonNullable); assert.deepEqual(ins, { mode: "catch-up", by: "default", state: "caught-up", starts: 1 }); assert.equal(startTimes?.length, 1, "each start's time (the hourly bound)"); assert.equal(s.landed?.seconds, 7200); assert.equal(row.coverage?.covers, true); assert.ok(row.removedParts?.some((r) => /ytdlp-insure$/.test(r.stem)), "removed only because the landed file holds the whole stream"); assert.equal(row.needsAttention, false); }); test("slice 4: the default is by keep mark (asked, or on the record before); the request overrides either way", { timeout: 60_000 }, async () => { // Not marked, asked: on. const asked = insuranceFake({ caughtUp: false }); const a = await incidentRun("exmplinsur3", asked.attempt, { request: { insurance: true, doNotClean: false, note: undefined }, deps: FAST_INSURE }); await a.run; assert.equal(a.calls.filter(isInsurance).length, 1); assert.equal((await rowOf("exmplinsur3"))[0]!.insurance?.by, "asked"); // Marked on the record before the recording: on by default. const { setDoNotClean } = await import("../lib/doNotClean-server"); const dir = path.join(CORPUS, "channels", YT_SLUG, "data", "exmplinsur4"); await mkdir(dir, { recursive: true }); await setDoNotClean(dir, true, { by: "live-recording", via: "record-live", note: "keep this one" }); const pre = insuranceFake({ caughtUp: false }); const b = await incidentRun("exmplinsur4", pre.attempt, { request: { insurance: undefined, doNotClean: false, note: undefined }, deps: FAST_INSURE }); await b.run; assert.equal(b.calls.filter(isInsurance).length, 1); assert.equal((await rowOf("exmplinsur4"))[0]!.insurance?.by, "default"); // Marked, asked off: none. const off = await incidentRun("exmplinsur5", writesAfter(0), { request: { insurance: false }, deps: FAST_INSURE }); await off.run; assert.equal(off.calls.length, 1); assert.equal((await rowOf("exmplinsur5"))[0]!.insurance, undefined); }); test("slice 4: not marked keep, not asked: no insurance recorder at all", { timeout: 60_000 }, async () => { const id = "exmplinsur6"; const { run, calls } = await incidentRun(id, writesAfter(0), { request: { insurance: undefined, doNotClean: false, note: undefined }, deps: FAST_INSURE }); await run; assert.equal(calls.length, 1); assert.equal((await rowOf(id))[0]!.insurance, undefined); }); test("slice 4: \"whole\" is not stopped by the catch-up, only after the stream's end", { timeout: 60_000 }, async () => { const id = "exmplinsur7"; const f = insuranceFake(); const { run } = await incidentRun(id, f.attempt, { request: { insurance: "whole" }, deps: FAST_INSURE }); await run; const row = (await rowOf(id))[0]!; assert.equal(row.insurance?.mode, "whole"); assert.equal(row.insurance?.state, "ended", "stopped by the grace after the stream ended, not by the catch-up"); }); test("slice 4: the stream removed mid-catch-up — the insurance part holds the end the from-start part never reached: kept, listed, needing a person", { timeout: 60_000 }, async () => { const id = "exmplinsur8"; const f = insuranceFake({ mainSeconds: 3000, edgeSeconds: 1800, caughtUp: false }); const { run } = await incidentRun(id, f.attempt, { request: { insurance: undefined }, deps: FAST_INSURE, refresh: { failAfterFirst: `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video` }, }); const s = await run; assert.equal(s.status, "landed"); assert.equal(s.landed?.seconds, 3000, "the longest lands"); const row = (await rowOf(id))[0]!; assert.equal(row.coverage?.covers, false); const kept = row.keptParts?.find((k) => /ytdlp-insure$/.test(k.stem)); assert.ok(kept, "the insurance part is kept"); assert.equal(kept!.seconds, 1800); assert.equal(row.needsAttention, true); assert.ok((await readdir(store())).some((n) => n.includes(".ytdlp-insure.")), "its file is still on disk"); }); test("slice 4: the insurance knob is parsed and asked again by Record again", { timeout: 60_000 }, async () => { const { recordAgainRequest } = await import("./recordLive"); const ok = parseRecordLiveRequest({ slug: "s", url: "https://www.youtube.com/watch?v=exmplknob01", insurance: "whole" }); assert.equal((ok as { insurance?: unknown }).insurance, "whole"); assert.match((parseRecordLiveRequest({ slug: "s", url: "https://www.youtube.com/watch?v=exmplknob01", insurance: "yes" }) as { error: string }).error, /insurance/); assert.deepEqual(recordAgainRequest({ slug: "s", insurance: false } as never), { insurance: false }); }); // --- SLICE 5: parts joined into one file, proven or not at all --------------------- // // A fake "media" file here also says where it sits in the stream and what it // sounds like (`stream=;seed=`): the fake decode hands back that sound, // a deterministic noise of the stream's own sample index, so the real // alignment (lib/recordingClock.mjs locate) finds parts by their sound. The // fake cut starts at the keyframe at or before the cut (every 2 s); the fake // concat writes the segments it was given (or, `drop`, loses the last). const noiseAt = (seed: number, n: number) => { let x = (Math.imul(n, 2654435761) + Math.imul(seed + 1, 40503)) >>> 0; x ^= x >>> 13; x = Math.imul(x, 0x5bd1e995) >>> 0; x ^= x >>> 15; return x / 4294967296 - 0.5; }; // `vseed`: what its picture shows (default: the same as its sound). type FakeSeg = { stream: number; seconds: number; seed: number; vseed: number }; const readFake = async (file: string): Promise => { const t = await readFile(file, "utf8").catch(() => ""); const segs = /segs=([^;]+)/.exec(t); if (segs) return segs[1]!.split(",").map((x) => { const [s, l, k, v] = x.split(":").map(Number); return { stream: s!, seconds: l!, seed: k!, vseed: v ?? k! }; }); const num = (k: string, d: number) => Number(new RegExp(`(?:^|;)${k}=([\\d.]+)`).exec(t)?.[1] ?? d); const seed = num("seed", 0); return [{ stream: num("stream", 0), seconds: num("seconds", 0), seed, vseed: num("vseed", seed) }]; }; function fakeJoinDeps( o: { drop?: boolean; cutLate?: boolean; cutThrows?: boolean; garblePicture?: boolean; staticPicture?: boolean; ptsJump?: boolean; noTimestamps?: boolean } = {}, ) { return { // The packets' timestamps of [from, from + seconds) of the file: video at // 5 frames a second, audio every 0.02 s, continuous across segments // (`ptsJump`: a 2 s jump at each segment boundary). timestamps: async (file: string, from: number, seconds: number) => { if (o.noTimestamps) return null; const segs = await readFake(file); const bounds: number[] = []; let acc = 0; for (const g of segs) bounds.push((acc += g.seconds)); const shift = (t: number) => (o.ptsJump ? bounds.slice(0, -1).filter((b) => t >= b).length * 2 : 0); const at = (step: number) => { const out: number[] = []; for (let t = Math.ceil(from / step) * step; t < from + seconds; t += step) out.push(Math.round((t + shift(t)) * 1000) / 1000); return out; }; return { video: at(0.2), audio: at(0.02) }; }, // A 32-byte "frame" of the picture at that second (5 frames a second). frame: async (file: string, at: number) => { if (o.staticPicture) return new Uint8Array(32).fill(16); const segs = await readFake(file); let t = at; for (const g of segs) { if (t < g.seconds) { const f = Math.floor((g.stream + t) * 5); return Uint8Array.from({ length: 32 }, (_, i) => Math.floor((noiseAt(g.vseed + 1000, f * 32 + i) + 0.5) * 255)); } t -= g.seconds; } return null; }, decode: async (file: string, from: number, seconds: number, rate: number) => { const segs = await readFake(file); const out = new Float32Array(Math.round(seconds * rate)); for (let i = 0; i < out.length; i++) { let t = from + i / rate; for (const g of segs) { if (t < g.seconds) { out[i] = noiseAt(g.seed, Math.round((g.stream + t) * rate)); break; } t -= g.seconds; } } return out; }, cut: async (file: string, from: number, out: string) => { const [g] = await readFake(file); // A late cut: the stream copy starts after the point asked (a hole). const real = o.cutLate ? Math.ceil(from) + 2 : Math.floor(from / 2) * 2; await writeFile(out, `format=mov,mp4;seconds=${g!.seconds - real};stream=${g!.stream + real};seed=${g!.seed};vseed=${g!.vseed};`); if (o.cutThrows) throw new Error("No space left on device"); return real; }, concat: async (files: string[], out: string) => { const all = (await Promise.all(files.map(readFake))).flat(); const kept = o.drop ? all.slice(0, -1) : all; const total = kept.reduce((n, g) => n + g.seconds, 0); // garblePicture: the joined file's picture after the first segment is // not the segment's (its sound is). await writeFile( out, `format=matroska;seconds=${total};segs=${kept.map((g, i) => `${g.stream}:${g.seconds}:${g.seed}:${o.garblePicture && i > 0 ? g.vseed + 1 : g.vseed}`).join(",")};`, ); }, probe: async (file: string) => { const t = await readFile(file, "utf8").catch(() => ""); if (!/format=/.test(t)) return null; const segs = await readFake(file); return { seconds: segs.reduce((n, g) => n + g.seconds, 0), videoCodec: "h264", audioCodec: "aac", width: 1280, height: 720, sampleRate: 48000, channels: 2 }; }, }; } // An earlier run left a from-start part (stream 0–3000 s) and a live-edge part // whose recorder started `edgeClock` s into the stream and whose sound begins // at `edgeStream` (the live edge lags the clock); the stream has ended; the // boot pass's restart lands what is in staging. async function joinCase( id: string, o: { edgeClock: number; edgeStream: number; edgeSeconds: number; edgeSeed?: number; edgeVseed?: number; duration?: number; deps?: ReturnType; signal?: AbortSignal; shuttingDown?: boolean; before?: () => Promise; refresh?: Parameters[1]; extraDeps?: Record; }, ) { const S0 = 1_790_000_000; const iso = (sec: number) => new Date((S0 + sec) * 1000).toISOString(); const runAt = iso(0); const stamp = runAt.replace(/[:.]/g, "-"); const a = `.${id}.live-${stamp}.ytdlp`; const b = `.${id}.live-${stamp}.ytdlp-edge-a4`; await mkdir(store(), { recursive: true }); await writeFile(path.join(store(), `${a}.mp4`), "format=mov,mp4;seconds=3000;stream=0;seed=7;"); await writeFile( path.join(store(), `${b}.mp4`), `format=mov,mp4;seconds=${o.edgeSeconds};stream=${o.edgeStream};seed=${o.edgeSeed ?? 7};${o.edgeVseed !== undefined ? `vseed=${o.edgeVseed};` : ""}`, ); const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await ytChannel(); await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt: runAt, endedAt: iso(o.edgeClock + o.edgeSeconds), status: "interrupted", stoppedBy: "shutdown", fromStart: true, attempts: 2, mustKeep: true, streamStartedAt: iso(0), parts: [ { method: "ytdlp", url: ytUrl(id), fromStart: true, provenStart: true, startedAt: iso(1), stem: a }, { method: "ytdlp", url: ytUrl(id), fromStart: false, startedAt: iso(o.edgeClock), stem: b }, ], restart: { at: iso(9000), by: "boot", state: "asked" }, }); await o.before?.(); return incidentRun(id, writesAfter(0), { request: { resumeOf: runAt }, meta: { ...YT_META(id), live_status: "was_live", release_timestamp: S0, ...(o.duration ? { duration: o.duration } : {}) }, ...(o.signal ? { signal: o.signal } : {}), ...(o.refresh ? { refresh: o.refresh } : {}), deps: { join: o.deps ?? fakeJoinDeps(), ...(o.shuttingDown ? { shuttingDown: () => true } : {}), ...(o.extraDeps ?? {}) }, }); } const left = async (id: string) => (await readdir(store())).filter((n) => n.startsWith(`.${id}.`)); test("slice 5: an overlap found by its sound — the two parts joined at it, proven, landed whole; both parts removed only after, the joins recorded", async () => { const id = "exmpljoin01"; // The live edge started 20 s behind the clock, at stream second 2401. const { run, calls, log } = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 3000, duration: 5401 }); const s = await run; assert.equal(calls.length, 0); assert.equal(s.status, "landed"); assert.ok(log.some((l) => /Joined 2 parts/.test(l)), log.filter((l) => /join/i.test(l)).join("")); // 3000 s of the first, then the second from its keyframe at 598 s. assert.equal(s.landed?.seconds, 3000 + (3000 - 598)); const row = (await rowOf(id)).find((r) => r.resumeOf)!; assert.equal(row.joins?.length, 1); const j = row.joins![0]!; assert.equal(j.kind, "overlap"); assert.equal(j.basis, "content"); assert.equal(j.at, 3000); assert.equal(j.seconds, 599, "the overlap, found by sound (the clock said 579)"); assert.equal(j.duplicatedSeconds, 1, "the cut starts a keyframe early"); assert.equal(j.cutAt, 599, "where the second part was asked to start"); assert.equal(j.cutFrom, 598, "where its copy really starts"); assert.equal(row.coverage?.covers, true); assert.equal(row.removedParts?.length, 2); assert.ok(row.removedParts!.every((r) => /inside the joined file/.test(r.why))); assert.deepEqual(await left(id), [], "nothing left in staging: the joined file landed, its parts went after"); assert.equal(row.needsAttention, false); const { liveJoinsSidecar } = await import("../lib/mediaImport-server"); const side = await liveJoinsSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id)); assert.equal(side?.segments.length, 2); assert.deepEqual( side!.segments.map((g) => [g.streamFrom, g.streamFromBasis, g.fileFrom, g.joinedFrom, g.joinedTo]), [ [0, "start", 0, 0, 3000], [2401, "content", 598, 3000, 5402], ], ); }); test("slice 5: a gap — joined as they are, the gap stated by the clock, never covering; the row needs a person", async () => { const id = "exmpljoin02"; const { run } = await joinCase(id, { edgeClock: 3600, edgeStream: 3600, edgeSeconds: 1800, duration: 5400 }); const s = await run; assert.equal(s.status, "landed"); assert.equal(s.landed?.seconds, 4800); const row = (await rowOf(id)).find((r) => r.resumeOf)!; assert.equal(row.joins?.[0]?.kind, "gap"); assert.equal(row.joins?.[0]?.basis, "clock"); assert.equal(row.joins?.[0]?.seconds, 600); assert.equal(row.coverage?.covers, false, "a gap never holds the whole stream"); assert.equal(row.needsAttention, true); assert.match(row.reason, /GAP of about 10 min/); const { liveJoinsSidecar } = await import("../lib/mediaImport-server"); const side = await liveJoinsSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id)); assert.deepEqual(side!.segments[1], { stem: side!.segments[1]!.stem, streamFrom: 3600, streamFromBasis: "clock", fileFrom: 0, fileTo: 1800, joinedFrom: 3000, joinedTo: 4800 }); }); test("slice 5: an unprovable join — the sound does not match, or the joined file is not what it should be — lands the longest and keeps the rest", async () => { // (a) The live-edge part's sound is not the stream the first part holds. const id = "exmpljoin03"; const a = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, edgeSeed: 99, duration: 5301 }); const s = await a.run; assert.equal(s.landed?.seconds, 3000, "the longest"); assert.ok(a.log.some((l) => /Not joined/.test(l))); const row = (await rowOf(id)).find((r) => r.resumeOf)!; assert.equal(row.joins, undefined); assert.equal(row.keptParts?.length, 1, "the other part is kept"); assert.equal(row.needsAttention, true); const files = await left(id); assert.equal(files.length, 1); assert.match(files[0]!, /ytdlp-edge-a4\.mp4$/, "no joined or scratch file is left"); // (b) The joined file lost a segment: its length is not its parts' — not proven. const id2 = "exmpljoin04"; const b = await joinCase(id2, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ drop: true }) }); const s2 = await b.run; assert.equal(s2.landed?.seconds, 3000); assert.ok(b.log.some((l) => /not proven/.test(l))); const row2 = (await rowOf(id2)).find((r) => r.resumeOf)!; assert.equal(row2.keptParts?.length, 1); assert.deepEqual((await left(id2)).map((n) => /ytdlp-edge-a4\.mp4$/.test(n)), [true]); }); test("slice 3 / DESIGN-5 1: attempts that each record only one of the two streams — while the stream reads live the recording goes on past the schedule (never ended quietly); when it ends, the row is loud about the missing stream", async () => { const id = "exmplpart02"; let n = 0; const videoOnly: Attempt = async (args) => { n++; await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=45;a=none;"); return { exitCode: 1, stderrTail: "2: ERROR: The downloaded file is empty\n", signalled: false }; }; const { run, calls } = await incidentRun(id, videoOnly, { deps: { ...FAST_WATCH, freshFromStart: false }, refresh: { stillLive: () => n < 9 } }); await run.catch(() => {}); assert.ok(calls.length > 6, `restarted past the schedule while live: ${calls.length}`); const row = (await rowOf(id))[0]!; assert.ok((row.restarts?.count ?? 0) > 0); assert.equal(row.needsAttention, true); }); // --- REVIEW-1 of live-guard-2: the store, containment, and the join's proof -------- // // A container already in the store is never deleted around or replaced by a // part that is not proven to hold it; a part is removed only when THIS landing // stored and verified a file that holds it. const dataDir = (id: string) => path.join(CORPUS, "channels", YT_SLUG, "data", id); const storedSeconds = async (id: string): Promise => { const { savedVideoPath } = await import("../lib/savedVideo"); const p = await loadSavedVideo(dataDir(id)); return p ? ((await fakeProbe(savedVideoPath(p)))?.seconds ?? null) : null; }; const okExit = { exitCode: 0, stderrTail: "", signalled: false }; // Run 1: `seconds` from its start, landed by an editor shutdown. async function landedAtShutdown(id: string, seconds: number, request: Record = {}) { const ac = new AbortController(); const r = await incidentRun( id, async (args) => { await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};stream=0;seed=7;`); ac.abort(); return { exitCode: null, stderrTail: "", signalled: true }; }, { signal: ac.signal, request, deps: { shuttingDown: () => true, join: null } }, ); assert.equal((await r.run).status, "interrupted"); assert.equal(await storedSeconds(id), seconds); } test("landing 1.2/1.1: a later run's live-edge part — longer or shorter — never replaces the stored start and is never deleted: kept, the store untouched, a person asked", async () => { for (const [id, edge] of [ ["exmpllf1201", 7000], ["exmpllf1202", 2000], ] as const) { await landedAtShutdown(id, 3600); const r = await incidentRun(id, async (args, n) => { if (n <= 3) return failEmpty; await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${edge};`); return okExit; }); await assert.rejects(r.run, /not landed/); assert.equal(await storedSeconds(id), 3600, `${id}: the stored start is still the stored container`); assert.ok((await left(id)).some((n) => /ytdlp-edge-a4\.mp4$/.test(n)), `${id}: the live-edge part is still on disk`); const row = (await rowOf(id)).find((x) => x.status === "failed")!; assert.ok(row.keptParts?.some((k) => /ytdlp-edge-a4$/.test(k.stem))); assert.equal(row.needsAttention, true); } }); test("landing 1.1: when the landing keeps the container already in the store, NOTHING is removed", async () => { const id = "exmpllf1101"; const one = await incidentRun(id, async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7300;"); return okExit; }); assert.equal((await one.run).status, "landed"); const earlier = await leftover(id, 300); const two = await incidentRun(id, async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); return okExit; }); await assert.rejects(two.run, /not landed/); assert.equal(await storedSeconds(id), 7300); assert.ok((await stat(earlier)).size > 0, "the earlier part is not removed"); assert.equal((await left(id)).filter((n) => n !== path.basename(earlier)).length, 1, "this run's part is not removed"); const row = (await rowOf(id)).find((x) => x.status === "failed")!; assert.equal(row.removedParts, undefined); assert.equal(row.keptParts?.length, 2); assert.equal(row.needsAttention, true); }); test("REVIEW 1.1(c): a joined file the store's longer container is kept over is not removed, nor are its parts", { timeout: 60_000 }, async () => { const id = "exmpljoin05"; const r = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 3000, duration: 5401, before: async () => { // The store already holds a longer recording (by another way). const { landMediaFile } = await import("./landMedia"); await mkdir(dataDir(id), { recursive: true }); await writeFile(path.join(dataDir(id), "metadata.info.json"), JSON.stringify(YT_META(id))); const src = path.join(ROOT, `${id}-stored.mp4`); await writeFile(src, "format=mov,mp4;seconds=10800;"); await landMediaFile({ paths, slug: YT_SLUG, channelConfig: YT_CONFIG, videoId: id, sourcePath: src, via: "record-live", move: true, onLog: () => {}, signal: new AbortController().signal, deps: land }); }, }); await assert.rejects(r.run, /not landed/); assert.equal(await storedSeconds(id), 10800); const files = await left(id); assert.ok(files.some((n) => /\.joined\.mkv$/.test(n)), `the joined file is kept: ${files.join(", ")}`); assert.ok(files.some((n) => /\.ytdlp\.mp4$/.test(n)) && files.some((n) => /ytdlp-edge-a4\.mp4$/.test(n)), "its parts are kept"); const row = (await rowOf(id)).find((x) => x.resumeOf)!; assert.equal(row.removedParts, undefined); assert.equal(row.needsAttention, true); }); test("REVIEW 1.4: a restart's earlier sibling from its start is not removed on the strength of index 0 — only the coverage rule removes it", { timeout: 60_000 }, async () => { const id = "exmplrv1401"; let live = true; const hang = hangAfter(300); const { run } = await incidentRun( id, async (args, n, signal) => { if (n === 1) return hang(args, n, signal); await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=5000;"); live = false; return okExit; }, { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await run).status, "landed"); const row = (await rowOf(id))[0]!; assert.equal(row.coverage?.covers, false); assert.ok(row.keptParts?.some((k) => /\.ytdlp$/.test(k.stem)), "the stalled first part is kept"); assert.ok((await left(id)).some((n) => /\.ytdlp\.mp4$/.test(n))); }); test("REVIEW 1.7: no join during a shutdown's landing — the longest lands, the rest are kept", { timeout: 60_000 }, async () => { const id = "exmpljoin06"; const ac = new AbortController(); let calls = 0; const deps = fakeJoinDeps(); const counted = { ...deps, decode: async (...a: Parameters) => (calls++, deps.decode(...a)) }; const r = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, signal: ac.signal, shuttingDown: true, deps: counted, // The shutdown comes as the landing begins. extraDeps: { land: { ...land, probe: async (f: string) => (ac.abort(), fakeProbe(f)) } }, }); const s = await r.run; assert.equal(calls, 0, "the join never ran"); assert.equal(s.landed?.seconds, 3000); assert.ok((await left(id)).some((n) => /ytdlp-edge-a4\.mp4$/.test(n)), "the other part is kept"); }); test("REVIEW 1.5/1.6: the join's proof checks the PICTURE, refuses a cut that starts late (a hole), and leaves no scratch when a tool throws", { timeout: 120_000 }, async () => { // (a) The sound is right but the joined file's picture after the join is // not the second part's. const a = await joinCase("exmpljoin07", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ garblePicture: true }) }); await a.run; assert.ok(a.log.some((l) => /Not joined/.test(l) && /picture/.test(l)), a.log.filter((l) => /join/i.test(l)).join("")); assert.equal((await rowOf("exmpljoin07")).find((r) => r.resumeOf)!.keptParts?.length, 1); // (b) The stream copy starts after the cut point: seconds in neither part. const b = await joinCase("exmpljoin08", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ cutLate: true }) }); await b.run; assert.ok(b.log.some((l) => /Not joined/.test(l) && /hole/.test(l))); // (c) The cut throws (a full disk): the scratch it wrote is gone, the longest lands, the rest kept. const c = await joinCase("exmpljoin09", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ cutThrows: true }) }); const sc = await c.run; assert.equal(sc.landed?.seconds, 3000); const files = await left("exmpljoin09"); assert.deepEqual(files.filter((n) => /\.temp\./.test(n)), [], `no scratch left: ${files.join(", ")}`); assert.equal(files.length, 1); }); // --- REVIEW-1 of live-guard-2: the restarts' politeness, the passes, the floor ----- test("REVIEW 2.1(a): a restart refused with a 429 gets ONE more after 15 min, then no more", { timeout: 60_000 }, async () => { const id = "exmplrv2101"; const { run, calls, waits } = await incidentRun( id, async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; } return { exitCode: 1, stderrTail: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests\n", signalled: false }; }, { deps: { ...FAST_WATCH, freshFromStart: false }, refresh: { stillLive: () => true }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 }, }, ); await run; assert.equal(calls.length, 3, "the first recorder, a restart refused with a 429, one more after 15 min"); assert.ok(waits.includes(15 * 60_000)); const row = (await rowOf(id))[0]!; assert.match(row.restarts?.refused ?? "", /rate/); assert.equal(row.needsAttention, true); }); test("REVIEW 2.1(b): a part that died WITH bytes on a 429 is classified and recorded, and restarted only after 15 min", { timeout: 60_000 }, async () => { const id = "exmplrv2102"; let live = true; const { run, calls, waits } = await incidentRun( id, async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 429: Too Many Requests\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); live = false; return okExit; }, { deps: FAST_WATCH, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 }, }, ); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2); assert.ok(waits.includes(15 * 60_000), "the 15 min wait"); assert.ok(!waits.includes(30_000), "not the 30 s pause"); const row = (await rowOf(id))[0]!; assert.equal(row.parts[0]!.failureClass, "rate-limited"); assert.match(row.parts[0]!.error ?? "", /429/); }); test("REVIEW 2.3: the free-space floor is read before a start-recovery try and the insurance start; a spawn that would breach it does not start, and the row says so", { timeout: 60_000 }, async () => { // A recovery try with no room: the disk is full after the run's start. let reads = 0; const r = await incidentRun( "exmplrv2301", async (args, n) => { if (n <= 3) return failEmpty; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); await new Promise((res) => setTimeout(res, 100)); return okExit; }, { recovery: "immediate", deps: { freeBytes: async () => (++reads >= 2 ? 0 : 1e15) } }, ); await r.run; assert.equal(r.calls.filter(isRecovery).length, 0, "no recovery try was started"); const row = (await rowOf("exmplrv2301"))[0]!; assert.equal(row.startRecovery?.state, "gave-up"); assert.equal(row.startRecovery?.failureClass, "disk"); assert.ok(row.spaceHeld?.some((x) => /start recovery/.test(x.what))); assert.equal(row.needsAttention, true); // The insurance with no room. let reads2 = 0; const f = insuranceFake({ caughtUp: false }); const i = await incidentRun( "exmplrv2302", async (args, n, sig, onLine) => Promise.race([f.attempt(args, n, sig, onLine), new Promise((res) => setTimeout(() => res(okExit), 300))]), { request: { insurance: undefined }, deps: { ...FAST_INSURE, freeBytes: async () => (++reads2 >= 2 ? 0 : 1e15) } }, ); await i.run; assert.equal(i.calls.filter(isInsurance).length, 0); const row2 = (await rowOf("exmplrv2302"))[0]!; assert.equal(row2.insurance?.state, "not-started"); assert.ok(row2.spaceHeld?.some((x) => /insurance/.test(x.what))); }); // --- REVIEW-1 of live-guard-2: the insurance that dies, and is re-armed ------------ const until = async (cond: () => boolean, ms = 3000) => { for (let t = 0; t < ms && !cond(); t += 10) await new Promise((r) => setTimeout(r, 10)); }; const abortOf = (signal: AbortSignal) => new Promise((r) => (signal.aborted ? r() : signal.addEventListener("abort", () => r(), { once: true }))); test("REVIEW 3.1: an insurance recorder that dies early reads 'died', never 'to the end', and is started again", { timeout: 60_000 }, async () => { const id = "exmplrv3101"; let starts = 0; let secondStopped = false; const { run, calls, log } = await incidentRun( id, async (args, _n, signal, onLine) => { if (isInsurance(args)) { starts++; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=120;"); if (starts === 1) return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; await abortOf(signal); secondStopped = true; return { exitCode: null, stderrTail: "", signalled: true }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); onLine?.("1: [download] 10.0% of ~ 1.20GiB at 2.00MiB/s ETA 10:00 (frag 100/3000)"); await until(() => starts >= 2); onLine?.("1: [download] 99.9% of ~ 1.20GiB at 2.00MiB/s ETA 00:01 (frag 2990/3000)"); await until(() => secondStopped); return okExit; }, { request: { insurance: undefined }, deps: FAST_INSURE }, ); await run; assert.equal(calls.filter(isInsurance).length, 2, "started again after it died"); assert.ok(log.some((l) => /died early/.test(l))); const row = (await rowOf(id))[0]!; assert.equal(row.insurance?.starts, 2); assert.equal(row.insurance?.state, "caught-up"); assert.ok(!log.some((l) => /recorded the live edge to the end/.test(l))); }); test("REVIEW 3.3: an unreadable state at boot is read three times over about ten minutes; read live, it records; never readable, the row says the stream may be live and unrecorded", { timeout: 60_000 }, async () => { const t0 = "2026-11-21T08:00:00.000Z"; // Read on the third try: it records. const a = "exmplrv3301"; await interruptedRow(a, t0); const ra = await incidentRun(a, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1, 2] } }); assert.equal((await ra.run).status, "landed"); assert.equal(ra.calls.length, 1); assert.deepEqual(ra.waits.slice(0, 2), [120_000, 480_000]); assert.equal((await oldRow(a, t0)).restart?.state, "restarted"); // Never read. const b = "exmplrv3302"; await interruptedRow(b, t0); const rb = await incidentRun(b, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1, 2, 3] } }); await assert.rejects(rb.run); assert.equal(rb.calls.length, 0); assert.deepEqual(rb.waits, [120_000, 480_000]); const ob = await oldRow(b, t0); assert.equal(ob.restart?.state, "unknown"); assert.match(ob.restart?.reason ?? "", /3 reads failed.*may still be live and is NOT being recorded/); assert.equal(ob.needsAttention, true); // A rate limit is not read again. const c = "exmplrv3303"; await interruptedRow(c, t0); const rc = await incidentRun(c, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1], failWith: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests" } }); await assert.rejects(rc.run); assert.deepEqual(rc.waits, []); }); // --- REVIEW-2 of live-guard-2: a stream that reads live is never left unrecorded quietly -- // // A recorder that exits or stalls while an earlier part holds the past is // restarted at the LIVE EDGE (its own stem; the earlier part kept); the // stream is taken as ended only on evidence: the state read says so, or three // live-edge recorders in a row capture nothing. const isEdge = (args: string[]) => !fromStartArg(args); test("REVIEW2 3.1: a caught-up from-start recorder that exits while the stream reads live is restarted at the live edge, never landed quietly", { timeout: 60_000 }, async () => { const id = "exmplr2a301"; let live = true; const { run, calls } = await incidentRun( id, async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=900;"); live = false; return okExit; }, { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; assert.equal(calls.length, 2, "restarted"); assert.ok(isEdge(calls[1]!), "at the live edge: the past is held by the first part"); assert.ok((await left(id)).some((n) => /\.ytdlp-r1\.mp4$/.test(n)) || (await rowOf(id))[0]!.parts.some((p) => p.restart === 1)); }); test("REVIEW2 3.2: a second and a third death while the stream reads live restart again, at the live edge; when the bounds are spent the row says the stream is live and unrecorded", { timeout: 60_000 }, async () => { const id = "exmplr2a302"; let live = true; const deaths = { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; const a = await incidentRun( id, async (args, n) => { await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${n === 1 ? 3000 : 400};`); if (n === 3) live = false; return n === 3 ? okExit : deaths; }, { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 3000 }, }, ); await a.run; assert.equal(a.calls.length, 3, "two deaths, two restarts"); assert.ok(a.calls.slice(1).every(isEdge), "every restart at the live edge"); // Dying again and again while live: the hour's bound is waited out (said), // and it goes on until the stream ends (REVIEW-5 note 3). const id2 = "exmplr2a303"; let k = 0; const b = await incidentRun( id2, async (args) => { k++; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); return deaths; }, { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => k < 10 }, meta: { ...YT_META(id2), release_timestamp: Math.floor(Date.now() / 1000) - 300 } }, ); await b.run.catch(() => {}); assert.ok(b.calls.length > 1 + 6, `past the hour's bound: ${b.calls.length}`); const row = (await rowOf(id2))[0]!; assert.equal(row.restarts?.refused, undefined); assert.ok((row.restarts?.waited ?? 0) >= 1, "the row says it waited"); }); test("REVIEW2 3.1: three live-edge recorders in a row that capture nothing are the evidence the stream ended; still reading live, the row is loud", { timeout: 60_000 }, async () => { const id = "exmplr2a304"; const { run, calls } = await incidentRun( id, async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3000;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; } return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; }, { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => true }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 3000 }, }, ); assert.equal((await run).status, "landed"); assert.equal(calls.length, 4, "the first, then three empty live-edge recorders"); const row = (await rowOf(id))[0]!; assert.match(row.restarts?.refused ?? "", /three live-edge recorders in a row captured nothing/); assert.equal(row.needsAttention, true); }); test("REVIEW2 3.3: the class is read from the recorder's last output — a 429 retried an hour ago does not delay a normal end; ended/private text is checked by a state read", { timeout: 60_000 }, async () => { // (a) A stale 429, then fragments, then the normal end. const a = await incidentRun( "exmplr2a305", async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 429: Too Many Requests\n[download] 40.0% (frag 400/1000)\n[download] 100.0% (frag 1000/1000)\nERROR: fragment 1001 not found\n", signalled: false, }; }, { deps: { ...FAST_WATCH, join: null, merge: fakeMerge } }, ); assert.equal((await a.run).status, "landed"); assert.ok(!a.waits.includes(15 * 60_000), "no 15 min wait for an old 429"); // (b) "Private video" with bytes, but the stream reads live: restarted. let live = true; const b = await incidentRun( "exmplr2a306", async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3000;"); return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Private video. Sign in if you've been granted access\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); live = false; return okExit; }, { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live }, meta: { ...YT_META("exmplr2a306"), release_timestamp: Math.floor(Date.now() / 1000) - 3000 } }, ); await b.run; assert.equal(b.calls.length, 2, "the state was read, it is live: restarted"); }); test("REVIEW2 3.4: the floor before a spawn is max(the floor, twice the largest part so far)", { timeout: 60_000 }, async () => { const id = "exmplr2a307"; const { run, calls } = await incidentRun( id, async (args) => { await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=3000;${"x".repeat(2000)}`); return { exitCode: 1, stderrTail: "ERROR: Connection reset by peer\n", signalled: false }; }, // A floor of 1 kB; 3 kB free; the part is ~2 kB: twice it is not there. { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 3000 }, refresh: { stillLive: () => true } }, ); await run; assert.equal(calls.length, 1, "no restart: twice the largest part is not free"); const row = (await rowOf(id))[0]!; assert.ok(row.spaceHeld?.length); assert.equal(row.needsAttention, true); }); test("REVIEW2 4.1: the insurance on a rate limit: ONE retry after 15 min, then stop", { timeout: 60_000 }, async () => { const id = "exmplr2a308"; let insurers = 0; const { run, waits } = await incidentRun( id, async (args) => { if (isInsurance(args)) { insurers++; return { exitCode: 1, stderrTail: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); await until(() => insurers >= 3, 1500); return okExit; }, { request: { insurance: undefined }, deps: { ...FAST_INSURE, join: null } }, ); await run; assert.equal(insurers, 2, "the first and one retry"); assert.ok(waits.includes(15 * 60_000)); const row = (await rowOf(id))[0]!; assert.match(row.insurance?.reason ?? "", /rate/); }); test("REVIEW2 1.1: a part holding the stream's end is kept by its place on the stream's clock, not by wall-clock ends; never removed on a clock-basis coverage", { timeout: 60_000 }, async () => { // The main from-start part (7140 s) and the insurance end together; the // stream's own duration is 7200 s: 7140 + 72 covers by the tolerance, but // the insurance (from stream second 6000, 1210 s) reaches 7210. const id = "exmplr2a309"; const start = Math.floor(Date.now() / 1000) - 7200; let insStarted = false; const { run } = await incidentRun( id, async (args, _n, signal) => { if (isInsurance(args)) { insStarted = true; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=1210;"); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7140;"); await until(() => insStarted); return okExit; }, { request: { insurance: true }, meta: { ...YT_META(id), release_timestamp: start }, deps: { ...FAST_INSURE, join: null }, refresh: {}, }, ); // The ended stream says 7200 s; its insurance part started 6000 s in. const rows = await rowOf(id); void rows; await run; const row = (await rowOf(id))[0]!; const ins = row.parts.find((p) => p.insurance)!; assert.ok(ins, "the insurance ran"); assert.ok(row.keptParts?.some((k) => /ytdlp-insure$/.test(k.stem)), "kept: it may hold the end"); }); test("REVIEW2 2.1: the join's picture proof compares the two SOURCE parts across the overlap; on a static scene the timestamps' continuity decides; neither, no join", { timeout: 120_000 }, async () => { const base = { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301 }; // (a) The second part's picture is another moment than the first's at the same stream time. const a = await joinCase("exmplr2j101", { ...base, edgeVseed: 55 }); await a.run; assert.ok(a.log.some((l) => /Not joined/.test(l) && /picture/.test(l)), a.log.filter((l) => /join/i.test(l)).join("")); // (b) A static scene, the timestamps continuous: joined. const b = await joinCase("exmplr2j102", { ...base, deps: fakeJoinDeps({ staticPicture: true }) }); await b.run; assert.ok(b.log.some((l) => /Joined 2 parts/.test(l)), b.log.filter((l) => /join/i.test(l)).join("")); // (c) A static scene and a jump in the timestamps at the join: no join. const c = await joinCase("exmplr2j103", { ...base, deps: fakeJoinDeps({ staticPicture: true, ptsJump: true }) }); await c.run; assert.ok(c.log.some((l) => /Not joined/.test(l) && /timestamps/.test(l))); // (d) A static scene and no timestamps to read: neither proof, no join. const d = await joinCase("exmplr2j104", { ...base, deps: fakeJoinDeps({ staticPicture: true, noTimestamps: true }) }); await d.run; assert.ok(d.log.some((l) => /Not joined/.test(l))); assert.equal((await rowOf("exmplr2j104")).find((r) => r.resumeOf)!.keptParts?.length, 1); }); // --- REVIEW-3 of live-guard-2: no span of a live stream left in no part ---------- // // When a recorder dies or stalls: a live-edge recorder at once, AND, when the // kept parts do not reach the live edge, the missing span on the row (loud) // and a from-start recovery beside it until a from-start part reaches where // the live-edge part begins. const isRestart = (args: string[]) => /\.ytdlp-r\d+$/.test(outOf(args)); const hoursAgo = (h: number) => Math.floor(Date.now() / 1000) - h * 3600; test("REVIEW3 3.1: the 20 Nov shape — from its start dies a minute in on a stream 5 h old: the live edge at once, the span said lost, and a from-start recovery beside it until it reaches the live edge", { timeout: 60_000 }, async () => { const id = "exmplr3a301"; let live = true; let recovered = false; let fromStartActive = 0; let maxFromStart = 0; let lostSeen: unknown = null; const { run, calls } = await incidentRun( id, async (args, n, signal) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=60;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; } if (isRecovery(args)) { fromStartActive++; maxFromStart = Math.max(maxFromStart, fromStartActive); lostSeen = (await liveRecordingSidecar.load(dataDir(id)))?.lost ?? null; // It catches up past where the live-edge part begins, and is stopped there. await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=18100;"); await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]); recovered = signal.aborted; fromStartActive--; return { exitCode: null, stderrTail: "", signalled: true }; } // The live-edge restart. await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); await until(() => recovered, 3000); live = false; return okExit; }, // (The recovery begins once the live-edge part holds bytes: REVIEW-4 1.1.) { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, ); await run; assert.ok(calls.some(isRestart) && isEdge(calls.find(isRestart)!), "a live-edge recorder at once"); assert.equal(calls.filter(isRecovery).length, 1, "one from-start recovery"); assert.equal(maxFromStart, 1, "never two from-start captures at once"); assert.ok(lostSeen && (lostSeen as { fromSeconds: number }).fromSeconds === 60, `the span was said lost while it was: ${JSON.stringify(lostSeen)}`); assert.ok(recovered, "the recovery was stopped once it reached the live edge"); const row = (await rowOf(id))[0]!; assert.equal(row.startRecovery?.state, "recovered"); assert.doesNotMatch(row.reason, /in no part/); }); test("REVIEW3 3.1: a from-start recorder that stalls while 2 h behind: the live edge, the span 3 h-5 h said lost, and a recovery", { timeout: 60_000 }, async () => { const id = "exmplr3a302"; let live = true; let recDone = false; const hang = hangAfter(10800); const { run, calls } = await incidentRun( id, async (args, n, signal) => { if (n === 1) return hang(args, n, signal); if (isRecovery(args)) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=18100;"); await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]); recDone = true; return { exitCode: null, stderrTail: "", signalled: true }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); await until(() => recDone, 3000); live = false; return okExit; }, // (The recovery begins once the live-edge part holds bytes: REVIEW-4 1.1.) { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, ); await run; assert.ok(isEdge(calls[1]!) || isEdge(calls[2]!), "a live-edge recorder"); assert.equal(calls.filter(isRecovery).length, 1, "a from-start recovery"); const row = (await rowOf(id))[0]!; assert.equal(row.lost?.fromSeconds, 10800); assert.ok((row.lost?.toSeconds ?? 0) >= 17900); }); test("REVIEW3 3.1: a from-start recorder that had caught up needs no recovery: the live edge only, nothing said lost", { timeout: 60_000 }, async () => { const id = "exmplr3a303"; let live = true; const { run, calls } = await incidentRun( id, async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); live = false; return okExit; }, { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; assert.equal(calls.length, 2); assert.equal(calls.filter(isRecovery).length, 0); assert.equal((await rowOf(id))[0]!.lost, undefined); }); test("REVIEW3 3.2: a restart never stops a working insurance recorder", { timeout: 60_000 }, async () => { const id = "exmplr3a304"; let live = true; let insStarted = false; let insStoppedBeforeRestart = false; let restarted = false; const { run } = await incidentRun( id, async (args, n, signal) => { if (isInsurance(args)) { insStarted = true; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); await abortOf(signal); if (!restarted || live) insStoppedBeforeRestart = true; return { exitCode: null, stderrTail: "", signalled: true }; } if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); await until(() => insStarted); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; } restarted = true; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); await new Promise((r) => setTimeout(r, 200)); live = false; return okExit; }, { request: { insurance: true }, deps: { ...FAST_INSURE, watchMs: 10, stallMs: 5000, join: null }, refresh: { stillLive: () => live } }, ); await run; assert.equal(insStoppedBeforeRestart, false, "the insurance ran on through the restart"); assert.notEqual((await rowOf(id))[0]!.insurance?.reason, "the run fell back to the live edge"); }); test("REVIEW3 1.1: a failed state read after an exit never ends the recording: the live edge is restarted meanwhile", { timeout: 60_000 }, async () => { const id = "exmplr3a305"; let live = true; const { run, calls } = await incidentRun( id, async (args, n) => { if (n === 1) { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); live = false; return okExit; }, // The read after the exit fails (the same network drop). { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live, failReads: [2] } }, ); await run; assert.equal(calls.length, 2, "restarted at the live edge though the state could not be read"); assert.ok(isEdge(calls[1]!)); }); test("REVIEW3 4.1: a live-edge part goes only when the landed file is the media's own length within a minute of the ended stream's duration", { timeout: 60_000 }, async () => { for (const [id, main, gone] of [ ["exmplr3a306", 7140, true], ["exmplr3a307", 7100, false], ] as const) { const f = insuranceFake({ mainSeconds: undefined, edgeSeconds: 30 }); void f; let insStarted = false; const { run } = await incidentRun( id, async (args, _n, signal) => { if (isInsurance(args)) { insStarted = true; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=30;"); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; } await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${main};`); await until(() => insStarted); return okExit; }, { request: { insurance: true }, meta: { ...ytLiveMeta(id), duration: 7200 }, deps: { ...FAST_INSURE, join: null } }, ); await run; const row = (await rowOf(id))[0]!; const kept = row.keptParts?.some((k) => /ytdlp-insure$/.test(k.stem)) ?? false; assert.equal(kept, !gone, `${id}: the live-edge part ${gone ? "goes" : "is kept"}`); } }); // --- DESIGN-3: a from-start recorder is RESUMED IN PLACE --------------------------- // // A fake yt-dlp that keeps a state file as the real one does for a // --live-from-start download (downloader/fragment.py: `.ytdl`, written // after every fragment, removed when the download finishes): on a run with // the same output and the state there, it continues from the saved fragment // (one fragment = 5 s here). SIGINT finishes (the state goes); SIGTERM, a // kill or a crash leaves it. type FakeResume = { exitCode: number | null; stderrTail: string; signalled: boolean }; // Two stream files, as a real separate-streams from-start download has from // its first second (dash.py: each opened, its state written, before any // fragment): the picture `.f136.mp4`, the sound `.f140.m4a`, each // with its own `.ytdl`. A normal end (and SIGINT) merges them into // `.mp4` and removes them, as yt-dlp does without `-k`. const FAKE_V = "f136.mp4"; // One fake fragment: a minute of stream. const FAKE_FRAG_S = 60; const FAKE_A = "f140.m4a"; const dropState = async (args: string[]) => { for (const f of [FAKE_V, FAKE_A]) await rm(`${outOf(args)}.${f}.ytdl`, { force: true }); }; // Nothing provable to reuse either (DESIGN-5 7): a kept fragment gone. const noReuse = async (args: string[]) => rm(`${outOf(args)}.${FAKE_V}-Frag2`, { force: true }); const fakeMerge = async (args: string[]) => { const ins = args.flatMap((a, k) => (a === "-i" ? [args[k + 1]!] : [])); let sec = 0; let bytes = 0; for (const f of ins) { sec = Math.max(sec, (await fakeProbe(f))?.seconds ?? 0); bytes += (await stat(f).catch(() => null))?.size ?? 0; } // (As large as its streams together, as a real merge is.) await writeFile(args[args.length - 1]!, `format=mov,mp4;seconds=${sec};${"x".repeat(bytes)}`); }; function resumableYtdlp( script: (call: { n: number; resumedFrom: number | null; write: (seconds: number) => Promise; writeStream: (kind: "video" | "audio", seconds: number) => Promise; // A stop inside the append of the next fragment: `frac` of it written, // its Frag file kept, the state not rewritten (DESIGN-4 1). tear: (kind: "video" | "audio", frac: number) => Promise; // A line on its output, as the recorder reads it. print: (line: string) => void; signal: AbortSignal; args: string[]; }) => Promise<"die" | "end" | "hang" | FakeResume>, ) { let n = 0; return async (args: string[], _n: number, signal: AbortSignal, onLine?: (l: string) => void): Promise => { n++; const out = outOf(args); const fromStart = fromStartArg(args); const keepFrags = args.includes("--keep-fragments"); const files = { video: `${out}.${FAKE_V}`, audio: `${out}.${FAKE_A}` }; // As yt-dlp's FragmentFD with --keep-fragments: fragment 1 the init, each // later one FAKE_FRAG_S seconds; written to -Frag, appended, THEN // the state. const fragOf = (kind: "video" | "audio", k: number) => k === 1 ? `format=mp4;${kind === "video" ? "a=none;" : "v=none;"}` : `seconds=${FAKE_FRAG_S};#${k};${"x".repeat(k % 5)}`; const count = { video: 0, audio: 0 }; let resumedFrom: number | null = null; if (fromStart) { for (const kind of ["video", "audio"] as const) { const st = await readFile(`${files[kind]}.ytdl`, "utf8").catch(() => null); if (st) count[kind] = JSON.parse(st).downloader.current_fragment.index as number; if (st && kind === "video") resumedFrom = count.video; if (!(await stat(files[kind]).catch(() => null))) { await writeFile(files[kind], ""); await writeFile(`${files[kind]}.ytdl`, JSON.stringify({ downloader: { current_fragment: { index: 0 } } })); count[kind] = 0; } } } const appendOne = async (kind: "video" | "audio") => { const k = ++count[kind]; const frag = `${files[kind]}-Frag${k}`; await writeFile(frag, fragOf(kind, k)); await appendFile(files[kind], fragOf(kind, k)); await writeFile(`${files[kind]}.ytdl`, JSON.stringify({ downloader: { current_fragment: { index: k } } })); if (!keepFrags) await rm(frag, { force: true }); }; const want = (seconds: number) => 1 + Math.floor(seconds / FAKE_FRAG_S); const writeStream = async (kind: "video" | "audio", seconds: number) => { while (count[kind] < want(seconds)) await appendOne(kind); }; const tear = async (kind: "video" | "audio", frac: number) => { const k = count[kind] + 1; const body = fragOf(kind, k); await writeFile(`${files[kind]}-Frag${k}`, body); await appendFile(files[kind], body.slice(0, Math.max(1, Math.floor(body.length * frac)))); }; const write = async (seconds: number) => { if (!fromStart) { await writeFile(`${out}.mp4`, `format=mp4;seconds=${seconds};${"x".repeat(Math.floor(seconds / 60))}`); return; } // Both streams at once, fragment by fragment (two threads in yt-dlp). while (count.video < want(seconds) || count.audio < want(seconds)) { if (count.video < want(seconds)) await appendOne("video"); if (count.audio < want(seconds)) await appendOne("audio"); } }; const finalize = async () => { if (!fromStart) return; await fakeMerge(["-i", files.video, "-i", files.audio, `${out}.mp4`]); for (const f of Object.values(files)) { // `-k`: the streams outlive the merge; without it yt-dlp deletes them. if (!args.includes("-k")) await rm(f, { force: true }); await rm(`${f}.ytdl`, { force: true }); } }; if (fromStart) { // As measured (LOG, DESIGN-5 point 7): the merged file at its final name // and no state — "has already been downloaded", nothing recorded, exit 0; // stream files with bytes and no state — fragment 1 asked again by // Range, a 416, fatal. const st = await readFile(`${files.video}.ytdl`, "utf8").catch(() => null); if (!st && (await stat(`${out}.mp4`).catch(() => null))) { onLine?.(`[download] ${out}.mp4 has already been downloaded`); return okExit; } if (!st && ((await stat(files.video).catch(() => null))?.size ?? 0) > 0 && resumedFrom === null && count.video === 0 && (await stat(`${files.video}-Frag1`).catch(() => null))) { return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 416: Range Not Satisfiable. Giving up after 10 retries\n", signalled: false }; } // REVIEW-6 2, measured against a Range server: a COMPLETE kept fragment // just past the state is asked for by Range past its end — 416, exit 3, // nothing recorded. (A partial one is resumed by Range.) for (const kind of ["video", "audio"] as const) { const next = `${files[kind]}-Frag${count[kind] + 1}`; const have = await readFile(next, "utf8").catch(() => null); if (st && have !== null && have === fragOf(kind, count[kind] + 1)) { return { exitCode: 3, stderrTail: "ERROR: \r[download] Got error: HTTP Error 416: Range Not Satisfiable. Giving up after 10 retries\n", signalled: false }; } } } const what = await script({ n, resumedFrom, write, writeStream, tear, print: (l) => onLine?.(l), signal, args }); if (what === "die") return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; if (what === "end") { await finalize(); return okExit; } if (what === "hang") { await abortOf(signal); // SIGINT finishes the download (merged, the state gone); SIGTERM leaves it. if (signal.reason === "SIGINT") await finalize(); return { exitCode: null, stderrTail: "", signalled: true }; } return what; }; } test("DESIGN-3: a from-start recorder that dies is RESUMED in place: the same stem, the format pinned, from the saved fragment — no new part, no live edge, no recovery", { timeout: 60_000 }, async () => { const id = "exmplres3a01"; let live = true; const resumed: (number | null)[] = []; const fake = resumableYtdlp(async ({ n, resumedFrom, write }) => { resumed.push(resumedFrom); if (n === 1) { await write(3600); return "die"; } await write(7200); live = false; return "end"; }); const { run, calls } = await incidentRun(id, fake, { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2); assert.equal(outOf(calls[1]!), outOf(calls[0]!), "the same output stem"); assert.ok(fromStartArg(calls[1]!), "from its start, resumed"); assert.equal(calls[1]![calls[1]!.indexOf("-f") + 1], "136+140", "the format pinned to the ids on disk"); assert.deepEqual(resumed, [null, 61], "continued from the saved fragment (the init and 60 one-minute fragments)"); assert.equal(calls.filter(isRecovery).length, 0); const row = (await rowOf(id))[0]!; assert.equal(row.parts.length, 1, "no new part"); assert.equal(row.parts[0]!.resumes, 1); assert.equal(row.lost, undefined); assert.equal(row.coverage?.covers, true); }); test("DESIGN-3: a stalled from-start recorder is stopped WITHOUT finishing (SIGTERM) and resumed; a person's Cancel finishes it (SIGINT)", { timeout: 60_000 }, async () => { const id = "exmplres3a02"; let live = true; const reasons: unknown[] = []; const fake = resumableYtdlp(async ({ n, write, signal }) => { if (n === 1) { await write(3000); const r = await (async () => { await abortOf(signal); return signal.reason; })(); reasons.push(r); return { exitCode: null, stderrTail: "", signalled: true }; } await write(7200); live = false; return "end"; }); const wrapped = async (args: string[], n: number, signal: AbortSignal) => { const o = await fake(args, n, signal); return o; }; const { run, calls } = await incidentRun(id, wrapped, { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }); await run; assert.deepEqual(reasons, ["SIGTERM"], "the watchdog's stop keeps the state"); assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place"); // A person's Cancel: SIGINT. const ac = new AbortController(); const id2 = "exmplres3a03"; const seen: unknown[] = []; const c = await incidentRun( id2, resumableYtdlp(async ({ write, signal }) => { await write(600); setTimeout(() => ac.abort(), 10); await abortOf(signal); seen.push(signal.reason); return { exitCode: null, stderrTail: "", signalled: true }; }), { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge } }, ); await c.run; assert.deepEqual(seen, ["SIGINT"]); }); test("DESIGN-3: an editor shutdown leaves the state (SIGTERM), and the boot's restart resumes the SAME stem", { timeout: 60_000 }, async () => { const id = "exmplres3a04"; const ac = new AbortController(); const first = await incidentRun( id, resumableYtdlp(async ({ write, signal }) => { await write(3000); setTimeout(() => ac.abort(), 10); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); const s1 = await first.run; assert.equal(s1.status, "interrupted"); const stem = outOf(first.calls[0]!); assert.ok((await left(id)).some((n) => n.endsWith(".f136.mp4.ytdl")), "the state survived the shutdown"); assert.equal(await storedSeconds(id), null, "nothing landed: the part waits to be resumed"); const t0 = (await rowOf(id))[0]!.startedAt; const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server"); await patchLiveRecordingRow(paths, YT_SLUG, id, t0, (r) => { r.restart = { at: t0, by: "boot", state: "asked" }; }); let live = true; const second = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write }) => { assert.equal(resumedFrom, 51); await write(7200); live = false; return "end"; }), { request: { resumeOf: t0 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await second.run).status, "landed"); assert.equal(outOf(second.calls[0]!), stem, "the boot's restart resumed the interrupted stem"); }); test("DESIGN-3: no state to resume (the part was finished) — the fallback: a live-edge restart", { timeout: 60_000 }, async () => { const id = "exmplres3a05"; let live = true; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(7200); // It finished (the state went), then exited 1. await dropState(args); await noReuse(args); return "die"; } await write(300); live = false; return "end"; }), { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; assert.equal(calls.length, 2); assert.ok(isEdge(calls[1]!), "the live edge: nothing to resume"); }); test("DESIGN-3 5.1: a read refused as private is confirmed a minute later; confirmed, the row says the stream went private while recording; not confirmed, it goes on", { timeout: 60_000 }, async () => { const id = "exmplres3a06"; const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`; const a = await incidentRun( id, resumableYtdlp(async ({ write, args }) => { await write(3000); await dropState(args); return "die"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failAfterFirst: PRIVATE } }, ); await a.run.catch(() => {}); assert.ok(a.waits.includes(60_000), "read again a minute later"); const row = (await rowOf(id))[0]!; assert.equal(row.endedBy?.class, "private"); assert.match(row.reason, /went private or was removed while recording/); assert.equal(row.needsAttention, true); // Refused once, then it reads live: the recording goes on. const id2 = "exmplres3a07"; let live = true; const b = await incidentRun( id2, resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(7200); await dropState(args); return "die"; } await write(300); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [2], failWith: PRIVATE, stillLive: () => live } }, ); await b.run; assert.ok(b.calls.length >= 2, "not ended on one refused read"); }); test("DESIGN-3 fallback (REVIEW-4 3.1): a hole of minutes on a long stream is not under a 1 % tolerance: flat 180 s", { timeout: 60_000 }, async () => { const id = "exmplres3a08"; let live = true; // A 9 h stream; the finished from-start part holds up to 5 min before now. const { run } = await incidentRun( id, resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(9 * 3600 - 300); await dropState(args); await noReuse(args); return "die"; } if (isRecovery(args)) { await write(9 * 3600 + 200); return "end"; } await write(120); await new Promise((r) => setTimeout(r, 200)); live = false; return "end"; }), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 9 * 3600 }, deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; const row = (await rowOf(id))[0]!; assert.ok(row.lost, "the 5 min are said lost (1 % of 9 h, 324 s, would have hidden them)"); }); test("DESIGN-3 fallback (REVIEW-4 1.1): the gap recovery's first try waits until the live-edge part holds bytes", { timeout: 60_000 }, async () => { const id = "exmplres3a09"; let live = true; let edgeBytesAt = Infinity; let recoveryAt = 0; const { run } = await incidentRun( id, resumableYtdlp(async ({ n, write, args, signal }) => { if (n === 1) { await write(60); await dropState(args); await noReuse(args); return "die"; } if (isRecovery(args)) { recoveryAt = Date.now(); await write(18100); await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 2000))]); return { exitCode: null, stderrTail: "", signalled: true }; } await new Promise((r) => setTimeout(r, 150)); await write(300); edgeBytesAt = Date.now(); await until(() => recoveryAt > 0, 3000); await new Promise((r) => setTimeout(r, 100)); live = false; return "end"; }), { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, ); await run; assert.ok(recoveryAt > 0, "a recovery try ran"); assert.ok(recoveryAt >= edgeBytesAt, "it began only once the live-edge part held bytes"); }); test("landing: an index-0 part is not 'inside' a longer index-0 part of the run (a sliding window): kept", async () => { const id = "exmpllfidx1"; const UNSUPPORTED = "ERROR: [youtube] x: --live-from-start is passed, but there are no formats that can be downloaded from the start\n"; const { run } = await incidentRun(id, async (args, n) => { if (n === 1) return { exitCode: 1, stderrTail: UNSUPPORTED, signalled: false }; if (n === 2) { // Audio only, then the video stream failed: retried. await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=300;v=none;"); return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false }; } await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); return okExit; }); assert.equal((await run).status, "landed"); assert.ok((await left(id)).some((n) => /\.f140\.m4a$/.test(n)), "the earlier index-0 part is kept"); const row = (await rowOf(id))[0]!; assert.ok(row.keptParts?.length); }); test("landing: a live-edge part goes only when the landed file is from the start and as long as the ended stream's own duration less a minute", async () => { const KICK = { handling: "transcribe", url: "https://kick.com/synthc/videos", platform: "kick", name: "Synth Kick C" } as ChannelConfig; const slug = "synth-kick-c"; await mkdir(path.join(CORPUS, "channels", slug, "data"), { recursive: true }); await writeFile(path.join(CORPUS, "channels", slug, "config.json"), JSON.stringify(KICK)); // The VOD's length against the ended stream's duration: by the clock // nothing is proven; with a duration the live-edge part goes at exactly // duration - 60 s, not a second short (the tolerance, 100 s here, covers both). // (A VOD whose poll did not begin at segment 0 is not proven: kept.) for (const [uuid, duration, vod, gone, firstSeq] of [ ["01a164b1-0c18-723a-a785-f9637c98bbb1", null, 5000, false, 0], ["01a164b1-0c18-723a-a785-f9637c98bbb2", 10000, 9940, true, 0], ["01a164b1-0c18-723a-a785-f9637c98bbb3", 10000, 9939, false, 0], ["01a164b1-0c18-723a-a785-f9637c98bbb4", 10000, 9990, false, 40], ] as const) { let reads = 0; const meta = { id: uuid, extractor: "kick:vod", uploader_id: "synthc", release_timestamp: Math.floor(Date.now() / 1000) - (duration ?? 5000), formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/y/360p30/playlist.m3u8" }] }; await recordLiveRun({ paths, request: { slug, url: "https://kick.com/synthc" }, plan: { url: "https://kick.com/synthc", platform: "kick", id: null, kickChannel: "synthc" }, channelConfig: KICK, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: new AbortController().signal, deps: { kickVod: async () => ({ id: uuid, url: `https://kick.com/synthc/videos/${uuid}` }), // Live at the first read; ended (with its duration, when known) after. refresh: async (cwd: string, args: string[]) => { reads++; const o = args[args.indexOf("-o") + 1]!; const m = reads === 1 ? { ...meta, live_status: "is_live" } : { ...meta, live_status: "was_live", ...(duration ? { duration } : {}) }; await writeFile(path.join(cwd, path.dirname(o), "metadata.info.json"), JSON.stringify(m)); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }, spawn: async ({ args }) => { await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=30;"); return { exitCode: 0, stderrTail: "", signalled: false }; }, poll: async (o) => { await writeFile(o.output, `format=mpegts;seconds=${vod};`); return { segments: 500, seconds: vod, gaps: 0, firstSeq, ended: "the VOD has not grown" }; }, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, shuttingDown: () => false, }, }); const files = (await readdir(path.join(paths.savedVideosDir, slug))).filter((n) => n.startsWith(`.${uuid}.`)); assert.equal(files.length === 0, gone, `${uuid}: the channel's live-edge part ${gone ? "goes" : "is kept"}`); const { listLiveRecordings } = await import("./liveRecordings"); const row = (await listLiveRecordings(paths, { slug, id: uuid, all: true })).rows[0]!; if (gone) { // (covered (a)'s guarantees: removed, said why, nothing kept, nobody asked.) assert.equal(row.coverage?.covers, true); assert.equal(row.removedParts?.length, 1); assert.match(row.removedParts![0]!.why, /holds the whole stream/); assert.equal(row.keptParts, undefined); assert.equal(row.needsAttention, false); } else { assert.equal(row.keptParts?.length, 1); assert.equal(row.needsAttention, true); } } }); // --- REVIEW-LF-1 ------------------------------------------------------------------ // An earlier run's row describing one part of the stream (a leftover in staging). async function rowFor(id: string, stem: string, part: Record) { const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await ytChannel(); await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt: "2026-11-20T01:00:00.000Z", status: "failed", fromStart: true, attempts: 1, mustKeep: true, parts: [{ method: "ytdlp", url: ytUrl(id), fromStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem, ...part }], } as never); } const UNSUPPORTED = "ERROR: [youtube] x: --live-from-start is passed, but there are no formats that can be downloaded from the start\n"; // From its start unsupported: an index-0 part records `seconds`. const index0Run = (seconds: number) => async (args: string[], n: number) => { if (n === 1) return { exitCode: 1, stderrTail: UNSUPPORTED, signalled: false }; await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`); return okExit; }; test("LF finding 1: an index-0 part is not proven from the start — it never replaces a stored container nor removes a proven from-start part, on length alone", async () => { // (a) A stored container from the start; an index-0 run "covers" by length. const a = "exmpllfidx2"; await landedAtShutdown(a, 3600); const r = await incidentRun(a, index0Run(7200), { meta: { ...YT_META(a), live_status: "post_live", duration: 7210 } }); await assert.rejects(r.run, /not landed/); assert.equal(await storedSeconds(a), 3600, "the stored start stays"); // (b) An earlier proven from-start part; an index-0 landing that "covers" leaves it. const b = "exmpllfidx3"; const earlier = await leftover(b, 300); await rowFor(b, path.basename(earlier).replace(/\.mp4$/, ""), { provenStart: true }); const rb = await incidentRun(b, index0Run(7200), { meta: { ...YT_META(b), live_status: "post_live", duration: 7210 } }); assert.equal((await rb.run).status, "landed"); assert.ok((await stat(earlier)).size > 0, "the proven from-start part is kept"); assert.equal((await rowOf(b)).find((x) => x.status === "landed")!.coverage?.covers, false); }); test("LF finding 2: a part holding video is never 'inside' a longer audio-only landed part", async () => { const id = "exmpllfvid1"; const ac = new AbortController(); const { run } = await incidentRun( id, async (args, n) => { if (n === 1) { // Only its audio stream wrote (3 h of backlog); the video failed. await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=10800;v=none;"); return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false }; } // Both streams, merged, 1 h — then a Cancel. await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3600;"); ac.abort(); return { exitCode: null, stderrTail: "", signalled: true }; }, { signal: ac.signal, request: { doNotClean: false, note: undefined } }, ); await run; assert.ok((await left(id)).some((n) => /ytdlp-a2\.mp4$/.test(n)), `the only video stays: ${(await left(id)).join(", ")}`); }); test("LF note 3: no pointer, but a source-media file in the store: a container is stored (fail closed) — nothing lands over it", async () => { const id = "exmpllfstr1"; const { savedVideoDir } = await import("../lib/savedVideo"); const dir = savedVideoDir(paths, YT_CONFIG, YT_SLUG, id); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, "source-media.mp4"), "format=mov,mp4;seconds=9000;"); const r = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); await assert.rejects(r.run, /not landed/); assert.equal(await readFile(path.join(dir, "source-media.mp4"), "utf8"), "format=mov,mp4;seconds=9000;", "the unnamed container is untouched"); }); test("LF note 6: a run asked to keep the stream marks it even when nothing landed", async () => { const id = "exmpllfkep1"; await landedAtShutdown(id, 3600, { doNotClean: false, note: undefined }); assert.equal(await isDoNotClean(dataDir(id)), false); const r = await incidentRun(id, async (args, n) => { if (n <= 3) return failEmpty; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=2000;"); return okExit; }); await assert.rejects(r.run, /not landed/); assert.equal(await isDoNotClean(dataDir(id)), true); }); test("LF note 5: a row's part with no proven-start mark (an older row) is not removed under coverage; marked, it is", async () => { const id = "exmpllfold1"; const earlier = await leftover(id, 300); await rowFor(id, path.basename(earlier).replace(/\.mp4$/, ""), {}); const r = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); assert.equal((await r.run).status, "landed"); assert.ok((await stat(earlier)).size > 0, "kept: not proven from its start"); }); test("LF 9/10: landing 1.1 with a part meant for removal — kept when the store keeps its own", async () => { const id = "exmpllf1102"; const one = await incidentRun(id, async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7300;"); return okExit; }); assert.equal((await one.run).status, "landed"); const earlier = await leftover(id, 300); await rowFor(id, path.basename(earlier).replace(/\.mp4$/, ""), { provenStart: true }); const two = await incidentRun(id, async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); return okExit; }); await assert.rejects(two.run, /not landed/); assert.ok((await stat(earlier)).size > 0); const row = (await rowOf(id)).find((x) => x.status === "failed" && /not landed/.test(x.error ?? ""))!; assert.ok(row.keptParts?.some((k) => /kept: nothing was landed/.test(k.why)), "the part meant for removal is kept and says so"); assert.equal(row.removedParts, undefined); }); test("LF 9: with an empty store a short from-start partial lands and does not supersede (2.3's guarantee)", async () => { const id = "exmpllf2301"; const first = await incidentRun(id, writesAfter(Infinity)); await assert.rejects(first.run); const short = await incidentRun(id, writesAfter(0)); assert.equal((await short.run).status, "landed"); assert.ok(short.log.some((l) => /does not supersede/.test(l))); const rows = await rowOf(id); assert.equal(rows.find((r) => r.status === "landed")!.coverage?.covers, false); assert.equal(rows.find((r) => r.status === "failed")!.needsAttention, true); }); // --- REVIEW-LF-2 ------------------------------------------------------------------ // Rumble: `--live-from-start` is ffmpeg at the DVR playlist's first LISTED // segment. A run whose playlist read still lists segment 1 is from the start; // one that began after the window slid is not. const DVR_SLID = "#EXTM3U\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:151\n#EXTINF:2,\nm_151.ts\n#EXTINF:2,\nm_152.ts\n"; async function rumbleRun(id: string, o: { dvr: string; seconds: number; duration: number; stop?: "shutdown" }) { const ac = new AbortController(); let reads = 0; const meta = { ...RUMBLE_META, id, live_status: "is_live", timestamp: Math.floor(Date.now() / 1000) - o.duration }; return recordLiveRun({ paths, request: { slug: SLUG, url: `https://rumble.com/${id}-show.html` }, plan: { url: `https://rumble.com/${id}-show.html`, platform: "rumble", id }, channelConfig: CONFIG, cookiePolicy: NO_COOKIES, onLog: () => {}, signal: ac.signal, deps: { refresh: async (cwd: string, args: string[]) => { reads++; const out = args[args.indexOf("-o") + 1]!; const m = reads === 1 ? meta : { ...meta, live_status: "was_live", duration: o.duration }; await writeFile(path.join(cwd, path.dirname(out), "metadata.info.json"), JSON.stringify(m)); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }, fetchText: async () => o.dvr, spawn: async ({ args }) => { await writeFile(args[args.indexOf("-o") + 1]!, `format=mpegts;seconds=${o.seconds};`); if (o.stop) { ac.abort(); return { exitCode: null, stderrTail: "", signalled: true }; } return { exitCode: 0, stderrTail: "", signalled: false }; }, land, ...VERIFY_OK, freeBytes: async () => 1e15, handoff, shuttingDown: () => o.stop === "shutdown", }, }); } const rumbleStored = async (id: string) => { const { savedVideoPath } = await import("../lib/savedVideo"); const p = await loadSavedVideo(path.join(CORPUS, "channels", SLUG, "data", id)); return p ? ((await fakeProbe(savedVideoPath(p)))?.seconds ?? null) : null; }; const rumbleLeft = async (id: string) => (await readdir(path.join(paths.savedVideosDir, SLUG)).catch(() => [] as string[])).filter((n) => n.startsWith(`.${id}.`)); test("LF2 finding 1 (Rumble): a from-start run that began after the DVR window slid is not proven — it never replaces the stored start nor removes run 1's part", async () => { // (a) Run 1 from the true start, landed by a shutdown; run 2 after the slide "covers" by length. const a = "v7lfslid1"; await rumbleRun(a, { dvr: DVR, seconds: 3600, duration: 10000, stop: "shutdown" }); assert.equal(await rumbleStored(a), 3600); await assert.rejects(rumbleRun(a, { dvr: DVR_SLID, seconds: 9950, duration: 10000 }), /not landed/); assert.equal(await rumbleStored(a), 3600, "the stored start stays"); // (b) Run 1's part in staging (its row: proven); run 2 after the slide lands, run 1's part is kept. const b = "v7lfslid2"; const stem = `.${b}.live-2026-11-20T01-00-00-000Z.ytdlp`; await mkdir(path.join(paths.savedVideosDir, SLUG), { recursive: true }); await writeFile(path.join(paths.savedVideosDir, SLUG, `${stem}.ts`), "format=mpegts;seconds=3600;"); const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await upsertLiveRecordingRow(paths, SLUG, { id: b, url: `https://rumble.com/${b}-show.html`, platform: "rumble", startedAt: "2026-11-20T01:00:00.000Z", status: "interrupted", fromStart: true, attempts: 1, mustKeep: false, parts: [{ method: "ytdlp", url: "u", fromStart: true, provenStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem }], } as never); const s = await rumbleRun(b, { dvr: DVR_SLID, seconds: 9950, duration: 10000 }); assert.equal(s.status, "landed"); assert.ok((await rumbleLeft(b)).some((n) => n === `${stem}.ts`), "run 1's part is kept"); }); test("LF2 finding 1 (YouTube): a from-start run of a stream older than 120 h is not proven (the generator starts 120 h back)", async () => { const id = "exmpllf120h"; await landedAtShutdown(id, 3600); const old = Math.floor(Date.now() / 1000) - 121 * 3600; // 7200 s of a stream whose ended duration is 7210 s: it "covers" and is longer than the stored hour. const r = await incidentRun( id, async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); return okExit; }, { meta: { ...YT_META(id), release_timestamp: old, live_status: "post_live", duration: 7210 } }, ); await assert.rejects(r.run, /not landed/); assert.equal(await storedSeconds(id), 3600); }); test("LF2 note 3: a pointer whose file is gone is 'stored, unknown' when the store folder holds a source-media file; with the folder empty or absent it is an empty store", async () => { const { savedVideoDir } = await import("../lib/savedVideo"); // (a) The pointer names source-media.mp4 (gone); source-media.mkv is there. const a = "exmpllfptr1"; await landedAtShutdown(a, 3600); const dirA = savedVideoDir(paths, YT_CONFIG, YT_SLUG, a); const named = (await readdir(dirA)).find((n) => n.startsWith("source-media."))!; await rm(path.join(dirA, named)); await writeFile(path.join(dirA, "source-media.mkv"), "format=matroska;seconds=5000;"); const ra = await incidentRun(a, writesAfter(0), { meta: { ...YT_META(a), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); await assert.rejects(ra.run, /not landed/); assert.ok((await stat(path.join(dirA, "source-media.mkv"))).size > 0); // (b) The pointer names a file that is gone, the folder empty: lands as an empty store. const b = "exmpllfptr2"; await landedAtShutdown(b, 3600); const dirB = savedVideoDir(paths, YT_CONFIG, YT_SLUG, b); await rm(dirB, { recursive: true, force: true }); const rb = await incidentRun(b, writesAfter(0), { meta: { ...YT_META(b), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); assert.equal((await rb.run).status, "landed"); }); test("LF2 note 4: an audio-only part is not 'inside' a longer part whose own audio may be shorter", async () => { const id = "exmpllfaud1"; const ac = new AbortController(); const { run } = await incidentRun( id, async (args, n) => { if (n === 1) { // Only its audio (1 h), then the video failed. await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=3600;v=none;"); return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false }; } // Both, 4 h on the container's length (its audio may be shorter) — a Cancel. await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=14400;"); ac.abort(); return { exitCode: null, stderrTail: "", signalled: true }; }, { signal: ac.signal, request: { doNotClean: false, note: undefined } }, ); await run; assert.ok((await left(id)).some((n) => /\.f140\.m4a$/.test(n)), "the audio-only part is kept"); }); test("LF2 note 7: with a container stored, a zero-byte file and a fragments-only part's .ytdl are not removed by a run that lands nothing", async () => { const id = "exmpllfg7a1"; await landedAtShutdown(id, 3600); await mkdir(store(), { recursive: true }); const zero = path.join(store(), `.${id}.live-2026-11-20T02-00-00-000Z.ytdlp.f18.mp4`); await writeFile(zero, ""); const frag = `.${id}.live-2026-11-20T03-00-00-000Z.ytdlp.f18.mp4`; await writeFile(path.join(store(), `${frag}-Frag7`), "bytes of a fragment"); await writeFile(path.join(store(), `${frag}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: 7 } } })); const r = await incidentRun(id, async (args, n) => { if (n <= 3) return failEmpty; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=2000;"); return okExit; }); await assert.rejects(r.run, /not landed/); assert.ok(await stat(zero).then(() => true, () => false), "the zero-byte file stays"); assert.ok(await stat(path.join(store(), `${frag}.ytdl`)).then(() => true, () => false), "the .ytdl stays"); }); test("LF3 note 5: a proven, same-kind, shorter part of this run IS removed after the landing (inside the landed part)", async () => { const id = "exmpllfcon1"; // Every attempt writes only its audio (the video fails): the from-start // attempts 100 s, 200 s, 5000 s, the live-edge ones 10 s each. const secs = [100, 200, 5000, 10, 10, 10]; const { run } = await incidentRun( id, async (args, n) => { await writeFile(`${outOf(args)}.f140.m4a`, `format=mp4;seconds=${secs[n - 1]};v=none;`); return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false }; }, { request: { doNotClean: false, note: undefined } }, ); await run.catch(() => {}); const row = (await rowOf(id))[0]!; assert.equal(row.parts[row.landedPart ?? -1]?.seconds, 5000, "the longest from-start part landed"); const gone = (row.removedParts ?? []).filter((r) => /a shorter part of this run from its start/.test(r.why)); assert.equal(gone.length, 2, "the two shorter from-start audio parts are inside it, and go"); const files = await left(id); assert.ok(!files.some((n) => /-a2\.f140|ytdlp\.f140/.test(n)), `removed from staging: ${files.join(", ")}`); assert.equal(files.filter((n) => /edge/.test(n)).length, 3, "the live-edge parts (not proven) are kept"); }); // --- The flows this lane is for (REVIEW-LF-4 notes 2 and 4) ---------------------- const choughOf = (endSeconds: number) => JSON.stringify({ chunk_data: [{ start_time: 0, end_time: 30, text: "hello" }, { start_time: endSeconds - 20, end_time: endSeconds, text: "the last words" }] }); test("flow: an editor shutdown stops a from-start run, the BOOT PASS resumes it in place, the stream ends, ONE whole file lands and nothing is left", { timeout: 60_000 }, async () => { const id = "exmplflowa1"; const ac = new AbortController(); const first = await incidentRun( id, resumableYtdlp(async ({ write, signal }) => { await write(3000); setTimeout(() => ac.abort(), 10); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); assert.equal((await first.run).status, "interrupted"); const stem = outOf(first.calls[0]!); const row1 = (await rowOf(id))[0]!; assert.deepEqual(row1.awaitingResume, [path.basename(stem)], "the part waits, with its state, to be resumed"); assert.equal(row1.parts[0]!.provenStart, true, "a YouTube from-start part under 120 h old: proven as it was recorded"); assert.equal(await storedSeconds(id), null, "nothing landed at the shutdown"); // The editor comes back: the boot pass (the real one) restarts the row. await new Promise((r) => setTimeout(r, 20)); const { restartInterruptedLiveRecordings } = await import("./liveRecordingBoot"); let live = true; let second: Awaited> | null = null; const outcomes = await restartInterruptedLiveRecordings({ paths, bootedAt: Date.now(), isRunning: () => false, orphanLooks: 1, sleep: async () => {}, // (The pass walks the whole test corpus: only this test's row is started.) start: async (_slug, body, resumeOf) => { if (body.url !== ytUrl(id)) return { ok: false, error: "another test's row" }; second = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write }) => { assert.equal(resumedFrom, 51, "from the saved fragment"); await write(7200); live = false; return "end"; }), { request: { ...body, resumeOf }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); return { ok: true, jobId: "job-boot" }; }, }); assert.deepEqual(outcomes.filter((o) => o.id === id).map((o) => o.state), ["asked"]); const s2 = await second!.run; assert.equal(s2.status, "landed"); assert.equal(outOf(second!.calls[0]!), stem, "the same stem, resumed in place"); assert.equal(await storedSeconds(id), 7200, "one whole file in the store"); assert.deepEqual(await left(id), [], "nothing left in staging: no part, no state"); const rows = await rowOf(id); const run2 = rows.find((r) => r.resumeOf)!; assert.equal(run2.parts.length, 1); assert.equal(run2.parts[0]!.provenStart, true, "the resumed part keeps the mark the original run earned"); assert.equal(run2.parts[0]!.resumes, 1); assert.equal(run2.coverage?.covers, true); assert.equal(run2.needsAttention, false); const old = rows.find((r) => r.startedAt === row1.startedAt)!; assert.equal(old.awaitingResume, undefined, "the old row no longer says a part waits"); assert.equal(old.needsAttention, false, "the interruption is superseded by the whole"); }); test("B3 / DESIGN-5 7: a part an earlier run left waiting is never left as the only copy in staging: a later run (a Record again) REUSES it — the same files continued — and lands the whole", { timeout: 60_000 }, async () => { const id = "exmplflowa2"; const { stem } = await waitingAtShutdown(id, 3000); let live = true; const again = await incidentRun( id, resumableYtdlp(async ({ n, resumedFrom, write, args }) => { if (n === 1) assert.equal(resumedFrom, 51, "from what the earlier run downloaded"); await write(7200); live = false; return "end"; }), // (No stall watch under a loaded machine: the reuse is what is tested.) { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await again.run).status, "landed"); assert.equal(outOf(again.calls[0]!), stem, "the same files"); assert.equal(await storedSeconds(id), 7200); assert.deepEqual(await left(id), [], "confirmed done: nothing left"); assert.ok((await rowOf(id)).every((r) => !r.awaitingResume), "no row says a part waits"); }); async function replacedOverShutdown(id: string, transcript: string | null, requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>) { await landedAtShutdown(id, 3600); if (transcript !== null) await writeFile(path.join(dataDir(id), "transcript.json"), transcript); let live = true; const r = await incidentRun( id, async (args) => { await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); live = false; return okExit; }, // (The hand-off reads a transcript there, as the real one does.) { deps: { join: null, handoff: async () => ({ ...(await handoff()), hasTranscript: transcript !== null }) }, refresh: { stillLive: () => live }, ...(requestTranscription ? { requestTranscription } : {}) }, ); const s = await r.run; return { s, log: r.log, row: (await rowOf(id)).find((x) => x.status === "landed")! }; } test("flow (REVIEW-LF-4 4): a shutdown's landing from the start is stored, then a WHOLE from-start run replaces it — nobody is asked", async () => { const id = "exmplflowb1"; const { s, row } = await replacedOverShutdown(id, null); assert.equal(s.status, "landed"); assert.equal(await storedSeconds(id), 7200, "the whole replaced the shutdown's short landing"); assert.equal(row.kept, "new"); assert.equal(row.coverage?.covers, true); assert.equal(row.transcriptRedo, undefined, "no transcript: the ordinary hand-off asks"); assert.equal(row.needsAttention, false); assert.ok((await rowOf(id)).every((r) => !r.needsAttention), "the interruption is superseded"); }); test("flow (REVIEW-LF-4 2): the replaced short landing's transcript ends inside it → the transcription is asked again", async () => { const id = "exmplflowb2"; const asked: string[] = []; const { row, log } = await replacedOverShutdown(id, choughOf(3580), async (_slug, vid, o) => { asked.push(`${vid}${o?.replace ? " replace" : ""}`); return { ok: true, jobId: "job-redo" }; }); assert.deepEqual(asked, [`${id} replace`], "asked once, to REPLACE the transcript (the job would otherwise skip it)"); assert.equal(row.transcriptRedo?.verdict, "shorter"); assert.equal(row.transcriptRedo?.replacedSeconds, 3600); assert.equal(row.transcriptRedo?.lastCueEnd, 3580); assert.equal(row.transcriptRedo?.jobId, "job-redo"); assert.equal(row.needsAttention, false, "asked: nobody needs to"); assert.ok(log.some((l) => /transcript .*shorter file/i.test(l))); }); test("flow (REVIEW-LF-4 2): asked again but nothing to ask with, or the ask refused → the row needs a person", async () => { const id = "exmplflowb3"; const { row } = await replacedOverShutdown(id, choughOf(3580)); assert.equal(row.transcriptRedo?.verdict, "shorter"); assert.equal(row.needsAttention, true); assert.match(row.reason, /transcript/); const id2 = "exmplflowb4"; const r2 = await replacedOverShutdown(id2, choughOf(3580), async () => ({ ok: false, error: "the lane is held" })); assert.equal(r2.row.transcriptRedo?.error, "the lane is held"); assert.equal(r2.row.needsAttention, true); }); test("flow (REVIEW-LF-4 2): a transcript that cannot be read → not known which file it came from: the row says so and asks a person, nothing is queued", async () => { const id = "exmplflowb5"; const asked: string[] = []; const { row } = await replacedOverShutdown(id, "{ not json", async (_s, vid) => { asked.push(vid); return { ok: true, jobId: "job-x" }; }); assert.deepEqual(asked, []); assert.equal(row.transcriptRedo?.verdict, "unknown"); assert.equal(row.needsAttention, true); assert.match(row.reason, /transcript/); }); test("flow (REVIEW-LF-4 2): a transcript whose speech runs past the short file's end was not made from it → nothing is asked", async () => { const id = "exmplflowb6"; const asked: string[] = []; const { row } = await replacedOverShutdown(id, choughOf(7150), async (_s, vid) => { asked.push(vid); return { ok: true, jobId: "job-y" }; }); assert.deepEqual(asked, []); assert.equal(row.transcriptRedo, undefined); assert.equal(row.needsAttention, false); }); test("flow: a boot resume of a part its original run did NOT prove (a row written before the mark) earns no mark: it lands, unproven, covering nothing", { timeout: 60_000 }, async () => { const id = "exmplflowa3"; const ac = new AbortController(); const first = await incidentRun( id, resumableYtdlp(async ({ write, signal }) => { await write(3000); setTimeout(() => ac.abort(), 10); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); await first.run; const t0 = (await rowOf(id))[0]!.startedAt; const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server"); await patchLiveRecordingRow(paths, YT_SLUG, id, t0, (r) => { for (const p of r.parts) delete p.provenStart; r.restart = { at: t0, by: "boot", state: "asked" }; }); let live = true; const second = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write }) => { assert.equal(resumedFrom, 51); await write(7200); live = false; return "end"; }), { request: { resumeOf: t0 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await second.run).status, "landed"); const run2 = (await rowOf(id)).find((r) => r.resumeOf)!; assert.equal(run2.parts[0]!.resumes, 1, "resumed in place"); assert.equal(run2.parts[0]!.provenStart, undefined, "the mark is not earned by a resume"); assert.equal(run2.coverage?.covers, false); }); // --- REVIEW-5 B: a waiting part always has a way into the store; the recorder tree; every stream pinned; the boot's age --- // A shutdown leaves one from-start part waiting (both streams, their state). async function waitingAtShutdown(id: string, seconds = 3000, opts: { video?: number } = {}) { const ac = new AbortController(); const r = await incidentRun( id, resumableYtdlp(async ({ write, writeStream, signal }) => { if (opts.video === undefined) await write(seconds); else { await writeStream("audio", seconds); if (opts.video > 0) await writeStream("video", opts.video); } setTimeout(() => ac.abort(), 10); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), // (One stream empty on purpose: no stall watch meanwhile.) { signal: ac.signal, deps: { ...FAST_WATCH, ...(opts.video !== undefined ? { stallMs: 60_000 } : {}), join: null, merge: fakeMerge, shuttingDown: () => true } }, ); assert.equal((await r.run).status, "interrupted"); const row = (await rowOf(id))[0]!; assert.equal(row.awaitingResume?.length, 1, "one part waits"); return { stem: outOf(r.calls[0]!), startedAt: row.startedAt, row }; } const askBoot = async (id: string, startedAt: string) => { const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server"); await patchLiveRecordingRow(paths, YT_SLUG, id, startedAt, (r) => { r.restart = { at: startedAt, by: "boot", state: "asked" }; }); }; test("B3: the stream ENDED while the editor was down — the boot's run finalizes and lands the waiting part, and the old row says what was done", { timeout: 60_000 }, async () => { const id = "exmplb3end1"; const { startedAt } = await waitingAtShutdown(id); await askBoot(id, startedAt); const r = await incidentRun(id, async () => assert.fail("nothing is recorded for an ended stream"), { request: { resumeOf: startedAt }, meta: { ...YT_META(id), live_status: "was_live", duration: 3000 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, }); const s = await r.run; assert.equal(s.status, "landed"); assert.equal(await storedSeconds(id), 3000, "the waiting part is in the store"); assert.deepEqual(await left(id), [], "nothing left in staging, no state"); const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!; assert.equal(old.restart?.state, "landed"); assert.doesNotMatch(old.reason, /is landed$/); assert.match(old.reason, /was landed/); assert.equal(old.awaitingResume, undefined); }); test("B3: the stream was REMOVED while the editor was down (every read refused as private) — the waiting part is landed, the row says the stream is gone", { timeout: 60_000 }, async () => { const id = "exmplb3gone"; const { startedAt } = await waitingAtShutdown(id); await askBoot(id, startedAt); const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`; const r = await incidentRun(id, async () => assert.fail("nothing is recorded for a removed stream"), { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [1, 2, 3, 4, 5, 6], failWith: PRIVATE }, }); await r.run.catch(() => {}); assert.equal(await storedSeconds(id), 3000, "the only copy is in the store"); // (REVIEW-6 12: gone is endedBy private — nothing on disk is removed.) assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`))); const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!; assert.equal(old.restart?.state, "landed"); assert.match(old.reason, /private or removed/); }); test("B3: the stream's state cannot be read at the boot (a network error, every read) — what was left is landed all the same; the row says the state is not known and to Record again", { timeout: 60_000 }, async () => { const id = "exmplb3unk1"; const { startedAt } = await waitingAtShutdown(id); await askBoot(id, startedAt); const r = await incidentRun(id, async () => assert.fail("never a recording on a guess"), { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [1, 2, 3, 4, 5, 6] }, }); await r.run.catch(() => {}); assert.equal(await storedSeconds(id), 3000); const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!; assert.equal(old.restart?.state, "landed"); assert.match(old.reason, /could not be read/); assert.match(old.reason, /Record again/); assert.equal(old.needsAttention, true, "the stream may still be live: a person"); }); test("B3: the boot resume takes the LONGEST resumable from-start part of any row of the id; the others are released and landed by the rules", { timeout: 60_000 }, async () => { const id = "exmplb3long"; const a = await waitingAtShutdown(id, 3000); // A second run (no resume) also stopped by a shutdown, with a shorter part: // the first run's part keeps waiting beside it. const ac = new AbortController(); const b = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write, signal }) => { // (DESIGN-5 7: it continues the earlier waiting part, the longest.) assert.equal(resumedFrom, 51); await write(3600); setTimeout(() => ac.abort(), 10); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); await b.run; assert.equal(outOf(b.calls[0]!), a.stem, "the second run continued the first's part"); const rowB = (await rowOf(id)).find((x) => x.startedAt !== a.startedAt)!; assert.equal(rowB.awaitingResume?.length, 1, "that part waits again, listed on the newest row"); await askBoot(id, rowB.startedAt); let live = true; const c = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write }) => { assert.equal(resumedFrom, 61, "the part, now 3600 s, is resumed"); await write(7200); live = false; return "end"; }), { request: { resumeOf: rowB.startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await c.run).status, "landed"); assert.equal(outOf(c.calls[0]!), a.stem); assert.equal(await storedSeconds(id), 7200); assert.deepEqual(await left(id), [], "the shorter waiting part was released, and inside the whole it went"); assert.ok((await rowOf(id)).every((r) => !r.awaitingResume)); }); test("B4: a stop reaches the recorder's whole tree, and the recorder returns when yt-dlp exits — not when a grandchild holding its pipes does", { timeout: 30_000 }, async () => { const pidFile = path.join(ROOT, "grandchild.pid"); // yt-dlp's stand-in: starts a child that inherits its stdout/stderr (as // yt-dlp's ffmpeg does), says ready, and has no handler for SIGTERM. const script = `const c = require("child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: ["ignore", "inherit", "inherit"] }); require("fs").writeFileSync(${JSON.stringify(pidFile)}, String(c.pid)); console.log("ready"); setInterval(() => {}, 1000);`; const ac = new AbortController(); const lines: string[] = []; const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: (l) => void lines.push(l), signal: ac.signal, label: "t" }); const readyBy = Date.now() + 20_000; while (!lines.some((l) => /^(?:\[t\] )?ready\s*$/.test(l))) { assert.ok(Date.now() < readyBy, "the child never said it was ready"); await new Promise((r) => setTimeout(r, 10)); } const grandchild = Number(await readFile(pidFile, "utf8")); const t0 = Date.now(); ac.abort("SIGTERM"); const o = await p; assert.ok(Date.now() - t0 < 8000, `returned ${Date.now() - t0} ms after the stop`); assert.equal(o.signalled, true); await new Promise((r) => setTimeout(r, 200)); assert.throws(() => process.kill(grandchild, 0), "the grandchild is gone too"); }); test("B4: a from-start recorder whose part cannot be resumed (a muxed download, no state) is stopped with SIGINT, which finishes it — never SIGTERM", { timeout: 60_000 }, async () => { const id = "exmplb4mux1"; const reasons: unknown[] = []; const ac = new AbortController(); const r = await incidentRun( id, async (args, _n, signal) => { // One muxed file, no `.ytdl` (an ffmpeg download keeps none). await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); setTimeout(() => ac.abort(), 10); await abortOf(signal); reasons.push(signal.reason); return { exitCode: null, stderrTail: "", signalled: true }; }, { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); await r.run.catch(() => {}); assert.deepEqual(reasons, ["SIGINT"]); }); test("B5: a resume pins EVERY stream the run was recording, the empty one included; the empty stream is said at once, not at the landing", { timeout: 60_000 }, async () => { const id = "exmplb5pin1"; const { row } = await waitingAtShutdown(id, 3000, { video: 0 }); assert.equal(row.parts[0]!.missingStream, "video", "said when the recorder stopped"); assert.match(row.reason, /video/); await askBoot(id, row.startedAt); let live = true; const c = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(7200); live = false; return "end"; }), { request: { resumeOf: row.startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await c.run; assert.equal(c.calls[0]![c.calls[0]!.indexOf("-f") + 1], "136+140", "both ids, the empty stream's too"); }); test("B5: a stem with only one stream file of a separate recording is not resumed in place (never `-f` one stream alone)", { timeout: 60_000 }, async () => { const id = "exmplb5one1"; const { stem, startedAt } = await waitingAtShutdown(id, 3000); // The picture's file is gone (its state too): one stream left. await rm(`${stem}.${FAKE_V}`, { force: true }); await rm(`${stem}.${FAKE_V}.ytdl`, { force: true }); await askBoot(id, startedAt); let live = true; const c = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(7200); live = false; return "end"; }), { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await c.run.catch(() => {}); assert.notEqual(c.calls[0]![c.calls[0]!.indexOf("-f") + 1], "140", "never one stream alone"); assert.notEqual(outOf(c.calls[0]!), stem, "not resumed in place: a new from-start part"); assert.ok(fromStartArg(c.calls[0]!)); }); test("REVIEW-5 note 1: one stream that stops growing while the other grows is a stall — stopped (SIGTERM, resumable) and resumed with both", { timeout: 60_000 }, async () => { const id = "exmplnote1a"; let live = true; const reasons: unknown[] = []; const { run, calls, log } = await incidentRun( id, resumableYtdlp(async ({ n, writeStream, write, signal }) => { if (n === 1) { await write(3000); // The sound goes on; the picture's thread has ended alone. for (let k = 1; k < 150 && !signal.aborted; k++) { await writeStream("audio", 3000 + k * FAKE_FRAG_S); await new Promise((r) => setTimeout(r, 15)); } reasons.push(signal.aborted ? signal.reason : "never stopped"); return { exitCode: null, stderrTail: "", signalled: signal.aborted }; } await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; assert.deepEqual(reasons, ["SIGTERM"]); assert.ok(log.some((l) => /stream .*f136\.mp4 has not grown/.test(l)), `said which stream: ${log.filter((l) => /stall/.test(l)).join(" | ")}`); assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place"); assert.equal(calls[1]![calls[1]!.indexOf("-f") + 1], "136+140"); }); test("REVIEW-5 note 3: the restart bound reached on a stream still live does not end the recording: it waits out the hour, continues, and the row says it waited", { timeout: 60_000 }, async () => { const id = "exmplnote3a"; let live = true; const { run, calls, waits, log } = await incidentRun( id, async (args, n) => { // Every recorder exits a moment later with what it wrote (an IRL // stream whose ingest keeps dropping); the stream ends after 9. await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${60 + n};`); if (n >= 9) live = false; return okExit; }, { request: { fromStart: false }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); const row = (await rowOf(id))[0]!; assert.equal(row.restarts?.refused, undefined, "never refused while live"); assert.ok((row.restarts?.count ?? 0) >= 7, `restarted past the hour's 6 (${row.restarts?.count})`); assert.ok((row.restarts?.waited ?? 0) >= 1, "it waited"); assert.ok(waits.some((w) => w > 60_000 && w <= 3_600_000), `an hour's wait: ${waits.join(", ")}`); assert.ok(log.some((l) => /waits? .*before restart/i.test(l))); assert.ok(calls.length >= 8); }); // --- DESIGN-4: resume only on proof, a fresh part first, no silent skip, the merge checked --------- const isFresh = (args: string[]) => /\.ytdlp-f\d+$/.test(outOf(args)); test("DESIGN-4 2: a from-start part with nothing to resume or reuse (no state, a kept fragment gone) while the stream is live — a FRESH part from the start (a new stem, proven), never the live edge; the whole lands and covers", { timeout: 60_000 }, async () => { const id = "exmpld4fr01"; let live = true; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(3000); await dropState(args); // Nothing provable to reuse either: a kept fragment is gone. await rm(`${outOf(args)}.${FAKE_V}-Frag20`, { force: true }); return "die"; } assert.ok(fromStartArg(args) && isFresh(args), `call ${n}: a fresh from-start part`); await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2); assert.notEqual(outOf(calls[1]!), outOf(calls[0]!), "a new stem"); const row = (await rowOf(id))[0]!; const fresh = row.parts.find((p) => p.fresh !== undefined)!; assert.equal(fresh.provenStart, true, "a YouTube from-start part under 119 h: proven"); assert.equal(row.coverage?.covers, true); assert.equal(row.verification?.state, "verified"); assert.deepEqual(await left(id), [], "the earlier part and every stream file went, after the check"); }); test("DESIGN-4 1: a torn tail (a shutdown inside an append) — the boot's resume truncates it back (both lengths logged) and resumes; the landed file is whole", { timeout: 60_000 }, async () => { const id = "exmpld4tear"; const ac = new AbortController(); const first = await incidentRun( id, resumableYtdlp(async ({ write, tear, signal }) => { await write(3000); await tear("video", 0.6); setTimeout(() => ac.abort(), 10); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); await first.run; const t0 = (await rowOf(id))[0]!.startedAt; await askBoot(id, t0); let live = true; const second = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write }) => { assert.equal(resumedFrom, 51); await write(7200); live = false; return "end"; }), { request: { resumeOf: t0 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await second.run).status, "landed"); assert.equal(outOf(second.calls[0]!), outOf(first.calls[0]!), "resumed in place"); assert.ok(second.log.some((l) => /truncated from \d+ to \d+ bytes/.test(l)), "the repair is logged with both lengths"); assert.equal(await storedSeconds(id), 7200); }); test("DESIGN-4 1: an excess that is NOT the start of the next kept fragment, or with that fragment gone — never truncated, never resumed in place: a fresh part from the start records, and the old part is landed by the rules", { timeout: 60_000 }, async () => { for (const [id, how] of [ ["exmpld4ref1", "garbage"], ["exmpld4ref2", "nofrag"], ] as const) { const { stem, startedAt } = await waitingAtShutdown(id, 3000); // After the shutdown (a crash of the machine, a hand): the tail of the // picture's file is not provable any more. const v = `${stem}.${FAKE_V}`; const before = (await stat(v)).size; await writeFile(`${v}-Frag52`, "seconds=60;#52;xx"); await appendFile(v, how === "garbage" ? "garbage that no fragment begins with" : "seconds=60;"); if (how === "nofrag") await rm(`${v}-Frag52`, { force: true }); const after = (await stat(v)).size; await askBoot(id, startedAt); let live = true; const second = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write }) => { assert.equal(resumedFrom, null, `${how}: not the old files`); await write(7200); live = false; return "end"; }), { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await second.run.catch(() => {}); assert.notEqual(outOf(second.calls[0]!), stem, `${how}: not resumed in place`); assert.ok(fromStartArg(second.calls[0]!), `${how}: a fresh part from the start`); assert.ok(!second.log.some((l) => /truncated from/.test(l)), `${how}: nothing truncated`); assert.ok(after > before); assert.equal(await storedSeconds(id), 7200, `${how}: the fresh whole landed`); } }); test("DESIGN-4 1 / DESIGN-5 7: while recording EVERY fragment is kept (nothing pruned until the stream is confirmed done); short of disk they are DROPPED (loud), the recording goes on, no longer resumable in place", { timeout: 60_000 }, async () => { const id = "exmpld4prn1"; let live = true; let free = 1e15; const seenFrags: number[] = []; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(3000); await new Promise((r) => setTimeout(r, 150)); const names = await readdir(store()); seenFrags.push(names.filter((x) => x.startsWith(path.basename(`${outOf(args)}.${FAKE_V}-Frag`))).length); free = 1e9; await write(3600); await new Promise((r) => setTimeout(r, 150)); // Room again (a restart needs it): the fragments stay dropped. free = 1e15; return "die"; } await write(7200); live = false; return "end"; }), // (No stall while it waits on purpose.) { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, freeBytes: async () => free }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); assert.equal(seenFrags[0], 51, "all 51 kept while recording"); const row = (await rowOf(id))[0]!; assert.match(row.parts[0]!.fragmentsDropped ?? "", /free/); assert.notEqual(outOf(calls[1]!), outOf(calls[0]!), "not resumed in place: its fragments were dropped"); assert.match(row.reason, /lost its kept fragments/); }); test("DESIGN-4 3: a fragment that cannot be fetched stops the recorder (SIGTERM) and resumes it after 20 s, 60 s, 180 s; then a fresh part; that one stuck at the same fragment — ONE run that may skip: marked, never proven, the row loud after the landing", { timeout: 60_000 }, async () => { const id = "exmpld4abt1"; let live = true; const reasons: unknown[] = []; // (As the recorder reads yt-dlp's `ERROR: \\r[download] …` line: REVIEW-6 1.) const GOT = "ERROR: [download] Got error: HTTP Error 404: Not Found. Giving up after 10 retries"; const { run, calls, waits, log } = await incidentRun( id, resumableYtdlp(async ({ write, print, signal, args }) => { if (args.includes("--skip-unavailable-fragments")) { // The last resort: it skips the fragment and goes on to the end. print("1: [download] fragment not found; Skipping fragment 52 ..."); await write(7200); live = false; return "end"; } assert.ok(args.includes("--abort-on-unavailable-fragments")); await write(3000); // Fragment 52 of the picture cannot be fetched: its thread ends; yt-dlp // would record the sound on alone — the recorder is stopped. print(GOT); await abortOf(signal); reasons.push(signal.reason); return { exitCode: null, stderrTail: "", signalled: true }; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); const s = await run.catch((e) => e); void s; assert.ok(reasons.every((r) => r === "SIGTERM"), `stopped with SIGTERM, its state kept: ${reasons.join(",")}`); for (const w of [20_000, 60_000, 180_000]) assert.ok(waits.includes(w), `a ${w / 1000} s wait before a resume`); assert.ok(calls.some(isFresh), "then a fresh part from the start"); const last = calls[calls.length - 1]!; assert.ok(last.includes("--skip-unavailable-fragments"), "the last resort may skip"); // (That the line is never thinned out of the job log: the progress-line test.) assert.ok(log.some((l) => /a fragment could not be fetched/.test(l)), "the stop is said"); const row = (await rowOf(id))[0]!; assert.equal(row.status, "landed"); assert.equal(row.skippedFragments?.count, 1); assert.deepEqual(row.skippedFragments?.positions, [52]); assert.equal(row.coverage?.covers, false, "a part with a hole never covers"); assert.equal(row.needsAttention, true, "loud after the landing"); assert.match(row.reason, /HOLE/); }); test("DESIGN-4 4: the landed file NOT verified whole — nothing removed: its stream files and the other parts stay, the row loud; verified — they go, after the check, never before", { timeout: 60_000 }, async () => { const id = "exmpld4ver1"; const earlier = await leftover(id, 300); const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt: "2026-11-20T01:00:00.000Z", status: "failed", fromStart: true, attempts: 1, mustKeep: true, parts: [{ method: "ytdlp", url: ytUrl(id), fromStart: true, provenStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem: path.basename(earlier).replace(/\.mp4$/, "") }], }); let live = true; let storedAtCheck: number | null = null; let streamsAtCheck = 0; const r = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, verifyMerged: async (_m: string, streams: readonly string[]) => { storedAtCheck = await storedSeconds(id); for (const f of streams) if ((await stat(f).catch(() => null))?.size) streamsAtCheck++; return { ok: false, why: "its video: 3590 packets merged, 3600 in the stream" }; }, }, refresh: { stillLive: () => live }, }, ); assert.equal((await r.run).status, "landed"); assert.equal(storedAtCheck, 7200, "the check runs after the landing"); assert.equal(streamsAtCheck, 2, "with both stream files still there"); assert.ok((await stat(earlier)).size > 0, "the earlier part is not removed"); assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files are kept"); const row = (await rowOf(id)).find((x) => x.status === "landed")!; assert.equal(row.verification?.state, "failed"); assert.equal(row.removedParts, undefined); assert.equal(row.needsAttention, true); assert.match(row.reason, /NOT verified whole/); }); test("DESIGN-4 5: a from-start recorder that ends by itself (an ingest pause, no state) while the stream is live — the insurance holds the live edge BEFORE the confirming read, then the same files continued (reused), never fragment 0", { timeout: 60_000 }, async () => { const id = "exmpld4ing1"; let live = true; const order: string[] = []; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ n, write, args, signal }) => { if (isInsurance(args)) { order.push("insurance"); await write(60); await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]); return { exitCode: null, stderrTail: "", signalled: true }; } if (n === 1) { // Caught up, then yt-dlp's own finalized end ~35 s after the last fragment. await write(3000); await new Promise((r) => setTimeout(r, 30)); return "end"; } order.push(isFresh(args) ? "fresh" : "resume"); await write(7200); live = false; return "end"; }), { request: { insurance: true }, onWait: (ms) => { if (ms === 60_000) order.push("confirm-read"); }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live }, }, ); await run.catch(() => {}); // (DESIGN-5 7: the same files continued, reusing what is downloaded.) const mains = calls.filter((c) => !isInsurance(c)); assert.equal(outOf(mains[1]!), outOf(mains[0]!), "the same files, not a fresh part"); const ins = order.indexOf("insurance"); assert.ok(ins >= 0 && order.indexOf("confirm-read") >= 0 && ins < order.indexOf("resume"), `order: ${order.join(" → ")}`); }); test("note 4: at a shutdown with a part waiting, NOTHING lands — the other part waits too, for the restart", { timeout: 60_000 }, async () => { const id = "exmpln4wt01"; const earlier = await leftover(id, 300); const ac = new AbortController(); const r = await incidentRun( id, resumableYtdlp(async ({ write, signal }) => { await write(3000); setTimeout(() => ac.abort(), 10); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); assert.equal((await r.run).status, "interrupted"); assert.equal(await storedSeconds(id), null, "nothing in the store"); assert.ok((await stat(earlier)).size > 0); const row = (await rowOf(id))[0]!; assert.equal(row.awaitingResume?.length, 2, "both wait for the restart"); }); test("note 5: one recorder per stem — a lock held by a live process refuses a second; a lock of a dead process, or one older than the machine's boot, is stale and taken over", async () => { const { takeStemLock } = await import("./recordLive"); const dir = path.join(ROOT, "locks"); await mkdir(dir, { recursive: true }); const a = await takeStemLock(dir, ".x.live-1.ytdlp"); assert.equal(a.ok, true); const b = await takeStemLock(dir, ".x.live-1.ytdlp"); assert.equal(b.ok, false, "held by a live process (this one)"); assert.match((b as { why: string }).why, /another recorder holds/); if (a.ok) await a.release(); // A dead process's lock. await writeFile(path.join(dir, ".x.live-2.ytdlp.rec.lock"), JSON.stringify({ pid: 2 ** 22 + 12345, at: new Date().toISOString() })); assert.equal((await takeStemLock(dir, ".x.live-2.ytdlp")).ok, true); // Made before the machine last booted (a pid may be reused since). await writeFile(path.join(dir, ".x.live-3.ytdlp.rec.lock"), JSON.stringify({ pid: process.pid, at: "2000-01-01T00:00:00.000Z" })); assert.equal((await takeStemLock(dir, ".x.live-3.ytdlp")).ok, true); }); test("note 12: a boot restart still `starting` after 10 minutes never went on — the row says so and needs a person", async () => { const id = "exmpln12st1"; const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await ytChannel(); const at = new Date(Date.now() - 20 * 60_000).toISOString(); await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt: at, status: "interrupted", stoppedBy: "shutdown", fromStart: true, attempts: 1, mustKeep: true, parts: [], restart: { at, by: "boot", state: "starting" }, }); const row = (await rowOf(id))[0]!; assert.match(row.reason, /never got going/); assert.equal(row.needsAttention, true); }); test("slice 2, the other order: the from-start try ends BEFORE the live edge does — its recovery state is still `recorded` (the loop's later stop does not hide it)", async () => { const id = "exmplrecov1b"; let endStream!: () => void; const ended = new Promise((r) => (endStream = r)); const edge = edgeUntil(ended); let recoveries = 0; const { run } = await incidentRun(id, async (args) => { if (!fromStartArg(args)) return edge(args); if (!isRecovery(args)) return failEmpty; recoveries++; if (recoveries === 1) return failEmpty; await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); // The live edge ends a moment AFTER this try has returned. setTimeout(() => endStream(), 150); return { exitCode: 0, stderrTail: "", signalled: false }; }, { recovery: 2, meta: { ...ytLiveMeta(id), duration: 7200 } }); assert.equal((await run).status, "landed"); const row = (await rowOf(id))[0]!; assert.equal(row.startRecovery?.state, "recorded"); }); // --- DESIGN-5: a recorder that ends by itself while the stream is live ------------------ const REFRESH_FAIL = [ "WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Retrying (1/3)...", "WARNING: [youtube] Cannot find refreshed url for format 136; please report this issue. Retrying (1/3)...", "WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Giving up after 3 retries", ]; test("DESIGN-5 1/2/7: yt-dlp gives up refreshing the URL, merges and exits 0 while the stream is live — never landed as whole; classed url-refresh in plain words; the SAME files resumed reusing every fragment downloaded, again and again while it is live", { timeout: 60_000 }, async () => { const id = "exmpld5url1"; let live = true; const resumed: (number | null)[] = []; const { run, calls, log } = await incidentRun( id, resumableYtdlp(async ({ n, resumedFrom, write, print }) => { resumed.push(resumedFrom); // (The stream is 2 h old: the last part reaches its end.) await write(n < 4 ? 3000 + (n - 1) * 1200 : 7200); if (n < 4) { for (const l of REFRESH_FAIL) print(l); return "end"; // merged, the state removed, exit 0 — the stream goes on } live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); const s = await run; assert.equal(s.status, "landed"); assert.equal(calls.length, 4, "three self-exits while live: three restarts"); assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "the same files every time"); assert.deepEqual(resumed, [null, 51, 71, 91], "each restart from what is on disk, never fragment 0"); assert.ok(log.some((l) => /could not refresh the stream's URL for format 140/.test(l))); const row = (await rowOf(id))[0]!; assert.equal(row.parts[0]!.failureClass, "url-refresh"); assert.equal(row.parts[0]!.reused?.fragments, 91, "the last reuse"); assert.match(row.reason, /could not refresh the stream's URL/); assert.equal(row.landedWhileLive, undefined, "landed once the stream was over"); assert.equal(row.coverage?.covers, true); assert.deepEqual(await left(id), [], "confirmed done: the streams, fragments and merged copies go"); }); test("DESIGN-5 1: a partial exit (one stream missing) while the stream is live restarts — never a landing", { timeout: 60_000 }, async () => { const id = "exmpld5par1"; let live = true; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ n, writeStream, write, args }) => { if (n === 1) { await writeStream("audio", 600); await rm(`${outOf(args)}.${FAKE_V}`, { force: true }); await rm(`${outOf(args)}.${FAKE_V}.ytdl`, { force: true }); return { exitCode: 1, stderrTail: "ERROR: The downloaded file is empty\n", signalled: false }; } await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); assert.ok(calls.length >= 2, "restarted"); const row = (await rowOf(id))[0]!; assert.equal(row.landedWhileLive, undefined); }); test("DESIGN-5 3/4/7: a Cancel while the stream is live — landed, but `landedWhileLive` with the unrecorded time, loud, never 'the whole stream', no superseding; the stream files and fragments kept; a Record again then REUSES them", { timeout: 60_000 }, async () => { const id = "exmpld5cnl1"; const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); await ytChannel(); await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt: "2026-11-20T01:00:00.000Z", status: "failed", fromStart: true, attempts: 1, mustKeep: true, parts: [] }); const ac = new AbortController(); const a = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(3000); setTimeout(() => ac.abort(), 10); // SIGINT: yt-dlp finishes (merged, its state removed). return "hang"; }), { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => true } }, ); await a.run.catch(() => {}); const rows = await rowOf(id); const row = rows.find((r) => r.startedAt !== "2026-11-20T01:00:00.000Z")!; assert.ok(row.landedWhileLive, "landed while live"); assert.ok((row.landedWhileLive!.unrecordedSeconds ?? 0) > 3000, `unrecorded by the clock: ${row.landedWhileLive!.unrecordedSeconds}`); assert.match(row.landedWhileLive!.why, /cancelled/); assert.equal(row.needsAttention, true); assert.match(row.reason, /LANDED WHILE THE STREAM WAS STILL LIVE/); assert.ok(!a.log.some((l) => /holds the whole stream/.test(l)), "no claim of wholeness"); assert.equal(rows.find((r) => r.startedAt === "2026-11-20T01:00:00.000Z")!.supersededBy, undefined, "supersedes nothing"); const stem = outOf(a.calls[0]!); assert.ok((await left(id)).some((n) => n === path.basename(`${stem}.${FAKE_V}`)), "the stream files are kept for reuse"); assert.ok((await left(id)).some((n) => n === path.basename(`${stem}.${FAKE_V}-Frag51`)), "and the fragments"); // A person's Record again: the kept part is resumed, not fragment 0. let live = true; const b = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write }) => { assert.equal(resumedFrom, 51, "reused"); await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await b.run).status, "landed"); assert.equal(outOf(b.calls[0]!), stem, "the same files"); const last = (await rowOf(id)).find((r) => r.status === "landed" && !r.landedWhileLive)!; assert.equal(last.parts[0]!.reused?.fragments, 51); }); test("DESIGN-5 2: the url-refresh class", async () => { const { liveFailureClass: liveFailureClassOf } = await import("../lib/liveCapture"); assert.equal(liveFailureClassOf("WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Giving up after 3 retries"), "url-refresh"); }); test("DESIGN-5 (c): fragments answered 403 while recording, then a read says private — `went-private`: what is on disk lands, loud, no retry loop, NOTHING on disk removed", { timeout: 60_000 }, async () => { const id = "exmpld5prv1"; const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`; const { run, calls, waits } = await incidentRun( id, resumableYtdlp(async ({ write, print, signal }) => { await write(3000); for (let k = 1; k <= 3; k++) print(`[download] Got error: HTTP Error 403: Forbidden. Retrying fragment 52 (${k}/10)...`); print("ERROR: [download] Got error: HTTP Error 403: Forbidden. Giving up after 10 retries"); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failAfterFirst: PRIVATE } }, ); await run.catch(() => {}); assert.equal(calls.length, 1, "never retried in a loop"); assert.ok(waits.includes(60_000), "the private read confirmed a minute later"); assert.equal(await storedSeconds(id), 3000, "what is on disk is landed"); const row = (await rowOf(id))[0]!; assert.equal(row.failureClass, "went-private"); assert.equal(row.parts[0]!.failureClass, "went-private"); assert.equal(row.endedBy?.class, "private"); assert.equal(row.needsAttention, true); assert.match(row.reason, /went private while it was recorded/); const files = await left(id); assert.ok(files.some((n) => n.endsWith(`.${FAKE_V}`)) && files.some((n) => n.endsWith(`.${FAKE_V}-Frag51`)), `nothing on disk removed: ${files.length} files`); }); // --- REVIEW-6: the real yt-dlp bytes, the repair's leftover fragment, the verifier's two holes --------- // yt-dlp's fatal fragment line, as its bytes are (measured in exp4/r5, r7b): // `ERROR: ` then "\r", then the line — here split across two writes. const FATAL_CHUNKS = ["[download] 12.0% of ~ 1.20GiB at 2.00MiB/s (frag 51/2000)\nERROR: \r[download] Got er", "ror: HTTP Error 404: Not Found. Giving up after 10 retries\n"]; const fatalScript = `process.stderr.write(${JSON.stringify(FATAL_CHUNKS[0])}); setTimeout(() => process.stderr.write(${JSON.stringify(FATAL_CHUNKS[1])}), 150); setInterval(() => {}, 1000);`; test("REVIEW-6 1: through the real recorder reader, yt-dlp's `ERROR: \\r[download] Got error … Giving up` arriving in two chunks is ONE line, and it is a fragment's final failure", async () => { const { isFragmentFatalLine } = await import("./recordLive"); const ac = new AbortController(); const lines: string[] = []; const p = spawnRecorder({ bin: process.execPath, args: ["-e", fatalScript], cwd: ROOT, onLog: () => {}, signal: ac.signal, label: "t", onLine: (l) => void lines.push(l) }); const by = Date.now() + 20_000; while (!lines.some((l) => /Giving up/.test(l))) { assert.ok(Date.now() < by, `no whole line: ${JSON.stringify(lines)}`); await new Promise((r) => setTimeout(r, 20)); } ac.abort("SIGTERM"); await p; const fatal = lines.find((l) => /Giving up/.test(l))!; assert.equal(fatal, "ERROR: [download] Got error: HTTP Error 404: Not Found. Giving up after 10 retries"); assert.equal(isFragmentFatalLine(fatal), true); assert.equal(isFragmentFatalLine("[download] Got error: HTTP Error 404: Not Found. Retrying fragment 52 (3/10)..."), false, "a retry is not the end"); assert.ok(!lines.includes("ERROR:"), "no bare ERROR: line"); }); test("REVIEW-6 1: a self-rewriting line (\\r, no \\n — ffmpeg's frame=) is read as it comes, not held until a newline", async () => { const ac = new AbortController(); const lines: string[] = []; const script = `let i = 0; const t = setInterval(() => { process.stderr.write("frame=" + (++i) + "\\r"); }, 20);`; const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: () => {}, signal: ac.signal, label: "t", onLine: (l) => void lines.push(l) }); const by = Date.now() + 20_000; while (lines.filter((l) => /^frame=/.test(l)).length < 3) { assert.ok(Date.now() < by, "the \\r segments never came"); await new Promise((r) => setTimeout(r, 20)); } ac.abort(); await p; }); test("REVIEW-6 1: the real fatal bytes through spawnRecorder STOP the recorder at once (SIGTERM, its state kept) and the resume waits 20 s — not the stall watchdog 10 minutes later", { timeout: 40_000 }, async () => { const id = "exmplr6fat1"; let live = true; const { run, calls, waits, log } = await incidentRun( id, resumableYtdlp(async ({ n, write, print, signal }) => { if (n === 1) { await write(3000); // The other stream's thread goes on: the process does not exit. const o = await spawnRecorder({ bin: process.execPath, args: ["-e", fatalScript], cwd: ROOT, onLog: () => {}, signal, label: "real", onLine: print }); return { exitCode: o.exitCode, stderrTail: o.stderrTail, signalled: o.signalled }; } await write(7200); live = false; return "end"; }), // (No stall watch in the way: only the line can stop it.) { deps: { ...FAST_WATCH, stallMs: 600_000, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await run).status, "landed"); assert.ok(log.some((l) => /a fragment could not be fetched/.test(l)), "the stop is said"); assert.ok(waits.includes(20_000), `the first wait before a resume: ${waits.join(", ")}`); assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place"); }); test("REVIEW-6 3: before any fragment goes, each stream file must be byte for byte its kept fragments — one that is not fails the check and NOTHING is removed", { timeout: 60_000 }, async () => { const id = "exmplr6eq01"; let live = true; const { run } = await incidentRun( id, resumableYtdlp(async ({ write, args }) => { await write(7200); // A kept fragment that is not what the stream file holds there. const f = `${outOf(args)}.${FAKE_V}-Frag10`; const b = await readFile(f, "utf8"); await writeFile(f, b.replace("#10;", "#99;")); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await run).status, "landed"); const row = (await rowOf(id))[0]!; assert.equal(row.verification?.state, "failed"); assert.match(row.verification?.why ?? "", /not fragment 10/); assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files are kept"); assert.equal(row.needsAttention, true); }); // --- REVIEW-6 4-13 -------------------------------------------------------------------- test("REVIEW-6 4 / REVIEW-7 2: the stream ENDS (post_live) while its from-start part is behind — resumed once to its end, not landed short", { timeout: 60_000 }, async () => { const id = "exmplr6end1"; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ n, write }) => { if (n === 1) { await write(3000); return "die"; } await write(7200); return "end"; }), { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "post_live" } }, ); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2, "one resume after the end"); assert.equal(outOf(calls[1]!), outOf(calls[0]!)); assert.equal(await storedSeconds(id), 7200); }); test("REVIEW-6 4: landed SHORT of an ended stream's own duration — needs a person: \"download the VOD now\"", { timeout: 60_000 }, async () => { const id = "exmplr6end2"; const { run } = await incidentRun( id, resumableYtdlp(async ({ write, args }) => { await write(3000); await dropState(args); await noReuse(args); return "die"; }), { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge } }, ); await run.catch(() => {}); const row = (await rowOf(id))[0]!; assert.equal(row.status, "landed"); assert.equal(row.coverage?.covers, false); assert.equal(row.needsAttention, true); assert.match(row.reason, /download the VOD now/); }); test("REVIEW-6 5: a resume that fails for the NETWORK is tried again on the waits, the same files — not given up after one try", { timeout: 60_000 }, async () => { const id = "exmplr6net1"; let live = true; const { run, calls, waits } = await incidentRun( id, resumableYtdlp(async ({ n, write }) => { if (n === 1) { await write(3000); return "die"; } if (n === 2) return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Unable to download webpage: The read operation timed out\n", signalled: false }; await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await run).status, "landed"); assert.ok(waits.includes(20_000), `waited before the retry: ${waits.join(", ")}`); assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "the same files throughout"); }); test("REVIEW-6 5: empty live-edge recorders while the state cannot be read (offline) are not evidence the stream ended", { timeout: 60_000 }, async () => { const id = "exmplr6net2"; let reads = 0; const { run } = await incidentRun( id, resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(3000); await dropState(args); await noReuse(args); return "die"; } return { exitCode: 1, stderrTail: "ERROR: Unable to download webpage: timed out\n", signalled: false }; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, freshFromStart: false }, refresh: { failReads: [2, 3, 4, 5, 6, 7], afterRead: (k) => void (reads = k), stillLive: () => reads < 9 }, }, ); await run.catch(() => {}); const row = (await rowOf(id))[0]!; assert.doesNotMatch(row.restarts?.refused ?? "", /three live-edge recorders/); }); test("REVIEW-6 7: a resume in place needs the floor plus the stream files — not twice everything on disk (fragments, merged copies)", { timeout: 60_000 }, async () => { const id = "exmplr6rm01"; let live = true; let streams = 0; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(3000); for (const f of [FAKE_V, FAKE_A]) streams += (await stat(`${outOf(args)}.${f}`)).size; return "die"; } await write(7200); live = false; return "end"; }), // Room for the floor and the streams, not for twice the part (fragments included). { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 1000 + streams + 10 }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); assert.ok(calls.length >= 2, "the resume was not refused for want of disk"); assert.equal(outOf(calls[1]!), outOf(calls[0]!)); }); test("REVIEW-6 8: one moved-aside merged copy at a time, however many self-exits", { timeout: 60_000 }, async () => { const id = "exmplr6pm01"; let live = true; let premerges = 0; const { run } = await incidentRun( id, resumableYtdlp(async ({ n, write }) => { premerges = Math.max(premerges, (await left(id)).filter((x) => /\.premerge-\d+\./.test(x)).length); await write(3000 + n * 600); if (n < 4) return "end"; live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; assert.equal(premerges, 1, "never two copies aside"); }); test("REVIEW-6 9: the stem lock names the RECORDER too — its live recorder keeps the lock though the editor that made it is gone", async () => { const { takeStemLock } = await import("./recordLive"); const dir = path.join(ROOT, "locks9"); await mkdir(dir, { recursive: true }); await writeFile(path.join(dir, ".x.live-9.ytdlp.rec.lock"), JSON.stringify({ pid: 2 ** 22 + 54321, recorderPid: process.pid, at: new Date().toISOString() })); const r = await takeStemLock(dir, ".x.live-9.ytdlp"); assert.equal(r.ok, false, "an orphan recorder still writes those files"); assert.match((r as { why: string }).why, /its recorder/); }); test("REVIEW-6 10: a RAW source (an audio stream landed as it is) stays in staging until the stored file is checked against it", { timeout: 60_000 }, async () => { const id = "exmplr6raw1"; let existedAtCheck = false; let checked = ""; const { run } = await incidentRun( id, async (args) => { await writeFile(`${outOf(args)}.${FAKE_A}`, "format=mp4;seconds=7200;v=none;"); return okExit; }, { meta: { ...YT_META(id), duration: 7200 }, deps: { join: null, merge: fakeMerge, verifyMerged: async (_m: string, streams: readonly string[]) => { existedAtCheck = streams.length > 0 && (await stat(streams[0]!).catch(() => null)) !== null; checked = streams[0] ?? ""; return { ok: true }; }, }, }, ); await run.catch(() => {}); assert.equal(existedAtCheck, true, "checked against the raw file, which was still there"); assert.equal(await stat(checked).catch(() => null), null, "the landed raw file removed after the check"); }); test("REVIEW-6 12: private while the editor was down — `endedBy` on the new row as when it happens while recording, and nothing removed", { timeout: 60_000 }, async () => { const id = "exmplr6bg01"; const { startedAt } = await waitingAtShutdown(id); await askBoot(id, startedAt); const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`; const r = await incidentRun(id, async () => assert.fail("nothing is recorded"), { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [1, 2, 3, 4, 5, 6], failWith: PRIVATE }, }); await r.run.catch(() => {}); const row = (await rowOf(id)).find((x) => x.startedAt !== startedAt)!; assert.equal(row.endedBy?.class, "private"); assert.equal(row.needsAttention, true); assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files kept"); }); test("REVIEW-6 13: one stream finished (its state gone), the other with its state — rebuilt per stream and resumed in place, not a fresh part", { timeout: 60_000 }, async () => { const id = "exmplr6ps01"; let live = true; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(3000); await rm(`${outOf(args)}.${FAKE_V}.ytdl`, { force: true }); return "die"; } await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await run).status, "landed"); assert.equal(outOf(calls[1]!), outOf(calls[0]!), "the same files"); }); // --- DESIGN-5 point 5 (the orchestrator's go): the insurance when a from-start part is far behind --------- const FRAG_LINE = (n: number, m: number) => `1: [download] 0.1% of ~ 9.00GiB at 5.00MiB/s ETA 02:00:00 (frag ${n}/${m})`; async function behindRun(id: string, frag: [number, number], o: { insurance?: boolean; insuranceWhenBehind?: boolean } = {}) { let live = true; const r = await incidentRun( id, resumableYtdlp(async ({ write, print, args, signal }) => { if (isInsurance(args)) { await write(60); await Promise.race([abortOf(signal), new Promise((res) => setTimeout(res, 2000))]); return { exitCode: null, stderrTail: "", signalled: true }; } print(FRAG_LINE(frag[0], frag[1])); await write(3000); await new Promise((res) => setTimeout(res, 300)); await write(7200); live = false; return "end"; }), { // Not keep-marked, no insurance asked: only the behind check can start one. request: { doNotClean: false, insurance: o.insurance }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5, ...(o.insuranceWhenBehind !== undefined ? { insuranceWhenBehind: o.insuranceWhenBehind } : {}) }, refresh: { stillLive: () => live }, }, ); await r.run.catch(() => {}); return r; } test("point 5: a from-start part whose first frag N/M shows it hours behind starts the live-edge insurance beside it, whatever the keep mark", { timeout: 60_000 }, async () => { const id = "exmplp5beh1"; const r = await behindRun(id, [10, 7200]); assert.ok(r.calls.some(isInsurance), "a live-edge recorder beside it"); const row = (await rowOf(id))[0]!; assert.equal(row.insurance?.by, "behind"); assert.ok(r.log.some((l) => /behind the live edge: a live-edge recorder \(the insurance\) starts beside it/.test(l))); }); test("point 5: a part that is NOT far behind (under 10 min) starts no insurance; the setting off or `insurance: false` starts none either", { timeout: 60_000 }, async () => { const near = await behindRun("exmplp5beh2", [7190, 7200]); assert.ok(!near.calls.some(isInsurance), "a minute behind: none"); const off = await behindRun("exmplp5beh3", [10, 7200], { insuranceWhenBehind: false }); assert.ok(!off.calls.some(isInsurance), "the setting off: none"); assert.ok(off.log.some((l) => /insuranceWhenBehind is off/.test(l))); const no = await behindRun("exmplp5beh4", [10, 7200], { insurance: false }); assert.ok(!no.calls.some(isInsurance), "asked not to: none"); }); test("point 5: the insurance's starts are bounded per HOUR (3), not per run — a fourth start waits the hour out", { timeout: 60_000 }, async () => { const id = "exmplp5hr01"; let live = true; let insurers = 0; const { run, waits } = await incidentRun( id, resumableYtdlp(async ({ write, args }) => { if (isInsurance(args)) { insurers++; await write(30); // It dies early, again and again (an ingest that keeps dropping). return { exitCode: 1, stderrTail: "ERROR: Connection reset by peer\n", signalled: false }; } await write(3000); await until(() => insurers >= 4, 4000); await write(7200); live = false; return "end"; }), { request: { insurance: true }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); assert.ok(insurers >= 4, `started past 3 in the run: ${insurers}`); assert.ok(waits.some((w) => w > 60_000 && w <= 3_600_000), "the fourth waited for the hour"); }); // --- REVIEW-7 ------------------------------------------------------------------------------ const NET = "ERROR: [youtube] x: Unable to download webpage: The read operation timed out"; test("REVIEW-7 1: a network outage — reads and resumes failing for the network — spawns nothing new and spends no restart: no wait over 10 minutes, and once it reads again the SAME files are resumed", { timeout: 60_000 }, async () => { const id = "exmplr7net1"; let live = true; const { run, calls, waits, log } = await incidentRun( id, resumableYtdlp(async ({ n, write }) => { if (n === 1) { await write(3000); return "die"; } // yt-dlp's own extraction fails too while the route is down. if (n <= 7) return { exitCode: 1, stderrTail: `${NET}\n`, signalled: false }; await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [2, 3, 4, 5, 6, 7, 8], failWith: NET, stillLive: () => live } }, ); assert.equal((await run).status, "landed"); assert.ok(waits.every((w) => w <= 600_000), `no wait over 10 min: ${waits.join(", ")}`); assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "only the same files, never a fresh part or the live edge"); assert.ok(!log.some((l) => /restart bound is reached/.test(l)), "no restart bound spent"); assert.equal(await storedSeconds(id), 7200); }); test("REVIEW-7 2: the stream ENDS as was_live while a part may be behind — NOT resumed (its formats are plain files: foreign bytes would be appended); landed and loud: download the VOD now", { timeout: 60_000 }, async () => { const id = "exmplr7was1"; const { run, calls, log } = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(3000); return "die"; }), { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "was_live" } }, ); await run.catch(() => {}); assert.equal(calls.length, 1, "no resume on was_live"); assert.ok(log.some((l) => /NOT resumed \(only a post_live stream/.test(l))); const row = (await rowOf(id))[0]!; assert.equal(row.needsAttention, true); assert.match(row.reason, /download the VOD now/); }); test("REVIEW-7 2 (b83460a1f): a part that reached the stream's end by itself is NOT resumed again on post_live", { timeout: 60_000 }, async () => { const id = "exmplr7end2"; const { run, calls } = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(7200); return "end"; }), { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "post_live" } }, ); assert.equal((await run).status, "landed"); assert.equal(calls.length, 1, "exit 0 at the end: nothing more"); }); test("REVIEW-7 3: an insurance that ends by itself while the from-start part is still behind is started again; one whose loop RETURNED is started anew by a later part found behind — and 're-armed' is said only when a start follows", { timeout: 60_000 }, async () => { const id = "exmplr7ins1"; let live = true; let insurers = 0; const { run, log } = await incidentRun( id, resumableYtdlp(async ({ n, write, print, args }) => { if (isInsurance(args)) { insurers++; await write(60); // The first two end by themselves (exit 0); then it is members-only // (a final class: the loop returns). if (insurers <= 1) return okExit; return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Join this channel to get access to members-only content\n", signalled: false }; } // (The fresh part comes after the second insurance's loop has returned.) if (isFresh(args)) await new Promise((r) => setTimeout(r, 400)); print(FRAG_LINE(10, 7200)); await write(3000); await until(() => insurers >= 2, 3000); if (n === 1 || !isFresh(args)) { await dropState(args); await noReuse(args); return "die"; } await until(() => insurers >= 3, 3000); await write(7200); live = false; return "end"; }), { request: { doNotClean: false, insurance: undefined }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); assert.ok(insurers >= 3, `started again after its own end, and anew after its loop returned: ${insurers}`); const starts = log.filter((l) => /a live-edge recorder \(the insurance\) starts beside it/.test(l)).length; assert.ok(starts >= 2, `two behind starts said: ${starts}`); assert.ok(!log.some((l) => /the insurance is re-armed beside it/.test(l)) || insurers >= 3, "never 're-armed' with nothing started"); }); test("REVIEW-7 (the re-arm removal): a keep-marked recording's insurance, stopped once the part caught up, is NOT started again by a resume that is not far behind", { timeout: 60_000 }, async () => { const id = "exmplr7nra1"; let live = true; let insurers = 0; let mainN = 0; const { run } = await incidentRun( id, resumableYtdlp(async ({ write, print, args, signal }) => { if (isInsurance(args)) { insurers++; await write(60); await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]); return { exitCode: null, stderrTail: "", signalled: true }; } mainN++; if (mainN === 1) { await write(3000); // Caught up with the live edge: the insurance stops after its margin. await until(() => insurers >= 1, 3000); print(FRAG_LINE(7200, 7200)); print("2: [download] 99.9% of ~ 1.00GiB (frag 7200/7200)"); await new Promise((r) => setTimeout(r, 300)); return "die"; } // The resume, a few fragments behind the head. print(FRAG_LINE(7195, 7200)); await write(7200); await new Promise((r) => setTimeout(r, 200)); live = false; return "end"; }), // Keep-marked (the default insurance), its margin short. { request: { insurance: undefined }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5, insuranceMarginMs: 5 }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); assert.equal(insurers, 1, `not started again on the restart: ${insurers}`); }); // --- REVIEW-7 4-8 -------------------------------------------------------------------------- test("REVIEW-7 4: a verification that failed is checked AGAIN by reverifyLiveLanding — verified and the stream done, the stream files go and the row says verified", { timeout: 60_000 }, async () => { const id = "exmplr7ver1"; let live = true; const r = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, verifyMerged: async () => ({ ok: false, why: "a transient read error" }) }, refresh: { stillLive: () => live } }, ); await r.run; assert.equal((await rowOf(id))[0]!.verification?.state, "failed"); assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`))); const { reverifyLiveLanding } = await import("./recordLive"); const out = await reverifyLiveLanding({ paths, slug: YT_SLUG, id, channelConfig: YT_CONFIG, deps: { verifyMerged: async () => ({ ok: true }) } }); assert.equal(out.ok && out.verified, true, JSON.stringify(out)); assert.deepEqual(await left(id), [], "the stream files, state and fragments went"); assert.equal((await rowOf(id))[0]!.verification?.state, "verified"); }); test("REVIEW-7 4 / REVIEW-8 3: a part whose fragments were dropped for want of disk is NOT 'verified whole' on the track spans alone — nothing removed, loud", { timeout: 60_000 }, async () => { const id = "exmplr7drp1"; let live = true; let free = 1e15; const { run, log } = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(3000); free = 1e9; await new Promise((r) => setTimeout(r, 150)); free = 1e15; await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, freeBytes: async () => free }, refresh: { stillLive: () => live } }, ); await run; assert.ok(log.some((l) => /byte check .* is skipped: they were dropped/.test(l))); const row = (await rowOf(id))[0]!; assert.equal(row.verification?.state, "failed"); assert.match(row.verification?.why ?? "", /cannot be proven whole/); assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files are kept"); }); test("REVIEW-8 3: one fragment's length comes from the HIGHEST fragment number, never the count of files left (5 kept of 3601 is not 30 min a fragment), capped at 10 s", async () => { const { fragmentSecondsOf } = await import("./recordLive"); const dir = path.join(ROOT, "frag8"); await mkdir(dir, { recursive: true }); const f = ".x.live-8.ytdlp.f136.mp4"; await writeFile(path.join(dir, f), "x"); for (const n of [3597, 3598, 3599, 3600, 3601]) await writeFile(path.join(dir, `${f}-Frag${n}`), "x"); const sec = await fragmentSecondsOf(dir, [f], 7200); assert.ok(sec !== undefined && sec <= 2.01, `about 2 s a fragment: ${sec}`); const g = ".x.live-9.ytdlp.f136.mp4"; await writeFile(path.join(dir, g), "x"); for (const n of [1, 2]) await writeFile(path.join(dir, `${g}-Frag${n}`), "x"); assert.ok(((await fragmentSecondsOf(dir, [g], 7200)) ?? 0) <= 10, "capped at 10 s"); }); test("REVIEW-7 5: a merge that fails leaves its output set aside (never at the finished name the next run would land)", async () => { const { resolvePart } = await import("./recordLive"); const dir = path.join(ROOT, "merge5"); await mkdir(dir, { recursive: true }); const stem = ".exmplr7mrg1.live-x.ytdlp"; await writeFile(path.join(dir, `${stem}.f136.mp4`), "format=mp4;seconds=60;a=none;"); await writeFile(path.join(dir, `${stem}.f140.m4a`), "format=mp4;seconds=60;v=none;"); const { livePartFiles: livePartFilesOf } = await import("../lib/liveCapture"); const g = livePartFilesOf("exmplr7mrg1", await readdir(dir)).find((x) => x.stem === stem)!; await assert.rejects( resolvePart(g, dir, { probe: fakeProbe, merge: async (args) => { await writeFile(args[args.length - 1]!, "format=mov,mp4;seconds=60;"); throw new Error("ffmpeg's merge reported: Packet corrupt"); }, say: () => {}, }), /set aside as .*merge-failed-/, ); const names = await readdir(dir); assert.ok(!names.some((n) => /\.merged\.(mp4|mkv)$/.test(n)), `no finished merge left: ${names.join(", ")}`); assert.ok(names.some((n) => /\.merge-failed-\d+\./.test(n))); }); test("REVIEW-7 6: with a live recorder holding the stem's lock, the boot's resume is refused BEFORE any repair — the torn tail and its fragments untouched", { timeout: 60_000 }, async () => { const id = "exmplr7lck1"; const { stem, startedAt } = await waitingAtShutdown(id, 3000); const v = `${stem}.${FAKE_V}`; await writeFile(`${v}-Frag52`, "seconds=60;#52;xx"); await appendFile(v, "seconds=60;"); const sizeBefore = (await stat(v)).size; // An orphan recorder of the last process still holds it (this pid is alive). await writeFile(`${stem}.rec.lock`, JSON.stringify({ pid: 2 ** 22 + 777, recorderPid: process.pid, at: new Date().toISOString() })); await askBoot(id, startedAt); let live = true; const r = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(7200); live = false; return "end"; }), { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await r.run.catch(() => {}); void sizeBefore; assert.ok(r.log.some((l) => /another recorder holds/.test(l)), "refused by the lock"); assert.ok(!r.log.some((l) => /truncated from/.test(l)), "no repair under a live writer"); assert.ok(!r.log.some((l) => /past its state .* removed before the resume/.test(l)), "no fragment removed under it"); assert.notEqual(outOf(r.calls[0]!), stem, "a fresh part instead"); await rm(`${stem}.rec.lock`, { force: true }); }); test("REVIEW-7 8: a raw source that must be copied with too little room — not landed, said plainly, everything kept", { timeout: 60_000 }, async () => { const id = "exmplr7rom1"; const { run } = await incidentRun( id, async (args) => { await writeFile(`${outOf(args)}.${FAKE_A}`, `format=mp4;seconds=7200;v=none;${"x".repeat(5000)}`); return okExit; }, { meta: { ...YT_META(id), duration: 7200 }, deps: { join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 2000 } }, ); await run.catch(() => {}); const row = (await rowOf(id))[0]!; assert.match(row.error ?? "", /landed by a copy .* needs .* free/); assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_A}`)), "kept"); }); // --- REVIEW-8 ------------------------------------------------------------------------------ test("REVIEW-8 1: one state read failing for a NON-network reason does not abandon the resumable part — resumed in place (with the insurance when it is far behind), never 'nothing on disk can be reused'", { timeout: 60_000 }, async () => { const id = "exmplr8one1"; let live = true; const { run, calls, log } = await incidentRun( id, resumableYtdlp(async ({ n, write, print, args, signal }) => { if (isInsurance(args)) { await write(60); await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 2000))]); return { exitCode: null, stderrTail: "", signalled: true }; } if (n === 1) { await write(3000); return "die"; } print(FRAG_LINE(10, 7200)); await write(7200); await new Promise((r) => setTimeout(r, 200)); live = false; return "end"; }), { request: { doNotClean: false, insurance: undefined }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { failReads: [2], failWith: "ERROR: [youtube] x: Failed to extract any player response; please report this issue", stillLive: () => live }, }, ); await run.catch(() => {}); const mains = calls.filter((c) => !isInsurance(c)); assert.equal(outOf(mains[1]!), outOf(mains[0]!), "the same files resumed, not a fresh part"); assert.ok(!log.some((l) => /nothing on disk can be reused with proof/.test(l))); assert.ok(calls.some(isInsurance), "the insurance beside the part found far behind"); }); test("REVIEW-8 2: a resume stopped inside an append (a torn tail the repair allows) is NOT 'damaged'; once the stream ends whole the row needs nobody", { timeout: 60_000 }, async () => { const id = "exmplr8dmg1"; let live = true; const { run, log } = await incidentRun( id, resumableYtdlp(async ({ n, write, tear }) => { if (n === 1) { await write(3000); return "die"; } if (n === 2) { await write(3600); await tear("video", 0.5); return "die"; } await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await run).status, "landed"); const row = (await rowOf(id))[0]!; assert.ok(row.parts.every((p) => !p.resumeDamaged), `no false damage: ${JSON.stringify(row.parts.map((p) => p.resumeDamaged))}`); assert.ok(!log.some((l) => /after the resume, .* the file is kept as it is/.test(l))); assert.equal(row.needsAttention, false); }); test("REVIEW-8 4: `offline` does not outlive the outage — a resume failed for the network, then the stream ended: the landed row is not 'NOTHING is recording'", { timeout: 60_000 }, async () => { const id = "exmplr8off1"; let live = true; const { run } = await incidentRun( id, resumableYtdlp(async ({ n, write }) => { if (n === 1) { await write(3000); return "die"; } live = false; return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Unable to download webpage: The read operation timed out\n", signalled: false }; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); const row = (await rowOf(id))[0]!; assert.equal(row.offline, undefined); assert.doesNotMatch(row.reason, /NOTHING is recording/); }); test("REVIEW-8 5: a raw source's copy asks the room the landing needs (its size plus 2 GB), not the 20 GB floor", { timeout: 60_000 }, async () => { const id = "exmplr8rom1"; const { run } = await incidentRun( id, async (args) => { await writeFile(`${outOf(args)}.${FAKE_A}`, `format=mp4;seconds=7200;v=none;${"x".repeat(5000)}`); return okExit; }, // The floor is 3 GB here and the disk has a little more: the recorder // starts, and the copy (5 kB + 2 GB) fits. { meta: { ...YT_META(id), duration: 7200 }, deps: { join: null, merge: fakeMerge, minFreeBytes: 3e9, freeBytes: async () => 3e9 + 100 } }, ); await run.catch(() => {}); const row = (await rowOf(id))[0]!; assert.doesNotMatch(row.error ?? "", /landed by a copy/); assert.equal(await storedSeconds(id), 7200); }); test("REVIEW-8 6: 'Verify again' takes the stem's lock — refused while a recorder holds it, nothing removed", { timeout: 60_000 }, async () => { const id = "exmplr8vlk1"; let live = true; const r = await incidentRun( id, resumableYtdlp(async ({ write }) => { await write(7200); live = false; return "end"; }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, verifyMerged: async () => ({ ok: false, why: "a transient read error" }) }, refresh: { stillLive: () => live } }, ); await r.run; const stem = outOf(r.calls[0]!); await writeFile(`${stem}.rec.lock`, JSON.stringify({ pid: 2 ** 22 + 99, recorderPid: process.pid, at: new Date().toISOString() })); const before = (await left(id)).length; const { reverifyLiveLanding } = await import("./recordLive"); const out = await reverifyLiveLanding({ paths, slug: YT_SLUG, id, channelConfig: YT_CONFIG, deps: { verifyMerged: async () => ({ ok: true }) } }); assert.equal(out.ok, false); assert.match((out as { error: string }).error, /recorder holds/); assert.equal((await left(id)).length, before, "nothing removed"); await rm(`${stem}.rec.lock`, { force: true }); });