Archilyzer · Source

archilyzer

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

commit aacb11c6800e3cbbe726c08d359726a6f8f020f8
parent c0c08ee4aee3cd7d0546e621fecaa2bab0350af9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 22 Nov 2026 04:36:51 -0500

record-live: REVIEW-6 4-13: an ended stream behind is resumed once, network drops retried, the proof tightened, the lock names the recorder

- 4: when the stream ends while its from-start part is behind, the part is
  resumed once to the end. A landing short of an ended stream's own
  duration needs a person: "download the VOD now".
- 5: a resume that fails for the network is tried again on the 20/60/180 s
  waits. Empty live-edge recorders while the state cannot be read are not
  counted toward "taken as ended".
- 6: the equation refuses an empty kept fragment, and the file must end
  with its last fragment's bytes.
- 7: a resume in place needs the floor plus its stream files. A fresh part
  checks the full floor.
- 8: one moved-aside merged copy at a time. A resume's progress is the
  stream files' bytes only.
- 9: the stem lock names the recorder's pid (onSpawn). It is stale only
  when neither the editor nor the recorder is alive.
- 10: a raw source (a stream landed as it is, a muxed .ts) is copied, kept,
  and verified against before it goes.
- 11: no fragment is dropped without a numeric state (read twice); a state
  caught mid-rewrite is read again before it is taken as unreadable.
- 12: private while the editor was down sets endedBy; nothing on disk is
  removed.
- 13: the state is rebuilt per stream (one finished, one with its state).
- Wording: a landing while live "matches its stream files". OPERATING.md
  now gives the reuse order and drops the checkpoint text.

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

Diffstat:
MOPERATING.md | 52+++++++++++++++++++++++++++++-----------------------
Mcommon/controller/liveRecordings.ts | 6++++++
Mcommon/controller/recordLive.test.ts | 210++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/recordLive.ts | 161+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcommon/lib/liveFragments-server.test.ts | 30++++++++++++++++++++++++++++++
Mcommon/lib/liveFragments-server.ts | 33+++++++++++++++++++++++++++++----
Mcommon/lib/liveRecordings-server.ts | 6+++++-
7 files changed, 445 insertions(+), 53 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1499,27 +1499,31 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note": resume is impossible (no state: the file was finished; an unreadable state; a stream past 119 h, or whose start time is not known; a resume that writes nothing) does the live-edge fallback below run. A state read refused as private or removed is read again a minute later; confirmed, the row says the stream went private or was removed while recording and what is held (`endedBy`, needing a person). -- **A resume appends only to a file proven whole; otherwise a FRESH part from the start (DESIGN-4).** A separate-streams - from-start recorder runs with `--keep-fragments`, `-k`, `--abort-on-unavailable-fragments` and `--retry-sleep - fragment:exp=1:20`. Each stream file must equal its checkpoint (`<f>.frags.json`) plus the kept `<f>-Frag<n>` up to - the `.ytdl` index; the only repair is a tail that is byte for byte the start of the next kept fragment (a stop inside - an append), truncated back and logged with both lengths. Anything else — shorter, an excess that is not that prefix, - the next fragment gone, a missing fragment, no checkpoint (every part of earlier builds) — is no resume in place: - the first fallback is a FRESH part from the stream's start (a new stem, `ytdlp-f<n>`, proven on YouTube under - 119 h), the insurance re-armed beside it; live edge plus recovery only when from-start cannot reach the start. EVERY - fragment is kept until the stream is CONFIRMED done (the platform says it is over AND the landed file is verified): - the stream files plus their fragments are twice the stream on disk (about 6 GB for 6 h at 720p). Short of disk - (under the floor, checked at each recorder's start and every minute) the fragments are dropped — the recording goes - on, the part can no longer be resumed in place, and the row says so (`fragmentsDropped`); never a silent prune. A fragment that cannot be fetched stops the - recorder (SIGTERM; yt-dlp would record the other stream on alone) and resumes it after 20 s, 60 s and 180 s; still - stuck there, a fresh part; that one stuck at the same fragment, ONE run that may skip it — the part and the landed - file carry `skippedFragments` (count, positions), it is never proven and never covers, and the row stays loud after - the landing. Those lines (`Skipping fragment`, `Got error`, `.ytdl file is corrupt`, …) are never thinned out of the - job log. A from-start recorder that ends by itself while the stream still reads live (yt-dlp's own end ~35 s after - its last fragment: an ingest pause) has the insurance re-armed BEFORE the confirming read, then a fresh part. - One recorder per stem: `<stem>.rec.lock`, held while it runs; a lock of a dead process, or made before the machine's - last boot, is stale and taken over. At a shutdown with a part waiting to be resumed nothing lands: every part waits - for the restart's landing. A boot restart still `starting` after 10 minutes never went on: the row says so. +- **A resume appends only to a file proven whole (DESIGN-4, REVIEW-6).** A separate-streams from-start recorder runs + with `--keep-fragments`, `-k`, `--abort-on-unavailable-fragments` and `--retry-sleep fragment:exp=1:20`. Every + fragment `<f>-Frag<n>` is kept until the stream is confirmed done. Before a resume each stream file must equal its + kept fragments 1..N (the `.ytdl` index), none empty, the file ending with the last one's bytes; the only repair is a + tail that is byte for byte the start of the next kept fragment (a stop inside an append), truncated back and logged + with both lengths; and every kept fragment past the index is removed (a complete one would be asked for by Range past + its end: 416, and the resume would record nothing). After yt-dlp finished a part by itself while the stream went on + (a self-exit: merged, its state removed), the state is written again, per stream, at the count the kept fragments + prove and the merged copy is moved aside (one copy at a time) — the same files continue. Order when a recorder stops + while live: resume in place, else that reuse, else a FRESH part from the start (a new stem, `ytdlp-f<n>`, proven on + YouTube under 119 h, the log saying how much it fetches again), else the live edge plus recovery. A resume needs the + floor plus its stream files free; a fresh part the floor and twice the largest part. The stream files plus their + fragments are twice the stream on disk (about 6 GB for 6 h at 720p); short of disk (checked at each recorder's start + and every minute) the fragments are dropped — the recording goes on, the part can no longer be resumed in place, the + row says so (`fragmentsDropped`); never a silent prune. A fragment that cannot be fetched (yt-dlp's `ERROR: \r[download] + Got error: … Giving up after N retries`, read as one line) stops the recorder (SIGTERM; yt-dlp would record the + other stream on alone) and resumes it after 20 s, 60 s and 180 s; still stuck there, a fresh part; that one stuck at + the same fragment, ONE run that may skip it — the part and the landed file carry `skippedFragments`, it is never + proven, and the row stays loud after the landing. A resume that fails for the network is tried again on the same + waits, and empty live-edge recorders while the state cannot be read are not taken as the stream's end. Those lines are + never thinned out of the job log. When the stream ENDS while a from-start part is behind, that part is resumed once + to the end (an ended stream is still served from its start); a landing short of an ended stream's own duration + needs a person ("download the VOD now"). One recorder per stem: `<stem>.rec.lock` names the editor and the recorder; + stale only when neither is alive, or made before the machine's last boot. At a shutdown with a part waiting to be + resumed nothing lands. A boot restart still `starting` after 10 minutes never went on: the row says so. - **A recorder that ends by itself while the stream is live is never "the whole stream" (DESIGN-5).** yt-dlp can merge and exit 0 mid-stream — "Cannot find refreshed url for format N … Giving up after 3 retries" (the platform stopped serving the format, e.g. its DVR switched off): that part gets `failureClass: "url-refresh"` and a plain @@ -1536,8 +1540,10 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note": fragments) is removed until the stream is confirmed done. - **The landed file is verified before anything is removed (DESIGN-4).** After the landing and the transcription hand-off the landed file is checked against the stream files it was merged from (packets per track equal, spans - within max(0.5 s, 2 frames), no step between packets over 1.5× the median video step or 2× the audio, nor 0.1 s; - decode times only forward), or scanned alone. ffprobe runs at `-v error`: a raw WebM's "unknown-length element" + within max(0.5 s, 2 frames), the picture's and the sound's spans within max(2 s, 2 fragments) of each other, no step + between packets over 1.5× the median video step or 2× the audio, nor 0.1 s; decode times only forward), or scanned + alone; each stream file must also be byte for byte its kept fragments, and the editor's own merge fails on any line + ffmpeg writes. A raw source (a stream landed as it is, a muxed `.ts`) is copied, kept, and checked against. ffprobe runs at `-v error`: a raw WebM's "unknown-length element" warning, one per fragment, is not an error. Until it is verified the row says `verification: pending`; verified, the stream files, their fragments and every part meant for removal go; not verified, NOTHING is removed and the row needs a person. Cost: about 115 k packets a second plus reading the files — for a 6 h 19 min stream of 683 k video diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -190,6 +190,11 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: (v.status === "interrupted" ? "" : " — not resumed by this run: a person decides"), ); } + if (v.status === "landed" && v.coverage?.basis === "duration" && v.coverage.covers === false && v.coverage.capturedSeconds !== null && v.coverage.streamSeconds !== null) { + extra.unshift( + `landed ${spanWords(v.coverage.capturedSeconds)} of the ended stream's ${spanWords(v.coverage.streamSeconds)}: the rest is in no file — download the VOD now`, + ); + } if (v.landedWhileLive) { const u = v.landedWhileLive.unrecordedSeconds; extra.unshift( @@ -421,6 +426,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO skippedFragments: own?.skippedFragments ?? row.skippedFragments, parts: own?.parts ?? row.parts, landedWhileLive: own?.landedWhileLive ?? row.landedWhileLive, + coverage: own?.coverage ?? row.coverage, }), }; const shown = diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -3772,7 +3772,8 @@ test("B3: the stream was REMOVED while the editor was down (every read refused a }); await r.run.catch(() => {}); assert.equal(await storedSeconds(id), 3000, "the only copy is in the store"); - assert.deepEqual(await left(id), []); + // (REVIEW-6 12: gone is endedBy private — nothing on disk is removed.) + assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`))); const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!; assert.equal(old.restart?.state, "landed"); assert.match(old.reason, /private or removed/); @@ -4552,3 +4553,210 @@ test("REVIEW-6 3: before any fragment goes, each stream file must be byte for by assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files are kept"); assert.equal(row.needsAttention, true); }); + +// --- REVIEW-6 4-13 -------------------------------------------------------------------- + +test("REVIEW-6 4: the stream ENDS while its from-start part is behind — resumed once to its end, not landed short", { timeout: 60_000 }, async () => { + const id = "exmplr6end1"; + const { run, calls } = await incidentRun( + id, + resumableYtdlp(async ({ n, write }) => { + if (n === 1) { + await write(3000); + return "die"; + } + await write(7200); + return "end"; + }), + { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge } }, + ); + assert.equal((await run).status, "landed"); + assert.equal(calls.length, 2, "one resume after the end"); + assert.equal(outOf(calls[1]!), outOf(calls[0]!)); + assert.equal(await storedSeconds(id), 7200); +}); + +test("REVIEW-6 4: landed SHORT of an ended stream's own duration — needs a person: \"download the VOD now\"", { timeout: 60_000 }, async () => { + const id = "exmplr6end2"; + const { run } = await incidentRun( + id, + resumableYtdlp(async ({ write, args }) => { + await write(3000); + await dropState(args); + await noReuse(args); + return "die"; + }), + { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge } }, + ); + await run.catch(() => {}); + const row = (await rowOf(id))[0]!; + assert.equal(row.status, "landed"); + assert.equal(row.coverage?.covers, false); + assert.equal(row.needsAttention, true); + assert.match(row.reason, /download the VOD now/); +}); + +test("REVIEW-6 5: a resume that fails for the NETWORK is tried again on the waits, the same files — not given up after one try", { timeout: 60_000 }, async () => { + const id = "exmplr6net1"; + let live = true; + const { run, calls, waits } = await incidentRun( + id, + resumableYtdlp(async ({ n, write }) => { + if (n === 1) { + await write(3000); + return "die"; + } + if (n === 2) return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Unable to download webpage: The read operation timed out\n", signalled: false }; + await write(7200); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + assert.equal((await run).status, "landed"); + assert.ok(waits.includes(20_000), `waited before the retry: ${waits.join(", ")}`); + assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "the same files throughout"); +}); + +test("REVIEW-6 5: empty live-edge recorders while the state cannot be read (offline) are not evidence the stream ended", { timeout: 60_000 }, async () => { + const id = "exmplr6net2"; + let reads = 0; + const { run } = await incidentRun( + id, + resumableYtdlp(async ({ n, write, args }) => { + if (n === 1) { + await write(3000); + await dropState(args); + await noReuse(args); + return "die"; + } + return { exitCode: 1, stderrTail: "ERROR: Unable to download webpage: timed out\n", signalled: false }; + }), + { + deps: { ...FAST_WATCH, join: null, merge: fakeMerge, freshFromStart: false }, + refresh: { failReads: [2, 3, 4, 5, 6, 7], afterRead: (k) => void (reads = k), stillLive: () => reads < 9 }, + }, + ); + await run.catch(() => {}); + const row = (await rowOf(id))[0]!; + assert.doesNotMatch(row.restarts?.refused ?? "", /three live-edge recorders/); +}); + +test("REVIEW-6 7: a resume in place needs the floor plus the stream files — not twice everything on disk (fragments, merged copies)", { timeout: 60_000 }, async () => { + const id = "exmplr6rm01"; + let live = true; + let streams = 0; + const { run, calls } = await incidentRun( + id, + resumableYtdlp(async ({ n, write, args }) => { + if (n === 1) { + await write(3000); + for (const f of [FAKE_V, FAKE_A]) streams += (await stat(`${outOf(args)}.${f}`)).size; + return "die"; + } + await write(7200); + live = false; + return "end"; + }), + // Room for the floor and the streams, not for twice the part (fragments included). + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 1000 + streams + 10 }, refresh: { stillLive: () => live } }, + ); + await run.catch(() => {}); + assert.ok(calls.length >= 2, "the resume was not refused for want of disk"); + assert.equal(outOf(calls[1]!), outOf(calls[0]!)); +}); + +test("REVIEW-6 8: one moved-aside merged copy at a time, however many self-exits", { timeout: 60_000 }, async () => { + const id = "exmplr6pm01"; + let live = true; + let premerges = 0; + const { run } = await incidentRun( + id, + resumableYtdlp(async ({ n, write }) => { + premerges = Math.max(premerges, (await left(id)).filter((x) => /\.premerge-\d+\./.test(x)).length); + await write(3000 + n * 600); + if (n < 4) return "end"; + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + await run; + assert.equal(premerges, 1, "never two copies aside"); +}); + +test("REVIEW-6 9: the stem lock names the RECORDER too — its live recorder keeps the lock though the editor that made it is gone", async () => { + const { takeStemLock } = await import("./recordLive"); + const dir = path.join(ROOT, "locks9"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, ".x.live-9.ytdlp.rec.lock"), JSON.stringify({ pid: 2 ** 22 + 54321, recorderPid: process.pid, at: new Date().toISOString() })); + const r = await takeStemLock(dir, ".x.live-9.ytdlp"); + assert.equal(r.ok, false, "an orphan recorder still writes those files"); + assert.match((r as { why: string }).why, /its recorder/); +}); + +test("REVIEW-6 10: a RAW source (an audio stream landed as it is) stays in staging until the stored file is checked against it", { timeout: 60_000 }, async () => { + const id = "exmplr6raw1"; + let existedAtCheck = false; + let checked = ""; + const { run } = await incidentRun( + id, + async (args) => { + await writeFile(`${outOf(args)}.${FAKE_A}`, "format=mp4;seconds=7200;v=none;"); + return okExit; + }, + { + meta: { ...YT_META(id), duration: 7200 }, + deps: { + join: null, + merge: fakeMerge, + verifyMerged: async (_m: string, streams: readonly string[]) => { + existedAtCheck = streams.length > 0 && (await stat(streams[0]!).catch(() => null)) !== null; + checked = streams[0] ?? ""; + return { ok: true }; + }, + }, + }, + ); + await run.catch(() => {}); + assert.equal(existedAtCheck, true, "checked against the raw file, which was still there"); + assert.equal(await stat(checked).catch(() => null), null, "the landed raw file removed after the check"); +}); + +test("REVIEW-6 12: private while the editor was down — `endedBy` on the new row as when it happens while recording, and nothing removed", { timeout: 60_000 }, async () => { + const id = "exmplr6bg01"; + const { startedAt } = await waitingAtShutdown(id); + await askBoot(id, startedAt); + const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`; + const r = await incidentRun(id, async () => assert.fail("nothing is recorded"), { + request: { resumeOf: startedAt }, + deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, + refresh: { failReads: [1, 2, 3, 4, 5, 6], failWith: PRIVATE }, + }); + await r.run.catch(() => {}); + const row = (await rowOf(id)).find((x) => x.startedAt !== startedAt)!; + assert.equal(row.endedBy?.class, "private"); + assert.equal(row.needsAttention, true); + assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files kept"); +}); + +test("REVIEW-6 13: one stream finished (its state gone), the other with its state — rebuilt per stream and resumed in place, not a fresh part", { timeout: 60_000 }, async () => { + const id = "exmplr6ps01"; + let live = true; + const { run, calls } = await incidentRun( + id, + resumableYtdlp(async ({ n, write, args }) => { + if (n === 1) { + await write(3000); + await rm(`${outOf(args)}.${FAKE_V}.ytdl`, { force: true }); + return "die"; + } + await write(7200); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + assert.equal((await run).status, "landed"); + assert.equal(outOf(calls[1]!), outOf(calls[0]!), "the same files"); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -387,6 +387,8 @@ export type RecorderSpawn = (opts: { label: string; // Every line the recorder prints, progress included (before the thinning). onLine?: (line: string) => void; + // The recorder's pid, once spawned (REVIEW-6 9: the stem lock names it). + onSpawn?: (pid: number) => void; }) => Promise<RecorderOutcome>; // A progress line yt-dlp or ffmpeg repeats every second for hours. yt-dlp @@ -413,25 +415,45 @@ export function isProgressLine(line: string): boolean { return PROGRESS_RE.test(line) && !NEVER_THINNED_RE.test(line); } +// A `.ytdl` state's fragment index, or null when it does not parse. +function readYtdlRaw(raw: string): number | null { + try { + const idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index; + return typeof idx === "number" && idx >= 0 ? idx : null; + } catch { + return null; + } +} + // NOTE 5 (REVIEW-5) — THE STEM LOCK: `<stem>.rec.lock` in the store's staging // dir, made with O_EXCL while a recorder of that stem runs, removed when it // returns. STALE when the process that made it is gone (its pid answers no // signal) or it was made before the machine last booted (a pid may be // reused): a stale lock is taken over, said. Held by a live process (this // editor's or another's), the recorder is not started on that stem. -export async function takeStemLock(dir: string, stem: string): Promise<{ ok: true; release: () => Promise<void> } | { ok: false; why: string }> { +export async function takeStemLock( + dir: string, + stem: string, +): Promise<{ ok: true; release: () => Promise<void>; setRecorder: (pid: number) => Promise<void> } | { ok: false; why: string }> { const file = path.join(dir, `${stem}.rec.lock`); - const body = JSON.stringify({ pid: process.pid, at: new Date().toISOString() }); + const at = new Date().toISOString(); + const body = (recorderPid?: number) => JSON.stringify({ pid: process.pid, ...(recorderPid ? { recorderPid } : {}), at }); for (let tries = 0; tries < 2; tries++) { try { const fh = await open(file, "wx"); - await fh.writeFile(body); + await fh.writeFile(body()); await fh.close(); - return { ok: true, release: () => rm(file, { force: true }) }; + return { + ok: true, + release: () => rm(file, { force: true }), + // REVIEW-6 9: the RECORDER's pid too — it runs in its own process + // group and outlives an editor killed outside the unit. + setRecorder: (pid: number) => writeFile(file, body(pid)).catch(() => {}), + }; } catch (err) { if ((err as NodeJS.ErrnoException).code !== "EEXIST") return { ok: false, why: `its lock could not be made (${(err as Error).message})` }; } - const held = await readFile(file, "utf8").then((t) => JSON.parse(t) as { pid?: number; at?: string }, () => null); + const held = await readFile(file, "utf8").then((t) => JSON.parse(t) as { pid?: number; recorderPid?: number; at?: string }, () => null); const bootMs = Date.now() - uptime() * 1000; const alive = (pid: unknown) => { if (typeof pid !== "number") return false; @@ -442,8 +464,13 @@ export async function takeStemLock(dir: string, stem: string): Promise<{ ok: tru return (e as NodeJS.ErrnoException).code === "EPERM"; } }; - const stale = !held || !alive(held.pid) || !held.at || Date.parse(held.at) < bootMs; - if (!stale) return { ok: false, why: `another recorder holds ${path.basename(file)} (pid ${held!.pid}, since ${held!.at})` }; + // Stale only when NEITHER the editor nor the recorder it names is alive, + // or it was made before the machine last booted (pids are reused). + const stale = !held || (!alive(held.pid) && !alive(held.recorderPid)) || !held.at || Date.parse(held.at) < bootMs; + if (!stale) { + const who = alive(held!.recorderPid) ? `its recorder, pid ${held!.recorderPid}` : `pid ${held!.pid}`; + return { ok: false, why: `another recorder holds ${path.basename(file)} (${who}, since ${held!.at})` }; + } await rm(file, { force: true }); } return { ok: false, why: `its lock ${path.basename(file)} could not be taken` }; @@ -468,10 +495,11 @@ async function writeStemMarks(dir: string, stem: string, patch: StemMarks): Prom // log with the per-second progress thinned to one line every five minutes. // It returns when yt-dlp EXITS: a grandchild still holding the pipes a few // seconds later is killed with the group, never waited on. -export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, label, onLine }) => +export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, label, onLine, onSpawn }) => new Promise((resolve) => { onLog(`[${label}] $ ${bin} ${args.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(" ")}\n`); const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"], detached: true }); + if (child.pid) onSpawn?.(child.pid); const killTree = (sig: NodeJS.Signals) => { try { if (child.pid) process.kill(-child.pid, sig); @@ -1288,6 +1316,9 @@ async function recordLiveRunInner( const leftInStaging = async () => livePartFiles(id, await readdir(path.dirname(savedVideoDir(paths, opts.channelConfig, req.slug, id))).catch(() => [] as string[])).length; let bootUnread: string | null = null; + // REVIEW-6 12: private or removed while the editor was down — said on the + // new record as when it happens while recording (endedBy). + let bootGone: { class: LiveFailureClass; message: string; at: string } | null = null; try { await refresh(); } catch (err) { @@ -1326,7 +1357,10 @@ async function recordLiveRunInner( if (await leftInStaging()) { // Never a recording on a guess — but what is left lands. // (Gone is the platform's word: the stream is confirmed done.) - if (gone) endedByRefusal = true; + if (gone) { + endedByRefusal = true; + bootGone = { class: "private", message: first, at: now().toISOString() }; + } bootUnread = gone ? `the stream was made private or removed while the editor was down (${first})` : `the stream's state could not be read (${reads} reads: ${first}) — it may still be live and is NOT being recorded: Record again if it is`; @@ -1432,6 +1466,7 @@ async function recordLiveRunInner( const streamStartSec = typeof meta?.release_timestamp === "number" ? (meta.release_timestamp as number) : typeof meta?.timestamp === "number" ? (meta.timestamp as number) : null; const record: LiveRecordingRecord = { + ...(bootGone ? { endedBy: bootGone } : {}), status: "recording", url: plan.url, platform: plan.platform, @@ -1800,6 +1835,7 @@ async function recordLiveRunInner( signal: own.signal, label: tag, onLine: lineHook, + onSpawn: (pid) => void lock.setRecorder(pid), }); } finally { if (timer) clearInterval(timer); @@ -1830,6 +1866,12 @@ async function recordLiveRunInner( const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0); const filesOf = async (stem: string): Promise<LivePartFiles | null> => livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])).find((g) => g.stem === stem) ?? null; + const streamBytesOf = async (stem: string) => { + const g = await filesOf(stem); + let n = 0; + for (const f of g?.streams ?? []) n += await sizeOf(path.join(slugStore, f)); + return n; + }; const bytesOf = async (stem: string) => { const g = await filesOf(stem); let n = 0; @@ -1843,10 +1885,12 @@ async function recordLiveRunInner( // The floor scales with the stream (REVIEW-2 3.4): max(the floor, twice the // largest part of this run so far) — a new part may grow as large, and a // landing's merge needs as much again. - const roomFor = async (what: string): Promise<boolean> => { + // REVIEW-6 7: before a resume in place, the floor plus the stream files' + // size (the files continue; the kept fragments and merges are not new). + const roomFor = async (what: string, o: { resumeStem?: string } = {}): Promise<boolean> => { let largest = 0; for (const p of parts) largest = Math.max(largest, await allBytesOf(p.stem)); - const need = Math.max(minFree, 2 * largest); + const need = o.resumeStem ? minFree + (await streamBytesOf(o.resumeStem)) : Math.max(minFree, 2 * largest); const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0); if (free >= need) return true; (record.spaceHeld ??= []).push({ what, at: now().toISOString(), freeBytes: free }); @@ -1873,7 +1917,12 @@ async function recordLiveRunInner( if (!(await bytesOf(stem))) return { ok: false, why: "nothing to resume" }; let fragment = Infinity; for (const f of streams) { - const raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null); + let raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null); + // REVIEW-6 11: a state caught mid-rewrite is read again once. + if (raw !== null && readYtdlRaw(raw) === null) { + await new Promise((r) => setTimeout(r, 50)); + raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null); + } if (raw === null) { // An empty stream file with no state yet is resumed from 0. if ((await sizeOf(path.join(slugStore, f))) === 0) { @@ -1947,7 +1996,14 @@ async function recordLiveRunInner( for (const f of g.streams) { const file = path.join(slugStore, f); const idx = await readYtdlIndex(file); - if (idx !== "absent") return { ok: false, why: `${f} still has its state (a resume, not a reuse)` }; + // REVIEW-6 13: per stream — one that still has its state is resumed as + // it is (its accounting is checked before the resume); one without is + // rebuilt from its kept fragments. + if (typeof idx === "number") { + counts.push(-1); + continue; + } + if (idx === null) return { ok: false, why: `${f}.ytdl does not read` }; const kept = fragNumbers(f, names); const k = kept.length && kept[kept.length - 1] === kept.length ? kept.length : 0; if (!k) return { ok: false, why: `${f}: its kept fragments are not 1..N without a gap` }; @@ -1957,18 +2013,23 @@ async function recordLiveRunInner( if (sum !== size) return { ok: false, why: `${f} is ${size} bytes, its ${k} kept fragments ${sum}` }; counts.push(k); } + if (!counts.some((c) => c >= 0)) return { ok: false, why: "every stream still has its state (a resume, not a reuse)" }; if (apply) { for (const [i, f] of g.streams.entries()) { + if (counts[i]! < 0) continue; await writeFile(path.join(slugStore, `${f}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: counts[i] } } })); } const stamp = Date.now(); + // REVIEW-6 8: one moved-aside merge at a time (each self-exit would + // leave another full copy of the stream so far). + for (const f of g.scratch) if (/\.premerge-\d+\.[a-z0-9]+$/i.test(f)) await rm(path.join(slugStore, f), { force: true }); for (const f of g.finished) { const m = /^(.*)\.([a-z0-9]+)$/i.exec(f); if (m) await rename(path.join(slugStore, f), path.join(slugStore, `${m[1]}.premerge-${stamp}.${m[2]}`)).catch(() => {}); } - say(`${stem}: yt-dlp had finished it while the stream went on; its state is rebuilt at the ${Math.min(...counts)} fragments its kept files prove, the merged copy moved aside — resumed, reusing what is on disk.`); + say(`${stem}: yt-dlp had finished it while the stream went on; its state is rebuilt at the ${Math.min(...counts.filter((c) => c >= 0))} fragments its kept files prove, the merged copy moved aside — resumed, reusing what is on disk.`); } - return { ok: true, fragments: Math.min(...counts) }; + return { ok: true, fragments: Math.min(...counts.filter((c) => c >= 0)) }; }; // The one repair (DESIGN-4 1), made just before a resume: a torn last // append truncated back, logged with both lengths. Anything it cannot @@ -2660,6 +2721,8 @@ async function recordLiveRunInner( // DESIGN-4 3: aborts per stem at one fragment; where a fresh part's // predecessor could not get past; whether the last fresh part wrote nothing. const abortTries = new Map<string, { fragment: number; n: number }>(); + const netTries = new Map<string, number>(); + let endResumed = false; let freshAbortAt: number | null = null; let freshFailedLast = false; while (cur && !signal.aborted && !pathB) { @@ -2715,6 +2778,29 @@ async function recordLiveRunInner( state = await liveNow(); } if (state === "ended") { + // REVIEW-6 4: the stream ended while its from-start part may still + // be behind — an ended stream is still served from its start (the + // generator runs once more, post_live): resumed ONCE to its end. + if (!endResumed && !endedByRefusal && cur.mode === "from-start" && separate && !signal.aborted) { + endResumed = true; + let st = await resumeStateOf(cur.o.stem); + if (!st.ok) { + const ru = await restoreForReuse(cur.o.stem, true); + if (ru.ok) st = await resumeStateOf(cur.o.stem); + } + const rc = st.ok ? await reconcileForResume(cur.o.stem) : null; + if (st.ok && rc?.ok) { + say(`The stream has ended: ${cur.o.part.stem} is resumed once from fragment ${st.fragment} to the stream's end (an ended stream is still served from its start).`); + const o = await ytdlpPart(plan.url, "resume", "from-start", "resume to the end; ", { + resume: { stem: cur.o.stem, formats: st.formats }, + noWait: true, + onStart: onMainStart("from-start", true), + onLine: onMainLine, + }); + cur = { o, bytes: await bytesOf(o.stem), mode: "from-start", partial: false }; + continue; + } + } if (cur.o.stalled) say(`The stream has ended: what was recorded lands (no restart).`); break; } @@ -2758,7 +2844,7 @@ async function recordLiveRunInner( if (signal.aborted) break; if ((await liveNow()) === "ended") break; } - if (!(await roomFor(`restart ${restarts.count + 1}`))) { + if (!(await roomFor(`restart ${restarts.count + 1}`, cur.mode === "from-start" ? { resumeStem: cur.o.stem } : {}))) { await refuse("not enough room on the store's disk: the stream reads live and is NOT recorded", "NOT restarted for want of disk: the stream reads live and is NOT recorded; the row needs a person."); break; } @@ -2812,7 +2898,8 @@ async function recordLiveRunInner( if (st.ok) { restarts.count += 1; restarts.at.push(now().toISOString()); - const before = await bytesOf(cur.o.stem); + // (REVIEW-6 8: the stream files' bytes only — a re-merge is no progress.) + const before = await streamBytesOf(cur.o.stem); say(`Resume ${(cur.o.part.resumes ?? 0) + 1} of ${cur.o.part.stem} (${why}): the same files from fragment ${st.fragment}, format ${st.formats}.`); const o = await ytdlpPart(plan.url, "resume", "from-start", `resume (${why}); `, { resume: { stem: cur.o.stem, formats: st.formats }, @@ -2823,9 +2910,10 @@ async function recordLiveRunInner( }); // Media bytes only (REVIEW-5 note 12: a rewritten state is no progress). const bytes = await bytesOf(o.stem); + const grew = (await streamBytesOf(o.stem)) > before; // A resume stopped again by a fragment it cannot fetch is one more // try at that fragment (DESIGN-4 3), not "wrote nothing". - if (bytes > before || (o.fragAbort && !signal.aborted)) { + if (grew || (o.fragAbort && !signal.aborted)) { emptyInRow = 0; const partial = separate && !o.signalled && bytes > 0 ? (await missingStreamOf(o.stem)) !== null : false; cur = { o, bytes, mode: "from-start", partial }; @@ -2835,8 +2923,21 @@ async function recordLiveRunInner( o.part.resumeError = o.locked ?? lastErrorLine(last) ?? `yt-dlp exit ${o.exitCode ?? "null"}`; await save(); say(`The resume wrote nothing (${o.part.resumeError}).`); - resumeFailed.add(o.stem); if (o.signalled && signal.aborted) break; + // REVIEW-6 5: a resume that failed for the network is tried again + // (20 s, 60 s, 180 s), not given up after one try. + const rcls = liveFailureClass(last); + const nt = (netTries.get(o.stem) ?? 0) + 1; + if (rcls === "network" && nt <= FRAGMENT_ABORT_WAITS_MS.length && bytes > 0) { + netTries.set(o.stem, nt); + const w = FRAGMENT_ABORT_WAITS_MS[nt - 1]!; + say(`${o.stem}: the resume failed for the network; tried again in ${spanWords(w / 1000)} (${nt} of ${FRAGMENT_ABORT_WAITS_MS.length}).`); + await waitFor(stretch(w), signal); + if (signal.aborted) break; + cur = { o, bytes, mode: "from-start", partial: false }; + continue; + } + resumeFailed.add(o.stem); } else { say(`${cur.o.part.stem} cannot be resumed in place (${st.why}).`); resumeFailed.add(cur.o.stem); @@ -2848,7 +2949,7 @@ async function recordLiveRunInner( // stays (a copy); the fresh whole covers it at the landing. A // catching-up fresh part re-arms the insurance (onMainStart). Live // edge plus recovery only when it cannot, or it wrote nothing. - if (fromStart && separate && deps.freshFromStart !== false && !freshFailedLast && startProvable(false)) { + if (fromStart && separate && deps.freshFromStart !== false && !freshFailedLast && startProvable(false) && (await roomFor(`fresh part ${restarts.count + 1}`))) { restarts.count += 1; restarts.at.push(now().toISOString()); const k = restarts.count; @@ -2960,7 +3061,10 @@ async function recordLiveRunInner( const bytes = await bytesOf(o.stem); const partial = separate && !o.signalled && bytes > 0 ? (await missingStreamOf(o.stem)) !== null : false; if (bytes === 0 && !o.signalled) { - emptyInRow += 1; + // REVIEW-6 5: while the state cannot be read (offline), an empty + // recorder is not evidence that the stream ended. + if (state !== "unknown") emptyInRow += 1; + else say(`Restart ${k} recorded nothing while the stream's state cannot be read (offline?): not counted toward "taken as ended".`); const last = recentOutput(o); o.part.error = lastErrorLine(last) ?? `yt-dlp exit ${o.exitCode ?? "null"}`; o.part.failureClass = liveFailureClass(last); @@ -3538,6 +3642,10 @@ async function recordLiveRunInner( "and this one is not proven to hold it (not the whole stream from its start, nor a join that includes it): the stored one stays", ); } + // REVIEW-6 10: a RAW source (a stream file landed as it is, a muxed .ts the + // landing remuxes) is copied, not moved: it stays until the stored file is + // verified against it. A merged file is moved (its streams are the source). + const rawSource = best.group.streams.includes(path.basename(best.file)) || /\.ts$/i.test(best.file); let landed: Awaited<ReturnType<typeof landMediaFile>>; try { landed = await landMediaFile({ @@ -3547,7 +3655,7 @@ async function recordLiveRunInner( videoId: id, sourcePath: best.file, via: "record-live", - move: true, + move: !rawSource, url: plan.url, note: req.note ?? `a live recording (${best.part?.method ?? "an earlier run's part"})`, onLog, @@ -3575,10 +3683,11 @@ async function recordLiveRunInner( // store; the stream files it was merged from, and every part meant for // removal, stay until it is verified (after the hand-off, below) — never // the other order. The landed file in staging itself was moved or copied. - await rm(best.file, { force: true }); + if (!rawSource) await rm(best.file, { force: true }); const mergedFrom = best.group.streams.filter((f) => at(f) !== best.file); const verifyAgainst: string[] = []; for (const f of mergedFrom) if ((await sizeOf(at(f))) > 0) verifyAgainst.push(at(f)); + if (rawSource && !verifyAgainst.length) verifyAgainst.push(best.file); record.verification = { state: "pending", at: now().toISOString(), ...(verifyAgainst.length ? { against: verifyAgainst.map((f) => path.basename(f)) } : {}) }; if (stillLive) { const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; @@ -3699,7 +3808,11 @@ async function recordLiveRunInner( const keptBefore = kept.length; if (verdict.ok) { record.verification = { ...record.verification!, state: "verified", at: now().toISOString() }; - say(`The landed file is verified whole (${verifyAgainst.length ? `against ${verifyAgainst.map((f) => path.basename(f)).join(", ")}` : "its scan"}).`); + say( + stillLive + ? `The landed file matches its stream files (${verifyAgainst.length ? verifyAgainst.map((f) => path.basename(f)).join(", ") : "its scan"}) — the stream SO FAR, not the whole: it is still live.` + : `The landed file is verified whole (${verifyAgainst.length ? `against ${verifyAgainst.map((f) => path.basename(f)).join(", ")}` : "its scan"}).`, + ); // (Nothing on disk is removed for a stream that went private.) if (record.endedBy?.class === "private") for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: the stream went private or was removed`, r.o); else for (const r of toRemove) await removeGroup(r.group, r.why, r.extra); diff --git a/common/lib/liveFragments-server.test.ts b/common/lib/liveFragments-server.test.ts @@ -123,3 +123,33 @@ test("short of disk: the fragments are dropped (resumability goes, the recording assert.equal((await accountStream(s.dir, s.name)).ok, false); assert.deepEqual(fragmentGaps([3, 4, 7, 8, 10], 3), [5, 6, 9]); }); + +test("REVIEW-6 6: an EMPTY kept fragment is no proof, and the file must END with its last fragment's bytes", async () => { + const s = await laid(4); + await writeFile(`${s.file}-Frag3`, ""); + assert.match(((await accountStream(s.dir, s.name)) as { why: string }).why, /fragment 3 .* is empty/); + const t = await laid(4); + // Same sizes, other bytes at the end: not the fragments. + const { open } = await import("node:fs/promises"); + const fh = await open(t.file, "r+"); + await fh.write(Buffer.from("XX"), 0, 2, (await stat(t.file)).size - 2); + await fh.close(); + assert.match(((await accountStream(t.dir, t.name)) as { why: string }).why, /does not end with its fragment 4/); +}); + +test("REVIEW-6 11: with the state unreadable (caught mid-rewrite), nothing is dropped", async () => { + const s = await laid(5); + await writeFile(`${s.file}.ytdl`, "{ half"); + assert.equal(await dropFragments(s.dir, s.name), 0); + assert.equal((await readdir(s.dir)).filter((x) => /-Frag/.test(x)).length, 5); +}); + +test("REVIEW-6 2/3: the fragments past the state go before a resume; a stream file equals its fragments byte for byte, or not", async () => { + const { dropFragmentsAbove, streamEqualsFragments } = await import("./liveFragments-server"); + const s = await laid(6); + await writeFile(`${s.file}-Frag7`, frag(7)); + assert.deepEqual(await dropFragmentsAbove(s.dir, s.name, 6), [7]); + assert.deepEqual(await streamEqualsFragments(s.dir, s.name), { ok: true, fragments: 6 }); + await writeFile(`${s.file}-Frag2`, Buffer.from(frag(2).toString().replace("2", "9"))); + assert.match(((await streamEqualsFragments(s.dir, s.name)) as { why: string }).why, /not fragment 2/); +}); diff --git a/common/lib/liveFragments-server.ts b/common/lib/liveFragments-server.ts @@ -90,9 +90,27 @@ export async function accountStream(dir: string, name: string, names?: readonly let expected = checkpoint.bytes; for (let n = checkpoint.index + 1; n <= idx; n++) { if (!have.has(n)) return { ok: false, why: `fragment ${n} of ${name} is not kept (no byte accounting for it)`, index: idx, size }; - expected += (await sizeOf(path.join(dir, `${name}-Frag${n}`))) ?? 0; + const fs = (await sizeOf(path.join(dir, `${name}-Frag${n}`))) ?? 0; + // REVIEW-6 6: an empty kept fragment is no proof (a crash can leave the + // state flushed and the fragment and the append not). + if (fs === 0) return { ok: false, why: `fragment ${n} of ${name} is empty`, index: idx, size }; + expected += fs; + } + if (size === expected) { + // ... and the file ENDS with the last fragment's bytes. + if (idx > checkpoint.index) { + const last = await readFile(path.join(dir, `${name}-Frag${idx}`)); + const tail = Buffer.alloc(last.length); + const fh = await open(file, "r"); + try { + await fh.read(tail, 0, last.length, size - last.length); + } finally { + await fh.close(); + } + if (!tail.equals(last)) return { ok: false, why: `${name} does not end with its fragment ${idx}`, index: idx, size }; + } + return { ok: true, index: idx, size, expected, checkpoint, kept }; } - if (size === expected) return { ok: true, index: idx, size, expected, checkpoint, kept }; if (size < expected) return { ok: false, why: `${name} is ${size} bytes, its fragments ${expected}: bytes the state counts are not in the file`, index: idx, size, expected }; return { ok: false, why: `${name} is ${size} bytes, ${size - expected} more than its fragments 1..${idx}`, index: idx, size, expected, excess: size - expected, next: idx + 1 }; } @@ -173,11 +191,18 @@ export async function pruneStream(dir: string, name: string, deps: { remove?: (f // kept fragment up to the state's index is deleted, without accounting. export async function dropFragments(dir: string, name: string): Promise<number> { const file = path.join(dir, name); - const idx = await readYtdlIndex(file); + // REVIEW-6 11: read twice (yt-dlp rewrites it); no index, nothing dropped — + // never the fragment being downloaded. + let idx = await readYtdlIndex(file); + if (typeof idx !== "number") { + await new Promise((r) => setTimeout(r, 50)); + idx = await readYtdlIndex(file); + } + if (typeof idx !== "number") return 0; const names = await readdir(dir).catch(() => [] as string[]); let n = 0; for (const k of fragNumbers(name, names)) { - if (typeof idx === "number" && k > idx) continue; + if (k > idx) continue; await rm(path.join(dir, `${name}-Frag${k}`), { force: true }); n++; } diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts @@ -183,7 +183,7 @@ export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, s // recording that holds the whole stream (supersededBy). export function rowNeedsAttention( r: Pick<LiveRecordingRow, "status" | "fallback" | "acknowledgedAt" | "supersededBy"> & - Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost" | "endedBy" | "awaitingResume" | "transcriptRedo" | "verification" | "skippedFragments" | "parts" | "landedWhileLive">>, + Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost" | "endedBy" | "awaitingResume" | "transcriptRedo" | "verification" | "skippedFragments" | "parts" | "landedWhileLive" | "coverage">>, ): boolean { if (r.acknowledgedAt) return false; if (r.keptParts && r.keptParts.length > 0) return true; @@ -195,6 +195,10 @@ export function rowNeedsAttention( if (r.supersededBy) return false; // DESIGN-5 4: landed while the stream was still live — until acknowledged. if (r.landedWhileLive) return true; + // REVIEW-6 4: landed SHORT of an ended stream's own duration — the rest is + // in no file (and the archive line stops any later download): a person, + // "download the VOD now". + if (r.status === "landed" && r.coverage?.basis === "duration" && r.coverage.covers === false) return true; // Parts left in staging with their state, to be resumed: a resume, or a // person (DESIGN-3; a later run that did not resume them lists them too). if (r.awaitingResume && r.awaitingResume.length) return true;