Archilyzer · Source

archilyzer

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

commit e7a6d69a4878172f883008b1517e2d01aa6da714
parent a933fb940880bd42c03926b916ea312f329fa90a
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 19:09:04 -0500

record-live: no span of a live stream is left in no part while it can be fetched

REVIEW-3 of live-guard-2:

- 3.1: when a recorder dies or stalls, a live-edge recorder starts at once
  and, when the kept parts' union (from-start parts from 0, live-edge parts
  from their recorder's start) falls short of now by more than max(180 s,
  1 %) — the live edge's own lag plus the minute an exit and its read take —
  the span is set on the row as lost ("hours 1:12-3:40 are in no part yet",
  loud) and a from-start recovery runs beside the live-edge recorder: its
  first try at once, one at a time, at most 8 tries a run every 15 min,
  under the free-space floor and the rate-limit rule; a try is stopped once
  it reaches where the newest live-edge part begins (+60 s overlap for the
  join), and only then is the row quiet about the span.
- 3.2: a restart never stops a working insurance recorder; it is re-armed
  (within its 3 starts) beside a from-start recovery try.
- 1.1: an unreadable state after an exit restarts at the live edge
  meanwhile; after an empty recorder the state is read again at 2 and 8
  min; only the evidence (ended, three empty recorders) ends it. A read
  refused as ended/private is the platform's word.
- 4.1: a part not from the start goes only when the landed file is from
  the start and at least the ended stream's own duration less 60 s;
  nothing is assumed inside a live or unknown-length stream's file.

Tests whose streams were older than their parts (so the new gap recovery
fired) were given a stream start matching their first part; the stall
test now expects the live edge at once.

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

Diffstat:
Mcommon/controller/liveRecordings.ts | 9+++++++++
Mcommon/controller/recordLive.test.ts | 213+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----
Mcommon/controller/recordLive.ts | 206++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/lib/liveRecordings-server.ts | 4+++-
4 files changed, 382 insertions(+), 50 deletions(-)

diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -180,6 +180,14 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: if (v.spaceHeld && v.spaceHeld.length) extra.push(`NOT started for want of disk: ${v.spaceHeld.map((x) => x.what).join(", ")}`); if (v.restarts && v.restarts.count > 0) extra.push(`its recorder was restarted ${v.restarts.count} time${v.restarts.count === 1 ? "" : "s"} (stalled or died while live)`); if (v.restarts?.refused) extra.push(`NOT restarted again though the stream was live: ${v.restarts.refused}`); + if (v.lost && !v.fallback && v.startRecovery?.state !== "recovered") { + const hm = (x: number) => `${Math.floor(x / 3600)}:${String(Math.floor((x % 3600) / 60)).padStart(2, "0")}`; + extra.unshift( + v.lost.toSeconds !== null + ? `hours ${hm(v.lost.fromSeconds)}-${hm(v.lost.toSeconds)} are in no part yet (${spanWords(v.lost.toSeconds - v.lost.fromSeconds)})` + : "what lies before the live edge may be in no part (the stream's start time is not known)", + ); + } const tail = extra.length ? `; ${extra.join("; ")}` : ""; const cls = v.failureClass && v.failureClass !== "unknown" ? ` [${v.failureClass}]` : ""; switch (v.status) { @@ -350,6 +358,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO startRecovery: own?.startRecovery ?? row.startRecovery, restarts: own?.restarts ?? row.restarts, joins: own?.joins ?? row.joins, + lost: own?.lost ?? row.lost, spaceHeld: own?.spaceHeld ?? row.spaceHeld, }), }; diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -1400,14 +1400,15 @@ test("slice 3: a stalled recorder is stopped, the stream still live, a new part live = false; return { exitCode: 0, stderrTail: "", signalled: false }; }, - { deps: FAST_WATCH, refresh: { stillLive: () => live }, meta: { ...ytLiveMeta(id) } }, + // (The stream is as old as the stalled part: it had reached the live edge.) + { deps: FAST_WATCH, 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), "a pause before the restart"); + 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); @@ -1431,7 +1432,7 @@ test("slice 3: a recorder that exits with bytes while the stream still reads liv live = false; return { exitCode: 0, stderrTail: "", signalled: false }; }, - { deps: FAST_WATCH, refresh: { stillLive: () => live } }, + { 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); @@ -1449,7 +1450,7 @@ test("slice 3: restarts are bounded (6 an hour); past it the run lands what it h const { run, calls } = await incidentRun( id, async (args, n, signal) => hangAfter(100 * n)(args, n, signal), - { deps: FAST_WATCH, refresh: { stillLive: () => true } }, + { deps: FAST_WATCH, refresh: { stillLive: () => true }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 100 }, }, ); const s = await run; assert.equal(s.status, "landed"); @@ -2177,7 +2178,7 @@ test("REVIEW 2.1(a): a restart refused with a 429 gets ONE more after 15 min, th } return { exitCode: 1, stderrTail: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests\n", signalled: false }; }, - { deps: FAST_WATCH, refresh: { stillLive: () => true } }, + { deps: FAST_WATCH, 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"); @@ -2201,7 +2202,7 @@ test("REVIEW 2.1(b): a part that died WITH bytes on a 429 is classified and reco live = false; return okExit; }, - { deps: FAST_WATCH, refresh: { stillLive: () => live } }, + { 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); @@ -2359,7 +2360,7 @@ test("REVIEW2 3.2: a second and a third death while the stream reads live restar if (n === 3) live = false; return n === 3 ? okExit : deaths; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { deps: { ...FAST_WATCH, join: null }, 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"); @@ -2372,7 +2373,7 @@ test("REVIEW2 3.2: a second and a third death while the stream reads live restar await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); return deaths; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => true } }, + { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => true }, meta: { ...YT_META(id2), release_timestamp: Math.floor(Date.now() / 1000) - 300 } }, ); await b.run; assert.equal(b.calls.length, 1 + 6, "the first recorder and 6 restarts (the hour's bound)"); @@ -2392,7 +2393,7 @@ test("REVIEW2 3.1: three live-edge recorders in a row that capture nothing are t } return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => true } }, + { deps: { ...FAST_WATCH, join: null }, 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"); @@ -2430,7 +2431,7 @@ test("REVIEW2 3.3: the class is read from the recorder's last output — a 429 r live = false; return okExit; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { deps: { ...FAST_WATCH, join: null }, 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"); @@ -2534,3 +2535,195 @@ test("REVIEW2 2.1: the join's picture proof compares the two SOURCE parts across 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; + }, + { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null }, 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; + }, + { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null }, 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 }, 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, join: null }, 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"}`); + } +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -186,6 +186,9 @@ export const RECORD_LIVE_MIN_FREE_BYTES = 20 * 1024 ** 3; // Live-edge recorders in a row that capture nothing: the evidence a stream // that still reads live has ended (REVIEW-2 3.1 of live-guard-2). export const LIVE_EDGE_EMPTY_TO_END = 3; +// A from-start part short of the live edge by more than max(this, 1 % of the +// stream so far) leaves a span in no part: recovered beside the live edge. +export const LIVE_GAP_TOLERANCE_SECONDS = 180; // A restart after the editor's: the stream's state read again after these // waits when it could not be read (three reads over about ten minutes). export const LIVE_BOOT_STATE_READ_WAITS_MS: readonly number[] = [120_000, 480_000]; @@ -1038,7 +1041,16 @@ async function recordLiveRunInner( try { await refresh(); } catch (err) { - say(`The stream's metadata could not be read (${(err as Error).message.split("\n")[0]}).`); + const msg = (err as Error).message; + // A read refused because the stream is over, private or removed is the + // platform's word (REVIEW-3 1.1 of live-guard-2): it ends. + const c = liveFailureClass(msg); + if (c === "ended" || c === "private") { + say(`The stream's metadata says it is ${c === "ended" ? "over" : "private or removed"} (${msg.split("\n")[0]}).`); + endRead = true; + return "ended"; + } + say(`The stream's metadata could not be read (${msg.split("\n")[0]}).`); return "unknown"; } const ls = (await readMeta(videoDir))?.live_status; @@ -1411,6 +1423,13 @@ async function recordLiveRunInner( await save(); return false; }; + // The longest a part's files play (its streams' probes), 0 when unread. + const secondsOf = async (stem: string): Promise<number> => { + const g = await filesOf(stem); + let best = 0; + for (const f of g ? [...g.finished, ...g.streams] : []) best = Math.max(best, (await probe(path.join(slugStore, f)).catch(() => null))?.seconds ?? 0); + return best; + }; // Every file of the part, scratch too (the watchdog's growth). const allBytesOf = async (stem: string) => { const g = await filesOf(stem); @@ -1512,24 +1531,30 @@ async function recordLiveRunInner( // A from-start RESTART is behind the live edge again: the catch-up is // read afresh and a stopped insurance is re-armed (REVIEW-1 3.2 of // live-guard-2). A fall back to the live edge stops the insurance. + // Re-arm a stopped insurance (within its bound) beside a from-start + // capture that is behind again: a recovery try (REVIEW-3 3.2). + const rearmInsurance = () => { + if (!record.insurance) return; + if (caughtUpTimer) clearTimeout(caughtUpTimer); + caughtUpTimer = null; + if (insureStop.signal.aborted && insuranceStopFor === "caught-up") { + insureStop = new AbortController(); + insuranceStopFor = null; + } + rearm?.(); + }; + // A RESTART never stops a working insurance recorder (REVIEW-3 3.2 of + // live-guard-2): only the schedule's own fall back to the live edge does. const onMainStart = (mode: "from-start" | "index0" | "now", restart = false) => (stem: string) => { mainStem = stem; mainFromStart = mode !== "now"; tracker.reset(); if (!record.insurance) return; - if (mode === "now" && !insureStop.signal.aborted) { + if (mode === "now" && !restart && !insureStop.signal.aborted) { insuranceStopFor = "fallback"; insureStop.abort(); } - if (restart && mode !== "now") { - if (caughtUpTimer) clearTimeout(caughtUpTimer); - caughtUpTimer = null; - if (insureStop.signal.aborted && insuranceStopFor === "caught-up") { - insureStop = new AbortController(); - insuranceStopFor = null; - } - rearm?.(); - } + if (restart && mode !== "now") rearmInsurance(); }; const onMainLine = (l: string) => { if (record.insurance?.mode !== "catch-up" || caughtUpTimer || insureStop.signal.aborted || !mainFromStart) return; @@ -1576,6 +1601,7 @@ async function recordLiveRunInner( // The from-start part's first bytes (its extraction is done). while (!waitStop.aborted && !record.fallback) { if (mainStem && mainFromStart && (await bytesOf(mainStem)) > 0) break; + if (recoveryStem && (await bytesOf(recoveryStem)) > 0) break; await sleep(deps.insurancePollMs ?? 5_000, waitStop); } if (record.fallback) return notStarted("the run fell back to the live edge"); @@ -1669,19 +1695,43 @@ async function recordLiveRunInner( // the schedule above already tried). let lastMain: { o: Awaited<ReturnType<typeof ytdlpPart>>; bytes: number; mode: "from-start" | "index0" | "now"; partial: boolean } | null = null; let recovery: Promise<void> | null = null; + let recoveryRunning = false; + // The recovery try recording now (the insurance's re-arm watches it). + let recoveryStem: string | null = null; + // A GAP recovery (REVIEW-3 3.1): its tries stop once a from-start part + // reaches this stream second (where the newest live-edge part begins). + let gapTarget: number | null = null; const recoveryStop = new AbortController(); let edgeDone = false; - const recoverStart = async (useIndex0: boolean): Promise<void> => { - const rs: StartRecovery = { tries: 0, max: LIVE_RECOVERY_MAX_TRIES, everyMs: LIVE_RECOVERY_EVERY_MS, state: "waiting" }; + const recoverStart = async (useIndex0: boolean, ro: { gap?: boolean } = {}): Promise<void> => { + recoveryRunning = true; + try { + await recoverLoop(useIndex0, ro); + } finally { + recoveryRunning = false; + recoveryStem = null; + } + }; + const recoverLoop = async (useIndex0: boolean, ro: { gap?: boolean }): Promise<void> => { + // The tries of the run are one bound across every recovery (8). + const rs: StartRecovery = record.startRecovery && record.startRecovery.state !== "recovered" + ? record.startRecovery + : { tries: record.startRecovery?.tries ?? 0, max: LIVE_RECOVERY_MAX_TRIES, everyMs: LIVE_RECOVERY_EVERY_MS, state: "waiting" }; + rs.state = "waiting"; record.startRecovery = rs; const waitStop = AbortSignal.any([signal, recoveryStop.signal]); say( - `From its start is tried again beside the live edge: every ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}, ` + - `at most ${LIVE_RECOVERY_MAX_TRIES} times, one at a time; the live-edge recording is not touched.`, + ro.gap + ? `From its start is fetched again beside the live edge, at once, until it reaches where the live-edge part begins: ` + + `one try at a time, at most ${LIVE_RECOVERY_MAX_TRIES} a run, every ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}.` + : `From its start is tried again beside the live edge: every ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}, ` + + `at most ${LIVE_RECOVERY_MAX_TRIES} times, one at a time; the live-edge recording is not touched.`, ); let limited = false; + let first = true; while (rs.tries < rs.max) { - await (deps.recoveryWait ?? waitFor)(stretch(LIVE_RECOVERY_EVERY_MS), waitStop); + if (!(ro.gap && first)) await (deps.recoveryWait ?? waitFor)(stretch(LIVE_RECOVERY_EVERY_MS), waitStop); + first = false; if (waitStop.aborted || edgeDone) { rs.state = "stopped"; say(`Start recovery: the live-edge recording ${signal.aborted ? "was stopped" : "ended"} before try ${rs.tries + 1}; no more tries.`); @@ -1695,9 +1745,44 @@ async function recordLiveRunInner( } rs.tries++; rs.state = "trying"; - const o = await ytdlpPart(plan.url, `ytdlp-recover-r${rs.tries}`, useIndex0 ? "index0" : "from-start", `start recovery ${rs.tries}/${rs.max}; `, { + // A gap's try is stopped once it reaches the live-edge part's start + // (plus a minute's overlap for the join), then the span is held. + const reached = new AbortController(); + let covered = false; + let watcher: NodeJS.Timeout | null = null; + const tag = `ytdlp-recover-r${rs.tries}`; + const o = await ytdlpPart(plan.url, tag, useIndex0 ? "index0" : "from-start", `start recovery ${rs.tries}/${rs.max}; `, { recovery: true, + stop: reached.signal, + onStart: (stem) => { + recoveryStem = stem; + rearmInsurance(); + if (!ro.gap) return; + let busy = false; + watcher = setInterval(() => { + if (busy || reached.signal.aborted || gapTarget === null) return; + busy = true; + void secondsOf(stem) + .then((sec) => { + if (gapTarget !== null && sec >= gapTarget + 60) { + covered = true; + say(`Start recovery: try ${rs.tries} holds the stream to ${spanWords(sec)}, past where the live-edge part begins: the span is held; it is stopped.`); + reached.abort(); + } + }) + .finally(() => { + busy = false; + }); + }, watchMs); + }, }); + if (watcher) clearInterval(watcher); + recoveryStem = null; + if (covered) { + rs.state = "recovered"; + await save(); + break; + } const bytes = await bytesOf(o.stem); const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(o.stem) : null; // A try the watchdog stopped with nothing written failed; one with @@ -1749,7 +1834,8 @@ async function recordLiveRunInner( ); await save(); } - if (rs.state === "waiting" || rs.state === "trying") { + const endState = rs.state as StartRecovery["state"] as string; + if (endState === "waiting" || endState === "trying") { rs.state = "exhausted"; say(`Start recovery: all ${rs.max} tries made; the stream's start is NOT recorded.`); } @@ -1944,17 +2030,17 @@ async function recordLiveRunInner( if (cur.o.stalled) say(`The stream has ended: what was recorded lands (no restart).`); break; } - if (state === "unknown" && !cur.o.stalled) { - await refuse( - "the stream's state could not be read after its recorder ended", - "The stream's state could not be read after its recorder ended: what was recorded lands — the stream may be live and NOT recorded; the row needs a person.", - ); - break; - } + // A state that cannot be read never ends the recording (REVIEW-3 1.1): + // the live edge is restarted meanwhile; the next reads come after + // each recorder, paced (2 and 8 min after an empty one); only the + // evidence (ended, or three empty recorders in a row) ends it. + if (state === "unknown") say("The stream's state could not be read: restarted at the live edge meanwhile; it is read again after the recorder."); if (cls === "ended" || cls === "private" || cls === "members") { say(`The recorder said the stream is ${cls === "ended" ? "over" : cls === "private" ? "private or removed" : "members-only"}, but it reads live: restarted.`); } - let pause = LIVE_RESTART_WAIT_MS; + // At once after a recorder that held bytes; after an empty one, 30 s + // (2 and 8 min while the state cannot be read). + let pause = emptyInRow === 0 ? 0 : state === "unknown" ? (LIVE_BOOT_STATE_READ_WAITS_MS[emptyInRow - 1] ?? LIVE_RESTART_WAIT_MS) : LIVE_RESTART_WAIT_MS; if (cls === "rate-limited") { if (restartLimited) { await refuse( @@ -1980,6 +2066,51 @@ async function recordLiveRunInner( } if (pause) await waitFor(stretch(pause), signal); if (signal.aborted) break; + // NO SPAN OF A LIVE STREAM IN NO PART WHILE IT CAN BE FETCHED (REVIEW-3 + // 3.1): where do the kept parts reach on the stream's clock? From-start + // parts from 0, live-edge parts from their recorder's start; their + // union from 0. Short of now by more than max(180 s, 1 %) — the live + // edge's own lag (up to a minute) plus the minute the exit and the read + // take, which a whole-stream download is not spent on — the span is + // said lost-so-far (loud) and a from-start recovery runs beside the + // live-edge recorder until a from-start part reaches it. + if (fromStart) { + const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; + const elapsed = Number.isFinite(startMs) ? (now().getTime() - startMs) / 1000 : null; + const spans: [number, number][] = []; + for (const p of parts) { + const sec = await secondsOf(p.stem); + if (sec <= 0) continue; + if (p.part.fromStart && !p.part.index0) spans.push([0, sec]); + else if (Number.isFinite(startMs)) { + const at0 = (Date.parse(p.part.startedAt) - startMs) / 1000; + spans.push([at0, at0 + sec]); + } + } + spans.sort((a, b) => a[0] - b[0]); + const tol = elapsed !== null ? Math.max(LIVE_GAP_TOLERANCE_SECONDS, elapsed * 0.01) : LIVE_GAP_TOLERANCE_SECONDS; + let reach = 0; + for (const [a, b] of spans) if (a <= reach + tol) reach = Math.max(reach, b); + if (elapsed === null || elapsed - reach > tol) { + const hm = (x: number) => `${Math.floor(x / 3600)}:${String(Math.floor((x % 3600) / 60)).padStart(2, "0")}`; + record.lost = { fromSeconds: Math.round(reach), toSeconds: elapsed !== null ? Math.round(elapsed) : null }; + if (elapsed !== null) gapTarget = Math.max(gapTarget ?? 0, elapsed); + await save(); + say( + elapsed !== null + ? `Hours ${hm(reach)}-${hm(elapsed)} of the stream are in no part yet: fetched again from its start beside the live edge.` + : "The stream's start time is not known: what lies before the live edge may be in no part; fetched again from its start beside the live edge.", + ); + if (!recoveryRunning && (record.startRecovery?.tries ?? 0) < LIVE_RECOVERY_MAX_TRIES) { + recoveryRunning = true; + const prev = recovery; + recovery = (async () => { + await prev; + await recoverStart(index0, { gap: true }); + })(); + } + } + } restarts.count += 1; restarts.at.push(now().toISOString()); const k = restarts.count; @@ -2365,25 +2496,22 @@ async function recordLiveRunInner( // is inside the landed file by definition, and goes (recorded, with why). // 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. - // A PART THAT MAY HOLD THE STREAM'S END (REVIEW-2 1.1 of live-guard-2): one + // A PART THAT MAY HOLD THE STREAM'S END (REVIEW-2 1.1, REVIEW-3 4.1): one // not from the start (live edge, insurance, restart), this run's or an - // earlier one's (its row), or one no row describes, is removed only when - // its span is proven inside the landed file — on the STREAM's clock: its - // place (its recorder's start minus the stream's start, which the live - // edge's lag can only overstate) plus its length within a minute of the - // landed file's end, against the ended stream's own duration. Never on a + // earlier one's (its row), or one no row describes, is never removed on a // coverage by the clock. 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 streamStartMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; - const landedEnd = landedFromStart && best.seconds !== null ? best.seconds : null; + // REVIEW-3 4.1: on the media's own length, never the stream's start + // timestamp as the media's zero: a part not from the start goes only when + // the landed file is from the start and as long as the ENDED stream's own + // duration within a minute; on a live or unknown-length stream nothing is + // assumed inside it. + const endedDuration = cov.basis === "duration" ? cov.streamSeconds : null; const mayHoldEnd = (o: Other): boolean => { const p = o.part ?? placeOf.get(o.group.stem); - if (p?.fromStart) return false; - if (cov.basis !== "duration" || landedEnd === null || !p?.startedAt || !Number.isFinite(streamStartMs)) return true; - const secs = o.seconds ?? p.seconds ?? null; - if (secs === null) return true; - return (Date.parse(p.startedAt) - streamStartMs) / 1000 + secs > landedEnd + 60; + if (p?.fromStart && !p.index0) return false; + return !(landedFromStart && best.seconds !== null && endedDuration !== null && best.seconds >= endedDuration - 60); }; for (const o of others) { const laterEnd = mayHoldEnd(o); diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts @@ -175,7 +175,7 @@ export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, s // recording that holds the whole stream (supersededBy). export function rowNeedsAttention( r: Pick<LiveRecordingRow, "status" | "fallback" | "acknowledgedAt" | "supersededBy"> & - Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld">>, + Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost">>, ): boolean { if (r.acknowledgedAt) return false; if (r.keptParts && r.keptParts.length > 0) return true; @@ -183,6 +183,8 @@ export function rowNeedsAttention( if (r.status === "failed" || r.status === "interrupted") return true; if (r.status === "cancelled" && r.mustKeep === true) return true; if (r.fallback === "live-edge" && r.startRecovery?.state !== "recovered") return true; + // A span of the stream in no part (REVIEW-3 3.1), until a part holds it. + if (r.lost && r.startRecovery?.state !== "recovered") return true; if (r.restarts?.refused) return true; // A recorder (or a join) not started for want of disk. if (r.spaceHeld && r.spaceHeld.length) return true;