Archilyzer · Source

archilyzer

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

commit f5e2981b81344783a468c921cbe85202a78cc42c
parent 50aedbcc2a26db8502f697b131aac20e9af2ff3d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 22 Nov 2026 05:40:42 -0500

record-live: REVIEW-7 1-3: an outage spends nothing and resumes in place; resume on an end only for post_live; the insurance starts again

- 1: while the state read fails for the network, nothing is spawned and no
  restart is spent. The read is made again on a paced wait (20 s, 60 s,
  180 s, then every 5 min) for as long as it takes, loud on the row
  (`offline`).
  - A resume that failed for the network refunds its restart, is never put
    in resumeFailed, and is tried again on the same waits; growth resets it.
  - Test: reads and resumes failing for the network, then the network
    back. No wait over 10 min, only the same -o, no restart bound.
- 2: the resume on an end happens only when the last read is post_live; on
  was_live it lands and says "download the VOD now".
  - An in-run resume needs a read that says live.
  - An end found after a bound wait goes through the same decision.
  - After every resume each stream file must still be its kept
    fragments; it is said (`resumeDamaged`, loud) when it is not.
- 3: an insurance exit 0 while the from-start part is still behind counts
  as died and starts again within the hourly bound. A loop that returned
  is started anew by a later part found behind. "Re-armed" is logged only
  when a start follows.
- The trigger:
  - needs a read that says is_live (the run's first read counts);
  - says so on the part when the start time is unknown or no frag N/M was
    printed;
  - checks the stop again after the hour's wait.
- Tests for 6b980b489's tightening and for the re-arm removal, each red on
  the commit before its change.

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

Diffstat:
Mcommon/controller/liveRecordings.ts | 5+++++
Mcommon/controller/recordLive.test.ts | 146++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/recordLive.ts | 148++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/lib/liveCapture.ts | 8++++++++
Mcommon/lib/liveRecordings-server.ts | 7++++++-
5 files changed, 290 insertions(+), 24 deletions(-)

diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -210,7 +210,10 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: `LANDED WHILE THE STREAM WAS STILL LIVE (${v.landedWhileLive.why})${u !== null ? `: about ${spanWords(u)} of it, by the clock, were in no landed file at that moment` : ""} — what is landed is the stream SO FAR, not the whole`, ); } + if (v.offline) extra.unshift(`the stream's state cannot be read since ${v.offline.since} (the network?): NOTHING is recording; read again every few minutes (${v.offline.reads} so far), and resumed in place once it reads`); for (const p of v.parts ?? []) { + if (p.resumeDamaged) extra.unshift(`${p.stem ?? "a part"}: after a resume it is NOT its kept fragments (${p.resumeDamaged}) — kept as it is, never removed`); + if (p.behindUnknown) extra.push(`${p.stem ?? "a part"}: how far behind the live edge it was could not be told (${p.behindUnknown}): no live-edge insurance by the behind rule`); if (p.failureClass === "went-private") extra.push(`${p.stem ?? "a part"}: its fragment requests were answered 403 Forbidden and the stream reads private or removed — it went private while it was recorded; what is on disk is landed and nothing is removed`); if (p.failureClass === "url-refresh") extra.push(`${p.stem ?? "a part"}: yt-dlp could not refresh the stream's URL (the platform stopped serving the format — DVR switched off?) and ended by itself`); if (p.reused) extra.push(`${p.stem ?? "a part"} was resumed after it had ended, reusing ${p.reused.fragments} fragments already downloaded (only what came since was fetched)`); @@ -407,6 +410,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO ...(own?.verification ? { verification: own.verification } : {}), ...(own?.skippedFragments ? { skippedFragments: own.skippedFragments } : {}), ...(own?.landedWhileLive ? { landedWhileLive: own.landedWhileLive } : {}), + ...(own?.offline ? { offline: own.offline } : {}), attempts: own?.attempts ?? row.attempts, parts, slug, @@ -436,6 +440,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO parts: own?.parts ?? row.parts, landedWhileLive: own?.landedWhileLive ?? row.landedWhileLive, coverage: own?.coverage ?? row.coverage, + offline: own?.offline ?? row.offline, }), }; const shown = diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -89,7 +89,7 @@ const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const; // `stillLive` says it is still live. function refreshWith( meta: Record<string, unknown>, - opts: { failFirst?: string; stillLive?: () => boolean; failAfterFirst?: string; afterRead?: (n: number) => void; failReads?: number[]; failWith?: string } = {}, + opts: { failFirst?: string; stillLive?: () => boolean; failAfterFirst?: string; afterRead?: (n: number) => void; failReads?: number[]; failWith?: string; endedAs?: string } = {}, ) { let n = 0; let wrote = 0; @@ -102,7 +102,7 @@ function refreshWith( const dir = path.join(cwd, path.dirname(o)); wrote++; const ended = wrote > 1 && meta.live_status === "is_live" && !(opts.stillLive?.() ?? false); - await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(ended ? { ...meta, live_status: "was_live" } : meta)); + await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(ended ? { ...meta, live_status: opts.endedAs ?? "was_live" } : meta)); opts.afterRead?.(n); return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null }; }; @@ -4559,7 +4559,7 @@ test("REVIEW-6 3: before any fragment goes, each stream file must be byte for by // --- REVIEW-6 4-13 -------------------------------------------------------------------- -test("REVIEW-6 4: the stream ENDS while its from-start part is behind — resumed once to its end, not landed short", { timeout: 60_000 }, async () => { +test("REVIEW-6 4 / REVIEW-7 2: the stream ENDS (post_live) while its from-start part is behind — resumed once to its end, not landed short", { timeout: 60_000 }, async () => { const id = "exmplr6end1"; const { run, calls } = await incidentRun( id, @@ -4571,7 +4571,7 @@ test("REVIEW-6 4: the stream ENDS while its from-start part is behind — resume await write(7200); return "end"; }), - { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge } }, + { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "post_live" } }, ); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2, "one resume after the end"); @@ -4839,3 +4839,141 @@ test("point 5: the insurance's starts are bounded per HOUR (3), not per run — assert.ok(insurers >= 4, `started past 3 in the run: ${insurers}`); assert.ok(waits.some((w) => w > 60_000 && w <= 3_600_000), "the fourth waited for the hour"); }); + +// --- REVIEW-7 ------------------------------------------------------------------------------ + +const NET = "ERROR: [youtube] x: Unable to download webpage: The read operation timed out"; + +test("REVIEW-7 1: a network outage — reads and resumes failing for the network — spawns nothing new and spends no restart: no wait over 10 minutes, and once it reads again the SAME files are resumed", { timeout: 60_000 }, async () => { + const id = "exmplr7net1"; + let live = true; + const { run, calls, waits, log } = await incidentRun( + id, + resumableYtdlp(async ({ n, write }) => { + if (n === 1) { + await write(3000); + return "die"; + } + // yt-dlp's own extraction fails too while the route is down. + if (n <= 7) return { exitCode: 1, stderrTail: `${NET}\n`, signalled: false }; + await write(7200); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [2, 3, 4, 5, 6, 7, 8], failWith: NET, stillLive: () => live } }, + ); + assert.equal((await run).status, "landed"); + assert.ok(waits.every((w) => w <= 600_000), `no wait over 10 min: ${waits.join(", ")}`); + assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "only the same files, never a fresh part or the live edge"); + assert.ok(!log.some((l) => /restart bound is reached/.test(l)), "no restart bound spent"); + assert.equal(await storedSeconds(id), 7200); +}); + +test("REVIEW-7 2: the stream ENDS as was_live while a part may be behind — NOT resumed (its formats are plain files: foreign bytes would be appended); landed and loud: download the VOD now", { timeout: 60_000 }, async () => { + const id = "exmplr7was1"; + const { run, calls, log } = await incidentRun( + id, + resumableYtdlp(async ({ write }) => { + await write(3000); + return "die"; + }), + { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "was_live" } }, + ); + await run.catch(() => {}); + assert.equal(calls.length, 1, "no resume on was_live"); + assert.ok(log.some((l) => /NOT resumed \(only a post_live stream/.test(l))); + const row = (await rowOf(id))[0]!; + assert.equal(row.needsAttention, true); + assert.match(row.reason, /download the VOD now/); +}); + +test("REVIEW-7 2 (b83460a1f): a part that reached the stream's end by itself is NOT resumed again on post_live", { timeout: 60_000 }, async () => { + const id = "exmplr7end2"; + const { run, calls } = await incidentRun( + id, + resumableYtdlp(async ({ write }) => { + await write(7200); + return "end"; + }), + { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "post_live" } }, + ); + assert.equal((await run).status, "landed"); + assert.equal(calls.length, 1, "exit 0 at the end: nothing more"); +}); + +test("REVIEW-7 3: an insurance that ends by itself while the from-start part is still behind is started again; one whose loop RETURNED is started anew by a later part found behind — and 're-armed' is said only when a start follows", { timeout: 60_000 }, async () => { + const id = "exmplr7ins1"; + let live = true; + let insurers = 0; + const { run, log } = await incidentRun( + id, + resumableYtdlp(async ({ n, write, print, args }) => { + if (isInsurance(args)) { + insurers++; + await write(60); + // The first two end by themselves (exit 0); then it is members-only + // (a final class: the loop returns). + if (insurers <= 1) return okExit; + return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Join this channel to get access to members-only content\n", signalled: false }; + } + // (The fresh part comes after the second insurance's loop has returned.) + if (isFresh(args)) await new Promise((r) => setTimeout(r, 400)); + print(FRAG_LINE(10, 7200)); + await write(3000); + await until(() => insurers >= 2, 3000); + if (n === 1 || !isFresh(args)) { + await dropState(args); + await noReuse(args); + return "die"; + } + await until(() => insurers >= 3, 3000); + await write(7200); + live = false; + return "end"; + }), + { request: { doNotClean: false, insurance: undefined }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, + ); + await run.catch(() => {}); + assert.ok(insurers >= 3, `started again after its own end, and anew after its loop returned: ${insurers}`); + const starts = log.filter((l) => /a live-edge recorder \(the insurance\) starts beside it/.test(l)).length; + assert.ok(starts >= 2, `two behind starts said: ${starts}`); + assert.ok(!log.some((l) => /the insurance is re-armed beside it/.test(l)) || insurers >= 3, "never 're-armed' with nothing started"); +}); + +test("REVIEW-7 (the re-arm removal): a keep-marked recording's insurance, stopped once the part caught up, is NOT started again by a resume that is not far behind", { timeout: 60_000 }, async () => { + const id = "exmplr7nra1"; + let live = true; + let insurers = 0; + let mainN = 0; + const { run } = await incidentRun( + id, + resumableYtdlp(async ({ write, print, args, signal }) => { + if (isInsurance(args)) { + insurers++; + await write(60); + await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]); + return { exitCode: null, stderrTail: "", signalled: true }; + } + mainN++; + if (mainN === 1) { + await write(3000); + // Caught up with the live edge: the insurance stops after its margin. + await until(() => insurers >= 1, 3000); + print(FRAG_LINE(7200, 7200)); + print("2: [download] 99.9% of ~ 1.00GiB (frag 7200/7200)"); + await new Promise((r) => setTimeout(r, 300)); + return "die"; + } + // The resume, a few fragments behind the head. + print(FRAG_LINE(7195, 7200)); + await write(7200); + await new Promise((r) => setTimeout(r, 200)); + live = false; + return "end"; + }), + // Keep-marked (the default insurance), its margin short. + { request: { insurance: undefined }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5, insuranceMarginMs: 5 }, refresh: { stillLive: () => live } }, + ); + await run.catch(() => {}); + assert.equal(insurers, 1, `not started again on the restart: ${insurers}`); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -198,6 +198,9 @@ export const RECORDER_EXIT_DRAIN_MS = 3_000; // DESIGN-4 3: the waits before a resume after a fragment could not be // fetched, at the same fragment; past them a fresh from-start part. export const FRAGMENT_ABORT_WAITS_MS: readonly number[] = [20_000, 60_000, 180_000]; +// REVIEW-7 1: while the network is down, the waits between two reads (or two +// resumes): then every 5 min, for as long as it takes. Never a restart spent. +export const OFFLINE_READ_WAITS_MS: readonly number[] = [20_000, 60_000, 180_000, 300_000]; // The store's disk must have this much free before a recording starts (four // hours of 720p is ~6 GB, of 1080p ~9 GB). export const RECORD_LIVE_MIN_FREE_BYTES = 20 * 1024 ** 3; @@ -1245,6 +1248,9 @@ async function recordLiveRunInner( // read that says it ended is the end read the landing would make. let endRead = false; let endedByRefusal = false; + // REVIEW-7: what the LAST state read said (its live_status), or the class + // of its failure — `post_live` and a network failure decide what follows. + const lastRead: { status: string | null; failClass: LiveFailureClass | null } = { status: null, failClass: null }; const liveNow = async (confirm = true): Promise<"live" | "ended" | "unknown"> => { try { await refresh(); @@ -1283,9 +1289,13 @@ async function recordLiveRunInner( return "ended"; } say(`The stream's metadata could not be read (${msg.split("\n")[0]}).`); + lastRead.status = null; + lastRead.failClass = c; return "unknown"; } const ls = (await readMeta(videoDir))?.live_status; + lastRead.status = typeof ls === "string" ? ls : null; + lastRead.failClass = null; if (ls === "is_live") return "live"; if (ls === "was_live" || ls === "post_live" || ls === "not_live") { endRead = true; @@ -1392,6 +1402,8 @@ async function recordLiveRunInner( } const meta = await readMeta(videoDir); const liveStatus = typeof meta?.live_status === "string" ? meta.live_status : null; + // (The run's first read is the first "last read".) + lastRead.status = liveStatus; // A restart of a stream that has ended records nothing: what the // interrupted run left in staging lands (the slice-1 landing), or, with // nothing there, the row says so. @@ -1868,6 +1880,19 @@ async function recordLiveRunInner( } } if (fragAbort && part.fragmentErrors) await save(); + // REVIEW-7 2: after EVERY resume, each stream file must still be its kept + // fragments; said (and the part loud) when it is not. + if (opts.resume && separate && !part.fragmentsDropped) { + const g = await filesOf(stem); + for (const f of g?.streams ?? []) { + const eq = await streamEqualsFragments(slugStore, f).catch((e: Error) => ({ ok: false as const, why: e.message })); + if (eq && !eq.ok) { + part.resumeDamaged = eq.why; + say(`[${tag}] after the resume, ${eq.why}: the file is kept as it is and never removed; the row needs a person.`); + break; + } + } + } await save(); return { ...o, part, stem, stalled, ...(fragAbort ? { fragAbort } : {}), ...(urlRefreshHere ? { urlRefresh: true } : {}) }; }; @@ -2182,20 +2207,30 @@ async function recordLiveRunInner( // 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 = () => { + // True when a start follows (REVIEW-7 3: never "re-armed" in the log + // when nothing starts). + const rearmInsurance = (): boolean => { // Not while a live-edge main records already (REVIEW-4 1.2). - if (!record.insurance || !mainFromStart) return; + if (!record.insurance || !mainFromStart) return false; if (caughtUpTimer) clearTimeout(caughtUpTimer); caughtUpTimer = null; if (insureStop.signal.aborted && insuranceStopFor === "caught-up") { insureStop = new AbortController(); insuranceStopFor = null; } - rearm?.(); + const r = rearm; + r?.(); + return r !== null; }; // 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) => { + // REVIEW-7 7: a from-start part that printed no `frag N/M` line could + // not be judged behind or not — said on its part. + if (mainStem && mainStem !== stem && mainFromStart && !behindChecked.has(mainStem)) { + const prev = parts.find((x) => x.stem === mainStem)?.part; + if (prev && (prev.bytes ?? 0) > 0) prev.behindUnknown ??= "it printed no frag N/M line"; + } if (stem !== mainStem) mainTracker.reset(); mainStem = stem; mainFromStart = mode !== "now"; @@ -2222,7 +2257,15 @@ async function recordLiveRunInner( if (!fp || fp.total <= 0) return; behindChecked.add(mainStem); const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; - if (!Number.isFinite(startMs)) return; + const mainPart = parts.find((x) => x.stem === mainStem)?.part; + if (!Number.isFinite(startMs)) { + if (mainPart) mainPart.behindUnknown = "the stream's start time is not known"; + say(`${mainStem}: how far behind the live edge it is cannot be told (the stream's start time is not known): no live-edge insurance by the behind rule.`); + return; + } + // REVIEW-7 7: a live-edge recorder only beside a stream that reads LIVE + // (a boot run on a post_live stream behind must not start one). + if (lastRead.status !== "is_live") return; const behind = ((now().getTime() - startMs) / 1000) * (1 - fp.frag / fp.total); if (behind <= LIVE_INSURANCE_BEHIND_SECONDS) return; if (req.insurance === false) return; @@ -2230,13 +2273,19 @@ async function recordLiveRunInner( say(`${mainStem} is about ${spanWords(behind)} behind the live edge; no live-edge recorder beside it (settings.liveRecording.insuranceWhenBehind is off).`); return; } - if (!insurance) { - decided = { mode: "catch-up", by: "behind" }; + if (!insurance || insuranceReturned) { + // (REVIEW-7 3: also when an earlier insurance loop has returned.) + decided = decided ?? { mode: "catch-up", by: "behind" }; + if (insuranceReturned) { + insureStop = new AbortController(); + insuranceStopFor = null; + } say(`${mainStem} is about ${spanWords(behind)} behind the live edge: a live-edge recorder (the insurance) starts beside it, so the tail is held while it catches up.`); - insurance = insureLoop(); - } else { + startInsuranceLoop(); + } else if (rearmInsurance()) { say(`${mainStem} is about ${spanWords(behind)} behind the live edge: the insurance is re-armed beside it.`); - rearmInsurance(); + } else { + say(`${mainStem} is about ${spanWords(behind)} behind the live edge; the insurance recorder is already recording beside it.`); } }; const onMainLine = (l: string) => { @@ -2318,6 +2367,8 @@ async function recordLiveRunInner( say(`The insurance recorder has started ${recent.length} times in the last hour: the next start waits ${spanWords(ms / 1000)}.`); await waitFor(ms, waitStop); if (signal.aborted || mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began"); + // (REVIEW-7 7: stopped while it waited — no start spent on it.) + if (stopNow.signal.aborted) continue; } } if (!(await roomFor("the insurance recorder"))) return notStarted("the store's disk is under the free-space floor"); @@ -2342,7 +2393,13 @@ async function recordLiveRunInner( ins.reason = "the run fell back to the live edge"; } else if (insuranceStopFor === "caught-up") ins.state = "caught-up"; else if (insuranceStopFor === "ended" || (mainDoneCtl.signal.aborted && endRead)) ins.state = "ended"; - else if (!o.signalled && !o.stalled && o.exitCode === 0 && bytes > 0) ins.state = "ended"; // the live edge ended: the stream is over + // REVIEW-7 3: an exit 0 while the from-start part still records and + // has not caught up is not the stream's end — it died (an ingest + // pause ends a live-edge recorder too): started again. + else if (!o.signalled && !o.stalled && o.exitCode === 0 && bytes > 0 && !mainDoneCtl.signal.aborted && caughtUpStem !== mainStem) { + ins.state = "died"; + ins.reason = "it ended by itself while the from-start recording was still behind"; + } else if (!o.signalled && !o.stalled && o.exitCode === 0 && bytes > 0) ins.state = "ended"; // the live edge ended: the stream is over else if (cls === "ended" || cls === "private" || cls === "members" || cls === "disk") { ins.state = bytes > 0 ? "ended" : "failed"; ins.reason = errLine ?? `yt-dlp exit ${o.exitCode ?? "null"}`; @@ -2374,7 +2431,18 @@ async function recordLiveRunInner( return; } }; - let insurance: Promise<void> | null = decided ? insureLoop() : null; + let insurance: Promise<void> | null = null; + let insuranceReturned = false; + const insuranceLoops: Promise<void>[] = []; + const startInsuranceLoop = () => { + insuranceReturned = false; + const p = insureLoop().finally(() => { + insuranceReturned = true; + }); + insuranceLoops.push(p); + insurance = p; + }; + if (decided) startInsuranceLoop(); let index0 = false; let fromStartFailures = 0; let edgeFailures = 0; @@ -2833,6 +2901,28 @@ async function recordLiveRunInner( if (signal.aborted) break; state = await liveNow(); } + // REVIEW-7 1 — OFFLINE: while the state read fails for the NETWORK, + // nothing is spawned and no restart is spent: the read is made again + // on a paced wait (20 s, 60 s, 180 s, then every 5 min) for as long as + // it takes, said on the row; once it reads again, the part is resumed + // in place first. + if (state === "unknown" && lastRead.failClass === "network") { + const since = now().toISOString(); + let k = 0; + while (state === "unknown" && lastRead.failClass === "network" && !signal.aborted) { + const w = OFFLINE_READ_WAITS_MS[Math.min(k, OFFLINE_READ_WAITS_MS.length - 1)]!; + k++; + record.offline = { since, reads: k }; + await save(); + say(`The stream's state cannot be read (the network?): nothing is started; read again in ${spanWords(w / 1000)} (read ${k}).`); + await waitFor(stretch(w), signal); + if (signal.aborted) break; + state = await liveNow(); + } + delete record.offline; + await save(); + if (signal.aborted) break; + } if (state === "ended") { // REVIEW-6 4: the stream ended while its from-start part may still // be behind — an ended stream is still served from its start (the @@ -2842,7 +2932,14 @@ async function recordLiveRunInner( // refresh, and not seen caught up — yt-dlp ends a from-start // download at the stream's end.) const mayBeBehind = cur.o.signalled || cur.o.stalled || cur.o.exitCode !== 0 || cur.o.fragAbort !== undefined || cur.o.urlRefresh === true; - if (!endResumed && mayBeBehind && caughtUpStem !== cur.o.stem && !endedByRefusal && cur.mode === "from-start" && separate && !signal.aborted) { + // REVIEW-7 2: ONLY on `post_live` — a was_live stream's formats are + // ordinary files, and the same output name would have yt-dlp append + // foreign bytes to the stream files (measured). Otherwise it lands + // (short of the ended duration: "download the VOD now"). + if (mayBeBehind && !endResumed && lastRead.status !== "post_live" && cur.mode === "from-start" && !endedByRefusal) { + say(`The stream has ended (${lastRead.status ?? "its state"}): ${cur.o.part.stem} is NOT resumed (only a post_live stream is still served from its start); what is held lands — if it is short of the stream, download the VOD now.`); + } + if (!endResumed && mayBeBehind && lastRead.status === "post_live" && caughtUpStem !== cur.o.stem && !endedByRefusal && cur.mode === "from-start" && separate && !signal.aborted) { endResumed = true; let st = await resumeStateOf(cur.o.stem); if (!st.ok) { @@ -2903,7 +3000,9 @@ async function recordLiveRunInner( delete restarts.waiting; await save(); if (signal.aborted) break; - if ((await liveNow()) === "ended") break; + // (REVIEW-7 2: an end found after the wait goes through the same + // decision as any other — the loop reads again at its top.) + if ((await liveNow()) === "ended") continue; } // (A resume in place, when one is possible, needs only the floor plus // its stream files: REVIEW-6 7.) @@ -2921,7 +3020,7 @@ async function recordLiveRunInner( // no recovery. Only when that is impossible (no state, an unreadable // one, a stream past 120 h, or the resume writes nothing) does the // live-edge fallback below run. - if (cur.mode === "from-start" && !resumeFailed.has(cur.o.stem)) { + if (cur.mode === "from-start" && !resumeFailed.has(cur.o.stem) && state === "live") { let st = await resumeStateOf(cur.o.stem); // DESIGN-5 7: finished by yt-dlp itself (exit 0, merged) while live — // reuse what is downloaded, not fragment 0 again. @@ -2979,6 +3078,10 @@ async function recordLiveRunInner( // try at that fragment (DESIGN-4 3), not "wrote nothing". if (grew || (o.fragAbort && !signal.aborted)) { emptyInRow = 0; + if (grew) { + netTries.delete(o.stem); + delete record.offline; + } const partial = separate && !o.signalled && bytes > 0 ? (await missingStreamOf(o.stem)) !== null : false; cur = { o, bytes, mode: "from-start", partial }; continue; @@ -2991,11 +3094,18 @@ async function recordLiveRunInner( // REVIEW-6 5: a resume that failed for the network is tried again // (20 s, 60 s, 180 s), not given up after one try. const rcls = liveFailureClass(last); - const nt = (netTries.get(o.stem) ?? 0) + 1; - if (rcls === "network" && nt <= FRAGMENT_ABORT_WAITS_MS.length && bytes > 0) { + if (rcls === "network" && bytes > 0) { + // REVIEW-7 1: a resume that failed for the network spends no + // restart, never gives the stem up, and is tried again on the + // paced waits (then every 5 min) for as long as it takes. + restarts.count = Math.max(0, restarts.count - 1); + restarts.at.pop(); + const nt = (netTries.get(o.stem) ?? 0) + 1; netTries.set(o.stem, nt); - const w = FRAGMENT_ABORT_WAITS_MS[nt - 1]!; - say(`${o.stem}: the resume failed for the network; tried again in ${spanWords(w / 1000)} (${nt} of ${FRAGMENT_ABORT_WAITS_MS.length}).`); + const w = OFFLINE_READ_WAITS_MS[Math.min(nt, OFFLINE_READ_WAITS_MS.length) - 1]!; + record.offline = { since: record.offline?.since ?? now().toISOString(), reads: nt }; + await save(); + say(`${o.stem}: the resume failed for the network (no restart spent); tried again in ${spanWords(w / 1000)} (try ${nt}).`); await waitFor(stretch(w), signal); if (signal.aborted) break; cur = { o, bytes, mode: "from-start", partial: false }; @@ -3151,7 +3261,7 @@ async function recordLiveRunInner( insureStop.abort(); }, deps.insuranceGraceMs ?? LIVE_INSURANCE_END_GRACE_MS); } - await insurance; + await Promise.all(insuranceLoops); } if (caughtUpTimer) clearTimeout(caughtUpTimer); if (graceTimer) clearTimeout(graceTimer); diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -499,6 +499,11 @@ export type LivePart = { fragmentsDropped?: string; // A fresh from-start part after a stop (DESIGN-4 2), its number. fresh?: number; + // REVIEW-7 2: after a resume, a stream file that is not its kept fragments + // (why) — the resume may have appended what is not the stream. + resumeDamaged?: string; + // REVIEW-7 7: why the behind check could not tell how far behind it is. + behindUnknown?: string; // DESIGN-5 7: resumed after yt-dlp had finished it (a self-exit): its // state rebuilt at the fragment count the byte equation proves — the // fragments it reused (not fetched again). @@ -631,6 +636,9 @@ export type LiveRecordingRecord = { // could not be read): never "the whole stream"; how much of it, by the // clock at that moment, is in no landed file. landedWhileLive?: { at: string; unrecordedSeconds: number | null; why: string }; + // REVIEW-7 1: the state cannot be read for the network: nothing is started, + // the read is made again on a paced wait (since, how many reads). + offline?: { since: string; reads: number }; // Spawns that did not start because the store's disk was under the floor // (RECORD_LIVE_MIN_FREE_BYTES): what, when, and how much was free. spaceHeld?: LiveSpaceHeld[]; diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts @@ -94,6 +94,7 @@ export type LiveRecordingRow = { verification?: LiveVerification; skippedFragments?: { count: number; positions: number[] }; landedWhileLive?: { at: string; unrecordedSeconds: number | null; why: string }; + offline?: { since: string; reads: number }; // What the landing kept: this run's file stored ("new"), or the store's. kept?: "new" | "existing"; acknowledgedAt?: string; @@ -183,7 +184,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" | "lost" | "endedBy" | "awaitingResume" | "transcriptRedo" | "verification" | "skippedFragments" | "parts" | "landedWhileLive" | "coverage">>, + Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost" | "endedBy" | "awaitingResume" | "transcriptRedo" | "verification" | "skippedFragments" | "parts" | "landedWhileLive" | "coverage" | "offline">>, ): boolean { if (r.acknowledgedAt) return false; if (r.keptParts && r.keptParts.length > 0) return true; @@ -195,6 +196,9 @@ export function rowNeedsAttention( if (r.supersededBy) return false; // DESIGN-5 4: landed while the stream was still live — until acknowledged. if (r.landedWhileLive) return true; + // REVIEW-7 1: the state cannot be read (offline): nothing records meanwhile. + if (r.offline) return true; + if (r.parts?.some((p) => p.resumeDamaged)) return true; // REVIEW-6 4: landed SHORT of an ended stream's own duration — the rest is // in no file (and the archive line stops any later download): a person, // "download the VOD now". @@ -295,6 +299,7 @@ export function rowOfRecord( ...(rec.verification ? { verification: { ...rec.verification } } : {}), ...(rec.skippedFragments ? { skippedFragments: { ...rec.skippedFragments } } : {}), ...(rec.landedWhileLive ? { landedWhileLive: { ...rec.landedWhileLive } } : {}), + ...(rec.offline ? { offline: { ...rec.offline } } : {}), ...(rec.spaceHeld && rec.spaceHeld.length ? { spaceHeld: rec.spaceHeld.map((x) => ({ ...x })) } : {}), ...(rec.failureClass ? { failureClass: rec.failureClass } : {}), ...(rec.missingStream ? { missingStream: rec.missingStream } : {}),