commit 0a0b141b3c613d4d1824e0ba4d81b7a0c3d9b0cb
parent 9b439e1306af91f0a0b57fcf832f63de6a0797ed
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 16:52:23 -0500
record-live, boot pass: an unreadable state is read three times over ten minutes, and the orphan check looks more than once
REVIEW-1 of live-guard-2, 3.3 and 1.8:
- A restart after the editor's whose first read of the stream's state
fails reads it again after 2 and 8 minutes (jittered) before it gives
up — not after a rate limit, members-only or the disk, which another
read does not change. Read, it goes on as usual; never read, nothing is
recorded or landed and the interrupted row says the stream may still be
live and is NOT being recorded, needing a person.
- The boot pass looks at the id's part files three times, 20 s apart: a
file written after the boot, or one whose size or time changes between
two looks, is a recorder of the last process that may still be writing:
refused, said, needing a person; nothing of it lands.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
4 files changed, 140 insertions(+), 21 deletions(-)
diff --git a/common/controller/liveRecordingBoot.test.ts b/common/controller/liveRecordingBoot.test.ts
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises";
+import { appendFile, mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
@@ -71,6 +71,8 @@ const pass = (start: import("./liveRecordingBoot").LiveBootStart, extra: Partial
start,
isRunning: (jobId) => jobId === "job-running",
now: () => NOW,
+ // The orphan check's looks pass at once unless a case says otherwise.
+ sleep: async () => {},
...extra,
});
const rowsOf = async (id: string) => (await loadLiveRecordingRows(paths, SLUG)).filter((r) => r.id === id);
@@ -170,3 +172,29 @@ test("a start that fails is said on the row and not tried again; the setting off
assert.equal(s2.asked.filter((a) => String(a.body.url).endsWith(off)).length, 0);
assert.equal((await rowsOf(off))[0]!.restart?.state, "refused");
});
+
+test("REVIEW 1.8 (live-guard-2): the orphan check looks more than once — a part whose size changes between looks (its time kept old) is refused", async () => {
+ const id = "exbootorph2";
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(25)));
+ const f = path.join(store, `.${id}.live-2026-11-21T11-35-00-000Z.ytdlp.mp4`);
+ await writeFile(f, "first bytes");
+ const old = new Date(BOOTED - 120_000);
+ await utimes(f, old, old);
+ const s = starter();
+ let looks = 0;
+ await pass(s.start, {
+ orphanLooks: 3,
+ // Between two looks, the last process's recorder appends (and the file's
+ // time is set back, as a coarse clock or a copy would leave it).
+ sleep: async () => {
+ looks++;
+ await appendFile(f, " more");
+ await utimes(f, old, old);
+ },
+ });
+ assert.equal(looks, 1, "it looked again, and the change refused it at once");
+ assert.equal(s.asked.filter((a) => String(a.body.url).endsWith(id)).length, 0);
+ const r = (await rowsOf(id))[0]!;
+ assert.equal(r.restart?.state, "refused");
+ assert.match(r.restart?.reason ?? "", /changed between two looks/);
+});
diff --git a/common/controller/liveRecordingBoot.ts b/common/controller/liveRecordingBoot.ts
@@ -21,9 +21,11 @@
// (its rows carrying `resumeOf`, started in the last 60 minutes): a
// crash-looping editor stops restarting after three, and the row says so
// and needs a person.
-// 3. A part file of the id written after this process booted: a recorder of
-// the last process may still be running (an orphan) — never a second one
-// beside it; refused, said, needs a person.
+// 3. A part file of the id written after this process booted, or one whose
+// size or time changes between LIVE_BOOT_ORPHAN_LOOKS looks
+// LIVE_BOOT_ORPHAN_LOOK_MS apart: a recorder of the last process may still
+// be running (an orphan, perhaps mid-write) — never a second one beside
+// it, and nothing of it lands; refused, said, needs a person.
//
// The pass itself makes NO request. It asks for a record-live run with the
// interrupted run's own url and request (`resumeOf` its startedAt); that run's
@@ -55,6 +57,9 @@ export const LIVE_BOOT_MAX_RESTARTS_PER_HOUR = 3;
export const LIVE_BOOT_MAX_AGE_MS = 12 * 3_600_000;
// How long after boot the pass runs (an orphan recorder has written by then).
export const LIVE_BOOT_DELAY_MS = 30_000;
+// The orphan check: this many looks at the id's part files, this far apart.
+export const LIVE_BOOT_ORPHAN_LOOKS = 3;
+export const LIVE_BOOT_ORPHAN_LOOK_MS = 20_000;
export type LiveBootStart = (
slug: string,
@@ -94,6 +99,10 @@ export async function restartInterruptedLiveRecordings(o: {
enabled?: boolean;
now?: () => Date;
log?: (line: string) => void;
+ // The orphan check's looks and the wait between two (tests).
+ orphanLooks?: number;
+ orphanLookMs?: number;
+ sleep?: (ms: number) => Promise<void>;
}): Promise<LiveBootOutcome[]> {
const now = o.now ?? (() => new Date());
const log = o.log ?? (() => {});
@@ -146,16 +155,34 @@ export async function restartInterruptedLiveRecordings(o: {
if (!refusal) {
const config = await readChannelConfig(o.paths, slug).catch(() => null);
const slugStore = path.join(savedVideoRoot(o.paths, config), slug);
- names ??= await readdir(slugStore).catch(() => [] as string[]);
- for (const g of livePartFiles(row.id, names)) {
- for (const f of [...g.finished, ...g.streams, ...g.scratch]) {
- const st = await stat(path.join(slugStore, f)).catch(() => null);
- if (st && st.mtimeMs >= o.bootedAt) {
- refusal = `${f} was written after this editor started: a recorder of the last process may still be running`;
- break;
+ const looks = Math.max(1, o.orphanLooks ?? LIVE_BOOT_ORPHAN_LOOKS);
+ const wait = o.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ let before: Map<string, string> | null = null;
+ for (let look = 0; look < looks && !refusal; look++) {
+ if (look > 0) await wait(o.orphanLookMs ?? LIVE_BOOT_ORPHAN_LOOK_MS);
+ names = await readdir(slugStore).catch(() => [] as string[]);
+ const seen = new Map<string, string>();
+ for (const g of livePartFiles(row.id, names)) {
+ for (const f of [...g.finished, ...g.streams, ...g.scratch]) {
+ const st = await stat(path.join(slugStore, f)).catch(() => null);
+ if (!st) continue;
+ seen.set(f, `${st.size}:${st.mtimeMs}`);
+ if (st.mtimeMs >= o.bootedAt) {
+ refusal = `${f} was written after this editor started: a recorder of the last process may still be running`;
+ break;
+ }
}
+ if (refusal) break;
}
- if (refusal) break;
+ if (!refusal && before) {
+ for (const [f, v] of seen) {
+ if (before.get(f) !== v) {
+ refusal = `${f} changed between two looks ${Math.round((o.orphanLookMs ?? LIVE_BOOT_ORPHAN_LOOK_MS) / 1000)} s apart: a recorder of the last process may still be writing it`;
+ break;
+ }
+ }
+ }
+ before = seen;
}
}
if (refusal) {
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -1561,9 +1561,10 @@ test("slice 3 resume: ended with nothing left says so and still needs a person;
const id2 = "exmplresum4";
await interruptedRow(id2, t0);
+ // (Every read fails: three over about ten minutes, then unknown.)
const unknown = await incidentRun(id2, writesAfter(0), {
request: { resumeOf: t0 },
- refresh: { failFirst: "ERROR: [youtube] exmplresum4: Unable to download webpage: The read operation timed out" },
+ refresh: { failReads: [1, 2, 3], failWith: "ERROR: [youtube] exmplresum4: Unable to download webpage: The read operation timed out" },
});
await assert.rejects(unknown.run, /timed out/);
assert.equal(unknown.calls.length, 0, "never a recording on a guess");
@@ -2301,3 +2302,32 @@ test("REVIEW 3.2: a from-start restart re-arms an insurance that had stopped aft
assert.equal(row.restarts?.count, 1);
assert.equal(row.insurance?.starts, 2);
});
+
+test("REVIEW 3.3: an unreadable state at boot is read three times over about ten minutes; read live, it records; never readable, the row says the stream may be live and unrecorded", { timeout: 60_000 }, async () => {
+ const t0 = "2026-11-21T08:00:00.000Z";
+ // Read on the third try: it records.
+ const a = "exmplrv3301";
+ await interruptedRow(a, t0);
+ const ra = await incidentRun(a, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1, 2] } });
+ assert.equal((await ra.run).status, "landed");
+ assert.equal(ra.calls.length, 1);
+ assert.deepEqual(ra.waits.slice(0, 2), [120_000, 480_000]);
+ assert.equal((await oldRow(a, t0)).restart?.state, "restarted");
+ // Never read.
+ const b = "exmplrv3302";
+ await interruptedRow(b, t0);
+ const rb = await incidentRun(b, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1, 2, 3] } });
+ await assert.rejects(rb.run);
+ assert.equal(rb.calls.length, 0);
+ assert.deepEqual(rb.waits, [120_000, 480_000]);
+ const ob = await oldRow(b, t0);
+ assert.equal(ob.restart?.state, "unknown");
+ assert.match(ob.restart?.reason ?? "", /3 reads failed.*may still be live and is NOT being recorded/);
+ assert.equal(ob.needsAttention, true);
+ // A rate limit is not read again.
+ const c = "exmplrv3303";
+ await interruptedRow(c, t0);
+ const rc = await incidentRun(c, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1], failWith: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests" } });
+ await assert.rejects(rc.run);
+ assert.deepEqual(rc.waits, []);
+});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -181,6 +181,9 @@ export const RECORDER_GRACE_MS = 60_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;
+// 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];
export type RecordLiveRequest = {
slug: string;
@@ -989,6 +992,7 @@ async function recordLiveRunInner(
await rmdir(videoDir).catch(() => {});
};
let extractionError: string | null = null;
+ let extractionErrObj: Error | null = null;
const refresh = () =>
refreshVideoMetadata({
paths,
@@ -1041,19 +1045,49 @@ async function recordLiveRunInner(
await refresh();
} catch (err) {
extractionError = (err as Error).message;
+ extractionErrObj = err as Error;
if (resumeOf) {
- // Never a recording on a guess: the stream's state is not known.
- const reason = extractionError.split("\n")[0]!.slice(0, 300);
- say(`Restart after the editor restart: the stream's state could not be read (${reason}) — nothing is recorded or landed; Record again if it is still live.`);
- await markResume("unknown", { reason });
- hooks.quiet = true;
- await abandon();
- throw err;
+ // Never a recording on a guess: the stream's state is not known. A
+ // reboot or a network drop is the commonest boot, so the read is made
+ // three times over about ten minutes (REVIEW-1 3.3 of live-guard-2) —
+ // not after a rate limit, members-only or the disk, which another read
+ // does not change.
+ let lastErr = err as Error;
+ let read = false;
+ const cls0 = liveFailureClass(lastErr.message);
+ if (cls0 !== "rate-limited" && cls0 !== "members" && cls0 !== "disk") {
+ for (const w of LIVE_BOOT_STATE_READ_WAITS_MS) {
+ say(`Restart after the editor restart: the stream's state could not be read (${lastErr.message.split("\n")[0]!.slice(0, 200)}); read again in ${spanWords(w / 1000)}.`);
+ await waitFor(stretch(w), signal);
+ if (signal.aborted) break;
+ try {
+ await refresh();
+ read = true;
+ break;
+ } catch (e) {
+ lastErr = e as Error;
+ const c = liveFailureClass(lastErr.message);
+ if (c === "rate-limited" || c === "members" || c === "disk") break;
+ }
+ }
+ }
+ if (read) extractionError = null;
+ else {
+ const reads = 1 + LIVE_BOOT_STATE_READ_WAITS_MS.length;
+ const reason = `${lastErr.message.split("\n")[0]!.slice(0, 240)} — the stream may still be live and is NOT being recorded`;
+ say(`Restart after the editor restart: the stream's state could not be read (${reason}); nothing is recorded or landed — Record again if it is still live.`);
+ await markResume("unknown", { reason: `${reads} reads failed: ${reason}` });
+ hooks.quiet = true;
+ await abandon();
+ throw lastErr;
+ }
}
+ }
+ if (extractionError !== null) {
const canFallBack = BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(extractionError);
if (!canFallBack) {
await abandon();
- throw err;
+ throw extractionErrObj ?? new Error(extractionError);
}
say(`yt-dlp could not read the stream (${extractionError.split("\n")[0]}); recording from the page's own playlist.`);
}