commit b675800f72143e62446ee795ad955647d4b32533
parent 3c999157823bd58b5816b9a36c2232ab08a61960
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sun, 22 Nov 2026 00:18:30 -0500
record-live: DESIGN-4 — resume only on proof, a fresh part first, no silent skip, the landed file verified before anything is removed
- 1: from-start separate recorders keep every fragment (--keep-fragments).
lib/liveFragments-server.ts holds the byte accounting:
size == checkpoint + the kept Frags up to the .ytdl index. Only a tail
that is byte for byte the start of the next kept fragment is truncated
back (logged with both lengths); anything else is no resume in place.
The watchdog prunes verified fragments after writing and fsyncing a
checkpoint; short of disk it drops them (the recording goes on, the
part loses resumability, loudly).
- 2: the first fallback is a fresh from-start part (a new stem, proven on
YouTube under 119 h, the insurance re-armed); the live edge plus
recovery only when from-start cannot reach the start.
- 3: --abort-on-unavailable-fragments and --retry-sleep
fragment:exp=1:20. The error line stops the recorder (SIGTERM), which
resumes after 20 s, 60 s and 180 s, then a fresh part; one run that may
skip is the last resort. skippedFragments goes on the part, the landed
file and the row (loud); such a part is never proven. Those lines are
never thinned out of the log.
- 4: -k keeps the stream files through yt-dlp's merge.
lib/liveVerify-server.ts checks the landed file against them per track
(packets equal, spans, a hole scan; ffprobe -v error, so the raw WebM's
unknown-length warnings are not errors). The check runs after the
landing and the hand-off; only a verified file lets the streams,
fragments and parts meant for removal go. Not verified: nothing removed,
the row loud.
- 5: a from-start recorder ending by itself while live has the insurance
re-armed before the confirming read, then a fresh part.
- Note 4: nothing lands at a shutdown while a part waits to be resumed.
- Note 5: a stem lock (<stem>.rec.lock); stale when its process is gone or
it predates the machine's boot.
- Note 12: a boot row stuck at `starting` for more than 10 minutes says it
needs a person.
- The slice-2 recovery state stays "recorded" whichever ends first; both
orders are tested.
- The resumable fake keeps fragments as yt-dlp does and can tear an append.
The live-edge-path tests say freshFromStart: false.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
12 files changed, 1453 insertions(+), 64 deletions(-)
diff --git a/OPERATING.md b/OPERATING.md
@@ -1492,13 +1492,43 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":
EVERY stream file of the part, an empty one included; a separate part with fewer than two streams, or two of one
kind, is not resumed. A stream that recorded nothing is said on the row when its recorder stops. Each stream file
must grow: one that stops for `stallMinutes` while the other grows is a stall. At a shutdown a resumable part is
- not landed: it waits in staging (`awaitingResume`) and the boot's restart resumes the LONGEST resumable from-start
+ not landed (nor is anything else then): it waits in staging (`awaitingResume`) and the boot's restart resumes the LONGEST resumable from-start
part any row of the stream lists (no row then lists it). A waiting part is never the only copy left in staging for
good: any later run of the stream not itself stopped by a shutdown — the boot's run that did not resume it, a
person's Record again — takes it into its landing by the rules (merged, landed, or kept and listed). Only when a
resume is impossible (no state: the file was finished; an unreadable state; a stream past 119 h, or whose start
time is not known; a resume that writes nothing) does the live-edge fallback below run. A state read refused as private or removed is read again a minute later; confirmed, the row says the stream
went private or was removed while recording and what is held (`endedBy`, needing a person).
+- **A resume appends only to a file proven whole; otherwise a FRESH part from the start (DESIGN-4).** A separate-streams
+ from-start recorder runs with `--keep-fragments`, `-k`, `--abort-on-unavailable-fragments` and `--retry-sleep
+ fragment:exp=1:20`. Each stream file must equal its checkpoint (`<f>.frags.json`) plus the kept `<f>-Frag<n>` up to
+ the `.ytdl` index; the only repair is a tail that is byte for byte the start of the next kept fragment (a stop inside
+ an append), truncated back and logged with both lengths. Anything else — shorter, an excess that is not that prefix,
+ the next fragment gone, a missing fragment, no checkpoint (every part of earlier builds) — is no resume in place:
+ the first fallback is a FRESH part from the stream's start (a new stem, `ytdlp-f<n>`, proven on YouTube under
+ 119 h), the insurance re-armed beside it; live edge plus recovery only when from-start cannot reach the start. 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
+ recorder (SIGTERM; yt-dlp would record the other stream on alone) and resumes it after 20 s, 60 s and 180 s; still
+ stuck there, a fresh part; that one stuck at the same fragment, ONE run that may skip it — the part and the landed
+ file carry `skippedFragments` (count, positions), it is never proven and never covers, and the row stays loud after
+ the landing. Those lines (`Skipping fragment`, `Got error`, `.ytdl file is corrupt`, …) are never thinned out of the
+ job log. A from-start recorder that ends by itself while the stream still reads live (yt-dlp's own end ~35 s after
+ its last fragment: an ingest pause) has the insurance re-armed BEFORE the confirming read, then a fresh part.
+ One recorder per stem: `<stem>.rec.lock`, held while it runs; a lock of a dead process, or made before the machine's
+ last boot, is stale and taken over. At a shutdown with a part waiting to be resumed nothing lands: every part waits
+ for the restart's landing. A boot restart still `starting` after 10 minutes never went on: the row says so.
+- **The landed file is verified before anything is removed (DESIGN-4).** After the landing and the transcription
+ hand-off the landed file is checked against the stream files it was merged from (packets per track equal, spans
+ within max(0.5 s, 2 frames), no step between packets over 1.5× the median video step or 2× the audio, nor 0.1 s;
+ decode times only forward), or scanned alone. ffprobe runs at `-v error`: a raw WebM's "unknown-length element"
+ warning, one per fragment, is not an error. Until it is verified the row says `verification: pending`; verified,
+ the stream files, their fragments and every part meant for removal go; not verified, NOTHING is removed and the row
+ needs a person. Cost: about 115 k packets a second plus reading the files — for a 6 h 19 min stream of 683 k video
+ and 980 k audio packets about 15 s of CPU per file, the merged file and its two streams about 30 s, plus reading
+ them (minutes on a spinning disk); it runs at a lower priority, off the landing's own path.
- **A whole file that replaces a shorter stored one asks for the transcription again when the transcript is the short
one's.** Told by the transcript itself: its last cue ends no later than the replaced container's length plus 60 s
while the new container runs on more than 60 s past it, so it holds nothing of the rest (`transcriptRedo` on the
diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts
@@ -130,6 +130,9 @@ async function channelSlugs(paths: Paths): Promise<string[]> {
const ACTIVE = new Set(["running", "queued"]);
+// A boot restart still `starting` after this long never went on.
+export const LIVE_BOOT_STARTING_STALE_MS = 10 * 60_000;
+
function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes: number): string {
const lostWords =
v.lost && v.lost.toSeconds !== null ? `the first ${spanWords(v.lost.toSeconds)} of the stream are NOT recorded` : "the stream's start is NOT recorded";
@@ -187,6 +190,14 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes:
(v.status === "interrupted" ? "" : " — not resumed by this run: a person decides"),
);
}
+ 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`);
+ }
+ for (const p of v.parts ?? []) {
+ if (p.fragmentsDropped) extra.push(`${p.stem ?? "a part"} lost its kept fragments (${p.fragmentsDropped}): it could not be resumed in place`);
+ }
+ if (v.verification?.state === "failed") extra.unshift(`the landed file is NOT verified whole (${v.verification.why ?? "?"}): the stream files it was made from are kept`);
+ else if (v.verification?.state === "pending") extra.push("the landed file is not yet verified against its stream files");
if (v.transcriptRedo) {
const t = v.transcriptRedo;
extra.push(
@@ -217,7 +228,12 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes:
const r = v.restart;
const boot = r
? {
- starting: "being restarted automatically",
+ // REVIEW-5 note 12: `starting` past 10 min is an editor that died
+ // mid-pass — the restart never went on: a person.
+ starting:
+ Date.now() - Date.parse(r.at) > LIVE_BOOT_STARTING_STALE_MS
+ ? `the automatic restart began at ${r.at} and never got going (the editor stopped mid-pass?) — it needs a person: Record again if the stream is still live`
+ : "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: `${r.reason ?? "the stream had ended by the restart"}: what this run left is being landed (job ${r.jobId ?? "?"})`,
@@ -363,6 +379,8 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
...(own?.endedBy ? { endedBy: own.endedBy } : {}),
...(own?.awaitingResume ? { awaitingResume: own.awaitingResume } : {}),
...(own?.transcriptRedo ? { transcriptRedo: own.transcriptRedo } : {}),
+ ...(own?.verification ? { verification: own.verification } : {}),
+ ...(own?.skippedFragments ? { skippedFragments: own.skippedFragments } : {}),
attempts: own?.attempts ?? row.attempts,
parts,
slug,
@@ -387,6 +405,9 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
spaceHeld: own?.spaceHeld ?? row.spaceHeld,
awaitingResume: own?.awaitingResume ?? row.awaitingResume,
transcriptRedo: own?.transcriptRedo ?? row.transcriptRedo,
+ verification: own?.verification ?? row.verification,
+ skippedFragments: own?.skippedFragments ?? row.skippedFragments,
+ parts: own?.parts ?? row.parts,
}),
};
const shown =
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { appendFile, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
@@ -69,6 +69,9 @@ const land = {
},
freeBytes: async () => 1e15,
};
+// The fakes' files are not media: the landing's check (DESIGN-4 4) passes
+// unless a case says otherwise.
+const VERIFY_OK = { verifyMerged: async () => ({ ok: true as const }), verifyScan: async () => ({ ok: true as const }) };
const handoff = async () => ({
workersPaused: true,
laneEnabled: true,
@@ -157,6 +160,7 @@ test("Rumble path A: yt-dlp --live-from-start into a staging part, then landed;
return { exitCode: 0, stderrTail: "", signalled: false };
},
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
},
@@ -216,6 +220,7 @@ test("preclip: the knob parsed (implies transcribe), the pre-clip asked for once
return { exitCode: 0, stderrTail: "", signalled: false };
},
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
},
@@ -248,6 +253,7 @@ test("yt-dlp cannot start at the start: --no-live-from-start with ffmpeg at inde
return { exitCode: 0, stderrTail: "", signalled: false };
},
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
},
@@ -283,6 +289,7 @@ test("Rumble refuses yt-dlp: path B — the page's playlist from a browser, reco
return { exitCode: 0, stderrTail: "", signalled: false };
},
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
},
@@ -344,6 +351,7 @@ test("Kick: the ongoing VOD polled from segment 0 beside the channel's live stre
return { segments: 500, seconds: 5000, gaps: 0, firstSeq: 0, ended: "the VOD has not grown" };
},
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
},
@@ -430,6 +438,7 @@ test("a cancelled recording still lands what it has", async () => {
return { exitCode: 255, stderrTail: "", signalled: true };
},
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
},
@@ -717,9 +726,13 @@ async function incidentRun(
},
jitter: (ms) => ms,
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
shuttingDown: () => false,
+ // The fakes' files are not media: the check passes unless a case says.
+ verifyMerged: async () => ({ ok: true }),
+ verifyScan: async () => ({ ok: true }),
...(opts.deps ?? {}),
},
} as Parameters<typeof recordLiveRun>[0]);
@@ -871,6 +884,15 @@ test("the recorder's progress thinning also catches yt-dlp's numbered stream lin
assert.equal(isProgressLine("2: [download] Destination: x.f140.m4a"), true);
assert.equal(isProgressLine("[download] 50.0% of 10MiB"), true);
assert.equal(isProgressLine("ERROR: The downloaded file is empty"), false);
+ // DESIGN-4 3: a missing or failed fragment is never thinned out of the log
+ // (the lines as the installed yt-dlp printed them, LOG.md DESIGN-4).
+ for (const l of [
+ "[download] fragment not found; Skipping fragment 21 ...",
+ "1: [download] Got error: HTTP Error 503. Retrying fragment 40 (1/10)...",
+ "[download] Skipping fragment 7 ...",
+ "WARNING: .ytdl file is corrupt. Restarting from the beginning ...",
+ "WARNING: Inconsistent state of incomplete fragment download. Restarting from the beginning ...",
+ ]) assert.equal(isProgressLine(l), false, l);
});
// --- REVIEW-1 (21 Nov 2026): what the first slice got wrong, pinned ----------------
@@ -1247,8 +1269,9 @@ test("slice 2: the live edge records, a from-start try beside it records from th
assert.equal(row.parts.find((p) => p.recovery && (p.seconds ?? 0) > 0)?.provenStart, undefined);
assert.ok(row.parts.filter((p) => !p.fromStart).every((p) => p.provenStart === undefined), "nor a live-edge part");
assert.equal(row.coverage?.covers, false);
- // (recorded, or stopped when the live edge ends first under load.)
- assert.ok(["recorded", "stopped"].includes(row.startRecovery?.state ?? ""), `start recovery ${row.startRecovery?.state}`);
+ // "recorded" whichever ends first, the try or the live edge (the loop's
+ // later stop no longer turns a try that recorded into "stopped").
+ assert.equal(row.startRecovery?.state, "recorded");
assert.ok(row.keptParts?.some((k) => /ytdlp-edge-a4$/.test(k.stem)), "the live-edge part is kept");
assert.equal(row.needsAttention, true);
});
@@ -1357,7 +1380,7 @@ test("slice 3: a stalled recorder is stopped, the stream still live, a new part
return { exitCode: 0, stderrTail: "", signalled: false };
},
// (The stream is as old as the stalled part: it had reached the live edge.)
- { deps: FAST_WATCH, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 } },
+ { deps: { ...FAST_WATCH, freshFromStart: false }, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 } },
);
const s = await run;
assert.equal(s.status, "landed");
@@ -2134,7 +2157,7 @@ test("REVIEW 2.1(a): a restart refused with a 429 gets ONE more after 15 min, th
}
return { exitCode: 1, stderrTail: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests\n", signalled: false };
},
- { deps: FAST_WATCH, refresh: { stillLive: () => true }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 }, },
+ { deps: { ...FAST_WATCH, freshFromStart: false }, refresh: { stillLive: () => true }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 }, },
);
await run;
assert.equal(calls.length, 3, "the first recorder, a restart refused with a 429, one more after 15 min");
@@ -2297,7 +2320,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, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
);
await run;
assert.equal(calls.length, 2, "restarted");
@@ -2316,7 +2339,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, merge: fakeMerge }, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 3000 }, },
+ { deps: { ...FAST_WATCH, freshFromStart: false, 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");
@@ -2332,7 +2355,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, merge: fakeMerge }, refresh: { stillLive: () => k < 10 }, meta: { ...YT_META(id2), release_timestamp: Math.floor(Date.now() / 1000) - 300 } },
+ { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => k < 10 }, meta: { ...YT_META(id2), release_timestamp: Math.floor(Date.now() / 1000) - 300 } },
);
await b.run.catch(() => {});
assert.ok(b.calls.length > 1 + 6, `past the hour's bound: ${b.calls.length}`);
@@ -2352,7 +2375,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, merge: fakeMerge }, refresh: { stillLive: () => true }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 3000 }, },
+ { deps: { ...FAST_WATCH, freshFromStart: false, 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");
@@ -2537,7 +2560,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, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
+ { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, freshFromStart: false, 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");
@@ -2571,7 +2594,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, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
+ { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
);
await run;
assert.ok(isEdge(calls[1]!) || isEdge(calls[2]!), "a live-edge recorder");
@@ -2652,7 +2675,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, merge: fakeMerge }, refresh: { stillLive: () => live, failReads: [2] } },
+ { deps: { ...FAST_WATCH, freshFromStart: false, 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");
@@ -2705,6 +2728,8 @@ type FakeResume = { exitCode: number | null; stderrTail: string; signalled: bool
// 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";
+// One fake fragment: a minute of stream.
+const FAKE_FRAG_S = 60;
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 });
@@ -2726,50 +2751,80 @@ function resumableYtdlp(
resumedFrom: number | null;
write: (seconds: number) => Promise<void>;
writeStream: (kind: "video" | "audio", seconds: number) => Promise<void>;
+ // A stop inside the append of the next fragment: `frac` of it written,
+ // its Frag file kept, the state not rewritten (DESIGN-4 1).
+ tear: (kind: "video" | "audio", frac: number) => Promise<void>;
+ // A line on its output, as the recorder reads it.
+ print: (line: string) => void;
signal: AbortSignal;
args: string[];
}) => Promise<"die" | "end" | "hang" | FakeResume>,
) {
let n = 0;
- return async (args: string[], _n: number, signal: AbortSignal): Promise<FakeResume> => {
+ return async (args: string[], _n: number, signal: AbortSignal, onLine?: (l: string) => void): Promise<FakeResume> => {
n++;
const out = outOf(args);
const fromStart = fromStartArg(args);
+ const keepFrags = args.includes("--keep-fragments");
const files = { video: `${out}.${FAKE_V}`, audio: `${out}.${FAKE_A}` };
+ // As yt-dlp's FragmentFD with --keep-fragments: fragment 1 the init, each
+ // later one FAKE_FRAG_S seconds; written to <f>-Frag<n>, appended, THEN
+ // the state.
+ const fragOf = (kind: "video" | "audio", k: number) =>
+ k === 1 ? `format=mp4;${kind === "video" ? "a=none;" : "v=none;"}` : `seconds=${FAKE_FRAG_S};#${k};${"x".repeat(k % 5)}`;
+ const count = { video: 0, audio: 0 };
let resumedFrom: number | null = null;
if (fromStart) {
- 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 } } }));
+ for (const kind of ["video", "audio"] as const) {
+ const st = await readFile(`${files[kind]}.ytdl`, "utf8").catch(() => null);
+ if (st) count[kind] = JSON.parse(st).downloader.current_fragment.index as number;
+ if (st && kind === "video") resumedFrom = count.video;
+ if (!(await stat(files[kind]).catch(() => null))) {
+ await writeFile(files[kind], "");
+ await writeFile(`${files[kind]}.ytdl`, JSON.stringify({ downloader: { current_fragment: { index: 0 } } }));
+ count[kind] = 0;
}
}
}
+ const appendOne = async (kind: "video" | "audio") => {
+ const k = ++count[kind];
+ const frag = `${files[kind]}-Frag${k}`;
+ await writeFile(frag, fragOf(kind, k));
+ await appendFile(files[kind], fragOf(kind, k));
+ await writeFile(`${files[kind]}.ytdl`, JSON.stringify({ downloader: { current_fragment: { index: k } } }));
+ if (!keepFrags) await rm(frag, { force: true });
+ };
+ const want = (seconds: number) => 1 + Math.floor(seconds / FAKE_FRAG_S);
const writeStream = async (kind: "video" | "audio", seconds: number) => {
- // (Its bytes grow with what it holds, as a real stream file's do.)
- 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) } } }));
+ while (count[kind] < want(seconds)) await appendOne(kind);
+ };
+ const tear = async (kind: "video" | "audio", frac: number) => {
+ const k = count[kind] + 1;
+ const body = fragOf(kind, k);
+ await writeFile(`${files[kind]}-Frag${k}`, body);
+ await appendFile(files[kind], body.slice(0, Math.max(1, Math.floor(body.length * frac))));
};
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);
+ // Both streams at once, fragment by fragment (two threads in yt-dlp).
+ while (count.video < want(seconds) || count.audio < want(seconds)) {
+ if (count.video < want(seconds)) await appendOne("video");
+ if (count.audio < want(seconds)) await appendOne("audio");
+ }
};
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 });
+ // `-k`: the streams outlive the merge; without it yt-dlp deletes them.
+ if (!args.includes("-k")) await rm(f, { force: true });
await rm(`${f}.ytdl`, { force: true });
}
};
- const what = await script({ n, resumedFrom, write, writeStream, signal, args });
+ 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") {
await finalize();
@@ -2805,7 +2860,7 @@ test("DESIGN-3: a from-start recorder that dies is RESUMED in place: the same st
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], "136+140", "the format pinned to the ids on disk");
- assert.deepEqual(resumed, [null, 720], "continued from the saved fragment");
+ assert.deepEqual(resumed, [null, 61], "continued from the saved fragment (the init and 60 one-minute fragments)");
assert.equal(calls.filter(isRecovery).length, 0);
const row = (await rowOf(id))[0]!;
assert.equal(row.parts.length, 1, "no new part");
@@ -2883,7 +2938,7 @@ test("DESIGN-3: an editor shutdown leaves the state (SIGTERM), and the boot's re
const second = await incidentRun(
id,
resumableYtdlp(async ({ resumedFrom, write }) => {
- assert.equal(resumedFrom, 600);
+ assert.equal(resumedFrom, 51);
await write(7200);
live = false;
return "end";
@@ -2910,7 +2965,7 @@ test("DESIGN-3: no state to resume (the part was finished) — the fallback: a l
live = false;
return "end";
}),
- { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
);
await run;
assert.equal(calls.length, 2);
@@ -2977,7 +3032,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, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 9 * 3600 }, deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
);
await run;
const row = (await rowOf(id))[0]!;
@@ -3011,7 +3066,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, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
+ { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
);
await run;
assert.ok(recoveryAt > 0, "a recovery try ran");
@@ -3081,6 +3136,7 @@ test("landing: a live-edge part goes only when the landed file is from the start
return { segments: 500, seconds: vod, gaps: 0, firstSeq, ended: "the VOD has not grown" };
},
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
shuttingDown: () => false,
@@ -3270,6 +3326,7 @@ async function rumbleRun(id: string, o: { dvr: string; seconds: number; duration
return { exitCode: 0, stderrTail: "", signalled: false };
},
land,
+ ...VERIFY_OK,
freeBytes: async () => 1e15,
handoff,
shuttingDown: () => o.stop === "shutdown",
@@ -3448,7 +3505,7 @@ test("flow: an editor shutdown stops a from-start run, the BOOT PASS resumes it
second = await incidentRun(
id,
resumableYtdlp(async ({ resumedFrom, write }) => {
- assert.equal(resumedFrom, 600, "from the saved fragment");
+ assert.equal(resumedFrom, 51, "from the saved fragment");
await write(7200);
live = false;
return "end";
@@ -3620,7 +3677,7 @@ test("flow: a boot resume of a part its original run did NOT prove (a row writte
const second = await incidentRun(
id,
resumableYtdlp(async ({ resumedFrom, write }) => {
- assert.equal(resumedFrom, 600);
+ assert.equal(resumedFrom, 51);
await write(7200);
live = false;
return "end";
@@ -3651,7 +3708,8 @@ async function waitingAtShutdown(id: string, seconds = 3000, opts: { video?: num
await abortOf(signal);
return { exitCode: null, stderrTail: "", signalled: true };
}),
- { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } },
+ // (One stream empty on purpose: no stall watch meanwhile.)
+ { signal: ac.signal, deps: { ...FAST_WATCH, ...(opts.video !== undefined ? { stallMs: 60_000 } : {}), join: null, merge: fakeMerge, shuttingDown: () => true } },
);
assert.equal((await r.run).status, "interrupted");
const row = (await rowOf(id))[0]!;
@@ -3745,7 +3803,7 @@ test("B3: the boot resume takes the LONGEST resumable from-start part of any row
const c = await incidentRun(
id,
resumableYtdlp(async ({ resumedFrom, write }) => {
- assert.equal(resumedFrom, 600, "the 3000 s part, the longest, is resumed");
+ assert.equal(resumedFrom, 51, "the 3000 s part, the longest, is resumed");
await write(7200);
live = false;
return "end";
@@ -3853,10 +3911,10 @@ test("REVIEW-5 note 1: one stream that stops growing while the other grows is a
id,
resumableYtdlp(async ({ n, writeStream, write, signal }) => {
if (n === 1) {
- await writeStream("video", 3000);
+ await write(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);
+ for (let k = 1; k < 150 && !signal.aborted; k++) {
+ await writeStream("audio", 3000 + k * FAKE_FRAG_S);
await new Promise((r) => setTimeout(r, 15));
}
reasons.push(signal.aborted ? signal.reason : "never stopped");
@@ -3898,3 +3956,341 @@ test("REVIEW-5 note 3: the restart bound reached on a stream still live does not
assert.ok(log.some((l) => /waits? .*before restart/i.test(l)));
assert.ok(calls.length >= 8);
});
+
+// --- DESIGN-4: resume only on proof, a fresh part first, no silent skip, the merge checked ---------
+
+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 () => {
+ const id = "exmpld4fr01";
+ let live = true;
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(3000);
+ await dropState(args);
+ return "die";
+ }
+ assert.ok(fromStartArg(args) && isFresh(args), `call ${n}: a fresh from-start part`);
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 2);
+ assert.notEqual(outOf(calls[1]!), outOf(calls[0]!), "a new stem");
+ const row = (await rowOf(id))[0]!;
+ const fresh = row.parts.find((p) => p.fresh !== undefined)!;
+ assert.equal(fresh.provenStart, true, "a YouTube from-start part under 119 h: proven");
+ assert.equal(row.coverage?.covers, true);
+ assert.equal(row.verification?.state, "verified");
+ assert.deepEqual(await left(id), [], "the earlier part and every stream file went, after the check");
+});
+
+test("DESIGN-4 1: a torn tail (a shutdown inside an append) — the boot's resume truncates it back (both lengths logged) and resumes; the landed file is whole", { timeout: 60_000 }, async () => {
+ const id = "exmpld4tear";
+ const ac = new AbortController();
+ const first = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, tear, signal }) => {
+ await write(3000);
+ await tear("video", 0.6);
+ 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;
+ const t0 = (await rowOf(id))[0]!.startedAt;
+ await askBoot(id, t0);
+ let live = true;
+ const second = await incidentRun(
+ id,
+ resumableYtdlp(async ({ resumedFrom, write }) => {
+ assert.equal(resumedFrom, 51);
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { 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]!), outOf(first.calls[0]!), "resumed in place");
+ assert.ok(second.log.some((l) => /truncated from \d+ to \d+ bytes/.test(l)), "the repair is logged with both lengths");
+ assert.equal(await storedSeconds(id), 7200);
+});
+
+test("DESIGN-4 1: an excess that is NOT the start of the next kept fragment, or with that fragment gone — never truncated, never resumed in place: a fresh part from the start records, and the old part is landed by the rules", { timeout: 60_000 }, async () => {
+ for (const [id, how] of [
+ ["exmpld4ref1", "garbage"],
+ ["exmpld4ref2", "nofrag"],
+ ] as const) {
+ const { stem, startedAt } = await waitingAtShutdown(id, 3000);
+ // After the shutdown (a crash of the machine, a hand): the tail of the
+ // picture's file is not provable any more.
+ const v = `${stem}.${FAKE_V}`;
+ const before = (await stat(v)).size;
+ await writeFile(`${v}-Frag52`, "seconds=60;#52;xx");
+ await appendFile(v, how === "garbage" ? "garbage that no fragment begins with" : "seconds=60;");
+ if (how === "nofrag") await rm(`${v}-Frag52`, { force: true });
+ const after = (await stat(v)).size;
+ await askBoot(id, startedAt);
+ let live = true;
+ const second = await incidentRun(
+ id,
+ resumableYtdlp(async ({ resumedFrom, write }) => {
+ assert.equal(resumedFrom, null, `${how}: not the old files`);
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await second.run.catch(() => {});
+ assert.notEqual(outOf(second.calls[0]!), stem, `${how}: not resumed in place`);
+ assert.ok(fromStartArg(second.calls[0]!), `${how}: a fresh part from the start`);
+ assert.ok(!second.log.some((l) => /truncated from/.test(l)), `${how}: nothing truncated`);
+ assert.ok(after > before);
+ assert.equal(await storedSeconds(id), 7200, `${how}: the fresh whole landed`);
+ }
+});
+
+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 () => {
+ const id = "exmpld4prn1";
+ let live = true;
+ let free = 1e15;
+ const seenFrags: number[] = [];
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(3000);
+ 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));
+ // Room again (a restart needs it): the fragments stay dropped.
+ free = 1e15;
+ return "die";
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ // (No stall while it waits on purpose: the prune is what is watched.)
+ { 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`);
+ 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");
+ assert.match(row.reason, /lost its kept fragments/);
+});
+
+test("DESIGN-4 3: a fragment that cannot be fetched stops the recorder (SIGTERM) and resumes it after 20 s, 60 s, 180 s; then a fresh part; that one stuck at the same fragment — ONE run that may skip: marked, never proven, the row loud after the landing", { timeout: 60_000 }, async () => {
+ const id = "exmpld4abt1";
+ let live = true;
+ const reasons: unknown[] = [];
+ const GOT = "1: ERROR: [download] Got error: HTTP Error 404: Not Found";
+ const { run, calls, waits, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, print, signal, args }) => {
+ if (args.includes("--skip-unavailable-fragments")) {
+ // The last resort: it skips the fragment and goes on to the end.
+ print("1: [download] fragment not found; Skipping fragment 52 ...");
+ await write(7200);
+ live = false;
+ return "end";
+ }
+ assert.ok(args.includes("--abort-on-unavailable-fragments"));
+ await write(3000);
+ // Fragment 52 of the picture cannot be fetched: its thread ends; yt-dlp
+ // would record the sound on alone — the recorder is stopped.
+ print(GOT);
+ await abortOf(signal);
+ reasons.push(signal.reason);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ const s = await run.catch((e) => e);
+ void s;
+ assert.ok(reasons.every((r) => r === "SIGTERM"), `stopped with SIGTERM, its state kept: ${reasons.join(",")}`);
+ for (const w of [20_000, 60_000, 180_000]) assert.ok(waits.includes(w), `a ${w / 1000} s wait before a resume`);
+ assert.ok(calls.some(isFresh), "then a fresh part from the start");
+ const last = calls[calls.length - 1]!;
+ assert.ok(last.includes("--skip-unavailable-fragments"), "the last resort may skip");
+ // (That the line is never thinned out of the job log: the progress-line test.)
+ assert.ok(log.some((l) => /a fragment could not be fetched/.test(l)), "the stop is said");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.status, "landed");
+ assert.equal(row.skippedFragments?.count, 1);
+ assert.deepEqual(row.skippedFragments?.positions, [52]);
+ assert.equal(row.coverage?.covers, false, "a part with a hole never covers");
+ assert.equal(row.needsAttention, true, "loud after the landing");
+ assert.match(row.reason, /HOLE/);
+});
+
+test("DESIGN-4 4: the landed file NOT verified whole — nothing removed: its stream files and the other parts stay, the row loud; verified — they go, after the check, never before", { timeout: 60_000 }, async () => {
+ const id = "exmpld4ver1";
+ const earlier = await leftover(id, 300);
+ const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ 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: [{ method: "ytdlp", url: ytUrl(id), fromStart: true, provenStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem: path.basename(earlier).replace(/\.mp4$/, "") }],
+ });
+ let live = true;
+ let storedAtCheck: number | null = null;
+ let streamsAtCheck = 0;
+ const r = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write }) => {
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ {
+ deps: {
+ ...FAST_WATCH, join: null, merge: fakeMerge,
+ verifyMerged: async (_m: string, streams: readonly string[]) => {
+ storedAtCheck = await storedSeconds(id);
+ for (const f of streams) if ((await stat(f).catch(() => null))?.size) streamsAtCheck++;
+ return { ok: false, why: "its video: 3590 packets merged, 3600 in the stream" };
+ },
+ },
+ refresh: { stillLive: () => live },
+ },
+ );
+ assert.equal((await r.run).status, "landed");
+ assert.equal(storedAtCheck, 7200, "the check runs after the landing");
+ assert.equal(streamsAtCheck, 2, "with both stream files still there");
+ assert.ok((await stat(earlier)).size > 0, "the earlier part is not removed");
+ assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files are kept");
+ const row = (await rowOf(id)).find((x) => x.status === "landed")!;
+ assert.equal(row.verification?.state, "failed");
+ assert.equal(row.removedParts, undefined);
+ assert.equal(row.needsAttention, true);
+ 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 () => {
+ const id = "exmpld4ing1";
+ let live = true;
+ const order: string[] = [];
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args, signal }) => {
+ if (isInsurance(args)) {
+ order.push("insurance");
+ await write(60);
+ await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ if (n === 1) {
+ // Caught up, then yt-dlp's own finalized end ~35 s after the last fragment.
+ await write(3000);
+ await new Promise((r) => setTimeout(r, 30));
+ return "end";
+ }
+ order.push(isFresh(args) ? "fresh" : "other");
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ {
+ request: { insurance: true },
+ onWait: (ms) => {
+ if (ms === 60_000) order.push("confirm-read");
+ },
+ deps: { ...FAST_WATCH, join: null, merge: fakeMerge, insurancePollMs: 5 },
+ refresh: { stillLive: () => live },
+ },
+ );
+ 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(" → ")}`);
+});
+
+test("note 4: at a shutdown with a part waiting, NOTHING lands — the other part waits too, for the restart", { timeout: 60_000 }, async () => {
+ const id = "exmpln4wt01";
+ const earlier = await leftover(id, 300);
+ const ac = new AbortController();
+ const r = 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 } },
+ );
+ assert.equal((await r.run).status, "interrupted");
+ assert.equal(await storedSeconds(id), null, "nothing in the store");
+ assert.ok((await stat(earlier)).size > 0);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.awaitingResume?.length, 2, "both wait for the restart");
+});
+
+test("note 5: one recorder per stem — a lock held by a live process refuses a second; a lock of a dead process, or one older than the machine's boot, is stale and taken over", async () => {
+ const { takeStemLock } = await import("./recordLive");
+ const dir = path.join(ROOT, "locks");
+ await mkdir(dir, { recursive: true });
+ const a = await takeStemLock(dir, ".x.live-1.ytdlp");
+ assert.equal(a.ok, true);
+ const b = await takeStemLock(dir, ".x.live-1.ytdlp");
+ assert.equal(b.ok, false, "held by a live process (this one)");
+ assert.match((b as { why: string }).why, /another recorder holds/);
+ if (a.ok) await a.release();
+ // A dead process's lock.
+ await writeFile(path.join(dir, ".x.live-2.ytdlp.rec.lock"), JSON.stringify({ pid: 2 ** 22 + 12345, at: new Date().toISOString() }));
+ assert.equal((await takeStemLock(dir, ".x.live-2.ytdlp")).ok, true);
+ // Made before the machine last booted (a pid may be reused since).
+ await writeFile(path.join(dir, ".x.live-3.ytdlp.rec.lock"), JSON.stringify({ pid: process.pid, at: "2000-01-01T00:00:00.000Z" }));
+ assert.equal((await takeStemLock(dir, ".x.live-3.ytdlp")).ok, true);
+});
+
+test("note 12: a boot restart still `starting` after 10 minutes never went on — the row says so and needs a person", async () => {
+ const id = "exmpln12st1";
+ const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await ytChannel();
+ const at = new Date(Date.now() - 20 * 60_000).toISOString();
+ await upsertLiveRecordingRow(paths, YT_SLUG, {
+ id, url: ytUrl(id), platform: "youtube", startedAt: at, status: "interrupted", stoppedBy: "shutdown", fromStart: true, attempts: 1, mustKeep: true, parts: [],
+ restart: { at, by: "boot", state: "starting" },
+ });
+ const row = (await rowOf(id))[0]!;
+ assert.match(row.reason, /never got going/);
+ assert.equal(row.needsAttention, true);
+});
+
+test("slice 2, the other order: the from-start try ends BEFORE the live edge does — its recovery state is still `recorded` (the loop's later stop does not hide it)", async () => {
+ const id = "exmplrecov1b";
+ let endStream!: () => void;
+ const ended = new Promise<void>((r) => (endStream = r));
+ const edge = edgeUntil(ended);
+ let recoveries = 0;
+ const { run } = await incidentRun(id, async (args) => {
+ if (!fromStartArg(args)) return edge(args);
+ if (!isRecovery(args)) return failEmpty;
+ recoveries++;
+ if (recoveries === 1) return failEmpty;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ // The live edge ends a moment AFTER this try has returned.
+ setTimeout(() => endStream(), 150);
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ }, { recovery: 2, meta: { ...ytLiveMeta(id), duration: 7200 } });
+ assert.equal((await run).status, "landed");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.startRecovery?.state, "recorded");
+});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -53,7 +53,8 @@
import path from "node:path";
import { spawn } from "node:child_process";
import { createWriteStream } from "node:fs";
-import { mkdir, readFile, readdir, rm, rmdir, stat } from "node:fs/promises";
+import { mkdir, open, readFile, readdir, rm, rmdir, stat, writeFile } from "node:fs/promises";
+import { uptime } from "node:os";
import { execa } from "execa";
import type { ChannelConfig } from "../lib/channelConfig";
import { assertChannelTextReadable } from "../lib/channelMedia";
@@ -112,6 +113,8 @@ 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 { verifyMerged, verifyScan } from "../lib/liveVerify-server";
import { liveJoinsSidecar, liveRecordingSidecar } from "../lib/mediaImport-server";
import { ffmpegJoinDeps, joinLiveParts, type JoinDeps } from "./liveJoin";
import { loadLiveRecordingRows, patchLiveRecordingRow, rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server";
@@ -188,6 +191,9 @@ 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;
+// DESIGN-4 3: the waits before a resume after a fragment could not be
+// fetched, at the same fragment; past them a fresh from-start part.
+export const FRAGMENT_ABORT_WAITS_MS: readonly number[] = [20_000, 60_000, 180_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;
@@ -389,8 +395,59 @@ export type RecorderSpawn = (opts: {
const PROGRESS_RE = /^(?:\d+:\s*)?(?:frame=|size=|\[download\]\s+(?:\d|Destination:)?)|time=\d\d:\d\d:\d\d/;
const PROGRESS_EVERY_MS = 5 * 60_000;
+// Never thinned (DESIGN-4 3): what says a fragment is missing, failed, or the
+// state is not trusted — each such line is in the job's log.
+const NEVER_THINNED_RE = /Skipping fragment|Got error|fragment \d+ not found|\.ytdl file is corrupt|Inconsistent state|Unable to resume/i;
+
export function isProgressLine(line: string): boolean {
- return PROGRESS_RE.test(line);
+ return PROGRESS_RE.test(line) && !NEVER_THINNED_RE.test(line);
+}
+
+// NOTE 5 (REVIEW-5) — THE STEM LOCK: `<stem>.rec.lock` in the store's staging
+// dir, made with O_EXCL while a recorder of that stem runs, removed when it
+// returns. STALE when the process that made it is gone (its pid answers no
+// signal) or it was made before the machine last booted (a pid may be
+// reused): a stale lock is taken over, said. Held by a live process (this
+// editor's or another's), the recorder is not started on that stem.
+export async function takeStemLock(dir: string, stem: string): Promise<{ ok: true; release: () => Promise<void> } | { ok: false; why: string }> {
+ const file = path.join(dir, `${stem}.rec.lock`);
+ const body = JSON.stringify({ pid: process.pid, at: new Date().toISOString() });
+ for (let tries = 0; tries < 2; tries++) {
+ try {
+ const fh = await open(file, "wx");
+ await fh.writeFile(body);
+ await fh.close();
+ return { ok: true, release: () => rm(file, { force: true }) };
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") return { ok: false, why: `its lock could not be made (${(err as Error).message})` };
+ }
+ const held = await readFile(file, "utf8").then((t) => JSON.parse(t) as { pid?: number; at?: string }, () => null);
+ const bootMs = Date.now() - uptime() * 1000;
+ const alive = (pid: unknown) => {
+ if (typeof pid !== "number") return false;
+ try {
+ process.kill(pid, 0);
+ return true;
+ } catch (e) {
+ return (e as NodeJS.ErrnoException).code === "EPERM";
+ }
+ };
+ const stale = !held || !alive(held.pid) || !held.at || Date.parse(held.at) < bootMs;
+ if (!stale) return { ok: false, why: `another recorder holds ${path.basename(file)} (pid ${held!.pid}, since ${held!.at})` };
+ await rm(file, { force: true });
+ }
+ return { ok: false, why: `its lock ${path.basename(file)} could not be taken` };
+}
+
+// A stem's marks that outlive a run (DESIGN-4): its skipped fragments, and
+// that its kept fragments were dropped for want of disk.
+type StemMarks = { skipped?: { count: number; positions: number[] }; dropped?: string };
+export async function readStemMarks(dir: string, stem: string): Promise<StemMarks> {
+ return readFile(path.join(dir, `${stem}.live-marks.json`), "utf8").then((t) => JSON.parse(t) as StemMarks, () => ({}));
+}
+async function writeStemMarks(dir: string, stem: string, patch: StemMarks): Promise<void> {
+ const cur = await readStemMarks(dir, stem);
+ await writeFile(path.join(dir, `${stem}.live-marks.json`), JSON.stringify({ ...cur, ...patch })).catch(() => {});
}
// ONE RECORDER: spawned in a process group of its own (REVIEW-5 B4), so a
@@ -692,6 +749,12 @@ export type RecordLiveDeps = {
// (default 5 s), its margin after catch-up and its grace after the end
// (defaults LIVE_INSURANCE_MARGIN_MS, LIVE_INSURANCE_END_GRACE_MS).
insurancePollMs?: number;
+ // DESIGN-4 2: false — never a fresh from-start part (tests of the
+ // live-edge path, as where from-start cannot reach the start).
+ freshFromStart?: boolean;
+ // DESIGN-4 4: the merged file against its stream files, and a file alone.
+ verifyMerged?: (merged: string, streams: readonly string[], signal: AbortSignal) => Promise<{ ok: true } | { ok: false; why: string }>;
+ verifyScan?: (file: string, signal: AbortSignal) => Promise<{ ok: true } | { ok: false; why: string }>;
insuranceMarginMs?: number;
insuranceGraceMs?: number;
// Joining parts at the landing (controller/liveJoin.ts; default ffmpeg's);
@@ -1418,8 +1481,11 @@ async function recordLiveRunInner(
resume?: { stem: string; formats: string; provenStart?: boolean };
// The run's first attempt, made with no wait before it (main's proof).
firstAttempt?: boolean;
+ // DESIGN-4 3: the last resort — this run of the part may skip a
+ // fragment that cannot be fetched (the part is marked, never proven).
+ allowSkip?: boolean;
} = {},
- ): Promise<RecorderOutcome & { part: LivePart; stem: string; stalled: boolean }> => {
+ ): Promise<RecorderOutcome & { part: LivePart; stem: string; stalled: boolean; fragAbort?: { index: number | null } ; locked?: string }> => {
const file = opts.resume
? path.join(slugStore, separate ? opts.resume.stem : `${opts.resume.stem}.ts`)
: separate
@@ -1459,6 +1525,7 @@ async function recordLiveRunInner(
separate,
waitForVideo,
...(opts.resume ? { format: opts.resume.formats } : {}),
+ ...(opts.allowSkip ? { allowSkip: true } : {}),
channelArgs: [
...channelExtraArgs(cfg, cookies),
"--downloader-args",
@@ -1494,8 +1561,53 @@ 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.
+ const keptFragmentsTick = async () => {
+ const g = await filesOf(stem);
+ if (!g) return;
+ const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => Infinity);
+ for (const f of g.streams) {
+ if (part.fragmentsDropped) {
+ await dropFragments(slugStore, f).catch(() => 0);
+ continue;
+ }
+ if (free < minFree) {
+ part.fragmentsDropped = `the store's disk had ${formatBytes(free)} free (under ${formatBytes(minFree)})`;
+ await writeStemMarks(slugStore, stem, { dropped: part.fragmentsDropped });
+ say(`[${tag}] the store's disk is short (${formatBytes(free)} free): the recording goes on, but its kept fragments are dropped — this part can no longer be resumed in place.`);
+ await save();
+ 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 });
+ }
+ }
+ }
+ };
let stalled = false;
let timer: NodeJS.Timeout | null = null;
+ // The watch tick in flight: awaited before the recorder's part is handed
+ // back, so no prune or checkpoint write races the landing.
+ let inFlight: Promise<void> = Promise.resolve();
if (opts.watch !== false) {
let last = -1;
let lastGrowth = now().getTime();
@@ -1507,7 +1619,8 @@ async function recordLiveRunInner(
timer = setInterval(() => {
if (busy || own.signal.aborted) return;
busy = true;
- void (async () => {
+ inFlight = (async () => {
+ if (separate && mode === "from-start") await keptFragmentsTick();
const b = await allBytesOf(stem);
const t = now().getTime();
let still: string | null = null;
@@ -1548,6 +1661,44 @@ async function recordLiveRunInner(
});
}, watchMs);
}
+ // NOTE 5 (REVIEW-5) — ONE RECORDER PER STEM: a lock file held while the
+ // recorder runs. yt-dlp would let a second writer append to the same file.
+ const lock = await takeStemLock(slugStore, stem);
+ if (!lock.ok) {
+ if (timer) clearInterval(timer);
+ signal.removeEventListener("abort", onJobAbort);
+ opts.stop?.removeEventListener("abort", onOwnStop);
+ part.error = `not started: ${lock.why}`;
+ finish(part, `${extraNote}not started (${lock.why})`);
+ say(`[${tag}] NOT started: ${lock.why}.`);
+ await save();
+ return { exitCode: null, stderrTail: lock.why, signalled: false, part, stem, stalled: false, locked: lock.why };
+ }
+ // DESIGN-4 3: a fragment that cannot be fetched ends that stream's thread
+ // (--abort-on-unavailable-fragments) while yt-dlp records the other on:
+ // the error line stops the whole recorder, for a resume from the saved
+ // fragment. Every skipped fragment (the last resort) is counted.
+ let fragAbort: { index: number | null } | undefined;
+ const lineHook = (l: string) => {
+ opts.onLine?.(l);
+ if (mode === "now") return;
+ const skip = /Skipping fragment (\d+)/i.exec(l);
+ if (skip) {
+ const sf = (part.skippedFragments ??= { count: 0, positions: [] });
+ sf.count += 1;
+ if (sf.positions.length < 200) sf.positions.push(Number(skip[1]));
+ void writeStemMarks(slugStore, stem, { skipped: sf });
+ }
+ 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) {
+ const m = /fragment (\d+)/i.exec(l);
+ fragAbort = { index: m ? Number(m[1]) : null };
+ say(`[${tag}] a fragment could not be fetched (${l.slice(0, 200)}): its stream stopped; the recorder is stopped for a resume from the saved fragment.`);
+ void stopHow().then((how) => own.abort(how));
+ }
+ }
+ };
let o: RecorderOutcome;
try {
o = await runRecorder({
@@ -1557,12 +1708,14 @@ async function recordLiveRunInner(
onLog,
signal: own.signal,
label: tag,
- ...(opts.onLine ? { onLine: opts.onLine } : {}),
+ onLine: lineHook,
});
} finally {
if (timer) clearInterval(timer);
+ await inFlight;
signal.removeEventListener("abort", onJobAbort);
opts.stop?.removeEventListener("abort", onOwnStop);
+ await lock.release();
}
if (stalled) part.stalled = true;
finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? (stalled ? " (stopped: stalled)" : " (stopped)") : ""}`);
@@ -1579,8 +1732,9 @@ async function recordLiveRunInner(
delete part.missingStream;
}
}
+ if (fragAbort && part.fragmentErrors) await save();
await save();
- return { ...o, part, stem, stalled };
+ return { ...o, part, stem, stalled, ...(fragAbort ? { fragAbort } : {}) };
};
const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0);
const filesOf = async (stem: string): Promise<LivePartFiles | null> =>
@@ -1668,8 +1822,31 @@ async function recordLiveRunInner(
return { ok: false, why: `two streams of one kind (${ids.join(", ")})` };
}
}
+ // DESIGN-4 1: only a file the byte accounting proves (read only here; the
+ // one repair is made just before the resume, reconcileForResume).
+ const marks = await readStemMarks(slugStore, stem);
+ const mine = parts.find((p) => p.stem === stem)?.part;
+ const dropped = marks.dropped ?? mine?.fragmentsDropped;
+ 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 };
+ }
return { ok: true, formats: ids.join("+"), fragment: Number.isFinite(fragment) ? fragment : 0 };
};
+ // The one repair (DESIGN-4 1), made just before a resume: a torn last
+ // append truncated back, logged with both lengths. Anything it cannot
+ // prove: no resume in place.
+ const reconcileForResume = async (stem: string): Promise<{ ok: true } | { ok: false; why: string }> => {
+ const g = await filesOf(stem);
+ for (const f of g?.streams ?? []) {
+ const r = await reconcileStream(slugStore, f, true, say);
+ if (!r.ok) return { ok: false, why: r.why };
+ }
+ return { ok: true };
+ };
// 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
// SHORTEST of its separate streams (REVIEW-4 2.1(a): the picture may lag
@@ -1998,11 +2175,15 @@ async function recordLiveRunInner(
);
let limited = false;
let first = true;
+ // A try that recorded from its start and stopped while the stream was
+ // live: the loop's later stop does not make that "stopped" (the
+ // order of the live edge's end and that try's end is not the point).
+ let recordedOne = false;
while (rs.tries < rs.max) {
if (!(ro.gap && first)) await (deps.recoveryWait ?? waitFor)(stretch(LIVE_RECOVERY_EVERY_MS), waitStop);
first = false;
if (waitStop.aborted || edgeDone) {
- rs.state = "stopped";
+ rs.state = recordedOne ? "recorded" : "stopped";
say(`Start recovery: the live-edge recording ${signal.aborted ? "was stopped" : "ended"} before try ${rs.tries + 1}; no more tries.`);
break;
}
@@ -2081,6 +2262,7 @@ async function recordLiveRunInner(
break;
}
say(`Start recovery: try ${rs.tries} recorded from its start and stopped while the stream is live; its part is kept, the next try follows.`);
+ recordedOne = true;
rs.state = "waiting";
await save();
continue;
@@ -2155,6 +2337,15 @@ async function recordLiveRunInner(
if (!best || b > best.bytes) best = { stem, formats: st.formats, fragment: st.fragment, bytes: b };
}
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.`);
+ best = null;
+ }
+ }
+ 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 } : {}) };
@@ -2308,12 +2499,19 @@ async function recordLiveRunInner(
let emptyInRow = 0;
// Stems whose resume was impossible or wrote nothing (not tried again).
const resumeFailed = new Set<string>();
+ // DESIGN-4 3: aborts per stem at one fragment; where a fresh part's
+ // predecessor could not get past; whether the last fresh part wrote nothing.
+ const abortTries = new Map<string, { fragment: number; n: number }>();
+ let freshAbortAt: number | null = null;
+ 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;
+ 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 && !failedRestart) break;
- const why = cur.o.stalled ? "stalled" : exitedWithBytes ? "exited while the stream was live" : "recorded nothing";
+ if (!stalledWithBytes && !exitedWithBytes && !fragAborted && !failedRestart) break;
+ if (cur.bytes > 0) freshFailedLast = false;
+ const why = cur.o.stalled ? "stalled" : fragAborted ? "a fragment could not be fetched" : exitedWithBytes ? "exited while the stream was live" : "recorded nothing";
// What the recorder said LAST (its output after its last progress
// line), classified — also for a part with bytes (REVIEW-2 3.3).
const said = recentOutput(cur.o);
@@ -2347,6 +2545,10 @@ async function recordLiveRunInner(
// alone): the platform's word decides.
let state = await liveNow();
if (state === "live" && exitedWithBytes && cls !== "rate-limited") {
+ // DESIGN-4 5: a from-start recorder that ended by itself (yt-dlp's
+ // own end after ~35 s with no fragment: an ingest pause) — the live
+ // edge is held at once (the insurance re-armed) before the read.
+ if (cur.mode === "from-start") rearmInsurance();
say(`${cur.o.part.stem}: its recorder exited while the stream reads live; read again in ${spanWords(LIVE_RESTART_CONFIRM_MS / 1000)} before restarting.`);
await waitFor(stretch(LIVE_RESTART_CONFIRM_MS), signal);
if (signal.aborted) break;
@@ -2410,37 +2612,96 @@ async function recordLiveRunInner(
// one, a stream past 120 h, or the resume writes nothing) does the
// live-edge fallback below run.
if (cur.mode === "from-start" && !resumeFailed.has(cur.o.stem)) {
- const st = await resumeStateOf(cur.o.stem);
+ let st = await resumeStateOf(cur.o.stem);
+ // 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
+ // fragment is gone: ONE run of it that may skip (marked, loud).
+ let allowSkip = false;
+ if (st.ok && cur.o.fragAbort) {
+ const a = abortTries.get(cur.o.stem);
+ const n = a && a.fragment === st.fragment ? a.n + 1 : 1;
+ abortTries.set(cur.o.stem, { fragment: st.fragment, n });
+ if (cur.o.part.fresh !== undefined && freshAbortAt !== null && st.fragment === freshAbortAt && n > FRAGMENT_ABORT_WAITS_MS.length) {
+ allowSkip = true;
+ say(`${cur.o.part.stem}: fragment ${st.fragment + 1} cannot be fetched by a fresh part either — the fragment is gone; one run that may SKIP it (the part is marked, never proven, and the row stays loud).`);
+ } else if (n <= FRAGMENT_ABORT_WAITS_MS.length) {
+ const w = FRAGMENT_ABORT_WAITS_MS[n - 1]!;
+ say(`${cur.o.part.stem}: fragment ${st.fragment + 1} could not be fetched; resumed in ${spanWords(w / 1000)} (try ${n} of ${FRAGMENT_ABORT_WAITS_MS.length} at that fragment).`);
+ await waitFor(stretch(w), signal);
+ if (signal.aborted) break;
+ } else {
+ freshAbortAt = st.fragment;
+ st = { ok: false, why: `fragment ${st.fragment + 1} could not be fetched after ${FRAGMENT_ABORT_WAITS_MS.length} resumes` };
+ }
+ }
+ if (st.ok) {
+ const rc = await reconcileForResume(cur.o.stem);
+ if (!rc.ok) st = { ok: false, why: rc.why };
+ }
if (st.ok) {
restarts.count += 1;
restarts.at.push(now().toISOString());
- const before = await allBytesOf(cur.o.stem);
+ const before = await bytesOf(cur.o.stem);
say(`Resume ${(cur.o.part.resumes ?? 0) + 1} of ${cur.o.part.stem} (${why}): the same files from fragment ${st.fragment}, format ${st.formats}.`);
const o = await ytdlpPart(plan.url, "resume", "from-start", `resume (${why}); `, {
resume: { stem: cur.o.stem, formats: st.formats },
noWait: true,
onStart: onMainStart("from-start", true),
onLine: onMainLine,
+ ...(allowSkip ? { allowSkip: true } : {}),
});
- const after = await allBytesOf(o.stem);
+ // Media bytes only (REVIEW-5 note 12: a rewritten state is no progress).
const bytes = await bytesOf(o.stem);
- if (after > before) {
+ // A resume stopped again by a fragment it cannot fetch is one more
+ // try at that fragment (DESIGN-4 3), not "wrote nothing".
+ if (bytes > before || (o.fragAbort && !signal.aborted)) {
emptyInRow = 0;
const partial = separate && !o.signalled && bytes > 0 ? (await missingStreamOf(o.stem)) !== null : false;
cur = { o, bytes, mode: "from-start", partial };
continue;
}
const last = recentOutput(o);
- o.part.resumeError = lastErrorLine(last) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
+ o.part.resumeError = o.locked ?? lastErrorLine(last) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
await save();
- say(`The resume wrote nothing (${o.part.resumeError}): the live-edge fallback.`);
+ say(`The resume wrote nothing (${o.part.resumeError}).`);
resumeFailed.add(o.stem);
if (o.signalled && signal.aborted) break;
} else {
- say(`${cur.o.part.stem} cannot be resumed (${st.why}): the live-edge fallback.`);
+ say(`${cur.o.part.stem} cannot be resumed in place (${st.why}).`);
resumeFailed.add(cur.o.stem);
}
}
+ // DESIGN-4 2 — THE FIRST FALLBACK IS A FRESH FROM-START PART (a new
+ // stem) wherever from-start still reaches the start: YouTube, its
+ // start known and under 119 h (the proof's rule). The earlier part
+ // stays (a copy); the fresh whole covers it at the landing. A
+ // catching-up fresh part re-arms the insurance (onMainStart). Live
+ // edge plus recovery only when it cannot, or it wrote nothing.
+ if (fromStart && separate && deps.freshFromStart !== false && !freshFailedLast && startProvable(false)) {
+ 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 o = await ytdlpPart(plan.url, `ytdlp-f${k}`, "from-start", `fresh ${k} (${why}); `, {
+ restart: k,
+ noWait: true,
+ onStart: onMainStart("from-start", true),
+ onLine: onMainLine,
+ });
+ o.part.fresh = k;
+ await save();
+ const bytes = await bytesOf(o.stem);
+ if (bytes > 0) {
+ emptyInRow = 0;
+ const partial = separate && !o.signalled ? (await missingStreamOf(o.stem)) !== null : false;
+ cur = { o, bytes, mode: "from-start", partial };
+ continue;
+ }
+ freshFailedLast = true;
+ if (o.signalled && signal.aborted) break;
+ say(`The fresh from-start part wrote nothing (${lastErrorLine(recentOutput(o)) ?? `yt-dlp exit ${o.exitCode ?? "null"}`}): the live-edge fallback.`);
+ }
// NO SPAN OF A LIVE STREAM IN NO PART WHILE IT CAN BE FETCHED (REVIEW-3
// 3.1): where do the kept parts reach on the stream's clock? From-start
// parts from 0, live-edge parts from their recorder's start; their
@@ -2657,6 +2918,12 @@ async function recordLiveRunInner(
const waitsForResume = new Set<string>();
if (stopped?.by === "shutdown") {
for (const g of groups) if ((await resumeStateOf(g.stem)).ok) waitsForResume.add(g.stem);
+ // REVIEW-5 note 4: with a part waiting the run is not over — NOTHING
+ // lands at this shutdown; every part waits for the restart's landing.
+ if (waitsForResume.size) {
+ for (const g of groups) waitsForResume.add(g.stem);
+ say(`A part waits to be resumed: nothing lands at this shutdown; all ${groups.length} part(s) stay in staging for the restart.`);
+ }
}
// 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
@@ -2678,7 +2945,7 @@ async function recordLiveRunInner(
const part = partOf.get(g.stem);
if (waitsForResume.has(g.stem)) {
(record.awaitingResume ??= []).push(g.stem);
- say(`${g.stem}: kept as it is, with its .ytdl state, to be resumed after the restart.`);
+ say(`${g.stem}: kept as it is, for the restart (resumed in place when it can be, else landed by its rules).`);
continue;
}
let got: ResolvedPart | null = null;
@@ -2797,7 +3064,9 @@ async function recordLiveRunInner(
// live-edge part, and a part of a row written before the mark are not
// proven, whatever `fromStart` says. And never a restart's sibling or a
// stalled part (REVIEW-1 1.4 of live-guard-2): those go by coverage only.
- const proven = (p: Pick<LivePart, "fromStart" | "provenStart"> | undefined) => p?.fromStart === true && p.provenStart === true;
+ // (DESIGN-4 3: never a part with a skipped fragment.)
+ const proven = (p: Pick<LivePart, "fromStart" | "provenStart" | "skippedFragments"> | undefined) =>
+ p?.fromStart === true && p.provenStart === true && !(p.skippedFragments && p.skippedFragments.count > 0);
const sure = (p: LivePart) => p.restart === undefined && !p.stalled;
const contained = (c: Candidate) =>
c !== best &&
@@ -3117,11 +3386,20 @@ async function recordLiveRunInner(
if (landed.kept !== "new") {
return notLanded(`the store holds a recording as long or longer (${spanWords(landed.existingSeconds ?? 0)}); this one may hold time it does not`);
}
- for (const r of toRemove) await removeGroup(r.group, r.why, r.extra);
- // The landed part's files were staging scratch (it is moved or copied into
- // the store), and so were the streams a merge was made from.
+ // DESIGN-4 4 — LANDED AS "NOT YET VERIFIED": the landed file is in the
+ // store; the stream files it was merged from, and every part meant for
+ // removal, stay until it is verified (after the hand-off, below) — never
+ // the other order. The landed file in staging itself was moved or copied.
await rm(best.file, { force: true });
- for (const f of [...best.group.finished, ...best.group.streams, ...best.group.scratch]) await rm(at(f), { force: true });
+ const mergedFrom = best.group.streams.filter((f) => at(f) !== best.file);
+ const verifyAgainst: string[] = [];
+ for (const f of mergedFrom) if ((await sizeOf(at(f))) > 0) verifyAgainst.push(at(f));
+ record.verification = { state: "pending", at: now().toISOString(), ...(verifyAgainst.length ? { against: verifyAgainst.map((f) => path.basename(f)) } : {}) };
+ const skippedHere = best.part?.skippedFragments ?? (await readStemMarks(slugStore, best.group.stem)).skipped;
+ if (skippedHere && skippedHere.count > 0) {
+ record.skippedFragments = { ...skippedHere };
+ say(`The landed file holds a HOLE: ${skippedHere.count} fragment(s) yt-dlp could not fetch${skippedHere.positions.length ? ` (positions ${skippedHere.positions.slice(0, 10).join(", ")})` : ""}; the row stays loud.`);
+ }
sayKept();
record.landedPart = best.part ? record.parts.indexOf(best.part) : undefined;
record.kept = landed.kept;
@@ -3185,6 +3463,47 @@ async function recordLiveRunInner(
say(r.ok ? `transcribe-one job ${r.jobId}` : `The transcribe-one job was not queued: ${r.error ?? "no job"}`);
}
for (const l of transcriptionHandoffLines(facts)) say(l);
+
+ // 5. DESIGN-4 4 — THE CHECK, then the removals: the landed file against the
+ // stream files it was merged from (packets per track, spans, a hole scan),
+ // or scanned alone. Verified: the streams, their fragments and every part
+ // meant for removal go. Not: nothing goes — kept and listed, the row loud.
+ {
+ const ffprobe = paths.ffprobeBin || "ffprobe";
+ let verdict: { ok: true } | { ok: false; why: string };
+ try {
+ verdict = !landed.container
+ ? { ok: false, why: "there is no stored file to check" }
+ : verifyAgainst.length
+ ? await (deps.verifyMerged ?? ((m, st, sg) => verifyMerged(ffprobe, m, st, sg)))(landed.container, verifyAgainst, landSignal)
+ : await (deps.verifyScan ?? ((f, sg) => verifyScan(ffprobe, f, sg)))(landed.container, landSignal);
+ } catch (err) {
+ verdict = { ok: false, why: (err as Error).message };
+ }
+ const keptBefore = kept.length;
+ if (verdict.ok) {
+ record.verification = { ...record.verification!, state: "verified", at: now().toISOString() };
+ say(`The landed file is verified whole (${verifyAgainst.length ? `against ${verifyAgainst.map((f) => path.basename(f)).join(", ")}` : "its scan"}).`);
+ 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 });
+ if (removed.length) record.removedParts = removed;
+ for (const r of removed) say(`Removed: ${r.stem} (${formatBytes(r.bytes)}) — ${r.why}.`);
+ } else if (landSignal.aborted) {
+ record.verification = { ...record.verification!, why: "stopped before the check" };
+ say("Stopped before the landed file was verified: nothing is removed; the stream files and the other parts stay.");
+ for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: the landed file is not yet verified`, r.o);
+ } else {
+ record.verification = { ...record.verification!, state: "failed", at: now().toISOString(), why: verdict.why };
+ say(`The landed file is NOT verified whole (${verdict.why}): nothing is removed — its stream files and every other part stay, and the row needs a person.`);
+ await keep(best.group, `the files the landed file was made from: it is NOT verified whole (${verdict.why})`, { ...(best.part ? { part: best.part } : {}) });
+ for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: the landed file is not verified whole`, r.o);
+ }
+ if (kept.length > keptBefore) {
+ record.keptParts = kept;
+ for (const k of kept.slice(keptBefore)) say(`Kept, not removed: ${k.stem} (${formatBytes(k.bytes)}) — ${k.why}.`);
+ }
+ await save();
+ }
say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
return summary;
}
diff --git a/common/lib/liveCapture.test.ts b/common/lib/liveCapture.test.ts
@@ -189,6 +189,15 @@ test("separate streams (YouTube): the video at the height plus the best audio, m
assert.equal(args[args.indexOf("--merge-output-format") + 1], "mp4/mkv");
assert.equal(args[args.indexOf("-o") + 1], "/store/s/.5-XlMxKT494.live-T.ytdlp.%(ext)s");
for (const flag of ["--live-from-start", "--no-part"]) assert.ok(args.includes(flag), flag);
+ // DESIGN-4: the streams kept through the merge, every fragment kept, a
+ // fragment that cannot be fetched ends the stream (retried with a back-off).
+ for (const flag of ["-k", "--keep-fragments", "--abort-on-unavailable-fragments"]) assert.ok(args.includes(flag), flag);
+ assert.equal(args[args.indexOf("--retry-sleep") + 1], "fragment:exp=1:20");
+ assert.ok(!args.includes("--skip-unavailable-fragments"));
+ const last = ytdlpLiveArgs({ url: "u", output: "o", fromStart: true, maxHeight: 720, channelArgs: [], separate: true, allowSkip: true });
+ assert.ok(last.includes("--skip-unavailable-fragments") && !last.includes("--abort-on-unavailable-fragments"), "the last resort may skip");
+ const edge = ytdlpLiveArgs({ url: "u", output: "o", fromStart: false, maxHeight: 720, channelArgs: [], separate: true });
+ assert.ok(edge.includes("-k") && !edge.includes("--keep-fragments"), "the live edge keeps its streams through the merge, no fragments");
assert.ok(formatUnavailable("ERROR: [youtube] 5-XlMxKT494: Requested format is not available. Use --list-formats"));
});
diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts
@@ -258,6 +258,9 @@ export function ytdlpLiveArgs(opts: {
waitForVideo?: boolean;
// A resume (DESIGN-3): the format ids already on disk, pinned.
format?: string;
+ // DESIGN-4 3: the last resort for a fragment that cannot be fetched — this
+ // one run may SKIP it (the part is then marked, never proven).
+ allowSkip?: boolean;
}): string[] {
return [
"--ignore-config",
@@ -269,6 +272,17 @@ export function ytdlpLiveArgs(opts: {
"-f",
opts.format ?? liveFormatSelector(opts.maxHeight, opts.separate === true),
...(opts.separate ? ["--merge-output-format", LIVE_MERGE_OUTPUT_FORMAT] : []),
+ // DESIGN-4 4: the stream files outlive yt-dlp's merge, until the editor
+ // has checked the merged file against them.
+ ...(opts.separate ? ["-k"] : []),
+ // DESIGN-4 1, 3: a from-start download keeps every fragment (the byte
+ // accounting a resume rests on), and a fragment that cannot be fetched
+ // ends its stream instead of leaving a hole, retried with a back-off.
+ // (Separate streams only: a muxed recording is ffmpeg's, with no fragments
+ // of yt-dlp's, and its argv stays exactly what it was.)
+ ...(opts.fromStart && opts.separate
+ ? ["--keep-fragments", ...(opts.allowSkip ? ["--skip-unavailable-fragments"] : ["--abort-on-unavailable-fragments"]), "--retry-sleep", "fragment:exp=1:20"]
+ : []),
"--hls-use-mpegts",
"--no-part",
"--fixup",
@@ -470,6 +484,18 @@ export type LivePart = {
resumes?: number;
// Why the last resume wrote nothing (the fallback followed).
resumeError?: string;
+ // DESIGN-4 3: fragments yt-dlp skipped (the last resort, or a gap in the
+ // kept fragment numbers): how many, and which (generator positions, as far
+ // as known). A part with any is never proven, never covers, never resumed
+ // in place, and its row stays loud after the landing.
+ skippedFragments?: { count: number; positions: number[] };
+ // Fragments that could not be fetched (the abort's error lines).
+ fragmentErrors?: 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;
// 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
@@ -588,6 +614,12 @@ export type LiveRecordingRecord = {
awaitingResume?: string[];
// The transcript was the replaced shorter file's (LiveTranscriptRedo).
transcriptRedo?: LiveTranscriptRedo;
+ // DESIGN-4 4: the landed file checked against the stream files it was
+ // merged from (or scanned alone) before they, and every part meant for
+ // removal, were removed. pending: landed, not yet verified.
+ verification?: LiveVerification;
+ // The landed file holds skipped fragments (its part's skippedFragments).
+ skippedFragments?: { count: number; positions: number[] };
// 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[];
@@ -637,6 +669,8 @@ export const LIVE_JOINS_FILENAME = "live-joins.json";
export type LiveSpaceHeld = { what: string; at: string; freeBytes: number };
+export type LiveVerification = { state: "pending" | "verified" | "failed"; at: string; why?: string; against?: string[] };
+
// A landing that REPLACED a shorter stored container while the video's
// transcript does not reach past that container's end (REVIEW-LF-4 2): the
// transcript is the short file's, and the transcription is asked again.
diff --git a/common/lib/liveFragments-server.test.ts b/common/lib/liveFragments-server.test.ts
@@ -0,0 +1,125 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { appendFile, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { accountStream, checkpointName, dropFragments, fragmentGaps, pruneStream, reconcileStream } from "./liveFragments-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/liveFragments-server.test.ts
+//
+// The layout is the one the installed yt-dlp leaves with --keep-fragments
+// (measured, LOG.md DESIGN-4): `<f>` the appended fragments, `<f>-Frag<n>`
+// each fragment, `<f>.ytdl` the count appended.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-frags-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+let k = 0;
+const frag = (n: number) => Buffer.from(`<fragment ${n} ${"x".repeat(40 + (n % 7))}>`);
+// A stream file of fragments 1..n appended, each kept, the state at n.
+async function laid(n: number) {
+ const dir = path.join(ROOT, `d${k++}`);
+ const { mkdir } = await import("node:fs/promises");
+ await mkdir(dir);
+ const name = "s.f136.mp4";
+ await writeFile(path.join(dir, name), "");
+ for (let i = 1; i <= n; i++) {
+ await writeFile(path.join(dir, `${name}-Frag${i}`), frag(i));
+ await appendFile(path.join(dir, name), frag(i));
+ }
+ await writeFile(path.join(dir, `${name}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: n } } }));
+ return { dir, name, file: path.join(dir, name) };
+}
+
+test("aligned: the size is the sum of fragments 1..index", async () => {
+ const s = await laid(12);
+ const a = await accountStream(s.dir, s.name);
+ assert.equal(a.ok, true);
+ assert.deepEqual(await reconcileStream(s.dir, s.name, true), { ok: true });
+});
+
+test("a stop inside the append of the next fragment (torn tail): truncated back, logged with both lengths; a whole uncounted fragment too", async () => {
+ const s = await laid(12);
+ const before = (await stat(s.file)).size;
+ await writeFile(`${s.file}-Frag13`, frag(13));
+ await appendFile(s.file, frag(13).subarray(0, 20));
+ const said: string[] = [];
+ assert.deepEqual(await reconcileStream(s.dir, s.name, false), { ok: true, truncated: { from: before + 20, to: before } });
+ assert.equal((await stat(s.file)).size, before + 20, "a dry run writes nothing");
+ const r = await reconcileStream(s.dir, s.name, true, (l) => void said.push(l));
+ assert.deepEqual(r, { ok: true, truncated: { from: before + 20, to: before } });
+ assert.equal((await stat(s.file)).size, before);
+ assert.match(said[0]!, new RegExp(`from ${before + 20} to ${before} bytes`));
+ // The whole fragment appended, the state not yet rewritten.
+ await appendFile(s.file, frag(13));
+ assert.equal((await reconcileStream(s.dir, s.name, true)).ok, true);
+ assert.equal((await stat(s.file)).size, before);
+});
+
+test("REFUSED: an excess that is not the start of the next fragment, and an excess with the next fragment not kept — nothing written", async () => {
+ const s = await laid(12);
+ const before = (await stat(s.file)).size;
+ await writeFile(`${s.file}-Frag13`, frag(13));
+ await appendFile(s.file, Buffer.from("something else entirely"));
+ const r = await reconcileStream(s.dir, s.name, true);
+ assert.equal(r.ok, false);
+ assert.match((r as { why: string }).why, /not the start of fragment 13/);
+ assert.equal((await stat(s.file)).size, before + 23, "untouched");
+ await rm(`${s.file}-Frag13`);
+ const r2 = await reconcileStream(s.dir, s.name, true);
+ assert.equal(r2.ok, false);
+ assert.match((r2 as { why: string }).why, /fragment 13 is not kept/);
+ assert.equal((await stat(s.file)).size, before + 23, "untouched");
+});
+
+test("REFUSED: a file shorter than its fragments (a crash lost unflushed bytes), a missing fragment, no accounting at all", async () => {
+ const s = await laid(12);
+ const { truncate } = await import("node:fs/promises");
+ await truncate(s.file, (await stat(s.file)).size - 5);
+ assert.match(((await accountStream(s.dir, s.name)) as { why: string }).why, /not in the file/);
+ const t = await laid(12);
+ await rm(`${t.file}-Frag5`);
+ assert.match(((await accountStream(t.dir, t.name)) as { why: string }).why, /fragment 5 .* is not kept/);
+ // A part of an earlier build: bytes and a state, no fragments kept.
+ const u = await laid(3);
+ for (const n of [1, 2, 3]) await rm(`${u.file}-Frag${n}`);
+ assert.equal((await reconcileStream(u.dir, u.name, true)).ok, false);
+});
+
+test("the prune: checkpoint written BEFORE the fragments it covers go; a crash between the two leaves the accounting whole", async () => {
+ const s = await laid(10);
+ // The delete dies after two fragments (a crash).
+ let n = 0;
+ await assert.rejects(
+ pruneStream(s.dir, s.name, {
+ remove: async (f) => {
+ if (n++ === 2) throw new Error("crash");
+ await rm(f);
+ },
+ }),
+ );
+ assert.deepEqual(JSON.parse(await readFile(path.join(s.dir, checkpointName(s.name)), "utf8")), { index: 10, bytes: (await stat(s.file)).size });
+ assert.equal((await accountStream(s.dir, s.name)).ok, true, "the leftovers are below the checkpoint");
+ // More fragments, a second prune: only the checkpoint and nothing kept below it.
+ for (const i of [11, 12]) {
+ await writeFile(`${s.file}-Frag${i}`, frag(i));
+ await appendFile(s.file, frag(i));
+ }
+ await writeFile(`${s.file}.ytdl`, JSON.stringify({ downloader: { current_fragment: { index: 12 } } }));
+ assert.equal((await accountStream(s.dir, s.name)).ok, true);
+ const p = await pruneStream(s.dir, s.name);
+ assert.equal((p as { index: number }).index, 12);
+ assert.deepEqual((await readdir(s.dir)).filter((x) => /-Frag/.test(x)), []);
+ // A torn append after a prune is still repaired from the next kept fragment.
+ await writeFile(`${s.file}-Frag13`, frag(13));
+ await appendFile(s.file, frag(13).subarray(0, 9));
+ assert.equal((await reconcileStream(s.dir, s.name, true)).ok, true);
+});
+
+test("short of disk: the fragments are dropped (resumability goes, the recording does not); gaps in kept numbers are skips", async () => {
+ const s = await laid(6);
+ await writeFile(`${s.file}-Frag7`, frag(7));
+ assert.equal(await dropFragments(s.dir, s.name), 6, "up to the state's index; the one in flight stays");
+ assert.equal((await accountStream(s.dir, s.name)).ok, false);
+ assert.deepEqual(fragmentGaps([3, 4, 7, 8, 10], 3), [5, 6, 9]);
+});
diff --git a/common/lib/liveFragments-server.ts b/common/lib/liveFragments-server.ts
@@ -0,0 +1,196 @@
+// THE BYTE ACCOUNTING A RESUME IN PLACE RESTS ON (DESIGN-4 1).
+//
+// A separate-streams from-start recording runs yt-dlp with `--keep-fragments`:
+// every fragment it appends to a stream file `<f>` stays on disk as
+// `<f>-Frag<n>` (downloader/fragment.py: the fragment is written, appended,
+// THEN the `.ytdl` index is rewritten, and only then — without the flag — is
+// the fragment file removed). So after any stop the stream file's size is
+// exactly the sum of Frag1..Frag<index>, the index the `.ytdl` holds — measured
+// on the installed yt-dlp, fMP4 and WebM alike (LOG.md, DESIGN-4).
+//
+// The editor deletes the fragments it has verified, a minute at a time, after
+// writing (and fsyncing) a checkpoint `<f>.frags.json` {index, bytes}: the
+// stream file's first `bytes` are fragments 1..index. The equation is then
+//
+// size(<f>) == checkpoint.bytes + Σ size(Frag<n>), n = checkpoint.index+1 .. index
+//
+// with every such Frag present. A resume appends only to a file for which it
+// holds. The one repair: a stop inside (or just after) the append of fragment
+// index+1 leaves the file LONGER by a prefix of that fragment (the state not
+// yet rewritten); when the excess is byte for byte the start of the kept
+// Frag<index+1>, the file is truncated back to the equation — the only
+// destructive write of the design, logged with both lengths. Anything else
+// (shorter: a crash lost unflushed data; an excess that is not that prefix; a
+// missing Frag; no checkpoint for a file that holds bytes; an unreadable
+// state) is no resume in place: a fresh from-start part records instead.
+
+import { closeSync, fsyncSync, openSync } from "node:fs";
+import { open, readFile, readdir, rename, rm, stat, truncate } from "node:fs/promises";
+import path from "node:path";
+
+export type FragCheckpoint = { index: number; bytes: number };
+
+export const checkpointName = (stream: string) => `${stream}.frags.json`;
+const FRAG_RE = /-Frag(\d+)$/;
+
+export async function readYtdlIndex(file: string): Promise<number | null | "absent"> {
+ const raw = await readFile(`${file}.ytdl`, "utf8").catch((e: NodeJS.ErrnoException) => (e.code === "ENOENT" ? "absent" : null));
+ if (raw === "absent" || raw === null) return raw;
+ try {
+ const idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index;
+ return typeof idx === "number" && Number.isInteger(idx) && idx >= 0 ? idx : null;
+ } catch {
+ return null;
+ }
+}
+
+async function readCheckpoint(file: string): Promise<FragCheckpoint | null | "corrupt"> {
+ const raw = await readFile(checkpointName(file), "utf8").catch(() => null);
+ if (raw === null) return null;
+ try {
+ const c = JSON.parse(raw) as FragCheckpoint;
+ return Number.isInteger(c.index) && c.index >= 0 && Number.isInteger(c.bytes) && c.bytes >= 0 ? c : "corrupt";
+ } catch {
+ return "corrupt";
+ }
+}
+
+const sizeOf = (f: string) => stat(f).then((s) => s.size, () => null);
+
+// The kept fragment numbers of stream file `name` in `names` (a listing).
+export function fragNumbers(name: string, names: readonly string[]): number[] {
+ const out: number[] = [];
+ for (const n of names) {
+ if (!n.startsWith(`${name}-Frag`)) continue;
+ const m = FRAG_RE.exec(n);
+ if (m) out.push(Number(m[1]));
+ }
+ return out.sort((a, b) => a - b);
+}
+
+export type StreamAccount =
+ | { ok: true; index: number; size: number; expected: number; checkpoint: FragCheckpoint; kept: number[] }
+ | { ok: false; why: string; index?: number; size?: number; expected?: number; excess?: number; next?: number };
+
+// The equation for one stream file, read only.
+export async function accountStream(dir: string, name: string, names?: readonly string[]): Promise<StreamAccount> {
+ const file = path.join(dir, name);
+ const listing = names ?? (await readdir(dir).catch(() => [] as string[]));
+ const size = await sizeOf(file);
+ if (size === null) return { ok: false, why: `${name} is gone` };
+ const idx = await readYtdlIndex(file);
+ if (idx === null) return { ok: false, why: `${name}.ytdl does not read` };
+ if (idx === "absent") return size === 0 ? { ok: true, index: 0, size, expected: 0, checkpoint: { index: 0, bytes: 0 }, kept: [] } : { ok: false, why: `${name} has no .ytdl state` };
+ const cp = await readCheckpoint(file);
+ if (cp === "corrupt") return { ok: false, why: `${checkpointName(name)} does not read` };
+ const checkpoint = cp ?? { index: 0, bytes: 0 };
+ if (checkpoint.index > idx) return { ok: false, why: `its checkpoint (${checkpoint.index}) is past its state (${idx})`, index: idx, size };
+ const kept = fragNumbers(name, listing);
+ const have = new Set(kept);
+ let expected = checkpoint.bytes;
+ for (let n = checkpoint.index + 1; n <= idx; n++) {
+ if (!have.has(n)) return { ok: false, why: `fragment ${n} of ${name} is not kept (no byte accounting for it)`, index: idx, size };
+ expected += (await sizeOf(path.join(dir, `${name}-Frag${n}`))) ?? 0;
+ }
+ if (size === expected) return { ok: true, index: idx, size, expected, checkpoint, kept };
+ if (size < expected) return { ok: false, why: `${name} is ${size} bytes, its fragments ${expected}: bytes the state counts are not in the file`, index: idx, size, expected };
+ return { ok: false, why: `${name} is ${size} bytes, ${size - expected} more than its fragments 1..${idx}`, index: idx, size, expected, excess: size - expected, next: idx + 1 };
+}
+
+export type Reconciled = { ok: true; truncated?: { from: number; to: number } } | { ok: false; why: string };
+
+// The equation, and the one repair. `apply` false: what it would do.
+export async function reconcileStream(dir: string, name: string, apply: boolean, say: (s: string) => void = () => {}): Promise<Reconciled> {
+ const a = await accountStream(dir, name);
+ if (a.ok) return { ok: true };
+ if (a.excess === undefined || a.expected === undefined || a.size === undefined) return { ok: false, why: a.why };
+ const next = path.join(dir, `${name}-Frag${a.next}`);
+ const frag = await readFile(next).catch(() => null);
+ if (!frag) return { ok: false, why: `${a.why}, and fragment ${a.next} is not kept: the excess cannot be proven a torn append` };
+ if (a.excess > frag.length) return { ok: false, why: `${a.why}, more than fragment ${a.next} (${frag.length} bytes)` };
+ const tail = Buffer.alloc(a.excess);
+ const fh = await open(path.join(dir, name), "r");
+ try {
+ await fh.read(tail, 0, a.excess, a.expected);
+ } finally {
+ await fh.close();
+ }
+ if (!tail.equals(frag.subarray(0, a.excess))) return { ok: false, why: `${a.why}, and the excess is not the start of fragment ${a.next}` };
+ if (apply) {
+ await truncate(path.join(dir, name), a.expected);
+ say(`${name}: truncated from ${a.size} to ${a.expected} bytes — its last ${a.excess} bytes were the first ${a.excess} of fragment ${a.next} (a stop inside its append); fragment ${a.next} is fetched again.`);
+ }
+ return { ok: true, truncated: { from: a.size, to: a.expected } };
+}
+
+// A checkpoint written so a crash leaves the old one or the new one, whole:
+// a temp file, fsynced, renamed over, the directory fsynced.
+export async function writeCheckpointDurable(dir: string, name: string, cp: FragCheckpoint): Promise<void> {
+ const final = path.join(dir, checkpointName(name));
+ const tmp = `${final}.tmp`;
+ const fh = await open(tmp, "w");
+ try {
+ await fh.writeFile(JSON.stringify(cp));
+ await fh.sync();
+ } finally {
+ await fh.close();
+ }
+ await rename(tmp, final);
+ const d = openSync(dir, "r");
+ try {
+ fsyncSync(d);
+ } finally {
+ closeSync(d);
+ }
+}
+
+export type Pruned = { pruned: number; index: number } | { pruned: 0; why: string };
+
+// THE WATCHDOG'S PRUNE: on a stable read (the index the same before and after
+// the size), when the equation holds, the checkpoint moves to the index —
+// written and fsynced FIRST — and only then are the fragments it covers
+// deleted (and any older one a crash left). A crash between the two leaves
+// fragments the next accounting ignores (they are at or below the checkpoint).
+export async function pruneStream(dir: string, name: string, deps: { remove?: (f: string) => Promise<void> } = {}): Promise<Pruned> {
+ const file = path.join(dir, name);
+ const before = await readYtdlIndex(file);
+ const a = await accountStream(dir, name);
+ const after = await readYtdlIndex(file);
+ if (typeof before !== "number" || before !== after) return { pruned: 0, why: "the state moved during the read" };
+ if (!a.ok) return { pruned: 0, why: a.why };
+ if (a.index > a.checkpoint.index) await writeCheckpointDurable(dir, name, { index: a.index, bytes: a.size });
+ const remove = deps.remove ?? ((f: string) => rm(f, { force: true }));
+ let pruned = 0;
+ for (const n of a.kept) {
+ if (n > a.index) continue;
+ await remove(path.join(dir, `${name}-Frag${n}`));
+ pruned++;
+ }
+ return { pruned, index: a.index };
+}
+
+// Short of disk (DESIGN-4: the recording goes on, resumability goes): every
+// kept fragment up to the state's index is deleted, without accounting.
+export async function dropFragments(dir: string, name: string): Promise<number> {
+ const file = path.join(dir, name);
+ const idx = await readYtdlIndex(file);
+ const names = await readdir(dir).catch(() => [] as string[]);
+ let n = 0;
+ for (const k of fragNumbers(name, names)) {
+ if (typeof idx === "number" && k > idx) continue;
+ await rm(path.join(dir, `${name}-Frag${k}`), { force: true });
+ n++;
+ }
+ return n;
+}
+
+// Fragment numbers missing between kept ones (a skip leaves no Frag file).
+export function fragmentGaps(kept: readonly number[], from: number): number[] {
+ const out: number[] = [];
+ let want = from;
+ for (const n of kept) {
+ while (want < n) out.push(want++);
+ want = n + 1;
+ }
+ return out;
+}
diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts
@@ -39,6 +39,7 @@ import type {
LiveRestarts,
LiveSpaceHeld,
LiveTranscriptRedo,
+ LiveVerification,
MissingStream,
StartRecovery,
StreamCoverage,
@@ -90,6 +91,8 @@ export type LiveRecordingRow = {
endedBy?: { class: LiveFailureClass; message: string; at: string };
awaitingResume?: string[];
transcriptRedo?: LiveTranscriptRedo;
+ verification?: LiveVerification;
+ skippedFragments?: { count: number; positions: number[] };
// What the landing kept: this run's file stored ("new"), or the store's.
kept?: "new" | "existing";
acknowledgedAt?: string;
@@ -179,10 +182,15 @@ 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">>,
+ Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost" | "endedBy" | "awaitingResume" | "transcriptRedo" | "verification" | "skippedFragments" | "parts">>,
): boolean {
if (r.acknowledgedAt) return false;
if (r.keptParts && r.keptParts.length > 0) return true;
+ // DESIGN-4: a landed file with fragments skipped, one not verified whole,
+ // a part that lost its kept fragments — loud after the landing too.
+ if (r.skippedFragments && r.skippedFragments.count > 0) return true;
+ 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;
// 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).
@@ -277,6 +285,8 @@ export function rowOfRecord(
...(rec.endedBy ? { endedBy: { ...rec.endedBy } } : {}),
...(rec.awaitingResume && rec.awaitingResume.length ? { awaitingResume: [...rec.awaitingResume] } : {}),
...(rec.transcriptRedo ? { transcriptRedo: { ...rec.transcriptRedo } } : {}),
+ ...(rec.verification ? { verification: { ...rec.verification } } : {}),
+ ...(rec.skippedFragments ? { skippedFragments: { ...rec.skippedFragments } } : {}),
...(rec.spaceHeld && rec.spaceHeld.length ? { spaceHeld: rec.spaceHeld.map((x) => ({ ...x })) } : {}),
...(rec.failureClass ? { failureClass: rec.failureClass } : {}),
...(rec.missingStream ? { missingStream: rec.missingStream } : {}),
diff --git a/common/lib/liveVerify-server.test.ts b/common/lib/liveVerify-server.test.ts
@@ -0,0 +1,101 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+import { verifyMerged, verifyScan } from "./liveVerify-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/liveVerify-server.test.ts
+//
+// Real files made by ffmpeg (no network): DASH segments of a picture and a
+// sound, laid end to end as yt-dlp appends them, merged by a stream copy.
+
+const run = promisify(execFile);
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-verify-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+const FFPROBE = process.env.FFPROBE_BIN ?? "ffprobe";
+
+await run("ffmpeg", [
+ "-hide_banner", "-loglevel", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc2=size=160x90:rate=30",
+ "-f", "lavfi", "-i", "anoisesrc=color=pink:sample_rate=48000",
+ "-t", "20", "-c:v", "libx264", "-preset", "ultrafast", "-g", "30", "-keyint_min", "30", "-sc_threshold", "0",
+ "-c:a", "aac", "-b:a", "48k", "-map", "0:v", "-map", "1:a",
+ "-f", "dash", "-seg_duration", "1", "-use_template", "1", "-use_timeline", "0",
+ "-init_seg_name", "init-$RepresentationID$.m4s", "-media_seg_name", "c-$RepresentationID$-$Number%05d$.m4s",
+ path.join(ROOT, "s.mpd"),
+]);
+const segs = (rep: number) => readdir(ROOT).then((n) => n.filter((x) => x.startsWith(`c-${rep}-`)).sort());
+async function streamFile(rep: number, out: string, skip: number[] = []) {
+ const parts = [await readFile(path.join(ROOT, `init-${rep}.m4s`))];
+ for (const [i, s] of (await segs(rep)).entries()) if (!skip.includes(i + 1)) parts.push(await readFile(path.join(ROOT, s)));
+ await writeFile(out, Buffer.concat(parts));
+ return out;
+}
+const merge = async (v: string, a: string, out: string) => {
+ await run("ffmpeg", ["-hide_banner", "-loglevel", "error", "-y", "-i", v, "-i", a, "-map", "0:v:0", "-map", "1:a:0", "-c", "copy", out]);
+ return out;
+};
+
+test("whole: the merged file holds every packet of each stream file, no hole", async () => {
+ const v = await streamFile(0, path.join(ROOT, "v.mp4"));
+ const a = await streamFile(1, path.join(ROOT, "a.m4a"));
+ const m = await merge(v, a, path.join(ROOT, "m.mp4"));
+ const r = await verifyMerged(FFPROBE, m, [v, a]);
+ assert.equal(r.ok, true, JSON.stringify(r));
+ assert.equal((await verifyScan(FFPROBE, m)).ok, true);
+});
+
+test("a skipped fragment: the length hides it, the scan does not", async () => {
+ const v = await streamFile(0, path.join(ROOT, "vh.mp4"), [7]);
+ const a = await streamFile(1, path.join(ROOT, "ah.m4a"));
+ const m = await merge(v, a, path.join(ROOT, "mh.mp4"));
+ const r = await verifyMerged(FFPROBE, m, [v, a]);
+ assert.equal(r.ok, false);
+ assert.match((r as { why: string }).why, /step in its video.*a hole/);
+});
+
+test("a merged file that lost packets of a stream file (a merge cut short) is not whole", async () => {
+ const v = await streamFile(0, path.join(ROOT, "v2.mp4"));
+ const a = await streamFile(1, path.join(ROOT, "a2.m4a"));
+ const vShort = await streamFile(0, path.join(ROOT, "v2s.mp4"), [16, 17, 18, 19, 20]);
+ const m = await merge(vShort, a, path.join(ROOT, "m2.mp4"));
+ const r = await verifyMerged(FFPROBE, m, [v, a]);
+ assert.equal(r.ok, false);
+ assert.match((r as { why: string }).why, /packets merged/);
+});
+
+test("a file that does not read is not whole", async () => {
+ const bad = path.join(ROOT, "bad.mp4");
+ await writeFile(bad, "not media");
+ assert.equal((await verifyScan(FFPROBE, bad)).ok, false);
+});
+
+test("WebM stream files as yt-dlp appends them (Matroska clusters of unknown length: ffprobe warns once per fragment) read as whole — the warnings are not errors", async () => {
+ const dir = path.join(ROOT, "webm");
+ const { mkdir } = await import("node:fs/promises");
+ await mkdir(dir);
+ await run("ffmpeg", [
+ "-hide_banner", "-loglevel", "error", "-y",
+ "-f", "lavfi", "-i", "testsrc2=size=160x90:rate=30",
+ "-f", "lavfi", "-i", "anoisesrc=color=pink:sample_rate=48000",
+ "-t", "12", "-c:v", "libvpx-vp9", "-deadline", "realtime", "-cpu-used", "8", "-g", "30", "-keyint_min", "30",
+ "-c:a", "libopus", "-b:a", "48k", "-map", "0:v", "-map", "1:a",
+ "-f", "dash", "-dash_segment_type", "webm", "-seg_duration", "1", "-use_template", "1", "-use_timeline", "0",
+ "-init_seg_name", "init-$RepresentationID$.webm", "-media_seg_name", "c-$RepresentationID$-$Number%05d$.webm",
+ path.join(dir, "w.mpd"),
+ ]);
+ const lay = async (rep: number, out: string) => {
+ const names = (await readdir(dir)).filter((x) => x.startsWith(`c-${rep}-`)).sort();
+ await writeFile(out, Buffer.concat([await readFile(path.join(dir, `init-${rep}.webm`)), ...(await Promise.all(names.map((n) => readFile(path.join(dir, n)))))]));
+ return out;
+ };
+ const v = await lay(0, path.join(dir, "v.webm"));
+ const a = await lay(1, path.join(dir, "a.webm"));
+ const m = await merge(v, a, path.join(dir, "m.mkv"));
+ const r = await verifyMerged(FFPROBE, m, [v, a]);
+ assert.equal(r.ok, true, JSON.stringify(r));
+});
diff --git a/common/lib/liveVerify-server.ts b/common/lib/liveVerify-server.ts
@@ -0,0 +1,141 @@
+// IS THE MERGED FILE WHOLE (DESIGN-4 4)? yt-dlp's merge (and the editor's own)
+// is a stream copy: every packet of each stream file is in the merged file.
+// A torn or skipped fragment does not change a file's probed LENGTH (the
+// timestamps carry it), so the length proves nothing; the packets do. Per
+// track, one ffprobe pass over each file:
+// - the merged file's packet count equals its stream file's;
+// - their spans agree within max(0.5 s, 2 frames);
+// - in every file, consecutive packet times (sorted) never step more than
+// 1.5× the track's median step for video, 2× for audio, nor 0.1 s (a hole), and the
+// decode times, where the file has them, only go forward.
+// ffprobe runs at `-v error`: a raw WebM stream file's "unknown-length
+// element" warning, one per fragment (Matroska clusters of a live stream), is
+// a warning, never an error here; only the exit and the packets count.
+// Cost, measured: about 115 k packets a second (a 3 h file, 830 k packets,
+// 7.2 s cached) plus the read of the file — for a 6 h 19 min stream (683 k
+// video + 980 k audio packets) about 15 s of CPU per file, the merged file and
+// its two streams about 30 s plus reading them twice over (minutes on a
+// spinning disk). It runs AFTER the landing and the transcription hand-off;
+// the stream files go only after it passes.
+
+import { spawn } from "node:child_process";
+import { setPriority } from "node:os";
+import { createInterface } from "node:readline";
+
+export type TrackScan = { kind: "video" | "audio" | "other"; packets: number; span: number; medianStep: number; maxStep: number; backward: number };
+export type FileScan = { file: string; tracks: TrackScan[] } | { file: string; error: string };
+
+export async function scanMediaFile(ffprobeBin: string, file: string, signal?: AbortSignal): Promise<FileScan> {
+ const kinds = await new Promise<string[] | string>((resolve) => {
+ const c = spawn(ffprobeBin, ["-v", "error", "-show_entries", "stream=codec_type", "-of", "csv=p=0", file], { stdio: ["ignore", "pipe", "pipe"], signal });
+ let out = "";
+ let err = "";
+ c.stdout.on("data", (d: Buffer) => (out += d.toString()));
+ c.stderr.on("data", (d: Buffer) => (err += d.toString()));
+ c.on("error", (e) => resolve(e.message));
+ c.on("close", (code) => resolve(code === 0 ? out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean) : `ffprobe exit ${code}: ${err.trim().slice(0, 300)}`));
+ });
+ if (typeof kinds === "string") return { file, error: kinds };
+ const pts: number[][] = kinds.map(() => []);
+ const dur: number[] = kinds.map(() => 0);
+ const lastDts: number[] = kinds.map(() => -Infinity);
+ const backward: number[] = kinds.map(() => 0);
+ const code = await new Promise<number | string>((resolve) => {
+ const c = spawn(ffprobeBin, ["-v", "error", "-show_entries", "packet=stream_index,pts_time,dts_time,duration_time", "-of", "csv=p=0", file], {
+ stdio: ["ignore", "pipe", "pipe"],
+ signal,
+ });
+ try {
+ if (c.pid) setPriority(c.pid, 10);
+ } catch {
+ // (Best effort: a lower priority.)
+ }
+ let err = "";
+ c.stderr.on("data", (d: Buffer) => (err = (err + d.toString()).slice(-2000)));
+ const rl = createInterface({ input: c.stdout });
+ rl.on("line", (line) => {
+ const [si, p, d, du] = line.split(",");
+ const i = Number(si);
+ if (!Number.isInteger(i) || i < 0 || i >= kinds.length) return;
+ const pt = Number(p);
+ if (!Number.isFinite(pt)) return;
+ pts[i]!.push(pt);
+ const dd = Number(d);
+ if (Number.isFinite(dd)) {
+ if (dd <= lastDts[i]!) backward[i]!++;
+ lastDts[i] = dd;
+ }
+ const dn = Number(du);
+ if (Number.isFinite(dn)) dur[i] = dn;
+ });
+ c.on("error", (e) => resolve(e.message));
+ c.on("close", (code) => resolve(code === 0 ? 0 : `ffprobe exit ${code}: ${err.trim().slice(0, 300)}`));
+ });
+ if (code !== 0) return { file, error: String(code) };
+ const tracks: TrackScan[] = kinds.map((k, i) => {
+ const t = Float64Array.from(pts[i]!).sort();
+ const steps = new Float64Array(Math.max(0, t.length - 1));
+ for (let j = 1; j < t.length; j++) steps[j - 1] = t[j]! - t[j - 1]!;
+ const sorted = Float64Array.from(steps).sort();
+ const median = sorted.length ? sorted[Math.floor(sorted.length / 2)]! : 0;
+ return {
+ kind: k === "video" ? "video" : k === "audio" ? "audio" : "other",
+ packets: t.length,
+ span: t.length ? t[t.length - 1]! + dur[i]! - t[0]! : 0,
+ medianStep: median,
+ maxStep: sorted.length ? sorted[sorted.length - 1]! : 0,
+ backward: backward[i]!,
+ };
+ });
+ return { file, tracks };
+}
+
+export const HOLE_FLOOR_SECONDS = 0.1;
+
+export type Verdict = { ok: true; tracks: TrackScan[] } | { ok: false; why: string };
+
+const holeOf = (t: TrackScan): string | null => {
+ if (t.kind === "other" || t.packets < 3) return null;
+ // A floor of 0.1 s: an encoder's dropped frame (0.067 s at 30 fps) is not a
+ // hole; a lost fragment (1-5 s of a YouTube stream) always is.
+ const limit = Math.max(HOLE_FLOOR_SECONDS, (t.kind === "video" ? 1.5 : 2) * t.medianStep);
+ if (t.maxStep > limit + 1e-6) return `a ${t.maxStep.toFixed(3)} s step in its ${t.kind} (median ${t.medianStep.toFixed(3)} s): a hole`;
+ if (t.backward > 0) return `${t.backward} ${t.kind} packet(s) decode backwards`;
+ return null;
+};
+
+// One file alone (a muxed recording): the scan.
+export async function verifyScan(ffprobeBin: string, file: string, signal?: AbortSignal): Promise<Verdict> {
+ const s = await scanMediaFile(ffprobeBin, file, signal);
+ if ("error" in s) return { ok: false, why: `it does not read (${s.error})` };
+ for (const t of s.tracks) {
+ const h = holeOf(t);
+ if (h) return { ok: false, why: h };
+ }
+ return { ok: true, tracks: s.tracks };
+}
+
+// A merged file against the stream files it was made from.
+export async function verifyMerged(ffprobeBin: string, merged: string, streams: readonly string[], signal?: AbortSignal): Promise<Verdict> {
+ const m = await scanMediaFile(ffprobeBin, merged, signal);
+ if ("error" in m) return { ok: false, why: `the merged file does not read (${m.error})` };
+ for (const t of m.tracks) {
+ const h = holeOf(t);
+ if (h) return { ok: false, why: `the merged file has ${h}` };
+ }
+ for (const f of streams) {
+ const s = await scanMediaFile(ffprobeBin, f, signal);
+ if ("error" in s) return { ok: false, why: `${f.split("/").pop()} does not read (${s.error})` };
+ for (const t of s.tracks) {
+ if (t.kind === "other") continue;
+ const h = holeOf(t);
+ if (h) return { ok: false, why: `${f.split("/").pop()} has ${h}` };
+ const mt = m.tracks.find((x) => x.kind === t.kind);
+ if (!mt) return { ok: false, why: `the merged file has no ${t.kind} track` };
+ if (mt.packets !== t.packets) return { ok: false, why: `its ${t.kind}: ${mt.packets} packets merged, ${t.packets} in ${f.split("/").pop()}` };
+ const tol = Math.max(0.5, 2 * t.medianStep);
+ if (Math.abs(mt.span - t.span) > tol) return { ok: false, why: `its ${t.kind}: ${mt.span.toFixed(2)} s merged, ${t.span.toFixed(2)} s in ${f.split("/").pop()}` };
+ }
+ }
+ return { ok: true, tracks: m.tracks };
+}
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -29,6 +29,13 @@
is not resumable.
- The boot pass measures a row's age from its recorder's last write, and marks a row it skips for its age.
- A restart bound reached on a stream still live is waited out (said on the row), not the end of the recording.
+ - A resume appends only to a file the kept fragments prove whole (a torn last append is truncated back, logged);
+ otherwise a FRESH part from the stream's start records, with the insurance beside it.
+ - A fragment that cannot be fetched stops and resumes the recorder (20 s, 60 s, 180 s), then a fresh part; only a
+ last run may skip it, and the hole is marked on the part, the landed file and the row (loud).
+ - 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 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