Archilyzer · Source

archilyzer

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

commit 25156ab10ca6c9fd32d7e8a54b00776a7bacd9cb
parent 909d54e1d9c88e61d0fd40b43a3301cf4e935ca1
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 06:16:46 -0500

Merge lane/clean-unverified: clean audio without checking, and a rate-limited clean that retries

"Clean audio without checking" removes transcribed audio without asking the source, after a counted
confirmation, and removes only what was confirmed; a per-channel key makes every clean on that channel
unchecked. No clean whose availability check did not complete prunes a saved video. A checked clean
the source rate-limits ends deferred and retries off the queue, twice at most.

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

Diffstat:
MCHANNEL.md | 1+
MCOMMANDS.md | 4++--
MOPERATING.md | 58++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/channels.ts | 10+++++++++-
Mcommon/controller/cleanAudioFromTranscribed.ts | 252++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------
Acommon/controller/cleanAudioJob.test.ts | 382+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/cleanAudioJob.ts | 316+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/cleanReplay.test.ts | 223+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/cleanRetrySchedule.test.ts | 267+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/cleanRetrySchedule.ts | 359+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/cleanUnchecked.test.ts | 540+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/verifyBeforeClean.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/jobs/bootQueuedJobs.test.ts | 27+++++++++++++++++++++++++++
Mcommon/jobs/bootQueuedJobs.ts | 16++++++++++++++--
Mcommon/jobs/jobDetail.test.ts | 6++++++
Mcommon/jobs/jobDetail.ts | 9+++++++++
Mcommon/jobs/jobKinds.test.ts | 24++++++++++++++++++++++++
Mcommon/jobs/jobKinds.ts | 34++++++++++++++++++++++++++++++++++
Mcommon/jobs/registry.ts | 4+++-
Mcommon/lib/channelConfig.ts | 6++++++
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
Acommon/lib/cleanAudioConfirm.test.ts | 34++++++++++++++++++++++++++++++++++
Acommon/lib/cleanAudioConfirm.ts | 43+++++++++++++++++++++++++++++++++++++++++++
Mcommon/views/cleanable.ts | 4++++
Mcommon/views/pipeline/stageStatus.ts | 2++
Meditor/CHANGELOG.md | 30++++++++++++++++++++++++++++++
Meditor/app/api/ops/_writes.test.ts | 31+++++++++++++++++++++++++++++++
Meditor/app/api/ops/channel-config/route.ts | 19+++++++++++++++----
Meditor/app/api/ops/cleanup/route.ts | 48++++++++++++++++++++++++++++++++++++++++++++++--
Aeditor/app/channels/[slug]/cleanRetryScheduler.ts | 78++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aeditor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx | 217+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/channels/[slug]/components/stages/CleanupStage.tsx | 59+++++++++++++++++++++++++++++++++++++++++++----------------
Meditor/app/channels/[slug]/page.tsx | 6++++++
Meditor/app/channels/[slug]/whisperActions.ts | 194++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Meditor/app/channels/actions.ts | 25+++++++++++++++++++++++++
Meditor/app/cleanup/components/ChannelCleanupCard.tsx | 31++++++++++++++++++++++---------
Meditor/app/cleanup/lib/loadCleanup.ts | 9++++++++-
Meditor/app/cleanup/page.tsx | 1+
Meditor/app/components/actions/InlineActionButton.tsx | 62+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Meditor/app/components/channelWork/sections.tsx | 6+++++-
Meditor/app/jobs/actions.ts | 8+++++++-
Meditor/app/jobs/components/JobRow.tsx | 7+++++++
Meditor/app/jobs/jobReplayRegistry.ts | 26++++++++++++++++++++++----
Meditor/app/widget/components/MonitorWidget.tsx | 2+-
Meditor/instrumentation.ts | 13+++++++++++++
Mscripts/archilyzer-ops.mjs | 23++++++++++++++++++++---
47 files changed, 3475 insertions(+), 99 deletions(-)

diff --git a/CHANNEL.md b/CHANNEL.md @@ -45,6 +45,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f | `excludeFromCleanup` | config | Leave this channel's reclaimable bytes out of the aggregate "cleanable data" total on /cleanup and its badge. The per-channel cleanup sweeps stay available; only the running total changes. | | `excludeFromCompaction` | config | Keep this channel's saved videos out of compaction (`compact-saved-videos`, a re-encode to AV1 that becomes the active copy): neither the selector nor an explicit list touches them. For a channel whose stored bytes are kept as evidence. Absent = false. | | `cleanAfterCaptureUnverified` | config | Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel ("no source to check: clean by hand") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held. | +| `cleanAudioWithoutChecking` | config | Every clean of this channel's transcribed audio runs WITHOUT the availability check: the Clean audio button, the /cleanup row, `pnpm ops cleanup` and clean after capture alike ask the source nothing, so the audio of a video no longer available anywhere is removed too (it is no longer pinned do-not-clean). Every other protection holds: do-not-clean marks, the keep-latest window, the speaker holds (awaiting diarization / voice fingerprint), untranscribed videos, an unreachable or moving media drive. Those jobs run as "Clean audio without checking"; the key is read again when each starts, and a saved video container is never pruned by them. The buttons (Cleanup stage, /cleanup, the dashboard) show a count first; these run unchecked with NO count, the key being the standing consent: clean after capture, `pnpm ops cleanup` with no `unchecked` flag, a /jobs Retry, Retry all failed or `pnpm ops job retry` of a clean of this channel, and the boot's re-queue of one a restart caught queued (titled "Clean audio without checking · channel setting"). A rate-limited clean's retry stays checked; no other automatic lane runs a channel clean. A replayed confirmed clean without checking needs its carried plan, and none replays unchecked once the key is off. A new channel never starts with it (createChannel drops it). For a platform whose VODs expire by design (Twitch, Kick), where "gone from the source" is the normal state; never set by platform. Absent/false = checked. Set on the channel's Cleanup stage or with `pnpm ops channel-config {"cleanAudioWithoutChecking": true}`. | | `syncIntervalMinutes` | config | Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. AN INSTAGRAM CHANNEL is synced seldom, because every sync is a logged-in read: absent = every 12 hours at the most often (the global default when that is longer), and a value of its own is never under 240 (4 hours); 0 still turns it off (`common/jobs/syncScheduler.ts`). | | `fullSweepIntervalMinutes` | config | Full-sweep cadence: a sync upgrades itself to a full sweep when `now - lastFullSweepAt >= fullSweepIntervalMinutes`. Absent = inherit `syncScheduler.fullSweepIntervalMinutes`; 0 = never sweep (every sync is a paged walk); positives clamp to [1, 44640]. | | `skipLiveDownloads` | config | Per-channel override for the global `skipLiveDownloads`. Absent = inherit; false = allow downloading currently-live / upcoming videos. | diff --git a/COMMANDS.md b/COMMANDS.md @@ -128,7 +128,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) |---|---|---| | `channel-priority` | channel-priority sets channels' priority, as the /channels deck's tier control does: {"slugs", "tier": "normal" \| "low" \| "paused"} sets the base tier; with "operation" (sync, transcription, download, digest, backfill) it pins that operation's tier, "tier": null clearing it back to the base; "preset": "sync-only" \| "clear" is the deck's two shortcuts and takes no tier. A manual change clears an automatic pause. {"focus": {"kind": "site", "siteId"} \| {"kind": "channels", "slugs"} \| {"kind": "none"}} alone is the deck's focus bar: those channels lead every lane (a site focus follows its membership); "none" ends it. | `pnpm ops channel-priority --json '{"slugs":["x"],"operation":"download","tier":"paused"}'`<br>`pnpm ops channel-priority --json '{"focus":{"kind":"site","siteId":"x"}}'` | | `channel-rank` | channel-rank places one channel in the order every lane and the sync scheduler follow inside a tier (one rank per channel, 0 first; unranked channels come after every ranked one, by slug): {"slug"} and exactly one of "rank": &lt;n&gt; (before any channel holding it) or null (unranked), "top": true, "bottom": true, "before": "&lt;slug&gt;", "after": "&lt;slug&gt;" (a ranked channel; immediately next to it, a tie on its rank included). The channels after it move down only as far as they must. Only the rank moves — no tier, override or lane changes, unlike /channels' "Add to top". Refused: an unknown channel, an unranked anchor, a channel paused for every operation. Answers {slug, rank, order: \[{slug, rank}, …\]}. | `pnpm ops channel-rank --json '{"slug":"x","top":true}'`<br>`pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'`<br>`pnpm ops channel-rank --json '{"slug":"x","rank":null}'` | -| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild" and "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "&lt;slug&gt;, &lt;slug&gt;"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). Manual downloads: "patch": {"downloadMode": "manual"} — only videos you add (import-video, the video page) are downloaded; the download lane, a sync's new uploads and download-missing leave the channel alone; "" (or "auto") is automatic (CHANNEL.md, downloadMode). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'` | +| `channel-config` | channel-config changes a channel as its Configure form does: {"slug"} and any of "patch" (form field names; "" clears one), "sites" (the WHOLE membership set: \[{"siteId", "groupId"? \| "newGroupName"?}\], \[\] = on no site; an unknown site id is refused), "excludeFromBuild", "excludeFromCleanup" and "cleanAudioWithoutChecking" (every clean of the channel skips the availability check; set to the value given, not toggled). A VOD mirror's recorded date: "patch": {"recordedDateTitlePattern": "&lt;regex with named groups year, month, day&gt;"} (CHANNEL.md, recordedDate). A mirror's creator channels: "patch": {"mirrorOf": "&lt;slug&gt;, &lt;slug&gt;"} (CHANNEL.md, mirror; then mirror-scan). Caption languages and the live chat: "patch": {"subLangs": "en.\*", "chat": "with-download" \| "later" \| "never"} (CHANNEL.md, subLangs and chat). Manual downloads: "patch": {"downloadMode": "manual"} — only videos you add (import-video, the video page) are downloaded; the download lane, a sync's new uploads and download-missing leave the channel alone; "" (or "auto") is automatic (CHANNEL.md, downloadMode). | `pnpm ops channel-config --json '{"slug":"demo-yt","patch":{"chat":"later","subLangs":"en.*"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadFilterExclude":"rerun"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}'`<br>`pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}'`<br>`pnpm ops channel-config --json '{"slug":"x","cleanAudioWithoutChecking":true}'` | | `create-site` | create-site is the New site form: {"siteId", "siteTitle"} and any of its fields — "headerTitle" (default the title), "siteDescription", "homeTagline", "wordmarkLead", "accent" (an id or "#rrggbb"), "siteUrl", "cloudflareProject", "hubUrl", "audience" ("private" \| "public"; default PRIVATE), "listed" (default FALSE), "publishAuto", "search", "archives", "duplicates", "transcriptDownloads", "pwa", "archiveMaxMB" (null = the global default), "groups" (\[{"id", "name", "selectedByDefault"?, "description"?, "inline"?}\]), "defaultGroupId", "channels" (slugs, or {"slug", "groupId"?}: the pool), "citedChannels" (slugs), "socialLinks" (\[{"label", "url", "svg"}\], null = inherit), "relatedSites". Saved by the form's action (its validation, its sentences). An existing id is refused (409) unless "update": true — the site page's Save with the keys given changed, every other key kept — one read-modify-write under the site's lock. An unknown channel, or a channel's groupId naming no group of the site, is refused. Answers {siteId, created, site}. | `pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}'`<br>`pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}'` | | `site-config` | site-config sets two keys of a site as its form does: {"siteId"} and any of "citedChannels" (the WHOLE cited scope, channel slugs: what the site's reports may cite without publishing the channel; \[\] clears it; a slug the pool holds is dropped) and "publishAuto" ("off" \| "build" \| "preview" \| "production", the publish lane's policy; a deploying one needs a Pages project, a private site is clamped to "build"). Only those two keys; an unknown site or channel is refused before anything is written. Answers the saved values. | `pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}'`<br>`pnpm ops site-config --json '{"siteId":"anilyzer","publishAuto":"build"}'` | | `articles-config` | articles-config sets an article's audience and its place in the published list (transcripts/reports/index.json), through the article registry: {"id"} and any of "audience" ("public" \| "private"; absent in report.json = private), "published" (true = listed, false = a draft) and "position" (its place in the list, 0 = first; publishing with none keeps a listed article where it is, else puts it last). Refused before anything is written: an unknown article, a position on a draft or out of range, publishing an article whose report.json has problems (listed). Answers the article as saved. | `pnpm ops articles-config --json '{"id":"demo-article","published":true}'`<br>`pnpm ops articles-config --json '{"id":"demo-article","audience":"public","position":0}'` | @@ -206,7 +206,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `delete-file` | delete-file deletes one file of one video, as its Files list does: {"slug", "id", "file"}. A tiered media file goes with its bytes on the media drive (never a bare link); refused while that drive is not answering. No undo. A raw live chat named in one form while the other is there (transcript.live\_chat.json and its .zst): only the named one goes, never the other, and "note" says the other is still there. | | | `do-not-clean` | do-not-clean sets one video's "Do not clean" marker: {"slug", "id", "keep"?: true}; "keep": false removes it. (keep-videos is the bulk form.) | | | `drop-saved-alternate` | drop-saved-alternate deletes one saved alternate of one video, as its "Drop this alternate" button does: {"slug", "id", "file", "dryRun"?}. "file" is a name `get saved-alternates` lists under "alternates"; the active copy, an unlisted name and any path are refused, and so is a store being moved. The file goes from the store and its entry from saved-video.json (the rest of the pointer is untouched); one already gone is cleaned from the pointer ("existed": false). "dryRun": true answers the same and changes nothing. No undo. An ORIGINAL ("keptAs": "original", the source of a compacted copy) needs "confirmOriginal": true; the compacted copy is read back from disk (size, sha256, container, length) before it goes; a video not freshly checked on its platform needs a review of this copy recorded first; and nothing goes while a download or persist of the video is queued or running, or while it is being compacted. A FORMER original ("former-original") needs its own "confirmFormerOriginal": true, and the same gone/review rule. | | -| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait` | +| `cleanup` | cleanup runs one of a channel's cleanup sweeps as a job: {"slug", "sweep": "transcribed" (audio of transcribed videos — the /cleanup total) \| "extra-formats" \| "wrong-format" \| "failed-transcriptions" (clears the list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup <slug>` says what each would reclaim. "unchecked": true (transcribed only) is "Clean without checking": the source is not asked, so the audio of videos no longer available anywhere goes too; every other protection holds; the job is "Clean audio without checking". With "dryRun": true it answers what it would remove — {plan: {ids, videos, files, bytes, protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and starts nothing; without it the plan is counted at the call, its counts answered ({jobId, plan}) and logged, and the job removes at most those videos' audio. It never touches a saved video. With the channel's cleanAudioWithoutChecking on, "transcribed" with no flag runs unchecked with no count (so do job retry and retry-failed of a clean). A checked clean the source rate-limits ends deferred and schedules a retry off the queue after at least 15 min (twice at most), then gives up; `job cancel <the deferred job id>` cancels the retry. | `pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait`<br>`pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'` | | `diarize` | diarize runs a channel's "Diarize speakers" as a job: {"slug"}. Every video still holding audio with no current diarization.json is diarized, and a diarized one without voice fingerprints gets them from its own turns — the voiceprint backfill, one channel at a time. Runs while the Speakers lane is paused; nothing is deleted. | `pnpm ops diarize --json '{"slug":"x"}' --wait` | | `web-search` | web-search searches the web (DuckDuckGo's HTML page) and answers the results: {"query", "n"?: 6 (at most 20)} -&gt; {results: \[{title, url, snippet}\]}. Read only, through the editor's one web queue: one request at a time, 3 s apart, backing off on a 429 or 503. For context; a web page is never cited as what someone said. | `pnpm ops web-search --json '{"query":"second shop opening","n":5}'` | | `web-fetch` | web-fetch reads one web page as plain text: {"url", "maxChars"?: 12000 (at most 60000)} -&gt; {page: {url, finalUrl, status, contentType, title?, text, truncated}}. http and https only; a private or loopback host (by name, by address, or by what its name resolves to, every redirect checked) is refused before any request, and so is a page that is not text (a PDF, an image). Read only, on the same web queue as web-search. | `pnpm ops web-fetch --json '{"url":"https://example.com/news/item","maxChars":4000}'` | diff --git a/OPERATING.md b/OPERATING.md @@ -1096,6 +1096,64 @@ pnpm ops diarize --json '{"slug":"example"}' --wait # one channe decode is recorded in `audio-integrity.json` and skipped until a different file is there. - **A render gets the cores**: render mode holds the Speakers lane with transcription and download. +## Clean audio without checking + +```sh +pnpm ops cleanup --json '{"slug":"example","sweep":"transcribed","unchecked":true,"dryRun":true}' # what it would remove +pnpm ops cleanup --json '{"slug":"example","sweep":"transcribed","unchecked":true}' --wait # Clean without checking +pnpm ops channel-config --json '{"slug":"example","cleanAudioWithoutChecking":true}' # always, for this channel +``` + +- **Clean audio checks first**: before deleting a transcribed video's audio it asks the source whether the video is + still there (`verifyAvailabilityBeforeClean`), and pins one that is gone as do-not-clean. On Twitch and Kick VODs + expire by design, so "gone" is the normal state there and the check keeps audio nobody wants kept. +- **Clean without checking** (the Cleanup stage, `"unchecked": true`) skips that check and asks the source nothing, so + the audio of videos no longer available anywhere is removed too. Every other protection holds: do-not-clean, the + keep-latest window, awaiting diarization or voice fingerprint, untranscribed videos, and a media drive that is + unreachable or being moved (asked again immediately before anything is removed). It never touches a saved video: + the saved-video retention prune runs only in a checked Clean audio whose availability check completed — never in an + unchecked one, and never after a check the source rate-limited or that failed (on the first run and every retry). The page counts first (`dryRun`: files, bytes, + videos, what it keeps, and the video `ids`) and asks: "Remove N audio files (X) from M transcribed videos without + checking? The source is not asked, so the audio of videos no longer available anywhere is removed too." The job + carries those ids and removes **at most** them: a video protected since is skipped, one that became eligible since + is left for the next run ("not in the confirmed plan" in its log). Over ops, a call without `dryRun` counts at the + call and carries that plan. The job is titled "Clean audio without checking". A Retry of it, or a restart that + caught it queued, runs it again with its carried plan only; with no plan it removes nothing and ends failed, + "Confirmed plan lost; confirm again" (on a key-off channel a replay of it is refused instead). The `cleanup` reply + answers the plan's counts, and the job's log states them before anything is removed. +- **`cleanAudioWithoutChecking`** on a channel (CHANNEL.md; the Cleanup stage's checkbox, which asks before turning it + on) makes every clean of it unchecked: Clean audio, the /cleanup card, the dashboard's buttons, `cleanup` over ops + and clean after capture. Each button then shows the same counted confirmation and carries its plan. **With the key + on, these run unchecked with no count** — the key is the operator's standing consent for the channel: clean after + capture, a `cleanup` call with no `unchecked` flag, a /jobs **Retry**, **Retry all failed** or `pnpm ops job retry` + of a clean of the channel, and the boot's re-queue of one a restart caught queued. Each discovers when it starts and + is titled "Clean audio without checking · channel setting", its first log line "Clean without checking (channel + setting): …". A rate-limited clean's retry stays checked; no other automatic lane runs a channel clean. A replayed + confirmed "Clean without checking" (· confirmed count) runs again only with its carried plan, and on a channel whose + key is off no replay runs unchecked at all: it is refused. The key is read again when the job starts: if + it was turned off meanwhile, the job runs checked and says so in its log. Off unless set; never set by platform; a + new channel never starts with it. Clean after capture still holds a URL-less channel + (`cleanAfterCaptureUnverified`) and a whole-recording one (`diarization.cleanWholeRecordingAudio`) — those holds + are not the availability check. Audio an earlier checked clean pinned as "deleted from source (pre-clean check)" + stays do-not-clean: unpin it on the video page (or `pnpm ops do-not-clean --json '{"slug":"example","id":"<id>","keep":false}'`) to let + it go. +- **A checked clean the source rate-limits** (HTTP 429 on the channel listing or on a confirmation probe) deletes + nothing it could not verify and ends **deferred** on /jobs, with its counts. **The 429 counts toward the + platform's pace and hold**: a rate-limited listing records the platform's cooldown as Sync does + (`recordDownloadBackoff`), which widens that platform's request pace and counts toward a platform hold, so + downloads, Sync, fetch-windows and imports on that platform wait too. It schedules ONE retry, not before 15 minutes + or the platform's cooldown, whichever is later. The retry waits **off the queue** — a record in + `.jobs/clean-retries.json` and a timer — so it holds neither the channel's queue nor a job slot, and it is queued + as "Clean audio (rate-limit retry)" only when its time comes (later still if the cooldown is still running then). + The record survives a restart: the retry keeps its attempt and its time. If the channel's media is held when its + time comes (a relocation in flight, a drive away), it waits 15 minutes and tries again, same attempt, for up to 24 + hours; then it gives up and the Cleanup stage says why until dismissed. **Cancel** the deferred job to cancel the + retry (`pnpm ops job cancel <deferred job id>`), or use **Cancel retry** on the + Cleanup stage; any Clean audio or Clean without checking a person starts on the channel replaces it. After 2 + retries the next rate limit ends the job **failed**: "Gave up: rate-limited … It needs a person". A failure that is + not a rate limit (a network error, an extractor break) ends failed, "Could not verify availability …", and retries + nothing. + ## Record a live stream; import a file ```sh diff --git a/common/controller/channels.ts b/common/controller/channels.ts @@ -564,6 +564,13 @@ export async function patchChannelConfig( }); } +// A NEW CHANNEL NEVER STARTS CLEANING WITHOUT CHECKING (lane clean-unverified): +// `cleanAudioWithoutChecking` deletes audio unverified from every clean, +// automatic ones included, so it is a decision about THIS channel, made on its +// Cleanup stage (or `channel-config`) after a confirmation — never carried in +// by a config built or copied from elsewhere. Dropped here, the one door every +// new channel comes through (the form, `create-channel`, a remote-only +// registration, an X trending library). export async function createChannel( paths: Paths, slug: string, @@ -572,7 +579,8 @@ export async function createChannel( if (await channelExists(paths, slug)) { throw new Error(`Channel ${slug} already exists`); } - await writeChannelConfig(paths, slug, config); + const { cleanAudioWithoutChecking: _dropped, ...rest } = config; + await writeChannelConfig(paths, slug, rest as ChannelConfig); } // DELETING A RELOCATED CHANNEL HAS TO REACH THE OTHER DRIVE. `rm -r` on the diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts @@ -22,7 +22,12 @@ import { audioFilesToRemove } from "../lib/videoStatus"; import { readChannelConfig } from "./channels"; import { computeKeptVideoIds } from "./keptVideos"; import { pruneSavedVideos } from "./pruneSavedVideos"; -import { excludedIds, verifyBeforeClean } from "./verifyBeforeClean"; +import { + excludedIds, + verifyBeforeClean, + type CleanVerifyStop, + type VerifyProbes, +} from "./verifyBeforeClean"; const { pathExists, readdir, stat } = fs; @@ -33,10 +38,40 @@ export type CleanAudioOptions = { // (see verifyBeforeClean). Omitted → the global // SiteSettings.verifyAvailabilityBeforeClean, which defaults to true. verifyAvailability?: boolean; + // CLEAN WITHOUT CHECKING (lane clean-unverified): the availability verdict — + // every tier of verifyBeforeClean, the cached one included — is skipped and + // nothing is asked of the source; every other gate below holds. Why it is + // unchecked: the one-off button, or the channel's `cleanAudioWithoutChecking` + // (read by the caller that names the job, so the job's title is truthful). + unchecked?: UncheckedReason; + // THE CONFIRMED PLAN (review 1, ruling 2): the video ids a person was shown + // and confirmed (planAudioClean's `ids`). When given, the sweep removes only + // the intersection of this list with what is still eligible NOW: an id that + // became protected since is skipped by its gate, and a video that became + // eligible since is left for the next run, counted as "not in the confirmed + // plan". Absent = discover at start (the checked clean, a channel-key clean + // nobody confirmed). + onlyIds?: readonly string[]; + // Test seam for the availability probes (verifyBeforeClean). + probes?: VerifyProbes; + // Test seam for the media guard asked immediately before anything is + // removed (assertChannelMediaReachable). + assertReachable?: (paths: Paths, slug: string) => Promise<unknown>; onLog?: (msg: string) => void; signal?: AbortSignal; }; +export type UncheckedReason = "button" | "channel-setting"; + +// The first line of an unchecked clean's log, in both of its forms. +export function uncheckedLogLine(reason: UncheckedReason): string { + return ( + (reason === "channel-setting" ? "Clean without checking (channel setting): " : "Clean without checking: ") + + "the source is not asked, so the audio of videos no longer available anywhere is removed too" + + (reason === "channel-setting" ? " (this channel's cleanAudioWithoutChecking is on; no count was shown for this run unless it carries a plan)." : ".") + ); +} + export type CleanAudioResult = { inspected: number; cleanedDirs: number; @@ -62,9 +97,19 @@ export type CleanAudioResult = { // Bytes of audio removed (through tier links: the bytes on the media tier). bytesFreed: number; // Saved-store containers evicted because they rolled out of the keep-latest - // window (the retention prune runs alongside the audio sweep). + // window (the retention prune runs alongside the CHECKED audio sweep only — + // an unchecked one never touches a saved video container). prunedSavedVideos: number; prunedBytes: number; + // With a confirmed plan (`onlyIds`): eligible now but not in the plan, so + // left for the next run; and plan ids no longer eligible (protected or gone + // since the plan was made), skipped. + notInPlan?: number; + planNoLongerEligible?: number; + // Set when the availability gate stopped short — the source rate-limited it + // (`rate-limit`) or it failed (`error`) — and so cleaned nothing it could + // not verify (verifyBeforeClean's CleanVerdicts.stopped). + stopped?: CleanVerifyStop; }; type CleanCandidate = { @@ -169,6 +214,10 @@ export async function cleanAudioFromTranscribed({ channelSlug, paths, verifyAvailability, + unchecked, + onlyIds, + probes, + assertReachable = assertChannelMediaReachable, onLog, signal, }: CleanAudioOptions): Promise<CleanAudioResult> { @@ -191,46 +240,43 @@ export async function cleanAudioFromTranscribed({ }; } const dirs = await readdir(dataDir); - - // The rolling keep-latest window is protected from cleanup just like the - // explicit do-not-clean marker (the source media of recent videos is kept). - const config = await readChannelConfig(paths, channelSlug); - const keptIds = await computeKeptVideoIds({ - paths, - channelSlug, - keepLatest: config?.keepLatest ?? 0, - }); + if (unchecked) log(uncheckedLogLine(unchecked)); let cleanedDirs = 0; let removedFiles = 0; let bytesFreed = 0; - let protectedCount = 0; - let awaitingDiarization = 0; - let awaitingVoiceprint = 0; - - const diarization = getSettings().diarization; // --- Discover ------------------------------------------------------------- - // Nothing is deleted in this pass. Protected videos are filtered out here, so - // the availability gate never spends a spawn on a video we would keep anyway. - const candidates: CleanCandidate[] = []; - for (const id of dirs) { - if (signal?.aborted) break; - const videoDir = path.join(dataDir, id); - const { gate, audioFiles } = await audioCleanGate(videoDir, id, { keptIds, diarization }); - if (gate === "no-transcript" || gate === "no-audio") continue; - if (gate !== "candidate") log(`Skipped ${id} (${SKIP_LOG[gate]})`); - if (gate === "keep-latest" || gate === "do-not-clean") protectedCount++; - else if (gate === "awaiting-diarization") awaitingDiarization++; - else if (gate === "awaiting-voiceprint") awaitingVoiceprint++; - else candidates.push({ id, videoDir, audioFiles }); + const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log, signal }); + let candidates = found.candidates; + let protectedCount = found.protectedCount; + const { awaitingDiarization, awaitingVoiceprint } = found; + + // --- The confirmed plan: never more than a person was shown --------------- + let notInPlan: number | undefined; + let planNoLongerEligible: number | undefined; + if (onlyIds) { + const plan = new Set(onlyIds); + const inPlan = candidates.filter((c) => plan.has(c.id)); + notInPlan = candidates.length - inPlan.length; + planNoLongerEligible = plan.size - inPlan.length; + log( + `Confirmed plan: ${plan.size} video(s); ${inPlan.length} still eligible` + + (planNoLongerEligible > 0 ? `, ${planNoLongerEligible} protected or gone since (skipped)` : "") + + (notInPlan > 0 ? `; ${notInPlan} newly eligible video(s) left for the next run (not in the confirmed plan)` : "") + + ".", + ); + candidates = inPlan; } // --- Verify --------------------------------------------------------------- - const verify = verifyAvailability ?? getSettings().verifyAvailabilityBeforeClean; + const verify = unchecked + ? false + : (verifyAvailability ?? getSettings().verifyAvailabilityBeforeClean); let excluded = new Set<string>(); let pinned = 0; let unverified = 0; + let stopped: CleanVerifyStop | undefined; if (verify && candidates.length > 0 && !signal?.aborted) { const verdicts = await verifyBeforeClean({ channelSlug, @@ -238,15 +284,25 @@ export async function cleanAudioFromTranscribed({ candidateIds: candidates.map((c) => c.id), onLog: log, signal, + ...(probes ? { probes } : {}), }); excluded = excludedIds(verdicts); pinned = verdicts.pinned.size; unverified = verdicts.unverified.size; + stopped = verdicts.stopped; // A video already pinned by someone else is protected, not newly pinned. protectedCount += verdicts.alreadyGone.size; } // --- Delete --------------------------------------------------------------- + // THE GUARDS AGAIN, IMMEDIATELY BEFORE ANYTHING IS REMOVED (review 1, F4): + // the job kind's needsMedia guard ran when the queue started the job, and a + // listing can take minutes. A drive that went away or a relocation that + // started since (its marker) stops the sweep here, removing nothing: a + // removed tier link on an absent drive strands its bytes there. + if (candidates.some((c) => !excluded.has(c.id)) && !signal?.aborted) { + await assertReachable(paths, channelSlug); + } for (const candidate of candidates) { if (signal?.aborted) break; if (excluded.has(candidate.id)) continue; @@ -280,7 +336,23 @@ export async function cleanAudioFromTranscribed({ // Retention prune of the saved-video store: evict any keep-latest containers // that have rolled out of the window (pinned/manually-archived ones survive). - const prune = await pruneSavedVideos({ channelSlug, paths, onLog: log, signal }); + // ONLY WHEN THE AVAILABILITY GATE COMPLETED (review 1 F1, review 2 F1). The + // prune keeps a rolled-out container only when the video is do-not-clean, + // and that pin is written by the gate just above — for a video gone from + // the source, whose container may be its only copy anywhere. So the prune + // is skipped when the gate did not run to the end: + // - an UNCHECKED sweep skips the gate, so no pin would exist; + // - a checked sweep whose gate STOPPED (the source rate-limited it, or it + // failed) wrote no pins past where it stopped — on the first run and on + // every retry of the chain. (Before this lane the prune ran then too.) + const pruneSkipped = unchecked + ? "a clean without checking never touches a saved video container (a checked Clean audio runs it)" + : stopped + ? `the availability check did not complete (${stopped.kind === "rate-limit" ? `rate-limited by ${stopped.platform}` : "it failed"}), so a video gone from the source may not be pinned yet` + : null; + const prune = pruneSkipped + ? (log(`Saved-video retention prune skipped: ${pruneSkipped}.`), { pruned: 0, bytesFreed: 0 }) + : await pruneSavedVideos({ channelSlug, paths, onLog: log, signal }); return { inspected: dirs.length, @@ -294,6 +366,113 @@ export async function cleanAudioFromTranscribed({ bytesFreed, prunedSavedVideos: prune.pruned, prunedBytes: prune.bytesFreed, + ...(notInPlan !== undefined ? { notInPlan, planNoLongerEligible } : {}), + ...(stopped ? { stopped } : {}), + }; +} + +// THE DISCOVER PASS of the channel sweep, shared with the dry plan below so +// the two can never disagree about what a clean would remove. Nothing is +// deleted here. Protected videos are filtered out, so the availability gate +// never spends a spawn on a video we would keep anyway. +async function discoverAudioCandidates({ + paths, + channelSlug, + dataDir, + dirs, + log, + signal, +}: { + paths: Paths; + channelSlug: string; + dataDir: string; + dirs: string[]; + log: (m: string) => void; + signal?: AbortSignal; +}): Promise<{ + candidates: CleanCandidate[]; + protectedCount: number; + awaitingDiarization: number; + awaitingVoiceprint: number; +}> { + // The rolling keep-latest window is protected from cleanup just like the + // explicit do-not-clean marker (the source media of recent videos is kept). + const config = await readChannelConfig(paths, channelSlug); + const keptIds = await computeKeptVideoIds({ + paths, + channelSlug, + keepLatest: config?.keepLatest ?? 0, + }); + const diarization = getSettings().diarization; + let protectedCount = 0; + let awaitingDiarization = 0; + let awaitingVoiceprint = 0; + const candidates: CleanCandidate[] = []; + for (const id of dirs) { + if (signal?.aborted) break; + const videoDir = path.join(dataDir, id); + const { gate, audioFiles } = await audioCleanGate(videoDir, id, { keptIds, diarization }); + if (gate === "no-transcript" || gate === "no-audio") continue; + if (gate !== "candidate") log(`Skipped ${id} (${SKIP_LOG[gate]})`); + if (gate === "keep-latest" || gate === "do-not-clean") protectedCount++; + else if (gate === "awaiting-diarization") awaitingDiarization++; + else if (gate === "awaiting-voiceprint") awaitingVoiceprint++; + else candidates.push({ id, videoDir, audioFiles }); + } + return { candidates, protectedCount, awaitingDiarization, awaitingVoiceprint }; +} + +export type AudioCleanPlan = { + inspected: number; + // The video ids it would remove audio from — what a confirmed run carries + // (CleanAudioOptions.onlyIds) so it removes at most these. + ids: string[]; + // What an unchecked clean would remove now: the videos, their audio files + // and the bytes those free (through tier links: the bytes on the media tier). + videos: number; + files: number; + bytes: number; + // What it would keep: do-not-clean or keep-latest, and the two speaker holds. + protected: number; + awaitingDiarization: number; + awaitingVoiceprint: number; +}; + +// THE DRY PLAN of a clean without checking — the confirmation's numbers and +// `cleanup {"unchecked": true, "dryRun": true}`'s. The sweep's own discover +// pass, then a stat of each audio file; no network, no deletes, no markers. A +// channel whose media is not reachable (an unmounted drive, a move in flight) +// is refused with the guard's sentence rather than read as empty. +export async function planAudioClean({ + channelSlug, + paths, + signal, +}: { + channelSlug: string; + paths: Paths; + signal?: AbortSignal; +}): Promise<AudioCleanPlan> { + await assertChannelMediaReachable(paths, channelSlug); + const dataDir = path.join(paths.channelsDir, channelSlug, "data"); + const dirs = (await pathExists(dataDir)) ? await readdir(dataDir) : []; + const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log: () => {}, signal }); + let files = 0; + let bytes = 0; + for (const c of found.candidates) { + for (const f of c.audioFiles) { + files++; + bytes += await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0); + } + } + return { + inspected: dirs.length, + ids: found.candidates.map((c) => c.id), + videos: found.candidates.length, + files, + bytes, + protected: found.protectedCount, + awaitingDiarization: found.awaitingDiarization, + awaitingVoiceprint: found.awaitingVoiceprint, }; } @@ -390,8 +569,15 @@ export async function cleanAudioForVideo({ } // ALWAYS, whatever verifyAvailabilityBeforeClean says: that setting governs // the manual sweep the operator presses. An automatic delete is never - // unverified — only a URL-less channel's explicit opt-in skips this. - if (!unverifiedOptIn) { + // unverified — only a URL-less channel's explicit opt-in skips this, and a + // channel whose config says `cleanAudioWithoutChecking` (lane + // clean-unverified: an expiring-VOD platform, where "gone from the source" + // is the normal state) — no cached verdict, no listing, no check requested. + const withoutChecking = config?.cleanAudioWithoutChecking === true; + if (withoutChecking && !unverifiedOptIn) { + log(`Cleaning ${videoId}'s audio without checking (this channel's cleanAudioWithoutChecking is on).`); + } + if (!unverifiedOptIn && !withoutChecking) { const cached = await resolveEffectiveAvailability(videoDir); if (isPermanentlyGone(cached)) { if (!(await loadDoNotClean(videoDir))) { diff --git a/common/controller/cleanAudioJob.test.ts b/common/controller/cleanAudioJob.test.ts @@ -0,0 +1,382 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { VerifyProbes } from "./verifyBeforeClean"; +import { + CLEAN_RATE_LIMIT_MAX_RETRIES, + CLEAN_RETRY_PAUSE_MS, + PLAN_LOST_SENTENCE, + cleanAudioRequestFor, + cleanReplayFor, + REPLAY_UNCHECKED_KEY_OFF, + runCleanAudioJob, + type CleanRetry, +} from "./cleanAudioJob"; +import { parseChannelConfig } from "../lib/channelConfig"; +import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanAudioJob.test.ts +// +// A CHECKED CLEAN THE SOURCE RATE-LIMITED (lane clean-unverified, ruling 2): +// it cleans nothing it could not verify, ends DEFERRED with one retry +// SCHEDULED (off-queue: cleanRetrySchedule.ts) after the pause, at most twice; +// the third rate limit in a row gives up for a person. Any other failure to +// verify retries nothing. And how the job decides, WHEN IT STARTS, whether it +// runs unchecked and what it may remove (review 1, F2, F3, F5). Temp corpus, +// stub probes, an injected clock. + +const ROOT = await mkdtemp(path.join(tmpdir(), "clean-audio-job-")); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true })); + +const T0 = Date.parse("2026-11-21T03:00:00.000Z"); + +let n = 0; +async function corpus(config: Record<string, unknown> = {}, ids = ["a", "b"]) { + const dir = path.join(ROOT, `c${n++}`); + const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: path.join(dir, "no-ytdlp") } as unknown as Paths; + await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); + await writeFile( + path.join(paths.channelsDir, "ch", "config.json"), + JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/example", ...config }), + ); + for (const id of ids) { + const v = path.join(paths.channelsDir, "ch", "data", id); + await mkdir(v, { recursive: true }); + await writeFile(path.join(v, "transcript.json"), "{}"); + await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(100)); + } + return paths; +} + +const has = (paths: Paths, id: string) => + access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false); +const audioLeft = async (paths: Paths, ids = ["a", "b"]) => { + let left = 0; + for (const id of ids) left += (await has(paths, id)) ? 1 : 0; + return left; +}; + +function rateLimitedListing() { + const calls = { quick: 0, full: 0, backoff: 0 }; + const probes: VerifyProbes = { + quick: async () => { + calls.quick++; + throw new EnumerationIncompleteError(1, "rumble", null, 0); + }, + full: async () => { + calls.full++; + throw new Error("tier C is not reached"); + }, + recordBackoff: async () => { + calls.backoff++; + }, + }; + return { calls, probes }; +} + +const allListed = () => { + const calls = { quick: 0 }; + const probes: VerifyProbes = { + quick: async () => (calls.quick++, { knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }), + }; + return { calls, probes }; +}; + +function retryRecorder() { + const scheduled: CleanRetry[] = []; + return { + scheduled, + scheduleRetry: async (r: CleanRetry) => { + scheduled.push(r); + return { ok: true as const, id: `${r.of}.retry${r.attempt}` }; + }, + }; +} + +const base = (paths: Paths, over: Partial<Parameters<typeof runCleanAudioJob>[0]> = {}) => ({ + channelSlug: "ch", + paths, + jobId: "job-1", + onLog: () => {}, + ...over, +}); + +test("a rate-limited listing: 0 cleaned, a DEFERRED end, exactly one retry scheduled at now + 15 min", async () => { + const paths = await corpus(); + const { calls, probes } = rateLimitedListing(); + const r = retryRecorder(); + const out = await runCleanAudioJob({ + ...base(paths), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(calls.quick, 1); + assert.equal(calls.backoff, 1, "the cooldown is recorded once for this step of the chain"); + assert.equal(await audioLeft(paths), 2, "nothing unverified was cleaned"); + assert.equal(out.end, "deferred"); + assert.equal(CLEAN_RETRY_PAUSE_MS, 15 * 60_000); + assert.deepEqual(r.scheduled, [{ attempt: 1, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS, platform: "rumble" }]); + if (out.end !== "deferred") return; + assert.equal(out.until, T0 + CLEAN_RETRY_PAUSE_MS); + assert.equal(out.retryId, "job-1.retry1"); + assert.match(out.sentence, /rate-limited/i); + assert.match(out.sentence, /0 cleaned/); + assert.match(out.sentence, /2 left unverified/); + assert.match(out.sentence, /Retry 1 of 2 is scheduled/); + assert.match(out.sentence, /waits off the queue/); + assert.match(out.sentence, /Cancel this job to cancel it/); +}); + +test("the retry never lands inside the platform's cooldown: a longer cooldown moves it later", async () => { + const paths = await corpus(); + const { probes } = rateLimitedListing(); + const r = retryRecorder(); + await runCleanAudioJob({ + ...base(paths), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 25 * 60_000 }, + }); + assert.equal(r.scheduled[0]?.notBefore, T0 + 25 * 60_000); +}); + +test("a rate-limited confirmation probe (tier C blocked) defers the same way", async () => { + const paths = await corpus(); + const r = retryRecorder(); + const probes: VerifyProbes = { + quick: async () => ({ knownCount: 2, freshCount: 1, maybeMissingCount: 1, ids: ["b"] }), + full: async () => ({ + attempted: 1, + checked: 0, + skipped: 1, + byStatus: { public: 0, unlisted: 0, private: 0, members_only: 0, needs_auth: 0, deleted: 0, error: 0 }, + blocked: true, + blockMessage: "HTTP Error 429", + probedIds: [], + }), + }; + const out = await runCleanAudioJob({ + ...base(paths), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "deferred"); + assert.equal(await audioLeft(paths), 1, "the listed video was cleaned; the unprobed suspect was not"); + assert.equal(r.scheduled.length, 1); + if (out.end === "deferred") assert.match(out.sentence, /1 cleaned/); +}); + +test("the third rate limit in a row (retry 2 of 2) gives up for a person: no further retry", async () => { + const paths = await corpus(); + const { probes } = rateLimitedListing(); + const r = retryRecorder(); + assert.equal(CLEAN_RATE_LIMIT_MAX_RETRIES, 2); + const out = await runCleanAudioJob({ + ...base(paths, { jobId: "job-3", retry: { attempt: 2, of: "job-1", notBefore: T0 - 1, platform: "rumble" } }), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "failed"); + if (out.end === "failed") assert.match(out.sentence, /^Gave up: rate-limited/); + assert.equal(r.scheduled.length, 0); + assert.equal(await audioLeft(paths), 2); +}); + +test("a retry that is rate-limited again schedules the next one, keeping the original request's id", async () => { + const paths = await corpus(); + const { probes } = rateLimitedListing(); + const r = retryRecorder(); + const out = await runCleanAudioJob({ + ...base(paths, { jobId: "job-2", retry: { attempt: 1, of: "job-1", notBefore: T0 - 1, platform: "rumble" } }), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "deferred"); + assert.deepEqual(r.scheduled, [{ attempt: 2, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS, platform: "rumble" }]); +}); + +test("a retry started before its not-before asks nothing and cleans nothing", async () => { + const paths = await corpus(); + const { calls, probes } = rateLimitedListing(); + const r = retryRecorder(); + const out = await runCleanAudioJob({ + ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 + 60_000, platform: "rumble" } }), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "failed"); + if (out.end === "failed") assert.match(out.sentence, /before its time/); + assert.equal(calls.quick, 0); + assert.equal(r.scheduled.length, 0); + assert.equal(await audioLeft(paths), 2); +}); + +test("a listing that failed for another reason: 'could not verify', nothing scheduled", async () => { + const paths = await corpus(); + const r = retryRecorder(); + const probes: VerifyProbes = { + quick: async () => { + throw new Error("yt-dlp exited with code 1"); + }, + }; + const out = await runCleanAudioJob({ + ...base(paths), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "failed"); + if (out.end === "failed") assert.match(out.sentence, /^Could not verify availability/); + assert.equal(r.scheduled.length, 0); + assert.equal(await audioLeft(paths), 2); +}); + +test("a verified clean ends plain done and schedules nothing", async () => { + const paths = await corpus(); + const r = retryRecorder(); + const { probes } = allListed(); + const out = await runCleanAudioJob({ + ...base(paths), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "done"); + assert.equal(r.scheduled.length, 0); + assert.equal(await audioLeft(paths), 0); +}); + +test("a confirmed unchecked job ('button') asks nothing and removes its plan only", async () => { + const paths = await corpus(); + const { calls, probes } = rateLimitedListing(); + const r = retryRecorder(); + const out = await runCleanAudioJob({ + ...base(paths, { unchecked: "button", plan: ["a"] }), + deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "done"); + assert.equal(calls.quick, 0); + assert.equal(r.scheduled.length, 0); + assert.equal(await has(paths, "a"), false); + assert.equal(await has(paths, "b"), true, "not in the confirmed plan"); +}); + +test("ruling 5: a 'button' job whose plan is missing removes nothing and ends failed, asking to confirm again", async () => { + const paths = await corpus(); + const { calls, probes } = rateLimitedListing(); + const out = await runCleanAudioJob({ + ...base(paths, { unchecked: "button" }), + deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, + }); + assert.deepEqual(out, { end: "failed", sentence: PLAN_LOST_SENTENCE }); + assert.match(PLAN_LOST_SENTENCE, /^Confirmed plan lost; confirm again/); + assert.equal(calls.quick, 0); + assert.equal(await audioLeft(paths), 2); +}); + +test("ruling 3: a key-driven job whose key was turned off after it was queued runs CHECKED and says so", async () => { + const paths = await corpus(); // the key is OFF now + const { calls, probes } = allListed(); + const logs: string[] = []; + const out = await runCleanAudioJob({ + ...base(paths, { unchecked: "channel-setting", onLog: (m) => logs.push(m) }), + deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, + }); + assert.equal(out.end, "done"); + assert.equal(calls.quick, 1, "the source was asked: it ran checked"); + assert.ok(logs.some((l) => /turned off after this clean was queued: it runs CHECKED/.test(l)), logs.join("\n")); + assert.ok(!logs.some((l) => l.startsWith("Clean without checking:")), logs.join("\n")); +}); + +test("ruling 3: a key-driven job whose key is still on runs unchecked, discovering at start", async () => { + const paths = await corpus({ cleanAudioWithoutChecking: true }); + const { calls, probes } = rateLimitedListing(); + const out = await runCleanAudioJob({ + ...base(paths, { unchecked: "channel-setting" }), + deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, + }); + assert.equal(out.end, "done"); + assert.equal(calls.quick, 0); + assert.equal(await audioLeft(paths), 0); +}); + +test("a retry stays CHECKED even if the channel's key was turned on since (nobody confirmed an unchecked run)", async () => { + const paths = await corpus({ cleanAudioWithoutChecking: true }); + const { calls, probes } = allListed(); + await runCleanAudioJob({ + ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 - 1, platform: "rumble" } }), + deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, + }); + assert.equal(calls.quick, 1); +}); + +test("ruling 4: whatever runs after the wait re-asserts the media guard immediately before removing anything", async () => { + const paths = await corpus(); + const { probes } = allListed(); + // A relocation started during the wait: its marker stands. + await writeFile( + path.join(paths.channelsDir, "ch", ".relocating.json"), + JSON.stringify({ target: "/elsewhere/ch/media", direction: "out", startedAt: "now", phase: "copy", scope: "media" }), + ); + await assert.rejects( + runCleanAudioJob({ + ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 - 1, platform: "rumble" } }), + deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, + }), + /relocation/, + ); + assert.equal(await audioLeft(paths), 2, "nothing removed under a relocation"); +}); + +test("what a request queues: kind, unchecked reason and carried plan, from the key and the explicit flag", () => { + const off = parseChannelConfig({ handling: "transcribe", name: "a" }); + const on = parseChannelConfig({ handling: "transcribe", name: "a", cleanAudioWithoutChecking: true }); + assert.deepEqual(cleanAudioRequestFor(off), { kind: "clean-audio-transcribed" }); + assert.deepEqual(cleanAudioRequestFor(on), { kind: "clean-audio-unchecked", unchecked: "channel-setting" }); + assert.deepEqual(cleanAudioRequestFor(on, { plan: ["x"] }), { kind: "clean-audio-unchecked", unchecked: "channel-setting", plan: ["x"] }); + assert.deepEqual(cleanAudioRequestFor(off, { explicit: "button", plan: ["x"] }), { + kind: "clean-audio-unchecked", + unchecked: "button", + plan: ["x"], + }); + assert.deepEqual(cleanAudioRequestFor(null, { explicit: "button" }), { kind: "clean-audio-unchecked", unchecked: "button" }); +}); + +test("replay: unchecked only with the explicit flag and its carried plan; a retry's replay is a fresh chain", () => { + const cleanReplay = (k: string, p: Record<string, unknown>) => cleanReplayFor(k, p, true); + assert.deepEqual(cleanReplay("clean-audio-transcribed", {}), { ok: true, call: "clean" }); + assert.deepEqual(cleanReplay("clean-audio-transcribed", { plan: ["a"] }), { ok: true, call: "clean", plan: ["a"] }); + assert.deepEqual( + cleanReplay("clean-audio-retry", { retry: { attempt: 1, of: "j", notBefore: 1, platform: "rumble" }, plan: ["a"] }), + { ok: true, call: "clean" }, + "the retry's chain and count are the schedule's, never a replay's", + ); + assert.deepEqual(cleanReplay("clean-audio-unchecked", { unchecked: "button", plan: ["a", "b"] }), { + ok: true, + call: "unchecked", + plan: ["a", "b"], + }); + // No plan: replayed into a job that ends failed (PLAN_LOST_SENTENCE), never an unbounded run. + assert.deepEqual(cleanReplay("clean-audio-unchecked", { unchecked: "button" }), { ok: true, call: "unchecked" }); + assert.deepEqual(cleanReplay("clean-audio-unchecked", { unchecked: "button", plan: "a" }), { ok: true, call: "unchecked" }); + assert.deepEqual(cleanReplay("clean-audio-unchecked", { unchecked: "channel-setting" }), { ok: true, call: "clean" }); + assert.equal(cleanReplay("clean-audio-unchecked", {}).ok, false); + // Key OFF: a confirmed unchecked run is never replayed unchecked. + assert.deepEqual(cleanReplayFor("clean-audio-unchecked", { unchecked: "button", plan: ["a"] }, false), { + ok: false, + info: true, + error: REPLAY_UNCHECKED_KEY_OFF, + }); +}); + +test("ops nit: a carried plan's counts are stated in the job's log before anything is removed", async () => { + const paths = await corpus(); + const { probes } = rateLimitedListing(); + const logs: string[] = []; + await runCleanAudioJob({ + ...base(paths, { + unchecked: "button", + plan: ["a", "b"], + planCounts: { files: 2, bytes: 200, videos: 2, protected: 0, awaitingDiarization: 0, awaitingVoiceprint: 0 }, + onLog: (m) => logs.push(m), + }), + deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 }, + }); + const counted = logs.findIndex((l) => l.startsWith("Plan counted when this clean was asked for: 2 audio file(s) (200 bytes) from 2 video(s); kept: 0")); + const removed = logs.findIndex((l) => l.startsWith("Removed ")); + assert.ok(counted >= 0 && removed > counted, logs.join("\n")); +}); diff --git a/common/controller/cleanAudioJob.ts b/common/controller/cleanAudioJob.ts @@ -0,0 +1,316 @@ +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { platformCooldownRemainingMs } from "../jobs/downloadBackoff"; +import { + cleanAudioFromTranscribed, + type CleanAudioResult, + type UncheckedReason, +} from "./cleanAudioFromTranscribed"; +import { readChannelConfig } from "./channels"; +import type { VerifyProbes } from "./verifyBeforeClean"; + +// THE CLEAN-AUDIO JOB'S BODY (lane clean-unverified): what the channel sweep +// does inside its job, and how that job ENDS. +// +// A CHECKED CLEAN THE SOURCE RATE-LIMITED (operator ruling, 21 Nov 2026). The +// gate fails closed — nothing it could not verify is deleted — and the job +// used to end a plain `done` that did nothing (a Rumble listing answered 429: +// 0 of 350 cleaned, `done`). Now: +// - rate-limited, retries left: the job ends DEFERRED (JobRecord.deferred, +// the job system's own state, drawn "deferred" on /jobs) with the counts, +// and ONE retry is scheduled (off-queue, below), not before +// max(now + CLEAN_RETRY_PAUSE_MS, the platform's recorded cooldown end); +// - the third rate limit in a row (the request and its 2 retries): FAILED, +// "Gave up: rate-limited …" — a person decides; +// - any other failure to verify (a network error, an extractor break): +// FAILED, "Could not verify availability …", no retry (only a rate limit +// is retried — nothing else here suggests waiting helps). +// The retry's wait is OFF-QUEUE (review 1 F4–F6): a durable record and a +// timer (controller/cleanRetrySchedule.ts) that queues the retry job only at +// its not-before time, so it holds no queue and no job slot meanwhile. +// Cancelling the deferred job cancels the retry. A person's Retry of any of +// these jobs starts a fresh chain. +// +// An UNCHECKED clean asks nothing, so none of this applies to it. + +// The pause before a rate-limited clean is retried. The repo's per-platform +// cooldown (jobs/platformBackoff.ts) starts at 1 minute and doubles — a floor +// for downloads, too short to be a pause for a cleanup nobody is waiting on — +// so the retry waits whichever is later: this, or that cooldown's end. +export const CLEAN_RETRY_PAUSE_MS = 15 * 60_000; +// Automatic retries per original request; the next rate limit gives up. +export const CLEAN_RATE_LIMIT_MAX_RETRIES = 2; + +// A retry of a rate-limited clean, carried in its record and its job's spec +// params. `of` is the ORIGINAL request's job id (the chain's), `attempt` +// 1-based, `platform` the key the rate limit was recorded under (its cooldown), +// `id` the schedule record's (cleanRetrySchedule.ts) once it has one. +export type CleanRetry = { attempt: number; of: string; notBefore: number; platform: string; id?: string }; + +export type CleanJobOutcome = + | { end: "done"; result: CleanAudioResult } + | { end: "deferred"; until: number; sentence: string; retryId: string; result: CleanAudioResult } + | { end: "failed"; sentence: string; result?: CleanAudioResult } + | { end: "cancelled" }; + +export type CleanJobDeps = { + // Schedule the retry OFF-QUEUE (the action: cleanRetrySchedule's record and + // timer, which queue a clean-audio-retry job at `notBefore`). + scheduleRetry: (retry: CleanRetry) => Promise<{ ok: true; id: string } | { ok: false; error: string }>; + now?: () => number; + cooldownRemainingMs?: (platform: string) => Promise<number>; + probes?: VerifyProbes; + // Test seam for the sweep's guard immediately before it removes anything. + assertReachable?: (paths: Paths, slug: string) => Promise<unknown>; +}; + +// THE SENTENCE OF A CONFIRMED UNCHECKED JOB WHOSE PLAN IS GONE (ruling 5): a +// "Clean without checking" removes at most what a person confirmed, so a job +// that has no plan to carry (a spec from before plans, or one a restart +// re-queued without it) removes nothing and asks for the confirmation again. +export const PLAN_LOST_SENTENCE = + "Confirmed plan lost; confirm again: this clean without checking carries no list of what a person confirmed, so it removed nothing. Run Clean without checking again and confirm its count."; + +// The channel key's verdict for a sweep the operator did not explicitly ask to +// run unchecked: "channel-setting" when `cleanAudioWithoutChecking` is on. +export function uncheckedReasonFor(config: ChannelConfig | null | undefined): UncheckedReason | undefined { + return config?.cleanAudioWithoutChecking === true ? "channel-setting" : undefined; +} + +// WHAT A CLEAN REQUEST QUEUES — the job kind (so the job list's title is +// truthful) and what its spec carries. The one rule the action, the ops twin +// and replay share: +// - "button" (a person confirmed a counted plan, or `cleanup {"unchecked": +// true}` computed one at the call): unchecked, the plan carried; +// - the channel's key on: unchecked by "channel-setting", with the plan when +// a person confirmed one, else discovered at start; the key is re-read +// when the job starts (runCleanAudioJob); +// - otherwise the checked clean (bounded by a plan when one was confirmed). +export type CleanAudioRequest = { + kind: "clean-audio-transcribed" | "clean-audio-unchecked"; + unchecked?: UncheckedReason; + plan?: string[]; +}; + +export function cleanAudioRequestFor( + config: ChannelConfig | null | undefined, + opts: { explicit?: "button"; plan?: readonly string[] } = {}, +): CleanAudioRequest { + const plan = opts.plan ? [...opts.plan] : undefined; + const reason: UncheckedReason | undefined = opts.explicit ?? uncheckedReasonFor(config); + if (reason) return { kind: "clean-audio-unchecked", unchecked: reason, ...(plan ? { plan } : {}) }; + return { kind: "clean-audio-transcribed", ...(plan ? { plan } : {}) }; +} + +// A spec's carried plan, or undefined for anything that is not a list of ids. +export function planFromParams(p: Record<string, unknown> | undefined): string[] | undefined { + const v = p?.plan; + return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined; +} + +// HOW A CLEAN JOB IS REPLAYED — by every replay path alike: a /jobs Retry, +// Retry all failed, `pnpm ops job retry`, and the boot's re-queue of a job a +// restart caught queued (all four go through the editor's runJobSpec). Operator +// ruling (review 2): the channel key is the operator's standing consent for +// that channel, so on a KEY-ON channel a replay may run unchecked WITHOUT a +// new count, like any key-driven job (the key read at start, "without +// checking (channel setting)" in its title and first line, no prune). But a +// replay never becomes a person-confirmed unchecked run without its plan, and +// on a KEY-OFF channel no replay runs unchecked at all: +// - clean-audio-transcribed, clean-audio-retry (a FRESH chain: a scheduled +// retry is re-armed from its own record, never replayed) and a +// "channel-setting" clean-audio-unchecked → Clean audio again, the key as +// it is now decides (a carried plan, if any, still bounds it); +// - a "button" clean-audio-unchecked (a person confirmed a count) → on a +// key-on channel, unchecked again WITH ITS CARRIED PLAN only; with no plan +// it replays into a job that removes nothing and ends failed, "Confirmed +// plan lost; confirm again". On a key-OFF channel it is REFUSED: it would +// be an unchecked run nobody asked for now; +// - anything else is refused. +export type CleanReplay = + | { ok: true; call: "clean" | "unchecked"; plan?: string[] } + | { ok: false; error: string; info?: boolean }; + +export const REPLAY_UNCHECKED_KEY_OFF = + "This was a clean without checking, and this channel cleans checked now: a Retry does not run it unchecked. Run Clean without checking again and confirm its count, or Clean audio."; + +export function cleanReplayFor( + kind: string, + params: Record<string, unknown> | undefined, + keyOn: boolean, +): CleanReplay { + const plan = planFromParams(params); + if (kind === "clean-audio-transcribed") return { ok: true, call: "clean", ...(plan ? { plan } : {}) }; + if (kind === "clean-audio-retry") return { ok: true, call: "clean" }; + if (kind === "clean-audio-unchecked") { + if (params?.unchecked === "button") { + if (!keyOn) return { ok: false, info: true, error: REPLAY_UNCHECKED_KEY_OFF }; + return { ok: true, call: "unchecked", ...(plan ? { plan } : {}) }; + } + if (params?.unchecked === "channel-setting") return { ok: true, call: "clean", ...(plan ? { plan } : {}) }; + return { + ok: false, + error: "This clean without checking carries no unchecked flag to replay it with — run Clean audio or Clean without checking instead.", + }; + } + return { ok: false, error: `not a clean-audio kind: ${kind}` }; +} + +// The replay itself, over the actions it calls (the editor's cleanAudioAction +// and cleanAudioUncheckedAction): the channel's key is read NOW. +export async function replayCleanSpec<R>( + spec: { kind: string; slug: string; params?: Record<string, unknown> }, + deps: { + readConfig: (slug: string) => Promise<ChannelConfig | null>; + clean: (slug: string, queueKey: string | undefined, plan?: string[]) => Promise<R>; + unchecked: (slug: string, queueKey: string | undefined, plan?: string[]) => Promise<R>; + }, +): Promise<R | { ok: false; error: string; info?: boolean }> { + const p = spec.params ?? {}; + const queueKey = typeof p.queueKey === "string" ? p.queueKey : undefined; + const keyOn = uncheckedReasonFor(await deps.readConfig(spec.slug).catch(() => null)) !== undefined; + const r = cleanReplayFor(spec.kind, p, keyOn); + if (!r.ok) return r; + return r.call === "unchecked" ? deps.unchecked(spec.slug, queueKey, r.plan) : deps.clean(spec.slug, queueKey, r.plan); +} + +// What the plan counted, as the job's log states it before anything is removed +// (and `pnpm ops cleanup {"unchecked": true}` answers it). +export type CleanPlanCountsLog = { + files: number; + bytes: number; + videos: number; + protected: number; + awaitingDiarization: number; + awaitingVoiceprint: number; +}; + +export function planCountsLine(c: CleanPlanCountsLog): string { + return ( + `Plan counted when this clean was asked for: ${c.files} audio file(s) (${c.bytes} bytes) from ${c.videos} video(s); ` + + `kept: ${c.protected} marked do not clean or in the keep-latest window, ${c.awaitingDiarization} awaiting diarization, ` + + `${c.awaitingVoiceprint} awaiting voice fingerprint.` + ); +} + +function clock(ms: number): string { + return new Date(ms).toISOString().slice(11, 16) + " UTC"; +} + +export async function runCleanAudioJob({ + channelSlug, + paths, + jobId, + unchecked, + plan, + planCounts, + retry, + onLog, + signal, + deps, +}: { + channelSlug: string; + paths: Paths; + jobId: string; + // Why the job was queued unchecked. "button": a person confirmed a counted + // plan (`plan` required). "channel-setting": the channel's key — RE-READ + // HERE, when the job starts (ruling 3). + unchecked?: UncheckedReason; + // The confirmed plan's video ids: the run removes at most these. + plan?: readonly string[]; + // The plan's counts, logged before anything is removed (an ops call). + planCounts?: CleanPlanCountsLog; + retry?: CleanRetry; + onLog: (m: string) => void; + signal?: AbortSignal; + deps: CleanJobDeps; +}): Promise<CleanJobOutcome> { + const now = deps.now ?? (() => Date.now()); + const cooldown = deps.cooldownRemainingMs ?? ((pf: string) => platformCooldownRemainingMs(pf, paths)); + const config = await readChannelConfig(paths, channelSlug); + + // --- Unchecked, decided NOW -------------------------------------------------- + let mode: UncheckedReason | undefined = unchecked; + if (mode === "button" && !plan) { + return { end: "failed", sentence: PLAN_LOST_SENTENCE }; + } + if (mode === "channel-setting" && !uncheckedReasonFor(config)) { + onLog( + "This channel's cleanAudioWithoutChecking was turned off after this clean was queued: it runs CHECKED (the source is asked, as Clean audio does).", + ); + mode = undefined; + } + // A retry is the continuation of a CHECKED request: it stays checked even if + // the channel's key was turned on since (nobody confirmed an unchecked run). + if (retry) mode = undefined; + + // --- A retry never runs before its time -------------------------------------- + // The schedule queues it only at its not-before; a spec replayed by hand + // earlier than that asks nothing. + if (retry && now() < retry.notBefore) { + return { + end: "failed", + sentence: `This retry was started before its time (not before ${clock(retry.notBefore)}): nothing was asked or cleaned.`, + }; + } + if (plan && planCounts) onLog(planCountsLine(planCounts)); + if (retry) { + onLog(`Retry ${retry.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} of rate-limited clean ${retry.of}.`); + } + + const result = await cleanAudioFromTranscribed({ + channelSlug, + paths, + onLog, + signal, + ...(mode ? { unchecked: mode } : {}), + ...(plan ? { onlyIds: plan } : {}), + ...(deps.probes ? { probes: deps.probes } : {}), + ...(deps.assertReachable ? { assertReachable: deps.assertReachable } : {}), + }); + if (signal?.aborted) return { end: "cancelled" }; + const stop = result.stopped; + if (!stop) return { end: "done", result }; + + const counts = `${result.cleanedDirs} cleaned, ${result.unverified} left unverified`; + if (stop.kind === "error") { + return { + end: "failed", + sentence: + `Could not verify availability (${stop.message}): ${counts}. Nothing unverified was deleted, and no retry is queued ` + + `(only a rate limit is retried) — run Clean audio again once the source answers.`, + result, + }; + } + const attempt = retry?.attempt ?? 0; + if (attempt >= CLEAN_RATE_LIMIT_MAX_RETRIES) { + return { + end: "failed", + sentence: + `Gave up: rate-limited by ${stop.platform} ${attempt + 1} times in a row (this request and ${CLEAN_RATE_LIMIT_MAX_RETRIES} automatic retries; ` + + `${counts}). Nothing unverified was deleted. It needs a person: run Clean audio again later, or Clean without checking.`, + result, + }; + } + const t = now(); + const notBefore = Math.max(t + CLEAN_RETRY_PAUSE_MS, t + (await cooldown(stop.platform).catch(() => 0))); + const next: CleanRetry = { attempt: attempt + 1, of: retry?.of ?? jobId, notBefore, platform: stop.platform }; + const scheduled = await deps.scheduleRetry(next); + if (!scheduled.ok) { + return { + end: "failed", + sentence: `Rate-limited by ${stop.platform} (${counts}); the retry could not be scheduled: ${scheduled.error}`, + result, + }; + } + return { + end: "deferred", + until: notBefore, + retryId: scheduled.id, + sentence: + `Rate-limited by ${stop.platform} (${stop.message}): ${counts}; nothing unverified was deleted. ` + + `Retry ${next.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} is scheduled, not before ${clock(notBefore)}; it waits off the queue. ` + + `Cancel this job to cancel it (or Cancel retry on the channel's Cleanup stage).`, + result, + }; +} diff --git a/common/controller/cleanReplay.test.ts b/common/controller/cleanReplay.test.ts @@ -0,0 +1,223 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, readdir, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { JobSpec } from "../jobs/jobSpec"; +import type { VerifyProbes } from "./verifyBeforeClean"; +import { + PLAN_LOST_SENTENCE, + REPLAY_UNCHECKED_KEY_OFF, + cleanAudioRequestFor, + replayCleanSpec, + runCleanAudioJob, + type CleanJobOutcome, +} from "./cleanAudioJob"; +import { readChannelConfig } from "./channels"; +import { jobSpecDetail } from "../jobs/jobDetail"; +import { settleQueuedJobMetas } from "../jobs/bootQueuedJobs"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanReplay.test.ts +// +// REPLAYING A CLEAN (lane clean-unverified, review 2 ruling): the four replay +// paths — a /jobs Retry, Retry all failed, `pnpm ops job retry`, and the boot's +// re-queue — all reach replayCleanSpec (the editor's runJobSpec → +// JOB_REPLAY_HANDLERS → replayClean; the boot's requeue is runJobSpec too). +// Each path is driven here as its caller drives it, over the same composition +// the editor's actions make: cleanAudioRequestFor on the config read at the +// call, then the job body. On a KEY-ON channel a replay may run unchecked with +// no count ("channel setting", no prune); a confirmed run needs its plan; on a +// KEY-OFF channel nothing replays unchecked. + +const ROOT = await mkdtemp(path.join(tmpdir(), "clean-replay-")); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true })); +const T0 = Date.parse("2026-11-21T03:00:00.000Z"); + +let n = 0; +async function corpus(keyOn: boolean) { + const dir = path.join(ROOT, `c${n++}`); + const paths = { + channelsDir: path.join(dir, "channels"), + transcriptsDir: dir, + savedVideosDir: path.join(dir, "saved"), + jobsDir: path.join(dir, ".jobs"), + ytdlpBin: path.join(dir, "no-ytdlp"), + } as unknown as Paths; + await mkdir(paths.jobsDir, { recursive: true }); + await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); + await writeFile( + path.join(paths.channelsDir, "ch", "config.json"), + JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.twitch.tv/example", ...(keyOn ? { cleanAudioWithoutChecking: true } : {}) }), + ); + for (const id of ["a", "b"]) { + const v = path.join(paths.channelsDir, "ch", "data", id); + await mkdir(v, { recursive: true }); + await writeFile(path.join(v, "transcript.json"), "{}"); + await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(100)); + } + return paths; +} + +type Ran = { kind: string; unchecked?: string; detail?: string; out: CleanJobOutcome; logs: string[]; asked: number }; + +// The editor's actions, composed as whisperActions composes them: the request +// from the config read NOW, then the job body (its key read again at start). +function actions(paths: Paths) { + const ran: Ran[] = []; + const run = async (explicit: "button" | undefined, slug: string, plan?: string[]) => { + const req = cleanAudioRequestFor(await readChannelConfig(paths, slug), { ...(explicit ? { explicit } : {}), ...(plan ? { plan } : {}) }); + const params = { ...(req.unchecked ? { unchecked: req.unchecked } : {}), ...(req.plan ? { plan: req.plan } : {}) }; + let asked = 0; + const probes: VerifyProbes = { + quick: async () => (asked++, { knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }), + }; + const logs: string[] = []; + const out = await runCleanAudioJob({ + channelSlug: slug, + paths, + jobId: `job-${ran.length}`, + ...(req.unchecked ? { unchecked: req.unchecked } : {}), + ...(req.plan ? { plan: req.plan } : {}), + onLog: (m) => logs.push(m), + deps: { probes, now: () => T0, cooldownRemainingMs: async () => 0, scheduleRetry: async () => ({ ok: false, error: "none" }) }, + }); + const r: Ran = { kind: req.kind, ...(req.unchecked ? { unchecked: req.unchecked } : {}), detail: jobSpecDetail(req.kind, { kind: req.kind, slug, params }), out, logs, asked }; + ran.push(r); + return { ok: true as const, jobId: `job-${ran.length - 1}` }; + }; + return { + ran, + deps: { + readConfig: (slug: string) => readChannelConfig(paths, slug), + clean: (slug: string, _q: string | undefined, plan?: string[]) => run(undefined, slug, plan), + unchecked: (slug: string, _q: string | undefined, plan?: string[]) => run("button", slug, plan), + }, + }; +} + +// The four paths, each as its caller drives replay. +type Path = "retry" | "retry-all-failed" | "ops-job-retry" | "boot"; +const PATHS: Path[] = ["retry", "retry-all-failed", "ops-job-retry", "boot"]; + +async function replayBy(via: Path, paths: Paths, spec: JobSpec, deps: ReturnType<typeof actions>["deps"]) { + if (via === "retry" || via === "ops-job-retry") return replayCleanSpec(spec, deps); + if (via === "retry-all-failed") { + // Every failed job with a spec, one after another. + const out = []; + for (const s of [spec]) out.push(await replayCleanSpec(s, deps)); + return out[0]; + } + // The boot: a meta a restart caught queued, re-queued through its spec. + const metaId = `M${n++}`; + await writeFile( + path.join(paths.jobsDir, `${metaId}.meta.json`), + JSON.stringify({ id: metaId, kind: spec.kind, queueKey: "channel:ch", status: "queued", queuedAt: Date.now() - 60_000, channelSlug: "ch", spec }), + ); + let answer: unknown; + const res = await settleQueuedJobMetas({ + paths, + bootedAt: Date.now() + 60_000, + log: () => {}, + requeue: async (s) => { + const r = await replayCleanSpec(s, deps); + answer = r; + return r as { ok: true; jobId: string } | { ok: false; error: string }; + }, + }); + if (!answer) return { ok: false, error: `not re-queued: ${JSON.stringify(res.cancelled)}` }; + return answer; +} + +const has = (paths: Paths, id: string) => + access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false); + +const CHECKED_SPECS: JobSpec[] = [ + { kind: "clean-audio-transcribed", slug: "ch", params: {} }, + { kind: "clean-audio-retry", slug: "ch", params: { retry: { attempt: 1, of: "j", notBefore: 1, platform: "twitch", id: "j.retry1" } } }, + { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "channel-setting" } }, +]; +const BUTTON_WITH_PLAN: JobSpec = { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "button", plan: ["a"] } }; +const BUTTON_NO_PLAN: JobSpec = { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "button" } }; + +for (const via of PATHS) { + test(`${via}, key OFF: no replay runs unchecked — the clean kinds run checked, a confirmed unchecked one is refused`, async () => { + for (const spec of CHECKED_SPECS) { + const paths = await corpus(false); + const a = actions(paths); + await replayBy(via, paths, spec, a.deps); + // At boot a queued retry is not replayed at all: its schedule re-arms it. + if (via === "boot" && spec.kind === "clean-audio-retry") { + assert.equal(a.ran.length, 0); + continue; + } + assert.equal(a.ran.length, 1, `${spec.kind}: replayed`); + const [r] = a.ran; + assert.equal(r.kind, "clean-audio-transcribed", `${spec.kind}: checked kind`); + assert.equal(r.unchecked, undefined); + assert.equal(r.asked, 1, `${spec.kind}: the source was asked`); + assert.ok(!r.logs.some((l) => l.includes("without checking")), r.logs.join("\n")); + } + for (const spec of [BUTTON_WITH_PLAN, BUTTON_NO_PLAN]) { + const paths = await corpus(false); + const a = actions(paths); + const out = (await replayBy(via, paths, spec, a.deps)) as { ok: boolean; error?: string }; + assert.equal(a.ran.length, 0, "nothing ran"); + assert.equal(out.ok, false); + if (via !== "boot") assert.equal(out.error, REPLAY_UNCHECKED_KEY_OFF); + assert.equal(await has(paths, "a"), true); + assert.equal(await has(paths, "b"), true); + } + if (via === "boot") { + // The boot pass closes a refused re-queue with the refusal. + const paths = await corpus(false); + const a = actions(paths); + await replayBy(via, paths, BUTTON_WITH_PLAN, a.deps); + const files = (await readdir(paths.jobsDir)).filter((f) => f.endsWith(".meta.json")); + const metas = await Promise.all(files.map((f) => readFile(path.join(paths.jobsDir, f), "utf8"))); + assert.ok(metas.some((m) => m.includes("re-queue refused") && m.includes("cleans checked now")), metas.join("\n")); + } + }); + + test(`${via}, key ON: a clean replays unchecked with no count ("channel setting", no prune); a confirmed one needs its plan`, async () => { + for (const spec of CHECKED_SPECS) { + const paths = await corpus(true); + const a = actions(paths); + await replayBy(via, paths, spec, a.deps); + if (via === "boot" && spec.kind === "clean-audio-retry") { + assert.equal(a.ran.length, 0, "a queued retry is re-armed by its schedule, never replayed at boot"); + continue; + } + assert.equal(a.ran.length, 1); + const [r] = a.ran; + assert.equal(r.kind, "clean-audio-unchecked", `${spec.kind}`); + assert.equal(r.unchecked, "channel-setting"); + assert.equal(r.detail, "channel setting", "the title reads … without checking · channel setting"); + assert.ok(r.logs[0]?.startsWith("Clean without checking (channel setting):"), r.logs.join("\n")); + assert.ok(r.logs.some((l) => l.startsWith("Saved-video retention prune skipped")), r.logs.join("\n")); + assert.equal(r.asked, 0, "the source was not asked"); + assert.equal(r.out.end, "done"); + } + // A confirmed run with its plan: unchecked, at most the plan. + { + const paths = await corpus(true); + const a = actions(paths); + await replayBy(via, paths, BUTTON_WITH_PLAN, a.deps); + assert.equal(a.ran[0]?.unchecked, "button"); + assert.equal(a.ran[0]?.detail, "confirmed count"); + assert.equal(await has(paths, "a"), false); + assert.equal(await has(paths, "b"), true, "not in the carried plan"); + } + // A confirmed run without its plan: removes nothing, ends failed. + { + const paths = await corpus(true); + const a = actions(paths); + await replayBy(via, paths, BUTTON_NO_PLAN, a.deps); + assert.deepEqual(a.ran[0]?.out, { end: "failed", sentence: PLAN_LOST_SENTENCE }); + assert.equal(await has(paths, "a"), true); + assert.equal(await has(paths, "b"), true); + } + }); +} diff --git a/common/controller/cleanRetrySchedule.test.ts b/common/controller/cleanRetrySchedule.test.ts @@ -0,0 +1,267 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, readFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { + HOLD_PAUSE_MS, + MAX_HOLDS, + MAX_REARMS, + armCleanRetriesAtBoot, + cancelCleanRetries, + cleanRetriesFile, + finishCleanRetry, + readCleanRetries, + resetCleanRetryTimers, + scheduleCleanRetry, + startCleanRetry, + type CleanRetryDeps, + type ScheduledCleanRetry, +} from "./cleanRetrySchedule"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanRetrySchedule.test.ts +// +// A RATE-LIMITED CLEAN'S RETRY WAITS OFF THE QUEUE (lane clean-unverified, +// rulings 4 and 5): a durable record and a timer; nothing is queued until its +// not-before time; a restart re-arms it with its attempt and time; Cancel +// reaches it. A fake clock and a fake timer table: no real wait. + +const T0 = Date.parse("2026-11-21T03:00:00.000Z"); +const MIN = 60_000; + +let n = 0; +async function jobsDir(): Promise<Pick<Paths, "jobsDir">> { + return { jobsDir: path.join(await mkdtemp(path.join(tmpdir(), "clean-retry-")), `j${n++}`) }; +} + +// A fake "process": a clock, a timer table, and recorders for what it queues +// and cancels. `restart()` is a new process: every timer is gone. +function fakeProcess(start = T0) { + let now = start; + let seq = 0; + const pending = new Map<number, { at: number; fn: () => Promise<unknown> }>(); + const enqueued: ScheduledCleanRetry[] = []; + const cancelledJobs: string[] = []; + let cooldown = 0; + let hold: string | null = null; + let refuse: string | null = null; + const deps: CleanRetryDeps = { + now: () => now, + setTimer: (fn, ms) => { + const id = ++seq; + pending.set(id, { at: now + ms, fn }); + return id; + }, + clearTimer: (h) => void pending.delete(h as number), + cooldownRemainingMs: async () => cooldown, + enqueue: async (e) => { + if (refuse) return { ok: false, error: refuse }; + enqueued.push({ ...e }); + return { ok: true, jobId: `job-${enqueued.length}` }; + }, + mediaHold: async () => hold, + cancelJob: (id) => (cancelledJobs.push(id), true), + }; + return { + deps, + enqueued, + cancelledJobs, + pending, + setCooldown: (ms: number) => void (cooldown = ms), + setHold: (why: string | null) => void (hold = why), + setRefuse: (why: string | null) => void (refuse = why), + // Advance the clock, firing due timers (and letting their async work run). + async advance(ms: number) { + now += ms; + for (;;) { + const due = [...pending.entries()].filter(([, t]) => t.at <= now).sort((a, b) => a[1].at - b[1].at); + if (due.length === 0) break; + for (const [id, t] of due) { + pending.delete(id); + await t.fn(); + } + } + }, + restart() { + resetCleanRetryTimers({ clearTimer: (h) => void pending.delete(h as number) }); + pending.clear(); + }, + }; +} + +const REQ = { slug: "ch", attempt: 1, of: "J0", deferredJobId: "J0", platform: "rumble", notBefore: T0 + 15 * MIN }; + +test("a scheduled retry holds nothing while it waits: no job until its not-before, then exactly one", async () => { + const p = await jobsDir(); + const proc = fakeProcess(); + const entry = await scheduleCleanRetry(p, REQ, proc.deps); + assert.equal(entry.id, "J0.retry1"); + assert.equal(entry.state, "scheduled"); + // Durable: on disk, with its attempt and time. + const onDisk = JSON.parse(await readFile(cleanRetriesFile(p), "utf8")); + assert.deepEqual( + onDisk.retries.map((e: ScheduledCleanRetry) => [e.id, e.attempt, e.notBefore, e.state]), + [["J0.retry1", 1, T0 + 15 * MIN, "scheduled"]], + ); + await proc.advance(15 * MIN - 1000); + assert.equal(proc.enqueued.length, 0, "nothing queued a second before its time"); + await proc.advance(1000); + assert.equal(proc.enqueued.length, 1); + assert.equal(proc.enqueued[0].attempt, 1); + const [after] = await readCleanRetries(p); + assert.equal(after.state, "enqueued"); + assert.equal(after.jobId, "job-1"); + proc.restart(); +}); + +test("a cooldown still running when the timer fires moves it to the cooldown's end, a bounded number of times", async () => { + const p = await jobsDir(); + const proc = fakeProcess(); + await scheduleCleanRetry(p, REQ, proc.deps); + proc.setCooldown(10 * MIN); + await proc.advance(15 * MIN); + assert.equal(proc.enqueued.length, 0, "not queued inside the cooldown"); + const [moved] = await readCleanRetries(p); + assert.equal(moved.notBefore, T0 + 25 * MIN); + assert.equal(moved.rearms, 1); + // A cooldown that never ends is waited out MAX_REARMS times, then the retry + // is queued and meets it (judged a rate limit again). + for (let i = 0; i < MAX_REARMS; i++) await proc.advance(10 * MIN); + assert.equal(proc.enqueued.length, 1); + proc.restart(); +}); + +test("restart: the record survives, keeps its attempt and time, and is never queued early", async () => { + const p = await jobsDir(); + const first = fakeProcess(); + await scheduleCleanRetry(p, { ...REQ, attempt: 2 }, first.deps); + await first.advance(5 * MIN); + first.restart(); // the server goes down; its timer is gone + + const second = fakeProcess(T0 + 6 * MIN); + const boot = await armCleanRetriesAtBoot(p, second.deps); + assert.deepEqual(boot.armed, ["J0.retry2"]); + await second.advance(8 * MIN); // T0 + 14 min + assert.equal(second.enqueued.length, 0, "still before its not-before"); + await second.advance(1 * MIN); // T0 + 15 min + assert.equal(second.enqueued.length, 1); + assert.equal(second.enqueued[0].attempt, 2, "the attempt count survived the restart"); + second.restart(); +}); + +test("restart: a retry caught queued is queued again by its schedule; one caught running is re-armed once, then dropped", async () => { + const p = await jobsDir(); + const a = fakeProcess(); + await scheduleCleanRetry(p, REQ, a.deps); + await a.advance(15 * MIN); + assert.equal((await readCleanRetries(p))[0].state, "enqueued"); + a.restart(); + + // Caught queued: the boot pass closes the stale meta; the schedule re-queues. + const b = fakeProcess(T0 + 20 * MIN); + await armCleanRetriesAtBoot(p, b.deps); + await b.advance(0); + assert.equal(b.enqueued.length, 1); + assert.equal(b.enqueued[0].attempt, 1); + + // Caught running, twice: re-armed the first time, dropped the second. + assert.ok(await startCleanRetry(p, "J0.retry1", "job-1")); + b.restart(); + const c = fakeProcess(T0 + 30 * MIN); + const boot1 = await armCleanRetriesAtBoot(p, c.deps); + assert.deepEqual(boot1, { armed: ["J0.retry1"], dropped: [] }); + await c.advance(0); + assert.ok(await startCleanRetry(p, "J0.retry1", "job-2")); + c.restart(); + const d = fakeProcess(T0 + 40 * MIN); + const boot2 = await armCleanRetriesAtBoot(p, d.deps); + assert.deepEqual(boot2, { armed: [], dropped: ["J0.retry1"] }); + assert.deepEqual(await readCleanRetries(p), []); + d.restart(); +}); + +test("cancel by the deferred job's id removes the record and its timer; nothing is queued, and a late start is refused", async () => { + const p = await jobsDir(); + const proc = fakeProcess(); + await scheduleCleanRetry(p, REQ, proc.deps); + assert.equal(proc.pending.size, 1); + const removed = await cancelCleanRetries(p, { id: "J0" }, proc.deps); + assert.deepEqual(removed.map((e) => e.id), ["J0.retry1"]); + assert.equal(proc.pending.size, 0, "its timer is cleared"); + await proc.advance(60 * MIN); + assert.equal(proc.enqueued.length, 0); + assert.equal(await startCleanRetry(p, "J0.retry1", "job-x"), null, "a job whose record is gone does not run"); +}); + +test("cancel of a retry the schedule already queued cancels its job too", async () => { + const p = await jobsDir(); + const proc = fakeProcess(); + await scheduleCleanRetry(p, REQ, proc.deps); + await proc.advance(15 * MIN); + await cancelCleanRetries(p, { slug: "ch" }, proc.deps); + assert.deepEqual(proc.cancelledJobs, ["job-1"]); + assert.deepEqual(await readCleanRetries(p), []); +}); + +test("one retry per channel: a new one supersedes the old; another channel's is untouched; finish removes it", async () => { + const p = await jobsDir(); + const proc = fakeProcess(); + await scheduleCleanRetry(p, REQ, proc.deps); + await scheduleCleanRetry(p, { ...REQ, slug: "other", of: "J5", deferredJobId: "J5" }, proc.deps); + await scheduleCleanRetry(p, { ...REQ, of: "J9", deferredJobId: "J9" }, proc.deps); + assert.deepEqual((await readCleanRetries(p)).map((e) => e.id).sort(), ["J5.retry1", "J9.retry1"]); + assert.deepEqual((await readCleanRetries(p)).map((e) => e.slug).sort(), ["ch", "other"]); + await finishCleanRetry(p, "J9.retry1"); + assert.deepEqual((await readCleanRetries(p)).map((e) => e.slug), ["other"]); + proc.restart(); +}); + +test("review 2 F3: a relocation or an absent drive when its time comes DEFERS the retry, same attempt — never a silent drop", async () => { + const p = await jobsDir(); + const proc = fakeProcess(); + await scheduleCleanRetry(p, REQ, proc.deps); + proc.setHold('Channel "ch" media is in transition: a media relocation (out) is in progress'); + await proc.advance(15 * MIN); + assert.equal(proc.enqueued.length, 0, "not queued while held"); + const [held] = await readCleanRetries(p); + assert.equal(held.attempt, 1, "the same attempt"); + assert.equal(held.holds, 1); + assert.match(held.heldReason ?? "", /in transition/); + assert.equal(held.notBefore, T0 + 15 * MIN + HOLD_PAUSE_MS); + // A refused enqueue (the job's own media guard) holds it the same way. + proc.setHold(null); + proc.setRefuse("media unreachable"); + await proc.advance(HOLD_PAUSE_MS); + assert.equal((await readCleanRetries(p))[0].holds, 2); + // The media is back: queued, with the same attempt; the reason is cleared. + proc.setRefuse(null); + await proc.advance(HOLD_PAUSE_MS); + assert.equal(proc.enqueued.length, 1); + assert.equal(proc.enqueued[0].attempt, 1); + assert.equal((await readCleanRetries(p))[0].heldReason, undefined); + proc.restart(); +}); + +test("review 2 F3: held for 24 h it gives up VISIBLY — the record stays, says why, is not re-armed at boot, and Cancel dismisses it", async () => { + assert.equal(MAX_HOLDS * HOLD_PAUSE_MS, 24 * 60 * MIN); + const p = await jobsDir(); + const proc = fakeProcess(); + await scheduleCleanRetry(p, REQ, proc.deps); + proc.setHold("the drive is not mounted"); + await proc.advance(15 * MIN); + for (let i = 1; i < MAX_HOLDS; i++) await proc.advance(HOLD_PAUSE_MS); + assert.equal(proc.enqueued.length, 0); + const [gone] = await readCleanRetries(p); + assert.ok(gone, "kept, not dropped"); + assert.match(gone.gaveUp ?? "", /^Gave up after 96 tries over 24 h: the drive is not mounted/); + assert.equal(proc.pending.size, 0, "no timer"); + proc.restart(); + const next = fakeProcess(T0 + 48 * 60 * MIN); + const boot = await armCleanRetriesAtBoot(p, next.deps); + assert.deepEqual(boot.armed, []); + assert.equal((await readCleanRetries(p)).length, 1, "still there for the Cleanup stage"); + await cancelCleanRetries(p, { slug: "ch" }, next.deps); + assert.deepEqual(await readCleanRetries(p), []); +}); diff --git a/common/controller/cleanRetrySchedule.ts b/common/controller/cleanRetrySchedule.ts @@ -0,0 +1,359 @@ +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; + +// THE OFF-QUEUE WAIT OF A RATE-LIMITED CLEAN'S RETRY (lane clean-unverified, +// review 1 F4–F6, operator rulings 4 and 5). +// +// A checked Clean audio the source rate-limited ends deferred and asks for ONE +// retry, not before `notBefore`. That wait used to happen inside a queued job: +// it held the channel's queue (every other cleanup, diarize backfill, attach +// media… and "Clean without checking" itself waited behind it) and, being only +// in memory and in a queued job's spec, a restart either lost it or re-ran it +// at once as a fresh request with two more retries. +// +// Now the wait is a RECORD and a TIMER, and holds no queue and no job slot: +// - the record is durable, `<jobsDir>/clean-retries.json`: one entry per +// scheduled retry, with its attempt, its chain's original job, and its +// not-before time — so a chain never exceeds 2 retries and never runs +// earlier than its not-before, whatever restarts happen; +// - a timer in this process fires at not-before. If the platform's cooldown +// is still running then (it is re-read), the record moves to the +// cooldown's end and the timer is re-armed — at most MAX_REARMS times, +// then the retry is queued anyway and meets the cooldown as a rate limit; +// - only then is the retry QUEUED, as a `clean-audio-retry` job on the +// channel's queue, which re-asserts every guard as any job does (and the +// sweep again immediately before it removes anything); +// - the boot arms every record again (an idle boot does not, and keeps them). +// A retry that a restart caught queued is re-armed from its record (the +// boot pass closes its stale meta: the kind is `rescheduledOnBoot`); one a +// restart caught RUNNING is re-armed once, then dropped. +// CANCEL reaches it three ways: `cancelCleanRetries` by the deferred job's id +// (/jobs' and `pnpm ops job {"verb":"cancel"}`'s Cancel of that job, through +// cancelJobAction), the channel's Cleanup stage ("Cancel retry"), and any +// new clean of the channel a person starts, which supersedes it. A record +// cancelled while its job is queued cancels that job too. + +export type ScheduledCleanRetry = { + // This retry's own id: `<of>.retry<attempt>`. + id: string; + slug: string; + // 1-based; at most CLEAN_RATE_LIMIT_MAX_RETRIES (cleanAudioJob.ts). + attempt: number; + // The ORIGINAL request's job id (the chain's). + of: string; + // The job that ended deferred and asked for this retry. + deferredJobId: string; + // The platform key the rate limit was recorded under (its cooldown). + platform: string; + // Never queued before this (epoch ms). + notBefore: number; + scheduledAt: number; + // scheduled: waiting off-queue. enqueued: its job is in the channel queue. + // running: its job started (removed when the job ends). + state: "scheduled" | "enqueued" | "running"; + jobId?: string; + // Times the timer moved later for a platform cooldown still running. + rearms?: number; + // Times a restart caught it running and it was re-armed. + restarts?: number; + // HELD (review 2 F3): times its time came while the channel's media was not + // reachable (a relocation in flight, a drive away) or its job was refused, + // and why the last time — so the Cleanup stage can say so. + holds?: number; + heldReason?: string; + // Set when it was held MAX_HOLDS times in a row: it no longer fires, and + // the Cleanup stage says why until a person dismisses it (Cancel retry) or a + // new clean replaces it. Never dropped silently. + gaveUp?: string; +}; + +type StoreFile = { version: 1; retries: ScheduledCleanRetry[] }; + +export const CLEAN_RETRIES_FILENAME = "clean-retries.json"; +export const MAX_REARMS = 8; +// A retry whose channel's media is held when its time comes waits HOLD_PAUSE_MS +// and tries again, at most MAX_HOLDS times: 96 × 15 min = 24 hours. A media +// move of a large channel takes hours, and a drive coming back after a reboot +// minutes, so a day covers both; a drive away longer than that is not a pause, +// and a retry a day late is no longer the clean that was asked for — it gives +// up visibly instead. +export const HOLD_PAUSE_MS = 15 * 60_000; +export const MAX_HOLDS = 96; +// setTimeout's ceiling (~24.8 days); a longer wait is re-armed when it fires. +const MAX_TIMER_MS = 2 ** 31 - 1; + +export function cleanRetriesFile(paths: Pick<Paths, "jobsDir">): string { + return path.join(paths.jobsDir, CLEAN_RETRIES_FILENAME); +} + +function isEntry(v: unknown): v is ScheduledCleanRetry { + const e = v as Partial<ScheduledCleanRetry> | null; + return ( + !!e && + typeof e.id === "string" && + typeof e.slug === "string" && + typeof e.attempt === "number" && + typeof e.of === "string" && + typeof e.notBefore === "number" && + (e.state === "scheduled" || e.state === "enqueued" || e.state === "running") + ); +} + +export async function readCleanRetries(paths: Pick<Paths, "jobsDir">): Promise<ScheduledCleanRetry[]> { + const r = await readJsonFile(cleanRetriesFile(paths)); + if (!r.ok) return []; + const list = (r.value as Partial<StoreFile> | null)?.retries; + return Array.isArray(list) ? list.filter(isEntry) : []; +} + +// Read-modify-write under the file's lock; `fn` returns the new list, or +// `list: null` when nothing changed (no write: a clean with no retry +// scheduled writes nothing). +async function update<T>( + paths: Pick<Paths, "jobsDir">, + fn: (list: ScheduledCleanRetry[]) => { list: ScheduledCleanRetry[] | null; out: T }, +): Promise<T> { + const file = cleanRetriesFile(paths); + return withJsonFileLock(file, async () => { + const { list, out } = fn(await readCleanRetries(paths)); + if (list) await writeJsonAtomic(file, { version: 1, retries: list } satisfies StoreFile, { mkdir: true }); + return out; + }); +} + +export type CleanRetryDeps = { + now?: () => number; + // The timer's callback answers the fire's promise (a test awaits it). + setTimer?: (fn: () => Promise<unknown>, ms: number) => unknown; + clearTimer?: (handle: unknown) => void; + cooldownRemainingMs: (platform: string) => Promise<number>; + // Queue the retry's job on the channel's queue. + enqueue: (entry: ScheduledCleanRetry) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>; + // Cancel a queued job (the registry's cancel). + cancelJob?: (jobId: string) => boolean; + // Why the channel's media cannot be touched now (a relocation marker, an + // unreachable drive), or null — asked when the timer fires, before queueing. + mediaHold?: (slug: string) => Promise<string | null>; + log?: (m: string) => void; +}; + +// The timers of this process, keyed by retry id; on globalThis like the +// registry, so a reloaded module does not arm a second timer for one record. +type TimerState = { timers: Map<string, unknown> }; +declare global { + // eslint-disable-next-line no-var + var __yttCleanRetryTimers__: TimerState | undefined; +} +function timers(): Map<string, unknown> { + return (globalThis.__yttCleanRetryTimers__ ??= { timers: new Map() }).timers; +} + +function clearTimerFor(id: string, deps: CleanRetryDeps): void { + const t = timers().get(id); + if (t !== undefined) (deps.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>)))(t); + timers().delete(id); +} + +function arm(paths: Pick<Paths, "jobsDir">, entry: ScheduledCleanRetry, deps: CleanRetryDeps): void { + clearTimerFor(entry.id, deps); + if (entry.gaveUp) return; + const now = (deps.now ?? Date.now)(); + const ms = Math.min(MAX_TIMER_MS, Math.max(0, entry.notBefore - now)); + const set = deps.setTimer ?? ((fn: () => Promise<unknown>, d: number) => setTimeout(() => void fn(), d)); + const handle = set(() => { + timers().delete(entry.id); + return fireCleanRetry(paths, entry.id, deps).catch((err) => + deps.log?.(`[clean-retry] ${entry.id}: ${(err as Error).message}`), + ); + }, ms); + timers().set(entry.id, handle); +} + +// Schedule a retry: write its record, arm its timer. A channel has at most one +// scheduled retry: a record already there for the slug is superseded. +export async function scheduleCleanRetry( + paths: Pick<Paths, "jobsDir">, + req: Omit<ScheduledCleanRetry, "id" | "state" | "scheduledAt">, + deps: CleanRetryDeps, +): Promise<ScheduledCleanRetry> { + const entry: ScheduledCleanRetry = { + ...req, + id: `${req.of}.retry${req.attempt}`, + state: "scheduled", + scheduledAt: (deps.now ?? Date.now)(), + }; + const superseded = await update(paths, (list) => ({ + list: [...list.filter((e) => e.slug !== req.slug), entry], + out: list.filter((e) => e.slug === req.slug), + })); + for (const old of superseded) { + clearTimerFor(old.id, deps); + if (old.state === "enqueued" && old.jobId) deps.cancelJob?.(old.jobId); + } + arm(paths, entry, deps); + return entry; +} + +// The timer fired: queue the retry, or move it to the end of a cooldown that +// is still running. A record cancelled meanwhile is simply not there. +export async function fireCleanRetry( + paths: Pick<Paths, "jobsDir">, + id: string, + deps: CleanRetryDeps, +): Promise<"enqueued" | "rearmed" | "gone" | "early" | "held" | "gave-up"> { + const now = (deps.now ?? Date.now)(); + const entry = (await readCleanRetries(paths)).find((e) => e.id === id); + if (!entry || entry.state !== "scheduled" || entry.gaveUp) return "gone"; + // Never before its time (a long wait is armed in setTimeout-sized steps). + if (now < entry.notBefore) { + arm(paths, entry, deps); + return "early"; + } + const cooldown = await deps.cooldownRemainingMs(entry.platform).catch(() => 0); + if (cooldown > 0 && (entry.rearms ?? 0) < MAX_REARMS) { + const moved = await update(paths, (list) => { + const e = list.find((x) => x.id === id && x.state === "scheduled"); + if (!e) return { list: null, out: null }; + e.notBefore = now + cooldown; + e.rearms = (e.rearms ?? 0) + 1; + return { list, out: { ...e } }; + }); + if (!moved) return "gone"; + deps.log?.(`[clean-retry] ${id}: ${entry.platform} is still cooling down; moved to ${new Date(moved.notBefore).toISOString()}.`); + arm(paths, moved, deps); + return "rearmed"; + } + // THE MEDIA HELD (review 2 F3): a relocation in flight or a drive away when + // its time comes DEFERS the retry, same attempt; so does a refused enqueue + // (the job's own media guard). Never a silent drop. + const held = await (deps.mediaHold?.(entry.slug) ?? Promise.resolve(null)).catch((err) => (err as Error).message); + const res = held + ? ({ ok: false as const, error: held }) + : await deps.enqueue(entry).catch((err) => ({ ok: false as const, error: (err as Error).message })); + if (!res.ok) { + const after = await update(paths, (list) => { + const e = list.find((x) => x.id === id && x.state === "scheduled"); + if (!e) return { list: null, out: null }; + e.holds = (e.holds ?? 0) + 1; + e.heldReason = res.error; + if (e.holds >= MAX_HOLDS) { + e.gaveUp = + `Gave up after ${e.holds} tries over ${Math.round((MAX_HOLDS * HOLD_PAUSE_MS) / 3_600_000)} h: ${res.error}. ` + + "Nothing was asked or cleaned; run Clean audio again once the channel's media is back."; + } else { + e.notBefore = now + HOLD_PAUSE_MS; + } + return { list, out: { ...e } }; + }); + if (!after) return "gone"; + if (after.gaveUp) { + deps.log?.(`[clean-retry] ${id}: ${after.gaveUp}`); + return "gave-up"; + } + deps.log?.(`[clean-retry] ${id}: held (${res.error}); tries again at ${new Date(after.notBefore).toISOString()}.`); + arm(paths, after, deps); + return "held"; + } + const kept = await update(paths, (list) => { + const e = list.find((x) => x.id === id); + if (!e) return { list: null, out: false }; + // A Start that raced ahead of this write has already moved it on. + if (e.state === "scheduled") { + e.state = "enqueued"; + e.jobId = res.jobId; + delete e.heldReason; + } + return { list, out: true }; + }); + // Cancelled between the enqueue and this write: cancel the job too. + if (!kept) deps.cancelJob?.(res.jobId); + return "enqueued"; +} + +// The retry's job started: mark it running. Null = the record is gone (it was +// cancelled or superseded) and the job must not run. +export async function startCleanRetry( + paths: Pick<Paths, "jobsDir">, + id: string, + jobId: string, +): Promise<ScheduledCleanRetry | null> { + return update(paths, (list) => { + const e = list.find((x) => x.id === id); + if (!e) return { list: null, out: null }; + e.state = "running"; + e.jobId = jobId; + return { list, out: { ...e } }; + }); +} + +// The retry's job ended, however it ended: its record goes. +export async function finishCleanRetry(paths: Pick<Paths, "jobsDir">, id: string): Promise<void> { + await update(paths, (list) => ({ list: list.some((e) => e.id === id) ? list.filter((e) => e.id !== id) : null, out: null })); +} + +// Cancel scheduled retries: by the slug, by a retry's own id, by the job that +// ended deferred, or by the chain's original job. A record whose job is +// queued cancels that job too; a RUNNING retry is the job's own Cancel's. +export async function cancelCleanRetries( + paths: Pick<Paths, "jobsDir">, + match: { slug?: string; id?: string }, + deps: Pick<CleanRetryDeps, "cancelJob" | "clearTimer">, +): Promise<ScheduledCleanRetry[]> { + const hit = (e: ScheduledCleanRetry) => + e.state !== "running" && + ((match.slug !== undefined && e.slug === match.slug) || + (match.id !== undefined && (e.id === match.id || e.deferredJobId === match.id || e.of === match.id || e.jobId === match.id))); + const removed = await update(paths, (list) => { + const out = list.filter(hit); + return { list: out.length ? list.filter((e) => !hit(e)) : null, out }; + }); + for (const e of removed) { + clearTimerFor(e.id, deps as CleanRetryDeps); + if (e.state === "enqueued" && e.jobId) deps.cancelJob?.(e.jobId); + } + return removed; +} + +// THE BOOT: arm every record again. A retry a restart caught queued is +// scheduled again (its time has passed, so it is queued at once — never +// earlier than its not-before). One caught running is re-armed once; a second +// time it is dropped, so a retry that takes the server down cannot loop. +export async function armCleanRetriesAtBoot( + paths: Pick<Paths, "jobsDir">, + deps: CleanRetryDeps, +): Promise<{ armed: string[]; dropped: string[] }> { + const out = await update(paths, (list) => { + const armed: ScheduledCleanRetry[] = []; + const dropped: string[] = []; + const next: ScheduledCleanRetry[] = []; + for (const e of list) { + if (e.gaveUp) { + next.push(e); // kept for the Cleanup stage to say why; never fired + continue; + } + if (e.state === "running") { + if ((e.restarts ?? 0) >= 1) { + dropped.push(e.id); + continue; + } + e.restarts = (e.restarts ?? 0) + 1; + } + e.state = "scheduled"; + delete e.jobId; + next.push(e); + armed.push({ ...e }); + } + return { list: list.length ? next : null, out: { armed, dropped } }; + }); + for (const e of out.armed) arm(paths, e, deps); + for (const id of out.dropped) { + deps.log?.(`[clean-retry] ${id}: a restart interrupted it twice while it ran; dropped (run Clean audio again).`); + } + return { armed: out.armed.map((e) => e.id), dropped: out.dropped }; +} + +// For tests: forget every timer of this process (clearing each). +export function resetCleanRetryTimers(deps: Pick<CleanRetryDeps, "clearTimer"> = {}): void { + for (const id of [...timers().keys()]) clearTimerFor(id, deps as CleanRetryDeps); +} diff --git a/common/controller/cleanUnchecked.test.ts b/common/controller/cleanUnchecked.test.ts @@ -0,0 +1,540 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { + cleanAudioForVideo, + cleanAudioFromTranscribed, + planAudioClean, +} from "./cleanAudioFromTranscribed"; +import type { VerifyProbes } from "./verifyBeforeClean"; +import type { CheckRequestDeps } from "./availabilityVerdict"; +import { runCleanAudioJob, uncheckedReasonFor } from "./cleanAudioJob"; +import { parseChannelConfig } from "../lib/channelConfig"; +import { channelConfigSchema } from "../lib/channelConfigSchema"; +import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; +import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server"; +import { createChannel, readChannelConfig } from "./channels"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanUnchecked.test.ts +// +// CLEAN WITHOUT CHECKING (lane clean-unverified). The availability verdict is +// the ONE gate skipped; every other protection holds. Temp corpus, temp +// settings; every probe is a stub that throws, so a test that reaches the +// network fails loudly — and each asserts its probe was never called. + +const ROOT = await mkdtemp(path.join(tmpdir(), "clean-unchecked-")); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0"; + +async function settings(diarization: Record<string, unknown>, over: Record<string, unknown> = {}) { + await writeFile( + process.env.SETTINGS_FILE!, + JSON.stringify({ + verifyAvailabilityBeforeClean: true, + diarization: { enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx", ...diarization }, + ...over, + }), + ); +} + +const VOICEPRINTS = [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }]; +function sidecar(voiceprints: boolean): string { + return JSON.stringify({ + videoId: "v", + generatedAt: "2026-08-07T00:00:00.000Z", + speakers: 1, + turns: [{ start: 0, end: 4, speaker: 0 }], + engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 }, + ...(voiceprints ? { voiceprints: VOICEPRINTS } : {}), + }); +} + +// Probes that count their calls and throw — the source "rate-limits" every ask. +function throwingProbes() { + const calls = { quick: 0, full: 0, backoff: 0 }; + const probes: VerifyProbes = { + quick: async () => { + calls.quick++; + throw new Error("HTTP Error 429: Too Many Requests"); + }, + full: async () => { + calls.full++; + throw new Error("HTTP Error 429: Too Many Requests"); + }, + recordBackoff: async () => { + calls.backoff++; + }, + }; + return { calls, probes }; +} + +const NO_CHECK: CheckRequestDeps = { + start: async () => { + throw new Error("a test asked for a real availability check"); + }, + platformRefusal: async () => null, + serviceAlert: async () => null, +}; + +let n = 0; +async function corpus(config: Record<string, unknown> = {}) { + const dir = path.join(ROOT, `c${n++}`); + const paths = { + channelsDir: path.join(dir, "channels"), + transcriptsDir: dir, + savedVideosDir: path.join(dir, "saved"), + ytdlpBin: path.join(dir, "no-such-ytdlp"), + } as unknown as Paths; + await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); + await writeFile( + path.join(paths.channelsDir, "ch", "config.json"), + JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.twitch.tv/example", ...config }), + ); + const video = async ( + id: string, + o: { + transcript?: boolean; + diarization?: "plain" | "voiceprints"; + doNotClean?: boolean; + gone?: boolean; + bytes?: number; + uploadDate?: string; + } = {}, + ) => { + const v = path.join(paths.channelsDir, "ch", "data", id); + await mkdir(v, { recursive: true }); + if (o.uploadDate) await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, upload_date: o.uploadDate })); + if (o.transcript !== false) await writeFile(path.join(v, "transcript.json"), "{}"); + await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(o.bytes ?? 1000)); + if (o.diarization === "plain") await writeFile(path.join(v, "diarization.json"), sidecar(false)); + if (o.diarization === "voiceprints") await writeFile(path.join(v, "diarization.json"), sidecar(true)); + if (o.doNotClean) { + await writeFile(path.join(v, "do-not-clean.json"), JSON.stringify({ setAt: "now", note: "deleted from source (pre-clean check): deleted" })); + } + if (o.gone) { + await writeFile(path.join(v, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), availability: "deleted" })); + } + return v; + }; + return { paths, video }; +} + +const exists = (f: string) => access(f).then(() => true, () => false); + +async function seed(video: Awaited<ReturnType<typeof corpus>>["video"]) { + return { + expired: await video("expired", { diarization: "voiceprints", gone: true, bytes: 3000 }), + plain: await video("listed", { diarization: "voiceprints", bytes: 2000 }), + pinned: await video("pinned", { diarization: "voiceprints", doNotClean: true }), + noprint: await video("noprint", { diarization: "plain" }), + nodiar: await video("nodiar"), + untranscribed: await video("untranscribed", { transcript: false, diarization: "voiceprints" }), + }; +} + +test("unchecked: removes transcribed audio though every probe would throw, asks none, keeps every other protection", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await seed(video); + const { calls, probes } = throwingProbes(); + const logs: string[] = []; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m), unchecked: "button", probes }); + + assert.deepEqual(calls, { quick: 0, full: 0, backoff: 0 }, "the source was never asked"); + // Gone from source and expired VODs go too: that is what was asked for. + assert.equal(await exists(path.join(v.expired, "audio.mp3")), false); + assert.equal(await exists(path.join(v.plain, "audio.mp3")), false); + assert.equal(await exists(path.join(v.expired, "do-not-clean.json")), false, "no pin written"); + // Every other protection holds. + assert.equal(await exists(path.join(v.pinned, "audio.mp3")), true, "do-not-clean"); + assert.equal(await exists(path.join(v.noprint, "audio.mp3")), true, "awaiting voice fingerprint"); + assert.equal(await exists(path.join(v.nodiar, "audio.mp3")), true, "awaiting diarization"); + assert.equal(await exists(path.join(v.untranscribed, "audio.mp3")), true, "not transcribed"); + assert.equal(r.cleanedDirs, 2); + assert.equal(r.bytesFreed, 5000); + assert.equal(r.unverified, 0); + assert.equal(r.pinned, 0); + assert.equal(r.stopped, undefined); + assert.ok(logs[0]?.startsWith("Clean without checking:"), logs.join("\n")); +}); + +test("the dry plan counts exactly what the unchecked clean removes, and asks nothing", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await seed(video); + const plan = await planAudioClean({ channelSlug: "ch", paths }); + assert.deepEqual(plan, { + inspected: 6, + ids: ["expired", "listed"], + videos: 2, + files: 2, + bytes: 5000, + protected: 1, + awaitingDiarization: 1, + awaitingVoiceprint: 1, + }); + // Nothing was deleted by the plan. + assert.equal(await exists(path.join(v.plain, "audio.mp3")), true); + const { probes } = throwingProbes(); + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, unchecked: "button", probes }); + assert.equal(r.removedFiles, plan.files); + assert.equal(r.bytesFreed, plan.bytes); + assert.equal(r.cleanedDirs, plan.videos); +}); + +test("checked: unchanged — the same gate runs, pins the gone, cleans the listed, and logs as before", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await seed(video); + let quick = 0; + const probes: VerifyProbes = { + quick: async () => { + quick++; + return { knownCount: 6, freshCount: 6, maybeMissingCount: 0, ids: [] }; + }, + full: async () => { + throw new Error("no suspects: tier C is not reached"); + }, + }; + const logs: string[] = []; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m), probes }); + assert.equal(quick, 1); + assert.equal(await exists(path.join(v.expired, "audio.mp3")), true, "tier A pins the cached gone"); + assert.equal(await exists(path.join(v.expired, "do-not-clean.json")), true); + assert.equal(await exists(path.join(v.plain, "audio.mp3")), false); + assert.equal(r.pinned, 1); + assert.equal(r.stopped, undefined); + assert.ok(!logs.some((l) => l.includes("without checking")), logs.join("\n")); + assert.ok(logs.includes("Verify before clean: all 1 candidate(s) still listed on the source."), logs.join("\n")); + assert.ok( + logs.includes( + "Cleaned 1 audio file(s) from 1 of 6 video dir(s). Skipped 4 (1 protected, 1 gone-from-source pinned, 0 unverified, 1 awaiting diarization, 1 awaiting voice fingerprint).", + ), + logs.join("\n"), + ); +}); + +test("checked: a rate-limited listing cleans nothing unverified and says why it stopped", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await seed(video); + const { calls, probes } = throwingProbes(); + // A rate-limited listing is what runYtdlp throws for a 429 on it. + probes.quick = async () => { + calls.quick++; + throw new EnumerationIncompleteError(1, "twitch", null, 0); + }; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, probes }); + assert.equal(calls.quick, 1); + assert.equal(calls.backoff, 1, "the platform cooldown is recorded, as Sync does"); + assert.equal(r.cleanedDirs, 0); + assert.equal(await exists(path.join(v.plain, "audio.mp3")), true); + assert.deepEqual(r.stopped && { kind: r.stopped.kind, platform: r.stopped.platform }, { kind: "rate-limit", platform: "twitch" }); +}); + +test("checked: a listing that fails for another reason is an error stop, not a rate limit, and records no cooldown", async () => { + await settings({}); + const { paths, video } = await corpus(); + await seed(video); + const { calls, probes } = throwingProbes(); + probes.quick = async () => { + calls.quick++; + throw new Error("yt-dlp exited with code 1"); + }; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, probes }); + assert.equal(r.cleanedDirs, 0); + assert.equal(r.stopped?.kind, "error"); + assert.equal(calls.backoff, 0); +}); + +test("the channel key: absent = checked (no reason), true = unchecked by the channel setting", () => { + assert.equal(uncheckedReasonFor(parseChannelConfig({ handling: "transcribe", name: "a" })), undefined); + assert.equal(uncheckedReasonFor(parseChannelConfig({ handling: "transcribe", name: "a", cleanAudioWithoutChecking: false })), undefined); + assert.equal(uncheckedReasonFor(parseChannelConfig({ handling: "transcribe", name: "a", cleanAudioWithoutChecking: true })), "channel-setting"); + assert.equal(uncheckedReasonFor(null), undefined); + // The schema keeps it (true) and omits anything else. + assert.equal(channelConfigSchema.parse({ handling: "transcribe", cleanAudioWithoutChecking: true })?.cleanAudioWithoutChecking, true); + assert.equal("cleanAudioWithoutChecking" in (channelConfigSchema.parse({ handling: "transcribe", cleanAudioWithoutChecking: "yes" }) ?? {}), false); +}); + +test("key on: the sweep the action runs asks nothing and keeps the protections", async () => { + await settings({}); + const { paths, video } = await corpus({ cleanAudioWithoutChecking: true }); + const v = await seed(video); + const config = JSON.parse(await readFile(path.join(paths.channelsDir, "ch", "config.json"), "utf8")); + const { calls, probes } = throwingProbes(); + const r = await cleanAudioFromTranscribed({ + channelSlug: "ch", + paths, + onLog: () => {}, + unchecked: uncheckedReasonFor(parseChannelConfig(config)), + probes, + }); + assert.deepEqual(calls, { quick: 0, full: 0, backoff: 0 }); + assert.equal(r.cleanedDirs, 2); + assert.equal(await exists(path.join(v.pinned, "audio.mp3")), true); + assert.equal(await exists(path.join(v.noprint, "audio.mp3")), true); + assert.equal(await exists(path.join(v.untranscribed, "audio.mp3")), true); +}); + +test("key on: clean after capture asks no check, reads no verdict, and cleans an expired VOD — protections still hold", async () => { + await settings({}); + const { paths, video } = await corpus({ cleanAudioWithoutChecking: true }); + const v = await seed(video); + const logs: string[] = []; + const one = (id: string) => cleanAudioForVideo({ channelSlug: "ch", paths, videoId: id, onLog: (m) => logs.push(m), checkDeps: NO_CHECK }); + assert.equal((await one("expired")).outcome, "cleaned"); + assert.equal(await exists(path.join(v.expired, "audio.mp3")), false); + assert.equal((await one("listed")).outcome, "cleaned"); + assert.equal((await one("pinned")).gate, "do-not-clean"); + assert.equal((await one("noprint")).gate, "awaiting-voiceprint"); + assert.equal((await one("untranscribed")).gate, "no-transcript"); + assert.ok(logs.some((l) => l.includes("without checking")), logs.join("\n")); +}); + +test("key off: clean after capture is unchanged — no verdict, held awaiting a check", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await video("v1", { diarization: "voiceprints" }); + let started = 0; + const out = await cleanAudioForVideo({ + channelSlug: "ch", + paths, + videoId: "v1", + onLog: () => {}, + checkDeps: { start: async () => (started++, { ok: true, jobId: "x" }) as never, platformRefusal: async () => null, serviceAlert: async () => null }, + }); + assert.equal(out.gate, "awaiting-availability"); + assert.equal(started, 1); + assert.equal(await exists(path.join(v, "audio.mp3")), true); +}); + +// --- Review 1 ----------------------------------------------------------------- + +test("F1 (BLOCKING): an unchecked sweep never prunes a saved video container — a rolled-out keep-latest container of an expired VOD survives", async () => { + await settings({ enabled: false }); + const { paths, video } = await corpus({ keepLatest: 1 }); + // The newest video is in the window; the old one rolled out of it, has a + // transcript, audio and a saved container kept by the window — and is gone + // from the source (its VOD expired). The container may be its only copy. + await video("new", { uploadDate: "20261101" }); + const old = await video("old", { uploadDate: "20261001", gone: true }); + await writeFile(path.join(old, "source-media.mp4"), "container-bytes"); + await persistSourceVideo({ + videoDir: old, + sourceFilename: "source-media.mp4", + storeDir: path.join(paths.savedVideosDir, "ch", "old"), + keepReason: "keep-latest", + }); + const { calls, probes } = throwingProbes(); + const logs: string[] = []; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m), unchecked: "button", probes }); + assert.deepEqual(calls, { quick: 0, full: 0, backoff: 0 }); + assert.equal(await exists(path.join(old, "audio.mp3")), false, "its audio is what was asked to go"); + assert.notEqual(await loadSavedVideo(old), null, "the saved container is untouched"); + assert.equal(await exists(path.join(paths.savedVideosDir, "ch", "old", "source-media.mp4")), true); + assert.equal(r.prunedSavedVideos, 0); + assert.ok(logs.some((l) => l.startsWith("Saved-video retention prune skipped")), logs.join("\n")); + // The keep-latest window held its audio in the unchecked path too. + assert.equal(await exists(path.join(paths.channelsDir, "ch", "data", "new", "audio.mp3")), true, "in the keep-latest window"); +}); + +test("the keep-latest window: the unchecked sweep and its plan both keep it", async () => { + await settings({ enabled: false }); + const { paths, video } = await corpus({ keepLatest: 2 }); + const a = await video("a", { uploadDate: "20261103" }); + const b = await video("b", { uploadDate: "20261102" }); + const c = await video("c", { uploadDate: "20261101" }); + const plan = await planAudioClean({ channelSlug: "ch", paths }); + assert.deepEqual(plan.ids, ["c"]); + assert.equal(plan.protected, 2); + const { probes } = throwingProbes(); + await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, unchecked: "button", onlyIds: plan.ids, probes }); + assert.equal(await exists(path.join(a, "audio.mp3")), true); + assert.equal(await exists(path.join(b, "audio.mp3")), true); + assert.equal(await exists(path.join(c, "audio.mp3")), false); +}); + +test("F2: plan, then the corpus changes, then the run — it removes only the intersection and leaves the newly eligible", async () => { + await settings({}); + const { paths, video } = await corpus(); + const p1 = await video("p1", { diarization: "voiceprints" }); + const p2 = await video("p2", { diarization: "voiceprints" }); + const later = await video("later", { diarization: "plain" }); // awaiting a fingerprint at plan time + const plan = await planAudioClean({ channelSlug: "ch", paths }); + assert.deepEqual(plan.ids, ["p1", "p2"]); + assert.equal(plan.awaitingVoiceprint, 1); + // Meanwhile: p2 is marked do not clean; "later" gets its fingerprints. + await writeFile(path.join(p2, "do-not-clean.json"), JSON.stringify({ setAt: "now" })); + await writeFile(path.join(later, "diarization.json"), sidecar(true)); + const { calls, probes } = throwingProbes(); + const logs: string[] = []; + const r = await cleanAudioFromTranscribed({ + channelSlug: "ch", + paths, + onLog: (m) => logs.push(m), + unchecked: "button", + onlyIds: plan.ids, + probes, + }); + assert.deepEqual(calls, { quick: 0, full: 0, backoff: 0 }); + assert.equal(await exists(path.join(p1, "audio.mp3")), false); + assert.equal(await exists(path.join(p2, "audio.mp3")), true, "became protected since: skipped"); + assert.equal(await exists(path.join(later, "audio.mp3")), true, "newly eligible: not in the confirmed plan"); + assert.equal(r.cleanedDirs, 1); + assert.equal(r.notInPlan, 1); + assert.equal(r.planNoLongerEligible, 1); + assert.ok(logs.some((l) => l.includes("left for the next run (not in the confirmed plan)")), logs.join("\n")); +}); + +test("tier-linked audio: the plan counts the bytes through the link, and the sweep removes link and bytes", async () => { + await settings({ enabled: false }); + const { paths, video } = await corpus(); + const v = await video("t1", { bytes: 1 }); + // Tier the audio: the real file in channels/ch/media/t1/, a relative link in data/t1/. + const mediaDir = path.join(paths.channelsDir, "ch", "media", "t1"); + await mkdir(mediaDir, { recursive: true }); + await writeFile(path.join(mediaDir, "audio.mp3"), Buffer.alloc(4096)); + await rm(path.join(v, "audio.mp3")); + await symlink("../../media/t1/audio.mp3", path.join(v, "audio.mp3")); + const plan = await planAudioClean({ channelSlug: "ch", paths }); + assert.equal(plan.bytes, 4096); + const { probes } = throwingProbes(); + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, unchecked: "button", onlyIds: plan.ids, probes }); + assert.equal(r.bytesFreed, 4096); + assert.equal(await exists(path.join(mediaDir, "audio.mp3")), false, "the bytes on the media tier go with the link"); +}); + +test("an unreachable drive or a relocation in flight: the plan refuses, and the sweep removes nothing", async () => { + await settings({ enabled: false }); + for (const hold of ["relocating", "unmounted"] as const) { + const { paths, video } = await corpus( + hold === "unmounted" ? { mediaDir: "/nonexistent-drive/ch/media" } : {}, + ); + const v = await video("v1"); + const channelDir = path.join(paths.channelsDir, "ch"); + if (hold === "relocating") { + await writeFile( + path.join(channelDir, ".relocating.json"), + JSON.stringify({ target: "/elsewhere/ch/media", direction: "out", startedAt: "now", phase: "copy", scope: "media" }), + ); + } else { + await symlink("/nonexistent-drive/ch/media", path.join(channelDir, "media")); + } + const why = hold === "relocating" ? /relocation/ : /does not exist/; + await assert.rejects(planAudioClean({ channelSlug: "ch", paths }), why); + const { probes } = throwingProbes(); + await assert.rejects( + cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, unchecked: "button", onlyIds: ["v1"], probes }), + why, + ); + assert.equal(await exists(path.join(v, "audio.mp3")), true, `${hold}: nothing removed`); + } +}); + +test("an empty transcript.json counts as transcribed in both paths alike (parity: the name decides, as before this lane)", async () => { + await settings({ enabled: false }); + const { paths, video } = await corpus(); + await video("e1"); // transcript.json is "{}" + const plan = await planAudioClean({ channelSlug: "ch", paths }); + assert.deepEqual(plan.ids, ["e1"]); +}); + +test("key on: clean after capture still holds a whole-recording channel's audio and a URL-less channel's", async () => { + await settings({ enabled: false }); + const whole = await corpus({ cleanAudioWithoutChecking: true, url: "https://rumble.com/c/example", platform: "rumble" }); + const w = await whole.video("w1"); + const out1 = await cleanAudioForVideo({ channelSlug: "ch", paths: whole.paths, videoId: "w1", onLog: () => {}, checkDeps: NO_CHECK }); + assert.equal(out1.gate, "whole-recording"); + assert.equal(await exists(path.join(w, "audio.mp3")), true); + const nourl = await corpus({ cleanAudioWithoutChecking: true, url: undefined }); + const u = await nourl.video("u1"); + const out2 = await cleanAudioForVideo({ channelSlug: "ch", paths: nourl.paths, videoId: "u1", onLog: () => {}, checkDeps: NO_CHECK }); + assert.equal(out2.gate, "no-source-url"); + assert.equal(await exists(path.join(u, "audio.mp3")), true); +}); + +test("no leak: a channel beside a key-on one is cleaned checked", async () => { + await settings({ enabled: false }); + const { paths, video } = await corpus({ cleanAudioWithoutChecking: true }); + await video("k1"); + // A second channel in the same corpus, key absent. + const other = path.join(paths.channelsDir, "other", "data", "o1"); + await mkdir(other, { recursive: true }); + await writeFile(path.join(paths.channelsDir, "other", "config.json"), JSON.stringify({ handling: "transcribe", name: "o", url: "https://www.twitch.tv/other" })); + await writeFile(path.join(other, "transcript.json"), "{}"); + await writeFile(path.join(other, "audio.mp3"), Buffer.alloc(10)); + assert.equal(uncheckedReasonFor(await readChannelConfig(paths, "other")), undefined); + assert.equal(uncheckedReasonFor(await readChannelConfig(paths, "ch")), "channel-setting"); + let started = 0; + const out = await cleanAudioForVideo({ + channelSlug: "other", + paths, + videoId: "o1", + onLog: () => {}, + checkDeps: { start: async () => (started++, { ok: true, jobId: "x" }) as never, platformRefusal: async () => null, serviceAlert: async () => null }, + }); + assert.equal(out.gate, "awaiting-availability", "the other channel is checked"); + assert.equal(started, 1); +}); + +test("a new channel never starts with cleanAudioWithoutChecking: createChannel drops it", async () => { + const { paths } = await corpus(); + await createChannel(paths, "fresh", parseChannelConfig({ handling: "transcribe", name: "f", cleanAudioWithoutChecking: true })!); + const cfg = JSON.parse(await readFile(path.join(paths.channelsDir, "fresh", "config.json"), "utf8")); + assert.equal("cleanAudioWithoutChecking" in cfg, false); + assert.equal(cfg.name, "f"); +}); + +// --- Review 2 ----------------------------------------------------------------- + +test("review 2 F1: a checked clean the source rate-limits prunes no saved container — across the whole retry chain", async () => { + await settings({ enabled: false }); + const { paths, video } = await corpus({ keepLatest: 1, url: "https://rumble.com/c/example" }); + await video("new", { uploadDate: "20261101" }); + // Rolled out of the window, gone upstream, never probed: only the listing + // could have found it gone, and the listing is rate-limited. + const old = await video("old", { uploadDate: "20261001" }); + await writeFile(path.join(old, "source-media.mp4"), "container-bytes"); + await persistSourceVideo({ + videoDir: old, + sourceFilename: "source-media.mp4", + storeDir: path.join(paths.savedVideosDir, "ch", "old"), + keepReason: "keep-latest", + }); + const { calls, probes } = throwingProbes(); + probes.quick = async () => { + calls.quick++; + throw new EnumerationIncompleteError(1, "rumble", null, 0); + }; + const T = Date.parse("2026-11-21T03:00:00.000Z"); + const retries: Array<undefined | { attempt: number; of: string; notBefore: number; platform: string }> = [ + undefined, + { attempt: 1, of: "j0", notBefore: T - 1, platform: "rumble" }, + { attempt: 2, of: "j0", notBefore: T - 1, platform: "rumble" }, + ]; + const ends: string[] = []; + for (const retry of retries) { + const logs: string[] = []; + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: retry ? `j${retry.attempt}` : "j0", + ...(retry ? { retry } : {}), + onLog: (m) => logs.push(m), + deps: { probes, now: () => T, cooldownRemainingMs: async () => 0, scheduleRetry: async (r) => ({ ok: true, id: `${r.of}.retry${r.attempt}` }) }, + }); + ends.push(out.end); + assert.notEqual(await loadSavedVideo(old), null, `the container survives step ${retry?.attempt ?? 0}`); + assert.ok( + logs.some((l) => l.startsWith("Saved-video retention prune skipped: the availability check did not complete (rate-limited by rumble)")), + logs.join("\n"), + ); + } + assert.deepEqual(ends, ["deferred", "deferred", "failed"]); + assert.equal(await exists(path.join(old, "audio.mp3")), true, "nothing unverified was cleaned"); +}); diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts @@ -6,6 +6,9 @@ import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; import { readChannelConfig } from "./channels"; import { runAvailabilityCheck } from "./checkAvailability"; import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck"; +import { recordDownloadBackoff } from "../jobs/downloadBackoff"; +import { detectPlatform } from "../lib/platform"; +import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; // Availability gate for the transcribed-audio cleanup sweep. // @@ -39,6 +42,30 @@ export type CleanVerdicts = { alreadyGone: Set<string>; // Probe inconclusive (error / needs_auth / never resolved). Skip, no marker. unverified: Set<string>; + // WHY THE GATE STOPPED SHORT, when a whole tier gave no answer (lane + // clean-unverified, ruling 2): the listing or the confirmation was + // rate-limited by the source (`rate-limit` — a retry later may succeed), or + // failed for another reason (`error`). Absent when every tier answered — + // a per-video `error` / `needs_auth` verdict is not a stop. + stopped?: CleanVerifyStop; +}; + +export type CleanVerifyStop = { + kind: "rate-limit" | "error"; + // The cooldown key (detectPlatform(url) ?? "unknown"), as Sync and the + // download lane use it. + platform: string; + message: string; +}; + +// THE PROBES, as a test seam: production passes nothing. `recordBackoff` is +// how a rate-limited LISTING records the platform's cooldown — the one a +// download's 429 and Sync's record (jobs/downloadBackoff.ts); a rate-limited +// confirmation records it inside runAvailabilityCheck. +export type VerifyProbes = { + quick?: typeof runQuickAvailabilityCheck; + full?: typeof runAvailabilityCheck; + recordBackoff?: (platform: string) => Promise<void>; }; export type VerifyBeforeCleanOptions = { @@ -47,6 +74,7 @@ export type VerifyBeforeCleanOptions = { candidateIds: string[]; onLog?: (msg: string) => void; signal?: AbortSignal; + probes?: VerifyProbes; }; function emptyVerdicts(): CleanVerdicts { @@ -68,6 +96,7 @@ export async function verifyBeforeClean({ candidateIds, onLog, signal, + probes, }: VerifyBeforeCleanOptions): Promise<CleanVerdicts> { const log = onLog ?? ((m: string) => console.log(m)); const verdicts = emptyVerdicts(); @@ -119,9 +148,10 @@ export async function verifyBeforeClean({ } // Ids known on disk but ABSENT from the channel's current flat playlist. + const platform = detectPlatform(config.url) ?? "unknown"; let maybeMissing: Set<string>; try { - const quick = await runQuickAvailabilityCheck({ + const quick = await (probes?.quick ?? runQuickAvailabilityCheck)({ channelSlug, paths, onLog: log, @@ -137,6 +167,17 @@ export async function verifyBeforeClean({ log( `Verify before clean: could not verify availability (${reason}) — nothing cleaned this run.`, ); + // A 429 on the listing (runYtdlp's EnumerationIncompleteError) is a rate + // limit: the platform's cooldown is recorded, as Sync records it, so the + // downloads and the retry of this clean both stay away for it. + if (err instanceof EnumerationIncompleteError) { + await (probes?.recordBackoff ?? ((pf: string) => recordDownloadBackoff(pf, paths, "rate_limit")))( + err.platform, + ).catch(() => {}); + verdicts.stopped = { kind: "rate-limit", platform: err.platform, message: reason }; + } else if (!signal?.aborted) { + verdicts.stopped = { kind: "error", platform, message: reason }; + } return verdicts; } @@ -155,7 +196,7 @@ export async function verifyBeforeClean({ ); let check: Awaited<ReturnType<typeof runAvailabilityCheck>>; try { - check = await runAvailabilityCheck({ + check = await (probes?.full ?? runAvailabilityCheck)({ channelSlug, paths, mode: "recheck-all", @@ -180,6 +221,7 @@ export async function verifyBeforeClean({ log( `Verify before clean: confirmation probe failed (${reason}) — leaving ${suspects.length} candidate(s) unverified.`, ); + if (!signal?.aborted) verdicts.stopped = { kind: "error", platform, message: reason }; return verdicts; } @@ -203,6 +245,15 @@ export async function verifyBeforeClean({ `${unprobed.size} suspect(s) it did not reach are left unverified, not judged on an old record.`, ); } + // The source rate-limited the confirmation (runAvailabilityCheck recorded + // the cooldown): a retry later may reach what this run could not. + if (check.blocked && unprobed.size > 0 && !signal?.aborted) { + verdicts.stopped = { + kind: "rate-limit", + platform, + message: check.blockMessage ?? "rate-limited", + }; + } for (const id of suspects) { if (signal?.aborted) break; diff --git a/common/jobs/bootQueuedJobs.test.ts b/common/jobs/bootQueuedJobs.test.ts @@ -653,3 +653,30 @@ test("compress-text in any state a restart leaves is never started by the boot", await rm(f.root, { recursive: true, force: true }); } }); + +// Lane clean-unverified (review 1, F5): a rate-limited clean's retry left +// QUEUED by a restart is never re-queued from its spec — that would run it at +// once as a fresh request with two more retries. Its schedule's record +// (controller/cleanRetrySchedule.ts) queues it again, attempt and not-before +// kept. A queued unchecked clean IS re-queued, its carried plan in its spec. +test("a queued clean-audio-retry is closed `rescheduled`; a queued unchecked clean is re-queued with its plan", async () => { + const retry: JobSpec = { + kind: "clean-audio-retry", + slug: "ch", + params: { retry: { attempt: 1, of: "J0", notBefore: BOOT - 1, platform: "rumble", id: "J0.retry1" } }, + }; + const unchecked: JobSpec = { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "button", plan: ["a", "b"] } }; + const f = await fixture([ + { id: "R1", kind: "clean-audio-retry", queueKey: "channel:ch", spec: retry }, + { id: "U1", kind: "clean-audio-unchecked", queueKey: "channel:ch", spec: unchecked }, + ]); + try { + const rq = recordingRequeue(); + const res = await settleQueuedJobMetas({ paths: f.paths, requeue: rq.fn, bootedAt: BOOT, log: () => {} }); + assert.deepEqual(rq.calls, [unchecked]); + assert.deepEqual(res.cancelled.map((c) => [c.id, c.category]), [["R1", "rescheduled"]]); + assert.match((await f.read("R1")).cancelReason ?? "", /queued again by its schedule/); + } finally { + await rm(f.root, { recursive: true, force: true }); + } +}); diff --git a/common/jobs/bootQueuedJobs.ts b/common/jobs/bootQueuedJobs.ts @@ -28,7 +28,8 @@ import { getJobKind, isPublishStageJobKind } from "./jobKinds"; // lane and Publish now re-derive stages from the stamps on disk, and a // stage re-queued with its run's preconditions would wait on a run that // is gone; nor is a kind that starts only on a person's click -// (`startedByPerson`: the X run); +// (`startedByPerson`: the X run); nor one its own durable schedule +// queues again (`rescheduledOnBoot`: a rate-limited clean's retry); // 3. a meta queued more than REQUEUE_MAX_AGE_MS before this boot is stale; // 4. a meta with no replay spec cannot be re-queued; // 5. of what is left, only the NEWEST meta per kind + channel + params is @@ -56,7 +57,15 @@ export type RequeueFn = ( ) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>; export type CancelCategory = - "idle" | "sync" | "publish" | "person" | "stale" | "no-spec" | "superseded" | "refused"; + | "idle" + | "sync" + | "publish" + | "person" + | "rescheduled" + | "stale" + | "no-spec" + | "superseded" + | "refused"; export type BootQueuedResult = { requeued: { id: string; newId: string }[]; @@ -300,6 +309,9 @@ export async function settleQueuedJobMetas( } else if (getJobKind(meta.kind)?.startedByPerson) { // An X run starts only on a person's click, never by a boot. await cancel(meta, "person", PERSON_RESTART_REASON); + } else if (getJobKind(meta.kind)?.rescheduledOnBoot) { + // Its own durable schedule queues it again (a rate-limited clean's retry). + await cancel(meta, "rescheduled", getJobKind(meta.kind)!.rescheduledOnBoot!); } else if ( typeof meta.queuedAt !== "number" || opts.bootedAt - meta.queuedAt > maxAgeMs diff --git a/common/jobs/jobDetail.test.ts b/common/jobs/jobDetail.test.ts @@ -64,3 +64,9 @@ test("a batch names who asked, for what, and how many windows", () => { test("other kinds add nothing", () => { assert.equal(jobSpecDetail("sync", spec("sync", { requestedBy: "x" })), undefined); }); + +test("lane clean-unverified: a clean without checking says why on its row", () => { + assert.equal(jobSpecDetail("clean-audio-unchecked", { kind: "clean-audio-unchecked", slug: "x", params: { unchecked: "channel-setting" } }), "channel setting"); + assert.equal(jobSpecDetail("clean-audio-unchecked", { kind: "clean-audio-unchecked", slug: "x", params: { unchecked: "button", plan: ["a"] } }), "confirmed count"); + assert.equal(jobSpecDetail("clean-audio-transcribed", { kind: "clean-audio-transcribed", slug: "x", params: {} }), undefined); +}); diff --git a/common/jobs/jobDetail.ts b/common/jobs/jobDetail.ts @@ -27,6 +27,15 @@ export function jobSpecDetail( if (!runId || !target) return undefined; return `run ${runId.slice(-6)} · ${target}`; } + // A CLEAN WITHOUT CHECKING (lane clean-unverified) says why it is + // unchecked, so the row reads "Clean audio without checking · channel + // setting" for a run the channel's key made (no count shown, unless it + // carries a plan) apart from a count a person confirmed. + if (kind === "clean-audio-unchecked") { + if (p.unchecked === "channel-setting") return "channel setting"; + if (p.unchecked === "button") return "confirmed count"; + return undefined; + } if (kind !== "fetch-window" && kind !== "fetch-windows") return undefined; const by = s(p.requestedBy); if (!by) return undefined; diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts @@ -211,6 +211,8 @@ const STILL_MEDIA = [ "scan-media", "scan-media-channel", "clean-audio-transcribed", + "clean-audio-unchecked", + "clean-audio-retry", "clean-extra-audio-formats", "remove-wrong-format-audio", "reports-prepare", @@ -471,3 +473,25 @@ test("no kind is both startedByPerson and resumeOnBoot", () => { assert.notEqual(getJobKind(k)?.startedByPerson, true, `${k}`); } }); + +test("lane clean-unverified: the unchecked clean is its own kind, so its title says so", () => { + assert.equal(jobKindLabel("clean-audio-transcribed"), "Clean audio"); + assert.equal(jobKindLabel("clean-audio-unchecked"), "Clean audio without checking"); + assert.equal(getJobKind("clean-audio-unchecked")?.replayable, true); + assert.equal(isDrainableKind("clean-audio-unchecked"), false); + assert.equal(kindIsNetwork("clean-audio-unchecked"), false); +}); + +test("lane clean-unverified: a rate-limited clean's retry is its own kind, queued again by its schedule at boot", () => { + const meta = getJobKind("clean-audio-retry"); + assert.ok(meta, "registered"); + assert.equal(jobKindLabel("clean-audio-retry"), "Clean audio (rate-limit retry)"); + assert.equal(kindNeedsMedia("clean-audio-retry"), true); + assert.equal(meta.replayable, true); + assert.equal(meta.resumeOnBoot, undefined); + assert.match(meta.rescheduledOnBoot ?? "", /queued again by its schedule/); + // Neither of the other two clean kinds is rescheduled: the boot re-queues a + // queued one from its spec (an unchecked one with its carried plan). + assert.equal(getJobKind("clean-audio-unchecked")?.rescheduledOnBoot, undefined); + assert.equal(getJobKind("clean-audio-transcribed")?.rescheduledOnBoot, undefined); +}); diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -103,6 +103,13 @@ export type JobKindMeta = { // as interrupted, and Resume on /review is the person's click. Absent // means false. startedByPerson?: boolean; + // Whether a job of this kind is queued by a DURABLE SCHEDULE of its own, + // which the boot re-arms: one left queued by a restart is closed by the + // boot pass with this sentence, never re-queued from its spec — the + // schedule queues it again (lane clean-unverified: a rate-limited clean's + // retry, controller/cleanRetrySchedule.ts, whose attempt count and + // not-before time live in its record). Absent = not. + rescheduledOnBoot?: string; }; // One entry per kind known to the system. `label` is included only where the @@ -430,6 +437,33 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "custom", needsMedia: true, }, + // The same sweep with the availability verdict skipped (lane + // clean-unverified): the one-off "Clean without checking" button, or any + // clean of a channel whose config sets cleanAudioWithoutChecking. Its own + // kind so the job list's title says so. The same media guard, the same + // channel queue; replayed unchecked only with the explicit flag in its spec. + "clean-audio-unchecked": { + kind: "clean-audio-unchecked", + label: "Clean audio without checking", + drainable: false, + replayable: true, + queueKeyStrategy: "custom", + needsMedia: true, + }, + // The retry of a checked Clean audio the source rate-limited, queued on the + // channel's queue by its schedule at its not-before time (the wait itself is + // off-queue: controller/cleanRetrySchedule.ts). The same sweep, checked; the + // same media guard. A person's Retry of it is a fresh Clean audio. + "clean-audio-retry": { + kind: "clean-audio-retry", + label: "Clean audio (rate-limit retry)", + drainable: false, + replayable: true, + queueKeyStrategy: "custom", + needsMedia: true, + rescheduledOnBoot: + "server restarted; a rate-limited clean's retry is queued again by its schedule (its attempt and not-before time are kept), not re-queued from its spec", + }, // Speaker-diarization backfill over a channel's retained audio. The capture // lane's catch-all: it picks up everything the post-transcribe hook missed // (videos transcribed before the feature, or with the inline hook off — which diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -188,7 +188,9 @@ export type JobRecord = { // A JOB THAT ENDED DEFERRED (review 2, ruling R-b): X's job cap was reached // when its queue started it, so it did not run — not a failure. It ends // `done` with this: the sentence, and when the next X job may start. - // Nothing re-queues it by itself. + // Nothing re-queues it by itself. ALSO (lane clean-unverified): a checked + // Clean audio the source rate-limited — it deleted nothing it could not + // verify and queued its own retry for `until` (controller/cleanAudioJob.ts). deferred?: { until: number; sentence: string }; }; diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -280,6 +280,9 @@ export type ChannelConfig = { excludeFromCleanup?: boolean; excludeFromCompaction?: boolean; cleanAfterCaptureUnverified?: boolean; + // Lane clean-unverified: every clean of this channel's audio runs WITHOUT + // the availability check (see CHANNEL_CONFIG_FIELD_DOCS). Absent = checked. + cleanAudioWithoutChecking?: boolean; syncIntervalMinutes?: number; fullSweepIntervalMinutes?: number; skipLiveDownloads?: boolean; @@ -370,6 +373,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { "Keep this channel's saved videos out of compaction (`compact-saved-videos`, a re-encode to AV1 that becomes the active copy): neither the selector nor an explicit list touches them. For a channel whose stored bytes are kept as evidence. Absent = false.", cleanAfterCaptureUnverified: "Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel (\"no source to check: clean by hand\") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held.", + cleanAudioWithoutChecking: + "Every clean of this channel's transcribed audio runs WITHOUT the availability check: the Clean audio button, the /cleanup row, `pnpm ops cleanup` and clean after capture alike ask the source nothing, so the audio of a video no longer available anywhere is removed too (it is no longer pinned do-not-clean). Every other protection holds: do-not-clean marks, the keep-latest window, the speaker holds (awaiting diarization / voice fingerprint), untranscribed videos, an unreachable or moving media drive. Those jobs run as \"Clean audio without checking\"; the key is read again when each starts, and a saved video container is never pruned by them. The buttons (Cleanup stage, /cleanup, the dashboard) show a count first; these run unchecked with NO count, the key being the standing consent: clean after capture, `pnpm ops cleanup` with no `unchecked` flag, a /jobs Retry, Retry all failed or `pnpm ops job retry` of a clean of this channel, and the boot's re-queue of one a restart caught queued (titled \"Clean audio without checking · channel setting\"). A rate-limited clean's retry stays checked; no other automatic lane runs a channel clean. A replayed confirmed clean without checking needs its carried plan, and none replays unchecked once the key is off. A new channel never starts with it (createChannel drops it). For a platform whose VODs expire by design (Twitch, Kick), where \"gone from the source\" is the normal state; never set by platform. Absent/false = checked. Set on the channel's Cleanup stage or with `pnpm ops channel-config {\"cleanAudioWithoutChecking\": true}`.", syncIntervalMinutes: "Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. AN INSTAGRAM CHANNEL is synced seldom, because every sync is a logged-in read: absent = every 12 hours at the most often (the global default when that is longer), and a value of its own is never under 240 (4 hours); 0 still turns it off (`common/jobs/syncScheduler.ts`).", fullSweepIntervalMinutes: @@ -601,6 +606,7 @@ export const CHANNEL_CONFIG_COERCIONS: { excludeFromCleanup: bool, excludeFromCompaction: bool, cleanAfterCaptureUnverified: bool, + cleanAudioWithoutChecking: (v) => (v === true ? true : undefined), syncIntervalMinutes: zeroOrClamped(SYNC_INTERVAL_MIN_MINUTES, SYNC_INTERVAL_MAX_MINUTES), fullSweepIntervalMinutes: zeroOrClamped( SYNC_INTERVAL_MIN_MINUTES, diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 49); // lane x-trending: `xTrending`; 2026-11-13: `excludeFromCompaction`; 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl` + assert.equal(CHANNEL_CONFIG_KEYS.length, 50); // lane clean-unverified: `cleanAudioWithoutChecking`; lane x-trending: `xTrending`; 2026-11-13: `excludeFromCompaction`; 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl` assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -74,6 +74,7 @@ export const channelConfigObjectSchema = z.object({ excludeFromCleanup: field("excludeFromCleanup"), excludeFromCompaction: field("excludeFromCompaction"), cleanAfterCaptureUnverified: field("cleanAfterCaptureUnverified"), + cleanAudioWithoutChecking: field("cleanAudioWithoutChecking"), syncIntervalMinutes: field("syncIntervalMinutes"), fullSweepIntervalMinutes: field("fullSweepIntervalMinutes"), skipLiveDownloads: field("skipLiveDownloads"), diff --git a/common/lib/cleanAudioConfirm.test.ts b/common/lib/cleanAudioConfirm.test.ts @@ -0,0 +1,34 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { TURN_ON_CONFIRMATION, cleanConfirmationText } from "./cleanAudioConfirm"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/cleanAudioConfirm.test.ts +// +// THE ONE COUNTED CONFIRMATION every button that would clean without checking +// shows (lane clean-unverified, ruling 6), word for word. + +test("the counted confirmation states what goes, that the source is not asked, and what is kept", () => { + const t = cleanConfirmationText({ files: 40, bytes: 3 * 1024 ** 3, videos: 38, protected: 12, awaitingDiarization: 3, awaitingVoiceprint: 1 }); + assert.match( + t.ask, + /^Remove 40 audio files \(.+\) from 38 transcribed videos without checking\? The source is not asked, so the audio of videos no longer available anywhere is removed too\.$/, + ); + assert.equal( + t.kept, + "Kept: 12 marked do not clean or in the keep-latest window, 3 awaiting diarization, 1 awaiting voice fingerprint. Videos with no transcript are not touched, and no saved video is.", + ); + assert.equal(t.button, "Remove 40 files without checking"); + const one = cleanConfirmationText({ files: 1, bytes: 10, videos: 1, protected: 0, awaitingDiarization: 0, awaitingVoiceprint: 0 }); + assert.match(one.ask, /^Remove 1 audio file \(.+\) from 1 transcribed video without checking\?/); + assert.equal(one.button, "Remove 1 file without checking"); + const none = cleanConfirmationText({ files: 0, bytes: 0, videos: 0, protected: 2, awaitingDiarization: 0, awaitingVoiceprint: 0 }); + assert.match(none.ask, /^Nothing to remove/); +}); + +test("turning the channel key on states what it changes before it changes it", () => { + assert.match(TURN_ON_CONFIRMATION, /^Turn on cleaning without checking for this channel\?/); + assert.match(TURN_ON_CONFIRMATION, /without asking the source whether the video is still there/); + assert.match(TURN_ON_CONFIRMATION, /these do not: clean after capture/); + assert.match(TURN_ON_CONFIRMATION, /a Retry \(or Retry all failed\) of an earlier clean, and a clean a restart re-queues/); +}); diff --git a/common/lib/cleanAudioConfirm.ts b/common/lib/cleanAudioConfirm.ts @@ -0,0 +1,43 @@ +// Client-safe: the counted confirmation of a clean WITHOUT CHECKING (lane +// clean-unverified), the one text every button that would run unchecked shows +// — the channel page's Cleanup stage (the one-off button, and Clean audio when +// the channel's key is on), the /cleanup card and the dashboard's inline +// buttons. Its numbers are planAudioClean's (no network, no deletes). +import { formatBytes } from "./format"; + +// The counts it states: the structural part of controller +// cleanAudioFromTranscribed's AudioCleanPlan (lib may not import controller). +export type CleanPlanCounts = { + files: number; + bytes: number; + videos: number; + protected: number; + awaitingDiarization: number; + awaitingVoiceprint: number; +}; + +const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; + +export function cleanConfirmationText(plan: CleanPlanCounts): { ask: string; kept: string; button: string } { + return { + ask: + plan.files === 0 + ? "Nothing to remove: no transcribed video here holds audio a clean would take." + : `Remove ${plural(plan.files, "audio file")} (${formatBytes(plan.bytes)}) from ${plural(plan.videos, "transcribed video")} without checking? ` + + "The source is not asked, so the audio of videos no longer available anywhere is removed too.", + kept: + `Kept: ${plan.protected} marked do not clean or in the keep-latest window, ` + + `${plan.awaitingDiarization} awaiting diarization, ${plan.awaitingVoiceprint} awaiting voice fingerprint. ` + + "Videos with no transcript are not touched, and no saved video is.", + button: `Remove ${plural(plan.files, "file")} without checking`, + }; +} + +// The confirmation to turn the channel's key ON: what it changes, stated +// before it changes it. +export const TURN_ON_CONFIRMATION = + "Turn on cleaning without checking for this channel? From now on every clean of its audio — Clean audio here and on /cleanup, " + + "the dashboard's buttons, pnpm ops and clean after capture — deletes audio without asking the source whether the video is still there, " + + "so the audio of a video removed upstream is deleted too. The buttons still show a count before they run; these do not: clean after capture, " + + "pnpm ops cleanup without its unchecked flag, a Retry (or Retry all failed) of an earlier clean, and a clean a restart re-queues. " + + "Videos already marked do not clean, the keep-latest window and the speaker holds stay kept."; diff --git a/common/views/cleanable.ts b/common/views/cleanable.ts @@ -22,6 +22,10 @@ export type CleanableChannel = { count: number; // Reclaim estimate for the primary "clean audio" sweep, net of protection. bytes: number; + // The channel's cleanAudioWithoutChecking: its Clean audio runs without + // checking (the button says so, and its click shows the counted + // confirmation). Absent = checked. + withoutChecking?: boolean; }; export type CleanablePayload = { diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts @@ -144,6 +144,8 @@ const JOB_KIND_TO_STAGE: Record<string, StageId> = { // but is the same work this card is about, so it lights this card too. "diarize-channel": "speakers", "clean-audio-transcribed": "cleanup", + "clean-audio-unchecked": "cleanup", + "clean-audio-retry": "cleanup", "purge-superseded-auto-subs": "cleanup", "clean-extra-audio-formats": "cleanup", "remove-wrong-format-audio": "cleanup", diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -79,6 +79,36 @@ stored chat again on purpose: the stored capture is kept as `chat-capture-kept.<stamp>.json.zst` and never removed automatically; the log compares both. An empty replay leaves the stored capture the chat. - Two different captures are never settled by deleting one. A second editor process waits for a video's lock. +- **Clean audio without checking, and a rate-limited clean that says so.** + - The channel page's Cleanup stage has **Clean without checking…** beside Clean audio. It first counts what it would + remove (files, bytes, videos, and what it keeps; no request to the source) and asks: "Remove N audio files (X) + from M transcribed videos without checking? The source is not asked, so the audio of videos no longer available + anywhere is removed too." The job carries the counted videos' ids and removes at most those. Every other + protection holds: do-not-clean, keep-latest, awaiting diarization or voice fingerprint, untranscribed videos, an + unreachable or moving media drive (asked again just before anything is removed). It never touches a saved video. + The job is titled **Clean audio without checking**. CLI: `pnpm ops cleanup --json + '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}'` (the counts and ids), then without `dryRun`. + - New channel key `cleanAudioWithoutChecking` (off unless set): every clean of the channel runs unchecked — the + button, /cleanup, the dashboard's buttons, `pnpm ops cleanup` and clean after capture. Every button then shows the + same counted confirmation. A checkbox on the Cleanup stage sets it and asks first; Twitch and Kick channels show + a hint, nothing is set by platform, and a new channel never starts with it. A queued job reads the key again when + it starts. CLI: `pnpm ops channel-config --json '{"slug":"x","cleanAudioWithoutChecking":true}'`. + - A checked clean the source rate-limits (HTTP 429 on the listing or a confirmation probe) still deletes nothing it + could not verify, and now ends **deferred** with its counts instead of a plain done. It schedules one retry, not + before 15 minutes or the platform's cooldown, whichever is later. The retry waits off the queue and survives a + restart; it runs as **Clean audio (rate-limit retry)** when its time comes. Cancel the deferred job, or Cancel + retry on the Cleanup stage, to cancel it. After two retries it ends failed, "Gave up: rate-limited", for a + person. A failure that is not a rate limit ends failed, "Could not verify availability", with no retry. A + rate-limited listing now records the platform cooldown, as Sync does. A retry whose channel's media is held when + its time comes (a relocation, a drive away) waits and tries again for up to a day, and the Cleanup stage says so. + - **Fixed (also on earlier releases): a checked Clean audio whose availability check the source rate-limited, or + that failed, no longer runs the saved-video retention prune.** The prune keeps a rolled-out keep-latest container + only when the video is pinned do-not-clean, and the check that pins a video gone from the source had not finished, + so such a container — possibly the only copy — could be evicted. It now logs that the prune was skipped and why. + - With the channel key on, a /jobs Retry, Retry all failed, `pnpm ops job retry` and a restart's re-queue of a clean + run without checking and without a count, titled "Clean audio without checking · channel setting"; a confirmed + clean without checking replays only with its plan, and never once the key is off. `pnpm ops cleanup + {"unchecked": true}` answers the plan's counts. Turning the key on cancels a scheduled rate-limit retry. - **umtool: the gap mark's border is the deck's accent colour.** - The operator picked variant B. The border is drawn in the deck's accent, the colour of the deck's accent rule and the dots in its source line, at full opacity. The box behind the text is near-black at 90 %, and the text diff --git a/editor/app/api/ops/_writes.test.ts b/editor/app/api/ops/_writes.test.ts @@ -266,6 +266,37 @@ test("cleanup refuses an unknown sweep and a traversing slug, before any job", a assert.deepEqual(await corpus.listJobIds(), []); }); +test("cleanup unchecked dryRun answers the confirmation's plan and starts nothing; misuse is refused", async () => { + const cleanup = await route("cleanup"); + const dry = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: true, dryRun: true }); + assert.equal(dry.status, 200, JSON.stringify(dry.body)); + assert.equal(dry.body.dryRun, true); + const plan = dry.body.plan as Record<string, unknown>; + for (const k of ["inspected", "videos", "files", "bytes", "protected", "awaitingDiarization", "awaitingVoiceprint"]) { + assert.equal(typeof plan[k], "number", k); + } + // The ids a confirmed run carries, one per video counted. + assert.ok(Array.isArray(plan.ids)); + assert.equal((plan.ids as unknown[]).length, plan.videos); + const wrongSweep = await callPost(cleanup, { slug: SLUG, sweep: "extra-formats", unchecked: true }); + assert.equal(wrongSweep.status, 400); + assert.match(String(wrongSweep.body.error), /"unchecked" applies to the "transcribed" sweep only/); + const checkedDry = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", dryRun: true }); + assert.equal(checkedDry.status, 400); + assert.match(String(checkedDry.body.error), /give "unchecked": true/); + const notBool = await callPost(cleanup, { slug: SLUG, sweep: "transcribed", unchecked: "yes" }); + assert.equal(notBool.status, 400); + assert.deepEqual(await corpus.listJobIds(), []); +}); + +test("channel-config refuses a cleanAudioWithoutChecking that is not a boolean, writing nothing", async () => { + const cfgRoute = await route("channel-config"); + const res = await callPost(cfgRoute, { slug: SLUG, cleanAudioWithoutChecking: "on" }); + assert.equal(res.status, 400); + const cfg = JSON.parse(await readFile(path.join(corpus.transcripts, "channels", SLUG, "config.json"), "utf8")); + assert.equal("cleanAudioWithoutChecking" in cfg, false); +}); + test("relocate dryRun answers each channel's preview and moves nothing", async () => { const relocate = await route("relocate"); const res = await callPost(relocate, { slugs: [SLUG, "no-such"], root: elsewhere, dryRun: true }); diff --git a/editor/app/api/ops/channel-config/route.ts b/editor/app/api/ops/channel-config/route.ts @@ -7,6 +7,7 @@ import { } from "../../../channels/components/channelConfigToForm"; import { setChannelExclusionsAction, + setCleanAudioWithoutCheckingAction, updateChannelAction, } from "../../../channels/actions"; import { @@ -26,8 +27,10 @@ export const dynamic = "force-dynamic"; // sites?: [{ siteId, groupId? | newGroupName? }], // excludeFromBuild?: boolean, // excludeFromCleanup?: boolean, +// cleanAudioWithoutChecking?: boolean, // } -// — at least one of patch / sites / excludeFromBuild / excludeFromCleanup. +// — at least one of patch / sites / excludeFromBuild / excludeFromCleanup / +// cleanAudioWithoutChecking. // // The patch keys are the FORM's field names, not ChannelConfig's, because the // form is what validates them: `downloadFilterInclude` / `downloadFilterExclude` @@ -43,10 +46,12 @@ export const dynamic = "force-dynamic"; // // The two exclusions are the /channels rack's build and cleanup toggles, set // to a value rather than flipped, since a caller cannot see the switch. +// `cleanAudioWithoutChecking` is the Cleanup stage's "Always clean this +// channel without checking" (CHANNEL.md), set the same way. export async function POST(request: Request) { return ops( request, - ["slug", "patch", "sites", "excludeFromBuild", "excludeFromCleanup"], + ["slug", "patch", "sites", "excludeFromBuild", "excludeFromCleanup", "cleanAudioWithoutChecking"], async (body) => { const slug = reqSlug(body, "slug"); const patch = body.patch; @@ -59,14 +64,16 @@ export async function POST(request: Request) { const sites = readSiteMemberships(body); const excludeFromBuild = optBool(body, "excludeFromBuild"); const excludeFromCleanup = optBool(body, "excludeFromCleanup"); + const cleanAudioWithoutChecking = optBool(body, "cleanAudioWithoutChecking"); if ( patch === undefined && sites === undefined && excludeFromBuild === undefined && - excludeFromCleanup === undefined + excludeFromCleanup === undefined && + cleanAudioWithoutChecking === undefined ) { throw new OpsInputError( - 'nothing to change — give "patch", "sites", "excludeFromBuild" or "excludeFromCleanup"', + 'nothing to change — give "patch", "sites", "excludeFromBuild", "excludeFromCleanup" or "cleanAudioWithoutChecking"', ); } // KEYS FIRST, CHANNEL SECOND. A misspelled field is a fact about the @@ -92,6 +99,10 @@ export async function POST(request: Request) { const saved = await updateChannelAction(slug, undefined, fd); if (saved?.error) return actionResponse(saved); } + if (cleanAudioWithoutChecking !== undefined) { + const set = await setCleanAudioWithoutCheckingAction(slug, cleanAudioWithoutChecking); + if (set?.error) return actionResponse(set); + } return actionResponse( await setChannelExclusionsAction(slug, { excludeFromBuild, diff --git a/editor/app/api/ops/cleanup/route.ts b/editor/app/api/ops/cleanup/route.ts @@ -1,10 +1,13 @@ +import { NextResponse } from "next/server"; import { cleanAudioAction, + cleanAudioUncheckedAction, cleanExtraAudioFormatsAction, clearFailedTranscriptionsAction, + planCleanAudioUncheckedAction, removeWrongFormatAudioAction, } from "../../../channels/[slug]/whisperActions"; -import { jobResponse, oneOf, ops, reqSlug } from "../_lib"; +import { jobResponse, oneOf, ops, opsFail, OpsInputError, optBool, reqSlug } from "../_lib"; export const dynamic = "force-dynamic"; @@ -27,6 +30,20 @@ export const dynamic = "force-dynamic"; // keep-latest window and audio still awaiting diarization; every one deletes // through the media tier's remover (removeMediaFile), never a bare link. // `get cleanup <slug>` says what each would reclaim. +// +// CLEAN WITHOUT CHECKING (lane clean-unverified): "unchecked": true with +// "transcribed" is the Cleanup stage's "Clean without checking" — the +// availability check is skipped and the source is not asked, so the audio of +// videos no longer available anywhere goes too; every other protection holds. +// "dryRun": true (unchecked only) answers the confirmation's numbers — +// {plan: {inspected, ids, videos, files, bytes, protected, +// awaitingDiarization, awaitingVoiceprint}} — and starts nothing. Without +// "dryRun" the plan is computed at the call and carried by the job, which +// removes at most those videos' audio (what became protected since is +// skipped; what became eligible since is left for the next run). A channel +// whose config sets cleanAudioWithoutChecking runs "transcribed" unchecked +// without the flag, discovering at start (nobody confirmed a count); the key +// is re-read when the job starts. const SWEEPS = { transcribed: cleanAudioAction, "extra-formats": cleanExtraAudioFormatsAction, @@ -35,9 +52,36 @@ const SWEEPS = { } as const; export async function POST(request: Request) { - return ops(request, ["slug", "sweep"], async (body) => { + return ops(request, ["slug", "sweep", "unchecked", "dryRun"], async (body) => { const slug = reqSlug(body, "slug"); const sweep = oneOf(body, "sweep", Object.keys(SWEEPS) as (keyof typeof SWEEPS)[]); + const unchecked = optBool(body, "unchecked") ?? false; + const dryRun = optBool(body, "dryRun") ?? false; + if (unchecked && sweep !== "transcribed") { + throw new OpsInputError('"unchecked" applies to the "transcribed" sweep only'); + } + if (dryRun && !unchecked) { + throw new OpsInputError('"dryRun" is the unchecked clean\'s plan — give "unchecked": true (`get cleanup <slug>` estimates the others)'); + } + if (unchecked && dryRun) { + const r = await planCleanAudioUncheckedAction(slug); + if (!r.ok) return opsFail(r.error); + return NextResponse.json({ ok: true, dryRun: true, plan: r.plan }); + } + // A non-dry unchecked call is its own confirmation: its plan is computed + // NOW and carried, so the job removes at most what this call would have + // answered (the intersection with what is still eligible when it starts). + // Its reply, and the job's log before anything is removed, state the + // plan's counts. + if (unchecked) { + const r = await planCleanAudioUncheckedAction(slug); + if (!r.ok) return opsFail(r.error); + const { ids, ...counts } = r.plan; + const job = await cleanAudioUncheckedAction(slug, undefined, ids, counts); + if (!job.ok) return jobResponse(job); + void job.stream.cancel(); + return NextResponse.json({ ok: true, jobId: job.jobId, plan: counts }); + } return jobResponse(await SWEEPS[sweep](slug)); }); } diff --git a/editor/app/channels/[slug]/cleanRetryScheduler.ts b/editor/app/channels/[slug]/cleanRetryScheduler.ts @@ -0,0 +1,78 @@ +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { getRegistry, onJobEnd } from "yt-dlp-transcript-common/jobs/registry"; +import { platformCooldownRemainingMs } from "yt-dlp-transcript-common/jobs/downloadBackoff"; +import { assertChannelMediaReachable } from "yt-dlp-transcript-common/lib/channelMedia"; +import { + armCleanRetriesAtBoot, + cancelCleanRetries, + type CleanRetryDeps, +} from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; + +// THE EDITOR'S WIRING of a rate-limited clean's off-queue retry +// (common/controller/cleanRetrySchedule.ts): how its timer queues the retry +// job (cleanAudioRetryAction, on the channel's queue), how a cancel reaches a +// job it already queued (the registry's cancel), and the platform cooldown it +// re-reads. Not a "use server" module: nothing here is a client-callable +// action. +export function cleanRetryDeps(): CleanRetryDeps { + const paths = getPaths(); + return { + cooldownRemainingMs: (pf) => platformCooldownRemainingMs(pf, paths), + enqueue: async (entry) => { + // Lazy: whisperActions imports this module. + const { cleanAudioRetryAction } = await import("./whisperActions"); + const r = await cleanAudioRetryAction(entry.slug, { + attempt: entry.attempt, + of: entry.of, + notBefore: entry.notBefore, + platform: entry.platform, + id: entry.id, + }); + if (!r.ok) return { ok: false, error: r.error }; + // Nobody reads this job's stream; it is followed on /jobs. + void r.stream.cancel().catch(() => {}); + return { ok: true, jobId: r.jobId }; + }, + cancelJob: (jobId) => getRegistry().cancel(jobId), + // A relocation in flight or a drive away when its time comes: the retry + // waits and tries again (cleanRetrySchedule: HOLD_PAUSE_MS, MAX_HOLDS). + mediaHold: async (slug) => { + try { + await assertChannelMediaReachable(paths, slug); + return null; + } catch (err) { + return (err as Error).message; + } + }, + log: (m) => console.log(m), + }; +} + +// A RETRY JOB CANCELLED WHILE QUEUED is a person's decision (a /jobs Cancel, +// Drain all): its record goes too, or the next boot would re-arm it. Not at +// shutdown — the reaper's cancels are nobody's, and the boot re-arms those. +// (A retry that ran removes its own record when it ends.) Once per process. +declare global { + // eslint-disable-next-line no-var + var __yttCleanRetryEndListener__: boolean | undefined; +} +if (!globalThis.__yttCleanRetryEndListener__) { + globalThis.__yttCleanRetryEndListener__ = true; + onJobEnd((job) => { + if (job.kind !== "clean-audio-retry" || job.status !== "cancelled") return; + if (getRegistry().isShuttingDown()) return; + void cancelCleanRetries(getPaths(), { id: job.id }, cleanRetryDeps()).catch(() => {}); + }); +} + +// The boot (instrumentation.ts, below the idle gate): arm every scheduled +// retry again from its record. +export async function armCleanRetriesOnBoot(): Promise<void> { + const out = await armCleanRetriesAtBoot(getPaths(), cleanRetryDeps()); + if (out.armed.length || out.dropped.length) { + console.log( + `[boot] clean retries: ${out.armed.length} re-armed from their schedule` + + (out.dropped.length ? `, ${out.dropped.length} dropped (interrupted twice)` : ""), + ); + } +} diff --git a/editor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx b/editor/app/channels/[slug]/components/stages/CleanWithoutChecking.tsx @@ -0,0 +1,217 @@ +"use client"; + +import { useState } from "react"; +import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActionLog"; +import type { AudioCleanPlan } from "yt-dlp-transcript-common/controller/cleanAudioFromTranscribed"; +import type { ScheduledCleanRetry } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { + TURN_ON_CONFIRMATION, + cleanConfirmationText, +} from "yt-dlp-transcript-common/lib/cleanAudioConfirm"; +import { cancelJobAction } from "../../../../jobs/actions"; +import { setCleanAudioWithoutCheckingAction } from "../../../actions"; +import { useHydrated } from "../../../../operations/components/useOperationsStatus"; +import { + cancelCleanRetryAction, + cleanAudioAction, + cleanAudioUncheckedAction, + planCleanAudioUncheckedAction, +} from "../../whisperActions"; + +// Platforms whose VODs expire by design, where "gone from the source" is the +// normal state and the availability check protects nothing. A hint only: the +// key is never set by platform. +const EXPIRING_VOD_PLATFORMS = new Set(["twitch", "kick"]); + +// A clean without checking, in two steps: the plan is counted (no network, no +// deletes) and stated, then a second button runs THAT plan — the job carries +// its video ids and removes at most those. `mode`: "button" is the one-off +// "Clean without checking"; "channel-setting" is Clean audio on a channel whose +// key is on (the key is read again when the job starts). +export function CleanWithoutCheckingSection({ + slug, + mode = "button", + queueKey, +}: { + slug: string; + mode?: "button" | "channel-setting"; + queueKey?: string; +}) { + const hydrated = useHydrated(); + const [plan, setPlan] = useState<AudioCleanPlan | null>(null); + const [error, setError] = useState<string | null>(null); + const [busy, setBusy] = useState(false); + const ask = async () => { + setBusy(true); + setError(null); + const r = await planCleanAudioUncheckedAction(slug); + setBusy(false); + if (r.ok) setPlan(r.plan); + else setError(r.error); + }; + const text = plan ? cleanConfirmationText(plan) : null; + const run = (ids: string[]) => + mode === "button" ? cleanAudioUncheckedAction(slug, queueKey, ids) : cleanAudioAction(slug, queueKey, ids); + return ( + <div aria-label="clean without checking section" className="flex flex-col gap-2 rounded border border-border p-3"> + <div> + <h4 className="text-sm font-semibold"> + {mode === "button" ? "Clean without checking" : "Clean audio without checking"} + </h4> + <p className="text-xs text-muted-foreground"> + {mode === "button" + ? "The same clean, without asking the source whether each video is still there." + : "This channel cleans without checking: the source is not asked."} + </p> + </div> + {!plan && ( + <div> + <button + type="button" + onClick={ask} + disabled={!hydrated || busy} + className="rounded border border-border bg-card px-3 py-1 text-sm hover:bg-accent disabled:opacity-50" + > + {busy ? "Counting…" : mode === "button" ? "Clean without checking…" : "Clean audio without checking…"} + </button> + </div> + )} + {error && ( + <p role="alert" className="text-sm text-destructive"> + {error} + </p> + )} + {plan && text && ( + <div role="group" aria-label="confirm clean without checking" className="flex flex-col gap-2"> + <p className="text-sm font-medium">{text.ask}</p> + <p className="text-xs text-muted-foreground">{text.kept}</p> + <div className="flex flex-wrap items-start gap-2"> + {plan.files > 0 && ( + <StreamActionLog + trigger={() => run(plan.ids)} + cancelAction={cancelJobAction} + buttonLabel={text.button} + runningLabel="Cleaning…" + label={mode === "button" ? "Clean without checking" : "Clean audio without checking"} + /> + )} + <button + type="button" + onClick={() => setPlan(null)} + className="rounded border border-border px-3 py-1 text-sm hover:bg-accent" + > + Cancel + </button> + </div> + </div> + )} + </div> + ); +} + +// The channel key cleanAudioWithoutChecking, set to a value. Turning it ON +// asks first, stating what it changes; turning it off does not. +export function AlwaysCleanWithoutCheckingToggle({ + slug, + on, + platform, +}: { + slug: string; + on: boolean; + platform: string; +}) { + const hydrated = useHydrated(); + const [pending, setPending] = useState(false); + const [asking, setAsking] = useState(false); + const set = async (value: boolean) => { + setPending(true); + await setCleanAudioWithoutCheckingAction(slug, value); + setPending(false); + setAsking(false); + }; + return ( + <div className="flex flex-col gap-1"> + <label className="flex items-center gap-2 text-sm"> + <input + type="checkbox" + checked={on || asking} + disabled={!hydrated || pending} + onChange={(e) => { + if (e.target.checked) setAsking(true); + else if (asking) setAsking(false); + else void set(false); + }} + aria-label="always clean this channel without checking" + /> + Always clean this channel without checking + </label> + {asking && !on && ( + <div role="group" aria-label="confirm always clean without checking" className="flex flex-col gap-2 rounded border border-border p-2"> + <p className="text-sm">{TURN_ON_CONFIRMATION}</p> + <div className="flex gap-2"> + <button + type="button" + disabled={pending} + onClick={() => void set(true)} + className="rounded border border-border bg-card px-3 py-1 text-sm hover:bg-accent disabled:opacity-50" + > + Turn on + </button> + <button + type="button" + onClick={() => setAsking(false)} + className="rounded border border-border px-3 py-1 text-sm hover:bg-accent" + > + Cancel + </button> + </div> + </div> + )} + <p className="text-xs text-muted-foreground"> + Every clean of this channel — the buttons here, /cleanup, pnpm ops and clean after capture — deletes audio + without asking the source whether the video is still there, so a video removed upstream loses its only copy. + </p> + {!on && EXPIRING_VOD_PLATFORMS.has(platform) && ( + <p className="text-xs text-muted-foreground"> + Twitch and Kick VODs expire on their own, so a check here mostly finds them gone. + </p> + )} + </div> + ); +} + +// A rate-limited Clean audio's retry, scheduled off the queue: when, and a +// Cancel that reaches it. +export function ScheduledCleanRetryNote({ slug, retry }: { slug: string; retry: ScheduledCleanRetry }) { + const hydrated = useHydrated(); + const [state, setState] = useState<"idle" | "busy" | "cancelled">("idle"); + if (state === "cancelled") { + return <p className="text-xs text-muted-foreground">Retry cancelled.</p>; + } + const when = new Date(retry.notBefore).toLocaleString(); + return ( + <div aria-label="scheduled clean retry" className="flex flex-wrap items-center gap-2 text-sm"> + <span> + {retry.gaveUp + ? `The source rate-limited the last Clean audio, and its retry ${retry.attempt} of 2 gave up: ${retry.gaveUp}` + : retry.state === "enqueued" + ? `The source rate-limited the last Clean audio: retry ${retry.attempt} of 2 is queued.` + : retry.heldReason + ? `The source rate-limited the last Clean audio: retry ${retry.attempt} of 2 is held (${retry.heldReason}); it tries again at ${when}.` + : `The source rate-limited the last Clean audio: retry ${retry.attempt} of 2 is scheduled, not before ${when}.`} + </span> + <button + type="button" + disabled={!hydrated || state === "busy"} + onClick={async () => { + setState("busy"); + await cancelCleanRetryAction(slug); + setState("cancelled"); + }} + className="rounded border border-border px-2 py-0.5 text-xs hover:bg-accent disabled:opacity-50" + > + {retry.gaveUp ? "Dismiss" : "Cancel retry"} + </button> + </div> + ); +} diff --git a/editor/app/channels/[slug]/components/stages/CleanupStage.tsx b/editor/app/channels/[slug]/components/stages/CleanupStage.tsx @@ -9,7 +9,7 @@ import { QueueControl } from "../../../../components/QueueControl"; import { cancelJobAction } from "../../../../jobs/actions"; import { checkKeptDeletedAction, - cleanAudioAction, + cleanAudioButtonAction, cleanExtraAudioFormatsAction, diarizeChannelAction, purgeSupersededAutoSubsAction, @@ -18,6 +18,12 @@ import { import { persistKeptAction } from "../../persistActions"; import { backupSavedVideosAction } from "../../../../saved-videos/backupActions"; import { VideoIdList } from "../VideoIdList"; +import { + AlwaysCleanWithoutCheckingToggle, + CleanWithoutCheckingSection, + ScheduledCleanRetryNote, +} from "./CleanWithoutChecking"; +import type { ScheduledCleanRetry } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; type Props = { slug: string; @@ -47,6 +53,12 @@ type Props = { // sweep holds audio back for any transcribed video without a sidecar, so the // backfill button that clears that hold belongs next to it. diarizationEnabled: boolean; + // The channel's cleanAudioWithoutChecking (every clean skips the + // availability check), and its platform, for the expiring-VOD hint. + cleanWithoutChecking: boolean; + platform: string; + // A rate-limited Clean audio's retry, waiting off the queue (or queued). + scheduledCleanRetry: ScheduledCleanRetry | null; }; export function CleanupStage({ @@ -65,6 +77,9 @@ export function CleanupStage({ savedBytes, backupConfigured, diarizationEnabled, + cleanWithoutChecking, + platform, + scheduledCleanRetry, }: Props) { const defaultQueueKey = `channel:${slug}`; const [cleanQueue, setCleanQueue] = useState(defaultQueueKey); @@ -115,22 +130,34 @@ export function CleanupStage({ desc="Delete audio.* files in any video directory that has a transcript.json (whisper output). YouTube videos with only auto-sub .vtt files have no audio and are skipped automatically. While diarization is on, a video awaiting its speakers or voice fingerprints keeps its audio." /> <ReclaimEstimate bytes={transcribedAudioBytes} /> - <StreamActionLog - trigger={() => cleanAudioAction(slug, cleanQueue)} - cancelAction={cancelJobAction} - buttonLabel="Clean audio" - runningLabel="Cleaning…" - label="Clean audio" - extraControls={ - <QueueControl - value={cleanQueue} - onChange={setCleanQueue} - defaultQueueKey={defaultQueueKey} - existingQueues={existingQueues} - actionLabel="Clean audio" + {scheduledCleanRetry && <ScheduledCleanRetryNote slug={slug} retry={scheduledCleanRetry} />} + {cleanWithoutChecking ? ( + // THE KEY IS ON: Clean audio runs without checking, so it shows the + // same counted confirmation as the one-off button and carries the + // confirmed plan. + <CleanWithoutCheckingSection slug={slug} mode="channel-setting" queueKey={cleanQueue} /> + ) : ( + <> + <StreamActionLog + trigger={() => cleanAudioButtonAction(slug, cleanQueue)} + cancelAction={cancelJobAction} + buttonLabel="Clean audio" + runningLabel="Cleaning…" + label="Clean audio" + extraControls={ + <QueueControl + value={cleanQueue} + onChange={setCleanQueue} + defaultQueueKey={defaultQueueKey} + existingQueues={existingQueues} + actionLabel="Clean audio" + /> + } /> - } - /> + <CleanWithoutCheckingSection slug={slug} queueKey={cleanQueue} /> + </> + )} + <AlwaysCleanWithoutCheckingToggle slug={slug} on={cleanWithoutChecking} platform={platform} /> </div> {supersededAutoSubsIds.length > 0 && ( <SupersededAutoSubsSection diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx @@ -1,5 +1,6 @@ import { displayPath, hidePrivateSites } from "yt-dlp-transcript-common/lib/privacy/privacy-server"; import { LiveRecordingsAttention } from "../../components/LiveRecordingsAttention"; +import { readCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; import { isPrivateSite } from "yt-dlp-transcript-common/lib/siteSchema"; import path from "node:path"; import { Suspense, type ReactNode } from "react"; @@ -824,6 +825,11 @@ export default async function ChannelDetailPage({ savedBytes={savedTotals.bytes} backupConfigured={settings.savedVideoBackup.dest.trim() !== ""} diarizationEnabled={settings.diarization.enabled} + cleanWithoutChecking={config!.cleanAudioWithoutChecking === true} + platform={config!.platform ?? detectUrlPlatform(config!.url ?? "") ?? ""} + scheduledCleanRetry={ + (await readCleanRetries(paths).catch(() => [])).find((r) => r.slug === slug && r.state !== "running") ?? null + } /> ); } diff --git a/editor/app/channels/[slug]/whisperActions.ts b/editor/app/channels/[slug]/whisperActions.ts @@ -19,7 +19,25 @@ import { } from "yt-dlp-transcript-common/controller/channels"; import { runWhisperBatch } from "yt-dlp-transcript-common/controller/whisperBatch"; import { clearFailedTranscriptions } from "yt-dlp-transcript-common/controller/failedTranscriptions"; -import { cleanAudioFromTranscribed } from "yt-dlp-transcript-common/controller/cleanAudioFromTranscribed"; +import { + planAudioClean, + type AudioCleanPlan, +} from "yt-dlp-transcript-common/controller/cleanAudioFromTranscribed"; +import { + cleanAudioRequestFor, + runCleanAudioJob, + uncheckedReasonFor, + type CleanAudioRequest, + type CleanPlanCountsLog, + type CleanRetry, +} from "yt-dlp-transcript-common/controller/cleanAudioJob"; +import { + cancelCleanRetries, + finishCleanRetry, + scheduleCleanRetry, + startCleanRetry, +} from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { cleanRetryDeps } from "./cleanRetryScheduler"; import { diarizeAll } from "yt-dlp-transcript-common/controller/diarizeAll"; import { purgeSupersededAutoSubs } from "yt-dlp-transcript-common/controller/purgeSupersededAutoSubs"; import { checkKeptDeleted } from "yt-dlp-transcript-common/controller/checkKeptDeleted"; @@ -27,6 +45,7 @@ import { cleanExtraAudioFormats } from "yt-dlp-transcript-common/controller/clea import { removeWrongFormatAudio } from "yt-dlp-transcript-common/controller/removeWrongFormatAudio"; import { verifyTranscripts } from "yt-dlp-transcript-common/controller/verifyTranscripts"; import { + JobDeferredError, runManagedFunction, type StreamActionResult, } from "yt-dlp-transcript-common/jobs/streamCommand"; @@ -294,25 +313,176 @@ export async function removeWrongFormatAudioAction( }); } +// "Clean audio": the checked sweep — unless the channel's config sets +// cleanAudioWithoutChecking, when it runs as "Clean audio without checking" +// (its own job kind, so the job list says so; the key is read again when the +// job starts). `plan` is a confirmed plan's video ids (a button that showed +// the counted confirmation): the run removes at most those. A clean a person +// starts supersedes the channel's scheduled rate-limit retry, if any. export async function cleanAudioAction( slug: string, queueKey?: string, + plan?: string[], ): Promise<StreamActionResult> { const paths = getPaths(); + const config = await readChannelConfig(paths, slug).catch(() => null); + await supersedeCleanRetries(slug); + return runCleanAudio(slug, queueKey, cleanAudioRequestFor(config, { plan })); +} + +// A PLAIN "Clean audio" BUTTON drawn while the channel's key was off. If the +// key is on by the time it is pressed, it would run without checking with no +// count shown, so it refuses and says to reload: the page then draws the +// counted confirmation (ruling 6). +export async function cleanAudioButtonAction( + slug: string, + queueKey?: string, +): Promise<StreamActionResult> { + const config = await readChannelConfig(getPaths(), slug).catch(() => null); + if (uncheckedReasonFor(config)) { + return { + ok: false, + info: true, + error: "This channel now cleans without checking: reload the page to see what would be removed before cleaning.", + }; + } + return cleanAudioAction(slug, queueKey); +} + +// "Clean without checking": the one-off, explicit unchecked sweep of a plan a +// person confirmed (its ids, from planCleanAudioUncheckedAction). The source is +// not asked; every other protection of the sweep holds; at most the plan's +// videos lose their audio. A call with no plan queues a job that removes +// nothing and ends failed, "Confirmed plan lost; confirm again". +export async function cleanAudioUncheckedAction( + slug: string, + queueKey?: string, + plan?: string[], + // The plan's counts, stated in the job's log before anything is removed + // (`pnpm ops cleanup {"unchecked": true}` counts at the call). + planCounts?: CleanPlanCountsLog, +): Promise<StreamActionResult> { + await supersedeCleanRetries(slug); + return runCleanAudio(slug, queueKey, cleanAudioRequestFor(null, { explicit: "button", plan }), undefined, planCounts); +} + +// The retry of a rate-limited clean, queued by its schedule at its not-before +// time (controller/cleanRetrySchedule.ts) — never a person's call: a retry +// whose record is gone (cancelled, superseded) does not run. +export async function cleanAudioRetryAction( + slug: string, + retry: CleanRetry, +): Promise<StreamActionResult> { + return runCleanAudio(slug, undefined, { kind: "clean-audio-transcribed" }, retry); +} + +// The confirmation's numbers: what a clean without checking would remove now +// (controller planAudioClean — no network, no deletes), and the ids a +// confirmed run carries. +export async function planCleanAudioUncheckedAction( + slug: string, +): Promise<{ ok: true; plan: AudioCleanPlan } | { ok: false; error: string }> { + try { + return { ok: true, plan: await planAudioClean({ channelSlug: slug, paths: getPaths() }) }; + } catch (err) { + return { ok: false, error: (err as Error).message }; + } +} + +// What a Clean audio button would do NOW: checked, or without checking (the +// channel's key) — and then the counted plan its confirmation shows (ruling 6: +// every button that would run unchecked shows the same counted confirmation). +export async function prepareCleanAudioAction( + slug: string, +): Promise<{ ok: true; withoutChecking: boolean; plan?: AudioCleanPlan } | { ok: false; error: string }> { + const paths = getPaths(); + const config = await readChannelConfig(paths, slug).catch(() => null); + if (!uncheckedReasonFor(config)) return { ok: true, withoutChecking: false }; + const r = await planCleanAudioUncheckedAction(slug); + return r.ok ? { ok: true, withoutChecking: true, plan: r.plan } : r; +} + +// The Cleanup stage's "Cancel retry": cancel this channel's scheduled retry of +// a rate-limited clean (and its job, if the schedule has queued it). +export async function cancelCleanRetryAction(slug: string): Promise<{ ok: boolean; cancelled: number }> { + const removed = await cancelCleanRetries(getPaths(), { slug }, cleanRetryDeps()); + safeRevalidate([`/channels/${slug}`]); + return { ok: true, cancelled: removed.length }; +} + +async function supersedeCleanRetries(slug: string): Promise<void> { + const removed = await cancelCleanRetries(getPaths(), { slug }, cleanRetryDeps()).catch(() => []); + for (const r of removed) { + console.log(`[clean-retry] ${r.id}: superseded by a new clean of ${slug}.`); + } +} + +function runCleanAudio( + slug: string, + queueKey: string | undefined, + req: CleanAudioRequest, + retry?: CleanRetry, + planCounts?: CleanPlanCountsLog, +): Promise<StreamActionResult> { + const paths = getPaths(); + const kind = retry ? "clean-audio-retry" : req.kind; + const { unchecked, plan } = req; + // A retry runs on the CHANNEL's queue, whatever queue the request took. + const key = retry ? channelQueueKey(slug) : resolveQueueKey(channelQueueKey(slug), queueKey); return runManagedFunction({ - kind: "clean-audio-transcribed", - queueKey: resolveQueueKey(channelQueueKey(slug), queueKey), + kind, + queueKey: key, paths, channelSlug: slug, - spec: { kind: "clean-audio-transcribed", slug, params: { queueKey } }, - fn: async (onLog, signal) => { - await cleanAudioFromTranscribed({ - channelSlug: slug, - paths, - onLog, - signal, - }); - safeRevalidate([`/channels/${slug}`]); + spec: { + kind, + slug, + params: { + queueKey, + ...(unchecked ? { unchecked } : {}), + ...(plan ? { plan } : {}), + ...(plan && planCounts ? { planCounts } : {}), + ...(retry ? { retry } : {}), + }, + }, + fn: async (onLog, signal, _setProgress, ctx) => { + // A retry runs only while its schedule's record says so. + if (retry?.id && !(await startCleanRetry(paths, retry.id, ctx.jobId))) { + onLog("This retry was cancelled or superseded before it started: nothing was asked or cleaned."); + return; + } + try { + const out = await runCleanAudioJob({ + channelSlug: slug, + paths, + jobId: ctx.jobId, + ...(unchecked ? { unchecked } : {}), + ...(plan ? { plan } : {}), + ...(plan && planCounts ? { planCounts } : {}), + ...(retry ? { retry } : {}), + onLog, + signal, + deps: { + scheduleRetry: async (next) => { + try { + const entry = await scheduleCleanRetry( + paths, + { slug, attempt: next.attempt, of: next.of, notBefore: next.notBefore, platform: next.platform, deferredJobId: ctx.jobId }, + cleanRetryDeps(), + ); + return { ok: true, id: entry.id }; + } catch (err) { + return { ok: false, error: (err as Error).message }; + } + }, + }, + }); + safeRevalidate([`/channels/${slug}`]); + if (out.end === "deferred") throw new JobDeferredError(out.sentence, out.until); + if (out.end === "failed") throw new Error(out.sentence); + } finally { + if (retry?.id) await finishCleanRetry(paths, retry.id).catch(() => {}); + } }, }); } diff --git a/editor/app/channels/actions.ts b/editor/app/channels/actions.ts @@ -1,5 +1,7 @@ "use server"; +import { cancelCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { cleanRetryDeps } from "./[slug]/cleanRetryScheduler"; import { isRemoteOnlyChannel } from "yt-dlp-transcript-common/lib/channelConfig"; import { prepareLocalArchiveChannel } from "./lib/prepareLocalArchiveChannel"; import { withRumbleDefaults } from "yt-dlp-transcript-common/lib/rumbleDefaults"; @@ -642,6 +644,29 @@ export async function setChannelExclusionsAction( return undefined; } +// CLEAN WITHOUT CHECKING, ALWAYS (lane clean-unverified): set this channel's +// cleanAudioWithoutChecking to a stated value — the Cleanup stage's checkbox +// and `channel-config {"cleanAudioWithoutChecking"}`. `false` removes the key +// (absent = checked, the default). Through patchChannelConfig only. +export async function setCleanAudioWithoutCheckingAction( + slug: string, + on: boolean, +): Promise<ActionResult> { + const paths = getPaths(); + const existing = await readChannelConfig(paths, slug); + if (!existing) return { error: `Channel "${slug}" not found` }; + await (on + ? patchChannelConfig(paths, slug, { cleanAudioWithoutChecking: true }) + : patchChannelConfig(paths, slug, {}, { unset: ["cleanAudioWithoutChecking"] })); + // A rate-limited clean's scheduled retry would list the source and pin gone + // videos do-not-clean, which every unchecked clean then skips: turning the + // key on cancels it. + if (on) await cancelCleanRetries(paths, { slug }, cleanRetryDeps()).catch(() => []); + revalidatePath(`/channels/${slug}`); + revalidatePath("/cleanup"); + return undefined; +} + // Toggle whether this channel's reclaimable bytes count toward the aggregate // "cleanable data" total on the /cleanup page (and its sidebar badge). The // cleanup sweeps themselves stay available regardless; this only flips the diff --git a/editor/app/cleanup/components/ChannelCleanupCard.tsx b/editor/app/cleanup/components/ChannelCleanupCard.tsx @@ -7,12 +7,13 @@ import { formatBytes } from "yt-dlp-transcript-common/lib/format"; import { Badge } from "yt-dlp-transcript-common/components/ui/badge"; import { cancelJobAction } from "../../jobs/actions"; import { - cleanAudioAction, + cleanAudioButtonAction, cleanExtraAudioFormatsAction, removeWrongFormatAudioAction, clearFailedTranscriptionsAction, } from "../../channels/[slug]/whisperActions"; import { ChannelCleanupToggle } from "./ChannelCleanupToggle"; +import { CleanWithoutCheckingSection } from "../../channels/[slug]/components/stages/CleanWithoutChecking"; export type ChannelCleanupCardProps = { slug: string; @@ -23,6 +24,9 @@ export type ChannelCleanupCardProps = { foreignBytes: number; hasTargetFormat: boolean; failedTranscriptions: number; + // The channel's cleanAudioWithoutChecking: its Clean audio runs unchecked, + // so the card shows the counted confirmation instead of a one-click button. + withoutChecking?: boolean; }; export function ChannelCleanupCard({ @@ -34,6 +38,7 @@ export function ChannelCleanupCard({ foreignBytes, hasTargetFormat, failedTranscriptions, + withoutChecking = false, }: ChannelCleanupCardProps) { const queueKey = `channel:${slug}`; const [armed, setArmed] = useState(false); @@ -80,15 +85,23 @@ export function ChannelCleanupCard({ {transcribedBytes > 0 && ( <SweepRow estimate={transcribedBytes} - caption="Audio in transcribed video dirs" + caption={ + withoutChecking + ? "Audio in transcribed video dirs (cleaned without checking)" + : "Audio in transcribed video dirs" + } > - <StreamActionLog - trigger={() => cleanAudioAction(slug, queueKey)} - cancelAction={cancelJobAction} - buttonLabel="Clean audio" - runningLabel="Cleaning…" - label={`Clean audio ${slug}`} - /> + {withoutChecking ? ( + <CleanWithoutCheckingSection slug={slug} mode="channel-setting" queueKey={queueKey} /> + ) : ( + <StreamActionLog + trigger={() => cleanAudioButtonAction(slug, queueKey)} + cancelAction={cancelJobAction} + buttonLabel="Clean audio" + runningLabel="Cleaning…" + label={`Clean audio ${slug}`} + /> + )} </SweepRow> )} diff --git a/editor/app/cleanup/lib/loadCleanup.ts b/editor/app/cleanup/lib/loadCleanup.ts @@ -230,6 +230,8 @@ export type CleanableChannelRow = { count: number; // Reclaim estimate for the primary "clean audio" sweep, net of protection. bytes: number; + // The channel's cleanAudioWithoutChecking (its Clean audio button says so). + withoutChecking?: boolean; }; // Lean per-channel breakdown for the sidebar badge and the widget API — the @@ -256,7 +258,12 @@ export async function cleanableChannels( // Nothing to reclaim and nothing to sweep — drop the row. Zero-byte rows // contribute nothing to the total, so dropping them keeps it unchanged. if (bytes <= 0 && count <= 0) return null; - return { slug: channel.slug, count, bytes }; + return { + slug: channel.slug, + count, + bytes, + ...(channel.config.cleanAudioWithoutChecking === true ? { withoutChecking: true } : {}), + }; }); return rows .filter((r): r is CleanableChannelRow => r !== null) diff --git a/editor/app/cleanup/page.tsx b/editor/app/cleanup/page.tsx @@ -177,6 +177,7 @@ export default async function CleanupPage() { foreignBytes={r.foreignBytes} hasTargetFormat={r.hasTargetFormat} failedTranscriptions={r.failedTranscriptions} + withoutChecking={r.channel.config.cleanAudioWithoutChecking === true} /> ))} </section> diff --git a/editor/app/components/actions/InlineActionButton.tsx b/editor/app/components/actions/InlineActionButton.tsx @@ -9,9 +9,12 @@ import { } from "../../channels/[slug]/pipelineActions"; import { cleanAudioAction, + cleanAudioButtonAction, cleanExtraAudioFormatsAction, + prepareCleanAudioAction, transcribeMissingAction, } from "../../channels/[slug]/whisperActions"; +import { cleanConfirmationText } from "yt-dlp-transcript-common/lib/cleanAudioConfirm"; import { clearIncompleteTranscriptsAction, redownloadIncompleteBucketAction, @@ -28,7 +31,9 @@ type Variant = | { kind: "redownloadIncomplete"; slug: string } | { kind: "clearIncomplete"; slug: string } | { kind: "redownloadShortAudio"; slug: string } - | { kind: "cleanTranscribedAudio"; slug: string } + // `withoutChecking`: the channel's cleanAudioWithoutChecking as the page + // read it (the label); the click asks the server again either way. + | { kind: "cleanTranscribedAudio"; slug: string; withoutChecking?: boolean } | { kind: "cleanExtraFormats"; slug: string } | { kind: "backfillChannel"; slug: string } // The digest lane's LOCAL half only. The metered lane is behind a settings @@ -94,7 +99,7 @@ async function runAction(variant: Variant): Promise<StreamActionResult> { return redownloadShortAudioBucketAction(variant.slug); } if (variant.kind === "cleanTranscribedAudio") { - return cleanAudioAction(variant.slug); + return cleanAudioButtonAction(variant.slug); } if (variant.kind === "cleanExtraFormats") { return cleanExtraAudioFormatsAction(variant.slug); @@ -141,13 +146,64 @@ export function InlineActionButton({ }) { const [status, setStatus] = useState<Status>({ kind: "idle" }); const [pending, startTransition] = useTransition(); - const base = LABEL[variant.kind]; + const base = + variant.kind === "cleanTranscribedAudio" && variant.withoutChecking + ? { idle: "Clean audio without checking", running: "Queuing…" } + : LABEL[variant.kind]; const labels = label ? { ...base, idle: label } : base; const slug = variant.slug; const ariaLabel = `${labels.idle.toLowerCase()} ${slug}`; + // CLEAN AUDIO asks the server first what it would do now: checked (the + // plain confirm), or WITHOUT CHECKING (the channel's key) — then the counted + // confirmation every unchecked button shows, and the run carries that plan. + async function cleanTranscribed() { + setStatus({ kind: "running" }); + const prep = await prepareCleanAudioAction(slug); + if (!prep.ok) { + setStatus({ kind: "error", message: prep.error }); + return; + } + let result: StreamActionResult; + if (prep.withoutChecking && prep.plan) { + const text = cleanConfirmationText(prep.plan); + if (prep.plan.files === 0) { + setStatus({ kind: "done", message: "nothing to remove" }); + return; + } + if (!window.confirm(`${text.ask}\n\n${text.kept}`)) { + setStatus({ kind: "idle" }); + return; + } + result = await cleanAudioAction(slug, undefined, prep.plan.ids); + } else { + if (!window.confirm(CONFIRM.cleanTranscribedAudio!(slug))) { + setStatus({ kind: "idle" }); + return; + } + // Refuses if the key came on since the prepare said "checked". + result = await cleanAudioButtonAction(slug); + } + if (!result.ok) { + setStatus({ kind: "error", message: result.error }); + return; + } + void result.stream.cancel(); + setStatus({ kind: "queued", jobId: result.jobId }); + } + function handleClick() { + if (variant.kind === "cleanTranscribedAudio") { + startTransition(async () => { + try { + await cleanTranscribed(); + } catch (e) { + setStatus({ kind: "error", message: (e as Error).message }); + } + }); + return; + } const confirmMessage = CONFIRM[variant.kind]?.(slug); if (confirmMessage && !window.confirm(confirmMessage)) return; setStatus({ kind: "running" }); diff --git a/editor/app/components/channelWork/sections.tsx b/editor/app/components/channelWork/sections.tsx @@ -226,7 +226,11 @@ export function channelWorkSections(): SectionConfig[] { }, primaryAction: (r) => ( <InlineActionButton - variant={{ kind: "cleanTranscribedAudio", slug: r.channel.slug }} + variant={{ + kind: "cleanTranscribedAudio", + slug: r.channel.slug, + withoutChecking: r.channel.config.cleanAudioWithoutChecking === true, + }} /> ), }, diff --git a/editor/app/jobs/actions.ts b/editor/app/jobs/actions.ts @@ -24,6 +24,8 @@ import { readJobMeta } from "yt-dlp-transcript-common/jobs/jobMeta"; import type { JobSpec } from "yt-dlp-transcript-common/jobs/jobSpec"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; import { runJobSpec } from "./runJobSpec"; +import { cancelCleanRetries } from "yt-dlp-transcript-common/controller/cleanRetrySchedule"; +import { cleanRetryDeps } from "../channels/[slug]/cleanRetryScheduler"; import { stuckJobIds } from "./active/buildActiveJobs"; export async function cancelJobAction(id: string): Promise<{ ok: boolean }> { @@ -31,8 +33,12 @@ export async function cancelJobAction(id: string): Promise<{ ok: boolean }> { // work on (a whisper-video, once its audio is down: JobRecord.handedOffTo) // cancels the job doing that work now — the panel is still showing it. const ok = getRegistry().cancel(jobDoingTheWork(id)); + // A CLEAN THE SOURCE RATE-LIMITED ended deferred and scheduled its retry + // off-queue (controller/cleanRetrySchedule.ts): Cancel of that job — or of + // the retry's own queued job — cancels the scheduled retry. + const retries = await cancelCleanRetries(getPaths(), { id }, cleanRetryDeps()).catch(() => []); revalidatePath("/jobs"); - return { ok }; + return { ok: ok || retries.length > 0 }; } // Escape hatch for a WEDGED slot (see registry.forceRelease): unconditionally diff --git a/editor/app/jobs/components/JobRow.tsx b/editor/app/jobs/components/JobRow.tsx @@ -183,6 +183,8 @@ function videoHref(job: JobRowView): string | null { // anything live, and Force-release anything running or stuck (the escape hatch // for a Cancel that leaves a queue wedged; see registry.forceRelease — a stuck // terminal/evicted row has no Cancel to offer, so it gets this instead). +const CLEAN_KINDS_WITH_RETRY = new Set(["clean-audio-transcribed", "clean-audio-unchecked", "clean-audio-retry"]); + export function JobRowActions({ job, forceRelease = "running-or-stuck", @@ -210,6 +212,11 @@ export function JobRowActions({ {(job.status === "running" || job.status === "queued") && ( <CancelJobButton jobId={job.id} /> )} + {/* A Clean audio the source rate-limited ended deferred and scheduled its + retry off the queue: Cancel here cancels that retry (cancelJobAction). */} + {job.status === "done" && job.deferred && CLEAN_KINDS_WITH_RETRY.has(job.kind) && ( + <CancelJobButton jobId={job.id} /> + )} {((forceRelease === "running-or-stuck" && job.status === "running") || Boolean(job.stuck)) && <ForceReleaseJobButton jobId={job.id} />} </> diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -12,6 +12,8 @@ import { savePageNowBatchAction } from "../channels/[slug]/waybackLiveActions"; import { xRunAction } from "../review/xRunActions"; import { coerceClipCopy } from "yt-dlp-transcript-common/lib/clipWindow"; import { isStoredUrlMode } from "yt-dlp-transcript-common/lib/storedMediaUrl"; +import { replayCleanSpec } from "yt-dlp-transcript-common/controller/cleanAudioJob"; +import { readChannelConfig } from "yt-dlp-transcript-common/controller/channels"; import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot"; import type { JobSpec, ReplayBucket } from "yt-dlp-transcript-common/jobs/jobSpec"; import type { StreamActionResult } from "yt-dlp-transcript-common/jobs/streamCommand"; @@ -35,6 +37,7 @@ import { import { checkKeptDeletedAction, cleanAudioAction, + cleanAudioUncheckedAction, cleanExtraAudioFormatsAction, diarizeChannelAction, clearFailedTranscriptionsAction, @@ -144,6 +147,16 @@ function params(spec: JobSpec): { return { p, queueKey: str(p.queueKey) }; } +// Every replay path (Retry, Retry all failed, `ops job retry`, the boot's +// re-queue) comes through runJobSpec to here; the channel's key is read now +// (controller/cleanAudioJob.ts replayCleanSpec). +const replayClean: ReplayHandler = (spec) => + replayCleanSpec(spec, { + readConfig: (slug) => readChannelConfig(getPaths(), slug), + clean: (slug, queueKey, plan) => cleanAudioAction(slug, queueKey, plan), + unchecked: (slug, queueKey, plan) => cleanAudioUncheckedAction(slug, queueKey, plan), + }); + // A PUBLISH STAGE (release 18): the spec IS the stage request, so a retry // re-enqueues it as it was — same run id, same preconditions, which the child // re-asks on disk. A spec the stage row would refuse is refused here. @@ -534,10 +547,15 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { const { queueKey } = params(spec); return purgeSupersededAutoSubsAction(spec.slug, queueKey); }, - "clean-audio-transcribed": (spec) => { - const { queueKey } = params(spec); - return cleanAudioAction(spec.slug, queueKey); - }, + // THE CLEAN KINDS (lane clean-unverified): one rule, cleanReplayFor + // (controller/cleanAudioJob.ts). A Retry is a person's — and the boot's + // re-queue of a job a restart caught queued: Clean audio again (the key as + // it is now decides), a retry's Retry a fresh chain, and an unchecked + // "button" run again WITH ITS CARRIED PLAN only (no plan: a job that + // removes nothing and ends "Confirmed plan lost; confirm again"). + "clean-audio-transcribed": replayClean, + "clean-audio-retry": replayClean, + "clean-audio-unchecked": replayClean, "diarize-channel": (spec) => { const { queueKey } = params(spec); return diarizeChannelAction(spec.slug, queueKey); diff --git a/editor/app/widget/components/MonitorWidget.tsx b/editor/app/widget/components/MonitorWidget.tsx @@ -964,7 +964,7 @@ function CleanableChannelsStrip({ {interactive && ( <div className="flex flex-wrap items-center gap-1.5"> <InlineActionButton - variant={{ kind: "cleanTranscribedAudio", slug: c.slug }} + variant={{ kind: "cleanTranscribedAudio", slug: c.slug, withoutChecking: c.withoutChecking === true }} /> </div> )} diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -325,6 +325,19 @@ export async function register() { /* a runner that fails to start must not block server readiness */ } + // A RATE-LIMITED CLEAN'S SCHEDULED RETRY (lane clean-unverified): each + // record in `.jobs/clean-retries.json` gets its timer again, so a retry + // survives a restart with its attempt count and never runs before its + // not-before time. Below the idle gate: a retry lists the channel. An idle + // boot keeps the records for the next boot. + // See common/controller/cleanRetrySchedule.ts. + try { + const { armCleanRetriesOnBoot } = await import("./app/channels/[slug]/cleanRetryScheduler"); + void armCleanRetriesOnBoot().catch(() => {}); + } catch { + /* a schedule that fails to arm must not block server readiness */ + } + // AN `auto` RESEARCH RUN CONTINUES BY ITSELF (release 28 F1): the job-end // listener and one scan of the research runs now; the heartbeat scans again // on each beat. Below the idle gate: a continuation is a generation job. diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -85,6 +85,7 @@ // pnpm ops channel-config --json '{"slug":"x","patch":{"downloadMode":"manual"}}' // pnpm ops channel-config --json '{"slug":"x","sites":[{"siteId":"anilyzer"}]}' // pnpm ops channel-config --json '{"slug":"x","sites":[],"excludeFromBuild":true}' +// pnpm ops channel-config --json '{"slug":"x","cleanAudioWithoutChecking":true}' // pnpm ops create-site --json '{"siteId":"demo-site","siteTitle":"Demoalyzer","channels":["demo-yt"]}' // pnpm ops create-site --json '{"siteId":"demo-site","update":true,"homeTagline":"Every stream, searchable"}' // pnpm ops site-config --json '{"siteId":"anilyzer","citedChannels":["critic-channel"]}' @@ -119,6 +120,7 @@ // pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}' // pnpm ops lane --json '{"lane":"publish","action":"drain"}' // pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait +// pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed","unchecked":true,"dryRun":true}' // pnpm ops workers --json '{"op":"disable","ids":["parakeet-cpu"]}' // pnpm ops get job <jobId> --tail 20 // pnpm ops get jobs --failed --slug x @@ -1820,7 +1822,20 @@ export function usage() { ' "transcribed" (audio of transcribed videos — the /cleanup total) |', ' "extra-formats" | "wrong-format" | "failed-transcriptions" (clears the', ' list; deletes nothing)}. Do-not-clean videos are skipped; `get cleanup', - ' <slug>` says what each would reclaim.', + ' <slug>` says what each would reclaim. "unchecked": true (transcribed', + ' only) is "Clean without checking": the source is not asked, so the audio', + ' of videos no longer available anywhere goes too; every other protection', + ' holds; the job is "Clean audio without checking". With "dryRun": true it', + ' answers what it would remove — {plan: {ids, videos, files, bytes,', + ' protected, awaitingDiarization, awaitingVoiceprint, inspected}} — and', + ' starts nothing; without it the plan is counted at the call, its counts', + ' answered ({jobId, plan}) and logged, and the job removes at most those', + ' videos\' audio. It never touches a saved video. With the channel\'s', + ' cleanAudioWithoutChecking on, "transcribed" with no flag runs unchecked', + ' with no count (so do job retry and retry-failed of a clean).', + ' A checked clean the source rate-limits ends deferred and schedules a', + ' retry off the queue after at least 15 min (twice at most), then gives', + ' up; `job cancel <the deferred job id>` cancels the retry.', "", 'relocate moves channels\' media to a location: {"slugs", "locationId" |', ' "root"}. "dryRun": true answers each channel\'s preview (bytes to copy,', @@ -1939,8 +1954,10 @@ export function usage() { 'channel-config changes a channel as its Configure form does: {"slug"} and', ' any of "patch" (form field names; "" clears one), "sites" (the WHOLE', ' membership set: [{"siteId", "groupId"? | "newGroupName"?}], [] = on no', - ' site; an unknown site id is refused), "excludeFromBuild" and', - ' "excludeFromCleanup" (set to the value given, not toggled). A VOD mirror\'s', + ' site; an unknown site id is refused), "excludeFromBuild",', + ' "excludeFromCleanup" and "cleanAudioWithoutChecking" (every clean of the', + ' channel skips the availability check; set to the value given, not', + ' toggled). A VOD mirror\'s', ' recorded date: "patch": {"recordedDateTitlePattern": "<regex with named', ' groups year, month, day>"} (CHANNEL.md, recordedDate). A mirror\'s', ' creator channels: "patch": {"mirrorOf": "<slug>, <slug>"} (CHANNEL.md,',