commit b1cbc3b4906d263db85a9401557886d02f7cf92a
parent 57a612ce1cb11e6ea0bd00a5316ada816bdf9074
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Tue, 24 Nov 2026 13:39:05 -0500
Merge lane/live-guard-2: a live recording survives outages, ends and restarts without losing stream time
A network outage spends no restart and resumes the same files in place; a read that fails for any other reason resumes in place too. A from-start part found far behind gets a live-edge insurance beside it, started again if it ends early. A resume on an end happens only for post_live. Every resume is checked against its kept fragments; a landing is verified against the stream files (tracks within max(2 s, 2 fragments), bytes against the fragments) before anything is removed, and a part that cannot be proven whole keeps its files. "Verify again" re-checks a landing under the stem lock. The stem lock is taken before any repair and is never read empty.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
33 files changed, 9605 insertions(+), 469 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. | `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; while the stream still reads live (one metadata read; an exit is read twice, a minute apart) a from-start recorder (dead, stalled, stopped by a shutdown, or ended by itself) is RESUMED in place — the same files, every kept fragment reused — and only when that cannot be proven does a FRESH part record from the stream's start, then the live edge (6 restarts an hour, waited out, never an end); while the state cannot be read for the network nothing is started and no restart spent. "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 when the stream is marked keep ("doNotClean", the record's Do-not-clean marker, a pending keep), and also when a from-start part shows itself more than 10 min behind the live edge (liveRecording.insuranceWhenBehind). 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"}}'` |
@@ -156,6 +156,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `live-preclip` | live-preclip transcribes and mines a recording WHILE it records: {"slug", "id", "action"?: "start" (default) \| "stop" \| "status" \| "finalize"}, and for start "everyMinutes"? (10), "maxChunkMinutes"? (20), "overlapSeconds"? (15), "scan"? (true: the laugh scan), "mine"? (true), "project"? (the umtool project, <id>-live). One job per stream beside the recorder's: each tick reads only the new span of the growing file (never writing it), transcribes it on a worker lease (one at a time — a busy worker coalesces ticks), splices it into data/<id>/live-transcript.json (provisional) and grows the umtool project. Skipped and said: under 30 s new, MemAvailable under HEAVY\_MIN\_FREE\_MB (6000), the store's disk under 2 GB. When the stream lands: the clock check (flagged when the landed video's start differs), then the final transcript supersedes the live one. stop cancels the job, never the recording; status prints the state; finalize does the supersede by hand. No network request. | `pnpm ops live-preclip --json '{"slug":"demo-yt","id":"<videoId>","action":"status"}'` |
| `live-clip` | live-clip makes a shareable clip of a stream still live: {"slug", "id", "start", "end"} (seconds of the stream, at most 2:20) or "clip" (a clip id of the project), "project"? (<id>-live), "replace"?. umtool cuts the window from the recording now (the editor's /api/media/live-window: the part being written, or the saved video once landed; no network), adds the clip, and makes its short with the live transcript's captions. With --wait the result (the short's URL) is stdout. | `pnpm ops live-clip --json '{"slug":"demo-yt","id":"<videoId>","start":3605,"end":3660}' --wait` |
| `live-recording-ack` | live-recording-ack {"slug", "id", "startedAt"?, "by"?} acknowledges every run of the record that needs a person (or the one run startedAt names): listed still, counted no more. {"slug", "file"} acknowledges a set-aside live-recordings.json (it stays where it is). /review's Acknowledge. | `pnpm ops live-recording-ack --json '{"slug":"demo-yt","id":"<videoId>"}'` |
+| `live-recording-verify` | live-recording-verify {"slug", "id", "startedAt"?} checks a landed file whose verification failed or never ran against the stream files it was made from (packets per track, the tracks' spans, a hole scan, each stream file byte for byte its kept fragments); verified and the stream confirmed done, those stream files, their state and fragments are removed; else the row says why and nothing is. The row's Verify button. | |
| `prepare-playable` | prepare-playable remuxes each of a channel's saved containers, losslessly (-c copy), into a browser-playable mp4 (+faststart) or webm, and makes one single-file torrent per copy, under playable/ beside the saved-video store: {"slug"}. "ids" narrows it; "trackers": \[...\] is each .torrent's announce list (none by default; the infohash does not depend on it); "root" names another playable root. A video prepared from the same source (by sha256) is skipped; "dryRun": true logs each decision. | |
| `compact-saved-videos` | compact-saved-videos re-encodes saved videos to AV1 (SVT-AV1, settings savedVideoCompaction: crf 36, preset 8, a keyframe every 5 s, the source's height, Kick and Twitch above 30 fps to 30, every other stream and the chapters copied), verifies the copy and makes it the active one; the original stays beside it ("keptAs": "original"): {"items": \[{"slug", "id"}, ...\]} names videos (deliberately stored only: a pin, an explicit persist, a requested or landed container -- never keep-latest, never persist-kept's override); {"select": true, "slugs"?} asks the selector (and platform, height and video bitrate) and is a DRY RUN unless "dryRun": false. A named video the selector would not pick is refused unless "belowThreshold": true (the refusal says how little it saves). "dryRun": true answers each video's line -- size, bitrate, height, fps, the estimate (size, hours), the disk it needs, or why it is skipped. "crf", "preset", "maxFps", "chunkMinutes" override the settings for the run; "retryFailed": true encodes again one whose last checks failed; "reverify": true checks its KEPT encode again without encoding (a chunk whose own content failed is encoded again). One job per channel on the compact queue, one video at a time, each chunk through the heavy slot; a Retry resumes. The checks include a whole-file comparison and excerpts across every chunk join. dropOriginal is "keep" by default; under "after-verify" the original is dropped in a later step once the copy re-checks from disk -- never for a video not freshly checked on its platform (get compaction-review). There is no backup of the store: after a drop the compacted copy is the only copy. | |
| `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "<file>" reviews the active copy that replaced a former original instead. | |
@@ -516,7 +517,8 @@ get live-recordings [<slug>[/<id>]] [--all] is THE answer to "is this
bytes and lastGrowthAt while recording), stalled (not grown for
settings.liveRecording.stallMinutes, 10), streamElapsedSeconds,
capturedSeconds (once landed), coverage, attempts, failureClass,
- fallback, lost, missingStream, keptParts, error, mustKeep,
+ fallback, lost, startRecovery, restarts, insurance, restart (what the
+ boot pass did), joins, missingStream, keptParts, error, mustKeep,
needsAttention, reason, check; `files` names a live-recordings.json that
did not read (set aside, never overwritten). Default: what is recording,
what needs a person, the last 7 days; --all every run kept
diff --git a/OPERATING.md b/OPERATING.md
@@ -1400,7 +1400,8 @@ pnpm ops import-media --json '{"slug":"example-archive","path":"/mnt/old/talk.mk
pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":"keep"}'
```
-- `record-live` (the channel page's Media → **Record live**, or a video's Media tools) records until the stream
+- `record-live` (the channel page → the Cleanup stage → **Media for the whole channel** → Record live, or a video's page
+ → **Media tools**) records until the stream
ends — hours, one job per stream on its own queue — then lands the recording as the video's source. From the
start by default: Rumble's DVR playlist holds a stream's first 4 hours (past that, the last 4), which yt-dlp's
`--live-from-start` reads (the private fork's Rumble support). When Rumble refuses yt-dlp, the page is opened in a
@@ -1462,10 +1463,184 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note":
only by a file that holds the whole stream from its start; otherwise nothing lands, every part stays listed
(`keptParts`), the run is `failed` ("not landed: …") and needs a person — and whenever the landing keeps the stored
container, nothing is removed.
+- **A recording already in the store is never replaced or deleted around by one not proven to hold it.** When the
+ saved-video store already holds a container for the stream (an earlier run's landing — a shutdown's included), a
+ new run lands over it only when its file holds the whole stream from its start (the coverage rule), or when it is a
+ proven join that includes the stored container (as its base, when the run that stored it landed a part PROVEN from its
+ start). Otherwise nothing lands: the store keeps what it holds, every part stays in staging as `keptParts`, the run
+ is `failed` ("not landed: …") and needs a person. And whenever the landing ends up keeping the stored container,
+ nothing is removed. A part is removed only when THIS landing stored and verified a file that holds it; a restart's
+ earlier sibling, a stalled part or an index-0 part is never "inside" a longer one by itself — only the coverage rule
+ removes it — and a live-edge part that ended over a minute after the landed part is kept.
+- **After a live-edge fallback, the start is tried again beside it.** From the first live-edge attempt, a from-start try
+ runs BESIDE the live-edge recorder (never touching it): every 15 min (jittered), one try at a time, at most 8 (about
+ 2 h; each failed try costs one extraction, as the failed attempt did). The tries stop when the live-edge recording
+ ends (a try still waiting is not made, one in flight is awaited), on a failure no try can help (`ended`, `private`,
+ `members`, `disk`, `argv`, from-the-start unsupported), on a second rate limit, on a Cancel. The row's
+ `startRecovery` says the tries and their state. A try's part is never PROVEN from the start (`provenStart`, the
+ landing rules above): it lands when it is the longest, but it never covers the stream nor removes the live-edge
+ part, which stays listed; the row needs a person to say the start is held.
+- **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). A resumed part keeps the proof of start its original run earned
+ (`provenStart`); a live-edge or recovery part never has one. The watchdog and a shutdown stop it with SIGTERM, which
+ leaves the state — but only when the part can be resumed at that moment (separate streams, each with its state);
+ every other recorder, a muxed ffmpeg download included, gets SIGINT, which finishes its file. A person's Cancel is
+ SIGINT. The recorder runs in a process group of its own, so a stop reaches yt-dlp's ffmpeg too, and the recorder
+ returns when yt-dlp exits (a process still holding its output 3 s later is killed with the group). A resume pins
+ 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 (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 (DESIGN-4, REVIEW-6).** A separate-streams from-start recorder runs
+ with `--keep-fragments`, `-k`, `--abort-on-unavailable-fragments` and `--retry-sleep fragment:exp=1:20`. Every
+ fragment `<f>-Frag<n>` is kept until the stream is confirmed done. Before a resume each stream file must equal its
+ kept fragments 1..N (the `.ytdl` index), none empty, the file ending with the last one's bytes; the only repair is a
+ tail that is byte for byte the start of the next kept fragment (a stop inside an append), truncated back and logged
+ with both lengths; and every kept fragment past the index is removed (a complete one would be asked for by Range past
+ its end: 416, and the resume would record nothing). After yt-dlp finished a part by itself while the stream went on
+ (a self-exit: merged, its state removed), the state is written again, per stream, at the count the kept fragments
+ prove and the merged copy is moved aside (one copy at a time) — the same files continue. Order when a recorder stops
+ while live: resume in place, else that reuse, else a FRESH part from the start (a new stem, `ytdlp-f<n>`, proven on
+ YouTube under 119 h, the log saying how much it fetches again), else the live edge plus recovery. A resume needs the
+ floor plus its stream files free; a fresh part the floor and twice the largest part. The stream files plus their
+ fragments are twice the stream on disk (about 6 GB for 6 h at 720p); short of disk (checked at each recorder's start
+ and every minute) the fragments are dropped — the recording goes on, the part can no longer be resumed in place, the
+ row says so (`fragmentsDropped`); never a silent prune. A fragment that cannot be fetched (yt-dlp's `ERROR: \r[download]
+ Got error: … Giving up after N retries`, read as one line) stops the recorder (SIGTERM; yt-dlp would record the
+ other stream on alone) and resumes it after 20 s, 60 s and 180 s; still stuck there, a fresh part; that one stuck at
+ the same fragment, ONE run that may skip it — the part and the landed file carry `skippedFragments`, it is never
+ proven, and the row stays loud after the landing. A resume that fails for the network is tried again on the same
+ waits, and empty live-edge recorders while the state cannot be read are not taken as the stream's end. Those lines are
+ never thinned out of the job log. When the stream ENDS while a from-start part is behind, that part is resumed once
+ to the end (an ended stream is still served from its start); a landing short of an ended stream's own duration
+ needs a person ("download the VOD now"). One recorder per stem: `<stem>.rec.lock` names the editor and the recorder;
+ stale only when neither is alive, or made before the machine's last boot. At a shutdown with a part waiting to be
+ resumed nothing lands. A boot restart still `starting` after 10 minutes never went on: the row says so.
+- **A recorder that ends by itself while the stream is live is never "the whole stream" (DESIGN-5).** yt-dlp can
+ merge and exit 0 mid-stream — "Cannot find refreshed url for format N … Giving up after 3 retries" (the platform
+ stopped serving the format, e.g. its DVR switched off): that part gets `failureClass: "url-refresh"` and a plain
+ sentence on the row. ANY exit with bytes (exit 0, a partial one included) is followed by a state read; live (or a
+ read that fails), the recording goes on, for as long as the platform says live (429 and the bot check still stop it,
+ loudly). The restart REUSES what is downloaded: yt-dlp skips the fragments its `.ytdl` state counts, so after a
+ self-exit (it removed that state) the editor writes it again at the count the kept fragments prove (each stream file
+ equal to its fragments 1..N) and moves the merged copy aside (left at its final name yt-dlp would say "already
+ downloaded" and record nothing) — the same files continue, no catch-up from fragment 0; a Record again does the same
+ with a part an earlier run left. Only when nothing can be proven does a fresh part from the start record, and the
+ log says how much stream it fetches again. A landing made while the last read says live (a Cancel, a shutdown, a
+ refusal) is `landedWhileLive` (when, why, how much of the stream by the clock is in no landed file), needs a person
+ until acknowledged, supersedes nothing, and every line says "so far"; nothing reusable (stream files, state,
+ fragments) is removed until the stream is confirmed done.
+- **A from-start part far behind gets a live-edge recorder beside it (DESIGN-5 point 5, the orchestrator's go —
+ `liveRecording.insuranceWhenBehind`, default on).** When a fresh part or a first attempt shows itself, by its first
+ `frag N/M`, more than 10 minutes behind the live edge (the stream's age × (1 − N/M)), the insurance starts beside it
+ whatever the keep mark (not when the request said `insurance: false`), so the tail is held while it catches up — a
+ stream can go private within minutes, and a download in progress does not survive it. It is not re-armed on every
+ self-exit or resume (the reuse makes those seconds); its starts are bounded 3 an hour (the hour waited out) and 24 a
+ run. The live-edge part is never proven: it goes only on an ended stream's duration, is joined only by the
+ proven-overlap join, and after a private switch both parts stay and the row is loud.
+- **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), the picture's and the sound's spans within max(2 s, 2 fragments) of each other, no step
+ between packets over 1.5× the median video step or 2× the audio, nor 0.1 s; decode times only forward), or scanned
+ alone; each stream file must also be byte for byte its kept fragments, and the editor's own merge fails on any line
+ ffmpeg writes. A raw source (a stream landed as it is, a muxed `.ts`) is copied, kept, and checked against. ffprobe runs at `-v error`: a raw WebM's "unknown-length element"
+ warning, one per fragment, is not an error. Until it is verified the row says `verification: pending`; verified,
+ the stream files, their fragments and every part meant for removal go; not verified, NOTHING is removed and the row
+ needs a person. Cost: about 115 k packets a second plus reading the files — for a 6 h 19 min stream of 683 k video
+ 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
+ row, verdict `shorter`: the transcription is asked, the job on the row). When that cannot be told — the transcript
+ does not read or parse, holds no cues, or the replaced file's length is not known — the verdict is `unknown`, nothing
+ is asked, and the row needs a person; so does a `shorter` whose ask was refused. The ask REPLACES the transcript
+ (`replace`: without it the job would find `transcript.json` and do nothing); the old one stays until the new one is
+ written over it. A transcript whose speech runs past
+ the replaced file's end is left as it is.
+- **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
+ recorder that exited with bytes, one metadata read asks whether the stream is still live (an exit is read twice, a
+ minute apart: a stream that has just ended may read live a moment). **A stream that reads live is never left
+ 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; 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 past 24 in a run at most one an hour: a bound reached on
+ a stream still live is WAITED OUT, not an end — the row says it is not recording until the hour frees a restart
+ (`restarts.waiting`, needing a person while it waits; `restarts.waited` counts them), then it goes on. When the
+ state cannot be read after an exit, the row says the stream may be live and is NOT recorded (`restarts.refused`) and
+ needs a person.
+ What the recorder said LAST (its output after its last progress line) is classified, also for a part that died
+ with bytes; the state is read before any conclusion: the disk is not restarted; a 429 or the bot check, with the
+ stream live, gets ONE restart after 15 min, a second is refused; "ended"/"private" text while the stream reads live
+ is restarted. The floor before every spawn — each restart, start-recovery try, the insurance's start, a join — is
+ max(20 GB, twice the largest part of this run so far); a spawn under it does not start, and the row says so
+ (`spaceHeld`) and needs a person. A stall with nothing written is an attempt that recorded nothing, on the
+ schedule above. Not for Kick (its VOD poll decides its end) or the browser path.
+- **An insurance recorder while the start catches up.** A from-start recording of a stream already live is behind
+ the live edge for a long time; a second recorder records the live edge beside it (`ytdlp-insure`), starting 60 s
+ after the from-start part's first bytes, and stops 5 min after the from-start recorder has caught up (every stream
+ it reports within 30 fragments of its total, read from yt-dlp's own `(frag N/M)` lines; none read, it runs to the
+ end). One that exits or stalls before the catch-up or the stream's end reads `died` (never "to the end") and is
+ started again; a from-start restart, behind the live edge again, re-arms one that had stopped after the catch-up; at
+ most 3 starts a run (`starts`); a rate limit gets one more start after 15 min, then it stops. `"insurance"`: `true` (that), `"whole"` (the whole stream), `false` (none); absent, it is ON exactly when the
+ stream is marked keep before or when the recording starts — `doNotClean` asked, the record's Do-not-clean marker,
+ or a pending keep (`keep-videos`) — and off otherwise. Its part is removed at the landing only when the landed file
+ holds the whole stream; otherwise it is kept and listed (the stream removed mid-catch-up: it holds the end). It
+ costs one extraction and a viewer's live-edge reads, about a tenth of the catch-up's rate, until it stops; `"whole"`
+ doubles the realtime reads for the stream, as Kick's two recorders do. Not for Kick, the browser path or an
+ upcoming stream.
+- **Parts joined when together they hold more.** When the landed file would not hold the stream and two or more parts
+ with a known place do (a from-start part that stopped short and a live-edge part; live-edge parts a restart left one
+ after another), they are joined `-c copy` (`controller/liveJoin.ts`). A live-edge part's place is found by its
+ sound (its first 20 s searched in the part before, around its clock place) and checked again near the join; the
+ next part is cut where the one before ends (the keyframe before the cut: `duplicatedSeconds` heard twice). A part
+ that starts after the one before ends is joined as it is, and the GAP is stated by the clock — the joined file's
+ timeline after it is not the stream's. The joined file lands only when proven: its length is its segments' within
+ max(1 s, 0.2 %), the sound 5–25 s either side of every join (and its head and tail) matches its parts, the two
+ parts' PICTURES match each other at the same stream times across the overlap (and the timestamps of the joined
+ file's video and audio run on at every join: on a static scene they alone decide; with neither, no join); a cut whose copy starts after the point asked (a hole) refuses
+ the join, and each overlap records where it was cut (`cutAt`, `cutFrom`). No join runs during a shutdown's
+ landing, and its scratch is removed however it ends. Its parts are removed only after it has landed. The row's `joins` and `data/<id>/live-joins.json` (each segment: its place in the
+ stream, in its file and in the joined file) say where the joins are. A gap needs a person. Unproven, parts whose
+ codecs or picture size differ (no re-encode is made), or a part with no known place: the longest lands and the rest
+ are kept, as before.
- **An editor shutdown is not a Cancel.** A run stopped by the editor going down (a restart, a rollout) is
`interrupted` (`stoppedBy: "shutdown"`), never `cancelled`, and needs a person — Record again if the stream is still
live. A person's Cancel is `cancelled`; it needs a person only when the stream was must-keep (`doNotClean` or a
`note`), and is quiet otherwise.
+- **An editor restart's interruption restarts by itself** (`liveRecording.autoRestartOnBoot`, default on). 30 s after
+ the editor starts (not on an idle boot or the test server), the newest run of each stream that the shutdown
+ interrupted, or that a crash left saying `recording` (now `interrupted`, `stoppedBy: "crash"`), asks for a
+ record-live run with its own url and options. That run's first step is record-live's one paced metadata read:
+ live, it records again (the earlier parts stay for the landing's rules) and the interrupted row says `restart:
+ restarted` — and needs a person until the NEW run's part is growing (a new run that fails, never starts or lands
+ short leaves it loud, and the listing says which); ended, it records nothing and lands what is in staging
+ (`landing`, then `landed` or `failed` with what the landing did), or with nothing left says `ended` (the end is not
+ recorded: needs a person); unreadable, the state is read again after 2 and 8 minutes (not after a rate limit,
+ members-only or the disk), and if it never reads it records nothing but STILL lands what is in staging — the only
+ copy — and the row says the state could not be read (or that the stream was made private or removed) and to Record
+ again if it is live; with nothing left it says `unknown`. The age that makes a row too old to restart (12 h) is
+ from its recorder's LAST WRITE (the newest part file), and a row skipped for it is marked `refused` and logged. A person's Cancel never restarts. A restart loop cannot
+ run: the row is marked before the job is asked (a run restarts once), at most 3 automatic restarts of a stream in
+ an hour (then `refused`), and a part file written after the boot, or one that changes between three looks 20 s
+ apart — a recorder of the last process may still be writing — refuses it too.
- **Is it recording, and is it growing? `pnpm ops get live-recordings [<slug>[/<id>]] [--all]`** — never "is there
a job for this video id" (a live-chat capture is one too). Each run from its own record: `status` (`recording`,
`interrupted` when no record-live job runs it, `landed`, `failed`, `cancelled`), the job, `bytes` and
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -262,19 +262,23 @@ Default:
## `liveRecording`
-How a running live recording is judged (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled. See common/controller/liveRecordings.ts.
+How a running live recording is judged and kept alive (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled (and restart its recorder), and whether an editor restart's interruption restarts by itself. See common/controller/liveRecordings.ts and common/controller/liveRecordingBoot.ts.
#### `liveRecording`
| Key | Default | Description |
|---|---|---|
-| `stallMinutes` | `10` | Minutes a running live recording's files may go without growing before `pnpm ops get live-recordings` (and /review, the banners) mark it `stalled`. Clamped 1–240; default 10. |
+| `stallMinutes` | `10` | Minutes a running live recording's files may go without growing before `pnpm ops get live-recordings` (and /review, the banners) mark it `stalled` — and before record-live's own watchdog stops that recorder and, while the stream is still live, starts a new part from the live edge (at most 6 restarts an hour, 24 a run). Clamped 1–240; default 10. |
+| `autoRestartOnBoot` | `true` | After an editor restart, a live recording the shutdown (or a crash) interrupted is restarted by itself: the new run reads the stream's state first (one paced metadata request) and records only if it is still live; ended, it lands what is in staging; unreadable, it starts nothing. At most once per interrupted run and 3 times an hour per stream; never after a person's Cancel (common/controller/liveRecordingBoot.ts). Default true; false leaves every interruption to /review's Record again. |
+| `insuranceWhenBehind` | `true` | When a from-start part (a fresh part after a stop, or a first attempt) shows itself, by its first `frag N/M`, more than 10 minutes behind the live edge, a live-edge recorder starts beside it — the insurance — whatever the keep mark (unless the request said `insurance: false`), so the stream's tail is held while the catch-up runs (a stream can go private within minutes, and a download in progress does not survive it). Not re-armed on every self-exit: the reuse of kept fragments makes those catch-ups seconds. Its starts are bounded 3 an hour, 24 a run. Default true (the orchestrator's go, DESIGN-5 point 5: the whole stream must be captured); false leaves the insurance to the keep mark and the request. |
Default:
```json
{
- "stallMinutes": 10
+ "stallMinutes": 10,
+ "autoRestartOnBoot": true,
+ "insuranceWhenBehind": true
}
```
diff --git a/common/controller/liveJoin.test.ts b/common/controller/liveJoin.test.ts
@@ -0,0 +1,66 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFile } from "node:child_process";
+import { mkdtemp, readdir, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { promisify } from "node:util";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveJoin.test.ts
+//
+// The join of live-recording parts (controller/liveJoin.ts) with the REAL
+// tools — ffmpeg's cut and concat, ffprobe, the decode the recording clock
+// uses — over two small files made here from one seeded noise "stream": part
+// A is its seconds 0–90, part B its seconds 60–150 (a 30 s overlap), whose
+// recorder started 2 s after its sound (the clock says 62). No network.
+
+const run = promisify(execFile);
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-join-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+const { joinLiveParts, ffmpegJoinDeps } = await import("./liveJoin");
+
+const have = await run("ffmpeg", ["-version"]).then(() => true, () => false);
+
+async function part(name: string, from: number, seconds: number): Promise<string> {
+ const out = path.join(ROOT, name);
+ await run("ffmpeg", [
+ "-v", "error", "-y",
+ "-f", "lavfi", "-i", `anoisesrc=d=160:c=pink:r=16000:seed=42:a=0.5`,
+ "-f", "lavfi", "-i", "testsrc=s=64x48:r=5:d=160",
+ "-ss", String(from), "-t", String(seconds),
+ "-map", "1:v", "-map", "0:a",
+ "-c:v", "libx264", "-preset", "ultrafast", "-g", "10",
+ "-c:a", "aac", "-b:a", "32k",
+ out,
+ ]);
+ return out;
+}
+
+test("two overlapping parts are joined by ffmpeg at the overlap their sound shares, and the join is proven", { skip: !have && "no ffmpeg" }, async () => {
+ const a = await part(".exmpl.live-s.ytdlp.mp4", 0, 90);
+ const b = await part(".exmpl.live-s.ytdlp-edge.mp4", 60, 90);
+ const start = Date.parse("2026-11-21T00:00:00.000Z");
+ const said: string[] = [];
+ const r = await joinLiveParts({
+ parts: [
+ { stem: "a", file: a, seconds: 90, fromStart: true, startedAt: new Date(start).toISOString() },
+ { stem: "b", file: b, seconds: 90, fromStart: false, startedAt: new Date(start + 62_000).toISOString() },
+ ],
+ streamStartedAt: new Date(start).toISOString(),
+ outStem: path.join(ROOT, ".exmpl.live-s.joined"),
+ deps: ffmpegJoinDeps({ ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" }),
+ say: (s) => void said.push(s),
+ });
+ assert.ok(r.ok, `joined: ${"why" in r ? r.why : ""} ${said.join(" | ")}`);
+ if (!r.ok) return;
+ assert.equal(r.joins.length, 1);
+ assert.equal(r.joins[0]!.kind, "overlap");
+ assert.ok(Math.abs(r.joins[0]!.seconds - 30) < 0.1, `overlap ${r.joins[0]!.seconds}`);
+ assert.ok(Math.abs(r.segments[1]!.streamFrom - 60) < 0.1, `B found at ${r.segments[1]!.streamFrom}`);
+ assert.ok(Math.abs(r.seconds - (90 + 90 - r.segments[1]!.fileFrom)) < 1, `joined ${r.seconds} s`);
+ assert.ok(r.seconds >= 149 && r.seconds <= 153, `the union: ${r.seconds} s`);
+ const names = await readdir(ROOT);
+ assert.ok(names.includes(path.basename(r.file)), "the joined file");
+ assert.equal(names.filter((n) => /\.temp\./.test(n)).length, 0, "no scratch left");
+});
diff --git a/common/controller/liveJoin.ts b/common/controller/liveJoin.ts
@@ -0,0 +1,540 @@
+// PARTS OF ONE LIVE RECORDING JOINED INTO ONE FILE — record-live's landing
+// (controller/recordLive.ts), when no single part holds the stream but two or
+// more together hold more than the longest alone: a from-start part that
+// stopped short and a live-edge part (a fallback, the insurance recorder), or
+// live-edge parts a restart left one after the other.
+//
+// WHERE EACH PART SITS IN THE STREAM. A from-start part begins at the
+// stream's second 0. A live-edge part begins about (its startedAt − the
+// stream's start) in, by the clock — and the live edge lags the clock, so its
+// real place is found BY CONTENT: its first PROBE_SECONDS of sound (8 kHz,
+// lib/recordingClock.mjs locate) searched in the part before it, from
+// SEARCH_BEFORE_S before its clock place to SEARCH_AFTER_S after; a match
+// must score ≥ MIN_SCORE and stand MIN_PEAK_RATIO above any other peak, and a
+// second anchor near where the join will be must agree within LAG_TOLERANCE_S.
+//
+// overlap the next part is cut where the one before ends (`-c copy`, which
+// starts at the keyframe at or before the cut: those seconds are
+// heard twice, `duplicatedSeconds`); the joined file's timeline is
+// the stream's from the first part's start
+// gap the next part begins after the one before ends (or overlaps it
+// too little to align): joined as it is, the gap stated by the
+// clock (`basis: "clock"`, about N s). The joined file's timeline
+// is NOT the stream's after it — live-joins.json maps each segment.
+//
+// NOTHING IS TRUSTED UNTIL PROVEN. The joined file is written under a scratch
+// name (no reader takes it for a part) and kept only when its duration is the
+// segments' sum within max(1 s, 0.2 %) and, at every join, the sound 5–25 s
+// before matches the segment before and 5–25 s after matches the segment
+// after (and its head matches the first part). Anything else — a failed
+// check, codecs or sizes that differ (a stream copy cannot join them, and a
+// re-encode of hours is not done here), a part with no known place — and the
+// joined file is removed: the landing lands the longest and keeps the rest,
+// as before. The parts themselves are never touched here; the landing
+// removes a joined part only after the joined file has landed.
+
+import path from "node:path";
+import { rename, rm, writeFile } from "node:fs/promises";
+import { execa } from "execa";
+import { locate } from "../lib/recordingClock.mjs";
+import { decodeExcerpt } from "../lib/recordingClock-server";
+import type { LiveJoin, LiveJoinSegment } from "../lib/liveCapture";
+import "../lib/childKillGuard";
+
+export const JOIN_SAMPLE_RATE = 8000;
+export const JOIN_PROBE_SECONDS = 20;
+export const JOIN_SEARCH_BEFORE_S = 180;
+export const JOIN_SEARCH_AFTER_S = 60;
+export const JOIN_MIN_SCORE = 0.35;
+export const JOIN_MIN_PEAK_RATIO = 1.15;
+export const JOIN_LAG_TOLERANCE_S = 0.25;
+// An overlap shorter than this (by the clock) is not aligned: a gap join.
+export const JOIN_MIN_OVERLAP_S = 25;
+// A part that adds less than this past the union's end is not joined.
+export const JOIN_MIN_GAIN_S = 30;
+export const JOIN_MAX_PARTS = 4;
+// A part shorter than this is never joined (the checks need its sound).
+export const JOIN_MIN_PART_S = 60;
+// A cut whose stream copy starts this much after the point asked leaves a hole;
+// one that starts more than JOIN_MAX_EARLY_CUT_S before it is not a keyframe
+// snap (REVIEW-1 1.5 of live-guard-2).
+export const JOIN_CUT_LATE_TOLERANCE_S = 0.25;
+export const JOIN_MAX_EARLY_CUT_S = 30;
+// Two frames (32x18 grey) are the same picture when they differ by at most
+// this on average (0-255): a re-mux decodes the same frame, a frame or two off
+// still matches, another moment does not.
+export const JOIN_FRAME_MAX_DIFF = 12;
+// Frames compared across an overlap, and how much more the same frames one
+// second apart must differ for the picture to prove the alignment.
+export const JOIN_PICTURE_SAMPLES = 4;
+export const JOIN_PICTURE_MARGIN = 4;
+
+export type JoinStreams = {
+ seconds: number | null;
+ videoCodec: string | null;
+ audioCodec: string | null;
+ width: number | null;
+ height: number | null;
+ sampleRate: number | null;
+ channels: number | null;
+};
+
+export type JoinDeps = {
+ // Mono float samples at `rate` of [from, from + seconds) of `file`.
+ decode: (file: string, from: number, seconds: number, rate: number) => Promise<Float32Array>;
+ // `file` from `from` seconds to its end, stream-copied into `out`; returns
+ // where the copy really starts (the keyframe at or before `from`).
+ cut: (file: string, from: number, out: string) => Promise<number>;
+ // The files one after the other, stream-copied into `out`.
+ concat: (files: string[], out: string) => Promise<void>;
+ probe: (file: string) => Promise<JoinStreams | null>;
+ // A small grey frame of the picture at `at` seconds (null: no picture
+ // decoded there).
+ frame: (file: string, at: number) => Promise<Uint8Array | null>;
+ // The packets' timestamps (seconds) of [from, from + seconds) of `file`,
+ // video and audio (null: cannot be read).
+ timestamps: (file: string, from: number, seconds: number) => Promise<{ video: number[]; audio: number[] } | null>;
+};
+
+export function frameDiff(a: Uint8Array, b: Uint8Array): number {
+ if (a.length !== b.length || a.length === 0) return Infinity;
+ let d = 0;
+ for (let i = 0; i < a.length; i++) d += Math.abs(a[i]! - b[i]!);
+ return d / a.length;
+}
+
+export type JoinPart = {
+ stem: string;
+ file: string;
+ seconds: number;
+ fromStart: boolean;
+ // When its recorder started (ISO).
+ startedAt: string | null;
+};
+
+export type JoinResult =
+ | { ok: true; file: string; seconds: number; joins: LiveJoin[]; segments: LiveJoinSegment[]; stems: string[] }
+ | { ok: false; why: string };
+
+type Seg = { part: JoinPart; file: string; fileFrom: number; streamFrom: number; streamFromBasis: "start" | "content" | "clock" };
+
+function matchAt(
+ probe: Float32Array,
+ search: Float32Array,
+ searchStart: number,
+ expected: number | null,
+): { at: number; score: number; ok: boolean; why?: string } {
+ const hit = locate(probe, search, { guard: Math.round(0.25 * JOIN_SAMPLE_RATE) });
+ if (!hit) return { at: NaN, score: 0, ok: false, why: "silent" };
+ const at = searchStart + hit.lag / JOIN_SAMPLE_RATE;
+ const ratio = hit.second > 1e-9 ? hit.score / hit.second : 99;
+ if (hit.score < JOIN_MIN_SCORE) return { at, score: hit.score, ok: false, why: `weak (${hit.score.toFixed(2)})` };
+ if (ratio < JOIN_MIN_PEAK_RATIO) return { at, score: hit.score, ok: false, why: `ambiguous (${ratio.toFixed(2)})` };
+ if (expected !== null && Math.abs(at - expected) > JOIN_LAG_TOLERANCE_S) {
+ return { at, score: hit.score, ok: false, why: `off by ${(at - expected).toFixed(2)} s` };
+ }
+ return { at, score: hit.score, ok: true };
+}
+
+const r3 = (x: number) => Math.round(x * 1000) / 1000;
+
+export type JoinOpts = {
+ parts: JoinPart[];
+ streamStartedAt: string | null;
+ // `<stem>` for the joined file (its scratch name is `<stem>.temp.<ext>`).
+ outStem: string;
+ deps: JoinDeps;
+ say: (s: string) => void;
+};
+
+// Every scratch file the join writes is removed however it ends — a refusal,
+// a proof that fails, or a tool that throws (REVIEW-1 1.6 of live-guard-2).
+// Only the proven joined file, renamed out of its scratch name, stays.
+export async function joinLiveParts(o: JoinOpts): Promise<JoinResult> {
+ const scratch: string[] = [];
+ try {
+ return await joinInner(o, scratch);
+ } finally {
+ for (const f of scratch) await rm(f, { force: true }).catch(() => {});
+ }
+}
+
+async function joinInner(o: JoinOpts, scratch: string[]): Promise<JoinResult> {
+ const { deps, say } = o;
+ const startMs = o.streamStartedAt ? Date.parse(o.streamStartedAt) : NaN;
+ const usable = o.parts.filter((p) => p.seconds >= JOIN_MIN_PART_S);
+ const fromStart = usable.filter((p) => p.fromStart).sort((a, b) => b.seconds - a.seconds);
+ const base = fromStart[0] ?? [...usable].filter((p) => p.startedAt).sort((a, b) => Date.parse(a.startedAt!) - Date.parse(b.startedAt!))[0];
+ if (!base) return { ok: false, why: "no part long enough to join" };
+ // A part's place by the clock, in the stream (from-start base) or after
+ // the base's start (a live-edge base).
+ const clockPlace = (p: JoinPart): number | null => {
+ if (!p.startedAt) return null;
+ const t = Date.parse(p.startedAt);
+ if (base.fromStart) return Number.isFinite(startMs) ? (t - startMs) / 1000 : null;
+ return (t - Date.parse(base.startedAt!)) / 1000;
+ };
+ const others = usable
+ .filter((p) => p !== base && !p.fromStart)
+ .map((p) => ({ p, place: clockPlace(p) }))
+ .filter((x): x is { p: JoinPart; place: number } => x.place !== null)
+ .sort((a, b) => a.place - b.place);
+ if (!others.length) return { ok: false, why: "no other part with a known place in the stream" };
+
+ const probes = new Map<string, JoinStreams>();
+ for (const p of [base, ...others.map((x) => x.p)]) {
+ const s = await deps.probe(p.file);
+ if (!s) return { ok: false, why: `${path.basename(p.file)} cannot be read` };
+ probes.set(p.stem, s);
+ }
+ const b0 = probes.get(base.stem)!;
+ const same = (s: JoinStreams) =>
+ s.videoCodec === b0.videoCodec &&
+ s.audioCodec === b0.audioCodec &&
+ s.width === b0.width &&
+ s.height === b0.height &&
+ s.sampleRate === b0.sampleRate &&
+ s.channels === b0.channels;
+
+ const segs: Seg[] = [{ part: base, file: base.file, fileFrom: 0, streamFrom: 0, streamFromBasis: base.fromStart ? "start" : "clock" }];
+ const joins: LiveJoin[] = [];
+ const cleanup = async () => {
+ for (const f of scratch) await rm(f, { force: true });
+ };
+ let unionEnd = base.seconds;
+ const rate = JOIN_SAMPLE_RATE;
+ let stopWhy: string | null = null;
+ // Per join: did the two parts' pictures prove it (REVIEW-2 2.1)?
+ const provenByPicture: boolean[] = [];
+ for (const { p, place } of others) {
+ if (segs.length >= JOIN_MAX_PARTS) break;
+ if (place + p.seconds < unionEnd + JOIN_MIN_GAIN_S) continue;
+ if (!same(probes.get(p.stem)!)) {
+ say(`${path.basename(p.file)} is not joined: its codecs or picture size differ from ${path.basename(base.file)} (a stream copy cannot join them).`);
+ continue;
+ }
+ const last = segs[segs.length - 1]!;
+ // Stream second → seconds into the last segment's file.
+ const inLast = (t: number) => t - last.streamFrom + last.fileFrom;
+ const lastFileEnd = inLast(unionEnd);
+ if (place < unionEnd - JOIN_MIN_OVERLAP_S) {
+ // OVERLAP: where does this part's start sit in the last one?
+ const from = Math.max(last.fileFrom, inLast(place) - JOIN_SEARCH_BEFORE_S);
+ const to = Math.min(lastFileEnd, inLast(place) + JOIN_SEARCH_AFTER_S + JOIN_PROBE_SECONDS);
+ if (to - from < JOIN_PROBE_SECONDS * 1.5) {
+ stopWhy = `${path.basename(p.file)}: too little of the part before it to search; not joined.`;
+ say(stopWhy);
+ break;
+ }
+ const probeA = await deps.decode(p.file, 0, JOIN_PROBE_SECONDS, rate);
+ const search = await deps.decode(last.file, from, to - from, rate);
+ const m1 = matchAt(probeA, search, from, null);
+ if (!m1.ok) {
+ stopWhy = `${path.basename(p.file)}: its start is not found in ${path.basename(last.file)} (${m1.why}); not joined — the longest lands, the rest are kept.`;
+ say(stopWhy);
+ break;
+ }
+ // m1.at: seconds into the last file where this part's second 0 is.
+ const streamAt = m1.at - last.fileFrom + last.streamFrom;
+ const cutAt = unionEnd - streamAt; // seconds into this part
+ // The second anchor, just before where the join will be.
+ const a2 = Math.max(0, cutAt - JOIN_PROBE_SECONDS - 5);
+ const probeB = await deps.decode(p.file, a2, JOIN_PROBE_SECONDS, rate);
+ const expect2 = m1.at + a2;
+ const from2 = Math.max(last.fileFrom, expect2 - 3);
+ const search2 = await deps.decode(last.file, from2, Math.min(lastFileEnd, expect2 + JOIN_PROBE_SECONDS + 3) - from2, rate);
+ const m2 = matchAt(probeB, search2, from2, expect2);
+ if (!m2.ok) {
+ stopWhy = `${path.basename(p.file)}: the second check near the join does not agree (${m2.why}); not joined — the longest lands, the rest are kept.`;
+ say(stopWhy);
+ break;
+ }
+ // THE PICTURE ACROSS THE OVERLAP (REVIEW-2 2.1): the two SOURCE parts
+ // compared with each other at matching stream times, spread over the
+ // overlap; and the same frames one second apart, which must differ
+ // for the picture to prove anything (a static scene cannot).
+ let pictureProves = false;
+ if (b0.videoCodec) {
+ const lo = streamAt + 2;
+ const hi = unionEnd - 2;
+ const match: number[] = [];
+ const off: number[] = [];
+ for (let k = 0; k < JOIN_PICTURE_SAMPLES && hi > lo; k++) {
+ const t = lo + ((hi - lo) * (k + 0.5)) / JOIN_PICTURE_SAMPLES;
+ const [x, y, z] = await Promise.all([deps.frame(last.file, inLast(t)), deps.frame(p.file, t - streamAt), deps.frame(p.file, t - streamAt + 1)]);
+ if (!x || !y || !z) continue;
+ match.push(frameDiff(x, y));
+ off.push(frameDiff(x, z));
+ }
+ if (match.some((d) => d > JOIN_FRAME_MAX_DIFF)) {
+ stopWhy = `${path.basename(p.file)}: its picture is not ${path.basename(last.file)}'s at the same stream times across the overlap (difference up to ${Math.max(...match).toFixed(1)}); not joined.`;
+ say(stopWhy);
+ break;
+ }
+ const mean = (v: number[]) => v.reduce((n, x) => n + x, 0) / (v.length || 1);
+ pictureProves = match.length >= 2 && mean(off) > 2 * mean(match) + JOIN_PICTURE_MARGIN;
+ }
+ provenByPicture.push(pictureProves);
+ const segFile = `${o.outStem}.seg${segs.length}.temp${path.extname(p.file) || ".mkv"}`;
+ scratch.push(segFile);
+ const realFrom = await deps.cut(p.file, cutAt, segFile);
+ if (realFrom > cutAt + JOIN_CUT_LATE_TOLERANCE_S) {
+ stopWhy = `${path.basename(p.file)}: its stream copy starts ${(realFrom - cutAt).toFixed(2)} s after the cut point — a hole of seconds in neither part; not joined.`;
+ say(stopWhy);
+ break;
+ }
+ if (cutAt - realFrom > JOIN_MAX_EARLY_CUT_S) {
+ stopWhy = `${path.basename(p.file)}: its stream copy starts ${(cutAt - realFrom).toFixed(2)} s before the cut point (not a keyframe's snap); not joined.`;
+ say(stopWhy);
+ break;
+ }
+ // The seconds heard twice: where the copy really starts, against where
+ // it was asked to (both recorded).
+ const dup = cutAt - realFrom;
+ joins.push({
+ at: 0, // set below, once the segments' lengths are known
+ kind: "overlap",
+ seconds: r3(unionEnd - streamAt),
+ duplicatedSeconds: r3(dup),
+ cutAt: r3(cutAt),
+ cutFrom: r3(realFrom),
+ basis: "content",
+ score: r3(Math.min(m1.score, m2.score)),
+ parts: [last.part.stem, p.stem],
+ });
+ segs.push({ part: p, file: segFile, fileFrom: realFrom, streamFrom: streamAt, streamFromBasis: "content" });
+ unionEnd = streamAt + p.seconds;
+ } else {
+ // GAP (or too little overlap to align): joined as it is, stated.
+ const gap = Math.max(0, place - unionEnd);
+ joins.push({ at: 0, kind: "gap", seconds: r3(gap), basis: "clock", parts: [last.part.stem, p.stem] });
+ provenByPicture.push(false);
+ segs.push({ part: p, file: p.file, fileFrom: 0, streamFrom: Math.max(place, unionEnd), streamFromBasis: "clock" });
+ unionEnd = Math.max(place, unionEnd) + p.seconds;
+ }
+ }
+ if (segs.length < 2) {
+ await cleanup();
+ return { ok: false, why: stopWhy ?? "nothing could be joined" };
+ }
+
+ // Each segment's length in the joined file, and where each join falls.
+ const lengths: number[] = [];
+ for (let i = 0; i < segs.length; i++) {
+ const s = segs[i]!;
+ const total = i === 0 ? s.part.seconds : (await deps.probe(s.file))?.seconds ?? null;
+ if (total === null) {
+ await cleanup();
+ return { ok: false, why: `the cut of ${path.basename(s.part.file)} cannot be read` };
+ }
+ lengths.push(i === 0 ? total : total);
+ }
+ const ext = segs.every((s) => /\.ts$/i.test(s.part.file)) ? ".ts" : ".mkv";
+ const temp = `${o.outStem}.temp${ext}`;
+ const final = `${o.outStem}${ext}`;
+ scratch.push(temp);
+ try {
+ await deps.concat(
+ segs.map((s) => s.file),
+ temp,
+ );
+ } catch (err) {
+ await cleanup();
+ return { ok: false, why: `the join failed: ${(err as Error).message.split("\n")[0]}` };
+ }
+
+ // PROVEN, or nothing.
+ const joined = await deps.probe(temp);
+ const sum = lengths.reduce((n, l) => n + l, 0);
+ const tol = Math.max(1, sum * 0.002);
+ if (!joined?.seconds || Math.abs(joined.seconds - sum) > tol) {
+ await cleanup();
+ return { ok: false, why: `the joined file is ${joined?.seconds ?? "?"} s, its parts ${r3(sum)} s: not proven` };
+ }
+ const check = async (segFile: string, segAt: number, joinedAt: number, what: string): Promise<string | null> => {
+ const probe = await deps.decode(segFile, segAt, JOIN_PROBE_SECONDS, rate);
+ const from = Math.max(0, joinedAt - 3);
+ const search = await deps.decode(temp, from, JOIN_PROBE_SECONDS + 6, rate);
+ const m = matchAt(probe, search, from, joinedAt);
+ return m.ok ? null : `${what}: ${m.why}`;
+ };
+ const fails: string[] = [];
+ const head = await check(segs[0]!.file, 5, 5, "the head");
+ if (head) fails.push(head);
+ let at = 0;
+ for (let i = 0; i < segs.length; i++) {
+ const s = segs[i]!;
+ const len = lengths[i]!;
+ // The segment file's own clock: the base whole, a cut from 0, a gap part whole.
+ if (i > 0) {
+ joins[i - 1]!.at = r3(at);
+ const before = segs[i - 1]!;
+ const beforeLen = lengths[i - 1]!;
+ const b = await check(before.file, beforeLen - 25, at - 25, `before join ${i}`);
+ const a = await check(s.file, 5, at + 5, `after join ${i}`);
+ if (b) fails.push(b);
+ if (a) fails.push(a);
+ }
+ at += len;
+ }
+ // The tail: the joined file ends with its last segment.
+ {
+ const lastSeg = segs[segs.length - 1]!;
+ const lastLen = lengths[lengths.length - 1]!;
+ const tail = await check(lastSeg.file, lastLen - 25, sum - 25, "the tail");
+ if (tail) fails.push(tail);
+ }
+ // THE PICTURE (REVIEW-1 1.5): on both sides of every join, at the head and
+ // at the tail, the joined file's frame is the segment's.
+ if (b0.videoCodec) {
+ const pic = async (segFile: string, segAt: number, joinedAt: number, what: string) => {
+ const [x, y] = await Promise.all([deps.frame(segFile, segAt), deps.frame(temp, joinedAt)]);
+ if (!x || !y) return `${what}: no picture decoded`;
+ const d = frameDiff(x, y);
+ return d <= JOIN_FRAME_MAX_DIFF ? null : `${what}: the picture differs (${d.toFixed(1)})`;
+ };
+ const checks: Promise<string | null>[] = [pic(segs[0]!.file, 5, 5, "the head's picture")];
+ let pAt = 0;
+ for (let i = 0; i < segs.length; i++) {
+ if (i > 0) {
+ checks.push(pic(segs[i - 1]!.file, lengths[i - 1]! - 10, pAt - 10, `the picture before join ${i}`));
+ checks.push(pic(segs[i]!.file, 10, pAt + 10, `the picture after join ${i}`));
+ }
+ pAt += lengths[i]!;
+ }
+ checks.push(pic(segs[segs.length - 1]!.file, lengths[lengths.length - 1]! - 10, sum - 10, "the tail's picture"));
+ for (const r of await Promise.all(checks)) if (r) fails.push(r);
+ }
+ // THE TIMESTAMPS ACROSS EACH JOIN (REVIEW-2 2.1): in the joined file,
+ // video (and audio) packets 5 s either side of every join go on with no
+ // jump larger than a frame (a packet) interval. A join the pictures did
+ // not prove needs this; when it cannot be read either, no join.
+ {
+ let jAt = 0;
+ for (let i = 1; i < segs.length; i++) {
+ jAt += lengths[i - 1]!;
+ const ts = await deps.timestamps(temp, Math.max(0, jAt - 5), 10).catch(() => null);
+ const jumps = (v: number[]) => {
+ const d = [...v].sort((a, b) => a - b).slice(1).map((x, k) => x - [...v].sort((a, b) => a - b)[k]!);
+ if (d.length < 3) return null;
+ const med = [...d].sort((a, b) => a - b)[Math.floor(d.length / 2)]!;
+ return Math.max(...d) > med * 1.5 + 0.001 ? Math.max(...d) : 0;
+ };
+ const v = ts && (b0.videoCodec ? jumps(ts.video) : 0);
+ const a = ts && jumps(ts.audio);
+ const established = ts !== null && v !== null && a !== null;
+ if (established && ((v ?? 0) > 0 || (a ?? 0) > 0)) {
+ fails.push(`join ${i}: the timestamps jump by ${Math.max(v ?? 0, a ?? 0).toFixed(3)} s`);
+ } else if (!established && !provenByPicture[i - 1]) {
+ fails.push(`join ${i}: neither the picture (a static scene, or none) nor the timestamps can prove it`);
+ }
+ }
+ }
+ if (fails.length) {
+ await cleanup();
+ return { ok: false, why: `the joined file does not hold its parts where it should (${fails.join("; ")}): not proven` };
+ }
+ await rename(temp, final);
+ for (const f of scratch) if (f !== temp) await rm(f, { force: true });
+ let joinedFrom = 0;
+ const segments: LiveJoinSegment[] = segs.map((s, i) => {
+ const len = lengths[i]!;
+ const seg: LiveJoinSegment = {
+ stem: s.part.stem,
+ streamFrom: r3(s.streamFrom + 0),
+ streamFromBasis: s.streamFromBasis,
+ fileFrom: r3(s.fileFrom),
+ fileTo: r3(s.fileFrom + len),
+ joinedFrom: r3(joinedFrom),
+ joinedTo: r3(joinedFrom + len),
+ };
+ joinedFrom += len;
+ return seg;
+ });
+ return { ok: true, file: final, seconds: joined.seconds, joins, segments, stems: segs.map((s) => s.part.stem) };
+}
+
+// --- the real tools: ffmpeg/ffprobe -----------------------------------------------
+
+// `run`: how ffmpeg's cut and concat are run (record-live: the heavy slot,
+// controller/recordLive.ts runFfmpegHeavy); default, ffmpeg directly.
+export function ffmpegJoinDeps(
+ bins: { ffmpegBin: string; ffprobeBin: string; run?: (args: string[]) => Promise<void> },
+ signal?: AbortSignal,
+): JoinDeps {
+ const opt = signal ? { cancelSignal: signal } : {};
+ const ffmpeg = bins.run ?? (async (args: string[]) => void (await execa(bins.ffmpegBin, args, opt)));
+ return {
+ decode: (file, from, seconds, rate) =>
+ decodeExcerpt({ ffmpegBin: bins.ffmpegBin, file, from, seconds, sampleRate: rate, ...(signal ? { signal } : {}) }),
+ cut: async (file, from, out) => {
+ await ffmpeg(["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-ss", from.toFixed(3), "-i", file, "-map", "0", "-c", "copy", "-avoid_negative_ts", "make_zero", out]);
+ // Where the copy starts: its length against the whole's.
+ const whole = await probeJoinStreams(bins.ffprobeBin, file);
+ const part = await probeJoinStreams(bins.ffprobeBin, out);
+ if (!whole?.seconds || !part?.seconds) throw new Error(`the cut of ${path.basename(file)} cannot be read`);
+ return Math.max(0, whole.seconds - part.seconds);
+ },
+ concat: async (files, out) => {
+ const list = `${out}.list.txt`;
+ await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n");
+ try {
+ const mkv = /\.mkv$/i.test(out);
+ await ffmpeg(["-nostdin", "-hide_banner", "-loglevel", "error", "-y", "-f", "concat", "-safe", "0", "-i", list, "-map", "0", "-c", "copy", ...(mkv ? ["-f", "matroska"] : ["-f", "mpegts"]), out]);
+ } finally {
+ await rm(list, { force: true });
+ }
+ },
+ probe: (file) => probeJoinStreams(bins.ffprobeBin, file),
+ timestamps: async (file, from, seconds) => {
+ const read = async (sel: string) => {
+ const r = await execa(
+ bins.ffprobeBin,
+ ["-v", "error", "-select_streams", sel, "-read_intervals", `${Math.max(0, from).toFixed(3)}%+${seconds.toFixed(3)}`, "-show_entries", "packet=pts_time", "-of", "csv=p=0", file],
+ { reject: false, timeout: 60_000, ...opt },
+ );
+ if (r.exitCode !== 0) return null;
+ return String(r.stdout)
+ .split("\n")
+ .map((l) => Number(l.trim().replace(/,$/, "")))
+ .filter((x) => Number.isFinite(x) && x >= from && x < from + seconds);
+ };
+ const [video, audio] = await Promise.all([read("v:0"), read("a:0")]);
+ return video && audio ? { video, audio } : null;
+ },
+ frame: async (file, at) => {
+ const r = await execa(
+ bins.ffmpegBin,
+ ["-v", "error", "-nostdin", "-ss", Math.max(0, at).toFixed(3), "-i", file, "-frames:v", "1", "-vf", "scale=32:18,format=gray", "-f", "rawvideo", "pipe:1"],
+ { encoding: "buffer", reject: false, timeout: 60_000, ...opt },
+ );
+ const buf = Buffer.from((r.stdout ?? new Uint8Array()) as Uint8Array);
+ return r.exitCode === 0 && buf.length === 32 * 18 ? new Uint8Array(buf) : null;
+ },
+ };
+}
+
+export async function probeJoinStreams(ffprobeBin: string, file: string): Promise<JoinStreams | null> {
+ const r = await execa(ffprobeBin, ["-v", "error", "-show_format", "-show_streams", "-of", "json", file], { reject: false });
+ if (r.exitCode !== 0) return null;
+ try {
+ const j = JSON.parse(String(r.stdout)) as {
+ format?: { duration?: string };
+ streams?: { codec_type?: string; codec_name?: string; width?: number; height?: number; sample_rate?: string; channels?: number }[];
+ };
+ const v = j.streams?.find((s) => s.codec_type === "video");
+ const a = j.streams?.find((s) => s.codec_type === "audio");
+ const d = Number(j.format?.duration);
+ return {
+ seconds: Number.isFinite(d) ? d : null,
+ videoCodec: v?.codec_name ?? null,
+ audioCodec: a?.codec_name ?? null,
+ width: v?.width ?? null,
+ height: v?.height ?? null,
+ sampleRate: a?.sample_rate ? Number(a.sample_rate) : null,
+ channels: a?.channels ?? null,
+ };
+ } catch {
+ return null;
+ }
+}
diff --git a/common/controller/liveRecordingBoot.test.ts b/common/controller/liveRecordingBoot.test.ts
@@ -0,0 +1,231 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { appendFile, mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/liveRecordingBoot.test.ts
+//
+// The boot pass that restarts live recordings an editor restart interrupted
+// (controller/liveRecordingBoot.ts), over a temp corpus: the rows written
+// through lib/liveRecordings-server.ts, the job start a stub that records
+// what it was asked. No request is made by the pass.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "live-boot-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+
+const { getPaths } = await import("../lib/paths");
+const { restartInterruptedLiveRecordings, LIVE_BOOT_MAX_RESTARTS_PER_HOUR } = await import("./liveRecordingBoot");
+const { upsertLiveRecordingRow, loadLiveRecordingRows, rowNeedsAttention } = await import("../lib/liveRecordings-server");
+const { liveRecordingSidecar } = await import("../lib/mediaImport-server");
+
+const paths = getPaths();
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const SLUG = "synth-boot";
+await mkdir(path.join(CORPUS, "channels", SLUG, "data"), { recursive: true });
+await writeFile(path.join(CORPUS, "channels", SLUG, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: "Synth" }));
+const store = path.join(paths.savedVideosDir, SLUG);
+await mkdir(store, { recursive: true });
+
+const NOW = new Date("2026-11-21T12:00:00.000Z");
+const BOOTED = NOW.getTime() - 30_000;
+const ago = (min: number) => new Date(NOW.getTime() - min * 60_000).toISOString();
+
+type RowIn = Parameters<typeof upsertLiveRecordingRow>[2];
+const row = (id: string, startedAt: string, extra: Partial<RowIn> = {}): RowIn => ({
+ id,
+ url: `https://www.youtube.com/watch?v=${id}`,
+ platform: "youtube",
+ startedAt,
+ status: "interrupted",
+ stoppedBy: "shutdown",
+ endedAt: startedAt,
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ parts: [],
+ request: { fromStart: true, doNotClean: true, note: "keep", transcribe: true },
+ ...extra,
+});
+
+function starter() {
+ const asked: { slug: string; body: Record<string, unknown>; resumeOf: string }[] = [];
+ return {
+ asked,
+ start: async (slug: string, body: Record<string, unknown>, resumeOf: string) => {
+ asked.push({ slug, body, resumeOf });
+ return { ok: true as const, jobId: `boot-${asked.length}` };
+ },
+ };
+}
+const pass = (start: import("./liveRecordingBoot").LiveBootStart, extra: Partial<Parameters<typeof restartInterruptedLiveRecordings>[0]> = {}) =>
+ restartInterruptedLiveRecordings({
+ paths,
+ bootedAt: BOOTED,
+ start,
+ isRunning: (jobId) => jobId === "job-running",
+ now: () => NOW,
+ // The orphan check's looks pass at once unless a case says otherwise.
+ sleep: async () => {},
+ ...extra,
+ });
+const rowsOf = async (id: string) => (await loadLiveRecordingRows(paths, SLUG)).filter((r) => r.id === id);
+
+test("only a shutdown's or a crash's interruption restarts — never a cancel, an acknowledged one, an old one, one with a job, one restarted already, nor an older run", async () => {
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootshut1", ago(90)));
+ // A crash: the row and the record still say recording, no job runs it.
+ const crashAt = ago(60);
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootcrsh1", crashAt, { status: "recording", stoppedBy: undefined, endedAt: undefined, jobId: "job-dead" }));
+ const dir = path.join(CORPUS, "channels", SLUG, "data", "exbootcrsh1");
+ await mkdir(dir, { recursive: true });
+ await liveRecordingSidecar.write(dir, { status: "recording", url: "u", platform: "youtube", fromStart: true, startedAt: crashAt, parts: [] });
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootcanc1", ago(30), { status: "cancelled", stoppedBy: "operator" }));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootackd1", ago(30)));
+ const { acknowledgeLiveRecordingRows } = await import("../lib/liveRecordings-server");
+ await acknowledgeLiveRecordingRows(paths, SLUG, "exbootackd1", { by: "test" });
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootold01", ago(13 * 60)));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootrun01", ago(10), { status: "recording", stoppedBy: undefined, jobId: "job-running" }));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootdone1", ago(20), { restart: { at: ago(19), by: "boot", state: "asked", jobId: "x" } }));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootnewr1", ago(50)));
+ await upsertLiveRecordingRow(paths, SLUG, row("exbootnewr1", ago(40), { status: "landed", stoppedBy: undefined }));
+
+ const s = starter();
+ const out = await pass(s.start);
+ assert.deepEqual(s.asked.map((a) => a.body.url).sort(), [
+ "https://www.youtube.com/watch?v=exbootcrsh1",
+ "https://www.youtube.com/watch?v=exbootshut1",
+ ]);
+ const shut = s.asked.find((a) => a.body.url === "https://www.youtube.com/watch?v=exbootshut1")!;
+ assert.equal(shut.resumeOf, ago(90));
+ assert.deepEqual(shut.body, { fromStart: true, doNotClean: true, note: "keep", transcribe: true, slug: SLUG, url: "https://www.youtube.com/watch?v=exbootshut1" });
+ assert.equal(out.filter((o) => o.state === "asked").length, 2);
+
+ const crash = (await rowsOf("exbootcrsh1"))[0]!;
+ assert.equal(crash.status, "interrupted");
+ assert.equal(crash.stoppedBy, "crash");
+ assert.equal(crash.restart?.state, "asked");
+ assert.equal((await liveRecordingSidecar.load(dir))?.status, "interrupted", "the crashed record says so too");
+
+ // HOW A LOOP IS PREVENTED (1): a second boot asks for nothing again.
+ const again = starter();
+ await pass(again.start);
+ assert.deepEqual(again.asked, []);
+});
+
+test("a restart loop is refused: three automatic restarts of an id in the last hour, then no more, said and needing a person", async () => {
+ const id = "exbootloop1";
+ for (let i = 0; i < LIVE_BOOT_MAX_RESTARTS_PER_HOUR; i++) {
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(50 - i * 10), { resumeOf: ago(55 - i * 10), restart: { at: ago(49 - i * 10), by: "boot", state: "restarted" } }));
+ }
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(5), { resumeOf: ago(10) }));
+ const s = starter();
+ await pass(s.start);
+ assert.equal(s.asked.filter((a) => a.body.url === `https://www.youtube.com/watch?v=${id}`).length, 0);
+ const newest = (await rowsOf(id)).find((r) => r.startedAt === ago(5))!;
+ assert.equal(newest.restart?.state, "refused");
+ assert.match(newest.restart?.reason ?? "", /restart loop/);
+ assert.equal(rowNeedsAttention(newest), true);
+});
+
+test("a part written after this boot began is a recorder of the last process still running: refused, never a second recorder", async () => {
+ const id = "exbootorph1";
+ const startedAt = ago(30);
+ await upsertLiveRecordingRow(paths, SLUG, row(id, startedAt));
+ const f = path.join(store, `.${id}.live-2026-11-21T11-30-00-000Z.ytdlp.mp4`);
+ await writeFile(f, "growing");
+ await utimes(f, new Date(BOOTED + 5_000), new Date(BOOTED + 5_000));
+ const s = starter();
+ await pass(s.start);
+ assert.equal(s.asked.filter((a) => String(a.body.url).endsWith(id)).length, 0);
+ const r = (await rowsOf(id))[0]!;
+ assert.equal(r.restart?.state, "refused");
+ assert.match(r.restart?.reason ?? "", /may still be running/);
+ // Written before the boot: an ordinary leftover, restarted.
+ await utimes(f, new Date(BOOTED - 60_000), new Date(BOOTED - 60_000));
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(20)));
+ const s2 = starter();
+ await pass(s2.start);
+ assert.equal(s2.asked.filter((a) => String(a.body.url).endsWith(id)).length, 1);
+});
+
+test("a start that fails is said on the row and not tried again; the setting off refuses", async () => {
+ const id = "exbootfail1";
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(15)));
+ await pass(async () => ({ ok: false as const, error: "This stream is already being recorded (job j1)" }));
+ const r = (await rowsOf(id))[0]!;
+ assert.equal(r.restart?.state, "failed");
+ assert.match(r.restart?.reason ?? "", /already being recorded/);
+ const s = starter();
+ await pass(s.start);
+ assert.equal(s.asked.filter((a) => String(a.body.url).endsWith(id)).length, 0);
+
+ const off = "exbootoff01";
+ await upsertLiveRecordingRow(paths, SLUG, row(off, ago(15)));
+ const s2 = starter();
+ await pass(s2.start, { enabled: false });
+ assert.equal(s2.asked.filter((a) => String(a.body.url).endsWith(off)).length, 0);
+ assert.equal((await rowsOf(off))[0]!.restart?.state, "refused");
+});
+
+test("REVIEW 1.8 (live-guard-2): the orphan check looks more than once — a part whose size changes between looks (its time kept old) is refused", async () => {
+ const id = "exbootorph2";
+ await upsertLiveRecordingRow(paths, SLUG, row(id, ago(25)));
+ const f = path.join(store, `.${id}.live-2026-11-21T11-35-00-000Z.ytdlp.mp4`);
+ await writeFile(f, "first bytes");
+ const old = new Date(BOOTED - 120_000);
+ await utimes(f, old, old);
+ const s = starter();
+ let looks = 0;
+ await pass(s.start, {
+ orphanLooks: 3,
+ // Between two looks, the last process's recorder appends (and the file's
+ // time is set back, as a coarse clock or a copy would leave it).
+ sleep: async () => {
+ looks++;
+ await appendFile(f, " more");
+ await utimes(f, old, old);
+ },
+ });
+ assert.equal(looks, 1, "it looked again, and the change refused it at once");
+ assert.equal(s.asked.filter((a) => String(a.body.url).endsWith(id)).length, 0);
+ const r = (await rowsOf(id))[0]!;
+ assert.equal(r.restart?.state, "refused");
+ assert.match(r.restart?.reason ?? "", /changed between two looks/);
+});
+
+test("REVIEW-5 B6: the age is the recorder's LAST WRITE — a 14-hour part written a minute before the crash restarts; one idle for 13 h is refused, marked and logged", async () => {
+ // A crash 14 h into a stream: one from-start part since hour 0, no end time.
+ const id = "exbootlong1";
+ const startedAt = ago(14 * 60);
+ await upsertLiveRecordingRow(
+ paths,
+ SLUG,
+ row(id, startedAt, { status: "recording", stoppedBy: undefined, endedAt: undefined, jobId: "job-dead", parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt, stem: `.${id}.live-x.ytdlp` }] }),
+ );
+ const f = path.join(store, `.${id}.live-x.ytdlp.f136.mp4`);
+ await writeFile(f, "bytes");
+ const last = new Date(NOW.getTime() - 60_000);
+ await utimes(f, last, last);
+ // Idle for 13 h: its files last written then.
+ const old = "exbootidle1";
+ await upsertLiveRecordingRow(paths, SLUG, row(old, ago(14 * 60)));
+ const g = path.join(store, `.${old}.live-y.ytdlp.f136.mp4`);
+ await writeFile(g, "bytes");
+ const then = new Date(NOW.getTime() - 13 * 3_600_000);
+ await utimes(g, then, then);
+ const s = starter();
+ const lines: string[] = [];
+ await pass(s.start, { log: (l) => void lines.push(l) });
+ assert.ok(s.asked.some((a) => a.body.url === `https://www.youtube.com/watch?v=${id}`), "restarted: its recorder wrote a minute ago");
+ assert.ok(!s.asked.some((a) => a.body.url === `https://www.youtube.com/watch?v=${old}`));
+ const r = (await rowsOf(old))[0]!;
+ assert.equal(r.restart?.state, "refused");
+ assert.match(r.restart?.reason ?? "", /last wrote 13 h ago/);
+ assert.ok(lines.some((l) => l.includes(old) && /refused/.test(l)), "logged");
+});
diff --git a/common/controller/liveRecordingBoot.ts b/common/controller/liveRecordingBoot.ts
@@ -0,0 +1,256 @@
+// A LIVE RECORDING THE EDITOR'S RESTART INTERRUPTED RESTARTS BY ITSELF
+// (operator ruling, 21 Nov 2026) — the boot pass, armed by the editor's
+// instrumentation (editor/app/api/ops/_liveRecordingBoot.ts) below the idle
+// gate and never on the test server.
+//
+// Per recorded id of every channel, the NEWEST run's row is a candidate when
+// it is
+// interrupted, stopped by the shutdown (stoppedBy "shutdown"), or
+// recording with no job running it — the editor died under it (a crash);
+// it is written `interrupted`, stoppedBy "crash", first.
+// Never a cancelled run (a person's Cancel), a failed or a landed one.
+// Skipped: acknowledged; already carrying `restart` (a row restarts at most
+// once); last active more than LIVE_BOOT_MAX_AGE_MS ago; the setting off
+// (settings.liveRecording.autoRestartOnBoot).
+//
+// HOW A RESTART LOOP IS PREVENTED:
+// 1. The row is marked `restart: {state: "starting"}` BEFORE the job is asked
+// for, and a marked row is never a candidate again — an editor that dies
+// in the middle of this pass does not restart that row twice.
+// 2. At most LIVE_BOOT_MAX_RESTARTS_PER_HOUR automatic restarts of one id
+// (its rows carrying `resumeOf`, started in the last 60 minutes): a
+// crash-looping editor stops restarting after three, and the row says so
+// and needs a person.
+// 3. A part file of the id written after this process booted, or one whose
+// size or time changes between LIVE_BOOT_ORPHAN_LOOKS looks
+// LIVE_BOOT_ORPHAN_LOOK_MS apart: a recorder of the last process may still
+// be running (an orphan, perhaps mid-write) — never a second one beside
+// it, and nothing of it lands; refused, said, needs a person.
+//
+// The pass itself makes NO request. It asks for a record-live run with the
+// interrupted run's own url and request (`resumeOf` its startedAt); that run's
+// first step is record-live's one paced metadata read (the platform's pace,
+// the channel's cookies, as every record-live run), and it decides:
+// live record — a new run beside the earlier parts (slice 1's landing
+// keeps or removes them); the row says `restarted`
+// ended no recorder; whatever the earlier run left in staging lands
+// (`landing`), or with nothing left the row says `ended`
+// unknown the read failed: NOTHING is started and nothing lands — never a
+// recording on a guess; the row says `unknown` and needs a person
+// (Record again)
+// (controller/recordLive.ts, `resumeOf`).
+
+import path from "node:path";
+import { readdir, stat } from "node:fs/promises";
+import type { Paths } from "../lib/paths";
+import { livePartFiles, type LiveBootRestart } from "../lib/liveCapture";
+import { liveRecordingSidecar } from "../lib/mediaImport-server";
+import {
+ loadLiveRecordingRows,
+ patchLiveRecordingRow,
+ type LiveRecordingRow,
+} from "../lib/liveRecordings-server";
+import { savedVideoRoot } from "../lib/savedVideo";
+import { readChannelConfig } from "./channels";
+
+export const LIVE_BOOT_MAX_RESTARTS_PER_HOUR = 3;
+export const LIVE_BOOT_MAX_AGE_MS = 12 * 3_600_000;
+// How long after boot the pass runs (an orphan recorder has written by then).
+export const LIVE_BOOT_DELAY_MS = 30_000;
+// The orphan check: this many looks at the id's part files, this far apart.
+export const LIVE_BOOT_ORPHAN_LOOKS = 3;
+export const LIVE_BOOT_ORPHAN_LOOK_MS = 20_000;
+
+export type LiveBootStart = (
+ slug: string,
+ body: Record<string, unknown>,
+ resumeOf: string,
+) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>;
+
+export type LiveBootOutcome = {
+ slug: string;
+ id: string;
+ startedAt: string;
+ state: LiveBootRestart["state"];
+ jobId?: string;
+ reason?: string;
+};
+
+async function channelSlugs(paths: Paths): Promise<string[]> {
+ const entries = await readdir(paths.channelsDir, { withFileTypes: true }).catch(() => []);
+ return entries.filter((e) => e.isDirectory()).map((e) => e.name).sort();
+}
+
+function lastActivityMs(r: LiveRecordingRow): number {
+ const times = [r.startedAt, r.endedAt, ...r.parts.flatMap((p) => [p.startedAt, p.endedAt])]
+ .filter((t): t is string => typeof t === "string")
+ .map((t) => Date.parse(t))
+ .filter(Number.isFinite);
+ return times.length ? Math.max(...times) : 0;
+}
+
+export async function restartInterruptedLiveRecordings(o: {
+ paths: Paths;
+ // When this process started: a part file written since is an orphan's.
+ bootedAt: number;
+ start: LiveBootStart;
+ // A record-live job of this id runs (the registry).
+ isRunning: (jobId: string | undefined, slug: string, id: string) => boolean;
+ enabled?: boolean;
+ now?: () => Date;
+ log?: (line: string) => void;
+ // The orphan check's looks and the wait between two (tests).
+ orphanLooks?: number;
+ orphanLookMs?: number;
+ sleep?: (ms: number) => Promise<void>;
+}): Promise<LiveBootOutcome[]> {
+ const now = o.now ?? (() => new Date());
+ const log = o.log ?? (() => {});
+ const out: LiveBootOutcome[] = [];
+ for (const slug of await channelSlugs(o.paths)) {
+ const rows = await loadLiveRecordingRows(o.paths, slug).catch(() => [] as LiveRecordingRow[]);
+ if (!rows.length) continue;
+ const newest = new Map<string, LiveRecordingRow>();
+ for (const r of rows) {
+ const cur = newest.get(r.id);
+ if (!cur || Date.parse(r.startedAt) > Date.parse(cur.startedAt)) newest.set(r.id, r);
+ }
+ let names: string[] | null = null;
+ for (const row of newest.values()) {
+ const crashed = row.status === "recording" && !o.isRunning(row.jobId, slug, row.id);
+ const shutdown = row.status === "interrupted" && (row.stoppedBy === "shutdown" || row.stoppedBy === "crash");
+ if (!crashed && !shutdown) continue;
+ if (row.acknowledgedAt || row.restart) continue;
+ const at = now();
+ const tag = `${slug}/${row.id}`;
+ const mark = (restart: Partial<LiveBootRestart> & { state: LiveBootRestart["state"] }) =>
+ patchLiveRecordingRow(o.paths, slug, row.id, row.startedAt, (r) => {
+ r.restart = { ...(r.restart ?? { at: at.toISOString(), by: "boot" as const }), ...restart };
+ if (crashed && r.status === "recording") {
+ r.status = "interrupted";
+ r.stoppedBy = "crash";
+ }
+ });
+ const result = (state: LiveBootRestart["state"], extra: { jobId?: string; reason?: string } = {}) => {
+ out.push({ slug, id: row.id, startedAt: row.startedAt, state, ...extra });
+ log(`[boot] live recording ${tag}: ${state}${extra.jobId ? ` (job ${extra.jobId})` : ""}${extra.reason ? ` — ${extra.reason}` : ""}`);
+ };
+ // A crash leaves the record saying `recording`: it says interrupted now.
+ if (crashed) {
+ const dir = path.join(o.paths.channelsDir, slug, "data", row.id);
+ const rec = await liveRecordingSidecar.load(dir).catch(() => null);
+ if (rec && rec.startedAt === row.startedAt && rec.status === "recording") {
+ await liveRecordingSidecar.write(dir, { ...rec, status: "interrupted", stoppedBy: "crash" }).catch(() => {});
+ }
+ }
+ let refusal: string | null = null;
+ // THE AGE (REVIEW-5 B6): from the recorder's LAST WRITE — the newest
+ // mtime of the id's part files — or the row's own times, whichever is
+ // later; a part that is recording has no end time, and a killed editor
+ // writes none. A row skipped for its age is marked and logged.
+ {
+ const config = await readChannelConfig(o.paths, slug).catch(() => null);
+ const slugStore = path.join(savedVideoRoot(o.paths, config), slug);
+ const listing = await readdir(slugStore).catch(() => [] as string[]);
+ let newest = lastActivityMs(row);
+ for (const g of livePartFiles(row.id, listing)) {
+ for (const f of [...g.finished, ...g.streams, ...g.scratch]) {
+ const st = await stat(path.join(slugStore, f)).catch(() => null);
+ if (st) newest = Math.max(newest, st.mtimeMs);
+ }
+ }
+ const idle = at.getTime() - newest;
+ if (idle > LIVE_BOOT_MAX_AGE_MS) {
+ refusal = `its recorder last wrote ${Math.round(idle / 3_600_000)} h ago (more than ${LIVE_BOOT_MAX_AGE_MS / 3_600_000} h): too old to restart automatically`;
+ }
+ }
+ if (!refusal && o.enabled === false) refusal = "settings.liveRecording.autoRestartOnBoot is off";
+ if (!refusal) {
+ const recent = rows.filter((r) => r.id === row.id && r.resumeOf && at.getTime() - Date.parse(r.startedAt) < 3_600_000).length;
+ if (recent >= LIVE_BOOT_MAX_RESTARTS_PER_HOUR) {
+ refusal = `${recent} automatic restarts of it in the last hour (at most ${LIVE_BOOT_MAX_RESTARTS_PER_HOUR}): a restart loop?`;
+ }
+ }
+ if (!refusal) {
+ const config = await readChannelConfig(o.paths, slug).catch(() => null);
+ const slugStore = path.join(savedVideoRoot(o.paths, config), slug);
+ const looks = Math.max(1, o.orphanLooks ?? LIVE_BOOT_ORPHAN_LOOKS);
+ const wait = o.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
+ let before: Map<string, string> | null = null;
+ for (let look = 0; look < looks && !refusal; look++) {
+ if (look > 0) await wait(o.orphanLookMs ?? LIVE_BOOT_ORPHAN_LOOK_MS);
+ names = await readdir(slugStore).catch(() => [] as string[]);
+ const seen = new Map<string, string>();
+ for (const g of livePartFiles(row.id, names)) {
+ for (const f of [...g.finished, ...g.streams, ...g.scratch]) {
+ const st = await stat(path.join(slugStore, f)).catch(() => null);
+ if (!st) continue;
+ seen.set(f, `${st.size}:${st.mtimeMs}`);
+ if (st.mtimeMs >= o.bootedAt) {
+ refusal = `${f} was written after this editor started: a recorder of the last process may still be running`;
+ break;
+ }
+ }
+ if (refusal) break;
+ }
+ if (!refusal && before) {
+ for (const [f, v] of seen) {
+ if (before.get(f) !== v) {
+ refusal = `${f} changed between two looks ${Math.round((o.orphanLookMs ?? LIVE_BOOT_ORPHAN_LOOK_MS) / 1000)} s apart: a recorder of the last process may still be writing it`;
+ break;
+ }
+ }
+ }
+ before = seen;
+ }
+ }
+ if (refusal) {
+ await mark({ state: "refused", reason: refusal });
+ result("refused", { reason: refusal });
+ continue;
+ }
+ if (!row.url) {
+ await mark({ state: "failed", reason: "the row names no url" });
+ result("failed", { reason: "the row names no url" });
+ continue;
+ }
+ // Marked first: this row is never restarted twice.
+ await mark({ state: "starting" });
+ const body = { ...(row.request ?? { fromStart: row.fromStart }), slug, url: row.url };
+ let r: Awaited<ReturnType<LiveBootStart>>;
+ try {
+ r = await o.start(slug, body, row.startedAt);
+ } catch (err) {
+ r = { ok: false, error: (err as Error).message };
+ }
+ if (r.ok) {
+ // The run writes what it found (restarted, landing, ended, unknown)
+ // over this; until then the row says it was asked.
+ const jobId = r.jobId;
+ await patchLiveRecordingRow(o.paths, slug, row.id, row.startedAt, (x) => {
+ if (x.restart?.state !== "starting") return false;
+ x.restart = { ...x.restart, state: "asked", jobId };
+ });
+ result("asked", { jobId: r.jobId });
+ } else {
+ await mark({ state: "failed", reason: r.error });
+ result("failed", { reason: r.error });
+ }
+ }
+ }
+ return out;
+}
+
+// What a restarted run writes on the interrupted run's row.
+export async function markLiveBootRestart(
+ paths: Paths,
+ slug: string,
+ id: string,
+ resumeOf: string,
+ patch: { state: LiveBootRestart["state"]; jobId?: string; reason?: string },
+ now: () => Date = () => new Date(),
+): Promise<void> {
+ await patchLiveRecordingRow(paths, slug, id, resumeOf, (r) => {
+ r.restart = { ...(r.restart ?? { at: now().toISOString(), by: "boot" as const }), ...patch };
+ });
+}
diff --git a/common/controller/liveRecordings.test.ts b/common/controller/liveRecordings.test.ts
@@ -203,3 +203,68 @@ test("needsAttention: interrupted always, a cancel only when must-keep, kept par
assert.equal(rowNeedsAttention({ ...base, status: "landed", acknowledgedAt: "t", keptParts: kept }), false);
assert.equal(rowNeedsAttention({ ...base, status: "landed", missingStream: "video" }), true);
});
+
+test("REVIEW 1.3 (live-guard-2): an interruption 'restarted' by the boot pass needs a person until the NEW run's part grows; a new run that failed or never began leaves it loud", async () => {
+ const id = "exmplrest01";
+ const t0 = minutesAgo(90).toISOString();
+ await upsertLiveRecordingRow(paths, SLUG, {
+ id,
+ url: `https://www.youtube.com/watch?v=${id}`,
+ platform: "youtube",
+ startedAt: t0,
+ endedAt: minutesAgo(31).toISOString(),
+ status: "interrupted",
+ stoppedBy: "shutdown",
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ parts: [],
+ restart: { at: minutesAgo(30).toISOString(), by: "boot", state: "restarted", jobId: "job-new" },
+ });
+ const old = async (jobs: () => { id: string; kind: string; status: "running"; channelSlug: string; videoId: string }[] = () => []) =>
+ (await listLiveRecordings(paths, { slug: SLUG, id, now: NOW, all: true, jobs })).rows.find((r) => r.startedAt === t0)!;
+ // No new run at all.
+ let r = await old();
+ assert.equal(r.needsAttention, true, "the restart has not recorded a byte");
+ assert.match(r.reason, /no new run|not recorded/i);
+ // The new run records, and its part grows.
+ const stem = `.${id}.live-2026-11-20T11-30-00-000Z.ytdlp`;
+ const started = minutesAgo(29).toISOString();
+ await upsertLiveRecordingRow(paths, SLUG, {
+ id,
+ url: `https://www.youtube.com/watch?v=${id}`,
+ platform: "youtube",
+ startedAt: started,
+ status: "recording",
+ jobId: "job-new",
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ resumeOf: t0,
+ parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: started, stem }],
+ });
+ await writeFile(path.join(store, `${stem}.ts`), Buffer.alloc(2000));
+ await utimes(path.join(store, `${stem}.ts`), minutesAgo(1), minutesAgo(1));
+ const running = () => [{ id: "job-new", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: id }];
+ r = await old(running);
+ assert.equal(r.needsAttention, false, "the new run records and grows");
+ // The new run failed: loud again, and says so.
+ await upsertLiveRecordingRow(paths, SLUG, {
+ id,
+ url: `https://www.youtube.com/watch?v=${id}`,
+ platform: "youtube",
+ startedAt: started,
+ endedAt: minutesAgo(5).toISOString(),
+ status: "failed",
+ error: "nothing was recorded",
+ jobId: "job-new",
+ fromStart: true,
+ attempts: 6,
+ mustKeep: true,
+ resumeOf: t0,
+ parts: [{ method: "ytdlp", url: "u", fromStart: true, startedAt: started, stem }],
+ });
+ r = await old();
+ assert.equal(r.needsAttention, true);
+ assert.match(r.reason, /failed/);
+});
diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts
@@ -113,7 +113,17 @@ export function liveRecordingCheckCommand(slug: string, id: string): string {
return `pnpm ops get live-recordings ${slug}/${id}`;
}
-function stallMinutesSetting(): number {
+// settings.liveRecording.stallMinutes (record-live's watchdog reads it too).
+// settings.liveRecording.insuranceWhenBehind (default true).
+export function liveInsuranceWhenBehind(): boolean {
+ try {
+ return getSettings().liveRecording?.insuranceWhenBehind !== false;
+ } catch {
+ return true;
+ }
+}
+
+export function liveStallMinutes(): number {
try {
const v = getSettings().liveRecording?.stallMinutes;
return typeof v === "number" && v > 0 ? v : LIVE_STALL_MINUTES_DEFAULT;
@@ -129,6 +139,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";
@@ -141,21 +154,138 @@ function reasonOf(v: Omit<LiveRecordingView, "reason" | "check">, stallMinutes:
if (v.status === "landed" && v.coverage && !v.coverage.covers && v.coverage.streamSeconds !== null && v.coverage.capturedSeconds !== null && !v.fallback) {
extra.push(`holds ${spanWords(v.coverage.capturedSeconds)} of a ${spanWords(v.coverage.streamSeconds)} stream (${v.coverage.basis === "duration" ? "its duration" : "by the clock"})`);
}
+ const rs = v.startRecovery;
+ if (rs) {
+ const words: Record<string, string> = {
+ waiting: `start recovery: ${rs.tries} of ${rs.max} tries made, the next within ${spanWords(rs.everyMs / 1000)}`,
+ trying: `start recovery: try ${rs.tries} of ${rs.max} records now`,
+ recorded: `start recovery: try ${rs.tries} recorded from its start (not proven whole)`,
+ recovered: "start recovered: a from-start try holds the whole stream",
+ "gave-up": `start recovery gave up after ${rs.tries} tries${rs.failureClass ? ` [${rs.failureClass}]` : ""}`,
+ exhausted: `start recovery: all ${rs.max} tries failed`,
+ stopped: `start recovery stopped after ${rs.tries} tries (the live edge ended first)`,
+ };
+ extra.unshift(words[rs.state] ?? `start recovery: ${rs.state}`);
+ }
+ if (v.insurance) {
+ const ins = v.insurance;
+ const w: Record<string, string> = {
+ waiting: "the insurance recorder waits for the from-start recording to begin",
+ recording: `the insurance recorder records the live edge beside it${ins.mode === "whole" ? " (the whole stream)" : " until it catches up"}`,
+ "caught-up": "the insurance recorder stopped: the from-start recording caught up",
+ ended: "the insurance recorder recorded the live edge to the end",
+ stalled: "the insurance recorder stalled and was stopped",
+ died: `the insurance recorder DIED before the start caught up${ins.reason ? ` (${ins.reason})` : ""}`,
+ stopped: `the insurance recorder was stopped${ins.reason ? ` (${ins.reason})` : ""}`,
+ failed: `the insurance recorder recorded nothing${ins.reason ? ` (${ins.reason})` : ""}`,
+ "not-started": `no insurance recorder${ins.reason ? ` (${ins.reason})` : ""}`,
+ };
+ extra.push(w[ins.state] ?? `insurance: ${ins.state}`);
+ }
+ if (v.joins && v.joins.length) {
+ const gaps = v.joins.filter((j) => j.kind === "gap");
+ extra.push(
+ `landed as ${v.joins.length + 1} parts joined` +
+ (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` +
+ (v.status === "interrupted" ? "" : " — not resumed by this run: a person decides"),
+ );
+ }
+ if (v.status === "landed" && v.coverage?.basis === "duration" && v.coverage.covers === false && v.coverage.capturedSeconds !== null && v.coverage.streamSeconds !== null) {
+ extra.unshift(
+ `landed ${spanWords(v.coverage.capturedSeconds)} of the ended stream's ${spanWords(v.coverage.streamSeconds)}: the rest is in no file — download the VOD now`,
+ );
+ }
+ if (v.landedWhileLive) {
+ const u = v.landedWhileLive.unrecordedSeconds;
+ extra.unshift(
+ `LANDED WHILE THE STREAM WAS STILL LIVE (${v.landedWhileLive.why})${u !== null ? `: about ${spanWords(u)} of it, by the clock, were in no landed file at that moment` : ""} — what is landed is the stream SO FAR, not the whole`,
+ );
+ }
+ if (v.offline) extra.unshift(`the stream's state cannot be read since ${v.offline.since} (the network?): NOTHING is recording; read again every few minutes (${v.offline.reads} so far), and resumed in place once it reads`);
+ for (const p of v.parts ?? []) {
+ if (p.resumeDamaged) extra.unshift(`${p.stem ?? "a part"}: after a resume it is NOT its kept fragments (${p.resumeDamaged}) — kept as it is, never removed`);
+ if (p.behindUnknown) extra.push(`${p.stem ?? "a part"}: how far behind the live edge it was could not be told (${p.behindUnknown}): no live-edge insurance by the behind rule`);
+ if (p.failureClass === "went-private") extra.push(`${p.stem ?? "a part"}: its fragment requests were answered 403 Forbidden and the stream reads private or removed — it went private while it was recorded; what is on disk is landed and nothing is removed`);
+ if (p.failureClass === "url-refresh") extra.push(`${p.stem ?? "a part"}: yt-dlp could not refresh the stream's URL (the platform stopped serving the format — DVR switched off?) and ended by itself`);
+ if (p.reused) extra.push(`${p.stem ?? "a part"} was resumed after it had ended, reusing ${p.reused.fragments} fragments already downloaded (only what came since was fetched)`);
+ }
+ if (v.skippedFragments?.count) {
+ extra.unshift(`the landed file is missing ${v.skippedFragments.count} fragment(s) yt-dlp could not fetch${v.skippedFragments.positions.length ? ` (positions ${v.skippedFragments.positions.slice(0, 10).join(", ")}${v.skippedFragments.positions.length > 10 ? ", …" : ""})` : ""}: a HOLE`);
+ }
+ 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(
+ t.verdict === "shorter"
+ ? `the transcript was the replaced shorter file's (${t.why}): ${t.jobId ? `transcription asked again (job ${t.jobId})` : `transcription NOT asked again${t.error ? ` (${t.error})` : ""} — a person decides`}`
+ : `the transcript may be the replaced shorter file's — not known (${t.why}): a person decides whether to transcribe again`,
+ );
+ }
+ 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}`);
+ if (v.restarts?.waiting) extra.push(`NOT recording until ${v.restarts.waiting.until}: the restart bound (${v.restarts.waiting.why}) is waited out, then it goes on`);
+ else if (v.restarts?.waited) extra.push(`waited out the restart bound ${v.restarts.waited} time${v.restarts.waited === 1 ? "" : "s"} (nothing recorded while it waited)`);
+ if (v.lost && !v.fallback && v.startRecovery?.state !== "recovered") {
+ const hm = (x: number) => `${Math.floor(x / 3600)}:${String(Math.floor((x % 3600) / 60)).padStart(2, "0")}`;
+ extra.unshift(
+ v.lost.toSeconds !== null
+ ? `hours ${hm(v.lost.fromSeconds)}-${hm(v.lost.toSeconds)} are in no part yet (${spanWords(v.lost.toSeconds - v.lost.fromSeconds)})`
+ : "what lies before the live edge may be in no part (the stream's start time is not known)",
+ );
+ }
const tail = extra.length ? `; ${extra.join("; ")}` : "";
const cls = v.failureClass && v.failureClass !== "unknown" ? ` [${v.failureClass}]` : "";
switch (v.status) {
case "failed":
return `failed${cls}: ${v.error ?? "no reason recorded"}${tail}`;
- case "interrupted":
- return (
- (v.stoppedBy === "shutdown"
- ? "interrupted: the editor shut down while it recorded — Record again if the stream is still live"
- : "interrupted: its record says recording, and no record-live job runs it (an editor restart?) — Record again") + tail
- );
+ case "interrupted": {
+ const r = v.restart;
+ const boot = r
+ ? {
+ // 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 ?? "?"})`,
+ landed: `${r.reason ?? "the stream had ended by the restart"}: what this run left was landed (job ${r.jobId ?? "?"})`,
+ ended: "the stream had ended by the restart, and nothing was left to land — the end of the stream is NOT recorded",
+ unknown: `NOT restarted: the stream's state could not be read${r.reason ? ` (${r.reason})` : ""} — Record again if it is still live`,
+ refused: `NOT restarted automatically: ${r.reason ?? "refused"} — Record again if the stream is still live`,
+ failed: `the automatic restart failed: ${r.reason ?? "no job"} — Record again if the stream is still live`,
+ }[r.state]
+ : null;
+ const head =
+ v.stoppedBy === "shutdown"
+ ? "interrupted: the editor shut down while it recorded"
+ : v.stoppedBy === "crash"
+ ? "interrupted: the editor stopped (a crash?) while it recorded"
+ : "interrupted: its record says recording, and no record-live job runs it (an editor restart?)";
+ return `${head} — ${boot ?? "Record again if the stream is still live"}${tail}`;
+ }
case "cancelled":
return `cancelled${v.mustKeep ? " (a must-keep stream: is that what you wanted?)" : ""}${tail}`;
case "landed":
- return (v.fallback === "live-edge" ? `landed from the live edge: ${lostWords}` : "landed") + tail;
+ return (
+ (v.fallback === "live-edge" && rs?.state !== "recovered" ? `landed from the live edge: ${lostWords}` : "landed") + tail
+ );
case "recording": {
const parts = [v.fallback === "live-edge" ? `recording from the live edge: ${lostWords}` : "recording"];
if (v.bytes !== null) parts.push(`${Math.round(v.bytes / 1024 / 1024)} MB so far`);
@@ -175,7 +305,7 @@ function fileProblemMessage(slug: string, p: Pick<LiveRecordingsFileProblem, "fi
// Every live recording (of one channel, one id), newest first.
export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsOpts = {}): Promise<LiveRecordingsListing> {
const now = (opts.now ?? new Date()).getTime();
- const stallMinutes = opts.stallMinutes ?? stallMinutesSetting();
+ const stallMinutes = opts.stallMinutes ?? liveStallMinutes();
const jobs = (opts.jobs ?? (() => getRegistry().list()))();
const byId = new Map(jobs.map((j) => [j.id, j]));
const slugs = opts.slug ? [opts.slug] : await channelSlugs(paths);
@@ -269,6 +399,18 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
...(own?.keptParts ? { keptParts: own.keptParts } : {}),
...(own?.removedParts ? { removedParts: own.removedParts } : {}),
...(own?.coverage ? { coverage: own.coverage } : {}),
+ ...(own?.startRecovery ? { startRecovery: own.startRecovery } : {}),
+ ...(own?.restarts ? { restarts: own.restarts } : {}),
+ ...(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 } : {}),
+ ...(own?.transcriptRedo ? { transcriptRedo: own.transcriptRedo } : {}),
+ ...(own?.verification ? { verification: own.verification } : {}),
+ ...(own?.skippedFragments ? { skippedFragments: own.skippedFragments } : {}),
+ ...(own?.landedWhileLive ? { landedWhileLive: own.landedWhileLive } : {}),
+ ...(own?.offline ? { offline: own.offline } : {}),
attempts: own?.attempts ?? row.attempts,
parts,
slug,
@@ -285,6 +427,20 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
fallback: own?.fallback ?? row.fallback,
keptParts: own?.keptParts ?? row.keptParts,
missingStream: own?.missingStream ?? row.missingStream,
+ startRecovery: own?.startRecovery ?? row.startRecovery,
+ 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,
+ 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,
+ landedWhileLive: own?.landedWhileLive ?? row.landedWhileLive,
+ coverage: own?.coverage ?? row.coverage,
+ offline: own?.offline ?? row.offline,
}),
};
const shown =
@@ -297,6 +453,25 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO
out.push({ ...view, reason: reasonOf(view, stallMinutes), check: liveRecordingCheckCommand(slug, row.id) });
}
}
+ // AN INTERRUPTION THE BOOT PASS RESTARTED (REVIEW-1 1.3 of live-guard-2) is
+ // quiet only while the NEW run (its row's resumeOf) records and its part
+ // grows; a new run that failed, ended short or never began leaves it loud,
+ // and says so. A new run that holds the whole stream supersedes it anyway.
+ for (const v of out) {
+ if (v.status !== "interrupted" || v.restart?.state !== "restarted" || v.acknowledgedAt || v.supersededBy) continue;
+ const nv = out.find((x) => x.slug === v.slug && x.id === v.id && x.resumeOf === v.startedAt);
+ const growing = nv && nv.status === "recording" && !nv.stalled && (nv.bytes ?? 0) > 0;
+ if (growing && !(v.keptParts && v.keptParts.length)) {
+ v.needsAttention = false;
+ v.reason = `${v.reason} — the new run records (${Math.round((nv.bytes ?? 0) / 1024 / 1024)} MB, growing)`;
+ } else if (!nv) {
+ v.reason = `${v.reason} — but no new run has recorded anything yet`;
+ } else if (nv.status === "recording" || nv.status === "interrupted") {
+ v.reason = `${v.reason} — but the new run is ${nv.stalled ? "NOT growing" : nv.status === "interrupted" ? "interrupted too" : "not recording yet"}`;
+ } else {
+ v.reason = `${v.reason} — but the new run ${nv.status === "failed" ? `failed: ${nv.error ?? "no reason recorded"}` : `ended ${nv.status}${nv.coverage && !nv.coverage.covers ? " without the whole stream" : ""}`}`;
+ }
+ }
out.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt));
return {
rows: out,
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,
@@ -81,14 +84,26 @@ const handoff = async () => ({
const NO_COOKIES = { cookies: undefined, mode: "when-required" } as const;
// A refresh that writes the stream's metadata (live, with one HLS format).
-function refreshWith(meta: Record<string, unknown>, opts: { failFirst?: string } = {}) {
+// Read after the recording (the stream has ended): a live record then says
+// `was_live` (the platforms' own word for an ended stream), unless
+// `stillLive` says it is still live.
+function refreshWith(
+ meta: Record<string, unknown>,
+ opts: { failFirst?: string; stillLive?: () => boolean; failAfterFirst?: string; afterRead?: (n: number) => void; failReads?: number[]; failWith?: string; endedAs?: string } = {},
+) {
let n = 0;
+ let wrote = 0;
return async (cwd: string, args: string[]): Promise<AttemptOutcome> => {
n++;
if (opts.failFirst && n === 1) return { exitCode: 1, stderrTail: opts.failFirst, archiveLine: null, formatLine: null };
+ if (opts.failAfterFirst && n > 1) return { exitCode: 1, stderrTail: opts.failAfterFirst, archiveLine: null, formatLine: null };
+ if (opts.failReads?.includes(n)) return { exitCode: 1, stderrTail: opts.failWith ?? "ERROR: Unable to download webpage: timed out", archiveLine: null, formatLine: null };
const o = args[args.indexOf("-o") + 1]!;
const dir = path.join(cwd, path.dirname(o));
- await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(meta));
+ wrote++;
+ const ended = wrote > 1 && meta.live_status === "is_live" && !(opts.stillLive?.() ?? false);
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify(ended ? { ...meta, live_status: opts.endedAs ?? "was_live" } : meta));
+ opts.afterRead?.(n);
return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
};
}
@@ -145,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,
},
@@ -204,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,
},
@@ -236,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,
},
@@ -271,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,
},
@@ -332,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,
},
@@ -418,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,
},
@@ -640,7 +661,7 @@ const ytChannel = async () => {
const ytLiveMeta = (id: string) => ({ ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 7200 });
const ytUrl = (id: string) => `https://www.youtube.com/watch?v=${id}`;
-type Attempt = (args: string[], n: number) => Promise<{ exitCode: number | null; stderrTail: string; signalled: boolean }>;
+type Attempt = (args: string[], n: number, signal: AbortSignal, onLine?: (l: string) => void) => Promise<{ exitCode: number | null; stderrTail: string; signalled: boolean }>;
const writesAfter = (failures: number, stderr = EMPTY): Attempt => async (args, n) => {
if (n <= failures) return { exitCode: 1, stderrTail: stderr, signalled: false };
const out = args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, ".mp4");
@@ -657,39 +678,61 @@ async function incidentRun(
request?: Record<string, unknown>;
meta?: Record<string, unknown>;
deps?: Record<string, unknown>;
+ // Slice 2's tries beside the live edge: their 15 min waits pass at once
+ // ("immediate", recorded in `waits`), or never come before the run ends
+ // (the default: no try is made).
+ // A number: that many pass at once, the rest never come.
+ recovery?: "immediate" | number;
+ refresh?: Parameters<typeof refreshWith>[1];
+ requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>;
} = {},
) {
await ytChannel();
const calls: string[][] = [];
const waits: number[] = [];
const log: string[] = [];
+ let recoveryWaits = 0;
const run = recordLiveRun({
paths,
- request: { slug: YT_SLUG, url: ytUrl(id), fromStart: true, transcribe: true, doNotClean: true, note: "must not lose", ...(opts.request ?? {}) },
+ // The insurance recorder (slice 4) is off unless a case asks for it.
+ request: { slug: YT_SLUG, url: ytUrl(id), fromStart: true, transcribe: true, doNotClean: true, note: "must not lose", insurance: false, ...(opts.request ?? {}) },
plan: { url: ytUrl(id), platform: "youtube", id },
channelConfig: YT_CONFIG,
cookiePolicy: NO_COOKIES,
onLog: (l) => void log.push(l),
signal: opts.signal ?? new AbortController().signal,
jobId: `job-${id}`,
+ ...(opts.requestTranscription ? { requestTranscription: opts.requestTranscription } : {}),
deps: {
- refresh: refreshWith(opts.meta ?? ytLiveMeta(id)),
+ refresh: refreshWith(opts.meta ?? ytLiveMeta(id), opts.refresh ?? {}),
fetchText: async () => {
throw new Error("no playlist read is expected");
},
- spawn: async ({ args }: { args: string[] }) => {
+ spawn: async ({ args, signal, onLine }: { args: string[]; signal: AbortSignal; onLine?: (l: string) => void }) => {
calls.push(args);
- return attempt(args, calls.length);
+ return attempt(args, calls.length, signal, onLine);
},
wait: async (ms) => {
waits.push(ms);
opts.onWait?.(ms);
},
+ recoveryWait: (ms: number, sig: AbortSignal) => {
+ const passes = opts.recovery === "immediate" || (typeof opts.recovery === "number" && recoveryWaits++ < opts.recovery);
+ if (passes) {
+ waits.push(ms);
+ return Promise.resolve();
+ }
+ return new Promise<void>((r) => (sig.aborted ? r() : sig.addEventListener("abort", () => r(), { once: true })));
+ },
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]);
@@ -841,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 ----------------
@@ -869,7 +921,9 @@ test("1.4: a normal stream end where yt-dlp exits 1 but the parts hold bytes lan
assert.equal(row.status, "landed");
assert.equal(row.error, undefined);
assert.equal(row.failureClass, undefined);
- assert.equal(row.parts[0]!.error, undefined);
+ // What the recorder said at its end is classified on the part (REVIEW-1 2.1
+ // of live-guard-2); the run is not failed for it.
+ assert.equal(row.parts[0]!.failureClass, "network");
assert.equal(row.needsAttention, false);
});
@@ -999,7 +1053,6 @@ test("2.3: only a landed from-start run that covers the stream supersedes; a liv
assert.equal(shortRow.keptParts?.length, 1);
assert.equal(shortRow.coverage?.covers, false);
assert.equal(shortRow.coverage?.basis, "clock");
- // (c) the ended stream's own duration, 610 s, against 600 s captured: covers.
// (c) the ended stream's own duration, 710 s, against 700 s captured: covers,
// so it replaces the stored live-edge recording.
const whole = await incidentRun(
@@ -1156,8 +1209,795 @@ test("a landing that fails removes nothing: the covered landing's other part and
assert.equal(row.needsAttention, true);
});
-// --- The landing and the store (lane landing-fix): a container already in the
-// store is never deleted around nor replaced by a part not proven to hold it ---
+// --- SLICE 2: the start recovered beside a live-edge recording ---------------------
+//
+// From its start failed three times, the run records from the live edge, and
+// BESIDE it — never touching it — tries from its start again every 15 min, one
+// try at a time, at most 8 times. The waits are recorded, never slept.
+
+const RECOVERY_WAIT = 15 * 60_000;
+const isRecovery = (args: string[]) => /\.ytdlp-recover-r\d+$/.test(outOf(args));
+// The live-edge recorder: records 1800 s, and runs until `ended` resolves.
+const edgeUntil = (ended: Promise<unknown>, seconds = 30) => async (args: string[]) => {
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`);
+ await ended;
+ return { exitCode: 0, stderrTail: "", signalled: false };
+};
+const failEmpty = { exitCode: 1, stderrTail: EMPTY, signalled: false };
+
+test("slice 2: the live edge records, a from-start try beside it records from the start; unproven (a recovery part), it lands, the live-edge part is kept for a person", async () => {
+ const id = "exmplrecov1";
+ let endStream!: () => void;
+ const ended = new Promise<void>((r) => (endStream = r));
+ let active = 0;
+ let maxActive = 0;
+ const edge = edgeUntil(ended);
+ let recoveries = 0;
+ const { run, calls, waits, log } = await incidentRun(id, async (args) => {
+ if (!fromStartArg(args)) return edge(args);
+ active++;
+ maxActive = Math.max(maxActive, active);
+ try {
+ if (!isRecovery(args)) return failEmpty;
+ recoveries++;
+ if (recoveries === 1) return failEmpty;
+ // The second try catches up and runs to the stream's end.
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ endStream();
+ await new Promise((r) => setTimeout(r, 30));
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ } finally {
+ active--;
+ }
+ // The third 15 min wait never comes: the stream ends first. The ended
+ // stream's own duration proves the live edge's 30 s inside the whole.
+ }, { recovery: 2, meta: { ...ytLiveMeta(id), duration: 7200 } });
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(recoveries, 2, "two tries: the first failed, the second recorded");
+ assert.equal(calls.length, 6, "3 from its start, 1 live edge, 2 recovery tries");
+ assert.equal(maxActive, 1, "never two from-start recorders at once");
+ assert.equal(waits.filter((w) => w === RECOVERY_WAIT).length, 2, "each try after a 15 min wait");
+ assert.equal(s.landed?.seconds, 7200, "the from-start try's part, the longest, lands");
+ assert.ok(log.some((l) => /tried again beside the live edge/.test(l)));
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.fallback, "live-edge");
+ assert.equal(row.startRecovery?.tries, 2);
+ // A recovery part never carries the proof of start (main's rule): it lands,
+ // but it is not taken as the whole stream — the live-edge part is kept and
+ // a person decides.
+ 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" 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);
+});
+
+test("slice 2: bounded — 8 failed tries beside the live edge, one at a time, then no more; the start stays lost and needs a person", async () => {
+ const id = "exmplrecov2";
+ let recoveries = 0;
+ let active = 0;
+ let maxActive = 0;
+ const { run, calls } = await incidentRun(id, async (args) => {
+ if (!fromStartArg(args)) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=1800;");
+ // The stream runs until the tries are spent (or 3 s, whichever first).
+ for (let i = 0; i < 300 && recoveries < 8; i++) await new Promise((r) => setTimeout(r, 10));
+ await new Promise((r) => setTimeout(r, 50));
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ }
+ active++;
+ maxActive = Math.max(maxActive, active);
+ if (isRecovery(args)) recoveries++;
+ await new Promise((r) => setTimeout(r, 2));
+ active--;
+ return failEmpty;
+ }, { recovery: "immediate" });
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(recoveries, 8, "at most 8 tries");
+ assert.equal(calls.length, 3 + 1 + 8);
+ assert.equal(maxActive, 1);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.startRecovery?.state, "exhausted");
+ assert.match(row.startRecovery?.lastError ?? "", /downloaded file is empty/);
+ assert.equal(row.needsAttention, true, "the start is still lost");
+});
+
+test("slice 2: a try that says the stream is private stops the tries; the stream ending while a try waits stops them too", async () => {
+ const gone = "exmplrecov3";
+ let tries = 0;
+ const a = await incidentRun(gone, async (args) => {
+ if (!fromStartArg(args)) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=1800;");
+ for (let i = 0; i < 100 && tries < 1; i++) await new Promise((r) => setTimeout(r, 10));
+ await new Promise((r) => setTimeout(r, 100));
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ }
+ if (isRecovery(args)) {
+ tries++;
+ return { exitCode: 1, stderrTail: `ERROR: [youtube] ${gone}: Private video\n`, signalled: false };
+ }
+ return failEmpty;
+ }, { recovery: "immediate" });
+ await a.run;
+ assert.equal(tries, 1, "not tried again");
+ const r3 = (await rowOf(gone))[0]!;
+ assert.equal(r3.startRecovery?.state, "gave-up");
+ assert.equal(r3.startRecovery?.failureClass, "private");
+
+ // The stream ends while the first try is still 15 min away: no try.
+ const early = "exmplrecov4";
+ const b = await incidentRun(
+ early,
+ async (args) => {
+ if (fromStartArg(args)) return failEmpty;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=1800;");
+ await new Promise((r) => setTimeout(r, 20));
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ // (the default: the 15 min never comes before the stream ends)
+ );
+ assert.equal((await b.run).status, "landed");
+ assert.equal(b.calls.filter(isRecovery).length, 0);
+ const r4 = (await rowOf(early))[0]!;
+ assert.equal(r4.startRecovery?.state, "stopped");
+ assert.equal(r4.needsAttention, true);
+});
+
+// --- SLICE 3: the stall watchdog acts, and a recorder that dies is restarted --------
+//
+// The watchdog compares the part's files every `watchMs`; no growth for
+// `stallMs` stops that recorder alone. Then one metadata read: still live → a
+// new part (its own stem; the stalled part kept until the landing decides),
+// bounded; ended → land.
+
+const hangAfter = (seconds: number) => async (args: string[], _n: number, signal: AbortSignal) => {
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`);
+ await new Promise<void>((r) => (signal.aborted ? r() : signal.addEventListener("abort", () => r(), { once: true })));
+ return { exitCode: null, stderrTail: "", signalled: true };
+};
+const FAST_WATCH = { watchMs: 10, stallMs: 80 };
+
+test("slice 3: a stalled recorder is stopped, the stream still live, a new part records: the stalled part was kept until the landing, the whole lands", async () => {
+ const id = "exmplstall1";
+ let live = true;
+ const hang = hangAfter(300);
+ const { run, calls, waits, log } = await incidentRun(
+ id,
+ async (args, n, signal) => {
+ if (n === 1) return hang(args, n, signal);
+ // The restart records from its start to the end.
+ assert.ok(
+ (await readdir(store())).some((f) => f.startsWith(`.${id}.`) && f.endsWith(".ytdlp.mp4")),
+ "the stalled part is still on disk while the restart records",
+ );
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ live = false;
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ // (The stream is as old as the stalled part: it had reached the live edge.)
+ { 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");
+ assert.equal(calls.length, 2, "the stalled recorder, then one restart");
+ assert.ok(!fromStartArg(calls[1]!), "restarted at the live edge: the stalled part holds the past (REVIEW-2)");
+ assert.match(outOf(calls[1]!), /\.ytdlp-r1$/, "the restart's own stem");
+ assert.ok(!waits.includes(30_000), "the live edge at once (REVIEW-3)");
+ assert.ok(log.some((l) => /stalled/.test(l)));
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.parts[0]!.stalled, true);
+ assert.equal(row.restarts?.count, 1);
+ assert.equal(s.landed?.seconds, 7200);
+ assert.ok(row.keptParts?.some((k) => /\.ytdlp$/.test(k.stem)), "the stalled from-start part is kept: the join or a person decides");
+ assert.equal(row.needsAttention, true);
+});
+
+test("slice 3: a recorder that exits with bytes while the stream still reads live (twice, 60 s apart) is restarted; a normal end is not", async () => {
+ const id = "exmplexitl1";
+ let live = true;
+ const { run, calls, waits } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ live = false;
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ { deps: FAST_WATCH, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 }, },
+ );
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 2);
+ assert.ok(waits.includes(60_000), "read again a minute later before restarting");
+ // A normal end (the stream reads ended at once): one spawn, no restart.
+ const plain = await incidentRun("exmplexitl2", writesAfter(0), { deps: FAST_WATCH });
+ assert.equal((await plain.run).status, "landed");
+ assert.equal(plain.calls.length, 1);
+ assert.deepEqual(plain.waits, []);
+});
+
+test("slice 3: restarts are bounded (6 an hour); past it the run WAITS the hour out and goes on (REVIEW-5 note 3), and every part is accounted for", { timeout: 60_000 }, async () => {
+ const id = "exmplbound1";
+ // Each recorder writes and then stalls; the stream ends after the 9th.
+ let n0 = 0;
+ const { run, calls, waits } = await incidentRun(
+ id,
+ async (args, n, signal) => {
+ n0 = n;
+ return hangAfter(100 * n)(args, n, signal);
+ },
+ { deps: FAST_WATCH, refresh: { stillLive: () => n0 < 9 }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 100 }, },
+ );
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.ok(calls.length >= 8, `past the hour's 6 restarts: ${calls.length} recorders`);
+ assert.ok(waits.some((w) => w > 60_000 && w <= 3_600_000), "the hour waited out");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.restarts?.refused, undefined);
+ assert.ok((row.restarts?.waited ?? 0) >= 1);
+ assert.ok((row.keptParts?.length ?? 0) + (row.removedParts?.length ?? 0) >= 3, "every part is accounted for");
+});
+
+test("slice 3: a stall when the stream has ended lands what was recorded, no restart; a stall with nothing written is a failed attempt on the schedule", async () => {
+ const id = "exmplstall2";
+ const { run, calls } = await incidentRun(id, hangAfter(600), { deps: FAST_WATCH });
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 1);
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.parts[0]!.stalled, true);
+ assert.equal(row.restarts?.count ?? 0, 0);
+
+ const id2 = "exmplstall3";
+ const two = await incidentRun(
+ id2,
+ async (args, n, signal) => {
+ if (n === 1) {
+ await new Promise<void>((r) => signal.addEventListener("abort", () => r(), { once: true }));
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ { deps: FAST_WATCH },
+ );
+ assert.equal((await two.run).status, "landed");
+ assert.equal(two.calls.length, 2);
+ assert.deepEqual(two.waits, [60_000], "the schedule's second from-start attempt");
+ const r2 = (await rowOf(id2))[0]!;
+ assert.equal(r2.parts[0]!.failureClass, "stalled");
+});
+
+// --- SLICE 3: the run the boot pass starts for an interrupted recording -------------
+//
+// `resumeOf` names the interrupted run (its startedAt). The run's own first
+// read decides: live → record; ended → land what is in staging, or say there
+// is nothing; unreadable → nothing at all.
+
+const interruptedRow = async (id: string, startedAt: string, parts: { stem: string; fromStart: boolean }[] = []) => {
+ const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await ytChannel();
+ await upsertLiveRecordingRow(paths, YT_SLUG, {
+ id,
+ url: ytUrl(id),
+ platform: "youtube",
+ startedAt,
+ endedAt: startedAt,
+ status: "interrupted",
+ stoppedBy: "shutdown",
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ // (A from-start part recorded by this build carries its proof.)
+ parts: parts.map((p) => ({ method: "ytdlp" as const, url: ytUrl(id), fromStart: p.fromStart, ...(p.fromStart ? { provenStart: true } : {}), startedAt, stem: p.stem })),
+ restart: { at: startedAt, by: "boot", state: "asked", jobId: `job-${id}` },
+ });
+};
+const oldRow = async (id: string, startedAt: string) => (await rowOf(id)).find((r) => r.startedAt === startedAt)!;
+
+test("slice 3 resume: the stream is still live → it records again; the interrupted row says restarted and no longer needs a person", async () => {
+ const id = "exmplresum1";
+ const t0 = "2026-11-21T08:00:00.000Z";
+ await interruptedRow(id, t0);
+ // The new run lands 600 s of a stream that started 590 s ago: the whole.
+ const { run, calls, log } = await incidentRun(id, writesAfter(0), {
+ request: { resumeOf: t0 },
+ meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 },
+ });
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 1);
+ assert.ok(log.some((l) => /recording again/.test(l)));
+ const old = await oldRow(id, t0);
+ assert.equal(old.restart?.state, "restarted");
+ assert.equal(old.restart?.jobId, `job-${id}`);
+ assert.ok(old.supersededBy, "the new run holds the whole stream: it supersedes the interruption");
+ assert.equal(old.needsAttention, false);
+ // A restarted run that lands short leaves the interruption loud (REVIEW-1 1.3).
+ const id2 = "exmplresum5";
+ await interruptedRow(id2, t0);
+ const short = await incidentRun(id2, writesAfter(0), { request: { resumeOf: t0 } });
+ assert.equal((await short.run).status, "landed");
+ const old2 = await oldRow(id2, t0);
+ assert.equal(old2.restart?.state, "restarted");
+ assert.equal(old2.needsAttention, true, "600 s of a two-hour stream does not carry the interruption");
+ assert.match(old2.reason, /without the whole stream/);
+ const fresh = (await rowOf(id)).find((r) => r.startedAt !== t0)!;
+ assert.equal(fresh.resumeOf, t0);
+});
+
+test("slice 3 resume: the stream has ended → no recorder; the interrupted run's part lands, and covering the stream it clears the row", async () => {
+ const id = "exmplresum2";
+ const t0 = "2026-11-21T08:00:00.000Z";
+ const stem = `.${id}.live-2026-11-21T08-00-00-000Z.ytdlp`;
+ await mkdir(store(), { recursive: true });
+ await writeFile(path.join(store(), `${stem}.mp4`), "format=mov,mp4;seconds=3000;");
+ await interruptedRow(id, t0, [{ stem, fromStart: true }]);
+ const { run, calls } = await incidentRun(id, writesAfter(0), {
+ request: { resumeOf: t0 },
+ meta: { ...YT_META(id), live_status: "was_live", duration: 3010 },
+ });
+ const s = await run;
+ assert.equal(calls.length, 0, "nothing is recorded");
+ assert.equal(s.status, "landed");
+ assert.equal(s.landed?.seconds, 3000);
+ const old = await oldRow(id, t0);
+ // What was done, not what was meant (REVIEW-5 B3).
+ assert.equal(old.restart?.state, "landed");
+ assert.ok(old.supersededBy, "the landed whole supersedes the interruption");
+ assert.equal(old.needsAttention, false);
+});
+
+test("slice 3 resume: ended with nothing left says so and still needs a person; an unreadable state starts nothing and writes no row of its own", async () => {
+ const id = "exmplresum3";
+ const t0 = "2026-11-21T08:00:00.000Z";
+ await interruptedRow(id, t0);
+ const ended = await incidentRun(id, writesAfter(0), { request: { resumeOf: t0 }, meta: { ...YT_META(id), live_status: "was_live" } });
+ assert.equal((await ended.run).status, "interrupted");
+ assert.equal(ended.calls.length, 0);
+ const rows = await rowOf(id);
+ assert.equal(rows.length, 1, "no row of its own");
+ assert.equal(rows[0]!.restart?.state, "ended");
+ assert.equal(rows[0]!.needsAttention, true);
+ assert.match(rows[0]!.reason, /end of the stream is NOT recorded/);
+
+ const id2 = "exmplresum4";
+ await interruptedRow(id2, t0);
+ // (Every read fails: three over about ten minutes, then unknown.)
+ const unknown = await incidentRun(id2, writesAfter(0), {
+ request: { resumeOf: t0 },
+ refresh: { failReads: [1, 2, 3], failWith: "ERROR: [youtube] exmplresum4: Unable to download webpage: The read operation timed out" },
+ });
+ await assert.rejects(unknown.run, /timed out/);
+ assert.equal(unknown.calls.length, 0, "never a recording on a guess");
+ const rows2 = await rowOf(id2);
+ assert.equal(rows2.length, 1, "no failed row of its own");
+ assert.equal(rows2[0]!.restart?.state, "unknown");
+ assert.match(rows2[0]!.restart?.reason ?? "", /timed out/);
+ assert.equal(rows2[0]!.needsAttention, true);
+});
+
+// --- SLICE 4: the insurance recorder beside a from-start recording catching up ------
+//
+// On by default for a stream marked keep before or when the recording starts;
+// the request's `insurance` overrides. It records the live edge, its own part,
+// and stops once the from-start recorder has caught up (yt-dlp's `(frag N/M)`
+// on every stream) plus a margin — or runs the whole stream when asked.
+
+const isInsurance = (args: string[]) => /\.ytdlp-insure(?:-r\d+)?$/.test(outOf(args));
+const FAST_INSURE = { insurancePollMs: 5, insuranceMarginMs: 10, insuranceGraceMs: 10 };
+function insuranceFake(o: { mainSeconds?: number; edgeSeconds?: number; caughtUp?: boolean } = {}) {
+ // (The insurance's part is 30 s by default: the live edge at the stream's end.)
+ let started!: () => void;
+ const insStarted = new Promise<void>((r) => (started = r));
+ let stoppedBy: "signal" | null = null;
+ let mainReturned!: () => void;
+ const mainDone = new Promise<void>((r) => (mainReturned = r));
+ const state = { stoppedBy: () => stoppedBy };
+ const attempt: Attempt = async (args, _n, signal, onLine) => {
+ if (isInsurance(args)) {
+ assert.equal(fromStartArg(args), false, "the insurance records the live edge");
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${o.edgeSeconds ?? 30};`);
+ started();
+ await Promise.race([
+ new Promise<void>((r) => signal.addEventListener("abort", () => r(), { once: true })),
+ mainDone.then(() => new Promise((r) => setTimeout(r, 200))),
+ ]);
+ if (signal.aborted) {
+ stoppedBy = "signal";
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Private video\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${o.mainSeconds ?? 7200};`);
+ onLine?.("1: [download] 10.0% of ~ 1.20GiB at 2.00MiB/s ETA 10:00 (frag 100/3000)");
+ onLine?.("2: [download] 10.0% of ~ 90.0MiB at 1.00MiB/s ETA 10:00 (frag 300/9000)");
+ await insStarted;
+ if (o.caughtUp !== false) {
+ onLine?.("1: [download] 99.9% of ~ 1.20GiB at 2.00MiB/s ETA 00:01 (frag 2990/3000)");
+ await new Promise((r) => setTimeout(r, 60));
+ assert.equal(stoppedBy, null, "not stopped while the audio stream is still behind");
+ onLine?.("2: [download] 99.9% of ~ 90.0MiB at 1.00MiB/s ETA 00:01 (frag 8990/9000)");
+ await new Promise((r) => setTimeout(r, 80));
+ }
+ mainReturned();
+ if (o.mainSeconds !== undefined && o.mainSeconds < 7200) {
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Private video\n", signalled: false };
+ }
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ };
+ return { attempt, state };
+}
+
+test("slice 4: a stream marked keep gets the insurance by default; it stops once every stream has caught up, and covered by the whole it goes at landing", { timeout: 60_000 }, async () => {
+ const id = "exmplinsur1";
+ const f = insuranceFake();
+ const { run, calls, waits } = await incidentRun(id, f.attempt, {
+ request: { insurance: undefined },
+ deps: FAST_INSURE,
+ meta: { ...ytLiveMeta(id), duration: 7200 },
+ });
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(calls.length, 2, "the from-start recorder and the insurance");
+ assert.equal(calls.filter(isInsurance).length, 1);
+ assert.equal(f.state.stoppedBy(), "signal", "stopped after the catch-up");
+ assert.ok(waits.includes(60_000), "a pause after the from-start part's first bytes");
+ const row = (await rowOf(id))[0]!;
+ const { startTimes, ...ins } = row.insurance ?? ({} as NonNullable<typeof row.insurance>);
+ assert.deepEqual(ins, { mode: "catch-up", by: "default", state: "caught-up", starts: 1 });
+ assert.equal(startTimes?.length, 1, "each start's time (the hourly bound)");
+ assert.equal(s.landed?.seconds, 7200);
+ assert.equal(row.coverage?.covers, true);
+ assert.ok(row.removedParts?.some((r) => /ytdlp-insure$/.test(r.stem)), "removed only because the landed file holds the whole stream");
+ assert.equal(row.needsAttention, false);
+});
+
+test("slice 4: the default is by keep mark (asked, or on the record before); the request overrides either way", { timeout: 60_000 }, async () => {
+ // Not marked, asked: on.
+ const asked = insuranceFake({ caughtUp: false });
+ const a = await incidentRun("exmplinsur3", asked.attempt, { request: { insurance: true, doNotClean: false, note: undefined }, deps: FAST_INSURE });
+ await a.run;
+ assert.equal(a.calls.filter(isInsurance).length, 1);
+ assert.equal((await rowOf("exmplinsur3"))[0]!.insurance?.by, "asked");
+ // Marked on the record before the recording: on by default.
+ const { setDoNotClean } = await import("../lib/doNotClean-server");
+ const dir = path.join(CORPUS, "channels", YT_SLUG, "data", "exmplinsur4");
+ await mkdir(dir, { recursive: true });
+ await setDoNotClean(dir, true, { by: "live-recording", via: "record-live", note: "keep this one" });
+ const pre = insuranceFake({ caughtUp: false });
+ const b = await incidentRun("exmplinsur4", pre.attempt, { request: { insurance: undefined, doNotClean: false, note: undefined }, deps: FAST_INSURE });
+ await b.run;
+ assert.equal(b.calls.filter(isInsurance).length, 1);
+ assert.equal((await rowOf("exmplinsur4"))[0]!.insurance?.by, "default");
+ // Marked, asked off: none.
+ const off = await incidentRun("exmplinsur5", writesAfter(0), { request: { insurance: false }, deps: FAST_INSURE });
+ await off.run;
+ assert.equal(off.calls.length, 1);
+ assert.equal((await rowOf("exmplinsur5"))[0]!.insurance, undefined);
+});
+
+test("slice 4: not marked keep, not asked: no insurance recorder at all", { timeout: 60_000 }, async () => {
+ const id = "exmplinsur6";
+ const { run, calls } = await incidentRun(id, writesAfter(0), { request: { insurance: undefined, doNotClean: false, note: undefined }, deps: FAST_INSURE });
+ await run;
+ assert.equal(calls.length, 1);
+ assert.equal((await rowOf(id))[0]!.insurance, undefined);
+});
+
+test("slice 4: \"whole\" is not stopped by the catch-up, only after the stream's end", { timeout: 60_000 }, async () => {
+ const id = "exmplinsur7";
+ const f = insuranceFake();
+ const { run } = await incidentRun(id, f.attempt, { request: { insurance: "whole" }, deps: FAST_INSURE });
+ await run;
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.insurance?.mode, "whole");
+ assert.equal(row.insurance?.state, "ended", "stopped by the grace after the stream ended, not by the catch-up");
+});
+
+test("slice 4: the stream removed mid-catch-up — the insurance part holds the end the from-start part never reached: kept, listed, needing a person", { timeout: 60_000 }, async () => {
+ const id = "exmplinsur8";
+ const f = insuranceFake({ mainSeconds: 3000, edgeSeconds: 1800, caughtUp: false });
+ const { run } = await incidentRun(id, f.attempt, {
+ request: { insurance: undefined },
+ deps: FAST_INSURE,
+ refresh: { failAfterFirst: `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video` },
+ });
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(s.landed?.seconds, 3000, "the longest lands");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.coverage?.covers, false);
+ const kept = row.keptParts?.find((k) => /ytdlp-insure$/.test(k.stem));
+ assert.ok(kept, "the insurance part is kept");
+ assert.equal(kept!.seconds, 1800);
+ assert.equal(row.needsAttention, true);
+ assert.ok((await readdir(store())).some((n) => n.includes(".ytdlp-insure.")), "its file is still on disk");
+});
+
+test("slice 4: the insurance knob is parsed and asked again by Record again", { timeout: 60_000 }, async () => {
+ const { recordAgainRequest } = await import("./recordLive");
+ const ok = parseRecordLiveRequest({ slug: "s", url: "https://www.youtube.com/watch?v=exmplknob01", insurance: "whole" });
+ assert.equal((ok as { insurance?: unknown }).insurance, "whole");
+ assert.match((parseRecordLiveRequest({ slug: "s", url: "https://www.youtube.com/watch?v=exmplknob01", insurance: "yes" }) as { error: string }).error, /insurance/);
+ assert.deepEqual(recordAgainRequest({ slug: "s", insurance: false } as never), { insurance: false });
+});
+
+// --- SLICE 5: parts joined into one file, proven or not at all ---------------------
+//
+// A fake "media" file here also says where it sits in the stream and what it
+// sounds like (`stream=<s>;seed=<k>`): the fake decode hands back that sound,
+// a deterministic noise of the stream's own sample index, so the real
+// alignment (lib/recordingClock.mjs locate) finds parts by their sound. The
+// fake cut starts at the keyframe at or before the cut (every 2 s); the fake
+// concat writes the segments it was given (or, `drop`, loses the last).
+
+const noiseAt = (seed: number, n: number) => {
+ let x = (Math.imul(n, 2654435761) + Math.imul(seed + 1, 40503)) >>> 0;
+ x ^= x >>> 13;
+ x = Math.imul(x, 0x5bd1e995) >>> 0;
+ x ^= x >>> 15;
+ return x / 4294967296 - 0.5;
+};
+// `vseed`: what its picture shows (default: the same as its sound).
+type FakeSeg = { stream: number; seconds: number; seed: number; vseed: number };
+const readFake = async (file: string): Promise<FakeSeg[]> => {
+ const t = await readFile(file, "utf8").catch(() => "");
+ const segs = /segs=([^;]+)/.exec(t);
+ if (segs) return segs[1]!.split(",").map((x) => { const [s, l, k, v] = x.split(":").map(Number); return { stream: s!, seconds: l!, seed: k!, vseed: v ?? k! }; });
+ const num = (k: string, d: number) => Number(new RegExp(`(?:^|;)${k}=([\\d.]+)`).exec(t)?.[1] ?? d);
+ const seed = num("seed", 0);
+ return [{ stream: num("stream", 0), seconds: num("seconds", 0), seed, vseed: num("vseed", seed) }];
+};
+function fakeJoinDeps(
+ o: { drop?: boolean; cutLate?: boolean; cutThrows?: boolean; garblePicture?: boolean; staticPicture?: boolean; ptsJump?: boolean; noTimestamps?: boolean } = {},
+) {
+ return {
+ // The packets' timestamps of [from, from + seconds) of the file: video at
+ // 5 frames a second, audio every 0.02 s, continuous across segments
+ // (`ptsJump`: a 2 s jump at each segment boundary).
+ timestamps: async (file: string, from: number, seconds: number) => {
+ if (o.noTimestamps) return null;
+ const segs = await readFake(file);
+ const bounds: number[] = [];
+ let acc = 0;
+ for (const g of segs) bounds.push((acc += g.seconds));
+ const shift = (t: number) => (o.ptsJump ? bounds.slice(0, -1).filter((b) => t >= b).length * 2 : 0);
+ const at = (step: number) => {
+ const out: number[] = [];
+ for (let t = Math.ceil(from / step) * step; t < from + seconds; t += step) out.push(Math.round((t + shift(t)) * 1000) / 1000);
+ return out;
+ };
+ return { video: at(0.2), audio: at(0.02) };
+ },
+ // A 32-byte "frame" of the picture at that second (5 frames a second).
+ frame: async (file: string, at: number) => {
+ if (o.staticPicture) return new Uint8Array(32).fill(16);
+ const segs = await readFake(file);
+ let t = at;
+ for (const g of segs) {
+ if (t < g.seconds) {
+ const f = Math.floor((g.stream + t) * 5);
+ return Uint8Array.from({ length: 32 }, (_, i) => Math.floor((noiseAt(g.vseed + 1000, f * 32 + i) + 0.5) * 255));
+ }
+ t -= g.seconds;
+ }
+ return null;
+ },
+ decode: async (file: string, from: number, seconds: number, rate: number) => {
+ const segs = await readFake(file);
+ const out = new Float32Array(Math.round(seconds * rate));
+ for (let i = 0; i < out.length; i++) {
+ let t = from + i / rate;
+ for (const g of segs) {
+ if (t < g.seconds) {
+ out[i] = noiseAt(g.seed, Math.round((g.stream + t) * rate));
+ break;
+ }
+ t -= g.seconds;
+ }
+ }
+ return out;
+ },
+ cut: async (file: string, from: number, out: string) => {
+ const [g] = await readFake(file);
+ // A late cut: the stream copy starts after the point asked (a hole).
+ const real = o.cutLate ? Math.ceil(from) + 2 : Math.floor(from / 2) * 2;
+ await writeFile(out, `format=mov,mp4;seconds=${g!.seconds - real};stream=${g!.stream + real};seed=${g!.seed};vseed=${g!.vseed};`);
+ if (o.cutThrows) throw new Error("No space left on device");
+ return real;
+ },
+ concat: async (files: string[], out: string) => {
+ const all = (await Promise.all(files.map(readFake))).flat();
+ const kept = o.drop ? all.slice(0, -1) : all;
+ const total = kept.reduce((n, g) => n + g.seconds, 0);
+ // garblePicture: the joined file's picture after the first segment is
+ // not the segment's (its sound is).
+ await writeFile(
+ out,
+ `format=matroska;seconds=${total};segs=${kept.map((g, i) => `${g.stream}:${g.seconds}:${g.seed}:${o.garblePicture && i > 0 ? g.vseed + 1 : g.vseed}`).join(",")};`,
+ );
+ },
+ probe: async (file: string) => {
+ const t = await readFile(file, "utf8").catch(() => "");
+ if (!/format=/.test(t)) return null;
+ const segs = await readFake(file);
+ return { seconds: segs.reduce((n, g) => n + g.seconds, 0), videoCodec: "h264", audioCodec: "aac", width: 1280, height: 720, sampleRate: 48000, channels: 2 };
+ },
+ };
+}
+
+// An earlier run left a from-start part (stream 0–3000 s) and a live-edge part
+// whose recorder started `edgeClock` s into the stream and whose sound begins
+// at `edgeStream` (the live edge lags the clock); the stream has ended; the
+// boot pass's restart lands what is in staging.
+async function joinCase(
+ id: string,
+ o: {
+ edgeClock: number;
+ edgeStream: number;
+ edgeSeconds: number;
+ edgeSeed?: number;
+ edgeVseed?: number;
+ duration?: number;
+ deps?: ReturnType<typeof fakeJoinDeps>;
+ signal?: AbortSignal;
+ shuttingDown?: boolean;
+ before?: () => Promise<void>;
+ refresh?: Parameters<typeof refreshWith>[1];
+ extraDeps?: Record<string, unknown>;
+ },
+) {
+ const S0 = 1_790_000_000;
+ const iso = (sec: number) => new Date((S0 + sec) * 1000).toISOString();
+ const runAt = iso(0);
+ const stamp = runAt.replace(/[:.]/g, "-");
+ const a = `.${id}.live-${stamp}.ytdlp`;
+ const b = `.${id}.live-${stamp}.ytdlp-edge-a4`;
+ await mkdir(store(), { recursive: true });
+ await writeFile(path.join(store(), `${a}.mp4`), "format=mov,mp4;seconds=3000;stream=0;seed=7;");
+ await writeFile(
+ path.join(store(), `${b}.mp4`),
+ `format=mov,mp4;seconds=${o.edgeSeconds};stream=${o.edgeStream};seed=${o.edgeSeed ?? 7};${o.edgeVseed !== undefined ? `vseed=${o.edgeVseed};` : ""}`,
+ );
+ const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await ytChannel();
+ await upsertLiveRecordingRow(paths, YT_SLUG, {
+ id,
+ url: ytUrl(id),
+ platform: "youtube",
+ startedAt: runAt,
+ endedAt: iso(o.edgeClock + o.edgeSeconds),
+ status: "interrupted",
+ stoppedBy: "shutdown",
+ fromStart: true,
+ attempts: 2,
+ mustKeep: true,
+ streamStartedAt: iso(0),
+ parts: [
+ { method: "ytdlp", url: ytUrl(id), fromStart: true, provenStart: true, startedAt: iso(1), stem: a },
+ { method: "ytdlp", url: ytUrl(id), fromStart: false, startedAt: iso(o.edgeClock), stem: b },
+ ],
+ restart: { at: iso(9000), by: "boot", state: "asked" },
+ });
+ await o.before?.();
+ return incidentRun(id, writesAfter(0), {
+ request: { resumeOf: runAt },
+ meta: { ...YT_META(id), live_status: "was_live", release_timestamp: S0, ...(o.duration ? { duration: o.duration } : {}) },
+ ...(o.signal ? { signal: o.signal } : {}),
+ ...(o.refresh ? { refresh: o.refresh } : {}),
+ deps: { join: o.deps ?? fakeJoinDeps(), ...(o.shuttingDown ? { shuttingDown: () => true } : {}), ...(o.extraDeps ?? {}) },
+ });
+}
+const left = async (id: string) => (await readdir(store())).filter((n) => n.startsWith(`.${id}.`));
+
+test("slice 5: an overlap found by its sound — the two parts joined at it, proven, landed whole; both parts removed only after, the joins recorded", async () => {
+ const id = "exmpljoin01";
+ // The live edge started 20 s behind the clock, at stream second 2401.
+ const { run, calls, log } = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 3000, duration: 5401 });
+ const s = await run;
+ assert.equal(calls.length, 0);
+ assert.equal(s.status, "landed");
+ assert.ok(log.some((l) => /Joined 2 parts/.test(l)), log.filter((l) => /join/i.test(l)).join(""));
+ // 3000 s of the first, then the second from its keyframe at 598 s.
+ assert.equal(s.landed?.seconds, 3000 + (3000 - 598));
+ const row = (await rowOf(id)).find((r) => r.resumeOf)!;
+ assert.equal(row.joins?.length, 1);
+ const j = row.joins![0]!;
+ assert.equal(j.kind, "overlap");
+ assert.equal(j.basis, "content");
+ assert.equal(j.at, 3000);
+ assert.equal(j.seconds, 599, "the overlap, found by sound (the clock said 579)");
+ assert.equal(j.duplicatedSeconds, 1, "the cut starts a keyframe early");
+ assert.equal(j.cutAt, 599, "where the second part was asked to start");
+ assert.equal(j.cutFrom, 598, "where its copy really starts");
+ assert.equal(row.coverage?.covers, true);
+ assert.equal(row.removedParts?.length, 2);
+ assert.ok(row.removedParts!.every((r) => /inside the joined file/.test(r.why)));
+ assert.deepEqual(await left(id), [], "nothing left in staging: the joined file landed, its parts went after");
+ assert.equal(row.needsAttention, false);
+ const { liveJoinsSidecar } = await import("../lib/mediaImport-server");
+ const side = await liveJoinsSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id));
+ assert.equal(side?.segments.length, 2);
+ assert.deepEqual(
+ side!.segments.map((g) => [g.streamFrom, g.streamFromBasis, g.fileFrom, g.joinedFrom, g.joinedTo]),
+ [
+ [0, "start", 0, 0, 3000],
+ [2401, "content", 598, 3000, 5402],
+ ],
+ );
+});
+
+test("slice 5: a gap — joined as they are, the gap stated by the clock, never covering; the row needs a person", async () => {
+ const id = "exmpljoin02";
+ const { run } = await joinCase(id, { edgeClock: 3600, edgeStream: 3600, edgeSeconds: 1800, duration: 5400 });
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(s.landed?.seconds, 4800);
+ const row = (await rowOf(id)).find((r) => r.resumeOf)!;
+ assert.equal(row.joins?.[0]?.kind, "gap");
+ assert.equal(row.joins?.[0]?.basis, "clock");
+ assert.equal(row.joins?.[0]?.seconds, 600);
+ assert.equal(row.coverage?.covers, false, "a gap never holds the whole stream");
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /GAP of about 10 min/);
+ const { liveJoinsSidecar } = await import("../lib/mediaImport-server");
+ const side = await liveJoinsSidecar.load(path.join(CORPUS, "channels", YT_SLUG, "data", id));
+ assert.deepEqual(side!.segments[1], { stem: side!.segments[1]!.stem, streamFrom: 3600, streamFromBasis: "clock", fileFrom: 0, fileTo: 1800, joinedFrom: 3000, joinedTo: 4800 });
+});
+
+test("slice 5: an unprovable join — the sound does not match, or the joined file is not what it should be — lands the longest and keeps the rest", async () => {
+ // (a) The live-edge part's sound is not the stream the first part holds.
+ const id = "exmpljoin03";
+ const a = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, edgeSeed: 99, duration: 5301 });
+ const s = await a.run;
+ assert.equal(s.landed?.seconds, 3000, "the longest");
+ assert.ok(a.log.some((l) => /Not joined/.test(l)));
+ const row = (await rowOf(id)).find((r) => r.resumeOf)!;
+ assert.equal(row.joins, undefined);
+ assert.equal(row.keptParts?.length, 1, "the other part is kept");
+ assert.equal(row.needsAttention, true);
+ const files = await left(id);
+ assert.equal(files.length, 1);
+ assert.match(files[0]!, /ytdlp-edge-a4\.mp4$/, "no joined or scratch file is left");
+
+ // (b) The joined file lost a segment: its length is not its parts' — not proven.
+ const id2 = "exmpljoin04";
+ const b = await joinCase(id2, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ drop: true }) });
+ const s2 = await b.run;
+ assert.equal(s2.landed?.seconds, 3000);
+ assert.ok(b.log.some((l) => /not proven/.test(l)));
+ const row2 = (await rowOf(id2)).find((r) => r.resumeOf)!;
+ assert.equal(row2.keptParts?.length, 1);
+ assert.deepEqual((await left(id2)).map((n) => /ytdlp-edge-a4\.mp4$/.test(n)), [true]);
+});
+
+test("slice 3 / DESIGN-5 1: attempts that each record only one of the two streams — while the stream reads live the recording goes on past the schedule (never ended quietly); when it ends, the row is loud about the missing stream", async () => {
+ const id = "exmplpart02";
+ let n = 0;
+ const videoOnly: Attempt = async (args) => {
+ n++;
+ await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=45;a=none;");
+ return { exitCode: 1, stderrTail: "2: ERROR: The downloaded file is empty\n", signalled: false };
+ };
+ const { run, calls } = await incidentRun(id, videoOnly, { deps: { ...FAST_WATCH, freshFromStart: false }, refresh: { stillLive: () => n < 9 } });
+ await run.catch(() => {});
+ assert.ok(calls.length > 6, `restarted past the schedule while live: ${calls.length}`);
+ const row = (await rowOf(id))[0]!;
+ assert.ok((row.restarts?.count ?? 0) > 0);
+ assert.equal(row.needsAttention, true);
+});
+
+// --- REVIEW-1 of live-guard-2: the store, containment, and the join's proof --------
+//
+// A container already in the store is never deleted around or replaced by a
+// part that is not proven to hold it; a part is removed only when THIS landing
+// stored and verified a file that holds it.
const dataDir = (id: string) => path.join(CORPUS, "channels", YT_SLUG, "data", id);
const storedSeconds = async (id: string): Promise<number | null> => {
@@ -1166,19 +2006,17 @@ const storedSeconds = async (id: string): Promise<number | null> => {
return p ? ((await fakeProbe(savedVideoPath(p)))?.seconds ?? null) : null;
};
const okExit = { exitCode: 0, stderrTail: "", signalled: false };
-const failEmpty = { exitCode: 1, stderrTail: EMPTY, signalled: false };
-const left = async (id: string) => (await readdir(store()).catch(() => [] as string[])).filter((n) => n.startsWith(`.${id}.`));
// Run 1: `seconds` from its start, landed by an editor shutdown.
async function landedAtShutdown(id: string, seconds: number, request: Record<string, unknown> = {}) {
const ac = new AbortController();
const r = await incidentRun(
id,
async (args) => {
- await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`);
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};stream=0;seed=7;`);
ac.abort();
return { exitCode: null, stderrTail: "", signalled: true };
},
- { signal: ac.signal, request, deps: { shuttingDown: () => true } },
+ { signal: ac.signal, request, deps: { shuttingDown: () => true, join: null } },
);
assert.equal((await r.run).status, "interrupted");
assert.equal(await storedSeconds(id), seconds);
@@ -1226,27 +2064,1071 @@ test("landing 1.1: when the landing keeps the container already in the store, NO
assert.equal(row.needsAttention, true);
});
-test("landing: an index-0 part is not 'inside' a longer index-0 part of the run (a sliding window): kept", async () => {
- const id = "exmpllfidx1";
- const UNSUPPORTED = "ERROR: [youtube] x: --live-from-start is passed, but there are no formats that can be downloaded from the start\n";
- const { run } = await incidentRun(id, async (args, n) => {
- if (n === 1) return { exitCode: 1, stderrTail: UNSUPPORTED, signalled: false };
- if (n === 2) {
- // Audio only, then the video stream failed: retried.
- await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=300;v=none;");
- return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false };
- }
- await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
- return okExit;
+test("REVIEW 1.1(c): a joined file the store's longer container is kept over is not removed, nor are its parts", { timeout: 60_000 }, async () => {
+ const id = "exmpljoin05";
+ const r = await joinCase(id, {
+ edgeClock: 2421,
+ edgeStream: 2401,
+ edgeSeconds: 3000,
+ duration: 5401,
+ before: async () => {
+ // The store already holds a longer recording (by another way).
+ const { landMediaFile } = await import("./landMedia");
+ await mkdir(dataDir(id), { recursive: true });
+ await writeFile(path.join(dataDir(id), "metadata.info.json"), JSON.stringify(YT_META(id)));
+ const src = path.join(ROOT, `${id}-stored.mp4`);
+ await writeFile(src, "format=mov,mp4;seconds=10800;");
+ await landMediaFile({ paths, slug: YT_SLUG, channelConfig: YT_CONFIG, videoId: id, sourcePath: src, via: "record-live", move: true, onLog: () => {}, signal: new AbortController().signal, deps: land });
+ },
});
+ await assert.rejects(r.run, /not landed/);
+ assert.equal(await storedSeconds(id), 10800);
+ const files = await left(id);
+ assert.ok(files.some((n) => /\.joined\.mkv$/.test(n)), `the joined file is kept: ${files.join(", ")}`);
+ assert.ok(files.some((n) => /\.ytdlp\.mp4$/.test(n)) && files.some((n) => /ytdlp-edge-a4\.mp4$/.test(n)), "its parts are kept");
+ const row = (await rowOf(id)).find((x) => x.resumeOf)!;
+ assert.equal(row.removedParts, undefined);
+ assert.equal(row.needsAttention, true);
+});
+
+test("REVIEW 1.4: a restart's earlier sibling from its start is not removed on the strength of index 0 — only the coverage rule removes it", { timeout: 60_000 }, async () => {
+ const id = "exmplrv1401";
+ let live = true;
+ const hang = hangAfter(300);
+ const { run } = await incidentRun(
+ id,
+ async (args, n, signal) => {
+ if (n === 1) return hang(args, n, signal);
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=5000;");
+ live = false;
+ return okExit;
+ },
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
assert.equal((await run).status, "landed");
- assert.ok((await left(id)).some((n) => /\.f140\.m4a$/.test(n)), "the earlier index-0 part is kept");
const row = (await rowOf(id))[0]!;
- assert.ok(row.keptParts?.length);
+ assert.equal(row.coverage?.covers, false);
+ assert.ok(row.keptParts?.some((k) => /\.ytdlp$/.test(k.stem)), "the stalled first part is kept");
+ assert.ok((await left(id)).some((n) => /\.ytdlp\.mp4$/.test(n)));
});
-test("landing: a live-edge part goes only when the landed file is from the start and as long as the ended stream's own duration less a minute", async () => {
- const KICK = { handling: "transcribe", url: "https://kick.com/synthc/videos", platform: "kick", name: "Synth Kick C" } as ChannelConfig;
+test("REVIEW 1.7: no join during a shutdown's landing — the longest lands, the rest are kept", { timeout: 60_000 }, async () => {
+ const id = "exmpljoin06";
+ const ac = new AbortController();
+ let calls = 0;
+ const deps = fakeJoinDeps();
+ const counted = { ...deps, decode: async (...a: Parameters<typeof deps.decode>) => (calls++, deps.decode(...a)) };
+ const r = await joinCase(id, { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, signal: ac.signal,
+ shuttingDown: true,
+ deps: counted,
+ // The shutdown comes as the landing begins.
+ extraDeps: { land: { ...land, probe: async (f: string) => (ac.abort(), fakeProbe(f)) } },
+ });
+ const s = await r.run;
+ assert.equal(calls, 0, "the join never ran");
+ assert.equal(s.landed?.seconds, 3000);
+ assert.ok((await left(id)).some((n) => /ytdlp-edge-a4\.mp4$/.test(n)), "the other part is kept");
+});
+
+test("REVIEW 1.5/1.6: the join's proof checks the PICTURE, refuses a cut that starts late (a hole), and leaves no scratch when a tool throws", { timeout: 120_000 }, async () => {
+ // (a) The sound is right but the joined file's picture after the join is
+ // not the second part's.
+ const a = await joinCase("exmpljoin07", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ garblePicture: true }) });
+ await a.run;
+ assert.ok(a.log.some((l) => /Not joined/.test(l) && /picture/.test(l)), a.log.filter((l) => /join/i.test(l)).join(""));
+ assert.equal((await rowOf("exmpljoin07")).find((r) => r.resumeOf)!.keptParts?.length, 1);
+ // (b) The stream copy starts after the cut point: seconds in neither part.
+ const b = await joinCase("exmpljoin08", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ cutLate: true }) });
+ await b.run;
+ assert.ok(b.log.some((l) => /Not joined/.test(l) && /hole/.test(l)));
+ // (c) The cut throws (a full disk): the scratch it wrote is gone, the longest lands, the rest kept.
+ const c = await joinCase("exmpljoin09", { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301, deps: fakeJoinDeps({ cutThrows: true }) });
+ const sc = await c.run;
+ assert.equal(sc.landed?.seconds, 3000);
+ const files = await left("exmpljoin09");
+ assert.deepEqual(files.filter((n) => /\.temp\./.test(n)), [], `no scratch left: ${files.join(", ")}`);
+ assert.equal(files.length, 1);
+});
+
+// --- REVIEW-1 of live-guard-2: the restarts' politeness, the passes, the floor -----
+
+test("REVIEW 2.1(a): a restart refused with a 429 gets ONE more after 15 min, then no more", { timeout: 60_000 }, async () => {
+ const id = "exmplrv2101";
+ const { run, calls, waits } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ }
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests\n", signalled: false };
+ },
+ { 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");
+ assert.ok(waits.includes(15 * 60_000));
+ const row = (await rowOf(id))[0]!;
+ assert.match(row.restarts?.refused ?? "", /rate/);
+ assert.equal(row.needsAttention, true);
+});
+
+test("REVIEW 2.1(b): a part that died WITH bytes on a 429 is classified and recorded, and restarted only after 15 min", { timeout: 60_000 }, async () => {
+ const id = "exmplrv2102";
+ let live = true;
+ const { run, calls, waits } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 429: Too Many Requests\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ live = false;
+ return okExit;
+ },
+ { deps: FAST_WATCH, refresh: { stillLive: () => live }, meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 300 }, },
+ );
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 2);
+ assert.ok(waits.includes(15 * 60_000), "the 15 min wait");
+ assert.ok(!waits.includes(30_000), "not the 30 s pause");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.parts[0]!.failureClass, "rate-limited");
+ assert.match(row.parts[0]!.error ?? "", /429/);
+});
+
+test("REVIEW 2.3: the free-space floor is read before a start-recovery try and the insurance start; a spawn that would breach it does not start, and the row says so", { timeout: 60_000 }, async () => {
+ // A recovery try with no room: the disk is full after the run's start.
+ let reads = 0;
+ const r = await incidentRun(
+ "exmplrv2301",
+ async (args, n) => {
+ if (n <= 3) return failEmpty;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
+ await new Promise((res) => setTimeout(res, 100));
+ return okExit;
+ },
+ { recovery: "immediate", deps: { freeBytes: async () => (++reads >= 2 ? 0 : 1e15) } },
+ );
+ await r.run;
+ assert.equal(r.calls.filter(isRecovery).length, 0, "no recovery try was started");
+ const row = (await rowOf("exmplrv2301"))[0]!;
+ assert.equal(row.startRecovery?.state, "gave-up");
+ assert.equal(row.startRecovery?.failureClass, "disk");
+ assert.ok(row.spaceHeld?.some((x) => /start recovery/.test(x.what)));
+ assert.equal(row.needsAttention, true);
+ // The insurance with no room.
+ let reads2 = 0;
+ const f = insuranceFake({ caughtUp: false });
+ const i = await incidentRun(
+ "exmplrv2302",
+ async (args, n, sig, onLine) =>
+ Promise.race([f.attempt(args, n, sig, onLine), new Promise<typeof okExit>((res) => setTimeout(() => res(okExit), 300))]),
+ { request: { insurance: undefined }, deps: { ...FAST_INSURE, freeBytes: async () => (++reads2 >= 2 ? 0 : 1e15) } },
+ );
+ await i.run;
+ assert.equal(i.calls.filter(isInsurance).length, 0);
+ const row2 = (await rowOf("exmplrv2302"))[0]!;
+ assert.equal(row2.insurance?.state, "not-started");
+ assert.ok(row2.spaceHeld?.some((x) => /insurance/.test(x.what)));
+});
+
+// --- REVIEW-1 of live-guard-2: the insurance that dies, and is re-armed ------------
+
+const until = async (cond: () => boolean, ms = 3000) => {
+ for (let t = 0; t < ms && !cond(); t += 10) await new Promise((r) => setTimeout(r, 10));
+};
+const abortOf = (signal: AbortSignal) => new Promise<void>((r) => (signal.aborted ? r() : signal.addEventListener("abort", () => r(), { once: true })));
+
+test("REVIEW 3.1: an insurance recorder that dies early reads 'died', never 'to the end', and is started again", { timeout: 60_000 }, async () => {
+ const id = "exmplrv3101";
+ let starts = 0;
+ let secondStopped = false;
+ const { run, calls, log } = await incidentRun(
+ id,
+ async (args, _n, signal, onLine) => {
+ if (isInsurance(args)) {
+ starts++;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=120;");
+ if (starts === 1) return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ await abortOf(signal);
+ secondStopped = true;
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ onLine?.("1: [download] 10.0% of ~ 1.20GiB at 2.00MiB/s ETA 10:00 (frag 100/3000)");
+ await until(() => starts >= 2);
+ onLine?.("1: [download] 99.9% of ~ 1.20GiB at 2.00MiB/s ETA 00:01 (frag 2990/3000)");
+ await until(() => secondStopped);
+ return okExit;
+ },
+ { request: { insurance: undefined }, deps: FAST_INSURE },
+ );
+ await run;
+ assert.equal(calls.filter(isInsurance).length, 2, "started again after it died");
+ assert.ok(log.some((l) => /died early/.test(l)));
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.insurance?.starts, 2);
+ assert.equal(row.insurance?.state, "caught-up");
+ assert.ok(!log.some((l) => /recorded the live edge to the end/.test(l)));
+});
+
+test("REVIEW 3.3: an unreadable state at boot is read three times over about ten minutes; read live, it records; never readable, the row says the stream may be live and unrecorded", { timeout: 60_000 }, async () => {
+ const t0 = "2026-11-21T08:00:00.000Z";
+ // Read on the third try: it records.
+ const a = "exmplrv3301";
+ await interruptedRow(a, t0);
+ const ra = await incidentRun(a, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1, 2] } });
+ assert.equal((await ra.run).status, "landed");
+ assert.equal(ra.calls.length, 1);
+ assert.deepEqual(ra.waits.slice(0, 2), [120_000, 480_000]);
+ assert.equal((await oldRow(a, t0)).restart?.state, "restarted");
+ // Never read.
+ const b = "exmplrv3302";
+ await interruptedRow(b, t0);
+ const rb = await incidentRun(b, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1, 2, 3] } });
+ await assert.rejects(rb.run);
+ assert.equal(rb.calls.length, 0);
+ assert.deepEqual(rb.waits, [120_000, 480_000]);
+ const ob = await oldRow(b, t0);
+ assert.equal(ob.restart?.state, "unknown");
+ assert.match(ob.restart?.reason ?? "", /3 reads failed.*may still be live and is NOT being recorded/);
+ assert.equal(ob.needsAttention, true);
+ // A rate limit is not read again.
+ const c = "exmplrv3303";
+ await interruptedRow(c, t0);
+ const rc = await incidentRun(c, writesAfter(0), { request: { resumeOf: t0 }, refresh: { failReads: [1], failWith: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests" } });
+ await assert.rejects(rc.run);
+ assert.deepEqual(rc.waits, []);
+});
+
+// --- REVIEW-2 of live-guard-2: a stream that reads live is never left unrecorded quietly --
+//
+// A recorder that exits or stalls while an earlier part holds the past is
+// restarted at the LIVE EDGE (its own stem; the earlier part kept); the
+// stream is taken as ended only on evidence: the state read says so, or three
+// live-edge recorders in a row capture nothing.
+
+const isEdge = (args: string[]) => !fromStartArg(args);
+
+test("REVIEW2 3.1: a caught-up from-start recorder that exits while the stream reads live is restarted at the live edge, never landed quietly", { timeout: 60_000 }, async () => {
+ const id = "exmplr2a301";
+ let live = true;
+ const { run, calls } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=900;");
+ live = false;
+ return okExit;
+ },
+ { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await run;
+ assert.equal(calls.length, 2, "restarted");
+ assert.ok(isEdge(calls[1]!), "at the live edge: the past is held by the first part");
+ assert.ok((await left(id)).some((n) => /\.ytdlp-r1\.mp4$/.test(n)) || (await rowOf(id))[0]!.parts.some((p) => p.restart === 1));
+});
+
+test("REVIEW2 3.2: a second and a third death while the stream reads live restart again, at the live edge; when the bounds are spent the row says the stream is live and unrecorded", { timeout: 60_000 }, async () => {
+ const id = "exmplr2a302";
+ let live = true;
+ const deaths = { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ const a = await incidentRun(
+ id,
+ async (args, n) => {
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${n === 1 ? 3000 : 400};`);
+ if (n === 3) live = false;
+ return n === 3 ? okExit : deaths;
+ },
+ { 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");
+ assert.ok(a.calls.slice(1).every(isEdge), "every restart at the live edge");
+ // Dying again and again while live: the hour's bound is waited out (said),
+ // and it goes on until the stream ends (REVIEW-5 note 3).
+ const id2 = "exmplr2a303";
+ let k = 0;
+ const b = await incidentRun(
+ id2,
+ async (args) => {
+ k++;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ return deaths;
+ },
+ { 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}`);
+ const row = (await rowOf(id2))[0]!;
+ assert.equal(row.restarts?.refused, undefined);
+ assert.ok((row.restarts?.waited ?? 0) >= 1, "the row says it waited");
+});
+
+test("REVIEW2 3.1: three live-edge recorders in a row that capture nothing are the evidence the stream ended; still reading live, the row is loud", { timeout: 60_000 }, async () => {
+ const id = "exmplr2a304";
+ const { run, calls } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3000;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ }
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ },
+ { 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");
+ const row = (await rowOf(id))[0]!;
+ assert.match(row.restarts?.refused ?? "", /three live-edge recorders in a row captured nothing/);
+ assert.equal(row.needsAttention, true);
+});
+
+test("REVIEW2 3.3: the class is read from the recorder's last output — a 429 retried an hour ago does not delay a normal end; ended/private text is checked by a state read", { timeout: 60_000 }, async () => {
+ // (a) A stale 429, then fragments, then the normal end.
+ const a = await incidentRun(
+ "exmplr2a305",
+ async (args) => {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
+ return {
+ exitCode: 1,
+ stderrTail: "ERROR: [download] Got error: HTTP Error 429: Too Many Requests\n[download] 40.0% (frag 400/1000)\n[download] 100.0% (frag 1000/1000)\nERROR: fragment 1001 not found\n",
+ signalled: false,
+ };
+ },
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge } },
+ );
+ assert.equal((await a.run).status, "landed");
+ assert.ok(!a.waits.includes(15 * 60_000), "no 15 min wait for an old 429");
+ // (b) "Private video" with bytes, but the stream reads live: restarted.
+ let live = true;
+ const b = await incidentRun(
+ "exmplr2a306",
+ async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3000;");
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Private video. Sign in if you've been granted access\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ live = false;
+ return okExit;
+ },
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live }, meta: { ...YT_META("exmplr2a306"), release_timestamp: Math.floor(Date.now() / 1000) - 3000 } },
+ );
+ await b.run;
+ assert.equal(b.calls.length, 2, "the state was read, it is live: restarted");
+});
+
+test("REVIEW2 3.4: the floor before a spawn is max(the floor, twice the largest part so far)", { timeout: 60_000 }, async () => {
+ const id = "exmplr2a307";
+ const { run, calls } = await incidentRun(
+ id,
+ async (args) => {
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=3000;${"x".repeat(2000)}`);
+ return { exitCode: 1, stderrTail: "ERROR: Connection reset by peer\n", signalled: false };
+ },
+ // A floor of 1 kB; 3 kB free; the part is ~2 kB: twice it is not there.
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 3000 }, refresh: { stillLive: () => true } },
+ );
+ await run;
+ assert.equal(calls.length, 1, "no restart: twice the largest part is not free");
+ const row = (await rowOf(id))[0]!;
+ assert.ok(row.spaceHeld?.length);
+ assert.equal(row.needsAttention, true);
+});
+
+test("REVIEW2 4.1: the insurance on a rate limit: ONE retry after 15 min, then stop", { timeout: 60_000 }, async () => {
+ const id = "exmplr2a308";
+ let insurers = 0;
+ const { run, waits } = await incidentRun(
+ id,
+ async (args) => {
+ if (isInsurance(args)) {
+ insurers++;
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] x: HTTP Error 429: Too Many Requests\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ await until(() => insurers >= 3, 1500);
+ return okExit;
+ },
+ { request: { insurance: undefined }, deps: { ...FAST_INSURE, join: null } },
+ );
+ await run;
+ assert.equal(insurers, 2, "the first and one retry");
+ assert.ok(waits.includes(15 * 60_000));
+ const row = (await rowOf(id))[0]!;
+ assert.match(row.insurance?.reason ?? "", /rate/);
+});
+
+test("REVIEW2 1.1: a part holding the stream's end is kept by its place on the stream's clock, not by wall-clock ends; never removed on a clock-basis coverage", { timeout: 60_000 }, async () => {
+ // The main from-start part (7140 s) and the insurance end together; the
+ // stream's own duration is 7200 s: 7140 + 72 covers by the tolerance, but
+ // the insurance (from stream second 6000, 1210 s) reaches 7210.
+ const id = "exmplr2a309";
+ const start = Math.floor(Date.now() / 1000) - 7200;
+ let insStarted = false;
+ const { run } = await incidentRun(
+ id,
+ async (args, _n, signal) => {
+ if (isInsurance(args)) {
+ insStarted = true;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=1210;");
+ await abortOf(signal);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7140;");
+ await until(() => insStarted);
+ return okExit;
+ },
+ {
+ request: { insurance: true },
+ meta: { ...YT_META(id), release_timestamp: start },
+ deps: { ...FAST_INSURE, join: null },
+ refresh: {},
+ },
+ );
+ // The ended stream says 7200 s; its insurance part started 6000 s in.
+ const rows = await rowOf(id);
+ void rows;
+ await run;
+ const row = (await rowOf(id))[0]!;
+ const ins = row.parts.find((p) => p.insurance)!;
+ assert.ok(ins, "the insurance ran");
+ assert.ok(row.keptParts?.some((k) => /ytdlp-insure$/.test(k.stem)), "kept: it may hold the end");
+});
+
+test("REVIEW2 2.1: the join's picture proof compares the two SOURCE parts across the overlap; on a static scene the timestamps' continuity decides; neither, no join", { timeout: 120_000 }, async () => {
+ const base = { edgeClock: 2421, edgeStream: 2401, edgeSeconds: 2900, duration: 5301 };
+ // (a) The second part's picture is another moment than the first's at the same stream time.
+ const a = await joinCase("exmplr2j101", { ...base, edgeVseed: 55 });
+ await a.run;
+ assert.ok(a.log.some((l) => /Not joined/.test(l) && /picture/.test(l)), a.log.filter((l) => /join/i.test(l)).join(""));
+ // (b) A static scene, the timestamps continuous: joined.
+ const b = await joinCase("exmplr2j102", { ...base, deps: fakeJoinDeps({ staticPicture: true }) });
+ await b.run;
+ assert.ok(b.log.some((l) => /Joined 2 parts/.test(l)), b.log.filter((l) => /join/i.test(l)).join(""));
+ // (c) A static scene and a jump in the timestamps at the join: no join.
+ const c = await joinCase("exmplr2j103", { ...base, deps: fakeJoinDeps({ staticPicture: true, ptsJump: true }) });
+ await c.run;
+ assert.ok(c.log.some((l) => /Not joined/.test(l) && /timestamps/.test(l)));
+ // (d) A static scene and no timestamps to read: neither proof, no join.
+ const d = await joinCase("exmplr2j104", { ...base, deps: fakeJoinDeps({ staticPicture: true, noTimestamps: true }) });
+ await d.run;
+ assert.ok(d.log.some((l) => /Not joined/.test(l)));
+ assert.equal((await rowOf("exmplr2j104")).find((r) => r.resumeOf)!.keptParts?.length, 1);
+});
+
+// --- REVIEW-3 of live-guard-2: no span of a live stream left in no part ----------
+//
+// When a recorder dies or stalls: a live-edge recorder at once, AND, when the
+// kept parts do not reach the live edge, the missing span on the row (loud)
+// and a from-start recovery beside it until a from-start part reaches where
+// the live-edge part begins.
+
+const isRestart = (args: string[]) => /\.ytdlp-r\d+$/.test(outOf(args));
+const hoursAgo = (h: number) => Math.floor(Date.now() / 1000) - h * 3600;
+
+test("REVIEW3 3.1: the 20 Nov shape — from its start dies a minute in on a stream 5 h old: the live edge at once, the span said lost, and a from-start recovery beside it until it reaches the live edge", { timeout: 60_000 }, async () => {
+ const id = "exmplr3a301";
+ let live = true;
+ let recovered = false;
+ let fromStartActive = 0;
+ let maxFromStart = 0;
+ let lostSeen: unknown = null;
+ const { run, calls } = await incidentRun(
+ id,
+ async (args, n, signal) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=60;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ }
+ if (isRecovery(args)) {
+ fromStartActive++;
+ maxFromStart = Math.max(maxFromStart, fromStartActive);
+ lostSeen = (await liveRecordingSidecar.load(dataDir(id)))?.lost ?? null;
+ // It catches up past where the live-edge part begins, and is stopped there.
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=18100;");
+ await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]);
+ recovered = signal.aborted;
+ fromStartActive--;
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ // The live-edge restart.
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ await until(() => recovered, 3000);
+ live = false;
+ 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, 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");
+ assert.equal(calls.filter(isRecovery).length, 1, "one from-start recovery");
+ assert.equal(maxFromStart, 1, "never two from-start captures at once");
+ assert.ok(lostSeen && (lostSeen as { fromSeconds: number }).fromSeconds === 60, `the span was said lost while it was: ${JSON.stringify(lostSeen)}`);
+ assert.ok(recovered, "the recovery was stopped once it reached the live edge");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.startRecovery?.state, "recovered");
+ assert.doesNotMatch(row.reason, /in no part/);
+});
+
+test("REVIEW3 3.1: a from-start recorder that stalls while 2 h behind: the live edge, the span 3 h-5 h said lost, and a recovery", { timeout: 60_000 }, async () => {
+ const id = "exmplr3a302";
+ let live = true;
+ let recDone = false;
+ const hang = hangAfter(10800);
+ const { run, calls } = await incidentRun(
+ id,
+ async (args, n, signal) => {
+ if (n === 1) return hang(args, n, signal);
+ if (isRecovery(args)) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=18100;");
+ await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]);
+ recDone = true;
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ await until(() => recDone, 3000);
+ live = false;
+ 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, 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");
+ assert.equal(calls.filter(isRecovery).length, 1, "a from-start recovery");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.lost?.fromSeconds, 10800);
+ assert.ok((row.lost?.toSeconds ?? 0) >= 17900);
+});
+
+test("REVIEW3 3.1: a from-start recorder that had caught up needs no recovery: the live edge only, nothing said lost", { timeout: 60_000 }, async () => {
+ const id = "exmplr3a303";
+ let live = true;
+ const { run, calls } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ live = false;
+ return okExit;
+ },
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await run;
+ assert.equal(calls.length, 2);
+ assert.equal(calls.filter(isRecovery).length, 0);
+ assert.equal((await rowOf(id))[0]!.lost, undefined);
+});
+
+test("REVIEW3 3.2: a restart never stops a working insurance recorder", { timeout: 60_000 }, async () => {
+ const id = "exmplr3a304";
+ let live = true;
+ let insStarted = false;
+ let insStoppedBeforeRestart = false;
+ let restarted = false;
+ const { run } = await incidentRun(
+ id,
+ async (args, n, signal) => {
+ if (isInsurance(args)) {
+ insStarted = true;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
+ await abortOf(signal);
+ if (!restarted || live) insStoppedBeforeRestart = true;
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ await until(() => insStarted);
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ }
+ restarted = true;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ await new Promise((r) => setTimeout(r, 200));
+ live = false;
+ return okExit;
+ },
+ { request: { insurance: true }, deps: { ...FAST_INSURE, watchMs: 10, stallMs: 5000, join: null }, refresh: { stillLive: () => live } },
+ );
+ await run;
+ assert.equal(insStoppedBeforeRestart, false, "the insurance ran on through the restart");
+ assert.notEqual((await rowOf(id))[0]!.insurance?.reason, "the run fell back to the live edge");
+});
+
+test("REVIEW3 1.1: a failed state read after an exit never ends the recording: the live edge is restarted meanwhile", { timeout: 60_000 }, async () => {
+ const id = "exmplr3a305";
+ let live = true;
+ const { run, calls } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;");
+ live = false;
+ return okExit;
+ },
+ // The read after the exit fails (the same network drop).
+ { 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");
+ assert.ok(isEdge(calls[1]!));
+});
+
+test("REVIEW3 4.1: a live-edge part goes only when the landed file is the media's own length within a minute of the ended stream's duration", { timeout: 60_000 }, async () => {
+ for (const [id, main, gone] of [
+ ["exmplr3a306", 7140, true],
+ ["exmplr3a307", 7100, false],
+ ] as const) {
+ const f = insuranceFake({ mainSeconds: undefined, edgeSeconds: 30 });
+ void f;
+ let insStarted = false;
+ const { run } = await incidentRun(
+ id,
+ async (args, _n, signal) => {
+ if (isInsurance(args)) {
+ insStarted = true;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=30;");
+ await abortOf(signal);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${main};`);
+ await until(() => insStarted);
+ return okExit;
+ },
+ { request: { insurance: true }, meta: { ...ytLiveMeta(id), duration: 7200 }, deps: { ...FAST_INSURE, join: null } },
+ );
+ await run;
+ const row = (await rowOf(id))[0]!;
+ const kept = row.keptParts?.some((k) => /ytdlp-insure$/.test(k.stem)) ?? false;
+ 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 };
+// Two stream files, as a real separate-streams from-start download has from
+// its first second (dash.py: each opened, its state written, before any
+// fragment): the picture `<out>.f136.mp4`, the sound `<out>.f140.m4a`, each
+// with its own `.ytdl`. A normal end (and SIGINT) merges them into
+// `<out>.mp4` and removes them, as yt-dlp does without `-k`.
+const FAKE_V = "f136.mp4";
+// 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 });
+};
+// Nothing provable to reuse either (DESIGN-5 7): a kept fragment gone.
+const noReuse = async (args: string[]) => rm(`${outOf(args)}.${FAKE_V}-Frag2`, { force: true });
+const fakeMerge = async (args: string[]) => {
+ const ins = args.flatMap((a, k) => (a === "-i" ? [args[k + 1]!] : []));
+ let sec = 0;
+ let bytes = 0;
+ for (const f of ins) {
+ sec = Math.max(sec, (await fakeProbe(f))?.seconds ?? 0);
+ bytes += (await stat(f).catch(() => null))?.size ?? 0;
+ }
+ // (As large as its streams together, as a real merge is.)
+ await writeFile(args[args.length - 1]!, `format=mov,mp4;seconds=${sec};${"x".repeat(bytes)}`);
+};
+function resumableYtdlp(
+ script: (call: {
+ n: number;
+ resumedFrom: number | null;
+ write: (seconds: number) => Promise<void>;
+ writeStream: (kind: "video" | "audio", seconds: number) => Promise<void>;
+ // 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, 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) {
+ 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) => {
+ 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;
+ }
+ // 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)) {
+ // `-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 });
+ }
+ };
+ if (fromStart) {
+ // As measured (LOG, DESIGN-5 point 7): the merged file at its final name
+ // and no state — "has already been downloaded", nothing recorded, exit 0;
+ // stream files with bytes and no state — fragment 1 asked again by
+ // Range, a 416, fatal.
+ const st = await readFile(`${files.video}.ytdl`, "utf8").catch(() => null);
+ if (!st && (await stat(`${out}.mp4`).catch(() => null))) {
+ onLine?.(`[download] ${out}.mp4 has already been downloaded`);
+ return okExit;
+ }
+ if (!st && ((await stat(files.video).catch(() => null))?.size ?? 0) > 0 && resumedFrom === null && count.video === 0 && (await stat(`${files.video}-Frag1`).catch(() => null))) {
+ return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 416: Range Not Satisfiable. Giving up after 10 retries\n", signalled: false };
+ }
+ // REVIEW-6 2, measured against a Range server: a COMPLETE kept fragment
+ // just past the state is asked for by Range past its end — 416, exit 3,
+ // nothing recorded. (A partial one is resumed by Range.)
+ for (const kind of ["video", "audio"] as const) {
+ const next = `${files[kind]}-Frag${count[kind] + 1}`;
+ const have = await readFile(next, "utf8").catch(() => null);
+ if (st && have !== null && have === fragOf(kind, count[kind] + 1)) {
+ return { exitCode: 3, stderrTail: "ERROR: \r[download] Got error: HTTP Error 416: Range Not Satisfiable. Giving up after 10 retries\n", signalled: false };
+ }
+ }
+ }
+ const what = await script({ n, resumedFrom, write, writeStream, tear, print: (l) => onLine?.(l), signal, args });
+ if (what === "die") return { exitCode: 1, stderrTail: "ERROR: [download] Got error: Connection reset by peer\n", signalled: false };
+ if (what === "end") {
+ await finalize();
+ return okExit;
+ }
+ if (what === "hang") {
+ await abortOf(signal);
+ // SIGINT finishes the download (merged, the state gone); SIGTERM leaves it.
+ if (signal.reason === "SIGINT") await finalize();
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ return what;
+ };
+}
+
+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, merge: fakeMerge }, refresh: { stillLive: () => live } });
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 2);
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!), "the same output stem");
+ assert.ok(fromStartArg(calls[1]!), "from its start, resumed");
+ assert.equal(calls[1]![calls[1]!.indexOf("-f") + 1], "136+140", "the format pinned to the ids on disk");
+ 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");
+ 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, merge: fakeMerge }, refresh: { stillLive: () => live } });
+ await run;
+ assert.deepEqual(reasons, ["SIGTERM"], "the watchdog's stop keeps the state");
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place");
+ // 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, merge: fakeMerge } },
+ );
+ 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, merge: fakeMerge, shuttingDown: () => true } },
+ );
+ const s1 = await first.run;
+ assert.equal(s1.status, "interrupted");
+ const stem = outOf(first.calls[0]!);
+ assert.ok((await left(id)).some((n) => n.endsWith(".f136.mp4.ytdl")), "the state survived the shutdown");
+ assert.equal(await storedSeconds(id), null, "nothing landed: the part waits to be resumed");
+ const t0 = (await rowOf(id))[0]!.startedAt;
+ const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ 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, 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]!), 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 dropState(args);
+ await noReuse(args);
+ return "die";
+ }
+ await write(300);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, freshFromStart: false, join: null, merge: fakeMerge }, 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 dropState(args);
+ return "die";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failAfterFirst: PRIVATE } },
+ );
+ await a.run.catch(() => {});
+ assert.ok(a.waits.includes(60_000), "read again a minute later");
+ 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 dropState(args);
+ return "die";
+ }
+ await write(300);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [2], failWith: PRIVATE, stillLive: () => live } },
+ );
+ await b.run;
+ assert.ok(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 dropState(args);
+ await noReuse(args);
+ 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, freshFromStart: false, join: null, merge: fakeMerge }, 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 dropState(args);
+ await noReuse(args);
+ 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, freshFromStart: false, join: null, merge: fakeMerge, 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");
+});
+
+test("landing: an index-0 part is not 'inside' a longer index-0 part of the run (a sliding window): kept", async () => {
+ const id = "exmpllfidx1";
+ const UNSUPPORTED = "ERROR: [youtube] x: --live-from-start is passed, but there are no formats that can be downloaded from the start\n";
+ const { run } = await incidentRun(id, async (args, n) => {
+ if (n === 1) return { exitCode: 1, stderrTail: UNSUPPORTED, signalled: false };
+ if (n === 2) {
+ // Audio only, then the video stream failed: retried.
+ await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=300;v=none;");
+ return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false };
+ }
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
+ return okExit;
+ });
+ assert.equal((await run).status, "landed");
+ assert.ok((await left(id)).some((n) => /\.f140\.m4a$/.test(n)), "the earlier index-0 part is kept");
+ const row = (await rowOf(id))[0]!;
+ assert.ok(row.keptParts?.length);
+});
+
+test("landing: a live-edge part goes only when the landed file is from the start and as long as the ended stream's own duration less a minute", async () => {
+ const KICK = { handling: "transcribe", url: "https://kick.com/synthc/videos", platform: "kick", name: "Synth Kick C" } as ChannelConfig;
const slug = "synth-kick-c";
await mkdir(path.join(CORPUS, "channels", slug, "data"), { recursive: true });
await writeFile(path.join(CORPUS, "channels", slug, "config.json"), JSON.stringify(KICK));
@@ -1260,358 +3142,2099 @@ test("landing: a live-edge part goes only when the landed file is from the start
["01a164b1-0c18-723a-a785-f9637c98bbb3", 10000, 9939, false, 0],
["01a164b1-0c18-723a-a785-f9637c98bbb4", 10000, 9990, false, 40],
] as const) {
- let reads = 0;
- const meta = { id: uuid, extractor: "kick:vod", uploader_id: "synthc", release_timestamp: Math.floor(Date.now() / 1000) - (duration ?? 5000), formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/y/360p30/playlist.m3u8" }] };
- await recordLiveRun({
- paths,
- request: { slug, url: "https://kick.com/synthc" },
- plan: { url: "https://kick.com/synthc", platform: "kick", id: null, kickChannel: "synthc" },
- channelConfig: KICK,
- cookiePolicy: NO_COOKIES,
- onLog: () => {},
- signal: new AbortController().signal,
+ let reads = 0;
+ const meta = { id: uuid, extractor: "kick:vod", uploader_id: "synthc", release_timestamp: Math.floor(Date.now() / 1000) - (duration ?? 5000), formats: [{ protocol: "m3u8_native", height: 360, url: "https://stream.kick.com/y/360p30/playlist.m3u8" }] };
+ await recordLiveRun({
+ paths,
+ request: { slug, url: "https://kick.com/synthc" },
+ plan: { url: "https://kick.com/synthc", platform: "kick", id: null, kickChannel: "synthc" },
+ channelConfig: KICK,
+ cookiePolicy: NO_COOKIES,
+ onLog: () => {},
+ signal: new AbortController().signal,
+ deps: {
+ kickVod: async () => ({ id: uuid, url: `https://kick.com/synthc/videos/${uuid}` }),
+ // Live at the first read; ended (with its duration, when known) after.
+ refresh: async (cwd: string, args: string[]) => {
+ reads++;
+ const o = args[args.indexOf("-o") + 1]!;
+ const m = reads === 1 ? { ...meta, live_status: "is_live" } : { ...meta, live_status: "was_live", ...(duration ? { duration } : {}) };
+ await writeFile(path.join(cwd, path.dirname(o), "metadata.info.json"), JSON.stringify(m));
+ return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
+ },
+ spawn: async ({ args }) => {
+ await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=30;");
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ poll: async (o) => {
+ await writeFile(o.output, `format=mpegts;seconds=${vod};`);
+ return { segments: 500, seconds: vod, gaps: 0, firstSeq, ended: "the VOD has not grown" };
+ },
+ land,
+ ...VERIFY_OK,
+ freeBytes: async () => 1e15,
+ handoff,
+ shuttingDown: () => false,
+ },
+ });
+ const files = (await readdir(path.join(paths.savedVideosDir, slug))).filter((n) => n.startsWith(`.${uuid}.`));
+ assert.equal(files.length === 0, gone, `${uuid}: the channel's live-edge part ${gone ? "goes" : "is kept"}`);
+ const { listLiveRecordings } = await import("./liveRecordings");
+ const row = (await listLiveRecordings(paths, { slug, id: uuid, all: true })).rows[0]!;
+ if (gone) {
+ // (covered (a)'s guarantees: removed, said why, nothing kept, nobody asked.)
+ assert.equal(row.coverage?.covers, true);
+ assert.equal(row.removedParts?.length, 1);
+ assert.match(row.removedParts![0]!.why, /holds the whole stream/);
+ assert.equal(row.keptParts, undefined);
+ assert.equal(row.needsAttention, false);
+ } else {
+ assert.equal(row.keptParts?.length, 1);
+ assert.equal(row.needsAttention, true);
+ }
+ }
+});
+
+// --- REVIEW-LF-1 ------------------------------------------------------------------
+
+// An earlier run's row describing one part of the stream (a leftover in staging).
+async function rowFor(id: string, stem: string, part: Record<string, unknown>) {
+ const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await ytChannel();
+ await upsertLiveRecordingRow(paths, YT_SLUG, {
+ id,
+ url: ytUrl(id),
+ platform: "youtube",
+ startedAt: "2026-11-20T01:00:00.000Z",
+ status: "failed",
+ fromStart: true,
+ attempts: 1,
+ mustKeep: true,
+ parts: [{ method: "ytdlp", url: ytUrl(id), fromStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem, ...part }],
+ } as never);
+}
+const UNSUPPORTED = "ERROR: [youtube] x: --live-from-start is passed, but there are no formats that can be downloaded from the start\n";
+// From its start unsupported: an index-0 part records `seconds`.
+const index0Run = (seconds: number) => async (args: string[], n: number) => {
+ if (n === 1) return { exitCode: 1, stderrTail: UNSUPPORTED, signalled: false };
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`);
+ return okExit;
+};
+
+test("LF finding 1: an index-0 part is not proven from the start — it never replaces a stored container nor removes a proven from-start part, on length alone", async () => {
+ // (a) A stored container from the start; an index-0 run "covers" by length.
+ const a = "exmpllfidx2";
+ await landedAtShutdown(a, 3600);
+ const r = await incidentRun(a, index0Run(7200), { meta: { ...YT_META(a), live_status: "post_live", duration: 7210 } });
+ await assert.rejects(r.run, /not landed/);
+ assert.equal(await storedSeconds(a), 3600, "the stored start stays");
+ // (b) An earlier proven from-start part; an index-0 landing that "covers" leaves it.
+ const b = "exmpllfidx3";
+ const earlier = await leftover(b, 300);
+ await rowFor(b, path.basename(earlier).replace(/\.mp4$/, ""), { provenStart: true });
+ const rb = await incidentRun(b, index0Run(7200), { meta: { ...YT_META(b), live_status: "post_live", duration: 7210 } });
+ assert.equal((await rb.run).status, "landed");
+ assert.ok((await stat(earlier)).size > 0, "the proven from-start part is kept");
+ assert.equal((await rowOf(b)).find((x) => x.status === "landed")!.coverage?.covers, false);
+});
+
+test("LF finding 2: a part holding video is never 'inside' a longer audio-only landed part", async () => {
+ const id = "exmpllfvid1";
+ const ac = new AbortController();
+ const { run } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ // Only its audio stream wrote (3 h of backlog); the video failed.
+ await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=10800;v=none;");
+ return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false };
+ }
+ // Both streams, merged, 1 h — then a Cancel.
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3600;");
+ ac.abort();
+ return { exitCode: null, stderrTail: "", signalled: true };
+ },
+ { signal: ac.signal, request: { doNotClean: false, note: undefined } },
+ );
+ await run;
+ assert.ok((await left(id)).some((n) => /ytdlp-a2\.mp4$/.test(n)), `the only video stays: ${(await left(id)).join(", ")}`);
+});
+
+test("LF note 3: no pointer, but a source-media file in the store: a container is stored (fail closed) — nothing lands over it", async () => {
+ const id = "exmpllfstr1";
+ const { savedVideoDir } = await import("../lib/savedVideo");
+ const dir = savedVideoDir(paths, YT_CONFIG, YT_SLUG, id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "source-media.mp4"), "format=mov,mp4;seconds=9000;");
+ const r = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
+ await assert.rejects(r.run, /not landed/);
+ assert.equal(await readFile(path.join(dir, "source-media.mp4"), "utf8"), "format=mov,mp4;seconds=9000;", "the unnamed container is untouched");
+});
+
+test("LF note 6: a run asked to keep the stream marks it even when nothing landed", async () => {
+ const id = "exmpllfkep1";
+ await landedAtShutdown(id, 3600, { doNotClean: false, note: undefined });
+ assert.equal(await isDoNotClean(dataDir(id)), false);
+ const r = await incidentRun(id, async (args, n) => {
+ if (n <= 3) return failEmpty;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=2000;");
+ return okExit;
+ });
+ await assert.rejects(r.run, /not landed/);
+ assert.equal(await isDoNotClean(dataDir(id)), true);
+});
+
+test("LF note 5: a row's part with no proven-start mark (an older row) is not removed under coverage; marked, it is", async () => {
+ const id = "exmpllfold1";
+ const earlier = await leftover(id, 300);
+ await rowFor(id, path.basename(earlier).replace(/\.mp4$/, ""), {});
+ const r = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
+ assert.equal((await r.run).status, "landed");
+ assert.ok((await stat(earlier)).size > 0, "kept: not proven from its start");
+});
+
+test("LF 9/10: landing 1.1 with a part meant for removal — kept when the store keeps its own", async () => {
+ const id = "exmpllf1102";
+ const one = await incidentRun(id, async (args) => {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7300;");
+ return okExit;
+ });
+ assert.equal((await one.run).status, "landed");
+ const earlier = await leftover(id, 300);
+ await rowFor(id, path.basename(earlier).replace(/\.mp4$/, ""), { provenStart: true });
+ const two = await incidentRun(id, async (args) => {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ return okExit;
+ });
+ await assert.rejects(two.run, /not landed/);
+ assert.ok((await stat(earlier)).size > 0);
+ const row = (await rowOf(id)).find((x) => x.status === "failed" && /not landed/.test(x.error ?? ""))!;
+ assert.ok(row.keptParts?.some((k) => /kept: nothing was landed/.test(k.why)), "the part meant for removal is kept and says so");
+ assert.equal(row.removedParts, undefined);
+});
+
+test("LF 9: with an empty store a short from-start partial lands and does not supersede (2.3's guarantee)", async () => {
+ const id = "exmpllf2301";
+ const first = await incidentRun(id, writesAfter(Infinity));
+ await assert.rejects(first.run);
+ const short = await incidentRun(id, writesAfter(0));
+ assert.equal((await short.run).status, "landed");
+ assert.ok(short.log.some((l) => /does not supersede/.test(l)));
+ const rows = await rowOf(id);
+ assert.equal(rows.find((r) => r.status === "landed")!.coverage?.covers, false);
+ assert.equal(rows.find((r) => r.status === "failed")!.needsAttention, true);
+});
+
+// --- REVIEW-LF-2 ------------------------------------------------------------------
+
+// Rumble: `--live-from-start` is ffmpeg at the DVR playlist's first LISTED
+// segment. A run whose playlist read still lists segment 1 is from the start;
+// one that began after the window slid is not.
+const DVR_SLID = "#EXTM3U\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:151\n#EXTINF:2,\nm_151.ts\n#EXTINF:2,\nm_152.ts\n";
+async function rumbleRun(id: string, o: { dvr: string; seconds: number; duration: number; stop?: "shutdown" }) {
+ const ac = new AbortController();
+ let reads = 0;
+ const meta = { ...RUMBLE_META, id, live_status: "is_live", timestamp: Math.floor(Date.now() / 1000) - o.duration };
+ return recordLiveRun({
+ paths,
+ request: { slug: SLUG, url: `https://rumble.com/${id}-show.html` },
+ plan: { url: `https://rumble.com/${id}-show.html`, platform: "rumble", id },
+ channelConfig: CONFIG,
+ cookiePolicy: NO_COOKIES,
+ onLog: () => {},
+ signal: ac.signal,
+ deps: {
+ refresh: async (cwd: string, args: string[]) => {
+ reads++;
+ const out = args[args.indexOf("-o") + 1]!;
+ const m = reads === 1 ? meta : { ...meta, live_status: "was_live", duration: o.duration };
+ await writeFile(path.join(cwd, path.dirname(out), "metadata.info.json"), JSON.stringify(m));
+ return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
+ },
+ fetchText: async () => o.dvr,
+ spawn: async ({ args }) => {
+ await writeFile(args[args.indexOf("-o") + 1]!, `format=mpegts;seconds=${o.seconds};`);
+ if (o.stop) {
+ ac.abort();
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ return { exitCode: 0, stderrTail: "", signalled: false };
+ },
+ land,
+ ...VERIFY_OK,
+ freeBytes: async () => 1e15,
+ handoff,
+ shuttingDown: () => o.stop === "shutdown",
+ },
+ });
+}
+const rumbleStored = async (id: string) => {
+ const { savedVideoPath } = await import("../lib/savedVideo");
+ const p = await loadSavedVideo(path.join(CORPUS, "channels", SLUG, "data", id));
+ return p ? ((await fakeProbe(savedVideoPath(p)))?.seconds ?? null) : null;
+};
+const rumbleLeft = async (id: string) => (await readdir(path.join(paths.savedVideosDir, SLUG)).catch(() => [] as string[])).filter((n) => n.startsWith(`.${id}.`));
+
+test("LF2 finding 1 (Rumble): a from-start run that began after the DVR window slid is not proven — it never replaces the stored start nor removes run 1's part", async () => {
+ // (a) Run 1 from the true start, landed by a shutdown; run 2 after the slide "covers" by length.
+ const a = "v7lfslid1";
+ await rumbleRun(a, { dvr: DVR, seconds: 3600, duration: 10000, stop: "shutdown" });
+ assert.equal(await rumbleStored(a), 3600);
+ await assert.rejects(rumbleRun(a, { dvr: DVR_SLID, seconds: 9950, duration: 10000 }), /not landed/);
+ assert.equal(await rumbleStored(a), 3600, "the stored start stays");
+ // (b) Run 1's part in staging (its row: proven); run 2 after the slide lands, run 1's part is kept.
+ const b = "v7lfslid2";
+ const stem = `.${b}.live-2026-11-20T01-00-00-000Z.ytdlp`;
+ await mkdir(path.join(paths.savedVideosDir, SLUG), { recursive: true });
+ await writeFile(path.join(paths.savedVideosDir, SLUG, `${stem}.ts`), "format=mpegts;seconds=3600;");
+ const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await upsertLiveRecordingRow(paths, SLUG, {
+ id: b, url: `https://rumble.com/${b}-show.html`, platform: "rumble", startedAt: "2026-11-20T01:00:00.000Z", status: "interrupted",
+ fromStart: true, attempts: 1, mustKeep: false,
+ parts: [{ method: "ytdlp", url: "u", fromStart: true, provenStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem }],
+ } as never);
+ const s = await rumbleRun(b, { dvr: DVR_SLID, seconds: 9950, duration: 10000 });
+ assert.equal(s.status, "landed");
+ assert.ok((await rumbleLeft(b)).some((n) => n === `${stem}.ts`), "run 1's part is kept");
+});
+
+test("LF2 finding 1 (YouTube): a from-start run of a stream older than 120 h is not proven (the generator starts 120 h back)", async () => {
+ const id = "exmpllf120h";
+ await landedAtShutdown(id, 3600);
+ const old = Math.floor(Date.now() / 1000) - 121 * 3600;
+ // 7200 s of a stream whose ended duration is 7210 s: it "covers" and is longer than the stored hour.
+ const r = await incidentRun(
+ id,
+ async (args) => {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ return okExit;
+ },
+ { meta: { ...YT_META(id), release_timestamp: old, live_status: "post_live", duration: 7210 } },
+ );
+ await assert.rejects(r.run, /not landed/);
+ assert.equal(await storedSeconds(id), 3600);
+});
+
+test("LF2 note 3: a pointer whose file is gone is 'stored, unknown' when the store folder holds a source-media file; with the folder empty or absent it is an empty store", async () => {
+ const { savedVideoDir } = await import("../lib/savedVideo");
+ // (a) The pointer names source-media.mp4 (gone); source-media.mkv is there.
+ const a = "exmpllfptr1";
+ await landedAtShutdown(a, 3600);
+ const dirA = savedVideoDir(paths, YT_CONFIG, YT_SLUG, a);
+ const named = (await readdir(dirA)).find((n) => n.startsWith("source-media."))!;
+ await rm(path.join(dirA, named));
+ await writeFile(path.join(dirA, "source-media.mkv"), "format=matroska;seconds=5000;");
+ const ra = await incidentRun(a, writesAfter(0), { meta: { ...YT_META(a), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
+ await assert.rejects(ra.run, /not landed/);
+ assert.ok((await stat(path.join(dirA, "source-media.mkv"))).size > 0);
+ // (b) The pointer names a file that is gone, the folder empty: lands as an empty store.
+ const b = "exmpllfptr2";
+ await landedAtShutdown(b, 3600);
+ const dirB = savedVideoDir(paths, YT_CONFIG, YT_SLUG, b);
+ await rm(dirB, { recursive: true, force: true });
+ const rb = await incidentRun(b, writesAfter(0), { meta: { ...YT_META(b), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
+ assert.equal((await rb.run).status, "landed");
+});
+
+test("LF2 note 4: an audio-only part is not 'inside' a longer part whose own audio may be shorter", async () => {
+ const id = "exmpllfaud1";
+ const ac = new AbortController();
+ const { run } = await incidentRun(
+ id,
+ async (args, n) => {
+ if (n === 1) {
+ // Only its audio (1 h), then the video failed.
+ await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=3600;v=none;");
+ return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false };
+ }
+ // Both, 4 h on the container's length (its audio may be shorter) — a Cancel.
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=14400;");
+ ac.abort();
+ return { exitCode: null, stderrTail: "", signalled: true };
+ },
+ { signal: ac.signal, request: { doNotClean: false, note: undefined } },
+ );
+ await run;
+ assert.ok((await left(id)).some((n) => /\.f140\.m4a$/.test(n)), "the audio-only part is kept");
+});
+
+test("LF2 note 7: with a container stored, a zero-byte file and a fragments-only part's .ytdl are not removed by a run that lands nothing", async () => {
+ const id = "exmpllfg7a1";
+ await landedAtShutdown(id, 3600);
+ await mkdir(store(), { recursive: true });
+ const zero = path.join(store(), `.${id}.live-2026-11-20T02-00-00-000Z.ytdlp.f18.mp4`);
+ await writeFile(zero, "");
+ const frag = `.${id}.live-2026-11-20T03-00-00-000Z.ytdlp.f18.mp4`;
+ await writeFile(path.join(store(), `${frag}-Frag7`), "bytes of a fragment");
+ await writeFile(path.join(store(), `${frag}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: 7 } } }));
+ const r = await incidentRun(id, async (args, n) => {
+ if (n <= 3) return failEmpty;
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=2000;");
+ return okExit;
+ });
+ await assert.rejects(r.run, /not landed/);
+ assert.ok(await stat(zero).then(() => true, () => false), "the zero-byte file stays");
+ assert.ok(await stat(path.join(store(), `${frag}.ytdl`)).then(() => true, () => false), "the .ytdl stays");
+});
+
+test("LF3 note 5: a proven, same-kind, shorter part of this run IS removed after the landing (inside the landed part)", async () => {
+ const id = "exmpllfcon1";
+ // Every attempt writes only its audio (the video fails): the from-start
+ // attempts 100 s, 200 s, 5000 s, the live-edge ones 10 s each.
+ const secs = [100, 200, 5000, 10, 10, 10];
+ const { run } = await incidentRun(
+ id,
+ async (args, n) => {
+ await writeFile(`${outOf(args)}.f140.m4a`, `format=mp4;seconds=${secs[n - 1]};v=none;`);
+ return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false };
+ },
+ { request: { doNotClean: false, note: undefined } },
+ );
+ await run.catch(() => {});
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.parts[row.landedPart ?? -1]?.seconds, 5000, "the longest from-start part landed");
+ const gone = (row.removedParts ?? []).filter((r) => /a shorter part of this run from its start/.test(r.why));
+ assert.equal(gone.length, 2, "the two shorter from-start audio parts are inside it, and go");
+ const files = await left(id);
+ assert.ok(!files.some((n) => /-a2\.f140|ytdlp\.f140/.test(n)), `removed from staging: ${files.join(", ")}`);
+ assert.equal(files.filter((n) => /edge/.test(n)).length, 3, "the live-edge parts (not proven) are kept");
+});
+
+// --- The flows this lane is for (REVIEW-LF-4 notes 2 and 4) ----------------------
+
+const choughOf = (endSeconds: number) => JSON.stringify({ chunk_data: [{ start_time: 0, end_time: 30, text: "hello" }, { start_time: endSeconds - 20, end_time: endSeconds, text: "the last words" }] });
+
+test("flow: an editor shutdown stops a from-start run, the BOOT PASS resumes it in place, the stream ends, ONE whole file lands and nothing is left", { timeout: 60_000 }, async () => {
+ const id = "exmplflowa1";
+ const ac = new AbortController();
+ const first = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, signal }) => {
+ await write(3000);
+ setTimeout(() => ac.abort(), 10);
+ await abortOf(signal);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }),
+ { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } },
+ );
+ assert.equal((await first.run).status, "interrupted");
+ const stem = outOf(first.calls[0]!);
+ const row1 = (await rowOf(id))[0]!;
+ assert.deepEqual(row1.awaitingResume, [path.basename(stem)], "the part waits, with its state, to be resumed");
+ assert.equal(row1.parts[0]!.provenStart, true, "a YouTube from-start part under 120 h old: proven as it was recorded");
+ assert.equal(await storedSeconds(id), null, "nothing landed at the shutdown");
+ // The editor comes back: the boot pass (the real one) restarts the row.
+ await new Promise((r) => setTimeout(r, 20));
+ const { restartInterruptedLiveRecordings } = await import("./liveRecordingBoot");
+ let live = true;
+ let second: Awaited<ReturnType<typeof incidentRun>> | null = null;
+ const outcomes = await restartInterruptedLiveRecordings({
+ paths,
+ bootedAt: Date.now(),
+ isRunning: () => false,
+ orphanLooks: 1,
+ sleep: async () => {},
+ // (The pass walks the whole test corpus: only this test's row is started.)
+ start: async (_slug, body, resumeOf) => {
+ if (body.url !== ytUrl(id)) return { ok: false, error: "another test's row" };
+ second = await incidentRun(
+ id,
+ resumableYtdlp(async ({ resumedFrom, write }) => {
+ assert.equal(resumedFrom, 51, "from the saved fragment");
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { ...body, resumeOf }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ return { ok: true, jobId: "job-boot" };
+ },
+ });
+ assert.deepEqual(outcomes.filter((o) => o.id === id).map((o) => o.state), ["asked"]);
+ const s2 = await second!.run;
+ assert.equal(s2.status, "landed");
+ assert.equal(outOf(second!.calls[0]!), stem, "the same stem, resumed in place");
+ assert.equal(await storedSeconds(id), 7200, "one whole file in the store");
+ assert.deepEqual(await left(id), [], "nothing left in staging: no part, no state");
+ const rows = await rowOf(id);
+ const run2 = rows.find((r) => r.resumeOf)!;
+ assert.equal(run2.parts.length, 1);
+ assert.equal(run2.parts[0]!.provenStart, true, "the resumed part keeps the mark the original run earned");
+ assert.equal(run2.parts[0]!.resumes, 1);
+ assert.equal(run2.coverage?.covers, true);
+ assert.equal(run2.needsAttention, false);
+ const old = rows.find((r) => r.startedAt === row1.startedAt)!;
+ assert.equal(old.awaitingResume, undefined, "the old row no longer says a part waits");
+ assert.equal(old.needsAttention, false, "the interruption is superseded by the whole");
+});
+
+test("B3 / DESIGN-5 7: a part an earlier run left waiting is never left as the only copy in staging: a later run (a Record again) REUSES it — the same files continued — and lands the whole", { timeout: 60_000 }, async () => {
+ const id = "exmplflowa2";
+ const { stem } = await waitingAtShutdown(id, 3000);
+ let live = true;
+ const again = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, resumedFrom, write, args }) => {
+ if (n === 1) assert.equal(resumedFrom, 51, "from what the earlier run downloaded");
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ // (No stall watch under a loaded machine: the reuse is what is tested.)
+ { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await again.run).status, "landed");
+ assert.equal(outOf(again.calls[0]!), stem, "the same files");
+ assert.equal(await storedSeconds(id), 7200);
+ assert.deepEqual(await left(id), [], "confirmed done: nothing left");
+ assert.ok((await rowOf(id)).every((r) => !r.awaitingResume), "no row says a part waits");
+});
+
+async function replacedOverShutdown(id: string, transcript: string | null, requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>) {
+ await landedAtShutdown(id, 3600);
+ if (transcript !== null) await writeFile(path.join(dataDir(id), "transcript.json"), transcript);
+ let live = true;
+ const r = await incidentRun(
+ id,
+ async (args) => {
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ live = false;
+ return okExit;
+ },
+ // (The hand-off reads a transcript there, as the real one does.)
+ { deps: { join: null, handoff: async () => ({ ...(await handoff()), hasTranscript: transcript !== null }) }, refresh: { stillLive: () => live }, ...(requestTranscription ? { requestTranscription } : {}) },
+ );
+ const s = await r.run;
+ return { s, log: r.log, row: (await rowOf(id)).find((x) => x.status === "landed")! };
+}
+
+test("flow (REVIEW-LF-4 4): a shutdown's landing from the start is stored, then a WHOLE from-start run replaces it — nobody is asked", async () => {
+ const id = "exmplflowb1";
+ const { s, row } = await replacedOverShutdown(id, null);
+ assert.equal(s.status, "landed");
+ assert.equal(await storedSeconds(id), 7200, "the whole replaced the shutdown's short landing");
+ assert.equal(row.kept, "new");
+ assert.equal(row.coverage?.covers, true);
+ assert.equal(row.transcriptRedo, undefined, "no transcript: the ordinary hand-off asks");
+ assert.equal(row.needsAttention, false);
+ assert.ok((await rowOf(id)).every((r) => !r.needsAttention), "the interruption is superseded");
+});
+
+test("flow (REVIEW-LF-4 2): the replaced short landing's transcript ends inside it → the transcription is asked again", async () => {
+ const id = "exmplflowb2";
+ const asked: string[] = [];
+ const { row, log } = await replacedOverShutdown(id, choughOf(3580), async (_slug, vid, o) => {
+ asked.push(`${vid}${o?.replace ? " replace" : ""}`);
+ return { ok: true, jobId: "job-redo" };
+ });
+ assert.deepEqual(asked, [`${id} replace`], "asked once, to REPLACE the transcript (the job would otherwise skip it)");
+ assert.equal(row.transcriptRedo?.verdict, "shorter");
+ assert.equal(row.transcriptRedo?.replacedSeconds, 3600);
+ assert.equal(row.transcriptRedo?.lastCueEnd, 3580);
+ assert.equal(row.transcriptRedo?.jobId, "job-redo");
+ assert.equal(row.needsAttention, false, "asked: nobody needs to");
+ assert.ok(log.some((l) => /transcript .*shorter file/i.test(l)));
+});
+
+test("flow (REVIEW-LF-4 2): asked again but nothing to ask with, or the ask refused → the row needs a person", async () => {
+ const id = "exmplflowb3";
+ const { row } = await replacedOverShutdown(id, choughOf(3580));
+ assert.equal(row.transcriptRedo?.verdict, "shorter");
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /transcript/);
+ const id2 = "exmplflowb4";
+ const r2 = await replacedOverShutdown(id2, choughOf(3580), async () => ({ ok: false, error: "the lane is held" }));
+ assert.equal(r2.row.transcriptRedo?.error, "the lane is held");
+ assert.equal(r2.row.needsAttention, true);
+});
+
+test("flow (REVIEW-LF-4 2): a transcript that cannot be read → not known which file it came from: the row says so and asks a person, nothing is queued", async () => {
+ const id = "exmplflowb5";
+ const asked: string[] = [];
+ const { row } = await replacedOverShutdown(id, "{ not json", async (_s, vid) => {
+ asked.push(vid);
+ return { ok: true, jobId: "job-x" };
+ });
+ assert.deepEqual(asked, []);
+ assert.equal(row.transcriptRedo?.verdict, "unknown");
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /transcript/);
+});
+
+test("flow (REVIEW-LF-4 2): a transcript whose speech runs past the short file's end was not made from it → nothing is asked", async () => {
+ const id = "exmplflowb6";
+ const asked: string[] = [];
+ const { row } = await replacedOverShutdown(id, choughOf(7150), async (_s, vid) => {
+ asked.push(vid);
+ return { ok: true, jobId: "job-y" };
+ });
+ assert.deepEqual(asked, []);
+ assert.equal(row.transcriptRedo, undefined);
+ assert.equal(row.needsAttention, false);
+});
+
+test("flow: a boot resume of a part its original run did NOT prove (a row written before the mark) earns no mark: it lands, unproven, covering nothing", { timeout: 60_000 }, async () => {
+ const id = "exmplflowa3";
+ const ac = new AbortController();
+ const first = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, signal }) => {
+ await write(3000);
+ setTimeout(() => ac.abort(), 10);
+ await abortOf(signal);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }),
+ { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } },
+ );
+ await first.run;
+ const t0 = (await rowOf(id))[0]!.startedAt;
+ const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await patchLiveRecordingRow(paths, YT_SLUG, id, t0, (r) => {
+ for (const p of r.parts) delete p.provenStart;
+ r.restart = { at: t0, by: "boot", state: "asked" };
+ });
+ 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");
+ const run2 = (await rowOf(id)).find((r) => r.resumeOf)!;
+ assert.equal(run2.parts[0]!.resumes, 1, "resumed in place");
+ assert.equal(run2.parts[0]!.provenStart, undefined, "the mark is not earned by a resume");
+ assert.equal(run2.coverage?.covers, false);
+});
+
+// --- REVIEW-5 B: a waiting part always has a way into the store; the recorder tree; every stream pinned; the boot's age ---
+
+// A shutdown leaves one from-start part waiting (both streams, their state).
+async function waitingAtShutdown(id: string, seconds = 3000, opts: { video?: number } = {}) {
+ const ac = new AbortController();
+ const r = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, writeStream, signal }) => {
+ if (opts.video === undefined) await write(seconds);
+ else {
+ await writeStream("audio", seconds);
+ if (opts.video > 0) await writeStream("video", opts.video);
+ }
+ setTimeout(() => ac.abort(), 10);
+ await abortOf(signal);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }),
+ // (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]!;
+ assert.equal(row.awaitingResume?.length, 1, "one part waits");
+ return { stem: outOf(r.calls[0]!), startedAt: row.startedAt, row };
+}
+const askBoot = async (id: string, startedAt: string) => {
+ const { patchLiveRecordingRow } = await import("../lib/liveRecordings-server");
+ await patchLiveRecordingRow(paths, YT_SLUG, id, startedAt, (r) => {
+ r.restart = { at: startedAt, by: "boot", state: "asked" };
+ });
+};
+
+test("B3: the stream ENDED while the editor was down — the boot's run finalizes and lands the waiting part, and the old row says what was done", { timeout: 60_000 }, async () => {
+ const id = "exmplb3end1";
+ const { startedAt } = await waitingAtShutdown(id);
+ await askBoot(id, startedAt);
+ const r = await incidentRun(id, async () => assert.fail("nothing is recorded for an ended stream"), {
+ request: { resumeOf: startedAt },
+ meta: { ...YT_META(id), live_status: "was_live", duration: 3000 },
+ deps: { ...FAST_WATCH, join: null, merge: fakeMerge },
+ });
+ const s = await r.run;
+ assert.equal(s.status, "landed");
+ assert.equal(await storedSeconds(id), 3000, "the waiting part is in the store");
+ assert.deepEqual(await left(id), [], "nothing left in staging, no state");
+ const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!;
+ assert.equal(old.restart?.state, "landed");
+ assert.doesNotMatch(old.reason, /is landed$/);
+ assert.match(old.reason, /was landed/);
+ assert.equal(old.awaitingResume, undefined);
+});
+
+test("B3: the stream was REMOVED while the editor was down (every read refused as private) — the waiting part is landed, the row says the stream is gone", { timeout: 60_000 }, async () => {
+ const id = "exmplb3gone";
+ const { startedAt } = await waitingAtShutdown(id);
+ await askBoot(id, startedAt);
+ const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`;
+ const r = await incidentRun(id, async () => assert.fail("nothing is recorded for a removed stream"), {
+ request: { resumeOf: startedAt },
+ deps: { ...FAST_WATCH, join: null, merge: fakeMerge },
+ refresh: { failReads: [1, 2, 3, 4, 5, 6], failWith: PRIVATE },
+ });
+ await r.run.catch(() => {});
+ assert.equal(await storedSeconds(id), 3000, "the only copy is in the store");
+ // (REVIEW-6 12: gone is endedBy private — nothing on disk is removed.)
+ assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)));
+ const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!;
+ assert.equal(old.restart?.state, "landed");
+ assert.match(old.reason, /private or removed/);
+});
+
+test("B3: the stream's state cannot be read at the boot (a network error, every read) — what was left is landed all the same; the row says the state is not known and to Record again", { timeout: 60_000 }, async () => {
+ const id = "exmplb3unk1";
+ const { startedAt } = await waitingAtShutdown(id);
+ await askBoot(id, startedAt);
+ const r = await incidentRun(id, async () => assert.fail("never a recording on a guess"), {
+ request: { resumeOf: startedAt },
+ deps: { ...FAST_WATCH, join: null, merge: fakeMerge },
+ refresh: { failReads: [1, 2, 3, 4, 5, 6] },
+ });
+ await r.run.catch(() => {});
+ assert.equal(await storedSeconds(id), 3000);
+ const old = (await rowOf(id)).find((x) => x.startedAt === startedAt)!;
+ assert.equal(old.restart?.state, "landed");
+ assert.match(old.reason, /could not be read/);
+ assert.match(old.reason, /Record again/);
+ assert.equal(old.needsAttention, true, "the stream may still be live: a person");
+});
+
+test("B3: the boot resume takes the LONGEST resumable from-start part of any row of the id; the others are released and landed by the rules", { timeout: 60_000 }, async () => {
+ const id = "exmplb3long";
+ const a = await waitingAtShutdown(id, 3000);
+ // A second run (no resume) also stopped by a shutdown, with a shorter part:
+ // the first run's part keeps waiting beside it.
+ const ac = new AbortController();
+ const b = await incidentRun(
+ id,
+ resumableYtdlp(async ({ resumedFrom, write, signal }) => {
+ // (DESIGN-5 7: it continues the earlier waiting part, the longest.)
+ assert.equal(resumedFrom, 51);
+ await write(3600);
+ setTimeout(() => ac.abort(), 10);
+ await abortOf(signal);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }),
+ { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } },
+ );
+ await b.run;
+ assert.equal(outOf(b.calls[0]!), a.stem, "the second run continued the first's part");
+ const rowB = (await rowOf(id)).find((x) => x.startedAt !== a.startedAt)!;
+ assert.equal(rowB.awaitingResume?.length, 1, "that part waits again, listed on the newest row");
+ await askBoot(id, rowB.startedAt);
+ let live = true;
+ const c = await incidentRun(
+ id,
+ resumableYtdlp(async ({ resumedFrom, write }) => {
+ assert.equal(resumedFrom, 61, "the part, now 3600 s, is resumed");
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { resumeOf: rowB.startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await c.run).status, "landed");
+ assert.equal(outOf(c.calls[0]!), a.stem);
+ assert.equal(await storedSeconds(id), 7200);
+ assert.deepEqual(await left(id), [], "the shorter waiting part was released, and inside the whole it went");
+ assert.ok((await rowOf(id)).every((r) => !r.awaitingResume));
+});
+
+test("B4: a stop reaches the recorder's whole tree, and the recorder returns when yt-dlp exits — not when a grandchild holding its pipes does", { timeout: 30_000 }, async () => {
+ const pidFile = path.join(ROOT, "grandchild.pid");
+ // yt-dlp's stand-in: starts a child that inherits its stdout/stderr (as
+ // yt-dlp's ffmpeg does), says ready, and has no handler for SIGTERM.
+ const script = `const c = require("child_process").spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: ["ignore", "inherit", "inherit"] }); require("fs").writeFileSync(${JSON.stringify(pidFile)}, String(c.pid)); console.log("ready"); setInterval(() => {}, 1000);`;
+ const ac = new AbortController();
+ const lines: string[] = [];
+ const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: (l) => void lines.push(l), signal: ac.signal, label: "t" });
+ const readyBy = Date.now() + 20_000;
+ while (!lines.some((l) => /^(?:\[t\] )?ready\s*$/.test(l))) {
+ assert.ok(Date.now() < readyBy, "the child never said it was ready");
+ await new Promise((r) => setTimeout(r, 10));
+ }
+ const grandchild = Number(await readFile(pidFile, "utf8"));
+ const t0 = Date.now();
+ ac.abort("SIGTERM");
+ const o = await p;
+ assert.ok(Date.now() - t0 < 8000, `returned ${Date.now() - t0} ms after the stop`);
+ assert.equal(o.signalled, true);
+ await new Promise((r) => setTimeout(r, 200));
+ assert.throws(() => process.kill(grandchild, 0), "the grandchild is gone too");
+});
+
+test("B4: a from-start recorder whose part cannot be resumed (a muxed download, no state) is stopped with SIGINT, which finishes it — never SIGTERM", { timeout: 60_000 }, async () => {
+ const id = "exmplb4mux1";
+ const reasons: unknown[] = [];
+ const ac = new AbortController();
+ const r = await incidentRun(
+ id,
+ async (args, _n, signal) => {
+ // One muxed file, no `.ytdl` (an ffmpeg download keeps none).
+ await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;");
+ setTimeout(() => ac.abort(), 10);
+ await abortOf(signal);
+ reasons.push(signal.reason);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ },
+ { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge, shuttingDown: () => true } },
+ );
+ await r.run.catch(() => {});
+ assert.deepEqual(reasons, ["SIGINT"]);
+});
+
+test("B5: a resume pins EVERY stream the run was recording, the empty one included; the empty stream is said at once, not at the landing", { timeout: 60_000 }, async () => {
+ const id = "exmplb5pin1";
+ const { row } = await waitingAtShutdown(id, 3000, { video: 0 });
+ assert.equal(row.parts[0]!.missingStream, "video", "said when the recorder stopped");
+ assert.match(row.reason, /video/);
+ await askBoot(id, row.startedAt);
+ let live = true;
+ const c = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write }) => {
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { resumeOf: row.startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await c.run;
+ assert.equal(c.calls[0]![c.calls[0]!.indexOf("-f") + 1], "136+140", "both ids, the empty stream's too");
+});
+
+test("B5: a stem with only one stream file of a separate recording is not resumed in place (never `-f` one stream alone)", { timeout: 60_000 }, async () => {
+ const id = "exmplb5one1";
+ const { stem, startedAt } = await waitingAtShutdown(id, 3000);
+ // The picture's file is gone (its state too): one stream left.
+ await rm(`${stem}.${FAKE_V}`, { force: true });
+ await rm(`${stem}.${FAKE_V}.ytdl`, { force: true });
+ await askBoot(id, startedAt);
+ let live = true;
+ const c = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write }) => {
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await c.run.catch(() => {});
+ assert.notEqual(c.calls[0]![c.calls[0]!.indexOf("-f") + 1], "140", "never one stream alone");
+ assert.notEqual(outOf(c.calls[0]!), stem, "not resumed in place: a new from-start part");
+ assert.ok(fromStartArg(c.calls[0]!));
+});
+
+test("REVIEW-5 note 1: one stream that stops growing while the other grows is a stall — stopped (SIGTERM, resumable) and resumed with both", { timeout: 60_000 }, async () => {
+ const id = "exmplnote1a";
+ let live = true;
+ const reasons: unknown[] = [];
+ const { run, calls, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, writeStream, write, signal }) => {
+ if (n === 1) {
+ await write(3000);
+ // The sound goes on; the picture's thread has ended alone.
+ 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");
+ return { exitCode: null, stderrTail: "", signalled: signal.aborted };
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await run;
+ assert.deepEqual(reasons, ["SIGTERM"]);
+ assert.ok(log.some((l) => /stream .*f136\.mp4 has not grown/.test(l)), `said which stream: ${log.filter((l) => /stall/.test(l)).join(" | ")}`);
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place");
+ assert.equal(calls[1]![calls[1]!.indexOf("-f") + 1], "136+140");
+});
+
+test("REVIEW-5 note 3: the restart bound reached on a stream still live does not end the recording: it waits out the hour, continues, and the row says it waited", { timeout: 60_000 }, async () => {
+ const id = "exmplnote3a";
+ let live = true;
+ const { run, calls, waits, log } = await incidentRun(
+ id,
+ async (args, n) => {
+ // Every recorder exits a moment later with what it wrote (an IRL
+ // stream whose ingest keeps dropping); the stream ends after 9.
+ await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${60 + n};`);
+ if (n >= 9) live = false;
+ return okExit;
+ },
+ { request: { fromStart: false }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await run.catch(() => {});
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.restarts?.refused, undefined, "never refused while live");
+ assert.ok((row.restarts?.count ?? 0) >= 7, `restarted past the hour's 6 (${row.restarts?.count})`);
+ assert.ok((row.restarts?.waited ?? 0) >= 1, "it waited");
+ assert.ok(waits.some((w) => w > 60_000 && w <= 3_600_000), `an hour's wait: ${waits.join(", ")}`);
+ 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 or reuse (no state, a kept fragment gone) while the stream is live — a FRESH part from the start (a new stem, proven), never the live edge; the whole lands and covers", { timeout: 60_000 }, async () => {
+ const id = "exmpld4fr01";
+ let live = true;
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(3000);
+ await dropState(args);
+ // Nothing provable to reuse either: a kept fragment is gone.
+ await rm(`${outOf(args)}.${FAKE_V}-Frag20`, { force: true });
+ return "die";
+ }
+ assert.ok(fromStartArg(args) && isFresh(args), `call ${n}: a fresh from-start part`);
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, stallMs: 60_000, 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 / DESIGN-5 7: while recording EVERY fragment is kept (nothing pruned until the stream is confirmed done); short of disk they are DROPPED (loud), the recording goes on, no longer resumable in place", { timeout: 60_000 }, async () => {
+ const id = "exmpld4prn1";
+ let live = true;
+ let free = 1e15;
+ 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);
+ 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.)
+ { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, freeBytes: async () => free }, refresh: { stillLive: () => live } },
+ );
+ await run.catch(() => {});
+ assert.equal(seenFrags[0], 51, "all 51 kept while recording");
+ const row = (await rowOf(id))[0]!;
+ assert.match(row.parts[0]!.fragmentsDropped ?? "", /free/);
+ assert.notEqual(outOf(calls[1]!), outOf(calls[0]!), "not resumed in place: its fragments were dropped");
+ 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[] = [];
+ // (As the recorder reads yt-dlp's `ERROR: \\r[download] …` line: REVIEW-6 1.)
+ const GOT = "ERROR: [download] Got error: HTTP Error 404: Not Found. Giving up after 10 retries";
+ 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: {
- kickVod: async () => ({ id: uuid, url: `https://kick.com/synthc/videos/${uuid}` }),
- // Live at the first read; ended (with its duration, when known) after.
- refresh: async (cwd: string, args: string[]) => {
- reads++;
- const o = args[args.indexOf("-o") + 1]!;
- const m = reads === 1 ? { ...meta, live_status: "is_live" } : { ...meta, live_status: "was_live", ...(duration ? { duration } : {}) };
- await writeFile(path.join(cwd, path.dirname(o), "metadata.info.json"), JSON.stringify(m));
- return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
- },
- spawn: async ({ args }) => {
- await writeFile(args[args.indexOf("-o") + 1]!, "format=mpegts;seconds=30;");
- return { exitCode: 0, stderrTail: "", signalled: false };
- },
- poll: async (o) => {
- await writeFile(o.output, `format=mpegts;seconds=${vod};`);
- return { segments: 500, seconds: vod, gaps: 0, firstSeq, ended: "the VOD has not grown" };
+ ...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" };
},
- land,
- freeBytes: async () => 1e15,
- handoff,
- shuttingDown: () => false,
},
- });
- const files = (await readdir(path.join(paths.savedVideosDir, slug))).filter((n) => n.startsWith(`.${uuid}.`));
- assert.equal(files.length === 0, gone, `${uuid}: the channel's live-edge part ${gone ? "goes" : "is kept"}`);
- const { listLiveRecordings } = await import("./liveRecordings");
- const row = (await listLiveRecordings(paths, { slug, id: uuid, all: true })).rows[0]!;
- if (gone) {
- // (covered (a)'s guarantees: removed, said why, nothing kept, nobody asked.)
- assert.equal(row.coverage?.covers, true);
- assert.equal(row.removedParts?.length, 1);
- assert.match(row.removedParts![0]!.why, /holds the whole stream/);
- assert.equal(row.keptParts, undefined);
- assert.equal(row.needsAttention, false);
- } else {
- assert.equal(row.keptParts?.length, 1);
- assert.equal(row.needsAttention, true);
- }
- }
+ 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 the same files continued (reused), never fragment 0", { 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" : "resume");
+ 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(() => {});
+ // (DESIGN-5 7: the same files continued, reusing what is downloaded.)
+ const mains = calls.filter((c) => !isInsurance(c));
+ assert.equal(outOf(mains[1]!), outOf(mains[0]!), "the same files, not a fresh part");
+ const ins = order.indexOf("insurance");
+ assert.ok(ins >= 0 && order.indexOf("confirm-read") >= 0 && ins < order.indexOf("resume"), `order: ${order.join(" → ")}`);
+});
+
+test("note 4: at a shutdown with a part waiting, NOTHING lands — the other part waits too, for the restart", { timeout: 60_000 }, async () => {
+ 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);
});
-// --- REVIEW-LF-1 ------------------------------------------------------------------
+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");
+});
-// An earlier run's row describing one part of the stream (a leftover in staging).
-async function rowFor(id: string, stem: string, part: Record<string, unknown>) {
+// --- DESIGN-5: a recorder that ends by itself while the stream is live ------------------
+
+const REFRESH_FAIL = [
+ "WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Retrying (1/3)...",
+ "WARNING: [youtube] Cannot find refreshed url for format 136; please report this issue. Retrying (1/3)...",
+ "WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Giving up after 3 retries",
+];
+
+test("DESIGN-5 1/2/7: yt-dlp gives up refreshing the URL, merges and exits 0 while the stream is live — never landed as whole; classed url-refresh in plain words; the SAME files resumed reusing every fragment downloaded, again and again while it is live", { timeout: 60_000 }, async () => {
+ const id = "exmpld5url1";
+ let live = true;
+ const resumed: (number | null)[] = [];
+ const { run, calls, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, resumedFrom, write, print }) => {
+ resumed.push(resumedFrom);
+ // (The stream is 2 h old: the last part reaches its end.)
+ await write(n < 4 ? 3000 + (n - 1) * 1200 : 7200);
+ if (n < 4) {
+ for (const l of REFRESH_FAIL) print(l);
+ return "end"; // merged, the state removed, exit 0 — the stream goes on
+ }
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ const s = await run;
+ assert.equal(s.status, "landed");
+ assert.equal(calls.length, 4, "three self-exits while live: three restarts");
+ assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "the same files every time");
+ assert.deepEqual(resumed, [null, 51, 71, 91], "each restart from what is on disk, never fragment 0");
+ assert.ok(log.some((l) => /could not refresh the stream's URL for format 140/.test(l)));
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.parts[0]!.failureClass, "url-refresh");
+ assert.equal(row.parts[0]!.reused?.fragments, 91, "the last reuse");
+ assert.match(row.reason, /could not refresh the stream's URL/);
+ assert.equal(row.landedWhileLive, undefined, "landed once the stream was over");
+ assert.equal(row.coverage?.covers, true);
+ assert.deepEqual(await left(id), [], "confirmed done: the streams, fragments and merged copies go");
+});
+
+test("DESIGN-5 1: a partial exit (one stream missing) while the stream is live restarts — never a landing", { timeout: 60_000 }, async () => {
+ const id = "exmpld5par1";
+ let live = true;
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, writeStream, write, args }) => {
+ if (n === 1) {
+ await writeStream("audio", 600);
+ await rm(`${outOf(args)}.${FAKE_V}`, { force: true });
+ await rm(`${outOf(args)}.${FAKE_V}.ytdl`, { force: true });
+ return { exitCode: 1, stderrTail: "ERROR: The downloaded file is empty\n", signalled: false };
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await run.catch(() => {});
+ assert.ok(calls.length >= 2, "restarted");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.landedWhileLive, undefined);
+});
+
+test("DESIGN-5 3/4/7: a Cancel while the stream is live — landed, but `landedWhileLive` with the unrecorded time, loud, never 'the whole stream', no superseding; the stream files and fragments kept; a Record again then REUSES them", { timeout: 60_000 }, async () => {
+ const id = "exmpld5cnl1";
const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
await ytChannel();
- await upsertLiveRecordingRow(paths, YT_SLUG, {
+ await upsertLiveRecordingRow(paths, YT_SLUG, { id, url: ytUrl(id), platform: "youtube", startedAt: "2026-11-20T01:00:00.000Z", status: "failed", fromStart: true, attempts: 1, mustKeep: true, parts: [] });
+ const ac = new AbortController();
+ const a = await incidentRun(
id,
- 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, startedAt: "2026-11-20T01:00:00.000Z", stem, ...part }],
- } as never);
-}
-const UNSUPPORTED = "ERROR: [youtube] x: --live-from-start is passed, but there are no formats that can be downloaded from the start\n";
-// From its start unsupported: an index-0 part records `seconds`.
-const index0Run = (seconds: number) => async (args: string[], n: number) => {
- if (n === 1) return { exitCode: 1, stderrTail: UNSUPPORTED, signalled: false };
- await writeFile(`${outOf(args)}.mp4`, `format=mov,mp4;seconds=${seconds};`);
- return okExit;
-};
+ resumableYtdlp(async ({ write }) => {
+ await write(3000);
+ setTimeout(() => ac.abort(), 10);
+ // SIGINT: yt-dlp finishes (merged, its state removed).
+ return "hang";
+ }),
+ { signal: ac.signal, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => true } },
+ );
+ await a.run.catch(() => {});
+ const rows = await rowOf(id);
+ const row = rows.find((r) => r.startedAt !== "2026-11-20T01:00:00.000Z")!;
+ assert.ok(row.landedWhileLive, "landed while live");
+ assert.ok((row.landedWhileLive!.unrecordedSeconds ?? 0) > 3000, `unrecorded by the clock: ${row.landedWhileLive!.unrecordedSeconds}`);
+ assert.match(row.landedWhileLive!.why, /cancelled/);
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /LANDED WHILE THE STREAM WAS STILL LIVE/);
+ assert.ok(!a.log.some((l) => /holds the whole stream/.test(l)), "no claim of wholeness");
+ assert.equal(rows.find((r) => r.startedAt === "2026-11-20T01:00:00.000Z")!.supersededBy, undefined, "supersedes nothing");
+ const stem = outOf(a.calls[0]!);
+ assert.ok((await left(id)).some((n) => n === path.basename(`${stem}.${FAKE_V}`)), "the stream files are kept for reuse");
+ assert.ok((await left(id)).some((n) => n === path.basename(`${stem}.${FAKE_V}-Frag51`)), "and the fragments");
+ // A person's Record again: the kept part is resumed, not fragment 0.
+ let live = true;
+ const b = await incidentRun(
+ id,
+ resumableYtdlp(async ({ resumedFrom, write }) => {
+ assert.equal(resumedFrom, 51, "reused");
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await b.run).status, "landed");
+ assert.equal(outOf(b.calls[0]!), stem, "the same files");
+ const last = (await rowOf(id)).find((r) => r.status === "landed" && !r.landedWhileLive)!;
+ assert.equal(last.parts[0]!.reused?.fragments, 51);
+});
-test("LF finding 1: an index-0 part is not proven from the start — it never replaces a stored container nor removes a proven from-start part, on length alone", async () => {
- // (a) A stored container from the start; an index-0 run "covers" by length.
- const a = "exmpllfidx2";
- await landedAtShutdown(a, 3600);
- const r = await incidentRun(a, index0Run(7200), { meta: { ...YT_META(a), live_status: "post_live", duration: 7210 } });
- await assert.rejects(r.run, /not landed/);
- assert.equal(await storedSeconds(a), 3600, "the stored start stays");
- // (b) An earlier proven from-start part; an index-0 landing that "covers" leaves it.
- const b = "exmpllfidx3";
- const earlier = await leftover(b, 300);
- await rowFor(b, path.basename(earlier).replace(/\.mp4$/, ""), { provenStart: true });
- const rb = await incidentRun(b, index0Run(7200), { meta: { ...YT_META(b), live_status: "post_live", duration: 7210 } });
- assert.equal((await rb.run).status, "landed");
- assert.ok((await stat(earlier)).size > 0, "the proven from-start part is kept");
- assert.equal((await rowOf(b)).find((x) => x.status === "landed")!.coverage?.covers, false);
+test("DESIGN-5 2: the url-refresh class", async () => {
+ const { liveFailureClass: liveFailureClassOf } = await import("../lib/liveCapture");
+ assert.equal(liveFailureClassOf("WARNING: [youtube] Cannot find refreshed url for format 140; please report this issue. Giving up after 3 retries"), "url-refresh");
});
-test("LF finding 2: a part holding video is never 'inside' a longer audio-only landed part", async () => {
- const id = "exmpllfvid1";
+test("DESIGN-5 (c): fragments answered 403 while recording, then a read says private — `went-private`: what is on disk lands, loud, no retry loop, NOTHING on disk removed", { timeout: 60_000 }, async () => {
+ const id = "exmpld5prv1";
+ const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`;
+ const { run, calls, waits } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, print, signal }) => {
+ await write(3000);
+ for (let k = 1; k <= 3; k++) print(`[download] Got error: HTTP Error 403: Forbidden. Retrying fragment 52 (${k}/10)...`);
+ print("ERROR: [download] Got error: HTTP Error 403: Forbidden. Giving up after 10 retries");
+ await abortOf(signal);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failAfterFirst: PRIVATE } },
+ );
+ await run.catch(() => {});
+ assert.equal(calls.length, 1, "never retried in a loop");
+ assert.ok(waits.includes(60_000), "the private read confirmed a minute later");
+ assert.equal(await storedSeconds(id), 3000, "what is on disk is landed");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.failureClass, "went-private");
+ assert.equal(row.parts[0]!.failureClass, "went-private");
+ assert.equal(row.endedBy?.class, "private");
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /went private while it was recorded/);
+ const files = await left(id);
+ assert.ok(files.some((n) => n.endsWith(`.${FAKE_V}`)) && files.some((n) => n.endsWith(`.${FAKE_V}-Frag51`)), `nothing on disk removed: ${files.length} files`);
+});
+
+// --- REVIEW-6: the real yt-dlp bytes, the repair's leftover fragment, the verifier's two holes ---------
+
+// yt-dlp's fatal fragment line, as its bytes are (measured in exp4/r5, r7b):
+// `ERROR: ` then "\r", then the line — here split across two writes.
+const FATAL_CHUNKS = ["[download] 12.0% of ~ 1.20GiB at 2.00MiB/s (frag 51/2000)\nERROR: \r[download] Got er", "ror: HTTP Error 404: Not Found. Giving up after 10 retries\n"];
+const fatalScript = `process.stderr.write(${JSON.stringify(FATAL_CHUNKS[0])}); setTimeout(() => process.stderr.write(${JSON.stringify(FATAL_CHUNKS[1])}), 150); setInterval(() => {}, 1000);`;
+
+test("REVIEW-6 1: through the real recorder reader, yt-dlp's `ERROR: \\r[download] Got error … Giving up` arriving in two chunks is ONE line, and it is a fragment's final failure", async () => {
+ const { isFragmentFatalLine } = await import("./recordLive");
+ const ac = new AbortController();
+ const lines: string[] = [];
+ const p = spawnRecorder({ bin: process.execPath, args: ["-e", fatalScript], cwd: ROOT, onLog: () => {}, signal: ac.signal, label: "t", onLine: (l) => void lines.push(l) });
+ const by = Date.now() + 20_000;
+ while (!lines.some((l) => /Giving up/.test(l))) {
+ assert.ok(Date.now() < by, `no whole line: ${JSON.stringify(lines)}`);
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ ac.abort("SIGTERM");
+ await p;
+ const fatal = lines.find((l) => /Giving up/.test(l))!;
+ assert.equal(fatal, "ERROR: [download] Got error: HTTP Error 404: Not Found. Giving up after 10 retries");
+ assert.equal(isFragmentFatalLine(fatal), true);
+ assert.equal(isFragmentFatalLine("[download] Got error: HTTP Error 404: Not Found. Retrying fragment 52 (3/10)..."), false, "a retry is not the end");
+ assert.ok(!lines.includes("ERROR:"), "no bare ERROR: line");
+});
+
+test("REVIEW-6 1: a self-rewriting line (\\r, no \\n — ffmpeg's frame=) is read as it comes, not held until a newline", async () => {
const ac = new AbortController();
+ const lines: string[] = [];
+ const script = `let i = 0; const t = setInterval(() => { process.stderr.write("frame=" + (++i) + "\\r"); }, 20);`;
+ const p = spawnRecorder({ bin: process.execPath, args: ["-e", script], cwd: ROOT, onLog: () => {}, signal: ac.signal, label: "t", onLine: (l) => void lines.push(l) });
+ const by = Date.now() + 20_000;
+ while (lines.filter((l) => /^frame=/.test(l)).length < 3) {
+ assert.ok(Date.now() < by, "the \\r segments never came");
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ ac.abort();
+ await p;
+});
+
+test("REVIEW-6 1: the real fatal bytes through spawnRecorder STOP the recorder at once (SIGTERM, its state kept) and the resume waits 20 s — not the stall watchdog 10 minutes later", { timeout: 40_000 }, async () => {
+ const id = "exmplr6fat1";
+ let live = true;
+ const { run, calls, waits, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, print, signal }) => {
+ if (n === 1) {
+ await write(3000);
+ // The other stream's thread goes on: the process does not exit.
+ const o = await spawnRecorder({ bin: process.execPath, args: ["-e", fatalScript], cwd: ROOT, onLog: () => {}, signal, label: "real", onLine: print });
+ return { exitCode: o.exitCode, stderrTail: o.stderrTail, signalled: o.signalled };
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ // (No stall watch in the way: only the line can stop it.)
+ { deps: { ...FAST_WATCH, stallMs: 600_000, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await run).status, "landed");
+ assert.ok(log.some((l) => /a fragment could not be fetched/.test(l)), "the stop is said");
+ assert.ok(waits.includes(20_000), `the first wait before a resume: ${waits.join(", ")}`);
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!), "resumed in place");
+});
+
+test("REVIEW-6 3: before any fragment goes, each stream file must be byte for byte its kept fragments — one that is not fails the check and NOTHING is removed", { timeout: 60_000 }, async () => {
+ const id = "exmplr6eq01";
+ let live = true;
const { run } = await incidentRun(
id,
- async (args, n) => {
+ resumableYtdlp(async ({ write, args }) => {
+ await write(7200);
+ // A kept fragment that is not what the stream file holds there.
+ const f = `${outOf(args)}.${FAKE_V}-Frag10`;
+ const b = await readFile(f, "utf8");
+ await writeFile(f, b.replace("#10;", "#99;"));
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await run).status, "landed");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.verification?.state, "failed");
+ assert.match(row.verification?.why ?? "", /not fragment 10/);
+ assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files are kept");
+ assert.equal(row.needsAttention, true);
+});
+
+// --- REVIEW-6 4-13 --------------------------------------------------------------------
+
+test("REVIEW-6 4 / REVIEW-7 2: the stream ENDS (post_live) while its from-start part is behind — resumed once to its end, not landed short", { timeout: 60_000 }, async () => {
+ const id = "exmplr6end1";
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write }) => {
if (n === 1) {
- // Only its audio stream wrote (3 h of backlog); the video failed.
- await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=10800;v=none;");
- return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false };
+ await write(3000);
+ return "die";
}
- // Both streams, merged, 1 h — then a Cancel.
- await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=3600;");
- ac.abort();
- return { exitCode: null, stderrTail: "", signalled: true };
+ await write(7200);
+ return "end";
+ }),
+ { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "post_live" } },
+ );
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 2, "one resume after the end");
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!));
+ assert.equal(await storedSeconds(id), 7200);
+});
+
+test("REVIEW-6 4: landed SHORT of an ended stream's own duration — needs a person: \"download the VOD now\"", { timeout: 60_000 }, async () => {
+ const id = "exmplr6end2";
+ const { run } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, args }) => {
+ await write(3000);
+ await dropState(args);
+ await noReuse(args);
+ return "die";
+ }),
+ { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge } },
+ );
+ await run.catch(() => {});
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.status, "landed");
+ assert.equal(row.coverage?.covers, false);
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /download the VOD now/);
+});
+
+test("REVIEW-6 5: a resume that fails for the NETWORK is tried again on the waits, the same files — not given up after one try", { timeout: 60_000 }, async () => {
+ const id = "exmplr6net1";
+ let live = true;
+ const { run, calls, waits } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write }) => {
+ if (n === 1) {
+ await write(3000);
+ return "die";
+ }
+ if (n === 2) return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Unable to download webpage: The read operation timed out\n", signalled: false };
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await run).status, "landed");
+ assert.ok(waits.includes(20_000), `waited before the retry: ${waits.join(", ")}`);
+ assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "the same files throughout");
+});
+
+test("REVIEW-6 5: empty live-edge recorders while the state cannot be read (offline) are not evidence the stream ended", { timeout: 60_000 }, async () => {
+ const id = "exmplr6net2";
+ let reads = 0;
+ const { run } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(3000);
+ await dropState(args);
+ await noReuse(args);
+ return "die";
+ }
+ return { exitCode: 1, stderrTail: "ERROR: Unable to download webpage: timed out\n", signalled: false };
+ }),
+ {
+ deps: { ...FAST_WATCH, join: null, merge: fakeMerge, freshFromStart: false },
+ refresh: { failReads: [2, 3, 4, 5, 6, 7], afterRead: (k) => void (reads = k), stillLive: () => reads < 9 },
},
- { signal: ac.signal, request: { doNotClean: false, note: undefined } },
+ );
+ await run.catch(() => {});
+ const row = (await rowOf(id))[0]!;
+ assert.doesNotMatch(row.restarts?.refused ?? "", /three live-edge recorders/);
+});
+
+test("REVIEW-6 7: a resume in place needs the floor plus the stream files — not twice everything on disk (fragments, merged copies)", { timeout: 60_000 }, async () => {
+ const id = "exmplr6rm01";
+ let live = true;
+ let streams = 0;
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(3000);
+ for (const f of [FAKE_V, FAKE_A]) streams += (await stat(`${outOf(args)}.${f}`)).size;
+ return "die";
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ // Room for the floor and the streams, not for twice the part (fragments included).
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 1000 + streams + 10 }, refresh: { stillLive: () => live } },
+ );
+ await run.catch(() => {});
+ assert.ok(calls.length >= 2, "the resume was not refused for want of disk");
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!));
+});
+
+test("REVIEW-6 8: one moved-aside merged copy at a time, however many self-exits", { timeout: 60_000 }, async () => {
+ const id = "exmplr6pm01";
+ let live = true;
+ let premerges = 0;
+ const { run } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write }) => {
+ premerges = Math.max(premerges, (await left(id)).filter((x) => /\.premerge-\d+\./.test(x)).length);
+ await write(3000 + n * 600);
+ if (n < 4) return "end";
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
);
await run;
- assert.ok((await left(id)).some((n) => /ytdlp-a2\.mp4$/.test(n)), `the only video stays: ${(await left(id)).join(", ")}`);
+ assert.equal(premerges, 1, "never two copies aside");
});
-test("LF note 3: no pointer, but a source-media file in the store: a container is stored (fail closed) — nothing lands over it", async () => {
- const id = "exmpllfstr1";
- const { savedVideoDir } = await import("../lib/savedVideo");
- const dir = savedVideoDir(paths, YT_CONFIG, YT_SLUG, id);
+test("REVIEW-6 9: the stem lock names the RECORDER too — its live recorder keeps the lock though the editor that made it is gone", async () => {
+ const { takeStemLock } = await import("./recordLive");
+ const dir = path.join(ROOT, "locks9");
await mkdir(dir, { recursive: true });
- await writeFile(path.join(dir, "source-media.mp4"), "format=mov,mp4;seconds=9000;");
- const r = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
- await assert.rejects(r.run, /not landed/);
- assert.equal(await readFile(path.join(dir, "source-media.mp4"), "utf8"), "format=mov,mp4;seconds=9000;", "the unnamed container is untouched");
+ await writeFile(path.join(dir, ".x.live-9.ytdlp.rec.lock"), JSON.stringify({ pid: 2 ** 22 + 54321, recorderPid: process.pid, at: new Date().toISOString() }));
+ const r = await takeStemLock(dir, ".x.live-9.ytdlp");
+ assert.equal(r.ok, false, "an orphan recorder still writes those files");
+ assert.match((r as { why: string }).why, /its recorder/);
+});
+
+test("REVIEW-6 10: a RAW source (an audio stream landed as it is) stays in staging until the stored file is checked against it", { timeout: 60_000 }, async () => {
+ const id = "exmplr6raw1";
+ let existedAtCheck = false;
+ let checked = "";
+ const { run } = await incidentRun(
+ id,
+ async (args) => {
+ await writeFile(`${outOf(args)}.${FAKE_A}`, "format=mp4;seconds=7200;v=none;");
+ return okExit;
+ },
+ {
+ meta: { ...YT_META(id), duration: 7200 },
+ deps: {
+ join: null,
+ merge: fakeMerge,
+ verifyMerged: async (_m: string, streams: readonly string[]) => {
+ existedAtCheck = streams.length > 0 && (await stat(streams[0]!).catch(() => null)) !== null;
+ checked = streams[0] ?? "";
+ return { ok: true };
+ },
+ },
+ },
+ );
+ await run.catch(() => {});
+ assert.equal(existedAtCheck, true, "checked against the raw file, which was still there");
+ assert.equal(await stat(checked).catch(() => null), null, "the landed raw file removed after the check");
+});
+
+test("REVIEW-6 12: private while the editor was down — `endedBy` on the new row as when it happens while recording, and nothing removed", { timeout: 60_000 }, async () => {
+ const id = "exmplr6bg01";
+ const { startedAt } = await waitingAtShutdown(id);
+ await askBoot(id, startedAt);
+ const PRIVATE = `ERROR: [youtube] ${id}: Private video. Sign in if you've been granted access to this video`;
+ const r = await incidentRun(id, async () => assert.fail("nothing is recorded"), {
+ request: { resumeOf: startedAt },
+ deps: { ...FAST_WATCH, join: null, merge: fakeMerge },
+ refresh: { failReads: [1, 2, 3, 4, 5, 6], failWith: PRIVATE },
+ });
+ await r.run.catch(() => {});
+ const row = (await rowOf(id)).find((x) => x.startedAt !== startedAt)!;
+ assert.equal(row.endedBy?.class, "private");
+ assert.equal(row.needsAttention, true);
+ assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files kept");
+});
+
+test("REVIEW-6 13: one stream finished (its state gone), the other with its state — rebuilt per stream and resumed in place, not a fresh part", { timeout: 60_000 }, async () => {
+ const id = "exmplr6ps01";
+ let live = true;
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, args }) => {
+ if (n === 1) {
+ await write(3000);
+ await rm(`${outOf(args)}.${FAKE_V}.ytdl`, { force: true });
+ return "die";
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await run).status, "landed");
+ assert.equal(outOf(calls[1]!), outOf(calls[0]!), "the same files");
+});
+
+// --- DESIGN-5 point 5 (the orchestrator's go): the insurance when a from-start part is far behind ---------
+
+const FRAG_LINE = (n: number, m: number) => `1: [download] 0.1% of ~ 9.00GiB at 5.00MiB/s ETA 02:00:00 (frag ${n}/${m})`;
+async function behindRun(id: string, frag: [number, number], o: { insurance?: boolean; insuranceWhenBehind?: boolean } = {}) {
+ let live = true;
+ const r = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, print, args, signal }) => {
+ if (isInsurance(args)) {
+ await write(60);
+ await Promise.race([abortOf(signal), new Promise((res) => setTimeout(res, 2000))]);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ print(FRAG_LINE(frag[0], frag[1]));
+ await write(3000);
+ await new Promise((res) => setTimeout(res, 300));
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ {
+ // Not keep-marked, no insurance asked: only the behind check can start one.
+ request: { doNotClean: false, insurance: o.insurance },
+ deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5, ...(o.insuranceWhenBehind !== undefined ? { insuranceWhenBehind: o.insuranceWhenBehind } : {}) },
+ refresh: { stillLive: () => live },
+ },
+ );
+ await r.run.catch(() => {});
+ return r;
+}
+
+test("point 5: a from-start part whose first frag N/M shows it hours behind starts the live-edge insurance beside it, whatever the keep mark", { timeout: 60_000 }, async () => {
+ const id = "exmplp5beh1";
+ const r = await behindRun(id, [10, 7200]);
+ assert.ok(r.calls.some(isInsurance), "a live-edge recorder beside it");
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.insurance?.by, "behind");
+ assert.ok(r.log.some((l) => /behind the live edge: a live-edge recorder \(the insurance\) starts beside it/.test(l)));
+});
+
+test("point 5: a part that is NOT far behind (under 10 min) starts no insurance; the setting off or `insurance: false` starts none either", { timeout: 60_000 }, async () => {
+ const near = await behindRun("exmplp5beh2", [7190, 7200]);
+ assert.ok(!near.calls.some(isInsurance), "a minute behind: none");
+ const off = await behindRun("exmplp5beh3", [10, 7200], { insuranceWhenBehind: false });
+ assert.ok(!off.calls.some(isInsurance), "the setting off: none");
+ assert.ok(off.log.some((l) => /insuranceWhenBehind is off/.test(l)));
+ const no = await behindRun("exmplp5beh4", [10, 7200], { insurance: false });
+ assert.ok(!no.calls.some(isInsurance), "asked not to: none");
+});
+
+test("point 5: the insurance's starts are bounded per HOUR (3), not per run — a fourth start waits the hour out", { timeout: 60_000 }, async () => {
+ const id = "exmplp5hr01";
+ let live = true;
+ let insurers = 0;
+ const { run, waits } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, args }) => {
+ if (isInsurance(args)) {
+ insurers++;
+ await write(30);
+ // It dies early, again and again (an ingest that keeps dropping).
+ return { exitCode: 1, stderrTail: "ERROR: Connection reset by peer\n", signalled: false };
+ }
+ await write(3000);
+ await until(() => insurers >= 4, 4000);
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { insurance: true }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
+ );
+ await run.catch(() => {});
+ assert.ok(insurers >= 4, `started past 3 in the run: ${insurers}`);
+ assert.ok(waits.some((w) => w > 60_000 && w <= 3_600_000), "the fourth waited for the hour");
+});
+
+// --- REVIEW-7 ------------------------------------------------------------------------------
+
+const NET = "ERROR: [youtube] x: Unable to download webpage: The read operation timed out";
+
+test("REVIEW-7 1: a network outage — reads and resumes failing for the network — spawns nothing new and spends no restart: no wait over 10 minutes, and once it reads again the SAME files are resumed", { timeout: 60_000 }, async () => {
+ const id = "exmplr7net1";
+ let live = true;
+ const { run, calls, waits, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write }) => {
+ if (n === 1) {
+ await write(3000);
+ return "die";
+ }
+ // yt-dlp's own extraction fails too while the route is down.
+ if (n <= 7) return { exitCode: 1, stderrTail: `${NET}\n`, signalled: false };
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { failReads: [2, 3, 4, 5, 6, 7, 8], failWith: NET, stillLive: () => live } },
+ );
+ assert.equal((await run).status, "landed");
+ assert.ok(waits.every((w) => w <= 600_000), `no wait over 10 min: ${waits.join(", ")}`);
+ assert.ok(calls.every((c) => outOf(c) === outOf(calls[0]!)), "only the same files, never a fresh part or the live edge");
+ assert.ok(!log.some((l) => /restart bound is reached/.test(l)), "no restart bound spent");
+ assert.equal(await storedSeconds(id), 7200);
+});
+
+test("REVIEW-7 2: the stream ENDS as was_live while a part may be behind — NOT resumed (its formats are plain files: foreign bytes would be appended); landed and loud: download the VOD now", { timeout: 60_000 }, async () => {
+ const id = "exmplr7was1";
+ const { run, calls, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write }) => {
+ await write(3000);
+ return "die";
+ }),
+ { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "was_live" } },
+ );
+ await run.catch(() => {});
+ assert.equal(calls.length, 1, "no resume on was_live");
+ assert.ok(log.some((l) => /NOT resumed \(only a post_live stream/.test(l)));
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.needsAttention, true);
+ assert.match(row.reason, /download the VOD now/);
+});
+
+test("REVIEW-7 2 (b83460a1f): a part that reached the stream's end by itself is NOT resumed again on post_live", { timeout: 60_000 }, async () => {
+ const id = "exmplr7end2";
+ const { run, calls } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write }) => {
+ await write(7200);
+ return "end";
+ }),
+ { meta: { ...YT_META(id), duration: 7200 }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { endedAs: "post_live" } },
+ );
+ assert.equal((await run).status, "landed");
+ assert.equal(calls.length, 1, "exit 0 at the end: nothing more");
+});
+
+test("REVIEW-7 3: an insurance that ends by itself while the from-start part is still behind is started again; one whose loop RETURNED is started anew by a later part found behind — and 're-armed' is said only when a start follows", { timeout: 60_000 }, async () => {
+ const id = "exmplr7ins1";
+ let live = true;
+ let insurers = 0;
+ const { run, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, print, args }) => {
+ if (isInsurance(args)) {
+ insurers++;
+ await write(60);
+ // The first two end by themselves (exit 0); then it is members-only
+ // (a final class: the loop returns).
+ if (insurers <= 1) return okExit;
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Join this channel to get access to members-only content\n", signalled: false };
+ }
+ // (The fresh part comes after the second insurance's loop has returned.)
+ if (isFresh(args)) await new Promise((r) => setTimeout(r, 400));
+ print(FRAG_LINE(10, 7200));
+ await write(3000);
+ await until(() => insurers >= 2, 3000);
+ if (n === 1 || !isFresh(args)) {
+ await dropState(args);
+ await noReuse(args);
+ return "die";
+ }
+ await until(() => insurers >= 3, 3000);
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { doNotClean: false, insurance: undefined }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5 }, refresh: { stillLive: () => live } },
+ );
+ await run.catch(() => {});
+ assert.ok(insurers >= 3, `started again after its own end, and anew after its loop returned: ${insurers}`);
+ const starts = log.filter((l) => /a live-edge recorder \(the insurance\) starts beside it/.test(l)).length;
+ assert.ok(starts >= 2, `two behind starts said: ${starts}`);
+ assert.ok(!log.some((l) => /the insurance is re-armed beside it/.test(l)) || insurers >= 3, "never 're-armed' with nothing started");
});
-test("LF note 6: a run asked to keep the stream marks it even when nothing landed", async () => {
- const id = "exmpllfkep1";
- await landedAtShutdown(id, 3600, { doNotClean: false, note: undefined });
- assert.equal(await isDoNotClean(dataDir(id)), false);
- const r = await incidentRun(id, async (args, n) => {
- if (n <= 3) return failEmpty;
- await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=2000;");
- return okExit;
- });
- await assert.rejects(r.run, /not landed/);
- assert.equal(await isDoNotClean(dataDir(id)), true);
+test("REVIEW-7 (the re-arm removal): a keep-marked recording's insurance, stopped once the part caught up, is NOT started again by a resume that is not far behind", { timeout: 60_000 }, async () => {
+ const id = "exmplr7nra1";
+ let live = true;
+ let insurers = 0;
+ let mainN = 0;
+ const { run } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write, print, args, signal }) => {
+ if (isInsurance(args)) {
+ insurers++;
+ await write(60);
+ await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 3000))]);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
+ mainN++;
+ if (mainN === 1) {
+ await write(3000);
+ // Caught up with the live edge: the insurance stops after its margin.
+ await until(() => insurers >= 1, 3000);
+ print(FRAG_LINE(7200, 7200));
+ print("2: [download] 99.9% of ~ 1.00GiB (frag 7200/7200)");
+ await new Promise((r) => setTimeout(r, 300));
+ return "die";
+ }
+ // The resume, a few fragments behind the head.
+ print(FRAG_LINE(7195, 7200));
+ await write(7200);
+ await new Promise((r) => setTimeout(r, 200));
+ live = false;
+ return "end";
+ }),
+ // Keep-marked (the default insurance), its margin short.
+ { request: { insurance: undefined }, deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5, insuranceMarginMs: 5 }, refresh: { stillLive: () => live } },
+ );
+ await run.catch(() => {});
+ assert.equal(insurers, 1, `not started again on the restart: ${insurers}`);
});
-test("LF note 5: a row's part with no proven-start mark (an older row) is not removed under coverage; marked, it is", async () => {
- const id = "exmpllfold1";
- const earlier = await leftover(id, 300);
- await rowFor(id, path.basename(earlier).replace(/\.mp4$/, ""), {});
- const r = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
- assert.equal((await r.run).status, "landed");
- assert.ok((await stat(earlier)).size > 0, "kept: not proven from its start");
-});
+// --- REVIEW-7 4-8 --------------------------------------------------------------------------
-test("LF 9/10: landing 1.1 with a part meant for removal — kept when the store keeps its own", async () => {
- const id = "exmpllf1102";
- const one = await incidentRun(id, async (args) => {
- await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7300;");
- return okExit;
- });
- assert.equal((await one.run).status, "landed");
- const earlier = await leftover(id, 300);
- await rowFor(id, path.basename(earlier).replace(/\.mp4$/, ""), { provenStart: true });
- const two = await incidentRun(id, async (args) => {
- await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
- return okExit;
- });
- await assert.rejects(two.run, /not landed/);
- assert.ok((await stat(earlier)).size > 0);
- const row = (await rowOf(id)).find((x) => x.status === "failed" && /not landed/.test(x.error ?? ""))!;
- assert.ok(row.keptParts?.some((k) => /kept: nothing was landed/.test(k.why)), "the part meant for removal is kept and says so");
- assert.equal(row.removedParts, undefined);
+test("REVIEW-7 4: a verification that failed is checked AGAIN by reverifyLiveLanding — verified and the stream done, the stream files go and the row says verified", { timeout: 60_000 }, async () => {
+ const id = "exmplr7ver1";
+ let live = true;
+ const r = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write }) => {
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, verifyMerged: async () => ({ ok: false, why: "a transient read error" }) }, refresh: { stillLive: () => live } },
+ );
+ await r.run;
+ assert.equal((await rowOf(id))[0]!.verification?.state, "failed");
+ assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)));
+ const { reverifyLiveLanding } = await import("./recordLive");
+ const out = await reverifyLiveLanding({ paths, slug: YT_SLUG, id, channelConfig: YT_CONFIG, deps: { verifyMerged: async () => ({ ok: true }) } });
+ assert.equal(out.ok && out.verified, true, JSON.stringify(out));
+ assert.deepEqual(await left(id), [], "the stream files, state and fragments went");
+ assert.equal((await rowOf(id))[0]!.verification?.state, "verified");
});
-test("LF 9: with an empty store a short from-start partial lands and does not supersede (2.3's guarantee)", async () => {
- const id = "exmpllf2301";
- const first = await incidentRun(id, writesAfter(Infinity));
- await assert.rejects(first.run);
- const short = await incidentRun(id, writesAfter(0));
- assert.equal((await short.run).status, "landed");
- assert.ok(short.log.some((l) => /does not supersede/.test(l)));
- const rows = await rowOf(id);
- assert.equal(rows.find((r) => r.status === "landed")!.coverage?.covers, false);
- assert.equal(rows.find((r) => r.status === "failed")!.needsAttention, true);
+test("REVIEW-7 4 / REVIEW-8 3: a part whose fragments were dropped for want of disk is NOT 'verified whole' on the track spans alone — nothing removed, loud", { timeout: 60_000 }, async () => {
+ const id = "exmplr7drp1";
+ let live = true;
+ let free = 1e15;
+ const { run, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write }) => {
+ await write(3000);
+ free = 1e9;
+ await new Promise((r) => setTimeout(r, 150));
+ free = 1e15;
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, freeBytes: async () => free }, refresh: { stillLive: () => live } },
+ );
+ await run;
+ assert.ok(log.some((l) => /byte check .* is skipped: they were dropped/.test(l)));
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.verification?.state, "failed");
+ assert.match(row.verification?.why ?? "", /cannot be proven whole/);
+ assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_V}`)), "the stream files are kept");
});
-// --- REVIEW-LF-2 ------------------------------------------------------------------
+test("REVIEW-8 3: one fragment's length comes from the HIGHEST fragment number, never the count of files left (5 kept of 3601 is not 30 min a fragment), capped at 10 s", async () => {
+ const { fragmentSecondsOf } = await import("./recordLive");
+ const dir = path.join(ROOT, "frag8");
+ await mkdir(dir, { recursive: true });
+ const f = ".x.live-8.ytdlp.f136.mp4";
+ await writeFile(path.join(dir, f), "x");
+ for (const n of [3597, 3598, 3599, 3600, 3601]) await writeFile(path.join(dir, `${f}-Frag${n}`), "x");
+ const sec = await fragmentSecondsOf(dir, [f], 7200);
+ assert.ok(sec !== undefined && sec <= 2.01, `about 2 s a fragment: ${sec}`);
+ const g = ".x.live-9.ytdlp.f136.mp4";
+ await writeFile(path.join(dir, g), "x");
+ for (const n of [1, 2]) await writeFile(path.join(dir, `${g}-Frag${n}`), "x");
+ assert.ok(((await fragmentSecondsOf(dir, [g], 7200)) ?? 0) <= 10, "capped at 10 s");
+});
-// Rumble: `--live-from-start` is ffmpeg at the DVR playlist's first LISTED
-// segment. A run whose playlist read still lists segment 1 is from the start;
-// one that began after the window slid is not.
-const DVR_SLID = "#EXTM3U\n#EXT-X-TARGETDURATION:2\n#EXT-X-MEDIA-SEQUENCE:151\n#EXTINF:2,\nm_151.ts\n#EXTINF:2,\nm_152.ts\n";
-async function rumbleRun(id: string, o: { dvr: string; seconds: number; duration: number; stop?: "shutdown" }) {
- const ac = new AbortController();
- let reads = 0;
- const meta = { ...RUMBLE_META, id, live_status: "is_live", timestamp: Math.floor(Date.now() / 1000) - o.duration };
- return recordLiveRun({
- paths,
- request: { slug: SLUG, url: `https://rumble.com/${id}-show.html` },
- plan: { url: `https://rumble.com/${id}-show.html`, platform: "rumble", id },
- channelConfig: CONFIG,
- cookiePolicy: NO_COOKIES,
- onLog: () => {},
- signal: ac.signal,
- deps: {
- refresh: async (cwd: string, args: string[]) => {
- reads++;
- const out = args[args.indexOf("-o") + 1]!;
- const m = reads === 1 ? meta : { ...meta, live_status: "was_live", duration: o.duration };
- await writeFile(path.join(cwd, path.dirname(out), "metadata.info.json"), JSON.stringify(m));
- return { exitCode: 0, stderrTail: "", archiveLine: null, formatLine: null };
- },
- fetchText: async () => o.dvr,
- spawn: async ({ args }) => {
- await writeFile(args[args.indexOf("-o") + 1]!, `format=mpegts;seconds=${o.seconds};`);
- if (o.stop) {
- ac.abort();
- return { exitCode: null, stderrTail: "", signalled: true };
- }
- return { exitCode: 0, stderrTail: "", signalled: false };
+test("REVIEW-7 5: a merge that fails leaves its output set aside (never at the finished name the next run would land)", async () => {
+ const { resolvePart } = await import("./recordLive");
+ const dir = path.join(ROOT, "merge5");
+ await mkdir(dir, { recursive: true });
+ const stem = ".exmplr7mrg1.live-x.ytdlp";
+ await writeFile(path.join(dir, `${stem}.f136.mp4`), "format=mp4;seconds=60;a=none;");
+ await writeFile(path.join(dir, `${stem}.f140.m4a`), "format=mp4;seconds=60;v=none;");
+ const { livePartFiles: livePartFilesOf } = await import("../lib/liveCapture");
+ const g = livePartFilesOf("exmplr7mrg1", await readdir(dir)).find((x) => x.stem === stem)!;
+ await assert.rejects(
+ resolvePart(g, dir, {
+ probe: fakeProbe,
+ merge: async (args) => {
+ await writeFile(args[args.length - 1]!, "format=mov,mp4;seconds=60;");
+ throw new Error("ffmpeg's merge reported: Packet corrupt");
},
- land,
- freeBytes: async () => 1e15,
- handoff,
- shuttingDown: () => o.stop === "shutdown",
- },
- });
-}
-const rumbleStored = async (id: string) => {
- const { savedVideoPath } = await import("../lib/savedVideo");
- const p = await loadSavedVideo(path.join(CORPUS, "channels", SLUG, "data", id));
- return p ? ((await fakeProbe(savedVideoPath(p)))?.seconds ?? null) : null;
-};
-const rumbleLeft = async (id: string) => (await readdir(path.join(paths.savedVideosDir, SLUG)).catch(() => [] as string[])).filter((n) => n.startsWith(`.${id}.`));
-
-test("LF2 finding 1 (Rumble): a from-start run that began after the DVR window slid is not proven — it never replaces the stored start nor removes run 1's part", async () => {
- // (a) Run 1 from the true start, landed by a shutdown; run 2 after the slide "covers" by length.
- const a = "v7lfslid1";
- await rumbleRun(a, { dvr: DVR, seconds: 3600, duration: 10000, stop: "shutdown" });
- assert.equal(await rumbleStored(a), 3600);
- await assert.rejects(rumbleRun(a, { dvr: DVR_SLID, seconds: 9950, duration: 10000 }), /not landed/);
- assert.equal(await rumbleStored(a), 3600, "the stored start stays");
- // (b) Run 1's part in staging (its row: proven); run 2 after the slide lands, run 1's part is kept.
- const b = "v7lfslid2";
- const stem = `.${b}.live-2026-11-20T01-00-00-000Z.ytdlp`;
- await mkdir(path.join(paths.savedVideosDir, SLUG), { recursive: true });
- await writeFile(path.join(paths.savedVideosDir, SLUG, `${stem}.ts`), "format=mpegts;seconds=3600;");
- const { upsertLiveRecordingRow } = await import("../lib/liveRecordings-server");
- await upsertLiveRecordingRow(paths, SLUG, {
- id: b, url: `https://rumble.com/${b}-show.html`, platform: "rumble", startedAt: "2026-11-20T01:00:00.000Z", status: "interrupted",
- fromStart: true, attempts: 1, mustKeep: false,
- parts: [{ method: "ytdlp", url: "u", fromStart: true, provenStart: true, startedAt: "2026-11-20T01:00:00.000Z", stem }],
- } as never);
- const s = await rumbleRun(b, { dvr: DVR_SLID, seconds: 9950, duration: 10000 });
- assert.equal(s.status, "landed");
- assert.ok((await rumbleLeft(b)).some((n) => n === `${stem}.ts`), "run 1's part is kept");
+ say: () => {},
+ }),
+ /set aside as .*merge-failed-/,
+ );
+ const names = await readdir(dir);
+ assert.ok(!names.some((n) => /\.merged\.(mp4|mkv)$/.test(n)), `no finished merge left: ${names.join(", ")}`);
+ assert.ok(names.some((n) => /\.merge-failed-\d+\./.test(n)));
});
-test("LF2 finding 1 (YouTube): a from-start run of a stream older than 120 h is not proven (the generator starts 120 h back)", async () => {
- const id = "exmpllf120h";
- await landedAtShutdown(id, 3600);
- const old = Math.floor(Date.now() / 1000) - 121 * 3600;
- // 7200 s of a stream whose ended duration is 7210 s: it "covers" and is longer than the stored hour.
+test("REVIEW-7 6: with a live recorder holding the stem's lock, the boot's resume is refused BEFORE any repair — the torn tail and its fragments untouched", { timeout: 60_000 }, async () => {
+ const id = "exmplr7lck1";
+ const { stem, startedAt } = await waitingAtShutdown(id, 3000);
+ const v = `${stem}.${FAKE_V}`;
+ await writeFile(`${v}-Frag52`, "seconds=60;#52;xx");
+ await appendFile(v, "seconds=60;");
+ const sizeBefore = (await stat(v)).size;
+ // An orphan recorder of the last process still holds it (this pid is alive).
+ await writeFile(`${stem}.rec.lock`, JSON.stringify({ pid: 2 ** 22 + 777, recorderPid: process.pid, at: new Date().toISOString() }));
+ await askBoot(id, startedAt);
+ let live = true;
const r = await incidentRun(
id,
+ resumableYtdlp(async ({ write }) => {
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { request: { resumeOf: startedAt }, deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await r.run.catch(() => {});
+ void sizeBefore;
+ assert.ok(r.log.some((l) => /another recorder holds/.test(l)), "refused by the lock");
+ assert.ok(!r.log.some((l) => /truncated from/.test(l)), "no repair under a live writer");
+ assert.ok(!r.log.some((l) => /past its state .* removed before the resume/.test(l)), "no fragment removed under it");
+ assert.notEqual(outOf(r.calls[0]!), stem, "a fresh part instead");
+ await rm(`${stem}.rec.lock`, { force: true });
+});
+
+test("REVIEW-7 8: a raw source that must be copied with too little room — not landed, said plainly, everything kept", { timeout: 60_000 }, async () => {
+ const id = "exmplr7rom1";
+ const { run } = await incidentRun(
+ id,
async (args) => {
- await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=7200;");
+ await writeFile(`${outOf(args)}.${FAKE_A}`, `format=mp4;seconds=7200;v=none;${"x".repeat(5000)}`);
return okExit;
},
- { meta: { ...YT_META(id), release_timestamp: old, live_status: "post_live", duration: 7210 } },
+ { meta: { ...YT_META(id), duration: 7200 }, deps: { join: null, merge: fakeMerge, minFreeBytes: 1000, freeBytes: async () => 2000 } },
);
- await assert.rejects(r.run, /not landed/);
- assert.equal(await storedSeconds(id), 3600);
+ await run.catch(() => {});
+ const row = (await rowOf(id))[0]!;
+ assert.match(row.error ?? "", /landed by a copy .* needs .* free/);
+ assert.ok((await left(id)).some((n) => n.endsWith(`.${FAKE_A}`)), "kept");
});
-test("LF2 note 3: a pointer whose file is gone is 'stored, unknown' when the store folder holds a source-media file; with the folder empty or absent it is an empty store", async () => {
- const { savedVideoDir } = await import("../lib/savedVideo");
- // (a) The pointer names source-media.mp4 (gone); source-media.mkv is there.
- const a = "exmpllfptr1";
- await landedAtShutdown(a, 3600);
- const dirA = savedVideoDir(paths, YT_CONFIG, YT_SLUG, a);
- const named = (await readdir(dirA)).find((n) => n.startsWith("source-media."))!;
- await rm(path.join(dirA, named));
- await writeFile(path.join(dirA, "source-media.mkv"), "format=matroska;seconds=5000;");
- const ra = await incidentRun(a, writesAfter(0), { meta: { ...YT_META(a), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
- await assert.rejects(ra.run, /not landed/);
- assert.ok((await stat(path.join(dirA, "source-media.mkv"))).size > 0);
- // (b) The pointer names a file that is gone, the folder empty: lands as an empty store.
- const b = "exmpllfptr2";
- await landedAtShutdown(b, 3600);
- const dirB = savedVideoDir(paths, YT_CONFIG, YT_SLUG, b);
- await rm(dirB, { recursive: true, force: true });
- const rb = await incidentRun(b, writesAfter(0), { meta: { ...YT_META(b), release_timestamp: Math.floor(Date.now() / 1000) - 590 } });
- assert.equal((await rb.run).status, "landed");
-});
+// --- REVIEW-8 ------------------------------------------------------------------------------
-test("LF2 note 4: an audio-only part is not 'inside' a longer part whose own audio may be shorter", async () => {
- const id = "exmpllfaud1";
- const ac = new AbortController();
- const { run } = await incidentRun(
+test("REVIEW-8 1: one state read failing for a NON-network reason does not abandon the resumable part — resumed in place (with the insurance when it is far behind), never 'nothing on disk can be reused'", { timeout: 60_000 }, async () => {
+ const id = "exmplr8one1";
+ let live = true;
+ const { run, calls, log } = await incidentRun(
id,
- async (args, n) => {
+ resumableYtdlp(async ({ n, write, print, args, signal }) => {
+ if (isInsurance(args)) {
+ await write(60);
+ await Promise.race([abortOf(signal), new Promise((r) => setTimeout(r, 2000))]);
+ return { exitCode: null, stderrTail: "", signalled: true };
+ }
if (n === 1) {
- // Only its audio (1 h), then the video failed.
- await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=3600;v=none;");
- return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false };
+ await write(3000);
+ return "die";
}
- // Both, 4 h on the container's length (its audio may be shorter) — a Cancel.
- await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=14400;");
- ac.abort();
- return { exitCode: null, stderrTail: "", signalled: true };
+ print(FRAG_LINE(10, 7200));
+ await write(7200);
+ await new Promise((r) => setTimeout(r, 200));
+ live = false;
+ return "end";
+ }),
+ {
+ request: { doNotClean: false, insurance: undefined },
+ deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge, insurancePollMs: 5 },
+ refresh: { failReads: [2], failWith: "ERROR: [youtube] x: Failed to extract any player response; please report this issue", stillLive: () => live },
},
- { signal: ac.signal, request: { doNotClean: false, note: undefined } },
);
- await run;
- assert.ok((await left(id)).some((n) => /\.f140\.m4a$/.test(n)), "the audio-only part is kept");
+ await run.catch(() => {});
+ const mains = calls.filter((c) => !isInsurance(c));
+ assert.equal(outOf(mains[1]!), outOf(mains[0]!), "the same files resumed, not a fresh part");
+ assert.ok(!log.some((l) => /nothing on disk can be reused with proof/.test(l)));
+ assert.ok(calls.some(isInsurance), "the insurance beside the part found far behind");
});
-test("LF2 note 7: with a container stored, a zero-byte file and a fragments-only part's .ytdl are not removed by a run that lands nothing", async () => {
- const id = "exmpllfg7a1";
- await landedAtShutdown(id, 3600);
- await mkdir(store(), { recursive: true });
- const zero = path.join(store(), `.${id}.live-2026-11-20T02-00-00-000Z.ytdlp.f18.mp4`);
- await writeFile(zero, "");
- const frag = `.${id}.live-2026-11-20T03-00-00-000Z.ytdlp.f18.mp4`;
- await writeFile(path.join(store(), `${frag}-Frag7`), "bytes of a fragment");
- await writeFile(path.join(store(), `${frag}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: 7 } } }));
- const r = await incidentRun(id, async (args, n) => {
- if (n <= 3) return failEmpty;
- await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=2000;");
- return okExit;
- });
- await assert.rejects(r.run, /not landed/);
- assert.ok(await stat(zero).then(() => true, () => false), "the zero-byte file stays");
- assert.ok(await stat(path.join(store(), `${frag}.ytdl`)).then(() => true, () => false), "the .ytdl stays");
+test("REVIEW-8 2: a resume stopped inside an append (a torn tail the repair allows) is NOT 'damaged'; once the stream ends whole the row needs nobody", { timeout: 60_000 }, async () => {
+ const id = "exmplr8dmg1";
+ let live = true;
+ const { run, log } = await incidentRun(
+ id,
+ resumableYtdlp(async ({ n, write, tear }) => {
+ if (n === 1) {
+ await write(3000);
+ return "die";
+ }
+ if (n === 2) {
+ await write(3600);
+ await tear("video", 0.5);
+ return "die";
+ }
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, stallMs: 60_000, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ assert.equal((await run).status, "landed");
+ const row = (await rowOf(id))[0]!;
+ assert.ok(row.parts.every((p) => !p.resumeDamaged), `no false damage: ${JSON.stringify(row.parts.map((p) => p.resumeDamaged))}`);
+ assert.ok(!log.some((l) => /after the resume, .* the file is kept as it is/.test(l)));
+ assert.equal(row.needsAttention, false);
});
-test("LF3 note 5: a proven, same-kind, shorter part of this run IS removed after the landing (inside the landed part)", async () => {
- const id = "exmpllfcon1";
- // Every attempt writes only its audio (the video fails): the from-start
- // attempts 100 s, 200 s, 5000 s, the live-edge ones 10 s each.
- const secs = [100, 200, 5000, 10, 10, 10];
+test("REVIEW-8 4: `offline` does not outlive the outage — a resume failed for the network, then the stream ended: the landed row is not 'NOTHING is recording'", { timeout: 60_000 }, async () => {
+ const id = "exmplr8off1";
+ let live = true;
const { run } = await incidentRun(
id,
- async (args, n) => {
- await writeFile(`${outOf(args)}.f140.m4a`, `format=mp4;seconds=${secs[n - 1]};v=none;`);
- return { exitCode: 1, stderrTail: "1: ERROR: The downloaded file is empty\n", signalled: false };
+ resumableYtdlp(async ({ n, write }) => {
+ if (n === 1) {
+ await write(3000);
+ return "die";
+ }
+ live = false;
+ return { exitCode: 1, stderrTail: "ERROR: [youtube] x: Unable to download webpage: The read operation timed out\n", signalled: false };
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge }, refresh: { stillLive: () => live } },
+ );
+ await run.catch(() => {});
+ const row = (await rowOf(id))[0]!;
+ assert.equal(row.offline, undefined);
+ assert.doesNotMatch(row.reason, /NOTHING is recording/);
+});
+
+test("REVIEW-8 5: a raw source's copy asks the room the landing needs (its size plus 2 GB), not the 20 GB floor", { timeout: 60_000 }, async () => {
+ const id = "exmplr8rom1";
+ const { run } = await incidentRun(
+ id,
+ async (args) => {
+ await writeFile(`${outOf(args)}.${FAKE_A}`, `format=mp4;seconds=7200;v=none;${"x".repeat(5000)}`);
+ return okExit;
},
- { request: { doNotClean: false, note: undefined } },
+ // The floor is 3 GB here and the disk has a little more: the recorder
+ // starts, and the copy (5 kB + 2 GB) fits.
+ { meta: { ...YT_META(id), duration: 7200 }, deps: { join: null, merge: fakeMerge, minFreeBytes: 3e9, freeBytes: async () => 3e9 + 100 } },
);
await run.catch(() => {});
const row = (await rowOf(id))[0]!;
- assert.equal(row.parts[row.landedPart ?? -1]?.seconds, 5000, "the longest from-start part landed");
- const gone = (row.removedParts ?? []).filter((r) => /a shorter part of this run from its start/.test(r.why));
- assert.equal(gone.length, 2, "the two shorter from-start audio parts are inside it, and go");
- const files = await left(id);
- assert.ok(!files.some((n) => /-a2\.f140|ytdlp\.f140/.test(n)), `removed from staging: ${files.join(", ")}`);
- assert.equal(files.filter((n) => /edge/.test(n)).length, 3, "the live-edge parts (not proven) are kept");
+ assert.doesNotMatch(row.error ?? "", /landed by a copy/);
+ assert.equal(await storedSeconds(id), 7200);
+});
+
+test("REVIEW-8 6: 'Verify again' takes the stem's lock — refused while a recorder holds it, nothing removed", { timeout: 60_000 }, async () => {
+ const id = "exmplr8vlk1";
+ let live = true;
+ const r = await incidentRun(
+ id,
+ resumableYtdlp(async ({ write }) => {
+ await write(7200);
+ live = false;
+ return "end";
+ }),
+ { deps: { ...FAST_WATCH, join: null, merge: fakeMerge, verifyMerged: async () => ({ ok: false, why: "a transient read error" }) }, refresh: { stillLive: () => live } },
+ );
+ await r.run;
+ const stem = outOf(r.calls[0]!);
+ await writeFile(`${stem}.rec.lock`, JSON.stringify({ pid: 2 ** 22 + 99, recorderPid: process.pid, at: new Date().toISOString() }));
+ const before = (await left(id)).length;
+ const { reverifyLiveLanding } = await import("./recordLive");
+ const out = await reverifyLiveLanding({ paths, slug: YT_SLUG, id, channelConfig: YT_CONFIG, deps: { verifyMerged: async () => ({ ok: true }) } });
+ assert.equal(out.ok, false);
+ assert.match((out as { error: string }).error, /recorder holds/);
+ assert.equal((await left(id)).length, before, "nothing removed");
+ await rm(`${stem}.rec.lock`, { force: true });
});
diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts
@@ -53,7 +53,9 @@
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 { link, mkdir, open, readFile, readdir, rename, rm, rmdir, stat, writeFile } from "node:fs/promises";
+import { uptime } from "node:os";
+import { StringDecoder } from "node:string_decoder";
import { execa } from "execa";
import type { ChannelConfig } from "../lib/channelConfig";
import { assertChannelTextReadable } from "../lib/channelMedia";
@@ -62,6 +64,21 @@ import {
BROWSER_FALLBACK_PLATFORMS,
LIVE_DEFAULT_MAX_HEIGHT,
LIVE_RATE_LIMIT_WAIT_MS,
+ LIVE_RECOVERY_EVERY_MS,
+ LIVE_RECOVERY_MAX_TRIES,
+ LIVE_RESTART_CONFIRM_MS,
+ LIVE_RESTART_WAIT_MS,
+ LIVE_WATCH_MS,
+ LIVE_INSURANCE_DELAY_MS,
+ LIVE_INSURANCE_END_GRACE_MS,
+ LIVE_INSURANCE_MARGIN_MS,
+ LIVE_INSURANCE_MAX_STARTS,
+ LIVE_INSURANCE_MAX_STARTS_PER_HOUR,
+ LIVE_INSURANCE_BEHIND_SECONDS,
+ parseFragProgress,
+ catchUpTracker,
+ insuranceDecision,
+ restartWaitMs,
classifyAttempt,
extractionRefused,
ffmpegLiveArgs,
@@ -80,6 +97,10 @@ import {
spanWords,
ytdlpLiveArgs,
type KeptPart,
+ type LiveVerification,
+ type LiveBootRestartState,
+ type LiveInsurance,
+ type LiveJoinsRecord,
type RemovedPart,
type LiveFailureClass,
type LivePart,
@@ -90,12 +111,21 @@ import {
type MediaSegment,
type MissingStream,
type PlaylistReach,
+ type StartRecovery,
type StreamCoverage,
+ type LiveTranscriptRedo,
} from "../lib/liveCapture";
-import { liveRecordingSidecar } from "../lib/mediaImport-server";
-import { loadLiveRecordingRows, rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server";
-import { liveRecordingCheckCommand } from "./liveRecordings";
-import { setDoNotClean } from "../lib/doNotClean-server";
+import { WHISPER_FILENAME } from "../lib/videoStatus";
+import { parseTranscriptJson } from "../lib/whisper";
+import { readStoredText } from "../lib/storedText-server";
+import { dropFragments, dropFragmentsAbove, fragmentGaps, fragNumbers, readYtdlIndex, reconcileStream, streamEqualsFragments } 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";
+import { liveInsuranceWhenBehind, liveRecordingCheckCommand, liveStallMinutes } from "./liveRecordings";
+import { markLiveBootRestart } from "./liveRecordingBoot";
+import { isDoNotClean, setDoNotClean } from "../lib/doNotClean-server";
import type { Paths } from "../lib/paths";
import { detectPlatform } from "../lib/platform";
import { savedVideoDir, savedVideoPath, savedVideoRoot } from "../lib/savedVideo";
@@ -103,7 +133,7 @@ import { loadSavedVideo, savedVideoPointerPath } from "../lib/savedVideo-server"
import { assertSavedVideosStoreWritable } from "../lib/savedVideoStore";
import { getFreeBytes } from "../lib/diskSpace";
import { formatBytes } from "../lib/format";
-import { applyPendingKeep } from "../lib/pendingKeep-server";
+import { applyPendingKeep, loadPendingKeep } from "../lib/pendingKeep-server";
import { mp4CanHold, type MediaProbe } from "../lib/mediaImport";
import { getRegistry } from "../jobs/registry";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
@@ -117,6 +147,7 @@ import {
readHandoffFacts,
transcriptionHandoffLines,
type LandMediaDeps,
+ LAND_MEDIA_DISK_MARGIN_BYTES,
} from "./landMedia";
import { refreshVideoMetadata, type RefreshRunner } from "./refreshVideoMetadata";
import { findVideoSourceUrl } from "./undownloadedVideos";
@@ -143,6 +174,7 @@ export const RECORD_LIVE_BODY_KEYS = [
"note",
"dryRun",
"preclip",
+ "insurance",
] as const;
// The user agent path B's ffmpeg and the playlist reads present: the Firefox on
@@ -162,9 +194,31 @@ export const VOD_IDLE_END_MS = 10 * 60_000;
export const VOD_IDLE_AFTER_LIVE_END_MS = 2 * 60_000;
// A recorder that ignores SIGINT this long is killed.
export const RECORDER_GRACE_MS = 60_000;
+// After the recorder exits, how long its output may take to drain before a
+// process still holding it is killed (REVIEW-5 B4).
+export const RECORDER_EXIT_DRAIN_MS = 3_000;
+// 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];
+// REVIEW-7 1: while the network is down, the waits between two reads (or two
+// resumes): then every 5 min, for as long as it takes. Never a restart spent.
+export const OFFLINE_READ_WAITS_MS: readonly number[] = [20_000, 60_000, 180_000, 300_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;
+// Live-edge recorders in a row that capture nothing: the evidence a stream
+// that still reads live has ended (REVIEW-2 3.1 of live-guard-2).
+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. 119 h (REVIEW-5 note 8): an
+// hour's margin, as yt-dlp measures the age again after its extraction.
+export const LIVE_RESUME_MAX_AGE_MS = 119 * 3_600_000;
+// A restart after the editor's: the stream's state read again after these
+// waits when it could not be read (three reads over about ten minutes).
+export const LIVE_BOOT_STATE_READ_WAITS_MS: readonly number[] = [120_000, 480_000];
export type RecordLiveRequest = {
slug: string;
@@ -186,6 +240,15 @@ export type RecordLiveRequest = {
// while it records — its own job (controller/livePreclip.ts), started once
// the first part begins. Implies `transcribe` unless that is false.
preclip?: PreclipOptions;
+ // THE INSURANCE RECORDER (slice 4, lib/liveCapture.ts LiveInsurance): true
+ // = the live edge beside the from-start recording until it catches up;
+ // "whole" = the whole stream; false = none. Absent: on exactly when the
+ // stream is marked keep before or when the recording starts.
+ insurance?: boolean | "whole";
+ // INTERNAL (never a body key): the boot pass's restart of the interrupted
+ // run that started at this time (controller/liveRecordingBoot.ts). The
+ // run reads the stream's state first and records only if it is live.
+ resumeOf?: string;
};
export function parseRecordLiveRequest(
@@ -219,6 +282,10 @@ export function parseRecordLiveRequest(
}
const note = str("note");
if (note) out.note = note;
+ if (body.insurance !== undefined) {
+ if (body.insurance === true || body.insurance === false || body.insurance === "whole") out.insurance = body.insurance;
+ else return { error: '"insurance" is true (until the start catches up), "whole" (the whole stream) or false' };
+ }
const preclip = parsePreclipKnob(body.preclip, preclipDefaults);
if (preclip && "error" in preclip) return preclip;
if (preclip) {
@@ -304,7 +371,20 @@ export function recordLiveQueueKey(slug: string, id: string | null, kickChannel?
// --- the recorder process ----------------------------------------------------------
-export type RecorderOutcome = { exitCode: number | null; stderrTail: string; signalled: boolean };
+// `exitTail`: what the recorder printed (both streams) after its last
+// progress line — its last words near the exit, what a failure is classified
+// from (REVIEW-2 3.3 of live-guard-2); never a line from hours earlier.
+export type RecorderOutcome = { exitCode: number | null; stderrTail: string; signalled: boolean; exitTail?: string };
+
+// The recorder's last words: its own exitTail, else (a stub's stderr) the
+// lines after the last progress line, at most the last 20.
+export function recentOutput(o: Pick<RecorderOutcome, "stderrTail" | "exitTail">): string {
+ if (o.exitTail !== undefined) return o.exitTail;
+ const lines = o.stderrTail.split(/[\r\n]+/).map((l) => l.trim()).filter(Boolean);
+ let i = lines.length;
+ while (i > 0 && !isProgressLine(lines[i - 1]!)) i--;
+ return lines.slice(Math.max(i, lines.length - 20)).join("\n");
+}
export type RecorderSpawn = (opts: {
bin: string;
@@ -313,6 +393,10 @@ export type RecorderSpawn = (opts: {
onLog: (s: string) => void;
signal: AbortSignal;
label: string;
+ // Every line the recorder prints, progress included (before the thinning).
+ onLine?: (line: string) => void;
+ // The recorder's pid, once spawned (REVIEW-6 9: the stem lock names it).
+ onSpawn?: (pid: number) => void;
}) => Promise<RecorderOutcome>;
// A progress line yt-dlp or ffmpeg repeats every second for hours. yt-dlp
@@ -322,31 +406,198 @@ 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;
+// REVIEW-6 1: a fragment's FINAL failure as yt-dlp prints it — the error
+// line (`ERROR: \r[download] Got error: …`, joined by the recorder's reader),
+// a "Giving up after N retries" on a fragment, or "fragment N not found,
+// unable to continue". Never a retry ("Retrying fragment N (k/10)").
+export function isFragmentFatalLine(l: string): boolean {
+ if (/Retrying fragment/i.test(l)) return false;
+ return /^(?:\d+:\s*)?ERROR: \[download\] Got error|Got error: .*Giving up after \d+ retries|fragment \d+ not found, unable to continue/i.test(l);
+}
+
+// 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);
+}
+
+// The longest a fragment can be taken to be (YouTube's are 1, 2 or 5 s).
+export const FRAGMENT_SECONDS_CAP = 10;
+
+// REVIEW-7 4: one fragment's length, from a stream file's kept fragments and
+// the landed length (undefined when nothing tells it).
+export async function fragmentSecondsOf(dir: string, streams: readonly string[], seconds: number | null): Promise<number | undefined> {
+ if (!seconds || !streams.length) return undefined;
+ const names = await readdir(dir).catch(() => [] as string[]);
+ // REVIEW-8 3: the HIGHEST fragment number (or the state's index), never the
+ // count of files left — a part whose fragments were dropped keeps a few.
+ const nums = fragNumbers(streams[0]!, names);
+ const idx = await readYtdlIndex(path.join(dir, streams[0]!));
+ const n = Math.max(nums.length ? nums[nums.length - 1]! : 0, typeof idx === "number" ? idx : 0);
+ return n > 1 ? Math.min(FRAGMENT_SECONDS_CAP, seconds / (n - 1)) : undefined;
+}
+
+// A `.ytdl` state's fragment index, or null when it does not parse.
+function readYtdlRaw(raw: string): number | null {
+ try {
+ const idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index;
+ return typeof idx === "number" && idx >= 0 ? idx : null;
+ } catch {
+ return null;
+ }
+}
+
+// NOTE 5 (REVIEW-5) — THE STEM LOCK: `<stem>.rec.lock` in the store's staging
+// dir, made with O_EXCL while a recorder of that stem runs, removed when it
+// returns. STALE when the process that made it is gone (its pid answers no
+// signal) or it was made before the machine last booted (a pid may be
+// reused): a stale lock is taken over, said. Held by a live process (this
+// editor's or another's), the recorder is not started on that stem.
+export type StemLock = { ok: true; release: () => Promise<void>; setRecorder: (pid: number) => Promise<void> };
+export async function takeStemLock(dir: string, stem: string): Promise<StemLock | { ok: false; why: string }> {
+ const file = path.join(dir, `${stem}.rec.lock`);
+ const at = new Date().toISOString();
+ const body = (recorderPid?: number) => JSON.stringify({ pid: process.pid, ...(recorderPid ? { recorderPid } : {}), at });
+ for (let tries = 0; tries < 2; tries++) {
+ // REVIEW-7 6: never a lock a reader can catch empty — written whole to a
+ // temp file, then linked into place (fails if one is there) or renamed
+ // over (its update).
+ const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
+ try {
+ await writeFile(tmp, body());
+ await link(tmp, file);
+ await rm(tmp, { force: true });
+ return {
+ ok: true,
+ release: () => rm(file, { force: true }),
+ // REVIEW-6 9: the RECORDER's pid too — it runs in its own process
+ // group and outlives an editor killed outside the unit.
+ setRecorder: async (pid: number) => {
+ const t2 = `${file}.${pid}.tmp`;
+ await writeFile(t2, body(pid)).catch(() => {});
+ await rename(t2, file).catch(() => {});
+ },
+ };
+ } catch (err) {
+ await rm(tmp, { force: true });
+ 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; recorderPid?: 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";
+ }
+ };
+ // Stale only when NEITHER the editor nor the recorder it names is alive,
+ // or it was made before the machine last booted (pids are reused).
+ const stale = !held || (!alive(held.pid) && !alive(held.recorderPid)) || !held.at || Date.parse(held.at) < bootMs;
+ if (!stale) {
+ const who = alive(held!.recorderPid) ? `its recorder, pid ${held!.recorderPid}` : `pid ${held!.pid}`;
+ return { ok: false, why: `another recorder holds ${path.basename(file)} (${who}, since ${held!.at})` };
+ }
+ await rm(file, { force: true });
+ }
+ return { ok: false, why: `its lock ${path.basename(file)} could not be taken` };
+}
+
+// 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 as a plain child (so a SIGINT reaches yt-dlp, which
-// asks its ffmpeg to quit with `q` and the file is finalized), its output in
-// the job's log with the per-second progress thinned to one line every five
-// minutes. A Cancel sends SIGINT, then SIGKILL after RECORDER_GRACE_MS.
-export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, label }) =>
+// ONE RECORDER: spawned in a process group of its own (REVIEW-5 B4), so a
+// stop reaches the whole tree — yt-dlp and the ffmpeg it starts with its own
+// stdout and stderr: SIGINT (yt-dlp asks its ffmpeg to quit, and ffmpeg
+// finishes its file on SIGINT itself), SIGTERM (a resumable part: nothing
+// finishes), then SIGKILL after RECORDER_GRACE_MS. Its output is in the job's
+// log with the per-second progress thinned to one line every five minutes.
+// It returns when yt-dlp EXITS: a grandchild still holding the pipes a few
+// seconds later is killed with the group, never waited on.
+export const spawnRecorder: RecorderSpawn = ({ bin, args, cwd, onLog, signal, label, onLine, onSpawn }) =>
new Promise((resolve) => {
onLog(`[${label}] $ ${bin} ${args.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(" ")}\n`);
- const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"] });
+ const child = spawn(bin, args, { cwd, stdio: ["ignore", "pipe", "pipe"], detached: true });
+ if (child.pid) onSpawn?.(child.pid);
+ const killTree = (sig: NodeJS.Signals) => {
+ try {
+ if (child.pid) process.kill(-child.pid, sig);
+ else child.kill(sig);
+ } catch {
+ child.kill(sig);
+ }
+ };
let tail = "";
+ let sinceProgress = "";
let lastProgress = 0;
let signalled = false;
let killTimer: NodeJS.Timeout | null = null;
+ // REVIEW-6 1: lines are cut on "\n" ACROSS chunks (a line may arrive in
+ // two), then on "\r" (a progress line rewrites itself). yt-dlp prints an
+ // error as `ERROR: \r[download] Got error: …`: a bare `ERROR:` (or
+ // `WARNING:`) segment is joined to the segment after it, so the line read
+ // is the one yt-dlp meant.
+ const pend = { out: "", err: "" };
+ const decoders = { out: new StringDecoder("utf8"), err: new StringDecoder("utf8") };
+ const segmentsOf = (line: string): string[] => {
+ const segs = line.split("\r").map((x) => x.trim()).filter(Boolean);
+ const out: string[] = [];
+ for (let i = 0; i < segs.length; i++) {
+ if (/^(?:\d+:\s*)?(?:ERROR|WARNING):$/.test(segs[i]!) && i + 1 < segs.length) {
+ out.push(`${segs[i]} ${segs[i + 1]}`);
+ i++;
+ } else out.push(segs[i]!);
+ }
+ return out;
+ };
+ const feedText = (text: string, isErr: boolean, flush = false) => {
+ const key = isErr ? "err" : "out";
+ const all = pend[key] + text;
+ const lines = all.split("\n");
+ let rest = flush ? "" : lines.pop()!;
+ for (const line of lines) for (const l of segmentsOf(line)) emit(l);
+ // A line that only ever rewrites itself (ffmpeg's `frame=` with "\r"
+ // and no "\n"): its finished segments are read now; the last one, and
+ // a bare `ERROR:` waiting for what follows it, stay pending.
+ const cut = rest.lastIndexOf("\r");
+ if (cut >= 0) {
+ let done = rest.slice(0, cut);
+ let keep = rest.slice(cut + 1);
+ const lastSeg = done.slice(done.lastIndexOf("\r") + 1);
+ if (/^\s*(?:\d+:\s*)?(?:ERROR|WARNING):\s*$/.test(lastSeg)) {
+ done = done.slice(0, done.length - lastSeg.length);
+ keep = `${lastSeg}\r${keep}`;
+ }
+ for (const l of segmentsOf(done)) emit(l);
+ rest = keep;
+ }
+ pend[key] = rest.slice(-64 * 1024);
+ };
const feed = (chunk: Buffer, isErr: boolean) => {
- const text = chunk.toString("utf8");
+ const text = decoders[isErr ? "err" : "out"].write(chunk);
if (isErr) tail = (tail + text).slice(-32 * 1024);
- for (const line of text.split(/[\r\n]+/)) {
- const l = line.trim();
- if (!l) continue;
+ feedText(text, isErr);
+ };
+ const emit = (l: string) => {
+ {
+ onLine?.(l);
+ if (isProgressLine(l)) sinceProgress = "";
+ else sinceProgress = (sinceProgress + l + "\n").slice(-8 * 1024);
if (isProgressLine(l)) {
const now = Date.now();
- if (now - lastProgress < PROGRESS_EVERY_MS) continue;
+ if (now - lastProgress < PROGRESS_EVERY_MS) return;
lastProgress = now;
}
onLog(`[${label}] ${l}\n`);
@@ -357,19 +608,43 @@ 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");
- killTimer = setTimeout(() => child.kill("SIGKILL"), RECORDER_GRACE_MS);
+ // 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`);
+ killTree(how);
+ killTimer = setTimeout(() => killTree("SIGKILL"), RECORDER_GRACE_MS);
};
if (signal.aborted) onAbort();
else signal.addEventListener("abort", onAbort, { once: true });
child.on("error", (err) => {
tail += `\n${err.message}`;
});
- child.on("close", (code) => {
+ let done = false;
+ const finish = (code: number | null) => {
+ if (done) return;
+ done = true;
if (killTimer) clearTimeout(killTimer);
signal.removeEventListener("abort", onAbort);
- resolve({ exitCode: code, stderrTail: tail, signalled });
+ resolve({ exitCode: code, stderrTail: tail, signalled, exitTail: sinceProgress });
+ };
+ child.on("close", (code) => {
+ // What is left without a final newline.
+ feedText(decoders.out.end(), false, true);
+ feedText(decoders.err.end(), true, true);
+ finish(code);
+ });
+ child.on("exit", (code) => {
+ // Its output drains on `close`; a grandchild that keeps the pipes open
+ // after yt-dlp is gone is killed with the group, and the recorder returns.
+ setTimeout(() => {
+ if (done) return;
+ onLog(`[${label}] yt-dlp exited (${code ?? "signal"}); a process it started still holds its output: the group is killed.\n`);
+ killTree("SIGKILL");
+ child.stdout?.destroy();
+ child.stderr?.destroy();
+ finish(code);
+ }, RECORDER_EXIT_DRAIN_MS);
});
});
@@ -575,10 +850,37 @@ export type RecordLiveDeps = {
// The wait between two recorder attempts (default: a sleep a Cancel ends),
// and the stretch applied to it (default jitterMs, pacing.jitter).
wait?: (ms: number, signal: AbortSignal) => Promise<void>;
+ // The wait before each start-recovery try beside a live-edge recording
+ // (slice 2; default: `wait`).
+ recoveryWait?: (ms: number, signal: AbortSignal) => Promise<void>;
jitter?: (ms: number) => number;
// Whether the editor is shutting down (default: the job registry's): a run
// stopped then is `interrupted`, never `cancelled`.
shuttingDown?: () => boolean;
+ // The stall watchdog's look (default LIVE_WATCH_MS) and how long without
+ // growth is a stall (default settings.liveRecording.stallMinutes).
+ watchMs?: number;
+ stallMs?: number;
+ // The insurance recorder's look for the from-start part's first bytes
+ // (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;
+ // settings.liveRecording.insuranceWhenBehind, for a test.
+ insuranceWhenBehind?: boolean;
+ // 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 }>;
+ // (The landing's fragmentSeconds is in the default; a test's own ignores it.)
+ 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);
+ // null never joins.
+ join?: JoinDeps | null;
+ // The free-space floor (default RECORD_LIVE_MIN_FREE_BYTES).
+ minFreeBytes?: number;
};
export type RecordLiveJobOpts = {
@@ -587,7 +889,8 @@ export type RecordLiveJobOpts = {
plan: RecordLivePlan;
channelConfig: ChannelConfig;
cookiePolicy: ResolvedCookiePolicy;
- requestTranscription?: (slug: string, id: string) => Promise<{ ok: boolean; jobId?: string; error?: string }>;
+ // `replace`: transcribe again over an existing transcript (transcriptRedo).
+ requestTranscription?: (slug: string, id: string, o?: { replace?: boolean }) => Promise<{ ok: boolean; jobId?: string; error?: string }>;
// The pre-clip job for this stream (request.preclip), asked for once the
// first part begins.
startPreclip?: (slug: string, id: string, options: PreclipOptions) => Promise<{ ok: boolean; jobId?: string; error?: string }>;
@@ -661,12 +964,22 @@ async function defaultKickVod(
// ffmpeg through the heavy slot when the checkout has the gate (a stream copy
// of hours of video, as the landing's remux is).
-export async function runFfmpegHeavy(paths: Paths, args: string[], signal?: AbortSignal): Promise<void> {
+// `strict`: any line ffmpeg writes (it runs at -loglevel error) is a failure —
+// the editor's own merge of a recording's streams (REVIEW-6 3); the heavy
+// slot's own waiting lines are not ffmpeg's.
+export async function runFfmpegHeavy(paths: Paths, args: string[], signal?: AbortSignal, o: { strict?: boolean } = {}): Promise<void> {
const gate = paths.monorepoRoot ? path.join(paths.monorepoRoot, "scripts", "queue-lock.mjs") : null;
const gated = gate !== null && (await stat(gate).then((s) => s.isFile(), () => false));
- await execa(gated ? process.execPath : paths.ffmpegBin, gated ? [gate, "--heavy", "--", paths.ffmpegBin, ...args] : args, {
+ const r = await execa(gated ? process.execPath : paths.ffmpegBin, gated ? [gate, "--heavy", "--", paths.ffmpegBin, ...args] : args, {
...(signal ? { cancelSignal: signal } : {}),
});
+ if (o.strict) {
+ const said = String(r.stderr ?? "")
+ .split(/\r?\n/)
+ .map((l) => l.trim())
+ .filter((l) => l && !/^(?:queue-lock|heavy)[:\s]/i.test(l));
+ if (said.length) throw new Error(`ffmpeg's merge reported: ${said.slice(0, 3).join(" | ").slice(0, 400)}`);
+ }
}
export type ResolvedPart = { file: string; seconds: number | null; merged?: boolean } | { error: string };
@@ -717,7 +1030,16 @@ export async function resolvePart(
`merging them (stream copy) into ${path.basename(output)}.`,
);
await rm(output, { force: true });
- await io.merge(mergeStreamsArgs({ video: video.file, audio: audio.file, output, mp4 }));
+ try {
+ await io.merge(mergeStreamsArgs({ video: video.file, audio: audio.file, output, mp4 }));
+ } catch (err) {
+ // REVIEW-7 5: never left at a name the next run lands as finished.
+ const aside = path.join(dir, `${g.stem}.merge-failed-${Date.now()}.${mp4 ? "mp4" : "mkv"}`);
+ await rename(output, aside).catch(() => {});
+ throw new Error(
+ `${(err as Error).message} — the merge's output is set aside as ${path.basename(aside)}; the streams are kept as they are: merge them again by hand, or land the longest stream`,
+ );
+ }
const p = await io.probe(output);
if (!p?.audioCodec) return { error: `the merge of its streams (${path.basename(output)}) cannot be read` };
return { file: output, seconds: p.seconds, merged: true };
@@ -739,6 +1061,9 @@ type RunHooks = {
platform?: string;
record?: LiveRecordingRecord;
save?: () => Promise<void>;
+ // The failure is said on the interrupted run's row (a restart that found
+ // the stream's state unreadable): no row of its own.
+ quiet?: boolean;
};
const isMustKeep = (req: RecordLiveRequest) => req.doNotClean === true || Boolean(req.note);
@@ -761,7 +1086,7 @@ function stopOf(deps: RecordLiveDeps | undefined): { status: "interrupted" | "ca
// transcribe, keep (doNotClean) and its note, and the live pre-clip.
export function recordAgainRequest(req: RecordLiveRequest): Record<string, unknown> {
const out: Record<string, unknown> = {};
- for (const k of ["fromStart", "maxHeight", "separate", "transcribe", "doNotClean", "note", "preclip"] as const) {
+ for (const k of ["fromStart", "maxHeight", "separate", "transcribe", "doNotClean", "note", "preclip", "insurance"] as const) {
if (req[k] !== undefined) out[k] = req[k];
}
return out;
@@ -831,7 +1156,7 @@ export async function recordLiveRun(
hooks.record.error = message;
await hooks.save();
}
- } else if (hooks.id && !opts.request.dryRun) {
+ } else if (hooks.id && !opts.request.dryRun && !hooks.quiet) {
const failureClass = stopped ? undefined : liveFailureClass(message);
await upsertLiveRecordingRow(opts.paths, opts.request.slug, {
...rowOfRecord(
@@ -874,6 +1199,10 @@ async function recordLiveRunInner(
const stretch = deps.jitter ?? ((ms: number) => jitterMs(ms));
const runRecorder = deps.spawn ?? spawnRecorder;
const getText = deps.fetchText ?? fetchText;
+ const watchMs = deps.watchMs ?? LIVE_WATCH_MS;
+ // The free-space floor (tests set a small one).
+ const minFree = deps.minFreeBytes ?? RECORD_LIVE_MIN_FREE_BYTES;
+ const stallMs = deps.stallMs ?? liveStallMinutes() * 60_000;
const fromStart = req.fromStart !== false;
const maxHeight = req.maxHeight === undefined ? LIVE_DEFAULT_MAX_HEIGHT : req.maxHeight;
const cookies = alwaysCookies(opts.cookiePolicy);
@@ -936,6 +1265,7 @@ async function recordLiveRunInner(
await rmdir(videoDir).catch(() => {});
};
let extractionError: string | null = null;
+ let extractionErrObj: Error | null = null;
const refresh = () =>
refreshVideoMetadata({
paths,
@@ -949,20 +1279,208 @@ async function recordLiveRunInner(
requestedBy: RECORD_LIVE_JOB_KIND,
...(deps.refresh ? { run: deps.refresh } : {}),
});
+ // 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;
+ let endedByRefusal = false;
+ // REVIEW-7: what the LAST state read said (its live_status), or the class
+ // of its failure — `post_live` and a network failure decide what follows.
+ const lastRead: { status: string | null; failClass: LiveFailureClass | null; goodStatus: string | null } = { status: null, failClass: null, goodStatus: null };
+ 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 — 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") {
+ 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() };
+ // DESIGN-5 (c): its fragments answered 403 before this read: it went
+ // private while it was recorded.
+ if (c === "private") {
+ for (const p of hooks.record!.parts) {
+ if ((p.fragment403 ?? 0) > 0) {
+ p.failureClass = "went-private";
+ p.error = `its fragment requests were answered 403 Forbidden, and the stream reads private or removed: it went private while it was recorded`;
+ }
+ }
+ if (hooks.record!.parts.some((p) => p.failureClass === "went-private")) hooks.record!.failureClass = "went-private";
+ }
+ await hooks.save?.();
+ say(`The stream ${c === "ended" ? "is over" : "went private or was removed"} while it was recorded (${msg.split("\n")[0]}): what is held lands, and the row needs a person.`);
+ return "ended";
+ }
+ say(`The stream's metadata could not be read (${msg.split("\n")[0]}).`);
+ lastRead.status = null;
+ lastRead.failClass = c;
+ return "unknown";
+ }
+ const ls = (await readMeta(videoDir))?.live_status;
+ lastRead.status = typeof ls === "string" ? ls : null;
+ lastRead.failClass = null;
+ if (lastRead.status) lastRead.goodStatus = lastRead.status;
+ if (ls === "is_live") return "live";
+ if (ls === "was_live" || ls === "post_live" || ls === "not_live") {
+ endRead = true;
+ return "ended";
+ }
+ return "unknown";
+ };
+ // A RESTART BY THE BOOT PASS (req.resumeOf): what it found goes on the
+ // interrupted run's row.
+ // Only a run the boot pass asked for (its row marked starting/asked) is
+ // one: a stray resumeOf is ignored.
+ let resumeOf: string | null = null;
+ if (req.resumeOf) {
+ const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []);
+ const r = rows.find((x) => x.id === id && x.startedAt === req.resumeOf);
+ if (r && (r.restart?.state === "starting" || r.restart?.state === "asked")) resumeOf = req.resumeOf;
+ else say(`"resumeOf" ${req.resumeOf} names no run the boot pass is restarting: recorded as an ordinary run.`);
+ }
+ const markResume = async (state: LiveBootRestartState, extra: { reason?: string } = {}) => {
+ if (!resumeOf) return;
+ await markLiveBootRestart(paths, req.slug, id, resumeOf, { state, ...(opts.jobId ? { jobId: opts.jobId } : {}), ...extra }, now).catch(
+ (e: Error) => say(`The interrupted run's row could not be updated (${e.message}).`),
+ );
+ };
+ // The boot's landing of what was left: the old row says what it did.
+ const bootLandingDone = async (landedIt: boolean, why = "") => {
+ if (!resumeOf || !bootLanding) return;
+ await markResume(landedIt ? "landed" : "failed", { reason: landedIt ? bootLanding : `${bootLanding}: what was left was NOT landed — ${why}` });
+ };
+ // REVIEW-5 B3: what the interrupted run left in staging has a way into the
+ // store whatever the boot's run finds — the stream ended, removed, or its
+ // state not readable: the landing takes it (the only copy) by its rules.
+ const leftInStaging = async () =>
+ livePartFiles(id, await readdir(path.dirname(savedVideoDir(paths, opts.channelConfig, req.slug, id))).catch(() => [] as string[])).length;
+ let bootUnread: string | null = null;
+ // REVIEW-6 12: private or removed while the editor was down — said on the
+ // new record as when it happens while recording (endedBy).
+ let bootGone: { class: LiveFailureClass; message: string; at: string } | null = null;
try {
await refresh();
} catch (err) {
extractionError = (err as Error).message;
+ extractionErrObj = err as Error;
+ if (resumeOf) {
+ // Never a recording on a guess: the stream's state is not known. A
+ // reboot or a network drop is the commonest boot, so the read is made
+ // three times over about ten minutes (REVIEW-1 3.3 of live-guard-2) —
+ // not after a rate limit, members-only or the disk, which another read
+ // does not change.
+ let lastErr = err as Error;
+ let read = false;
+ const cls0 = liveFailureClass(lastErr.message);
+ if (cls0 !== "rate-limited" && cls0 !== "members" && cls0 !== "disk") {
+ for (const w of LIVE_BOOT_STATE_READ_WAITS_MS) {
+ say(`Restart after the editor restart: the stream's state could not be read (${lastErr.message.split("\n")[0]!.slice(0, 200)}); read again in ${spanWords(w / 1000)}.`);
+ await waitFor(stretch(w), signal);
+ if (signal.aborted) break;
+ try {
+ await refresh();
+ read = true;
+ break;
+ } catch (e) {
+ lastErr = e as Error;
+ const c = liveFailureClass(lastErr.message);
+ if (c === "rate-limited" || c === "members" || c === "disk") break;
+ }
+ }
+ }
+ if (read) extractionError = null;
+ else {
+ const reads = 1 + LIVE_BOOT_STATE_READ_WAITS_MS.length;
+ const gone = liveFailureClass(lastErr.message) === "private";
+ const first = lastErr.message.split("\n")[0]!.slice(0, 240);
+ if (await leftInStaging()) {
+ // Never a recording on a guess — but what is left lands.
+ // (Gone is the platform's word: the stream is confirmed done.)
+ if (gone) {
+ endedByRefusal = true;
+ bootGone = { class: "private", message: first, at: now().toISOString() };
+ }
+ bootUnread = gone
+ ? `the stream was made private or removed while the editor was down (${first})`
+ : `the stream's state could not be read (${reads} reads: ${first}) — it may still be live and is NOT being recorded: Record again if it is`;
+ say(`Restart after the editor restart: ${bootUnread}; what the interrupted run left in staging is landed.`);
+ extractionError = null;
+ } else {
+ const reason = `${first} — the stream may still be live and is NOT being recorded`;
+ say(`Restart after the editor restart: the stream's state could not be read (${reason}); nothing is recorded or landed — Record again if it is still live.`);
+ await markResume("unknown", { reason: `${reads} reads failed: ${reason}` });
+ hooks.quiet = true;
+ await abandon();
+ throw lastErr;
+ }
+ }
+ }
+ }
+ if (extractionError !== null) {
const canFallBack = BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(extractionError);
if (!canFallBack) {
await abandon();
- throw err;
+ throw extractionErrObj ?? new Error(extractionError);
}
say(`yt-dlp could not read the stream (${extractionError.split("\n")[0]}); recording from the page's own playlist.`);
}
const meta = await readMeta(videoDir);
const liveStatus = typeof meta?.live_status === "string" ? meta.live_status : null;
- if (meta && liveStatus && !LIVE_STATES.has(liveStatus)) {
+ // (The run's first read is the first "last read".)
+ lastRead.status = liveStatus;
+ lastRead.goodStatus = liveStatus;
+ // A restart of a stream that has ended records nothing: what the
+ // interrupted run left in staging lands (the slice-1 landing), or, with
+ // nothing there, the row says so.
+ let resumeEnded = false;
+ // The words the interrupted run's row gets once the landing is done.
+ let bootLanding: string | null = null;
+ if (resumeOf && bootUnread) {
+ resumeEnded = true;
+ endRead = true;
+ bootLanding = bootUnread;
+ await markResume("landing", { reason: bootUnread });
+ } else if (resumeOf) {
+ if (!meta || !liveStatus) {
+ say("Restart after the editor restart: the stream's record says nothing of its state — nothing is recorded or landed.");
+ await markResume("unknown", { reason: "the metadata names no live_status" });
+ hooks.quiet = true;
+ await abandon();
+ throw new Error(`${plan.url}: its live state is not known; not restarted`);
+ }
+ if (!LIVE_STATES.has(liveStatus)) {
+ const stage = path.dirname(savedVideoDir(paths, opts.channelConfig, req.slug, id));
+ const left = livePartFiles(id, await readdir(stage).catch(() => [] as string[]));
+ if (!left.length) {
+ say(`Restart after the editor restart: the stream has ended (${liveStatus}) and nothing is left in staging — nothing more to record or land.`);
+ await markResume("ended");
+ summary.status = "interrupted";
+ say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
+ return summary;
+ }
+ say(`Restart after the editor restart: the stream has ended (${liveStatus}); the ${left.length} part(s) left in staging are landed.`);
+ bootLanding = `the stream had ended by the restart (${liveStatus})`;
+ await markResume("landing", { reason: bootLanding });
+ resumeEnded = true;
+ endRead = true;
+ } else {
+ say(`Restart after the editor restart: the stream is ${liveStatus}; recording again.`);
+ await markResume("restarted");
+ }
+ }
+ if (!resumeEnded && meta && liveStatus && !LIVE_STATES.has(liveStatus)) {
await abandon();
throw new Error(
`${plan.url} is not live (live_status ${liveStatus}): download it as a video, or import a recording of it`,
@@ -979,9 +1497,9 @@ async function recordLiveRunInner(
await ensureStoreRoot(paths, storeRoot, "nothing recorded");
await assertSavedVideosStoreWritable(paths, storeDir);
const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot);
- if (free < RECORD_LIVE_MIN_FREE_BYTES) {
+ if (free < minFree) {
throw new Error(
- `the store's disk has ${formatBytes(free)} free; a live recording needs ${formatBytes(RECORD_LIVE_MIN_FREE_BYTES)} — nothing recorded`,
+ `the store's disk has ${formatBytes(free)} free; a live recording needs ${formatBytes(minFree)} — nothing recorded`,
);
}
} catch (err) {
@@ -1002,6 +1520,7 @@ async function recordLiveRunInner(
const streamStartSec =
typeof meta?.release_timestamp === "number" ? (meta.release_timestamp as number) : typeof meta?.timestamp === "number" ? (meta.timestamp as number) : null;
const record: LiveRecordingRecord = {
+ ...(bootGone ? { endedBy: bootGone } : {}),
status: "recording",
url: plan.url,
platform: plan.platform,
@@ -1013,6 +1532,7 @@ async function recordLiveRunInner(
mustKeep: isMustKeep(req),
...(opts.jobId ? { jobId: opts.jobId } : {}),
...(streamStartSec !== null ? { streamStartedAt: new Date(streamStartSec * 1000).toISOString() } : {}),
+ ...(resumeOf ? { resumeOf } : {}),
};
// The record beside the video, and the channel's row (which outlives it).
let rowWarned = false;
@@ -1032,7 +1552,7 @@ async function recordLiveRunInner(
// (Not for separate streams from the start: YouTube's DASH from the start is
// not the HLS playlist the record lists, which holds only the live edge.)
const fmt = meta ? hlsFormatOf(meta, maxHeight) : null;
- if (fmt && plan.platform !== "kick" && !(separate && fromStart)) {
+ if (fmt && !resumeEnded && plan.platform !== "kick" && !(separate && fromStart)) {
try {
const pl = parsePlaylist(await getText(fmt.url, signal), fmt.url);
if (pl?.kind === "media") {
@@ -1099,7 +1619,8 @@ async function recordLiveRunInner(
if (youtube) {
// Its age: from its start time, else (an ended stream) its duration.
const age = streamStartSec !== null ? now().getTime() / 1000 - streamStartSec : typeof meta?.duration === "number" ? (meta.duration as number) : null;
- return age !== null && age < 120 * 3600;
+ // (119 h: an hour's margin, REVIEW-5 note 8.)
+ return age !== null && age * 1000 < LIVE_RESUME_MAX_AGE_MS;
}
return first && record.reach?.fromStart === true;
};
@@ -1108,28 +1629,72 @@ async function recordLiveRunInner(
tag: string,
mode: "from-start" | "index0" | "now",
extraNote = "",
- // The run's first attempt, made with no wait before it.
- firstAttempt = false,
- ): Promise<RecorderOutcome> => {
- const file = separate ? stemPath(tag) : partPath(tag);
- const part = begin("ytdlp", url, file, mode !== "now");
+ // recovery: a slice-2 try. noWait: never `--wait-for-video` (a restart or
+ // a try is of a stream already live). watch: the stall watchdog (off for
+ // Kick's channel recorder, which its VOD poll ends).
+ // insurance: slice 4's part. stop: a stop of this recorder alone (the
+ // insurance's, once caught up). onStart: its stem, once begun. onLine:
+ // every line it prints.
+ opts: {
+ recovery?: boolean;
+ restart?: number;
+ noWait?: boolean;
+ watch?: boolean;
+ insurance?: boolean;
+ 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; provenStart?: boolean; lock?: StemLock };
+ // 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; fragAbort?: { index: number | null }; locked?: string; urlRefresh?: boolean }> => {
+ 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;
if (mode === "index0") part.index0 = true;
- // PROVEN from the stream's start — a fact about what is recorded, not the
- // flag passed (REVIEW-LF-2 1): YouTube's from-start formats are the
- // extractor's own generator from fragment 0, on a stream under 120 h old
- // (past it the generator starts 120 h back); any other `--live-from-start`
- // (Rumble, Twitch: ffmpeg at the DVR playlist's first LISTED segment, a
- // window that slides) only when THIS run's playlist read listed the
- // start, and only for the first attempt (a wait lets the window slide).
- if (mode === "from-start" && startProvable(firstAttempt)) part.provenStart = true;
+ // PROVEN from the stream's start (main's rule, REVIEW-LF-2/3): by what is
+ // recorded — a YouTube `--live-from-start` part on a stream under 120 h
+ // old; another platform's only on the first attempt whose playlist read
+ // listed the start. A RESUME continues the same file from its saved
+ // fragment, so it keeps the mark the ORIGINAL run earned (this run's part,
+ // or the earlier run's by its row) and never earns one itself; a
+ // recovery try or a live-edge part never gets one.
+ if (opts.resume) {
+ if (!known && opts.resume.provenStart) part.provenStart = true;
+ } else if (mode === "from-start" && !opts.recovery && startProvable(opts.firstAttempt === true)) part.provenStart = true;
+ const stem = part.stem!;
+ opts.onStart?.(stem);
await save();
+ const waitForVideo = !opts.noWait && liveStatus === "is_upcoming" && tag !== "channel";
const args = ytdlpLiveArgs({
url,
output: file,
fromStart: mode === "from-start",
maxHeight,
separate,
- waitForVideo: liveStatus === "is_upcoming" && tag !== "channel",
+ waitForVideo,
+ ...(opts.resume ? { format: opts.resume.formats } : {}),
+ ...(opts.allowSkip ? { allowSkip: true } : {}),
channelArgs: [
...channelExtraArgs(cfg, cookies),
"--downloader-args",
@@ -1138,20 +1703,464 @@ async function recordLiveRunInner(
});
// The recorder's argv does not pass jitterYtdlpSleeps: asked here.
refuseInstagramYtdlp(args);
- const o = await runRecorder({ bin: paths.ytdlpBin, args, cwd: channelDir, onLog, signal, label: tag });
- finish(part, `${extraNote}yt-dlp exit ${o.exitCode ?? "null"}${o.signalled ? " (stopped)" : ""}`);
+ // SLICE 3 — THE STALL WATCHDOG: this recorder's own stop, besides the
+ // 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.
+ // REVIEW-5 B4: SIGTERM only for a part that CAN be resumed at the moment
+ // of the stop (separate streams, each with its state); every other
+ // recorder — a muxed ffmpeg download keeps no state — gets SIGINT, which
+ // finishes its file.
+ const resumable = mode === "from-start";
+ const stopHow = async (): Promise<"SIGTERM" | "SIGINT"> =>
+ resumable && separate && (await resumeStateOf(stem, { accounting: false }).catch(() => ({ ok: false }))).ok ? "SIGTERM" : "SIGINT";
+ const own = new AbortController();
+ const onJobAbort = () => {
+ if (!(resumable && stopOf(deps).by === "shutdown")) return own.abort("SIGINT");
+ void stopHow().then((how) => own.abort(how));
+ };
+ const onOwnStop = () => own.abort("SIGINT");
+ if (signal.aborted) onJobAbort();
+ else if (opts.stop?.aborted) onOwnStop();
+ else {
+ signal.addEventListener("abort", onJobAbort, { once: true });
+ opts.stop?.addEventListener("abort", onOwnStop, { once: true });
+ }
+ // DESIGN-4 1 / DESIGN-5 7 — THE KEPT FRAGMENTS, once a watch tick: every
+ // fragment stays until the stream is confirmed done (the platform says it
+ // is over AND the landed file is verified) — the bytes a restart reuses.
+ // The stream files plus their fragments are twice the stream on disk.
+ // Short of disk (under the floor) the recorder goes on and the fragments
+ // go — resumability lost, said, the row loud — never the reverse, never
+ // silently. A fragment number missing among the kept ones is a skip.
+ const keptFragmentsTick = async () => {
+ const g = await filesOf(stem);
+ if (!g) return;
+ 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;
+ }
+ // DESIGN-5 7: NO prune while recording — every fragment stays until
+ // the stream is confirmed done; a number missing among them is a skip.
+ const names = await readdir(slugStore).catch(() => [] as string[]);
+ const idx = await readYtdlIndex(path.join(slugStore, f));
+ const kept = fragNumbers(f, names).filter((n) => typeof idx !== "number" || n <= idx);
+ const gaps = kept.length ? fragmentGaps(kept, 1) : [];
+ if (gaps.length) {
+ const sf = (part.skippedFragments ??= { count: 0, positions: [] });
+ for (const n of gaps) {
+ if (sf.positions.includes(n)) continue;
+ sf.positions.push(n);
+ sf.count += 1;
+ }
+ await writeStemMarks(slugStore, stem, { skipped: sf });
+ }
+ }
+ };
+ 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();
+ let busy = false;
+ // REVIEW-5 note 1: EACH stream file of a separate from-start part must
+ // grow, not their sum — one format's thread may end alone (yt-dlp) while
+ // the other goes on for hours.
+ const perStream = new Map<string, { size: number; at: number }>();
+ timer = setInterval(() => {
+ if (busy || own.signal.aborted) return;
+ busy = true;
+ inFlight = (async () => {
+ if (separate && mode === "from-start") await keptFragmentsTick();
+ const b = await allBytesOf(stem);
+ const t = now().getTime();
+ let still: string | null = null;
+ if (separate && mode !== "now") {
+ const g = await filesOf(stem);
+ for (const f of g?.streams ?? []) {
+ const size = await sizeOf(path.join(slugStore, f));
+ const was = perStream.get(f);
+ if (!was || size !== was.size) perStream.set(f, { size, at: t });
+ else if (t - was.at >= stallMs && b > 0 && !(waitForVideo && b === 0)) still = f;
+ }
+ }
+ if (still === null && (b !== last || (waitForVideo && b === 0))) {
+ last = b;
+ lastGrowth = t;
+ return;
+ }
+ if (b !== last) {
+ last = b;
+ lastGrowth = t;
+ }
+ const since = still !== null ? t - perStream.get(still)!.at : t - lastGrowth;
+ if (since >= stallMs && !own.signal.aborted) {
+ stalled = true;
+ const how = await stopHow();
+ say(
+ (still !== null
+ ? `[${tag}] stalled: its stream ${still} has not grown for ${spanWords(since / 1000)} while the part's files did`
+ : `[${tag}] stalled: its files have not grown for ${spanWords(since / 1000)} (${formatBytes(b)})`) +
+ `; stopping this recorder (${how === "SIGTERM" ? "SIGTERM: its state is kept for the resume" : "SIGINT"}); its part is kept.`,
+ );
+ own.abort(how);
+ }
+ })()
+ .catch(() => {})
+ .finally(() => {
+ busy = false;
+ });
+ }, watchMs);
+ }
+ const streamBefore = opts.resume ? await streamBytesOf(stem) : 0;
+ // 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 = opts.resume?.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;
+ // This run's own failed URL refresh (the part's class may be an earlier run's).
+ let urlRefreshHere = false;
+ 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 });
+ }
+ // DESIGN-5 2: the URL could not be refreshed — said in plain words, on
+ // the part, as it is printed (the last lines before the exit are the
+ // merge's, not this).
+ const refresh = /Cannot find refreshed url for format (\S+?)[;,]/i.exec(l);
+ if (refresh) urlRefreshHere = true;
+ if (refresh || (/Giving up after \d+ retries/i.test(l) && part.failureClass === "url-refresh")) {
+ if (part.failureClass !== "url-refresh") {
+ part.failureClass = "url-refresh";
+ part.error = `yt-dlp could not refresh the stream's URL for format ${refresh?.[1] ?? "?"}: the platform stopped serving it (its DVR switched off?); yt-dlp then ends by itself`;
+ say(`[${tag}] ${part.error}.`);
+ }
+ }
+ if (/HTTP Error 403: Forbidden/i.test(l) && /fragment/i.test(l)) part.fragment403 = (part.fragment403 ?? 0) + 1;
+ if (isFragmentFatalLine(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({
+ bin: paths.ytdlpBin,
+ args,
+ cwd: channelDir,
+ onLog,
+ signal: own.signal,
+ label: tag,
+ onLine: lineHook,
+ onSpawn: (pid) => void lock.setRecorder(pid),
+ });
+ } 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)") : ""}`);
+ // REVIEW-5 B5: a stream that recorded nothing is said at once, when its
+ // recorder stops, not at the landing.
+ if (separate && mode !== "now") {
+ const miss = await missingStreamOf(stem).catch(() => null);
+ if (miss) {
+ part.missingStream = miss;
+ record.missingStream = miss;
+ say(`[${tag}] its ${miss === "unknown" ? "video or audio" : miss} stream has recorded nothing so far: it needs a person if no resume fills it.`);
+ } else if (part.missingStream && (await bytesOf(stem)) > 0) {
+ // A resume filled it.
+ delete part.missingStream;
+ }
+ }
+ if (fragAbort && part.fragmentErrors) await save();
+ // REVIEW-7 2 / REVIEW-8 2: after a resume that wrote, each stream file
+ // must still be what its fragments prove — with its state, the equation
+ // (fragments 1..index, a torn tail the repair allows, sizes and the last
+ // fragment's bytes: cheap); finished (no state), byte for byte. Said, and
+ // the part loud, when it is not; the mark clears when a later check holds.
+ if (opts.resume && separate && !part.fragmentsDropped && (await streamBytesOf(stem)) > streamBefore) {
+ let damaged: string | null = null;
+ const g = await filesOf(stem);
+ for (const f of g?.streams ?? []) {
+ const idx = await readYtdlIndex(path.join(slugStore, f));
+ if (typeof idx === "number") {
+ const r = await reconcileStream(slugStore, f, false).catch((e: Error) => ({ ok: false as const, why: e.message }));
+ if (!r.ok) damaged = r.why;
+ } else if (idx === "absent") {
+ const eq = await streamEqualsFragments(slugStore, f).catch((e: Error) => ({ ok: false as const, why: e.message }));
+ if (eq && !eq.ok) damaged = eq.why;
+ }
+ if (damaged) break;
+ }
+ if (damaged) {
+ part.resumeDamaged = damaged;
+ say(`[${tag}] after the resume, ${damaged}: the file is kept as it is and never removed; the row needs a person.`);
+ } else delete part.resumeDamaged;
+ }
await save();
- return o;
+ return { ...o, part, stem, stalled, ...(fragAbort ? { fragAbort } : {}), ...(urlRefreshHere ? { urlRefresh: true } : {}) };
};
const sizeOf = (f: string) => stat(f).then((s) => s.size, () => 0);
const filesOf = async (stem: string): Promise<LivePartFiles | null> =>
livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])).find((g) => g.stem === stem) ?? null;
+ const streamBytesOf = async (stem: string) => {
+ const g = await filesOf(stem);
+ let n = 0;
+ for (const f of g?.streams ?? []) n += await sizeOf(path.join(slugStore, f));
+ return n;
+ };
const bytesOf = async (stem: string) => {
const g = await filesOf(stem);
let n = 0;
for (const f of g ? [...g.finished, ...g.streams] : []) n += await sizeOf(path.join(slugStore, f));
return n;
};
+ // THE FLOOR BEFORE EVERY SPAWN (REVIEW-1 2.3 of live-guard-2): a recorder,
+ // a try, a restart or the insurance starts only with
+ // RECORD_LIVE_MIN_FREE_BYTES free on the store's disk; one that would breach
+ // it does not start, and the row says so (spaceHeld, needing a person).
+ // The floor scales with the stream (REVIEW-2 3.4): max(the floor, twice the
+ // largest part of this run so far) — a new part may grow as large, and a
+ // landing's merge needs as much again.
+ // REVIEW-6 7: before a resume in place, the floor plus the stream files'
+ // size (the files continue; the kept fragments and merges are not new).
+ const roomFor = async (what: string, o: { resumeStem?: string } = {}): Promise<boolean> => {
+ let largest = 0;
+ for (const p of parts) largest = Math.max(largest, await allBytesOf(p.stem));
+ const need = o.resumeStem ? minFree + (await streamBytesOf(o.resumeStem)) : Math.max(minFree, 2 * largest);
+ const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0);
+ if (free >= need) return true;
+ (record.spaceHeld ??= []).push({ what, at: now().toISOString(), freeBytes: free });
+ say(`${what}: NOT started — the store's disk has ${formatBytes(free)} free, at least ${formatBytes(need)} are needed.`);
+ 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.
+ // `accounting` false: the structure only (the stop signal's choice, made
+ // while the recorder still writes — the byte equation is for a stopped file).
+ const resumeStateOf = async (stem: string, o: { accounting?: boolean } = {}): Promise<{ ok: true; formats: string; fragment: number } | { ok: false; why: string }> => {
+ const g = await filesOf(stem);
+ if (!g) return { ok: false, why: "its files are gone" };
+ // EVERY stream file of the stem, an empty one included (REVIEW-5 B5):
+ // yt-dlp opens both and writes their state before any fragment, and
+ // resumes an empty one from 0 — pinning only the ones with bytes would
+ // record the rest of the stream without that stream.
+ const streams = [...g.streams];
+ if (!streams.length) return { ok: false, why: g.finished.length ? "it was finished (merged)" : "nothing to resume" };
+ if (!(await bytesOf(stem))) return { ok: false, why: "nothing to resume" };
+ let fragment = Infinity;
+ for (const f of streams) {
+ let raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null);
+ // REVIEW-6 11: a state caught mid-rewrite is read again once.
+ if (raw !== null && readYtdlRaw(raw) === null) {
+ await new Promise((r) => setTimeout(r, 50));
+ raw = await readFile(path.join(slugStore, `${f}.ytdl`), "utf8").catch(() => null);
+ }
+ if (raw === null) {
+ // An empty stream file with no state yet is resumed from 0.
+ if ((await sizeOf(path.join(slugStore, f))) === 0) {
+ fragment = Math.min(fragment, 0);
+ continue;
+ }
+ return { ok: false, why: `${f} has no .ytdl state (finished, or never kept)` };
+ }
+ let idx: unknown;
+ try {
+ idx = (JSON.parse(raw) as { downloader?: { current_fragment?: { index?: unknown } } }).downloader?.current_fragment?.index;
+ } 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;
+ // An unknown start is not provable (REVIEW-5 note 8): no resume.
+ if (!Number.isFinite(startMs)) return { ok: false, why: "the stream's start time is not known" };
+ if (now().getTime() - startMs > LIVE_RESUME_MAX_AGE_MS) return { ok: false, why: "the stream is over 119 h old" };
+ const ids = streams.map((f) => /\.f([^.]+)\.[a-z0-9]+$/i.exec(f)?.[1]).filter((x): x is string => !!x);
+ if (ids.length !== streams.length) return { ok: false, why: "its format ids cannot be read from its files" };
+ if (separate) {
+ // A separate recording is a picture and a sound: fewer than two, or two
+ // of one kind, is not that recording.
+ if (new Set(ids).size < 2) return { ok: false, why: `only one stream (${ids.join(", ")}) of a separate recording` };
+ const kinds: string[] = [];
+ for (const [k, f] of streams.entries()) {
+ const fm = Array.isArray(meta?.formats) ? (meta!.formats as Array<Record<string, unknown>>).find((x) => String(x.format_id) === ids[k]) : undefined;
+ let kind: string | null = fm ? (fm.vcodec === "none" ? "audio" : fm.acodec === "none" ? "video" : "both") : null;
+ if (!kind && (await sizeOf(path.join(slugStore, f))) > 0) {
+ const pv = await probe(path.join(slugStore, f)).catch(() => null);
+ kind = pv ? (pv.videoCodec && pv.audioCodec ? "both" : pv.videoCodec ? "video" : pv.audioCodec ? "audio" : null) : null;
+ }
+ if (kind) kinds.push(kind);
+ }
+ if (kinds.filter((x) => x === "video").length > 1 || kinds.filter((x) => x === "audio").length > 1) {
+ return { ok: false, why: `two streams of one kind (${ids.join(", ")})` };
+ }
+ }
+ // 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)` };
+ if (o.accounting !== false) {
+ for (const f of streams) {
+ const r = await reconcileStream(slugStore, f, false);
+ if (!r.ok) return { ok: false, why: r.why };
+ }
+ }
+ return { ok: true, formats: ids.join("+"), fragment: Number.isFinite(fragment) ? fragment : 0 };
+ };
+ // DESIGN-5 7 — REUSE AFTER A SELF-EXIT: yt-dlp finished the part (merged,
+ // its `.ytdl` removed) while the stream went on. Measured (LOG, point 7):
+ // the same -o reuses what is on disk only with a state whose index is right
+ // and the merged copy NOT at its final name (else "already downloaded" and
+ // nothing is recorded). So each kept stream file must equal its kept
+ // fragments 1..N exactly (contiguous); then its state is written at N and
+ // the merged copies are moved aside (scratch, until confirmed done).
+ // `apply` false: whether it can be.
+ const restoreForReuse = async (stem: string, apply: boolean): Promise<{ ok: true; fragments: number } | { ok: false; why: string }> => {
+ const g = await filesOf(stem);
+ if (!g || g.streams.length < (separate ? 2 : 1)) return { ok: false, why: "its stream files were not kept" };
+ const names = await readdir(slugStore).catch(() => [] as string[]);
+ const counts: number[] = [];
+ for (const f of g.streams) {
+ const file = path.join(slugStore, f);
+ const idx = await readYtdlIndex(file);
+ // REVIEW-6 13: per stream — one that still has its state is resumed as
+ // it is (its accounting is checked before the resume); one without is
+ // rebuilt from its kept fragments.
+ if (typeof idx === "number") {
+ counts.push(-1);
+ continue;
+ }
+ if (idx === null) return { ok: false, why: `${f}.ytdl does not read` };
+ const kept = fragNumbers(f, names);
+ const k = kept.length && kept[kept.length - 1] === kept.length ? kept.length : 0;
+ if (!k) return { ok: false, why: `${f}: its kept fragments are not 1..N without a gap` };
+ let sum = 0;
+ for (let n = 1; n <= k; n++) sum += await sizeOf(path.join(slugStore, `${f}-Frag${n}`));
+ const size = await sizeOf(file);
+ if (sum !== size) return { ok: false, why: `${f} is ${size} bytes, its ${k} kept fragments ${sum}` };
+ counts.push(k);
+ }
+ if (!counts.some((c) => c >= 0)) return { ok: false, why: "every stream still has its state (a resume, not a reuse)" };
+ if (apply) {
+ for (const [i, f] of g.streams.entries()) {
+ if (counts[i]! < 0) continue;
+ await writeFile(path.join(slugStore, `${f}.ytdl`), JSON.stringify({ downloader: { current_fragment: { index: counts[i] } } }));
+ }
+ const stamp = Date.now();
+ // REVIEW-6 8: one moved-aside merge at a time (each self-exit would
+ // leave another full copy of the stream so far).
+ for (const f of g.scratch) if (/\.premerge-\d+\.[a-z0-9]+$/i.test(f)) await rm(path.join(slugStore, f), { force: true });
+ for (const f of g.finished) {
+ const m = /^(.*)\.([a-z0-9]+)$/i.exec(f);
+ if (m) await rename(path.join(slugStore, f), path.join(slugStore, `${m[1]}.premerge-${stamp}.${m[2]}`)).catch(() => {});
+ }
+ say(`${stem}: yt-dlp had finished it while the stream went on; its state is rebuilt at the ${Math.min(...counts.filter((c) => c >= 0))} fragments its kept files prove, the merged copy moved aside — resumed, reusing what is on disk.`);
+ }
+ return { ok: true, fragments: Math.min(...counts.filter((c) => c >= 0)) };
+ };
+ // The one repair (DESIGN-4 1), made just before a resume: a torn last
+ // append truncated back, logged with both lengths. Anything it cannot
+ // prove: no resume in place.
+ // REVIEW-7 6: the stem's lock is taken FIRST — never a repair under a
+ // recorder that still writes those files — and handed to the resume.
+ const reconcileForResume = async (stem: string): Promise<{ ok: true; lock: StemLock } | { ok: false; why: string }> => {
+ const lock = await takeStemLock(slugStore, stem);
+ if (!lock.ok) return { ok: false, why: lock.why };
+ const fail = async (why: string) => {
+ await lock.release();
+ return { ok: false as const, why };
+ };
+ const g = await filesOf(stem);
+ for (const f of g?.streams ?? []) {
+ const r = await reconcileStream(slugStore, f, true, say);
+ if (!r.ok) return fail(r.why);
+ // REVIEW-6 2: no kept fragment past the index may meet the resume.
+ const idx = await readYtdlIndex(path.join(slugStore, f));
+ if (typeof idx !== "number") return fail(`${f}.ytdl does not read`);
+ const gone = await dropFragmentsAbove(slugStore, f, idx);
+ if (gone.length) say(`${f}: fragment(s) ${gone.join(", ")} past its state (${idx}) removed before the resume (a complete one would be refused, 416, and the resume would record nothing).`);
+ }
+ return { ok: true, lock };
+ };
+ // 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);
+ 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) => {
+ const g = await filesOf(stem);
+ let n = 0;
+ for (const f of g ? [...g.finished, ...g.streams, ...g.scratch] : []) n += await sizeOf(path.join(slugStore, f));
+ return n;
+ };
const probe = deps.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s));
// A separate-streams part where only one stream wrote bytes: which is
// missing (null: both wrote, or a finished file holds them).
@@ -1167,14 +2176,16 @@ async function recordLiveRunInner(
return p?.videoCodec ? "audio" : p?.audioCodec ? "video" : "unknown";
};
- if (plan.platform === "kick") {
+ if (resumeEnded) {
+ // Nothing to record: straight to the landing.
+ } else if (plan.platform === "kick") {
const vodFmt = fmt;
const channel = plan.kickChannel ?? (typeof meta?.uploader_id === "string" ? meta.uploader_id : null);
let liveDone = channel === null;
if (channel === null) say("The record names no Kick channel: only the VOD is recorded.");
const live = channel
? (async () => {
- const o = await ytdlpPart(`https://kick.com/${channel}`, "channel", "now");
+ const o = await ytdlpPart(`https://kick.com/${channel}`, "channel", "now", "", { watch: false });
liveDone = true;
return o;
})()
@@ -1221,29 +2232,572 @@ async function recordLiveRunInner(
// stream end often exits 1), a Cancel and an argv no try can fix end the
// attempts.
const schedule = liveAttemptSchedule(fromStart);
+ // SLICE 4 — THE INSURANCE RECORDER (lib/liveCapture.ts LiveInsurance):
+ // the live edge beside the from-start recording while it catches up.
+ // On by default when the stream is marked keep before or when the
+ // recording starts; the request's `insurance` overrides. Not for an
+ // upcoming stream (its from-start recording is never behind).
+ const keepMarked =
+ req.doNotClean === true ||
+ (await isDoNotClean(videoDir).catch(() => false)) ||
+ (await loadPendingKeep(paths, req.slug).catch(() => [])).some((e) => e.id === id);
+ let decided = fromStart && liveStatus !== "is_upcoming" ? insuranceDecision({ asked: req.insurance, keepMarked }) : null;
+ if (!decided && req.insurance) say("No insurance recorder: it runs only beside a from-start recording of a stream already live.");
+ // The insurance's stop: replaced when a from-start restart re-arms it.
+ let insureStop = new AbortController();
+ const mainDoneCtl = new AbortController();
+ let insuranceStopFor: "caught-up" | "ended" | "fallback" | null = null;
+ 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;
+ const margin = deps.insuranceMarginMs ?? LIVE_INSURANCE_MARGIN_MS;
+ // The main recorder's parts: which one records now, and its progress.
+ // A from-start RESTART is behind the live edge again: the catch-up is
+ // read afresh and a stopped insurance is re-armed (REVIEW-1 3.2 of
+ // live-guard-2). A fall back to the live edge stops the insurance.
+ // Re-arm a stopped insurance (within its bound) beside a from-start
+ // capture that is behind again: a recovery try (REVIEW-3 3.2).
+ // True when a start follows (REVIEW-7 3: never "re-armed" in the log
+ // when nothing starts).
+ const rearmInsurance = (): boolean => {
+ // Not while a live-edge main records already (REVIEW-4 1.2).
+ if (!record.insurance || !mainFromStart) return false;
+ if (caughtUpTimer) clearTimeout(caughtUpTimer);
+ caughtUpTimer = null;
+ if (insureStop.signal.aborted && insuranceStopFor === "caught-up") {
+ insureStop = new AbortController();
+ insuranceStopFor = null;
+ }
+ const r = rearm;
+ r?.();
+ return r !== null;
+ };
+ // 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) => {
+ // REVIEW-7 7: a from-start part that printed no `frag N/M` line could
+ // not be judged behind or not — said on its part.
+ if (mainStem && mainStem !== stem && mainFromStart && !behindChecked.has(mainStem)) {
+ const prev = parts.find((x) => x.stem === mainStem)?.part;
+ if (prev && (prev.bytes ?? 0) > 0) prev.behindUnknown ??= "it printed no frag N/M line";
+ }
+ if (stem !== mainStem) mainTracker.reset();
+ mainStem = stem;
+ mainFromStart = mode !== "now";
+ tracker.reset();
+ if (!record.insurance) return;
+ if (mode === "now" && !restart && !insureStop.signal.aborted) {
+ insuranceStopFor = "fallback";
+ insureStop.abort();
+ }
+ // (No re-arm on every restart or resume: DESIGN-5 point 5 — the
+ // behind check below starts or re-arms it when a part is far behind.)
+ void restart;
+ };
+ // DESIGN-5 POINT 5 (the orchestrator's go, settings.liveRecording.
+ // insuranceWhenBehind): a from-start main part's FIRST `frag N/M` shows
+ // how far behind the live edge it is — the stream's age × (1 − N/M).
+ // More than 10 min: the live-edge insurance starts beside it (or is
+ // re-armed), whatever the keep mark, so the tail is held while it
+ // catches up. Once per part.
+ const behindChecked = new Set<string>();
+ const behindCheck = (l: string) => {
+ if (!mainFromStart || !mainStem || behindChecked.has(mainStem)) return;
+ const fp = parseFragProgress(l);
+ if (!fp || fp.total <= 0) return;
+ behindChecked.add(mainStem);
+ const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN;
+ const mainPart = parts.find((x) => x.stem === mainStem)?.part;
+ if (!Number.isFinite(startMs)) {
+ if (mainPart) mainPart.behindUnknown = "the stream's start time is not known";
+ say(`${mainStem}: how far behind the live edge it is cannot be told (the stream's start time is not known): no live-edge insurance by the behind rule.`);
+ return;
+ }
+ const behind = ((now().getTime() - startMs) / 1000) * (1 - fp.frag / fp.total);
+ if (behind <= LIVE_INSURANCE_BEHIND_SECONDS) return;
+ // REVIEW-7 7: a live-edge recorder only beside a stream that reads LIVE
+ // (a boot run on a post_live stream behind must not start one) — by the
+ // last read that READ (REVIEW-8 1: a failed one says nothing), and said.
+ if (lastRead.goodStatus !== "is_live") {
+ say(`${mainStem} is about ${spanWords(behind)} behind, but the stream did not last read live (${lastRead.goodStatus ?? "unknown"}): no live-edge recorder beside it.`);
+ return;
+ }
+ if (req.insurance === false) return;
+ if (!(deps.insuranceWhenBehind ?? liveInsuranceWhenBehind())) {
+ say(`${mainStem} is about ${spanWords(behind)} behind the live edge; no live-edge recorder beside it (settings.liveRecording.insuranceWhenBehind is off).`);
+ return;
+ }
+ if (!insurance || insuranceReturned) {
+ // (REVIEW-7 3: also when an earlier insurance loop has returned.)
+ decided = decided ?? { mode: "catch-up", by: "behind" };
+ if (insuranceReturned) {
+ insureStop = new AbortController();
+ insuranceStopFor = null;
+ }
+ say(`${mainStem} is about ${spanWords(behind)} behind the live edge: a live-edge recorder (the insurance) starts beside it, so the tail is held while it catches up.`);
+ startInsuranceLoop();
+ } else if (rearmInsurance()) {
+ say(`${mainStem} is about ${spanWords(behind)} behind the live edge: the insurance is re-armed beside it.`);
+ } else {
+ say(`${mainStem} is about ${spanWords(behind)} behind the live edge; the insurance recorder is already recording beside it.`);
+ }
+ };
+ const onMainLine = (l: string) => {
+ behindCheck(l);
+ 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)}.`);
+ const stopping = insureStop;
+ caughtUpTimer = setTimeout(() => {
+ caughtUpTimer = null;
+ if (stopping !== insureStop) return;
+ insuranceStopFor = "caught-up";
+ stopping.abort();
+ }, margin);
+ };
+ // True when re-armed; false when the main recording ended or a Cancel.
+ const waitRearm = () =>
+ new Promise<boolean>((resolve) => {
+ if (mainDoneCtl.signal.aborted || signal.aborted) return resolve(false);
+ const end = () => resolve(false);
+ mainDoneCtl.signal.addEventListener("abort", end, { once: true });
+ signal.addEventListener("abort", end, { once: true });
+ rearm = () => {
+ rearm = null;
+ resolve(true);
+ };
+ });
+ // THE INSURANCE (slice 4), re-armed within LIVE_INSURANCE_MAX_STARTS:
+ // after it died early (REVIEW-1 3.1: an exit before the catch-up or the
+ // stream's end is `died`, never "to the end"), and after a from-start
+ // restart put the main behind again.
+ const insureLoop = async (): Promise<void> => {
+ const ins: LiveInsurance = { mode: decided!.mode, by: decided!.by, state: "waiting", starts: 0 };
+ let insLimited = false;
+ let rateWait: number | null = null;
+ record.insurance = ins;
+ await save();
+ const notStarted = async (reason: string) => {
+ if (!ins.starts) ins.state = "not-started";
+ ins.reason = reason;
+ await save();
+ };
+ for (;;) {
+ const stopNow = insureStop;
+ const waitStop = AbortSignal.any([signal, stopNow.signal, mainDoneCtl.signal]);
+ // The from-start part's first bytes (its extraction is done).
+ while (!waitStop.aborted && !record.fallback) {
+ if (mainStem && mainFromStart && (await bytesOf(mainStem)) > 0) break;
+ if (recoveryStem && (await bytesOf(recoveryStem)) > 0) break;
+ await sleep(deps.insurancePollMs ?? 5_000, waitStop);
+ }
+ if (record.fallback) return notStarted("the run fell back to the live edge");
+ if (signal.aborted) return notStarted("stopped");
+ if (mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began");
+ if (stopNow.signal.aborted) {
+ if (!ins.starts) await notStarted("the from-start recording caught up before it began");
+ if (!(await waitRearm())) return;
+ continue;
+ }
+ // After a rate limit: ONE more start after LIVE_RATE_LIMIT_WAIT_MS
+ // (REVIEW-2 4.1), never the 60 s pause.
+ await waitFor(stretch(rateWait ?? LIVE_INSURANCE_DELAY_MS), waitStop);
+ rateWait = null;
+ if (signal.aborted || mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began");
+ if (stopNow.signal.aborted) continue;
+ if ((ins.starts ?? 0) >= LIVE_INSURANCE_MAX_STARTS) {
+ ins.reason = `not started again: at most ${LIVE_INSURANCE_MAX_STARTS} starts a run`;
+ await save();
+ return;
+ }
+ // At most LIVE_INSURANCE_MAX_STARTS_PER_HOUR an hour: the hour is
+ // waited out, not an end.
+ {
+ const t = now().getTime();
+ const recent = (ins.startTimes ?? []).map((x) => Date.parse(x)).filter((x) => t - x < 3_600_000).sort((a, b) => a - b);
+ if (recent.length >= LIVE_INSURANCE_MAX_STARTS_PER_HOUR) {
+ const ms = Math.max(1_000, recent[0]! + 3_600_000 - t);
+ say(`The insurance recorder has started ${recent.length} times in the last hour: the next start waits ${spanWords(ms / 1000)}.`);
+ await waitFor(ms, waitStop);
+ if (signal.aborted || mainDoneCtl.signal.aborted) return notStarted("the from-start recording ended before it began");
+ // (REVIEW-7 7: stopped while it waited — no start spent on it.)
+ if (stopNow.signal.aborted) continue;
+ }
+ }
+ if (!(await roomFor("the insurance recorder"))) return notStarted("the store's disk is under the free-space floor");
+ ins.starts = (ins.starts ?? 0) + 1;
+ (ins.startTimes ??= []).push(now().toISOString());
+ ins.state = "recording";
+ delete ins.reason;
+ say(
+ `The insurance recorder records the live edge beside the from-start recording` +
+ `${ins.mode === "whole" ? " for the whole stream" : " until it catches up"} (${ins.by === "default" ? "the stream is marked keep" : ins.by === "behind" ? "the from-start part is far behind" : "asked"})` +
+ `${ins.starts > 1 ? `, start ${ins.starts} (at most ${LIVE_INSURANCE_MAX_STARTS_PER_HOUR} an hour)` : ""}.`,
+ );
+ const tag = ins.starts === 1 ? "ytdlp-insure" : `ytdlp-insure-r${ins.starts}`;
+ const o = await ytdlpPart(plan.url, tag, "now", "insurance; ", { insurance: true, noWait: true, stop: stopNow.signal });
+ const bytes = await bytesOf(o.stem);
+ const last = recentOutput(o);
+ const errLine = lastErrorLine(last);
+ const cls = !o.signalled && o.exitCode !== 0 ? liveFailureClass(last) : null;
+ if (signal.aborted) ins.state = "stopped";
+ else if (insuranceStopFor === "fallback") {
+ ins.state = "stopped";
+ ins.reason = "the run fell back to the live edge";
+ } else if (insuranceStopFor === "caught-up") ins.state = "caught-up";
+ else if (insuranceStopFor === "ended" || (mainDoneCtl.signal.aborted && endRead)) ins.state = "ended";
+ // REVIEW-7 3: an exit 0 while the from-start part still records and
+ // has not caught up is not the stream's end — it died (an ingest
+ // pause ends a live-edge recorder too): started again.
+ else if (!o.signalled && !o.stalled && o.exitCode === 0 && bytes > 0 && !mainDoneCtl.signal.aborted && caughtUpStem !== mainStem) {
+ ins.state = "died";
+ ins.reason = "it ended by itself while the from-start recording was still behind";
+ } else if (!o.signalled && !o.stalled && o.exitCode === 0 && bytes > 0) ins.state = "ended"; // the live edge ended: the stream is over
+ else if (cls === "ended" || cls === "private" || cls === "members" || cls === "disk") {
+ ins.state = bytes > 0 ? "ended" : "failed";
+ ins.reason = errLine ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
+ } else if (cls === "rate-limited") {
+ if (insLimited) {
+ ins.state = "stopped";
+ ins.reason = `rate-limited again after the ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)} wait (${errLine ?? "429"}): not started again`;
+ } else {
+ insLimited = true;
+ rateWait = LIVE_RATE_LIMIT_WAIT_MS;
+ ins.state = "died";
+ ins.reason = `rate-limited (${errLine ?? "429"}): ONE more start after ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)}`;
+ }
+ } else {
+ ins.state = "died";
+ ins.reason = o.stalled
+ ? "it stalled and was stopped"
+ : `it ${bytes > 0 ? "exited" : "recorded nothing and exited"} (${errLine ?? `yt-dlp exit ${o.exitCode ?? "null"}`}) before the from-start recording caught up`;
+ }
+ await save();
+ if (ins.state === "died") {
+ say(`The insurance recorder died early (${ins.reason}); ${(ins.starts ?? 0) < LIVE_INSURANCE_MAX_STARTS ? "it is started again" : "not started again"}.`);
+ continue;
+ }
+ if (ins.state === "caught-up") {
+ if (!(await waitRearm())) return;
+ continue;
+ }
+ return;
+ }
+ };
+ let insurance: Promise<void> | null = null;
+ let insuranceReturned = false;
+ const insuranceLoops: Promise<void>[] = [];
+ const startInsuranceLoop = () => {
+ insuranceReturned = false;
+ const p = insureLoop().finally(() => {
+ insuranceReturned = true;
+ });
+ insuranceLoops.push(p);
+ insurance = p;
+ };
+ if (decided) startInsuranceLoop();
let index0 = false;
let fromStartFailures = 0;
let edgeFailures = 0;
let lastReason: string | null = null;
let rateLimitRetried = false;
+ // SLICE 2 — THE START, TRIED AGAIN BESIDE THE LIVE EDGE (lib/liveCapture.ts
+ // LIVE_RECOVERY_*): one from-start try every 15 min (jittered), one at a
+ // time, at most 8, each its own part (`ytdlp-recover-r<N>`); the
+ // live-edge recorder is never signalled by it. It stops when the
+ // live-edge recording ends (a try still waiting is not made), on a
+ // failure no try can help, on a second rate limit, on a Cancel, or when
+ // the tries are spent. A try that records and ends while the live edge
+ // still records died mid-stream: the next try follows, inside the bound.
+ // The main recording's last attempt (what the restarts below look at).
+ // `partial`: only one of its two streams wrote (never restarted here:
+ // the schedule above already tried).
+ let lastMain: { o: Awaited<ReturnType<typeof ytdlpPart>>; bytes: number; mode: "from-start" | "index0" | "now"; partial: boolean } | null = null;
+ let recovery: Promise<void> | null = null;
+ let recoveryRunning = false;
+ // The recovery try recording now (the insurance's re-arm watches it).
+ let recoveryStem: string | null = null;
+ // 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> => {
+ recoveryRunning = true;
+ try {
+ await recoverLoop(useIndex0, ro);
+ } finally {
+ recoveryRunning = false;
+ recoveryStem = null;
+ }
+ };
+ const recoverLoop = async (useIndex0: boolean, ro: { gap?: boolean }): Promise<void> => {
+ // The tries of the run are one bound across every recovery (8).
+ const rs: StartRecovery = record.startRecovery && record.startRecovery.state !== "recovered"
+ ? record.startRecovery
+ : { tries: record.startRecovery?.tries ?? 0, max: LIVE_RECOVERY_MAX_TRIES, everyMs: LIVE_RECOVERY_EVERY_MS, state: "waiting" };
+ rs.state = "waiting";
+ record.startRecovery = rs;
+ const waitStop = AbortSignal.any([signal, recoveryStop.signal]);
+ say(
+ ro.gap
+ ? `From its start is fetched again beside the live edge, at once, until it reaches where the live-edge part begins: ` +
+ `one try at a time, at most ${LIVE_RECOVERY_MAX_TRIES} a run, every ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}.`
+ : `From its start is tried again beside the live edge: every ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}, ` +
+ `at most ${LIVE_RECOVERY_MAX_TRIES} times, one at a time; the live-edge recording is not touched.`,
+ );
+ 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 = recordedOne ? "recorded" : "stopped";
+ say(`Start recovery: the live-edge recording ${signal.aborted ? "was stopped" : "ended"} before try ${rs.tries + 1}; no more tries.`);
+ break;
+ }
+ if (!(await roomFor(`start recovery try ${rs.tries + 1}`))) {
+ rs.state = "gave-up";
+ rs.failureClass = "disk";
+ rs.lastError = "the store's disk is under the free-space floor";
+ break;
+ }
+ rs.tries++;
+ rs.state = "trying";
+ // A gap's try is stopped once it reaches the live-edge part's start
+ // (plus a minute's overlap for the join), then the span is held.
+ const reached = new AbortController();
+ 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();
+ if (!ro.gap) return;
+ 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) => {
+ if (gapTarget !== null && sec >= gapTarget + 60) {
+ covered = true;
+ say(`Start recovery: try ${rs.tries} holds the stream to ${spanWords(sec)}, past where the live-edge part begins: the span is held; it is stopped.`);
+ reached.abort();
+ }
+ })
+ .finally(() => {
+ busy = false;
+ });
+ }, watchMs);
+ },
+ });
+ if (watcher) clearInterval(watcher);
+ if (caughtTimer) clearTimeout(caughtTimer);
+ recoveryStem = null;
+ if (covered) {
+ rs.state = "recovered";
+ await save();
+ break;
+ }
+ const bytes = await bytesOf(o.stem);
+ const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(o.stem) : null;
+ // A try the watchdog stopped with nothing written failed; one with
+ // bytes died mid-stream like one that exited.
+ const stalledEmpty = o.stalled && bytes === 0 && !signal.aborted;
+ const cls = stalledEmpty ? "nothing" : o.stalled && !signal.aborted ? "recorded" : classifyAttempt({ ...o, bytes, partial: missing !== null });
+ if (cls === "recorded") {
+ if (edgeDone || signal.aborted) {
+ rs.state = "recorded";
+ say(`Start recovery: try ${rs.tries} recorded from its start to the stream's end.`);
+ 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;
+ }
+ if (cls === "stopped") {
+ rs.state = "stopped";
+ break;
+ }
+ const errLine = stalledEmpty
+ ? `stalled: nothing written for ${spanWords(stallMs / 1000)}`
+ : (lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`);
+ const failure: LiveFailureClass = stalledEmpty
+ ? "stalled"
+ : cls === "partial"
+ ? "partial"
+ : cls === "argv"
+ ? "argv"
+ : cls === "unsupported"
+ ? "unsupported"
+ : liveFailureClass(o.stderrTail);
+ o.part.error = missing !== null ? `the ${missing === "unknown" ? "video or audio" : missing} stream recorded nothing (${errLine})` : errLine;
+ o.part.failureClass = failure;
+ if (missing !== null) o.part.missingStream = missing;
+ rs.lastError = o.part.error;
+ rs.failureClass = failure;
+ if (cls === "final" || cls === "argv" || cls === "unsupported" || (cls === "rate-limited" && limited)) {
+ rs.state = "gave-up";
+ say(`Start recovery: try ${rs.tries} recorded nothing (${o.part.error}) [${failure}]: no more tries.`);
+ break;
+ }
+ if (cls === "rate-limited") limited = true;
+ rs.state = "waiting";
+ say(
+ `Start recovery: try ${rs.tries} of ${rs.max} recorded nothing (${o.part.error})` +
+ (rs.tries < rs.max ? `; the next in ${spanWords(LIVE_RECOVERY_EVERY_MS / 1000)}.` : "."),
+ );
+ await save();
+ }
+ const endState = rs.state as StartRecovery["state"] as string;
+ if (endState === "waiting" || endState === "trying") {
+ rs.state = "exhausted";
+ say(`Start recovery: all ${rs.max} tries made; the stream's start is NOT recorded.`);
+ }
+ await save();
+ };
for (let slot = 0; slot < schedule.length && !signal.aborted; ) {
const step = schedule[slot]!;
const n = (record.attempts ?? 0) + 1;
const mode = step.mode === "live-edge" ? "now" : index0 ? "index0" : "from-start";
const tag = `ytdlp${mode === "index0" ? "-index0" : ""}${mode === "now" && fromStart ? "-edge" : ""}${n > 1 && !(mode === "index0" && n === 2) ? `-a${n}` : ""}`;
- const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : "", n === 1);
- const last = parts[parts.length - 1]!;
+ // 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; provenStart?: boolean; lock?: StemLock } | null = null;
+ let bestLock: StemLock | null = null;
+ let reusedFragments: number | null = null;
+ // DESIGN-5 7: ANY run's first from-start attempt (a Record again too)
+ // reuses a part an earlier run left in staging when it can be proven.
+ if (slot === 0 && mode === "from-start" && n === 1 && (resumeOf || separate)) {
+ // REVIEW-5 B3: of every row of the id, the LONGEST resumable
+ // from-start part — a stem any row lists as waiting, or a from-start
+ // part of the interrupted row. The others are released to the landing.
+ const rows = (await loadLiveRecordingRows(paths, req.slug).catch(() => [])).filter((r) => r.id === id);
+ const partOfStem = new Map(rows.flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x]));
+ const inStaging = new Set(livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])).map((g) => g.stem));
+ const stems = new Set<string>([
+ ...rows.flatMap((r) => r.awaitingResume ?? []),
+ ...(rows.find((r) => r.startedAt === resumeOf)?.parts ?? []).filter((x) => x.stem && x.fromStart && !x.index0).map((x) => x.stem!),
+ // Every proven from-start part of the id still in staging.
+ ...(separate ? rows.flatMap((r) => r.parts).filter((x) => x.stem && x.provenStart && x.fromStart && !x.index0 && inStaging.has(x.stem)).map((x) => x.stem!) : []),
+ ]);
+ let best: { stem: string; formats: string; fragment: number; bytes: number; reuse?: boolean } | null = null;
+ for (const stem of stems) {
+ const st = await resumeStateOf(stem);
+ const ru = st.ok || !separate ? null : await restoreForReuse(stem, false);
+ if (!st.ok && !ru?.ok) continue;
+ const b = await allBytesOf(stem);
+ if (!best || b > best.bytes) best = { stem, formats: st.ok ? st.formats : "", fragment: st.ok ? st.fragment : ru!.ok ? ru!.fragments : 0, bytes: b, ...(st.ok ? {} : { reuse: true }) };
+ }
+ if (best?.reuse) {
+ const ru = await restoreForReuse(best.stem, true);
+ const st = ru.ok ? await resumeStateOf(best.stem) : null;
+ if (st?.ok && ru.ok) {
+ best = { ...best, formats: st.formats, fragment: st.fragment };
+ reusedFragments = ru.fragments;
+ } else best = null;
+ }
+ if (best) {
+ // The one repair (DESIGN-4 1) before the resume; not provable: a
+ // fresh from-start part (this attempt, a new stem) instead.
+ const rc = await reconcileForResume(best.stem);
+ if (!rc.ok) {
+ say(`${best.stem} is not resumed in place (${rc.why}); a fresh part from the stream's start records instead.`);
+ best = null;
+ } else bestLock = rc.lock;
+ }
+ 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 } : {}), ...(bestLock ? { lock: bestLock } : {}) };
+ say(`${resumeOf ? "Restart after the editor restart: " : ""}${best.stem}, an earlier part, is resumed in place from fragment ${best.fragment}${reusedFragments !== null ? " (its state rebuilt from its kept fragments: they are reused, not fetched again)" : ""}.`);
+ // This run holds it now: no row lists it as waiting.
+ const resumed = best.stem;
+ for (const r of rows.filter((x) => x.awaitingResume?.includes(resumed))) {
+ await patchLiveRecordingRow(paths, req.slug, id, r.startedAt, (x) => {
+ if (!x.awaitingResume?.includes(resumed)) return false;
+ x.awaitingResume = x.awaitingResume.filter((y) => y !== resumed);
+ if (!x.awaitingResume.length) delete x.awaitingResume;
+ }).catch((e: Error) => say(`The interrupted row could not be updated (${e.message}).`));
+ }
+ }
+ }
+ const o = await ytdlpPart(plan.url, tag, mode, mode === "index0" ? "--no-live-from-start + -live_start_index 0; " : "", {
+ onStart: onMainStart(mode),
+ onLine: onMainLine,
+ firstAttempt: n === 1,
+ ...(bootResume ? { resume: bootResume, noWait: true } : {}),
+ });
+ if (bootResume && reusedFragments !== null) {
+ o.part.reused = { fragments: reusedFragments, at: now().toISOString() };
+ await save();
+ }
+ // This attempt's own part (a try beside it may have begun one since).
+ const last = { part: o.part, stem: o.stem };
const bytes = await bytesOf(last.stem);
const missing = separate && !o.signalled && bytes > 0 ? await missingStreamOf(last.stem) : null;
- const cls = classifyAttempt({ ...o, bytes, partial: missing !== null });
+ lastMain = { o, bytes, mode, partial: missing !== null };
+ // Stopped by the watchdog with nothing written: an attempt that
+ // recorded nothing (the schedule goes on). With bytes: the restarts
+ // below decide.
+ const stalledEmpty = o.stalled && bytes === 0 && !signal.aborted;
+ const cls = stalledEmpty ? "nothing" : classifyAttempt({ ...o, bytes, partial: missing !== null });
if (cls === "recorded" || cls === "stopped" || signal.aborted) {
- delete record.missingStream;
+ // (A stream the part has not recorded stays said: REVIEW-5 B5.)
+ if (!last.part.missingStream) delete record.missingStream;
delete record.failureClass;
break;
}
- const errLine = lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
- const failure: LiveFailureClass =
- cls === "partial" ? "partial" : cls === "argv" ? "argv" : cls === "unsupported" ? "unsupported" : liveFailureClass(o.stderrTail);
+ const errLine = stalledEmpty
+ ? `stalled: nothing written for ${spanWords(stallMs / 1000)}`
+ : (lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`);
+ const failure: LiveFailureClass = stalledEmpty
+ ? "stalled"
+ : cls === "partial"
+ ? "partial"
+ : cls === "argv"
+ ? "argv"
+ : cls === "unsupported"
+ ? "unsupported"
+ : liveFailureClass(o.stderrTail);
const reason =
missing !== null
? `${missing === "unknown" ? "one of its two streams" : `the ${missing} stream`} recorded nothing (${errLine})`
@@ -1253,7 +2807,7 @@ async function recordLiveRunInner(
if (missing !== null) last.part.missingStream = missing;
record.failureClass = failure;
if (missing !== null) record.missingStream = missing;
- else delete record.missingStream;
+ else if (!last.part.missingStream) delete record.missingStream;
await save();
lastReason = reason;
if (o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) {
@@ -1322,8 +2876,481 @@ async function recordLiveRunInner(
}
await waitFor(stretch(next.waitMs), signal);
}
+ // SLICE 3 — THE RESTARTS (lib/liveCapture.ts LiveRestarts). The main
+ // recording's last part stalled with bytes, or its recorder exited with
+ // bytes: is the stream still live? One metadata read (the read the job
+ // makes at its end anyway; an exit is read twice, a minute apart, as a
+ // stream just ended may read live a moment). Live → a new part in the
+ // same mode after a pause, the old part kept for the landing; ended →
+ // land; unreadable → a stall restarts (the recorder's own exit says
+ // when a stream is over), an exit lands. Bounded: 3 in any hour, 12 in
+ // the run, and the store's disk must have room.
+ let cur = lastMain;
+ // SLICE 3 as REVIEW-2 of live-guard-2 ruled: A STREAM THAT READS LIVE IS
+ // NEVER LEFT UNRECORDED QUIETLY, and a restart never re-downloads what
+ // a kept part already holds. A recorder that exited or stalled is
+ // followed by a LIVE-EDGE recorder (its own stem; the earlier part kept
+ // for the landing and the join): an earlier part holds the past. (When
+ // no part holds the stream's START, the slice-2 tries beside the live
+ // edge are the from-start path, with their own bound.) The stream is
+ // taken as ended only on evidence: the state read says so, or three
+ // live-edge recorders in a row capture nothing. Bounds: 6 restarts in
+ // any hour and 24 in the run; past them, or when the state cannot be
+ // read after an exit, the row says the stream may be live and NOT
+ // 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>();
+ // 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 }>();
+ // Why the last resume was not made (the fresh part says it, only when known).
+ let noResumeWhy: string | null = null;
+ const netTries = new Map<string, number>();
+ let endResumed = false;
+ let freshAbortAt: number | null = null;
+ let freshFailedLast = false;
+ while (cur && !signal.aborted && !pathB) {
+ const stalledWithBytes = cur.o.stalled && cur.bytes > 0;
+ // (A partial exit too — one stream missing — DESIGN-5 1: while the
+ // stream is live it restarts; a fresh or resumed part asks for both.)
+ const exitedWithBytes = !cur.o.signalled && cur.bytes > 0;
+ const fragAborted = cur.o.fragAbort !== undefined && cur.bytes > 0 && !signal.aborted;
+ const failedRestart = cur.o.part.restart !== undefined && cur.bytes === 0 && !(cur.o.signalled && !cur.o.stalled);
+ if (!stalledWithBytes && !exitedWithBytes && !fragAborted && !failedRestart) break;
+ 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);
+ const cls: LiveFailureClass | null = !cur.o.signalled && cur.o.exitCode !== 0 ? liveFailureClass(said) : null;
+ if (cls && cls !== "unknown") {
+ cur.o.part.failureClass = cls;
+ cur.o.part.error ??= lastErrorLine(said) ?? `yt-dlp exit ${cur.o.exitCode ?? "null"}`;
+ await save();
+ }
+ const restarts = (record.restarts ??= { count: 0, at: [] });
+ const refuse = async (r: string, words: string) => {
+ restarts.refused = `${why}; ${r}`;
+ await save();
+ say(words);
+ };
+ if (cls === "disk") {
+ await refuse("the store's disk cannot take it", "NOT restarted: the store's disk cannot take it; what was recorded lands, and the row needs a person.");
+ break;
+ }
+ if (emptyInRow >= LIVE_EDGE_EMPTY_TO_END) {
+ const st = await liveNow();
+ if (st !== "ended") {
+ await refuse(
+ "three live-edge recorders in a row captured nothing",
+ "Three live-edge recorders in a row captured nothing: the stream is taken as ended, though it still reads live — it may be live and NOT recorded; the row needs a person.",
+ );
+ }
+ break;
+ }
+ // The state is ALWAYS read before a conclusion (never stderr text
+ // 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.
+ // (No re-arm here — REVIEW-6 / DESIGN-5 point 5: the same files
+ // continue, reused, in seconds; a part found far behind starts the
+ // insurance by its first frag N/M.)
+ 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;
+ state = await liveNow();
+ }
+ // REVIEW-7 1 — OFFLINE: while the state read fails for the NETWORK,
+ // nothing is spawned and no restart is spent: the read is made again
+ // on a paced wait (20 s, 60 s, 180 s, then every 5 min) for as long as
+ // it takes, said on the row; once it reads again, the part is resumed
+ // in place first.
+ if (state === "unknown" && lastRead.failClass === "network") {
+ const since = now().toISOString();
+ let k = 0;
+ while (state === "unknown" && lastRead.failClass === "network" && !signal.aborted) {
+ const w = OFFLINE_READ_WAITS_MS[Math.min(k, OFFLINE_READ_WAITS_MS.length - 1)]!;
+ k++;
+ record.offline = { since, reads: k };
+ await save();
+ say(`The stream's state cannot be read (the network?): nothing is started; read again in ${spanWords(w / 1000)} (read ${k}).`);
+ await waitFor(stretch(w), signal);
+ if (signal.aborted) break;
+ state = await liveNow();
+ }
+ delete record.offline;
+ await save();
+ if (signal.aborted) break;
+ }
+ if (state === "ended") {
+ // REVIEW-6 4: the stream ended while its from-start part may still
+ // be behind — an ended stream is still served from its start (the
+ // generator runs once more, post_live): resumed ONCE to its end.
+ // (Not after a recorder that reached the stream's end by itself:
+ // exit 0 with no fragment it could not fetch, no failed URL
+ // refresh, and not seen caught up — yt-dlp ends a from-start
+ // download at the stream's end.)
+ const mayBeBehind = cur.o.signalled || cur.o.stalled || cur.o.exitCode !== 0 || cur.o.fragAbort !== undefined || cur.o.urlRefresh === true;
+ // REVIEW-7 2: ONLY on `post_live` — a was_live stream's formats are
+ // ordinary files, and the same output name would have yt-dlp append
+ // foreign bytes to the stream files (measured). Otherwise it lands
+ // (short of the ended duration: "download the VOD now").
+ if (mayBeBehind && !endResumed && lastRead.status !== "post_live" && cur.mode === "from-start" && !endedByRefusal) {
+ say(`The stream has ended (${lastRead.status ?? "its state"}): ${cur.o.part.stem} is NOT resumed (only a post_live stream is still served from its start); what is held lands — if it is short of the stream, download the VOD now.`);
+ }
+ if (!endResumed && mayBeBehind && lastRead.status === "post_live" && caughtUpStem !== cur.o.stem && !endedByRefusal && cur.mode === "from-start" && separate && !signal.aborted) {
+ endResumed = true;
+ let st = await resumeStateOf(cur.o.stem);
+ if (!st.ok) {
+ const ru = await restoreForReuse(cur.o.stem, true);
+ if (ru.ok) st = await resumeStateOf(cur.o.stem);
+ }
+ const rc = st.ok ? await reconcileForResume(cur.o.stem) : null;
+ if (st.ok && rc?.ok) {
+ say(`The stream has ended: ${cur.o.part.stem} is resumed once from fragment ${st.fragment} to the stream's end (an ended stream is still served from its start).`);
+ const o = await ytdlpPart(plan.url, "resume", "from-start", "resume to the end; ", {
+ resume: { stem: cur.o.stem, formats: st.formats, ...(rc?.ok ? { lock: rc.lock } : {}) },
+ noWait: true,
+ onStart: onMainStart("from-start", true),
+ onLine: onMainLine,
+ });
+ cur = { o, bytes: await bytesOf(o.stem), mode: "from-start", partial: false };
+ continue;
+ }
+ }
+ if (cur.o.stalled) say(`The stream has ended: what was recorded lands (no restart).`);
+ break;
+ }
+ // A state that cannot be read never ends the recording (REVIEW-3 1.1):
+ // the live edge is restarted meanwhile; the next reads come after
+ // each recorder, paced (2 and 8 min after an empty one); only the
+ // evidence (ended, or three empty recorders in a row) ends it.
+ if (state === "unknown") say("The stream's state could not be read: restarted at the live edge meanwhile; it is read again after the recorder.");
+ if (cls === "ended" || cls === "private" || cls === "members") {
+ say(`The recorder said the stream is ${cls === "ended" ? "over" : cls === "private" ? "private or removed" : "members-only"}, but it reads live: restarted.`);
+ }
+ // At once after a recorder that held bytes; after an empty one, 30 s
+ // (2 and 8 min while the state cannot be read).
+ let pause = emptyInRow === 0 ? 0 : state === "unknown" ? (LIVE_BOOT_STATE_READ_WAITS_MS[emptyInRow - 1] ?? LIVE_RESTART_WAIT_MS) : LIVE_RESTART_WAIT_MS;
+ if (cls === "rate-limited") {
+ if (restartLimited) {
+ await refuse(
+ "rate-limited again after the 15 min wait",
+ "NOT restarted: rate-limited again after the 15 min wait — the stream reads live and is NOT recorded; the row needs a person.",
+ );
+ break;
+ }
+ restartLimited = true;
+ say(`${cur.o.part.stem}: refused by a rate limit or the bot check, and the stream reads live — ONE restart after ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)}, then no more.`);
+ await waitFor(stretch(LIVE_RATE_LIMIT_WAIT_MS), signal);
+ if (signal.aborted) break;
+ pause = 0;
+ }
+ // THE BOUNDS ARE WAITED OUT (REVIEW-5 note 3): on a stream that reads
+ // live the recording does not end at the bound — it waits until the
+ // hour frees a restart, said on the row, and goes on.
+ const bound = restartWaitMs(restarts, now().getTime());
+ if (bound) {
+ restarts.waiting = { until: new Date(now().getTime() + bound.ms).toISOString(), why: bound.why };
+ restarts.waited = (restarts.waited ?? 0) + 1;
+ await save();
+ say(`The restart bound is reached (${bound.why}) while the stream reads live: it waits ${spanWords(bound.ms / 1000)} before restart ${restarts.count + 1} — the stream is NOT recorded meanwhile.`);
+ await waitFor(bound.ms, signal);
+ delete restarts.waiting;
+ await save();
+ if (signal.aborted) break;
+ // (REVIEW-7 2: an end found after the wait goes through the same
+ // decision as any other — the loop reads again at its top.)
+ if ((await liveNow()) === "ended") continue;
+ }
+ // (A resume in place, when one is possible, needs only the floor plus
+ // its stream files: REVIEW-6 7.)
+ const resumable = cur.mode === "from-start" && separate && ((await resumeStateOf(cur.o.stem, { accounting: false })).ok || (await restoreForReuse(cur.o.stem, false)).ok);
+ if (!(await roomFor(`restart ${restarts.count + 1}`, resumable ? { resumeStem: cur.o.stem } : {}))) {
+ await refuse("not enough room on the store's disk: the stream reads live and is NOT recorded", "NOT restarted for want of disk: the stream reads live and is NOT recorded; the row needs a person.");
+ break;
+ }
+ 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.
+ // (REVIEW-8 1: a read that failed for anything but the network — a 429,
+ // the bot check, an extractor error — does not abandon the part: it is
+ // resumed in place as before, its files checked after the resume. A
+ // network failure never gets here: it waits offline above.)
+ const resumeRead = state === "live" || (state === "unknown" && lastRead.failClass !== "network");
+ if (cur.mode === "from-start" && !resumeFailed.has(cur.o.stem) && !resumeRead) noResumeWhy = `the last state read says ${lastRead.status ?? "nothing"}`;
+ if (cur.mode === "from-start" && !resumeFailed.has(cur.o.stem) && resumeRead) {
+ let st = await resumeStateOf(cur.o.stem);
+ // DESIGN-5 7: finished by yt-dlp itself (exit 0, merged) while live —
+ // reuse what is downloaded, not fragment 0 again.
+ if (!st.ok && separate) {
+ const ru = await restoreForReuse(cur.o.stem, true);
+ if (ru.ok) {
+ cur.o.part.reused = { fragments: ru.fragments, at: now().toISOString() };
+ await save();
+ st = await resumeStateOf(cur.o.stem);
+ } else say(`${cur.o.part.stem}: no reuse of what it downloaded (${ru.why}).`);
+ }
+ // DESIGN-4 3 — A FRAGMENT THAT COULD NOT BE FETCHED: resumed after
+ // 20 s, 60 s and 180 s at the same fragment; still failing there, a
+ // fresh from-start part; that one failing at the same place, the
+ // 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` };
+ }
+ }
+ let heldLock: StemLock | null = null;
+ if (st.ok) {
+ const rc = await reconcileForResume(cur.o.stem);
+ if (!rc.ok) st = { ok: false, why: rc.why };
+ else heldLock = rc.lock;
+ }
+ if (st.ok) {
+ restarts.count += 1;
+ restarts.at.push(now().toISOString());
+ // (REVIEW-6 8: the stream files' bytes only — a re-merge is no progress.)
+ const before = await streamBytesOf(cur.o.stem);
+ say(`Resume ${(cur.o.part.resumes ?? 0) + 1} of ${cur.o.part.stem} (${why}): the same files from fragment ${st.fragment}, format ${st.formats}.`);
+ const o = await ytdlpPart(plan.url, "resume", "from-start", `resume (${why}); `, {
+ resume: { stem: cur.o.stem, formats: st.formats, ...(heldLock ? { lock: heldLock } : {}) },
+ noWait: true,
+ onStart: onMainStart("from-start", true),
+ onLine: onMainLine,
+ ...(allowSkip ? { allowSkip: true } : {}),
+ });
+ // Media bytes only (REVIEW-5 note 12: a rewritten state is no progress).
+ const bytes = await bytesOf(o.stem);
+ const grew = (await streamBytesOf(o.stem)) > before;
+ // A resume stopped again by a fragment it cannot fetch is one more
+ // try at that fragment (DESIGN-4 3), not "wrote nothing".
+ if (grew || (o.fragAbort && !signal.aborted)) {
+ emptyInRow = 0;
+ if (grew) {
+ netTries.delete(o.stem);
+ delete record.offline;
+ }
+ 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 = o.locked ?? lastErrorLine(last) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
+ await save();
+ say(`The resume wrote nothing (${o.part.resumeError}).`);
+ if (o.signalled && signal.aborted) break;
+ // REVIEW-6 5: a resume that failed for the network is tried again
+ // (20 s, 60 s, 180 s), not given up after one try.
+ const rcls = liveFailureClass(last);
+ if (rcls === "network" && bytes > 0) {
+ // REVIEW-7 1: a resume that failed for the network spends no
+ // restart, never gives the stem up, and is tried again on the
+ // paced waits (then every 5 min) for as long as it takes.
+ restarts.count = Math.max(0, restarts.count - 1);
+ restarts.at.pop();
+ const nt = (netTries.get(o.stem) ?? 0) + 1;
+ netTries.set(o.stem, nt);
+ const w = OFFLINE_READ_WAITS_MS[Math.min(nt, OFFLINE_READ_WAITS_MS.length) - 1]!;
+ record.offline = { since: record.offline?.since ?? now().toISOString(), reads: nt };
+ await save();
+ say(`${o.stem}: the resume failed for the network (no restart spent); tried again in ${spanWords(w / 1000)} (try ${nt}).`);
+ await waitFor(stretch(w), signal);
+ if (signal.aborted) break;
+ cur = { o, bytes, mode: "from-start", partial: false };
+ continue;
+ }
+ resumeFailed.add(o.stem);
+ } else {
+ say(`${cur.o.part.stem} cannot be resumed in place (${st.why}).`);
+ noResumeWhy = 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) && (await roomFor(`fresh part ${restarts.count + 1}`))) {
+ restarts.count += 1;
+ restarts.at.push(now().toISOString());
+ const k = restarts.count;
+ const sm = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN;
+ const age = Number.isFinite(sm) ? (now().getTime() - sm) / 1000 : null;
+ say(
+ `Restart ${k} (${why}): ${noResumeWhy ? `no resume in place (${noResumeWhy}) — ` : ""}a FRESH part from the stream's start (a new stem: YouTube serves it whole under 119 h)` +
+ (age !== null ? `; the stream is ${spanWords(age)} old: about ${spanWords(age)} of it is fetched again from fragment 0 before the live edge` : "") +
+ `; the earlier part is kept for the landing.`,
+ );
+ const o = await ytdlpPart(plan.url, `ytdlp-f${k}`, "from-start", `fresh ${k} (${why}); `, {
+ restart: k,
+ noWait: true,
+ 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
+ // union from 0. Short of now by more than max(180 s, 1 %) — the live
+ // edge's own lag (up to a minute) plus the minute the exit and the read
+ // take, which a whole-stream download is not spent on — the span is
+ // said lost-so-far (loud) and a from-start recovery runs beside the
+ // live-edge recorder until a from-start part reaches it.
+ if (fromStart) {
+ const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN;
+ const elapsed = Number.isFinite(startMs) ? (now().getTime() - startMs) / 1000 : null;
+ const spans: [number, number][] = [];
+ for (const p of parts) {
+ const sec = await secondsOf(p.stem);
+ if (sec <= 0) continue;
+ if (p.part.fromStart && !p.part.index0) spans.push([0, sec]);
+ else if (Number.isFinite(startMs)) {
+ const at0 = (Date.parse(p.part.startedAt) - startMs) / 1000;
+ spans.push([at0, at0 + sec]);
+ }
+ }
+ spans.sort((a, b) => a[0] - b[0]);
+ // 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);
+ // 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);
+ await save();
+ say(
+ elapsed !== null
+ ? `Hours ${hm(reach)}-${hm(elapsed)} of the stream are in no part yet: fetched again from its start beside the live edge.`
+ : "The stream's start time is not known: what lies before the live edge may be in no part; fetched again from its start beside the live edge.",
+ );
+ 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();
+ }
+ }
+ }
+ restarts.count += 1;
+ restarts.at.push(now().toISOString());
+ const k = restarts.count;
+ say(`Restart ${k} (${why}, the stream ${state === "live" ? "is live" : "state unknown"}): a new part from the live edge; the earlier part is kept for the landing.`);
+ const o = await ytdlpPart(plan.url, `ytdlp-r${k}`, "now", `restart ${k} (${why}); `, {
+ restart: k,
+ noWait: true,
+ onStart: (stem) => {
+ edgeRestartStem = stem;
+ onMainStart("now", true)(stem);
+ },
+ onLine: onMainLine,
+ });
+ const bytes = await bytesOf(o.stem);
+ const partial = separate && !o.signalled && bytes > 0 ? (await missingStreamOf(o.stem)) !== null : false;
+ if (bytes === 0 && !o.signalled) {
+ // REVIEW-6 5: while the state cannot be read (offline), an empty
+ // recorder is not evidence that the stream ended.
+ if (state !== "unknown") emptyInRow += 1;
+ else say(`Restart ${k} recorded nothing while the stream's state cannot be read (offline?): not counted toward "taken as ended".`);
+ const last = recentOutput(o);
+ o.part.error = lastErrorLine(last) ?? `yt-dlp exit ${o.exitCode ?? "null"}`;
+ o.part.failureClass = liveFailureClass(last);
+ await save();
+ if (classifyAttempt({ ...o, stderrTail: last, bytes }) === "argv") {
+ await refuse("the live-edge command cannot work (argv)", `Restart ${k} recorded nothing (${o.part.error}): the command cannot work — the stream may be live and NOT recorded; the row needs a person.`);
+ break;
+ }
+ } else if (bytes > 0) emptyInRow = 0;
+ cur = { o, bytes, mode: "now", partial };
+ }
+ // REVIEW-8 4: the outage is over with the recording, whatever ended it.
+ if (record.offline) {
+ delete record.offline;
+ await save();
+ }
+ // The main recording is over. The insurance: with the stream read as
+ // ended, it is stopped after a grace (its live edge is at the end too);
+ // otherwise it runs on by itself — it may be the only recorder left.
+ mainDoneCtl.abort();
+ if (insurance) {
+ if (endRead && !endedByRefusal && !insureStop.signal.aborted) {
+ graceTimer = setTimeout(() => {
+ insuranceStopFor ??= "ended";
+ insureStop.abort();
+ }, deps.insuranceGraceMs ?? LIVE_INSURANCE_END_GRACE_MS);
+ }
+ await Promise.all(insuranceLoops);
+ }
+ if (caughtUpTimer) clearTimeout(caughtUpTimer);
+ if (graceTimer) clearTimeout(graceTimer);
+ // The live-edge recording is over: a recovery try still WAITING stops
+ // (the stream ended, or the live edge failed); one in flight is awaited,
+ // never stopped — it may hold the only copy.
+ edgeDone = true;
+ recoveryStop.abort();
+ if (recovery) await recovery;
if (lastReason !== null && record.failureClass !== undefined) {
- const tries = record.attempts ?? 0;
+ const tries = (record.attempts ?? 0) - (record.startRecovery?.tries ?? 0);
const split = fromStartFailures && edgeFailures ? ` (${fromStartFailures} from its start, ${edgeFailures} from the live edge)` : "";
attemptsSummary = `${tries} attempt${tries === 1 ? "" : "s"}${split}: ${lastReason}`;
}
@@ -1357,13 +3384,23 @@ async function recordLiveRunInner(
const stopped = signal.aborted ? stopOf(deps) : null;
const cancelled = stopped !== null;
const landSignal = new AbortController().signal;
- try {
- await refresh();
- } catch (err) {
- say(`The ended stream's metadata was not re-read (${(err as Error).message.split("\n")[0]}).`);
+ // (Read already when the restarts asked whether the stream is still live.)
+ if (!endRead) {
+ try {
+ await refresh();
+ } catch (err) {
+ say(`The ended stream's metadata was not re-read (${(err as Error).message.split("\n")[0]}).`);
+ }
}
const endMeta = await readMeta(videoDir);
- const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s));
+ // DESIGN-5 3/4: does the platform's LAST word say the stream is over? Not
+ // over (is_live, upcoming, a read that failed, a record with no state): no
+ // landing now is "the whole stream", nothing reusable goes, and the row says
+ // it landed while live. Over: was_live / post_live / not_live, or a refusal
+ // as private or removed confirmed by the second read.
+ const lsEnd = typeof endMeta?.live_status === "string" ? endMeta.live_status : null;
+ const stillLive = !endedByRefusal && !(lsEnd === "was_live" || lsEnd === "post_live" || lsEnd === "not_live");
+ const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s, { strict: true }));
const at = (n: string) => path.join(slugStore, n);
// Every part on disk now — this run's and an earlier run's — by its stem.
// WHAT THE STORE HOLDS for this id, failing CLOSED: a pointer that does not
@@ -1414,8 +3451,42 @@ 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);
+ // 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
+ // (the boot pass restarts only the newest row), so it is an ordinary part
+ // of this landing — merged, landed or kept by the rules, never left as the
+ // only copy in staging. Only a run itself stopped by a shutdown leaves it
+ // waiting (above), listed on its own row for the next boot.
+ if (stopped?.by !== "shutdown") {
+ const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []);
+ for (const r of rows.filter((x) => x.id === id && x.startedAt !== record.startedAt && x.awaitingResume?.length)) {
+ say(`${r.awaitingResume!.join(", ")}: left waiting by the run of ${r.startedAt}, not resumed — landed by the rules with this run's parts.`);
+ await patchLiveRecordingRow(paths, req.slug, id, r.startedAt, (x) => {
+ if (!x.awaitingResume?.length) return false;
+ delete x.awaitingResume;
+ }).catch((e: Error) => say(`That row could not be updated (${e.message}).`));
+ }
+ }
for (const g of groups) {
const part = partOf.get(g.stem);
+ if (waitsForResume.has(g.stem)) {
+ (record.awaitingResume ??= []).push(g.stem);
+ 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;
try {
got = await resolvePart(g, slugStore, { probe: (f) => probe(f, landSignal), merge: (a) => merge(a, landSignal), say });
@@ -1516,34 +3587,34 @@ async function recordLiveRunInner(
sayKept();
await save();
if (!unlandable.length && !kept.length) await abandon();
+ await bootLandingDone(false, error);
summary.status = record.status;
say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
if (!cancelled) throw new Error(error);
return summary;
}
candidates.sort((a, b) => (b.seconds ?? -1) - (a.seconds ?? -1));
- const best = candidates[0]!;
+ let best = candidates[0]!;
// Inside the landed file without asking how long the stream is: a shorter
// part of THIS run, both from the start (both begin where the stream's
// record begins).
- // Never an index-0 part (`--no-live-from-start`, ffmpeg at the playlist's
- // first LISTED segment) unless the playlist was read to reach the start: on
- // a DVR window that slides, a later one starts later. Those go only by the
- // coverage rule.
- // PROVEN from the start: a part marked so when it was recorded (yt-dlp
- // `--live-from-start`, a platform VOD from its first segment). An index-0
- // part, the browser path, and a part of a row written before the mark are
- // not proven, whatever `fromStart` says.
- const proven = (p: Pick<LivePart, "fromStart" | "provenStart"> | undefined) => p?.fromStart === true && p.provenStart === true;
- // Never a part with a picture beside a landed part with none, nor beside a
- // landed file merged here from separate streams (its length is the longer
- // stream's: its picture may be shorter).
+ // PROVEN from the start (main's rule): a part marked so when it was
+ // recorded. An index-0 part, the browser path, a recovery try or a
+ // 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.
+ // (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 &&
c.part !== undefined &&
best.part !== undefined &&
proven(c.part) &&
proven(best.part) &&
+ sure(c.part) &&
+ sure(best.part) &&
// Same kind only, as per-stream lengths are not known: a picture part
// inside a picture part not merged here; an audio-only part only inside
// an audio-only one (a part with both may hold less sound than its
@@ -1602,7 +3673,125 @@ async function recordLiveRunInner(
lastEndedAt: record.parts.reduce<string | null>((m, p) => (p.endedAt && (!m || p.endedAt > m) ? p.endedAt : m), null),
wholeFromStart: landedFromStart === true && !record.missingStream,
});
- const cov = record.coverage;
+ let cov = record.coverage;
+ // SLICE 5 — PARTS JOINED (controller/liveJoin.ts): the longest does not hold
+ // the stream, and two or more parts with a known place together hold more.
+ // The joined file lands only once PROVEN (its length, its sound at every
+ // join); its parts are removed only after it has landed. Unproven: the
+ // longest lands and the rest are kept, as before.
+ let joinsRecord: Omit<LiveJoinsRecord, "landedAt" | "container"> | null = null;
+ // WHAT THE STORE ALREADY HOLDS for this id (REVIEW-1 1.2 of live-guard-2):
+ // it is replaced only by a file that holds the whole stream from its start,
+ // or by a proven join that holds it. Its place is known only when the run
+ // that stored it says it landed a part from the start.
+ const STORED = "<the store>";
+ const pointer = await loadSavedVideo(videoDir).catch(() => null);
+ const storedPath = pointer ? savedVideoPath(pointer) : null;
+ const storedSeconds = storedPath && (await stat(storedPath).then((x) => x.isFile(), () => false)) ? ((await probe(storedPath, landSignal).catch(() => null))?.seconds ?? null) : null;
+ const stored = storedPath && storedSeconds !== null ? { file: storedPath, seconds: storedSeconds } : null;
+ let storedInJoin = false;
+ // Never while the run is being stopped (REVIEW-1 1.7): land the longest,
+ // keep the rest; the next run joins.
+ if (!cov.covers && (candidates.length >= 2 || stored) && !record.missingStream && deps.join !== null && !stopped && !signal.aborted) {
+ const rows = await loadLiveRecordingRows(paths, req.slug).catch(() => []);
+ const earlier = new Map(rows.filter((r) => r.id === id).flatMap((r) => r.parts).filter((x) => x.stem).map((x) => [x.stem!, x]));
+ const placed = candidates.flatMap((c) => {
+ const p = c.part ?? earlier.get(c.group.stem);
+ // "From the start" in a join only on proof (main's rule).
+ return p && c.seconds !== null ? [{ c, jp: { stem: c.group.stem, file: c.file, seconds: c.seconds, fromStart: proven(p), startedAt: p.startedAt ?? null } }] : [];
+ });
+ if (stored) {
+ const by = rows
+ .filter((r) => r.id === id && r.kept === "new" && r.landedPart !== undefined && r.startedAt !== record.startedAt)
+ .sort((a, b) => Date.parse(b.endedAt ?? b.startedAt) - Date.parse(a.endedAt ?? a.startedAt))[0];
+ const lp = by?.parts[by.landedPart!];
+ if (proven(lp) && !lp!.restart && !lp!.stalled) {
+ placed.push({ c: null as unknown as Candidate, jp: { stem: STORED, file: stored.file, seconds: stored.seconds, fromStart: true, startedAt: lp.startedAt ?? null } });
+ }
+ }
+ // The joined file needs as much room again as its parts (staging is the
+ // store's disk).
+ let room = true;
+ if (placed.length >= 2) {
+ let need = 0;
+ for (const x of placed) need += await sizeOf(x.jp.file);
+ const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0);
+ if (free < need + minFree) {
+ room = false;
+ (record.spaceHeld ??= []).push({ what: "the join of the parts", at: now().toISOString(), freeBytes: free });
+ say(`Not joined: the store's disk has ${formatBytes(free)} free, a join of these parts needs ${formatBytes(need + minFree)}. The longest lands; the rest are kept.`);
+ }
+ }
+ if (placed.length >= 2 && room) {
+ const joinStem = stemPath("joined");
+ const r = await joinLiveParts({
+ parts: placed.map((x) => x.jp),
+ streamStartedAt: record.streamStartedAt ?? null,
+ outStem: joinStem,
+ // The cut and the concat are stream copies of hours: the heavy slot,
+ // as the landing's remux.
+ deps: deps.join ?? ffmpegJoinDeps({ ffmpegBin: paths.ffmpegBin, ffprobeBin: paths.ffprobeBin, run: (args) => runFfmpegHeavy(paths, args, landSignal) }, landSignal),
+ say,
+ }).catch((err: Error) => ({ ok: false as const, why: err.message }));
+ if (r.ok) {
+ const inJoin = new Set(r.stems);
+ const gaps = r.joins.filter((j) => j.kind === "gap");
+ say(
+ `Joined ${r.stems.length} parts into one (${spanWords(r.seconds)}): ` +
+ r.joins
+ .map((j) =>
+ j.kind === "overlap"
+ ? `at ${spanWords(j.at)} an overlap of ${spanWords(j.seconds)} found by their sound${j.duplicatedSeconds ? ` (${j.duplicatedSeconds} s heard twice)` : ""}`
+ : `at ${spanWords(j.at)} a GAP of about ${spanWords(j.seconds)} by the clock — not recorded`,
+ )
+ .join("; ") +
+ ". Each join was checked.",
+ );
+ // Every joined part is inside the joined file (proven): removed
+ // after it lands. The rest keep the coverage rule below.
+ storedInJoin = inJoin.has(STORED);
+ // (The stored container is replaced by the landing itself, never removed here.)
+ for (const c of placed.filter((x) => x.jp.stem !== STORED).map((x) => x.c).filter((c) => inJoin.has(c.group.stem))) {
+ const i = others.findIndex((o) => o.group.stem === c.group.stem);
+ if (i >= 0) others.splice(i, 1);
+ if (toRemove.some((t) => t.group.stem === c.group.stem)) continue;
+ toRemove.push({
+ group: c.group,
+ why: "inside the joined file (its length and its sound at each join checked)",
+ extra: [c.file],
+ o: { group: c.group, why: `joined into ${path.basename(r.file)}`, seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file] },
+ });
+ }
+ const base = r.segments[0]!;
+ const jp = await probe(r.file, landSignal).catch(() => null);
+ best = {
+ file: r.file,
+ seconds: r.seconds,
+ group: { stem: path.basename(joinStem), finished: [path.basename(r.file)], streams: [], scratch: [] },
+ video: jp ? Boolean(jp.videoCodec) : null,
+ merged: false,
+ };
+ landedFromStart = base.streamFromBasis === "start";
+ record.joins = r.joins;
+ joinsRecord = { seconds: r.seconds, segments: r.segments, joins: r.joins };
+ const dup = r.joins.reduce((n, j) => n + (j.duplicatedSeconds ?? 0), 0);
+ record.coverage = streamCoverage({
+ capturedSeconds: Math.round((r.seconds - dup) * 1000) / 1000,
+ endMeta,
+ streamStartedAt: record.streamStartedAt ?? null,
+ lastEndedAt: record.parts.reduce<string | null>((m, p) => (p.endedAt && (!m || p.endedAt > m) ? p.endedAt : m), null),
+ // A join with a gap never holds the whole stream.
+ wholeFromStart: landedFromStart && gaps.length === 0,
+ });
+ cov = record.coverage;
+ } else {
+ say(`Not joined: ${r.why}. The longest lands; the rest are kept.`);
+ }
+ }
+ }
+ // (SLICE 2: a from-start try beside the live edge never carries the proof of
+ // start — main's rule — so its landing never "recovers" the start by the
+ // coverage rule: the live-edge part stays and a person decides.)
// Covered: every other part of the stream, this run's or an earlier one's,
// is inside the landed file, and goes (recorded, with why) — except a part
// that may hold the stream's END: one not from the start (a live-edge part,
@@ -1628,7 +3817,9 @@ async function recordLiveRunInner(
if (cov.covers && !mayHoldEnd(o)) {
toRemove.push({
group: o.group,
- why: `inside the landed file, which holds the whole stream from its start (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)}, ${cov.basis === "duration" ? "its duration" : "by the clock"})`,
+ why: stillLive
+ ? `inside the landed file, which holds the stream from its start SO FAR (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)} by the clock; the stream still reads live)`
+ : `inside the landed file, which holds the whole stream from its start (${spanWords(cov.capturedSeconds ?? 0)} of ${spanWords(cov.streamSeconds ?? 0)}, ${cov.basis === "duration" ? "its duration" : "by the clock"})`,
extra: o.extra ?? [],
o,
});
@@ -1653,13 +3844,14 @@ async function recordLiveRunInner(
if (kept.length) record.keptParts = kept;
sayKept();
await save();
+ await bootLandingDone(false, `the landing failed: ${why}`);
summary.status = record.status;
say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`);
throw new Error(record.error);
};
// NOTHING LANDED: the store keeps what it holds, and every part — the one
- // that would have landed and every part meant for removal — stays, listed,
- // needing a person. Nothing is removed.
+ // that would have landed, every part meant for removal, a joined file and
+ // its parts — stays, listed, needing a person. Nothing is removed.
const notLanded = async (why: string): Promise<RecordLiveSummary> => {
await keep(best.group, `not landed: ${why}`, { seconds: best.seconds, ...(best.part ? { part: best.part } : {}), extra: [best.file] });
for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: nothing was landed`, r.o);
@@ -1668,8 +3860,10 @@ async function recordLiveRunInner(
record.endedAt = now().toISOString();
record.error = `not landed: ${why}`;
if (kept.length) record.keptParts = kept;
+ delete record.joins;
sayKept();
await save();
+ await bootLandingDone(false, `not landed: ${why}`);
// The operator's keep marks hold whatever landed (as main did).
if (req.doNotClean) {
await setDoNotClean(videoDir, true, {
@@ -1687,20 +3881,36 @@ async function recordLiveRunInner(
};
// A CONTAINER ALREADY IN THE STORE (an earlier run's landing, a shutdown's
// included) is replaced only by a file that holds the whole stream from its
- // start (the coverage rule): "longer" is not containment — a live-edge part
- // after a restart is longer and holds none of the stored start.
+ // start (the coverage rule), or by a proven join that includes it: "longer"
+ // is not containment. The store read fails closed (main's storeState).
const store = await storeState();
if (store.kind === "unknown") {
return notLanded(`${store.why}: a container may be stored, and nothing lands over it unproven`);
}
- if (store.kind === "stored" && !cov.covers) {
- const storedPath = store.path;
- const storedSeconds = (await probe(storedPath, landSignal).catch(() => null))?.seconds ?? null;
+ if (store.kind === "stored" && !cov.covers && !storedInJoin) {
+ const storedSeconds = (await probe(store.path, landSignal).catch(() => null))?.seconds ?? null;
return notLanded(
`the store already holds a recording of this stream (${storedSeconds !== null ? spanWords(storedSeconds) : "length unknown"}), ` +
- "and this one is not proven to hold it (not the whole stream from its start): the stored one stays",
+ "and this one is not proven to hold it (not the whole stream from its start, nor a join that includes it): the stored one stays",
);
}
+ // REVIEW-6 10: a RAW source (a stream file landed as it is, a muxed .ts the
+ // landing remuxes) is copied, not moved: it stays until the stored file is
+ // verified against it. A merged file is moved (its streams are the source).
+ const rawSource = best.group.streams.includes(path.basename(best.file)) || /\.ts$/i.test(best.file);
+ // REVIEW-7 8: a copy needs its size plus the floor free where a rename
+ // needed nothing — checked first, said plainly; everything is kept.
+ if (rawSource) {
+ const free = await (deps.freeBytes ?? getFreeBytes)(storeRoot).catch(() => 0);
+ // (REVIEW-8 5: the room the landing itself asks — the size plus its 2 GB
+ // margin — not the recorders' 20 GB floor.)
+ const need = bestBytes + LAND_MEDIA_DISK_MARGIN_BYTES;
+ if (free < need) {
+ return notLanded(
+ `${path.basename(best.file)} is landed by a copy (it is kept until the stored file is checked against it), which needs ${formatBytes(need)} free on the store's disk; it has ${formatBytes(free)} — everything is kept, free some space and Record again or land it by hand`,
+ );
+ }
+ }
let landed: Awaited<ReturnType<typeof landMediaFile>>;
try {
landed = await landMediaFile({
@@ -1710,7 +3920,7 @@ async function recordLiveRunInner(
videoId: id,
sourcePath: best.file,
via: "record-live",
- move: true,
+ move: !rawSource,
url: plan.url,
note: req.note ?? `a live recording (${best.part?.method ?? "an earlier run's part"})`,
onLog,
@@ -1734,11 +3944,41 @@ 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.
- 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 });
+ // 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.
+ if (!rawSource) await rm(best.file, { force: true });
+ const mergedFrom = best.group.streams.filter((f) => at(f) !== best.file);
+ const verifyAgainst: string[] = [];
+ for (const f of mergedFrom) if ((await sizeOf(at(f))) > 0) verifyAgainst.push(at(f));
+ if (rawSource && !verifyAgainst.length) verifyAgainst.push(best.file);
+ record.verification = { state: "pending", at: now().toISOString(), ...(verifyAgainst.length ? { against: verifyAgainst.map((f) => path.basename(f)) } : {}) };
+ if (stillLive) {
+ const startMs = record.streamStartedAt ? Date.parse(record.streamStartedAt) : NaN;
+ const elapsed = Number.isFinite(startMs) ? (now().getTime() - startMs) / 1000 : null;
+ const unrecorded = elapsed !== null && best.seconds !== null ? Math.max(0, Math.round(elapsed - best.seconds)) : null;
+ const why = stopped
+ ? stopped.by === "shutdown"
+ ? "an editor shutdown stopped it"
+ : "it was cancelled"
+ : record.restarts?.refused
+ ? `not restarted: ${record.restarts.refused}`
+ : lsEnd === "is_live" || lsEnd === "is_upcoming"
+ ? "the last read says the stream is live"
+ : "the stream's state could not be read";
+ record.landedWhileLive = { at: now().toISOString(), unrecordedSeconds: unrecorded, why };
+ say(
+ `LANDED WHILE THE STREAM IS STILL LIVE (${why}): what is stored is the stream SO FAR, not the whole` +
+ (unrecorded !== null ? ` — about ${spanWords(unrecorded)} of it, by the clock, is in no landed file now` : "") +
+ "; the row needs a person, and nothing reusable is removed until the stream is confirmed done.",
+ );
+ }
+ const skippedHere = best.part?.skippedFragments ?? (await readStemMarks(slugStore, best.group.stem)).skipped;
+ if (skippedHere && skippedHere.count > 0) {
+ record.skippedFragments = { ...skippedHere };
+ 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;
@@ -1747,6 +3987,11 @@ async function recordLiveRunInner(
if (kept.length) record.keptParts = kept;
record.endedAt = now().toISOString();
if (removed.length) record.removedParts = removed;
+ if (joinsRecord) {
+ await liveJoinsSidecar
+ .write(videoDir, { landedAt: now().toISOString(), container: landed.container, ...joinsRecord })
+ .catch((e: Error) => say(`live-joins.json could not be written (${e.message}); the joins are on the row.`));
+ }
if (record.missingStream) say(`Landed without its ${record.missingStream} stream: it needs a person.`);
if (!record.coverage.covers && record.coverage.streamSeconds !== null && record.coverage.capturedSeconds !== null) {
say(
@@ -1757,6 +4002,7 @@ async function recordLiveRunInner(
await save();
summary.landed = { kept: landed.kept, seconds: landed.newSeconds, container: landed.container };
summary.status = record.status;
+ await bootLandingDone(true);
// 4. Keep it, and hand it on.
if (req.doNotClean) {
@@ -1775,15 +4021,261 @@ async function recordLiveRunInner(
videoDir,
transcribeJob: req.transcribe === true,
});
- if (req.transcribe === true && !facts.hasTranscript && opts.requestTranscription) {
+ // A SHORTER STORED CONTAINER WAS REPLACED (REVIEW-LF-4 2): a transcript
+ // that ends inside it is that file's, and is asked for again.
+ const redo = landed.existingSeconds !== undefined ? await transcriptOfReplaced(videoDir, landed.existingSeconds, landed.newSeconds ?? null) : null;
+ if (redo) {
+ record.transcriptRedo = { ...redo, at: now().toISOString() };
+ if (redo.verdict === "shorter") {
+ say(`The transcript is the replaced shorter file's (${redo.why}): the transcription is asked again.`);
+ // `replace`: the job would otherwise find transcript.json and do nothing.
+ const r = opts.requestTranscription ? await opts.requestTranscription(req.slug, id, { replace: true }) : { ok: false, error: "no transcription can be asked from here" };
+ if (r.ok && r.jobId) record.transcriptRedo.jobId = r.jobId;
+ else record.transcriptRedo.error = r.error ?? "no job";
+ say(r.ok ? `transcribe-one job ${r.jobId}` : `The transcription was not asked again: ${r.error ?? "no job"} — it needs a person.`);
+ } else {
+ say(`The transcript may be the replaced shorter file's; that cannot be told (${redo.why}): nothing is asked, it needs a person.`);
+ }
+ await save();
+ } else if (req.transcribe === true && !facts.hasTranscript && opts.requestTranscription) {
const r = await opts.requestTranscription(req.slug, id);
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 {
+ // REVIEW-7 4: the tracks' tolerance is max(2 s, 2 fragments) — the
+ // fragment's length from the stream file's kept fragments.
+ const fragmentSeconds = await fragmentSecondsOf(slugStore, mergedFrom, best.seconds);
+ 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, { fragmentSeconds })))(landed.container, verifyAgainst, landSignal)
+ : await (deps.verifyScan ?? ((f, sg) => verifyScan(ffprobe, f, sg, { fragmentSeconds })))(landed.container, landSignal);
+ } catch (err) {
+ verdict = { ok: false, why: (err as Error).message };
+ }
+ // REVIEW-6 3: before any fragment goes, each stream file is exactly its
+ // kept fragments 1..N, byte for byte (they may be the only whole copy).
+ // (REVIEW-7 4: a part whose fragments were dropped for want of disk has
+ // none to compare with — the byte check is skipped, said.)
+ const droppedHere = best.part?.fragmentsDropped ?? (await readStemMarks(slugStore, best.group.stem)).dropped;
+ if (verdict.ok && droppedHere && mergedFrom.length) {
+ say(`The byte check against the kept fragments is skipped: they were dropped for want of disk (${droppedHere}).`);
+ // REVIEW-8 3: the track spans alone are no proof — never "verified whole".
+ verdict = { ok: false, why: `its fragments were dropped for want of disk (${droppedHere}): it cannot be proven whole by its track spans alone` };
+ }
+ if (verdict.ok && !droppedHere) {
+ for (const f of mergedFrom) {
+ const eq = await streamEqualsFragments(slugStore, f).catch((e: Error) => ({ ok: false as const, why: e.message }));
+ if (eq && !eq.ok) {
+ verdict = { ok: false, why: eq.why };
+ break;
+ }
+ }
+ }
+ const keptBefore = kept.length;
+ if (verdict.ok) {
+ record.verification = { ...record.verification!, state: "verified", at: now().toISOString() };
+ const gaps = record.joins?.filter((j) => j.kind === "gap").length ?? 0;
+ say(
+ gaps
+ ? `The landed file reads clean, but it was joined with ${gaps} gap(s) by the clock: it is NOT whole.`
+ : stillLive
+ ? `The landed file matches its stream files (${verifyAgainst.length ? verifyAgainst.map((f) => path.basename(f)).join(", ") : "its scan"}) — the stream SO FAR, not the whole: it is still live.`
+ : `The landed file is verified whole (${verifyAgainst.length ? `against ${verifyAgainst.map((f) => path.basename(f)).join(", ")}` : "its scan"}).`,
+ );
+ // (Nothing on disk is removed for a stream that went private.)
+ if (record.endedBy?.class === "private") for (const r of toRemove) await keep(r.group, `${r.o.why}; kept: the stream went private or was removed`, r.o);
+ else for (const r of toRemove) await removeGroup(r.group, r.why, r.extra);
+ // DESIGN-5 7 — ONLY WHEN CONFIRMED DONE (the platform says over, and
+ // verified): the landed part's stream files, state and fragments go.
+ // Still live: they stay, for a restart's reuse.
+ // (A stream that went private or was removed keeps everything on disk:
+ // DESIGN-5 (c) — it may come back, and what is there is all there is.)
+ const wentPrivate = record.endedBy?.class === "private";
+ if (!stillLive && !wentPrivate) {
+ for (const f of [...best.group.finished, ...best.group.streams, ...best.group.scratch]) await rm(at(f), { force: true });
+ } else {
+ await keep(
+ best.group,
+ wentPrivate
+ ? "the landed part's stream files, state and fragments, kept: the stream went private or was removed while it was recorded"
+ : "the landed part's stream files, state and fragments, kept for a restart's reuse until the stream is confirmed done",
+ { ...(best.part ? { part: best.part } : {}) },
+ );
+ }
+ if (removed.length) record.removedParts = removed;
+ for (const r of removed) say(`Removed: ${r.stem} (${formatBytes(r.bytes)}) — ${r.why}.`);
+ } else if (landSignal.aborted) {
+ 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;
}
+// WAS THE VIDEO'S TRANSCRIPT MADE FROM THE FILE A LANDING JUST REPLACED
+// (REVIEW-LF-4 2)? Told by the transcript itself, against the two lengths: its
+// last cue ends inside the replaced container (no later than its length plus
+// 60 s) while the new container runs on more than 60 s past that — so it
+// holds nothing of the rest, whichever file it was made from, and is the
+// short one's. A transcript whose speech runs past the replaced file's end
+// was not made from it; a new file not longer than the old leaves nothing to
+// redo; no transcript.json, nothing to redo (the ordinary hand-off asks).
+// Not tellable — the transcript does not read or holds no cues, or the
+// replaced length is not known — "unknown": a person decides.
+export const TRANSCRIPT_REDO_TOLERANCE_SECONDS = 60;
+export async function transcriptOfReplaced(
+ videoDir: string,
+ replacedSeconds: number | null,
+ newSeconds: number | null,
+): Promise<Omit<LiveTranscriptRedo, "at"> | null> {
+ const tol = TRANSCRIPT_REDO_TOLERANCE_SECONDS;
+ let src: string;
+ try {
+ // (Its plain form, else its stored, compressed one.)
+ src = await readStoredText(videoDir, WHISPER_FILENAME, "utf8");
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return null;
+ return { verdict: "unknown", why: `${WHISPER_FILENAME} does not read (${(err as Error).message})`, replacedSeconds, lastCueEnd: null };
+ }
+ if (replacedSeconds === null || newSeconds === null) {
+ return { verdict: "unknown", why: `the ${replacedSeconds === null ? "replaced" : "new"} file's length is not known`, replacedSeconds, lastCueEnd: null };
+ }
+ if (newSeconds <= replacedSeconds + tol) return null;
+ let lastCueEnd = 0;
+ try {
+ const cues = parseTranscriptJson(src);
+ if (!cues.length) return { verdict: "unknown", why: `${WHISPER_FILENAME} holds no cues`, replacedSeconds, lastCueEnd: null };
+ for (const c of cues) if (typeof c.end === "number" && c.end > lastCueEnd) lastCueEnd = c.end;
+ } catch (err) {
+ return { verdict: "unknown", why: `${WHISPER_FILENAME} does not parse (${(err as Error).message})`, replacedSeconds, lastCueEnd: null };
+ }
+ if (lastCueEnd > replacedSeconds + tol) return null;
+ return {
+ verdict: "shorter",
+ why: `its last cue ends at ${spanWords(lastCueEnd)}, inside the replaced ${spanWords(replacedSeconds)}; the new file is ${spanWords(newSeconds)}`,
+ replacedSeconds,
+ lastCueEnd,
+ };
+}
+
+// REVIEW-7 4 — THE CHECK, AGAIN: a landing whose verification is `failed` or
+// `pending` is checked once more against the stream files it was made from
+// (`pnpm ops live-recording-verify`, the row's Verify button). Verified, and
+// the stream confirmed done (not landed while live, not gone private), the
+// stream files, their state and fragments go and the row says so; otherwise
+// the row says why, and nothing is removed.
+export async function reverifyLiveLanding(o: {
+ paths: Paths;
+ slug: string;
+ id: string;
+ startedAt?: string;
+ channelConfig: ChannelConfig | null;
+ deps?: { verifyMerged?: RecordLiveDeps["verifyMerged"]; say?: (s: string) => void };
+}): Promise<{ ok: true; verified: boolean; why?: string; removed: string[] } | { ok: false; error: string }> {
+ const say = o.deps?.say ?? (() => {});
+ const rows = (await loadLiveRecordingRows(o.paths, o.slug).catch(() => [])).filter((r) => r.id === o.id);
+ const row = o.startedAt
+ ? rows.find((r) => r.startedAt === o.startedAt)
+ : rows.filter((r) => r.verification && r.verification.state !== "verified").sort((a, b) => b.startedAt.localeCompare(a.startedAt))[0];
+ if (!row) return { ok: false, error: `${o.slug}/${o.id}: no landing waiting for its check` };
+ const against = row.verification?.against ?? [];
+ if (!row.verification || row.verification.state === "verified") return { ok: false, error: `${o.slug}/${o.id} (${row.startedAt}): already verified` };
+ if (!against.length) return { ok: false, error: `${o.slug}/${o.id} (${row.startedAt}): no stream files are named to check against` };
+ const videoDir = path.join(o.paths.channelsDir, o.slug, "data", o.id);
+ const pointer = await loadSavedVideo(videoDir).catch(() => null);
+ if (!pointer) return { ok: false, error: `${o.slug}/${o.id}: the store holds no container to check` };
+ const stored = savedVideoPath(pointer);
+ const slugStore = path.join(savedVideoRoot(o.paths, o.channelConfig), o.slug);
+ const files = against.map((n) => path.join(slugStore, n));
+ for (const f of files) if (!(await stat(f).catch(() => null))) return { ok: false, error: `${path.basename(f)} is no longer in staging` };
+ const ffprobe = o.paths.ffprobeBin || "ffprobe";
+ const fragmentSeconds = await fragmentSecondsOf(slugStore, against, row.coverage?.capturedSeconds ?? null);
+ let verdict: { ok: true } | { ok: false; why: string } = await (o.deps?.verifyMerged ?? ((m, st, sg) => verifyMerged(ffprobe, m, st, sg, { fragmentSeconds })))(
+ stored,
+ files,
+ new AbortController().signal,
+ ).catch((e: Error) => ({ ok: false as const, why: e.message }));
+ const stems = [...new Set(livePartFiles(o.id, against).map((g) => g.stem))];
+ // REVIEW-8 6: never under a recorder that still writes these files.
+ const locks: StemLock[] = [];
+ for (const st of stems) {
+ const lk = await takeStemLock(slugStore, st);
+ if (!lk.ok) {
+ for (const l of locks) await l.release();
+ return { ok: false, error: `${o.slug}/${o.id}: ${lk.why} — not checked again while it records` };
+ }
+ locks.push(lk);
+ }
+ try {
+ const dropped = (await Promise.all(stems.map((st) => readStemMarks(slugStore, st)))).some((m) => m.dropped);
+ if (verdict.ok && dropped) verdict = { ok: false, why: "its fragments were dropped for want of disk: it cannot be proven whole by its track spans alone" };
+ if (verdict.ok && !dropped) {
+ for (const n of against) {
+ const eq = await streamEqualsFragments(slugStore, n).catch((e: Error) => ({ ok: false as const, why: e.message }));
+ if (eq && !eq.ok) {
+ verdict = { ok: false, why: eq.why };
+ break;
+ }
+ }
+ }
+ const at = new Date().toISOString();
+ const confirmedDone = !row.landedWhileLive && row.endedBy?.class !== "private";
+ const removed: string[] = [];
+ if (verdict.ok && confirmedDone) {
+ const names = await readdir(slugStore).catch(() => [] as string[]);
+ for (const g of livePartFiles(o.id, names).filter((x) => stems.includes(x.stem))) {
+ for (const f of [...g.finished, ...g.streams, ...g.scratch]) {
+ if (f.endsWith(".rec.lock")) continue; // (ours: released below)
+ await rm(path.join(slugStore, f), { force: true });
+ removed.push(f);
+ }
+ }
+ }
+ const apply = <T extends { verification?: LiveVerification; keptParts?: KeptPart[] }>(r: T): T => {
+ r.verification = verdict.ok ? { ...r.verification!, state: "verified", at } : { ...r.verification!, state: "failed", at, why: (verdict as { why: string }).why };
+ if (removed.length && r.keptParts) r.keptParts = r.keptParts.filter((k) => !stems.includes(k.stem));
+ if (r.keptParts && !r.keptParts.length) delete r.keptParts;
+ return r;
+ };
+ await patchLiveRecordingRow(o.paths, o.slug, o.id, row.startedAt, (r) => {
+ apply(r);
+ });
+ // The record beside the video says the same, when it is this run's.
+ const rec = await liveRecordingSidecar.load(videoDir).catch(() => null);
+ if (rec && rec.startedAt === row.startedAt) await liveRecordingSidecar.write(videoDir, apply(rec)).catch(() => {});
+ say(
+ verdict.ok
+ ? `${o.slug}/${o.id}: the landed file is verified${confirmedDone ? `; ${removed.length} file(s) of its stream files removed` : " (the stream is not confirmed done: its stream files are kept)"}.`
+ : `${o.slug}/${o.id}: NOT verified (${(verdict as { why: string }).why}); nothing is removed.`,
+ );
+ return { ok: true, verified: verdict.ok, ...(verdict.ok ? {} : { why: (verdict as { why: string }).why }), removed };
+ } finally {
+ for (const l of locks) await l.release();
+ }
+}
+
// Every refusal before any job; then the job.
export async function runRecordLiveJob(
opts: Omit<RecordLiveJobOpts, "plan">,
diff --git a/common/controller/transcribeOne.test.ts b/common/controller/transcribeOne.test.ts
@@ -136,3 +136,29 @@ test("isMediaDriveHeld: the held class, by instance or by its flag; nothing else
assert.equal(isMediaDriveHeld(new Error("boom")), false);
assert.equal(isMediaDriveHeld(null), false);
});
+
+// REVIEW-5 note 11 (live-guard-2): a transcription ASKED AGAIN because the
+// transcript is a shorter file's must replace it. Without `replace` an
+// existing transcript.json is "already-exists" (the job does nothing); with
+// it the engine runs, and the old transcript stays until a new one is made.
+test("replace: an existing transcript.json is transcribed again (the engine runs), and is not removed before a new one is made", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "transcribe-replace-"));
+ try {
+ const ran = path.join(dir, "engine-ran");
+ const bin = path.join(dir, "fake-engine.sh");
+ await writeFile(bin, `#!/bin/sh\ntouch ${ran}\nexit 1\n`, { mode: 0o755 });
+ await writeFile(path.join(dir, "audio.mp3"), "not really audio");
+ await writeFile(path.join(dir, "transcript.json"), "{\"transcription\":[]}");
+ const worker: Worker = { id: "w1", name: "fake", kind: "local", enabled: true, priority: 0, appId: "whisper-cpp", config: { bin, model: "model.bin" } };
+ const base = { paths: {} as Paths, videoDir: dir, videoId: "vid1", audioFilename: "audio.mp3", worker, onLog: () => {} };
+ assert.equal(await transcribeOneVideo(base), "already-exists", "without replace: nothing is done");
+ const { existsSync } = await import("node:fs");
+ assert.equal(existsSync(ran), false);
+ const err = await transcribeOneVideo({ ...base, replace: true }).then((v) => v, (e) => e);
+ assert.notEqual(err, "already-exists");
+ assert.equal(existsSync(ran), true, "the engine ran");
+ assert.equal(existsSync(path.join(dir, "transcript.json")), true, "the old transcript stays when the engine fails");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/controller/transcribeOne.ts b/common/controller/transcribeOne.ts
@@ -166,6 +166,10 @@ async function throwIfAudioVanished(
export type TranscribeOneOptions = {
paths: Paths;
+ // True transcribes again over an existing transcript.json (a record-live
+ // landing that replaced the shorter file the transcript was made from). The
+ // old one stays until the new one is renamed over it.
+ replace?: boolean;
videoDir: string;
videoId: string;
audioFilename: string;
@@ -216,10 +220,11 @@ export async function transcribeOneVideo(
const log = opts.onLog ?? ((m: string) => console.log(m));
const transcriptPath = path.join(opts.videoDir, "transcript.json");
- if (await pathExists(transcriptPath)) {
+ if (!opts.replace && (await pathExists(transcriptPath))) {
log(`Transcription for ${opts.videoId} already exists`);
return "already-exists";
}
+ if (opts.replace && (await pathExists(transcriptPath))) log(`Transcribing ${opts.videoId} again: its transcript.json is replaced when the new one is made.`);
// NOT OPENED ON A DRIVE THAT IS NOT ANSWERING (lane drive-stall). The audio
// is a tierable file, a link onto the channel's media drive; asking for it
@@ -592,6 +597,8 @@ export const MAX_WORKER_ATTEMPTS = 3;
export type TranscribeWithWorkerOptions = {
paths: Paths;
+ // See TranscribeOneOptions.replace.
+ replace?: boolean;
videoDir: string;
videoId: string;
audioFilename: string;
@@ -700,6 +707,7 @@ export async function transcribeWithWorker(
skipInlineDiarization: opts.skipInlineDiarization,
words: opts.words,
...(opts.salvage !== undefined ? { salvage: opts.salvage } : {}),
+ ...(opts.replace ? { replace: true } : {}),
});
pool.markSuccess(worker.id);
return outcome;
diff --git a/common/lib/liveCapture.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
@@ -256,6 +256,11 @@ 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;
+ // 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",
@@ -265,8 +270,19 @@ 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] : []),
+ // 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",
@@ -449,17 +465,58 @@ export type LivePart = {
// nothing: the stream that is missing ("unknown": the one that wrote could
// not be read).
missingStream?: MissingStream;
+ // A from-start try beside a live-edge recording (StartRecovery).
+ recovery?: boolean;
+ // The stall watchdog stopped its recorder: its files had not grown for
+ // stallMinutes (LiveRestarts).
+ stalled?: boolean;
+ // A restart of the recording after a stall or a recorder that died while
+ // the stream was live (1-based).
+ restart?: number;
+ // The insurance recorder's part: the live edge, beside a from-start
+ // recording that is catching up (LiveInsurance).
+ insurance?: boolean;
// 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;
+ // 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;
+ // Fragment requests answered "HTTP Error 403: Forbidden" (with a private
+ // or removed state read after them: went-private).
+ fragment403?: number;
+ // DESIGN-4 1: its kept fragments were dropped for want of disk (why): the
+ // recording went on, resumability went.
+ fragmentsDropped?: string;
+ // A fresh from-start part after a stop (DESIGN-4 2), its number.
+ fresh?: number;
+ // REVIEW-7 2: after a resume, a stream file that is not its kept fragments
+ // (why) — the resume may have appended what is not the stream.
+ resumeDamaged?: string;
+ // REVIEW-7 7: why the behind check could not tell how far behind it is.
+ behindUnknown?: string;
+ // DESIGN-5 7: resumed after yt-dlp had finished it (a self-exit): its
+ // state rebuilt at the fragment count the byte equation proves — the
+ // fragments it reused (not fetched again).
+ reused?: { fragments: number; at: string };
// Proven to begin at the stream's start, by what was recorded: a YouTube
// `--live-from-start` part (not one fallen to index 0) on a stream under
// 120 h old; another platform's
// `--live-from-start` only when that run's first playlist read listed the
// start; a platform VOD whose poll began at its first segment. A part
// without it (index-0, the browser path, a later attempt, rows written
- // before the mark) is never taken as holding the start for a removal or a
- // replacement.
+ // before the mark, a recovery try, a live-edge part) is never taken as
+ // holding the start for a removal or a replacement. A part RESUMED in place
+ // keeps the mark its original run earned (the same file continues).
provenStart?: boolean;
};
@@ -543,13 +600,333 @@ export type LiveRecordingRecord = {
missingStream?: MissingStream;
// Who stopped it, when it was stopped: a person's Cancel, or the editor
// shutting down (then the status is `interrupted`).
- stoppedBy?: "operator" | "shutdown";
+ // `crash`: the editor died with it recording (found so at the next boot).
+ stoppedBy?: "operator" | "shutdown" | "crash";
// Parts left on disk, not landed (KeptPart).
keptParts?: KeptPart[];
// Parts the landing removed as inside the landed file (RemovedPart).
removedParts?: RemovedPart[];
// Once landed: does it hold the whole stream (StreamCoverage).
coverage?: StreamCoverage;
+ // After a fallback to the live edge: the from-start tries beside it
+ // (StartRecovery).
+ startRecovery?: StartRecovery;
+ // The recorder restarted after a stall or a death mid-stream (LiveRestarts).
+ restarts?: LiveRestarts;
+ // This run was started by the boot pass after an editor restart, for the
+ // interrupted run that started at this time (its row's startedAt).
+ 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[];
+ // 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[] };
+ // DESIGN-5 4: landed while the last state read said the stream is live (or
+ // could not be read): never "the whole stream"; how much of it, by the
+ // clock at that moment, is in no landed file.
+ landedWhileLive?: { at: string; unrecordedSeconds: number | null; why: string };
+ // REVIEW-7 1: the state cannot be read for the network: nothing is started,
+ // the read is made again on a paced wait (since, how many reads).
+ offline?: { since: string; reads: 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[];
+ // The landed file is parts joined into one (controller/liveJoin.ts): where
+ // each join is, and what it is. Also in data/<id>/live-joins.json.
+ joins?: LiveJoin[];
+};
+
+// --- parts joined into one file (controller/liveJoin.ts) ---------------------------
+
+// One join in the joined file: `at` seconds into it. overlap: the two parts
+// share `seconds` of the stream, found by their sound (basis "content");
+// `duplicatedSeconds` are heard twice at the join (the cut starts at a
+// keyframe). gap: `seconds` of the stream are in NEITHER part, by the clock
+// (basis "clock", about) — the joined file's timeline after it is not the
+// stream's (live-joins.json maps it).
+export type LiveJoin = {
+ at: number;
+ kind: "overlap" | "gap";
+ seconds: number;
+ duplicatedSeconds?: number;
+ // An overlap: where the next part was asked to start, and where its stream
+ // copy really starts (seconds into that part); duplicatedSeconds is the
+ // difference.
+ cutAt?: number;
+ cutFrom?: number;
+ basis: "content" | "clock";
+ score?: number;
+ parts: string[];
+};
+
+// Where one part is in the joined file and in the stream: the joined file's
+// [joinedFrom, joinedTo) is the part file's [fileFrom, fileTo), which begins
+// `streamFrom` seconds into the stream (basis: "start" a from-start part,
+// "content" found by sound, "clock" by the clock).
+export type LiveJoinSegment = {
+ stem: string;
+ streamFrom: number;
+ streamFromBasis: "start" | "content" | "clock";
+ fileFrom: number;
+ fileTo: number;
+ joinedFrom: number;
+ joinedTo: number;
+};
+
+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.
+// "shorter": its last cue ends inside the replaced file's length (within
+// 60 s) and the new file runs on past it; "unknown": which file it came from
+// cannot be told (it does not read, holds no cues, or the replaced file's
+// length is not known) — nothing is asked, a person decides. jobId: the
+// transcription asked; error: why it was not.
+export type LiveTranscriptRedo = {
+ verdict: "shorter" | "unknown";
+ why: string;
+ replacedSeconds: number | null;
+ lastCueEnd: number | null;
+ at: string;
+ jobId?: string;
+ error?: string;
+};
+
+// data/<id>/live-joins.json: the landed container was joined from parts.
+export type LiveJoinsRecord = {
+ landedAt: string;
+ container: string | null;
+ seconds: number;
+ segments: LiveJoinSegment[];
+ joins: LiveJoin[];
+};
+
+export function coerceLiveJoins(raw: unknown): LiveJoinsRecord | null {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const r = raw as LiveJoinsRecord;
+ if (!Array.isArray(r.segments) || !Array.isArray(r.joins) || typeof r.seconds !== "number") return null;
+ return r;
+}
+
+// --- the insurance recorder: the live edge while the start catches up ----------
+//
+// A from-start recording of a stream that has run for a while is BEHIND the
+// live edge for a long time (20 Nov 2026: fragment 4453 of 30299 after ten
+// minutes). A stream removed in that window loses everything between the
+// catch-up point and its end. The insurance recorder records the live edge
+// beside it — its own part, its own recorder — and stops LIVE_INSURANCE_MARGIN_MS
+// after the from-start recorder has caught up (every stream it reports within
+// LIVE_CAUGHT_UP_FRAGS fragments of its total), or runs the whole stream
+// ("whole"). It starts LIVE_INSURANCE_DELAY_MS after the from-start part's
+// first bytes, so the two extractions are never back to back. Its part lands
+// only under the landing's rules: removed when the landed file holds the
+// whole stream, else kept and listed.
+//
+// ON by default when the stream is marked keep before or when the recording
+// starts (doNotClean asked, the record's Do-not-clean marker, a pending
+// keep); OFF otherwise; the request's `insurance` overrides either way.
+export const LIVE_CAUGHT_UP_FRAGS = 30;
+export const LIVE_INSURANCE_DELAY_MS = 60_000;
+export const LIVE_INSURANCE_MARGIN_MS = 5 * 60_000;
+// After the main recording ends with the stream read as ended.
+export const LIVE_INSURANCE_END_GRACE_MS = 2 * 60_000;
+// Starts of the insurance recorder: the first, after it died early, after a
+// from-start part showed itself far behind again. Bounded PER HOUR (DESIGN-5
+// point 5: ingest pauses must not spend them), and per run.
+export const LIVE_INSURANCE_MAX_STARTS_PER_HOUR = 3;
+export const LIVE_INSURANCE_MAX_STARTS = 24;
+// How far behind the live edge a from-start part must show itself (its first
+// `frag N/M`: the stream's age × (1 − N/M)) for the insurance to start.
+export const LIVE_INSURANCE_BEHIND_SECONDS = 10 * 60;
+
+// waiting for the from-start part's first bytes (and the pause)
+// recording it records
+// caught-up stopped: the from-start recording caught up (+ the margin)
+// ended its recorder ended (the stream ended, or the grace after it)
+// stalled the stall watchdog stopped it (older rows)
+// died it exited (or stalled) before the from-start recording
+// caught up or the stream ended: started again within
+// LIVE_INSURANCE_MAX_STARTS
+// stopped a Cancel or a shutdown, or the run fell back to the live edge
+// failed it recorded nothing
+// not-started not needed or not possible: the from-start part never
+// recorded, the run fell back to the live edge, or it caught
+// up before the insurance began
+export type LiveInsuranceState = "waiting" | "recording" | "caught-up" | "ended" | "stalled" | "died" | "stopped" | "failed" | "not-started";
+
+export type LiveInsurance = {
+ mode: "catch-up" | "whole";
+ // On by the keep-mark default, asked by the request, or started because a
+ // from-start part showed itself far behind (insuranceWhenBehind).
+ by: "default" | "asked" | "behind";
+ // When each start was made (the hourly bound).
+ startTimes?: string[];
+ state: LiveInsuranceState;
+ reason?: string;
+ // How many times it was started.
+ starts?: number;
+};
+
+// Whether the insurance runs, and how: the request's `insurance` (true, false,
+// "whole") wins; absent, on ("catch-up") exactly when the stream is marked keep.
+export function insuranceDecision(o: { asked: boolean | "whole" | undefined; keepMarked: boolean }): Pick<LiveInsurance, "mode" | "by"> | null {
+ if (o.asked === false) return null;
+ if (o.asked === "whole") return { mode: "whole", by: "asked" };
+ if (o.asked === true) return { mode: "catch-up", by: "asked" };
+ return o.keepMarked ? { mode: "catch-up", by: "default" } : null;
+}
+
+// yt-dlp's fragment progress, `[download] … (frag N/M)`, with the separate
+// stream's number (`1: …`, `2: …`; "0" for a muxed one).
+export function parseFragProgress(line: string): { stream: string; frag: number; total: number } | null {
+ const m = /^(?:(\d+):\s*)?\[download\].*\(frag (\d+)\/(\d+)\)/.exec(line.trim());
+ if (!m) return null;
+ return { stream: m[1] ?? "0", frag: Number(m[2]), total: Number(m[3]) };
+}
+
+// Caught up: every stream that has reported is within LIVE_CAUGHT_UP_FRAGS of
+// its total. `feed` answers whether it is now.
+export function catchUpTracker(): { feed: (line: string) => boolean; reset: () => void; seen: () => boolean } {
+ const by = new Map<string, { frag: number; total: number }>();
+ return {
+ feed(line) {
+ const p = parseFragProgress(line);
+ if (!p) return false;
+ by.set(p.stream, { frag: p.frag, total: p.total });
+ return [...by.values()].every((v) => v.total > 0 && v.frag >= v.total - LIVE_CAUGHT_UP_FRAGS);
+ },
+ reset() {
+ by.clear();
+ },
+ seen: () => by.size > 0,
+ };
+}
+
+// WHAT THE BOOT PASS DID WITH AN INTERRUPTED RUN (controller/liveRecordingBoot.ts),
+// on that run's row. Written BEFORE the new run is asked for (`starting`), so
+// a row is restarted at most once, even if the boot itself dies after.
+// starting the new run is being asked for
+// asked a record-live job was queued (jobId)
+// restarted that job found the stream live and records it
+// landing the stream had ended; what the earlier run left lands
+// ended the stream had ended and nothing was left to land
+// unknown the stream's state could not be read: nothing was started
+// (never a recording on a guess) — Record again
+// refused not restarted (reason: a restart loop, a recorder of the last
+// process still writing, the setting off)
+// failed the job could not be queued (reason)
+// landing: the boot's run is landing what the interrupted run left (the
+// stream ended, gone, or its state not readable); landed / failed: what that
+// landing did (REVIEW-5 B3: the row says what was done, not what was meant).
+export type LiveBootRestartState = "starting" | "asked" | "restarted" | "landing" | "landed" | "ended" | "unknown" | "refused" | "failed";
+
+export type LiveBootRestart = { at: string; by: "boot"; state: LiveBootRestartState; jobId?: string; reason?: string };
+
+// --- the stall watchdog and the restarts ------------------------------------------
+//
+// While a recorder runs, its part's files (every one: a merge's temp file is
+// growth too) are compared every LIVE_WATCH_MS. No growth for stallMinutes
+// (settings.liveRecording.stallMinutes, default 10) stops THAT recorder
+// (SIGINT, so its file is finalized); its part stays. A recorder that stalled
+// with bytes, or exited with bytes while the stream still reads live (two
+// reads LIVE_RESTART_CONFIRM_MS apart — a stream that has just ended may read
+// live for a moment), is restarted: one metadata read (the read the job makes
+// at its end anyway), LIVE_RESTART_WAIT_MS, a new part with its own stem
+// from the LIVE EDGE (the earlier part holds the past; REVIEW-2 of
+// live-guard-2). Bounded: LIVE_RESTART_MAX_PER_HOUR in any 60 minutes and
+// LIVE_RESTART_MAX_PER_RUN in all; past either the run lands what it has and
+// `refused` needs a person.
+export const LIVE_WATCH_MS = 60_000;
+export const LIVE_RESTART_WAIT_MS = 30_000;
+export const LIVE_RESTART_CONFIRM_MS = 60_000;
+// Restarts are live-edge recorders (REVIEW-2 of live-guard-2): cheap, so a
+// flaky connection gets more of them than the whole-stream passes once did.
+export const LIVE_RESTART_MAX_PER_HOUR = 6;
+export const LIVE_RESTART_MAX_PER_RUN = 24;
+
+export type LiveRestarts = {
+ count: number;
+ // When each restart was made, ISO.
+ at: string[];
+ // Why no further restart was made though the stream was live.
+ refused?: string;
+ // REVIEW-5 note 3: a bound reached on a stream still live is waited out,
+ // not an end: how many times, and the wait in progress (nothing records
+ // meanwhile — the row says so).
+ waited?: number;
+ waiting?: { until: string; why: string };
+};
+
+// How long to wait before one more restart at `nowMs` (REVIEW-5 note 3): the
+// hour's bound frees when its oldest restart is an hour old; past the run's
+// bound, at most one an hour. null: no wait.
+export function restartWaitMs(r: Pick<LiveRestarts, "count" | "at">, nowMs: number): { ms: number; why: string } | null {
+ const recent = r.at.map((a) => Date.parse(a)).filter((t) => nowMs - t < 3_600_000).sort((a, b) => a - b);
+ if (recent.length >= LIVE_RESTART_MAX_PER_HOUR) {
+ return { ms: Math.max(1_000, recent[0]! + 3_600_000 - nowMs), why: `${recent.length} restarts in the last hour (at most ${LIVE_RESTART_MAX_PER_HOUR})` };
+ }
+ if (r.count >= LIVE_RESTART_MAX_PER_RUN && recent.length) {
+ return { ms: Math.max(1_000, recent[recent.length - 1]! + 3_600_000 - nowMs), why: `${r.count} restarts in this run (past ${LIVE_RESTART_MAX_PER_RUN}: at most one an hour)` };
+ }
+ return null;
+}
+
+// Whether one more restart is allowed at `nowMs`; else the reason.
+export function restartRefusal(r: Pick<LiveRestarts, "count" | "at">, nowMs: number): string | null {
+ if (r.count >= LIVE_RESTART_MAX_PER_RUN) return `${r.count} restarts in this run (at most ${LIVE_RESTART_MAX_PER_RUN})`;
+ const recent = r.at.filter((a) => nowMs - Date.parse(a) < 3_600_000).length;
+ if (recent >= LIVE_RESTART_MAX_PER_HOUR) return `${recent} restarts in the last hour (at most ${LIVE_RESTART_MAX_PER_HOUR})`;
+ return null;
+}
+
+// --- recovering the start beside a live-edge recording ----------------------------
+//
+// A run that fell back to the live edge (its from-start attempts recorded
+// nothing) tries from its start again BESIDE the live-edge recorder, which is
+// never touched: every LIVE_RECOVERY_EVERY_MS (stretched by pacing.jitter), one
+// try at a time, at most LIVE_RECOVERY_MAX_TRIES. YouTube keeps a live stream's
+// start for days, so a refusal that passes (20 Nov 2026: the same argv worked
+// hours later) still gets the whole stream. Each failed try costs what the
+// failed from-start attempt did: one extraction and its probes, at the pace.
+export const LIVE_RECOVERY_EVERY_MS = 15 * 60_000;
+export const LIVE_RECOVERY_MAX_TRIES = 8;
+
+// waiting the next try is due (or the first)
+// trying a try records now
+// recorded a try recorded from its start and the stream ended: the
+// landing decides whether it holds the whole stream
+// recovered the landed file is a from-start try and holds the whole stream
+// gave-up a failure no try can help (ended, private, members, the disk,
+// the argv, from-its-start unsupported, a second rate limit)
+// exhausted every try was made
+// stopped the live-edge recording ended (or a Cancel) before a try
+// recorded
+export type StartRecoveryState = "waiting" | "trying" | "recorded" | "recovered" | "gave-up" | "exhausted" | "stopped";
+
+export type StartRecovery = {
+ tries: number;
+ max: number;
+ everyMs: number;
+ state: StartRecoveryState;
+ // The last failed try's reason and class.
+ lastError?: string;
+ failureClass?: LiveFailureClass;
};
const LIVE_STATUSES: ReadonlySet<string> = new Set(["recording", "landed", "failed", "cancelled", "interrupted"]);
@@ -635,7 +1012,18 @@ export type LiveFailureClass =
| "unknown"
| "argv"
| "unsupported"
- | "partial";
+ | "partial"
+ | "stalled"
+ // DESIGN-5: yt-dlp could not refresh the stream's URL ("Cannot find
+ // refreshed url for format …", "Giving up after N retries") — the platform
+ // stopped serving that format (its DVR switched off mid-stream); yt-dlp then
+ // merges and exits 0 while the stream may still be live.
+ | "url-refresh"
+ // DESIGN-5 (c): fragment requests answered 403 Forbidden, then the state
+ // read says the video is private or removed — the platform pulled it while
+ // it was recorded: what is on disk lands, loud, never retried in a loop,
+ // and nothing on disk is removed.
+ | "went-private";
// What yt-dlp says when the stream is over or gone: no attempt can help.
export function liveStreamGone(stderr: string): boolean {
@@ -647,8 +1035,11 @@ export function liveFailureClass(stderr: string): LiveFailureClass {
const t = stderr;
// First: no space is no space, whatever else the tail says.
if (/No space left on device|Errno 28\b|Disk quota exceeded|Read-only file system|\[Errno 13\] Permission denied/i.test(t)) return "disk";
+ if (/Cannot find refreshed url for format/i.test(t)) return "url-refresh";
// Before `members`: the bot check's message also says "use --cookies".
- 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/liveFragments-server.test.ts b/common/lib/liveFragments-server.test.ts
@@ -0,0 +1,155 @@
+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]);
+});
+
+test("REVIEW-6 6: an EMPTY kept fragment is no proof, and the file must END with its last fragment's bytes", async () => {
+ const s = await laid(4);
+ await writeFile(`${s.file}-Frag3`, "");
+ assert.match(((await accountStream(s.dir, s.name)) as { why: string }).why, /fragment 3 .* is empty/);
+ const t = await laid(4);
+ // Same sizes, other bytes at the end: not the fragments.
+ const { open } = await import("node:fs/promises");
+ const fh = await open(t.file, "r+");
+ await fh.write(Buffer.from("XX"), 0, 2, (await stat(t.file)).size - 2);
+ await fh.close();
+ assert.match(((await accountStream(t.dir, t.name)) as { why: string }).why, /does not end with its fragment 4/);
+});
+
+test("REVIEW-6 11: with the state unreadable (caught mid-rewrite), nothing is dropped", async () => {
+ const s = await laid(5);
+ await writeFile(`${s.file}.ytdl`, "{ half");
+ assert.equal(await dropFragments(s.dir, s.name), 0);
+ assert.equal((await readdir(s.dir)).filter((x) => /-Frag/.test(x)).length, 5);
+});
+
+test("REVIEW-6 2/3: the fragments past the state go before a resume; a stream file equals its fragments byte for byte, or not", async () => {
+ const { dropFragmentsAbove, streamEqualsFragments } = await import("./liveFragments-server");
+ const s = await laid(6);
+ await writeFile(`${s.file}-Frag7`, frag(7));
+ assert.deepEqual(await dropFragmentsAbove(s.dir, s.name, 6), [7]);
+ assert.deepEqual(await streamEqualsFragments(s.dir, s.name), { ok: true, fragments: 6 });
+ await writeFile(`${s.file}-Frag2`, Buffer.from(frag(2).toString().replace("2", "9")));
+ assert.match(((await streamEqualsFragments(s.dir, s.name)) as { why: string }).why, /not fragment 2/);
+});
diff --git a/common/lib/liveFragments-server.ts b/common/lib/liveFragments-server.ts
@@ -0,0 +1,266 @@
+// 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 };
+ const fs = (await sizeOf(path.join(dir, `${name}-Frag${n}`))) ?? 0;
+ // REVIEW-6 6: an empty kept fragment is no proof (a crash can leave the
+ // state flushed and the fragment and the append not).
+ if (fs === 0) return { ok: false, why: `fragment ${n} of ${name} is empty`, index: idx, size };
+ expected += fs;
+ }
+ if (size === expected) {
+ // ... and the file ENDS with the last fragment's bytes.
+ if (idx > checkpoint.index) {
+ const last = await readFile(path.join(dir, `${name}-Frag${idx}`));
+ const tail = Buffer.alloc(last.length);
+ const fh = await open(file, "r");
+ try {
+ await fh.read(tail, 0, last.length, size - last.length);
+ } finally {
+ await fh.close();
+ }
+ if (!tail.equals(last)) return { ok: false, why: `${name} does not end with its fragment ${idx}`, index: idx, size };
+ }
+ return { ok: true, index: idx, size, expected, checkpoint, kept };
+ }
+ if (size < expected) return { ok: 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);
+ // REVIEW-6 11: read twice (yt-dlp rewrites it); no index, nothing dropped —
+ // never the fragment being downloaded.
+ let idx = await readYtdlIndex(file);
+ if (typeof idx !== "number") {
+ await new Promise((r) => setTimeout(r, 50));
+ idx = await readYtdlIndex(file);
+ }
+ if (typeof idx !== "number") return 0;
+ const names = await readdir(dir).catch(() => [] as string[]);
+ let n = 0;
+ for (const k of fragNumbers(name, names)) {
+ if (k > idx) continue;
+ await rm(path.join(dir, `${name}-Frag${k}`), { force: true });
+ n++;
+ }
+ return n;
+}
+
+// REVIEW-6 2: BEFORE EVERY RESUME, every kept fragment past the state's
+// index goes. Under --no-part a complete `-Frag<index+1>` gets a Range request
+// past its end on the resume: 416, "Giving up", exit 3, nothing recorded
+// (measured, LOG REVIEW-6). A partial one would be resumed by Range — it goes
+// too; it costs a re-download, the whole one costs the resume.
+export async function dropFragmentsAbove(dir: string, name: string, index: number): Promise<number[]> {
+ const names = await readdir(dir).catch(() => [] as string[]);
+ const gone: number[] = [];
+ for (const k of fragNumbers(name, names)) {
+ if (k <= index) continue;
+ await rm(path.join(dir, `${name}-Frag${k}`), { force: true });
+ gone.push(k);
+ }
+ return gone;
+}
+
+// REVIEW-6 3: does the stream file hold exactly its kept fragments 1..N, in
+// order, every one non-empty? (Before the fragments are removed: they may be
+// the only whole copy.) null: no fragments kept to compare with.
+export async function streamEqualsFragments(dir: string, name: string): Promise<{ ok: true; fragments: number } | { ok: false; why: string } | null> {
+ const names = await readdir(dir).catch(() => [] as string[]);
+ const kept = fragNumbers(name, names);
+ if (!kept.length) return null;
+ if (kept[0] !== 1 || kept[kept.length - 1] !== kept.length) return { ok: false, why: `${name}: its kept fragments are not 1..${kept.length} without a gap` };
+ const file = path.join(dir, name);
+ const size = (await stat(file).catch(() => null))?.size ?? 0;
+ let off = 0;
+ const fh = await open(file, "r").catch(() => null);
+ if (!fh) return { ok: false, why: `${name} does not open` };
+ try {
+ for (const n of kept) {
+ const frag = await readFile(path.join(dir, `${name}-Frag${n}`));
+ if (!frag.length) return { ok: false, why: `${name}: fragment ${n} is empty` };
+ const here = Buffer.alloc(frag.length);
+ const { bytesRead } = await fh.read(here, 0, frag.length, off);
+ if (bytesRead !== frag.length || !here.equals(frag)) return { ok: false, why: `${name}: its bytes at ${off} are not fragment ${n}` };
+ off += frag.length;
+ }
+ } finally {
+ await fh.close();
+ }
+ if (off !== size) return { ok: false, why: `${name} is ${size} bytes, its ${kept.length} fragments ${off}` };
+ return { ok: true, fragments: kept.length };
+}
+
+// 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
@@ -33,7 +33,15 @@ import type {
LiveRecordingRecord,
LiveRecordingStatus,
LostSpan,
+ LiveBootRestart,
+ LiveInsurance,
+ LiveJoin,
+ LiveRestarts,
+ LiveSpaceHeld,
+ LiveTranscriptRedo,
+ LiveVerification,
MissingStream,
+ StartRecovery,
StreamCoverage,
} from "./liveCapture";
@@ -67,10 +75,28 @@ export type LiveRecordingRow = {
landedPart?: number;
failureClass?: LiveFailureClass;
missingStream?: MissingStream;
- stoppedBy?: "operator" | "shutdown";
+ stoppedBy?: "operator" | "shutdown" | "crash";
keptParts?: KeptPart[];
removedParts?: RemovedPart[];
coverage?: StreamCoverage;
+ startRecovery?: StartRecovery;
+ restarts?: LiveRestarts;
+ // This run was started by the boot pass for the interrupted run of this
+ // startedAt; and, on an interrupted run, what the boot pass did with it.
+ resumeOf?: string;
+ restart?: LiveBootRestart;
+ insurance?: LiveInsurance;
+ joins?: LiveJoin[];
+ spaceHeld?: LiveSpaceHeld[];
+ endedBy?: { class: LiveFailureClass; message: string; at: string };
+ awaitingResume?: string[];
+ transcriptRedo?: LiveTranscriptRedo;
+ verification?: LiveVerification;
+ skippedFragments?: { count: number; positions: number[] };
+ landedWhileLive?: { at: string; unrecordedSeconds: number | null; why: string };
+ offline?: { since: string; reads: number };
+ // What the landing kept: this run's file stored ("new"), or the store's.
+ kept?: "new" | "existing";
acknowledgedAt?: string;
acknowledgedBy?: string;
// The run (its jobId, else its startedAt) that later landed this id.
@@ -135,11 +161,21 @@ export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, s
// Needs a person, as the row stands (the listing adds `interrupted` for a
// `recording` no job runs).
-// failed, interrupted always
+// failed, interrupted always (the listing lets an
+// interruption the boot pass restarted
+// go quiet only while the NEW run's
+// part grows)
// cancelled when the stream was must-keep (a
// person's Cancel of any other stream
// is quiet)
-// recorded from the live edge the stream's start is lost
+// recorded from the live edge the stream's start is lost — unless
+// a from-start try beside it was
+// landed and holds the whole stream
+// (startRecovery "recovered")
+// restarts refused the stream was live and its recorder
+// stalled or died once too often
+// joined with a gap parts joined into the landed file
+// with seconds of the stream in none
// one stream missing it landed without video or audio
// parts kept on disk (keptParts) until acknowledged, whatever lands
// later: a later recording does not
@@ -148,14 +184,45 @@ 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">>,
+ Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream" | "startRecovery" | "restarts" | "restart" | "fromStart" | "joins" | "spaceHeld" | "lost" | "endedBy" | "awaitingResume" | "transcriptRedo" | "verification" | "skippedFragments" | "parts" | "landedWhileLive" | "coverage" | "offline">>,
): 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;
+ // DESIGN-5 4: landed while the stream was still live — until acknowledged.
+ if (r.landedWhileLive) return true;
+ // REVIEW-7 1: the state cannot be read (offline): nothing records meanwhile.
+ if (r.offline) return true;
+ if (r.parts?.some((p) => p.resumeDamaged)) return true;
+ // REVIEW-6 4: landed SHORT of an ended stream's own duration — the rest is
+ // in no file (and the archive line stops any later download): a person,
+ // "download the VOD now".
+ if (r.status === "landed" && r.coverage?.basis === "duration" && r.coverage.covers === false) return true;
+ // Parts left in staging with their state, to be resumed: a resume, or a
+ // person (DESIGN-3; a later run that did not resume them lists them too).
+ if (r.awaitingResume && r.awaitingResume.length) return true;
+ // The transcript is (or may be) the replaced shorter file's and no
+ // transcription was asked (REVIEW-LF-4 2).
+ if (r.transcriptRedo && (r.transcriptRedo.verdict === "unknown" || !r.transcriptRedo.jobId)) return true;
if (r.status === "failed" || r.status === "interrupted") return true;
if (r.status === "cancelled" && r.mustKeep === true) return true;
- if (r.fallback === "live-edge") return true;
+ if (r.fallback === "live-edge" && r.startRecovery?.state !== "recovered") return true;
+ // A span of the stream in no part (REVIEW-3 3.1), until a part holds it.
+ if (r.lost && r.startRecovery?.state !== "recovered") return true;
+ if (r.restarts?.refused) return true;
+ // Waiting out a restart bound: nothing records meanwhile.
+ if (r.restarts?.waiting) 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;
}
@@ -225,20 +292,40 @@ export function rowOfRecord(
...(rec.streamStartedAt ? { streamStartedAt: rec.streamStartedAt } : {}),
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.transcriptRedo ? { transcriptRedo: { ...rec.transcriptRedo } } : {}),
+ ...(rec.verification ? { verification: { ...rec.verification } } : {}),
+ ...(rec.skippedFragments ? { skippedFragments: { ...rec.skippedFragments } } : {}),
+ ...(rec.landedWhileLive ? { landedWhileLive: { ...rec.landedWhileLive } } : {}),
+ ...(rec.offline ? { offline: { ...rec.offline } } : {}),
+ ...(rec.spaceHeld && rec.spaceHeld.length ? { spaceHeld: rec.spaceHeld.map((x) => ({ ...x })) } : {}),
...(rec.failureClass ? { failureClass: rec.failureClass } : {}),
...(rec.missingStream ? { missingStream: rec.missingStream } : {}),
...(rec.stoppedBy ? { stoppedBy: rec.stoppedBy } : {}),
...(rec.keptParts && rec.keptParts.length ? { keptParts: rec.keptParts.map((k) => ({ ...k, files: k.files.map((f) => ({ ...f })) })) } : {}),
...(rec.removedParts && rec.removedParts.length ? { removedParts: rec.removedParts.map((r) => ({ ...r })) } : {}),
...(rec.coverage ? { coverage: { ...rec.coverage } } : {}),
+ ...(rec.startRecovery ? { startRecovery: { ...rec.startRecovery } } : {}),
+ ...(rec.restarts ? { restarts: { ...rec.restarts, at: [...rec.restarts.at] } } : {}),
+ ...(rec.resumeOf ? { resumeOf: rec.resumeOf } : {}),
+ ...(rec.insurance ? { insurance: { ...rec.insurance } } : {}),
+ ...(rec.joins && rec.joins.length ? { joins: rec.joins.map((j) => ({ ...j, parts: [...j.parts] })) } : {}),
};
}
// Whether a row holds the whole stream: landed, from its start, with video and
// audio, and as long as the stream within the coverage's tolerance
-// (controller/recordLive.ts streamCoverage). Only such a run supersedes.
-export function rowCoversStream(r: Pick<LiveRecordingRow, "status" | "fromStart" | "fallback" | "missingStream" | "coverage">): boolean {
- return r.status === "landed" && r.fromStart && !r.fallback && !r.missingStream && r.coverage?.covers === true;
+// (controller/recordLive.ts streamCoverage). Only such a run supersedes. A run
+// that fell back to the live edge qualifies only when a from-start try beside
+// it was the landed file and covers (startRecovery "recovered").
+export function rowCoversStream(
+ r: Pick<LiveRecordingRow, "status" | "fromStart" | "fallback" | "missingStream" | "coverage"> & Partial<Pick<LiveRecordingRow, "startRecovery">>,
+): boolean {
+ const startHeld = !r.fallback || r.startRecovery?.state === "recovered";
+ // (Never a landing made while the stream still read live: DESIGN-5 3.)
+ return r.status === "landed" && r.fromStart && startHeld && !r.missingStream && r.coverage?.covers === true && !(r as { landedWhileLive?: unknown }).landedWhileLive;
}
// Writes (or rewrites) the run's row. A run that lands the WHOLE stream
@@ -258,6 +345,7 @@ export async function upsertLiveRecordingRow(
...(prev?.acknowledgedAt ? { acknowledgedAt: prev.acknowledgedAt } : {}),
...(prev?.acknowledgedBy ? { acknowledgedBy: prev.acknowledgedBy } : {}),
...(prev?.supersededBy ? { supersededBy: prev.supersededBy } : {}),
+ ...(prev?.restart ? { restart: prev.restart } : {}),
};
if (i >= 0) rows[i] = next;
else rows.push(next);
@@ -314,3 +402,20 @@ export async function acknowledgeSetAsideFiles(
return [n, n > 0];
});
}
+
+// Changes one row (by id and startedAt) under the file's lock. False: no such
+// row. `fn` returns false to write nothing.
+export async function patchLiveRecordingRow(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ id: string,
+ startedAt: string,
+ fn: (row: LiveRecordingRow) => boolean | void,
+): Promise<boolean> {
+ return mutate(paths, slug, (rows) => {
+ const r = rows.find((x) => x.id === id && x.startedAt === startedAt);
+ if (!r) return [false, false];
+ const changed = fn(r) !== false;
+ return [true, changed];
+ });
+}
diff --git a/common/lib/liveVerify-server.test.ts b/common/lib/liveVerify-server.test.ts
@@ -0,0 +1,135 @@
+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|stopped short/);
+});
+
+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));
+});
+
+// REVIEW-6 3: the two cases the packet comparison alone passed.
+test("a TORN raw video track (a fragment cut, later ones appended): raw and merged agree, but the picture stops where the tear is — not whole", async () => {
+ const parts = [await readFile(path.join(ROOT, "init-0.m4s"))];
+ const names = await segs(0);
+ for (const [i, n] of names.entries()) {
+ const b = await readFile(path.join(ROOT, n));
+ parts.push(i === 6 ? b.subarray(0, Math.floor(b.length * 0.6)) : b);
+ }
+ const v = path.join(ROOT, "vt.mp4");
+ await writeFile(v, Buffer.concat(parts));
+ const a = await streamFile(1, path.join(ROOT, "at.m4a"));
+ const m = await merge(v, a, path.join(ROOT, "mt.mp4"));
+ const r = await verifyMerged(FFPROBE, m, [v, a]);
+ assert.equal(r.ok, false, JSON.stringify(r));
+ assert.match((r as { why: string }).why, /stopped short|hole/);
+});
+
+test("a video track that STOPPED EARLY (its thread ended, the sound went on): not whole", async () => {
+ const v = await streamFile(0, path.join(ROOT, "vs.mp4"), [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]);
+ const a = await streamFile(1, path.join(ROOT, "as.m4a"));
+ const m = await merge(v, a, path.join(ROOT, "ms.mp4"));
+ const r = await verifyMerged(FFPROBE, m, [v, a]);
+ assert.equal(r.ok, false, JSON.stringify(r));
+ assert.match((r as { why: string }).why, /stopped short/);
+});
+
+test("REVIEW-7 4: the tracks' tolerance is max(2 s, 2 fragments) — 4 s apart fails with no fragment length, passes with 5 s fragments", async () => {
+ const v = await streamFile(0, path.join(ROOT, "vf.mp4"), [17, 18, 19, 20]);
+ const a = await streamFile(1, path.join(ROOT, "af.m4a"));
+ const m = await merge(v, a, path.join(ROOT, "mf.mp4"));
+ assert.equal((await verifyMerged(FFPROBE, m, [v, a])).ok, false, "2 s by default");
+ assert.equal((await verifyMerged(FFPROBE, m, [v, a], undefined, { fragmentSeconds: 5 })).ok, true, "2 fragments of 5 s");
+});
diff --git a/common/lib/liveVerify-server.ts b/common/lib/liveVerify-server.ts
@@ -0,0 +1,158 @@
+// 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;
+};
+
+// REVIEW-6 3: the picture and the sound of one recording end together. A
+// track torn or stopped early reads, raw and merged alike, only up to where
+// it stopped (ffprobe stops where the merge did), so the packets agree; the
+// OTHER track does not. Apart by more than max(2 s, 2 fragments): not whole.
+export const TRACK_SPAN_MIN_TOLERANCE_SECONDS = 2;
+const tracksApart = (tracks: TrackScan[], fragmentSeconds: number): string | null => {
+ const v = tracks.find((t) => t.kind === "video");
+ const a = tracks.find((t) => t.kind === "audio");
+ if (!v || !a) return null;
+ const tol = Math.max(TRACK_SPAN_MIN_TOLERANCE_SECONDS, 2 * fragmentSeconds);
+ return Math.abs(v.span - a.span) > tol ? `its video holds ${v.span.toFixed(1)} s and its audio ${a.span.toFixed(1)} s (more than ${tol} s apart): one track stopped short` : null;
+};
+
+// One file alone (a muxed recording): the scan.
+export async function verifyScan(ffprobeBin: string, file: string, signal?: AbortSignal, o: { fragmentSeconds?: number } = {}): 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 };
+ }
+ const apart = tracksApart(s.tracks, o.fragmentSeconds ?? 0);
+ if (apart) return { ok: false, why: apart };
+ 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, o: { fragmentSeconds?: number } = {}): 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}` };
+ }
+ const apart = tracksApart(m.tracks, o.fragmentSeconds ?? 0);
+ if (apart) return { ok: false, why: `the merged file: ${apart}` };
+ 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/common/lib/mediaImport-server.ts b/common/lib/mediaImport-server.ts
@@ -8,11 +8,14 @@ import {
coerceMediaImport,
type MediaImportEntry,
} from "./mediaImport";
-import { LIVE_RECORDING_FILENAME, coerceLiveRecording } from "./liveCapture";
+import { LIVE_JOINS_FILENAME, LIVE_RECORDING_FILENAME, coerceLiveJoins, coerceLiveRecording } from "./liveCapture";
export const mediaImportSidecar = sidecar(MEDIA_IMPORT_FILENAME, sidecarField(coerceMediaImport));
export const liveRecordingSidecar = sidecar(LIVE_RECORDING_FILENAME, sidecarField(coerceLiveRecording));
+// A landed live recording joined from parts (controller/liveJoin.ts): the
+// segments and the joins, for the clip tools.
+export const liveJoinsSidecar = sidecar(LIVE_JOINS_FILENAME, sidecarField(coerceLiveJoins), { indent: 2 });
export async function recordMediaImport(videoDir: string, entry: MediaImportEntry): Promise<void> {
const prev = await mediaImportSidecar.load(videoDir);
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -1016,17 +1016,34 @@ export function sanitizeLivePreclip(v: unknown): LivePreclipSettingsBlock {
// LIVE_RECORDING_SETTINGS_FIELD_DOCS (rendered into SETTINGS.md).
export type LiveRecordingSettingsBlock = {
stallMinutes: number;
+ autoRestartOnBoot: boolean;
+ insuranceWhenBehind: boolean;
};
export const LIVE_RECORDING_SETTINGS_FIELD_DOCS: FieldDocs<LiveRecordingSettingsBlock> = {
stallMinutes:
"Minutes a running live recording's files may go without growing before `pnpm ops get live-recordings` (and /review, " +
- "the banners) mark it `stalled`. Clamped 1–240; default 10.",
+ "the banners) mark it `stalled` — and before record-live's own watchdog stops that recorder and, while the stream is " +
+ "still live, starts a new part from the live edge (at most 6 restarts an hour, 24 a run). Clamped 1–240; default 10.",
+ autoRestartOnBoot:
+ "After an editor restart, a live recording the shutdown (or a crash) interrupted is restarted by itself: the new run " +
+ "reads the stream's state first (one paced metadata request) and records only if it is still live; ended, it lands what " +
+ "is in staging; unreadable, it starts nothing. At most once per interrupted run and 3 times an hour per stream; never " +
+ "after a person's Cancel (common/controller/liveRecordingBoot.ts). Default true; false leaves every interruption to " +
+ "/review's Record again.",
+ insuranceWhenBehind:
+ "When a from-start part (a fresh part after a stop, or a first attempt) shows itself, by its first `frag N/M`, more " +
+ "than 10 minutes behind the live edge, a live-edge recorder starts beside it — the insurance — whatever the keep mark " +
+ "(unless the request said `insurance: false`), so the stream's tail is held while the catch-up runs (a stream can go " +
+ "private within minutes, and a download in progress does not survive it). Not re-armed on every self-exit: the reuse " +
+ "of kept fragments makes those catch-ups seconds. Its starts are bounded 3 an hour, 24 a run. Default true (the " +
+ "orchestrator's go, DESIGN-5 point 5: the whole stream must be captured); false leaves the insurance to the keep mark " +
+ "and the request.",
};
export function sanitizeLiveRecording(v: unknown): LiveRecordingSettingsBlock {
const r = (v && typeof v === "object" ? v : {}) as Record<string, unknown>;
- return { stallMinutes: clampInt(r.stallMinutes, 1, 240, 10) };
+ return { stallMinutes: clampInt(r.stallMinutes, 1, 240, 10), autoRestartOnBoot: r.autoRestartOnBoot !== false, insuranceWhenBehind: r.insuranceWhenBehind !== false };
}
export const SLEEP_BETWEEN_DOWNLOADS_MAX_SECONDS = 600;
@@ -2040,7 +2057,7 @@ export const siteSettingsSchema = z.object({
"The defaults of LIVE PRE-CLIP (plans/live-preclip.md): a live recording transcribed and mined while it records — record-live's `\"preclip\": true`, `pnpm ops live-preclip`. A request's own `preclip` keys override these. See common/controller/livePreclip.ts.",
),
liveRecording: settingsField((v): LiveRecordingSettingsBlock => sanitizeLiveRecording(v)).describe(
- "How a running live recording is judged (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled. See common/controller/liveRecordings.ts.",
+ "How a running live recording is judged and kept alive (record-live; `pnpm ops get live-recordings`): when its files have stopped growing long enough to call it stalled (and restart its recorder), and whether an editor restart's interruption restarts by itself. See common/controller/liveRecordings.ts and common/controller/liveRecordingBoot.ts.",
),
pacing: settingsField((v): PacingSettingsBlock => sanitizePacing(v)).describe(
"How the download pace adapts to rate limits, per platform (release 17). Every yt-dlp spawn against a platform paces its requests (`--sleep-requests`) at the platform's adaptive pace, and the download lane waits sleepBetweenDownloadsSeconds plus the pace above its fixed value between units. A rate limit doubles the pace; clean units ease it back; a rate limit that outlasts the cooldown cap holds the platform to one probe at a time. The live pace, cooldowns and holds are in `.auto-queue/state.json`, shown on /operations/download. See common/jobs/platformBackoff.ts.",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,54 @@
# Changelog
## [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's
+ part lands when it is the longest, but it is never proven from the start: the live-edge part stays for a person.
+ - A recorder whose files stop growing for `liveRecording.stallMinutes`, or that exits while the stream still reads
+ live, is restarted as a new part from the live edge (at most 6 an hour, 24 a run); its earlier part stays for the
+ landing, and a stream that reads live is never left unrecorded quietly: a span the kept parts do not reach is
+ said on the row and fetched again from the start beside the live-edge recorder.
+ - `"insurance"` on record-live: a live-edge recorder beside a from-start recording until it catches up (or the whole
+ stream). On by default for a stream marked keep.
+ - After an editor restart, a recording the shutdown or a crash interrupted restarts by itself once the stream reads
+ live (`liveRecording.autoRestartOnBoot`); ended, what is in staging lands; unreadable, nothing starts.
+ - Parts that together hold more than the longest are joined `-c copy` when proven (length and sound at each join),
+ the joins on the row and in `live-joins.json`; a gap is stated and needs a person.
+ - A part resumed in place keeps the proof of start its original run earned; a part waiting to be resumed is never
+ landed, removed or counted by a run that did not resume it.
+ - A whole file that replaces a stored shorter landing asks for the transcription again, replacing the transcript,
+ when the transcript's last cue ends inside the shorter file (`transcriptRedo`); when that cannot be told, the row
+ needs a person.
+ - A part left waiting to be resumed always reaches the store: the boot's run lands it when the stream ended, was
+ removed or cannot be read, and any later run takes it into its landing; the row says what was done.
+ - The recorder runs in its own process group (a stop reaches yt-dlp's ffmpeg); SIGTERM only for a part that can
+ be resumed; a resume pins every stream, the empty one too; each stream must grow; 119 h, and an unknown start
+ 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 recorder that ends by itself while the stream is live (yt-dlp's "Cannot find refreshed url … Giving up", now
+ `url-refresh`; any exit, partial ones too) is restarted for as long as the platform says live, REUSING what is
+ downloaded (its state rebuilt at the proven fragment count, the merged copy moved aside) instead of fragment 0;
+ every fragment is kept until the stream is confirmed done.
+ - A landing while the stream still reads live is `landedWhileLive`: loud, "so far", the unrecorded time by the
+ clock, superseding nothing.
+ - yt-dlp's fatal fragment line (`ERROR: \r[download] Got error …`) is read whole and stops the recorder; the fragments
+ past a resume's state are removed first; a short or torn track, or a stream file that is not its fragments, is
+ never "verified".
+ - A stream that ends while its from-start part is behind is resumed once to the end; a landing short of an ended
+ stream's duration says "download the VOD now"; a network drop no longer spends the resume or ends the recording.
+ - A from-start part found more than 10 minutes behind starts the live-edge insurance beside it
+ (`liveRecording.insuranceWhenBehind`, default on); the insurance's starts are bounded per hour.
- **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
diff --git a/editor/app/api/ops/_liveRecordingBoot.ts b/editor/app/api/ops/_liveRecordingBoot.ts
@@ -0,0 +1,47 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
+import {
+ LIVE_BOOT_DELAY_MS,
+ restartInterruptedLiveRecordings,
+} from "yt-dlp-transcript-common/controller/liveRecordingBoot";
+import { recordLiveAction } from "../../channels/[slug]/liveMediaActions";
+
+// THE LIVE RECORDINGS AN EDITOR RESTART INTERRUPTED, RESTARTED (operator
+// ruling, 21 Nov 2026): instrumentation.ts arms this below the idle gate and
+// never on the e2e test server. LIVE_BOOT_DELAY_MS after boot (an orphan
+// recorder of the last process has written by then, and is refused), one pass
+// of common/controller/liveRecordingBoot.ts: each interrupted run asks for a
+// record-live job through the same door the ops route and Record again use,
+// with `resumeOf`, and that job reads the stream's state before it records.
+// The pass itself makes no request.
+export function armLiveRecordingBootPass(bootedAt: number): void {
+ const t = setTimeout(() => {
+ void runPass(bootedAt).catch((e: Error) => console.log(`[boot] live recordings: the restart pass failed (${e.message})`));
+ }, LIVE_BOOT_DELAY_MS);
+ t.unref?.();
+}
+
+async function runPass(bootedAt: number): Promise<void> {
+ const settings = getSettings();
+ await restartInterruptedLiveRecordings({
+ paths: getPaths(),
+ bootedAt,
+ enabled: settings.liveRecording.autoRestartOnBoot,
+ isRunning: (jobId, slug, id) => {
+ const jobs = getRegistry().list();
+ return jobs.some(
+ (j) =>
+ (j.status === "running" || j.status === "queued") &&
+ (jobId ? j.id === jobId : j.kind === "record-live" && j.channelSlug === slug && j.videoId === id),
+ );
+ },
+ start: async (_slug, body, resumeOf) => {
+ const r = await recordLiveAction(body, { resumeOf });
+ if (!r.ok) return { ok: false, error: r.error };
+ void r.stream.cancel();
+ return { ok: true, jobId: r.jobId };
+ },
+ log: (line) => console.log(line),
+ });
+}
diff --git a/editor/app/api/ops/live-recording-verify/route.ts b/editor/app/api/ops/live-recording-verify/route.ts
@@ -0,0 +1,24 @@
+import { NextResponse } from "next/server";
+import { reverifyLiveRecordingAction } from "../../../channels/[slug]/liveMediaActions";
+import { forgetAttention } from "../_attention";
+import { ops, opsFail, reqSlug, reqString } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug, id, startedAt? } -> { ok: true, verified, why?, removed }
+//
+// THE LANDING'S CHECK, AGAIN (controller/recordLive.ts reverifyLiveLanding):
+// a recording whose landed file is `failed` or `pending` against the stream
+// files it was made from is checked once more. Verified, and the stream
+// confirmed done, those stream files, their state and fragments go; else the
+// row says why and nothing is removed. The row's Verify button.
+export async function POST(request: Request) {
+ return ops(request, ["slug", "id", "startedAt"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ const id = reqString(body, "id");
+ const r = await reverifyLiveRecordingAction({ slug, id, ...(typeof body.startedAt === "string" ? { startedAt: body.startedAt } : {}) });
+ if (!r.ok) return opsFail(r.error);
+ forgetAttention();
+ return NextResponse.json(r);
+ });
+}
diff --git a/editor/app/api/ops/record-live/route.ts b/editor/app/api/ops/record-live/route.ts
@@ -7,6 +7,7 @@ export const dynamic = "force-dynamic";
// POST { slug, url? | id?, fromStart? (true), maxHeight? (720; null = tallest),
// separate? (YouTube true, else false), transcribe?, doNotClean?, note?,
+// insurance? (true | "whole" | false; absent: on when marked keep),
// dryRun? } -> { ok: true, jobId, kind: "record-live", check }
//
// `check` is the command that answers for the recording afterwards (`pnpm ops
diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts
@@ -31,7 +31,7 @@ import { resolveCookiePolicy } from "yt-dlp-transcript-common/lib/cookiePolicy";
import { isValidChannelSlug, readChannelConfig } from "yt-dlp-transcript-common/controller/channels";
import { parseImportRequest } from "yt-dlp-transcript-common/lib/mediaImport";
import { isArchivePath, runImportMediaJob } from "yt-dlp-transcript-common/controller/importMedia";
-import { parseRecordLiveRequest, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive";
+import { parseRecordLiveRequest, reverifyLiveLanding, runRecordLiveJob } from "yt-dlp-transcript-common/controller/recordLive";
import { acknowledgeLiveRecording } from "yt-dlp-transcript-common/controller/liveRecordings";
import { loadLiveRecordingRows } from "yt-dlp-transcript-common/lib/liveRecordings-server";
import {
@@ -52,8 +52,8 @@ import { whisperVideoAction } from "./videos/[id]/videoActions";
const escapeRegex = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
-async function requestTranscription(slug: string, id: string): Promise<{ ok: boolean; jobId?: string; error?: string }> {
- const r = await whisperVideoAction(slug, id);
+async function requestTranscription(slug: string, id: string, o: { replace?: boolean } = {}): Promise<{ ok: boolean; jobId?: string; error?: string }> {
+ const r = await whisperVideoAction(slug, id, undefined, undefined, undefined, undefined, undefined, o.replace === true);
if (!r.ok) return { ok: false, error: r.error };
void r.stream.cancel();
return { ok: true, jobId: r.jobId };
@@ -99,9 +99,12 @@ export async function importMediaAction(body: Record<string, unknown>): Promise<
});
}
-export async function recordLiveAction(body: Record<string, unknown>): Promise<StreamActionResult> {
- const req = parseRecordLiveRequest(body, preclipDefaults());
- if ("error" in req) return { ok: false, error: req.error };
+// `internal.resumeOf`: the boot pass's restart of an interrupted run
+// (app/api/ops/_liveRecordingBoot.ts) — never read from a body.
+export async function recordLiveAction(body: Record<string, unknown>, internal: { resumeOf?: string } = {}): Promise<StreamActionResult> {
+ const parsed = parseRecordLiveRequest(body, preclipDefaults());
+ if ("error" in parsed) return { ok: false, error: parsed.error };
+ const req = internal.resumeOf ? { ...parsed, resumeOf: internal.resumeOf } : parsed;
if (!isValidChannelSlug(req.slug)) return { ok: false, error: `"${req.slug}" is not a channel slug` };
const paths = getPaths();
const config = await readChannelConfig(paths, req.slug);
@@ -129,6 +132,23 @@ export async function recordLiveAction(body: Record<string, unknown>): Promise<S
// needing anyone.
// recordLiveAgainAction the Record again button: record-live with
// the run's own url and recording keys.
+// REVIEW-7 4: a landing whose check failed or never ran, checked again —
+// verified (and the stream confirmed done), its stream files go.
+// `pnpm ops live-recording-verify`, the row's Verify button.
+export async function reverifyLiveRecordingAction(body: {
+ slug: string;
+ id: string;
+ startedAt?: string;
+}): Promise<{ ok: true; verified: boolean; why?: string; removed: string[] } | { ok: false; error: string }> {
+ if (!isValidChannelSlug(body.slug)) return { ok: false, error: `"${body.slug}" is not a channel slug` };
+ const paths = getPaths();
+ const config = await readChannelConfig(paths, body.slug);
+ if (!config) return { ok: false, error: `Channel "${body.slug}" not found` };
+ const r = await reverifyLiveLanding({ paths, slug: body.slug, id: body.id, ...(body.startedAt ? { startedAt: body.startedAt } : {}), channelConfig: config });
+ if (r.ok) safeRevalidate(["/review", `/channels/${body.slug}`]);
+ return r;
+}
+
export async function acknowledgeLiveRecordingAction(body: {
slug: string;
id?: string;
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -313,6 +313,7 @@ async function queueTranscribeOne(o: {
salvage?: boolean;
whilePaused?: boolean;
prelude?: string[];
+ replace?: boolean;
}): Promise<StreamActionResult> {
const { slug, videoId, salvage, whilePaused } = o;
const paths = getPaths();
@@ -338,6 +339,7 @@ async function queueTranscribeOne(o: {
signal,
...(salvage !== undefined ? { salvage } : {}),
...(whilePaused ? { whilePaused: true } : {}),
+ ...(o.replace ? { replace: true } : {}),
});
safeRevalidate([`/channels/${slug}/videos/${videoId}`, `/channels/${slug}`]);
},
@@ -737,6 +739,9 @@ export async function whisperVideoAction(
// true: speech recognition even for a youtube-handling video that lists
// English captions (the page's "Audio + Whisper" is that ask).
asr?: boolean,
+ // True transcribes again over an existing transcript.json (record-live's
+ // landing replaced the shorter file it was made from).
+ replace?: boolean,
): Promise<WhisperVideoResult> {
const r = await loadConfigOrError(slug);
if (!r.ok) return r;
@@ -750,6 +755,7 @@ export async function whisperVideoAction(
const opts = {
...(salvage !== undefined ? { salvage } : {}),
...(whilePaused ? { whilePaused: true } : {}),
+ ...(replace ? { replace: true } : {}),
};
const firstEntries = await readdir(videoDir).catch(() => [] as string[]);
const audioOnDisk = firstEntries.some(isRealAudioFile);
diff --git a/editor/app/components/LiveRecordingActions.tsx b/editor/app/components/LiveRecordingActions.tsx
@@ -9,6 +9,7 @@ import { useState, useTransition } from "react";
import {
acknowledgeLiveRecordingAction,
recordLiveAgainAction,
+ reverifyLiveRecordingAction,
} from "../channels/[slug]/liveMediaActions";
export function LiveRecordingActions({
@@ -17,6 +18,7 @@ export function LiveRecordingActions({
startedAt,
file,
canRecordAgain,
+ canVerify = false,
}: {
slug: string;
// A recording's run (id + startedAt), or a set-aside live-recordings.json.
@@ -24,6 +26,8 @@ export function LiveRecordingActions({
startedAt?: string;
file?: string;
canRecordAgain: boolean;
+ // Its landed file's check failed or never ran (REVIEW-7 4): Verify again.
+ canVerify?: boolean;
}): React.ReactNode {
const what = file ?? `${slug}/${id ?? ""}`;
const [pending, startTransition] = useTransition();
@@ -51,6 +55,22 @@ export function LiveRecordingActions({
Record again
</button>
)}
+ {canVerify && id && (
+ <button
+ type="button"
+ aria-label={`verify ${what} again`}
+ disabled={pending}
+ className={btn}
+ onClick={() =>
+ press(
+ () => reverifyLiveRecordingAction({ slug, id, ...(startedAt ? { startedAt } : {}) }),
+ (r) => (r.verified ? `Verified${Array.isArray(r.removed) && r.removed.length ? `; ${r.removed.length} file(s) removed` : ""}` : `Not verified: ${String(r.why ?? "")}`),
+ )
+ }
+ >
+ Verify again
+ </button>
+ )}
<button
type="button"
aria-label={`acknowledge ${what}`}
diff --git a/editor/app/components/LiveRecordingsAttention.tsx b/editor/app/components/LiveRecordingsAttention.tsx
@@ -58,7 +58,13 @@ function Row({ r }: { r: LiveRecordingView }) {
</ul>
) : null}
{r.needsAttention ? (
- <LiveRecordingActions slug={r.slug} id={r.id} startedAt={r.startedAt} canRecordAgain={r.status !== "recording" && Boolean(r.url)} />
+ <LiveRecordingActions
+ slug={r.slug}
+ id={r.id}
+ startedAt={r.startedAt}
+ canRecordAgain={r.status !== "recording" && Boolean(r.url)}
+ canVerify={Boolean(r.verification && r.verification.state !== "verified" && r.verification.against?.length)}
+ />
) : null}
</li>
);
diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -370,6 +370,23 @@ export async function register() {
/* a schedule that fails to arm must not block server readiness */
}
+ // A LIVE RECORDING AN EDITOR RESTART INTERRUPTED RESTARTS BY ITSELF
+ // (operator ruling, 21 Nov 2026): one pass, 30 s after boot — each run the
+ // shutdown (or a crash) interrupted asks for a record-live job that reads
+ // the stream's state first and records only if it is still live; a
+ // person's Cancel never restarts. At most once per run and 3 an hour per
+ // stream (settings.liveRecording.autoRestartOnBoot). Below the idle gate —
+ // the job makes a request to the platform — and not on the e2e test
+ // server. See common/controller/liveRecordingBoot.ts.
+ if (process.env.E2E_TEST_ROUTES !== "1") {
+ try {
+ const { armLiveRecordingBootPass } = await import("./app/api/ops/_liveRecordingBoot");
+ armLiveRecordingBootPass(bootedAt);
+ } catch {
+ /* a pass that fails to arm must not block server readiness */
+ }
+ }
+
// AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1): the job-end
// listener and one scan of the research runs now; the heartbeat scans again
// on each beat. Below the idle gate: a continuation is a generation job.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -566,7 +566,7 @@ const ACTIONS = [
// LIVE STREAM RECORDED from its start (plans/live-capture.md): import-media
// ({slug, path, url? | id? | meta?, move?, replace?, audio?, transcribe?,
// doNotClean?, note?, dryRun?}) and record-live ({slug, url? | id?,
- // fromStart?, maxHeight?, separate?, transcribe?, doNotClean?, note?, dryRun?}), each a
+ // fromStart?, maxHeight?, separate?, transcribe?, doNotClean?, note?, insurance?, dryRun?}), each a
// job; both land through the same code.
"import-media",
"record-live",
@@ -592,6 +592,9 @@ const ACTIONS = [
// a person ({slug, id, startedAt?, by?}): it stays in `get live-recordings`
// and no longer counts as needing anyone. /review's Acknowledge.
"live-recording-ack",
+ // A landing whose check failed or never ran, checked again against its
+ // stream files ({slug, id, startedAt?}); verified and the stream done, they go.
+ "live-recording-verify",
// A channel's saved containers remuxed losslessly into browser-playable
// copies, one torrent each ({slug, ids?, trackers?, root?, dryRun?}).
"prepare-playable",
@@ -2818,6 +2821,38 @@ export function usage() {
" 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 from-start recorder (dead, stalled,",
+ " stopped by a shutdown, or ended by itself) is RESUMED in place — the same",
+ " files, every kept fragment reused — and only when that cannot be proven",
+ " does a FRESH part record from the stream's start, then the live edge",
+ " (6 restarts an hour, waited out, never an end); while the state cannot",
+ " be read for the network nothing is started and no restart spent.",
+ " \"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 when the stream",
+ " is marked keep (\"doNotClean\", the record's Do-not-clean marker, a",
+ " pending keep), and also when a from-start part shows itself more than",
+ " 10 min behind the live edge (liveRecording.insuranceWhenBehind).",
+ " 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.",
"",
"get live-recordings [<slug>[/<id>]] [--all] is THE answer to \"is this",
" stream being recorded, and is it growing\" — never a job for the video",
@@ -2827,7 +2862,8 @@ export function usage() {
" bytes and lastGrowthAt while recording), stalled (not grown for",
" settings.liveRecording.stallMinutes, 10), streamElapsedSeconds,",
" capturedSeconds (once landed), coverage, attempts, failureClass,",
- " fallback, lost, missingStream, keptParts, error, mustKeep,",
+ " fallback, lost, startRecovery, restarts, insurance, restart (what the",
+ " boot pass did), joins, missingStream, keptParts, error, mustKeep,",
" needsAttention, reason, check; `files` names a live-recordings.json that",
" did not read (set aside, never overwritten). Default: what is recording,",
" what needs a person, the last 7 days; --all every run kept",
@@ -2839,6 +2875,13 @@ export function usage() {
" pages show the same rows and the stalled ones, and every ops reply then",
" prints \"! N live recordings need you; M ... NOT growing\" on stderr.",
"",
+ 'live-recording-verify {"slug", "id", "startedAt"?} checks a landed file whose',
+ " verification failed or never ran against the stream files it was made",
+ " from (packets per track, the tracks' spans, a hole scan, each stream file",
+ " byte for byte its kept fragments); verified and the stream confirmed",
+ " done, those stream files, their state and fragments are removed; else",
+ " the row says why and nothing is. The row's Verify button.",
+ "",
'live-recording-ack {"slug", "id", "startedAt"?, "by"?} acknowledges every',
" run of the record that needs a person (or the one run startedAt names):",
' listed still, counted no more. {"slug", "file"} acknowledges a set-aside',
diff --git a/settings.json.example b/settings.json.example
@@ -17,7 +17,9 @@
"mine": true
},
"liveRecording": {
- "stallMinutes": 10
+ "stallMinutes": 10,
+ "autoRestartOnBoot": true,
+ "insuranceWhenBehind": true
},
"pacing": {
"sleepRequestsCapSeconds": 16,