Archilyzer · Source

archilyzer

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

commit a6bed6c8855c8a2587a5405ea5a0bb4030591bc4
parent a6c5d7ffbd78e5eed5825310f894d0da1eda7581
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 16:43:53 -0500

record-live: a rate limit gets one restart after 15 min, one extra from-start pass at most, and the floor before every spawn

REVIEW-1 of live-guard-2, 2.1 to 2.3:

- Before a restart, what the recorder said is classified, also for a part
  that died WITH bytes (recorded on the part). ended, private, members and
  disk are not restarted; a 429 or the bot check gets ONE restart after
  15 min (no 30 s pause), a second is refused and needs a person. Only a
  stall restarts when the stream's state cannot be read.
- No from-start pass starts once a from-start part holds the stream up to
  now (the coverage rule by the clock), whatever is_live says; after a
  recorder that ENDED with bytes while the stream read live, at most one
  extra from-start pass is made, then refused.
- The free-space floor (20 GB) is read before every start-recovery try,
  restart and the insurance start; a spawn under it does not start and the
  row says so (spaceHeld, needing a person).

Tests changed with the rules: the restart bound is now shown with stalls
(exits with bytes stop after one extra pass), and a normal end's part
carries its exit's class.

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

Diffstat:
Mcommon/controller/liveRecordings.ts | 3+++
Mcommon/controller/recordLive.test.ts | 115++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Mcommon/controller/recordLive.ts | 114++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/liveCapture.ts | 5+++++
Mcommon/lib/liveRecordings-server.ts | 7++++++-
5 files changed, 223 insertions(+), 21 deletions(-)

diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -175,6 +175,7 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: (gaps.length ? ` — ${gaps.length} GAP${gaps.length === 1 ? "" : "S"} of about ${gaps.map((g) => spanWords(g.seconds)).join(", ")} (by the clock) NOT recorded` : ", each join checked by its sound"), ); } + 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}`); const tail = extra.length ? `; ${extra.join("; ")}` : ""; @@ -327,6 +328,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO ...(own?.restarts ? { restarts: own.restarts } : {}), ...(own?.insurance ? { insurance: own.insurance } : {}), ...(own?.joins ? { joins: own.joins } : {}), + ...(own?.spaceHeld ? { spaceHeld: own.spaceHeld } : {}), attempts: own?.attempts ?? row.attempts, parts, slug, @@ -346,6 +348,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO startRecovery: own?.startRecovery ?? row.startRecovery, restarts: own?.restarts ?? row.restarts, joins: own?.joins ?? row.joins, + spaceHeld: own?.spaceHeld ?? row.spaceHeld, }), }; const shown = diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -894,7 +894,9 @@ test("1.4: a normal stream end where yt-dlp exits 1 but the parts hold bytes lan assert.equal(row.status, "landed"); assert.equal(row.error, undefined); assert.equal(row.failureClass, undefined); - assert.equal(row.parts[0]!.error, undefined); + // What the recorder said at its end is classified on the part (REVIEW-1 2.1 + // of live-guard-2); the run is not failed for it. + assert.equal(row.parts[0]!.failureClass, "network"); assert.equal(row.needsAttention, false); }); @@ -1422,14 +1424,11 @@ test("slice 3: a recorder that exits with bytes while the stream still reads liv test("slice 3: restarts are bounded (3 an hour); past it the run lands what it has and the row needs a person", async () => { const id = "exmplbound1"; - const at = new Date("2026-11-21T10:00:00.000Z"); + // Each recorder writes and then stalls. const { run, calls } = await incidentRun( id, - async (args, n) => { - await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${100 * n};`); - return { exitCode: 1, stderrTail: "ERROR: Connection reset by peer\n", signalled: false }; - }, - { deps: { ...FAST_WATCH, now: () => at }, refresh: { stillLive: () => true } }, + async (args, n, signal) => hangAfter(100 * n)(args, n, signal), + { deps: FAST_WATCH, refresh: { stillLive: () => true } }, ); const s = await run; assert.equal(s.status, "landed"); @@ -2117,3 +2116,105 @@ test("REVIEW 1.5/1.6: the join's proof checks the PICTURE, refuses a cut that st assert.deepEqual(files.filter((n) => /\.temp\./.test(n)), [], `no scratch left: ${files.join(", ")}`); assert.equal(files.length, 1); }); + +// --- REVIEW-1 of live-guard-2: the restarts' politeness, the passes, the floor ----- + +test("REVIEW 2.1(a): a restart refused with a 429 gets ONE more after 15 min, then no more", { timeout: 60_000 }, async () => { + const id = "exmplrv2101"; + const { run, calls, waits } = await incidentRun( + id, + async (args, n) => { + if (n === 1) { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); + return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; + } + return { exitCode: 1, stderrTail: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests\n", signalled: false }; + }, + { deps: FAST_WATCH, refresh: { stillLive: () => true } }, + ); + await run; + assert.equal(calls.length, 3, "the first recorder, a restart refused with a 429, one more after 15 min"); + assert.ok(waits.includes(15 * 60_000)); + const row = (await rowOf(id))[0]!; + assert.match(row.restarts?.refused ?? "", /rate/); + assert.equal(row.needsAttention, true); +}); + +test("REVIEW 2.1(b): a part that died WITH bytes on a 429 is classified and recorded, and restarted only after 15 min", { timeout: 60_000 }, async () => { + const id = "exmplrv2102"; + let live = true; + const { run, calls, waits } = await incidentRun( + id, + async (args, n) => { + if (n === 1) { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); + return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 429: Too Many Requests\n", signalled: false }; + } + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); + live = false; + return okExit; + }, + { deps: FAST_WATCH, refresh: { stillLive: () => live } }, + ); + assert.equal((await run).status, "landed"); + assert.equal(calls.length, 2); + assert.ok(waits.includes(15 * 60_000), "the 15 min wait"); + assert.ok(!waits.includes(30_000), "not the 30 s pause"); + const row = (await rowOf(id))[0]!; + assert.equal(row.parts[0]!.failureClass, "rate-limited"); + assert.match(row.parts[0]!.error ?? "", /429/); +}); + +test("REVIEW 2.2: an ended stream that still reads live — no from-start pass once a part covers the stream, and at most ONE extra otherwise", { timeout: 60_000 }, async () => { + // (a) The first pass holds the stream to now (by the clock): no restart. + const a = await incidentRun("exmplrv2201", async (args) => { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); + return okExit; + }, { deps: FAST_WATCH, refresh: { stillLive: () => true } }); + await a.run; + assert.equal(a.calls.length, 1, "it already covers the stream: no second whole-stream download"); + // (b) Short of it, and the stream reads live for ever: one extra pass, then stop. + const b = await incidentRun("exmplrv2202", async (args) => { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3000;"); + return okExit; + }, { deps: FAST_WATCH, refresh: { stillLive: () => true } }); + await b.run; + assert.equal(b.calls.length, 2, "the first pass and ONE extra from-start pass"); + assert.match((await rowOf("exmplrv2202"))[0]!.restarts?.refused ?? "", /from-start pass/); +}); + +test("REVIEW 2.3: the free-space floor is read before a start-recovery try and the insurance start; a spawn that would breach it does not start, and the row says so", { timeout: 60_000 }, async () => { + // A recovery try with no room: the disk is full after the run's start. + let reads = 0; + const r = await incidentRun( + "exmplrv2301", + async (args, n) => { + if (n <= 3) return failEmpty; + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); + await new Promise((res) => setTimeout(res, 100)); + return okExit; + }, + { recovery: "immediate", deps: { freeBytes: async () => (++reads >= 2 ? 0 : 1e15) } }, + ); + await r.run; + assert.equal(r.calls.filter(isRecovery).length, 0, "no recovery try was started"); + const row = (await rowOf("exmplrv2301"))[0]!; + assert.equal(row.startRecovery?.state, "gave-up"); + assert.equal(row.startRecovery?.failureClass, "disk"); + assert.ok(row.spaceHeld?.some((x) => /start recovery/.test(x.what))); + assert.equal(row.needsAttention, true); + // The insurance with no room. + let reads2 = 0; + const f = insuranceFake({ caughtUp: false }); + const i = await incidentRun( + "exmplrv2302", + async (args, n, sig, onLine) => + Promise.race([f.attempt(args, n, sig, onLine), new Promise<typeof okExit>((res) => setTimeout(() => res(okExit), 300))]), + { request: { insurance: undefined }, deps: { ...FAST_INSURE, freeBytes: async () => (++reads2 >= 2 ? 0 : 1e15) } }, + ); + await i.run; + assert.equal(i.calls.filter(isInsurance).length, 0); + const row2 = (await rowOf("exmplrv2302"))[0]!; + assert.equal(row2.insurance?.state, "not-started"); + assert.ok(row2.spaceHeld?.some((x) => /insurance/.test(x.what))); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -1333,6 +1333,18 @@ async function recordLiveRunInner( for (const f of g ? [...g.finished, ...g.streams] : []) n += await sizeOf(path.join(slugStore, f)); return n; }; + // THE FLOOR BEFORE EVERY SPAWN (REVIEW-1 2.3 of live-guard-2): a recorder, + // a try, a restart or the insurance starts only with + // RECORD_LIVE_MIN_FREE_BYTES free on the store's disk; one that would breach + // it does not start, and the row says so (spaceHeld, needing a person). + const roomFor = async (what: string): Promise<boolean> => { + const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0); + if (free >= RECORD_LIVE_MIN_FREE_BYTES) return true; + (record.spaceHeld ??= []).push({ what, at: now().toISOString(), freeBytes: free }); + say(`${what}: NOT started — the store's disk has ${formatBytes(free)} free, at least ${formatBytes(RECORD_LIVE_MIN_FREE_BYTES)} are needed.`); + await save(); + return false; + }; // Every file of the part, scratch too (the watchdog's growth). const allBytesOf = async (stem: string) => { const g = await filesOf(stem); @@ -1429,10 +1441,11 @@ async function recordLiveRunInner( let graceTimer: NodeJS.Timeout | null = null; const margin = deps.insuranceMarginMs ?? LIVE_INSURANCE_MARGIN_MS; // The main recorder's parts: which one records now, and its progress. - const onMainStart = (mode: "from-start" | "index0" | "now") => (stem: string) => { + const onMainStart = (mode: "from-start" | "index0" | "now", restart = false) => (stem: string) => { mainStem = stem; mainFromStart = mode !== "now"; tracker.reset(); + void restart; }; const onMainLine = (l: string) => { if (record.insurance?.mode !== "catch-up" || caughtUpTimer || insureStop.signal.aborted || !mainFromStart) return; @@ -1465,6 +1478,7 @@ async function recordLiveRunInner( 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` + @@ -1516,6 +1530,12 @@ async function recordLiveRunInner( say(`Start recovery: the live-edge recording ${signal.aborted ? "was stopped" : "ended"} before try ${rs.tries + 1}; no more tries.`); break; } + if (!(await roomFor(`start recovery try ${rs.tries + 1}`))) { + rs.state = "gave-up"; + rs.failureClass = "disk"; + rs.lastError = "the store's disk is under the free-space floor"; + break; + } 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}; `, { @@ -1705,12 +1725,56 @@ async function recordLiveRunInner( // when a stream is over), an exit lands. Bounded: 3 in any hour, 12 in // the run, and the store's disk must have room. let cur = lastMain; + // A rate limit gets ONE more restart after LIVE_RATE_LIMIT_WAIT_MS, as + // slice 1's attempts do; a second is not restarted (REVIEW-1 2.1). + let restartLimited = false; + // After a recorder ENDED with bytes and the stream still reading live, + // at most one more from-start pass (REVIEW-1 2.2): a stream that has + // ended may read live for a while, and each pass is the whole stream. + let extraPasses = 0; + 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; + }; while (cur && !signal.aborted && !pathB) { const stalledWithBytes = cur.o.stalled && cur.bytes > 0; const exitedWithBytes = !cur.o.signalled && cur.bytes > 0 && !cur.partial; const failedRestart = cur.o.part.restart !== undefined && cur.bytes === 0 && !(cur.o.signalled && !cur.o.stalled); if (!stalledWithBytes && !exitedWithBytes && !failedRestart) break; const why = cur.o.stalled ? "stalled" : exitedWithBytes ? "exited while the stream was live" : "recorded nothing"; + // What the recorder said, classified — also for a part WITH bytes. + const cls: LiveFailureClass | null = + !cur.o.signalled && cur.o.exitCode !== 0 ? liveFailureClass(cur.o.stderrTail) : null; + if (cls && cls !== "unknown") { + cur.o.part.failureClass = cls; + cur.o.part.error ??= lastErrorLine(cur.o.stderrTail) ?? `yt-dlp exit ${cur.o.exitCode ?? "null"}`; + await save(); + } + const restarts = (record.restarts ??= { count: 0, at: [] }); + const refuse = async (r: string, words: string) => { + restarts.refused = `${why}; ${r}`; + await save(); + say(words); + }; + if (cls === "disk" || cls === "ended" || cls === "private" || cls === "members") { + if (cls === "disk") await refuse("the store's disk cannot take it", "NOT restarted: the store's disk cannot take it; what was recorded lands."); + else say(`Not restarted: the recorder said the stream is ${cls === "ended" ? "over" : cls === "private" ? "private or removed" : "members-only"}.`); + break; + } + let pause = LIVE_RESTART_WAIT_MS; + if (cls === "rate-limited") { + if (restartLimited) { + await refuse("rate-limited again after the 15 min wait", "NOT restarted: rate-limited again after the 15 min wait; what was recorded lands, and the row needs a person."); + break; + } + restartLimited = true; + say(`${cur.o.part.stem}: refused by a rate limit or the bot check — ONE restart after ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)}, then no more.`); + await waitFor(stretch(LIVE_RATE_LIMIT_WAIT_MS), signal); + if (signal.aborted) break; + pause = 0; + } let state = await liveNow(); if (state === "live" && exitedWithBytes) { say(`${cur.o.part.stem}: its recorder exited while the stream reads live; read again in ${spanWords(LIVE_RESTART_CONFIRM_MS / 1000)} before restarting.`); @@ -1722,24 +1786,48 @@ 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 && !failedRestart) { + // Only a stall restarts on a state that could not be read. + if (state === "unknown" && !cur.o.stalled) { say("The stream's state could not be read: what was recorded lands (no restart)."); break; } - const restarts = (record.restarts ??= { count: 0, at: [] }); - const refusal = - restartRefusal(restarts, now().getTime()) ?? - ((await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0)) < RECORD_LIVE_MIN_FREE_BYTES - ? `the store's disk has less than ${formatBytes(RECORD_LIVE_MIN_FREE_BYTES)} free` - : null); + if (cur.mode !== "now") { + // A from-start part that holds the stream up to now (the coverage + // rule, by the clock): no further from-start pass, whatever is_live + // says. + let longest = 0; + for (const p of parts) if (p.part.fromStart && !p.part.recovery && !p.part.insurance) longest = Math.max(longest, await secondsOf(p.stem)); + const c = streamCoverage({ + capturedSeconds: longest, + endMeta: null, + streamStartedAt: record.streamStartedAt ?? null, + lastEndedAt: now().toISOString(), + wholeFromStart: true, + }); + if (c.covers) { + say(`A part from its start already holds the stream to now (${spanWords(longest)} of ${spanWords(c.streamSeconds ?? 0)}): no further from-start pass.`); + break; + } + if (exitedWithBytes && extraPasses >= 1) { + await refuse( + "one extra from-start pass was already made after a recorder ended with the stream reading live", + "NOT restarted: one extra from-start pass was already made after a recorder ended while the stream read live; what was recorded lands, and the row needs a person.", + ); + break; + } + } + const refusal = restartRefusal(restarts, now().getTime()); if (refusal) { - restarts.refused = `${why}; ${refusal}`; - await save(); - say(`NOT restarted (${refusal}) though the stream is live: what was recorded lands, and the row needs a person.`); + await refuse(refusal, `NOT restarted (${refusal}) though the stream is live: what was recorded lands, and the row needs a person.`); + break; + } + if (!(await roomFor(`restart ${restarts.count + 1}`))) { + await refuse(`the store's disk has less than ${formatBytes(RECORD_LIVE_MIN_FREE_BYTES)} free`, "NOT restarted for want of disk; what was recorded lands."); break; } - await waitFor(stretch(LIVE_RESTART_WAIT_MS), signal); + if (pause) await waitFor(stretch(pause), signal); if (signal.aborted) break; + if (exitedWithBytes && cur.mode !== "now") extraPasses += 1; restarts.count += 1; restarts.at.push(now().toISOString()); const k = restarts.count; @@ -1747,7 +1835,7 @@ async function recordLiveRunInner( const o = await ytdlpPart(plan.url, `ytdlp-r${k}`, cur.mode, `restart ${k} (${why}); `, { restart: k, noWait: true, - onStart: onMainStart(cur.mode), + onStart: onMainStart(cur.mode, true), onLine: onMainLine, }); const bytes = await bytesOf(o.stem); diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -563,6 +563,9 @@ export type LiveRecordingRecord = { resumeOf?: string; // The insurance recorder beside the from-start recording (LiveInsurance). insurance?: LiveInsurance; + // 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[]; // The landed file is parts joined into one (controller/liveJoin.ts): where // each join is, and what it is. Also in data/<id>/live-joins.json. joins?: LiveJoin[]; @@ -607,6 +610,8 @@ export type LiveJoinSegment = { export const LIVE_JOINS_FILENAME = "live-joins.json"; +export type LiveSpaceHeld = { what: string; at: string; freeBytes: number }; + // data/<id>/live-joins.json: the landed container was joined from parts. export type LiveJoinsRecord = { landedAt: string; diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts @@ -37,6 +37,7 @@ import type { LiveInsurance, LiveJoin, LiveRestarts, + LiveSpaceHeld, MissingStream, StartRecovery, StreamCoverage, @@ -84,6 +85,7 @@ export type LiveRecordingRow = { restart?: LiveBootRestart; insurance?: LiveInsurance; joins?: LiveJoin[]; + spaceHeld?: LiveSpaceHeld[]; // What the landing kept: this run's file stored ("new"), or the store's. kept?: "new" | "existing"; acknowledgedAt?: string; @@ -173,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">>, + Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld">>, ): boolean { if (r.acknowledgedAt) return false; if (r.keptParts && r.keptParts.length > 0) return true; @@ -182,6 +184,8 @@ export function rowNeedsAttention( if (r.status === "cancelled" && r.mustKeep === true) return true; if (r.fallback === "live-edge" && 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; // Landed as parts joined with a gap: those seconds are in no part. if (r.joins?.some((j) => j.kind === "gap")) return true; return r.missingStream !== undefined; @@ -254,6 +258,7 @@ export function rowOfRecord( parts: rec.parts.map((p) => ({ ...p })), ...(rec.landedPart !== undefined ? { landedPart: rec.landedPart } : {}), ...(rec.kept ? { kept: rec.kept } : {}), + ...(rec.spaceHeld && rec.spaceHeld.length ? { spaceHeld: rec.spaceHeld.map((x) => ({ ...x })) } : {}), ...(rec.failureClass ? { failureClass: rec.failureClass } : {}), ...(rec.missingStream ? { missingStream: rec.missingStream } : {}), ...(rec.stoppedBy ? { stoppedBy: rec.stoppedBy } : {}),