Archilyzer · Source

archilyzer

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

commit 57a612ce1cb11e6ea0bd00a5316ada816bdf9074
parent 76f69a14e061a9e4ca80137ec473ba92c4e6d899
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 21:03:32 -0500

Merge lane/landing-fix: a landing removes or replaces only on proof

When the store keeps its own container nothing is removed and the run is not landed; a stored container is replaced only by a file proven to cover the stream from its start; a part is contained only in a proven part of the same kind; the store check fails closed. Proof of the start is what was recorded: YouTube from-start under 120 h, an HLS run whose playlist read listed the start, a Kick poll from the first segment.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MOPERATING.md | 13++++++++++++-
Mcommon/controller/recordLive.test.ts | 576+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/controller/recordLive.ts | 194+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/liveCapture.ts | 12++++++++++++
Meditor/CHANGELOG.md | 8++++++++
5 files changed, 721 insertions(+), 82 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1450,7 +1450,18 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note": holds bytes — an earlier run's, one from the live edge, one that cannot be landed as it is, fragments a recorder left — stays in the store's staging dir, listed as `keptParts` (files, sizes, why), and the row needs a person until acknowledged. A later recording does not clear that; nothing removes kept files automatically. On Kick, a - VOD that covers the stream removes the channel's live-edge part; one that does not keeps it. + VOD that covers the stream removes the channel's live-edge part; one that does not keeps it. A part not from the + start (a live-edge part, one no row describes) goes only when the landed file is from the start and at least the + ENDED stream's own duration less 60 s — never on a coverage by the clock. Only a part PROVEN to begin at the start + (`provenStart`: a YouTube `--live-from-start` part (not one that fell to index 0) on a stream under 120 h old; on Rumble, Twitch and the rest only a + first attempt whose playlist read still listed the start; a Kick VOD whose poll began at its first segment) counts as from the start for + a removal, a replacement or the coverage; an index-0 part, the browser path and a part of a row written before the + mark do not. A part with a picture is never "inside" an audio-only landed part, nor one merged here from separate + streams. A retry that wrote only its audio leaves that audio-only part staged beside the landed one, and the row + asks for a person (its sound is not proven inside the landed file). A stored container that cannot be read, or a `source-media` file no pointer names, counts as stored. **A recording already in the store** (an earlier run's landing, a shutdown's included) is replaced + only by a file that holds the whole stream from its start; otherwise nothing lands, every part stays listed + (`keptParts`), the run is `failed` ("not landed: …") and needs a person — and whenever the landing keeps the stored + container, nothing is removed. - **An editor shutdown is not a Cancel.** A run stopped by the editor going down (a restart, a rollout) is `interrupted` (`stoppedBy: "shutdown"`), never `cancelled`, and needs a person — Record again if the stream is still live. A person's Cancel is `cancelled`; it needs a person only when the stream was must-keep (`doNotClean` or a diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -184,8 +184,8 @@ test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once const log: string[] = []; await recordLiveRun({ paths, - request: { slug: SLUG, url: "https://rumble.com/v3ccccc-show.html", preclip: p.preclip }, - plan: { url: "https://rumble.com/v3ccccc-show.html", platform: "rumble", id: "v3ccccc" }, + 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), @@ -208,10 +208,10 @@ test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once handoff, }, }); - assert.deepEqual(asked, [{ slug: SLUG, id: "v3ccccc", every: 5 }]); + 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", "v3ccccc")); - assert.match(rec?.parts[0]?.stem ?? "", /^\.v3ccccc\.live-.+\.ytdlp$/); + 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 () => { @@ -508,14 +508,17 @@ const realLand = { }, 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: "234", protocol: "http_dash_segments_generator", vcodec: "none", acodec: "mp4a.40.2", url: "https://dash.example/234" }, - { format_id: "270", protocol: "http_dash_segments_generator", height: 1080, vcodec: "avc1", acodec: "none", url: "https://dash.example/270" }, + { 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" }, ], }); @@ -903,7 +906,7 @@ test("1.1: an earlier run's longer from-start part lands, and this run's live-ed 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 from-start part is inside the landed one and goes", async () => { +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. @@ -917,9 +920,11 @@ test("1.1: of this run's own parts, a shorter from-start part is inside the land }); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2); - assert.deepEqual((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)), []); + // 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, undefined); + 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"); @@ -978,23 +983,33 @@ test("2.3: only a landed from-start run that covers the stream supersedes; a liv 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")!; + 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. + // (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)); - const shortLog = short.log; - assert.equal((await short.run).status, "landed"); + await assert.rejects(short.run, /not landed/); assert.equal((await stillNeeds()).needsAttention, true, "a short partial does not supersede"); - assert.ok(shortLog.some((l) => /does not supersede/.test(l))); - const shortRow = (await rowOf(id)).find((r) => r.status === "landed" && r.fromStart && r.coverage)!; + 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, 610 s, against 600 s captured: covers. - const whole = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), live_status: "post_live", duration: 610 } }); + // (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"); @@ -1067,59 +1082,24 @@ const leftover = async (id: string, seconds: number) => { return f; }; -test("covered (a): a Kick VOD that covers the stream lands, the channel's live-edge part is removed, nobody is asked", async () => { - const KICK = { handling: "transcribe", url: "https://kick.com/synthb/videos", platform: "kick", name: "Synth Kick B" } as ChannelConfig; - const slug = "synth-kick-b"; - 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-f9637c98aaaa"; - const s = await recordLiveRun({ - paths, - request: { slug, url: "https://kick.com/synthb" }, - plan: { url: "https://kick.com/synthb", platform: "kick", id: null, kickChannel: "synthb" }, - channelConfig: KICK, - cookiePolicy: NO_COOKIES, - onLog: () => {}, - signal: new AbortController().signal, - deps: { - kickVod: async () => ({ id: uuid, url: `https://kick.com/synthb/videos/${uuid}` }), - refresh: refreshWith({ - id: uuid, - extractor: "kick:vod", - live_status: "is_live", - uploader_id: "synthb", - // Started 5000 s ago: the VOD's 5000 s is the whole stream. - release_timestamp: Math.floor(Date.now() / 1000) - 5000, - formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/y/360p30/playlist.m3u8" }], - }), - spawn: async ({ args }) => { - await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=1000;"); - return { exitCode: 0, stderrTail: "", signalled: false }; - }, - poll: async (o) => { - await writeFile(o.output, "format=mpegts;seconds=5000;"); - return { segments: 500, seconds: 5000, gaps: 0, firstSeq: 0, ended: "the VOD has not grown" }; - }, - land, - freeBytes: async () => 1e15, - handoff, - shuttingDown: () => false, - }, - }); - assert.equal(s.landed?.seconds, 5000); - assert.deepEqual((await readdir(path.join(paths.savedVideosDir, slug))).filter((n) => n.startsWith(`.${uuid}.`)), [], "the live-edge part went"); - const { listLiveRecordings } = await import("./liveRecordings"); - const row = (await listLiveRecordings(paths, { slug, id: uuid, all: true })).rows[0]!; - assert.equal(row.coverage?.covers, true); - assert.equal(row.keptParts, undefined); - assert.equal(row.removedParts?.length, 1); - assert.match(row.removedParts![0]!.why, /holds the whole stream/); - assert.equal(row.needsAttention, false); -}); - 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"); @@ -1147,7 +1127,7 @@ test("not covered (d): a stream whose length cannot be established keeps every o 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) }); + 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]!; @@ -1175,3 +1155,463 @@ test("a landing that fails removes nothing: the covered landing's other part and assert.equal(row.keptParts?.length, 2); assert.equal(row.needsAttention, true); }); + +// --- The landing and the store (lane landing-fix): a container already in the +// store is never deleted around nor replaced by a part not proven to hold it --- + +const dataDir = (id: string) => path.join(CORPUS, "channels", YT_SLUG, "data", id); +const storedSeconds = async (id: string): Promise<number | null> => { + 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 }; +const failEmpty = { exitCode: 1, stderrTail: EMPTY, signalled: false }; +const left = async (id: string) => (await readdir(store()).catch(() => [] as string[])).filter((n) => n.startsWith(`.${id}.`)); +// Run 1: `seconds` from its start, landed by an editor shutdown. +async function landedAtShutdown(id: string, seconds: number, request: Record<string, unknown> = {}) { + const ac = new AbortController(); + const r = await incidentRun( + id, + async (args) => { + await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`); + ac.abort(); + return { exitCode: null, stderrTail: "", signalled: true }; + }, + { signal: ac.signal, request, deps: { shuttingDown: () => true } }, + ); + 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("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, + 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<string, unknown>) { + 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, + 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"); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -65,6 +65,7 @@ import { classifyAttempt, extractionRefused, ffmpegLiveArgs, + firstSequenceOf, formatUnavailable, lastErrorLine, liveAttemptSchedule, @@ -97,7 +98,8 @@ import { liveRecordingCheckCommand } from "./liveRecordings"; import { setDoNotClean } from "../lib/doNotClean-server"; import type { Paths } from "../lib/paths"; import { detectPlatform } from "../lib/platform"; -import { savedVideoDir, savedVideoRoot } from "../lib/savedVideo"; +import { savedVideoDir, savedVideoPath, savedVideoRoot } from "../lib/savedVideo"; +import { loadSavedVideo, savedVideoPointerPath } from "../lib/savedVideo-server"; import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore"; import { getFreeBytes } from "../lib/diskSpace"; import { formatBytes } from "../lib/format"; @@ -1084,14 +1086,42 @@ async function recordLiveRunInner( // the same thing for a DVR playlist); "index0": `--no-live-from-start` with // ffmpeg told index 0 — for an extractor that does not mark a format from // the start; "now": the live edge. + // YouTube (REVIEW-LF-3 1): a `--live-from-start` run there either fails + // "no formats that can be downloaded from the start" (→ index 0, never + // marked) or downloads only the extractor's own fragment generator, which + // begins at fragment 0 for a stream under 120 h old (YoutubeDL.py's + // is_from_start format filter; extractor/youtube/_video.py MAX_DURATION). + // So the proof is the platform plus the age — not the metadata read's + // formats, which never carry the generator protocol (that read passes no + // --live-from-start: a real live record lists HLS formats only). + const youtube = plan.platform === "youtube" || /^youtube/i.test(String(meta?.extractor ?? "")); + const startProvable = (first: boolean): boolean => { + if (youtube) { + // Its age: from its start time, else (an ended stream) its duration. + const age = streamStartSec !== null ? now().getTime() / 1000 - streamStartSec : typeof meta?.duration === "number" ? (meta.duration as number) : null; + return age !== null && age < 120 * 3600; + } + return first && record.reach?.fromStart === true; + }; const ytdlpPart = async ( url: string, tag: string, mode: "from-start" | "index0" | "now", extraNote = "", + // The run's first attempt, made with no wait before it. + firstAttempt = false, ): Promise<RecorderOutcome> => { const file = separate ? stemPath(tag) : partPath(tag); const part = begin("ytdlp", url, file, mode !== "now"); + if (mode === "index0") part.index0 = true; + // PROVEN from the stream's start — a fact about what is recorded, not the + // flag passed (REVIEW-LF-2 1): YouTube's from-start formats are the + // extractor's own generator from fragment 0, on a stream under 120 h old + // (past it the generator starts 120 h back); any other `--live-from-start` + // (Rumble, Twitch: ffmpeg at the DVR playlist's first LISTED segment, a + // window that slides) only when THIS run's playlist read listed the + // start, and only for the first attempt (a wait lets the window slide). + if (mode === "from-start" && startProvable(firstAttempt)) part.provenStart = true; await save(); const args = ytdlpLiveArgs({ url, @@ -1164,6 +1194,9 @@ async function recordLiveRunInner( ...(deps.fetchBytes ? { fetchBytes: deps.fetchBytes } : {}), }).then(async (r) => { finish(part, `${r.segments} segment(s) from ${r.firstSeq ?? "?"}, ${r.gaps} gap(s); ${r.ended}`); + // Proven from the start only when the poll's first segment is the + // platform's first (REVIEW-LF-2 2). + if (r.firstSeq !== null && r.firstSeq <= firstSequenceOf("kick")) part.provenStart = true; await save(); }); } else { @@ -1198,7 +1231,7 @@ async function recordLiveRunInner( const n = (record.attempts ?? 0) + 1; const mode = step.mode === "live-edge" ? "now" : index0 ? "index0" : "from-start"; const tag = `ytdlp${mode === "index0" ? "-index0" : ""}${mode === "now" && fromStart ? "-edge" : ""}${n > 1 && !(mode === "index0" && n === 2) ? `-a${n}` : ""}`; - const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : ""); + const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : "", n === 1); const last = parts[parts.length - 1]!; const bytes = await bytesOf(last.stem); const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(last.stem) : null; @@ -1333,9 +1366,50 @@ async function recordLiveRunInner( const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s)); const at = (n: string) => path.join(slugStore, n); // Every part on disk now — this run's and an earlier run's — by its stem. + // WHAT THE STORE HOLDS for this id, failing CLOSED: a pointer that does not + // read, a stored file that cannot be reached, or a source-media file no + // pointer names is "stored, not proven" — never an empty store. + const storeState = async (): Promise<{ kind: "empty" } | { kind: "stored"; path: string } | { kind: "unknown"; why: string }> => { + const pointerFile = savedVideoPointerPath(videoDir); + const pst = await stat(pointerFile).then( + () => "there" as const, + (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? ("absent" as const) : ("error" as const)), + ); + if (pst === "error") return { kind: "unknown", why: "the store's pointer cannot be read" }; + const pointer = pst === "there" ? await loadSavedVideo(videoDir).catch(() => null) : null; + if (pst === "there" && !pointer) return { kind: "unknown", why: "the store's pointer does not read" }; + if (pointer) { + const sp = savedVideoPath(pointer); + const st = await stat(sp).then( + (x) => (x.isFile() ? ("file" as const) : ("other" as const)), + (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? ("absent" as const) : ("error" as const)), + ); + if (st === "file") return { kind: "stored", path: sp }; + if (st !== "absent") return { kind: "unknown", why: `the stored file ${path.basename(sp)} cannot be reached` }; + } + const names = await readdir(storeDir).then( + (x) => x, + (e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? [] : null), + ); + if (names === null) return { kind: "unknown", why: "the store's folder cannot be read" }; + const sm = names.find((n) => n.startsWith("source-media.")); + return sm + ? { + kind: "unknown", + why: + `${sm} is in the store with no pointer naming it (a landing stopped between the file and its record?) — ` + + "compare it with the staged parts and land or remove it by hand; until then nothing of this stream lands", + } + : { kind: "empty" }; + }; + // With a container stored, no file of a part is removed before the landing + // decides (the zero-byte files, a fragments-only group's state). + const storeHeld = (await storeState()).kind !== "empty"; const groups = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])); const partOf = new Map(parts.map((p) => [p.stem, p.part])); - type Candidate = { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles }; + // video: it holds a picture; merged: record-live merged it from separate + // streams here (its length is the longer stream's). + type Candidate = { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles; video: boolean | null; merged: boolean }; const candidates: Candidate[] = []; const unlandable: string[] = []; const unlandableGroups: { group: LivePartFiles; why: string; part?: LivePart }[] = []; @@ -1358,10 +1432,15 @@ async function recordLiveRunInner( if (got && "error" in got) { unlandable.push(`${g.stem}: ${got.error}`); unlandableGroups.push({ group: g, why: got.error, ...(part ? { part } : {}) }); - } else if (got) candidates.push({ file: got.file, seconds: got.seconds, group: g, ...(part ? { part } : {}) }); + } else if (got) { + // null: the probe failed — not known, so never "contained" (REVIEW-LF-2 4). + const pv = await probe(got.file, landSignal).catch(() => null); + const video = pv ? Boolean(pv.videoCodec) : null; + candidates.push({ file: got.file, seconds: got.seconds, group: g, video, merged: got.merged === true, ...(part ? { part } : {}) }); + } else { empty.push(g); - for (const f of [...g.finished, ...g.streams, ...g.scratch]) if ((await sizeOf(at(f))) === 0) await rm(at(f), { force: true }); + if (!storeHeld) for (const f of [...g.finished, ...g.streams, ...g.scratch]) if ((await sizeOf(at(f))) === 0) await rm(at(f), { force: true }); } } for (const u of unlandable) say(`Not landable: ${u}`); @@ -1390,12 +1469,13 @@ async function recordLiveRunInner( }); }; // Every part that is not the landed one, and why it would be kept. - type Other = { group: LivePartFiles; why: string; seconds?: number | null; part?: LivePart; extra?: string[] }; + // video: what the candidate holds (undefined: not a candidate, not probed). + type Other = { group: LivePartFiles; why: string; seconds?: number | null; part?: LivePart; extra?: string[]; video?: boolean | null }; const others: Other[] = []; for (const u of unlandableGroups) others.push({ group: u.group, why: `not landable as it is: ${u.why}`, ...(u.part ? { part: u.part } : {}) }); for (const g of empty) { // Fragments a recorder left hold media too; yt-dlp's resume state does not. - for (const f of g.scratch) if (/\.ytdl$/i.test(f)) await rm(at(f), { force: true }); + if (!storeHeld) for (const f of g.scratch) if (/\.ytdl$/i.test(f)) await rm(at(f), { force: true }); const part = partOf.get(g.stem); others.push({ group: g, why: "fragments a recorder left, not landable as they are", ...(part ? { part } : {}) }); } @@ -1446,12 +1526,31 @@ async function recordLiveRunInner( // Inside the landed file without asking how long the stream is: a shorter // part of THIS run, both from the start (both begin where the stream's // record begins). + // Never an index-0 part (`--no-live-from-start`, ffmpeg at the playlist's + // first LISTED segment) unless the playlist was read to reach the start: on + // a DVR window that slides, a later one starts later. Those go only by the + // coverage rule. + // PROVEN from the start: a part marked so when it was recorded (yt-dlp + // `--live-from-start`, a platform VOD from its first segment). An index-0 + // part, the browser path, and a part of a row written before the mark are + // not proven, whatever `fromStart` says. + const proven = (p: Pick<LivePart, "fromStart" | "provenStart"> | undefined) => p?.fromStart === true && p.provenStart === true; + // Never a part with a picture beside a landed part with none, nor beside a + // landed file merged here from separate streams (its length is the longer + // stream's: its picture may be shorter). const contained = (c: Candidate) => c !== best && c.part !== undefined && best.part !== undefined && - c.part.fromStart && - best.part.fromStart && + proven(c.part) && + proven(best.part) && + // Same kind only, as per-stream lengths are not known: a picture part + // inside a picture part not merged here; an audio-only part only inside + // an audio-only one (a part with both may hold less sound than its + // container's length, which is its longer stream's). + c.video !== null && + best.video !== null && + ((c.video && best.video && !best.merged) || (!c.video && !best.video)) && c.seconds !== null && best.seconds !== null && c.seconds <= best.seconds; @@ -1477,6 +1576,7 @@ async function recordLiveRunInner( seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file], + video: c.video, }); } if (separate && !record.missingStream) { @@ -1487,11 +1587,13 @@ async function recordLiveRunInner( // also decides superseding). Its own record says whether it was from the // start: this run's part, or an earlier run's by the channel's rows (a part // no row names is not known to be). - let landedFromStart: boolean | null = best.part ? best.part.fromStart : null; + // Proven, not merely marked fromStart (REVIEW-LF-1 1): this run's part, or + // an earlier run's by its row. + let landedFromStart: boolean | null = best.part ? proven(best.part) : null; if (landedFromStart === null) { const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); const p = rows.filter((r) => r.id === id).flatMap((r) => r.parts).find((x) => x.stem === best.group.stem); - landedFromStart = p ? p.fromStart : null; + landedFromStart = p ? proven(p) : null; } record.coverage = streamCoverage({ capturedSeconds: best.seconds, @@ -1502,11 +1604,28 @@ async function recordLiveRunInner( }); const cov = record.coverage; // Covered: every other part of the stream, this run's or an earlier one's, - // is inside the landed file by definition, and goes (recorded, with why). + // is inside the landed file, and goes (recorded, with why) — except a part + // that may hold the stream's END: one not from the start (a live-edge part, + // one no row describes), which goes only when the landed file is from the + // start and, on the media's own length, at least the ENDED stream's own + // duration less 60 s; never on a coverage by the clock, nor on a live or + // unknown-length stream. // Not covered — a live-edge landing, a partial, a stream whose length is // not known — every other part with bytes is kept and needs a person. + const placeRows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); + const placeOf = new Map(placeRows.filter((r) => r.id === id).flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x])); + const endedDuration = cov.basis === "duration" ? cov.streamSeconds : null; + const mayHoldEnd = (o: Other): boolean => { + // An audio-only part beside a landed file with a picture: that file's + // own sound may be shorter than its length (REVIEW-LF-2 4) — kept. + if (o.video === false && best.video !== false) return true; + if (o.video === null) return true; + const p = o.part ?? placeOf.get(o.group.stem); + if (proven(p)) return false; + return !(landedFromStart === true && best.seconds !== null && endedDuration !== null && best.seconds >= endedDuration - 60); + }; for (const o of others) { - if (cov.covers) { + if (cov.covers && !mayHoldEnd(o)) { toRemove.push({ group: o.group, why: `inside the landed file, which holds the whole stream from its start (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)}, ${cov.basis === "duration" ? "its duration" : "by the clock"})`, @@ -1538,6 +1657,50 @@ async function recordLiveRunInner( say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); throw new Error(record.error); }; + // NOTHING LANDED: the store keeps what it holds, and every part — the one + // that would have landed and every part meant for removal — stays, listed, + // needing a person. Nothing is removed. + const notLanded = async (why: string): Promise<RecordLiveSummary> => { + await keep(best.group, `not landed: ${why}`, { seconds: best.seconds, ...(best.part ? { part: best.part } : {}), extra: [best.file] }); + for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: nothing was landed`, r.o); + record.status = stopped?.status ?? "failed"; + if (stopped) record.stoppedBy = stopped.by; + record.endedAt = now().toISOString(); + record.error = `not landed: ${why}`; + if (kept.length) record.keptParts = kept; + sayKept(); + await save(); + // The operator's keep marks hold whatever landed (as main did). + if (req.doNotClean) { + await setDoNotClean(videoDir, true, { + by: "live-recording", + via: "record-live", + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(req.note ? { note: req.note } : {}), + }).catch((e: Error) => say(`"Do not clean" could not be set (${e.message}).`)); + } + await applyPendingKeep(paths, req.slug, id, onLog, opts.jobId).catch((e: Error) => say(`The pending keep could not be applied (${e.message}).`)); + summary.status = record.status; + say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); + if (!cancelled) throw new Error(record.error); + return summary; + }; + // A CONTAINER ALREADY IN THE STORE (an earlier run's landing, a shutdown's + // included) is replaced only by a file that holds the whole stream from its + // start (the coverage rule): "longer" is not containment — a live-edge part + // after a restart is longer and holds none of the stored start. + const store = await storeState(); + if (store.kind === "unknown") { + return notLanded(`${store.why}: a container may be stored, and nothing lands over it unproven`); + } + if (store.kind === "stored" && !cov.covers) { + const storedPath = store.path; + const storedSeconds = (await probe(storedPath, landSignal).catch(() => null))?.seconds ?? null; + return notLanded( + `the store already holds a recording of this stream (${storedSeconds !== null ? spanWords(storedSeconds) : "length unknown"}), ` + + "and this one is not proven to hold it (not the whole stream from its start): the stored one stays", + ); + } let landed: Awaited<ReturnType<typeof landMediaFile>>; try { landed = await landMediaFile({ @@ -1566,6 +1729,11 @@ async function recordLiveRunInner( ); } } + // The landing kept the store's own container: nothing of this run was + // stored, so nothing is removed. + if (landed.kept !== "new") { + return notLanded(`the store holds a recording as long or longer (${spanWords(landed.existingSeconds ?? 0)}); this one may hold time it does not`); + } for (const r of toRemove) await removeGroup(r.group, r.why, r.extra); // The landed part's files were staging scratch (it is moved or copied into // the store), and so were the streams a merge was made from. diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -449,6 +449,18 @@ export type LivePart = { // nothing: the stream that is missing ("unknown": the one that wrote could // not be read). missingStream?: MissingStream; + // Recorded `--no-live-from-start` with ffmpeg at the playlist's first listed + // segment: from the start only if the playlist reaches it. + index0?: boolean; + // Proven to begin at the stream's start, by what was recorded: a YouTube + // `--live-from-start` part (not one fallen to index 0) on a stream under + // 120 h old; another platform's + // `--live-from-start` only when that run's first playlist read listed the + // start; a platform VOD whose poll began at its first segment. A part + // without it (index-0, the browser path, a later attempt, rows written + // before the mark) is never taken as holding the start for a removal or a + // replacement. + provenStart?: boolean; }; export type MissingStream = "video" | "audio" | "unknown"; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,14 @@ # Changelog ## [Unreleased] +- **A live recording's landing never deletes around, or replaces, a recording already in the store that it is not + proven to hold.** + - When the landing keeps the container already stored, nothing is removed: the part and every part meant for + removal stay, listed, and the run says "not landed" and needs a person. Before, those parts were deleted. + - A stored container is replaced only by a file that holds the whole stream from its start; a longer live-edge + part (after a restart) no longer replaces the stream's start. + - A live-edge part goes only when the landed file is as long as the ended stream's duration less a minute; an + index-0 part is never taken as inside a longer one. - **Network exits (trial): rumble and twitch listings through named proxies.** - New `settings.network`: exits `{id, label, scheme, host, port, credentials, enabled}` (`socks5h`, `socks5`, `http`, `https`), a policy per platform, cookie-jar pins, `credentialsFile` and `startupProbe`. Absent = every