Archilyzer · Source

archilyzer

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

commit 168a4c8f88bb41693ddd577d400d883d23bc76af
parent 14b7b84f0b0d6443ec027e05d34250c86aaef2e8
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 03:10:10 -0500

record-live: keep what the landing cannot prove it holds, interrupted is not cancelled, classify failures

The review of the first slice found two ways to lose or hide a recording,
and these are fixed here with a test each that failed before:

- The landing kept the longest part and deleted the rest. With the live-edge
  fallback (and on main already, with an earlier run's leftover) the rest can
  hold the only copy of the stream's end. Now only a shorter part of the same
  run, both from the start, is removed; every other part that holds bytes
  stays in staging, listed as keptParts (files, sizes, why) on the record and
  the channel's row, needing a person until acknowledged.
- An editor shutdown wrote `cancelled`, which needed nobody. It is now
  `interrupted` (stoppedBy shutdown) and needs a person; a person's Cancel of
  a must-keep stream needs one too.

Also: an attempt where one of the two streams recorded nothing is retried
and named (missingStream); a live-recordings.json that does not read is set
aside under a timestamped name, never overwritten; stalled recordings are
counted in the attention header and shown on the banners; only a landed
from-start run that covers the stream (duration, else the clock, within
max(60 s, 1 %)) supersedes earlier failures; --wait-started exits 3 when only
the live edge records; yt-dlp's failure is classified (ended, private,
members, disk: not retried; 429 or the bot check: one retry after 15 min;
empty, network, unknown: the schedule) and recorded; every ops GET route
carries the attention header; Record again carries the pre-clip too.

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

Diffstat:
MCOMMANDS.md | 27++++++++++++++++-----------
MOPERATING.md | 62+++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mcommon/controller/livePreclip.ts | 2+-
Mcommon/controller/liveRecordings.test.ts | 81++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
Mcommon/controller/liveRecordings.ts | 182++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------------
Mcommon/controller/recordLive.test.ts | 260++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/controller/recordLive.ts | 310+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/jobs/registry.ts | 6++++++
Mcommon/lib/liveCapture.ts | 148++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------
Mcommon/lib/liveRecordings-server.ts | 157+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Meditor/CHANGELOG.md | 9+++++++++
Meditor/app/api/ops/_attention.ts | 45+++++++++++++++++++++++++++++----------------
Meditor/app/api/ops/_liveRecordings.test.ts | 31+++++++++++++++++++++++++++++++
Meditor/app/api/ops/channel/[slug]/route.ts | 9++++++++-
Meditor/app/api/ops/channels/route.ts | 9++++++++-
Meditor/app/api/ops/job/[id]/route.ts | 9++++++++-
Meditor/app/api/ops/jobs/route.ts | 9++++++++-
Meditor/app/api/ops/live-recording-ack/route.ts | 12++++++++----
Meditor/app/api/ops/live-recordings/route.ts | 13++++++++-----
Meditor/app/api/ops/publish/route.ts | 9++++++++-
Meditor/app/api/ops/tags/route.ts | 9++++++++-
Meditor/app/api/ops/trending/route.ts | 9++++++++-
Meditor/app/channels/[slug]/liveMediaActions.ts | 12++++++++----
Meditor/app/components/LiveRecordingActions.tsx | 24+++++++++++++++++-------
Meditor/app/components/LiveRecordingsAttention.tsx | 50++++++++++++++++++++++++++++++++++++++++++++------
Mscripts/archilyzer-ops.mjs | 115+++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------------------
Mscripts/archilyzer-ops.test.mjs | 41+++++++++++++++++++++++++++++++++++++++++
27 files changed, 1431 insertions(+), 219 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 "(&lt;id&gt;)", 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.&lt;fmt&gt;, 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/&lt;channel&gt;" 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") is tried again at +60 and +180 s, then from the live edge at 0, +60 and +180 s (each wait jittered); a stream that has ended, an argv no try can fix and a Cancel are not retried. A live-edge fallback says what it lost (the first N min of the stream) and needs a person. The reply is {jobId, kind, "check"}: the `get live-recordings` command that answers for it. --wait-started returns once media bytes are being written (the recording's row on stdout, exit 0) or with the reason it failed (exit 1); 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/&lt;channel&gt;" 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` | | `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"} -&gt; {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)}} -&gt; {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"}}'` | @@ -155,7 +155,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `local-media-link` | local-media-link links a record the channel already holds to its library original: {"slug", "sourceToken", "media", "fingerprint", "dryRun"?} for an "existing" candidate. Only when the library's .info.json and transcript match the record's byte for byte is external-media.json written ("attached"; "already-linked"; "conflict" keeps a different one). Nothing else changes, and no playback is granted. "dryRun" answers "ready" without writing. | `pnpm ops local-media-link --json '{"slug":"demo-local","sourceToken":"<token>","media":"talk.mp4","fingerprint":"<fp>","dryRun":true}'` | | `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, &lt;id&gt;-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/&lt;id&gt;/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"? (&lt;id&gt;-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. /review's Acknowledge. | `pnpm ops live-recording-ack --json '{"slug":"demo-yt","id":"<videoId>"}'` | +| `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>"}'` | | `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": "&lt;file&gt;" reviews the active copy that replaced a former original instead. | | @@ -469,17 +469,22 @@ get transcript <videoId> [--slug <slug>] reads one video's cues off disk 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 id (a live-chat job is one too). Per run, from its own record: status - (recording | interrupted: no job runs it | landed | failed | cancelled), - job, bytes, lastGrowthAt, stalled (not grown for + (recording | interrupted: no job runs it, or the editor shut down | + landed | failed | cancelled), job, bytes, lastGrowthAt, parts (each its + bytes and lastGrowthAt while recording), stalled (not grown for settings.liveRecording.stallMinutes, 10), streamElapsedSeconds, - capturedSeconds (once landed), attempts, fallback, lost, error, mustKeep, - needsAttention, reason, check. Default: what is recording, what needs a - person, the last 7 days; --all every run kept + capturedSeconds (once landed), coverage, attempts, failureClass, + fallback, lost, 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 (channels/<slug>/live-recordings.json, never pruned of a failure). - needsAttention (failed, interrupted, or the stream's start lost) stays - until live-recording-ack or a later recording that lands from the start; - /review, /jobs, the channel and video pages show the same rows, and - every ops reply then prints "! N live recordings need you" on stderr. + needsAttention — failed, interrupted, cancelled when must-keep, the + stream's start lost, a stream missing, parts kept — stays until + live-recording-ack, or (all but kept parts) a later recording that lands + the WHOLE stream from its start; /review, /jobs, the channel and video + 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. "preview": "<branch>" on deploy-site or build-deploy makes it a Cloudflare Pages PREVIEW instead of production: the same bundle goes to a branch diff --git a/OPERATING.md b/OPERATING.md @@ -1127,26 +1127,62 @@ pnpm ops keep-videos --json '{"slug":"example-rumble","ids":["v1abcde"],"note": `--live-from-start` said "The downloaded file is empty" after 55 s, and nothing retried). The schedule: from its start at 0, +60 and +180 s, then from the live edge (`--no-live-from-start`, the request Kick's channel recorder already makes) at 0, +60 and +180 s — at most six recorder spawns in about eight minutes, each wait stretched by - `pacing.jitter`, a Cancel ending any wait. Not retried: a stream that has ended or gone private, an argv no try - can fix ("Requested format is not available"), a Cancel, a part that recorded bytes. A recording that falls back - to the live edge says in the log and the record what it lost ("the first 2 h 14 min are NOT recorded"); that is a - failure needing a person even while the live edge records. + `pacing.jitter`, a Cancel ending any wait. A separate-streams attempt where one stream wrote bytes and the other + nothing is a failed attempt too, on the same schedule. The failure's class (`failureClass` on the part and the + row) decides what follows: **not retried** — the stream has ended or is not live (`ended`), private or removed + (`private`), members-only or needs a login (`members`), the disk is full or the store unwritable (`disk`), an argv + no try can fix ("Requested format is not available", `argv`), a Cancel; **one more try after 15 min, then stop** + — HTTP 429 or "Sign in to confirm you're not a bot" (`rate-limited`), said in the log; **the schedule** — "The + downloaded file is empty" (`empty`), network errors (`network`), anything else (`unknown`). A part with bytes in + both streams ends the attempts whatever yt-dlp's exit (a normal stream end often exits 1): it lands, unretried. + A recording that falls back to the live edge says in the log and the record what it lost ("the first 2 h 14 min + are NOT recorded"); that is a failure needing a person even while the live edge records. When the attempts end + with one stream missing, the row says which (`missingStream`) and the parts that hold bytes are kept. +- **The landing never removes media it is not known to hold.** The longest part lands. A shorter part of the same + run, both from the start, is inside it and goes. Every other part that holds bytes — an earlier run's, one + recorded from the live edge while the landed one is from the start (or the other way round), one that cannot be + landed as it is (video with no audio), fragments a recorder left — stays in the store's staging dir, listed on the + record and the row as `keptParts` (each with its files and sizes, and why), and the row needs a person until it is + acknowledged. A later recording does not clear that; nothing removes those files automatically. On Kick, where + the VOD from its start and the channel's live edge are recorded side by side, the shorter one is kept the same way. +- **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. - **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 - `lastGrowthAt` of its staging files, `stalled` (not grown for `settings.liveRecording.stallMinutes`, 10), - `streamElapsedSeconds`, `capturedSeconds` once landed, `attempts`, `fallback`/`lost`, `error` (yt-dlp's own - `ERROR:` line, and the attempts), `needsAttention`, `reason`, `check`. record-live's reply carries that `check` - command beside the job id; `--wait-started` returns only once media bytes are growing (the row on stdout, exit - 0) or with the reason it failed (exit 1), within 15 minutes unless `--wait-timeout` says otherwise. + `lastGrowthAt` of its staging files (and each part's own while it records), `stalled` (not grown for + `settings.liveRecording.stallMinutes`, 10), `streamElapsedSeconds`, `capturedSeconds` and `coverage` once landed, + `attempts`, `failureClass`, `fallback`/`lost`, `missingStream`, `keptParts`, `error` (yt-dlp's own `ERROR:` line, + and the attempts), `needsAttention`, `reason`, `check`; `files` names a `live-recordings.json` that did not read. + record-live's reply carries that `check` command beside the job id; `--wait-started` exits 0 only once a + FROM-START part's bytes grow (the row on stdout; a run asked `"fromStart": false`, any part's), **3** when it records + only from the live edge (the start is lost), 1 with the reason it failed, within 15 minutes unless + `--wait-timeout` says otherwise. A stalled recording (its job runs, its files do not grow) is said wherever a + failure is — the banners, /review, and `stalled=M` in the attention header — but is not acknowledged: it clears + when the files grow or the run ends. +- **`landed` is not "the whole stream".** A recorder that dies mid-stream with bytes (network, a full disk, a 429 on + fragments) lands what it has and reads `landed`. `coverage` says whether the landed part holds the stream: its + captured seconds against the ended stream's `duration` (else the clock: the last part's end minus the stream's + start, which can only overstate it), within max(60 s, 1 %). Only a landed run from its start, with both streams, + that covers the stream supersedes an earlier failure of the same id; a live-edge landing, a run asked not from + its start and a short partial never do (the earlier failure stays until acknowledged). A short landing's `reason` + says how much it holds. - **A failure is loud until a person says otherwise.** Every run has a row in `channels/<slug>/live-recordings.json`, written on every save of its record and never removed for failing — also when the run removes the empty - `data/<id>/` it made, and also for a refusal before any recorder started. A row needs a person when it failed, - was interrupted, or lost the stream's start; it is shown on /review ("Live recordings that need you", with + `data/<id>/` it made, and also for a refusal before any recorder started. A `live-recordings.json` that does not + read is never overwritten: the next write renames it aside (`live-recordings.json.corrupt-<time>`, beside it), + starts a new file, and the kept file needs a person (`live-recording-ack {"slug","file"}`). A row needs a person + when it failed, was interrupted, was cancelled while must-keep, lost the stream's start, is missing a stream, or + kept parts; it is shown on /review ("Live recordings that need you", with **Record again** and **Acknowledge**), as a banner on /jobs and the channel and video pages, and as `! N live recordings need you` on stderr after every `pnpm ops` reply (the `x-archilyzer-attention` header). It - stops counting at `live-recording-ack` (or Acknowledge), or when a later recording of the same id lands from its - start. No desktop notification: the editor has no such path. + stops counting at `live-recording-ack` (or Acknowledge), or (all but kept parts) when a later recording of the same + id lands the whole stream from its start. The header rides on every ops GET route as well as every action, `get + job` and `get jobs` included. **Record again** asks record-live with the run's own options: from the start or not, + quality (`maxHeight`), separate streams, transcribe, keep (`doNotClean`) and its note, and the live pre-clip. No + desktop notification: the editor has no such path. - `import-media` (Media → **Import a file**) makes one file from outside the archive a normal transcribed item: `"url"` makes or refreshes the record from its page (metadata only, under the id the archive keys it by — a Rumble URL's id, not the embed id in the file name), `"id"` names a record already here, `"meta"` describes one diff --git a/common/controller/livePreclip.ts b/common/controller/livePreclip.ts @@ -670,7 +670,7 @@ export async function startLivePreclipJob(o: { const rec = await liveRecordingSidecar.load(videoDir); if (!rec) return { ok: false, error: `${o.slug}/${o.id} is not being recorded (no live-recording.json): start it with record-live {"preclip": true}` }; if (rec.status !== "recording") { - return { ok: false, error: `${o.slug}/${o.id}'s recording is ${rec.status}, not in progress${rec.status === "landed" || rec.status === "cancelled" ? ' — "finalize" supersedes a live transcript once the final one is here' : ""}` }; + return { ok: false, error: `${o.slug}/${o.id}'s recording is ${rec.status}, not in progress${rec.status === "landed" || rec.status === "cancelled" || rec.status === "interrupted" ? ' — "finalize" supersedes a live transcript once the final one is here' : ""}` }; } } const busy = runningJobOf(o.slug, o.id); diff --git a/common/controller/liveRecordings.test.ts b/common/controller/liveRecordings.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { mkdir, mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -124,3 +124,82 @@ test("record-live's reply names the command that answers for the recording", asy assert.equal(recordLiveCheckCommand("demo-yt", { id: "exampleid02" }), "pnpm ops get live-recordings demo-yt/exampleid02"); assert.equal(recordLiveCheckCommand("demo-kick", { url: "https://kick.com/somechannel" }), "pnpm ops get live-recordings demo-kick", "a Kick channel's VOD is found in the job"); }); + +test("1.8: an unparseable live-recordings.json is never overwritten — set aside under a timestamped name, a new file started, and the kept file needs a person", async () => { + const slug = "synth-corrupt"; + const dir = path.join(CORPUS, "channels", slug); + await mkdir(path.join(dir, "data"), { recursive: true }); + await writeFile(path.join(dir, "config.json"), JSON.stringify({ handling: "transcribe", platform: "youtube", name: "Corrupt" })); + const garbage = '{"rows": [{"id": "exmplcorr01", "status": "failed", "startedAt": "2026-11-19T00:00:00.000Z"'; // truncated + await writeFile(path.join(dir, "live-recordings.json"), garbage); + // Read side: said, not moved. + const before = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] }); + assert.equal(before.files.length, 1); + assert.equal(before.files[0]!.state, "unreadable"); + assert.equal(before.files[0]!.reason, "unparseable"); + assert.ok(before.needsAttention >= 1); + // A write: the file is renamed aside, byte for byte, and a new one begins. + await upsertLiveRecordingRow(paths, slug, { + id: "exmplcorr02", + url: "u", + platform: "youtube", + startedAt: NOW.toISOString(), + status: "failed", + fromStart: true, + attempts: 1, + mustKeep: true, + parts: [], + }); + const names = (await readdir(dir)).filter((n) => n.startsWith("live-recordings.json")); + const aside = names.find((n) => /^live-recordings\.json\.corrupt-\d{4}-\d\d-\d\dT[\d-]+Z$/.test(n)); + assert.ok(aside, names.join(", ")); + assert.equal(await readFile(path.join(dir, aside!), "utf8"), garbage, "kept as it was"); + const after = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] }); + assert.deepEqual(after.rows.map((r) => r.id), ["exmplcorr02"]); + assert.equal(after.files.length, 1); + assert.equal(after.files[0]!.state, "set-aside"); + assert.equal(after.files[0]!.file, aside); + assert.match(after.files[0]!.message, new RegExp(aside!.replace(/[.]/g, "\\."))); + assert.equal(after.needsAttention, 2, "the new failure and the kept file"); + // A second write does not set the new (good) file aside. + await upsertLiveRecordingRow(paths, slug, { id: "exmplcorr03", url: "u", platform: "youtube", startedAt: NOW.toISOString(), status: "landed", fromStart: true, attempts: 1, mustKeep: false, parts: [] }); + assert.equal((await readdir(dir)).filter((n) => n.includes(".corrupt-")).length, 1); + // Acknowledged: no longer counted; the file stays. + assert.deepEqual(await acknowledgeLiveRecording(paths, { slug, file: aside!, by: "test" }), { ok: true, acknowledged: 1 }); + const acked = await listLiveRecordings(paths, { slug, now: NOW, jobs: () => [] }); + assert.equal(acked.files.length, 0); + assert.equal(acked.needsAttention, 1); + assert.ok((await readdir(dir)).includes(aside!)); +}); + +test("2.2: a stalled recording is counted beside needsAttention, and each part says its own bytes while it records", async () => { + const stem = ".exmplstal02.live-2026-11-20T11-00-00-000Z.ytdlp"; + await recording("exmplstal02", stem, { jobId: "job-stall2" }); + await writeFile(path.join(store, `${stem}.f247.webm`), Buffer.alloc(700)); + await utimes(path.join(store, `${stem}.f247.webm`), minutesAgo(40), minutesAgo(40)); + const jobs = () => [{ id: "job-stall2", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstal02" }]; + const l = await listLiveRecordings(paths, { slug: SLUG, id: "exmplstal02", now: NOW, stallMinutes: 10, jobs }); + assert.equal(l.stalled, 1); + assert.equal(l.rows[0]!.needsAttention, false, "stalled is said on its own, not acknowledged"); + assert.equal(l.rows[0]!.parts[0]!.bytes, 700); + assert.equal(l.rows[0]!.parts[0]!.lastGrowthAt, minutesAgo(40).toISOString()); +}); + +test("2.5: a row that names its job is recording only while THAT job runs (a newer run of the id is another row)", async () => { + await recording("exmplstale1", ".exmplstale1.live-2026-11-20T10-00-00-000Z.ytdlp", { jobId: "job-old" }); + const jobs = () => [{ id: "job-new", kind: "record-live", status: "running" as const, channelSlug: SLUG, videoId: "exmplstale1" }]; + const r = (await listLiveRecordings(paths, { slug: SLUG, id: "exmplstale1", now: NOW, jobs })).rows[0]!; + assert.equal(r.status, "interrupted"); +}); + +test("needsAttention: interrupted always, a cancel only when must-keep, kept parts even when superseded", async () => { + const { rowNeedsAttention } = await import("../lib/liveRecordings-server"); + const base = { fallback: undefined, acknowledgedAt: undefined, supersededBy: undefined } as const; + assert.equal(rowNeedsAttention({ ...base, status: "interrupted", mustKeep: false }), true); + assert.equal(rowNeedsAttention({ ...base, status: "cancelled", mustKeep: true }), true); + assert.equal(rowNeedsAttention({ ...base, status: "cancelled", mustKeep: false }), false); + const kept = [{ stem: "s", files: [{ name: "s.mp4", bytes: 9 }], bytes: 9, seconds: 1, fromStart: false, run: "this" as const, why: "w" }]; + assert.equal(rowNeedsAttention({ ...base, status: "landed", supersededBy: "job-x", keptParts: kept }), true); + assert.equal(rowNeedsAttention({ ...base, status: "landed", acknowledgedAt: "t", keptParts: kept }), false); + assert.equal(rowNeedsAttention({ ...base, status: "landed", missingStream: "video" }), true); +}); diff --git a/common/controller/liveRecordings.ts b/common/controller/liveRecordings.ts @@ -14,11 +14,22 @@ // bytes while recording: the staging files of its parts, summed // (stat only); after: what each part held at its end // lastGrowthAt the newest of those files' mtimes +// parts[].bytes while recording: each part's own bytes and lastGrowthAt +// (what --wait-started reads: a FROM-START part growing) // stalled recording, and nothing has grown for stallMinutes -// (settings.liveRecording.stallMinutes, default 10) -// needsAttention failed, interrupted, or recorded from the live edge (the -// stream's start lost) — until a person acknowledges it or -// a later recording of the id lands from its start +// (settings.liveRecording.stallMinutes, default 10) — +// counted beside needsAttention (`stalled`), said wherever a +// failure is, never acknowledged (it clears when the files +// grow again or the run ends) +// needsAttention failed; interrupted (no job runs it, or the editor's +// shutdown stopped it); cancelled when must-keep; recorded +// from the live edge (the stream's start lost); one stream +// missing; parts kept on disk — until a person acknowledges +// it, or (all but kept parts) a later recording of the id +// lands the whole stream (rowCoversStream) +// files a live-recordings.json that did not read: set aside by a +// write (its kept name) or, until then, unreadable — needs a +// person, counted in needsAttention // // Reads only: no request leaves the machine, nothing is written. @@ -29,8 +40,10 @@ import { getSettings } from "../lib/settings"; import { livePartFiles, spanWords, type LiveRecordingStatus } from "../lib/liveCapture"; import { liveRecordingSidecar } from "../lib/mediaImport-server"; import { + LIVE_RECORDINGS_FILENAME, acknowledgeLiveRecordingRows, - loadLiveRecordingRows, + acknowledgeSetAsideFiles, + loadLiveRecordingsFile, rowNeedsAttention, type LiveRecordingRow, } from "../lib/liveRecordings-server"; @@ -61,10 +74,29 @@ export type LiveRecordingView = Omit<LiveRecordingRow, "status"> & { check: string; }; +// A channel's live-recordings.json that did not read. +export type LiveRecordingsFileProblem = { + slug: string; + // The kept (set-aside) file's name beside live-recordings.json, or + // live-recordings.json itself while it does not read and no write has set + // it aside yet. + file: string; + state: "set-aside" | "unreadable"; + reason: "unreadable" | "unparseable"; + at: string | null; + needsAttention: boolean; + acknowledgedAt?: string; + message: string; +}; + export type LiveRecordingsListing = { rows: LiveRecordingView[]; + // Rows that need a person, plus files that need one. needsAttention: number; + // Recordings that run and have not grown for stallMinutes. + stalled: number; stallMinutes: number; + files: LiveRecordingsFileProblem[]; }; export type ListLiveRecordingsOpts = { @@ -100,24 +132,46 @@ const ACTIVE = new Set(["running", "queued"]); 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"; + const extra: string[] = []; + if (v.missingStream) extra.push(`its ${v.missingStream === "unknown" ? "video or audio" : v.missingStream} stream recorded nothing`); + if (v.keptParts && v.keptParts.length) { + const b = v.keptParts.reduce((n, k) => n + k.bytes, 0); + extra.push(`${v.keptParts.length} part${v.keptParts.length === 1 ? "" : "s"} not landed kept in staging (${Math.round(b / 1024 / 1024)} MB): decide what to do with them`); + } + 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 tail = extra.length ? `; ${extra.join("; ")}` : ""; + const cls = v.failureClass && v.failureClass !== "unknown" ? ` [${v.failureClass}]` : ""; switch (v.status) { case "failed": - return `failed: ${v.error ?? "no reason recorded"}`; + return `failed${cls}: ${v.error ?? "no reason recorded"}${tail}`; case "interrupted": - return "interrupted: its record says recording, and no record-live job runs it (an editor restart?) — Record again"; + 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 "cancelled": - return "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"; + return (v.fallback === "live-edge" ? `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`); if (v.stalled) parts.push(`NOT growing for ${stallMinutes}+ min`); - return parts.join("; "); + return parts.join("; ") + tail; } } } +function fileProblemMessage(slug: string, p: Pick<LiveRecordingsFileProblem, "file" | "state" | "reason">): string { + const where = `channels/${slug}/${LIVE_RECORDINGS_FILENAME}`; + return p.state === "set-aside" + ? `${where} did not read (${p.reason}) and was set aside, kept as channels/${slug}/${p.file}: the runs it listed are not in this listing — read it by hand` + : `${where} does not read (${p.reason}): the runs it lists are not in this listing; the next write sets it aside (never overwrites it)`; +} + // 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(); @@ -126,8 +180,29 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO const byId = new Map(jobs.map((j) => [j.id, j])); const slugs = opts.slug ? [opts.slug] : await channelSlugs(paths); const out: LiveRecordingView[] = []; + const files: LiveRecordingsFileProblem[] = []; for (const slug of slugs) { - const rows = (await loadLiveRecordingRows(paths, slug)).filter((r) => !opts.id || r.id === opts.id); + const file = await loadLiveRecordingsFile(paths, slug); + if (!opts.id) { + if (file.problem) { + const p = { file: LIVE_RECORDINGS_FILENAME, state: "unreadable" as const, reason: file.problem }; + files.push({ slug, ...p, at: null, needsAttention: true, message: fileProblemMessage(slug, p) }); + } + for (const f of file.setAside) { + const p = { file: f.file, state: "set-aside" as const, reason: f.reason }; + if (!f.acknowledgedAt || opts.all) { + files.push({ + slug, + ...p, + at: f.at, + needsAttention: !f.acknowledgedAt, + ...(f.acknowledgedAt ? { acknowledgedAt: f.acknowledgedAt } : {}), + message: fileProblemMessage(slug, p), + }); + } + } + } + const rows = file.rows.filter((r) => !opts.id || r.id === opts.id); if (!rows.length) continue; const config = await readChannelConfig(paths, slug).catch(() => null); const slugStore = path.join(savedVideoRoot(paths, config), slug); @@ -136,28 +211,42 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO for (const row of rows) { const rec = await liveRecordingSidecar.load(path.join(paths.channelsDir, slug, "data", row.id)).catch(() => null); const own = rec && rec.startedAt === row.startedAt ? rec : null; - const parts = own?.parts ?? row.parts; + let parts = own?.parts ?? row.parts; let status: LiveRecordingViewStatus = own?.status ?? row.status; const named = row.jobId ? byId.get(row.jobId) : undefined; - const running = - (named && ACTIVE.has(named.status)) || - jobs.some((j) => j.kind === "record-live" && j.channelSlug === slug && j.videoId === row.id && ACTIVE.has(j.status)); + // A row that names its job is running only if THAT job runs (a newer + // run of the same id is another row); one that names none, by any + // record-live job of the id. + const running = row.jobId + ? Boolean(named && ACTIVE.has(named.status)) + : jobs.some((j) => j.kind === "record-live" && j.channelSlug === slug && j.videoId === row.id && ACTIVE.has(j.status)); if (status === "recording" && !running) status = "interrupted"; let bytes: number | null = null; let lastGrowthMs: number | null = null; if (status === "recording" || status === "interrupted") { names ??= await readdir(slugStore).catch(() => [] as string[]); - const stems = new Set(parts.map((p) => p.stem).filter(Boolean)); - bytes = 0; - for (const g of livePartFiles(row.id, names)) { - if (!stems.has(g.stem)) continue; - for (const f of [...g.finished, ...g.streams]) { - const st = await stat(path.join(slugStore, f)).catch(() => null); - if (!st) continue; - bytes += st.size; - lastGrowthMs = Math.max(lastGrowthMs ?? 0, st.mtimeMs); - } - } + const byStem = new Map(livePartFiles(row.id, names).map((g) => [g.stem, g])); + let sum = 0; + // Each part's own bytes and growth, now (a copy: the record is not + // changed by reading it). + parts = await Promise.all( + parts.map(async (p) => { + const g = p.stem ? byStem.get(p.stem) : undefined; + if (!g) return p; + let pb = 0; + let pg: number | null = null; + for (const f of [...g.finished, ...g.streams]) { + const st = await stat(path.join(slugStore, f)).catch(() => null); + if (!st) continue; + pb += st.size; + pg = Math.max(pg ?? 0, st.mtimeMs); + } + sum += pb; + if (pg !== null) lastGrowthMs = Math.max(lastGrowthMs ?? 0, pg); + return { ...p, bytes: pb, ...(pg !== null ? { lastGrowthAt: new Date(pg).toISOString() } : {}) }; + }), + ); + bytes = sum; } else if (parts.some((p) => typeof p.bytes === "number")) { bytes = parts.reduce((n, p) => n + (p.bytes ?? 0), 0); } @@ -174,6 +263,11 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO ...(own?.fallback ? { fallback: own.fallback } : {}), ...(own?.lost ? { lost: own.lost } : {}), ...(own?.endedAt ? { endedAt: own.endedAt } : {}), + ...(own?.failureClass ? { failureClass: own.failureClass } : {}), + ...(own?.missingStream ? { missingStream: own.missingStream } : {}), + ...(own?.stoppedBy ? { stoppedBy: own.stoppedBy } : {}), + ...(own?.keptParts ? { keptParts: own.keptParts } : {}), + ...(own?.coverage ? { coverage: own.coverage } : {}), attempts: own?.attempts ?? row.attempts, parts, slug, @@ -184,7 +278,13 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO stalled, streamElapsedSeconds, capturedSeconds, - needsAttention: rowNeedsAttention({ ...row, status: status === "interrupted" ? "failed" : status, fallback: own?.fallback ?? row.fallback }), + needsAttention: rowNeedsAttention({ + ...row, + status, + fallback: own?.fallback ?? row.fallback, + keptParts: own?.keptParts ?? row.keptParts, + missingStream: own?.missingStream ?? row.missingStream, + }), }; const shown = opts.all || @@ -197,10 +297,22 @@ export async function listLiveRecordings(paths: Paths, opts: ListLiveRecordingsO } } out.sort((a, b) => Date.parse(b.startedAt) - Date.parse(a.startedAt)); - return { rows: out, needsAttention: out.filter((r) => r.needsAttention).length, stallMinutes }; + return { + rows: out, + needsAttention: out.filter((r) => r.needsAttention).length + files.filter((f) => f.needsAttention).length, + stalled: out.filter((r) => r.stalled).length, + stallMinutes, + files, + }; +} + +// How many recordings (and files) need a person, and how many are stalled, +// across every channel. +export async function liveRecordingsAttentionCounts(paths: Paths): Promise<{ needsAttention: number; stalled: number }> { + const l = await listLiveRecordings(paths); + return { needsAttention: l.needsAttention, stalled: l.stalled }; } -// How many recordings need a person, across every channel. export async function countLiveRecordingsNeedingAttention(paths: Paths): Promise<number> { return (await listLiveRecordings(paths)).needsAttention; } @@ -210,8 +322,18 @@ export async function countLiveRecordingsNeedingAttention(paths: Paths): Promise // `startedAt` names. The rows stay listed. export async function acknowledgeLiveRecording( paths: Paths, - opts: { slug: string; id: string; startedAt?: string; by?: string; now?: Date }, + opts: { slug: string; id?: string; file?: string; startedAt?: string; by?: string; now?: Date }, ): Promise<{ ok: true; acknowledged: number } | { ok: false; error: string }> { + // A set-aside live-recordings.json: seen (it stays where it is). + if (opts.file !== undefined) { + const n = await acknowledgeSetAsideFiles(paths, opts.slug, { + file: opts.file, + ...(opts.by ? { by: opts.by } : {}), + ...(opts.now ? { now: opts.now } : {}), + }); + return n ? { ok: true, acknowledged: n } : { ok: false, error: `${opts.slug} has no set-aside file "${opts.file}" that needs acknowledging` }; + } + if (!opts.id) return { ok: false, error: 'send "id" (a recording) or "file" (a set-aside live-recordings.json)' }; const listing = await listLiveRecordings(paths, { slug: opts.slug, id: opts.id, all: true }); if (!listing.rows.length) return { ok: false, error: `${opts.slug}/${opts.id} has no live recording` }; const interrupted = new Set(listing.rows.filter((r) => r.status === "interrupted").map((r) => r.startedAt)); diff --git a/common/controller/recordLive.test.ts b/common/controller/recordLive.test.ts @@ -51,7 +51,13 @@ async function fakeProbe(file: string): Promise<MediaProbe | null> { const text = await readFile(file, "utf8").catch(() => ""); const all = [...text.matchAll(/seconds=([\d.]+)/g)].reduce((s, m) => s + Number(m[1]), 0); if (!/format=/.test(text)) return null; - return { formatName: /format=([^;]+)/.exec(text)![1]!, seconds: all, videoCodec: "h264", audioCodec: "aac" }; + // `v=none;` / `a=none;`: a stream with no video / no audio. + return { + formatName: /format=([^;]+)/.exec(text)![1]!, + seconds: all, + videoCodec: /v=none;/.test(text) ? null : "h264", + audioCodec: /a=none;/.test(text) ? null : "aac", + }; } const land = { probe: fakeProbe, @@ -632,7 +638,17 @@ const writesAfter = (failures: number, stderr = EMPTY): Attempt => async (args, return { exitCode: 0, stderrTail: "", signalled: false }; }; -async function incidentRun(id: string, attempt: Attempt, opts: { signal?: AbortSignal; onWait?: (ms: number) => void; request?: Record<string, unknown> } = {}) { +async function incidentRun( + id: string, + attempt: Attempt, + opts: { + signal?: AbortSignal; + onWait?: (ms: number) => void; + request?: Record<string, unknown>; + meta?: Record<string, unknown>; + deps?: Record<string, unknown>; + } = {}, +) { await ytChannel(); const calls: string[][] = []; const waits: number[] = []; @@ -647,11 +663,11 @@ async function incidentRun(id: string, attempt: Attempt, opts: { signal?: AbortS signal: opts.signal ?? new AbortController().signal, jobId: `job-${id}`, deps: { - refresh: refreshWith(ytLiveMeta(id)), + refresh: refreshWith(opts.meta ?? ytLiveMeta(id)), fetchText: async () => { throw new Error("no playlist read is expected"); }, - spawn: async ({ args }) => { + spawn: async ({ args }: { args: string[] }) => { calls.push(args); return attempt(args, calls.length); }, @@ -663,6 +679,8 @@ async function incidentRun(id: string, attempt: Attempt, opts: { signal?: AbortS land, freeBytes: async () => 1e15, handoff, + shuttingDown: () => false, + ...(opts.deps ?? {}), }, } as Parameters<typeof recordLiveRun>[0]); return { run, calls, waits, log }; @@ -738,7 +756,7 @@ test("from its start fails 3 times, the live edge records: landed, the start sai assert.equal(row.needsAttention, true, "a lost start is a failure needing attention"); }); -test("a stream that has ended is not retried; a cancel during a wait stops at once and alerts nobody", async () => { +test("a stream that has ended is not retried; a cancel during a wait stops at once (a must-keep stream's cancel needs a person, another's is quiet)", async () => { const ended = await incidentRun("exmplended1", writesAfter(Infinity, "ERROR: [youtube] exmplended1: This live event has ended.\n")); await assert.rejects(ended.run, /ended/); assert.equal(ended.calls.length, 1); @@ -752,7 +770,19 @@ test("a stream that has ended is not retried; a cancel during a wait stops at on const { listLiveRecordings } = await import("./liveRecordings"); const row = (await listLiveRecordings(paths, { slug: YT_SLUG, id: "exmplcancl1" })).rows[0]!; assert.equal(row.status, "cancelled"); - assert.equal(row.needsAttention, false); + assert.equal(row.stoppedBy, "operator"); + assert.equal(row.needsAttention, true, "a must-keep stream cancelled: is that what was wanted?"); + + const ac2 = new AbortController(); + const plain = await incidentRun("exmplcancl2", writesAfter(Infinity), { + signal: ac2.signal, + onWait: () => ac2.abort(), + request: { doNotClean: false, note: undefined }, + }); + assert.equal((await plain.run).status, "cancelled"); + const quiet = (await listLiveRecordings(paths, { slug: YT_SLUG, id: "exmplcancl2" })).rows[0]!; + assert.equal(quiet.mustKeep, false); + assert.equal(quiet.needsAttention, false, "a person's Cancel of a stream that is not must-keep is quiet"); }); test("a healthy recording is untouched: one spawn, no wait, today's argv byte for byte", async () => { @@ -783,7 +813,9 @@ test("a later recording of the same stream that lands supersedes the earlier fai const id = "exmplsuper1"; const first = await incidentRun(id, writesAfter(Infinity)); await assert.rejects(first.run); - const second = await incidentRun(id, writesAfter(0)); + // The second run holds the whole stream: 600 s of a stream that started + // ~600 s before it ended (by the clock). + const second = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), release_timestamp: Math.floor(Date.now() / 1000) - 590 } }); assert.equal((await second.run).status, "landed"); const { listLiveRecordings } = await import("./liveRecordings"); const rows = (await listLiveRecordings(paths, { slug: YT_SLUG, id, all: true })).rows; @@ -800,3 +832,217 @@ test("the recorder's progress thinning also catches yt-dlp's numbered stream lin assert.equal(isProgressLine("[download] 50.0% of 10MiB"), true); assert.equal(isProgressLine("ERROR: The downloaded file is empty"), false); }); + +// --- REVIEW-1 (21 Nov 2026): what the first slice got wrong, pinned ---------------- + +const store = () => path.join(paths.savedVideosDir, YT_SLUG); +const outOf = (args: string[]) => args[args.indexOf("-o") + 1]!.replace(/\.%\(ext\)s$/, ""); +const rowOf = async (id: string) => { + const { listLiveRecordings } = await import("./liveRecordings"); + return (await listLiveRecordings(paths, { slug: YT_SLUG, id, all: true })).rows; +}; + +test("1.4: a normal stream end where yt-dlp exits 1 but the parts hold bytes lands, unchanged: one spawn, no wait, not failed", async () => { + const id = "exmplexit01"; + const { run, calls, waits, log } = await incidentRun(id, async (args) => { + // Both streams written, yt-dlp's merge never ran (exit 1 at the end). + await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=3600;"); + await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=3600;"); + return { exitCode: 1, stderrTail: "ERROR: [download] Got error: HTTP Error 403\nERROR: unable to download fragment\n", signalled: false }; + }); + const s = await run; + assert.equal(s.status, "landed"); + assert.equal(calls.length, 1, "not retried"); + assert.deepEqual(waits, []); + assert.ok(!log.some((l) => /recorded nothing/.test(l))); + const row = (await rowOf(id))[0]!; + assert.equal(row.status, "landed"); + assert.equal(row.error, undefined); + assert.equal(row.failureClass, undefined); + assert.equal(row.parts[0]!.error, undefined); + assert.equal(row.needsAttention, false); +}); + +test("1.1: an earlier run's longer from-start part lands, and this run's live-edge part — the only copy of the stream's end — is KEPT, listed, needing a person", async () => { + const id = "exmplkeep01"; + await mkdir(store(), { recursive: true }); + // Run A (an earlier, interrupted run): 3 h from the start, left in staging. + const earlier = path.join(store(), `.${id}.live-2026-11-20T01-00-00-000Z.ytdlp.mp4`); + await writeFile(earlier, "format=mov,mp4;seconds=10800;"); + // Run B: from its start fails 3 times; the live edge records 1.8 h. + const { run, calls } = await incidentRun(id, async (args, n) => { + if (n <= 3) return { exitCode: 1, stderrTail: EMPTY, signalled: false }; + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=6480;"); + return { exitCode: 0, stderrTail: "", signalled: false }; + }); + const s = await run; + assert.equal(calls.length, 4); + assert.equal(s.landed?.seconds, 10800, "the longest (run A's) lands"); + const left = (await readdir(store())).filter((n) => n.startsWith(`.${id}.`)); + assert.equal(left.length, 1, `the live-edge part is still on disk: ${left.join(", ")}`); + assert.match(left[0]!, /ytdlp-edge-a4\.mp4$/); + const row = (await rowOf(id))[0]!; + assert.equal(row.keptParts?.length, 1); + const k = row.keptParts![0]!; + assert.equal(k.run, "this"); + assert.equal(k.fromStart, false); + assert.equal(k.seconds, 6480); + assert.ok(k.bytes > 0 && k.files[0]!.name === left[0]); + assert.equal(row.needsAttention, true); + assert.match(row.reason, /kept in staging/); + const { acknowledgeLiveRecording } = await import("./liveRecordings"); + assert.equal((await acknowledgeLiveRecording(paths, { slug: YT_SLUG, id, by: "test" })).ok, true); + assert.equal((await rowOf(id))[0]!.needsAttention, false, "acknowledged"); + assert.equal((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).length, 1, "an acknowledgement removes nothing"); +}); + +test("1.1: of this run's own parts, a shorter from-start part is inside the landed one and goes", async () => { + const id = "exmplkeep02"; + // Attempt 1 records audio only for 45 s (one stream missing: retried), + // attempt 2 records both from the start. + const { run, calls } = await incidentRun(id, async (args, n) => { + if (n === 1) { + await writeFile(`${outOf(args)}.f140.m4a`, "format=mp4;seconds=45;v=none;"); + return { exitCode: 1, stderrTail: "2: ERROR: The downloaded file is empty\n", signalled: false }; + } + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=600;"); + return { exitCode: 0, stderrTail: "", signalled: false }; + }); + assert.equal((await run).status, "landed"); + assert.equal(calls.length, 2); + assert.deepEqual((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)), []); + const row = (await rowOf(id))[0]!; + assert.equal(row.keptParts, undefined); + assert.equal(row.missingStream, undefined, "the second attempt has both"); + assert.equal(row.parts[0]!.missingStream, "video"); + assert.equal(row.parts[0]!.failureClass, "partial"); +}); + +test("1.7: one stream with bytes and the other empty is a failed attempt, retried; when every attempt ends so, the row names the missing stream and keeps the parts", async () => { + const id = "exmplpart01"; + const videoOnly: Attempt = async (args) => { + await writeFile(`${outOf(args)}.f247.webm`, "format=webm;seconds=45;a=none;"); + return { exitCode: 1, stderrTail: "1: [download] Destination: x\n2: ERROR: The downloaded file is empty\n", signalled: false }; + }; + const { run, calls, waits } = await incidentRun(id, videoOnly); + await assert.rejects(run, /audio stream recorded nothing/); + assert.equal(calls.length, 6, "the schedule, as for nothing at all"); + assert.deepEqual(waits, [60_000, 180_000, 0, 60_000, 180_000]); + const row = (await rowOf(id))[0]!; + assert.equal(row.status, "failed"); + assert.equal(row.missingStream, "audio"); + assert.equal(row.failureClass, "partial"); + assert.equal(row.keptParts?.length, 6, "every video-only part stays on disk"); + assert.ok(row.keptParts!.every((k) => k.bytes > 0 && /not landable/.test(k.why))); + assert.equal((await readdir(store())).filter((n) => n.startsWith(`.${id}.`)).length, 6); + assert.equal(row.needsAttention, true); +}); + +test("2.1: an editor shutdown stops a recording as `interrupted`, never `cancelled`, and it needs a person", async () => { + const ac = new AbortController(); + const { run } = await incidentRun("exmplshut01", writesAfter(Infinity), { + signal: ac.signal, + onWait: () => ac.abort(), + request: { doNotClean: false, note: undefined }, + deps: { shuttingDown: () => true }, + }); + const s = await run; + assert.equal(s.status, "interrupted"); + const row = (await rowOf("exmplshut01"))[0]!; + assert.equal(row.status, "interrupted"); + assert.equal(row.stoppedBy, "shutdown"); + assert.equal(row.needsAttention, true, "interrupted needs a person, must-keep or not"); + assert.match(row.reason, /editor shut down/); + + // Shut down mid-recording with bytes: what was recorded lands, interrupted. + const ac2 = new AbortController(); + const mid = await incidentRun("exmplshut02", async (args) => { + await writeFile(`${outOf(args)}.mp4`, "format=mov,mp4;seconds=300;"); + ac2.abort(); + return { exitCode: null, stderrTail: "", signalled: true }; + }, { signal: ac2.signal, deps: { shuttingDown: () => true } }); + const s2 = await mid.run; + assert.equal(s2.status, "interrupted"); + assert.equal(s2.landed?.seconds, 300); + assert.equal((await rowOf("exmplshut02"))[0]!.needsAttention, true); +}); + +test("2.3: only a landed from-start run that covers the stream supersedes; a live-edge run, a fromStart:false run and a short partial never do", async () => { + const id = "exmplcover1"; + const first = await incidentRun(id, writesAfter(Infinity)); + await assert.rejects(first.run); + const stillNeeds = async () => (await rowOf(id)).find((r) => r.status === "failed")!; + // (a) asked not from its start: lands, does not supersede. + const edge = await incidentRun(id, writesAfter(0), { request: { fromStart: false } }); + assert.equal((await edge.run).status, "landed"); + assert.equal((await stillNeeds()).needsAttention, true, "a run from now does not hold the start"); + assert.equal((await stillNeeds()).supersededBy, undefined); + // (b) from its start, 600 s of a stream that has run two hours. + const short = await incidentRun(id, writesAfter(0)); + const shortLog = short.log; + assert.equal((await short.run).status, "landed"); + assert.equal((await stillNeeds()).needsAttention, true, "a short partial does not supersede"); + assert.ok(shortLog.some((l) => /does not supersede/.test(l))); + const shortRow = (await rowOf(id)).find((r) => r.status === "landed" && r.fromStart && r.coverage)!; + 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. + const whole = await incidentRun(id, writesAfter(0), { meta: { ...YT_META(id), live_status: "post_live", duration: 610 } }); + assert.equal((await whole.run).status, "landed"); + const failed = await stillNeeds(); + assert.ok(failed.supersededBy, "the whole stream, from its start, supersedes"); + assert.equal(failed.needsAttention, false); +}); + +test("3.1: ended, private, members-only and a full disk are not retried; the row records the class", async () => { + const cases: [string, string, string][] = [ + ["exmplcls001", "ERROR: [youtube] exmplcls001: This live event has ended.\n", "ended"], + ["exmplcls002", "ERROR: [youtube] exmplcls002: Private video. Sign in if you've been granted access to this video\n", "private"], + ["exmplcls003", "ERROR: [youtube] exmplcls003: Join this channel to get access to members-only content like this video, and other exclusive perks.\n", "members"], + ["exmplcls004", "ERROR: unable to write data: [Errno 28] No space left on device\n", "disk"], + ]; + for (const [id, stderr, cls] of cases) { + const r = await incidentRun(id, writesAfter(Infinity, stderr)); + await assert.rejects(r.run); + assert.equal(r.calls.length, 1, `${cls}: one spawn`); + assert.deepEqual(r.waits, []); + const row = (await rowOf(id))[0]!; + assert.equal(row.failureClass, cls); + assert.equal(row.needsAttention, true); + } +}); + +test("3.1: a 429 or the bot check gets ONE more try after 15 min, then stops and says so", async () => { + for (const [id, stderr] of [ + ["exmpl429001", "ERROR: [youtube] exmpl429001: HTTP Error 429: Too Many Requests\n"], + ["exmplbot001", "ERROR: [youtube] exmplbot001: Sign in to confirm you're not a bot. Use --cookies-from-browser or --cookies for the authentication.\n"], + ] as const) { + const r = await incidentRun(id, writesAfter(Infinity, stderr)); + await assert.rejects(r.run, /429|not a bot/); + assert.equal(r.calls.length, 2, "one retry"); + assert.deepEqual(r.waits, [15 * 60_000]); + assert.ok(r.calls.every(fromStartArg), "the same mode"); + assert.ok(r.log.some((l) => /refused again/.test(l) && /not retried again/.test(l))); + assert.equal((await rowOf(id))[0]!.failureClass, "rate-limited"); + } + // Refused once, then the retry records: landed. + const ok = await incidentRun("exmpl429002", writesAfter(1, "ERROR: HTTP Error 429: Too Many Requests\n")); + assert.equal((await ok.run).status, "landed"); + assert.equal(ok.calls.length, 2); +}); + +test("a network or unknown failure keeps the designed schedule", async () => { + const r = await incidentRun("exmplnet001", writesAfter(Infinity, "ERROR: [download] Got error: <urlopen error [Errno 101] Network is unreachable>\nERROR: Unable to download fragment\n")); + await assert.rejects(r.run); + assert.equal(r.calls.length, 6); + assert.equal((await rowOf("exmplnet001"))[0]!.failureClass, "network"); +}); + +test("Record again asks what the run was asked: from the start, quality, transcribe, keep, its note and the pre-clip", async () => { + const { recordAgainRequest } = await import("./recordLive"); + const preclip = { everyMinutes: 10, maxChunkMinutes: 20, overlapSeconds: 5, scan: true, mine: false }; + assert.deepEqual( + recordAgainRequest({ slug: "s", url: "u", fromStart: true, maxHeight: 480, transcribe: true, doNotClean: true, note: "keep", preclip } as never), + { fromStart: true, maxHeight: 480, transcribe: true, doNotClean: true, note: "keep", preclip }, + ); +}); diff --git a/common/controller/recordLive.ts b/common/controller/recordLive.ts @@ -40,7 +40,12 @@ // interrupted run left — is landed by landMediaFile, the landing // import-media uses: probe, keep the longer over a container already in // the store, `-c copy` remux to mp4, the store, audio.<fmt>, the archive -// line, media-import.json. The other parts are removed (staging scratch). +// line, media-import.json. A part the landed one is known to contain (a +// shorter part of this run, both from the start) is removed; every other +// part that holds media — an earlier run's, one recorded from another +// point of the stream, one that cannot be landed — is KEPT in staging and +// listed on the record and the channel's row (keptParts) until a person +// decides. Nothing removes those automatically. // 4. live-recording.json beside the record says what was recorded, how, and // what was landed; the "Do not clean" marker when asked; the hand-off to // the transcription lane (never lifting a pause). @@ -48,7 +53,7 @@ import path from "node:path"; import { spawn } from "node:child_process"; import { createWriteStream } from "node:fs"; -import { mkdir, readFile, readdir, rm, stat } from "node:fs/promises"; +import { mkdir, readFile, readdir, rm, rmdir, stat } from "node:fs/promises"; import { execa } from "execa"; import type { ChannelConfig } from "../lib/channelConfig"; import { assertChannelTextReadable } from "../lib/channelMedia"; @@ -56,12 +61,14 @@ import { alwaysCookies, type ResolvedCookiePolicy } from "../lib/cookiePolicy"; import { BROWSER_FALLBACK_PLATFORMS, LIVE_DEFAULT_MAX_HEIGHT, + LIVE_RATE_LIMIT_WAIT_MS, classifyAttempt, extractionRefused, ffmpegLiveArgs, formatUnavailable, lastErrorLine, liveAttemptSchedule, + liveFailureClass, livePartFiles, mergeStreamsArgs, newSegments, @@ -71,13 +78,17 @@ import { separateStreamsDefault, spanWords, ytdlpLiveArgs, + type KeptPart, + type LiveFailureClass, type LivePart, type LivePartFiles, type LivePartMethod, type LiveRecordingRecord, type MediaPlaylist, type MediaSegment, + type MissingStream, type PlaylistReach, + type StreamCoverage, } from "../lib/liveCapture"; import { liveRecordingSidecar } from "../lib/mediaImport-server"; import { rowOfRecord, upsertLiveRecordingRow } from "../lib/liveRecordings-server"; @@ -560,6 +571,9 @@ export type RecordLiveDeps = { // and the stretch applied to it (default jitterMs, pacing.jitter). wait?: (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; }; export type RecordLiveJobOpts = { @@ -724,11 +738,25 @@ type RunHooks = { const isMustKeep = (req: RecordLiveRequest) => req.doNotClean === true || Boolean(req.note); +// A stopped run: by the editor shutting down (`interrupted`, which needs a +// person: the stream may still be live and nobody chose to stop it), else by a +// person's Cancel (`cancelled`). +function stopOf(deps: RecordLiveDeps | undefined): { status: "interrupted" | "cancelled"; by: "shutdown" | "operator" } { + let down = false; + try { + down = deps?.shuttingDown ? deps.shuttingDown() : getRegistry().isShuttingDown?.() === true; + } catch { + down = false; + } + return down ? { status: "interrupted", by: "shutdown" } : { status: "cancelled", by: "operator" }; +} + // The request's recording keys, as the channel's row keeps them (what "Record -// again" asks again). +// again" asks again): from the start or not, the quality, separate streams, +// 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"] as const) { + for (const k of ["fromStart", "maxHeight", "separate", "transcribe", "doNotClean", "note", "preclip"] as const) { if (req[k] !== undefined) out[k] = req[k]; } return out; @@ -736,6 +764,44 @@ export function recordAgainRequest(req: RecordLiveRequest): Record<string, unkno const rowExtra = (req: RecordLiveRequest) => ({ ...(req.note ? { note: req.note } : {}), request: recordAgainRequest(req) }); +// DOES THE LANDED RECORDING HOLD THE WHOLE STREAM — what supersedes an +// earlier failure of the same id (lib/liveRecordings-server.ts). The stream's +// length is the ended stream's own `duration` when its record has one, else +// the clock: the last part's end minus the stream's start. The clock can only +// OVERSTATE it (a recorder exits after the stream's last segment, and a +// scheduled start may precede the real one), so a whole recording may read +// "does not cover" by the clock — the safe direction: the earlier failure +// then stays until a person acknowledges it. +// The tolerance, max(60 s, 1 %): a recording from the start misses only +// seconds at its two ends (the first fragment, the live edge's last few +// segments of 2-6 s each, the container's rounding); 1 % absorbs probe and +// rounding drift on a stream of many hours. A recording short by more than +// that is missing content a person should hear about. +export const COVERAGE_MIN_TOLERANCE_SECONDS = 60; +export const COVERAGE_TOLERANCE_FRACTION = 0.01; + +export function streamCoverage(o: { + capturedSeconds: number | null; + endMeta: Record<string, unknown> | null; + streamStartedAt: string | null; + lastEndedAt: string | null; + // From its start as asked, with both streams, not a live-edge fallback. + wholeFromStart: boolean; +}): StreamCoverage { + const ls = typeof o.endMeta?.live_status === "string" ? o.endMeta.live_status : null; + const duration = + typeof o.endMeta?.duration === "number" && o.endMeta.duration > 0 && ls !== "is_live" && ls !== "is_upcoming" ? (o.endMeta.duration as number) : null; + const startMs = o.streamStartedAt ? Date.parse(o.streamStartedAt) : NaN; + const endMs = o.lastEndedAt ? Date.parse(o.lastEndedAt) : NaN; + const clock = Number.isFinite(startMs) && Number.isFinite(endMs) && endMs > startMs ? (endMs - startMs) / 1000 : null; + const streamSeconds = duration ?? clock; + const basis = duration !== null ? "duration" : clock !== null ? "clock" : null; + const toleranceSeconds = Math.round(Math.max(COVERAGE_MIN_TOLERANCE_SECONDS, (streamSeconds ?? 0) * COVERAGE_TOLERANCE_FRACTION)); + const covers = + o.wholeFromStart && o.capturedSeconds !== null && streamSeconds !== null && o.capturedSeconds + toleranceSeconds >= streamSeconds; + return { capturedSeconds: o.capturedSeconds, streamSeconds: streamSeconds !== null ? Math.round(streamSeconds) : null, basis, toleranceSeconds, covers }; +} + // THE RUN, AND ITS FAILURE RECORDED. Every way a recording can end without a // landing leaves a row in channels/<slug>/live-recordings.json that says why // (lib/liveRecordings-server.ts): the run's own saves write it; a throw the @@ -750,20 +816,25 @@ export async function recordLiveRun( return await recordLiveRunInner(opts, hooks); } catch (err) { const message = (err as Error).message; + const stopped = opts.signal.aborted ? stopOf(opts.deps) : null; try { if (hooks.record && hooks.save) { if (hooks.record.status === "recording") { - hooks.record.status = opts.signal.aborted ? "cancelled" : "failed"; + hooks.record.status = stopped?.status ?? "failed"; + if (stopped) hooks.record.stoppedBy = stopped.by; hooks.record.endedAt = now().toISOString(); hooks.record.error = message; await hooks.save(); } } else if (hooks.id && !opts.request.dryRun) { + const failureClass = stopped ? undefined : liveFailureClass(message); await upsertLiveRecordingRow(opts.paths, opts.request.slug, { ...rowOfRecord( hooks.id, { - status: opts.signal.aborted ? "cancelled" : "failed", + status: stopped?.status ?? "failed", + ...(stopped ? { stoppedBy: stopped.by } : {}), + ...(failureClass && failureClass !== "unknown" ? { failureClass } : {}), url: hooks.url ?? opts.plan.url, platform: hooks.platform ?? opts.plan.platform, fromStart: opts.request.fromStart !== false, @@ -850,10 +921,14 @@ async function recordLiveRunInner( // A record this run made and recorded nothing into is not left behind: a // data/<id>/ with metadata is what every enumerator reads as "fetched". const RECORD_ONLY = new Set(["metadata.info.json", "metadata.history.json", "live-recording.json"]); + // By name, then an rmdir that fails on anything else: a file another job + // (the live chat) writes into the dir meanwhile is never removed with it. const abandon = async () => { if (!created) return; const left = await readdir(videoDir).catch(() => [] as string[]); - if (left.every((n) => RECORD_ONLY.has(n))) await rm(videoDir, { recursive: true, force: true }); + if (!left.every((n) => RECORD_ONLY.has(n))) return; + for (const n of RECORD_ONLY) await rm(path.join(videoDir, n), { force: true }); + await rmdir(videoDir).catch(() => {}); }; let extractionError: string | null = null; const refresh = () => @@ -915,7 +990,7 @@ async function recordLiveRunInner( const stemPath = (tag: string) => path.join(slugStore, `.${id}.live-${stamp}.${tag}`); const partPath = (tag: string) => `${stemPath(tag)}.ts`; const leftovers = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])); - if (leftovers.length) say(`An earlier recording left ${leftovers.length} part(s); the longest of all is landed.`); + if (leftovers.length) say(`An earlier recording left ${leftovers.length} part(s); the longest of all is landed, and the others are kept.`); // When the stream started, as its record says (what a live-edge fallback // has lost is measured from it). @@ -1044,6 +1119,20 @@ async function recordLiveRunInner( for (const f of g ? [...g.finished, ...g.streams] : []) 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). + const missingStreamOf = async (stem: string): Promise<MissingStream | null> => { + const g = await filesOf(stem); + if (!g) return null; + for (const f of g.finished) if ((await sizeOf(path.join(slugStore, f))) > 0) return null; + const withBytes: string[] = []; + for (const f of g.streams) if ((await sizeOf(path.join(slugStore, f))) > 0) withBytes.push(f); + if (withBytes.length !== 1) return null; + const p = await probe(path.join(slugStore, withBytes[0]!)).catch(() => null); + if (p?.videoCodec && p.audioCodec) return null; + return p?.videoCodec ? "audio" : p?.audioCodec ? "video" : "unknown"; + }; if (plan.platform === "kick") { const vodFmt = fmt; @@ -1083,15 +1172,24 @@ async function recordLiveRunInner( if (extractionError === null) { // THE ATTEMPTS (lib/liveCapture.ts liveAttemptSchedule): from its start // at 0, +60 and +180 s, then from the live edge at 0, +60 and +180 s — - // each wait stretched by pacing.jitter, ended by a Cancel. Only an - // attempt that recorded NOTHING for a reason another try may not meet - // again is retried; a stream that has ended, an argv no try can fix, a - // Cancel and a part with bytes all end the attempts. + // each wait stretched by pacing.jitter, ended by a Cancel. An attempt + // that recorded NOTHING (or, for separate streams, only one of the two) + // is retried when another try may not meet the same failure: the + // failure's class (liveFailureClass) decides — + // ended, private, members-only, the disk not retried + // 429 / the bot check ONE more try, the same + // mode, after 15 min; then + // not again + // empty, network, unknown, one stream the schedule + // A part with bytes in both streams (whatever yt-dlp's exit: a normal + // stream end often exits 1), a Cancel and an argv no try can fix end the + // attempts. const schedule = liveAttemptSchedule(fromStart); let index0 = false; let fromStartFailures = 0; let edgeFailures = 0; let lastReason: string | null = null; + let rateLimitRetried = false; for (let slot = 0; slot < schedule.length && !signal.aborted; ) { const step = schedule[slot]!; const n = (record.attempts ?? 0) + 1; @@ -1099,10 +1197,27 @@ async function recordLiveRunInner( 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; " : ""); const last = parts[parts.length - 1]!; - const cls = classifyAttempt({ ...o, bytes: await bytesOf(last.stem) }); - if (cls === "recorded" || cls === "stopped" || signal.aborted) break; - const reason = lastErrorLine(o.stderrTail) ?? `yt-dlp exit ${o.exitCode ?? "null"}`; + 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 }); + if (cls === "recorded" || cls === "stopped" || signal.aborted) { + 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 reason = + missing !== null + ? `${missing === "unknown" ? "one of its two streams" : `the ${missing} stream`} recorded nothing (${errLine})` + : errLine; last.part.error = reason; + last.part.failureClass = failure; + if (missing !== null) last.part.missingStream = missing; + record.failureClass = failure; + if (missing !== null) record.missingStream = missing; + else delete record.missingStream; await save(); lastReason = reason; if (o.exitCode !== 0 && !separate && formatUnavailable(o.stderrTail)) { @@ -1110,7 +1225,7 @@ async function recordLiveRunInner( 'yt-dlp found no single stream with video and audio: this stream offers them separately — record it with "separate": true.', ); } - if (o.exitCode !== 0 && BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(o.stderrTail)) { + if (bytes === 0 && o.exitCode !== 0 && BROWSER_FALLBACK_PLATFORMS.has(plan.platform) && extractionRefused(o.stderrTail)) { say("yt-dlp was refused; recording from the page's own playlist."); pathB = true; break; @@ -1120,12 +1235,38 @@ async function recordLiveRunInner( index0 = true; continue; } - if (cls === "argv" || cls === "gone") { - say(`Attempt ${n} recorded nothing (${reason}); ${cls === "gone" ? "the stream is over or gone" : "the same command would fail the same way"}: not retried.`); + if (cls === "argv") { + say(`Attempt ${n} recorded nothing (${reason}); the same command would fail the same way: not retried.`); + break; + } + if (cls === "final") { + const why = + failure === "ended" + ? "the stream is over" + : failure === "private" + ? "the stream is private, removed or unavailable" + : failure === "members" + ? "the stream is members-only or needs a login" + : "the store's disk cannot take it"; + say(`Attempt ${n} recorded nothing (${reason}); ${why} (${failure}): not retried.`); break; } if (step.mode === "from-start") fromStartFailures++; else edgeFailures++; + if (cls === "rate-limited") { + if (rateLimitRetried) { + say( + `Attempt ${n} was refused again (${reason}) after a ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)} wait: a rate limit or the bot check — stopping, not retried again.`, + ); + break; + } + rateLimitRetried = true; + say( + `Attempt ${n} was refused (${reason}): a rate limit or the bot check — ONE more try ${step.mode === "live-edge" ? "from the live edge" : "from its start"} in ${spanWords(LIVE_RATE_LIMIT_WAIT_MS / 1000)}, then no more.`, + ); + await waitFor(stretch(LIVE_RATE_LIMIT_WAIT_MS), signal); + continue; + } slot++; const next = schedule[slot]; if (!next) break; @@ -1145,7 +1286,7 @@ async function recordLiveRunInner( } await waitFor(stretch(next.waitMs), signal); } - if (lastReason !== null) { + if (lastReason !== null && record.failureClass !== undefined) { const tries = record.attempts ?? 0; const split = fromStartFailures && edgeFailures ? ` (${fromStartFailures} from its start, ${edgeFailures} from the live edge)` : ""; attemptsSummary = `${tries} attempt${tries === 1 ? "" : "s"}${split}: ${lastReason}`; @@ -1175,21 +1316,26 @@ async function recordLiveRunInner( } // 3. The stream is over (or the recording was stopped): land the longest. - const cancelled = signal.aborted; + // A stop by the editor's shutdown is `interrupted` (it needs a person: the + // stream may still be live), a person's Cancel `cancelled`. + 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]}).`); } - const probe = deps.land?.probe ?? ((f: string, s?: AbortSignal) => probeMedia(paths, f, s)); + const endMeta = await readMeta(videoDir); const merge = deps.merge ?? ((args: string[], s: AbortSignal) => runFfmpegHeavy(paths, args, s)); const at = (n: string) => path.join(slugStore, n); // Every part on disk now — this run's and an earlier run's — by its stem. const groups = livePartFiles(id, await readdir(slugStore).catch(() => [] as string[])); const partOf = new Map(parts.map((p) => [p.stem, p.part])); - const candidates: { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles }[] = []; + type Candidate = { file: string; seconds: number | null; part?: LivePart; group: LivePartFiles }; + const candidates: Candidate[] = []; const unlandable: string[] = []; + const unlandableGroups: { group: LivePartFiles; why: string; part?: LivePart }[] = []; const empty: LivePartFiles[] = []; for (const g of groups) { const part = partOf.get(g.stem); @@ -1198,6 +1344,7 @@ async function recordLiveRunInner( got = await resolvePart(g, slugStore, { probe: (f) => probe(f, landSignal), merge: (a) => merge(a, landSignal), say }); } catch (err) { unlandable.push(`${g.stem}: ${(err as Error).message}`); + unlandableGroups.push({ group: g, why: (err as Error).message, ...(part ? { part } : {}) }); } if (part) { part.bytes = 0; @@ -1205,8 +1352,10 @@ async function recordLiveRunInner( part.seconds = got && !("error" in got) ? got.seconds : null; if (got && !("error" in got) && got.merged) part.merged = true; } - if (got && "error" in got) unlandable.push(`${g.stem}: ${got.error}`); - else if (got) candidates.push({ file: got.file, seconds: got.seconds, group: g, ...(part ? { part } : {}) }); + if (got && "error" in got) { + unlandable.push(`${g.stem}: ${got.error}`); + unlandableGroups.push({ group: g, why: got.error, ...(part ? { part } : {}) }); + } else if (got) candidates.push({ file: got.file, seconds: got.seconds, group: g, ...(part ? { part } : {}) }); else { empty.push(g); for (const f of [...g.finished, ...g.streams, ...g.scratch]) if ((await sizeOf(at(f))) === 0) await rm(at(f), { force: true }); @@ -1214,17 +1363,58 @@ async function recordLiveRunInner( } for (const u of unlandable) say(`Not landable: ${u}`); summary.parts = record.parts.map((p) => ({ method: p.method, seconds: p.seconds ?? null, fromStart: p.fromStart })); + + // WHAT STAYS ON DISK. A part that holds captured media and is not known to + // be inside the landed file is never removed: it is kept in staging and + // listed (record.keptParts, the channel's row), needing a person. + const kept: KeptPart[] = []; + const keep = async (g: LivePartFiles, why: string, o: { seconds?: number | null; part?: LivePart; extra?: string[] } = {}) => { + const names = [...new Set([...g.finished, ...g.streams, ...g.scratch, ...(o.extra ?? []).map((f) => path.basename(f))])]; + const files: { name: string; bytes: number }[] = []; + for (const name of names) { + const b = await sizeOf(at(name)); + if (b > 0) files.push({ name, bytes: b }); + } + if (!files.length) return; + kept.push({ + stem: g.stem, + files, + bytes: files.reduce((n, f) => n + f.bytes, 0), + seconds: o.seconds ?? null, + fromStart: o.part ? o.part.fromStart : null, + run: o.part ? "this" : "earlier", + why, + }); + }; + for (const u of unlandableGroups) await keep(u.group, `not landable as it is: ${u.why}`, { ...(u.part ? { part: u.part } : {}) }); + for (const g of empty) { + // Fragments a recorder left hold media too; yt-dlp's resume state does not. + for (const f of g.scratch) if (/\.ytdl$/i.test(f)) await rm(at(f), { force: true }); + const part = partOf.get(g.stem); + await keep(g, "fragments a recorder left, not landable as they are", { ...(part ? { part } : {}) }); + } + const sayKept = () => { + for (const k of kept) { + say(`Kept, not landed: ${k.stem} (${formatBytes(k.bytes)}, ${k.files.length} file${k.files.length === 1 ? "" : "s"}) — ${k.why}.`); + } + if (kept.length) say(`${kept.length} part${kept.length === 1 ? " is" : "s are"} kept in staging, listed in pnpm ops get live-recordings ${req.slug}/${id}; nothing removes them.`); + }; + if (candidates.length === 0) { - const error = unlandable.length - ? `nothing landable was recorded (${unlandable.join("; ")})` - : attemptsSummary - ? `nothing was recorded — ${attemptsSummary}` - : "nothing was recorded"; - record.status = cancelled ? "cancelled" : "failed"; + const error = [ + unlandable.length ? `nothing landable was recorded (${unlandable.join("; ")})` : null, + attemptsSummary ? `${unlandable.length ? "" : "nothing was recorded — "}${attemptsSummary}` : null, + ] + .filter(Boolean) + .join(" — ") || "nothing was recorded"; + record.status = stopped?.status ?? "failed"; + if (stopped) record.stoppedBy = stopped.by; record.endedAt = now().toISOString(); record.error = error; + if (kept.length) record.keptParts = kept; + sayKept(); await save(); - if (!unlandable.length) await abandon(); + if (!unlandable.length && !kept.length) await abandon(); summary.status = record.status; say(`${RECORD_LIVE_RESULT_MARKER}${JSON.stringify(summary)}`); if (!cancelled) throw new Error(error); @@ -1232,8 +1422,34 @@ async function recordLiveRunInner( } candidates.sort((a, b) => (b.seconds ?? -1) - (a.seconds ?? -1)); const best = candidates[0]!; + // Inside the landed file: a shorter part of THIS run, both from the start + // (both begin where the stream's record begins). Nothing else is assumed: + // an earlier run's part, or one recorded from the live edge, may hold time + // the landed one does not. + const contained = (c: Candidate) => + c !== best && + c.part !== undefined && + best.part !== undefined && + c.part.fromStart && + best.part.fromStart && + c.seconds !== null && + best.seconds !== null && + c.seconds <= best.seconds; for (const c of candidates) { say(`part ${path.basename(c.file)}: ${c.seconds !== null ? `${Math.round(c.seconds)} s` : "length unknown"}${c === best ? " — landed" : ""}`); + if (c === best || contained(c)) continue; + const where = (p?: LivePart) => (p ? (p.fromStart ? "from its start" : "from the live edge") : "by an earlier run"); + await keep( + c.group, + c.part && best.part + ? `recorded ${where(c.part)}, the landed part ${where(best.part)}: it may hold time the landed part does not` + : `recorded ${where(c.part)}; the landed part was recorded ${where(best.part)}: it may hold time the landed part does not`, + { seconds: c.seconds, ...(c.part ? { part: c.part } : {}), extra: [c.file] }, + ); + } + if (separate && !record.missingStream) { + const bp = await probe(best.file, landSignal).catch(() => null); + if (bp && !bp.videoCodec) record.missingStream = "video"; } const landed = await landMediaFile({ paths, @@ -1249,17 +1465,35 @@ async function recordLiveRunInner( signal: landSignal, ...(deps.land ? { deps: deps.land } : {}), }); - // Every part's files were staging scratch (the landed one is moved or - // copied into the store); a shorter (or unlanded) part goes, and so do the - // streams a merge was made from. - for (const c of candidates) await rm(c.file, { force: true }); - for (const g of [...candidates.map((c) => c.group), ...empty]) { - for (const f of [...g.finished, ...g.streams, ...g.scratch]) await rm(at(f), { force: true }); + // 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, and a part + // the landed one contains. Every other part stays (above). + for (const c of candidates) { + if (c !== best && !contained(c)) continue; + await rm(c.file, { force: true }); + for (const f of [...c.group.finished, ...c.group.streams, ...c.group.scratch]) await rm(at(f), { force: true }); } + sayKept(); record.landedPart = best.part ? record.parts.indexOf(best.part) : undefined; record.kept = landed.kept; - record.status = cancelled ? "cancelled" : "landed"; + record.status = stopped?.status ?? "landed"; + if (stopped) record.stoppedBy = stopped.by; + if (kept.length) record.keptParts = kept; record.endedAt = now().toISOString(); + record.coverage = streamCoverage({ + capturedSeconds: best.seconds, + endMeta, + streamStartedAt: record.streamStartedAt ?? null, + lastEndedAt: record.parts.reduce<string | null>((m, p) => (p.endedAt && (!m || p.endedAt > m) ? p.endedAt : m), null), + wholeFromStart: fromStart && !record.fallback && !record.missingStream && best.part?.fromStart === true, + }); + 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( + `The landed part holds ${spanWords(record.coverage.capturedSeconds)} of a ${spanWords(record.coverage.streamSeconds)} stream ` + + `(${record.coverage.basis === "duration" ? "its record's duration" : "by the clock"}): it does not supersede an earlier failure.`, + ); + } await save(); summary.landed = { kept: landed.kept, seconds: landed.newSeconds, container: landed.container }; summary.status = record.status; diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -291,6 +291,12 @@ class JobRegistry { this.shuttingDown = true; } + // Whether the cancels now arriving are the exit's (a run that is stopped + // says `interrupted`, not `cancelled`: controller/recordLive.ts). + isShuttingDown(): boolean { + return this.shuttingDown; + } + register(record: JobRecord): void { this.jobs.set(record.id, record); // Bound the registry. Drop oldest finished records past 100, but never diff --git a/common/lib/liveCapture.ts b/common/lib/liveCapture.ts @@ -440,6 +440,46 @@ export type LivePart = { // What the recorder said when the part recorded nothing: its last `ERROR:` // line (lastErrorLine), so the reason is in the record, not only the log. error?: string; + // What kind of failure that was (liveFailureClass). + failureClass?: LiveFailureClass; + // The listing's own (controller/liveRecordings.ts), while it records: when + // the part's files last grew. Never written to the record. + lastGrowthAt?: string; + // A separate-streams attempt where one stream wrote bytes and the other + // nothing: the stream that is missing ("unknown": the one that wrote could + // not be read). + missingStream?: MissingStream; +}; + +export type MissingStream = "video" | "audio" | "unknown"; + +// A PART THE LANDING DID NOT LAND AND DID NOT REMOVE. It holds captured media +// the landed file is not known to contain (an earlier run's part, a part +// recorded from another point of the stream, a part that cannot be landed as +// it is): its files stay in the store's staging dir, listed here with their +// sizes, until a person decides. Nothing removes them automatically. +export type KeptPart = { + stem: string; + files: { name: string; bytes: number }[]; + bytes: number; + seconds: number | null; + // Null: an earlier run's part (its record is that run's). + fromStart: boolean | null; + run: "this" | "earlier"; + why: string; +}; + +// Whether the landed recording holds the whole stream: what supersedes an +// earlier failure (lib/liveRecordings-server.ts). `basis` is where the +// stream's length came from: the ended stream's own `duration`, else the +// clock (the last part's end minus the stream's start, which can only +// overstate it). +export type StreamCoverage = { + capturedSeconds: number | null; + streamSeconds: number | null; + basis: "duration" | "clock" | null; + toleranceSeconds: number; + covers: boolean; }; // The span of the stream a recording does NOT hold, in stream seconds: a @@ -447,7 +487,9 @@ export type LivePart = { // stream's start is not known). export type LostSpan = { fromSeconds: number; toSeconds: number | null }; -export type LiveRecordingStatus = "recording" | "landed" | "failed" | "cancelled"; +// `interrupted`: stopped by an editor shutdown, not by a person (a Cancel is +// `cancelled`). +export type LiveRecordingStatus = "recording" | "landed" | "failed" | "cancelled" | "interrupted"; export type LiveRecordingRecord = { status: LiveRecordingStatus; @@ -478,9 +520,20 @@ export type LiveRecordingRecord = { jobId?: string; // When the stream started (its record's release_timestamp/timestamp), ISO. streamStartedAt?: string; + // The last failed attempt's class (liveFailureClass). + failureClass?: LiveFailureClass; + // The attempts ended with one of the two streams recording nothing. + 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"; + // Parts left on disk, not landed (KeptPart). + keptParts?: KeptPart[]; + // Once landed: does it hold the whole stream (StreamCoverage). + coverage?: StreamCoverage; }; -const LIVE_STATUSES: ReadonlySet<string> = new Set(["recording", "landed", "failed", "cancelled"]); +const LIVE_STATUSES: ReadonlySet<string> = new Set(["recording", "landed", "failed", "cancelled", "interrupted"]); const PART_METHODS: ReadonlySet<string> = new Set(["ytdlp", "browser", "vod-poll"]); export function coerceLiveRecording(raw: unknown): LiveRecordingRecord | null { @@ -535,29 +588,90 @@ export function liveAttemptSchedule(fromStart: boolean): { mode: LiveAttemptMode return [...LIVE_RETRY_WAITS_MS.map((waitMs) => ({ mode: "from-start" as const, waitMs })), ...edge]; } +// WHY AN ATTEMPT RECORDED NOTHING, from what the recorder said (its stderr +// tail). The class decides what is tried next and is kept on the part and the +// row: +// ended the stream is over, not live, or its recording is not +// available — not retried +// private private, removed, unavailable, the account terminated — +// not retried +// members members-only, paid, or a login is required — not retried +// disk no space left, the store read-only or not writable — not +// retried +// rate-limited HTTP 429 / "Too Many Requests" / the bot check — ONE more +// try after LIVE_RATE_LIMIT_WAIT_MS, then not again +// empty "The downloaded file is empty" (20 Nov 2026) — the schedule +// network a connection or HTTP 5xx error — the schedule +// unknown anything else — the schedule +// (A part with bytes, a Cancel, an argv no try can fix and a stream that +// cannot start at its start are told apart by classifyAttempt first.) +export type LiveFailureClass = + | "ended" + | "private" + | "members" + | "disk" + | "rate-limited" + | "empty" + | "network" + | "unknown" + | "argv" + | "unsupported" + | "partial"; + // What yt-dlp says when the stream is over or gone: no attempt can help. export function liveStreamGone(stderr: string): boolean { - return /This live event has ended|is no longer live|Private video|Video unavailable|This video has been removed|This video is private|has been terminated/i.test( - stderr, - ); + const c = liveFailureClass(stderr); + return c === "ended" || c === "private"; } +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"; + // 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"; + 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"; + if (/The downloaded file is empty/i.test(t)) return "empty"; + if (/timed out|Connection reset|Connection refused|Network is unreachable|Temporary failure in name resolution|getaddrinfo|Name or service not known|IncompleteRead|Remote end closed|HTTP Error 5\d\d|Unable to download/i.test(t)) return "network"; + return "unknown"; +} + +// The wait before the one more try a rate limit or a bot check gets. +export const LIVE_RATE_LIMIT_WAIT_MS = 15 * 60_000; + // What one attempt came to. -// recorded it wrote media (whatever its exit): never retried here -// stopped a Cancel's SIGINT -// unsupported yt-dlp cannot start this stream at its start (→ index 0) -// argv the same argv would fail the same way (no format the -// selector names, a URL no extractor takes): not retried -// gone the stream has ended, is private or removed: not retried -// nothing it recorded nothing for another reason: retried -export type LiveAttemptClass = "recorded" | "stopped" | "unsupported" | "argv" | "gone" | "nothing"; - -export function classifyAttempt(o: { exitCode: number | null; signalled: boolean; stderrTail: string; bytes: number }): LiveAttemptClass { +// recorded it wrote media (whatever its exit): never retried here +// stopped a Cancel's SIGINT +// partial separate streams, and one wrote bytes while the other wrote +// nothing: a failed attempt, retried on the schedule +// unsupported yt-dlp cannot start this stream at its start (→ index 0) +// argv the same argv would fail the same way (no format the +// selector names, a URL no extractor takes): not retried +// final ended, private, members-only or the disk (liveFailureClass): +// not retried +// rate-limited 429 or the bot check: one more try after a long wait +// nothing it recorded nothing for another reason (empty, network, +// unknown — an exit 0 with no bytes too: nothing was recorded, +// and the stream may still be live): retried on the schedule +export type LiveAttemptClass = "recorded" | "stopped" | "partial" | "unsupported" | "argv" | "final" | "rate-limited" | "nothing"; + +export function classifyAttempt(o: { + exitCode: number | null; + signalled: boolean; + stderrTail: string; + bytes: number; + // Separate streams: one of the two wrote nothing (the caller probes). + partial?: boolean; +}): LiveAttemptClass { if (o.signalled) return "stopped"; - if (o.bytes > 0) return "recorded"; + if (o.bytes > 0) return o.partial ? "partial" : "recorded"; if (liveFromStartUnsupported(o.stderrTail)) return "unsupported"; if (formatUnavailable(o.stderrTail) || /Unsupported URL/i.test(o.stderrTail)) return "argv"; - if (liveStreamGone(o.stderrTail)) return "gone"; + const c = liveFailureClass(o.stderrTail); + if (c === "ended" || c === "private" || c === "members" || c === "disk") return "final"; + if (c === "rate-limited") return "rate-limited"; return "nothing"; } diff --git a/common/lib/liveRecordings-server.ts b/common/lib/liveRecordings-server.ts @@ -13,11 +13,28 @@ // // Written only through these functions (one atomic write per change, under the // file's lock). +// +// A FILE THAT DOES NOT READ IS NEVER OVERWRITTEN. Its rows are the failures +// nobody has acknowledged yet: a write that finds it unparseable (or +// unreadable) renames it aside — `live-recordings.json.corrupt-<stamp>`, beside +// it — starts a new file, and names the kept one in the new file's `setAside`, +// which needs a person (the listing counts it) until acknowledged. A rename +// that fails is a write that fails: the file stays as it is. import path from "node:path"; +import { rename } from "node:fs/promises"; import type { Paths } from "./paths"; import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "./jsonFile-server"; -import type { LivePart, LiveRecordingRecord, LiveRecordingStatus, LostSpan } from "./liveCapture"; +import type { + KeptPart, + LiveFailureClass, + LivePart, + LiveRecordingRecord, + LiveRecordingStatus, + LostSpan, + MissingStream, + StreamCoverage, +} from "./liveCapture"; export const LIVE_RECORDINGS_FILENAME = "live-recordings.json"; @@ -47,6 +64,11 @@ export type LiveRecordingRow = { streamStartedAt?: string; parts: LivePart[]; landedPart?: number; + failureClass?: LiveFailureClass; + missingStream?: MissingStream; + stoppedBy?: "operator" | "shutdown"; + keptParts?: KeptPart[]; + coverage?: StreamCoverage; acknowledgedAt?: string; acknowledgedBy?: string; // The run (its jobId, else its startedAt) that later landed this id. @@ -72,18 +94,67 @@ function coerceRow(raw: unknown): LiveRecordingRow | null { }; } -export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, slug: string): Promise<LiveRecordingRow[]> { +// A live-recordings.json that did not read, renamed aside by a write. +export type SetAsideFile = { + // Its name beside live-recordings.json. + file: string; + at: string; + reason: "unreadable" | "unparseable"; + acknowledgedAt?: string; + acknowledgedBy?: string; +}; + +export type LiveRecordingsFile = { + rows: LiveRecordingRow[]; + setAside: SetAsideFile[]; + // The file as it is now does not read (the next write sets it aside). + problem: "unreadable" | "unparseable" | null; +}; + +function coerceSetAside(raw: unknown): SetAsideFile[] { + if (!Array.isArray(raw)) return []; + return raw.filter( + (x): x is SetAsideFile => !!x && typeof x === "object" && typeof (x as SetAsideFile).file === "string" && typeof (x as SetAsideFile).at === "string", + ); +} + +export async function loadLiveRecordingsFile(paths: Pick<Paths, "channelsDir">, slug: string): Promise<LiveRecordingsFile> { const read = await readJsonFile(fileOf(paths, slug)); - if (!read.ok) return []; - const rows = (read.value as { rows?: unknown } | null)?.rows; - if (!Array.isArray(rows)) return []; - return rows.map(coerceRow).filter((r): r is LiveRecordingRow => r !== null); + if (!read.ok) return { rows: [], setAside: [], problem: read.reason === "absent" ? null : read.reason }; + const value = read.value as { rows?: unknown; setAside?: unknown } | null; + if (!value || typeof value !== "object" || Array.isArray(value)) return { rows: [], setAside: [], problem: "unparseable" }; + const rows = Array.isArray(value.rows) ? value.rows.map(coerceRow).filter((r): r is LiveRecordingRow => r !== null) : []; + return { rows, setAside: coerceSetAside(value.setAside), problem: null }; } -// Needs a person, as the row stands (the listing adds `interrupted`). -export function rowNeedsAttention(r: Pick<LiveRecordingRow, "status" | "fallback" | "acknowledgedAt" | "supersededBy">): boolean { - if (r.acknowledgedAt || r.supersededBy) return false; - return r.status === "failed" || r.fallback === "live-edge"; +export async function loadLiveRecordingRows(paths: Pick<Paths, "channelsDir">, slug: string): Promise<LiveRecordingRow[]> { + return (await loadLiveRecordingsFile(paths, slug)).rows; +} + +// Needs a person, as the row stands (the listing adds `interrupted` for a +// `recording` no job runs). +// failed, interrupted always +// 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 +// one stream missing it landed without video or audio +// parts kept on disk (keptParts) until acknowledged, whatever lands +// later: a later recording does not +// decide what happens to them +// Cleared by an acknowledgement; all but the kept parts also by a later +// recording that holds the whole stream (supersededBy). +export function rowNeedsAttention( + r: Pick<LiveRecordingRow, "status" | "fallback" | "acknowledgedAt" | "supersededBy"> & + Partial<Pick<LiveRecordingRow, "mustKeep" | "keptParts" | "missingStream">>, +): boolean { + if (r.acknowledgedAt) return false; + if (r.keptParts && r.keptParts.length > 0) return true; + if (r.supersededBy) return false; + 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; + return r.missingStream !== undefined; } function cap(rows: LiveRecordingRow[]): LiveRecordingRow[] { @@ -102,13 +173,26 @@ async function mutate<T>( slug: string, // Returns its answer and whether it changed anything (nothing changed: // nothing written). - fn: (rows: LiveRecordingRow[]) => [T, boolean], + fn: (rows: LiveRecordingRow[], setAside: SetAsideFile[]) => [T, boolean], + now: () => Date = () => new Date(), ): Promise<T> { const file = fileOf(paths, slug); return withJsonFileLock(file, async () => { - const rows = await loadLiveRecordingRows(paths, slug); - const [out, changed] = fn(rows); - if (changed) await writeJsonAtomic(file, { rows: cap(rows) }); + const cur = await loadLiveRecordingsFile(paths, slug); + let forced = false; + if (cur.problem) { + // Never overwritten: renamed aside first (a failed rename throws, and + // nothing is written). + const at = now().toISOString(); + const aside = `${LIVE_RECORDINGS_FILENAME}.corrupt-${at.replace(/[:.]/g, "-")}`; + await rename(file, path.join(path.dirname(file), aside)); + cur.setAside.push({ file: aside, at, reason: cur.problem }); + forced = true; + } + const [out, changed] = fn(cur.rows, cur.setAside); + if (changed || forced) { + await writeJsonAtomic(file, { rows: cap(cur.rows), ...(cur.setAside.length ? { setAside: cur.setAside } : {}) }); + } return out; }); } @@ -139,11 +223,25 @@ export function rowOfRecord( ...(rec.streamStartedAt ? { streamStartedAt: rec.streamStartedAt } : {}), parts: rec.parts.map((p) => ({ ...p })), ...(rec.landedPart !== undefined ? { landedPart: rec.landedPart } : {}), + ...(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.coverage ? { coverage: { ...rec.coverage } } : {}), }; } -// Writes (or rewrites) the run's row. A run that LANDS marks every earlier -// row of the same id that still needs a person as superseded by it. +// 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; +} + +// Writes (or rewrites) the run's row. A run that lands the WHOLE stream +// (rowCoversStream) marks every earlier row of the same id that still needs a +// person as superseded by it. A live-edge landing, a run asked not to start at +// the start, or a short partial never does. export async function upsertLiveRecordingRow( paths: Pick<Paths, "channelsDir">, slug: string, @@ -160,12 +258,11 @@ export async function upsertLiveRecordingRow( }; if (i >= 0) rows[i] = next; else rows.push(next); - // Superseded only by a recording that holds the stream from its start. - if (row.status === "landed" && row.fallback !== "live-edge") { + if (rowCoversStream(row)) { const by = row.jobId ?? row.startedAt; for (const r of rows) { if (r === next || r.id !== row.id || r.supersededBy) continue; - if (r.status === "failed" || r.status === "recording" || r.fallback === "live-edge") r.supersededBy = by; + if (r.status === "recording" || rowNeedsAttention(r)) r.supersededBy = by; } } return [undefined, true]; @@ -184,7 +281,7 @@ export async function acknowledgeLiveRecordingRows( return mutate(paths, slug, (rows) => { let n = 0; for (const r of rows) { - if (r.id !== id || r.acknowledgedAt || r.supersededBy) continue; + if (r.id !== id || r.acknowledgedAt) continue; if (opts.startedAt && r.startedAt !== opts.startedAt) continue; if (!rowNeedsAttention(r) && !opts.interrupted?.(r)) continue; r.acknowledgedAt = at; @@ -194,3 +291,23 @@ export async function acknowledgeLiveRecordingRows( return [n, n > 0]; }); } + +// A person has seen a set-aside file (its name, or every one of the channel's +// when `file` is not given). The file stays where it is. +export async function acknowledgeSetAsideFiles( + paths: Pick<Paths, "channelsDir">, + slug: string, + opts: { file?: string; by?: string; now?: Date } = {}, +): Promise<number> { + const at = (opts.now ?? new Date()).toISOString(); + return mutate(paths, slug, (_rows, setAside) => { + let n = 0; + for (const f of setAside) { + if (f.acknowledgedAt || (opts.file && f.file !== opts.file)) continue; + f.acknowledgedAt = at; + if (opts.by) f.acknowledgedBy = opts.by; + n++; + } + return [n, n > 0]; + }); +} diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -11,6 +11,15 @@ banner on /jobs and the channel and video pages, and said on stderr after every `pnpm ops` reply, until it is acknowledged (`pnpm ops live-recording-ack`) or a later recording of it lands. Its row in `channels/<slug>/live-recordings.json` is never removed for failing. + - Why an attempt failed decides what follows: a stream that has ended, gone private, is members-only, or a full + disk is not retried; a 429 or YouTube's bot check gets one more try after 15 minutes, then stops; the row says + which (`failureClass`). An attempt where only one of the two streams recorded is retried too. + - The landing no longer deletes a part it is not known to hold (an earlier run's, one from the live edge, one it + cannot land): those stay in staging, listed with their sizes, until acknowledged. + - An editor shutdown leaves a recording `interrupted` (it needs you), never `cancelled`; cancelling a must-keep + stream needs you too. A stalled recording is said beside the failures. Only a recording that holds the whole + stream from its start clears an earlier failure. `--wait-started` exits 3 when only the live edge records. + - A `live-recordings.json` that does not read is set aside under a new name, never overwritten. - New setting `liveRecording.stallMinutes` (default 10). - The recorder's job log no longer takes every progress line of a separate-streams recording (~1 MB a minute). - **umtool: the gap mark's border is the deck's accent colour.** diff --git a/editor/app/api/ops/_attention.ts b/editor/app/api/ops/_attention.ts @@ -1,28 +1,36 @@ import type { NextResponse } from "next/server"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { countLiveRecordingsNeedingAttention } from "yt-dlp-transcript-common/controller/liveRecordings"; +import { liveRecordingsAttentionCounts } from "yt-dlp-transcript-common/controller/liveRecordings"; // WHAT NEEDS A PERSON, ON EVERY REPLY OF THE OPS DOOR. An agent polling the // editor reads replies, not pages: a live recording that failed (or lost its -// start, or was interrupted) is said in a header on every answer `ops()` and -// `readRoute()` give — +// start, was interrupted, kept parts it did not land), and one that runs but +// has stopped growing, is said in a header on every answer the door gives — +// `ops()`, `readRoute()`, and the GET routes that check opsAuth themselves +// (they wrap their answer in withAttention) — // -// x-archilyzer-attention: live-recordings=<N> +// x-archilyzer-attention: live-recordings=<N>[, stalled=<M>] // -// — only when N > 0, and `pnpm ops` prints one stderr line for it. The count -// (controller/liveRecordings.ts) is cached 30 s: it reads each channel's -// live-recordings.json, and a reply must not wait for that every time. +// — only when N or M is above 0, and `pnpm ops` prints one stderr line for it. +// The counts (controller/liveRecordings.ts) are cached 30 s: they read each +// channel's live-recordings.json, and a reply must not wait for that every +// time. A count that could not be read is not cached (and not said). export const ATTENTION_HEADER = "x-archilyzer-attention"; const TTL_MS = 30_000; -let cached: { at: number; n: number } | null = null; +type Counts = { needsAttention: number; stalled: number }; +let cached: { at: number; counts: Counts } | null = null; -export async function liveRecordingsAttention(now = Date.now()): Promise<number> { - if (cached && now - cached.at < TTL_MS) return cached.n; - const n = await countLiveRecordingsNeedingAttention(getPaths()).catch(() => 0); - cached = { at: now, n }; - return n; +export async function liveRecordingsAttention(now = Date.now()): Promise<Counts | null> { + if (cached && now - cached.at < TTL_MS) return cached.counts; + try { + const counts = await liveRecordingsAttentionCounts(getPaths()); + cached = { at: now, counts }; + return counts; + } catch { + return null; + } } // For a write that changed the answer (an acknowledgement): the next reply counts again. @@ -30,10 +38,15 @@ export function forgetAttention(): void { cached = null; } -export async function withAttention(res: NextResponse): Promise<NextResponse> { +export function attentionHeaderValue(c: Counts | null): string | null { + if (!c || (c.needsAttention <= 0 && c.stalled <= 0)) return null; + return `live-recordings=${c.needsAttention}${c.stalled > 0 ? `, stalled=${c.stalled}` : ""}`; +} + +export async function withAttention<R extends Response | NextResponse>(res: R): Promise<R> { try { - const n = await liveRecordingsAttention(); - if (n > 0) res.headers.set(ATTENTION_HEADER, `live-recordings=${n}`); + const v = attentionHeaderValue(await liveRecordingsAttention()); + if (v) res.headers.set(ATTENTION_HEADER, v); } catch { /* a reply is never refused for its header */ } diff --git a/editor/app/api/ops/_liveRecordings.test.ts b/editor/app/api/ops/_liveRecordings.test.ts @@ -71,3 +71,34 @@ test("live-recording-ack acknowledges it: listed still, counted no more, and the assert.equal(rows[0]?.needsAttention, false); assert.equal(rows[0]?.acknowledgedBy, "test"); }); + +test("the attention header rides on the GET routes that check their own auth too: get job, get jobs", async () => { + await upsertLiveRecordingRow(getPaths(), SLUG, { + id: "exampleid02", + url: "https://www.youtube.com/watch?v=exampleid02", + platform: "youtube", + startedAt: new Date().toISOString(), + status: "interrupted", + stoppedBy: "shutdown", + fromStart: true, + attempts: 1, + mustKeep: true, + parts: [], + }); + (await import("./_attention")).forgetAttention(); + const job = (await import("./job/[id]/route")).GET as unknown as (r: Request, c: { params: Promise<{ id: string }> }) => Promise<Response>; + const res = await job(new Request("http://localhost/api/ops/job/nosuchjob", { headers: authed }), { params: Promise.resolve({ id: "nosuchjob" }) }); + assert.equal(res.status, 404); + assert.equal(res.headers.get("x-archilyzer-attention"), "live-recordings=1", "a 404 says it too"); + const jobs = (await import("./jobs/route")).GET as unknown as (r: Request) => Promise<Response>; + const list2 = await jobs(new Request("http://localhost/api/ops/jobs?active=1", { headers: authed })); + assert.equal(list2.headers.get("x-archilyzer-attention"), "live-recordings=1"); +}); + +test("the header's value says stalled recordings beside those that need a person", async () => { + const { attentionHeaderValue } = await import("./_attention"); + assert.equal(attentionHeaderValue(null), null); + assert.equal(attentionHeaderValue({ needsAttention: 0, stalled: 0 }), null); + assert.equal(attentionHeaderValue({ needsAttention: 2, stalled: 0 }), "live-recordings=2"); + assert.equal(attentionHeaderValue({ needsAttention: 0, stalled: 1 }), "live-recordings=0, stalled=1"); +}); diff --git a/editor/app/api/ops/channel/[slug]/route.ts b/editor/app/api/ops/channel/[slug]/route.ts @@ -15,6 +15,7 @@ import { import { getSettings } from "yt-dlp-transcript-common/lib/settings"; import { readXSearchLeads } from "yt-dlp-transcript-common/controller/xSearchLeads"; import { opsAuth } from "../../_lib"; +import { withAttention } from "../../_attention"; export const dynamic = "force-dynamic"; @@ -38,7 +39,7 @@ export const dynamic = "force-dynamic"; // largest channel here. The report's totals answer the same question from a // file, and a poll loop asking for them every few seconds must not be the thing // that hammers the platter. -export async function GET( +async function get( request: Request, { params }: { params: Promise<{ slug: string }> }, ) { @@ -122,3 +123,9 @@ export async function GET( : null, }); } + +// Every answer says what needs a person (../_attention.ts), as ops() and +// readRoute() do. +export async function GET(request: Request, ctx: { params: Promise<{ slug: string }> }) { + return withAttention(await get(request, ctx)); +} diff --git a/editor/app/api/ops/channels/route.ts b/editor/app/api/ops/channels/route.ts @@ -4,6 +4,7 @@ import { listChannelConfigs } from "yt-dlp-transcript-common/controller/channels import { isRemoteOnlyChannel, isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { siteChannelIndex } from "yt-dlp-transcript-common/lib/site"; import { opsAuth } from "../_lib"; +import { withAttention } from "../_attention"; export const dynamic = "force-dynamic"; @@ -13,7 +14,7 @@ export const dynamic = "force-dynamic"; // other channel routes, and to see which sites carry it — a channel on no site // is private to this editor. Config reads only (no report, no media probe, no // directory walk); `get channel <slug>` is the deep read of one. -export async function GET(request: Request) { +async function get(request: Request) { const denied = opsAuth(request); if (denied) return denied; const paths = getPaths(); @@ -44,3 +45,9 @@ export async function GET(request: Request) { })), }); } + +// Every answer says what needs a person (../_attention.ts), as ops() and +// readRoute() do. +export async function GET(request: Request) { + return withAttention(await get(request)); +} diff --git a/editor/app/api/ops/job/[id]/route.ts b/editor/app/api/ops/job/[id]/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from "next/server"; import { opsAuth, opsFail } from "../../_lib"; import { readJob } from "../../_jobs"; +import { withAttention } from "../../_attention"; export const dynamic = "force-dynamic"; @@ -23,7 +24,7 @@ export const dynamic = "force-dynamic"; // An id neither the registry nor `.jobs/` knows is a 404 `{ ok: false }`. const MAX_TAIL = 500; -export async function GET( +async function get( request: Request, { params }: { params: Promise<{ id: string }> }, ) { @@ -50,3 +51,9 @@ export async function GET( if (!found) return opsFail(`no job "${id}"`, 404); return NextResponse.json({ ok: true, ...found }); } + +// Every answer says what needs a person (../_attention.ts), as ops() and +// readRoute() do. +export async function GET(request: Request, ctx: { params: Promise<{ id: string }> }) { + return withAttention(await get(request, ctx)); +} diff --git a/editor/app/api/ops/jobs/route.ts b/editor/app/api/ops/jobs/route.ts @@ -2,6 +2,7 @@ import { NextResponse } from "next/server"; import { isValidChannelSlug } from "yt-dlp-transcript-common/controller/channels"; import { opsAuth, opsFail } from "../_lib"; import { listJobs } from "../_jobs"; +import { withAttention } from "../_attention"; export const dynamic = "force-dynamic"; @@ -24,7 +25,7 @@ export const dynamic = "force-dynamic"; const KEYS = ["active", "failed", "kind", "slug", "limit"]; const MAX_LIMIT = 500; -export async function GET(request: Request) { +async function get(request: Request) { const denied = opsAuth(request); if (denied) return denied; const q = new URL(request.url).searchParams; @@ -61,3 +62,9 @@ export async function GET(request: Request) { const page = await listJobs({ active, failed, kind, slug, limit }); return NextResponse.json({ ok: true, ...page }); } + +// Every answer says what needs a person (../_attention.ts), as ops() and +// readRoute() do. +export async function GET(request: Request) { + return withAttention(await get(request)); +} diff --git a/editor/app/api/ops/live-recording-ack/route.ts b/editor/app/api/ops/live-recording-ack/route.ts @@ -5,20 +5,24 @@ import { ops, opsFail, reqSlug, reqString } from "../_lib"; export const dynamic = "force-dynamic"; -// POST { slug, id, startedAt?, by? } -> { ok: true, acknowledged } +// POST { slug, id, startedAt?, by? } | { slug, file, by? } -> { ok: true, acknowledged } // // A PERSON HAS SEEN IT (controller/liveRecordings.ts): every run of the record // that needs a person — failed, interrupted, or recorded from the live edge // with the stream's start lost — or the one run `startedAt` names, is // acknowledged. The rows stay in `get live-recordings`; they no longer count // in /review, the banners or the attention header. /review's Acknowledge. +// `file` instead of `id`: a live-recordings.json that did not read and was set +// aside under that name (the listing's `files`) has been seen — it stays. export async function POST(request: Request) { - return ops(request, ["slug", "id", "startedAt", "by"], async (body) => { + return ops(request, ["slug", "id", "file", "startedAt", "by"], async (body) => { const slug = reqSlug(body, "slug"); - const id = reqString(body, "id"); + const file = typeof body.file === "string" && body.file.trim() ? body.file.trim() : undefined; + const id = file ? undefined : reqString(body, "id"); const r = await acknowledgeLiveRecordingAction({ slug, - id, + ...(id ? { id } : {}), + ...(file ? { file } : {}), ...(typeof body.startedAt === "string" ? { startedAt: body.startedAt } : {}), by: typeof body.by === "string" && body.by.trim() ? body.by.trim() : "agent:ops", }); diff --git a/editor/app/api/ops/live-recordings/route.ts b/editor/app/api/ops/live-recordings/route.ts @@ -7,11 +7,14 @@ import { opsFail } from "../_lib"; export const dynamic = "force-dynamic"; // GET [?slug=<channel>[&id=<record id>]][&all=1] -// -> { ok, needsAttention, stallMinutes, rows: [{ slug, id, url, status -// (recording | interrupted | landed | failed | cancelled), job, bytes, -// lastGrowthAt, stalled, streamElapsedSeconds, capturedSeconds, -// attempts, fallback?, lost?, error?, mustKeep, needsAttention, -// reason, check, parts, … }] } +// -> { ok, needsAttention, stalled, stallMinutes, files: [{ slug, file, +// state (set-aside | unreadable), reason, needsAttention, message }], +// rows: [{ slug, id, url, status (recording | interrupted | landed | +// failed | cancelled), job, bytes, lastGrowthAt, stalled, +// streamElapsedSeconds, capturedSeconds, coverage?, attempts, +// failureClass?, fallback?, lost?, missingStream?, keptParts?, +// stoppedBy?, error?, mustKeep, needsAttention, reason, check, +// parts (each its bytes and lastGrowthAt while recording), … }] } // // IS THIS STREAM BEING RECORDED, AND IS IT GROWING (controller/ // liveRecordings.ts): each run from its own record, never from "a job for this diff --git a/editor/app/api/ops/publish/route.ts b/editor/app/api/ops/publish/route.ts @@ -15,6 +15,7 @@ import { reqSiteIds, type OpsBody, } from "../_lib"; +import { withAttention } from "../_attention"; export const dynamic = "force-dynamic"; @@ -180,8 +181,14 @@ export async function POST(request: Request) { }); } -export async function GET(request: Request) { +async function get(request: Request) { const denied = opsAuth(request); if (denied) return denied; return NextResponse.json({ ok: true, ...(await readPublishStatus(getPaths())) }); } + +// Every answer says what needs a person (../_attention.ts), as ops() and +// readRoute() do. +export async function GET(request: Request) { + return withAttention(await get(request)); +} diff --git a/editor/app/api/ops/tags/route.ts b/editor/app/api/ops/tags/route.ts @@ -8,6 +8,7 @@ import { removeTagDefAction, } from "../../../tags/actions"; import { OpsInputError, oneOf, ops, opsAuth, opsFail } from "../_lib"; +import { withAttention } from "../_attention"; export const dynamic = "force-dynamic"; @@ -21,7 +22,7 @@ export const dynamic = "force-dynamic"; // at every index build and its hits live on the records, so the only honest // answer from a file read is "what somebody said". For the built numbers, read // a site's published /tags.json after a build. -export async function GET(request: Request) { +async function get(request: Request) { const denied = opsAuth(request); if (denied) return denied; const config = readGlobalTags(getPaths()); @@ -147,3 +148,9 @@ export async function POST(request: Request) { : opsFail(result.error); }); } + +// Every answer says what needs a person (../_attention.ts), as ops() and +// readRoute() do. +export async function GET(request: Request) { + return withAttention(await get(request)); +} diff --git a/editor/app/api/ops/trending/route.ts b/editor/app/api/ops/trending/route.ts @@ -15,6 +15,7 @@ import { readXTrendingAccounts } from "yt-dlp-transcript-common/controller/xSear import { X_TRENDING_ACCOUNTS_MAX } from "yt-dlp-transcript-common/lib/xTrending/accounts"; import { readXTrendingPublished } from "yt-dlp-transcript-common/lib/xTrending/published"; import { opsAuth, opsFail } from "../_lib"; +import { withAttention } from "../_attention"; export const dynamic = "force-dynamic"; @@ -92,7 +93,7 @@ export const dynamic = "force-dynamic"; const PARAMS = ["slug", "topic", "limit", "offset", "state", "gone", "media", "author", "q", "since", "by", "seen", "ids", "detail", "accounts"]; const FLAGS = new Set(["1", "true"]); -export async function GET(request: Request) { +async function get(request: Request) { const denied = opsAuth(request); if (denied) return denied; const sp = new URL(request.url).searchParams; @@ -212,3 +213,9 @@ export async function GET(request: Request) { } return NextResponse.json({ ok: true, slug, name: config.name ?? slug, ...listing }); } + +// Every answer says what needs a person (../_attention.ts), as ops() and +// readRoute() do. +export async function GET(request: Request) { + return withAttention(await get(request)); +} diff --git a/editor/app/channels/[slug]/liveMediaActions.ts b/editor/app/channels/[slug]/liveMediaActions.ts @@ -131,19 +131,23 @@ export async function recordLiveAction(body: Record<string, unknown>): Promise<S // the run's own url and recording keys. export async function acknowledgeLiveRecordingAction(body: { slug: string; - id: string; + id?: string; + // A set-aside live-recordings.json (the listing's `files`), by its name. + file?: string; startedAt?: string; by?: string; }): Promise<{ ok: true; acknowledged: number } | { ok: false; error: string }> { if (!isValidChannelSlug(body.slug)) return { ok: false, error: `"${body.slug}" is not a channel slug` }; - if (!/^[\w.-]+$/.test(body.id)) return { ok: false, error: `"${body.id}" is not a record id` }; + if (body.file !== undefined) { + if (!/^live-recordings\.json\.corrupt-[\w-]+$/.test(body.file)) return { ok: false, error: `"${body.file}" is not a set-aside live-recordings file` }; + } else if (!body.id || !/^[\w.-]+$/.test(body.id)) return { ok: false, error: `"${body.id ?? ""}" is not a record id` }; const r = await acknowledgeLiveRecording(getPaths(), { slug: body.slug, - id: body.id, + ...(body.file !== undefined ? { file: body.file } : { id: body.id! }), ...(body.startedAt ? { startedAt: body.startedAt } : {}), by: body.by ?? "editor", }); - if (r.ok) safeRevalidate(["/review", "/jobs", `/channels/${body.slug}`, `/channels/${body.slug}/videos/${body.id}`]); + if (r.ok) safeRevalidate(["/review", "/jobs", `/channels/${body.slug}`, ...(body.id ? [`/channels/${body.slug}/videos/${body.id}`] : [])]); return r; } diff --git a/editor/app/components/LiveRecordingActions.tsx b/editor/app/components/LiveRecordingActions.tsx @@ -15,13 +15,17 @@ export function LiveRecordingActions({ slug, id, startedAt, + file, canRecordAgain, }: { slug: string; - id: string; - startedAt: string; + // A recording's run (id + startedAt), or a set-aside live-recordings.json. + id?: string; + startedAt?: string; + file?: string; canRecordAgain: boolean; }): React.ReactNode { + const what = file ?? `${slug}/${id ?? ""}`; const [pending, startTransition] = useTransition(); const [said, setSaid] = useState<{ error: boolean; text: string } | null>(null); const press = (fn: () => Promise<{ ok: boolean; error?: string } & Record<string, unknown>>, done: (r: Record<string, unknown>) => string) => @@ -36,23 +40,29 @@ export function LiveRecordingActions({ const btn = "rounded-md border border-border px-2 py-1 text-xs hover:bg-muted disabled:opacity-50"; return ( <span className="flex items-center gap-2 flex-wrap"> - {canRecordAgain && ( + {canRecordAgain && id && ( <button type="button" - aria-label={`record ${slug}/${id} again`} + aria-label={`record ${what} again`} disabled={pending} className={btn} - onClick={() => press(() => recordLiveAgainAction({ slug, id, startedAt }), (r) => `Recording: job ${String(r.jobId)}`)} + onClick={() => press(() => recordLiveAgainAction({ slug, id, ...(startedAt ? { startedAt } : {}) }), (r) => `Recording: job ${String(r.jobId)}`)} > Record again </button> )} <button type="button" - aria-label={`acknowledge ${slug}/${id}`} + aria-label={`acknowledge ${what}`} disabled={pending} className={btn} - onClick={() => press(() => acknowledgeLiveRecordingAction({ slug, id, startedAt }), () => "Acknowledged")} + onClick={() => + press( + () => + acknowledgeLiveRecordingAction(file ? { slug, file } : { slug, ...(id ? { id } : {}), ...(startedAt ? { startedAt } : {}) }), + () => "Acknowledged", + ) + } > Acknowledge </button> diff --git a/editor/app/components/LiveRecordingsAttention.tsx b/editor/app/components/LiveRecordingsAttention.tsx @@ -1,10 +1,18 @@ import Link from "next/link"; import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { listLiveRecordings, type LiveRecordingView } from "yt-dlp-transcript-common/controller/liveRecordings"; +import { + listLiveRecordings, + type LiveRecordingView, + type LiveRecordingsFileProblem, +} from "yt-dlp-transcript-common/controller/liveRecordings"; import { LiveRecordingActions } from "./LiveRecordingActions"; // LIVE RECORDINGS THAT NEED A PERSON (controller/liveRecordings.ts): failed, -// interrupted, or recorded from the live edge with the stream's start lost. +// interrupted, cancelled when must-keep, recorded from the live edge with the +// stream's start lost, one stream missing, parts kept on disk not landed — and +// every recording that runs but has STOPPED GROWING (stalled: said here as a +// failure is, with no Acknowledge, since it clears itself when the files grow +// or the run ends), and a live-recordings.json that did not read. // One component for the four places it is said — /review's section, and the // banners on /jobs, the channel page and the video page (narrowed by `slug`, // `id`) — so all four say the same sentence. It stays until a person presses @@ -40,7 +48,30 @@ function Row({ r }: { r: LiveRecordingView }) { </span> </span> <span>{r.reason}</span> - <LiveRecordingActions slug={r.slug} id={r.id} startedAt={r.startedAt} canRecordAgain={r.status !== "recording" && Boolean(r.url)} /> + {r.keptParts && r.keptParts.length > 0 ? ( + <ul className="text-xs text-muted-foreground"> + {r.keptParts.map((k) => ( + <li key={k.stem}> + kept: <code>{k.stem}</code> · {Math.round(k.bytes / 1024 / 1024)} MB · {k.why} + </li> + ))} + </ul> + ) : null} + {r.needsAttention ? ( + <LiveRecordingActions slug={r.slug} id={r.id} startedAt={r.startedAt} canRecordAgain={r.status !== "recording" && Boolean(r.url)} /> + ) : null} + </li> + ); +} + +function FileRow({ f }: { f: LiveRecordingsFileProblem }) { + return ( + <li + aria-label={`live recordings file ${f.slug}/${f.file}`} + className="flex flex-col gap-1 border-t border-destructive/30 pt-2 first:border-t-0 first:pt-0" + > + <span>{f.message}</span> + {f.state === "set-aside" ? <LiveRecordingActions slug={f.slug} file={f.file} canRecordAgain={false} /> : null} </li> ); } @@ -56,13 +87,17 @@ export async function LiveRecordingsAttention({ heading?: boolean; }) { let rows: LiveRecordingView[]; + let files: LiveRecordingsFileProblem[]; try { - rows = (await listLiveRecordings(getPaths(), { ...(slug ? { slug } : {}), ...(id ? { id } : {}) })).rows.filter((r) => r.needsAttention); + const l = await listLiveRecordings(getPaths(), { ...(slug ? { slug } : {}), ...(id ? { id } : {}) }); + rows = l.rows.filter((r) => r.needsAttention || r.stalled); + files = l.files.filter((f) => f.needsAttention); } catch { return null; } - if (rows.length === 0) return null; - const title = `Live recordings that need you (${rows.length})`; + if (rows.length === 0 && files.length === 0) return null; + const stalled = rows.filter((r) => r.stalled).length; + const title = `Live recordings that need you (${rows.length + files.length}${stalled ? `, ${stalled} not growing` : ""})`; return ( <section aria-label="live recordings that need you" @@ -75,6 +110,9 @@ export async function LiveRecordingsAttention({ {rows.map((r) => ( <Row key={`${r.slug}/${r.id}/${r.startedAt}`} r={r} /> ))} + {files.map((f) => ( + <FileRow key={`${f.slug}/${f.file}`} f={f} /> + ))} </ul> <span className="text-xs text-muted-foreground"> <code>pnpm ops get live-recordings</code> lists every recording; <code>pnpm ops live-recording-ack</code> is Acknowledge. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -1198,13 +1198,21 @@ export function previewUrlsIn(payload) { } // WHAT NEEDS A PERSON, said on every reply (editor/app/api/ops/_attention.ts): -// the header `x-archilyzer-attention: live-recordings=<N>` becomes one stderr -// line, so an agent that only ever reads replies still hears of a live -// recording that failed, was interrupted or lost its start. Null when N is 0. +// the header `x-archilyzer-attention: live-recordings=<N>[, stalled=<M>]` +// becomes one stderr line, so an agent that only ever reads replies still +// hears of a live recording that failed, was interrupted, lost its start or +// kept parts — and of one that runs and has stopped growing. Null when both +// are 0. export function attentionLine(headerValue) { const m = /live-recordings=(\d+)/.exec(headerValue ?? ""); + const st = /stalled=(\d+)/.exec(headerValue ?? ""); const n = m ? Number(m[1]) : 0; - return n > 0 ? `! ${n} live recording${n === 1 ? " needs" : "s need"} you: pnpm ops get live-recordings` : null; + const s = st ? Number(st[1]) : 0; + if (n <= 0 && s <= 0) return null; + const said = []; + if (n > 0) said.push(`${n} live recording${n === 1 ? " needs" : "s need"} you`); + if (s > 0) said.push(`${s} live recording${s === 1 ? " is" : "s are"} NOT growing (stalled)`); + return `! ${said.join("; ")}: pnpm ops get live-recordings`; } // --wait-started: how often the recording is asked after, and for how long by @@ -1212,24 +1220,52 @@ export function attentionLine(headerValue) { export const WAIT_STARTED_POLL_MS = 10_000; export const WAIT_STARTED_DEFAULT_SECONDS = 15 * 60; -// One poll's verdict on the run's row: {ok: true} once media bytes are being -// written (more than the poll before saw) or it landed; {ok: false, reason} -// once it failed, was cancelled or interrupted; null: ask again. +// The exit of `record-live --wait-started` when the recording runs, but only +// from the live edge: the stream's start is lost (not a success, and not the +// failure exit 1 is). +export const WAIT_STARTED_EDGE_ONLY_EXIT = 3; + +// The bytes that count as "started": a run asked from its start counts only +// its FROM-START parts (the listing gives each part's bytes while it +// records); a run asked from now (fromStart: false) counts every part. +export function startedBytes(row) { + if (!row) return null; + if (row.fromStart === false) return typeof row.bytes === "number" ? row.bytes : null; + if (Array.isArray(row.parts) && row.parts.some((p) => typeof p?.bytes === "number")) { + return row.parts.filter((p) => p?.fromStart).reduce((n, p) => n + (typeof p.bytes === "number" ? p.bytes : 0), 0); + } + return row.fallback === "live-edge" ? 0 : typeof row.bytes === "number" ? row.bytes : null; +} + +// One poll's verdict on the run's row: +// {ok: true} a from-start part's bytes grew since the poll +// before (a run asked from now: any part's), or +// it landed from its start +// {ok: false, edgeOnly: true} it records (or landed) from the live edge +// only: the stream's start is lost +// (WAIT_STARTED_EDGE_ONLY_EXIT) +// {ok: false, reason} it failed, was cancelled or interrupted +// null ask again export function startedVerdict(row, prevBytes) { if (!row) return null; if (row.status === "failed" || row.status === "cancelled" || row.status === "interrupted") { return { ok: false, reason: row.reason ?? row.status }; } - if (row.status === "landed") return { ok: true }; - if (typeof row.bytes === "number" && row.bytes > 0 && prevBytes !== null && row.bytes > prevBytes) return { ok: true }; + const edgeOnly = row.fromStart !== false && row.fallback === "live-edge"; + const edgeReason = () => `recording from the live edge only: the stream's start is LOST — ${row.reason ?? row.status}`; + if (row.status === "landed") return edgeOnly ? { ok: false, edgeOnly: true, reason: edgeReason() } : { ok: true }; + const now = startedBytes(row); + if (now !== null && now > 0 && prevBytes !== null && now > prevBytes) return { ok: true }; + if (edgeOnly && typeof row.bytes === "number" && row.bytes > 0) return { ok: false, edgeOnly: true, reason: edgeReason() }; return null; } // RECORD-LIVE --wait-started: returns once the recording's own row (the run // whose jobId the reply named, in `get live-recordings`) shows media bytes -// growing — or fails with the reason it gives. A job that ends with no row -// at all (a refusal before the recording) fails with the job's status. -// Answers {ok, row?, reason?}. +// growing (a FROM-START part's, when it was asked from its start) — or fails +// with the reason it gives, `edgeOnly` when it records from the live edge only +// (the start lost). A job that ends with no row at all (a refusal before the +// recording) fails with the job's status. Answers {ok, edgeOnly?, row?, reason?}. export async function waitStarted(reply, slug, opts = {}) { const doFetch = opts.fetch ?? fetch; const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))); @@ -1271,7 +1307,7 @@ export async function waitStarted(reply, slug, opts = {}) { const line = `[${reply.jobId}] ${row.reason}`; if (line !== lastSaid) say(line); lastSaid = line; - prevBytes = typeof row.bytes === "number" ? row.bytes : prevBytes; + prevBytes = startedBytes(row) ?? prevBytes; } if (now() >= deadline) { return { ok: false, row, reason: `--wait-started: no media bytes after ${seconds} s (${reply.check})` }; @@ -2532,33 +2568,48 @@ export function usage() { ' "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\") is tried again at +60 and +180 s, then from the live edge at", - " 0, +60 and +180 s (each wait jittered); a stream that has ended, an argv", - " no try can fix and a Cancel are not retried. A live-edge fallback says", - " what it lost (the first N min of the stream) and needs a person. The", - ' reply is {jobId, kind, "check"}: the `get live-recordings` command that', - " answers for it. --wait-started returns once media bytes are being", - " written (the recording's row on stdout, exit 0) or with the reason it", - " failed (exit 1); 15 minutes by default, --wait-timeout overrides.", + " 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.", "", "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", " id (a live-chat job is one too). Per run, from its own record: status", - " (recording | interrupted: no job runs it | landed | failed | cancelled),", - " job, bytes, lastGrowthAt, stalled (not grown for", + " (recording | interrupted: no job runs it, or the editor shut down |", + " landed | failed | cancelled), job, bytes, lastGrowthAt, parts (each its", + " bytes and lastGrowthAt while recording), stalled (not grown for", " settings.liveRecording.stallMinutes, 10), streamElapsedSeconds,", - " capturedSeconds (once landed), attempts, fallback, lost, error, mustKeep,", - " needsAttention, reason, check. Default: what is recording, what needs a", - " person, the last 7 days; --all every run kept", + " capturedSeconds (once landed), coverage, attempts, failureClass,", + " fallback, lost, 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", " (channels/<slug>/live-recordings.json, never pruned of a failure).", - " needsAttention (failed, interrupted, or the stream's start lost) stays", - " until live-recording-ack or a later recording that lands from the start;", - " /review, /jobs, the channel and video pages show the same rows, and", - " every ops reply then prints \"! N live recordings need you\" on stderr.", + " needsAttention — failed, interrupted, cancelled when must-keep, the", + " stream's start lost, a stream missing, parts kept — stays until", + " live-recording-ack, or (all but kept parts) a later recording that lands", + " the WHOLE stream from its start; /review, /jobs, the channel and video", + " 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-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. /review's Acknowledge.", + ' listed still, counted no more. {"slug", "file"} acknowledges a set-aside', + " live-recordings.json (it stays where it is). /review's Acknowledge.", "", 'live-preclip transcribes and mines a recording WHILE it records: {"slug",', ' "id", "action"?: "start" (default) | "stop" | "status" | "finalize"}, and', @@ -3621,7 +3672,7 @@ async function main() { if (r.row) console.log(JSON.stringify(r.row, null, 2)); if (!r.ok) console.error(r.reason); else if (!r.row) console.error(`[${payload.jobId}] done`); - return r.ok ? 0 : 1; + return r.ok ? 0 : r.edgeOnly ? WAIT_STARTED_EDGE_ONLY_EXIT : 1; } if (!parsed.wait) { printPreviewUrls(payload); diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -23,6 +23,8 @@ import { parseDotenv, previewUrlsIn, startedVerdict, + startedBytes, + WAIT_STARTED_EDGE_ONLY_EXIT, tokenHint, usage, waitStarted, @@ -1225,6 +1227,11 @@ test("the attention header becomes one stderr line, only when something needs a assert.equal(attentionLine("live-recordings=0"), null); assert.equal(attentionLine("live-recordings=1"), "! 1 live recording needs you: pnpm ops get live-recordings"); assert.equal(attentionLine("live-recordings=3"), "! 3 live recordings need you: pnpm ops get live-recordings"); + assert.equal(attentionLine("live-recordings=0, stalled=1"), "! 1 live recording is NOT growing (stalled): pnpm ops get live-recordings"); + assert.equal( + attentionLine("live-recordings=2, stalled=3"), + "! 2 live recordings need you; 3 live recordings are NOT growing (stalled): pnpm ops get live-recordings", + ); }); test("startedVerdict: growing bytes or a landing is started; failed, cancelled, interrupted are not", () => { @@ -1237,6 +1244,40 @@ test("startedVerdict: growing bytes or a landing is started; failed, cancelled, assert.equal(startedVerdict({ status: "interrupted", reason: "interrupted" }, 5).ok, false); }); +test("startedVerdict: only a FROM-START part's growth is started; a live-edge fallback is edge-only (the start is lost)", () => { + const edge = { + status: "recording", + fromStart: true, + fallback: "live-edge", + bytes: 9000, + reason: "recording from the live edge: the first 2 h 0 min of the stream are NOT recorded", + parts: [ + { fromStart: true, bytes: 0 }, + { fromStart: false, bytes: 9000 }, + ], + }; + assert.equal(startedBytes(edge), 0); + const v = startedVerdict(edge, 0); + assert.equal(v.ok, false); + assert.equal(v.edgeOnly, true); + assert.match(v.reason, /start is LOST/); + assert.equal(startedVerdict({ ...edge, status: "landed" }, null).edgeOnly, true, "a landing from the live edge is not a success either"); + const fs = { status: "recording", fromStart: true, bytes: 900, parts: [{ fromStart: true, bytes: 900 }] }; + assert.deepEqual(startedVerdict(fs, 400), { ok: true }); + assert.equal(startedVerdict(fs, 900), null, "not grown"); + // Asked from now: any part's growth is the start it asked for. + assert.deepEqual(startedVerdict({ status: "recording", fromStart: false, bytes: 900, parts: [{ fromStart: false, bytes: 900 }] }, 100), { ok: true }); +}); + +test("record-live --wait-started on a live-edge fallback: not ok, edgeOnly (exit 3), with the reason", async () => { + const edgeRow = { jobId: "job-1", status: "recording", fromStart: true, fallback: "live-edge", bytes: 5000, reason: "recording from the live edge", parts: [{ fromStart: false, bytes: 5000 }] }; + const ed = fakeLiveEditor([[{ jobId: "job-1", status: "recording", fromStart: true, bytes: 0, reason: "recording", parts: [] }], [edgeRow]]); + const r = await waitStarted(reply, "demo-yt", { ...quiet, fetch: ed.fetch }); + assert.equal(r.ok, false); + assert.equal(r.edgeOnly, true); + assert.equal(WAIT_STARTED_EDGE_ONLY_EXIT, 3); +}); + // A fake editor: the listing answers the rows given per poll, in turn. function fakeLiveEditor(listings, job = { status: "running" }) { let n = 0;