Archilyzer · Source

archilyzer

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

commit c2761b3b1d73fc55bbddab48bfdb46e54332a7e8
parent b675800f72143e62446ee795ad955647d4b32533
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sun, 22 Nov 2026 03:13:56 -0500

record-live: DESIGN-5 — an exit while live is never "the whole stream"; the restart reuses what is downloaded; went-private

- 1: any exit with bytes, a partial one included, is followed by a state
  read. Live, or a read that fails, gives a next part at once, for as
  long as the platform says live. 429 and the bot check still stop it,
  loudly.
- 2: a `url-refresh` failure class ("Cannot find refreshed url for format
  N … Giving up after N retries"), caught as the line is printed and said
  in plain words on the part and the row.
- 3/4: a landing made while the last state read says live (a cancel, a
  shutdown, a refusal) is `landedWhileLive` {at, unrecordedSeconds by the
  clock, why}. It needs a person until acknowledged, supersedes nothing,
  and its words say "so far".
- 7: every fragment is kept until the stream is confirmed done (the
  platform says over AND the landed file is verified). The watchdog's
  prune is off; short of disk the fragments are dropped, loudly.
  - A self-exit (merged, the state removed) is resumed in place: the state
    is rebuilt at the fragment count the kept fragments prove and the
    merged copy is moved aside. This was measured on the installed yt-dlp:
    without both steps it records nothing or fails at fragment 1; with
    them it is byte-identical to a straight download.
  - A Record again reuses a part an earlier run left the same way.
  - A fresh part says how much stream it fetches again.
- (c): `went-private`: fragment 403s, then a private or removed read
  confirmed. What is on disk lands, loud, never retried in a loop, and
  nothing on disk is removed.
- The tests of the live-edge path make reuse impossible (a kept fragment
  removed). The partial-attempts test now restarts while live. The fake
  models yt-dlp's "already downloaded" and its 416 at fragment 1.

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

Diffstat:
MOPERATING.md | 24+++++++++++++++++++-----
Mcommon/controller/liveRecordings.ts | 13+++++++++++++
Mcommon/controller/recordLive.test.ts | 250++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------
Mcommon/controller/recordLive.ts | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Mcommon/lib/liveCapture.ts | 24+++++++++++++++++++++++-
Mcommon/lib/liveRecordings-server.ts | 9+++++++--
Meditor/CHANGELOG.md | 6++++++
7 files changed, 462 insertions(+), 93 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1506,11 +1506,11 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note": 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. Once - a minute the watchdog writes and fsyncs the checkpoint, THEN deletes the fragments it covers (the disk grows by at - most a minute of fragments between two checks: tens of MB at the live edge, up to ~750 MB a minute while catching - up at 100 Mbit/s). Short of disk (under the floor) the fragments are dropped — the recording goes on, the part can - no longer be resumed in place, and the row says so (`fragmentsDropped`). A fragment that cannot be fetched stops the + 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 @@ -1520,6 +1520,20 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note": 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 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 + sentence on the row. ANY exit with bytes (exit 0, a partial one included) is followed by a state read; live (or a + read that fails), the recording goes on, for as long as the platform says live (429 and the bot check still stop it, + loudly). The restart REUSES what is downloaded: yt-dlp skips the fragments its `.ytdl` state counts, so after a + self-exit (it removed that state) the editor writes it again at the count the kept fragments prove (each stream file + equal to its fragments 1..N) and moves the merged copy aside (left at its final name yt-dlp would say "already + downloaded" and record nothing) — the same files continue, no catch-up from fragment 0; a Record again does the same + with a part an earlier run left. Only when nothing can be proven does a fresh part from the start record, and the + log says how much stream it fetches again. A landing made while the last read says live (a Cancel, a shutdown, a + refusal) is `landedWhileLive` (when, why, how much of the stream by the clock is in no landed file), needs a person + until acknowledged, supersedes nothing, and every line says "so far"; nothing reusable (stream files, state, + 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; diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -190,6 +190,17 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: (v.status === "interrupted" ? "" : " — not resumed by this run: a person decides"), ); } + if (v.landedWhileLive) { + const u = v.landedWhileLive.unrecordedSeconds; + extra.unshift( + `LANDED WHILE THE STREAM WAS STILL LIVE (${v.landedWhileLive.why})${u !== null ? `: about ${spanWords(u)} of it, by the clock, were in no landed file at that moment` : ""} — what is landed is the stream SO FAR, not the whole`, + ); + } + for (const p of v.parts ?? []) { + if (p.failureClass === "went-private") extra.push(`${p.stem ?? "a part"}: its fragment requests were answered 403 Forbidden and the stream reads private or removed — it went private while it was recorded; what is on disk is landed and nothing is removed`); + if (p.failureClass === "url-refresh") extra.push(`${p.stem ?? "a part"}: yt-dlp could not refresh the stream's URL (the platform stopped serving the format — DVR switched off?) and ended by itself`); + if (p.reused) extra.push(`${p.stem ?? "a part"} was resumed after it had ended, reusing ${p.reused.fragments} fragments already downloaded (only what came since was fetched)`); + } if (v.skippedFragments?.count) { extra.unshift(`the landed file is missing ${v.skippedFragments.count} fragment(s) yt-dlp could not fetch${v.skippedFragments.positions.length ? ` (positions ${v.skippedFragments.positions.slice(0, 10).join(", ")}${v.skippedFragments.positions.length > 10 ? ", …" : ""})` : ""}: a HOLE`); } @@ -381,6 +392,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO ...(own?.transcriptRedo ? { transcriptRedo: own.transcriptRedo } : {}), ...(own?.verification ? { verification: own.verification } : {}), ...(own?.skippedFragments ? { skippedFragments: own.skippedFragments } : {}), + ...(own?.landedWhileLive ? { landedWhileLive: own.landedWhileLive } : {}), attempts: own?.attempts ?? row.attempts, parts, slug, @@ -408,6 +420,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO verification: own?.verification ?? row.verification, skippedFragments: own?.skippedFragments ?? row.skippedFragments, parts: own?.parts ?? row.parts, + landedWhileLive: own?.landedWhileLive ?? row.landedWhileLive, }), }; const shown = diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -1975,16 +1975,20 @@ test("slice 5: an unprovable join — the sound does not match, or the joined fi assert.deepEqual((await left(id2)).map((n) => /ytdlp-edge-a4\.mp4$/.test(n)), [true]); }); -test("slice 3: attempts that each recorded only one of the two streams are not restarted after the schedule, even with the stream live", async () => { +test("slice 3 / DESIGN-5 1: attempts that each record only one of the two streams — while the stream reads live the recording goes on past the schedule (never ended quietly); when it ends, the row is loud about the missing stream", async () => { const id = "exmplpart02"; + let n = 0; const videoOnly: Attempt = async (args) => { + n++; await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=45;a=none;"); return { exitCode: 1, stderrTail: "2: ERROR: The downloaded file is empty\n", signalled: false }; }; - const { run, calls } = await incidentRun(id, videoOnly, { deps: FAST_WATCH, refresh: { stillLive: () => true } }); - await assert.rejects(run, /audio stream recorded nothing/); - assert.equal(calls.length, 6, "the schedule only: no restart on top of it"); - assert.equal((await rowOf(id))[0]!.restarts, undefined); + const { run, calls } = await incidentRun(id, videoOnly, { deps: { ...FAST_WATCH, freshFromStart: false }, refresh: { stillLive: () => n < 9 } }); + await run.catch(() => {}); + assert.ok(calls.length > 6, `restarted past the schedule while live: ${calls.length}`); + const row = (await rowOf(id))[0]!; + assert.ok((row.restarts?.count ?? 0) > 0); + assert.equal(row.needsAttention, true); }); // --- REVIEW-1 of live-guard-2: the store, containment, and the join's proof -------- @@ -2734,6 +2738,8 @@ const FAKE_A = "f140.m4a"; const dropState = async (args: string[]) => { for (const f of [FAKE_V, FAKE_A]) await rm(`${outOf(args)}.${f}.ytdl`, { force: true }); }; +// Nothing provable to reuse either (DESIGN-5 7): a kept fragment gone. +const noReuse = async (args: string[]) => rm(`${outOf(args)}.${FAKE_V}-Frag2`, { force: true }); const fakeMerge = async (args: string[]) => { const ins = args.flatMap((a, k) => (a === "-i" ? [args[k + 1]!] : [])); let sec = 0; @@ -2824,6 +2830,20 @@ function resumableYtdlp( await rm(`${f}.ytdl`, { force: true }); } }; + if (fromStart) { + // As measured (LOG, DESIGN-5 point 7): the merged file at its final name + // and no state — "has already been downloaded", nothing recorded, exit 0; + // stream files with bytes and no state — fragment 1 asked again by + // Range, a 416, fatal. + const st = await readFile(`${files.video}.ytdl`, "utf8").catch(() => null); + if (!st && (await stat(`${out}.mp4`).catch(() => null))) { + onLine?.(`[download] ${out}.mp4 has already been downloaded`); + return okExit; + } + if (!st && ((await stat(files.video).catch(() => null))?.size ?? 0) > 0 && resumedFrom === null && count.video === 0 && (await stat(`${files.video}-Frag1`).catch(() => null))) { + return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 416: Range Not Satisfiable. Giving up after 10 retries\n", signalled: false }; + } + } const what = await script({ n, resumedFrom, write, writeStream, tear, print: (l) => onLine?.(l), signal, args }); if (what === "die") return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; if (what === "end") { @@ -2959,6 +2979,7 @@ test("DESIGN-3: no state to resume (the part was finished) — the fallback: a l await write(7200); // It finished (the state went), then exited 1. await dropState(args); + await noReuse(args); return "die"; } await write(300); @@ -3021,6 +3042,7 @@ test("DESIGN-3 fallback (REVIEW-4 3.1): a hole of minutes on a long stream is no if (n === 1) { await write(9 * 3600 - 300); await dropState(args); + await noReuse(args); return "die"; } if (isRecovery(args)) { @@ -3050,6 +3072,7 @@ test("DESIGN-3 fallback (REVIEW-4 1.1): the gap recovery's first try waits until if (n === 1) { await write(60); await dropState(args); + await noReuse(args); return "die"; } if (isRecovery(args)) { @@ -3533,41 +3556,25 @@ test("flow: an editor shutdown stops a from-start run, the BOOT PASS resumes it assert.equal(old.needsAttention, false, "the interruption is superseded by the whole"); }); -test("B3: a part an earlier run left waiting is RELEASED by a later run that does not resume it: landed by the landing rules (here inside the whole), never left as the only copy in staging", { timeout: 60_000 }, async () => { +test("B3 / DESIGN-5 7: a part an earlier run left waiting is never left as the only copy in staging: a later run (a Record again) REUSES it — the same files continued — and lands the whole", { timeout: 60_000 }, async () => { const id = "exmplflowa2"; - const ac = new AbortController(); - const first = await incidentRun( - id, - resumableYtdlp(async ({ write, signal }) => { - await write(3000); - setTimeout(() => ac.abort(), 10); - await abortOf(signal); - return { exitCode: null, stderrTail: "", signalled: true }; - }), - { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, - ); - await first.run; - assert.ok((await left(id)).some((n) => n.endsWith(".ytdl"))); - // A person's Record again (no resume): its own whole from-start file. + const { stem } = await waitingAtShutdown(id, 3000); let live = true; const again = await incidentRun( id, - async (args) => { - await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;"); + resumableYtdlp(async ({ resumedFrom, write }) => { + assert.equal(resumedFrom, 51, "from what the earlier run downloaded"); + await write(7200); live = false; - return okExit; - }, + return "end"; + }), { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await again.run).status, "landed"); + assert.equal(outOf(again.calls[0]!), stem, "the same files"); assert.equal(await storedSeconds(id), 7200); - assert.deepEqual(await left(id), [], "the released part was merged and, inside the whole, removed"); - const rows = await rowOf(id); - const row = rows.find((r) => r.status === "landed")!; - assert.ok(row.removedParts?.some((r) => r.stem === path.basename(outOf(first.calls[0]!)))); - assert.equal(row.awaitingResume, undefined); - assert.ok(rows.every((r) => !r.awaitingResume), "no row says a part waits"); - assert.ok(rows.every((r) => !r.needsAttention)); + assert.deepEqual(await left(id), [], "confirmed done: nothing left"); + assert.ok((await rowOf(id)).every((r) => !r.awaitingResume), "no row says a part waits"); }); async function replacedOverShutdown(id: string, transcript: string | null, requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>) { @@ -3787,8 +3794,10 @@ test("B3: the boot resume takes the LONGEST resumable from-start part of any row const ac = new AbortController(); const b = await incidentRun( id, - resumableYtdlp(async ({ write, signal }) => { - await write(1000); + resumableYtdlp(async ({ resumedFrom, write, signal }) => { + // (DESIGN-5 7: it continues the earlier waiting part, the longest.) + assert.equal(resumedFrom, 51); + await write(3600); setTimeout(() => ac.abort(), 10); await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; @@ -3796,14 +3805,15 @@ test("B3: the boot resume takes the LONGEST resumable from-start part of any row { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); await b.run; + assert.equal(outOf(b.calls[0]!), a.stem, "the second run continued the first's part"); const rowB = (await rowOf(id)).find((x) => x.startedAt !== a.startedAt)!; - assert.equal(rowB.awaitingResume?.length, 2, "both wait, listed on the newest row"); + assert.equal(rowB.awaitingResume?.length, 1, "that part waits again, listed on the newest row"); await askBoot(id, rowB.startedAt); let live = true; const c = await incidentRun( id, resumableYtdlp(async ({ resumedFrom, write }) => { - assert.equal(resumedFrom, 51, "the 3000 s part, the longest, is resumed"); + assert.equal(resumedFrom, 61, "the part, now 3600 s, is resumed"); await write(7200); live = false; return "end"; @@ -3961,7 +3971,7 @@ test("REVIEW-5 note 3: the restart bound reached on a stream still live does not const isFresh = (args: string[]) => /\.ytdlp-f\d+$/.test(outOf(args)); -test("DESIGN-4 2: a from-start part with nothing to resume (it finished, then died) while the stream is live — a FRESH part from the start (a new stem, proven), never the live edge; the whole lands and covers", { timeout: 60_000 }, async () => { +test("DESIGN-4 2: a from-start part with nothing to resume or reuse (no state, a kept fragment gone) while the stream is live — a FRESH part from the start (a new stem, proven), never the live edge; the whole lands and covers", { timeout: 60_000 }, async () => { const id = "exmpld4fr01"; let live = true; const { run, calls } = await incidentRun( @@ -3970,6 +3980,8 @@ test("DESIGN-4 2: a from-start part with nothing to resume (it finished, then di if (n === 1) { await write(3000); await dropState(args); + // Nothing provable to reuse either: a kept fragment is gone. + await rm(`${outOf(args)}.${FAKE_V}-Frag20`, { force: true }); return "die"; } assert.ok(fromStartArg(args) && isFresh(args), `call ${n}: a fresh from-start part`); @@ -4059,7 +4071,7 @@ test("DESIGN-4 1: an excess that is NOT the start of the next kept fragment, or } }); -test("DESIGN-4 1: while recording, verified fragments are pruned after a checkpoint; short of disk, the fragments are DROPPED (loud) and the recording goes on, no longer resumable in place", { timeout: 60_000 }, async () => { +test("DESIGN-4 1 / DESIGN-5 7: while recording EVERY fragment is kept (nothing pruned until the stream is confirmed done); short of disk they are DROPPED (loud), the recording goes on, no longer resumable in place", { timeout: 60_000 }, async () => { const id = "exmpld4prn1"; let live = true; let free = 1e15; @@ -4072,7 +4084,6 @@ test("DESIGN-4 1: while recording, verified fragments are pruned after a checkpo await new Promise((r) => setTimeout(r, 150)); const names = await readdir(store()); seenFrags.push(names.filter((x) => x.startsWith(path.basename(`${outOf(args)}.${FAKE_V}-Frag`))).length); - assert.ok(names.includes(path.basename(`${outOf(args)}.${FAKE_V}.frags.json`)), "a checkpoint"); free = 1e9; await write(3600); await new Promise((r) => setTimeout(r, 150)); @@ -4084,11 +4095,11 @@ test("DESIGN-4 1: while recording, verified fragments are pruned after a checkpo live = false; return "end"; }), - // (No stall while it waits on purpose: the prune is what is watched.) + // (No stall while it waits on purpose.) { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, freeBytes: async () => free }, refresh: { stillLive: () => live } }, ); await run.catch(() => {}); - assert.ok(seenFrags[0]! < 51, `pruned: ${seenFrags[0]} fragments left of 51`); + assert.equal(seenFrags[0], 51, "all 51 kept while recording"); const row = (await rowOf(id))[0]!; assert.match(row.parts[0]!.fragmentsDropped ?? "", /free/); assert.notEqual(outOf(calls[1]!), outOf(calls[0]!), "not resumed in place: its fragments were dropped"); @@ -4181,7 +4192,7 @@ test("DESIGN-4 4: the landed file NOT verified whole — nothing removed: its st assert.match(row.reason, /NOT verified whole/); }); -test("DESIGN-4 5: a from-start recorder that ends by itself (an ingest pause, no state) while the stream is live — the insurance holds the live edge BEFORE the confirming read, then a fresh part from the start", { timeout: 60_000 }, async () => { +test("DESIGN-4 5: a from-start recorder that ends by itself (an ingest pause, no state) while the stream is live — the insurance holds the live edge BEFORE the confirming read, then the same files continued (reused), never fragment 0", { timeout: 60_000 }, async () => { const id = "exmpld4ing1"; let live = true; const order: string[] = []; @@ -4200,7 +4211,7 @@ test("DESIGN-4 5: a from-start recorder that ends by itself (an ingest pause, no await new Promise((r) => setTimeout(r, 30)); return "end"; } - order.push(isFresh(args) ? "fresh" : "other"); + order.push(isFresh(args) ? "fresh" : "resume"); await write(7200); live = false; return "end"; @@ -4215,10 +4226,11 @@ test("DESIGN-4 5: a from-start recorder that ends by itself (an ingest pause, no }, ); await run.catch(() => {}); - assert.ok(calls.some(isFresh), "a fresh part from the start, not the live edge"); - const ins = order.lastIndexOf("insurance"); - const conf = order.indexOf("confirm-read"); - assert.ok(ins >= 0 && conf >= 0 && order.indexOf("insurance") < order.indexOf("fresh"), `order: ${order.join(" → ")}`); + // (DESIGN-5 7: the same files continued, reusing what is downloaded.) + const mains = calls.filter((c) => !isInsurance(c)); + assert.equal(outOf(mains[1]!), outOf(mains[0]!), "the same files, not a fresh part"); + const ins = order.indexOf("insurance"); + assert.ok(ins >= 0 && order.indexOf("confirm-read") >= 0 && ins < order.indexOf("resume"), `order: ${order.join(" → ")}`); }); test("note 4: at a shutdown with a part waiting, NOTHING lands — the other part waits too, for the restart", { timeout: 60_000 }, async () => { @@ -4294,3 +4306,149 @@ test("slice 2, the other order: the from-start try ends BEFORE the live edge doe const row = (await rowOf(id))[0]!; assert.equal(row.startRecovery?.state, "recorded"); }); + +// --- DESIGN-5: a recorder that ends by itself while the stream is live ------------------ + +const REFRESH_FAIL = [ + "WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Retrying (1/3)...", + "WARNING: [youtube] Cannot find refreshed url for format 136; please report this issue. Retrying (1/3)...", + "WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Giving up after 3 retries", +]; + +test("DESIGN-5 1/2/7: yt-dlp gives up refreshing the URL, merges and exits 0 while the stream is live — never landed as whole; classed url-refresh in plain words; the SAME files resumed reusing every fragment downloaded, again and again while it is live", { timeout: 60_000 }, async () => { + const id = "exmpld5url1"; + let live = true; + const resumed: (number | null)[] = []; + const { run, calls, log } = await incidentRun( + id, + resumableYtdlp(async ({ n, resumedFrom, write, print }) => { + resumed.push(resumedFrom); + // (The stream is 2 h old: the last part reaches its end.) + await write(n < 4 ? 3000 + (n - 1) * 1200 : 7200); + if (n < 4) { + for (const l of REFRESH_FAIL) print(l); + return "end"; // merged, the state removed, exit 0 — the stream goes on + } + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + const s = await run; + assert.equal(s.status, "landed"); + assert.equal(calls.length, 4, "three self-exits while live: three restarts"); + assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "the same files every time"); + assert.deepEqual(resumed, [null, 51, 71, 91], "each restart from what is on disk, never fragment 0"); + assert.ok(log.some((l) => /could not refresh the stream's URL for format 140/.test(l))); + const row = (await rowOf(id))[0]!; + assert.equal(row.parts[0]!.failureClass, "url-refresh"); + assert.equal(row.parts[0]!.reused?.fragments, 91, "the last reuse"); + assert.match(row.reason, /could not refresh the stream's URL/); + assert.equal(row.landedWhileLive, undefined, "landed once the stream was over"); + assert.equal(row.coverage?.covers, true); + assert.deepEqual(await left(id), [], "confirmed done: the streams, fragments and merged copies go"); +}); + +test("DESIGN-5 1: a partial exit (one stream missing) while the stream is live restarts — never a landing", { timeout: 60_000 }, async () => { + const id = "exmpld5par1"; + let live = true; + const { run, calls } = await incidentRun( + id, + resumableYtdlp(async ({ n, writeStream, write, args }) => { + if (n === 1) { + await writeStream("audio", 600); + await rm(`${outOf(args)}.${FAKE_V}`, { force: true }); + await rm(`${outOf(args)}.${FAKE_V}.ytdl`, { force: true }); + return { exitCode: 1, stderrTail: "ERROR: The downloaded file is empty\n", signalled: false }; + } + await write(7200); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + await run.catch(() => {}); + assert.ok(calls.length >= 2, "restarted"); + const row = (await rowOf(id))[0]!; + assert.equal(row.landedWhileLive, undefined); +}); + +test("DESIGN-5 3/4/7: a Cancel while the stream is live — landed, but `landedWhileLive` with the unrecorded time, loud, never 'the whole stream', no superseding; the stream files and fragments kept; a Record again then REUSES them", { timeout: 60_000 }, async () => { + const id = "exmpld5cnl1"; + const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server"); + await ytChannel(); + await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt: "2026-11-20T01:00:00.000Z", status: "failed", fromStart: true, attempts: 1, mustKeep: true, parts: [] }); + const ac = new AbortController(); + const a = await incidentRun( + id, + resumableYtdlp(async ({ write }) => { + await write(3000); + setTimeout(() => ac.abort(), 10); + // SIGINT: yt-dlp finishes (merged, its state removed). + return "hang"; + }), + { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => true } }, + ); + await a.run.catch(() => {}); + const rows = await rowOf(id); + const row = rows.find((r) => r.startedAt !== "2026-11-20T01:00:00.000Z")!; + assert.ok(row.landedWhileLive, "landed while live"); + assert.ok((row.landedWhileLive!.unrecordedSeconds ?? 0) > 3000, `unrecorded by the clock: ${row.landedWhileLive!.unrecordedSeconds}`); + assert.match(row.landedWhileLive!.why, /cancelled/); + assert.equal(row.needsAttention, true); + assert.match(row.reason, /LANDED WHILE THE STREAM WAS STILL LIVE/); + assert.ok(!a.log.some((l) => /holds the whole stream/.test(l)), "no claim of wholeness"); + assert.equal(rows.find((r) => r.startedAt === "2026-11-20T01:00:00.000Z")!.supersededBy, undefined, "supersedes nothing"); + const stem = outOf(a.calls[0]!); + assert.ok((await left(id)).some((n) => n === path.basename(`${stem}.${FAKE_V}`)), "the stream files are kept for reuse"); + assert.ok((await left(id)).some((n) => n === path.basename(`${stem}.${FAKE_V}-Frag51`)), "and the fragments"); + // A person's Record again: the kept part is resumed, not fragment 0. + let live = true; + const b = await incidentRun( + id, + resumableYtdlp(async ({ resumedFrom, write }) => { + assert.equal(resumedFrom, 51, "reused"); + await write(7200); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + assert.equal((await b.run).status, "landed"); + assert.equal(outOf(b.calls[0]!), stem, "the same files"); + const last = (await rowOf(id)).find((r) => r.status === "landed" && !r.landedWhileLive)!; + assert.equal(last.parts[0]!.reused?.fragments, 51); +}); + +test("DESIGN-5 2: the url-refresh class", async () => { + const { liveFailureClass: liveFailureClassOf } = await import("../lib/liveCapture"); + assert.equal(liveFailureClassOf("WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Giving up after 3 retries"), "url-refresh"); +}); + +test("DESIGN-5 (c): fragments answered 403 while recording, then a read says private — `went-private`: what is on disk lands, loud, no retry loop, NOTHING on disk removed", { timeout: 60_000 }, async () => { + const id = "exmpld5prv1"; + const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`; + const { run, calls, waits } = await incidentRun( + id, + resumableYtdlp(async ({ write, print, signal }) => { + await write(3000); + for (let k = 1; k <= 3; k++) print(`1: [download] Got error: HTTP Error 403: Forbidden. Retrying fragment 52 (${k}/10)...`); + print("1: ERROR: [download] Got error: HTTP Error 403: Forbidden"); + await abortOf(signal); + return { exitCode: null, stderrTail: "", signalled: true }; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failAfterFirst: PRIVATE } }, + ); + await run.catch(() => {}); + assert.equal(calls.length, 1, "never retried in a loop"); + assert.ok(waits.includes(60_000), "the private read confirmed a minute later"); + assert.equal(await storedSeconds(id), 3000, "what is on disk is landed"); + const row = (await rowOf(id))[0]!; + assert.equal(row.failureClass, "went-private"); + assert.equal(row.parts[0]!.failureClass, "went-private"); + assert.equal(row.endedBy?.class, "private"); + assert.equal(row.needsAttention, true); + assert.match(row.reason, /went private while it was recorded/); + const files = await left(id); + assert.ok(files.some((n) => n.endsWith(`.${FAKE_V}`)) && files.some((n) => n.endsWith(`.${FAKE_V}-Frag51`)), `nothing on disk removed: ${files.length} files`); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -53,7 +53,7 @@ import path from "node:path"; import { spawn } from "node:child_process"; import { createWriteStream } from "node:fs"; -import { mkdir, open, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises"; +import { mkdir, open, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises"; import { uptime } from "node:os"; import { execa } from "execa"; import type { ChannelConfig } from "../lib/channelConfig"; @@ -113,7 +113,7 @@ import { import { WHISPER_FILENAME } from "../lib/videoStatus"; import { parseTranscriptJson } from "../lib/whisper"; import { readStoredText } from "../lib/storedText-server"; -import { dropFragments, fragmentGaps, fragNumbers, pruneStream, readYtdlIndex, reconcileStream } from "../lib/liveFragments-server"; +import { accountStream, dropFragments, fragmentGaps, fragNumbers, readYtdlIndex, reconcileStream } from "../lib/liveFragments-server"; import { verifyMerged, verifyScan } from "../lib/liveVerify-server"; import { liveJoinsSidecar, liveRecordingSidecar } from "../lib/mediaImport-server"; import { ffmpegJoinDeps, joinLiveParts, type JoinDeps } from "./liveJoin"; @@ -1167,6 +1167,17 @@ async function recordLiveRunInner( endRead = true; endedByRefusal = true; hooks.record!.endedBy = { class: c, message: msg.split("\n")[0]!.slice(0, 300), at: now().toISOString() }; + // DESIGN-5 (c): its fragments answered 403 before this read: it went + // private while it was recorded. + if (c === "private") { + for (const p of hooks.record!.parts) { + if ((p.fragment403 ?? 0) > 0) { + p.failureClass = "went-private"; + p.error = `its fragment requests were answered 403 Forbidden, and the stream reads private or removed: it went private while it was recorded`; + } + } + if (hooks.record!.parts.some((p) => p.failureClass === "went-private")) hooks.record!.failureClass = "went-private"; + } await hooks.save?.(); say(`The stream ${c === "ended" ? "is over" : "went private or was removed"} while it was recorded (${msg.split("\n")[0]}): what is held lands, and the row needs a person.`); return "ended"; @@ -1247,6 +1258,8 @@ async function recordLiveRunInner( const first = lastErr.message.split("\n")[0]!.slice(0, 240); 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; 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`; @@ -1548,7 +1561,7 @@ async function recordLiveRunInner( // finishes its file. const resumable = mode === "from-start"; const stopHow = async (): Promise<"SIGTERM" | "SIGINT"> => - resumable && separate && (await resumeStateOf(stem).catch(() => ({ ok: false }))).ok ? "SIGTERM" : "SIGINT"; + resumable && separate && (await resumeStateOf(stem, { accounting: false }).catch(() => ({ ok: false }))).ok ? "SIGTERM" : "SIGINT"; const own = new AbortController(); const onJobAbort = () => { if (!(resumable && stopOf(deps).by === "shutdown")) return own.abort("SIGINT"); @@ -1561,14 +1574,13 @@ async function recordLiveRunInner( signal.addEventListener("abort", onJobAbort, { once: true }); opts.stop?.addEventListener("abort", onOwnStop, { once: true }); } - // DESIGN-4 1 — THE KEPT FRAGMENTS, once a watch tick: each stream file's - // verified fragments are deleted after its checkpoint is written and - // fsynced (pruneStream). Between two ticks the disk grows by at most one - // tick of fragments (a minute of stream at the live edge, ~25-45 MB at - // 720p; up to a minute of download while catching up, ~750 MB at - // 100 Mbit/s). Short of disk (under the floor) the recorder goes on and - // the fragments go — resumability lost, said, the row loud — never the - // reverse. A fragment number missing among the kept ones is a skip. + // DESIGN-4 1 / DESIGN-5 7 — THE KEPT FRAGMENTS, once a watch tick: every + // fragment stays until the stream is confirmed done (the platform says it + // is over AND the landed file is verified) — the bytes a restart reuses. + // The stream files plus their fragments are twice the stream on disk. + // Short of disk (under the floor) the recorder goes on and the fragments + // go — resumability lost, said, the row loud — never the reverse, never + // silently. A fragment number missing among the kept ones is a skip. const keptFragmentsTick = async () => { const g = await filesOf(stem); if (!g) return; @@ -1586,20 +1598,20 @@ async function recordLiveRunInner( await dropFragments(slugStore, f).catch(() => 0); continue; } - const r = await pruneStream(slugStore, f).catch((e: Error) => ({ pruned: 0 as const, why: e.message })); - if ("why" in r && /is not kept/.test(r.why)) { - const names = await readdir(slugStore).catch(() => [] as string[]); - const idx = await readYtdlIndex(path.join(slugStore, f)); - const kept = fragNumbers(f, names).filter((n) => typeof idx !== "number" || n <= idx); - const gaps = fragmentGaps(kept, kept.length ? Math.min(...kept) : 1); - if (gaps.length) { - const sf = (part.skippedFragments ??= { count: 0, positions: [] }); - for (const n of gaps) if (!sf.positions.includes(n)) { - sf.positions.push(n); - sf.count += 1; - } - await writeStemMarks(slugStore, stem, { skipped: sf }); + // DESIGN-5 7: NO prune while recording — every fragment stays until + // the stream is confirmed done; a number missing among them is a skip. + const names = await readdir(slugStore).catch(() => [] as string[]); + const idx = await readYtdlIndex(path.join(slugStore, f)); + const kept = fragNumbers(f, names).filter((n) => typeof idx !== "number" || n <= idx); + const gaps = kept.length ? fragmentGaps(kept, 1) : []; + if (gaps.length) { + const sf = (part.skippedFragments ??= { count: 0, positions: [] }); + for (const n of gaps) { + if (sf.positions.includes(n)) continue; + sf.positions.push(n); + sf.count += 1; } + await writeStemMarks(slugStore, stem, { skipped: sf }); } } }; @@ -1689,6 +1701,18 @@ async function recordLiveRunInner( if (sf.positions.length < 200) sf.positions.push(Number(skip[1])); void writeStemMarks(slugStore, stem, { skipped: sf }); } + // DESIGN-5 2: the URL could not be refreshed — said in plain words, on + // the part, as it is printed (the last lines before the exit are the + // merge's, not this). + const refresh = /Cannot find refreshed url for format (\S+?)[;,]/i.exec(l); + if (refresh || (/Giving up after \d+ retries/i.test(l) && part.failureClass === "url-refresh")) { + if (part.failureClass !== "url-refresh") { + part.failureClass = "url-refresh"; + part.error = `yt-dlp could not refresh the stream's URL for format ${refresh?.[1] ?? "?"}: the platform stopped serving it (its DVR switched off?); yt-dlp then ends by itself`; + say(`[${tag}] ${part.error}.`); + } + } + if (/HTTP Error 403: Forbidden/i.test(l) && /fragment/i.test(l)) part.fragment403 = (part.fragment403 ?? 0) + 1; if (/^(?:\d+:\s*)?ERROR: \[download\] Got error|fragment \d+ not found, unable to continue/i.test(l)) { part.fragmentErrors = (part.fragmentErrors ?? 0) + 1; if (!fragAbort && !own.signal.aborted) { @@ -1768,7 +1792,9 @@ async function recordLiveRunInner( // (downloader/fragment.py), the stream is under 120 h old (past that the // from-start generator starts later and the saved index would misalign, // extractor/youtube/_video.py), and the ids on disk pin the format. - const resumeStateOf = async (stem: string): Promise<{ ok: true; formats: string; fragment: number } | { ok: false; why: string }> => { + // `accounting` false: the structure only (the stop signal's choice, made + // while the recorder still writes — the byte equation is for a stopped file). + const resumeStateOf = async (stem: string, o: { accounting?: boolean } = {}): Promise<{ ok: true; formats: string; fragment: number } | { ok: false; why: string }> => { const g = await filesOf(stem); if (!g) return { ok: false, why: "its files are gone" }; // EVERY stream file of the stem, an empty one included (REVIEW-5 B5): @@ -1830,12 +1856,53 @@ async function recordLiveRunInner( if (dropped) return { ok: false, why: `its kept fragments were dropped (${dropped})` }; const skipped = marks.skipped?.count ?? mine?.skippedFragments?.count ?? 0; if (skipped > 0) return { ok: false, why: `it skipped ${skipped} fragment(s)` }; - for (const f of streams) { - const r = await reconcileStream(slugStore, f, false); - if (!r.ok) return { ok: false, why: r.why }; + if (o.accounting !== false) { + for (const f of streams) { + const r = await reconcileStream(slugStore, f, false); + if (!r.ok) return { ok: false, why: r.why }; + } } return { ok: true, formats: ids.join("+"), fragment: Number.isFinite(fragment) ? fragment : 0 }; }; + // DESIGN-5 7 — REUSE AFTER A SELF-EXIT: yt-dlp finished the part (merged, + // its `.ytdl` removed) while the stream went on. Measured (LOG, point 7): + // the same -o reuses what is on disk only with a state whose index is right + // and the merged copy NOT at its final name (else "already downloaded" and + // nothing is recorded). So each kept stream file must equal its kept + // fragments 1..N exactly (contiguous); then its state is written at N and + // the merged copies are moved aside (scratch, until confirmed done). + // `apply` false: whether it can be. + const restoreForReuse = async (stem: string, apply: boolean): Promise<{ ok: true; fragments: number } | { ok: false; why: string }> => { + const g = await filesOf(stem); + if (!g || g.streams.length < (separate ? 2 : 1)) return { ok: false, why: "its stream files were not kept" }; + const names = await readdir(slugStore).catch(() => [] as string[]); + const counts: number[] = []; + 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)` }; + 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` }; + let sum = 0; + for (let n = 1; n <= k; n++) sum += await sizeOf(path.join(slugStore, `${f}-Frag${n}`)); + const size = await sizeOf(file); + if (sum !== size) return { ok: false, why: `${f} is ${size} bytes, its ${k} kept fragments ${sum}` }; + counts.push(k); + } + if (apply) { + for (const [i, f] of g.streams.entries()) { + await writeFile(path.join(slugStore, `${f}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: counts[i] } } })); + } + const stamp = Date.now(); + 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.`); + } + return { ok: true, fragments: Math.min(...counts) }; + }; // The one repair (DESIGN-4 1), made just before a resume: a torn last // append truncated back, logged with both lengths. Anything it cannot // prove: no resume in place. @@ -2319,29 +2386,44 @@ async function recordLiveRunInner( // DESIGN-3: a restart after the editor's resumes the interrupted run's // from-start part in place when its state is there. let bootResume: { stem: string; formats: string; provenStart?: boolean } | null = null; - if (resumeOf && slot === 0 && mode === "from-start" && n === 1) { + let reusedFragments: number | null = null; + // DESIGN-5 7: ANY run's first from-start attempt (a Record again too) + // reuses a part an earlier run left in staging when it can be proven. + if (slot === 0 && mode === "from-start" && n === 1 && (resumeOf || separate)) { // REVIEW-5 B3: of every row of the id, the LONGEST resumable // from-start part — a stem any row lists as waiting, or a from-start // part of the interrupted row. The others are released to the landing. const rows = (await loadLiveRecordingRows(paths, req.slug).catch(() => [])).filter((r) => r.id === id); const partOfStem = new Map(rows.flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x])); + const inStaging = new Set(livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])).map((g) => g.stem)); const stems = new Set<string>([ ...rows.flatMap((r) => r.awaitingResume ?? []), ...(rows.find((r) => r.startedAt === resumeOf)?.parts ?? []).filter((x) => x.stem && x.fromStart && !x.index0).map((x) => x.stem!), + // Every proven from-start part of the id still in staging. + ...(separate ? rows.flatMap((r) => r.parts).filter((x) => x.stem && x.provenStart && x.fromStart && !x.index0 && inStaging.has(x.stem)).map((x) => x.stem!) : []), ]); - let best: { stem: string; formats: string; fragment: number; bytes: number } | null = null; + let best: { stem: string; formats: string; fragment: number; bytes: number; reuse?: boolean } | null = null; for (const stem of stems) { const st = await resumeStateOf(stem); - if (!st.ok) continue; + const ru = st.ok || !separate ? null : await restoreForReuse(stem, false); + if (!st.ok && !ru?.ok) continue; const b = await allBytesOf(stem); - if (!best || b > best.bytes) best = { stem, formats: st.formats, fragment: st.fragment, bytes: b }; + if (!best || b > best.bytes) best = { stem, formats: st.ok ? st.formats : "", fragment: st.ok ? st.fragment : ru!.ok ? ru!.fragments : 0, bytes: b, ...(st.ok ? {} : { reuse: true }) }; + } + if (best?.reuse) { + const ru = await restoreForReuse(best.stem, true); + const st = ru.ok ? await resumeStateOf(best.stem) : null; + if (st?.ok && ru.ok) { + best = { ...best, formats: st.formats, fragment: st.fragment }; + reusedFragments = ru.fragments; + } else best = null; } if (best) { // The one repair (DESIGN-4 1) before the resume; not provable: a // fresh from-start part (this attempt, a new stem) instead. const rc = await reconcileForResume(best.stem); if (!rc.ok) { - say(`Restart after the editor restart: ${best.stem} is not resumed in place (${rc.why}); a fresh part from the stream's start records instead.`); + say(`${best.stem} is not resumed in place (${rc.why}); a fresh part from the stream's start records instead.`); best = null; } } @@ -2349,7 +2431,7 @@ async function recordLiveRunInner( const p = partOfStem.get(best.stem); // The mark the interrupted run earned travels with its file. bootResume = { stem: best.stem, formats: best.formats, ...(p?.provenStart ? { provenStart: true } : {}) }; - say(`Restart after the editor restart: ${best.stem} is resumed in place from fragment ${best.fragment}.`); + say(`${resumeOf ? "Restart after the editor restart: " : ""}${best.stem}, an earlier part, is resumed in place from fragment ${best.fragment}${reusedFragments !== null ? " (its state rebuilt from its kept fragments: they are reused, not fetched again)" : ""}.`); // This run holds it now: no row lists it as waiting. const resumed = best.stem; for (const r of rows.filter((x) => x.awaitingResume?.includes(resumed))) { @@ -2367,6 +2449,10 @@ async function recordLiveRunInner( firstAttempt: n === 1, ...(bootResume ? { resume: bootResume, noWait: true } : {}), }); + if (bootResume && reusedFragments !== null) { + o.part.reused = { fragments: reusedFragments, at: now().toISOString() }; + await save(); + } // This attempt's own part (a try beside it may have begun one since). const last = { part: o.part, stem: o.stem }; const bytes = await bytesOf(last.stem); @@ -2506,7 +2592,9 @@ async function recordLiveRunInner( let freshFailedLast = false; while (cur && !signal.aborted && !pathB) { const stalledWithBytes = cur.o.stalled && cur.bytes > 0; - const exitedWithBytes = !cur.o.signalled && cur.bytes > 0 && !cur.partial; + // (A partial exit too — one stream missing — DESIGN-5 1: while the + // stream is live it restarts; a fresh or resumed part asks for both.) + const exitedWithBytes = !cur.o.signalled && cur.bytes > 0; const fragAborted = cur.o.fragAbort !== undefined && cur.bytes > 0 && !signal.aborted; const failedRestart = cur.o.part.restart !== undefined && cur.bytes === 0 && !(cur.o.signalled && !cur.o.stalled); if (!stalledWithBytes && !exitedWithBytes && !fragAborted && !failedRestart) break; @@ -2613,6 +2701,16 @@ async function recordLiveRunInner( // live-edge fallback below run. if (cur.mode === "from-start" && !resumeFailed.has(cur.o.stem)) { let st = await resumeStateOf(cur.o.stem); + // DESIGN-5 7: finished by yt-dlp itself (exit 0, merged) while live — + // reuse what is downloaded, not fragment 0 again. + if (!st.ok && separate) { + const ru = await restoreForReuse(cur.o.stem, true); + if (ru.ok) { + cur.o.part.reused = { fragments: ru.fragments, at: now().toISOString() }; + await save(); + st = await resumeStateOf(cur.o.stem); + } else say(`${cur.o.part.stem}: no reuse of what it downloaded (${ru.why}).`); + } // DESIGN-4 3 — A FRAGMENT THAT COULD NOT BE FETCHED: resumed after // 20 s, 60 s and 180 s at the same fragment; still failing there, a // fresh from-start part; that one failing at the same place, the @@ -2682,7 +2780,13 @@ async function recordLiveRunInner( restarts.count += 1; restarts.at.push(now().toISOString()); const k = restarts.count; - say(`Restart ${k} (${why}): a FRESH part from the stream's start (a new stem: YouTube serves it whole under 119 h); the earlier part is kept for the landing.`); + const sm = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; + const age = Number.isFinite(sm) ? (now().getTime() - sm) / 1000 : null; + say( + `Restart ${k} (${why}): nothing on disk can be reused with proof — a FRESH part from the stream's start (a new stem: YouTube serves it whole under 119 h)` + + (age !== null ? `; the stream is ${spanWords(age)} old: about ${spanWords(age)} of it is fetched again from fragment 0 before the live edge` : "") + + `; the earlier part is kept for the landing.`, + ); const o = await ytdlpPart(plan.url, `ytdlp-f${k}`, "from-start", `fresh ${k} (${why}); `, { restart: k, noWait: true, @@ -2861,6 +2965,13 @@ async function recordLiveRunInner( } } const endMeta = await readMeta(videoDir); + // DESIGN-5 3/4: does the platform's LAST word say the stream is over? Not + // over (is_live, upcoming, a read that failed, a record with no state): no + // landing now is "the whole stream", nothing reusable goes, and the row says + // it landed while live. Over: was_live / post_live / not_live, or a refusal + // as private or removed confirmed by the second read. + const lsEnd = typeof endMeta?.live_status === "string" ? endMeta.live_status : null; + const stillLive = !endedByRefusal && !(lsEnd === "was_live" || lsEnd === "post_live" || lsEnd === "not_live"); const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s)); const at = (n: string) => path.join(slugStore, n); // Every part on disk now — this run's and an earlier run's — by its stem. @@ -3278,7 +3389,9 @@ async function recordLiveRunInner( if (cov.covers && !mayHoldEnd(o)) { toRemove.push({ group: o.group, - why: `inside the landed file, which holds the whole stream from its start (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)}, ${cov.basis === "duration" ? "its duration" : "by the clock"})`, + why: stillLive + ? `inside the landed file, which holds the stream from its start SO FAR (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)} by the clock; the stream still reads live)` + : `inside the landed file, which holds the whole stream from its start (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)}, ${cov.basis === "duration" ? "its duration" : "by the clock"})`, extra: o.extra ?? [], o, }); @@ -3395,6 +3508,26 @@ async function recordLiveRunInner( const verifyAgainst: string[] = []; for (const f of mergedFrom) if ((await sizeOf(at(f))) > 0) verifyAgainst.push(at(f)); 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; + const elapsed = Number.isFinite(startMs) ? (now().getTime() - startMs) / 1000 : null; + const unrecorded = elapsed !== null && best.seconds !== null ? Math.max(0, Math.round(elapsed - best.seconds)) : null; + const why = stopped + ? stopped.by === "shutdown" + ? "an editor shutdown stopped it" + : "it was cancelled" + : record.restarts?.refused + ? `not restarted: ${record.restarts.refused}` + : lsEnd === "is_live" || lsEnd === "is_upcoming" + ? "the last read says the stream is live" + : "the stream's state could not be read"; + record.landedWhileLive = { at: now().toISOString(), unrecordedSeconds: unrecorded, why }; + say( + `LANDED WHILE THE STREAM IS STILL LIVE (${why}): what is stored is the stream SO FAR, not the whole` + + (unrecorded !== null ? ` — about ${spanWords(unrecorded)} of it, by the clock, is in no landed file now` : "") + + "; the row needs a person, and nothing reusable is removed until the stream is confirmed done.", + ); + } const skippedHere = best.part?.skippedFragments ?? (await readStemMarks(slugStore, best.group.stem)).skipped; if (skippedHere && skippedHere.count > 0) { record.skippedFragments = { ...skippedHere }; @@ -3484,8 +3617,26 @@ async function recordLiveRunInner( 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"}).`); - for (const r of toRemove) await removeGroup(r.group, r.why, r.extra); - for (const f of [...best.group.finished, ...best.group.streams, ...best.group.scratch]) await rm(at(f), { force: true }); + // (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); + // DESIGN-5 7 — ONLY WHEN CONFIRMED DONE (the platform says over, and + // verified): the landed part's stream files, state and fragments go. + // Still live: they stay, for a restart's reuse. + // (A stream that went private or was removed keeps everything on disk: + // DESIGN-5 (c) — it may come back, and what is there is all there is.) + const wentPrivate = record.endedBy?.class === "private"; + if (!stillLive && !wentPrivate) { + for (const f of [...best.group.finished, ...best.group.streams, ...best.group.scratch]) await rm(at(f), { force: true }); + } else { + await keep( + best.group, + wentPrivate + ? "the landed part's stream files, state and fragments, kept: the stream went private or was removed while it was recorded" + : "the landed part's stream files, state and fragments, kept for a restart's reuse until the stream is confirmed done", + { ...(best.part ? { part: best.part } : {}) }, + ); + } if (removed.length) record.removedParts = removed; for (const r of removed) say(`Removed: ${r.stem} (${formatBytes(r.bytes)}) — ${r.why}.`); } else if (landSignal.aborted) { diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -491,11 +491,18 @@ export type LivePart = { skippedFragments?: { count: number; positions: number[] }; // Fragments that could not be fetched (the abort's error lines). fragmentErrors?: number; + // Fragment requests answered "HTTP Error 403: Forbidden" (with a private + // or removed state read after them: went-private). + fragment403?: number; // DESIGN-4 1: its kept fragments were dropped for want of disk (why): the // recording went on, resumability went. fragmentsDropped?: string; // A fresh from-start part after a stop (DESIGN-4 2), its number. fresh?: number; + // DESIGN-5 7: resumed after yt-dlp had finished it (a self-exit): its + // state rebuilt at the fragment count the byte equation proves — the + // fragments it reused (not fetched again). + reused?: { fragments: number; at: string }; // Proven to begin at the stream's start, by what was recorded: a YouTube // `--live-from-start` part (not one fallen to index 0) on a stream under // 120 h old; another platform's @@ -620,6 +627,10 @@ export type LiveRecordingRecord = { verification?: LiveVerification; // The landed file holds skipped fragments (its part's skippedFragments). skippedFragments?: { count: number; positions: number[] }; + // DESIGN-5 4: landed while the last state read said the stream is live (or + // could not be read): never "the whole stream"; how much of it, by the + // clock at that moment, is in no landed file. + landedWhileLive?: { at: string; unrecordedSeconds: number | null; why: string }; // Spawns that did not start because the store's disk was under the floor // (RECORD_LIVE_MIN_FREE_BYTES): what, when, and how much was free. spaceHeld?: LiveSpaceHeld[]; @@ -986,7 +997,17 @@ export type LiveFailureClass = | "argv" | "unsupported" | "partial" - | "stalled"; + | "stalled" + // DESIGN-5: yt-dlp could not refresh the stream's URL ("Cannot find + // refreshed url for format …", "Giving up after N retries") — the platform + // stopped serving that format (its DVR switched off mid-stream); yt-dlp then + // merges and exits 0 while the stream may still be live. + | "url-refresh" + // DESIGN-5 (c): fragment requests answered 403 Forbidden, then the state + // read says the video is private or removed — the platform pulled it while + // it was recorded: what is on disk lands, loud, never retried in a loop, + // and nothing on disk is removed. + | "went-private"; // What yt-dlp says when the stream is over or gone: no attempt can help. export function liveStreamGone(stderr: string): boolean { @@ -998,6 +1019,7 @@ export function liveFailureClass(stderr: string): LiveFailureClass { const t = stderr; // First: no space is no space, whatever else the tail says. if (/No space left on device|Errno 28\b|Disk quota exceeded|Read-only file system|\[Errno 13\] Permission denied/i.test(t)) return "disk"; + if (/Cannot find refreshed url for format/i.test(t)) return "url-refresh"; // Before `members`: the bot check's message also says "use --cookies". // (YouTube's soft block, "This content isn't available, try again later", // is a rate limit too: REVIEW-4 1.3 of live-guard-2.) diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts @@ -93,6 +93,7 @@ export type LiveRecordingRow = { transcriptRedo?: LiveTranscriptRedo; verification?: LiveVerification; skippedFragments?: { count: number; positions: number[] }; + landedWhileLive?: { at: string; unrecordedSeconds: number | null; why: string }; // What the landing kept: this run's file stored ("new"), or the store's. kept?: "new" | "existing"; acknowledgedAt?: string; @@ -182,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">>, + Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost" | "endedBy" | "awaitingResume" | "transcriptRedo" | "verification" | "skippedFragments" | "parts" | "landedWhileLive">>, ): boolean { if (r.acknowledgedAt) return false; if (r.keptParts && r.keptParts.length > 0) return true; @@ -192,6 +193,8 @@ export function rowNeedsAttention( if (r.parts?.some((p) => (p.skippedFragments?.count ?? 0) > 0 || p.fragmentsDropped)) return true; if (r.verification && r.verification.state !== "verified") return true; if (r.supersededBy) return false; + // DESIGN-5 4: landed while the stream was still live — until acknowledged. + if (r.landedWhileLive) 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; @@ -287,6 +290,7 @@ export function rowOfRecord( ...(rec.transcriptRedo ? { transcriptRedo: { ...rec.transcriptRedo } } : {}), ...(rec.verification ? { verification: { ...rec.verification } } : {}), ...(rec.skippedFragments ? { skippedFragments: { ...rec.skippedFragments } } : {}), + ...(rec.landedWhileLive ? { landedWhileLive: { ...rec.landedWhileLive } } : {}), ...(rec.spaceHeld && rec.spaceHeld.length ? { spaceHeld: rec.spaceHeld.map((x) => ({ ...x })) } : {}), ...(rec.failureClass ? { failureClass: rec.failureClass } : {}), ...(rec.missingStream ? { missingStream: rec.missingStream } : {}), @@ -311,7 +315,8 @@ export function rowCoversStream( r: Pick<LiveRecordingRow, "status" | "fromStart" | "fallback" | "missingStream" | "coverage"> & Partial<Pick<LiveRecordingRow, "startRecovery">>, ): boolean { const startHeld = !r.fallback || r.startRecovery?.state === "recovered"; - return r.status === "landed" && r.fromStart && startHeld && !r.missingStream && r.coverage?.covers === true; + // (Never a landing made while the stream still read live: DESIGN-5 3.) + return r.status === "landed" && r.fromStart && startHeld && !r.missingStream && r.coverage?.covers === true && !(r as { landedWhileLive?: unknown }).landedWhileLive; } // Writes (or rewrites) the run's row. A run that lands the WHOLE stream diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -36,6 +36,12 @@ - yt-dlp keeps the stream files through its merge; the landed file is verified against them per track before they, and every part meant for removal, are removed — not verified, nothing is removed. - One recorder per stem (a lock file); nothing lands at a shutdown while a part waits to be resumed. + - A recorder that ends by itself while the stream is live (yt-dlp's "Cannot find refreshed url … Giving up", now + `url-refresh`; any exit, partial ones too) is restarted for as long as the platform says live, REUSING what is + downloaded (its state rebuilt at the proven fragment count, the merged copy moved aside) instead of fragment 0; + every fragment is kept until the stream is confirmed done. + - A landing while the stream still reads live is `landedWhileLive`: loud, "so far", the unrecorded time by the + clock, superseding nothing. - **A live recording's landing never deletes around, or replaces, a recording already in the store that it is not proven to hold.** - When the landing keeps the container already stored, nothing is removed: the part and every part meant for