commit 40a6b9beb752b13c18adde50f248ba3d55fbf80f
parent fdf0f84ee5783de40ce8a2b6bc0af6a164f2bb21
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 20:09:44 -0500
record-live: a from-start recorder is resumed in place from yt-dlp's own state
DESIGN-3 of live-guard-2 (LOG.md cites the yt-dlp source): a
--live-from-start download keeps `<file>.ytdl` beside each stream file
(downloader/dash.py:42, fragment.py:79-80, 146-152) and a run with the
same output continues from the saved fragment (fragment.py:178-213,
dash.py:79-82); SIGINT finishes it and removes the state (fragment.py:
520-534, 286-288), while SIGTERM, a kill or a crash leave it (yt-dlp
installs no signal handler).
So a from-start recorder that dies, stalls, or is stopped by an editor
shutdown is RESUMED: the same stem, the format pinned to the ids on disk,
from where it stopped — the same part (`resumes`), no new part, no gap,
no second download, no live-edge recorder, no recovery. The watchdog and
a shutdown stop it with SIGTERM; a person's Cancel stays SIGINT. At a
shutdown such a part is not landed: it waits in staging (awaitingResume)
and the boot's restart resumes it in place. The live-edge restart and the
gap recovery remain only as the fallback (no state, an unreadable one, a
stream past 120 h, a resume that writes nothing), with REVIEW-4's fixes:
a flat 180 s tolerance; a part's length by its shortest stream; an
index-0 try never "reaches"; a try is also stopped by its own catch-up; a
part that showed itself caught up has no gap behind it; the recovery's
first try only once the live-edge part holds bytes; a new span with no
try left stays loud; the insurance is re-armed only beside a from-start
main; YouTube's soft block is a rate limit.
5.1: a state read refused as private/removed is read again a minute later
before the run ends; confirmed, the row says the stream went private or
was removed while recording and what is held (endedBy, needing a person),
and the insurance is not stopped by the end's grace.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
9 files changed, 563 insertions(+), 31 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -147,7 +147,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `remote-listing` | remote-listing lists an Odysee or BitChute channel upstream and diffs it against what it holds: {"slug"}. One flat-playlist read on the platform's queue (refused while it is held or cooling down; a 429 backs it off), nothing written. `get remote-listing <slug>` waits for the job and prints {listed, held, notHeld: \[{id, url}\], heldNotListed: \[id\], ...} on stdout. | |
| `attach-media` | attach-media copies each held video's file out of a LOCAL archive into the saved-video store, as its source container (nothing fetched): {"slug", "source"} — an absolute path to a directory, a .zip (read in place) or a .7z. The id is the folder's trailing "(<id>)", else the file's yt-dlp suffix; "items": \[{"id", "path"}\] names exact files (path inside the source), "match" narrows the folders by regex. "createRecords": true writes a record for a video the channel does not hold; "replace": true re-attaches over a saved container. "fillDates": true gives a held record attach-media made (saved-video.json origin "local-archive") that has no upload\_date the date from its folder's description.txt, through the metadata history ("dated" in the log and summary); a record with a date, or one attach-media did not make, is never touched. "dryRun": true logs each folder's class (attach, not-held, already-attached, lost, no-media, unmatched, ambiguous, and dated) and the held videos with no media in it, and writes nothing. The log ends with a summary: line; a re-run resumes. | `pnpm ops attach-media --json '{"slug":"demo-yt","source":"/abs/YouTube.zip","match":"aaaaaaaaaaa\|bbbbbbbbbbb","fillDates":true,"dryRun":true}' --wait` |
| `import-media` | import-media makes ONE file from outside the archive a normal transcribed item: {"slug", "path"} (absolute) and which record — "url" (the source page: one metadata-only pass makes or refreshes the record, under the id the archive keys it by — Rumble's URL id), "id" (a record already here) or "meta": {"title", "date"?, "duration"?, "description"?} (by hand). ffprobe must read it; an MPEG-TS, a .part or an FLV is remuxed -c copy to mp4 (+faststart), never re-encoded. It lands in the saved-video store only when longer than a container already there ("replace": true lands it anyway), then audio.<fmt>, the archive line and media-import.json. "move": true removes the original once the copy verifies; "audio": false lands the container only; "transcribe": true queues a transcribe-one job (held by any pause; without it the transcription lane takes it by its rules); "doNotClean": true marks it, with "note". "dryRun": true says what it would do and writes nothing. A directory, a .zip or a .7z goes to attach-media ("id", "replace", "dryRun" only). | `pnpm ops import-media --json '{"slug":"demo-rumble","path":"/abs/stream.mp4.part","url":"https://rumble.com/v1abcde-title.html","move":true}' --wait`<br>`pnpm ops import-media --json '{"slug":"demo-archive","path":"/abs/talk.mkv","meta":{"title":"A talk","date":"2019-05-01"},"dryRun":true}' --wait` |
-| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". A from-start attempt that records nothing (yt-dlp: "The downloaded file is empty"), or only one of its two streams, is tried again at +60 and +180 s, then from the live edge at 0, +60 and +180 s (each wait jittered). The failure's class decides: ended, private/removed, members-only/login and a full or unwritable disk are not retried; a 429 or the bot check gets ONE more try after 15 min, then stops; empty, network and unknown failures keep the schedule; a Cancel ends it. The row records the class (failureClass). A live-edge fallback says what it lost (the first N min of the stream) and needs a person. The landing never removes a part it is not known to contain (an earlier run's, one from another point of the stream, one it cannot land): those are kept in staging and listed (keptParts) until acknowledged. The reply is {jobId, kind, "check"}: the `get live-recordings` command that answers for it. --wait-started returns once a FROM-START part's bytes grow (the recording's row on stdout, exit 0; a run asked fromStart: false, any part's), exit 3 when it records only from the live edge (the start is lost), exit 1 with the reason it failed; 15 minutes by default, --wait-timeout overrides. After a live-edge fallback, from its start is tried again BESIDE the live-edge recording (never touching it): every 15 min (jittered), one try at a time, at most 8; a try that holds the whole stream when landed recovers the start (startRecovery). Each recorder has a stall watchdog: no growth for liveRecording.stallMinutes (10) stops that recorder, its part kept; while the stream still reads live (one metadata read; an exit is read twice, a minute apart) a new part records from the live edge — at most 6 restarts an hour and 24 a run (restarts); past them the row says the stream is live and NOT recorded. "insurance"?: true \| "whole" \| false — a live-edge recorder beside a from-start recording of a stream already live, until the start has caught up (+5 min), or for the whole stream; absent, on exactly when the stream is marked keep ("doNotClean", the record's Do-not-clean marker, a pending keep) when the recording starts. Its part goes at landing only when the landed file holds the whole stream; otherwise it is kept and listed. After an editor restart, a run the shutdown or a crash interrupted restarts by itself (once per run, 3 an hour per stream, never after a Cancel; liveRecording. autoRestartOnBoot): the new run reads the stream's state first — live, it records; ended, it lands what is in staging; unreadable, it starts nothing and the row needs a person. When no single part holds the stream but two or more together hold more, they are joined (-c copy): an overlap at the point their sound shares, a gap stated by the clock; the joined file lands only when PROVEN (its length, its sound around every join), its parts removed only after; the joins are on the row (joins) and in data/<id>/live-joins.json (each segment's place in the stream and in the file). Unproven, or codecs that differ: the longest lands and the rest are kept. A gap needs a person. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started` |
+| `record-live` | record-live records a live stream until it ends, then lands it as import-media lands a file: {"slug", "url"} (or "id" of a record here), "fromStart"? (true: yt-dlp --live-from-start — Rumble's DVR playlist holds a stream's first 4 hours), "maxHeight"? (720; null = the tallest), "separate"? (true: the video at maxHeight plus the best audio, merged — the default on YouTube, whose live streams from the start offer no single stream with both; false: one muxed stream — Rumble, Kick), "transcribe"?, "doNotClean"?, "note"?, "dryRun"?. On Rumble a refused yt-dlp falls back to the page's own playlist (a browser under xvfb, then ffmpeg). On Kick ("kick.com/<channel>" or its VOD) the ongoing VOD is polled from its first segment beside the channel's live stream. One job per stream; job cancel stops it with SIGINT and lands what it has (video and audio left unmerged are merged, -c copy); the longest part wins. Refused for a stream that is not live. "preclip": true (or {"everyMinutes", "maxChunkMinutes", "overlapSeconds", "scan", "mine", "project"}, over settings.livePreclip) starts live-preclip once the first part begins, and implies "transcribe". A from-start attempt that records nothing (yt-dlp: "The downloaded file is empty"), or only one of its two streams, is tried again at +60 and +180 s, then from the live edge at 0, +60 and +180 s (each wait jittered). The failure's class decides: ended, private/removed, members-only/login and a full or unwritable disk are not retried; a 429 or the bot check gets ONE more try after 15 min, then stops; empty, network and unknown failures keep the schedule; a Cancel ends it. The row records the class (failureClass). A live-edge fallback says what it lost (the first N min of the stream) and needs a person. The landing never removes a part it is not known to contain (an earlier run's, one from another point of the stream, one it cannot land): those are kept in staging and listed (keptParts) until acknowledged. The reply is {jobId, kind, "check"}: the `get live-recordings` command that answers for it. --wait-started returns once a FROM-START part's bytes grow (the recording's row on stdout, exit 0; a run asked fromStart: false, any part's), exit 3 when it records only from the live edge (the start is lost), exit 1 with the reason it failed; 15 minutes by default, --wait-timeout overrides. After a live-edge fallback, from its start is tried again BESIDE the live-edge recording (never touching it): every 15 min (jittered), one try at a time, at most 8; a try that holds the whole stream when landed recovers the start (startRecovery). Each recorder has a stall watchdog: no growth for liveRecording.stallMinutes (10) stops that recorder, its part kept; a from-start recorder (dead, stalled, or stopped by a shutdown) is RESUMED in place from yt-dlp's .ytdl state — the same part — and only when that is impossible does a live-edge recorder follow: while the stream still reads live (one metadata read; an exit is read twice, a minute apart) a new part records from the live edge — at most 6 restarts an hour and 24 a run (restarts); past them the row says the stream is live and NOT recorded. "insurance"?: true \| "whole" \| false — a live-edge recorder beside a from-start recording of a stream already live, until the start has caught up (+5 min), or for the whole stream; absent, on exactly when the stream is marked keep ("doNotClean", the record's Do-not-clean marker, a pending keep) when the recording starts. Its part goes at landing only when the landed file holds the whole stream; otherwise it is kept and listed. After an editor restart, a run the shutdown or a crash interrupted restarts by itself (once per run, 3 an hour per stream, never after a Cancel; liveRecording. autoRestartOnBoot): the new run reads the stream's state first — live, it records; ended, it lands what is in staging; unreadable, it starts nothing and the row needs a person. When no single part holds the stream but two or more together hold more, they are joined (-c copy): an overlap at the point their sound shares, a gap stated by the clock; the joined file lands only when PROVEN (its length, its sound around every join), its parts removed only after; the joins are on the row (joins) and in data/<id>/live-joins.json (each segment's place in the stream and in the file). Unproven, or codecs that differ: the longest lands and the rest are kept. A gap needs a person. | `pnpm ops record-live --json '{"slug":"demo-rumble","url":"https://rumble.com/v1abcde-title.html"}'`<br>`pnpm ops record-live --json '{"slug":"demo-kick","url":"https://kick.com/somechannel"}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","preclip":{"everyMinutes":10}}'`<br>`pnpm ops record-live --json '{"slug":"demo-yt","url":"https://www.youtube.com/watch?v=<id>","doNotClean":true}' --wait-started` |
| `local-media-configure` | local-media-configure gives a video channel a LOCAL MEDIA LIBRARY: {"slug", "sourceId", "directory"} — a stable lowercase id and an absolute directory on the editor server whose recordings stay where they are (never copied, moved or deleted). Written through the channel config; a channel that already has one is refused, and so is queued or running channel work. Playback is not set. Synchronous. | `pnpm ops local-media-configure --json '{"slug":"demo-local","sourceId":"library-1","directory":"/mnt/recordings"}'` |
| `local-media-preview` | local-media-preview scans the library and writes nothing: {"slug"} -> {preview: {sourceToken, counts, candidates}}. Each .mp4 directly in the directory (not its subdirectories) with its same-named .info.json and .vtt (or .srt) is "new", "existing" (its record is held) or "issue" (with issues). The sourceToken and a candidate's fingerprint (or preparationFingerprint, when it has no .info.json) are what the other local-media actions take. An unreachable library is an error, never an empty preview. | `pnpm ops local-media-preview --json '{"slug":"demo-local"}'` |
| `local-media-prepare` | local-media-prepare reviews details for a recording with no .info.json and writes nothing: {"slug", "sourceToken", "media", "sourceFingerprint" (the candidate's preparationFingerprint), "details": {"mode": "inspect" \| "manual", "title", "recordedDate"? (YYYY-MM-DD), "durationSeconds"? (manual)}} -> {review: {metadata, fingerprint}}. "inspect" measures the duration with ffprobe. Import it with local-media-import, the review's fingerprint and "preparation": {"sourceFingerprint", "details"}. | `pnpm ops local-media-prepare --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","sourceFingerprint":"<fp>","details":{"mode":"inspect","title":"A talk"}}'` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -1468,6 +1468,16 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":
`startRecovery` says the tries and their state; when the landed file is a from-start try that holds the whole
stream the start is `recovered`, the row no longer needs a person, and the live-edge part goes under the coverage
rule below. Otherwise the start stays lost.
+- **A from-start recorder is RESUMED in place.** yt-dlp keeps a `.ytdl` state file beside each stream file of a
+ `--live-from-start` download (downloader/fragment.py) and, run again with the same output, continues from the saved
+ fragment. So a from-start recorder that dies, stalls, or is stopped by an editor shutdown is restarted as the SAME
+ part: the same stem, the format pinned to the ids on disk, from where it stopped — no new part, no gap, no second
+ download (`resumes` on the part). The watchdog and a shutdown stop it with SIGTERM, which leaves the state; a
+ person's Cancel is SIGINT, which finishes the file. At a shutdown such a part is not landed: it waits in staging
+ (`awaitingResume`) and the boot's restart resumes it. Only when a resume is impossible (no state: the file was
+ finished; an unreadable state; a stream past 120 h; 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 stalled or dead recorder is restarted while the stream is live.** Every path-A recorder (and every try beside
the live edge) has a watchdog: its part's files, scratch included, are compared every minute; no growth for
`liveRecording.stallMinutes` (10) stops THAT recorder (SIGINT), and its part stays. After a stall with bytes, or a
@@ -1476,9 +1486,10 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":
unrecorded quietly, and no span of it is left in no part while it can be fetched**: live (or unreadable — a failed
read never ends a recording), at once a new part from the LIVE EDGE (`ytdlp-r<N>`, its own stem); the earlier part
stays for the landing and the join, and a restart never stops a working insurance recorder. When the kept parts
- (from-start ones from 0, live-edge ones from their recorder's start) do not reach the live edge within max(180 s,
- 1 %), the span is set on the row (`lost`: "hours 1:12-3:40 are in no part yet", needing a person) and a from-start
- recovery runs beside the live-edge recorder — first try at once, one at a time, at most 8 a run every 15 min —
+ (from-start ones from 0, live-edge ones from their recorder's start; a part with separate streams by its shortest)
+ do not reach the live edge within 180 s (and the dead part's own progress did not show it caught up), the span is set on the row (`lost`: "hours 1:12-3:40 are in no part yet", needing a person) and a from-start
+ recovery runs beside the live-edge recorder — its first try once the live-edge part holds bytes, one at a time, at
+ most 8 a run every 15 min (none left: the row stays loud) —
until a from-start part reaches where the live-edge part begins; then the row is quiet about it. The stream counts as ended only
on evidence: the state read says so, or three live-edge recorders in a row capture nothing (then, if it still reads
live, the row is loud). At most 6 restarts in any hour and 24 in a run; past them, or when the state cannot be read
diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts
@@ -177,6 +177,11 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes:
(gaps.length ? ` — ${gaps.length} GAP${gaps.length === 1 ? "" : "S"} of about ${gaps.map((g) => spanWords(g.seconds)).join(", ")} (by the clock) NOT recorded` : ", each join checked by its sound"),
);
}
+ if (v.endedBy?.class === "private") {
+ const held = (v.parts ?? []).reduce((n, p) => Math.max(n, p.seconds ?? 0), 0);
+ extra.unshift(`the stream went private or was removed while recording (${v.endedBy.message})${held ? `; ${spanWords(held)} are held` : "; what was recorded is held"}`);
+ }
+ if (v.awaitingResume && v.awaitingResume.length) extra.push(`${v.awaitingResume.length} part(s) wait in staging, with their state, to be resumed`);
if (v.spaceHeld && v.spaceHeld.length) extra.push(`NOT started for want of disk: ${v.spaceHeld.map((x) => x.what).join(", ")}`);
if (v.restarts && v.restarts.count > 0) extra.push(`its recorder was restarted ${v.restarts.count} time${v.restarts.count === 1 ? "" : "s"} (stalled or died while live)`);
if (v.restarts?.refused) extra.push(`NOT restarted again though the stream was live: ${v.restarts.refused}`);
@@ -339,6 +344,8 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
...(own?.insurance ? { insurance: own.insurance } : {}),
...(own?.joins ? { joins: own.joins } : {}),
...(own?.spaceHeld ? { spaceHeld: own.spaceHeld } : {}),
+ ...(own?.endedBy ? { endedBy: own.endedBy } : {}),
+ ...(own?.awaitingResume ? { awaitingResume: own.awaitingResume } : {}),
attempts: own?.attempts ?? row.attempts,
parts,
slug,
@@ -359,6 +366,7 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
restarts: own?.restarts ?? row.restarts,
joins: own?.joins ?? row.joins,
lost: own?.lost ?? row.lost,
+ endedBy: own?.endedBy ?? row.endedBy,
spaceHeld: own?.spaceHeld ?? row.spaceHeld,
}),
};
diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts
@@ -2577,7 +2577,8 @@ test("REVIEW3 3.1: the 20 Nov shape — from its start dies a minute in on a str
live = false;
return okExit;
},
- { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } },
+ // (The recovery begins once the live-edge part holds bytes: REVIEW-4 1.1.)
+ { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
);
await run;
assert.ok(calls.some(isRestart) && isEdge(calls.find(isRestart)!), "a live-edge recorder at once");
@@ -2610,7 +2611,8 @@ test("REVIEW3 3.1: a from-start recorder that stalls while 2 h behind: the live
live = false;
return okExit;
},
- { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } },
+ // (The recovery begins once the live-edge part holds bytes: REVIEW-4 1.1.)
+ { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
);
await run;
assert.ok(isEdge(calls[1]!) || isEdge(calls[2]!), "a live-edge recorder");
@@ -2727,3 +2729,286 @@ test("REVIEW3 4.1: a live-edge part goes only when the landed file is the media'
assert.equal(kept, !gone, `${id}: the live-edge part ${gone ? "goes" : "is kept"}`);
}
});
+
+// --- DESIGN-3: a from-start recorder is RESUMED IN PLACE ---------------------------
+//
+// A fake yt-dlp that keeps a state file as the real one does for a
+// --live-from-start download (downloader/fragment.py: `<file>.ytdl`, written
+// after every fragment, removed when the download finishes): on a run with
+// the same output and the state there, it continues from the saved fragment
+// (one fragment = 5 s here). SIGINT finishes (the state goes); SIGTERM, a
+// kill or a crash leaves it.
+
+type FakeResume = { exitCode: number | null; stderrTail: string; signalled: boolean };
+function resumableYtdlp(script: (call: { n: number; resumedFrom: number | null; write: (seconds: number) => Promise<void>; signal: AbortSignal; args: string[] }) => Promise<"die" | "end" | "hang" | FakeResume>) {
+ let n = 0;
+ return async (args: string[], _n: number, signal: AbortSignal): Promise<FakeResume> => {
+ n++;
+ const out = outOf(args);
+ const fromStart = fromStartArg(args);
+ const file = `${out}.f18.mp4`;
+ const state = `${file}.ytdl`;
+ let resumedFrom: number | null = null;
+ let have = 0;
+ if (fromStart) {
+ const st = await readFile(state, "utf8").catch(() => null);
+ if (st) {
+ resumedFrom = JSON.parse(st).downloader.current_fragment.index as number;
+ have = resumedFrom * 5;
+ }
+ }
+ const write = async (seconds: number) => {
+ have = seconds;
+ // (Its bytes grow with what it holds, as a real stream file's do.)
+ await writeFile(fromStart ? file : `${out}.mp4`, `format=mp4;seconds=${seconds};${"x".repeat(Math.floor(seconds / 60))}`);
+ if (fromStart) await writeFile(state, JSON.stringify({ downloader: { current_fragment: { index: Math.floor(seconds / 5) } } }));
+ };
+ void have;
+ const what = await script({ n, resumedFrom, write, signal, args });
+ if (what === "die") return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ if (what === "end") {
+ await rm(state, { force: true });
+ return okExit;
+ }
+ if (what === "hang") {
+ await abortOf(signal);
+ // SIGINT finishes the download (the state goes); SIGTERM leaves it.
+ if (signal.reason === "SIGINT") await rm(state, { force: true });
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ return what;
+ };
+}
+
+test("DESIGN-3: a from-start recorder that dies is RESUMED in place: the same stem, the format pinned, from the saved fragment — no new part, no live edge, no recovery", { timeout: 60_000 }, async () => {
+ const id = "exmplres3a01";
+ let live = true;
+ const resumed: (number | null)[] = [];
+ const fake = resumableYtdlp(async ({ n, resumedFrom, write }) => {
+ resumed.push(resumedFrom);
+ if (n === 1) {
+ await write(3600);
+ return "die";
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ });
+ const { run, calls } = await incidentRun(id, fake, { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } });
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 2);
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!), "the same output stem");
+ assert.ok(fromStartArg(calls[1]!), "from its start, resumed");
+ assert.equal(calls[1]![calls[1]!.indexOf("-f") + 1], "18", "the format pinned to the one on disk");
+ assert.deepEqual(resumed, [null, 720], "continued from the saved fragment");
+ assert.equal(calls.filter(isRecovery).length, 0);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.parts.length, 1, "no new part");
+ assert.equal(row.parts[0]!.resumes, 1);
+ assert.equal(row.lost, undefined);
+ assert.equal(row.coverage?.covers, true);
+});
+
+test("DESIGN-3: a stalled from-start recorder is stopped WITHOUT finishing (SIGTERM) and resumed; a person's Cancel finishes it (SIGINT)", { timeout: 60_000 }, async () => {
+ const id = "exmplres3a02";
+ let live = true;
+ const reasons: unknown[] = [];
+ const fake = resumableYtdlp(async ({ n, write, signal }) => {
+ if (n === 1) {
+ await write(3000);
+ const r = await (async () => { await abortOf(signal); return signal.reason; })();
+ reasons.push(r);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ });
+ const wrapped = async (args: string[], n: number, signal: AbortSignal) => {
+ const o = await fake(args, n, signal);
+ return o;
+ };
+ const { run, calls } = await incidentRun(id, wrapped, { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } });
+ await run;
+ assert.deepEqual(reasons, ["SIGTERM"], "the watchdog's stop keeps the state");
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place");
+ // A person's Cancel: SIGINT.
+ const ac = new AbortController();
+ const id2 = "exmplres3a03";
+ const seen: unknown[] = [];
+ const c = await incidentRun(
+ id2,
+ resumableYtdlp(async ({ write, signal }) => {
+ await write(600);
+ setTimeout(() => ac.abort(), 10);
+ await abortOf(signal);
+ seen.push(signal.reason);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }),
+ { signal: ac.signal, deps: { ...FAST_WATCH, join: null } },
+ );
+ await c.run;
+ assert.deepEqual(seen, ["SIGINT"]);
+});
+
+test("DESIGN-3: an editor shutdown leaves the state (SIGTERM), and the boot's restart resumes the SAME stem", { timeout: 60_000 }, async () => {
+ const id = "exmplres3a04";
+ const ac = new AbortController();
+ const first = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, signal }) => {
+ await write(3000);
+ setTimeout(() => ac.abort(), 10);
+ await abortOf(signal);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }),
+ { signal: ac.signal, deps: { ...FAST_WATCH, join: null, shuttingDown: () => true } },
+ );
+ const s1 = await first.run;
+ assert.equal(s1.status, "interrupted");
+ const stem = outOf(first.calls[0]!);
+ assert.ok((await left(id)).some((n) => n.endsWith(".f18.mp4.ytdl")), "the state survived the shutdown");
+ assert.equal(await storedSeconds(id), null, "nothing landed: the part waits to be resumed");
+ const t0 = (await rowOf(id))[0]!.startedAt;
+ const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await patchLiveRecordingRow(paths, YT_SLUG, id, t0, (r) => {
+ r.restart = { at: t0, by: "boot", state: "asked" };
+ });
+ let live = true;
+ const second = await incidentRun(
+ id,
+ resumableYtdlp(async ({ resumedFrom, write }) => {
+ assert.equal(resumedFrom, 600);
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { resumeOf: t0 }, deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await second.run).status, "landed");
+ assert.equal(outOf(second.calls[0]!), stem, "the boot's restart resumed the interrupted stem");
+});
+
+test("DESIGN-3: no state to resume (the part was finished) — the fallback: a live-edge restart", { timeout: 60_000 }, async () => {
+ const id = "exmplres3a05";
+ let live = true;
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(7200);
+ // It finished (the state went), then exited 1.
+ await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true });
+ return "die";
+ }
+ await write(300);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } },
+ );
+ await run;
+ assert.equal(calls.length, 2);
+ assert.ok(isEdge(calls[1]!), "the live edge: nothing to resume");
+});
+
+test("DESIGN-3 5.1: a read refused as private is confirmed a minute later; confirmed, the row says the stream went private while recording; not confirmed, it goes on", { timeout: 60_000 }, async () => {
+ const id = "exmplres3a06";
+ const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`;
+ const a = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, args }) => {
+ await write(3000);
+ await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true });
+ return "die";
+ }),
+ { deps: { ...FAST_WATCH, join: null }, refresh: { failAfterFirst: PRIVATE } },
+ );
+ await a.run.catch(() => {});
+ assert.ok(a.waits.includes(60_000), "read again a minute later");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.endedBy?.class, "private");
+ assert.match(row.reason, /went private or was removed while recording/);
+ assert.equal(row.needsAttention, true);
+ // Refused once, then it reads live: the recording goes on.
+ const id2 = "exmplres3a07";
+ let live = true;
+ const b = await incidentRun(
+ id2,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(7200);
+ await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true });
+ return "die";
+ }
+ await write(300);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null }, refresh: { failReads: [2], failWith: PRIVATE, stillLive: () => live } },
+ );
+ await b.run;
+ assert.equal(b.calls.length, 2, "not ended on one refused read");
+});
+
+test("DESIGN-3 fallback (REVIEW-4 3.1): a hole of minutes on a long stream is not under a 1 % tolerance: flat 180 s", { timeout: 60_000 }, async () => {
+ const id = "exmplres3a08";
+ let live = true;
+ // A 9 h stream; the finished from-start part holds up to 5 min before now.
+ const { run } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(9 * 3600 - 300);
+ await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true });
+ return "die";
+ }
+ if (isRecovery(args)) {
+ await write(9 * 3600 + 200);
+ return "end";
+ }
+ await write(120);
+ await new Promise((r) => setTimeout(r, 200));
+ live = false;
+ return "end";
+ }),
+ { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 9 * 3600 }, deps: { ...FAST_WATCH, join: null }, refresh: { stillLive: () => live } },
+ );
+ await run;
+ const row = (await rowOf(id))[0]!;
+ assert.ok(row.lost, "the 5 min are said lost (1 % of 9 h, 324 s, would have hidden them)");
+});
+
+test("DESIGN-3 fallback (REVIEW-4 1.1): the gap recovery's first try waits until the live-edge part holds bytes", { timeout: 60_000 }, async () => {
+ const id = "exmplres3a09";
+ let live = true;
+ let edgeBytesAt = Infinity;
+ let recoveryAt = 0;
+ const { run } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args, signal }) => {
+ if (n === 1) {
+ await write(60);
+ await rm(`${outOf(args)}.f18.mp4.ytdl`, { force: true });
+ return "die";
+ }
+ if (isRecovery(args)) {
+ recoveryAt = Date.now();
+ await write(18100);
+ await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 2000))]);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ await new Promise((r) => setTimeout(r, 150));
+ await write(300);
+ edgeBytesAt = Date.now();
+ await until(() => recoveryAt > 0, 3000);
+ await new Promise((r) => setTimeout(r, 100));
+ live = false;
+ return "end";
+ }),
+ { meta: { ...YT_META(id), release_timestamp: hoursAgo(5) }, deps: { ...FAST_WATCH, join: null, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
+ );
+ await run;
+ assert.ok(recoveryAt > 0, "a recovery try ran");
+ assert.ok(recoveryAt >= edgeBytesAt, "it began only once the live-edge part held bytes");
+});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -189,6 +189,9 @@ export const LIVE_EDGE_EMPTY_TO_END = 3;
// A from-start part short of the live edge by more than max(this, 1 % of the
// stream so far) leaves a span in no part: recovered beside the live edge.
export const LIVE_GAP_TOLERANCE_SECONDS = 180;
+// yt-dlp's YouTube from-start generator holds 120 h (MAX_DURATION): past it
+// a saved fragment index no longer lines up.
+export const LIVE_RESUME_MAX_AGE_MS = 120 * 3_600_000;
// A restart after the editor's: the stream's state read again after these
// waits when it could not be read (three reads over about ten minutes).
export const LIVE_BOOT_STATE_READ_WAITS_MS: readonly number[] = [120_000, 480_000];
@@ -416,8 +419,11 @@ export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, la
const onAbort = () => {
if (signalled) return;
signalled = true;
- onLog(`[${label}] stopping: SIGINT, so the recording is finalized\n`);
- child.kill("SIGINT");
+ // SIGTERM (DESIGN-3): yt-dlp installs no handler, so it ends without
+ // finishing and a from-start download's `.ytdl` state stays.
+ const how = signal.reason === "SIGTERM" ? "SIGTERM" : "SIGINT";
+ onLog(`[${label}] stopping: ${how === "SIGTERM" ? "SIGTERM, its state kept for a resume" : "SIGINT, so the recording is finalized"}\n`);
+ child.kill(how);
killTimer = setTimeout(() => child.kill("SIGKILL"), RECORDER_GRACE_MS);
};
if (signal.aborted) onAbort();
@@ -1037,17 +1043,31 @@ async function recordLiveRunInner(
// Is the stream still live? One metadata read (slice 3's restarts): a
// read that says it ended is the end read the landing would make.
let endRead = false;
- const liveNow = async (): Promise<"live" | "ended" | "unknown"> => {
+ let endedByRefusal = false;
+ const liveNow = async (confirm = true): Promise<"live" | "ended" | "unknown"> => {
try {
await refresh();
} catch (err) {
const msg = (err as Error).message;
// A read refused because the stream is over, private or removed is the
- // platform's word (REVIEW-3 1.1 of live-guard-2): it ends.
+ // platform's word — once CONFIRMED by a second read a minute later
+ // (REVIEW-4 5.1: "Video unavailable" is also what a geo refusal says).
+ // Confirmed, the row says the stream went private or was removed while
+ // it was recorded, and what is held: never a quiet landing.
const c = liveFailureClass(msg);
if (c === "ended" || c === "private") {
- say(`The stream's metadata says it is ${c === "ended" ? "over" : "private or removed"} (${msg.split("\n")[0]}).`);
+ if (confirm) {
+ say(`The stream's metadata was refused (${msg.split("\n")[0]}): read again in ${spanWords(LIVE_RESTART_CONFIRM_MS / 1000)} before the recording ends.`);
+ await waitFor(stretch(LIVE_RESTART_CONFIRM_MS), signal);
+ const again = await liveNow(false);
+ if (again !== "ended" || !endedByRefusal) return again;
+ return "ended";
+ }
endRead = true;
+ endedByRefusal = true;
+ hooks.record!.endedBy = { class: c, message: msg.split("\n")[0]!.slice(0, 300), at: now().toISOString() };
+ await hooks.save?.();
+ say(`The stream ${c === "ended" ? "is over" : "went private or was removed"} while it was recorded (${msg.split("\n")[0]}): what is held lands, and the row needs a person.`);
return "ended";
}
say(`The stream's metadata could not be read (${msg.split("\n")[0]}).`);
@@ -1306,10 +1326,25 @@ async function recordLiveRunInner(
stop?: AbortSignal;
onStart?: (stem: string) => void;
onLine?: (line: string) => void;
+ // DESIGN-3: RESUME IN PLACE — this stem's files and state again (same
+ // `-o`), the format pinned to the ids on disk; this run's part of that
+ // stem, or a new entry for it (a boot restart of an earlier run's part).
+ resume?: { stem: string; formats: string };
} = {},
): Promise<RecorderOutcome & { part: LivePart; stem: string; stalled: boolean }> => {
- const file = separate ? stemPath(tag) : partPath(tag);
- const part = begin("ytdlp", url, file, mode !== "now");
+ const file = opts.resume
+ ? path.join(slugStore, separate ? opts.resume.stem : `${opts.resume.stem}.ts`)
+ : separate
+ ? stemPath(tag)
+ : partPath(tag);
+ const known = opts.resume ? parts.find((p) => p.stem === opts.resume!.stem)?.part : undefined;
+ const part = known ?? begin("ytdlp", url, file, mode !== "now");
+ if (opts.resume) {
+ part.resumes = (part.resumes ?? 0) + 1;
+ delete part.endedAt;
+ delete part.stalled;
+ if (known) record.attempts = (record.attempts ?? 0) + 1;
+ }
if (opts.recovery) part.recovery = true;
if (opts.restart) part.restart = opts.restart;
if (opts.insurance) part.insurance = true;
@@ -1325,6 +1360,7 @@ async function recordLiveRunInner(
maxHeight,
separate,
waitForVideo,
+ ...(opts.resume ? { format: opts.resume.formats } : {}),
channelArgs: [
...channelExtraArgs(cfg, cookies),
"--downloader-args",
@@ -1337,12 +1373,19 @@ async function recordLiveRunInner(
// job's. Every watchMs the part's files (all of them) are summed; no
// change for stallMs stops this recorder only. An upcoming stream's
// recorder waiting for it with nothing written is not stalled.
+ // HOW IT IS STOPPED (DESIGN-3): a from-start recorder stopped by the
+ // watchdog or an editor shutdown gets SIGTERM — yt-dlp then does not
+ // finish, and its `.ytdl` state stays for the resume; a person's Cancel
+ // (and every other recorder) SIGINT, which finishes the file.
+ const resumable = mode === "from-start";
const own = new AbortController();
- const onJobAbort = () => own.abort();
- if (signal.aborted || opts.stop?.aborted) own.abort();
+ const onJobAbort = () => own.abort(resumable && stopOf(deps).by === "shutdown" ? "SIGTERM" : "SIGINT");
+ const onOwnStop = () => own.abort("SIGINT");
+ if (signal.aborted) onJobAbort();
+ else if (opts.stop?.aborted) onOwnStop();
else {
signal.addEventListener("abort", onJobAbort, { once: true });
- opts.stop?.addEventListener("abort", onJobAbort, { once: true });
+ opts.stop?.addEventListener("abort", onOwnStop, { once: true });
}
let stalled = false;
let timer: NodeJS.Timeout | null = null;
@@ -1365,9 +1408,9 @@ async function recordLiveRunInner(
stalled = true;
say(
`[${tag}] stalled: its files have not grown for ${spanWords((t - lastGrowth) / 1000)} (${formatBytes(b)}); ` +
- "stopping this recorder (SIGINT); its part is kept.",
+ `stopping this recorder (${resumable ? "SIGTERM: its state is kept for the resume" : "SIGINT"}); its part is kept.`,
);
- own.abort();
+ own.abort(resumable ? "SIGTERM" : "SIGINT");
}
})
.finally(() => {
@@ -1389,7 +1432,7 @@ async function recordLiveRunInner(
} finally {
if (timer) clearInterval(timer);
signal.removeEventListener("abort", onJobAbort);
- opts.stop?.removeEventListener("abort", onJobAbort);
+ opts.stop?.removeEventListener("abort", onOwnStop);
}
if (stalled) part.stalled = true;
finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? (stalled ? " (stopped: stalled)" : " (stopped)") : ""}`);
@@ -1423,12 +1466,52 @@ async function recordLiveRunInner(
await save();
return false;
};
+ // DESIGN-3: can this stem be resumed in place? Every stream file with bytes
+ // has yt-dlp's `<file>.ytdl` beside it with a readable fragment index
+ // (downloader/fragment.py), the stream is under 120 h old (past that the
+ // from-start generator starts later and the saved index would misalign,
+ // extractor/youtube/_video.py), and the ids on disk pin the format.
+ const resumeStateOf = async (stem: string): Promise<{ ok: true; formats: string; fragment: number } | { ok: false; why: string }> => {
+ const g = await filesOf(stem);
+ if (!g) return { ok: false, why: "its files are gone" };
+ const withBytes: string[] = [];
+ for (const f of g.streams) if ((await sizeOf(path.join(slugStore, f))) > 0) withBytes.push(f);
+ if (!withBytes.length) return { ok: false, why: g.finished.length ? "it was finished (merged)" : "nothing to resume" };
+ let fragment = Infinity;
+ for (const f of withBytes) {
+ const raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null);
+ if (raw === null) return { ok: false, why: `${f} has no .ytdl state (finished, or never kept)` };
+ let idx: unknown;
+ try {
+ idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index;
+ } catch {
+ idx = null;
+ }
+ if (typeof idx !== "number" || idx < 0) return { ok: false, why: `${f}.ytdl does not read` };
+ fragment = Math.min(fragment, idx);
+ }
+ const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN;
+ if (Number.isFinite(startMs) && now().getTime() - startMs > LIVE_RESUME_MAX_AGE_MS) return { ok: false, why: "the stream is over 120 h old" };
+ const ids = withBytes.map((f) => /\.f([^.]+)\.[a-z0-9]+$/i.exec(f)?.[1]).filter((x): x is string => !!x);
+ if (ids.length !== withBytes.length) return { ok: false, why: "its format ids cannot be read from its files" };
+ return { ok: true, formats: ids.join("+"), fragment };
+ };
// 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
+ // the sound) — 0 when unread.
const secondsOf = async (stem: string): Promise<number> => {
const g = await filesOf(stem);
- let best = 0;
- for (const f of g ? [...g.finished, ...g.streams] : []) best = Math.max(best, (await probe(path.join(slugStore, f)).catch(() => null))?.seconds ?? 0);
- return best;
+ if (!g) return 0;
+ let fin = 0;
+ for (const f of g.finished) fin = Math.max(fin, (await probe(path.join(slugStore, f)).catch(() => null))?.seconds ?? 0);
+ if (fin > 0) return fin;
+ let min = Infinity;
+ for (const f of g.streams) {
+ if ((await sizeOf(path.join(slugStore, f))) === 0) continue;
+ min = Math.min(min, (await probe(path.join(slugStore, f)).catch(() => null))?.seconds ?? 0);
+ }
+ return Number.isFinite(min) ? min : 0;
};
// Every file of the part, scratch too (the watchdog's growth).
const allBytesOf = async (stem: string) => {
@@ -1523,6 +1606,10 @@ async function recordLiveRunInner(
let mainStem: string | null = null;
let mainFromStart = false;
const tracker = catchUpTracker();
+ // The main from-start part's own catch-up (its frag N/M), and the stem
+ // that last showed it caught up.
+ const mainTracker = catchUpTracker();
+ let caughtUpStem: string | null = null;
let caughtUpTimer: NodeJS.Timeout | null = null;
let graceTimer: NodeJS.Timeout | null = null;
let rearm: (() => void) | null = null;
@@ -1534,7 +1621,8 @@ async function recordLiveRunInner(
// Re-arm a stopped insurance (within its bound) beside a from-start
// capture that is behind again: a recovery try (REVIEW-3 3.2).
const rearmInsurance = () => {
- if (!record.insurance) return;
+ // Not while a live-edge main records already (REVIEW-4 1.2).
+ if (!record.insurance || !mainFromStart) return;
if (caughtUpTimer) clearTimeout(caughtUpTimer);
caughtUpTimer = null;
if (insureStop.signal.aborted && insuranceStopFor === "caught-up") {
@@ -1546,6 +1634,7 @@ async function recordLiveRunInner(
// A RESTART never stops a working insurance recorder (REVIEW-3 3.2 of
// live-guard-2): only the schedule's own fall back to the live edge does.
const onMainStart = (mode: "from-start" | "index0" | "now", restart = false) => (stem: string) => {
+ if (stem !== mainStem) mainTracker.reset();
mainStem = stem;
mainFromStart = mode !== "now";
tracker.reset();
@@ -1557,6 +1646,7 @@ async function recordLiveRunInner(
if (restart && mode !== "now") rearmInsurance();
};
const onMainLine = (l: string) => {
+ if (mainFromStart && mainTracker.feed(l)) caughtUpStem = mainStem;
if (record.insurance?.mode !== "catch-up" || caughtUpTimer || insureStop.signal.aborted || !mainFromStart) return;
if (!tracker.feed(l)) return;
say(`The from-start recording has caught up with the live edge; the insurance recorder stops in ${spanWords(margin / 1000)}.`);
@@ -1701,6 +1791,8 @@ async function recordLiveRunInner(
// A GAP recovery (REVIEW-3 3.1): its tries stop once a from-start part
// reaches this stream second (where the newest live-edge part begins).
let gapTarget: number | null = null;
+ // The newest live-edge restart's stem (a gap recovery waits for its bytes).
+ let edgeRestartStem: string | null = null;
const recoveryStop = new AbortController();
let edgeDone = false;
const recoverStart = async (useIndex0: boolean, ro: { gap?: boolean } = {}): Promise<void> => {
@@ -1751,9 +1843,21 @@ async function recordLiveRunInner(
let covered = false;
let watcher: NodeJS.Timeout | null = null;
const tag = `ytdlp-recover-r${rs.tries}`;
+ // Also stopped on the stream's own clock: its frag N/M caught up, then
+ // a minute (REVIEW-4 2.1(c)).
+ const tryTracker = catchUpTracker();
+ let caughtTimer: NodeJS.Timeout | null = null;
const o = await ytdlpPart(plan.url, tag, useIndex0 ? "index0" : "from-start", `start recovery ${rs.tries}/${rs.max}; `, {
recovery: true,
stop: reached.signal,
+ onLine: (l) => {
+ if (!ro.gap || caughtTimer || reached.signal.aborted || !tryTracker.feed(l)) return;
+ caughtTimer = setTimeout(() => {
+ covered = true;
+ say(`Start recovery: try ${rs.tries} has caught up with the live edge (its own fragments): the span is held; it is stopped.`);
+ reached.abort();
+ }, LIVE_RESTART_CONFIRM_MS);
+ },
onStart: (stem) => {
recoveryStem = stem;
rearmInsurance();
@@ -1761,6 +1865,9 @@ async function recordLiveRunInner(
let busy = false;
watcher = setInterval(() => {
if (busy || reached.signal.aborted || gapTarget === null) return;
+ // An index-0 try begins at the playlist's first LISTED segment:
+ // its length is no stream position (REVIEW-4 2.1(b)).
+ if (useIndex0 && record.reach?.fromStart !== true) return;
busy = true;
void secondsOf(stem)
.then((sec) => {
@@ -1777,6 +1884,7 @@ async function recordLiveRunInner(
},
});
if (watcher) clearInterval(watcher);
+ if (caughtTimer) clearTimeout(caughtTimer);
recoveryStem = null;
if (covered) {
rs.state = "recovered";
@@ -1849,9 +1957,26 @@ async function recordLiveRunInner(
// SLICE 2: the first live-edge attempt after a fallback starts the
// from-start tries beside it (their first is 15 min away).
if (mode === "now" && fromStart && record.fallback === "live-edge" && recovery === null) recovery = recoverStart(index0);
+ // DESIGN-3: a restart after the editor's resumes the interrupted run's
+ // from-start part in place when its state is there.
+ let bootResume: { stem: string; formats: string } | null = null;
+ if (resumeOf && slot === 0 && mode === "from-start" && n === 1) {
+ const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []);
+ const oldRow = rows.find((r) => r.id === id && r.startedAt === resumeOf);
+ for (const p of oldRow?.parts ?? []) {
+ if (!p.stem || !p.fromStart || p.index0 || p.recovery) continue;
+ const st = await resumeStateOf(p.stem);
+ if (st.ok) {
+ bootResume = { stem: p.stem, formats: st.formats };
+ say(`Restart after the editor restart: ${p.stem} is resumed in place from fragment ${st.fragment}.`);
+ break;
+ }
+ }
+ }
const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : "", {
onStart: onMainStart(mode),
onLine: onMainLine,
+ ...(bootResume ? { resume: bootResume, noWait: true } : {}),
});
// This attempt's own part (a try beside it may have begun one since).
const last = { part: o.part, stem: o.stem };
@@ -1982,6 +2107,8 @@ async function recordLiveRunInner(
// recorded, and needs a person.
let restartLimited = false;
let emptyInRow = 0;
+ // Stems whose resume was impossible or wrote nothing (not tried again).
+ const resumeFailed = new Set<string>();
while (cur && !signal.aborted && !pathB) {
const stalledWithBytes = cur.o.stalled && cur.bytes > 0;
const exitedWithBytes = !cur.o.signalled && cur.bytes > 0 && !cur.partial;
@@ -2066,6 +2193,45 @@ async function recordLiveRunInner(
}
if (pause) await waitFor(stretch(pause), signal);
if (signal.aborted) break;
+ // DESIGN-3 — RESUME IN PLACE. A from-start part whose files keep
+ // yt-dlp's `.ytdl` state (it died, or was stopped without finishing)
+ // is continued: the same stem, its format pinned, from the saved
+ // fragment — no new part, no gap, no second download, no live edge,
+ // no recovery. Only when that is impossible (no state, an unreadable
+ // 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);
+ if (st.ok) {
+ restarts.count += 1;
+ restarts.at.push(now().toISOString());
+ const before = await allBytesOf(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,
+ });
+ const after = await allBytesOf(o.stem);
+ const bytes = await bytesOf(o.stem);
+ if (after > before) {
+ 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"}`;
+ await save();
+ say(`The resume wrote nothing (${o.part.resumeError}): the live-edge fallback.`);
+ 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.`);
+ resumeFailed.add(cur.o.stem);
+ }
+ }
// 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
@@ -2088,10 +2254,14 @@ async function recordLiveRunInner(
}
}
spans.sort((a, b) => a[0] - b[0]);
- const tol = elapsed !== null ? Math.max(LIVE_GAP_TOLERANCE_SECONDS, elapsed * 0.01) : LIVE_GAP_TOLERANCE_SECONDS;
+ // A flat 180 s (REVIEW-4 3.1): a fraction of a long stream would hide minutes.
+ const tol = LIVE_GAP_TOLERANCE_SECONDS;
let reach = 0;
for (const [a, b] of spans) if (a <= reach + tol) reach = Math.max(reach, b);
- if (elapsed === null || elapsed - reach > tol) {
+ // A from-start part whose own progress (frag N/M) showed it caught
+ // up has no gap behind it, whatever the clock says (REVIEW-4 2.2).
+ const caughtUp = caughtUpStem !== null && caughtUpStem === cur.o.stem;
+ if (!caughtUp && (elapsed === null || elapsed - reach > tol)) {
const hm = (x: number) => `${Math.floor(x / 3600)}:${String(Math.floor((x % 3600) / 60)).padStart(2, "0")}`;
record.lost = { fromSeconds: Math.round(reach), toSeconds: elapsed !== null ? Math.round(elapsed) : null };
if (elapsed !== null) gapTarget = Math.max(gapTarget ?? 0, elapsed);
@@ -2104,10 +2274,27 @@ async function recordLiveRunInner(
if (!recoveryRunning && (record.startRecovery?.tries ?? 0) < LIVE_RECOVERY_MAX_TRIES) {
recoveryRunning = true;
const prev = recovery;
+ // Its first try only once the live-edge restart holds bytes, then a
+ // jittered pause (REVIEW-4 1.1/6.1): never two extractions at once,
+ // and an ended stream's empty live edge starts none.
recovery = (async () => {
await prev;
+ const stop = AbortSignal.any([signal, recoveryStop.signal]);
+ while (!stop.aborted && !(edgeRestartStem && (await bytesOf(edgeRestartStem)) > 0)) await sleep(deps.insurancePollMs ?? 5_000, stop);
+ if (stop.aborted) {
+ recoveryRunning = false;
+ if (record.startRecovery && record.startRecovery.state !== "recovered") record.startRecovery.state = "stopped";
+ else record.startRecovery ??= { tries: 0, max: LIVE_RECOVERY_MAX_TRIES, everyMs: LIVE_RECOVERY_EVERY_MS, state: "stopped" };
+ await save();
+ return;
+ }
+ await waitFor(stretch(LIVE_INSURANCE_DELAY_MS), stop);
await recoverStart(index0, { gap: true });
})();
+ } else if (!recoveryRunning) {
+ // No try is left: the new span stays loud (REVIEW-4 2.3).
+ record.startRecovery = { ...(record.startRecovery ?? { tries: LIVE_RECOVERY_MAX_TRIES, max: LIVE_RECOVERY_MAX_TRIES, everyMs: LIVE_RECOVERY_EVERY_MS }), state: "exhausted" };
+ await save();
}
}
}
@@ -2118,7 +2305,10 @@ async function recordLiveRunInner(
const o = await ytdlpPart(plan.url, `ytdlp-r${k}`, "now", `restart ${k} (${why}); `, {
restart: k,
noWait: true,
- onStart: onMainStart("now", true),
+ onStart: (stem) => {
+ edgeRestartStem = stem;
+ onMainStart("now", true)(stem);
+ },
onLine: onMainLine,
});
const bytes = await bytesOf(o.stem);
@@ -2141,7 +2331,7 @@ async function recordLiveRunInner(
// otherwise it runs on by itself — it may be the only recorder left.
mainDoneCtl.abort();
if (insurance) {
- if (endRead && !insureStop.signal.aborted) {
+ if (endRead && !endedByRefusal && !insureStop.signal.aborted) {
graceTimer = setTimeout(() => {
insuranceStopFor ??= "ended";
insureStop.abort();
@@ -2211,8 +2401,20 @@ async function recordLiveRunInner(
const unlandable: string[] = [];
const unlandableGroups: { group: LivePartFiles; why: string; part?: LivePart }[] = [];
const empty: LivePartFiles[] = [];
+ // DESIGN-3: at an editor shutdown a part that can be resumed is not landed
+ // (a landing would merge its streams and end its state): it waits in
+ // staging, as it is, for the boot's restart to resume it.
+ const waitsForResume = new Set<string>();
+ if (stopped?.by === "shutdown") {
+ for (const g of groups) if ((await resumeStateOf(g.stem)).ok) waitsForResume.add(g.stem);
+ }
for (const g of groups) {
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.`);
+ continue;
+ }
let got: ResolvedPart | null = null;
try {
got = await resolvePart(g, slugStore, { probe: (f) => probe(f, landSignal), merge: (a) => merge(a, landSignal), say });
diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts
@@ -256,6 +256,8 @@ export function ytdlpLiveArgs(opts: {
// An upcoming stream: wait for it to start, re-asking every 60 s. Never for
// a stream that is (or was) live — yt-dlp would wait for the NEXT one.
waitForVideo?: boolean;
+ // A resume (DESIGN-3): the format ids already on disk, pinned.
+ format?: string;
}): string[] {
return [
"--ignore-config",
@@ -265,7 +267,7 @@ export function ytdlpLiveArgs(opts: {
opts.fromStart ? "--live-from-start" : "--no-live-from-start",
...(opts.waitForVideo ? ["--wait-for-video", "60"] : []),
"-f",
- liveFormatSelector(opts.maxHeight, opts.separate === true),
+ opts.format ?? liveFormatSelector(opts.maxHeight, opts.separate === true),
...(opts.separate ? ["--merge-output-format", LIVE_MERGE_OUTPUT_FORMAT] : []),
"--hls-use-mpegts",
"--no-part",
@@ -463,6 +465,11 @@ export type LivePart = {
// Recorded `--no-live-from-start` with ffmpeg at the playlist's first listed
// segment: from the start only if the playlist reaches it.
index0?: boolean;
+ // DESIGN-3: how many times its recorder was RESUMED in place (the same
+ // files, yt-dlp's own `.ytdl` state).
+ resumes?: number;
+ // Why the last resume wrote nothing (the fallback followed).
+ resumeError?: string;
};
export type MissingStream = "video" | "audio" | "unknown";
@@ -563,6 +570,12 @@ export type LiveRecordingRecord = {
resumeOf?: string;
// The insurance recorder beside the from-start recording (LiveInsurance).
insurance?: LiveInsurance;
+ // The platform refused a state read as private/removed (or over), twice a
+ // minute apart, while it was being recorded (REVIEW-4 5.1).
+ endedBy?: { class: LiveFailureClass; message: string; at: string };
+ // DESIGN-3: parts an editor shutdown stopped with their state kept, waiting
+ // in staging (not landed) for the boot's restart to resume them.
+ awaitingResume?: string[];
// Spawns that did not start because the store's disk was under the floor
// (RECORD_LIVE_MIN_FREE_BYTES): what, when, and how much was free.
spaceHeld?: LiveSpaceHeld[];
@@ -900,7 +913,9 @@ export function liveFailureClass(stderr: string): LiveFailureClass {
// First: no space is no space, whatever else the tail says.
if (/No space left on device|Errno 28\b|Disk quota exceeded|Read-only file system|\[Errno 13\] Permission denied/i.test(t)) return "disk";
// Before `members`: the bot check's message also says "use --cookies".
- if (/HTTP Error 429|Too Many Requests|Sign in to confirm you(?:'|’)re not a bot|confirm you(?:'|’)re not a bot/i.test(t)) return "rate-limited";
+ // (YouTube's soft block, "This content isn't available, try again later",
+ // is a rate limit too: REVIEW-4 1.3 of live-guard-2.)
+ if (/HTTP Error 429|Too Many Requests|Sign in to confirm you(?:'|’)re not a bot|confirm you(?:'|’)re not a bot|content isn(?:'|’)t available, try again later/i.test(t)) return "rate-limited";
if (/This live event has ended|is no longer live|is not currently live|This live stream recording is not available|live stream has ended/i.test(t)) return "ended";
if (/Private video|This video is private|Video unavailable|This video has been removed|has been terminated|This video is no longer available/i.test(t)) return "private";
if (/Join this channel|available to this channel's members|members-only|members only|requires payment|Sign in to confirm your age|login required|account is required|use --cookies|--cookies-from-browser/i.test(t)) return "members";
diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts
@@ -86,6 +86,8 @@ export type LiveRecordingRow = {
insurance?: LiveInsurance;
joins?: LiveJoin[];
spaceHeld?: LiveSpaceHeld[];
+ endedBy?: { class: LiveFailureClass; message: string; at: string };
+ awaitingResume?: string[];
// What the landing kept: this run's file stored ("new"), or the store's.
kept?: "new" | "existing";
acknowledgedAt?: string;
@@ -175,7 +177,7 @@ export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, s
// recording that holds the whole stream (supersededBy).
export function rowNeedsAttention(
r: Pick<LiveRecordingRow, "status" | "fallback" | "acknowledgedAt" | "supersededBy"> &
- Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost">>,
+ Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost" | "endedBy">>,
): boolean {
if (r.acknowledgedAt) return false;
if (r.keptParts && r.keptParts.length > 0) return true;
@@ -188,6 +190,8 @@ export function rowNeedsAttention(
if (r.restarts?.refused) return true;
// A recorder (or a join) not started for want of disk.
if (r.spaceHeld && r.spaceHeld.length) return true;
+ // The stream went private or was removed while it was recorded.
+ if (r.endedBy && r.endedBy.class === "private") return true;
// Landed as parts joined with a gap: those seconds are in no part.
if (r.joins?.some((j) => j.kind === "gap")) return true;
return r.missingStream !== undefined;
@@ -260,6 +264,8 @@ export function rowOfRecord(
parts: rec.parts.map((p) => ({ ...p })),
...(rec.landedPart !== undefined ? { landedPart: rec.landedPart } : {}),
...(rec.kept ? { kept: rec.kept } : {}),
+ ...(rec.endedBy ? { endedBy: { ...rec.endedBy } } : {}),
+ ...(rec.awaitingResume && rec.awaitingResume.length ? { awaitingResume: [...rec.awaitingResume] } : {}),
...(rec.spaceHeld && rec.spaceHeld.length ? { spaceHeld: rec.spaceHeld.map((x) => ({ ...x })) } : {}),
...(rec.failureClass ? { failureClass: rec.failureClass } : {}),
...(rec.missingStream ? { missingStream: rec.missingStream } : {}),
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -3,6 +3,8 @@
## [Unreleased]
- **A live recording keeps itself alive: the start retried beside the live edge, stalls restarted, an insurance
recorder, a restart after the editor's, and parts joined.**
+ - A from-start recorder that dies, stalls or is stopped by an editor shutdown is RESUMED in place from yt-dlp's
+ own `.ytdl` state: the same part, no gap, no second download; the live-edge restart is only the fallback.
- After a fallback to the live edge, from its start is tried again beside it every 15 min, at most 8 times; a try
that lands the whole stream recovers the start.
- A recorder whose files stop growing for `liveRecording.stallMinutes`, or that exits while the stream still reads
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -2823,7 +2823,10 @@ export function usage() {
" try at a time, at most 8; a try that holds the whole stream when landed",
" recovers the start (startRecovery). Each recorder has a stall watchdog:",
" no growth for liveRecording.stallMinutes (10) stops that recorder, its",
- " part kept; while the stream still reads live (one metadata read; an exit",
+ " part kept; a from-start recorder (dead, stalled, or stopped by a",
+ " shutdown) is RESUMED in place from yt-dlp's .ytdl state — the same part —",
+ " and only when that is impossible does a live-edge recorder follow:",
+ " while the stream still reads live (one metadata read; an exit",
" is read twice, a minute apart) a new part records from the live edge —",
" at most 6 restarts an hour and 24 a run (restarts); past them the row",
" says the stream is live and NOT recorded. \"insurance\"?: true | \"whole\" | false —",