Archilyzer · Source

archilyzer

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

commit 749ca718c037dc502ffc90bc59ee8dc2a8250aca
parent 97ba85133f3884e87d468f5941d2ceb60d89c270
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 22:52:14 -0500

record-live: a waiting part always reaches the store; the recorder tree; every stream pinned; the boot's age by the last write (REVIEW-5 B3-B6, notes 1, 8, 11)

- B3: a part an earlier run left waiting is released to the landing by any
  later run not itself stopped by a shutdown. The boot's run lands what was
  left whatever it finds: the stream ended, made private or removed, or its
  state unreadable after the three reads. The interrupted row says what was
  done ("landed" / "failed" with the reason), not what was meant. The boot
  resume takes the longest resumable from-start part of any row of the id.
- B4: the recorder runs in a process group of its own; a stop reaches the
  whole tree, and the recorder returns when yt-dlp exits (a grandchild
  still holding its pipes 3 s later is killed with the group). SIGTERM only
  for a part that can be resumed at the moment of the stop (separate
  streams, each with its state); everything else SIGINT.
- B5: a resume pins every stream file of the stem, an empty one included;
  fewer than two, or two of one kind, of a separate recording is not
  resumed. A stream that recorded nothing is said when its recorder stops.
- B6: the boot pass measures a row's age from the newest mtime of its part
  files; a row skipped for its age is marked refused and logged.
- Note 1: each stream file of a separate from-start part must grow; one
  that stops while the other grows is a stall (stopped, resumable).
- Note 8: 119 h, for the resume and the YouTube proof; an unknown start is
  not resumable.
- Note 11: the transcription asked again replaces the transcript
  (`replace` through whisperVideoAction to transcribeOneVideo, which
  otherwise returns already-exists); the old one stays until the new one
  is renamed over it.
- The resumable fake writes two stream files with their own state and
  merges at a normal end, as yt-dlp does.

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

Diffstat:
Mcommon/controller/liveRecordingBoot.test.ts | 31+++++++++++++++++++++++++++++++
Mcommon/controller/liveRecordingBoot.ts | 23+++++++++++++++++++++--
Mcommon/controller/liveRecordings.ts | 3++-
Mcommon/controller/recordLive.test.ts | 423++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mcommon/controller/recordLive.ts | 309++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------------
Mcommon/controller/transcribeOne.test.ts | 26++++++++++++++++++++++++++
Mcommon/controller/transcribeOne.ts | 10+++++++++-
Mcommon/lib/liveCapture.ts | 5++++-
Meditor/app/channels/[slug]/liveMediaActions.ts | 4++--
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 6++++++
10 files changed, 692 insertions(+), 148 deletions(-)

diff --git a/common/controller/liveRecordingBoot.test.ts b/common/controller/liveRecordingBoot.test.ts @@ -198,3 +198,34 @@ test("REVIEW 1.8 (live-guard-2): the orphan check looks more than once — a par assert.equal(r.restart?.state, "refused"); assert.match(r.restart?.reason ?? "", /changed between two looks/); }); + +test("REVIEW-5 B6: the age is the recorder's LAST WRITE — a 14-hour part written a minute before the crash restarts; one idle for 13 h is refused, marked and logged", async () => { + // A crash 14 h into a stream: one from-start part since hour 0, no end time. + const id = "exbootlong1"; + const startedAt = ago(14 * 60); + await upsertLiveRecordingRow( + paths, + SLUG, + row(id, startedAt, { status: "recording", stoppedBy: undefined, endedAt: undefined, jobId: "job-dead", parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt, stem: `.${id}.live-x.ytdlp` }] }), + ); + const f = path.join(store, `.${id}.live-x.ytdlp.f136.mp4`); + await writeFile(f, "bytes"); + const last = new Date(NOW.getTime() - 60_000); + await utimes(f, last, last); + // Idle for 13 h: its files last written then. + const old = "exbootidle1"; + await upsertLiveRecordingRow(paths, SLUG, row(old, ago(14 * 60))); + const g = path.join(store, `.${old}.live-y.ytdlp.f136.mp4`); + await writeFile(g, "bytes"); + const then = new Date(NOW.getTime() - 13 * 3_600_000); + await utimes(g, then, then); + const s = starter(); + const lines: string[] = []; + await pass(s.start, { log: (l) => void lines.push(l) }); + assert.ok(s.asked.some((a) => a.body.url === `https://www.youtube.com/watch?v=${id}`), "restarted: its recorder wrote a minute ago"); + assert.ok(!s.asked.some((a) => a.body.url === `https://www.youtube.com/watch?v=${old}`)); + const r = (await rowsOf(old))[0]!; + assert.equal(r.restart?.state, "refused"); + assert.match(r.restart?.reason ?? "", /last wrote 13 h ago/); + assert.ok(lines.some((l) => l.includes(old) && /refused/.test(l)), "logged"); +}); diff --git a/common/controller/liveRecordingBoot.ts b/common/controller/liveRecordingBoot.ts @@ -122,7 +122,6 @@ export async function restartInterruptedLiveRecordings(o: { if (!crashed && !shutdown) continue; if (row.acknowledgedAt || row.restart) continue; const at = now(); - if (at.getTime() - lastActivityMs(row) > LIVE_BOOT_MAX_AGE_MS) continue; const tag = `${slug}/${row.id}`; const mark = (restart: Partial<LiveBootRestart> & { state: LiveBootRestart["state"] }) => patchLiveRecordingRow(o.paths, slug, row.id, row.startedAt, (r) => { @@ -145,7 +144,27 @@ export async function restartInterruptedLiveRecordings(o: { } } let refusal: string | null = null; - if (o.enabled === false) refusal = "settings.liveRecording.autoRestartOnBoot is off"; + // THE AGE (REVIEW-5 B6): from the recorder's LAST WRITE — the newest + // mtime of the id's part files — or the row's own times, whichever is + // later; a part that is recording has no end time, and a killed editor + // writes none. A row skipped for its age is marked and logged. + { + const config = await readChannelConfig(o.paths, slug).catch(() => null); + const slugStore = path.join(savedVideoRoot(o.paths, config), slug); + const listing = await readdir(slugStore).catch(() => [] as string[]); + let newest = lastActivityMs(row); + for (const g of livePartFiles(row.id, listing)) { + for (const f of [...g.finished, ...g.streams, ...g.scratch]) { + const st = await stat(path.join(slugStore, f)).catch(() => null); + if (st) newest = Math.max(newest, st.mtimeMs); + } + } + const idle = at.getTime() - newest; + if (idle > LIVE_BOOT_MAX_AGE_MS) { + refusal = `its recorder last wrote ${Math.round(idle / 3_600_000)} h ago (more than ${LIVE_BOOT_MAX_AGE_MS / 3_600_000} h): too old to restart automatically`; + } + } + if (!refusal && o.enabled === false) refusal = "settings.liveRecording.autoRestartOnBoot is off"; if (!refusal) { const recent = rows.filter((r) => r.id === row.id && r.resumeOf && at.getTime() - Date.parse(r.startedAt) < 3_600_000).length; if (recent >= LIVE_BOOT_MAX_RESTARTS_PER_HOUR) { diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -218,7 +218,8 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: starting: "being restarted automatically", asked: `restarted automatically as job ${r.jobId ?? "?"}: it reads the stream's state first`, restarted: `restarted automatically (job ${r.jobId ?? "?"}): the stream was still live`, - landing: "the stream had ended by the restart: what this run left is landed", + landing: `${r.reason ?? "the stream had ended by the restart"}: what this run left is being landed (job ${r.jobId ?? "?"})`, + landed: `${r.reason ?? "the stream had ended by the restart"}: what this run left was landed (job ${r.jobId ?? "?"})`, ended: "the stream had ended by the restart, and nothing was left to land — the end of the stream is NOT recorded", unknown: `NOT restarted: the stream's state could not be read${r.reason ? ` (${r.reason})` : ""} — Record again if it is still live`, refused: `NOT restarted automatically: ${r.reason ?? "refused"} — Record again if the stream is still live`, diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -675,7 +675,7 @@ async function incidentRun( // A number: that many pass at once, the rest never come. recovery?: "immediate" | number; refresh?: Parameters<typeof refreshWith>[1]; - requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>; + requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>; } = {}, ) { await ytChannel(); @@ -1519,7 +1519,8 @@ test("slice 3 resume: the stream has ended → no recorder; the interrupted run' assert.equal(s.status, "landed"); assert.equal(s.landed?.seconds, 3000); const old = await oldRow(id, t0); - assert.equal(old.restart?.state, "landing"); + // What was done, not what was meant (REVIEW-5 B3). + assert.equal(old.restart?.state, "landed"); assert.ok(old.supersededBy, "the landed whole supersedes the interruption"); assert.equal(old.needsAttention, false); }); @@ -2068,7 +2069,7 @@ test("REVIEW 1.4: a restart's earlier sibling from its start is not removed on t live = false; return okExit; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await run).status, "landed"); const row = (await rowOf(id))[0]!; @@ -2291,7 +2292,7 @@ test("REVIEW2 3.1: a caught-up from-start recorder that exits while the stream r live = false; return okExit; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; assert.equal(calls.length, 2, "restarted"); @@ -2310,7 +2311,7 @@ test("REVIEW2 3.2: a second and a third death while the stream reads live restar if (n === 3) live = false; return n === 3 ? okExit : deaths; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 3000 }, }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 3000 }, }, ); await a.run; assert.equal(a.calls.length, 3, "two deaths, two restarts"); @@ -2323,7 +2324,7 @@ test("REVIEW2 3.2: a second and a third death while the stream reads live restar await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); return deaths; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => true }, meta: { ...YT_META(id2), release_timestamp: Math.floor(Date.now() / 1000) - 300 } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => true }, meta: { ...YT_META(id2), release_timestamp: Math.floor(Date.now() / 1000) - 300 } }, ); await b.run; assert.equal(b.calls.length, 1 + 6, "the first recorder and 6 restarts (the hour's bound)"); @@ -2343,7 +2344,7 @@ test("REVIEW2 3.1: three live-edge recorders in a row that capture nothing are t } return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => true }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 3000 }, }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => true }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 3000 }, }, ); assert.equal((await run).status, "landed"); assert.equal(calls.length, 4, "the first, then three empty live-edge recorders"); @@ -2364,7 +2365,7 @@ test("REVIEW2 3.3: the class is read from the recorder's last output — a 429 r signalled: false, }; }, - { deps: { ...FAST_WATCH, join: null } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge } }, ); assert.equal((await a.run).status, "landed"); assert.ok(!a.waits.includes(15 * 60_000), "no 15 min wait for an old 429"); @@ -2381,7 +2382,7 @@ test("REVIEW2 3.3: the class is read from the recorder's last output — a 429 r live = false; return okExit; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live }, meta: { ...YT_META("exmplr2a306"), release_timestamp: Math.floor(Date.now() / 1000) - 3000 } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live }, meta: { ...YT_META("exmplr2a306"), release_timestamp: Math.floor(Date.now() / 1000) - 3000 } }, ); await b.run; assert.equal(b.calls.length, 2, "the state was read, it is live: restarted"); @@ -2396,7 +2397,7 @@ test("REVIEW2 3.4: the floor before a spawn is max(the floor, twice the largest return { exitCode: 1, stderrTail: "ERROR: Connection reset by peer\n", signalled: false }; }, // A floor of 1 kB; 3 kB free; the part is ~2 kB: twice it is not there. - { deps: { ...FAST_WATCH, join: null, minFreeBytes: 1000, freeBytes: async () => 3000 }, refresh: { stillLive: () => true } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 3000 }, refresh: { stillLive: () => true } }, ); await run; assert.equal(calls.length, 1, "no restart: twice the largest part is not free"); @@ -2528,7 +2529,7 @@ test("REVIEW3 3.1: the 20 Nov shape — from its start dies a minute in on a str return okExit; }, // (The recovery begins once the live-edge part holds bytes: REVIEW-4 1.1.) - { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, + { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, ); await run; assert.ok(calls.some(isRestart) && isEdge(calls.find(isRestart)!), "a live-edge recorder at once"); @@ -2562,7 +2563,7 @@ test("REVIEW3 3.1: a from-start recorder that stalls while 2 h behind: the live return okExit; }, // (The recovery begins once the live-edge part holds bytes: REVIEW-4 1.1.) - { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, + { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, ); await run; assert.ok(isEdge(calls[1]!) || isEdge(calls[2]!), "a live-edge recorder"); @@ -2586,7 +2587,7 @@ test("REVIEW3 3.1: a from-start recorder that had caught up needs no recovery: t live = false; return okExit; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; assert.equal(calls.length, 2); @@ -2643,7 +2644,7 @@ test("REVIEW3 1.1: a failed state read after an exit never ends the recording: t return okExit; }, // The read after the exit fails (the same network drop). - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live, failReads: [2] } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live, failReads: [2] } }, ); await run; assert.equal(calls.length, 2, "restarted at the live edge though the state could not be read"); @@ -2690,40 +2691,86 @@ test("REVIEW3 4.1: a live-edge part goes only when the landed file is the media' // kill or a crash leaves it. type FakeResume = { exitCode: number | null; stderrTail: string; signalled: boolean }; -function resumableYtdlp(script: (call: { n: number; resumedFrom: number | null; write: (seconds: number) => Promise<void>; signal: AbortSignal; args: string[] }) => Promise<"die" | "end" | "hang" | FakeResume>) { +// Two stream files, as a real separate-streams from-start download has from +// its first second (dash.py: each opened, its state written, before any +// fragment): the picture `<out>.f136.mp4`, the sound `<out>.f140.m4a`, each +// with its own `.ytdl`. A normal end (and SIGINT) merges them into +// `<out>.mp4` and removes them, as yt-dlp does without `-k`. +const FAKE_V = "f136.mp4"; +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 }); +}; +const fakeMerge = async (args: string[]) => { + const ins = args.flatMap((a, k) => (a === "-i" ? [args[k + 1]!] : [])); + let sec = 0; + let bytes = 0; + for (const f of ins) { + sec = Math.max(sec, (await fakeProbe(f))?.seconds ?? 0); + bytes += (await stat(f).catch(() => null))?.size ?? 0; + } + // (As large as its streams together, as a real merge is.) + await writeFile(args[args.length - 1]!, `format=mov,mp4;seconds=${sec};${"x".repeat(bytes)}`); +}; +function resumableYtdlp( + script: (call: { + n: number; + resumedFrom: number | null; + write: (seconds: number) => Promise<void>; + writeStream: (kind: "video" | "audio", seconds: number) => Promise<void>; + signal: AbortSignal; + args: string[]; + }) => Promise<"die" | "end" | "hang" | FakeResume>, +) { let n = 0; return async (args: string[], _n: number, signal: AbortSignal): Promise<FakeResume> => { n++; const out = outOf(args); const fromStart = fromStartArg(args); - const file = `${out}.f18.mp4`; - const state = `${file}.ytdl`; + const files = { video: `${out}.${FAKE_V}`, audio: `${out}.${FAKE_A}` }; let resumedFrom: number | null = null; - let have = 0; if (fromStart) { - const st = await readFile(state, "utf8").catch(() => null); - if (st) { - resumedFrom = JSON.parse(st).downloader.current_fragment.index as number; - have = resumedFrom * 5; + const st = await readFile(`${files.video}.ytdl`, "utf8").catch(() => null); + if (st) resumedFrom = JSON.parse(st).downloader.current_fragment.index as number; + // Both opened, each with its state, from the first second. + for (const f of Object.values(files)) { + if (!(await stat(f).catch(() => null))) { + await writeFile(f, ""); + await writeFile(`${f}.ytdl`, JSON.stringify({ downloader: { current_fragment: { index: 0 } } })); + } } } - const write = async (seconds: number) => { - have = seconds; + const writeStream = async (kind: "video" | "audio", seconds: number) => { // (Its bytes grow with what it holds, as a real stream file's do.) - await writeFile(fromStart ? file : `${out}.mp4`, `format=mp4;seconds=${seconds};${"x".repeat(Math.floor(seconds / 60))}`); - if (fromStart) await writeFile(state, JSON.stringify({ downloader: { current_fragment: { index: Math.floor(seconds / 5) } } })); + await writeFile(files[kind], `format=mp4;seconds=${seconds};${kind === "video" ? "a=none;" : "v=none;"}${"x".repeat(Math.floor(seconds / 5))}`); + await writeFile(`${files[kind]}.ytdl`, JSON.stringify({ downloader: { current_fragment: { index: Math.floor(seconds / 5) } } })); }; - void have; - const what = await script({ n, resumedFrom, write, signal, args }); + const write = async (seconds: number) => { + if (!fromStart) { + await writeFile(`${out}.mp4`, `format=mp4;seconds=${seconds};${"x".repeat(Math.floor(seconds / 60))}`); + return; + } + await writeStream("video", seconds); + await writeStream("audio", seconds); + }; + const finalize = async () => { + if (!fromStart) return; + await fakeMerge(["-i", files.video, "-i", files.audio, `${out}.mp4`]); + for (const f of Object.values(files)) { + await rm(f, { force: true }); + await rm(`${f}.ytdl`, { force: true }); + } + }; + const what = await script({ n, resumedFrom, write, writeStream, signal, args }); if (what === "die") return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false }; if (what === "end") { - await rm(state, { force: true }); + await finalize(); return okExit; } if (what === "hang") { await abortOf(signal); - // SIGINT finishes the download (the state goes); SIGTERM leaves it. - if (signal.reason === "SIGINT") await rm(state, { force: true }); + // SIGINT finishes the download (merged, the state gone); SIGTERM leaves it. + if (signal.reason === "SIGINT") await finalize(); return { exitCode: null, stderrTail: "", signalled: true }; } return what; @@ -2744,12 +2791,12 @@ test("DESIGN-3: a from-start recorder that dies is RESUMED in place: the same st live = false; return "end"; }); - const { run, calls } = await incidentRun(id, fake, { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }); + const { run, calls } = await incidentRun(id, fake, { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }); assert.equal((await run).status, "landed"); assert.equal(calls.length, 2); assert.equal(outOf(calls[1]!), outOf(calls[0]!), "the same output stem"); assert.ok(fromStartArg(calls[1]!), "from its start, resumed"); - assert.equal(calls[1]![calls[1]!.indexOf("-f") + 1], "18", "the format pinned to the one on disk"); + assert.equal(calls[1]![calls[1]!.indexOf("-f") + 1], "136+140", "the format pinned to the ids on disk"); assert.deepEqual(resumed, [null, 720], "continued from the saved fragment"); assert.equal(calls.filter(isRecovery).length, 0); const row = (await rowOf(id))[0]!; @@ -2778,7 +2825,7 @@ test("DESIGN-3: a stalled from-start recorder is stopped WITHOUT finishing (SIGT const o = await fake(args, n, signal); return o; }; - const { run, calls } = await incidentRun(id, wrapped, { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }); + const { run, calls } = await incidentRun(id, wrapped, { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }); await run; assert.deepEqual(reasons, ["SIGTERM"], "the watchdog's stop keeps the state"); assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place"); @@ -2795,7 +2842,7 @@ test("DESIGN-3: a stalled from-start recorder is stopped WITHOUT finishing (SIGT seen.push(signal.reason); return { exitCode: null, stderrTail: "", signalled: true }; }), - { signal: ac.signal, deps: { ...FAST_WATCH, join: null } }, + { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge } }, ); await c.run; assert.deepEqual(seen, ["SIGINT"]); @@ -2812,12 +2859,12 @@ test("DESIGN-3: an editor shutdown leaves the state (SIGTERM), and the boot's re await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), - { signal: ac.signal, deps: { ...FAST_WATCH, join: null, shuttingDown: () => true } }, + { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); const s1 = await first.run; assert.equal(s1.status, "interrupted"); const stem = outOf(first.calls[0]!); - assert.ok((await left(id)).some((n) => n.endsWith(".f18.mp4.ytdl")), "the state survived the shutdown"); + assert.ok((await left(id)).some((n) => n.endsWith(".f136.mp4.ytdl")), "the state survived the shutdown"); assert.equal(await storedSeconds(id), null, "nothing landed: the part waits to be resumed"); const t0 = (await rowOf(id))[0]!.startedAt; const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server"); @@ -2833,7 +2880,7 @@ test("DESIGN-3: an editor shutdown leaves the state (SIGTERM), and the boot's re live = false; return "end"; }), - { request: { resumeOf: t0 }, deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { request: { resumeOf: t0 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await second.run).status, "landed"); assert.equal(outOf(second.calls[0]!), stem, "the boot's restart resumed the interrupted stem"); @@ -2848,14 +2895,14 @@ test("DESIGN-3: no state to resume (the part was finished) — the fallback: a l if (n === 1) { await write(7200); // It finished (the state went), then exited 1. - await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true }); + await dropState(args); return "die"; } await write(300); live = false; return "end"; }), - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; assert.equal(calls.length, 2); @@ -2869,10 +2916,10 @@ test("DESIGN-3 5.1: a read refused as private is confirmed a minute later; confi id, resumableYtdlp(async ({ write, args }) => { await write(3000); - await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true }); + await dropState(args); return "die"; }), - { deps: { ...FAST_WATCH, join: null }, refresh: { failAfterFirst: PRIVATE } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failAfterFirst: PRIVATE } }, ); await a.run.catch(() => {}); assert.ok(a.waits.includes(60_000), "read again a minute later"); @@ -2888,14 +2935,14 @@ test("DESIGN-3 5.1: a read refused as private is confirmed a minute later; confi resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(7200); - await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true }); + await dropState(args); return "die"; } await write(300); live = false; return "end"; }), - { deps: { ...FAST_WATCH, join: null }, refresh: { failReads: [2], failWith: PRIVATE, stillLive: () => live } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [2], failWith: PRIVATE, stillLive: () => live } }, ); await b.run; assert.equal(b.calls.length, 2, "not ended on one refused read"); @@ -2910,7 +2957,7 @@ test("DESIGN-3 fallback (REVIEW-4 3.1): a hole of minutes on a long stream is no resumableYtdlp(async ({ n, write, args }) => { if (n === 1) { await write(9 * 3600 - 300); - await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true }); + await dropState(args); return "die"; } if (isRecovery(args)) { @@ -2922,7 +2969,7 @@ test("DESIGN-3 fallback (REVIEW-4 3.1): a hole of minutes on a long stream is no live = false; return "end"; }), - { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 9 * 3600 }, deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 9 * 3600 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); await run; const row = (await rowOf(id))[0]!; @@ -2939,7 +2986,7 @@ test("DESIGN-3 fallback (REVIEW-4 1.1): the gap recovery's first try waits until resumableYtdlp(async ({ n, write, args, signal }) => { if (n === 1) { await write(60); - await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true }); + await dropState(args); return "die"; } if (isRecovery(args)) { @@ -2956,7 +3003,7 @@ test("DESIGN-3 fallback (REVIEW-4 1.1): the gap recovery's first try waits until live = false; return "end"; }), - { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, + { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } }, ); await run; assert.ok(recoveryAt > 0, "a recovery try ran"); @@ -3368,7 +3415,7 @@ test("flow: an editor shutdown stops a from-start run, the BOOT PASS resumes it await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), - { signal: ac.signal, deps: { ...FAST_WATCH, join: null, shuttingDown: () => true } }, + { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); assert.equal((await first.run).status, "interrupted"); const stem = outOf(first.calls[0]!); @@ -3398,7 +3445,7 @@ test("flow: an editor shutdown stops a from-start run, the BOOT PASS resumes it live = false; return "end"; }), - { request: { ...body, resumeOf }, deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { request: { ...body, resumeOf }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); return { ok: true, jobId: "job-boot" }; }, @@ -3421,7 +3468,7 @@ 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("flow: a part waiting to be resumed is not landed, removed or counted by a later run that does not resume it; that run says so and needs a person", { timeout: 60_000 }, async () => { +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 () => { const id = "exmplflowa2"; const ac = new AbortController(); const first = await incidentRun( @@ -3432,11 +3479,10 @@ test("flow: a part waiting to be resumed is not landed, removed or counted by a await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), - { signal: ac.signal, deps: { ...FAST_WATCH, join: null, shuttingDown: () => true } }, + { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); await first.run; - const waiting = (await left(id)).sort(); - assert.ok(waiting.some((n) => n.endsWith(".ytdl"))); + assert.ok((await left(id)).some((n) => n.endsWith(".ytdl"))); // A person's Record again (no resume): its own whole from-start file. let live = true; const again = await incidentRun( @@ -3446,20 +3492,20 @@ test("flow: a part waiting to be resumed is not landed, removed or counted by a live = false; return okExit; }, - { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await again.run).status, "landed"); assert.equal(await storedSeconds(id), 7200); - const after = await left(id); - for (const n of waiting) assert.ok(after.includes(n), `${n} is still in staging as it was`); - const row = (await rowOf(id)).find((r) => r.status === "landed")!; - assert.equal(row.removedParts, undefined, "not removed by the coverage rule"); - assert.deepEqual(row.awaitingResume, [path.basename(outOf(first.calls[0]!))]); - assert.equal(row.needsAttention, true, "a part with its state waits in staging: a person decides"); - assert.match(row.reason, /wait in staging/); + 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)); }); -async function replacedOverShutdown(id: string, transcript: string | null, requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>) { +async function replacedOverShutdown(id: string, transcript: string | null, requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>) { await landedAtShutdown(id, 3600); if (transcript !== null) await writeFile(path.join(dataDir(id), "transcript.json"), transcript); let live = true; @@ -3492,11 +3538,11 @@ test("flow (REVIEW-LF-4 4): a shutdown's landing from the start is stored, then test("flow (REVIEW-LF-4 2): the replaced short landing's transcript ends inside it → the transcription is asked again", async () => { const id = "exmplflowb2"; const asked: string[] = []; - const { row, log } = await replacedOverShutdown(id, choughOf(3580), async (_slug, vid) => { - asked.push(vid); + const { row, log } = await replacedOverShutdown(id, choughOf(3580), async (_slug, vid, o) => { + asked.push(`${vid}${o?.replace ? " replace" : ""}`); return { ok: true, jobId: "job-redo" }; }); - assert.deepEqual(asked, [id], "asked once"); + assert.deepEqual(asked, [`${id} replace`], "asked once, to REPLACE the transcript (the job would otherwise skip it)"); assert.equal(row.transcriptRedo?.verdict, "shorter"); assert.equal(row.transcriptRedo?.replacedSeconds, 3600); assert.equal(row.transcriptRedo?.lastCueEnd, 3580); @@ -3553,7 +3599,7 @@ test("flow: a boot resume of a part its original run did NOT prove (a row writte await abortOf(signal); return { exitCode: null, stderrTail: "", signalled: true }; }), - { signal: ac.signal, deps: { ...FAST_WATCH, join: null, shuttingDown: () => true } }, + { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, ); await first.run; const t0 = (await rowOf(id))[0]!.startedAt; @@ -3571,7 +3617,7 @@ test("flow: a boot resume of a part its original run did NOT prove (a row writte live = false; return "end"; }), - { request: { resumeOf: t0 }, deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } }, + { request: { resumeOf: t0 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, ); assert.equal((await second.run).status, "landed"); const run2 = (await rowOf(id)).find((r) => r.resumeOf)!; @@ -3579,3 +3625,244 @@ test("flow: a boot resume of a part its original run did NOT prove (a row writte assert.equal(run2.parts[0]!.provenStart, undefined, "the mark is not earned by a resume"); assert.equal(run2.coverage?.covers, false); }); + +// --- REVIEW-5 B: a waiting part always has a way into the store; the recorder tree; every stream pinned; the boot's age --- + +// A shutdown leaves one from-start part waiting (both streams, their state). +async function waitingAtShutdown(id: string, seconds = 3000, opts: { video?: number } = {}) { + const ac = new AbortController(); + const r = await incidentRun( + id, + resumableYtdlp(async ({ write, writeStream, signal }) => { + if (opts.video === undefined) await write(seconds); + else { + await writeStream("audio", seconds); + if (opts.video > 0) await writeStream("video", opts.video); + } + 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 } }, + ); + assert.equal((await r.run).status, "interrupted"); + const row = (await rowOf(id))[0]!; + assert.equal(row.awaitingResume?.length, 1, "one part waits"); + return { stem: outOf(r.calls[0]!), startedAt: row.startedAt, row }; +} +const askBoot = async (id: string, startedAt: string) => { + const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server"); + await patchLiveRecordingRow(paths, YT_SLUG, id, startedAt, (r) => { + r.restart = { at: startedAt, by: "boot", state: "asked" }; + }); +}; + +test("B3: the stream ENDED while the editor was down — the boot's run finalizes and lands the waiting part, and the old row says what was done", { timeout: 60_000 }, async () => { + const id = "exmplb3end1"; + const { startedAt } = await waitingAtShutdown(id); + await askBoot(id, startedAt); + const r = await incidentRun(id, async () => assert.fail("nothing is recorded for an ended stream"), { + request: { resumeOf: startedAt }, + meta: { ...YT_META(id), live_status: "was_live", duration: 3000 }, + deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, + }); + const s = await r.run; + assert.equal(s.status, "landed"); + assert.equal(await storedSeconds(id), 3000, "the waiting part is in the store"); + assert.deepEqual(await left(id), [], "nothing left in staging, no state"); + const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!; + assert.equal(old.restart?.state, "landed"); + assert.doesNotMatch(old.reason, /is landed$/); + assert.match(old.reason, /was landed/); + assert.equal(old.awaitingResume, undefined); +}); + +test("B3: the stream was REMOVED while the editor was down (every read refused as private) — the waiting part is landed, the row says the stream is gone", { timeout: 60_000 }, async () => { + const id = "exmplb3gone"; + 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 for a removed stream"), { + request: { resumeOf: startedAt }, + deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, + refresh: { failReads: [1, 2, 3, 4, 5, 6], failWith: PRIVATE }, + }); + await r.run.catch(() => {}); + assert.equal(await storedSeconds(id), 3000, "the only copy is in the store"); + assert.deepEqual(await left(id), []); + const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!; + assert.equal(old.restart?.state, "landed"); + assert.match(old.reason, /private or removed/); +}); + +test("B3: the stream's state cannot be read at the boot (a network error, every read) — what was left is landed all the same; the row says the state is not known and to Record again", { timeout: 60_000 }, async () => { + const id = "exmplb3unk1"; + const { startedAt } = await waitingAtShutdown(id); + await askBoot(id, startedAt); + const r = await incidentRun(id, async () => assert.fail("never a recording on a guess"), { + request: { resumeOf: startedAt }, + deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, + refresh: { failReads: [1, 2, 3, 4, 5, 6] }, + }); + await r.run.catch(() => {}); + assert.equal(await storedSeconds(id), 3000); + const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!; + assert.equal(old.restart?.state, "landed"); + assert.match(old.reason, /could not be read/); + assert.match(old.reason, /Record again/); + assert.equal(old.needsAttention, true, "the stream may still be live: a person"); +}); + +test("B3: the boot resume takes the LONGEST resumable from-start part of any row of the id; the others are released and landed by the rules", { timeout: 60_000 }, async () => { + const id = "exmplb3long"; + const a = await waitingAtShutdown(id, 3000); + // A second run (no resume) also stopped by a shutdown, with a shorter part: + // the first run's part keeps waiting beside it. + const ac = new AbortController(); + const b = await incidentRun( + id, + resumableYtdlp(async ({ write, signal }) => { + await write(1000); + 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 b.run; + const rowB = (await rowOf(id)).find((x) => x.startedAt !== a.startedAt)!; + assert.equal(rowB.awaitingResume?.length, 2, "both wait, 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, 600, "the 3000 s part, the longest, is resumed"); + await write(7200); + live = false; + return "end"; + }), + { request: { resumeOf: rowB.startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + assert.equal((await c.run).status, "landed"); + assert.equal(outOf(c.calls[0]!), a.stem); + assert.equal(await storedSeconds(id), 7200); + assert.deepEqual(await left(id), [], "the shorter waiting part was released, and inside the whole it went"); + assert.ok((await rowOf(id)).every((r) => !r.awaitingResume)); +}); + +test("B4: a stop reaches the recorder's whole tree, and the recorder returns when yt-dlp exits — not when a grandchild holding its pipes does", { timeout: 30_000 }, async () => { + const pidFile = path.join(ROOT, "grandchild.pid"); + // yt-dlp's stand-in: starts a child that inherits its stdout/stderr (as + // yt-dlp's ffmpeg does), says ready, and has no handler for SIGTERM. + const script = `const c = require("child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: ["ignore", "inherit", "inherit"] }); require("fs").writeFileSync(${JSON.stringify(pidFile)}, String(c.pid)); console.log("ready"); setInterval(() => {}, 1000);`; + const ac = new AbortController(); + const lines: string[] = []; + const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: (l) => void lines.push(l), signal: ac.signal, label: "t" }); + const readyBy = Date.now() + 20_000; + while (!lines.some((l) => /^(?:\[t\] )?ready\s*$/.test(l))) { + assert.ok(Date.now() < readyBy, "the child never said it was ready"); + await new Promise((r) => setTimeout(r, 10)); + } + const grandchild = Number(await readFile(pidFile, "utf8")); + const t0 = Date.now(); + ac.abort("SIGTERM"); + const o = await p; + assert.ok(Date.now() - t0 < 8000, `returned ${Date.now() - t0} ms after the stop`); + assert.equal(o.signalled, true); + await new Promise((r) => setTimeout(r, 200)); + assert.throws(() => process.kill(grandchild, 0), "the grandchild is gone too"); +}); + +test("B4: a from-start recorder whose part cannot be resumed (a muxed download, no state) is stopped with SIGINT, which finishes it — never SIGTERM", { timeout: 60_000 }, async () => { + const id = "exmplb4mux1"; + const reasons: unknown[] = []; + const ac = new AbortController(); + const r = await incidentRun( + id, + async (args, _n, signal) => { + // One muxed file, no `.ytdl` (an ffmpeg download keeps none). + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); + setTimeout(() => ac.abort(), 10); + await abortOf(signal); + reasons.push(signal.reason); + return { exitCode: null, stderrTail: "", signalled: true }; + }, + { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } }, + ); + await r.run.catch(() => {}); + assert.deepEqual(reasons, ["SIGINT"]); +}); + +test("B5: a resume pins EVERY stream the run was recording, the empty one included; the empty stream is said at once, not at the landing", { timeout: 60_000 }, async () => { + const id = "exmplb5pin1"; + const { row } = await waitingAtShutdown(id, 3000, { video: 0 }); + assert.equal(row.parts[0]!.missingStream, "video", "said when the recorder stopped"); + assert.match(row.reason, /video/); + await askBoot(id, row.startedAt); + let live = true; + const c = await incidentRun( + id, + resumableYtdlp(async ({ write }) => { + await write(7200); + live = false; + return "end"; + }), + { request: { resumeOf: row.startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + await c.run; + assert.equal(c.calls[0]![c.calls[0]!.indexOf("-f") + 1], "136+140", "both ids, the empty stream's too"); +}); + +test("B5: a stem with only one stream file of a separate recording is not resumed in place (never `-f` one stream alone)", { timeout: 60_000 }, async () => { + const id = "exmplb5one1"; + const { stem, startedAt } = await waitingAtShutdown(id, 3000); + // The picture's file is gone (its state too): one stream left. + await rm(`${stem}.${FAKE_V}`, { force: true }); + await rm(`${stem}.${FAKE_V}.ytdl`, { force: true }); + await askBoot(id, startedAt); + let live = true; + const c = await incidentRun( + id, + resumableYtdlp(async ({ write }) => { + await write(7200); + live = false; + return "end"; + }), + { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + await c.run.catch(() => {}); + assert.notEqual(c.calls[0]![c.calls[0]!.indexOf("-f") + 1], "140", "never one stream alone"); + assert.notEqual(outOf(c.calls[0]!), stem, "not resumed in place: a new from-start part"); + assert.ok(fromStartArg(c.calls[0]!)); +}); + +test("REVIEW-5 note 1: one stream that stops growing while the other grows is a stall — stopped (SIGTERM, resumable) and resumed with both", { timeout: 60_000 }, async () => { + const id = "exmplnote1a"; + let live = true; + const reasons: unknown[] = []; + const { run, calls, log } = await incidentRun( + id, + resumableYtdlp(async ({ n, writeStream, write, signal }) => { + if (n === 1) { + await writeStream("video", 3000); + // The sound goes on; the picture's thread has ended alone. + for (let k = 0; k < 150 && !signal.aborted; k++) { + await writeStream("audio", 3000 + k * 5); + await new Promise((r) => setTimeout(r, 15)); + } + reasons.push(signal.aborted ? signal.reason : "never stopped"); + return { exitCode: null, stderrTail: "", signalled: signal.aborted }; + } + await write(7200); + live = false; + return "end"; + }), + { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } }, + ); + await run; + assert.deepEqual(reasons, ["SIGTERM"]); + assert.ok(log.some((l) => /stream .*f136\.mp4 has not grown/.test(l)), `said which stream: ${log.filter((l) => /stall/.test(l)).join(" | ")}`); + assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place"); + assert.equal(calls[1]![calls[1]!.indexOf("-f") + 1], "136+140"); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -185,6 +185,9 @@ export const VOD_IDLE_END_MS = 10 * 60_000; export const VOD_IDLE_AFTER_LIVE_END_MS = 2 * 60_000; // A recorder that ignores SIGINT this long is killed. export const RECORDER_GRACE_MS = 60_000; +// After the recorder exits, how long its output may take to drain before a +// process still holding it is killed (REVIEW-5 B4). +export const RECORDER_EXIT_DRAIN_MS = 3_000; // The store's disk must have this much free before a recording starts (four // hours of 720p is ~6 GB, of 1080p ~9 GB). export const RECORD_LIVE_MIN_FREE_BYTES = 20 * 1024 ** 3; @@ -195,8 +198,9 @@ export const LIVE_EDGE_EMPTY_TO_END = 3; // stream so far) leaves a span in no part: recovered beside the live edge. export const LIVE_GAP_TOLERANCE_SECONDS = 180; // yt-dlp's YouTube from-start generator holds 120 h (MAX_DURATION): past it -// a saved fragment index no longer lines up. -export const LIVE_RESUME_MAX_AGE_MS = 120 * 3_600_000; +// a saved fragment index no longer lines up. 119 h (REVIEW-5 note 8): an +// hour's margin, as yt-dlp measures the age again after its extraction. +export const LIVE_RESUME_MAX_AGE_MS = 119 * 3_600_000; // A restart after the editor's: the stream's state read again after these // waits when it could not be read (three reads over about ten minutes). export const LIVE_BOOT_STATE_READ_WAITS_MS: readonly number[] = [120_000, 480_000]; @@ -389,14 +393,26 @@ export function isProgressLine(line: string): boolean { return PROGRESS_RE.test(line); } -// ONE RECORDER: spawned as a plain child (so a SIGINT reaches yt-dlp, which -// asks its ffmpeg to quit with `q` and the file is finalized), its output in -// the job's log with the per-second progress thinned to one line every five -// minutes. A Cancel sends SIGINT, then SIGKILL after RECORDER_GRACE_MS. +// ONE RECORDER: spawned in a process group of its own (REVIEW-5 B4), so a +// stop reaches the whole tree — yt-dlp and the ffmpeg it starts with its own +// stdout and stderr: SIGINT (yt-dlp asks its ffmpeg to quit, and ffmpeg +// finishes its file on SIGINT itself), SIGTERM (a resumable part: nothing +// finishes), then SIGKILL after RECORDER_GRACE_MS. Its output is in the job's +// 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 }) => 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"] }); + const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"], detached: true }); + const killTree = (sig: NodeJS.Signals) => { + try { + if (child.pid) process.kill(-child.pid, sig); + else child.kill(sig); + } catch { + child.kill(sig); + } + }; let tail = ""; let sinceProgress = ""; let lastProgress = 0; @@ -428,18 +444,34 @@ export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, la // finishing and a from-start download's `.ytdl` state stays. const how = signal.reason === "SIGTERM" ? "SIGTERM" : "SIGINT"; onLog(`[${label}] stopping: ${how === "SIGTERM" ? "SIGTERM, its state kept for a resume" : "SIGINT, so the recording is finalized"}\n`); - child.kill(how); - killTimer = setTimeout(() => child.kill("SIGKILL"), RECORDER_GRACE_MS); + killTree(how); + killTimer = setTimeout(() => killTree("SIGKILL"), RECORDER_GRACE_MS); }; if (signal.aborted) onAbort(); else signal.addEventListener("abort", onAbort, { once: true }); child.on("error", (err) => { tail += `\n${err.message}`; }); - child.on("close", (code) => { + let done = false; + const finish = (code: number | null) => { + if (done) return; + done = true; if (killTimer) clearTimeout(killTimer); signal.removeEventListener("abort", onAbort); resolve({ exitCode: code, stderrTail: tail, signalled, exitTail: sinceProgress }); + }; + child.on("close", (code) => finish(code)); + child.on("exit", (code) => { + // Its output drains on `close`; a grandchild that keeps the pipes open + // after yt-dlp is gone is killed with the group, and the recorder returns. + setTimeout(() => { + if (done) return; + onLog(`[${label}] yt-dlp exited (${code ?? "signal"}); a process it started still holds its output: the group is killed.\n`); + killTree("SIGKILL"); + child.stdout?.destroy(); + child.stderr?.destroy(); + finish(code); + }, RECORDER_EXIT_DRAIN_MS); }); }); @@ -675,7 +707,8 @@ export type RecordLiveJobOpts = { plan: RecordLivePlan; channelConfig: ChannelConfig; cookiePolicy: ResolvedCookiePolicy; - requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>; + // `replace`: transcribe again over an existing transcript (transcriptRedo). + requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>; // The pre-clip job for this stream (request.preclip), asked for once the // first part begins. startPreclip?: (slug: string, id: string, options: PreclipOptions) => Promise<{ ok: boolean; jobId?: string; error?: string }>; @@ -1103,6 +1136,17 @@ async function recordLiveRunInner( (e: Error) => say(`The interrupted run's row could not be updated (${e.message}).`), ); }; + // The boot's landing of what was left: the old row says what it did. + const bootLandingDone = async (landedIt: boolean, why = "") => { + if (!resumeOf || !bootLanding) return; + await markResume(landedIt ? "landed" : "failed", { reason: landedIt ? bootLanding : `${bootLanding}: what was left was NOT landed — ${why}` }); + }; + // REVIEW-5 B3: what the interrupted run left in staging has a way into the + // store whatever the boot's run finds — the stream ended, removed, or its + // state not readable: the landing takes it (the only copy) by its rules. + 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; try { await refresh(); } catch (err) { @@ -1136,12 +1180,23 @@ async function recordLiveRunInner( if (read) extractionError = null; else { const reads = 1 + LIVE_BOOT_STATE_READ_WAITS_MS.length; - const reason = `${lastErr.message.split("\n")[0]!.slice(0, 240)} — the stream may still be live and is NOT being recorded`; - say(`Restart after the editor restart: the stream's state could not be read (${reason}); nothing is recorded or landed — Record again if it is still live.`); - await markResume("unknown", { reason: `${reads} reads failed: ${reason}` }); - hooks.quiet = true; - await abandon(); - throw lastErr; + const gone = liveFailureClass(lastErr.message) === "private"; + const first = lastErr.message.split("\n")[0]!.slice(0, 240); + if (await leftInStaging()) { + // Never a recording on a guess — but what is left lands. + 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`; + say(`Restart after the editor restart: ${bootUnread}; what the interrupted run left in staging is landed.`); + extractionError = null; + } else { + const reason = `${first} — the stream may still be live and is NOT being recorded`; + say(`Restart after the editor restart: the stream's state could not be read (${reason}); nothing is recorded or landed — Record again if it is still live.`); + await markResume("unknown", { reason: `${reads} reads failed: ${reason}` }); + hooks.quiet = true; + await abandon(); + throw lastErr; + } } } } @@ -1159,7 +1214,14 @@ async function recordLiveRunInner( // interrupted run left in staging lands (the slice-1 landing), or, with // nothing there, the row says so. let resumeEnded = false; - if (resumeOf) { + // The words the interrupted run's row gets once the landing is done. + let bootLanding: string | null = null; + if (resumeOf && bootUnread) { + resumeEnded = true; + endRead = true; + bootLanding = bootUnread; + await markResume("landing", { reason: bootUnread }); + } else if (resumeOf) { if (!meta || !liveStatus) { say("Restart after the editor restart: the stream's record says nothing of its state — nothing is recorded or landed."); await markResume("unknown", { reason: "the metadata names no live_status" }); @@ -1178,7 +1240,8 @@ async function recordLiveRunInner( return summary; } say(`Restart after the editor restart: the stream has ended (${liveStatus}); the ${left.length} part(s) left in staging are landed.`); - await markResume("landing"); + bootLanding = `the stream had ended by the restart (${liveStatus})`; + await markResume("landing", { reason: bootLanding }); resumeEnded = true; endRead = true; } else { @@ -1324,7 +1387,8 @@ async function recordLiveRunInner( if (youtube) { // Its age: from its start time, else (an ended stream) its duration. const age = streamStartSec !== null ? now().getTime() / 1000 - streamStartSec : typeof meta?.duration === "number" ? (meta.duration as number) : null; - return age !== null && age < 120 * 3600; + // (119 h: an hour's margin, REVIEW-5 note 8.) + return age !== null && age * 1000 < LIVE_RESUME_MAX_AGE_MS; } return first && record.reach?.fromStart === true; }; @@ -1411,9 +1475,18 @@ async function recordLiveRunInner( // watchdog or an editor shutdown gets SIGTERM — yt-dlp then does not // finish, and its `.ytdl` state stays for the resume; a person's Cancel // (and every other recorder) SIGINT, which finishes the file. + // REVIEW-5 B4: SIGTERM only for a part that CAN be resumed at the moment + // of the stop (separate streams, each with its state); every other + // recorder — a muxed ffmpeg download keeps no state — gets SIGINT, which + // 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"; const own = new AbortController(); - const onJobAbort = () => own.abort(resumable && stopOf(deps).by === "shutdown" ? "SIGTERM" : "SIGINT"); + const onJobAbort = () => { + if (!(resumable && stopOf(deps).by === "shutdown")) return own.abort("SIGINT"); + void stopHow().then((how) => own.abort(how)); + }; const onOwnStop = () => own.abort("SIGINT"); if (signal.aborted) onJobAbort(); else if (opts.stop?.aborted) onOwnStop(); @@ -1427,26 +1500,49 @@ async function recordLiveRunInner( let last = -1; let lastGrowth = now().getTime(); let busy = false; + // REVIEW-5 note 1: EACH stream file of a separate from-start part must + // grow, not their sum — one format's thread may end alone (yt-dlp) while + // the other goes on for hours. + const perStream = new Map<string, { size: number; at: number }>(); timer = setInterval(() => { if (busy || own.signal.aborted) return; busy = true; - void allBytesOf(stem) - .then((b) => { - const t = now().getTime(); - if (b !== last || (waitForVideo && b === 0)) { - last = b; - lastGrowth = t; - return; - } - if (t - lastGrowth >= stallMs && !own.signal.aborted) { - stalled = true; - say( - `[${tag}] stalled: its files have not grown for ${spanWords((t - lastGrowth) / 1000)} (${formatBytes(b)}); ` + - `stopping this recorder (${resumable ? "SIGTERM: its state is kept for the resume" : "SIGINT"}); its part is kept.`, - ); - own.abort(resumable ? "SIGTERM" : "SIGINT"); + void (async () => { + const b = await allBytesOf(stem); + const t = now().getTime(); + let still: string | null = null; + if (separate && mode !== "now") { + const g = await filesOf(stem); + for (const f of g?.streams ?? []) { + const size = await sizeOf(path.join(slugStore, f)); + const was = perStream.get(f); + if (!was || size !== was.size) perStream.set(f, { size, at: t }); + else if (t - was.at >= stallMs && b > 0 && !(waitForVideo && b === 0)) still = f; } - }) + } + if (still === null && (b !== last || (waitForVideo && b === 0))) { + last = b; + lastGrowth = t; + return; + } + if (b !== last) { + last = b; + lastGrowth = t; + } + const since = still !== null ? t - perStream.get(still)!.at : t - lastGrowth; + if (since >= stallMs && !own.signal.aborted) { + stalled = true; + const how = await stopHow(); + say( + (still !== null + ? `[${tag}] stalled: its stream ${still} has not grown for ${spanWords(since / 1000)} while the part's files did` + : `[${tag}] stalled: its files have not grown for ${spanWords(since / 1000)} (${formatBytes(b)})`) + + `; stopping this recorder (${how === "SIGTERM" ? "SIGTERM: its state is kept for the resume" : "SIGINT"}); its part is kept.`, + ); + own.abort(how); + } + })() + .catch(() => {}) .finally(() => { busy = false; }); @@ -1470,6 +1566,19 @@ async function recordLiveRunInner( } if (stalled) part.stalled = true; finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? (stalled ? " (stopped: stalled)" : " (stopped)") : ""}`); + // REVIEW-5 B5: a stream that recorded nothing is said at once, when its + // recorder stops, not at the landing. + if (separate && mode !== "now") { + const miss = await missingStreamOf(stem).catch(() => null); + if (miss) { + part.missingStream = miss; + record.missingStream = miss; + say(`[${tag}] its ${miss === "unknown" ? "video or audio" : miss} stream has recorded nothing so far: it needs a person if no resume fills it.`); + } else if (part.missingStream && (await bytesOf(stem)) > 0) { + // A resume filled it. + delete part.missingStream; + } + } await save(); return { ...o, part, stem, stalled }; }; @@ -1508,13 +1617,24 @@ async function recordLiveRunInner( const resumeStateOf = async (stem: string): 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" }; - const withBytes: string[] = []; - for (const f of g.streams) if ((await sizeOf(path.join(slugStore, f))) > 0) withBytes.push(f); - if (!withBytes.length) return { ok: false, why: g.finished.length ? "it was finished (merged)" : "nothing to resume" }; + // EVERY stream file of the stem, an empty one included (REVIEW-5 B5): + // yt-dlp opens both and writes their state before any fragment, and + // resumes an empty one from 0 — pinning only the ones with bytes would + // record the rest of the stream without that stream. + const streams = [...g.streams]; + if (!streams.length) return { ok: false, why: g.finished.length ? "it was finished (merged)" : "nothing to resume" }; + if (!(await bytesOf(stem))) return { ok: false, why: "nothing to resume" }; let fragment = Infinity; - for (const f of withBytes) { + for (const f of streams) { const raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null); - if (raw === null) return { ok: false, why: `${f} has no .ytdl state (finished, or never kept)` }; + if (raw === null) { + // An empty stream file with no state yet is resumed from 0. + if ((await sizeOf(path.join(slugStore, f))) === 0) { + fragment = Math.min(fragment, 0); + continue; + } + return { ok: false, why: `${f} has no .ytdl state (finished, or never kept)` }; + } let idx: unknown; try { idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index; @@ -1525,10 +1645,30 @@ async function recordLiveRunInner( fragment = Math.min(fragment, idx); } const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN; - if (Number.isFinite(startMs) && now().getTime() - startMs > LIVE_RESUME_MAX_AGE_MS) return { ok: false, why: "the stream is over 120 h old" }; - const ids = withBytes.map((f) => /\.f([^.]+)\.[a-z0-9]+$/i.exec(f)?.[1]).filter((x): x is string => !!x); - if (ids.length !== withBytes.length) return { ok: false, why: "its format ids cannot be read from its files" }; - return { ok: true, formats: ids.join("+"), fragment }; + // An unknown start is not provable (REVIEW-5 note 8): no resume. + if (!Number.isFinite(startMs)) return { ok: false, why: "the stream's start time is not known" }; + if (now().getTime() - startMs > LIVE_RESUME_MAX_AGE_MS) return { ok: false, why: "the stream is over 119 h old" }; + const ids = streams.map((f) => /\.f([^.]+)\.[a-z0-9]+$/i.exec(f)?.[1]).filter((x): x is string => !!x); + if (ids.length !== streams.length) return { ok: false, why: "its format ids cannot be read from its files" }; + if (separate) { + // A separate recording is a picture and a sound: fewer than two, or two + // of one kind, is not that recording. + if (new Set(ids).size < 2) return { ok: false, why: `only one stream (${ids.join(", ")}) of a separate recording` }; + const kinds: string[] = []; + for (const [k, f] of streams.entries()) { + const fm = Array.isArray(meta?.formats) ? (meta!.formats as Array<Record<string, unknown>>).find((x) => String(x.format_id) === ids[k]) : undefined; + let kind: string | null = fm ? (fm.vcodec === "none" ? "audio" : fm.acodec === "none" ? "video" : "both") : null; + if (!kind && (await sizeOf(path.join(slugStore, f))) > 0) { + const pv = await probe(path.join(slugStore, f)).catch(() => null); + kind = pv ? (pv.videoCodec && pv.audioCodec ? "both" : pv.videoCodec ? "video" : pv.audioCodec ? "audio" : null) : null; + } + if (kind) kinds.push(kind); + } + if (kinds.filter((x) => x === "video").length > 1 || kinds.filter((x) => x === "audio").length > 1) { + return { ok: false, why: `two streams of one kind (${ids.join(", ")})` }; + } + } + return { ok: true, formats: ids.join("+"), fragment: Number.isFinite(fragment) ? fragment : 0 }; }; // The longest a part's files play (its streams' probes), 0 when unread. // The stream-level length a part holds: a finished file's, else the @@ -1998,24 +2138,35 @@ async function recordLiveRunInner( // 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) { - const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); - const oldRow = rows.find((r) => r.id === id && r.startedAt === resumeOf); - for (const p of oldRow?.parts ?? []) { - if (!p.stem || !p.fromStart || p.index0 || p.recovery) continue; - const st = await resumeStateOf(p.stem); - if (st.ok) { - // The mark the interrupted run earned travels with its file. - bootResume = { stem: p.stem, formats: st.formats, ...(p.provenStart ? { provenStart: true } : {}) }; - say(`Restart after the editor restart: ${p.stem} is resumed in place from fragment ${st.fragment}.`); - // This run holds it now: the interrupted row no longer lists it - // as waiting. - const resumed = p.stem; - await patchLiveRecordingRow(paths, req.slug, id, resumeOf, (r) => { - if (!r.awaitingResume?.includes(resumed)) return false; - r.awaitingResume = r.awaitingResume.filter((x) => x !== resumed); - if (!r.awaitingResume.length) delete r.awaitingResume; + // 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 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!), + ]); + let best: { stem: string; formats: string; fragment: number; bytes: number } | null = null; + for (const stem of stems) { + const st = await resumeStateOf(stem); + if (!st.ok) continue; + const b = await allBytesOf(stem); + if (!best || b > best.bytes) best = { stem, formats: st.formats, fragment: st.fragment, bytes: b }; + } + if (best) { + 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}.`); + // 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))) { + await patchLiveRecordingRow(paths, req.slug, id, r.startedAt, (x) => { + if (!x.awaitingResume?.includes(resumed)) return false; + x.awaitingResume = x.awaitingResume.filter((y) => y !== resumed); + if (!x.awaitingResume.length) delete x.awaitingResume; }).catch((e: Error) => say(`The interrupted row could not be updated (${e.message}).`)); - break; } } } @@ -2036,7 +2187,8 @@ async function recordLiveRunInner( const stalledEmpty = o.stalled && bytes === 0 && !signal.aborted; const cls = stalledEmpty ? "nothing" : classifyAttempt({ ...o, bytes, partial: missing !== null }); if (cls === "recorded" || cls === "stopped" || signal.aborted) { - delete record.missingStream; + // (A stream the part has not recorded stays said: REVIEW-5 B5.) + if (!last.part.missingStream) delete record.missingStream; delete record.failureClass; break; } @@ -2061,7 +2213,7 @@ async function recordLiveRunInner( if (missing !== null) last.part.missingStream = missing; record.failureClass = failure; if (missing !== null) record.missingStream = missing; - else delete record.missingStream; + else if (!last.part.missingStream) delete record.missingStream; await save(); lastReason = reason; if (o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) { @@ -2496,14 +2648,20 @@ async function recordLiveRunInner( if (stopped?.by === "shutdown") { for (const g of groups) if ((await resumeStateOf(g.stem)).ok) waitsForResume.add(g.stem); } - // A part an earlier run left waiting to be resumed (its row's - // awaitingResume), which this run did not resume, is not this run's to land, - // remove or count: it waits, as it is, while its state is there. - { + // A part an earlier run left waiting (its row's awaitingResume) that this + // run did not resume is RELEASED (REVIEW-5 B3): no later resume comes for it + // (the boot pass restarts only the newest row), so it is an ordinary part + // of this landing — merged, landed or kept by the rules, never left as the + // only copy in staging. Only a run itself stopped by a shutdown leaves it + // waiting (above), listed on its own row for the next boot. + if (stopped?.by !== "shutdown") { const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []); - const mine = new Set(parts.map((p) => p.stem)); - for (const stem of rows.filter((r) => r.id === id).flatMap((r) => r.awaitingResume ?? [])) { - if (!mine.has(stem) && (await resumeStateOf(stem)).ok) waitsForResume.add(stem); + for (const r of rows.filter((x) => x.id === id && x.startedAt !== record.startedAt && x.awaitingResume?.length)) { + say(`${r.awaitingResume!.join(", ")}: left waiting by the run of ${r.startedAt}, not resumed — landed by the rules with this run's parts.`); + await patchLiveRecordingRow(paths, req.slug, id, r.startedAt, (x) => { + if (!x.awaitingResume?.length) return false; + delete x.awaitingResume; + }).catch((e: Error) => say(`That row could not be updated (${e.message}).`)); } } for (const g of groups) { @@ -2613,6 +2771,7 @@ async function recordLiveRunInner( sayKept(); await save(); if (!unlandable.length && !kept.length) await abandon(); + await bootLandingDone(false, error); summary.status = record.status; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); if (!cancelled) throw new Error(error); @@ -2865,6 +3024,7 @@ async function recordLiveRunInner( if (kept.length) record.keptParts = kept; sayKept(); await save(); + await bootLandingDone(false, `the landing failed: ${why}`); summary.status = record.status; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); throw new Error(record.error); @@ -2883,6 +3043,7 @@ async function recordLiveRunInner( delete record.joins; sayKept(); await save(); + await bootLandingDone(false, `not landed: ${why}`); // The operator's keep marks hold whatever landed (as main did). if (req.doNotClean) { await setDoNotClean(videoDir, true, { @@ -2974,6 +3135,7 @@ async function recordLiveRunInner( await save(); summary.landed = { kept: landed.kept, seconds: landed.newSeconds, container: landed.container }; summary.status = record.status; + await bootLandingDone(true); // 4. Keep it, and hand it on. if (req.doNotClean) { @@ -2999,7 +3161,8 @@ async function recordLiveRunInner( record.transcriptRedo = { ...redo, at: now().toISOString() }; if (redo.verdict === "shorter") { say(`The transcript is the replaced shorter file's (${redo.why}): the transcription is asked again.`); - const r = opts.requestTranscription ? await opts.requestTranscription(req.slug, id) : { ok: false, error: "no transcription can be asked from here" }; + // `replace`: the job would otherwise find transcript.json and do nothing. + const r = opts.requestTranscription ? await opts.requestTranscription(req.slug, id, { replace: true }) : { ok: false, error: "no transcription can be asked from here" }; if (r.ok && r.jobId) record.transcriptRedo.jobId = r.jobId; else record.transcriptRedo.error = r.error ?? "no job"; say(r.ok ? `transcribe-one job ${r.jobId}` : `The transcription was not asked again: ${r.error ?? "no job"} — it needs a person.`); diff --git a/common/controller/transcribeOne.test.ts b/common/controller/transcribeOne.test.ts @@ -136,3 +136,29 @@ test("isMediaDriveHeld: the held class, by instance or by its flag; nothing else assert.equal(isMediaDriveHeld(new Error("boom")), false); assert.equal(isMediaDriveHeld(null), false); }); + +// REVIEW-5 note 11 (live-guard-2): a transcription ASKED AGAIN because the +// transcript is a shorter file's must replace it. Without `replace` an +// existing transcript.json is "already-exists" (the job does nothing); with +// it the engine runs, and the old transcript stays until a new one is made. +test("replace: an existing transcript.json is transcribed again (the engine runs), and is not removed before a new one is made", async () => { + const dir = await mkdtemp(path.join(tmpdir(), "transcribe-replace-")); + try { + const ran = path.join(dir, "engine-ran"); + const bin = path.join(dir, "fake-engine.sh"); + await writeFile(bin, `#!/bin/sh\ntouch ${ran}\nexit 1\n`, { mode: 0o755 }); + await writeFile(path.join(dir, "audio.mp3"), "not really audio"); + await writeFile(path.join(dir, "transcript.json"), "{\"transcription\":[]}"); + const worker: Worker = { id: "w1", name: "fake", kind: "local", enabled: true, priority: 0, appId: "whisper-cpp", config: { bin, model: "model.bin" } }; + const base = { paths: {} as Paths, videoDir: dir, videoId: "vid1", audioFilename: "audio.mp3", worker, onLog: () => {} }; + assert.equal(await transcribeOneVideo(base), "already-exists", "without replace: nothing is done"); + const { existsSync } = await import("node:fs"); + assert.equal(existsSync(ran), false); + const err = await transcribeOneVideo({ ...base, replace: true }).then((v) => v, (e) => e); + assert.notEqual(err, "already-exists"); + assert.equal(existsSync(ran), true, "the engine ran"); + assert.equal(existsSync(path.join(dir, "transcript.json")), true, "the old transcript stays when the engine fails"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts @@ -166,6 +166,10 @@ async function throwIfAudioVanished( export type TranscribeOneOptions = { paths: Paths; + // True transcribes again over an existing transcript.json (a record-live + // landing that replaced the shorter file the transcript was made from). The + // old one stays until the new one is renamed over it. + replace?: boolean; videoDir: string; videoId: string; audioFilename: string; @@ -216,10 +220,11 @@ export async function transcribeOneVideo( const log = opts.onLog ?? ((m: string) => console.log(m)); const transcriptPath = path.join(opts.videoDir, "transcript.json"); - if (await pathExists(transcriptPath)) { + if (!opts.replace && (await pathExists(transcriptPath))) { log(`Transcription for ${opts.videoId} already exists`); return "already-exists"; } + if (opts.replace && (await pathExists(transcriptPath))) log(`Transcribing ${opts.videoId} again: its transcript.json is replaced when the new one is made.`); // NOT OPENED ON A DRIVE THAT IS NOT ANSWERING (lane drive-stall). The audio // is a tierable file, a link onto the channel's media drive; asking for it @@ -592,6 +597,8 @@ export const MAX_WORKER_ATTEMPTS = 3; export type TranscribeWithWorkerOptions = { paths: Paths; + // See TranscribeOneOptions.replace. + replace?: boolean; videoDir: string; videoId: string; audioFilename: string; @@ -700,6 +707,7 @@ export async function transcribeWithWorker( skipInlineDiarization: opts.skipInlineDiarization, words: opts.words, ...(opts.salvage !== undefined ? { salvage: opts.salvage } : {}), + ...(opts.replace ? { replace: true } : {}), }); pool.markSuccess(worker.id); return outcome; diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -770,7 +770,10 @@ export function catchUpTracker(): { feed: (line: string) => boolean; reset: () = // refused not restarted (reason: a restart loop, a recorder of the last // process still writing, the setting off) // failed the job could not be queued (reason) -export type LiveBootRestartState = "starting" | "asked" | "restarted" | "landing" | "ended" | "unknown" | "refused" | "failed"; +// landing: the boot's run is landing what the interrupted run left (the +// stream ended, gone, or its state not readable); landed / failed: what that +// landing did (REVIEW-5 B3: the row says what was done, not what was meant). +export type LiveBootRestartState = "starting" | "asked" | "restarted" | "landing" | "landed" | "ended" | "unknown" | "refused" | "failed"; export type LiveBootRestart = { at: string; by: "boot"; state: LiveBootRestartState; jobId?: string; reason?: string }; diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts @@ -52,8 +52,8 @@ import { whisperVideoAction } from "./videos/[id]/videoActions"; const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -async function requestTranscription(slug: string, id: string): Promise<{ ok: boolean; jobId?: string; error?: string }> { - const r = await whisperVideoAction(slug, id); +async function requestTranscription(slug: string, id: string, o: { replace?: boolean } = {}): Promise<{ ok: boolean; jobId?: string; error?: string }> { + const r = await whisperVideoAction(slug, id, undefined, undefined, undefined, undefined, undefined, o.replace === true); if (!r.ok) return { ok: false, error: r.error }; void r.stream.cancel(); return { ok: true, jobId: r.jobId }; diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -313,6 +313,7 @@ async function queueTranscribeOne(o: { salvage?: boolean; whilePaused?: boolean; prelude?: string[]; + replace?: boolean; }): Promise<StreamActionResult> { const { slug, videoId, salvage, whilePaused } = o; const paths = getPaths(); @@ -338,6 +339,7 @@ async function queueTranscribeOne(o: { signal, ...(salvage !== undefined ? { salvage } : {}), ...(whilePaused ? { whilePaused: true } : {}), + ...(o.replace ? { replace: true } : {}), }); safeRevalidate([`/channels/${slug}/videos/${videoId}`, `/channels/${slug}`]); }, @@ -737,6 +739,9 @@ export async function whisperVideoAction( // true: speech recognition even for a youtube-handling video that lists // English captions (the page's "Audio + Whisper" is that ask). asr?: boolean, + // True transcribes again over an existing transcript.json (record-live's + // landing replaced the shorter file it was made from). + replace?: boolean, ): Promise<WhisperVideoResult> { const r = await loadConfigOrError(slug); if (!r.ok) return r; @@ -750,6 +755,7 @@ export async function whisperVideoAction( const opts = { ...(salvage !== undefined ? { salvage } : {}), ...(whilePaused ? { whilePaused: true } : {}), + ...(replace ? { replace: true } : {}), }; const firstEntries = await readdir(videoDir).catch(() => [] as string[]); const audioOnDisk = firstEntries.some(isRealAudioFile);