commit a25af365c639d66be0733956205006d682185e46
parent 44284b72e1c6f4fff3e0f8953ad6ba5291e54a29
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 14:04:34 -0500
record-live: a stalled or dead recorder restarts while the stream is live, and an editor restart's interruption restarts by itself
In the job: every recorder of path A (and each start-recovery try) has a
stall watchdog. Its part's files, scratch included, are summed every
minute; no growth for liveRecording.stallMinutes (default 10) stops that
recorder alone with SIGINT, and its part stays. A part that stalled with
bytes, or whose recorder exited with bytes, is followed by one metadata
read (the read the run made at its end anyway; an exit is read twice, a
minute apart): still live, a new part in the same mode with its own stem;
ended, the run lands what it has. At most 3 restarts in any hour and 12 in
a run, and only with room on the store's disk; past a bound the row says
why and needs a person. A stall with nothing written is an attempt that
recorded nothing, on the slice-1 schedule. A healthy recording makes the
same single end read as before.
At boot: 30 s after the editor starts (below the idle gate, not on the
test server, liveRecording.autoRestartOnBoot default true), the newest run
of each id that the shutdown interrupted, or that a crash left saying
recording, asks for a record-live run with its own url and request. That
run reads the stream's state first: live, it records again; ended, it
lands what is in staging (or says nothing was left); unreadable, it starts
nothing and lands nothing, and the row says so and needs a person. A
person's Cancel never restarts. A restart loop is prevented three ways: the
row is marked before the job is asked (a row restarts at most once), at
most 3 automatic restarts of a stream in an hour, and a part written after
the boot (a recorder of the last process may still run) is refused.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
13 files changed, 1125 insertions(+), 64 deletions(-)
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -256,19 +256,21 @@ Default:
## `liveRecording`
-How a running live recording is judged (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled. See common/controller/liveRecordings.ts.
+How a running live recording is judged and kept alive (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled (and restart its recorder), and whether an editor restart's interruption restarts by itself. See common/controller/liveRecordings.ts and common/controller/liveRecordingBoot.ts.
#### `liveRecording`
| Key | Default | Description |
|---|---|---|
-| `stallMinutes` | `10` | Minutes a running live recording's files may go without growing before `pnpm ops get live-recordings` (and /review, the banners) mark it `stalled`. Clamped 1–240; default 10. |
+| `stallMinutes` | `10` | Minutes a running live recording's files may go without growing before `pnpm ops get live-recordings` (and /review, the banners) mark it `stalled` — and before record-live's own watchdog stops that recorder and, while the stream is still live, starts a new part (at most 3 restarts an hour, 12 a run). Clamped 1–240; default 10. |
+| `autoRestartOnBoot` | `true` | After an editor restart, a live recording the shutdown (or a crash) interrupted is restarted by itself: the new run reads the stream's state first (one paced metadata request) and records only if it is still live; ended, it lands what is in staging; unreadable, it starts nothing. At most once per interrupted run and 3 times an hour per stream; never after a person's Cancel (common/controller/liveRecordingBoot.ts). Default true; false leaves every interruption to /review's Record again. |
Default:
```json
{
- "stallMinutes": 10
+ "stallMinutes": 10,
+ "autoRestartOnBoot": true
}
```
diff --git a/common/controller/liveRecordingBoot.test.ts b/common/controller/liveRecordingBoot.test.ts
@@ -0,0 +1,172 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveRecordingBoot.test.ts
+//
+// The boot pass that restarts live recordings an editor restart interrupted
+// (controller/liveRecordingBoot.ts), over a temp corpus: the rows written
+// through lib/liveRecordings-server.ts, the job start a stub that records
+// what it was asked. No request is made by the pass.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-boot-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const { restartInterruptedLiveRecordings, LIVE_BOOT_MAX_RESTARTS_PER_HOUR } = await import("./liveRecordingBoot");
+const { upsertLiveRecordingRow, loadLiveRecordingRows, rowNeedsAttention } = await import("../lib/liveRecordings-server");
+const { liveRecordingSidecar } = await import("../lib/mediaImport-server");
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-boot";
+await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true });
+await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: "Synth" }));
+const store = path.join(paths.savedVideosDir, SLUG);
+await mkdir(store, { recursive: true });
+
+const NOW = new Date("2026-11-21T12:00:00.000Z");
+const BOOTED = NOW.getTime() - 30_000;
+const ago = (min: number) => new Date(NOW.getTime() - min * 60_000).toISOString();
+
+type RowIn = Parameters<typeof upsertLiveRecordingRow>[2];
+const row = (id: string, startedAt: string, extra: Partial<RowIn> = {}): RowIn => ({
+ id,
+ url: `https://www.youtube.com/watch?v=${id}`,
+ platform: "youtube",
+ startedAt,
+ status: "interrupted",
+ stoppedBy: "shutdown",
+ endedAt: startedAt,
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ parts: [],
+ request: { fromStart: true, doNotClean: true, note: "keep", transcribe: true },
+ ...extra,
+});
+
+function starter() {
+ const asked: { slug: string; body: Record<string, unknown>; resumeOf: string }[] = [];
+ return {
+ asked,
+ start: async (slug: string, body: Record<string, unknown>, resumeOf: string) => {
+ asked.push({ slug, body, resumeOf });
+ return { ok: true as const, jobId: `boot-${asked.length}` };
+ },
+ };
+}
+const pass = (start: import("./liveRecordingBoot").LiveBootStart, extra: Partial<Parameters<typeof restartInterruptedLiveRecordings>[0]> = {}) =>
+ restartInterruptedLiveRecordings({
+ paths,
+ bootedAt: BOOTED,
+ start,
+ isRunning: (jobId) => jobId === "job-running",
+ now: () => NOW,
+ ...extra,
+ });
+const rowsOf = async (id: string) => (await loadLiveRecordingRows(paths, SLUG)).filter((r) => r.id === id);
+
+test("only a shutdown's or a crash's interruption restarts — never a cancel, an acknowledged one, an old one, one with a job, one restarted already, nor an older run", async () => {
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootshut1", ago(90)));
+ // A crash: the row and the record still say recording, no job runs it.
+ const crashAt = ago(60);
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootcrsh1", crashAt, { status: "recording", stoppedBy: undefined, endedAt: undefined, jobId: "job-dead" }));
+ const dir = path.join(CORPUS, "channels", SLUG, "data", "exbootcrsh1");
+ await mkdir(dir, { recursive: true });
+ await liveRecordingSidecar.write(dir, { status: "recording", url: "u", platform: "youtube", fromStart: true, startedAt: crashAt, parts: [] });
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootcanc1", ago(30), { status: "cancelled", stoppedBy: "operator" }));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootackd1", ago(30)));
+ const { acknowledgeLiveRecordingRows } = await import("../lib/liveRecordings-server");
+ await acknowledgeLiveRecordingRows(paths, SLUG, "exbootackd1", { by: "test" });
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootold01", ago(13 * 60)));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootrun01", ago(10), { status: "recording", stoppedBy: undefined, jobId: "job-running" }));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootdone1", ago(20), { restart: { at: ago(19), by: "boot", state: "asked", jobId: "x" } }));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootnewr1", ago(50)));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootnewr1", ago(40), { status: "landed", stoppedBy: undefined }));
+
+ const s = starter();
+ const out = await pass(s.start);
+ assert.deepEqual(s.asked.map((a) => a.body.url).sort(), [
+ "https://www.youtube.com/watch?v=exbootcrsh1",
+ "https://www.youtube.com/watch?v=exbootshut1",
+ ]);
+ const shut = s.asked.find((a) => a.body.url === "https://www.youtube.com/watch?v=exbootshut1")!;
+ assert.equal(shut.resumeOf, ago(90));
+ assert.deepEqual(shut.body, { fromStart: true, doNotClean: true, note: "keep", transcribe: true, slug: SLUG, url: "https://www.youtube.com/watch?v=exbootshut1" });
+ assert.equal(out.filter((o) => o.state === "asked").length, 2);
+
+ const crash = (await rowsOf("exbootcrsh1"))[0]!;
+ assert.equal(crash.status, "interrupted");
+ assert.equal(crash.stoppedBy, "crash");
+ assert.equal(crash.restart?.state, "asked");
+ assert.equal((await liveRecordingSidecar.load(dir))?.status, "interrupted", "the crashed record says so too");
+
+ // HOW A LOOP IS PREVENTED (1): a second boot asks for nothing again.
+ const again = starter();
+ await pass(again.start);
+ assert.deepEqual(again.asked, []);
+});
+
+test("a restart loop is refused: three automatic restarts of an id in the last hour, then no more, said and needing a person", async () => {
+ const id = "exbootloop1";
+ for (let i = 0; i < LIVE_BOOT_MAX_RESTARTS_PER_HOUR; i++) {
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(50 - i * 10), { resumeOf: ago(55 - i * 10), restart: { at: ago(49 - i * 10), by: "boot", state: "restarted" } }));
+ }
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(5), { resumeOf: ago(10) }));
+ const s = starter();
+ await pass(s.start);
+ assert.equal(s.asked.filter((a) => a.body.url === `https://www.youtube.com/watch?v=${id}`).length, 0);
+ const newest = (await rowsOf(id)).find((r) => r.startedAt === ago(5))!;
+ assert.equal(newest.restart?.state, "refused");
+ assert.match(newest.restart?.reason ?? "", /restart loop/);
+ assert.equal(rowNeedsAttention(newest), true);
+});
+
+test("a part written after this boot began is a recorder of the last process still running: refused, never a second recorder", async () => {
+ const id = "exbootorph1";
+ const startedAt = ago(30);
+ await upsertLiveRecordingRow(paths, SLUG, row(id, startedAt));
+ const f = path.join(store, `.${id}.live-2026-11-21T11-30-00-000Z.ytdlp.mp4`);
+ await writeFile(f, "growing");
+ await utimes(f, new Date(BOOTED + 5_000), new Date(BOOTED + 5_000));
+ const s = starter();
+ await pass(s.start);
+ 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 ?? "", /may still be running/);
+ // Written before the boot: an ordinary leftover, restarted.
+ await utimes(f, new Date(BOOTED - 60_000), new Date(BOOTED - 60_000));
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(20)));
+ const s2 = starter();
+ await pass(s2.start);
+ assert.equal(s2.asked.filter((a) => String(a.body.url).endsWith(id)).length, 1);
+});
+
+test("a start that fails is said on the row and not tried again; the setting off refuses", async () => {
+ const id = "exbootfail1";
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(15)));
+ await pass(async () => ({ ok: false as const, error: "This stream is already being recorded (job j1)" }));
+ const r = (await rowsOf(id))[0]!;
+ assert.equal(r.restart?.state, "failed");
+ assert.match(r.restart?.reason ?? "", /already being recorded/);
+ const s = starter();
+ await pass(s.start);
+ assert.equal(s.asked.filter((a) => String(a.body.url).endsWith(id)).length, 0);
+
+ const off = "exbootoff01";
+ await upsertLiveRecordingRow(paths, SLUG, row(off, ago(15)));
+ const s2 = starter();
+ await pass(s2.start, { enabled: false });
+ assert.equal(s2.asked.filter((a) => String(a.body.url).endsWith(off)).length, 0);
+ assert.equal((await rowsOf(off))[0]!.restart?.state, "refused");
+});
diff --git a/common/controller/liveRecordingBoot.ts b/common/controller/liveRecordingBoot.ts
@@ -0,0 +1,210 @@
+// A LIVE RECORDING THE EDITOR'S RESTART INTERRUPTED RESTARTS BY ITSELF
+// (operator ruling, 21 Nov 2026) — the boot pass, armed by the editor's
+// instrumentation (editor/app/api/ops/_liveRecordingBoot.ts) below the idle
+// gate and never on the test server.
+//
+// Per recorded id of every channel, the NEWEST run's row is a candidate when
+// it is
+// interrupted, stopped by the shutdown (stoppedBy "shutdown"), or
+// recording with no job running it — the editor died under it (a crash);
+// it is written `interrupted`, stoppedBy "crash", first.
+// Never a cancelled run (a person's Cancel), a failed or a landed one.
+// Skipped: acknowledged; already carrying `restart` (a row restarts at most
+// once); last active more than LIVE_BOOT_MAX_AGE_MS ago; the setting off
+// (settings.liveRecording.autoRestartOnBoot).
+//
+// HOW A RESTART LOOP IS PREVENTED:
+// 1. The row is marked `restart: {state: "starting"}` BEFORE the job is asked
+// for, and a marked row is never a candidate again — an editor that dies
+// in the middle of this pass does not restart that row twice.
+// 2. At most LIVE_BOOT_MAX_RESTARTS_PER_HOUR automatic restarts of one id
+// (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.
+//
+// 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
+// first step is record-live's one paced metadata read (the platform's pace,
+// the channel's cookies, as every record-live run), and it decides:
+// live record — a new run beside the earlier parts (slice 1's landing
+// keeps or removes them); the row says `restarted`
+// ended no recorder; whatever the earlier run left in staging lands
+// (`landing`), or with nothing left the row says `ended`
+// unknown the read failed: NOTHING is started and nothing lands — never a
+// recording on a guess; the row says `unknown` and needs a person
+// (Record again)
+// (controller/recordLive.ts, `resumeOf`).
+
+import path from "node:path";
+import { readdir, stat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { livePartFiles, type LiveBootRestart } from "../lib/liveCapture";
+import { liveRecordingSidecar } from "../lib/mediaImport-server";
+import {
+ loadLiveRecordingRows,
+ patchLiveRecordingRow,
+ type LiveRecordingRow,
+} from "../lib/liveRecordings-server";
+import { savedVideoRoot } from "../lib/savedVideo";
+import { readChannelConfig } from "./channels";
+
+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;
+
+export type LiveBootStart = (
+ slug: string,
+ body: Record<string, unknown>,
+ resumeOf: string,
+) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>;
+
+export type LiveBootOutcome = {
+ slug: string;
+ id: string;
+ startedAt: string;
+ state: LiveBootRestart["state"];
+ jobId?: string;
+ reason?: string;
+};
+
+async function channelSlugs(paths: Paths): Promise<string[]> {
+ const entries = await readdir(paths.channelsDir, { withFileTypes: true }).catch(() => []);
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
+}
+
+function lastActivityMs(r: LiveRecordingRow): number {
+ const times = [r.startedAt, r.endedAt, ...r.parts.flatMap((p) => [p.startedAt, p.endedAt])]
+ .filter((t): t is string => typeof t === "string")
+ .map((t) => Date.parse(t))
+ .filter(Number.isFinite);
+ return times.length ? Math.max(...times) : 0;
+}
+
+export async function restartInterruptedLiveRecordings(o: {
+ paths: Paths;
+ // When this process started: a part file written since is an orphan's.
+ bootedAt: number;
+ start: LiveBootStart;
+ // A record-live job of this id runs (the registry).
+ isRunning: (jobId: string | undefined, slug: string, id: string) => boolean;
+ enabled?: boolean;
+ now?: () => Date;
+ log?: (line: string) => void;
+}): Promise<LiveBootOutcome[]> {
+ const now = o.now ?? (() => new Date());
+ const log = o.log ?? (() => {});
+ const out: LiveBootOutcome[] = [];
+ for (const slug of await channelSlugs(o.paths)) {
+ const rows = await loadLiveRecordingRows(o.paths, slug).catch(() => [] as LiveRecordingRow[]);
+ if (!rows.length) continue;
+ const newest = new Map<string, LiveRecordingRow>();
+ for (const r of rows) {
+ const cur = newest.get(r.id);
+ if (!cur || Date.parse(r.startedAt) > Date.parse(cur.startedAt)) newest.set(r.id, r);
+ }
+ let names: string[] | null = null;
+ for (const row of newest.values()) {
+ const crashed = row.status === "recording" && !o.isRunning(row.jobId, slug, row.id);
+ const shutdown = row.status === "interrupted" && (row.stoppedBy === "shutdown" || row.stoppedBy === "crash");
+ if (!crashed && !shutdown) continue;
+ if (row.acknowledgedAt || row.restart) continue;
+ const at = now();
+ if (at.getTime() - lastActivityMs(row) > LIVE_BOOT_MAX_AGE_MS) continue;
+ const tag = `${slug}/${row.id}`;
+ const mark = (restart: Partial<LiveBootRestart> & { state: LiveBootRestart["state"] }) =>
+ patchLiveRecordingRow(o.paths, slug, row.id, row.startedAt, (r) => {
+ r.restart = { ...(r.restart ?? { at: at.toISOString(), by: "boot" as const }), ...restart };
+ if (crashed && r.status === "recording") {
+ r.status = "interrupted";
+ r.stoppedBy = "crash";
+ }
+ });
+ const result = (state: LiveBootRestart["state"], extra: { jobId?: string; reason?: string } = {}) => {
+ out.push({ slug, id: row.id, startedAt: row.startedAt, state, ...extra });
+ log(`[boot] live recording ${tag}: ${state}${extra.jobId ? ` (job ${extra.jobId})` : ""}${extra.reason ? ` — ${extra.reason}` : ""}`);
+ };
+ // A crash leaves the record saying `recording`: it says interrupted now.
+ if (crashed) {
+ const dir = path.join(o.paths.channelsDir, slug, "data", row.id);
+ const rec = await liveRecordingSidecar.load(dir).catch(() => null);
+ if (rec && rec.startedAt === row.startedAt && rec.status === "recording") {
+ await liveRecordingSidecar.write(dir, { ...rec, status: "interrupted", stoppedBy: "crash" }).catch(() => {});
+ }
+ }
+ let refusal: string | null = null;
+ if (o.enabled === false) refusal = "settings.liveRecording.autoRestartOnBoot is off";
+ if (!refusal) {
+ const recent = rows.filter((r) => r.id === row.id && r.resumeOf && at.getTime() - Date.parse(r.startedAt) < 3_600_000).length;
+ if (recent >= LIVE_BOOT_MAX_RESTARTS_PER_HOUR) {
+ refusal = `${recent} automatic restarts of it in the last hour (at most ${LIVE_BOOT_MAX_RESTARTS_PER_HOUR}): a restart loop?`;
+ }
+ }
+ 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;
+ }
+ }
+ if (refusal) break;
+ }
+ }
+ if (refusal) {
+ await mark({ state: "refused", reason: refusal });
+ result("refused", { reason: refusal });
+ continue;
+ }
+ if (!row.url) {
+ await mark({ state: "failed", reason: "the row names no url" });
+ result("failed", { reason: "the row names no url" });
+ continue;
+ }
+ // Marked first: this row is never restarted twice.
+ await mark({ state: "starting" });
+ const body = { ...(row.request ?? { fromStart: row.fromStart }), slug, url: row.url };
+ let r: Awaited<ReturnType<LiveBootStart>>;
+ try {
+ r = await o.start(slug, body, row.startedAt);
+ } catch (err) {
+ r = { ok: false, error: (err as Error).message };
+ }
+ if (r.ok) {
+ // The run writes what it found (restarted, landing, ended, unknown)
+ // over this; until then the row says it was asked.
+ const jobId = r.jobId;
+ await patchLiveRecordingRow(o.paths, slug, row.id, row.startedAt, (x) => {
+ if (x.restart?.state !== "starting") return false;
+ x.restart = { ...x.restart, state: "asked", jobId };
+ });
+ result("asked", { jobId: r.jobId });
+ } else {
+ await mark({ state: "failed", reason: r.error });
+ result("failed", { reason: r.error });
+ }
+ }
+ }
+ return out;
+}
+
+// What a restarted run writes on the interrupted run's row.
+export async function markLiveBootRestart(
+ paths: Paths,
+ slug: string,
+ id: string,
+ resumeOf: string,
+ patch: { state: LiveBootRestart["state"]; jobId?: string; reason?: string },
+ now: () => Date = () => new Date(),
+): Promise<void> {
+ await patchLiveRecordingRow(paths, slug, id, resumeOf, (r) => {
+ r.restart = { ...(r.restart ?? { at: now().toISOString(), by: "boot" as const }), ...patch };
+ });
+}
diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts
@@ -113,7 +113,8 @@ export function liveRecordingCheckCommand(slug: string, id: string): string {
return `pnpm ops get live-recordings ${slug}/${id}`;
}
-function stallMinutesSetting(): number {
+// settings.liveRecording.stallMinutes (record-live's watchdog reads it too).
+export function liveStallMinutes(): number {
try {
const v = getSettings().liveRecording?.stallMinutes;
return typeof v === "number" && v > 0 ? v : LIVE_STALL_MINUTES_DEFAULT;
@@ -154,17 +155,35 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes:
};
extra.unshift(words[rs.state] ?? `start recovery: ${rs.state}`);
}
+ 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("; ")}` : "";
const cls = v.failureClass && v.failureClass !== "unknown" ? ` [${v.failureClass}]` : "";
switch (v.status) {
case "failed":
return `failed${cls}: ${v.error ?? "no reason recorded"}${tail}`;
- case "interrupted":
- return (
- (v.stoppedBy === "shutdown"
- ? "interrupted: the editor shut down while it recorded — Record again if the stream is still live"
- : "interrupted: its record says recording, and no record-live job runs it (an editor restart?) — Record again") + tail
- );
+ case "interrupted": {
+ const r = v.restart;
+ const boot = r
+ ? {
+ starting: "being restarted automatically",
+ asked: `restarted automatically as job ${r.jobId ?? "?"}: it reads the stream's state first`,
+ restarted: `restarted automatically (job ${r.jobId ?? "?"}): the stream was still live`,
+ landing: "the stream had ended by the restart: what this run left is landed",
+ ended: "the stream had ended by the restart, and nothing was left to land — the end of the stream is NOT recorded",
+ unknown: `NOT restarted: the stream's state could not be read${r.reason ? ` (${r.reason})` : ""} — Record again if it is still live`,
+ refused: `NOT restarted automatically: ${r.reason ?? "refused"} — Record again if the stream is still live`,
+ failed: `the automatic restart failed: ${r.reason ?? "no job"} — Record again if the stream is still live`,
+ }[r.state]
+ : null;
+ const head =
+ v.stoppedBy === "shutdown"
+ ? "interrupted: the editor shut down while it recorded"
+ : v.stoppedBy === "crash"
+ ? "interrupted: the editor stopped (a crash?) while it recorded"
+ : "interrupted: its record says recording, and no record-live job runs it (an editor restart?)";
+ return `${head} — ${boot ?? "Record again if the stream is still live"}${tail}`;
+ }
case "cancelled":
return `cancelled${v.mustKeep ? " (a must-keep stream: is that what you wanted?)" : ""}${tail}`;
case "landed":
@@ -190,7 +209,7 @@ function fileProblemMessage(slug: string, p: Pick<LiveRecordingsFileProblem, "fi
// Every live recording (of one channel, one id), newest first.
export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsOpts = {}): Promise<LiveRecordingsListing> {
const now = (opts.now ?? new Date()).getTime();
- const stallMinutes = opts.stallMinutes ?? stallMinutesSetting();
+ const stallMinutes = opts.stallMinutes ?? liveStallMinutes();
const jobs = (opts.jobs ?? (() => getRegistry().list()))();
const byId = new Map(jobs.map((j) => [j.id, j]));
const slugs = opts.slug ? [opts.slug] : await channelSlugs(paths);
@@ -285,6 +304,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
...(own?.removedParts ? { removedParts: own.removedParts } : {}),
...(own?.coverage ? { coverage: own.coverage } : {}),
...(own?.startRecovery ? { startRecovery: own.startRecovery } : {}),
+ ...(own?.restarts ? { restarts: own.restarts } : {}),
attempts: own?.attempts ?? row.attempts,
parts,
slug,
@@ -302,6 +322,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
keptParts: own?.keptParts ?? row.keptParts,
missingStream: own?.missingStream ?? row.missingStream,
startRecovery: own?.startRecovery ?? row.startRecovery,
+ restarts: own?.restarts ?? row.restarts,
}),
};
const shown =
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -81,14 +81,21 @@ const handoff = async () => ({
const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const;
// A refresh that writes the stream's metadata (live, with one HLS format).
-function refreshWith(meta: Record<string, unknown>, opts: { failFirst?: string } = {}) {
+// Read after the recording (the stream has ended): a live record then says
+// `was_live` (the platforms' own word for an ended stream), unless
+// `stillLive` says it is still live.
+function refreshWith(meta: Record<string, unknown>, opts: { failFirst?: string; stillLive?: () => boolean; failAfterFirst?: string } = {}) {
let n = 0;
+ let wrote = 0;
return async (cwd: string, args: string[]): Promise<AttemptOutcome> => {
n++;
if (opts.failFirst && n === 1) return { exitCode: 1, stderrTail: opts.failFirst, archiveLine: null, formatLine: null };
+ if (opts.failAfterFirst && n > 1) return { exitCode: 1, stderrTail: opts.failAfterFirst, archiveLine: null, formatLine: null };
const o = args[args.indexOf("-o") + 1]!;
const dir = path.join(cwd, path.dirname(o));
- await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta));
+ 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));
return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
};
}
@@ -184,8 +191,8 @@ test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once
const log: string[] = [];
await recordLiveRun({
paths,
- request: { slug: SLUG, url: "https://rumble.com/v3ccccc-show.html", preclip: p.preclip },
- plan: { url: "https://rumble.com/v3ccccc-show.html", platform: "rumble", id: "v3ccccc" },
+ request: { slug: SLUG, url: "https://rumble.com/v3ppppp-show.html", preclip: p.preclip },
+ plan: { url: "https://rumble.com/v3ppppp-show.html", platform: "rumble", id: "v3ppppp" },
channelConfig: CONFIG,
cookiePolicy: NO_COOKIES,
onLog: (l) => void log.push(l),
@@ -208,10 +215,10 @@ test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once
handoff,
},
});
- assert.deepEqual(asked, [{ slug: SLUG, id: "v3ccccc", every: 5 }]);
+ assert.deepEqual(asked, [{ slug: SLUG, id: "v3ppppp", every: 5 }]);
assert.ok(log.some((l) => /Live pre-clip: job job-pre/.test(l)));
- const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", SLUG, "data", "v3ccccc"));
- assert.match(rec?.parts[0]?.stem ?? "", /^\.v3ccccc\.live-.+\.ytdlp$/);
+ const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", SLUG, "data", "v3ppppp"));
+ assert.match(rec?.parts[0]?.stem ?? "", /^\.v3ppppp\.live-.+\.ytdlp$/);
});
test("yt-dlp cannot start at the start: --no-live-from-start with ffmpeg at index 0; the longest part lands", async () => {
@@ -637,7 +644,7 @@ const ytChannel = async () => {
const ytLiveMeta = (id: string) => ({ ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 7200 });
const ytUrl = (id: string) => `https://www.youtube.com/watch?v=${id}`;
-type Attempt = (args: string[], n: number) => Promise<{ exitCode: number | null; stderrTail: string; signalled: boolean }>;
+type Attempt = (args: string[], n: number, signal: AbortSignal) => Promise<{ exitCode: number | null; stderrTail: string; signalled: boolean }>;
const writesAfter = (failures: number, stderr = EMPTY): Attempt => async (args, n) => {
if (n <= failures) return { exitCode: 1, stderrTail: stderr, signalled: false };
const out = args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, ".mp4");
@@ -657,13 +664,16 @@ async function incidentRun(
// Slice 2's tries beside the live edge: their 15 min waits pass at once
// ("immediate", recorded in `waits`), or never come before the run ends
// (the default: no try is made).
- recovery?: "immediate";
+ // A number: that many pass at once, the rest never come.
+ recovery?: "immediate" | number;
+ refresh?: Parameters<typeof refreshWith>[1];
} = {},
) {
await ytChannel();
const calls: string[][] = [];
const waits: number[] = [];
const log: string[] = [];
+ let recoveryWaits = 0;
const run = recordLiveRun({
paths,
request: { slug: YT_SLUG, url: ytUrl(id), fromStart: true, transcribe: true, doNotClean: true, note: "must not lose", ...(opts.request ?? {}) },
@@ -674,22 +684,26 @@ async function incidentRun(
signal: opts.signal ?? new AbortController().signal,
jobId: `job-${id}`,
deps: {
- refresh: refreshWith(opts.meta ?? ytLiveMeta(id)),
+ refresh: refreshWith(opts.meta ?? ytLiveMeta(id), opts.refresh ?? {}),
fetchText: async () => {
throw new Error("no playlist read is expected");
},
- spawn: async ({ args }: { args: string[] }) => {
+ spawn: async ({ args, signal }: { args: string[]; signal: AbortSignal }) => {
calls.push(args);
- return attempt(args, calls.length);
+ return attempt(args, calls.length, signal);
},
wait: async (ms) => {
waits.push(ms);
opts.onWait?.(ms);
},
- recoveryWait:
- opts.recovery === "immediate"
- ? async (ms: number) => void waits.push(ms)
- : (_ms: number, sig: AbortSignal) => new Promise<void>((r) => (sig.aborted ? r() : sig.addEventListener("abort", () => r(), { once: true }))),
+ recoveryWait: (ms: number, sig: AbortSignal) => {
+ const passes = opts.recovery === "immediate" || (typeof opts.recovery === "number" && recoveryWaits++ < opts.recovery);
+ if (passes) {
+ waits.push(ms);
+ return Promise.resolve();
+ }
+ return new Promise<void>((r) => (sig.aborted ? r() : sig.addEventListener("abort", () => r(), { once: true })));
+ },
jitter: (ms) => ms,
land,
freeBytes: async () => 1e15,
@@ -1224,7 +1238,8 @@ test("slice 2: the live edge records, a from-start try beside it recovers the st
} finally {
active--;
}
- }, { recovery: "immediate" });
+ // The third 15 min wait never comes: the stream ends first.
+ }, { recovery: 2 });
const s = await run;
assert.equal(s.status, "landed");
assert.equal(recoveries, 2, "two tries: the first failed, the second recorded");
@@ -1315,3 +1330,217 @@ test("slice 2: a try that says the stream is private stops the tries; the stream
assert.equal(r4.startRecovery?.state, "stopped");
assert.equal(r4.needsAttention, true);
});
+
+// --- SLICE 3: the stall watchdog acts, and a recorder that dies is restarted --------
+//
+// The watchdog compares the part's files every `watchMs`; no growth for
+// `stallMs` stops that recorder alone. Then one metadata read: still live → a
+// new part (its own stem; the stalled part kept until the landing decides),
+// bounded; ended → land.
+
+const hangAfter = (seconds: number) => async (args: string[], _n: number, signal: AbortSignal) => {
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`);
+ await new Promise<void>((r) => (signal.aborted ? r() : signal.addEventListener("abort", () => r(), { once: true })));
+ return { exitCode: null, stderrTail: "", signalled: true };
+};
+const FAST_WATCH = { watchMs: 10, stallMs: 80 };
+
+test("slice 3: a stalled recorder is stopped, the stream still live, a new part records: the stalled part was kept until the landing, the whole lands", async () => {
+ const id = "exmplstall1";
+ let live = true;
+ const hang = hangAfter(300);
+ const { run, calls, waits, log } = await incidentRun(
+ id,
+ async (args, n, signal) => {
+ if (n === 1) return hang(args, n, signal);
+ // The restart records from its start to the end.
+ assert.ok(
+ (await readdir(store())).some((f) => f.startsWith(`.${id}.`) && f.endsWith(".ytdlp.mp4")),
+ "the stalled part is still on disk while the restart records",
+ );
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ live = false;
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ { deps: FAST_WATCH, refresh: { stillLive: () => live }, meta: { ...ytLiveMeta(id) } },
+ );
+ 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 from its start, as the stalled part was");
+ 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(log.some((l) => /stalled/.test(l)));
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.parts[0]!.stalled, true);
+ assert.equal(row.restarts?.count, 1);
+ assert.equal(s.landed?.seconds, 7200);
+ assert.equal(row.needsAttention, false);
+});
+
+test("slice 3: a recorder that exits with bytes while the stream still reads live (twice, 60 s apart) is restarted; a normal end is not", async () => {
+ const id = "exmplexitl1";
+ 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: Connection reset by peer\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ live = false;
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ { deps: FAST_WATCH, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 2);
+ assert.ok(waits.includes(60_000), "read again a minute later before restarting");
+ // A normal end (the stream reads ended at once): one spawn, no restart.
+ const plain = await incidentRun("exmplexitl2", writesAfter(0), { deps: FAST_WATCH });
+ assert.equal((await plain.run).status, "landed");
+ assert.equal(plain.calls.length, 1);
+ assert.deepEqual(plain.waits, []);
+});
+
+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");
+ 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 } },
+ );
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(calls.length, 4, "the first recorder and 3 restarts, no more");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.restarts?.count, 3);
+ assert.match(row.restarts?.refused ?? "", /3 restarts in the last hour/);
+ assert.equal(row.needsAttention, true);
+ assert.ok((row.keptParts?.length ?? 0) + (row.removedParts?.length ?? 0) >= 3, "every part is accounted for");
+});
+
+test("slice 3: a stall when the stream has ended lands what was recorded, no restart; a stall with nothing written is a failed attempt on the schedule", async () => {
+ const id = "exmplstall2";
+ const { run, calls } = await incidentRun(id, hangAfter(600), { deps: FAST_WATCH });
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 1);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.parts[0]!.stalled, true);
+ assert.equal(row.restarts?.count ?? 0, 0);
+
+ const id2 = "exmplstall3";
+ const two = await incidentRun(
+ id2,
+ async (args, n, signal) => {
+ if (n === 1) {
+ await new Promise<void>((r) => signal.addEventListener("abort", () => r(), { once: true }));
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ { deps: FAST_WATCH },
+ );
+ assert.equal((await two.run).status, "landed");
+ assert.equal(two.calls.length, 2);
+ assert.deepEqual(two.waits, [60_000], "the schedule's second from-start attempt");
+ const r2 = (await rowOf(id2))[0]!;
+ assert.equal(r2.parts[0]!.failureClass, "stalled");
+});
+
+// --- SLICE 3: the run the boot pass starts for an interrupted recording -------------
+//
+// `resumeOf` names the interrupted run (its startedAt). The run's own first
+// read decides: live → record; ended → land what is in staging, or say there
+// is nothing; unreadable → nothing at all.
+
+const interruptedRow = async (id: string, startedAt: string, parts: { stem: string; fromStart: boolean }[] = []) => {
+ const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await ytChannel();
+ await upsertLiveRecordingRow(paths, YT_SLUG, {
+ id,
+ url: ytUrl(id),
+ platform: "youtube",
+ startedAt,
+ endedAt: startedAt,
+ status: "interrupted",
+ stoppedBy: "shutdown",
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ parts: parts.map((p) => ({ method: "ytdlp" as const, url: ytUrl(id), fromStart: p.fromStart, startedAt, stem: p.stem })),
+ restart: { at: startedAt, by: "boot", state: "asked", jobId: `job-${id}` },
+ });
+};
+const oldRow = async (id: string, startedAt: string) => (await rowOf(id)).find((r) => r.startedAt === startedAt)!;
+
+test("slice 3 resume: the stream is still live → it records again; the interrupted row says restarted and no longer needs a person", async () => {
+ const id = "exmplresum1";
+ const t0 = "2026-11-21T08:00:00.000Z";
+ await interruptedRow(id, t0);
+ const { run, calls, log } = await incidentRun(id, writesAfter(0), { request: { resumeOf: t0 } });
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 1);
+ assert.ok(log.some((l) => /recording again/.test(l)));
+ const old = await oldRow(id, t0);
+ assert.equal(old.restart?.state, "restarted");
+ assert.equal(old.restart?.jobId, `job-${id}`);
+ assert.equal(old.needsAttention, false, "the new run carries it");
+ const fresh = (await rowOf(id)).find((r) => r.startedAt !== t0)!;
+ assert.equal(fresh.resumeOf, t0);
+});
+
+test("slice 3 resume: the stream has ended → no recorder; the interrupted run's part lands, and covering the stream it clears the row", async () => {
+ const id = "exmplresum2";
+ const t0 = "2026-11-21T08:00:00.000Z";
+ const stem = `.${id}.live-2026-11-21T08-00-00-000Z.ytdlp`;
+ await mkdir(store(), { recursive: true });
+ await writeFile(path.join(store(), `${stem}.mp4`), "format=mov,mp4;seconds=3000;");
+ await interruptedRow(id, t0, [{ stem, fromStart: true }]);
+ const { run, calls } = await incidentRun(id, writesAfter(0), {
+ request: { resumeOf: t0 },
+ meta: { ...YT_META(id), live_status: "was_live", duration: 3010 },
+ });
+ const s = await run;
+ assert.equal(calls.length, 0, "nothing is recorded");
+ assert.equal(s.status, "landed");
+ assert.equal(s.landed?.seconds, 3000);
+ const old = await oldRow(id, t0);
+ assert.equal(old.restart?.state, "landing");
+ assert.ok(old.supersededBy, "the landed whole supersedes the interruption");
+ assert.equal(old.needsAttention, false);
+});
+
+test("slice 3 resume: ended with nothing left says so and still needs a person; an unreadable state starts nothing and writes no row of its own", async () => {
+ const id = "exmplresum3";
+ const t0 = "2026-11-21T08:00:00.000Z";
+ await interruptedRow(id, t0);
+ const ended = await incidentRun(id, writesAfter(0), { request: { resumeOf: t0 }, meta: { ...YT_META(id), live_status: "was_live" } });
+ assert.equal((await ended.run).status, "interrupted");
+ assert.equal(ended.calls.length, 0);
+ const rows = await rowOf(id);
+ assert.equal(rows.length, 1, "no row of its own");
+ assert.equal(rows[0]!.restart?.state, "ended");
+ assert.equal(rows[0]!.needsAttention, true);
+ assert.match(rows[0]!.reason, /end of the stream is NOT recorded/);
+
+ const id2 = "exmplresum4";
+ await interruptedRow(id2, t0);
+ const unknown = await incidentRun(id2, writesAfter(0), {
+ request: { resumeOf: t0 },
+ refresh: { failFirst: "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");
+ const rows2 = await rowOf(id2);
+ assert.equal(rows2.length, 1, "no failed row of its own");
+ assert.equal(rows2[0]!.restart?.state, "unknown");
+ assert.match(rows2[0]!.restart?.reason ?? "", /timed out/);
+ assert.equal(rows2[0]!.needsAttention, true);
+});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -64,6 +64,10 @@ import {
LIVE_RATE_LIMIT_WAIT_MS,
LIVE_RECOVERY_EVERY_MS,
LIVE_RECOVERY_MAX_TRIES,
+ LIVE_RESTART_CONFIRM_MS,
+ LIVE_RESTART_WAIT_MS,
+ LIVE_WATCH_MS,
+ restartRefusal,
classifyAttempt,
extractionRefused,
ffmpegLiveArgs,
@@ -81,6 +85,7 @@ import {
spanWords,
ytdlpLiveArgs,
type KeptPart,
+ type LiveBootRestartState,
type RemovedPart,
type LiveFailureClass,
type LivePart,
@@ -96,7 +101,8 @@ import {
} from "../lib/liveCapture";
import { liveRecordingSidecar } from "../lib/mediaImport-server";
import { loadLiveRecordingRows, rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server";
-import { liveRecordingCheckCommand } from "./liveRecordings";
+import { liveRecordingCheckCommand, liveStallMinutes } from "./liveRecordings";
+import { markLiveBootRestart } from "./liveRecordingBoot";
import { setDoNotClean } from "../lib/doNotClean-server";
import type { Paths } from "../lib/paths";
import { detectPlatform } from "../lib/platform";
@@ -185,6 +191,10 @@ export type RecordLiveRequest = {
// while it records — its own job (controller/livePreclip.ts), started once
// the first part begins. Implies `transcribe` unless that is false.
preclip?: PreclipOptions;
+ // INTERNAL (never a body key): the boot pass's restart of the interrupted
+ // run that started at this time (controller/liveRecordingBoot.ts). The
+ // run reads the stream's state first and records only if it is live.
+ resumeOf?: string;
};
export function parseRecordLiveRequest(
@@ -581,6 +591,10 @@ export type RecordLiveDeps = {
// Whether the editor is shutting down (default: the job registry's): a run
// stopped then is `interrupted`, never `cancelled`.
shuttingDown?: () => boolean;
+ // The stall watchdog's look (default LIVE_WATCH_MS) and how long without
+ // growth is a stall (default settings.liveRecording.stallMinutes).
+ watchMs?: number;
+ stallMs?: number;
};
export type RecordLiveJobOpts = {
@@ -741,6 +755,9 @@ type RunHooks = {
platform?: string;
record?: LiveRecordingRecord;
save?: () => Promise<void>;
+ // The failure is said on the interrupted run's row (a restart that found
+ // the stream's state unreadable): no row of its own.
+ quiet?: boolean;
};
const isMustKeep = (req: RecordLiveRequest) => req.doNotClean === true || Boolean(req.note);
@@ -833,7 +850,7 @@ export async function recordLiveRun(
hooks.record.error = message;
await hooks.save();
}
- } else if (hooks.id && !opts.request.dryRun) {
+ } else if (hooks.id && !opts.request.dryRun && !hooks.quiet) {
const failureClass = stopped ? undefined : liveFailureClass(message);
await upsertLiveRecordingRow(opts.paths, opts.request.slug, {
...rowOfRecord(
@@ -876,6 +893,8 @@ async function recordLiveRunInner(
const stretch = deps.jitter ?? ((ms: number) => jitterMs(ms));
const runRecorder = deps.spawn ?? spawnRecorder;
const getText = deps.fetchText ?? fetchText;
+ const watchMs = deps.watchMs ?? LIVE_WATCH_MS;
+ const stallMs = deps.stallMs ?? liveStallMinutes() * 60_000;
const fromStart = req.fromStart !== false;
const maxHeight = req.maxHeight === undefined ? LIVE_DEFAULT_MAX_HEIGHT : req.maxHeight;
const cookies = alwaysCookies(opts.cookiePolicy);
@@ -951,10 +970,54 @@ async function recordLiveRunInner(
requestedBy: RECORD_LIVE_JOB_KIND,
...(deps.refresh ? { run: deps.refresh } : {}),
});
+ // Is the stream still live? One metadata read (slice 3's restarts): a
+ // read that says it ended is the end read the landing would make.
+ let endRead = false;
+ const liveNow = async (): Promise<"live" | "ended" | "unknown"> => {
+ try {
+ await refresh();
+ } catch (err) {
+ say(`The stream's metadata could not be read (${(err as Error).message.split("\n")[0]}).`);
+ return "unknown";
+ }
+ const ls = (await readMeta(videoDir))?.live_status;
+ if (ls === "is_live") return "live";
+ if (ls === "was_live" || ls === "post_live" || ls === "not_live") {
+ endRead = true;
+ return "ended";
+ }
+ return "unknown";
+ };
+ // A RESTART BY THE BOOT PASS (req.resumeOf): what it found goes on the
+ // interrupted run's row.
+ // Only a run the boot pass asked for (its row marked starting/asked) is
+ // one: a stray resumeOf is ignored.
+ let resumeOf: string | null = null;
+ if (req.resumeOf) {
+ const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []);
+ const r = rows.find((x) => x.id === id && x.startedAt === req.resumeOf);
+ if (r && (r.restart?.state === "starting" || r.restart?.state === "asked")) resumeOf = req.resumeOf;
+ else say(`"resumeOf" ${req.resumeOf} names no run the boot pass is restarting: recorded as an ordinary run.`);
+ }
+ const markResume = async (state: LiveBootRestartState, extra: { reason?: string } = {}) => {
+ if (!resumeOf) return;
+ await markLiveBootRestart(paths, req.slug, id, resumeOf, { state, ...(opts.jobId ? { jobId: opts.jobId } : {}), ...extra }, now).catch(
+ (e: Error) => say(`The interrupted run's row could not be updated (${e.message}).`),
+ );
+ };
try {
await refresh();
} catch (err) {
extractionError = (err as Error).message;
+ 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;
+ }
const canFallBack = BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(extractionError);
if (!canFallBack) {
await abandon();
@@ -964,7 +1027,38 @@ async function recordLiveRunInner(
}
const meta = await readMeta(videoDir);
const liveStatus = typeof meta?.live_status === "string" ? meta.live_status : null;
- if (meta && liveStatus && !LIVE_STATES.has(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.
+ let resumeEnded = false;
+ if (resumeOf) {
+ if (!meta || !liveStatus) {
+ say("Restart after the editor restart: the stream's record says nothing of its state — nothing is recorded or landed.");
+ await markResume("unknown", { reason: "the metadata names no live_status" });
+ hooks.quiet = true;
+ await abandon();
+ throw new Error(`${plan.url}: its live state is not known; not restarted`);
+ }
+ if (!LIVE_STATES.has(liveStatus)) {
+ const stage = path.dirname(savedVideoDir(paths, opts.channelConfig, req.slug, id));
+ const left = livePartFiles(id, await readdir(stage).catch(() => [] as string[]));
+ if (!left.length) {
+ say(`Restart after the editor restart: the stream has ended (${liveStatus}) and nothing is left in staging — nothing more to record or land.`);
+ await markResume("ended");
+ summary.status = "interrupted";
+ say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
+ return summary;
+ }
+ say(`Restart after the editor restart: the stream has ended (${liveStatus}); the ${left.length} part(s) left in staging are landed.`);
+ await markResume("landing");
+ resumeEnded = true;
+ endRead = true;
+ } else {
+ say(`Restart after the editor restart: the stream is ${liveStatus}; recording again.`);
+ await markResume("restarted");
+ }
+ }
+ if (!resumeEnded && meta && liveStatus && !LIVE_STATES.has(liveStatus)) {
await abandon();
throw new Error(
`${plan.url} is not live (live_status ${liveStatus}): download it as a video, or import a recording of it`,
@@ -1015,6 +1109,7 @@ async function recordLiveRunInner(
mustKeep: isMustKeep(req),
...(opts.jobId ? { jobId: opts.jobId } : {}),
...(streamStartSec !== null ? { streamStartedAt: new Date(streamStartSec * 1000).toISOString() } : {}),
+ ...(resumeOf ? { resumeOf } : {}),
};
// The record beside the video, and the channel's row (which outlives it).
let rowWarned = false;
@@ -1034,7 +1129,7 @@ async function recordLiveRunInner(
// (Not for separate streams from the start: YouTube's DASH from the start is
// not the HLS playlist the record lists, which holds only the live edge.)
const fmt = meta ? hlsFormatOf(meta, maxHeight) : null;
- if (fmt && plan.platform !== "kick" && !(separate && fromStart)) {
+ if (fmt && !resumeEnded && plan.platform !== "kick" && !(separate && fromStart)) {
try {
const pl = parsePlaylist(await getText(fmt.url, signal), fmt.url);
if (pl?.kind === "media") {
@@ -1093,20 +1188,25 @@ async function recordLiveRunInner(
tag: string,
mode: "from-start" | "index0" | "now",
extraNote = "",
- opts: { recovery?: boolean } = {},
- ): Promise<RecorderOutcome & { part: LivePart; stem: string }> => {
+ // recovery: a slice-2 try. noWait: never `--wait-for-video` (a restart or
+ // a try is of a stream already live). watch: the stall watchdog (off for
+ // Kick's channel recorder, which its VOD poll ends).
+ opts: { recovery?: boolean; restart?: number; noWait?: boolean; watch?: boolean } = {},
+ ): Promise<RecorderOutcome & { part: LivePart; stem: string; stalled: boolean }> => {
const file = separate ? stemPath(tag) : partPath(tag);
const part = begin("ytdlp", url, file, mode !== "now");
if (opts.recovery) part.recovery = true;
+ if (opts.restart) part.restart = opts.restart;
const stem = part.stem!;
await save();
+ const waitForVideo = !opts.noWait && liveStatus === "is_upcoming" && tag !== "channel";
const args = ytdlpLiveArgs({
url,
output: file,
fromStart: mode === "from-start",
maxHeight,
separate,
- waitForVideo: liveStatus === "is_upcoming" && tag !== "channel",
+ waitForVideo,
channelArgs: [
...channelExtraArgs(cfg, cookies),
"--downloader-args",
@@ -1115,10 +1215,56 @@ async function recordLiveRunInner(
});
// The recorder's argv does not pass jitterYtdlpSleeps: asked here.
refuseInstagramYtdlp(args);
- const o = await runRecorder({ bin: paths.ytdlpBin, args, cwd: channelDir, onLog, signal, label: tag });
- finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? " (stopped)" : ""}`);
+ // SLICE 3 — THE STALL WATCHDOG: this recorder's own stop, besides the
+ // job's. Every watchMs the part's files (all of them) are summed; no
+ // change for stallMs stops this recorder only. An upcoming stream's
+ // recorder waiting for it with nothing written is not stalled.
+ const own = new AbortController();
+ const onJobAbort = () => own.abort();
+ if (signal.aborted) own.abort();
+ else signal.addEventListener("abort", onJobAbort, { once: true });
+ let stalled = false;
+ let timer: NodeJS.Timeout | null = null;
+ if (opts.watch !== false) {
+ let last = -1;
+ let lastGrowth = now().getTime();
+ let busy = false;
+ timer = setInterval(() => {
+ if (busy || own.signal.aborted) return;
+ busy = true;
+ void allBytesOf(stem)
+ .then((b) => {
+ const t = now().getTime();
+ if (b !== last || (waitForVideo && b === 0)) {
+ last = b;
+ lastGrowth = t;
+ return;
+ }
+ if (t - lastGrowth >= stallMs && !own.signal.aborted) {
+ stalled = true;
+ say(
+ `[${tag}] stalled: its files have not grown for ${spanWords((t - lastGrowth) / 1000)} (${formatBytes(b)}); ` +
+ "stopping this recorder (SIGINT); its part is kept.",
+ );
+ own.abort();
+ }
+ })
+ .finally(() => {
+ busy = false;
+ });
+ }, watchMs);
+ }
+ let o: RecorderOutcome;
+ try {
+ o = await runRecorder({ bin: paths.ytdlpBin, args, cwd: channelDir, onLog, signal: own.signal, label: tag });
+ } finally {
+ if (timer) clearInterval(timer);
+ signal.removeEventListener("abort", onJobAbort);
+ }
+ if (stalled) part.stalled = true;
+ finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? (stalled ? " (stopped: stalled)" : " (stopped)") : ""}`);
await save();
- return { ...o, part, stem };
+ return { ...o, part, stem, stalled };
};
const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0);
const filesOf = async (stem: string): Promise<LivePartFiles | null> =>
@@ -1129,6 +1275,13 @@ async function recordLiveRunInner(
for (const f of g ? [...g.finished, ...g.streams] : []) n += await sizeOf(path.join(slugStore, f));
return n;
};
+ // Every file of the part, scratch too (the watchdog's growth).
+ const allBytesOf = async (stem: string) => {
+ const g = await filesOf(stem);
+ let n = 0;
+ for (const f of g ? [...g.finished, ...g.streams, ...g.scratch] : []) n += await sizeOf(path.join(slugStore, f));
+ return n;
+ };
const probe = deps.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s));
// A separate-streams part where only one stream wrote bytes: which is
// missing (null: both wrote, or a finished file holds them).
@@ -1144,14 +1297,16 @@ async function recordLiveRunInner(
return p?.videoCodec ? "audio" : p?.audioCodec ? "video" : "unknown";
};
- if (plan.platform === "kick") {
+ if (resumeEnded) {
+ // Nothing to record: straight to the landing.
+ } else if (plan.platform === "kick") {
const vodFmt = fmt;
const channel = plan.kickChannel ?? (typeof meta?.uploader_id === "string" ? meta.uploader_id : null);
let liveDone = channel === null;
if (channel === null) say("The record names no Kick channel: only the VOD is recorded.");
const live = channel
? (async () => {
- const o = await ytdlpPart(`https://kick.com/${channel}`, "channel", "now");
+ const o = await ytdlpPart(`https://kick.com/${channel}`, "channel", "now", "", { watch: false });
liveDone = true;
return o;
})()
@@ -1208,6 +1363,8 @@ async function recordLiveRunInner(
// failure no try can help, on a second rate limit, on a Cancel, or when
// the tries are spent. A try that records and ends while the live edge
// still records died mid-stream: the next try follows, inside the bound.
+ // The main recording's last attempt (what the restarts below look at).
+ let lastMain: { o: Awaited<ReturnType<typeof ytdlpPart>>; bytes: number; mode: "from-start" | "index0" | "now" } | null = null;
let recovery: Promise<void> | null = null;
const recoveryStop = new AbortController();
let edgeDone = false;
@@ -1234,7 +1391,10 @@ async function recordLiveRunInner(
});
const bytes = await bytesOf(o.stem);
const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(o.stem) : null;
- const cls = classifyAttempt({ ...o, bytes, partial: missing !== null });
+ // A try the watchdog stopped with nothing written failed; one with
+ // bytes died mid-stream like one that exited.
+ const stalledEmpty = o.stalled && bytes === 0 && !signal.aborted;
+ const cls = stalledEmpty ? "nothing" : o.stalled && !signal.aborted ? "recorded" : classifyAttempt({ ...o, bytes, partial: missing !== null });
if (cls === "recorded") {
if (edgeDone || signal.aborted) {
rs.state = "recorded";
@@ -1250,9 +1410,18 @@ async function recordLiveRunInner(
rs.state = "stopped";
break;
}
- const errLine = lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
- const failure: LiveFailureClass =
- cls === "partial" ? "partial" : cls === "argv" ? "argv" : cls === "unsupported" ? "unsupported" : liveFailureClass(o.stderrTail);
+ const errLine = stalledEmpty
+ ? `stalled: nothing written for ${spanWords(stallMs / 1000)}`
+ : (lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`);
+ const failure: LiveFailureClass = stalledEmpty
+ ? "stalled"
+ : cls === "partial"
+ ? "partial"
+ : cls === "argv"
+ ? "argv"
+ : cls === "unsupported"
+ ? "unsupported"
+ : liveFailureClass(o.stderrTail);
o.part.error = missing !== null ? `the ${missing === "unknown" ? "video or audio" : missing} stream recorded nothing (${errLine})` : errLine;
o.part.failureClass = failure;
if (missing !== null) o.part.missingStream = missing;
@@ -1289,16 +1458,30 @@ async function recordLiveRunInner(
// This attempt's own part (a try beside it may have begun one since).
const last = { part: o.part, stem: o.stem };
const bytes = await bytesOf(last.stem);
+ lastMain = { o, bytes, mode };
const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(last.stem) : null;
- const cls = classifyAttempt({ ...o, bytes, partial: missing !== null });
+ // Stopped by the watchdog with nothing written: an attempt that
+ // recorded nothing (the schedule goes on). With bytes: the restarts
+ // below decide.
+ const stalledEmpty = o.stalled && bytes === 0 && !signal.aborted;
+ const cls = stalledEmpty ? "nothing" : classifyAttempt({ ...o, bytes, partial: missing !== null });
if (cls === "recorded" || cls === "stopped" || signal.aborted) {
delete record.missingStream;
delete record.failureClass;
break;
}
- const errLine = lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
- const failure: LiveFailureClass =
- cls === "partial" ? "partial" : cls === "argv" ? "argv" : cls === "unsupported" ? "unsupported" : liveFailureClass(o.stderrTail);
+ const errLine = stalledEmpty
+ ? `stalled: nothing written for ${spanWords(stallMs / 1000)}`
+ : (lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`);
+ const failure: LiveFailureClass = stalledEmpty
+ ? "stalled"
+ : cls === "partial"
+ ? "partial"
+ : cls === "argv"
+ ? "argv"
+ : cls === "unsupported"
+ ? "unsupported"
+ : liveFailureClass(o.stderrTail);
const reason =
missing !== null
? `${missing === "unknown" ? "one of its two streams" : `the ${missing} stream`} recorded nothing (${errLine})`
@@ -1377,6 +1560,69 @@ async function recordLiveRunInner(
}
await waitFor(stretch(next.waitMs), signal);
}
+ // SLICE 3 — THE RESTARTS (lib/liveCapture.ts LiveRestarts). The main
+ // recording's last part stalled with bytes, or its recorder exited with
+ // bytes: is the stream still live? One metadata read (the read the job
+ // makes at its end anyway; an exit is read twice, a minute apart, as a
+ // stream just ended may read live a moment). Live → a new part in the
+ // same mode after a pause, the old part kept for the landing; ended →
+ // land; unreadable → a stall restarts (the recorder's own exit says
+ // 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;
+ while (cur && !signal.aborted && !pathB) {
+ const stalledWithBytes = cur.o.stalled && cur.bytes > 0;
+ const exitedWithBytes = !cur.o.signalled && cur.bytes > 0;
+ 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";
+ 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.`);
+ await waitFor(stretch(LIVE_RESTART_CONFIRM_MS), signal);
+ if (signal.aborted) break;
+ state = await liveNow();
+ }
+ if (state === "ended") {
+ if (cur.o.stalled) say(`The stream has ended: what was recorded lands (no restart).`);
+ break;
+ }
+ if (state === "unknown" && !cur.o.stalled && !failedRestart) {
+ 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 (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.`);
+ break;
+ }
+ await waitFor(stretch(LIVE_RESTART_WAIT_MS), signal);
+ if (signal.aborted) break;
+ restarts.count += 1;
+ restarts.at.push(now().toISOString());
+ const k = restarts.count;
+ say(`Restart ${k} (${why}, the stream ${state === "live" ? "is live" : "state unknown"}): a new part ${cur.mode === "now" ? "from the live edge" : "from its start"}; the earlier part is kept for the landing.`);
+ const o = await ytdlpPart(plan.url, `ytdlp-r${k}`, cur.mode, `restart ${k} (${why}); `, { restart: k, noWait: true });
+ const bytes = await bytesOf(o.stem);
+ if (bytes === 0 && !o.signalled) {
+ const c = classifyAttempt({ ...o, bytes });
+ o.part.error = lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
+ o.part.failureClass = liveFailureClass(o.stderrTail);
+ await save();
+ if (c === "final" || c === "argv" || c === "unsupported") {
+ say(`Restart ${k} recorded nothing (${o.part.error}): no more restarts.`);
+ break;
+ }
+ }
+ cur = { o, bytes, mode: cur.mode };
+ }
// The live-edge recording is over: a recovery try still WAITING stops
// (the stream ended, or the live edge failed); one in flight is awaited,
// never stopped — it may hold the only copy.
@@ -1418,10 +1664,13 @@ async function recordLiveRunInner(
const stopped = signal.aborted ? stopOf(deps) : null;
const cancelled = stopped !== null;
const landSignal = new AbortController().signal;
- try {
- await refresh();
- } catch (err) {
- say(`The ended stream's metadata was not re-read (${(err as Error).message.split("\n")[0]}).`);
+ // (Read already when the restarts asked whether the stream is still live.)
+ if (!endRead) {
+ try {
+ await refresh();
+ } catch (err) {
+ say(`The ended stream's metadata was not re-read (${(err as Error).message.split("\n")[0]}).`);
+ }
}
const endMeta = await readMeta(videoDir);
const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s));
diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts
@@ -451,6 +451,12 @@ export type LivePart = {
missingStream?: MissingStream;
// A from-start try beside a live-edge recording (StartRecovery).
recovery?: boolean;
+ // The stall watchdog stopped its recorder: its files had not grown for
+ // stallMinutes (LiveRestarts).
+ stalled?: boolean;
+ // A restart of the recording after a stall or a recorder that died while
+ // the stream was live (1-based).
+ restart?: number;
};
export type MissingStream = "video" | "audio" | "unknown";
@@ -533,7 +539,8 @@ export type LiveRecordingRecord = {
missingStream?: MissingStream;
// Who stopped it, when it was stopped: a person's Cancel, or the editor
// shutting down (then the status is `interrupted`).
- stoppedBy?: "operator" | "shutdown";
+ // `crash`: the editor died with it recording (found so at the next boot).
+ stoppedBy?: "operator" | "shutdown" | "crash";
// Parts left on disk, not landed (KeptPart).
keptParts?: KeptPart[];
// Parts the landing removed as inside the landed file (RemovedPart).
@@ -543,8 +550,65 @@ export type LiveRecordingRecord = {
// After a fallback to the live edge: the from-start tries beside it
// (StartRecovery).
startRecovery?: StartRecovery;
+ // The recorder restarted after a stall or a death mid-stream (LiveRestarts).
+ restarts?: LiveRestarts;
+ // This run was started by the boot pass after an editor restart, for the
+ // interrupted run that started at this time (its row's startedAt).
+ resumeOf?: string;
};
+// WHAT THE BOOT PASS DID WITH AN INTERRUPTED RUN (controller/liveRecordingBoot.ts),
+// on that run's row. Written BEFORE the new run is asked for (`starting`), so
+// a row is restarted at most once, even if the boot itself dies after.
+// starting the new run is being asked for
+// asked a record-live job was queued (jobId)
+// restarted that job found the stream live and records it
+// landing the stream had ended; what the earlier run left lands
+// ended the stream had ended and nothing was left to land
+// unknown the stream's state could not be read: nothing was started
+// (never a recording on a guess) — Record again
+// refused not restarted (reason: a restart loop, a recorder of the last
+// process still writing, the setting off)
+// failed the job could not be queued (reason)
+export type LiveBootRestartState = "starting" | "asked" | "restarted" | "landing" | "ended" | "unknown" | "refused" | "failed";
+
+export type LiveBootRestart = { at: string; by: "boot"; state: LiveBootRestartState; jobId?: string; reason?: string };
+
+// --- the stall watchdog and the restarts ------------------------------------------
+//
+// While a recorder runs, its part's files (every one: a merge's temp file is
+// growth too) are compared every LIVE_WATCH_MS. No growth for stallMinutes
+// (settings.liveRecording.stallMinutes, default 10) stops THAT recorder
+// (SIGINT, so its file is finalized); its part stays. A recorder that stalled
+// with bytes, or exited with bytes while the stream still reads live (two
+// reads LIVE_RESTART_CONFIRM_MS apart — a stream that has just ended may read
+// live for a moment), is restarted: one metadata read (the read the job makes
+// at its end anyway), LIVE_RESTART_WAIT_MS, a new part with its own stem in
+// the same mode. Bounded: LIVE_RESTART_MAX_PER_HOUR in any 60 minutes and
+// LIVE_RESTART_MAX_PER_RUN in all; past either the run lands what it has and
+// `refused` needs a person.
+export const LIVE_WATCH_MS = 60_000;
+export const LIVE_RESTART_WAIT_MS = 30_000;
+export const LIVE_RESTART_CONFIRM_MS = 60_000;
+export const LIVE_RESTART_MAX_PER_HOUR = 3;
+export const LIVE_RESTART_MAX_PER_RUN = 12;
+
+export type LiveRestarts = {
+ count: number;
+ // When each restart was made, ISO.
+ at: string[];
+ // Why no further restart was made though the stream was live.
+ refused?: string;
+};
+
+// Whether one more restart is allowed at `nowMs`; else the reason.
+export function restartRefusal(r: Pick<LiveRestarts, "count" | "at">, nowMs: number): string | null {
+ if (r.count >= LIVE_RESTART_MAX_PER_RUN) return `${r.count} restarts in this run (at most ${LIVE_RESTART_MAX_PER_RUN})`;
+ const recent = r.at.filter((a) => nowMs - Date.parse(a) < 3_600_000).length;
+ if (recent >= LIVE_RESTART_MAX_PER_HOUR) return `${recent} restarts in the last hour (at most ${LIVE_RESTART_MAX_PER_HOUR})`;
+ return null;
+}
+
// --- recovering the start beside a live-edge recording ----------------------------
//
// A run that fell back to the live edge (its from-start attempts recorded
@@ -662,7 +726,8 @@ export type LiveFailureClass =
| "unknown"
| "argv"
| "unsupported"
- | "partial";
+ | "partial"
+ | "stalled";
// What yt-dlp says when the stream is over or gone: no attempt can help.
export function liveStreamGone(stderr: string): boolean {
diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts
@@ -33,6 +33,8 @@ import type {
LiveRecordingRecord,
LiveRecordingStatus,
LostSpan,
+ LiveBootRestart,
+ LiveRestarts,
MissingStream,
StartRecovery,
StreamCoverage,
@@ -68,11 +70,16 @@ export type LiveRecordingRow = {
landedPart?: number;
failureClass?: LiveFailureClass;
missingStream?: MissingStream;
- stoppedBy?: "operator" | "shutdown";
+ stoppedBy?: "operator" | "shutdown" | "crash";
keptParts?: KeptPart[];
removedParts?: RemovedPart[];
coverage?: StreamCoverage;
startRecovery?: StartRecovery;
+ restarts?: LiveRestarts;
+ // This run was started by the boot pass for the interrupted run of this
+ // startedAt; and, on an interrupted run, what the boot pass did with it.
+ resumeOf?: string;
+ restart?: LiveBootRestart;
acknowledgedAt?: string;
acknowledgedBy?: string;
// The run (its jobId, else its startedAt) that later landed this id.
@@ -137,7 +144,10 @@ export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, s
// Needs a person, as the row stands (the listing adds `interrupted` for a
// `recording` no job runs).
-// failed, interrupted always
+// failed, interrupted always — but an interrupted run the
+// boot pass restarted from its start
+// (restart "restarted"): its new run's
+// row carries it
// cancelled when the stream was must-keep (a
// person's Cancel of any other stream
// is quiet)
@@ -145,6 +155,8 @@ export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, s
// a from-start try beside it was
// landed and holds the whole stream
// (startRecovery "recovered")
+// restarts refused the stream was live and its recorder
+// stalled or died once too often
// one stream missing it landed without video or audio
// parts kept on disk (keptParts) until acknowledged, whatever lands
// later: a later recording does not
@@ -153,14 +165,19 @@ 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">>,
+ Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart">>,
): boolean {
if (r.acknowledgedAt) return false;
if (r.keptParts && r.keptParts.length > 0) return true;
if (r.supersededBy) return false;
+ // An interruption the boot pass restarted from its start is carried by the
+ // new run's own row (it records the whole stream again, or says what it
+ // lost); every other interruption needs a person.
+ if (r.status === "interrupted" && r.restart?.state === "restarted" && r.fromStart === true) return false;
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;
+ if (r.restarts?.refused) return true;
return r.missingStream !== undefined;
}
@@ -237,6 +254,8 @@ export function rowOfRecord(
...(rec.removedParts && rec.removedParts.length ? { removedParts: rec.removedParts.map((r) => ({ ...r })) } : {}),
...(rec.coverage ? { coverage: { ...rec.coverage } } : {}),
...(rec.startRecovery ? { startRecovery: { ...rec.startRecovery } } : {}),
+ ...(rec.restarts ? { restarts: { ...rec.restarts, at: [...rec.restarts.at] } } : {}),
+ ...(rec.resumeOf ? { resumeOf: rec.resumeOf } : {}),
};
}
@@ -269,6 +288,7 @@ export async function upsertLiveRecordingRow(
...(prev?.acknowledgedAt ? { acknowledgedAt: prev.acknowledgedAt } : {}),
...(prev?.acknowledgedBy ? { acknowledgedBy: prev.acknowledgedBy } : {}),
...(prev?.supersededBy ? { supersededBy: prev.supersededBy } : {}),
+ ...(prev?.restart ? { restart: prev.restart } : {}),
};
if (i >= 0) rows[i] = next;
else rows.push(next);
@@ -325,3 +345,20 @@ export async function acknowledgeSetAsideFiles(
return [n, n > 0];
});
}
+
+// Changes one row (by id and startedAt) under the file's lock. False: no such
+// row. `fn` returns false to write nothing.
+export async function patchLiveRecordingRow(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ id: string,
+ startedAt: string,
+ fn: (row: LiveRecordingRow) => boolean | void,
+): Promise<boolean> {
+ return mutate(paths, slug, (rows) => {
+ const r = rows.find((x) => x.id === id && x.startedAt === startedAt);
+ if (!r) return [false, false];
+ const changed = fn(r) !== false;
+ return [true, changed];
+ });
+}
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -992,17 +992,25 @@ export function sanitizeLivePreclip(v: unknown): LivePreclipSettingsBlock {
// LIVE_RECORDING_SETTINGS_FIELD_DOCS (rendered into SETTINGS.md).
export type LiveRecordingSettingsBlock = {
stallMinutes: number;
+ autoRestartOnBoot: boolean;
};
export const LIVE_RECORDING_SETTINGS_FIELD_DOCS: FieldDocs<LiveRecordingSettingsBlock> = {
stallMinutes:
"Minutes a running live recording's files may go without growing before `pnpm ops get live-recordings` (and /review, " +
- "the banners) mark it `stalled`. Clamped 1–240; default 10.",
+ "the banners) mark it `stalled` — and before record-live's own watchdog stops that recorder and, while the stream is " +
+ "still live, starts a new part (at most 3 restarts an hour, 12 a run). Clamped 1–240; default 10.",
+ autoRestartOnBoot:
+ "After an editor restart, a live recording the shutdown (or a crash) interrupted is restarted by itself: the new run " +
+ "reads the stream's state first (one paced metadata request) and records only if it is still live; ended, it lands what " +
+ "is in staging; unreadable, it starts nothing. At most once per interrupted run and 3 times an hour per stream; never " +
+ "after a person's Cancel (common/controller/liveRecordingBoot.ts). Default true; false leaves every interruption to " +
+ "/review's Record again.",
};
export function sanitizeLiveRecording(v: unknown): LiveRecordingSettingsBlock {
const r = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
- return { stallMinutes: clampInt(r.stallMinutes, 1, 240, 10) };
+ return { stallMinutes: clampInt(r.stallMinutes, 1, 240, 10), autoRestartOnBoot: r.autoRestartOnBoot !== false };
}
export const SLEEP_BETWEEN_DOWNLOADS_MAX_SECONDS = 600;
@@ -1995,7 +2003,7 @@ export const siteSettingsSchema = z.object({
"The defaults of LIVE PRE-CLIP (plans/live-preclip.md): a live recording transcribed and mined while it records — record-live's `\"preclip\": true`, `pnpm ops live-preclip`. A request's own `preclip` keys override these. See common/controller/livePreclip.ts.",
),
liveRecording: settingsField((v): LiveRecordingSettingsBlock => sanitizeLiveRecording(v)).describe(
- "How a running live recording is judged (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled. See common/controller/liveRecordings.ts.",
+ "How a running live recording is judged and kept alive (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled (and restart its recorder), and whether an editor restart's interruption restarts by itself. See common/controller/liveRecordings.ts and common/controller/liveRecordingBoot.ts.",
),
pacing: settingsField((v): PacingSettingsBlock => sanitizePacing(v)).describe(
"How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.",
diff --git a/editor/app/api/ops/_liveRecordingBoot.ts b/editor/app/api/ops/_liveRecordingBoot.ts
@@ -0,0 +1,47 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import {
+ LIVE_BOOT_DELAY_MS,
+ restartInterruptedLiveRecordings,
+} from "yt-dlp-transcript-common/controller/liveRecordingBoot";
+import { recordLiveAction } from "../../channels/[slug]/liveMediaActions";
+
+// THE LIVE RECORDINGS AN EDITOR RESTART INTERRUPTED, RESTARTED (operator
+// ruling, 21 Nov 2026): instrumentation.ts arms this below the idle gate and
+// never on the e2e test server. LIVE_BOOT_DELAY_MS after boot (an orphan
+// recorder of the last process has written by then, and is refused), one pass
+// of common/controller/liveRecordingBoot.ts: each interrupted run asks for a
+// record-live job through the same door the ops route and Record again use,
+// with `resumeOf`, and that job reads the stream's state before it records.
+// The pass itself makes no request.
+export function armLiveRecordingBootPass(bootedAt: number): void {
+ const t = setTimeout(() => {
+ void runPass(bootedAt).catch((e: Error) => console.log(`[boot] live recordings: the restart pass failed (${e.message})`));
+ }, LIVE_BOOT_DELAY_MS);
+ t.unref?.();
+}
+
+async function runPass(bootedAt: number): Promise<void> {
+ const settings = getSettings();
+ await restartInterruptedLiveRecordings({
+ paths: getPaths(),
+ bootedAt,
+ enabled: settings.liveRecording.autoRestartOnBoot,
+ isRunning: (jobId, slug, id) => {
+ const jobs = getRegistry().list();
+ return jobs.some(
+ (j) =>
+ (j.status === "running" || j.status === "queued") &&
+ (jobId ? j.id === jobId : j.kind === "record-live" && j.channelSlug === slug && j.videoId === id),
+ );
+ },
+ start: async (_slug, body, resumeOf) => {
+ const r = await recordLiveAction(body, { resumeOf });
+ if (!r.ok) return { ok: false, error: r.error };
+ void r.stream.cancel();
+ return { ok: true, jobId: r.jobId };
+ },
+ log: (line) => console.log(line),
+ });
+}
diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts
@@ -99,9 +99,12 @@ export async function importMediaAction(body: Record<string, unknown>): Promise<
});
}
-export async function recordLiveAction(body: Record<string, unknown>): Promise<StreamActionResult> {
- const req = parseRecordLiveRequest(body, preclipDefaults());
- if ("error" in req) return { ok: false, error: req.error };
+// `internal.resumeOf`: the boot pass's restart of an interrupted run
+// (app/api/ops/_liveRecordingBoot.ts) — never read from a body.
+export async function recordLiveAction(body: Record<string, unknown>, internal: { resumeOf?: string } = {}): Promise<StreamActionResult> {
+ const parsed = parseRecordLiveRequest(body, preclipDefaults());
+ if ("error" in parsed) return { ok: false, error: parsed.error };
+ const req = internal.resumeOf ? { ...parsed, resumeOf: internal.resumeOf } : parsed;
if (!isValidChannelSlug(req.slug)) return { ok: false, error: `"${req.slug}" is not a channel slug` };
const paths = getPaths();
const config = await readChannelConfig(paths, req.slug);
diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -338,6 +338,23 @@ export async function register() {
/* a schedule that fails to arm must not block server readiness */
}
+ // A LIVE RECORDING AN EDITOR RESTART INTERRUPTED RESTARTS BY ITSELF
+ // (operator ruling, 21 Nov 2026): one pass, 30 s after boot — each run the
+ // shutdown (or a crash) interrupted asks for a record-live job that reads
+ // the stream's state first and records only if it is still live; a
+ // person's Cancel never restarts. At most once per run and 3 an hour per
+ // stream (settings.liveRecording.autoRestartOnBoot). Below the idle gate —
+ // the job makes a request to the platform — and not on the e2e test
+ // server. See common/controller/liveRecordingBoot.ts.
+ if (process.env.E2E_TEST_ROUTES !== "1") {
+ try {
+ const { armLiveRecordingBootPass } = await import("./app/api/ops/_liveRecordingBoot");
+ armLiveRecordingBootPass(bootedAt);
+ } catch {
+ /* a pass that fails to arm must not block server readiness */
+ }
+ }
+
// AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1): the job-end
// listener and one scan of the research runs now; the heartbeat scans again
// on each beat. Below the idle gate: a continuation is a generation job.
diff --git a/settings.json.example b/settings.json.example
@@ -17,7 +17,8 @@
"mine": true
},
"liveRecording": {
- "stallMinutes": 10
+ "stallMinutes": 10,
+ "autoRestartOnBoot": true
},
"pacing": {
"sleepRequestsCapSeconds": 16,