Archilyzer · Source

archilyzer

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

commit 2f11fc510c8eda9e555019a930406d1d69a109a7
parent 6c65b20aa035723fc4ae8b4c677d7a9db2ef2d97
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 01:04:00 -0500

record-live: retry a from-start attempt that records nothing, fall back to the live edge, keep the failure

A from-start yt-dlp attempt that wrote nothing ("The downloaded file is
empty") ended the job with no retry, no fallback and, when the run had made
data/<id>/, no record at all. Now:

- attempts (lib/liveCapture.ts liveAttemptSchedule/classifyAttempt): from
  its start at 0/+60/+180 s, then from the live edge (--no-live-from-start,
  the request Kick's channel recorder already makes) at 0/+60/+180 s, each
  wait jittered and ended by a Cancel. An ended/private stream, an argv no
  try can fix, a Cancel and a part with bytes are not retried. A healthy
  recording's first argv is unchanged (tested byte for byte).
- the record says why: each part's last ERROR line, attempts, a live-edge
  fallback with the span of the stream it lost, mustKeep, jobId.
- channels/<slug>/live-recordings.json (lib/liveRecordings-server.ts): one
  row per run, written on every save, kept when the run's data/<id>/ is
  removed; a refusal before any recorder (and a throw mid-run) is written
  too. A later run that lands from the start supersedes earlier failures.
- controller/liveRecordings.ts: the listing (status from the record,
  interrupted when no job runs it, bytes, last growth, stalled,
  needsAttention) and the acknowledgement.
- settings.liveRecording.stallMinutes (default 10).
- the recorder's log thinning also catches yt-dlp's numbered stream lines
  ("1: [download] ..."), which were logged every second.

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

Diffstat:
MSETTINGS.md | 19+++++++++++++++++++
Acommon/controller/liveRecordings.test.ts | 119+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/liveRecordings.ts | 226+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/recordLive.test.ts | 196+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/recordLive.ts | 217++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Mcommon/lib/liveCapture.ts | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/lib/liveRecordings-server.ts | 192+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 8++++++++
Mcommon/lib/settingsSchema.test.ts | 6+++++-
Mcommon/lib/settingsSchema.ts | 21+++++++++++++++++++++
Msettings.json.example | 3+++
11 files changed, 1072 insertions(+), 29 deletions(-)

diff --git a/SETTINGS.md b/SETTINGS.md @@ -22,6 +22,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`social`](#social) | object — see below | | [`sleepBetweenDownloadsSeconds`](#sleepbetweendownloadsseconds) | `10` | | [`livePreclip`](#livepreclip) | object — see below | +| [`liveRecording`](#liverecording) | object — see below | | [`pacing`](#pacing) | object — see below | | [`downloadFormat`](#downloadformat) | `"auto"` | | [`sourceVideoQuality`](#sourcevideoquality) | `"original"` | @@ -252,6 +253,24 @@ 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. + +#### `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. | + +Default: + +```json +{ + "stallMinutes": 10 +} +``` + ## `pacing` 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/common/controller/liveRecordings.test.ts b/common/controller/liveRecordings.test.ts @@ -0,0 +1,119 @@ +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/liveRecordings.test.ts +// +// The live recordings listing (controller/liveRecordings.ts) over a temp +// corpus: rows written through lib/liveRecordings-server.ts, records and +// staging files made by hand, the job registry a stub. + +const ROOT = await mkdtemp(path.join(tmpdir(), "live-recordings-")); +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 { listLiveRecordings, acknowledgeLiveRecording, countLiveRecordingsNeedingAttention } = await import("./liveRecordings"); +const { upsertLiveRecordingRow, loadLiveRecordingRows } = 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-live"; +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-20T12:00:00.000Z"); +const minutesAgo = (m: number) => new Date(NOW.getTime() - m * 60_000); + +async function recording(id: string, stem: string, opts: { jobId?: string; startedAt?: Date } = {}) { + const startedAt = (opts.startedAt ?? minutesAgo(60)).toISOString(); + const rec = { + status: "recording" as const, + url: `https://www.youtube.com/watch?v=${id}`, + platform: "youtube", + fromStart: true, + startedAt, + parts: [{ method: "ytdlp" as const, url: "u", fromStart: true, startedAt, stem }], + attempts: 1, + mustKeep: true, + streamStartedAt: minutesAgo(120).toISOString(), + ...(opts.jobId ? { jobId: opts.jobId } : {}), + }; + const dir = path.join(CORPUS, "channels", SLUG, "data", id); + await mkdir(dir, { recursive: true }); + await liveRecordingSidecar.write(dir, rec); + await upsertLiveRecordingRow(paths, SLUG, { ...rec, id, mustKeep: true, attempts: 1 }); + return rec; +} + +test("a recording whose job runs and whose files grow: bytes summed, not stalled, elapsed from the stream's start", async () => { + const stem = ".exmplgrow01.live-2026-11-20T11-00-00-000Z.ytdlp"; + await recording("exmplgrow01", stem, { jobId: "job-grow" }); + await writeFile(path.join(store, `${stem}.f247.webm`), Buffer.alloc(3000)); + await writeFile(path.join(store, `${stem}.f140.m4a`), Buffer.alloc(1000)); + for (const f of [`${stem}.f247.webm`, `${stem}.f140.m4a`]) await utimes(path.join(store, f), minutesAgo(1), minutesAgo(1)); + const { rows } = await listLiveRecordings(paths, { + slug: SLUG, + id: "exmplgrow01", + now: NOW, + jobs: () => [{ id: "job-grow", kind: "record-live", status: "running", channelSlug: SLUG, videoId: "exmplgrow01" }], + }); + const r = rows[0]!; + assert.equal(r.status, "recording"); + assert.equal(r.bytes, 4000); + assert.equal(r.stalled, false); + assert.equal(r.lastGrowthAt, minutesAgo(1).toISOString()); + assert.equal(r.streamElapsedSeconds, 7200); + assert.equal(r.needsAttention, false); + assert.equal(r.job?.status, "running"); + assert.equal(r.check, "pnpm ops get live-recordings synth-live/exmplgrow01"); +}); + +test("stalled: recording, and nothing has grown for stallMinutes", async () => { + const stem = ".exmplstal01.live-2026-11-20T11-00-00-000Z.ytdlp"; + await recording("exmplstal01", stem, { jobId: "job-stall" }); + await writeFile(path.join(store, `${stem}.ts`), Buffer.alloc(500)); + await utimes(path.join(store, `${stem}.ts`), minutesAgo(25), minutesAgo(25)); + const jobs = () => [{ id: "job-stall", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstal01" }]; + const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal01", now: NOW, stallMinutes: 10, jobs })).rows[0]!; + assert.equal(r.stalled, true); + assert.match(r.reason, /NOT growing/); + const later = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal01", now: NOW, stallMinutes: 30, jobs })).rows[0]!; + assert.equal(later.stalled, false); +}); + +test("interrupted: the record says recording and no record-live job runs it — it needs a person until acknowledged", async () => { + await recording("exmplintr01", ".exmplintr01.live-2026-11-20T11-00-00-000Z.ytdlp", { jobId: "job-gone" }); + const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplintr01", now: NOW, jobs: () => [] })).rows[0]!; + assert.equal(r.status, "interrupted"); + assert.equal(r.needsAttention, true); + assert.equal(r.stalled, false, "stalled is for a recording that runs"); + assert.ok((await countLiveRecordingsNeedingAttention(paths)) >= 1); + const ack = await acknowledgeLiveRecording(paths, { slug: SLUG, id: "exmplintr01", by: "test" }); + assert.deepEqual(ack, { ok: true, acknowledged: 1 }); + const after = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplintr01", now: NOW, jobs: () => [] })).rows[0]!; + assert.equal(after.needsAttention, false); + assert.equal((await acknowledgeLiveRecording(paths, { slug: SLUG, id: "exmplintr01" })).ok, false, "nothing left to acknowledge"); +}); + +test("the default listing: recording, needing a person, or of the last week; --all is everything", async () => { + const old = { status: "landed" as const, url: "u", platform: "youtube", fromStart: true, startedAt: "2026-10-01T00:00:00.000Z", endedAt: "2026-10-01T03:00:00.000Z", parts: [] }; + await upsertLiveRecordingRow(paths, SLUG, { ...old, id: "exmplold001", attempts: 1, mustKeep: false }); + await upsertLiveRecordingRow(paths, SLUG, { ...old, status: "failed", id: "exmplold002", attempts: 6, mustKeep: true, error: "nothing was recorded" }); + const ids = (await listLiveRecordings(paths, { slug: SLUG, now: NOW, jobs: () => [] })).rows.map((r) => r.id); + assert.ok(!ids.includes("exmplold001"), "an old landed recording is not in the default view"); + assert.ok(ids.includes("exmplold002"), "an old failure that nobody acknowledged is"); + const all = (await listLiveRecordings(paths, { slug: SLUG, now: NOW, all: true, jobs: () => [] })).rows.map((r) => r.id); + assert.ok(all.includes("exmplold001")); + assert.equal((await loadLiveRecordingRows(paths, SLUG)).length, all.length); +}); diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -0,0 +1,226 @@ +// IS THIS STREAM BEING RECORDED, AND IS IT GROWING? — `pnpm ops get +// live-recordings`, GET /api/ops/live-recordings, /review's "Live recordings +// that need you" and the banners on /jobs, the channel and the video page. +// +// One answer for people and agents, read from the recordings' own records — +// never from "is there a job for this video id" (20 Nov 2026: a live-chat job +// for the same id was read as the recording for seven hours while the +// recording had failed). Per run (channels/<slug>/live-recordings.json, +// lib/liveRecordings-server.ts), cross-checked: +// +// status the record's own (data/<id>/live-recording.json, when it +// is this run's), else the row's; `interrupted` when it +// says recording and no record-live job runs it +// bytes while recording: the staging files of its parts, summed +// (stat only); after: what each part held at its end +// lastGrowthAt the newest of those files' mtimes +// stalled recording, and nothing has grown for stallMinutes +// (settings.liveRecording.stallMinutes, default 10) +// needsAttention failed, interrupted, or recorded from the live edge (the +// stream's start lost) — until a person acknowledges it or +// a later recording of the id lands from its start +// +// Reads only: no request leaves the machine, nothing is written. + +import path from "node:path"; +import { readdir, stat } from "node:fs/promises"; +import type { Paths } from "../lib/paths"; +import { getSettings } from "../lib/settings"; +import { livePartFiles, spanWords, type LiveRecordingStatus } from "../lib/liveCapture"; +import { liveRecordingSidecar } from "../lib/mediaImport-server"; +import { + acknowledgeLiveRecordingRows, + loadLiveRecordingRows, + rowNeedsAttention, + type LiveRecordingRow, +} from "../lib/liveRecordings-server"; +import { savedVideoRoot } from "../lib/savedVideo"; +import { getRegistry, type JobRecord } from "../jobs/registry"; +import { readChannelConfig } from "./channels"; + +export const LIVE_STALL_MINUTES_DEFAULT = 10; +// The default listing: what is recording, what needs a person, and the rest +// of the last week. +export const LIVE_RECORDINGS_RECENT_DAYS = 7; + +export type LiveRecordingViewStatus = LiveRecordingStatus | "interrupted"; + +export type LiveRecordingView = Omit<LiveRecordingRow, "status"> & { + slug: string; + status: LiveRecordingViewStatus; + job: { id: string; kind: string; status: string } | null; + bytes: number | null; + lastGrowthAt: string | null; + stalled: boolean; + streamElapsedSeconds: number | null; + capturedSeconds: number | null; + needsAttention: boolean; + // One sentence: what happened, for a banner or a line of output. + reason: string; + // The command that answers for this recording again. + check: string; +}; + +export type LiveRecordingsListing = { + rows: LiveRecordingView[]; + needsAttention: number; + stallMinutes: number; +}; + +export type ListLiveRecordingsOpts = { + slug?: string; + id?: string; + // Every row, not only what is recording, needs a person or is recent. + all?: boolean; + stallMinutes?: number; + now?: Date; + jobs?: () => readonly Pick<JobRecord, "id" | "kind" | "status" | "channelSlug" | "videoId">[]; +}; + +export function liveRecordingCheckCommand(slug: string, id: string): string { + return `pnpm ops get live-recordings ${slug}/${id}`; +} + +function stallMinutesSetting(): number { + try { + const v = getSettings().liveRecording?.stallMinutes; + return typeof v === "number" && v > 0 ? v : LIVE_STALL_MINUTES_DEFAULT; + } catch { + return LIVE_STALL_MINUTES_DEFAULT; + } +} + +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(); +} + +const ACTIVE = new Set(["running", "queued"]); + +function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: number): string { + const lostWords = + v.lost && v.lost.toSeconds !== null ? `the first ${spanWords(v.lost.toSeconds)} of the stream are NOT recorded` : "the stream's start is NOT recorded"; + switch (v.status) { + case "failed": + return `failed: ${v.error ?? "no reason recorded"}`; + case "interrupted": + return "interrupted: its record says recording, and no record-live job runs it (an editor restart?) — Record again"; + case "cancelled": + return "cancelled"; + case "landed": + return v.fallback === "live-edge" ? `landed from the live edge: ${lostWords}` : "landed"; + case "recording": { + const parts = [v.fallback === "live-edge" ? `recording from the live edge: ${lostWords}` : "recording"]; + if (v.bytes !== null) parts.push(`${Math.round(v.bytes / 1024 / 1024)} MB so far`); + if (v.stalled) parts.push(`NOT growing for ${stallMinutes}+ min`); + return parts.join("; "); + } + } +} + +// 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 jobs = (opts.jobs ?? (() => getRegistry().list()))(); + const byId = new Map(jobs.map((j) => [j.id, j])); + const slugs = opts.slug ? [opts.slug] : await channelSlugs(paths); + const out: LiveRecordingView[] = []; + for (const slug of slugs) { + const rows = (await loadLiveRecordingRows(paths, slug)).filter((r) => !opts.id || r.id === opts.id); + if (!rows.length) continue; + const config = await readChannelConfig(paths, slug).catch(() => null); + const slugStore = path.join(savedVideoRoot(paths, config), slug); + let names: string[] | null = null; + // The newest row of an id is the run its record (data/<id>/) belongs to. + for (const row of rows) { + const rec = await liveRecordingSidecar.load(path.join(paths.channelsDir, slug, "data", row.id)).catch(() => null); + const own = rec && rec.startedAt === row.startedAt ? rec : null; + const parts = own?.parts ?? row.parts; + let status: LiveRecordingViewStatus = own?.status ?? row.status; + const named = row.jobId ? byId.get(row.jobId) : undefined; + const running = + (named && ACTIVE.has(named.status)) || + jobs.some((j) => j.kind === "record-live" && j.channelSlug === slug && j.videoId === row.id && ACTIVE.has(j.status)); + if (status === "recording" && !running) status = "interrupted"; + let bytes: number | null = null; + let lastGrowthMs: number | null = null; + if (status === "recording" || status === "interrupted") { + names ??= await readdir(slugStore).catch(() => [] as string[]); + const stems = new Set(parts.map((p) => p.stem).filter(Boolean)); + bytes = 0; + for (const g of livePartFiles(row.id, names)) { + if (!stems.has(g.stem)) continue; + for (const f of [...g.finished, ...g.streams]) { + const st = await stat(path.join(slugStore, f)).catch(() => null); + if (!st) continue; + bytes += st.size; + lastGrowthMs = Math.max(lastGrowthMs ?? 0, st.mtimeMs); + } + } + } else if (parts.some((p) => typeof p.bytes === "number")) { + bytes = parts.reduce((n, p) => n + (p.bytes ?? 0), 0); + } + const current = parts.at(-1); + const sinceMs = lastGrowthMs ?? (current ? Date.parse(current.startedAt) : Date.parse(row.startedAt)); + const stalled = status === "recording" && Number.isFinite(sinceMs) && now - sinceMs > stallMinutes * 60_000; + const landed = own?.landedPart ?? row.landedPart; + const capturedSeconds = status === "landed" && landed !== undefined ? (parts[landed]?.seconds ?? null) : null; + const streamElapsedSeconds = + status === "recording" && row.streamStartedAt ? Math.max(0, Math.round((now - Date.parse(row.streamStartedAt)) / 1000)) : null; + const view: Omit<LiveRecordingView, "reason" | "check"> = { + ...row, + ...(own?.error ? { error: own.error } : {}), + ...(own?.fallback ? { fallback: own.fallback } : {}), + ...(own?.lost ? { lost: own.lost } : {}), + ...(own?.endedAt ? { endedAt: own.endedAt } : {}), + attempts: own?.attempts ?? row.attempts, + parts, + slug, + status, + job: named ? { id: named.id, kind: named.kind, status: named.status } : null, + bytes, + lastGrowthAt: lastGrowthMs !== null ? new Date(lastGrowthMs).toISOString() : null, + stalled, + streamElapsedSeconds, + capturedSeconds, + needsAttention: rowNeedsAttention({ ...row, status: status === "interrupted" ? "failed" : status, fallback: own?.fallback ?? row.fallback }), + }; + const shown = + opts.all || + opts.id || + view.needsAttention || + status === "recording" || + now - Date.parse(view.endedAt ?? view.startedAt) <= LIVE_RECORDINGS_RECENT_DAYS * 86_400_000; + if (!shown) continue; + out.push({ ...view, reason: reasonOf(view, stallMinutes), check: liveRecordingCheckCommand(slug, row.id) }); + } + } + out.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt)); + return { rows: out, needsAttention: out.filter((r) => r.needsAttention).length, stallMinutes }; +} + +// How many recordings need a person, across every channel. +export async function countLiveRecordingsNeedingAttention(paths: Paths): Promise<number> { + return (await listLiveRecordings(paths)).needsAttention; +} + +// A person has seen it (`pnpm ops live-recording-ack`, /review's +// Acknowledge): every run of `id` that needs a person, or the one run +// `startedAt` names. The rows stay listed. +export async function acknowledgeLiveRecording( + paths: Paths, + opts: { slug: string; id: string; startedAt?: string; by?: string; now?: Date }, +): Promise<{ ok: true; acknowledged: number } | { ok: false; error: string }> { + const listing = await listLiveRecordings(paths, { slug: opts.slug, id: opts.id, all: true }); + if (!listing.rows.length) return { ok: false, error: `${opts.slug}/${opts.id} has no live recording` }; + const interrupted = new Set(listing.rows.filter((r) => r.status === "interrupted").map((r) => r.startedAt)); + const n = await acknowledgeLiveRecordingRows(paths, opts.slug, opts.id, { + ...(opts.by ? { by: opts.by } : {}), + ...(opts.startedAt ? { startedAt: opts.startedAt } : {}), + ...(opts.now ? { now: opts.now } : {}), + interrupted: (r) => interrupted.has(r.startedAt), + }); + if (n === 0) return { ok: false, error: `Nothing of ${opts.slug}/${opts.id} needs acknowledging` }; + return { ok: true, acknowledged: n }; +} diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -604,3 +604,199 @@ test("an earlier run's unmerged streams are merged and landed by the next run", assert.equal((await streamsOf(s.landed!.container!)).a, "aac"); assert.deepEqual((await readdir(slugStore)).filter((n) => n.startsWith(".ytleft00001")), []); }); + +// --- THE INCIDENT (20 Nov 2026): a from-start attempt that records nothing ---------- +// +// A YouTube stream asked for `fromStart`, `doNotClean` and a note; yt-dlp +// `--live-from-start` exited 1 after seconds with "The downloaded file is +// empty" and wrote nothing; the job failed with no retry, no fallback and no +// alert. The recorder here is a stub that does exactly that, every time (or +// for the first N attempts); the waits between attempts are recorded, never +// slept. The listing (controller/liveRecordings.ts) is what a person and an +// agent read afterwards. + +const EMPTY = "[youtube] Sleeping 1.0 seconds ...\nERROR: The downloaded file is empty\n"; +const ytChannel = async () => { + await mkdir(path.join(CORPUS, "channels", YT_SLUG, "data"), { recursive: true }); + await writeFile(path.join(CORPUS, "channels", YT_SLUG, "config.json"), JSON.stringify(YT_CONFIG)); +}; +// The stream started two hours ago. +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 }>; +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"); + await writeFile(out, "format=mov,mp4;seconds=600;"); + return { exitCode: 0, stderrTail: "", signalled: false }; +}; + +async function incidentRun(id: string, attempt: Attempt, opts: { signal?: AbortSignal; onWait?: (ms: number) => void; request?: Record<string, unknown> } = {}) { + await ytChannel(); + const calls: string[][] = []; + const waits: number[] = []; + const log: string[] = []; + const run = recordLiveRun({ + paths, + request: { slug: YT_SLUG, url: ytUrl(id), fromStart: true, transcribe: true, doNotClean: true, note: "must not lose", ...(opts.request ?? {}) }, + plan: { url: ytUrl(id), platform: "youtube", id }, + channelConfig: YT_CONFIG, + cookiePolicy: NO_COOKIES, + onLog: (l) => void log.push(l), + signal: opts.signal ?? new AbortController().signal, + jobId: `job-${id}`, + deps: { + refresh: refreshWith(ytLiveMeta(id)), + fetchText: async () => { + throw new Error("no playlist read is expected"); + }, + spawn: async ({ args }) => { + calls.push(args); + return attempt(args, calls.length); + }, + wait: async (ms) => { + waits.push(ms); + opts.onWait?.(ms); + }, + jitter: (ms) => ms, + land, + freeBytes: async () => 1e15, + handoff, + }, + } as Parameters<typeof recordLiveRun>[0]); + return { run, calls, waits, log }; +} + +const fromStartArg = (args: string[]) => args.includes("--live-from-start"); +const startIndex0 = (args: string[]) => /-live_start_index 0/.test(args[args.indexOf("--downloader-args") + 1] ?? ""); + +test("THE INCIDENT: 'downloaded file is empty' every time → 3 from-start tries, 3 live-edge tries, then a durable loud failure in the listing", async () => { + const id = "exmplincid1"; + const { run, calls, waits, log } = await incidentRun(id, writesAfter(Infinity)); + await assert.rejects(run, /The downloaded file is empty/); + assert.equal(calls.length, 6, `six recorder attempts, not ${calls.length}`); + assert.deepEqual(calls.map(fromStartArg), [true, true, true, false, false, false]); + assert.deepEqual(calls.map(startIndex0), [true, true, true, false, false, false], "the live edge asks ffmpeg for no index 0"); + assert.deepEqual(waits, [60_000, 180_000, 0, 60_000, 180_000], "paced: 0/+60/+180 s, then the same from the live edge"); + assert.ok(log.some((l) => /from its start failed 3 times/.test(l)), "the log says the from-start attempts failed"); + // The run made data/<id>/ and recorded nothing into it: the dir goes (an + // enumerator would read it as fetched) — the failure record does NOT. + await assert.rejects(stat(path.join(CORPUS, "channels", YT_SLUG, "data", id))); + const { listLiveRecordings, acknowledgeLiveRecording } = await import("./liveRecordings"); + const rows = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows; + assert.equal(rows.length, 1); + const row = rows[0]!; + assert.equal(row.status, "failed"); + assert.equal(row.needsAttention, true); + assert.equal(row.mustKeep, true); + assert.equal(row.attempts, 6); + assert.equal(row.jobId, `job-${id}`); + assert.match(row.error ?? "", /The downloaded file is empty/); + assert.match(row.error ?? "", /6 attempts/); + assert.equal(row.parts.length, 6); + assert.match(row.parts[0]!.error ?? "", /The downloaded file is empty/); + // Acknowledged: it stays listed, and no longer needs anyone. + const ack = await acknowledgeLiveRecording(paths, { slug: YT_SLUG, id, by: "test" }); + assert.equal(ack.ok, true); + const after = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!; + assert.equal(after.needsAttention, false); + assert.ok(after.acknowledgedAt); +}); + +test("from its start fails twice, the third try records: landed, 3 attempts, nothing to attend to", async () => { + const id = "exmplretry1"; + const { run, calls, waits } = await incidentRun(id, writesAfter(2)); + const s = await run; + assert.equal(s.status, "landed"); + assert.equal(calls.length, 3); + assert.ok(calls.every(fromStartArg)); + assert.deepEqual(waits, [60_000, 180_000]); + const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id)); + assert.equal(rec?.attempts, 3); + assert.equal(rec?.fallback, undefined); + const { listLiveRecordings } = await import("./liveRecordings"); + const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!; + assert.equal(row.status, "landed"); + assert.equal(row.needsAttention, false); +}); + +test("from its start fails 3 times, the live edge records: landed, the start said LOST, and it needs a person", async () => { + const id = "exmpledge01"; + const { run, calls, log } = await incidentRun(id, writesAfter(3)); + const s = await run; + assert.equal(s.status, "landed"); + assert.equal(calls.length, 4); + assert.equal(fromStartArg(calls[3]!), false); + const rec = await liveRecordingSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id)); + assert.equal(rec?.fallback, "live-edge"); + assert.ok(rec?.lost && rec.lost.toSeconds !== null && Math.abs(rec.lost.toSeconds - 7200) < 120, JSON.stringify(rec?.lost)); + assert.ok(log.some((l) => /are NOT recorded/.test(l)), "the log says what was lost"); + const { listLiveRecordings } = await import("./liveRecordings"); + const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id })).rows[0]!; + assert.equal(row.fallback, "live-edge"); + assert.equal(row.needsAttention, true, "a lost start is a failure needing attention"); +}); + +test("a stream that has ended is not retried; a cancel during a wait stops at once and alerts nobody", async () => { + const ended = await incidentRun("exmplended1", writesAfter(Infinity, "ERROR: [youtube] exmplended1: This live event has ended.\n")); + await assert.rejects(ended.run, /ended/); + assert.equal(ended.calls.length, 1); + assert.deepEqual(ended.waits, []); + + const ac = new AbortController(); + const cancelled = await incidentRun("exmplcancl1", writesAfter(Infinity), { signal: ac.signal, onWait: () => ac.abort() }); + const s = await cancelled.run; + assert.equal(s.status, "cancelled"); + assert.equal(cancelled.calls.length, 1, "no attempt after the cancel"); + const { listLiveRecordings } = await import("./liveRecordings"); + const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id: "exmplcancl1" })).rows[0]!; + assert.equal(row.status, "cancelled"); + assert.equal(row.needsAttention, false); +}); + +test("a healthy recording is untouched: one spawn, no wait, today's argv byte for byte", async () => { + const { ytdlpLiveArgs } = await import("../lib/liveCapture"); + const { channelExtraArgs } = await import("../ytdlp/channelArgs"); + const id = "exmplhealth"; + const { run, calls, waits } = await incidentRun(id, writesAfter(0)); + const s = await run; + assert.equal(s.status, "landed"); + assert.equal(calls.length, 1); + assert.deepEqual(waits, []); + const out = calls[0]![calls[0]!.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, ""); + assert.deepEqual( + calls[0], + ytdlpLiveArgs({ + url: ytUrl(id), + output: out, + fromStart: true, + maxHeight: 720, + separate: true, + waitForVideo: false, + channelArgs: [...channelExtraArgs(YT_CONFIG, undefined), "--downloader-args", "ffmpeg_i:-live_start_index 0 -m3u8_hold_counters 180 -seg_max_retry 10"], + }), + ); +}); + +test("a later recording of the same stream that lands supersedes the earlier failure", async () => { + const id = "exmplsuper1"; + const first = await incidentRun(id, writesAfter(Infinity)); + await assert.rejects(first.run); + const second = await incidentRun(id, writesAfter(0)); + assert.equal((await second.run).status, "landed"); + const { listLiveRecordings } = await import("./liveRecordings"); + const rows = (await listLiveRecordings(paths, { slug: YT_SLUG, id, all: true })).rows; + assert.equal(rows.length, 2); + const failed = rows.find((r) => r.status === "failed")!; + assert.ok(failed.supersededBy, "the failure names the run that landed"); + assert.equal(failed.needsAttention, false); +}); + +test("the recorder's progress thinning also catches yt-dlp's numbered stream lines", async () => { + const { isProgressLine } = await import("./recordLive"); + assert.equal(isProgressLine("1: [download] 12.3% of ~ 1.20GiB at 2.00MiB/s ETA 10:00 (frag 4453/30299)"), true); + assert.equal(isProgressLine("2: [download] Destination: x.f140.m4a"), true); + assert.equal(isProgressLine("[download] 50.0% of 10MiB"), true); + assert.equal(isProgressLine("ERROR: The downloaded file is empty"), false); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -56,10 +56,12 @@ import { alwaysCookies, type ResolvedCookiePolicy } from "../lib/cookiePolicy"; import { BROWSER_FALLBACK_PLATFORMS, LIVE_DEFAULT_MAX_HEIGHT, + classifyAttempt, extractionRefused, ffmpegLiveArgs, formatUnavailable, - liveFromStartUnsupported, + lastErrorLine, + liveAttemptSchedule, livePartFiles, mergeStreamsArgs, newSegments, @@ -67,6 +69,7 @@ import { pickVariant, playlistReach, separateStreamsDefault, + spanWords, ytdlpLiveArgs, type LivePart, type LivePartFiles, @@ -77,6 +80,7 @@ import { type PlaylistReach, } from "../lib/liveCapture"; import { liveRecordingSidecar } from "../lib/mediaImport-server"; +import { rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server"; import { setDoNotClean } from "../lib/doNotClean-server"; import type { Paths } from "../lib/paths"; import { detectPlatform } from "../lib/platform"; @@ -284,10 +288,17 @@ export type RecorderSpawn = (opts: { label: string; }) => Promise<RecorderOutcome>; -// A progress line yt-dlp or ffmpeg repeats every second for hours. -const PROGRESS_RE = /^(?:frame=|size=|\[download\]\s+(?:\d|Destination:)?)|time=\d\d:\d\d:\d\d/; +// A progress line yt-dlp or ffmpeg repeats every second for hours. yt-dlp +// numbers each of a separate-streams recording's lines (`1: [download] …`, +// `2: [download] …`): those are progress too (20 Nov 2026: unthinned, they +// wrote ~1 MB of job log a minute while a from-start download caught up). +const PROGRESS_RE = /^(?:\d+:\s*)?(?:frame=|size=|\[download\]\s+(?:\d|Destination:)?)|time=\d\d:\d\d:\d\d/; const PROGRESS_EVERY_MS = 5 * 60_000; +export function isProgressLine(line: string): boolean { + return PROGRESS_RE.test(line); +} + // ONE RECORDER: spawned as a plain child (so a SIGINT reaches yt-dlp, which // asks its ffmpeg to quit with `q` and the file is finalized), its output in // the job's log with the per-second progress thinned to one line every five @@ -306,7 +317,7 @@ export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, la for (const line of text.split(/[\r\n]+/)) { const l = line.trim(); if (!l) continue; - if (PROGRESS_RE.test(l)) { + if (isProgressLine(l)) { const now = Date.now(); if (now - lastProgress < PROGRESS_EVERY_MS) continue; lastProgress = now; @@ -534,6 +545,10 @@ export type RecordLiveDeps = { merge?: (args: string[], signal: AbortSignal) => Promise<void>; freeBytes?: (dir: string) => Promise<number>; now?: () => Date; + // The wait between two recorder attempts (default: a sleep a Cancel ends), + // and the stretch applied to it (default jitterMs, pacing.jitter). + wait?: (ms: number, signal: AbortSignal) => Promise<void>; + jitter?: (ms: number) => number; }; export type RecordLiveJobOpts = { @@ -547,6 +562,8 @@ export type RecordLiveJobOpts = { // first part begins. startPreclip?: (slug: string, id: string, options: PreclipOptions) => Promise<{ ok: boolean; jobId?: string; error?: string }>; afterRun?: () => void | Promise<void>; + // The job running it: written into the record and the channel's row. + jobId?: string; deps?: RecordLiveDeps; }; @@ -682,13 +699,80 @@ export async function resolvePart( return { error: `video with no audio (${streams.map((s) => path.basename(s.file)).join(", ")}): nothing to transcribe` }; } +// What the run tells its wrapper (recordLiveRun) as it goes, so a failure the +// run did not record itself — a refusal before the recording, a throw in the +// middle of it — still ends in the record and the channel's row. +type RunHooks = { + startedAt: string; + id?: string; + url?: string; + platform?: string; + record?: LiveRecordingRecord; + save?: () => Promise<void>; +}; + +const isMustKeep = (req: RecordLiveRequest) => req.doNotClean === true || Boolean(req.note); + +// THE RUN, AND ITS FAILURE RECORDED. Every way a recording can end without a +// landing leaves a row in channels/<slug>/live-recordings.json that says why +// (lib/liveRecordings-server.ts): the run's own saves write it; a throw the +// run did not record (a refusal before any recorder started, a failure in the +// middle) is written here, and the record, when there is one, says `failed`. export async function recordLiveRun( opts: RecordLiveJobOpts & { onLog: (s: string) => void; signal: AbortSignal }, ): Promise<RecordLiveSummary> { + const now = opts.deps?.now ?? (() => new Date()); + const hooks: RunHooks = { startedAt: now().toISOString() }; + try { + return await recordLiveRunInner(opts, hooks); + } catch (err) { + const message = (err as Error).message; + try { + if (hooks.record && hooks.save) { + if (hooks.record.status === "recording") { + hooks.record.status = opts.signal.aborted ? "cancelled" : "failed"; + hooks.record.endedAt = now().toISOString(); + hooks.record.error = message; + await hooks.save(); + } + } else if (hooks.id && !opts.request.dryRun) { + await upsertLiveRecordingRow(opts.paths, opts.request.slug, { + ...rowOfRecord( + hooks.id, + { + status: opts.signal.aborted ? "cancelled" : "failed", + url: hooks.url ?? opts.plan.url, + platform: hooks.platform ?? opts.plan.platform, + fromStart: opts.request.fromStart !== false, + startedAt: hooks.startedAt, + endedAt: now().toISOString(), + parts: [], + error: `nothing was recorded: ${message}`, + attempts: 0, + mustKeep: isMustKeep(opts.request), + ...(opts.jobId ? { jobId: opts.jobId } : {}), + }, + opts.request.note ? { note: opts.request.note } : {}, + ), + }); + } + } catch (e) { + opts.onLog(`The failure could not be recorded in the channel's live recordings (${(e as Error).message}).\n`); + } + throw err; + } +} + +async function recordLiveRunInner( + opts: RecordLiveJobOpts & { onLog: (s: string) => void; signal: AbortSignal }, + hooks: RunHooks, +): Promise<RecordLiveSummary> { const { paths, request: req, onLog, signal } = opts; const say = (s: string) => onLog(s.endsWith("\n") ? s : `${s}\n`); const deps = opts.deps ?? {}; const now = deps.now ?? (() => new Date()); + const waitFor = deps.wait ?? sleep; + const stretch = deps.jitter ?? ((ms: number) => jitterMs(ms)); const runRecorder = deps.spawn ?? spawnRecorder; const getText = deps.fetchText ?? fetchText; const fromStart = req.fromStart !== false; @@ -705,6 +789,9 @@ export async function recordLiveRun( plan = { ...plan, url: vod.url, id: vod.id }; } const id = plan.id!; + hooks.id = id; + hooks.url = plan.url; + hooks.platform = plan.platform; const separate = req.separate ?? separateStreamsDefault(plan.platform); const cfg = configForVideoUrl(opts.channelConfig, plan.url); const channelDir = path.join(paths.channelsDir, req.slug); @@ -807,16 +894,36 @@ export async function recordLiveRun( const leftovers = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])); if (leftovers.length) say(`An earlier recording left ${leftovers.length} part(s); the longest of all is landed.`); + // When the stream started, as its record says (what a live-edge fallback + // has lost is measured from it). + const streamStartSec = + typeof meta?.release_timestamp === "number" ? (meta.release_timestamp as number) : typeof meta?.timestamp === "number" ? (meta.timestamp as number) : null; const record: LiveRecordingRecord = { status: "recording", url: plan.url, platform: plan.platform, fromStart, separate, - startedAt: now().toISOString(), + startedAt: hooks.startedAt, parts: [], + attempts: 0, + mustKeep: isMustKeep(req), + ...(opts.jobId ? { jobId: opts.jobId } : {}), + ...(streamStartSec !== null ? { streamStartedAt: new Date(streamStartSec * 1000).toISOString() } : {}), + }; + // The record beside the video, and the channel's row (which outlives it). + let rowWarned = false; + const save = async () => { + await liveRecordingSidecar.write(videoDir, record); + try { + await upsertLiveRecordingRow(paths, req.slug, rowOfRecord(id, record, req.note ? { note: req.note } : {})); + } catch (err) { + if (!rowWarned) say(`The channel's live recordings could not be written (${(err as Error).message}).`); + rowWarned = true; + } }; - const save = () => liveRecordingSidecar.write(videoDir, record); + hooks.record = record; + hooks.save = save; // How far back the playlist reaches (best effort, one read). // (Not for separate streams from the start: YouTube's DASH from the start is @@ -848,7 +955,8 @@ export async function recordLiveRun( let preclipAsked = false; const begin = (method: LivePartMethod, url: string, file: string, fs: boolean) => { const stem = path.basename(file).replace(/\.ts$/, ""); - const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString(), stem }; + record.attempts = (record.attempts ?? 0) + 1; + const part: LivePart = { method, url, fromStart: fs, startedAt: now().toISOString(), stem, attempt: record.attempts }; record.parts.push(part); parts.push({ part, stem }); if (req.preclip && !preclipAsked && opts.startPreclip) { @@ -869,6 +977,8 @@ export async function recordLiveRun( }; // 2. The recording. + // What the attempts came to when none recorded anything (the failure's words). + let attemptsSummary: string | null = null; // "from-start": yt-dlp `--live-from-start` (and ffmpeg told index 0 too, // the same thing for a DVR playlist); "index0": `--no-live-from-start` with // ffmpeg told index 0 — for an extractor that does not mark a format from @@ -948,27 +1058,74 @@ export async function recordLiveRun( } else { let pathB = false; if (extractionError === null) { - let o = await ytdlpPart(plan.url, "ytdlp", fromStart ? "from-start" : "now"); - if (!signal.aborted && fromStart && liveFromStartUnsupported(o.stderrTail)) { - say("yt-dlp cannot start this stream at its start; recording with ffmpeg told to start at the playlist's first segment."); - o = await ytdlpPart(plan.url, "ytdlp-index0", "index0", "--no-live-from-start + -live_start_index 0; "); - } - if (!signal.aborted && o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) { - say( - 'yt-dlp found no single stream with video and audio: this stream offers them separately — record it with "separate": true.', - ); + // THE ATTEMPTS (lib/liveCapture.ts liveAttemptSchedule): from its start + // at 0, +60 and +180 s, then from the live edge at 0, +60 and +180 s — + // each wait stretched by pacing.jitter, ended by a Cancel. Only an + // attempt that recorded NOTHING for a reason another try may not meet + // again is retried; a stream that has ended, an argv no try can fix, a + // Cancel and a part with bytes all end the attempts. + const schedule = liveAttemptSchedule(fromStart); + let index0 = false; + let fromStartFailures = 0; + let edgeFailures = 0; + let lastReason: string | null = null; + for (let slot = 0; slot < schedule.length && !signal.aborted; ) { + const step = schedule[slot]!; + const n = (record.attempts ?? 0) + 1; + const mode = step.mode === "live-edge" ? "now" : index0 ? "index0" : "from-start"; + const tag = `ytdlp${mode === "index0" ? "-index0" : ""}${mode === "now" && fromStart ? "-edge" : ""}${n > 1 && !(mode === "index0" && n === 2) ? `-a${n}` : ""}`; + const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : ""); + const last = parts[parts.length - 1]!; + const cls = classifyAttempt({ ...o, bytes: await bytesOf(last.stem) }); + if (cls === "recorded" || cls === "stopped" || signal.aborted) break; + const reason = lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`; + last.part.error = reason; + await save(); + lastReason = reason; + if (o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) { + say( + 'yt-dlp found no single stream with video and audio: this stream offers them separately — record it with "separate": true.', + ); + } + if (o.exitCode !== 0 && BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(o.stderrTail)) { + say("yt-dlp was refused; recording from the page's own playlist."); + pathB = true; + break; + } + if (cls === "unsupported" && !index0) { + say("yt-dlp cannot start this stream at its start; recording with ffmpeg told to start at the playlist's first segment."); + index0 = true; + continue; + } + if (cls === "argv" || cls === "gone") { + say(`Attempt ${n} recorded nothing (${reason}); ${cls === "gone" ? "the stream is over or gone" : "the same command would fail the same way"}: not retried.`); + break; + } + if (step.mode === "from-start") fromStartFailures++; + else edgeFailures++; + slot++; + const next = schedule[slot]; + if (!next) break; + if (next.mode === "live-edge" && step.mode === "from-start") { + const lostTo = streamStartSec !== null ? Math.max(0, Math.round(now().getTime() / 1000 - streamStartSec)) : null; + record.fallback = "live-edge"; + record.lost = { fromSeconds: 0, toSeconds: lostTo }; + await save(); + say( + `${plan.url} from its start failed ${fromStartFailures} times (${reason}); recording from the live edge` + + (lostTo !== null + ? ` since ${spanWords(lostTo)} into the stream — the first ${spanWords(lostTo)} are NOT recorded.` + : ` — the stream before now (its start is not known) is NOT recorded.`), + ); + } else { + say(`Attempt ${n} recorded nothing (${reason}); attempt ${n + 1} ${next.mode === "live-edge" ? "from the live edge" : "from its start"} in ${spanWords(next.waitMs / 1000)}.`); + } + await waitFor(stretch(next.waitMs), signal); } - const last = parts[parts.length - 1]; - if ( - !signal.aborted && - o.exitCode !== 0 && - last && - (await bytesOf(last.stem)) === 0 && - BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && - extractionRefused(o.stderrTail) - ) { - say("yt-dlp was refused; recording from the page's own playlist."); - pathB = true; + if (lastReason !== null) { + const tries = record.attempts ?? 0; + const split = fromStartFailures && edgeFailures ? ` (${fromStartFailures} from its start, ${edgeFailures} from the live edge)` : ""; + attemptsSummary = `${tries} attempt${tries === 1 ? "" : "s"}${split}: ${lastReason}`; } } else pathB = true; if (pathB && !signal.aborted) { @@ -1035,7 +1192,11 @@ export async function recordLiveRun( for (const u of unlandable) say(`Not landable: ${u}`); summary.parts = record.parts.map((p) => ({ method: p.method, seconds: p.seconds ?? null, fromStart: p.fromStart })); if (candidates.length === 0) { - const error = unlandable.length ? `nothing landable was recorded (${unlandable.join("; ")})` : "nothing was recorded"; + const error = unlandable.length + ? `nothing landable was recorded (${unlandable.join("; ")})` + : attemptsSummary + ? `nothing was recorded — ${attemptsSummary}` + : "nothing was recorded"; record.status = cancelled ? "cancelled" : "failed"; record.endedAt = now().toISOString(); record.error = error; diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -435,8 +435,18 @@ export type LivePart = { // Its separate streams were left unmerged (a cancel, a crash) and merged // by record-live. merged?: boolean; + // Which attempt of the run this part was (1-based; liveAttemptSchedule). + attempt?: number; + // What the recorder said when the part recorded nothing: its last `ERROR:` + // line (lastErrorLine), so the reason is in the record, not only the log. + error?: string; }; +// The span of the stream a recording does NOT hold, in stream seconds: a +// fallback to the live edge starts `toSeconds` into the stream (null: the +// stream's start is not known). +export type LostSpan = { fromSeconds: number; toSeconds: number | null }; + export type LiveRecordingStatus = "recording" | "landed" | "failed" | "cancelled"; export type LiveRecordingRecord = { @@ -456,6 +466,18 @@ export type LiveRecordingRecord = { // The playlist's reach when the recording started, when it was read. reach?: PlaylistReach; error?: string; + // How many recorder attempts the run made (liveAttemptSchedule). + attempts?: number; + // From its start kept failing and the run recorded from the live edge: + // what it does not hold is `lost`. + fallback?: "live-edge"; + lost?: LostSpan; + // A "must not lose" recording: asked with doNotClean or a note. + mustKeep?: boolean; + // The job that ran it. + jobId?: string; + // When the stream started (its record's release_timestamp/timestamp), ISO. + streamStartedAt?: string; }; const LIVE_STATUSES: ReadonlySet<string> = new Set(["recording", "landed", "failed", "cancelled"]); @@ -487,3 +509,75 @@ export function coerceLiveRecording(raw: unknown): LiveRecordingRecord | null { // The platforms a recording knows how to follow. Anything else is tried with // yt-dlp's own `--live-from-start` (YouTube, Twitch) and no fallback. export const BROWSER_FALLBACK_PLATFORMS: ReadonlySet<string> = new Set(["rumble"]); + +// --- attempts: what one recorder run came to, and what is tried next ------------ +// +// A from-start attempt that records nothing is not the end of a recording +// (20 Nov 2026: YouTube answered `--live-from-start`'s HEADs without a +// sequence number for ~45 s, yt-dlp said "The downloaded file is empty", and +// the same argv seven hours later worked). The run tries again, paced, and +// then from the live edge, so that something is captured; each wait is +// stretched by pacing.jitter and no attempt is a new kind of request: the +// live edge is the `--no-live-from-start` Kick's channel recorder already +// makes. + +// The waits before the 1st, 2nd and 3rd attempt of one mode. +export const LIVE_RETRY_WAITS_MS: readonly number[] = [0, 60_000, 180_000]; + +export type LiveAttemptMode = "from-start" | "live-edge"; + +// Every attempt a run may make, in order: from its start three times (0, +60, +// +180 s), then from the live edge three times (0, +60, +180 s). A run asked +// not to start at the start makes only the live-edge three. +export function liveAttemptSchedule(fromStart: boolean): { mode: LiveAttemptMode; waitMs: number }[] { + const edge = LIVE_RETRY_WAITS_MS.map((waitMs) => ({ mode: "live-edge" as const, waitMs })); + if (!fromStart) return edge; + return [...LIVE_RETRY_WAITS_MS.map((waitMs) => ({ mode: "from-start" as const, waitMs })), ...edge]; +} + +// What yt-dlp says when the stream is over or gone: no attempt can help. +export function liveStreamGone(stderr: string): boolean { + return /This live event has ended|is no longer live|Private video|Video unavailable|This video has been removed|This video is private|has been terminated/i.test( + stderr, + ); +} + +// What one attempt came to. +// recorded it wrote media (whatever its exit): never retried here +// stopped a Cancel's SIGINT +// unsupported yt-dlp cannot start this stream at its start (→ index 0) +// argv the same argv would fail the same way (no format the +// selector names, a URL no extractor takes): not retried +// gone the stream has ended, is private or removed: not retried +// nothing it recorded nothing for another reason: retried +export type LiveAttemptClass = "recorded" | "stopped" | "unsupported" | "argv" | "gone" | "nothing"; + +export function classifyAttempt(o: { exitCode: number | null; signalled: boolean; stderrTail: string; bytes: number }): LiveAttemptClass { + if (o.signalled) return "stopped"; + if (o.bytes > 0) return "recorded"; + if (liveFromStartUnsupported(o.stderrTail)) return "unsupported"; + if (formatUnavailable(o.stderrTail) || /Unsupported URL/i.test(o.stderrTail)) return "argv"; + if (liveStreamGone(o.stderrTail)) return "gone"; + return "nothing"; +} + +// The recorder's last `ERROR:` line (yt-dlp prefixes a separate stream's lines +// with its number, `1: ERROR: …`), else its last line; at most 300 characters. +export function lastErrorLine(stderr: string): string | null { + const lines = stderr + .split(/[\r\n]+/) + .map((l) => l.trim()) + .filter(Boolean); + const err = [...lines].reverse().find((l) => /^(?:\d+:\s*)?ERROR:/.test(l)); + const line = err ?? lines.at(-1) ?? null; + return line ? line.replace(/^\d+:\s*/, "").slice(0, 300) : null; +} + +// "2 h 14 min", "14 min", "40 s". +export function spanWords(seconds: number): string { + const s = Math.max(0, Math.round(seconds)); + if (s < 60) return `${s} s`; + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + return h ? `${h} h ${m} min` : `${m} min`; +} diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts @@ -0,0 +1,192 @@ +// EVERY LIVE RECORDING OF A CHANNEL, ONE ROW PER RUN — `channels/<slug>/live-recordings.json` +// ({rows: [...]}, beside pending-keep.json). +// +// A recording's own record (`data/<id>/live-recording.json`) is where a run +// says what it is doing; it is not where a FAILURE can be relied on to stay. A +// run that made data/<id>/ and recorded nothing removes the dir (every +// enumerator reads a dir with metadata as "fetched"), and the record with it. +// This file is the durable side: record-live writes its row on every save of +// the record, and nothing but the cap below ever removes a row — never a +// failed run, never a row that needs a person. A row is cleared from +// attention by a person (acknowledge) or by a later run of the same id that +// lands (supersededBy). +// +// Written only through these functions (one atomic write per change, under the +// file's lock). + +import path from "node:path"; +import type { Paths } from "./paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; +import type { LivePart, LiveRecordingRecord, LiveRecordingStatus, LostSpan } from "./liveCapture"; + +export const LIVE_RECORDINGS_FILENAME = "live-recordings.json"; + +// Rows kept per channel; past it the oldest rows that need nobody go first. +export const LIVE_RECORDINGS_MAX_ROWS = 500; + +export type LiveRecordingRow = { + id: string; + url: string; + platform: string; + // When the run started (the record's startedAt): with `id`, the row's key. + startedAt: string; + endedAt?: string; + status: LiveRecordingStatus; + jobId?: string; + fromStart: boolean; + separate?: boolean; + error?: string; + attempts: number; + fallback?: "live-edge"; + lost?: LostSpan; + mustKeep: boolean; + note?: string; + streamStartedAt?: string; + parts: LivePart[]; + landedPart?: number; + acknowledgedAt?: string; + acknowledgedBy?: string; + // The run (its jobId, else its startedAt) that later landed this id. + supersededBy?: string; +}; + +function fileOf(paths: Pick<Paths, "channelsDir">, slug: string): string { + return path.join(paths.channelsDir, slug, LIVE_RECORDINGS_FILENAME); +} + +function coerceRow(raw: unknown): LiveRecordingRow | null { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const r = raw as LiveRecordingRow; + if (typeof r.id !== "string" || typeof r.startedAt !== "string" || typeof r.status !== "string") return null; + return { + ...r, + url: typeof r.url === "string" ? r.url : "", + platform: typeof r.platform === "string" ? r.platform : "unknown", + fromStart: r.fromStart === true, + attempts: typeof r.attempts === "number" ? r.attempts : 0, + mustKeep: r.mustKeep === true, + parts: Array.isArray(r.parts) ? r.parts : [], + }; +} + +export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, slug: string): Promise<LiveRecordingRow[]> { + const read = await readJsonFile(fileOf(paths, slug)); + if (!read.ok) return []; + const rows = (read.value as { rows?: unknown } | null)?.rows; + if (!Array.isArray(rows)) return []; + return rows.map(coerceRow).filter((r): r is LiveRecordingRow => r !== null); +} + +// Needs a person, as the row stands (the listing adds `interrupted`). +export function rowNeedsAttention(r: Pick<LiveRecordingRow, "status" | "fallback" | "acknowledgedAt" | "supersededBy">): boolean { + if (r.acknowledgedAt || r.supersededBy) return false; + return r.status === "failed" || r.fallback === "live-edge"; +} + +function cap(rows: LiveRecordingRow[]): LiveRecordingRow[] { + if (rows.length <= LIVE_RECORDINGS_MAX_ROWS) return rows; + const out = [...rows]; + for (let i = 0; i < out.length && out.length > LIVE_RECORDINGS_MAX_ROWS; ) { + const r = out[i]!; + if (r.status !== "recording" && !rowNeedsAttention(r)) out.splice(i, 1); + else i++; + } + return out; +} + +async function mutate<T>( + paths: Pick<Paths, "channelsDir">, + slug: string, + // Returns its answer and whether it changed anything (nothing changed: + // nothing written). + fn: (rows: LiveRecordingRow[]) => [T, boolean], +): Promise<T> { + const file = fileOf(paths, slug); + return withJsonFileLock(file, async () => { + const rows = await loadLiveRecordingRows(paths, slug); + const [out, changed] = fn(rows); + if (changed) await writeJsonAtomic(file, { rows: cap(rows) }); + return out; + }); +} + +// The row a run's record makes. +export function rowOfRecord( + id: string, + rec: LiveRecordingRecord, + extra: { note?: string } = {}, +): Omit<LiveRecordingRow, "acknowledgedAt" | "acknowledgedBy" | "supersededBy"> { + return { + id, + url: rec.url, + platform: rec.platform, + startedAt: rec.startedAt, + ...(rec.endedAt ? { endedAt: rec.endedAt } : {}), + status: rec.status, + ...(rec.jobId ? { jobId: rec.jobId } : {}), + fromStart: rec.fromStart, + ...(rec.separate !== undefined ? { separate: rec.separate } : {}), + ...(rec.error ? { error: rec.error } : {}), + attempts: rec.attempts ?? rec.parts.length, + ...(rec.fallback ? { fallback: rec.fallback } : {}), + ...(rec.lost ? { lost: rec.lost } : {}), + mustKeep: rec.mustKeep === true, + ...(extra.note ? { note: extra.note } : {}), + ...(rec.streamStartedAt ? { streamStartedAt: rec.streamStartedAt } : {}), + parts: rec.parts.map((p) => ({ ...p })), + ...(rec.landedPart !== undefined ? { landedPart: rec.landedPart } : {}), + }; +} + +// Writes (or rewrites) the run's row. A run that LANDS marks every earlier +// row of the same id that still needs a person as superseded by it. +export async function upsertLiveRecordingRow( + paths: Pick<Paths, "channelsDir">, + slug: string, + row: Omit<LiveRecordingRow, "acknowledgedAt" | "acknowledgedBy" | "supersededBy">, +): Promise<void> { + await mutate(paths, slug, (rows) => { + const i = rows.findIndex((r) => r.id === row.id && r.startedAt === row.startedAt); + const prev = i >= 0 ? rows[i]! : null; + const next: LiveRecordingRow = { + ...row, + ...(prev?.acknowledgedAt ? { acknowledgedAt: prev.acknowledgedAt } : {}), + ...(prev?.acknowledgedBy ? { acknowledgedBy: prev.acknowledgedBy } : {}), + ...(prev?.supersededBy ? { supersededBy: prev.supersededBy } : {}), + }; + if (i >= 0) rows[i] = next; + else rows.push(next); + // Superseded only by a recording that holds the stream from its start. + if (row.status === "landed" && row.fallback !== "live-edge") { + const by = row.jobId ?? row.startedAt; + for (const r of rows) { + if (r === next || r.id !== row.id || r.supersededBy) continue; + if (r.status === "failed" || r.status === "recording" || r.fallback === "live-edge") r.supersededBy = by; + } + } + return [undefined, true]; + }); +} + +// A person has seen it: every row of `id` that needs a person (or the one +// run `startedAt` names) is acknowledged. The rows stay. +export async function acknowledgeLiveRecordingRows( + paths: Pick<Paths, "channelsDir">, + slug: string, + id: string, + opts: { by?: string; startedAt?: string; now?: Date; interrupted?: (r: LiveRecordingRow) => boolean } = {}, +): Promise<number> { + const at = (opts.now ?? new Date()).toISOString(); + return mutate(paths, slug, (rows) => { + let n = 0; + for (const r of rows) { + if (r.id !== id || r.acknowledgedAt || r.supersededBy) continue; + if (opts.startedAt && r.startedAt !== opts.startedAt) continue; + if (!rowNeedsAttention(r) && !opts.interrupted?.(r)) continue; + r.acknowledgedAt = at; + if (opts.by) r.acknowledgedBy = opts.by; + n++; + } + return [n, n > 0]; + }); +} diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -29,6 +29,7 @@ import { DIARIZATION_SETTINGS_FIELD_DOCS, PACING_SETTINGS_FIELD_DOCS, LIVE_PRECLIP_SETTINGS_FIELD_DOCS, + LIVE_RECORDING_SETTINGS_FIELD_DOCS, PUBLISH_SETTINGS_FIELD_DOCS, REPORT_SCHEDULE_SETTINGS_FIELD_DOCS, DIGEST_SETTINGS_FIELD_DOCS, @@ -168,6 +169,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.livePreclip), }, ], + liveRecording: [ + { + path: "liveRecording", + docs: LIVE_RECORDING_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.liveRecording), + }, + ], pacing: [ { path: "pacing", diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -50,6 +50,7 @@ import type { DigestSettings, PacingSettingsBlock, LivePreclipSettingsBlock, + LiveRecordingSettingsBlock, PublishSettings, ReportScheduleSettings, ReportDebouncePreset, @@ -88,6 +89,8 @@ type PreSchemaSiteSettings = { sleepBetweenDownloadsSeconds: number; // Live pre-clip (plans/live-preclip.md) — its defaults. livePreclip: LivePreclipSettingsBlock; + // The live recordings' stall threshold (controller/liveRecordings.ts). + liveRecording: LiveRecordingSettingsBlock; // Release 17 slice RL — the adaptive pace and the hold. pacing: PacingSettingsBlock; downloadFormat: DownloadFormatPreset; @@ -150,7 +153,7 @@ type PreSchemaSiteSettings = { type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 49 fields, in file order", () => { +test("SiteSettings keeps its 50 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -163,6 +166,7 @@ test("SiteSettings keeps its 49 fields, in file order", () => { "social", "sleepBetweenDownloadsSeconds", "livePreclip", + "liveRecording", "pacing", "downloadFormat", "sourceVideoQuality", diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -985,6 +985,24 @@ export function sanitizeLivePreclip(v: unknown): LivePreclipSettingsBlock { }; } +// LIVE RECORDINGS (controller/liveRecordings.ts): how the listing judges a +// recording that is running. Each field is documented in +// LIVE_RECORDING_SETTINGS_FIELD_DOCS (rendered into SETTINGS.md). +export type LiveRecordingSettingsBlock = { + stallMinutes: number; +}; + +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.", +}; + +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) }; +} + export const SLEEP_BETWEEN_DOWNLOADS_MAX_SECONDS = 600; export const SLEEP_BETWEEN_DOWNLOADS_DEFAULT_SECONDS = 10; @@ -1974,6 +1992,9 @@ export const siteSettingsSchema = z.object({ livePreclip: settingsField((v): LivePreclipSettingsBlock => sanitizeLivePreclip(v)).describe( "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.", + ), 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/settings.json.example b/settings.json.example @@ -16,6 +16,9 @@ "scan": true, "mine": true }, + "liveRecording": { + "stallMinutes": 10 + }, "pacing": { "sleepRequestsCapSeconds": 16, "decayAfterCleanUnits": 5,