Archilyzer · Source

archilyzer

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

commit 9b439e1306af91f0a0b57fcf832f63de6a0797ed
parent a6bed6c8855c8a2587a5405ea5a0bb4030591bc4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 16:48:26 -0500

record-live: an insurance recorder that dies early says so and is started again, also beside a from-start restart

REVIEW-1 of live-guard-2, 3.1 and 3.2: an insurance recorder that exited
while the from-start recording was still catching up read "recorded the
live edge to the end", and it ran only once: a from-start restart (behind
the live edge again) had none, with the row still reading caught-up.

Now its exit is "died" (an exit before the catch-up or the stream's end, a
stall), "stopped" (a Cancel, a shutdown, a fall back to the live edge),
"ended" (a clean end, the grace after the stream ended), and it is started
again after it died or when a from-start restart re-arms it: the
catch-up timer is cleared, the tracker reads the new part afresh, a stop
is replaced. At most 3 starts a run (starts on the row).

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

Diffstat:
Mcommon/controller/liveRecordings.ts | 2++
Mcommon/controller/recordLive.test.ts | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/controller/recordLive.ts | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mcommon/lib/liveCapture.ts | 13+++++++++++--
4 files changed, 206 insertions(+), 36 deletions(-)

diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -163,6 +163,8 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: "caught-up": "the insurance recorder stopped: the from-start recording caught up", ended: "the insurance recorder recorded the live edge to the end", stalled: "the insurance recorder stalled and was stopped", + died: `the insurance recorder DIED before the start caught up${ins.reason ? ` (${ins.reason})` : ""}`, + stopped: `the insurance recorder was stopped${ins.reason ? ` (${ins.reason})` : ""}`, failed: `the insurance recorder recorded nothing${ins.reason ? ` (${ins.reason})` : ""}`, "not-started": `no insurance recorder${ins.reason ? ` (${ins.reason})` : ""}`, }; diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -1581,7 +1581,7 @@ test("slice 3 resume: ended with nothing left says so and still needs a person; // and stops once the from-start recorder has caught up (yt-dlp's `(frag N/M)` // on every stream) plus a margin — or runs the whole stream when asked. -const isInsurance = (args: string[]) => /\.ytdlp-insure$/.test(outOf(args)); +const isInsurance = (args: string[]) => /\.ytdlp-insure(?:-r\d+)?$/.test(outOf(args)); const FAST_INSURE = { insurancePollMs: 5, insuranceMarginMs: 10, insuranceGraceMs: 10 }; function insuranceFake(o: { mainSeconds?: number; edgeSeconds?: number; caughtUp?: boolean } = {}) { let started!: () => void; @@ -1636,7 +1636,7 @@ test("slice 4: a stream marked keep gets the insurance by default; it stops once assert.equal(f.state.stoppedBy(), "signal", "stopped after the catch-up"); assert.ok(waits.includes(60_000), "a pause after the from-start part's first bytes"); const row = (await rowOf(id))[0]!; - assert.deepEqual(row.insurance, { mode: "catch-up", by: "default", state: "caught-up" }); + assert.deepEqual(row.insurance, { mode: "catch-up", by: "default", state: "caught-up", starts: 1 }); assert.equal(s.landed?.seconds, 7200); assert.equal(row.coverage?.covers, true); assert.ok(row.removedParts?.some((r) => /ytdlp-insure$/.test(r.stem)), "removed only because the landed file holds the whole stream"); @@ -2218,3 +2218,86 @@ test("REVIEW 2.3: the free-space floor is read before a start-recovery try and t assert.equal(row2.insurance?.state, "not-started"); assert.ok(row2.spaceHeld?.some((x) => /insurance/.test(x.what))); }); + +// --- REVIEW-1 of live-guard-2: the insurance that dies, and is re-armed ------------ + +const until = async (cond: () => boolean, ms = 3000) => { + for (let t = 0; t < ms && !cond(); t += 10) await new Promise((r) => setTimeout(r, 10)); +}; +const abortOf = (signal: AbortSignal) => new Promise<void>((r) => (signal.aborted ? r() : signal.addEventListener("abort", () => r(), { once: true }))); + +test("REVIEW 3.1: an insurance recorder that dies early reads 'died', never 'to the end', and is started again", { timeout: 60_000 }, async () => { + const id = "exmplrv3101"; + let starts = 0; + let secondStopped = false; + const { run, calls, log } = await incidentRun( + id, + async (args, _n, signal, onLine) => { + if (isInsurance(args)) { + starts++; + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=120;"); + if (starts === 1) return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; + await abortOf(signal); + secondStopped = true; + return { exitCode: null, stderrTail: "", signalled: true }; + } + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); + onLine?.("1: [download] 10.0% of ~ 1.20GiB at 2.00MiB/s ETA 10:00 (frag 100/3000)"); + await until(() => starts >= 2); + onLine?.("1: [download] 99.9% of ~ 1.20GiB at 2.00MiB/s ETA 00:01 (frag 2990/3000)"); + await until(() => secondStopped); + return okExit; + }, + { request: { insurance: undefined }, deps: FAST_INSURE }, + ); + await run; + assert.equal(calls.filter(isInsurance).length, 2, "started again after it died"); + assert.ok(log.some((l) => /died early/.test(l))); + const row = (await rowOf(id))[0]!; + assert.equal(row.insurance?.starts, 2); + assert.equal(row.insurance?.state, "caught-up"); + assert.ok(!log.some((l) => /recorded the live edge to the end/.test(l))); +}); + +test("REVIEW 3.2: a from-start restart re-arms an insurance that had stopped after the catch-up", { timeout: 60_000 }, async () => { + const id = "exmplrv3201"; + let live = true; + let starts = 0; + let stoppedCount = 0; + const { run, calls } = await incidentRun( + id, + async (args, n, signal, onLine) => { + if (isInsurance(args)) { + starts++; + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=60;"); + await abortOf(signal); + stoppedCount++; + return { exitCode: null, stderrTail: "", signalled: true }; + } + if (n === 1) { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3000;"); + onLine?.("1: [download] 10.0% (frag 100/3000)"); + await until(() => starts >= 1); + onLine?.("1: [download] 99.9% (frag 2990/3000)"); + await until(() => stoppedCount >= 1); + // Then it stalls, and the watchdog stops it. + await abortOf(signal); + return { exitCode: null, stderrTail: "", signalled: true }; + } + // The restart from the start: behind again. + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); + onLine?.("1: [download] 10.0% (frag 100/3600)"); + await until(() => starts >= 2); + live = false; + onLine?.("1: [download] 99.9% (frag 3590/3600)"); + await until(() => stoppedCount >= 2); + return okExit; + }, + { request: { insurance: undefined }, deps: { ...FAST_INSURE, watchMs: 10, stallMs: 1500 }, refresh: { stillLive: () => live } }, + ); + await run; + assert.equal(calls.filter(isInsurance).length, 2, "a second insurance beside the restarted from-start recording"); + const row = (await rowOf(id))[0]!; + assert.equal(row.restarts?.count, 1); + assert.equal(row.insurance?.starts, 2); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -70,6 +70,7 @@ import { LIVE_INSURANCE_DELAY_MS, LIVE_INSURANCE_END_GRACE_MS, LIVE_INSURANCE_MARGIN_MS, + LIVE_INSURANCE_MAX_STARTS, catchUpTracker, insuranceDecision, restartRefusal, @@ -1431,67 +1432,142 @@ async function recordLiveRunInner( (await loadPendingKeep(paths, req.slug).catch(() => [])).some((e) => e.id === id); const decided = fromStart && liveStatus !== "is_upcoming" ? insuranceDecision({ asked: req.insurance, keepMarked }) : null; if (!decided && req.insurance) say("No insurance recorder: it runs only beside a from-start recording of a stream already live."); - const insureStop = new AbortController(); + // The insurance's stop: replaced when a from-start restart re-arms it. + let insureStop = new AbortController(); const mainDoneCtl = new AbortController(); - let insuranceStopFor: "caught-up" | "ended" | null = null; + let insuranceStopFor: "caught-up" | "ended" | "fallback" | null = null; let mainStem: string | null = null; let mainFromStart = false; const tracker = catchUpTracker(); let caughtUpTimer: NodeJS.Timeout | null = null; let graceTimer: NodeJS.Timeout | null = null; + let rearm: (() => void) | null = null; const margin = deps.insuranceMarginMs ?? LIVE_INSURANCE_MARGIN_MS; // The main recorder's parts: which one records now, and its progress. + // 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. const onMainStart = (mode: "from-start" | "index0" | "now", restart = false) => (stem: string) => { mainStem = stem; mainFromStart = mode !== "now"; tracker.reset(); - void restart; + if (!record.insurance) return; + if (mode === "now" && !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?.(); + } }; const onMainLine = (l: string) => { if (record.insurance?.mode !== "catch-up" || caughtUpTimer || insureStop.signal.aborted || !mainFromStart) return; if (!tracker.feed(l)) return; say(`The from-start recording has caught up with the live edge; the insurance recorder stops in ${spanWords(margin / 1000)}.`); + const stopping = insureStop; caughtUpTimer = setTimeout(() => { + caughtUpTimer = null; + if (stopping !== insureStop) return; insuranceStopFor = "caught-up"; - insureStop.abort(); + stopping.abort(); }, margin); }; + // True when re-armed; false when the main recording ended or a Cancel. + const waitRearm = () => + new Promise<boolean>((resolve) => { + if (mainDoneCtl.signal.aborted || signal.aborted) return resolve(false); + const end = () => resolve(false); + mainDoneCtl.signal.addEventListener("abort", end, { once: true }); + signal.addEventListener("abort", end, { once: true }); + rearm = () => { + rearm = null; + resolve(true); + }; + }); + // THE INSURANCE (slice 4), re-armed within LIVE_INSURANCE_MAX_STARTS: + // after it died early (REVIEW-1 3.1: an exit before the catch-up or the + // stream's end is `died`, never "to the end"), and after a from-start + // restart put the main behind again. const insureLoop = async (): Promise<void> => { - const ins: LiveInsurance = { mode: decided!.mode, by: decided!.by, state: "waiting" }; + const ins: LiveInsurance = { mode: decided!.mode, by: decided!.by, state: "waiting", starts: 0 }; record.insurance = ins; await save(); - const waitStop = AbortSignal.any([signal, insureStop.signal, mainDoneCtl.signal]); const notStarted = async (reason: string) => { - ins.state = "not-started"; + if (!ins.starts) ins.state = "not-started"; ins.reason = reason; await save(); }; - // The from-start part's first bytes (its extraction is done). - while (!waitStop.aborted && !record.fallback) { - if (mainStem && mainFromStart && (await bytesOf(mainStem)) > 0) break; - await sleep(deps.insurancePollMs ?? 5_000, waitStop); + for (;;) { + const stopNow = insureStop; + const waitStop = AbortSignal.any([signal, stopNow.signal, mainDoneCtl.signal]); + // The from-start part's first bytes (its extraction is done). + while (!waitStop.aborted && !record.fallback) { + if (mainStem && mainFromStart && (await bytesOf(mainStem)) > 0) break; + await sleep(deps.insurancePollMs ?? 5_000, waitStop); + } + if (record.fallback) return notStarted("the run fell back to the live edge"); + if (signal.aborted) return notStarted("stopped"); + if (mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began"); + if (stopNow.signal.aborted) { + if (!ins.starts) await notStarted("the from-start recording caught up before it began"); + if (!(await waitRearm())) return; + continue; + } + await waitFor(stretch(LIVE_INSURANCE_DELAY_MS), waitStop); + if (signal.aborted || mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began"); + if (stopNow.signal.aborted) continue; + if ((ins.starts ?? 0) >= LIVE_INSURANCE_MAX_STARTS) { + ins.reason = `not started again: at most ${LIVE_INSURANCE_MAX_STARTS} starts`; + await save(); + return; + } + if (!(await roomFor("the insurance recorder"))) return notStarted("the store's disk is under the free-space floor"); + ins.starts = (ins.starts ?? 0) + 1; + ins.state = "recording"; + delete ins.reason; + say( + `The insurance recorder records the live edge beside the from-start recording` + + `${ins.mode === "whole" ? " for the whole stream" : " until it catches up"} (${ins.by === "default" ? "the stream is marked keep" : "asked"})` + + `${ins.starts > 1 ? `, start ${ins.starts} of at most ${LIVE_INSURANCE_MAX_STARTS}` : ""}.`, + ); + const tag = ins.starts === 1 ? "ytdlp-insure" : `ytdlp-insure-r${ins.starts}`; + const o = await ytdlpPart(plan.url, tag, "now", "insurance; ", { insurance: true, noWait: true, stop: stopNow.signal }); + const bytes = await bytesOf(o.stem); + const errLine = lastErrorLine(o.stderrTail); + const cls = !o.signalled && o.exitCode !== 0 ? liveFailureClass(o.stderrTail) : null; + if (signal.aborted) ins.state = "stopped"; + else if (insuranceStopFor === "fallback") { + ins.state = "stopped"; + 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 + 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"}`; + } else { + ins.state = "died"; + ins.reason = o.stalled + ? "it stalled and was stopped" + : `it ${bytes > 0 ? "exited" : "recorded nothing and exited"} (${errLine ?? `yt-dlp exit ${o.exitCode ?? "null"}`}) before the from-start recording caught up`; + } + await save(); + if (ins.state === "died") { + say(`The insurance recorder died early (${ins.reason}); ${(ins.starts ?? 0) < LIVE_INSURANCE_MAX_STARTS ? "it is started again" : "not started again"}.`); + continue; + } + if (ins.state === "caught-up") { + if (!(await waitRearm())) return; + continue; + } + return; } - if (record.fallback) return notStarted("the run fell back to the live edge"); - if (signal.aborted) return notStarted("stopped"); - if (insureStop.signal.aborted) return notStarted("the from-start recording caught up before it began"); - if (mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began"); - await waitFor(stretch(LIVE_INSURANCE_DELAY_MS), waitStop); - if (signal.aborted || mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began"); - if (insureStop.signal.aborted) return notStarted("the from-start recording caught up before it began"); - if (!(await roomFor("the insurance recorder"))) return notStarted("the store's disk is under the free-space floor"); - ins.state = "recording"; - say( - `The insurance recorder records the live edge beside the from-start recording` + - `${ins.mode === "whole" ? " for the whole stream" : " until it catches up"} (${ins.by === "default" ? "the stream is marked keep" : "asked"}).`, - ); - const o = await ytdlpPart(plan.url, "ytdlp-insure", "now", "insurance; ", { insurance: true, noWait: true, stop: insureStop.signal }); - const bytes = await bytesOf(o.stem); - if (o.stalled) ins.state = "stalled"; - else if (bytes === 0 && !o.signalled) { - ins.state = "failed"; - ins.reason = lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`; - } else ins.state = insuranceStopFor === "caught-up" ? "caught-up" : "ended"; - await save(); }; const insurance: Promise<void> | null = decided ? insureLoop() : null; let index0 = false; diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -650,17 +650,24 @@ export const LIVE_INSURANCE_DELAY_MS = 60_000; export const LIVE_INSURANCE_MARGIN_MS = 5 * 60_000; // After the main recording ends with the stream read as ended. export const LIVE_INSURANCE_END_GRACE_MS = 2 * 60_000; +// Starts of the insurance recorder in one run: the first, after it died +// early, after a from-start restart put the main behind again. +export const LIVE_INSURANCE_MAX_STARTS = 3; // waiting for the from-start part's first bytes (and the pause) // recording it records // caught-up stopped: the from-start recording caught up (+ the margin) // ended its recorder ended (the stream ended, or the grace after it) -// stalled the stall watchdog stopped it (not restarted) +// stalled the stall watchdog stopped it (older rows) +// died it exited (or stalled) before the from-start recording +// caught up or the stream ended: started again within +// LIVE_INSURANCE_MAX_STARTS +// stopped a Cancel or a shutdown, or the run fell back to the live edge // failed it recorded nothing // not-started not needed or not possible: the from-start part never // recorded, the run fell back to the live edge, or it caught // up before the insurance began -export type LiveInsuranceState = "waiting" | "recording" | "caught-up" | "ended" | "stalled" | "failed" | "not-started"; +export type LiveInsuranceState = "waiting" | "recording" | "caught-up" | "ended" | "stalled" | "died" | "stopped" | "failed" | "not-started"; export type LiveInsurance = { mode: "catch-up" | "whole"; @@ -668,6 +675,8 @@ export type LiveInsurance = { by: "default" | "asked"; state: LiveInsuranceState; reason?: string; + // How many times it was started. + starts?: number; }; // Whether the insurance runs, and how: the request's `insurance` (true, false,