commit 123f2f78da4717653467c1ec13a61bdfb99a7761
parent 4de99c54c9b007a916f83e70b1554cebcbb47334
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 11 Nov 2026 09:58:02 -0500
Merge main (7b841a82) into lane/local-media
The one conflict is the channel-config key count in
common/lib/channelConfigSchema.test.ts: 44, main's
`cleanAfterCaptureUnverified` plus this lane's `localMedia`. CHANNEL.md and
COMMANDS.md auto-merged and pass their --check.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat:
79 files changed, 4476 insertions(+), 229 deletions(-)
diff --git a/AGENTS.md b/AGENTS.md
@@ -91,7 +91,7 @@ pnpm ops render-mode --json '{"on":true,"for":"90m"}' # the same with only pnpm
While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other
renders) waits at the heavy slot's door — `queue-lock: held for a render (umtool take <p> --id
<t>, since 13:31) — waiting` is the gate working — while the render runs on the floor 4000 MB
-and the cap 10240 MB; the editor's transcription and download lanes are held (only the ones
+and the cap 10240 MB; the editor's transcription, download and Speakers lanes are held (only the ones
not already held; only those are released). **A script uses `render-mode on -- <cmd …>`, never a bare `on`**: the
command carries the token, the hold is its pid, and it ends when the command exits — a bare `on`
in a script leaves a window behind and its later commands wait at the door (the chain trap);
diff --git a/CHANNEL.md b/CHANNEL.md
@@ -40,6 +40,7 @@ Regenerate this file with `pnpm --filter yt-dlp-transcript-common exec tsx bin/f
| `lastFullSweepAt` | sync state | SYNC STATE. When this channel last paid for a sync FULL SWEEP — the deep pass that re-enumerates the whole listing to refresh `playlist` and flag videos that have left it. Stamped by the sweep; read by the cadence gate to decide whether the next sync sweeps or stays on the cheap newest-first paged walk. |
| `excludeFromBuild` | config | Leave this channel out of every site build. |
| `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. |
+| `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. |
| `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. |
| `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
@@ -172,8 +172,8 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `check-windows` | check-windows probes cached clip windows (data/<id>/clips/) for a picture that runs off the sound (a Rumble HLS seek) and sets each desynced one aside as <from>-<to>.desynced.<ext> (never deleted; no reader sees it, and evict-clips ages it out): {"slug"?, "video"?, "dryRun"?}. "video" needs "slug"; "dryRun" only lists. A fetch then fills the span again, from the saved video first. | |
| `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "<id>"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` |
| `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` |
-| `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` |
-| `render-mode` | render-mode gives a render the operator is waiting for the machine: {"on": true, "for"?: "90m" \| <minutes>, "note"?} opens a window (default 2h) in which every other heavy job — e2e suites, next builds, the publish stages, other renders — waits at the heavy slot's door, and holds the transcription and download lanes (only the ones not already held; only those are released). The answer's "join" (RENDER\_PRIORITY\_TOKEN=…) lets a render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take` joins by itself. {"on": false} ends it ("force": true ends a running take's hold, which otherwise ends with the take). `umtool take … --priority` is the same for one take. `get render-mode` says whether it is on, for what, since when, which lanes it holds. Close Firefox and other heavy apps while it renders. | `pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'`<br>`pnpm ops render-mode --json '{"on":false}'` |
+| `lane` | lane takes {"lane": "transcription"\|"download"\|"digest"\|"backfill"\| "publish", "enabled"?, "held"?, "action"?: "start"\|"stop"\|"drain"}, or {"lane": "report-schedule", "held"}: the recurring reports' gate, its only key. An auto-queue lane also takes "operations": \[ids\] \| null (dispatch only these — \["diarization"\] is speakers only; null widens it again) and "order" ("space" on backfill: corpus-disk channels first, then the most audio bytes per audio-hour). The backfill (Speakers) lane takes "speakers": "work" (the deck's Work through speakers: arm, lift the hold, start a run) \| "pause" (hold; stays armed). | `pnpm ops lane --json '{"lane":"download","held":true}'`<br>`pnpm ops lane --json '{"lane":"backfill","operations":["diarization"],"order":"space"}'`<br>`pnpm ops lane --json '{"lane":"backfill","speakers":"work"}'`<br>`pnpm ops lane --json '{"lane":"publish","action":"drain"}'` |
+| `render-mode` | render-mode gives a render the operator is waiting for the machine: {"on": true, "for"?: "90m" \| <minutes>, "note"?} opens a window (default 2h) in which every other heavy job — e2e suites, next builds, the publish stages, other renders — waits at the heavy slot's door, and holds the transcription, download and Speakers lanes (only the ones not already held; only those are released). The answer's "join" (RENDER\_PRIORITY\_TOKEN=…) lets a render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take` joins by itself. {"on": false} ends it ("force": true ends a running take's hold, which otherwise ends with the take). `umtool take … --priority` is the same for one take. `get render-mode` says whether it is on, for what, since when, which lanes it holds. Close Firefox and other heavy apps while it renders. | `pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'`<br>`pnpm ops render-mode --json '{"on":false}'` |
| `tags` | tags edits the curated-tag vocabulary through its one writer: {"op": "define", "tag": {...}} (the WHOLE definition: id, label, rules and "sites", the sites it exists on, absent = every site) or {"op": "remove", "tag": "<id>"}. `get tags [<id>]` reads it. | `pnpm ops tags --json '{"op":"define","tag":{"id":"eva-collab","label":"Collab"}}'` |
| `tag-videos` | tag-videos pins, unpins, suppresses or unsuppresses one tag on many videos in ONE write: {"tag", "op": "add" \| "remove" \| "suppress" \| "unsuppress", "videos": \[{"slug", "id"}, ...\]}. "remove" unpins only — a rule's hit survives; "suppress" rejects it. The write records who asked (ARCHILYZER\_AGENT); a big list goes in --file. | `pnpm ops tag-videos --file ids.json` |
| `keep-videos` | keep-videos sets the "Do not clean" marker on every held video of a channel whose title or description matches a download-filter pattern: {"slug", "match", "fields"?: \["title" \| "description"\], "note"?, "dryRun"?}. A match not held is reported in "notDownloaded", never created; a fresh channel wants metadata-scan first. Or by id: {"slug", "ids": \[...\], "note"?, "dryRun"?} — a held video is marked now, one not held yet (a live stream, a VOD not fetched) is PENDING and marked when its record is first written (a download, an import, a recording); "pendingAll" lists the channel's pending ids. | `pnpm ops keep-videos --json '{"slug":"demo-rumble","ids":["v1abcde"],"note":"keep"}'` |
@@ -185,7 +185,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `tts` | tts speaks a line with a local text-to-speech engine and a STOCK voice, as a job on the `tts` queue: {"text": "..."} or {"file": "/abs/script.txt"} (UTF-8, at most 20,000 characters), "engine" (kokoro \| orpheus \| espeak-ng), "voice" (one of the engine's stock voices; kokoro: af\_heart, bm\_george, ...; orpheus: leah, zac, ...), "speed" (0.5-2; orpheus has none) — defaults from settings.tts (kokoro, af\_heart, 1) — and "out" (an absolute .wav path the result is copied to, never inside the corpus). The expressive tags <laugh> <chuckle> <sigh> <cough> <sniffle> <groan> <yawn> <gasp> are performed by orpheus and stripped for the others; any other <...> is refused. Numbers, years, money and times are spoken (2024: "twenty twenty-four"). The result is {wav, seconds, engine, voice, cached, durationMs, waitedMs, sha, sampleRate, speed, disclosure}: wav is the 48 kHz mono WAV the editor wrote (out, or its cache), disclosure the line a narrated export carries. The same ask again is answered from the cache (cached: true, no engine run). Kokoro and orpheus need `archilyzer tts setup [--engine orpheus]` first; orpheus runs on the GPU (a local llama-server the editor starts and stops) and waits while a transcription holds it. With --wait the result is printed on stdout. | `pnpm ops tts --json '{"text":"In 2024 the archive spoke."}' --wait`<br>`pnpm ops tts --json '{"file":"/abs/script.txt","voice":"bm_george","out":"/abs/line.wav"}' --wait` |
| `voice-enhance` | voice-enhance cleans a speech recording up (denoise, soften the room, level it) as a job on the `voice` queue, behind the heavy slot: {"file": "/abs/take.wav", "out": "/abs/clean.wav"} (never inside the corpus; 48 kHz mono, exactly as long as the input), "engine" (deepfilternet \| rnnoise; settings.voice), "params" (the engine's knobs: lufs, highpass, attenLimDb, postFilter, mix), "parts" (\[{file, out}\], a take recorded part by part). deepfilternet needs `archilyzer voice setup --engine deepfilternet`; rnnoise needs nothing. The result is {op, engine, wav, seconds, samples, sampleRate, engineMs, durationMs, waitedMs, gainDb, params, parts?, synthetic}; with --wait it is printed on stdout. | |
| `voice-convert` | voice-convert keeps a recording's performance (timing, pitch contour) and swaps its timbre for a STOCK synthetic voice, as voice-enhance's job: the same body plus "voice" — "<tts engine>:<stock voice>" (orpheus:zac, orpheus:leah, kokoro:am\_michael, ...; settings.voice.convert.target); a file, a path or a recording is REFUSED as a target (no real person's voice) — and "engine" (openvoice \| seed-vc, each installed by `archilyzer voice setup --engine <id>`). The target's reference is synthesized once through the tts op and kept. The result adds target, voice, synthetic: true and the disclosure line. | |
-| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
+| `settings` | settings patches settings.json through the editor's one writer: {"patch": {"<top-level key>": value, …}} (SETTINGS.md). A block's keys merge one level; an array, a scalar or an object nested in a block replaces. Refused before anything is written: an unknown key; a key another writer owns (channelPriority, autoQueue, workers, storage — the refusal names it); a value the schema would not keep as sent (clamped, dropped), named with what would be saved. Answers the saved values. | `pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'`<br>`pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}'` |
| `clear-platform-hold` | clear-platform-hold clears a platform's rate-limit hold, backoff and raised pace, as the lane strip's Clear hold: {"platform"}. Answers the sentence. | |
| `recheck-service` | recheck-service asks a service whose cookie refresh alert is up ONE request through its own path, as the dashboard banner's Recheck: {"service"} ("rumble", "youtube", "odysee", "archive.today", "x" or a forum host). Waits for it: {jobId, result: "clean" \| "stale" \| "failed", message}; "clean" clears the alert (and a yt-dlp service's backoff, as any clean request). For "x" it sends X NO request: clean when the login on disk was renewed after the alert (Refresh cookies on /settings) — for a jar-age alert, when the jar is within social.x.maxCookieAgeMinutes. The editor also rechecks by itself on a timer (settings.serviceCookies.recheckIntervalMinutes, default 180, 0 = off; `pnpm ops settings --json '{"patch":{"serviceCookies":{"recheckIntervalMinutes":0}}}'`). dismiss-service clears a service's cookie alert by hand: {"service"}. rerun-service-jobs retries every job a service's cookie alert stopped, once it is OK again: {"service"} -> {jobIds, skipped}. --wait follows them. | `pnpm ops recheck-service --json '{"service":"rumble"}'`<br>`pnpm ops recheck-service --json '{"service":"x"}'` |
| `dismiss-service` | — | |
@@ -196,6 +196,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `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. | |
| `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` |
+| `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)} -> {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)} -> {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}'` |
| `archive-search` | archive-search searches archive.org (its advanced-search syntax) and answers the items: {"query", "limit"?: 50 (at most 500)} -> {found, items: \[{identifier, title?}\]}, in identifier order. One request through the editor's archive.org client, paced and backed off as an import is. Read only; import-archive-org with "query" imports what a search finds. {"youtubeId", "limit"?: 10} looks for mirrors of one YouTube upload instead: items OF it (their identifier, a file name or their original URL names the id; a title or description that mentions it is not enough), each read for its files -> {query, found, items: \[{identifier, title?, file, url, source, size?, seconds?, namedBy}\], skipped: \[{identifier, why}\]}: each mirror's direct video file URL, an original preferred. | `pnpm ops archive-search --json '{"query":"title:(kitchen) AND mediatype:movies","limit":20}'`<br>`pnpm ops archive-search --json '{"youtubeId":"dQw4w9WgXcQ"}'` |
@@ -248,6 +249,7 @@ Usage: pnpm ops <action> [--json '<body>' | --file <path>] [--wait]
pnpm ops get x-session [<slug>]
pnpm ops get x-run [<run id>]
pnpm ops get cleanup <slug>
+ pnpm ops get speakers
pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]
pnpm ops get transcript <videoId> [--slug <slug>]
pnpm ops get coverage <slug>
@@ -331,6 +333,14 @@ get x-run [<run id>] is the X run as /review's X run console shows it:
rank, slug), "jar" (its age, social.x.maxCookieAgeMinutes, staleAt:
when it passes the limit, and whether an X job would start now),
gapSeconds (X's queue gap) and maxPosts. Nothing is asked of X.
+get speakers is the speakers readout the lane deck and /cleanup print
+ ("line": waiting: X GB in N videos · freed this run: Y GB · about D
+ days left) and its numbers: waiting (audio held for the Speakers lane
+ that it will clear), neverClears, freed this run, the measured seconds
+ of engine per audio-hour, audio-hours and days left, voiceprinted and
+ noFingerprintPossible (diarized, audio already gone), per channel with
+ corpus-disk channels first; and the lane: armed, held, the operations
+ it dispatches, its order, cleanAfterCapture and requireVoiceprints.
get cleanup <slug> is one channel's /cleanup row: what each sweep would
reclaim (they overlap — never add them), what holds the rest, and the
failed-transcriptions count. measured: false means unknown, not zero.
diff --git a/OPERATING.md b/OPERATING.md
@@ -604,6 +604,57 @@ pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150
the pause alone switched off (never one drained, degraded or disabled by hand); the pause stays on. The video
page's Transcribe row says **Transcribe now (workers paused)**.
+## Work through speakers and free the audio
+
+```sh
+pnpm ops get speakers # waiting · freed this run · days left, per channel
+pnpm ops lane --json '{"lane":"backfill","operations":["diarization"],"order":"space"}'
+pnpm ops settings --json '{"patch":{"attribution":{"textOnlyEnabled":false}}}'
+pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'
+pnpm ops lane --json '{"lane":"backfill","speakers":"work"}' # the deck's Work through speakers
+pnpm ops lane --json '{"lane":"backfill","speakers":"pause"}' # Pause: hold; stays armed
+pnpm ops diarize --json '{"slug":"example"}' --wait # one channel now, lane paused or not
+```
+
+- **What a video needs before its audio may go**: a transcript, its speakers (`diarization.json`) and their
+ voice fingerprints (`voiceprints`: one TitaNet centroid per speaker). The fingerprint is the one part that cannot
+ be made again without the audio, so with `diarization.requireVoiceprints` (on by default) Clean audio skips a
+ diarized video without them — "awaiting voice fingerprint" — and the Speakers lane adds them from the existing
+ turns (seconds of work, no re-clustering).
+- **The lane does speakers only** with `operations: ["diarization"]` on the backfill lane (and the text-only naming
+ pass off): diarization for what has none, fingerprints for what has turns but none. `order: "space"` takes
+ channels whose media is on the corpus disk first, then the videos freeing the most bytes per audio-hour. The
+ channel tiers on /channels still come first.
+- **Work through speakers** (the Speakers lane card, `speakers: "work"`) arms the lane, lifts its hold and starts a
+ run; **Pause** holds it (the video in flight finishes). It refuses a lane not narrowed to `["diarization"]` (it
+ names the command above) and a lane a render holds. With `cleanAfterCapture` on, each captured video's audio is
+ removed at once through every Clean audio gate (keep-latest, do-not-clean), and the bytes are counted in "freed
+ this run" (`transcripts/.speakers-run.json`). Off, Clean audio on each channel (or `cleanup
+ {"sweep":"transcribed"}`) frees them later.
+- **Clean after capture never asks a platform anything.** It reads the channel's availability verdict
+ (`availability-verdict.json`, written by the Quick check): a video a listing younger than
+ `diarization.cleanVerdictMaxAgeHours` (24) names is cleaned; one it does not name is held ("maybe missing" — Check
+ maybe missing resolves it); with no fresh listing the video is held "awaiting an availability check" and ONE
+ Quick check of the channel is queued on its platform's queue (once per max age, never while the platform is
+ held). A video whose cached availability says it is gone is pinned, as the sweep does.
+- **Held by clean after capture, cleaned by hand**: a channel with no `url` ("no source to check: clean by hand";
+ `cleanAfterCaptureUnverified: true` in its config lets it through) and a whole-recording channel
+ (`clips.wholeRecordingPlatforms`, Rumble — its audio is the recording clock's source; `diarization.
+ cleanWholeRecordingAudio` lets it through).
+- **Videos already fingerprinted are not cleaned by the lane**: a unit that finds the work done reports `fresh` and
+ the hook does not fire. They — and the audio already clearable before voiceprints existed — go by hand, per
+ channel: `pnpm ops diarize --json '{"slug":"<slug>"}' --wait` (fingerprints from the existing turns) → spot-check
+ a few `diarization.json` (`voiceprints` with 192-float centroids for the speakers with long turns,
+ `voiceprintsFrom` naming the audio) → Clean audio on the channel (`cleanup {"sweep":"transcribed"}`).
+- **A fingerprint is real or it is not recorded**: every speaker with a turn of 0.5 s or more needs a 192-float
+ centroid from the record's embedding model; the voiceprint step cuts only the video's own audio (never a
+ container or a saved video, whose clock can differ), and refuses a file whose duration is not the record's.
+- **The readout** (`get speakers`, the lane card, /cleanup): waiting = the audio the lane will clear; days left =
+ the audio-hours left times the seconds per audio-hour the sidecars measured, at one video at a time. Diarized
+ videos whose audio is already gone are `noFingerprintPossible` — listed, never an error. Audio the engine cannot
+ 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.
+
## Record a live stream; import a file
```sh
diff --git a/SETTINGS.md b/SETTINGS.md
@@ -407,6 +407,7 @@ Configuration for the automatic priority-queue runners (auto-transcribe / auto-d
| `order` | transcription `"listed"`<br>download `"listed"`<br>digest `"cheapest"`<br>backfill `"listed"` | Ordering within each rule (see AutoQueueOrder). Optional exactly like replaceAutoSubs: settings files written before this field existed lack it, and the sanitizer defaults them to "listed" (today's behaviour). |
| `snoozeUntil` | `null` | Epoch ms until which this runner idles WITHOUT stopping: next() returns null so the loop stays up, re-reads settings each iteration, and resumes by itself when the moment passes. null/absent/past = not snoozed. Survives a restart because it lives in settings.json, not in runner memory. |
| `held` | transcription `false`<br>download `false`<br>digest `false`<br>backfill `true` | THE LANE'S PAUSE GATE. Shut means the lane holds: every dispatch path asks lib/pauseGates.ts, whose limit()/guard returns 0 so runPool idle-waits. A hold, never a stop — see that file's header.<br><br>OPTIONAL IN THE TYPE, FILLED BY THE SANITIZER. Until slice 1.4 four separate settings fields carried this — `transcriptionsPaused`, `downloadsPaused`, `digest.digestsPaused` and (inverted) `backfill.enabled` — so `undefined` meant "ask the legacy field" and `sanitizePolicy` deliberately refused to default it: a default would have read a paused corpus as running. S0-pause deleted those four, on the precondition that the live settings.json already carried every `held` key, and the default came in with them (`defaultHeldFor` — free everywhere except backfill, whose field was inverted and shipped held).<br><br>It stays optional because a reader may be handed a PARTIAL settings object (laneGuards.test.ts casts one), and `isGateHeld` answers `false` for a lane that carries no key at all rather than throwing. |
+| `operations` | absent | Narrow an OPERATION lane to these operation ids (e.g. ["diarization"] on the backfill lane: speakers only, no naming pass). Absent or empty = every enabled operation on the lane's queue, as before.<br><br>On the POLICY rather than a leaf's `match.operation` because a channel-priority document compiles the lane's tree from its tiers and the stored leaves are not used while one exists; a lane-wide narrowing survives that and narrows the per-channel run, the counts and the runner alike (lib/operations.ts operationsForLane). |
| `root` | object — see below | The lane's rule tree: a group whose children are groups and leaves (see the node table). A missing root is the lane's default — empty for the runner lanes, one catch-all leaf for digest and backfill. While a channel-priority document exists, the four roots are compiled from it and not hand-edited. |
#### `autoQueue.<lane>.root (tree nodes)`
@@ -774,6 +775,10 @@ Speaker diarization captured right after transcription, while the audio is still
| `sortformerModel` | `""` | Model for the sortformer engine, produced by scripts/build-sortformer.sh. Empty = that engine cannot run, reported as the same `not-configured` skip as an unset `sortformerBin`. |
| `concurrency` | `1` | How many diarize runs may execute at once in the backfill pass. Kept low by default: diarization is CPU-bound and competes with GPU feeding and the digest sweep for the same 8 threads. |
| `maxAudioHours` | `0` | Videos longer than this are DEFERRED rather than diarized: reported as a third number that is never summed into reachable work, so a capped corpus can never read as finished.<br><br>THIS IS A STOPGAP AND IT IS NOT THE FIX. sherpa-onnx's clustering holds a pairwise distance matrix over speech-segment embeddings — O(n^2) in SEGMENT count — and speaker-turn density varies 40x across this corpus (33-1364 turns/hour), so duration does not actually predict the blowup: a sparse 7h42m video completed while a dense 6h12m one was OOM-killed. Duration is merely the only predictor available for free, from metadata already on disk, BEFORE spending 45 minutes to find out. n^2 at 30k segments is 6.7 GiB and at 40k is 11.9 GiB, which brackets the 10.6 GB and 9.6 GB peaks measured on this 16 GB box.<br><br>0 disables the cap. That is where this goes once windowed diarization lands: windowing divides per-window n by the window count, so the matrix falls by its square, and the cap stops being needed rather than being tuned. |
+| `cleanAfterCapture` | `false` | Delete a video's audio as soon as the Speakers lane has captured it.<br><br>When ON, a diarization unit that finishes with a complete set of voice fingerprints (diarization.json `voiceprints`) is followed at once by the per-video half of Clean audio, with every one of its gates: a transcript.json, outside the keep-latest window, not marked do-not-clean, and the availability check (a video gone upstream is pinned, not deleted). The bytes freed are logged and counted in the speakers readout. OFF by default: nothing deletes audio until the operator says so. |
+| `requireVoiceprints` | `true` | Hold a video's audio until its diarization.json carries voice fingerprints.<br><br>A fingerprint is the one part of a diarization that cannot be made again once the audio is gone, so with this ON (the default) Clean audio skips a diarized video whose sidecar has none, saying "awaiting voice fingerprint", and the Speakers lane adds them from the existing turns. Applies only while diarization is enabled, like the diarization guard itself. |
+| `cleanVerdictMaxAgeHours` | `24` | How old the channel's last listing may be for clean-after-capture to trust it.<br><br>Clean after capture asks NOTHING of the network: it reads the channel's availability verdict (availability-verdict.json, written by the quick availability check) — a video named in a listing younger than this is cleaned, one not named is held (maybe missing). With no fresh listing the video is held and ONE quick check of the channel is queued on its platform's queue, at most once per this many hours, never while the platform is held. The manual Clean audio sweep keeps its own live check. |
+| `cleanWholeRecordingAudio` | `false` | Let clean-after-capture delete the audio of channels on `clips.wholeRecordingPlatforms` (Rumble by default).<br><br>OFF by default, and the reason is the recording clock: on those platforms the cues are the transcription of audio.<ext>, and every clip is cut from another file of the recording through a time map fitted against that audio (common/lib/recordingClock.mjs). Deleting it as each video is captured leaves those recordings with no map to make later. The manual Clean audio sweep is unaffected. |
Default:
@@ -791,7 +796,11 @@ Default:
"sortformerBin": "",
"sortformerModel": "",
"concurrency": 1,
- "maxAudioHours": 0
+ "maxAudioHours": 0,
+ "cleanAfterCapture": false,
+ "requireVoiceprints": true,
+ "cleanVerdictMaxAgeHours": 24,
+ "cleanWholeRecordingAudio": false
}
```
diff --git a/WORKTREES.md b/WORKTREES.md
@@ -437,7 +437,7 @@ While it is on:
released when it exits — done, failed, or umtool signalled (the signal is passed on); the
exit code is the command's. A bare `on` in a script is the chain trap: the window outlives
the script, and a command that never got the token waits at the door behind it.
-- **the editor's transcription and download lanes are held** — only the ones not already
+- **the editor's transcription, download and Speakers lanes are held** — only the ones not already
held, and only those are released at the end (a hold someone else made stays). With no
editor to ask, render mode still holds the door and says the lanes were not held.
- the umtool take panel and the editor's `/jobs` show a banner; **close Firefox and other
diff --git a/common/components/StreamActionLog.tsx b/common/components/StreamActionLog.tsx
@@ -26,6 +26,8 @@ type Props = {
* that need a typed-confirmation gate before allowing the action.
*/
disabled?: boolean;
+ /** What the button does, in one sentence, as its tooltip. */
+ title?: string;
/**
* Called when a run SETTLES — the job's stream has been read to the end (or
* the trigger refused before one existed). `started` is false for a refusal.
@@ -57,6 +59,7 @@ export function StreamActionLog({
cancelAction,
extraControls,
disabled = false,
+ title,
onSettled,
}: Props) {
const accessibleName = label ?? buttonLabel;
@@ -205,6 +208,7 @@ export function StreamActionLog({
size="sm"
onClick={handleClick}
disabled={!hydrated || running || disabled}
+ title={title}
>
{running ? runningLabel : buttonLabel}
</Button>
diff --git a/common/controller/autoRunner.ts b/common/controller/autoRunner.ts
@@ -1,4 +1,7 @@
import path from "node:path";
+import { readdir, stat } from "node:fs/promises";
+import { audioFilesToRemove } from "../lib/mediaFiles";
+import { audioBytesPerHour, spaceComparator } from "../lib/spaceOrder";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import { mapConcurrent } from "../lib/concurrency";
@@ -862,6 +865,11 @@ async function recencyOrdering(
if (order === "cheapest" && kind !== "digest") {
return { compare: null, keys: new Map() };
}
+ // `space` is the Speakers lane's: its candidates all hold audio and have a
+ // transcript, so each can be weighed. Elsewhere it is listed, as above.
+ if (order === "space" && kind !== "backfill") {
+ return { compare: null, keys: new Map() };
+ }
// Candidates AND their owning channel, derived in one pass from the same
// projection buildPendingByLeaf claims from — first-writer-wins, exactly as
// buildChannelWork builds its own owner map, so the two cannot disagree.
@@ -890,6 +898,21 @@ async function recencyOrdering(
// would be pure cost.
interpolate: kind === "download",
});
+ if (order === "space") {
+ // Corpus disk = the channel names no `mediaDir` (and no retired
+ // whole-dir `dataDir`); the rest live on another drive.
+ const external = new Set(
+ meta.filter((m) => !!m.config?.mediaDir || !!m.config?.dataDir).map((m) => m.slug),
+ );
+ const rates = await loadAudioRates(paths, owner, candidateIds);
+ return {
+ compare: spaceComparator({
+ external: (id) => external.has(owner.get(id) ?? ""),
+ bytesPerHour: (id) => rates.get(id) ?? null,
+ }),
+ keys,
+ };
+ }
if (order !== "cheapest") {
return { compare: makeRecencyComparator(keys, order), keys };
}
@@ -944,6 +967,34 @@ async function loadDurations(
const DURATION_READ_CONCURRENCY = 64;
+// Bytes of held audio per audio-hour, per candidate, for the `space` order. The
+// audio is what clean audio would remove (audioFilesToRemove), sized through
+// tier links; the duration is the memoized one `cheapest` uses. Read per tick
+// like the durations, at the same concurrency: a readdir and a stat or two per
+// candidate, and the Speakers lane's candidates are the videos still holding
+// audio (thousands, not the corpus).
+async function loadAudioRates(
+ paths: Paths,
+ owner: ReadonlyMap<string, string>,
+ candidateIds: ReadonlySet<string>,
+): Promise<Map<string, number | null>> {
+ const ids = [...candidateIds];
+ const rates = await mapConcurrent(ids, DURATION_READ_CONCURRENCY, async (id) => {
+ const slug = owner.get(id);
+ if (!slug) return null;
+ const dir = path.join(paths.channelsDir, slug, "data", id);
+ const entries = await readdir(dir).catch(() => [] as string[]);
+ let bytes = 0;
+ for (const name of audioFilesToRemove(entries)) {
+ bytes += await stat(path.join(dir, name)).then((st) => st.size, () => 0);
+ }
+ return audioBytesPerHour(bytes, await videoDurationSeconds(paths, slug, id));
+ });
+ const out = new Map<string, number | null>();
+ ids.forEach((id, i) => out.set(id, rates[i]));
+ return out;
+}
+
// How many drill-down ids the status payload carries per rule. Enough to see
// whether an ordering change did what you asked; small enough that a 9,000-video
// catch-all doesn't ship 9,000 strings on a 3-second poll.
diff --git a/common/controller/availabilityVerdict.ts b/common/controller/availabilityVerdict.ts
@@ -0,0 +1,210 @@
+// A CHANNEL'S AVAILABILITY VERDICT, cached: which videos its source listed the
+// last time the quick availability check asked, and when. Written by that check
+// (controller/quickAvailabilityCheck.ts, one flat-playlist listing on the
+// channel's platform queue); READ by clean-after-capture, which must never ask
+// the network itself (lane/speakers-run review, B1: one full listing per
+// cleaned video, outside every queue, gap and hold).
+//
+// The per-video question (verdictFor) has four answers:
+// listed — the channel's fresh listing names the video: safe to clean;
+// absent — a fresh listing does NOT name it: maybe deleted, maybe unlisted
+// (unlisted videos legitimately drop out of a listing). Held; the
+// manual "check maybe missing" resolves which;
+// stale — the newest listing is older than diarization.cleanVerdictMaxAgeHours;
+// none — the channel has never been listed by the check.
+// Stale and none hold the video "awaiting an availability check", and
+// requestAvailabilityCheck asks for at most one check of that channel per
+// max age, on its platform's own queue.
+
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server";
+import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
+import { heldPlatformRefusal } from "../jobs/downloadBackoff";
+import { raisedServiceAlert } from "../lib/serviceCookies-server";
+import { detectPlatform, platformQueueKey, queueKeyForUrl } from "../lib/platform";
+import { resolveQueueKey } from "../lib/queueKeys";
+import { readChannelConfig } from "./channels";
+import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck";
+
+export const AVAILABILITY_VERDICT_FILENAME = "availability-verdict.json";
+
+export type AvailabilityVerdictRecord = {
+ version: 1;
+ // ISO 8601 of the listing, or null before the first one.
+ checkedAt: string | null;
+ // Canonical ids (data-dir names) the listing named, sorted.
+ ids: string[];
+ // ISO 8601 of the last check REQUESTED by clean-after-capture, so a lane that
+ // holds a hundred videos of one channel asks once, and a restart does not
+ // ask again inside the max age.
+ requestedAt?: string;
+};
+
+export function availabilityVerdictPath(paths: Pick<Paths, "channelsDir">, slug: string): string {
+ return path.join(paths.channelsDir, slug, AVAILABILITY_VERDICT_FILENAME);
+}
+
+function coerce(value: unknown): AvailabilityVerdictRecord | null {
+ const v = value as Partial<AvailabilityVerdictRecord> | null;
+ if (!v || typeof v !== "object" || !Array.isArray(v.ids)) return null;
+ return {
+ version: 1,
+ checkedAt: typeof v.checkedAt === "string" ? v.checkedAt : null,
+ ids: v.ids.filter((x): x is string => typeof x === "string"),
+ ...(typeof v.requestedAt === "string" ? { requestedAt: v.requestedAt } : {}),
+ };
+}
+
+export async function readAvailabilityVerdict(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+): Promise<AvailabilityVerdictRecord | null> {
+ const read = await readJsonFile(availabilityVerdictPath(paths, slug));
+ return read.ok ? coerce(read.value) : null;
+}
+
+async function update(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ fn: (r: AvailabilityVerdictRecord) => AvailabilityVerdictRecord,
+): Promise<void> {
+ const file = availabilityVerdictPath(paths, slug);
+ await withJsonFileLock(file, async () => {
+ const cur = (await readAvailabilityVerdict(paths, slug)) ?? { version: 1, checkedAt: null, ids: [] };
+ await writeJsonAtomic(file, fn(cur));
+ });
+}
+
+// The quick check's half: what the listing named, and when.
+export function writeAvailabilityVerdict(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ listing: { checkedAt: string; ids: Iterable<string> },
+): Promise<void> {
+ return update(paths, slug, (r) => ({
+ ...r,
+ checkedAt: listing.checkedAt,
+ ids: [...new Set(listing.ids)].sort(),
+ }));
+}
+
+export function markAvailabilityCheckRequested(
+ paths: Pick<Paths, "channelsDir">,
+ slug: string,
+ at: string,
+): Promise<void> {
+ return update(paths, slug, (r) => ({ ...r, requestedAt: at }));
+}
+
+export type VideoVerdict = "listed" | "absent" | "stale" | "none";
+
+const HOUR = 3_600_000;
+
+// PURE.
+export function verdictFor(
+ record: AvailabilityVerdictRecord | null,
+ videoId: string,
+ maxAgeHours: number,
+ now: number = Date.now(),
+): VideoVerdict {
+ if (!record?.checkedAt) return "none";
+ const at = Date.parse(record.checkedAt);
+ if (!Number.isFinite(at) || now - at > maxAgeHours * HOUR) return "stale";
+ return record.ids.includes(videoId) ? "listed" : "absent";
+}
+
+// PURE: may clean-after-capture ask for another check of this channel now?
+// Not when one was asked for within the max age (it is queued, running, or
+// failed — and a failure is not a reason to ask again sooner).
+export function mayRequestCheck(
+ record: AvailabilityVerdictRecord | null,
+ maxAgeHours: number,
+ now: number = Date.now(),
+): boolean {
+ const at = record?.requestedAt ? Date.parse(record.requestedAt) : NaN;
+ return !Number.isFinite(at) || now - at > maxAgeHours * HOUR;
+}
+
+// ---------------------------------------------------------------------------
+// Asking for a check — never doing one.
+
+
+// The quick availability check as a job on the channel's PLATFORM queue — the
+// one the channel page's Quick check button runs (kind
+// quick-availability-check, network: so runManagedFunction's network guard
+// applies: never unqueued, and an X job only on a fresh jar with no alert up).
+export async function startQuickAvailabilityCheckJob(opts: {
+ paths: Paths;
+ slug: string;
+ queueKey?: string;
+ onDone?: () => void;
+}): Promise<StreamActionResult> {
+ const config = await readChannelConfig(opts.paths, opts.slug);
+ const defaultQueue = config?.platform
+ ? platformQueueKey(config.platform)
+ : queueKeyForUrl(config?.url);
+ return runManagedFunction({
+ kind: "quick-availability-check",
+ queueKey: resolveQueueKey(defaultQueue, opts.queueKey),
+ paths: opts.paths,
+ channelSlug: opts.slug,
+ fn: async (onLog, signal) => {
+ await runQuickAvailabilityCheck({ channelSlug: opts.slug, paths: opts.paths, onLog, signal });
+ opts.onDone?.();
+ },
+ });
+}
+
+export type CheckRequestDeps = {
+ start?: (paths: Paths, slug: string) => Promise<StreamActionResult>;
+ platformRefusal?: (platform: string) => Promise<string | null>;
+ // The platform's open cookie/service alert (the store `get services`
+ // reads), as its evidence line, or null.
+ serviceAlert?: (platform: string) => Promise<string | null>;
+ now?: () => number;
+};
+
+export type CheckRequest =
+ | { status: "requested"; jobId?: string }
+ | { status: "already-requested"; at: string }
+ | { status: "platform-held"; why: string }
+ | { status: "service-alert"; why: string }
+ | { status: "refused"; why: string }
+ | { status: "no-url" };
+
+// At most one check per channel per max age, and none while its platform is
+// held: a hold is the platform asking us to stop, and a check is a request.
+export async function requestAvailabilityCheck(
+ paths: Paths,
+ slug: string,
+ maxAgeHours: number,
+ deps: CheckRequestDeps = {},
+): Promise<CheckRequest> {
+ const now = deps.now?.() ?? Date.now();
+ const config = await readChannelConfig(paths, slug);
+ if (!config?.url) return { status: "no-url" };
+ const platform = config.platform ?? detectPlatform(config.url) ?? "unknown";
+ const held = await (deps.platformRefusal ?? ((p: string) => heldPlatformRefusal(p, "An availability check", paths)))(platform);
+ if (held) return { status: "platform-held", why: held };
+ // An open cookie alert is the platform answering with a challenge or a
+ // login wall: a listing now would only add to it. Asked nothing until the
+ // operator's Recheck or Dismiss clears it.
+ const alert = await (
+ deps.serviceAlert ??
+ (async (p: string) => {
+ const e = await raisedServiceAlert(paths, p);
+ return e ? (e.evidence?.line ?? "alert raised") : null;
+ })
+ )(platform);
+ if (alert) return { status: "service-alert", why: alert };
+ const record = await readAvailabilityVerdict(paths, slug);
+ if (!mayRequestCheck(record, maxAgeHours, now)) {
+ return { status: "already-requested", at: record!.requestedAt! };
+ }
+ // Marked BEFORE the start, so two units finishing at once cannot both ask.
+ await markAvailabilityCheckRequested(paths, slug, new Date(now).toISOString());
+ const started = await (deps.start ?? ((p: Paths, s: string) => startQuickAvailabilityCheckJob({ paths: p, slug: s })))(paths, slug);
+ if (!started.ok) return { status: "refused", why: started.error ?? "the check could not be queued" };
+ return { status: "requested", jobId: started.jobId };
+}
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -28,6 +28,8 @@ import { isTierable } from "../lib/mediaTier";
import { isDriveNotAnswering, onDrive } from "../lib/storageHealth";
import { CLIPS_DIR_NAME } from "../lib/clipWindow";
import { getSettings } from "../lib/settings";
+import { hasVoiceprints, voiceprintsPossible } from "../lib/diarization";
+import { loadDiarization } from "../lib/diarization-server";
import {
loadAvailability,
resolveEffectiveAvailability,
@@ -483,6 +485,9 @@ export type ChannelSnapshot = {
// fifth gate: the real gate needs a live probe, and folding a guess into the
// hero figure would move the sidebar badge and /cleanup's Est. reclaim too.
reclaimableAtRiskBytes?: number;
+ // The Speakers lane over this channel (the speakers readout's per-channel
+ // row). Optional: snapshots written before it lack it.
+ speakers?: SpeakersWork;
// The audio audit's verdicts over the channel (release 32). Optional: older
// snapshots lack it; readers show nothing until the next regen.
audioIntegrity?: AudioIntegrityTally;
@@ -502,6 +507,35 @@ export type HeldAudio = {
diarizationNeverClears: number;
};
+export type SpeakersWork = {
+ // Audio seconds of the awaiting-diarization videos the lane will clear (the
+ // hold minus diarizationNeverClears), by recorded duration; and how many of
+ // them have no duration on disk.
+ workSeconds: number;
+ workUnmeasured: number;
+ // The engine's measured cost on this channel's sidecars: summed durationMs
+ // over summed audioSeconds, from `measured` sidecars.
+ engineMs: number;
+ engineAudioSeconds: number;
+ measured: number;
+ // Sidecars with complete voice fingerprints; and diarized videos without
+ // them whose audio is already gone — no fingerprint is possible for those.
+ voiceprinted: number;
+ noFingerprintPossible: number;
+};
+
+export function emptySpeakersWork(): SpeakersWork {
+ return {
+ workSeconds: 0,
+ workUnmeasured: 0,
+ engineMs: 0,
+ engineAudioSeconds: 0,
+ measured: 0,
+ voiceprinted: 0,
+ noFingerprintPossible: 0,
+ };
+}
+
export function emptyHeldAudio(): HeldAudio {
return {
noTranscript: 0,
@@ -1225,6 +1259,11 @@ export async function generateChannelSnapshot(
// once per snapshot rather than per video — this and the sweep's own guard key
// off the same setting, and they have to agree or the reclaim estimate lies.
const diarizationEnabled = getSettings().diarization.enabled;
+ // …and, with diarization.requireVoiceprints, until the sidecar carries voice
+ // fingerprints (cleanAudioFromTranscribed's audioCleanGate). Read only for a
+ // video that has BOTH a sidecar and audio — the one population it can hold.
+ const voiceprintGuardOn =
+ diarizationEnabled && getSettings().diarization.requireVoiceprints;
// Videos the user has opted out of the truncated/incomplete-transcript check
// (e.g. legitimately have no speech for the back half). Suppressed from the
@@ -1313,6 +1352,7 @@ export async function generateChannelSnapshot(
let totalClipsBytes = 0;
const heldAudioBytes = emptyHeldAudio();
const heldAudioCounts = emptyHeldAudio();
+ const speakers = emptySpeakersWork();
let reclaimableAtRiskBytes = 0;
// Is the lane that would release an awaiting-diarization video even running?
// allOperations drops a kind whose enabled() is false, so an ABSENT entry
@@ -1362,6 +1402,30 @@ export async function generateChannelSnapshot(
0,
);
totalAudioBytes += audioBytes;
+ // Diarized AS FAR AS THE SWEEP IS CONCERNED: a sidecar without voice
+ // fingerprints is held at the same gate as an absent one — what it waits
+ // for is the Speakers lane either way. Only a video that holds audio pays
+ // the read.
+ const diarRecord = files.hasDiarization
+ ? await loadDiarization(path.join(dataDir, id))
+ : null;
+ const diarVoiceprinted = hasVoiceprints(diarRecord);
+ if (diarRecord) {
+ if (diarVoiceprinted) speakers.voiceprinted++;
+ else if (files.audioFiles.length === 0 || !voiceprintsPossible(diarRecord)) {
+ speakers.noFingerprintPossible++;
+ }
+ // The engine's own clock, for the readout's rate: wall time over the
+ // audio it was given.
+ if ((diarRecord.durationMs ?? 0) > 0 && (diarRecord.audioSeconds ?? 0) > 0) {
+ speakers.engineMs += diarRecord.durationMs!;
+ speakers.engineAudioSeconds += diarRecord.audioSeconds!;
+ speakers.measured++;
+ }
+ }
+ const diarizedForCleanup =
+ files.hasDiarization &&
+ (!voiceprintGuardOn || files.audioFiles.length === 0 || diarVoiceprinted);
if (files.audioFiles.length > 0) {
const gate = attributeAudioHold({
// The sweep's own gate — entries.includes("transcript.json"). NOT
@@ -1377,7 +1441,7 @@ export async function generateChannelSnapshot(
inKeepLatestWindow: keptIds.has(id),
doNotClean: doNotCleanIds.has(id),
diarizationGuardOn: diarizationEnabled,
- hasDiarization: files.hasDiarization,
+ hasDiarization: diarizedForCleanup,
});
if (gate === "reclaimable") {
// What verifyBeforeClean is likely to refuse at sweep time, from the
@@ -1401,6 +1465,12 @@ export async function generateChannelSnapshot(
) {
heldAudioBytes.diarizationNeverClears += audioBytes;
heldAudioCounts.diarizationNeverClears += 1;
+ } else if (gate === "awaitingDiarization") {
+ // Work the Speakers lane WILL do, in audio seconds (the readout's
+ // "days left"). The recorded duration; a video without one counted.
+ const sec = coverage?.cov.duration ?? 0;
+ if (sec > 0) speakers.workSeconds += sec;
+ else speakers.workUnmeasured++;
}
}
}
@@ -1550,7 +1620,7 @@ export async function generateChannelSnapshot(
// Held back by the diarization guard in cleanAudioFromTranscribed. Kept
// out of the bucket AND its byte total so "Est. reclaim" never promises
// space the sweep is going to refuse to take.
- !(diarizationEnabled && !files.hasDiarization)
+ !(diarizationEnabled && !diarizedForCleanup)
) {
transcribedWithAudio.push(id);
for (const name of files.audioFiles) {
@@ -1924,6 +1994,7 @@ export async function generateChannelSnapshot(
totalClipsBytes,
heldAudioBytes,
heldAudioCounts,
+ speakers,
reclaimableAtRiskBytes,
audioIntegrity,
};
diff --git a/common/controller/cleanAfterCapture.test.ts b/common/controller/cleanAfterCapture.test.ts
@@ -0,0 +1,439 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { access, lstat, 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 type { Operation } from "../lib/operations";
+import { cleanAudioForVideo, cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed";
+import { runOperationUnit, type OperationRun } from "./operationBatch";
+import { readSpeakersLedger } from "../lib/speakersLedger-server";
+import { readAvailabilityVerdict, requestAvailabilityCheck, writeAvailabilityVerdict, type CheckRequestDeps } from "./availabilityVerdict";
+
+// Any test that reaches the request path without saying otherwise fails loudly.
+const NO_NETWORK: CheckRequestDeps = {
+ start: async () => {
+ throw new Error("a test asked for a real availability check");
+ },
+ platformRefusal: async () => null,
+ serviceAlert: async () => null,
+};
+import { defaultSiteSettings, getSettings } from "../lib/settings";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test common/controller/cleanAfterCapture.test.ts
+//
+// Temp corpus, temp settings.json. Nothing here probes the network: availability
+// is checked from availability.json (tier A) or switched off per test.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "clean-after-capture-"));
+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: false,
+ 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 } : {}),
+ });
+}
+
+let n = 0;
+async function corpus() {
+ const dir = path.join(ROOT, `c${n++}`);
+ const paths = {
+ channelsDir: path.join(dir, "channels"),
+ transcriptsDir: dir,
+ 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.youtube.com/@ch" }));
+ const video = async (
+ id: string,
+ o: {
+ transcript?: boolean;
+ diarization?: "none" | "plain" | "voiceprints";
+ doNotClean?: boolean;
+ gone?: boolean;
+ bytes?: number;
+ // Named in a fresh availability listing of the channel (the verdict the
+ // automatic clean always reads). Default true; false = never listed.
+ listed?: boolean;
+ } = {},
+ ) => {
+ const v = path.join(paths.channelsDir, "ch", "data", id);
+ await mkdir(v, { recursive: true });
+ 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" }));
+ if (o.listed !== false) {
+ const cur = await readAvailabilityVerdict(paths, "ch");
+ await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: [...(cur?.ids ?? []), id] });
+ }
+ 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);
+
+test("Clean audio holds a diarized video whose sidecar has no voice fingerprints, and says so", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const plain = await video("plain", { diarization: "plain" });
+ const done = await video("done", { diarization: "voiceprints", bytes: 4096 });
+ const logs: string[] = [];
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m) });
+ assert.equal(await exists(path.join(plain, "audio.mp3")), true, "awaiting its fingerprint");
+ assert.equal(await exists(path.join(done, "audio.mp3")), false);
+ assert.equal(r.awaitingVoiceprint, 1);
+ assert.equal(r.bytesFreed, 4096);
+ assert.ok(logs.includes("Skipped plain (awaiting voice fingerprint)"));
+ assert.ok(
+ logs.some((l) => l.endsWith("Skipped 1 (0 protected, 0 gone-from-source pinned, 0 unverified, 1 awaiting voice fingerprint).")),
+ logs.join("\n"),
+ );
+});
+
+test("requireVoiceprints off: the old rule — a diarization.json is enough", async () => {
+ await settings({ requireVoiceprints: false });
+ const { paths, video } = await corpus();
+ const plain = await video("plain", { diarization: "plain" });
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} });
+ assert.equal(await exists(path.join(plain, "audio.mp3")), false);
+ assert.equal(r.awaitingVoiceprint, 0);
+});
+
+test("defaults: requireVoiceprints ON, cleanAfterCapture OFF", () => {
+ assert.equal(defaultSiteSettings().diarization.requireVoiceprints, true);
+ assert.equal(defaultSiteSettings().diarization.cleanAfterCapture, false);
+});
+
+test("cleanAudioForVideo keeps every gate of the channel sweep", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: true });
+ const { paths, video } = await corpus();
+ await video("untranscribed", { transcript: false, diarization: "voiceprints" });
+ await video("pinned", { diarization: "voiceprints", doNotClean: true });
+ await video("nodiar");
+ await video("plain", { diarization: "plain" });
+ const gone = await video("gone", { diarization: "voiceprints", gone: true });
+ const ok = await video("ok", { diarization: "voiceprints", bytes: 2048 });
+ await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: ["ok", "gone"] });
+ const one = (videoId: string) => cleanAudioForVideo({ channelSlug: "ch", paths, videoId, onLog: () => {}, checkDeps: NO_NETWORK });
+ assert.deepEqual(await one("untranscribed"), { outcome: "held", gate: "no-transcript", removedFiles: 0, bytesFreed: 0 });
+ assert.equal((await one("pinned")).gate, "do-not-clean");
+ assert.equal((await one("nodiar")).gate, "awaiting-diarization");
+ assert.equal((await one("plain")).gate, "awaiting-voiceprint");
+ // Gone upstream: pinned do-not-clean, audio kept.
+ assert.equal((await one("gone")).outcome, "pinned");
+ assert.equal(await exists(path.join(gone, "audio.mp3")), true);
+ assert.equal(await exists(path.join(gone, "do-not-clean.json")), true);
+ assert.deepEqual(await one("ok"), { outcome: "cleaned", removedFiles: 1, bytesFreed: 2048 });
+ assert.equal(await exists(path.join(ok, "audio.mp3")), false);
+});
+
+// ---- the hook: a diarization unit that returns done --------------------------
+
+function fakeDiarization(write: "voiceprints" | "plain"): Operation {
+ return {
+ id: "diarization",
+ lane: { queueKey: "backfill", contendsFor: "cpu" },
+ resolveTarget: () => ({}),
+ state: async () => "missing",
+ run: async ({ videoDir }: { videoDir: string }) => {
+ await writeFile(path.join(videoDir, "diarization.json"), sidecar(write === "voiceprints"));
+ return "done";
+ },
+ inputs: () => [],
+ outputs: ["diarization.json"],
+ } as unknown as Operation;
+}
+
+function fakeRun(paths: Paths): OperationRun {
+ return {
+ lane: "backfill",
+ paths,
+ settings: getSettings(),
+ force: false,
+ allowRedownload: false,
+ live: { llmActive: 0, unitActive: 0, costUsd: 0, diskFloorHit: false },
+ backfill: { targets: new Map(), llmFanout: null },
+ log: () => {},
+ } as unknown as OperationRun;
+}
+
+test("clean after capture: on, a captured video's audio goes at once, counted and ledgered", async () => {
+ await settings({ cleanAfterCapture: true });
+ const { paths, video } = await corpus();
+ const v = await video("v1", { bytes: 5000 });
+ const logs: string[] = [];
+ const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("voiceprints") }, { onLog: (m) => logs.push(m) });
+ assert.equal(report.outcome, "done");
+ assert.equal(await exists(path.join(v, "audio.mp3")), false);
+ assert.equal(report.audioCleaned, 1);
+ assert.equal(report.audioFreedBytes, 5000);
+ const ledger = await readSpeakersLedger(paths);
+ // Runtime state, at a dot path beside the corpus root's others.
+ assert.equal(await exists(path.join(paths.transcriptsDir, ".speakers-run.json")), true);
+ assert.equal(ledger.freedBytes, 5000);
+ assert.equal(ledger.freedVideos, 1);
+ assert.ok(logs.some((l) => l.startsWith("Freed 4.9 KB of audio from v1")), logs.join("\n"));
+});
+
+test("clean after capture: never before the fingerprint exists", async () => {
+ await settings({ cleanAfterCapture: true, requireVoiceprints: false });
+ const { paths, video } = await corpus();
+ const v = await video("v1");
+ const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("plain") }, { onLog: () => {} });
+ assert.equal(report.outcome, "done");
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ assert.equal(report.audioCleaned, 0);
+});
+
+test("clean after capture: off by default, and a protected video stays protected", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const a = await video("v1");
+ await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v1", op: fakeDiarization("voiceprints") }, { onLog: () => {} });
+ assert.equal(await exists(path.join(a, "audio.mp3")), true, "off by default");
+
+ await settings({ cleanAfterCapture: true });
+ const b = await video("v2", { doNotClean: true });
+ const report = await runOperationUnit(fakeRun(paths), { channelSlug: "ch", videoId: "v2", op: fakeDiarization("voiceprints") }, { onLog: () => {} });
+ assert.equal(await exists(path.join(b, "audio.mp3")), true, "do-not-clean holds");
+ assert.equal(report.audioCleaned, 0);
+});
+
+test("cleanAudioForVideo: an unmounted media drive keeps the audio link where it is", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints" });
+ // Tier the audio by hand onto a "drive" that is not mounted: a dangling
+ // media link and a relative link into it, as mediaTier writes them.
+ await rm(path.join(v, "audio.mp3"));
+ const channelDir = path.join(paths.channelsDir, "ch");
+ const target = path.join(ROOT, "platter-not-mounted", "ch", "media");
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.youtube.com/@ch", mediaDir: target }));
+ await symlink(target, path.join(channelDir, "media"));
+ await symlink("../../media/v1/audio.mp3", path.join(v, "audio.mp3"));
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {} });
+ assert.deepEqual(out, { outcome: "held", gate: "media-unreachable", removedFiles: 0, bytesFreed: 0 });
+ assert.ok((await lstat(path.join(v, "audio.mp3"))).isSymbolicLink(), "the link is untouched");
+});
+
+test("cleanAudioForVideo removes the audio and nothing else: no source media, clip, transcript, sidecar or saved-video pointer", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints" });
+ const keep = ["source-media.mp4", "transcript.json", "transcript.cues.json", "diarization.json", "saved-video.json"];
+ for (const f of keep.filter((f) => !["transcript.json", "diarization.json"].includes(f))) await writeFile(path.join(v, f), "keep");
+ await mkdir(path.join(v, "clips"));
+ await writeFile(path.join(v, "clips", "10.00-20.00.m4a"), "clip");
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {} });
+ assert.equal(out.outcome, "cleaned");
+ assert.equal(await exists(path.join(v, "audio.mp3")), false);
+ for (const f of keep) assert.equal(await exists(path.join(v, f)), true, f);
+ assert.equal(await readFile(path.join(v, "clips", "10.00-20.00.m4a"), "utf8"), "clip");
+});
+
+// ---- B1: the availability verdict cache, never a listing per video ------------
+
+test("no fresh listing: N captured videos of one channel are held, and at most ONE check is asked for", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: true });
+ const { paths, video } = await corpus();
+ const ids = ["a1", "a2", "a3", "a4", "a5"];
+ for (const id of ids) await video(id, { diarization: "voiceprints", listed: false });
+ const started: string[] = [];
+ const deps: CheckRequestDeps = {
+ start: async (_p, slug) => {
+ started.push(slug);
+ return { ok: true, jobId: "job-1" } as never;
+ },
+ platformRefusal: async () => null,
+ };
+ for (const id of ids) {
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: id, onLog: () => {}, checkDeps: deps });
+ assert.equal(out.gate, "awaiting-availability", id);
+ }
+ assert.deepEqual(started, ["ch"], "one check, on the channel, for five videos");
+ for (const id of ids) assert.equal(await exists(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")), true);
+ assert.equal(typeof (await readAvailabilityVerdict(paths, "ch"))?.requestedAt, "string");
+
+ // An OLD listing is no listing: still held, and the request is not repeated
+ // inside the max age.
+ await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date(Date.now() - 48 * 3_600_000).toISOString(), ids });
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: deps })).gate, "awaiting-availability");
+ assert.equal(started.length, 1);
+
+ // The check lands (a fresh listing naming them): cleaned, nothing asked.
+ await writeAvailabilityVerdict(paths, "ch", { checkedAt: new Date().toISOString(), ids: ["a1", "a2"] });
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: deps })).outcome, "cleaned");
+ // A fresh listing that does NOT name a video holds it: maybe missing.
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a3", onLog: () => {}, checkDeps: deps })).gate, "maybe-missing");
+ assert.equal(started.length, 1);
+});
+
+test("a held platform: the video is held, nothing deleted, nothing requested", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: true });
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints", listed: false });
+ let started = 0;
+ const logs: string[] = [];
+ const out = await cleanAudioForVideo({
+ channelSlug: "ch",
+ paths,
+ videoId: "v1",
+ onLog: (m) => logs.push(m),
+ checkDeps: {
+ start: async () => {
+ started++;
+ return { ok: true, jobId: "x" } as never;
+ },
+ platformRefusal: async (platform) => `${platform} is held after a 429`,
+ },
+ });
+ assert.equal(out.gate, "awaiting-availability");
+ assert.equal(started, 0);
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ assert.equal((await readAvailabilityVerdict(paths, "ch"))?.requestedAt, undefined, "not even marked as asked");
+ assert.ok(logs.some((l) => l.includes("youtube is held after a 429")), logs.join("\n"));
+});
+
+// ---- B2: a channel with no source URL ---------------------------------------
+
+test("no source URL: the automatic clean holds; the channel's opt-in lets it through; the manual sweep is unchanged", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: true });
+ const { paths, video } = await corpus();
+ const cfg = path.join(paths.channelsDir, "ch", "config.json");
+ await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch" }));
+ const a = await video("a1", { diarization: "voiceprints" });
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: NO_NETWORK });
+ assert.deepEqual(out, { outcome: "held", gate: "no-source-url", removedFiles: 0, bytesFreed: 0 });
+ assert.equal(await exists(path.join(a, "audio.mp3")), true);
+
+ await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch", cleanAfterCaptureUnverified: true }));
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "a1", onLog: () => {}, checkDeps: NO_NETWORK })).outcome, "cleaned");
+
+ // The manual sweep: as today — a channel with no URL cannot be verified and
+ // is cleaned (verifyBeforeClean fails open), opt-in or not.
+ await writeFile(cfg, JSON.stringify({ handling: "transcribe", name: "ch" }));
+ const b = await video("b1", { diarization: "voiceprints" });
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} });
+ assert.equal(r.cleanedDirs, 1);
+ assert.equal(await exists(path.join(b, "audio.mp3")), false);
+});
+
+// ---- whole-recording platforms ------------------------------------------------
+
+test("a whole-recording channel (Rumble): clean after capture holds its audio — the recording clock's source — unless cleanWholeRecordingAudio", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: false });
+ const { paths, video } = await corpus();
+ await writeFile(
+ path.join(paths.channelsDir, "ch", "config.json"),
+ JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/ch" }),
+ );
+ const v = await video("v1", { diarization: "voiceprints" });
+ const held = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: NO_NETWORK });
+ assert.deepEqual(held, { outcome: "held", gate: "whole-recording", removedFiles: 0, bytesFreed: 0 });
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ assert.equal(defaultSiteSettings().diarization.cleanWholeRecordingAudio, false);
+
+ await settings({ cleanWholeRecordingAudio: true }, { verifyAvailabilityBeforeClean: false });
+ assert.equal((await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: NO_NETWORK })).outcome, "cleaned");
+});
+
+test("the automatic clean requires the verdict even with verifyAvailabilityBeforeClean off (that setting is the manual sweep's)", async () => {
+ await settings({}, { verifyAvailabilityBeforeClean: false });
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints", listed: false });
+ let started = 0;
+ const deps: CheckRequestDeps = {
+ start: async () => {
+ started++;
+ return { ok: true, jobId: "x" } as never;
+ },
+ platformRefusal: async () => null,
+ };
+ const out = await cleanAudioForVideo({ channelSlug: "ch", paths, videoId: "v1", onLog: () => {}, checkDeps: deps });
+ assert.equal(out.gate, "awaiting-availability");
+ assert.equal(started, 1);
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ // …while the manual sweep, with the setting off, cleans without asking.
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {} });
+ assert.equal(r.cleanedDirs, 1);
+});
+
+test("an open service alert for the platform: held \"awaiting an availability check (service alert open)\", nothing requested", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const v = await video("v1", { diarization: "voiceprints", listed: false });
+ let started = 0;
+ const logs: string[] = [];
+ const out = await cleanAudioForVideo({
+ channelSlug: "ch",
+ paths,
+ videoId: "v1",
+ onLog: (m) => logs.push(m),
+ checkDeps: {
+ start: async () => {
+ started++;
+ return { ok: true, jobId: "x" } as never;
+ },
+ platformRefusal: async () => null,
+ serviceAlert: async (platform) => (platform === "youtube" ? "Sign in to confirm you're not a bot" : null),
+ },
+ });
+ assert.equal(out.gate, "awaiting-availability");
+ assert.equal(started, 0);
+ assert.equal((await readAvailabilityVerdict(paths, "ch"))?.requestedAt, undefined);
+ assert.equal(await exists(path.join(v, "audio.mp3")), true);
+ assert.ok(logs.some((l) => l.includes("awaiting an availability check (service alert open: Sign in to confirm")), logs.join("\n"));
+});
+
+test("the real alert store: a raised yt-dlp service alert for the channel's platform is read", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ await video("v1", { diarization: "voiceprints", listed: false });
+ await writeFile(
+ path.join(paths.transcriptsDir, ".service-cookies.json"),
+ JSON.stringify({ version: 1, services: { youtube: { since: new Date().toISOString(), raisedAt: new Date().toISOString(), kind: "challenge", evidence: { line: "bot check", at: new Date().toISOString() }, signals: 3 } } }),
+ );
+ const asked = await requestAvailabilityCheck(paths, "ch", 24, {
+ start: async () => {
+ throw new Error("must not start");
+ },
+ platformRefusal: async () => null,
+ });
+ assert.equal(asked.status, "service-alert");
+});
+
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+test("concurrency stays 1: one diarization at a time, one backfill unit at a time", () => {
+ // Load-bearing (plans/FACTS.md): two sherpa runs at once doubled the 11 GB
+ // transients that OOM-killed the box; the Speakers lane runs beside GPU
+ // transcription on four of eight threads.
+ assert.equal(defaultSiteSettings().diarization.concurrency, 1);
+ assert.equal(defaultSiteSettings().backfill.concurrency, 1);
+});
diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts
@@ -1,17 +1,30 @@
import { removeMediaFile } from "../lib/mediaTier-server";
+import { isPermanentlyGone } from "../lib/availability";
+import { detectPlatform } from "../lib/platform";
+import { DEFAULT_CLIPS_SETTINGS } from "../lib/clipSettings";
+import { resolveEffectiveAvailability } from "../lib/availability-server";
+import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server";
+import {
+ readAvailabilityVerdict,
+ requestAvailabilityCheck,
+ verdictFor,
+ type CheckRequestDeps,
+} from "./availabilityVerdict";
+import { assertChannelMediaReachable } from "../lib/channelMedia";
import path from "node:path";
import fs from "fs-extra";
import type { Paths } from "../lib/paths";
import { isDoNotClean } from "../lib/doNotClean-server";
-import { hasDiarization } from "../lib/diarization-server";
-import { getSettings } from "../lib/settings";
+import { loadDiarization } from "../lib/diarization-server";
+import { hasVoiceprints } from "../lib/diarization";
+import { getSettings, type DiarizationSettings } from "../lib/settings";
import { audioFilesToRemove } from "../lib/videoStatus";
import { readChannelConfig } from "./channels";
import { computeKeptVideoIds } from "./keptVideos";
import { pruneSavedVideos } from "./pruneSavedVideos";
import { excludedIds, verifyBeforeClean } from "./verifyBeforeClean";
-const { pathExists, readdir } = fs;
+const { pathExists, readdir, stat } = fs;
export type CleanAudioOptions = {
channelSlug: string;
@@ -42,6 +55,12 @@ export type CleanAudioResult = {
// catches up, and a number that only ever grows is the signal that the CPU
// lane has fallen behind the GPU.
awaitingDiarization: number;
+ // Left alone because the video IS diarized but its diarization.json has no
+ // voice fingerprints yet (diarization.requireVoiceprints). Transient like
+ // awaitingDiarization: the Speakers lane adds them while the audio is here.
+ awaitingVoiceprint: number;
+ // 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).
prunedSavedVideos: number;
@@ -54,6 +73,98 @@ type CleanCandidate = {
audioFiles: string[];
};
+// Where ONE video's audio leaves the sweep, or "candidate" when it passes every
+// gate that needs no network. The ONE rule both the channel sweep and the
+// per-video clean (cleanAudioForVideo) apply, in the same order, so the two can
+// never disagree about what is safe to delete. Availability (verifyBeforeClean)
+// is the last gate and is asked by the caller, for every candidate at once.
+export type AudioCleanGate =
+ | "candidate"
+ | "no-transcript"
+ | "no-audio"
+ | "keep-latest"
+ | "do-not-clean"
+ | "awaiting-diarization"
+ | "awaiting-voiceprint"
+ // cleanAudioForVideo only: the channel's media drive is not answering. The
+ // channel sweep is covered by its job kind's needsMedia guard instead.
+ | "media-unreachable"
+ // cleanAudioForVideo only, from the channel's availability verdict cache
+ // (controller/availabilityVerdict.ts): no listing within
+ // diarization.cleanVerdictMaxAgeHours (a check is requested), or a fresh
+ // listing that does not name the video (maybe deleted, maybe unlisted).
+ | "awaiting-availability"
+ | "maybe-missing"
+ // cleanAudioForVideo only (review B2): the channel has no source URL, so no
+ // check can vouch for anything — held unless its config sets
+ // cleanAfterCaptureUnverified. The manual sweep cleans these as before.
+ | "no-source-url"
+ // cleanAudioForVideo only: a channel on clips.wholeRecordingPlatforms
+ // (Rumble by default), whose audio.<ext> is the cue-clock source of the
+ // recording's time map (lib/recordingClock.mjs) — held unless
+ // diarization.cleanWholeRecordingAudio.
+ | "whole-recording";
+
+export async function audioCleanGate(
+ videoDir: string,
+ id: string,
+ ctx: { keptIds: Set<string>; diarization: DiarizationSettings },
+): Promise<{ gate: AudioCleanGate; audioFiles: string[] }> {
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (!entries.includes("transcript.json")) return { gate: "no-transcript", audioFiles: [] };
+ const audioFiles = audioFilesToRemove(entries);
+ if (audioFiles.length === 0) return { gate: "no-audio", audioFiles };
+ if (ctx.keptIds.has(id)) return { gate: "keep-latest", audioFiles };
+ if (await isDoNotClean(videoDir)) return { gate: "do-not-clean", audioFiles };
+ // While diarization is enabled, a transcribed video that still has audio but
+ // no diarization.json is NOT cleanable yet — its diarize job hasn't run.
+ //
+ // This guard is the whole reason deferring diarization to an async job is
+ // safe. Without it the sweep would delete the audio out from under a queued
+ // diarize job, silently and permanently: audio is the one input in this
+ // pipeline that cannot be regenerated, and the failure would leave no trace.
+ //
+ // A malformed sidecar reads as absent (loadDiarization), as it always has.
+ if (ctx.diarization.enabled) {
+ const record = entries.includes("diarization.json")
+ ? await loadDiarization(videoDir)
+ : null;
+ if (!record) return { gate: "awaiting-diarization", audioFiles };
+ // The voice fingerprint is the part of a diarization that cannot be made
+ // again without the audio, so it is waited for too.
+ if (ctx.diarization.requireVoiceprints && !hasVoiceprints(record)) {
+ return { gate: "awaiting-voiceprint", audioFiles };
+ }
+ }
+ return { gate: "candidate", audioFiles };
+}
+
+const SKIP_LOG: Partial<Record<AudioCleanGate, string>> = {
+ "keep-latest": "in keep-latest window",
+ "do-not-clean": "marked do not clean",
+ "awaiting-diarization": "awaiting diarization",
+ "awaiting-voiceprint": "awaiting voice fingerprint",
+};
+
+// Remove a candidate's audio files, through removeMediaFile (a tier link takes
+// its bytes on the media tier with it). Returns the bytes freed.
+async function removeCandidateAudio(
+ c: CleanCandidate,
+ log: (m: string) => void,
+): Promise<{ removed: number; bytes: number }> {
+ let removed = 0;
+ let bytes = 0;
+ for (const f of c.audioFiles) {
+ // stat follows a tier link to the bytes it frees.
+ const size = await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0);
+ await removeMediaFile(c.videoDir, f);
+ log(`Removed ${c.id}/${f}`);
+ removed++;
+ bytes += size;
+ }
+ return { removed, bytes };
+}
+
export async function cleanAudioFromTranscribed({
channelSlug,
paths,
@@ -73,6 +184,8 @@ export async function cleanAudioFromTranscribed({
pinned: 0,
unverified: 0,
awaitingDiarization: 0,
+ awaitingVoiceprint: 0,
+ bytesFreed: 0,
prunedSavedVideos: 0,
prunedBytes: 0,
};
@@ -90,16 +203,11 @@ export async function cleanAudioFromTranscribed({
let cleanedDirs = 0;
let removedFiles = 0;
+ let bytesFreed = 0;
let protectedCount = 0;
let awaitingDiarization = 0;
+ let awaitingVoiceprint = 0;
- // While diarization is enabled, a transcribed video that still has audio but
- // no diarization.json is NOT cleanable yet — its diarize job hasn't run.
- //
- // This guard is the whole reason deferring diarization to an async job is
- // safe. Without it the sweep would delete the audio out from under a queued
- // diarize job, silently and permanently: audio is the one input in this
- // pipeline that cannot be regenerated, and the failure would leave no trace.
const diarization = getSettings().diarization;
// --- Discover -------------------------------------------------------------
@@ -109,26 +217,13 @@ export async function cleanAudioFromTranscribed({
for (const id of dirs) {
if (signal?.aborted) break;
const videoDir = path.join(dataDir, id);
- const entries = await readdir(videoDir).catch(() => [] as string[]);
- if (!entries.includes("transcript.json")) continue;
- const audioFiles = audioFilesToRemove(entries);
- if (audioFiles.length === 0) continue;
- if (keptIds.has(id)) {
- log(`Skipped ${id} (in keep-latest window)`);
- protectedCount++;
- continue;
- }
- if (await isDoNotClean(videoDir)) {
- log(`Skipped ${id} (marked do not clean)`);
- protectedCount++;
- continue;
- }
- if (diarization.enabled && !(await hasDiarization(videoDir))) {
- log(`Skipped ${id} (awaiting diarization)`);
- awaitingDiarization++;
- continue;
- }
- candidates.push({ id, videoDir, audioFiles });
+ 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 });
}
// --- Verify ---------------------------------------------------------------
@@ -155,28 +250,28 @@ export async function cleanAudioFromTranscribed({
for (const candidate of candidates) {
if (signal?.aborted) break;
if (excluded.has(candidate.id)) continue;
- for (const f of candidate.audioFiles) {
- // Through its link when tiered (release 17): the bytes on the media tier go too.
- await removeMediaFile(candidate.videoDir, f);
- log(`Removed ${candidate.id}/${f}`);
- removedFiles++;
- }
+ const out = await removeCandidateAudio(candidate, log);
+ removedFiles += out.removed;
+ bytesFreed += out.bytes;
cleanedDirs++;
}
- const skipped = protectedCount + pinned + unverified + awaitingDiarization;
+ const skipped =
+ protectedCount + pinned + unverified + awaitingDiarization + awaitingVoiceprint;
// Keep the historical wording when the gate had nothing to report, and break
// the total down only when it would otherwise be misleading.
// The diarization clause is appended only when it is non-zero, so the message
// stays byte-identical for every install that doesn't use the capture lane —
// a "0 awaiting diarization" on a box with diarization off is noise, and this
// exact string is asserted in pre-clean-availability.spec.
+ // The voice-fingerprint clause follows the same rule.
const diarNote =
- awaitingDiarization > 0 ? `, ${awaitingDiarization} awaiting diarization` : "";
+ (awaitingDiarization > 0 ? `, ${awaitingDiarization} awaiting diarization` : "") +
+ (awaitingVoiceprint > 0 ? `, ${awaitingVoiceprint} awaiting voice fingerprint` : "");
const skippedNote =
skipped === 0
? ""
- : pinned === 0 && unverified === 0 && awaitingDiarization === 0
+ : pinned === 0 && unverified === 0 && awaitingDiarization === 0 && awaitingVoiceprint === 0
? ` Skipped ${skipped} (do not clean).`
: ` Skipped ${skipped} (${protectedCount} protected, ${pinned} gone-from-source pinned, ${unverified} unverified${diarNote}).`;
log(
@@ -195,7 +290,143 @@ export async function cleanAudioFromTranscribed({
pinned,
unverified,
awaitingDiarization,
+ awaitingVoiceprint,
+ bytesFreed,
prunedSavedVideos: prune.pruned,
prunedBytes: prune.bytesFreed,
};
}
+
+export type CleanOneOptions = {
+ channelSlug: string;
+ paths: Paths;
+ videoId: string;
+ onLog?: (msg: string) => void;
+ signal?: AbortSignal;
+ // Test seam: how a check is asked for (never run) — see availabilityVerdict.ts.
+ checkDeps?: CheckRequestDeps;
+};
+
+export type CleanOneResult = {
+ // cleaned: the audio is gone. held: a gate kept it (`gate` says which).
+ // pinned: its cached availability says it is gone upstream — now
+ // do-not-clean, kept.
+ outcome: "cleaned" | "held" | "pinned";
+ gate?: AudioCleanGate;
+ removedFiles: number;
+ bytesFreed: number;
+};
+
+// THE PER-VIDEO HALF of cleanAudioFromTranscribed, for clean-after-capture: the
+// same gates in the same order (audioCleanGate) and the same removeMediaFile.
+//
+// ITS AVAILABILITY CHECK ASKS NOTHING OF THE NETWORK (review B1). The channel
+// sweep's verifyBeforeClean lists the whole channel per call; called once per
+// captured video that is a full listing per video, outside every platform
+// queue, gap and hold. Here: a video whose cached per-video availability says
+// it is gone is pinned (verifyBeforeClean's tier A, no spawn); otherwise the
+// channel's verdict cache decides — listed in a fresh listing → clean; not named
+// → held (maybe missing); no fresh listing → held, and ONE quick check of the
+// channel is requested on its platform's queue, at most once per max age.
+// No saved-video prune: that is the channel sweep's retention pass.
+export async function cleanAudioForVideo({
+ channelSlug,
+ paths,
+ videoId,
+ onLog,
+ signal,
+ checkDeps,
+}: CleanOneOptions): Promise<CleanOneResult> {
+ const log = onLog ?? ((m: string) => console.log(m));
+ const held = (gate: AudioCleanGate): CleanOneResult => ({
+ outcome: "held",
+ gate,
+ removedFiles: 0,
+ bytesFreed: 0,
+ });
+ const videoDir = path.join(paths.channelsDir, channelSlug, "data", videoId);
+ const config = await readChannelConfig(paths, channelSlug);
+ const keptIds = await computeKeptVideoIds({
+ paths,
+ channelSlug,
+ keepLatest: config?.keepLatest ?? 0,
+ });
+ const diarization = getSettings().diarization;
+ const { gate, audioFiles } = await audioCleanGate(videoDir, videoId, { keptIds, diarization });
+ if (gate !== "candidate") {
+ if (SKIP_LOG[gate]) log(`Kept ${videoId}'s audio (${SKIP_LOG[gate]})`);
+ return held(gate);
+ }
+ if (signal?.aborted) return held(gate);
+ // THE CUE CLOCK (review). On a whole-recording platform the cues are the
+ // transcription of audio.<ext>, and every clip is cut from another file of
+ // the recording through a time map fitted against THAT audio
+ // (common/lib/recordingClock.mjs). Deleting it systematically leaves those
+ // recordings with no map to make later. Held by default; the operator rules.
+ const platform = config?.platform ?? detectPlatform(config?.url ?? "") ?? "";
+ const whole = getSettings().clips?.wholeRecordingPlatforms ?? DEFAULT_CLIPS_SETTINGS.wholeRecordingPlatforms;
+ if (whole.includes(platform) && !diarization.cleanWholeRecordingAudio) {
+ log(`Kept ${videoId}'s audio: ${platform} records whole — its audio is the recording clock's source (diarization.cleanWholeRecordingAudio).`);
+ return held("whole-recording");
+ }
+ // NO SOURCE, NO CHECK (review B2). verifyBeforeClean fails OPEN for a channel
+ // with no URL — right for a sweep the operator pressed, wrong for an
+ // automatic delete: an imported or hand-built channel's audio may be its only
+ // copy anywhere. Held unless the channel opts in.
+ const unverifiedOptIn = !config?.url && config?.cleanAfterCaptureUnverified === true;
+ if (!config?.url && !unverifiedOptIn) {
+ log(`Kept ${videoId}'s audio: no source to check — clean by hand (or set cleanAfterCaptureUnverified on the channel).`);
+ return held("no-source-url");
+ }
+ // AN UNMOUNTED DRIVE IS NOT AN EMPTY ONE. The audio here may be a tier link
+ // into a media/ that points at another disk; removing the link while that
+ // disk is away strands its bytes there. Asked fresh, per video: this runs
+ // from a unit hook, not from a job whose kind declares needsMedia.
+ try {
+ await assertChannelMediaReachable(paths, channelSlug);
+ } catch (err) {
+ log(`Kept ${videoId}'s audio: ${(err as Error).message}`);
+ return held("media-unreachable");
+ }
+ // 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) {
+ const cached = await resolveEffectiveAvailability(videoDir);
+ if (isPermanentlyGone(cached)) {
+ if (!(await loadDoNotClean(videoDir))) {
+ await setDoNotClean(videoDir, true, `deleted from source (pre-clean check): ${cached}`);
+ log(`Pinned ${videoId} as do-not-clean (${cached}) — gone from source.`);
+ }
+ return { outcome: "pinned", removedFiles: 0, bytesFreed: 0 };
+ }
+ const maxAge = diarization.cleanVerdictMaxAgeHours;
+ const verdict = verdictFor(await readAvailabilityVerdict(paths, channelSlug), videoId, maxAge);
+ if (verdict === "absent") {
+ log(`Kept ${videoId}'s audio: the channel's last listing does not name it (maybe missing — Check maybe missing resolves it).`);
+ return held("maybe-missing");
+ }
+ if (verdict !== "listed") {
+ const asked = await requestAvailabilityCheck(paths, channelSlug, maxAge, checkDeps);
+ if (asked.status === "service-alert") {
+ log(`Kept ${videoId}'s audio: awaiting an availability check (service alert open: ${asked.why}).`);
+ return held("awaiting-availability");
+ }
+ const why =
+ asked.status === "requested"
+ ? "a quick availability check of the channel is queued"
+ : asked.status === "already-requested"
+ ? `a check was requested at ${asked.at}`
+ : asked.status === "platform-held"
+ ? `its platform is held, so no check is asked: ${asked.why}`
+ : asked.status === "refused"
+ ? `the check was refused: ${asked.why}`
+ : "the channel has no source URL to list";
+ log(`Kept ${videoId}'s audio: awaiting an availability check (${verdict === "none" ? "never listed" : `no listing in ${maxAge} h`}; ${why}).`);
+ return held("awaiting-availability");
+ }
+ }
+ if (signal?.aborted) return held(gate);
+ const out = await removeCandidateAudio({ id: videoId, videoDir, audioFiles }, log);
+ return { outcome: "cleaned", removedFiles: out.removed, bytesFreed: out.bytes };
+}
diff --git a/common/controller/diarizeOne.test.ts b/common/controller/diarizeOne.test.ts
@@ -0,0 +1,186 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import path from "node:path";
+import os from "node:os";
+import { chmod, mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { diarizeOneVideo, voiceprintOneVideo } from "./diarizeOne";
+import { defaultSiteSettings } from "../lib/settings";
+import type { Paths } from "../lib/paths";
+import { hasVoiceprints, type DiarizationRecord } from "../lib/diarization";
+import { loadDiarization } from "../lib/diarization-server";
+import { loadAudioIntegrity } from "../lib/audioIntegrity-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test common/controller/diarizeOne.test.ts
+//
+// The engine is a fake DIARIZE_BIN: it logs its argv, and in --voiceprints-only
+// mode adds a voiceprint per speaker to the record it is given -- or exits 4
+// (diarize-sherpa.py's "ffmpeg failed") when FAKE_EXIT says so.
+
+const hasFfmpeg = spawnSync("ffmpeg", ["-version"], { stdio: "ignore" }).status === 0;
+
+const FAKE = `#!/usr/bin/env node
+const fs = require("node:fs");
+const argv = process.argv.slice(2);
+fs.appendFileSync(process.env.FAKE_LOG, JSON.stringify(argv) + "\\n");
+if (process.env.FAKE_STDERR) process.stderr.write(process.env.FAKE_STDERR + "\\n");
+if (process.env.FAKE_EXIT) process.exit(Number(process.env.FAKE_EXIT));
+const at = (f) => argv[argv.indexOf(f) + 1];
+const rec = JSON.parse(fs.readFileSync(at("--voiceprints-only"), "utf8"));
+const speakers = [...new Set(rec.turns.map((t) => t.speaker))];
+rec.voiceprints = speakers.map((s) => ({ speaker: s, seconds: 1, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }));
+rec.voiceprintsAt = "2026-11-11T00:00:00.000Z";
+fs.writeFileSync(at("--output"), JSON.stringify(rec) + "\\n");
+`;
+
+const EXISTING: DiarizationRecord = {
+ videoId: "vid1",
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ speakers: 2,
+ turns: [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4, end: 9, speaker: 1 },
+ ],
+ engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 },
+};
+
+async function setup(opts: { audio?: string | null } = {}) {
+ const root = await mkdtemp(path.join(os.tmpdir(), "diarize-one-"));
+ const bin = path.join(root, "fake-diarize.cjs");
+ await writeFile(bin, FAKE);
+ await chmod(bin, 0o755);
+ const log = path.join(root, "calls.log");
+ await writeFile(log, "");
+ const videoDir = path.join(root, "vid1");
+ await mkdir(videoDir);
+ await writeFile(path.join(videoDir, "diarization.json"), JSON.stringify(EXISTING) + "\n");
+ if (opts.audio !== null) await writeFile(path.join(videoDir, "audio.mp3"), opts.audio ?? "not really mp3");
+ const paths = { diarizeBin: bin, ffmpegBin: "ffmpeg", ffprobeBin: "ffprobe" } as unknown as Paths;
+ const settings = {
+ ...defaultSiteSettings().diarization,
+ enabled: true,
+ segModel: "/m/seg.onnx",
+ embModel: "/m/emb.onnx",
+ threshold: 0.9,
+ };
+ process.env.FAKE_LOG = log;
+ const calls = async () =>
+ (await readFile(log, "utf8")).split("\n").filter(Boolean).map((l) => JSON.parse(l) as string[]);
+ return { root, videoDir, paths, settings, calls, cleanup: () => rm(root, { recursive: true, force: true }) };
+}
+
+test("a fresh sidecar without voiceprints gets them from its own turns — no re-diarization, generatedAt kept", async () => {
+ const t = await setup();
+ try {
+ const out = await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} });
+ assert.equal(out, "diarized");
+ const calls = await t.calls();
+ assert.equal(calls.length, 1);
+ assert.ok(calls[0].includes("--voiceprints-only"), "the voiceprint step, not a diarization");
+ assert.ok(!calls[0].includes("--seg"));
+ const rec = await loadDiarization(t.videoDir);
+ assert.equal(hasVoiceprints(rec), true);
+ assert.equal(rec?.generatedAt, EXISTING.generatedAt);
+ assert.deepEqual(rec?.turns, EXISTING.turns);
+ // A second pass has nothing to do.
+ assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists");
+ assert.equal((await t.calls()).length, 1);
+ } finally {
+ await t.cleanup();
+ }
+});
+
+test("with the audio gone: no fingerprint is possible, and that is not a failure", async () => {
+ const t = await setup({ audio: null });
+ try {
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "no-audio");
+ assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists");
+ assert.equal((await t.calls()).length, 0);
+ assert.equal(hasVoiceprints(await loadDiarization(t.videoDir)), false);
+ } finally {
+ await t.cleanup();
+ }
+});
+
+test("a zero-byte audio is recorded as undecodable and skipped without running the engine", async () => {
+ const t = await setup({ audio: "" });
+ try {
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "unreadable");
+ assert.equal((await t.calls()).length, 0);
+ const rec = await loadAudioIntegrity(t.videoDir);
+ assert.equal(rec?.verdict, "undecodable");
+ assert.equal(rec?.by, "speakers");
+ assert.equal(rec?.size, 0);
+ } finally {
+ await t.cleanup();
+ }
+});
+
+test("an engine that cannot decode the audio (exit 4): recorded as undecodable, the sidecar untouched", { skip: !hasFfmpeg && "needs ffmpeg" }, async () => {
+ const t = await setup({ audio: "garbage, not audio" });
+ process.env.FAKE_EXIT = "4";
+ try {
+ const before = await readFile(path.join(t.videoDir, "diarization.json"), "utf8");
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "unreadable");
+ assert.equal(await readFile(path.join(t.videoDir, "diarization.json"), "utf8"), before);
+ assert.equal((await loadAudioIntegrity(t.videoDir))?.verdict, "undecodable");
+ } finally {
+ delete process.env.FAKE_EXIT;
+ await t.cleanup();
+ }
+});
+
+test("an engine failure for any other reason is a plain failure, and no verdict is written", async () => {
+ const t = await setup();
+ process.env.FAKE_EXIT = "1";
+ try {
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "failed");
+ // diarizeOne keeps the diarization: the sidecar is fine, only without voiceprints.
+ assert.equal(await diarizeOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "already-exists");
+ assert.equal(await loadAudioIntegrity(t.videoDir), null);
+ } finally {
+ delete process.env.FAKE_EXIT;
+ await t.cleanup();
+ }
+});
+
+test("the voiceprint step never falls back to a source container: with no audio, no fingerprint is possible", async () => {
+ const t = await setup({ audio: null });
+ try {
+ await writeFile(path.join(t.videoDir, "source-media.mp4"), "a container of the same recording");
+ assert.equal(await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: () => {} }), "no-audio");
+ assert.equal((await t.calls()).length, 0, "the engine is never given the container");
+ assert.equal(hasVoiceprints(await loadDiarization(t.videoDir)), false);
+ } finally {
+ await t.cleanup();
+ }
+});
+
+test("an exit-6 refusal is recorded against the file (voiceprintsRefused), turns and generatedAt kept, no voiceprints", async () => {
+ const t = await setup();
+ process.env.FAKE_EXIT = "6";
+ process.env.FAKE_STDERR = "diarize-sherpa: refused: the file is 99.000s, the record's audio 10s — not the audio these turns were made from";
+ try {
+ const logs: string[] = [];
+ assert.equal(
+ await voiceprintOneVideo({ paths: t.paths, videoDir: t.videoDir, videoId: "vid1", settings: t.settings, onLog: (m) => logs.push(m) }),
+ "refused",
+ );
+ const rec = await loadDiarization(t.videoDir);
+ assert.equal(rec?.generatedAt, EXISTING.generatedAt);
+ assert.deepEqual(rec?.turns, EXISTING.turns);
+ assert.equal(hasVoiceprints(rec), false);
+ assert.equal(rec?.voiceprintsRefused?.file, "audio.mp3");
+ assert.equal(rec?.voiceprintsRefused?.size, "not really mp3".length);
+ assert.match(rec?.voiceprintsRefused?.reason ?? "", /^the file is 99\.000s/);
+ assert.ok(logs.some((l) => l.includes("no fingerprint possible from this file: the file is 99.000s")));
+ // Not an integrity verdict: the audio decodes, it is just not these turns'.
+ assert.equal(await loadAudioIntegrity(t.videoDir), null);
+ } finally {
+ delete process.env.FAKE_EXIT;
+ delete process.env.FAKE_STDERR;
+ await t.cleanup();
+ }
+});
+
diff --git a/common/controller/diarizeOne.ts b/common/controller/diarizeOne.ts
@@ -20,10 +20,18 @@ import {
DIARIZATION_FILENAME,
SORTFORMER_DIARIZATION_ENGINE,
diarizationTarget,
+ hasVoiceprints,
isDiarizationFresh,
} from "../lib/diarization";
-import { hasDiarization, loadDiarization } from "../lib/diarization-server";
+import { hasDiarization, loadDiarization, writeDiarization } from "../lib/diarization-server";
import { findSourceMedia, isRealAudioFile } from "../lib/videoStatus";
+import {
+ fileIdentity,
+ integrityRecord,
+ measureAndRecordIntegrity,
+ writeAudioIntegrity,
+} from "../lib/audioIntegrity-server";
+import type { AudioIntegrityVerdict } from "../lib/audioIntegrity";
import { pickPreferredAudio } from "../lib/mediaFiles";
import { resolveSavedVideo } from "../lib/savedVideo-server";
@@ -107,12 +115,23 @@ export async function diarizeOneVideo(
if (!opts.force) {
const existing = await loadDiarization(opts.videoDir);
if (existing && isDiarizationFresh(existing, diarizationTarget(cfg))) {
+ // Fresh turns from before voiceprints existed: add them from those same
+ // turns while the audio is still here. Never a reason to fail the
+ // diarization itself — the sidecar is good, it is only without them.
+ if (!hasVoiceprints(existing)) {
+ const vp = await voiceprintOneVideo({ ...opts, settings: cfg });
+ if (vp === "voiceprinted") return "diarized";
+ }
return "already-exists";
}
}
const media = await resolveDiarizableMedia(opts.videoDir);
if (!media) return "no-audio";
+ if (await isZeroByteAudio(opts.videoDir, media)) {
+ await recordUnreadableAudio(opts, media, log);
+ return "failed";
+ }
const start = Date.now();
log(`Diarize ${opts.videoId} start (${media})`);
@@ -176,6 +195,9 @@ export async function diarizeOneVideo(
await child;
} catch (err) {
log(`Diarize ${opts.videoId} failed: ${(err as Error).message}`);
+ if (!opts.signal?.aborted && isDecodeFailure(err)) {
+ await recordUnreadableAudio(opts, media, log);
+ }
return "failed";
}
@@ -193,3 +215,177 @@ export async function diarizeOneVideo(
);
return "diarized";
}
+
+// ---------------------------------------------------------------------------
+// Voiceprints for a sidecar that predates them.
+
+export type VoiceprintOneOutcome =
+ // diarization.json now carries a voiceprint per speaker.
+ | "voiceprinted"
+ // It already did.
+ | "already-present"
+ // No (valid) diarization.json: diarize it first.
+ | "no-diarization"
+ // The audio is gone: no fingerprint is possible any more. A fact to list,
+ // never an error.
+ | "no-audio"
+ // No embedding model configured.
+ | "not-configured"
+ // The audio is on disk but does not decode (recorded in audio-integrity.json).
+ | "unreadable"
+ // The engine refused this file for these turns (exit 6), recorded on the
+ // sidecar as voiceprintsRefused: no fingerprint possible from it.
+ | "refused"
+ | "failed";
+
+// Add voiceprints to an existing diarization.json from its own turns: the
+// embedder only (scripts/diarize.mjs --voiceprints-only), no segmentation and
+// no re-clustering, so the turns, the engine and `generatedAt` are kept as they
+// are (attribution-diarized's freshness names generatedAt). The same embedding
+// model the sherpa engine clusters with, so these are the numbers a fresh
+// diarization would have recorded.
+export async function voiceprintOneVideo(
+ opts: DiarizeOneOptions,
+): Promise<VoiceprintOneOutcome> {
+ const log = opts.onLog ?? ((m: string) => console.log(m));
+ const cfg = opts.settings ?? getSettings().diarization;
+ if (!cfg.embModel) return "not-configured";
+ const existing = await loadDiarization(opts.videoDir);
+ if (!existing) return "no-diarization";
+ if (hasVoiceprints(existing)) return "already-present";
+ // THE VIDEO'S OWN AUDIO, NEVER resolveDiarizableMedia's fallback (review B3).
+ // Turns made from audio.<ext> are seconds on that file's clock; a source
+ // container or a saved video of the same recording can run seconds apart
+ // (Rumble: measured up to 13 s), and centroids cut from it would be other
+ // stretches — other voices. Without the audio, no fingerprint is possible.
+ const entries = await readdir(opts.videoDir).catch(() => [] as string[]);
+ const media = pickPreferredAudio(entries.filter(isRealAudioFile));
+ if (!media) return "no-audio";
+ if (await isZeroByteAudio(opts.videoDir, media)) {
+ await recordUnreadableAudio(opts, media, log);
+ return "unreadable";
+ }
+ const start = Date.now();
+ log(`Voiceprints ${opts.videoId} start (${media})`);
+ const output: string[] = [];
+ try {
+ const child = execa(
+ opts.paths.diarizeBin,
+ [
+ "--voiceprints-only",
+ DIARIZATION_FILENAME,
+ "--output",
+ DIARIZATION_FILENAME,
+ "--python",
+ cfg.python,
+ "--emb",
+ cfg.embModel,
+ "--threads",
+ String(cfg.threads),
+ "--ffmpeg",
+ opts.paths.ffmpegBin,
+ "--ffprobe",
+ opts.paths.ffprobeBin,
+ media,
+ ],
+ { cwd: opts.videoDir, cancelSignal: opts.signal, all: true, buffer: false },
+ );
+ child.all?.on("data", (c: Buffer) => {
+ const text = c.toString("utf8").trimEnd();
+ output.push(text);
+ log(text);
+ });
+ await child;
+ } catch (err) {
+ log(`Voiceprints ${opts.videoId} failed: ${(err as Error).message}`);
+ if (!opts.signal?.aborted && (err as { exitCode?: number })?.exitCode === 6) {
+ const reason = refusalReason(output.join("\n"));
+ const id = await fileIdentity(path.join(opts.videoDir, media)).catch(() => null);
+ const current = await loadDiarization(opts.videoDir);
+ if (id && current) {
+ await writeDiarization(opts.videoDir, {
+ ...current,
+ voiceprintsRefused: { file: media, size: id.size, mtime: id.mtime, reason, at: new Date().toISOString() },
+ });
+ }
+ log(`${opts.videoId}: no fingerprint possible from this file: ${reason}`);
+ return "refused";
+ }
+ if (!opts.signal?.aborted && isDecodeFailure(err)) {
+ const verdict = await recordUnreadableAudio(opts, media, log);
+ if (verdict === "undecodable") return "unreadable";
+ }
+ return "failed";
+ }
+ // Trust the file: the same turns, the same generatedAt, voiceprints complete.
+ const after = await loadDiarization(opts.videoDir);
+ if (
+ !after ||
+ !hasVoiceprints(after) ||
+ after.generatedAt !== existing.generatedAt ||
+ after.turns.length !== existing.turns.length
+ ) {
+ log(`Voiceprints ${opts.videoId} produced no complete voiceprints — treating as failed.`);
+ return "failed";
+ }
+ log(
+ `Voiceprints ${opts.videoId} done in ${((Date.now() - start) / 1000).toFixed(1)}s`,
+ );
+ return "voiceprinted";
+}
+
+// The engine's own sentence for an exit-6 refusal ("diarize-sherpa: refused:
+// <why>"), or a generic one.
+function refusalReason(output: string): string {
+ const lines = output.split("\n").filter((l) => l.includes("refused:"));
+ const last = lines[lines.length - 1];
+ return last ? last.slice(last.indexOf("refused:") + "refused:".length).trim() : "the engine refused this file";
+}
+
+// The engine's "could not decode" exits: diarize-sherpa.py returns 4 when
+// ffmpeg fails and 5 when it decodes zero samples, and diarize.mjs passes the
+// code through.
+function isDecodeFailure(err: unknown): boolean {
+ const code = (err as { exitCode?: number })?.exitCode;
+ return code === 4 || code === 5;
+}
+
+async function isZeroByteAudio(videoDir: string, media: string): Promise<boolean> {
+ if (!isRealAudioFile(media)) return false;
+ const id = await fileIdentity(path.join(videoDir, media)).catch(() => null);
+ return id !== null && id.size === 0;
+}
+
+// RECORD, THEN SKIP. An audio file the engine cannot decode gets a verdict in
+// audio-integrity.json (keyed to the file's size and mtime), and the
+// diarization operation reports a video whose held audio is `undecodable` as
+// blocked — so the lane does not spend a pass on it every run, and a re-fetched
+// file (a new size or mtime) is work again. Only a real audio file: a source
+// container or a saved video is not this lane's to judge.
+async function recordUnreadableAudio(
+ opts: DiarizeOneOptions,
+ media: string,
+ log: (m: string) => void,
+): Promise<AudioIntegrityVerdict | null> {
+ if (!isRealAudioFile(media)) return null;
+ try {
+ const file = path.join(opts.videoDir, media);
+ const id = await fileIdentity(file);
+ const record =
+ id.size === 0
+ ? integrityRecord(media, id, { decodedSeconds: 0, totalSeconds: 0, gaps: [] }, { by: "speakers" })
+ : await measureAndRecordIntegrity(
+ opts.videoDir,
+ media,
+ { ffmpegBin: opts.paths.ffmpegBin, ffprobeBin: opts.paths.ffprobeBin, signal: opts.signal, lowPriority: true },
+ { by: "speakers" },
+ );
+ if (!record) return null;
+ if (id.size === 0) await writeAudioIntegrity(opts.videoDir, record);
+ log(`${opts.videoId}/${media}: ${record.verdict} (${id.size} bytes) — recorded in audio-integrity.json.`);
+ return record.verdict;
+ } catch (err) {
+ log(`${opts.videoId}/${media}: could not record its integrity: ${(err as Error).message}`);
+ return null;
+ }
+}
diff --git a/common/controller/operationBatch.ts b/common/controller/operationBatch.ts
@@ -50,6 +50,7 @@ import type { TaskTracker } from "../jobs/taskHooks";
import type { JobProgress } from "../jobs/registry";
import { readVideoFiles, CUES_JSON_FILENAME } from "../lib/videoStatus";
import {
+ DIARIZATION_OPERATION_ID,
DIGEST_OPERATION_ID,
addOperationState,
digestLaneFor,
@@ -73,6 +74,11 @@ import { TranscribeError } from "./transcribeError";
import { readDigestContext } from "../lib/digestContext-server";
import type { StartWorkerUnitInput } from "./workerServer";
import { reacquireMediaFor, type ReacquireOutcome } from "./backfillReacquire";
+import { cleanAudioForVideo } from "./cleanAudioFromTranscribed";
+import { hasVoiceprints } from "../lib/diarization";
+import { loadDiarization } from "../lib/diarization-server";
+import { recordSpeakersFreed } from "../lib/speakersLedger-server";
+import { formatBytes } from "../lib/format";
import { batchRecencyComparator } from "./batchRecency";
import {
digestGate,
@@ -335,7 +341,7 @@ function backfillLaneLimit(
hold: {
hold: true,
reason: "paused",
- message: "Backfill lane disabled in settings — holding.",
+ message: "The Speakers lane is paused — holding. Work through speakers (on its lane card) lifts it.",
},
};
}
@@ -915,6 +921,10 @@ export type OperationUnitReport = {
reacquireHandedOff: number;
reacquireFailed: number;
diskFloorHit: boolean;
+ // Clean-after-capture (diarization.cleanAfterCapture): audio removed right
+ // after this unit captured the video's speakers and voice fingerprints.
+ audioCleaned: number;
+ audioFreedBytes: number;
};
function emptyReport(
@@ -932,6 +942,8 @@ function emptyReport(
reacquireHandedOff: 0,
reacquireFailed: 0,
diskFloorHit: false,
+ audioCleaned: 0,
+ audioFreedBytes: 0,
};
}
@@ -1062,9 +1074,53 @@ export async function runOperationUnit(
}
}
}
+ // AFTER the finally: a re-acquired file has already been removed above, and
+ // this must never race that cleanup.
+ if (report.outcome === "done" && unit.op.id === DIARIZATION_OPERATION_ID && !aborted()) {
+ await cleanAfterCapture(run, unit, videoDir, report, log, signal);
+ }
return report;
}
+// CLEAN AFTER CAPTURE. The per-video half of Clean audio, run the moment a
+// diarization unit has captured a video's speakers — and only when its sidecar
+// carries the voice fingerprints, because those are the part a deleted audio
+// can never give back. Every gate of the channel sweep applies
+// (cleanAudioForVideo → audioCleanGate + verifyBeforeClean); a gone-upstream
+// video is pinned, not deleted. Live settings, read per unit, so switching it
+// off mid-run takes effect on the next video. Never fails the unit: the
+// capture succeeded whatever happens here.
+async function cleanAfterCapture(
+ run: OperationRun,
+ unit: OperationUnit,
+ videoDir: string,
+ report: OperationUnitReport,
+ log: (m: string) => void,
+ signal: AbortSignal,
+): Promise<void> {
+ if (!getSettings().diarization.cleanAfterCapture) return;
+ try {
+ if (!hasVoiceprints(await loadDiarization(videoDir))) {
+ log(`Kept ${unit.videoId}'s audio: its diarization has no voice fingerprints yet.`);
+ return;
+ }
+ const out = await cleanAudioForVideo({
+ channelSlug: unit.channelSlug,
+ paths: run.paths,
+ videoId: unit.videoId,
+ onLog: log,
+ signal,
+ });
+ if (out.outcome !== "cleaned") return;
+ report.audioCleaned = 1;
+ report.audioFreedBytes = out.bytesFreed;
+ await recordSpeakersFreed(run.paths, out.bytesFreed);
+ log(`Freed ${formatBytes(out.bytesFreed)} of audio from ${unit.videoId} (speakers captured).`);
+ } catch (err) {
+ log(`Clean after capture for ${unit.videoId} failed: ${(err as Error)?.message ?? String(err)}`);
+ }
+}
+
// The work itself: a tagged remote executor when one is free, else the llm
// fan-out for the call-bound operations, else the local run.
//
@@ -1511,6 +1567,9 @@ export type OperationBatchResult = {
reacquireHandedOff: number;
reacquireFailed: number;
diskFloorHit: boolean;
+ // Clean-after-capture: videos whose audio was removed, and the bytes.
+ audioCleaned: number;
+ audioFreedBytes: number;
// Digest: mirrors that received the canonical member's digest, and mirrors
// the alignment gate refused. A refusal is a normal outcome, not an error.
shared: number;
@@ -1541,6 +1600,8 @@ export function emptyOperationBatchResult(): OperationBatchResult {
reacquireHandedOff: 0,
reacquireFailed: 0,
diskFloorHit: false,
+ audioCleaned: 0,
+ audioFreedBytes: 0,
shared: 0,
misaligned: 0,
engineCalls: 0,
@@ -1939,6 +2000,9 @@ export async function runOperationBatch(
function laneOrderFor(run: OperationRun): AutoQueueOrder {
const order = run.settings.autoQueue[run.digest ? "digest" : "backfill"].order;
if (order === "cheapest") return run.digest ? "newest" : "listed";
+ // "space" orders ACROSS channels (corpus disk first); one channel's run has
+ // one disk, so it keeps the listed order.
+ if (order === "space") return "listed";
return order ?? "listed";
}
@@ -2028,6 +2092,8 @@ function foldUnitReport(
result.reacquireCleaned += report.reacquireCleaned;
result.reacquireHandedOff += report.reacquireHandedOff;
result.reacquireFailed += report.reacquireFailed;
+ result.audioCleaned += report.audioCleaned;
+ result.audioFreedBytes += report.audioFreedBytes;
if (report.diskFloorHit) result.diskFloorHit = true;
switch (report.outcome) {
case "done":
diff --git a/common/controller/operationJobs.ts b/common/controller/operationJobs.ts
@@ -25,6 +25,7 @@
// without this module knowing Next exists. The digest runner already had one.
import type { Paths } from "../lib/paths";
+import { formatBytes } from "../lib/format";
import { getSettings } from "../lib/settings";
import {
runManagedFunction,
@@ -143,6 +144,9 @@ export async function runBackfillChannelJob(
? `, ${batch.reacquireHandedOff} handed to auto-transcribe`
: "")
: "") +
+ (batch.audioCleaned > 0
+ ? `; freed ${formatBytes(batch.audioFreedBytes)} of audio from ${batch.audioCleaned} video(s) after capture`
+ : "") +
(batch.diskFloorHit ? " (stopped re-acquiring at the disk floor)" : "") +
(batch.stoppedForRelocation
? " (stopped: a relocation is in flight)"
diff --git a/common/controller/quickAvailabilityCheck.ts b/common/controller/quickAvailabilityCheck.ts
@@ -9,6 +9,7 @@ import {
seedRosterIfAbsent,
} from "./rosterStore";
import type { Paths } from "../lib/paths";
+import { writeAvailabilityVerdict } from "./availabilityVerdict";
// The record itself lives in the dependency-free ./maybeMissingStore so
// runYtdlp's full sweep can write it too (this module imports runYtdlp, so the
@@ -102,11 +103,15 @@ export async function runQuickAvailabilityCheck({
const maybeMissing = diffMaybeMissing(knownIds, freshIds);
+ const checkedAt = new Date().toISOString();
await writeMaybeMissing(paths, channelSlug, {
- checkedAt: new Date().toISOString(),
+ checkedAt,
freshPlaylistCount: freshIds.size,
ids: maybeMissing,
});
+ // What the listing NAMED, for clean-after-capture's verdict cache (an id is
+ // safe to clean only while a fresh listing names it).
+ await writeAvailabilityVerdict(paths, channelSlug, { checkedAt, ids: freshIds });
log(
`Quick availability: ${knownIds.length} known, ${freshIds.size} in fresh playlist, ${maybeMissing.length} maybe-missing.`,
diff --git a/common/controller/recencyIndex.ts b/common/controller/recencyIndex.ts
@@ -569,7 +569,7 @@ export function makeRecencyComparator(
keys: ReadonlyMap<string, RecencyKey>,
order: AutoQueueOrder,
): ((a: string, b: string) => number) | null {
- if (order === "listed" || order === "cheapest") return null;
+ if (order === "listed" || order === "cheapest" || order === "space") return null;
// Keys are YYYYMMDD strings, so lexicographic order IS chronological order.
// "newest" therefore sorts DESCENDING: a smaller (older) key must come later,
// which is a positive comparator result.
diff --git a/common/controller/speakersReadout.test.ts b/common/controller/speakersReadout.test.ts
@@ -0,0 +1,81 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { buildSpeakersReadout } from "./speakersReadout";
+import { emptySpeakersLedger } from "../lib/speakersLedger-server";
+import { speakersReadoutLine } from "../lib/speakersReadout";
+import { emptyHeldAudio, emptySpeakersWork } from "./channelSnapshot";
+
+const GB = 1024 ** 3;
+
+function brief(slug: string, o: {
+ external?: boolean;
+ awaitingBytes: number;
+ awaitingVideos: number;
+ neverBytes?: number;
+ neverVideos?: number;
+ workSeconds?: number;
+ unmeasured?: number;
+ engineMs?: number;
+ engineAudioSeconds?: number;
+ measured?: number;
+ speakers?: boolean;
+}) {
+ const heldAudioBytes = { ...emptyHeldAudio(), awaitingDiarization: o.awaitingBytes, diarizationNeverClears: o.neverBytes ?? 0 };
+ const heldAudioCounts = { ...emptyHeldAudio(), awaitingDiarization: o.awaitingVideos, diarizationNeverClears: o.neverVideos ?? 0 };
+ return {
+ slug,
+ config: (o.external ? { mediaDir: "/mnt/x" } : {}) as never,
+ snapshot: {
+ heldAudioBytes,
+ heldAudioCounts,
+ ...(o.speakers === false
+ ? {}
+ : {
+ speakers: {
+ ...emptySpeakersWork(),
+ workSeconds: o.workSeconds ?? 0,
+ workUnmeasured: o.unmeasured ?? 0,
+ engineMs: o.engineMs ?? 0,
+ engineAudioSeconds: o.engineAudioSeconds ?? 0,
+ measured: o.measured ?? 0,
+ },
+ }),
+ } as never,
+ };
+}
+
+test("the readout: waiting is the hold the lane WILL clear; rate from the sidecars; days at concurrency 1", () => {
+ const r = buildSpeakersReadout(
+ [
+ // 10 GB held, 2 GB of it never clears; 9 h of work measured, 1 video unmeasured.
+ brief("ext", { external: true, awaitingBytes: 10 * GB, awaitingVideos: 10, neverBytes: 2 * GB, neverVideos: 2, workSeconds: 7 * 3600, unmeasured: 1 }),
+ brief("int", { awaitingBytes: 1 * GB, awaitingVideos: 2, workSeconds: 2 * 3600, engineMs: 600_000, engineAudioSeconds: 3600, measured: 4 }),
+ brief("old", { awaitingBytes: GB, awaitingVideos: 1, speakers: false }),
+ ],
+ { ...emptySpeakersLedger(), freedBytes: 3 * GB, freedVideos: 5, startedAt: "2026-11-11T00:00:00.000Z" },
+ );
+ assert.equal(r.waitingBytes, 10 * GB);
+ assert.equal(r.waitingVideos, 11);
+ assert.equal(r.neverClearsVideos, 2);
+ assert.equal(r.secondsPerAudioHour, 600);
+ assert.equal(r.unmeasuredVideos, 1);
+ // 9 measured hours; the unmeasured video is estimated at the measured mean.
+ assert.ok(r.remainingAudioHours > 9 && r.remainingAudioHours < 11);
+ assert.equal(r.etaDays, Math.round(((r.remainingAudioHours * 600) / 86400) * 10) / 10);
+ assert.equal(r.staleSnapshots, 1);
+ // Corpus disk first.
+ assert.deepEqual(r.channels.map((c) => c.slug), ["int", "old", "ext"]);
+ assert.equal(r.freedBytes, 3 * GB);
+ assert.equal(
+ speakersReadoutLine(r),
+ `waiting: 10.00 GB in 11 videos · freed this run: 3.00 GB · about ${r.etaDays! < 1 ? "under a day" : `${r.etaDays} day${r.etaDays === 1 ? "" : "s"}`} left`,
+ );
+});
+
+test("the readout line with nothing measured and nothing waiting", () => {
+ const unmeasured = buildSpeakersReadout([brief("a", { awaitingBytes: GB, awaitingVideos: 1, workSeconds: 3600 })], emptySpeakersLedger());
+ assert.equal(unmeasured.etaDays, null);
+ assert.match(speakersReadoutLine(unmeasured), /time left not yet measured$/);
+ const none = buildSpeakersReadout([], emptySpeakersLedger());
+ assert.equal(speakersReadoutLine(none), "waiting: 0 B in 0 videos · freed this run: 0 B · nothing left");
+});
diff --git a/common/controller/speakersReadout.ts b/common/controller/speakersReadout.ts
@@ -0,0 +1,104 @@
+// The speakers readout, built (lib/speakersReadout.ts has the types and the
+// line). Everything comes from what is already on disk and cheap: each
+// channel's snapshot (heldAudioBytes / heldAudioCounts for the hold, the
+// `speakers` block for work seconds and the measured engine rate) and the
+// ledger for "freed this run". No per-video read here: the snapshot paid for
+// those when it was regenerated.
+
+import type { Paths } from "../lib/paths";
+import type { ChannelBrief } from "./channels";
+import { listChannelBriefs } from "./channels";
+import { readSpeakersLedger, type SpeakersLedger } from "../lib/speakersLedger-server";
+import type { SpeakersChannelRow, SpeakersReadout } from "../lib/speakersReadout";
+
+// PURE: the readout for these briefs and this ledger.
+export function buildSpeakersReadout(
+ briefs: ReadonlyArray<Pick<ChannelBrief, "slug" | "config" | "snapshot">>,
+ ledger: SpeakersLedger,
+): SpeakersReadout {
+ const channels: SpeakersChannelRow[] = [];
+ let engineMs = 0;
+ let engineAudioSeconds = 0;
+ let measured = 0;
+ let staleSnapshots = 0;
+ for (const b of briefs) {
+ const snap = b.snapshot;
+ const held = snap?.heldAudioBytes;
+ const count = snap?.heldAudioCounts;
+ const work = snap?.speakers;
+ if (!snap || !held || !count) continue;
+ if (!work) staleSnapshots++;
+ if (work) {
+ engineMs += work.engineMs;
+ engineAudioSeconds += work.engineAudioSeconds;
+ measured += work.measured;
+ }
+ const row: SpeakersChannelRow = {
+ slug: b.slug,
+ external: !!b.config?.mediaDir || !!b.config?.dataDir,
+ waitingBytes: Math.max(0, held.awaitingDiarization - held.diarizationNeverClears),
+ waitingVideos: Math.max(0, count.awaitingDiarization - count.diarizationNeverClears),
+ neverClearsBytes: held.diarizationNeverClears,
+ neverClearsVideos: count.diarizationNeverClears,
+ remainingAudioHours: (work?.workSeconds ?? 0) / 3600,
+ unmeasuredVideos: work?.workUnmeasured ?? 0,
+ voiceprinted: work?.voiceprinted ?? 0,
+ noFingerprintPossible: work?.noFingerprintPossible ?? 0,
+ };
+ if (
+ row.waitingVideos > 0 ||
+ row.neverClearsVideos > 0 ||
+ row.voiceprinted > 0 ||
+ row.noFingerprintPossible > 0
+ ) {
+ channels.push(row);
+ }
+ }
+ // The lane's own order: corpus disk first, then the biggest hold.
+ channels.sort(
+ (a, b) =>
+ Number(a.external) - Number(b.external) ||
+ b.waitingBytes - a.waitingBytes ||
+ a.slug.localeCompare(b.slug),
+ );
+ const sum = (f: (r: SpeakersChannelRow) => number) => channels.reduce((s, r) => s + f(r), 0);
+ const waitingVideos = sum((r) => r.waitingVideos);
+ const unmeasuredVideos = sum((r) => r.unmeasuredVideos);
+ const measuredHours = sum((r) => r.remainingAudioHours);
+ const measuredVideos = waitingVideos - unmeasuredVideos;
+ const meanHours = measuredVideos > 0 ? measuredHours / measuredVideos : 0;
+ const remainingAudioHours = measuredHours + unmeasuredVideos * meanHours;
+ const secondsPerAudioHour =
+ measured > 0 && engineAudioSeconds > 0 ? engineMs / 1000 / (engineAudioSeconds / 3600) : null;
+ const etaDays =
+ secondsPerAudioHour === null ? null : (remainingAudioHours * secondsPerAudioHour) / 86_400;
+ return {
+ waitingBytes: sum((r) => r.waitingBytes),
+ waitingVideos,
+ neverClearsBytes: sum((r) => r.neverClearsBytes),
+ neverClearsVideos: sum((r) => r.neverClearsVideos),
+ freedBytes: ledger.freedBytes,
+ freedVideos: ledger.freedVideos,
+ runStartedAt: ledger.startedAt,
+ secondsPerAudioHour: secondsPerAudioHour === null ? null : Math.round(secondsPerAudioHour),
+ measured,
+ remainingAudioHours: Math.round(remainingAudioHours * 10) / 10,
+ unmeasuredVideos,
+ etaDays: etaDays === null ? null : Math.round(etaDays * 10) / 10,
+ voiceprinted: sum((r) => r.voiceprinted),
+ noFingerprintPossible: sum((r) => r.noFingerprintPossible),
+ staleSnapshots,
+ channels,
+ };
+}
+
+export async function loadSpeakersReadout(
+ paths: Paths,
+ briefs?: ReadonlyArray<Pick<ChannelBrief, "slug" | "config" | "snapshot">>,
+): Promise<SpeakersReadout> {
+ const [list, ledger] = await Promise.all([
+ briefs ? Promise.resolve(briefs) : listChannelBriefs(paths),
+ readSpeakersLedger(paths),
+ ]);
+ return buildSpeakersReadout(list, ledger);
+}
diff --git a/common/jobs/autoQueuePolicy.test.ts b/common/jobs/autoQueuePolicy.test.ts
@@ -1440,3 +1440,14 @@ test("bucketIdsFrom knows undownloadedIds is a TOP-LEVEL field", () => {
assert.deepEqual([...bucketIdsFrom({}, "partialDownloads")], []);
assert.deepEqual([...bucketIdsFrom({}, "undownloadedIds")], []);
});
+
+test("sanitize: order \"space\" is kept; a lane's `operations` narrowing is kept, deduped and trimmed, and absent when empty", () => {
+ const s = sanitizeAutoQueue({
+ backfill: { enabled: true, order: "space", operations: [" diarization ", "diarization", 3, ""] },
+ digest: { enabled: true, operations: [] },
+ });
+ assert.equal(s.backfill.order, "space");
+ assert.deepEqual(s.backfill.operations, ["diarization"]);
+ assert.equal("operations" in s.digest, false);
+ assert.equal("operations" in s.transcription, false);
+});
diff --git a/common/lib/audioIntegrity.ts b/common/lib/audioIntegrity.ts
@@ -51,8 +51,9 @@ export type AudioIntegrityRecord = {
verdict: AudioIntegrityVerdict;
// What measured it: the scan's own version and ffmpeg's `-version` line.
tool: { scan: string; ffmpeg?: string };
- // Who wrote it: the audit job, or the refetch that replaced the file.
- by: "audit" | "refetch";
+ // Who wrote it: the audit job, the refetch that replaced the file, or the
+ // speakers lane after its engine could not decode the file (diarizeOne).
+ by: "audit" | "refetch" | "speakers";
jobId?: string;
};
diff --git a/common/lib/autoQueueSchema.ts b/common/lib/autoQueueSchema.ts
@@ -48,6 +48,7 @@ export const AUTO_QUEUE_ORDERS: ReadonlyArray<AutoQueueOrder> = [
"newest",
"oldest",
"cheapest",
+ "space",
];
@@ -58,7 +59,10 @@ export const AUTO_QUEUE_ORDERS: ReadonlyArray<AutoQueueOrder> = [
// slice 1.3 folded digest.recencyOrder and backfill.order into them — and copies
// of this line would eventually disagree about what an absent field means.
export function sanitizeAutoQueueOrder(value: unknown): AutoQueueOrder {
- return value === "newest" || value === "oldest" || value === "cheapest"
+ return value === "newest" ||
+ value === "oldest" ||
+ value === "cheapest" ||
+ value === "space"
? value
: "listed";
}
@@ -267,6 +271,9 @@ function sanitizePolicy(value: unknown, lane: AutoQueueKind): AutoQueuePolicy {
// reading those fields gave a file that named no gate — free everywhere
// except backfill, whose field was inverted and defaulted to held.
held: typeof r.held === "boolean" ? r.held : defaultHeldFor(lane),
+ // Written only when it narrows: an absent key is every policy on disk
+ // today, and a default that wrote `[]` would change their bytes for nothing.
+ ...sanitizeLaneOperations(r.operations),
root:
r.root === undefined
? defaultRootFor(lane)
@@ -274,6 +281,19 @@ function sanitizePolicy(value: unknown, lane: AutoQueueKind): AutoQueuePolicy {
};
}
+function sanitizeLaneOperations(value: unknown): { operations?: string[] } {
+ if (!Array.isArray(value)) return {};
+ const ids = [
+ ...new Set(
+ value
+ .filter((v): v is string => typeof v === "string")
+ .map((v) => v.trim())
+ .filter(Boolean),
+ ),
+ ];
+ return ids.length > 0 ? { operations: ids } : {};
+}
+
export function sanitizeAutoQueue(value: unknown): AutoQueueSettings {
if (!value || typeof value !== "object") return defaultAutoQueue();
const r = value as Record<string, unknown>;
diff --git a/common/lib/autoQueueTypes.ts b/common/lib/autoQueueTypes.ts
@@ -33,7 +33,12 @@ export type AutoQueueMatchType = "channel" | "platform" | "all";
// SUPPLIED BY THE RUNNER (the engine never reads a duration off disk). A lane
// whose runner supplies no comparator for it falls back to today's order —
// which is what makes it safe to name here before anything computes it.
-export type AutoQueueOrder = "listed" | "newest" | "oldest" | "cheapest";
+//
+// "space" is the Speakers lane's free-the-disk order: channels whose media is
+// on the corpus disk (no `mediaDir`) first, then the videos holding the most
+// audio bytes per audio-hour of work — the space each hour of CPU frees.
+// Supplied by the runner for the backfill lane only; elsewhere it is "listed".
+export type AutoQueueOrder = "listed" | "newest" | "oldest" | "cheapest" | "space";
// Each field is documented in AUTO_QUEUE_MATCH_FIELD_DOCS below (rendered into SETTINGS.md).
export type AutoQueueMatch = {
@@ -128,6 +133,7 @@ export type AutoQueuePolicy = {
order?: AutoQueueOrder;
snoozeUntil?: number | null;
held?: boolean;
+ operations?: string[];
root: AutoQueueGroup;
};
@@ -176,6 +182,15 @@ export const AUTO_QUEUE_POLICY_FIELD_DOCS: FieldDocs<AutoQueuePolicy> = {
"It stays optional because a reader may be handed a PARTIAL settings " +
"object (laneGuards.test.ts casts one), and `isGateHeld` answers " +
"`false` for a lane that carries no key at all rather than throwing.",
+ operations:
+ "Narrow an OPERATION lane to these operation ids (e.g. [\"diarization\"] " +
+ "on the backfill lane: speakers only, no naming pass). Absent or empty = " +
+ "every enabled operation on the lane's queue, as before.\n\n" +
+ "On the POLICY rather than a leaf's `match.operation` because a channel-" +
+ "priority document compiles the lane's tree from its tiers and the stored " +
+ "leaves are not used while one exists; a lane-wide narrowing survives that " +
+ "and narrows the per-channel run, the counts and the runner alike " +
+ "(lib/operations.ts operationsForLane).",
root:
"The lane's rule tree: a group whose children are groups and leaves (see the node table). A missing root is the lane's default — empty for the runner lanes, one catch-all leaf for digest and backfill. While a channel-priority document exists, the four roots are compiled from it and not hand-edited.",
};
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -246,6 +246,7 @@ export type ChannelConfig = {
lastFullSweepAt?: string;
excludeFromBuild?: boolean;
excludeFromCleanup?: boolean;
+ cleanAfterCaptureUnverified?: boolean;
syncIntervalMinutes?: number;
fullSweepIntervalMinutes?: number;
skipLiveDownloads?: boolean;
@@ -320,6 +321,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
excludeFromBuild: "Leave this channel out of every site build.",
excludeFromCleanup:
"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.",
+ 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.",
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.",
fullSweepIntervalMinutes:
@@ -544,6 +547,7 @@ export const CHANNEL_CONFIG_COERCIONS: {
lastFullSweepAt: str,
excludeFromBuild: bool,
excludeFromCleanup: bool,
+ cleanAfterCaptureUnverified: bool,
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, 43); // 2026-10-30: `skipShorts`; 2026-11: opt-in `localMedia`
+ assert.equal(CHANNEL_CONFIG_KEYS.length, 44); // 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`
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
@@ -69,6 +69,7 @@ export const channelConfigObjectSchema = z.object({
lastFullSweepAt: field("lastFullSweepAt"),
excludeFromBuild: field("excludeFromBuild"),
excludeFromCleanup: field("excludeFromCleanup"),
+ cleanAfterCaptureUnverified: field("cleanAfterCaptureUnverified"),
syncIntervalMinutes: field("syncIntervalMinutes"),
fullSweepIntervalMinutes: field("fullSweepIntervalMinutes"),
skipLiveDownloads: field("skipLiveDownloads"),
diff --git a/common/lib/diarization.test.ts b/common/lib/diarization.test.ts
@@ -7,6 +7,12 @@ import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";
import {
DIARIZATION_FILENAME,
diarizationSpeechSeconds,
+ diarizationTarget,
+ hasVoiceprints,
+ isDiarizationFresh,
+ VOICEPRINT_DIM,
+ voiceprintCount,
+ voiceprintsPossible,
type DiarizationRecord,
} from "./diarization";
import {
@@ -124,3 +130,82 @@ test("speech seconds sums turns, and overlapping turns are not clamped", () => {
});
assert.equal(diarizationSpeechSeconds(overlapping), 12);
});
+
+// ---- voiceprints ------------------------------------------------------------
+
+const REAL = Array.from({ length: VOICEPRINT_DIM }, (_, i) => (i === 0 ? 1 : 0));
+const vp = (speaker: number, centroid: number[] | null = REAL, embeddingModel = "titanet.onnx") => ({
+ speaker,
+ seconds: 4,
+ embedded: centroid ? 2 : 0,
+ centroid,
+ embeddingModel,
+});
+const withModel = (over: Partial<DiarizationRecord>) =>
+ record({ engine: { engine: "sherpa-onnx", embeddingModel: "titanet.onnx", threshold: 0.9 }, ...over });
+
+test("hasVoiceprints: every embeddable speaker has a REAL centroid (192 finite numbers, the record's model)", () => {
+ assert.equal(hasVoiceprints(null), false);
+ assert.equal(hasVoiceprints(record()), false, "a sidecar from before voiceprints has none");
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0)] })), false, "speaker 1 is missing");
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1)] })), true);
+ // Both speakers have turns of 4 s and 6 s: a null is a fingerprint not made.
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, null)] })), false);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0, null), vp(1, null)] })), false, "all null, from audio that decoded");
+ assert.equal(voiceprintCount(withModel({ voiceprints: [vp(0), vp(1, null)] })), 1);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, [0.6, 0.8])] })), false, "not 192 floats");
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, REAL.map((x, i) => (i === 5 ? Number.NaN : x)))] })), false);
+ assert.equal(hasVoiceprints(withModel({ voiceprints: [vp(0), vp(1, REAL, "other.onnx")] })), false, "another embedding model");
+ assert.equal(
+ hasVoiceprints(withModel({ voiceprints: [vp(0), { speaker: 1, seconds: 1, centroid: REAL } as never] })),
+ false,
+ "no embeddingModel",
+ );
+ // A null IS allowed for a speaker with no turn long enough to embed.
+ const blip = withModel({
+ turns: [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4, end: 4.3, speaker: 1 },
+ ],
+ voiceprints: [vp(0), vp(1, null)],
+ });
+ assert.equal(hasVoiceprints(blip), true);
+ assert.equal(voiceprintsPossible(blip), true);
+ // Zero turns, or none long enough: nothing was fingerprinted — not complete.
+ assert.equal(hasVoiceprints(withModel({ turns: [], speakers: 0, voiceprints: [] })), false);
+ const short = withModel({ turns: [{ start: 0, end: 0.3, speaker: 0 }], voiceprints: [vp(0, null)] });
+ assert.equal(hasVoiceprints(short), false);
+ assert.equal(voiceprintsPossible(short), false);
+});
+
+test("hasVoiceprints with no model on the record: each voiceprint names one, and they all agree", () => {
+ const noModel = (voiceprints: unknown[]) =>
+ record({ engine: { engine: "sortformer", model: "sf.gguf" }, voiceprints: voiceprints as never });
+ assert.equal(hasVoiceprints(noModel([vp(0, REAL, "titanet.onnx"), vp(1, REAL, "titanet.onnx")])), true);
+ assert.equal(hasVoiceprints(noModel([vp(0, REAL, "titanet.onnx"), vp(1, REAL, "ecapa.onnx")])), false, "two models");
+ assert.equal(hasVoiceprints(noModel([vp(0, REAL, "titanet.onnx"), vp(1, REAL, "")])), false, "an empty model");
+ assert.equal(
+ hasVoiceprints(noModel([vp(0, REAL, "titanet.onnx"), { speaker: 1, seconds: 4, centroid: REAL }])),
+ false,
+ "a missing model",
+ );
+});
+
+test("voiceprints are outside the freshness identity: a sidecar without them is not stale", () => {
+ const target = diarizationTarget({ segModel: "/m/model.onnx", embModel: "/m/titanet.onnx", threshold: 0.9 });
+ const engine = { engine: "sherpa-onnx", segmentationModel: "model.onnx", embeddingModel: "titanet.onnx", threshold: 0.9 };
+ assert.equal(isDiarizationFresh(record({ engine }), target), true);
+ assert.equal(isDiarizationFresh(record({ engine, voiceprints: [vp(0, REAL, "titanet.onnx"), vp(1)], voiceprintsAt: "2026-11-11T00:00:00.000Z" }), target), true);
+});
+
+test("a sidecar with voiceprints round-trips through the writer and the coercer", async () => {
+ const dir = await tmpDir();
+ try {
+ await writeDiarization(dir, withModel({ voiceprints: [vp(0), vp(1)] }));
+ const loaded = await loadDiarization(dir);
+ assert.equal(hasVoiceprints(loaded), true);
+ assert.deepEqual(loaded?.voiceprints?.[0].centroid, REAL);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
diff --git a/common/lib/diarization.ts b/common/lib/diarization.ts
@@ -78,8 +78,136 @@ export type DiarizationRecord = {
windowSeconds: number;
overlapSeconds: number;
};
+ // One voice fingerprint per speaker cluster: the TitaNet embedding the
+ // diarizer clustered with, kept rather than discarded (scripts/
+ // diarize-sherpa.py). It is the ONE part of a diarization that cannot be
+ // recomputed once the audio is gone, so the cleanup gate waits for it
+ // (hasVoiceprints) before deleting the audio.
+ //
+ // OUTSIDE `engine` AND OUTSIDE THE FRESHNESS IDENTITY, exactly as `windowing`
+ // is: a sidecar written before voiceprints existed is not stale — its turns
+ // are what the engine produces today — it is only without them, and the
+ // voiceprint step (diarizeOne's voiceprintOneVideo) adds them from the same
+ // turns without re-clustering and without touching `generatedAt` (which
+ // attribution-diarized's freshness names).
+ voiceprints?: DiarizationVoiceprint[];
+ // ISO 8601, when the voiceprints were computed. Equal to (about) generatedAt
+ // for a sidecar that was written with them; later for one that got them from
+ // the voiceprint step.
+ voiceprintsAt?: string;
+ // The file the fingerprints were cut from (basename, size, duration). The
+ // voiceprint step only ever uses the video's own extracted audio — never a
+ // source container or a saved video, whose clock can differ (review B3).
+ voiceprintsFrom?: { file: string; bytes?: number; durationSeconds?: number };
+ // The voiceprint step REFUSED this audio file (scripts/diarize-sherpa.py
+ // exit 6: its duration is not the record's, an excerpt came back short, or a
+ // speaker with long turns got no embedding). Keyed to the file as it was
+ // (name, size, floored mtime): while that file is the one on disk, no
+ // fingerprint is possible from it, and the diarization operation reports the
+ // video blocked rather than retrying it every runner session. A different
+ // file (a re-download) is work again. The audio stays held either way.
+ voiceprintsRefused?: { file: string; size: number; mtime: number; reason: string; at: string };
+};
+
+// PURE: does this refusal still speak for the file on disk?
+export function voiceprintsRefusedFor(
+ record: Pick<DiarizationRecord, "voiceprintsRefused"> | null,
+ file: { name: string; size: number; mtime: number },
+): boolean {
+ const r = record?.voiceprintsRefused;
+ return !!r && r.file === file.name && r.size === file.size && r.mtime === Math.floor(file.mtime);
+}
+
+// A speaker cluster's voice fingerprint. `centroid` is the L2-normalised mean
+// TitaNet-small embedding (VOICEPRINT_DIM floats, rounded to 4 decimals) of the
+// speaker's longest turns, outliers trimmed as voiceMatch's robustCentroid does;
+// null when none of the speaker's turns were long enough to embed — a recorded
+// "nothing to fingerprint", not a missing one.
+export type DiarizationVoiceprint = {
+ speaker: number;
+ // Talk time of this cluster in the record's turns.
+ seconds: number;
+ // How many excerpts the centroid was made from (0 with a null centroid).
+ embedded?: number;
+ centroid: number[] | null;
+ // Basename of the embedding model, so a comparison never mixes models.
+ embeddingModel: string;
};
+export const VOICEPRINT_DIM = 192;
+
+// The shortest turn the embedder is given (scripts/diarize-sherpa.py
+// EMB_MIN_SEC). A speaker with a turn at least this long CAN be fingerprinted,
+// so a null centroid for one is a fingerprint that was not made.
+export const VOICEPRINT_MIN_SPAN_SEC = 0.5;
+
+function isRealCentroid(c: unknown): c is number[] {
+ return (
+ Array.isArray(c) &&
+ c.length === VOICEPRINT_DIM &&
+ c.every((x) => typeof x === "number" && Number.isFinite(x))
+ );
+}
+
+// Speakers with at least one turn long enough to embed.
+function embeddableSpeakers(record: Pick<DiarizationRecord, "turns">): Set<number> {
+ const out = new Set<number>();
+ for (const t of record.turns ?? []) {
+ if (t.end - t.start >= VOICEPRINT_MIN_SPAN_SEC) out.add(t.speaker);
+ }
+ return out;
+}
+
+// Could this record's turns be fingerprinted at all? False for a record with no
+// turns, or none long enough to embed — "no fingerprint possible" from these
+// turns, which nothing the lane does will change.
+export function voiceprintsPossible(record: Pick<DiarizationRecord, "turns"> | null): boolean {
+ return !!record && embeddableSpeakers(record).size > 0;
+}
+
+// Has this record's voice capture REALLY been done (review B3)? True only when
+// every speaker its turns name has an entry, and every speaker with a turn of at
+// least VOICEPRINT_MIN_SPAN_SEC has a centroid of exactly VOICEPRINT_DIM finite
+// numbers made by the record's embedding model (null is allowed only for a
+// speaker with no turn that long). A record with no turns, or no speaker long
+// enough to embed, is NOT complete: nothing was fingerprinted, and this is the
+// predicate the cleanup gate keys off — anything short of a real fingerprint
+// keeps the only audio one could still be made from.
+export function hasVoiceprints(
+ record: Pick<DiarizationRecord, "turns" | "voiceprints" | "engine"> | null,
+): boolean {
+ if (!record || !Array.isArray(record.voiceprints)) return false;
+ if (!(record.turns ?? []).length) return false;
+ const embeddable = embeddableSpeakers(record);
+ if (embeddable.size === 0) return false;
+ const model = record.engine?.embeddingModel;
+ const bySpeaker = new Map<number, DiarizationVoiceprint>();
+ for (const v of record.voiceprints) {
+ if (!v || typeof v !== "object" || !Number.isInteger(v.speaker)) return false;
+ if (typeof v.embeddingModel !== "string" || !v.embeddingModel) return false;
+ if (model && v.embeddingModel !== model) return false;
+ bySpeaker.set(v.speaker, v);
+ }
+ // With no model on the record (a sortformer record, an engine replacement),
+ // the voiceprints still say which model made them, and they must all say the
+ // same one: a cosine between two models' vectors means nothing.
+ if (new Set(record.voiceprints.map((v) => v.embeddingModel)).size > 1) return false;
+ for (const t of record.turns) if (!bySpeaker.has(t.speaker)) return false;
+ for (const [speaker, v] of bySpeaker) {
+ if (embeddable.has(speaker) ? !isRealCentroid(v.centroid) : v.centroid !== null && !isRealCentroid(v.centroid)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+// How many clusters carry an actual centroid.
+export function voiceprintCount(
+ record: Pick<DiarizationRecord, "voiceprints"> | null,
+): number {
+ return (record?.voiceprints ?? []).filter((v) => isRealCentroid(v?.centroid)).length;
+}
+
export const DIARIZATION_FILENAME = "diarization.json";
// The engine id scripts/diarize.mjs records when it runs its own default
diff --git a/common/lib/operations.test.ts b/common/lib/operations.test.ts
@@ -2,7 +2,8 @@ import { test } from "node:test";
import assert from "node:assert/strict";
import path from "node:path";
import os from "node:os";
-import { mkdtemp, mkdir, writeFile, rm, utimes } from "node:fs/promises";
+import { mkdtemp, mkdir, writeFile, rm, stat, utimes } from "node:fs/promises";
+import { AUDIO_INTEGRITY_FILENAME } from "./audioIntegrity";
import {
getOperation,
allOperations,
@@ -119,6 +120,8 @@ async function fixture(opts: {
// Written into metadata.info.json. Absent means NO metadata file at all,
// which is the "duration unknown" case the cap has to get right.
durationSec?: number;
+ // An audio-integrity.json verdict on audio.mp3.
+ integrity?: "undecodable" | "clean";
}): Promise<{ dir: string; cleanup: () => Promise<void> }> {
const root = await mkdtemp(path.join(os.tmpdir(), "backfill-kinds-"));
const dir = path.join(root, "vid1");
@@ -150,16 +153,41 @@ async function fixture(opts: {
JSON.stringify({ id: "vid1", duration: opts.durationSec }),
);
}
+ if (opts.integrity) {
+ // A verdict ON audio.mp3 as it is on disk (its size and mtime).
+ const st = await stat(path.join(dir, "audio.mp3"));
+ await writeFile(
+ path.join(dir, AUDIO_INTEGRITY_FILENAME),
+ JSON.stringify({
+ version: 1, checkedAt: "now", file: "audio.mp3", size: st.size, mtime: Math.floor(st.mtimeMs),
+ durationSeconds: opts.integrity === "undecodable" ? null : 1,
+ decodedSeconds: opts.integrity === "undecodable" ? 0 : 1,
+ gaps: [], verdict: opts.integrity, tool: { scan: "x" }, by: "speakers",
+ }),
+ );
+ }
return { dir, cleanup: () => rm(root, { recursive: true, force: true }) };
}
-function sidecar(engine: DiarizationRecord["engine"]): string {
+// A COMPLETE record by default — turns and the voice fingerprints a sidecar is
+// written with today. `voiceprints: false` is one written before they existed.
+function sidecar(
+ engine: DiarizationRecord["engine"],
+ { voiceprints = true }: { voiceprints?: boolean } = {},
+): string {
return JSON.stringify({
videoId: "vid1",
generatedAt: "2026-08-07T00:00:00.000Z",
speakers: 2,
turns: [{ start: 0, end: 4, speaker: 0 }],
engine,
+ ...(voiceprints
+ ? {
+ voiceprints: [
+ { speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb-1.onnx" },
+ ],
+ }
+ : {}),
} satisfies DiarizationRecord);
}
@@ -201,6 +229,77 @@ test("present: the sidecar matches the identity we would produce now", async ()
assert.equal(await classify({ sidecar: sidecar(CURRENT) }), "present");
});
+test("partial: fresh turns without voice fingerprints, while the audio is still here", async () => {
+ assert.equal(
+ await classify({ audio: true, sidecar: sidecar(CURRENT, { voiceprints: false }) }),
+ "partial",
+ );
+ // A persisted container is NOT: the voiceprint step cuts only the video's
+ // own audio (another file of the recording runs on another clock, review
+ // B3), so with only a container there is no fingerprint to be had.
+ assert.equal(
+ await classify({ container: true, sidecar: sidecar(CURRENT, { voiceprints: false }) }),
+ "present",
+ );
+});
+
+test("present: without fingerprints once the audio is gone — none is possible, and it is not work", async () => {
+ assert.equal(await classify({ sidecar: sidecar(CURRENT, { voiceprints: false }) }), "present");
+});
+
+test("present: without fingerprints when no embedding model is configured (a sortformer setup)", async () => {
+ assert.equal(
+ await classify(
+ { audio: true, sidecar: sidecar({ engine: "sortformer", model: "sf.gguf" }, { voiceprints: false }) },
+ settingsWithDiarization({ engine: "sortformer", sortformerModel: "/m/sf.gguf", embModel: "" }),
+ ),
+ "present",
+ );
+});
+
+test("blocked: held audio the engine could not decode is recorded and skipped, not offered every pass", async () => {
+ assert.equal(await classify({ audio: true, integrity: "undecodable" }), "blocked");
+ assert.equal(
+ await classify({ audio: true, integrity: "undecodable", sidecar: sidecar(CURRENT, { voiceprints: false }) }),
+ "present",
+ );
+ // A clean verdict changes nothing.
+ assert.equal(await classify({ audio: true, integrity: "clean" }), "missing");
+});
+
+test("the diarization unit ships an existing sidecar, so a unit executor can add its voiceprints", async () => {
+ const { dir, cleanup } = await fixture({ audio: true, sidecar: sidecar(CURRENT, { voiceprints: false }), durationSec: 9 });
+ try {
+ const files = await readVideoFiles(dir, { checkUntranscribable: true });
+ assert.deepEqual(diarization.inputs(files), [META_FILENAME, DIARIZATION_FILENAME, "audio.mp3"]);
+ } finally {
+ await cleanup();
+ }
+});
+
+test("blocked: the voiceprint step refused THIS audio file (exit 6); a different file is work again", async () => {
+ const { dir, cleanup } = await fixture({ audio: true });
+ try {
+ const st = await stat(path.join(dir, "audio.mp3"));
+ const refused = (size: number) =>
+ JSON.stringify({
+ ...JSON.parse(sidecar(CURRENT, { voiceprints: false })),
+ voiceprintsRefused: { file: "audio.mp3", size, mtime: Math.floor(st.mtimeMs), reason: "duration differs", at: "now" },
+ });
+ const settings = settingsWithDiarization();
+ const target = await diarization.resolveTarget(targetCtx(settings));
+ const classifyHere = async () =>
+ diarization.state({ videoDir: dir, videoId: "vid1", files: await readVideoFiles(dir, { checkUntranscribable: true }), target, settings });
+ await writeFile(path.join(dir, DIARIZATION_FILENAME), refused(st.size));
+ assert.equal(await classifyHere(), "blocked");
+ // The file on disk is another one now (a re-download): partial again.
+ await writeFile(path.join(dir, DIARIZATION_FILENAME), refused(st.size + 100));
+ assert.equal(await classifyHere(), "partial");
+ } finally {
+ await cleanup();
+ }
+});
+
test("stale: a different threshold or model is work, not coverage", async () => {
// The threshold is the single most consequential knob (it decides how many
// speakers come out), so a change to it MUST show as work. Before the
@@ -1671,3 +1770,19 @@ test("operationsForLane: digest stays on the digest lane on BOTH its queues", ()
// And the backfill lane never picks it up on either engine.
assert.deepEqual(operationsForLane("backfill", remote).map((o) => o.id), []);
});
+
+test("operationsForLane: autoQueue.backfill.operations narrows the lane — speakers only — and absent is everything", () => {
+ const s = settingsWithBackfillLane();
+ const all = operationsForLane("backfill", s).map((k) => k.id);
+ assert.ok(all.length > 1 && all.includes("diarization"));
+ const narrowed = {
+ ...s,
+ autoQueue: {
+ ...s.autoQueue,
+ backfill: { ...s.autoQueue.backfill, operations: ["diarization"] },
+ },
+ };
+ assert.deepEqual(operationsForLane("backfill", narrowed).map((k) => k.id), ["diarization"]);
+ const empty = { ...s, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, operations: [] } } };
+ assert.deepEqual(operationsForLane("backfill", empty).map((k) => k.id), all);
+});
diff --git a/common/lib/operations.ts b/common/lib/operations.ts
@@ -72,6 +72,8 @@
// because it is what keeps them apart if they are ever added: `inline` folds
// into an existing pass and `lane` gets the concurrent queue and the share.
+import path from "node:path";
+import { stat } from "node:fs/promises";
import type { Paths } from "./paths";
import type {
AttributionSettings,
@@ -106,13 +108,18 @@ import type { DigestContext } from "./digestContext-server";
import {
SORTFORMER_DIARIZATION_ENGINE,
diarizationTarget,
+ hasVoiceprints,
isDiarizationFresh,
+ voiceprintsPossible,
+ voiceprintsRefusedFor,
type DiarizationBackend,
type DiarizationEngineId,
type DiarizationFreshnessTarget,
type DiarizationRecord,
} from "./diarization";
import { loadDiarization, writeDiarization } from "./diarization-server";
+import { AUDIO_INTEGRITY_FILENAME } from "./audioIntegrity";
+import { heldAudioDamage } from "./audioIntegrity-server";
import {
ATTRIBUTION_FILENAME,
isAttributionDowngrade,
@@ -702,11 +709,39 @@ const diarization: Operation = {
// diarization-server.ts treats it: a half-written sidecar must never be
// what convinces anything the work is done.
if (record) {
- return isDiarizationFresh(record, target as DiarizationFreshnessTarget)
- ? "present"
- : "stale";
+ if (!isDiarizationFresh(record, target as DiarizationFreshnessTarget)) {
+ return "stale";
+ }
+ if (
+ hasVoiceprints(record) ||
+ !voiceprintsPossible(record) ||
+ !settings.diarization.embModel
+ ) {
+ return "present";
+ }
+ // Fresh turns WITHOUT voice fingerprints: PARTIAL while the video's own
+ // AUDIO is still here (diarizeOneVideo's voiceprint step adds them from
+ // the same turns, seconds of work — and only from that audio, never a
+ // container or a saved video, review B3); present once it is gone — no
+ // fingerprint is possible then, which the speakers readout lists, and
+ // nothing this lane can do about it.
+ if (files.audioFiles.length === 0) return "present";
+ // The voiceprint step refused this very file (exit 6, recorded on the
+ // sidecar): "no fingerprint possible from this file: <reason>" —
+ // blocked until a different file is there, not retried every session.
+ if (record.voiceprintsRefused) {
+ const name = pickPreferredAudio(files.audioFiles);
+ const st = name ? await stat(path.join(videoDir, name)).catch(() => null) : null;
+ if (name && st && voiceprintsRefusedFor(record, { name, size: st.size, mtime: st.mtimeMs })) {
+ return "blocked";
+ }
+ }
+ return (await heldAudioUndecodable(videoDir, files)) ? "present" : "partial";
}
}
+ // Audio this lane's engine could not decode, recorded against the file
+ // (audio-integrity.json): not work until a different file is there.
+ if (await heldAudioUndecodable(videoDir, files)) return "blocked";
if (!(await hasDiarizableInput(videoDir, files))) {
// Read the cap here ONLY when this branch can dispatch a download: with
// re-download armed, missing-input is a fetch, and diarizeOneVideo does not
@@ -760,6 +795,9 @@ const diarization: Operation = {
inputs(files) {
const out: string[] = [];
if (files.entries.includes(META_FILENAME)) out.push(META_FILENAME);
+ // The existing sidecar travels too: a fresh one without voiceprints is a
+ // voiceprint step (its own turns, re-embedded), not a re-diarization.
+ if (files.hasDiarization) out.push(DIARIZATION_FILENAME);
const audio =
pickPreferredAudio(files.audioFiles) ?? findSourceMedia(files.entries);
if (audio) out.push(audio);
@@ -786,6 +824,19 @@ async function hasDiarizableInput(
return (await resolveSavedVideo(videoDir)) !== null;
}
+// Is the audio diarization would read known to be undecodable? Answered from
+// the listing first: only a dir holding audio-integrity.json pays a read.
+async function heldAudioUndecodable(
+ videoDir: string,
+ files: VideoFiles,
+): Promise<boolean> {
+ if (!files.entries.includes(AUDIO_INTEGRITY_FILENAME)) return false;
+ const preferred = pickPreferredAudio(files.audioFiles);
+ if (!preferred) return false;
+ const damage = await heldAudioDamage(videoDir, files.entries);
+ return damage?.file === preferred && damage.record.verdict === "undecodable";
+}
+
// Is this video longer than the diarization duration cap?
//
// THE CAP IS OFF BY DEFAULT NOW — windowed diarization removed the OOM it
@@ -1636,6 +1687,17 @@ export function backfillLaneOperations(settings: SiteSettings): Operation[] {
);
}
+// The backfill lane's kinds AS IT DISPATCHES THEM: backfillLaneOperations with
+// the lane's `operations` narrowing (autoQueue.backfill.operations) applied —
+// what operationsForLane("backfill") runs, for the surfaces that name and count
+// the lane (the deck, the Speakers stage, the /channels sections). Asks no
+// laneFor, so a partial settings object is safe here.
+export function backfillLaneDispatchOperations(settings: SiteSettings): Operation[] {
+ const only = settings.autoQueue?.backfill?.operations;
+ const lane = backfillLaneOperations(settings);
+ return only && only.length > 0 ? lane.filter((k) => only.includes(k.id)) : lane;
+}
+
// The READ-SIDE twin of backfillLaneOperations: given a snapshot's per-kind map,
// return only the entries belonging to the shared backfill lane — KEYED, so a
// surface can say WHICH kind a number came from. backfillLaneEntriesOf below is this
@@ -1721,9 +1783,15 @@ export function operationsForLane(
? [BACKFILL_QUEUE]
: [];
if (keys.length === 0) return [];
+ // The lane-wide narrowing (autoQueue.<lane>.operations): the one place every
+ // dispatch path, count and per-channel run asks, so "speakers only" is one
+ // setting rather than a leaf the channel-priority compiler would discard.
+ const only = settings.autoQueue?.[lane]?.operations;
return orderByDependencies(
- allOperations(settings).filter((op) =>
- keys.includes((op.laneFor?.(settings) ?? op.lane).queueKey),
+ allOperations(settings).filter(
+ (op) =>
+ keys.includes((op.laneFor?.(settings) ?? op.lane).queueKey) &&
+ (!only || only.length === 0 || only.includes(op.id)),
),
);
}
diff --git a/common/lib/renderPriority.mjs b/common/lib/renderPriority.mjs
@@ -14,7 +14,7 @@
// subprocesses: RENDER_PRIORITY_TOKEN) is admitted, with the floor 4000 MB
// and the cap 10240 MB unless HEAVY_MIN_FREE_MB / HEAVY_CAP_MB say
// otherwise;
-// - holds the editor's transcription and download lanes, remembering which
+// - holds the editor's transcription, download and Speakers lanes, remembering which
// ones IT held (`lanesHeld`), so ending it releases only those — a lane
// someone else held before stays held.
//
@@ -52,8 +52,9 @@ import { tmpPathFor } from "./atomicFile.mjs";
export const RENDER_PRIORITY_FLOOR_MB = 4000;
/** The render's heavy cap (MemoryMax) in render mode, absent HEAVY_CAP_MB. */
export const RENDER_PRIORITY_CAP_MB = 10240;
-/** The editor lanes render mode holds. */
-export const RENDER_MODE_LANES = Object.freeze(["transcription", "download"]);
+/** The editor lanes render mode holds: the GPU transcription lane, downloads, and
+ * the Speakers (backfill) lane — CPU diarization, ~4 cores, which a render wants. */
+export const RENDER_MODE_LANES = Object.freeze(["transcription", "download", "backfill"]);
/** A manual window with no --for ends after this. */
export const DEFAULT_RENDER_MODE_WINDOW_MS = 2 * 60 * 60 * 1000;
/** The env var a render (and everything under it) carries the hold's token in. */
diff --git a/common/lib/renderPriority.test.ts b/common/lib/renderPriority.test.ts
@@ -36,7 +36,9 @@ function tmpFile() {
}
/** A fake editor's lanes: `held` is what it holds; `calls` what was asked. */
-function fakeLanes(held: Record<string, boolean> = {}, { failRelease = false } = {}) {
+// The Speakers (backfill) lane starts held, as it ships.
+function fakeLanes(initial: Record<string, boolean> = {}, { failRelease = false } = {}) {
+ const held: Record<string, boolean> = { backfill: true, ...initial };
const calls: string[] = [];
const lanes: RenderModeLanes = {
async isHeld(lane) {
@@ -139,13 +141,15 @@ test("describeRenderPriority and parseDurationMs", () => {
test("on holds only the lanes not held already, and off releases only those", async () => {
const file = tmpFile();
- const ed = fakeLanes({ download: true }); // someone else's hold
+ // Someone else's hold on download; the Speakers (backfill) lane running —
+ // a render takes its cores too (RENDER_MODE_LANES).
+ const ed = fakeLanes({ download: true, backfill: false });
const on = await renderModeOn({ file, holder: { pid: process.pid, cmd: "umtool take p --id t", project: "p", take: "t" }, lanes: ed.lanes, editor: "http://localhost:3001" });
assert.equal(on.ok, true);
- assert.deepEqual(on.state?.lanesHeld, ["transcription"]);
+ assert.deepEqual(on.state?.lanesHeld, ["transcription", "backfill"]);
assert.deepEqual(on.state?.lanesSkipped, ["download"]);
assert.equal(on.state?.until, null); // a take's hold ends with its process
- assert.deepEqual(ed.calls, ["hold transcription"]);
+ assert.deepEqual(ed.calls, ["hold transcription", "hold backfill"]);
const onDisk = readRenderPriorityState(file);
assert.equal(onDisk?.token, on.state?.token);
assert.equal(readRenderPriority(file).held, true);
@@ -161,8 +165,8 @@ test("on holds only the lanes not held already, and off releases only those", as
assert.equal(existsSync(file), true);
const off = await renderModeOff({ file, token: on.state?.token, lanes: ed.lanes });
- assert.deepEqual(off.released, ["transcription"]);
- assert.deepEqual(ed.calls, ["hold transcription", "release transcription"]);
+ assert.deepEqual(off.released, ["transcription", "backfill"]);
+ assert.deepEqual(ed.calls, ["hold transcription", "hold backfill", "release transcription", "release backfill"]);
assert.equal(ed.held.download, true, "the hold it found stays");
assert.equal(existsSync(file), false);
});
diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts
@@ -333,6 +333,10 @@ export type DiarizationSettings = {
sortformerModel: string;
concurrency: number;
maxAudioHours: number;
+ cleanAfterCapture: boolean;
+ requireVoiceprints: boolean;
+ cleanVerdictMaxAgeHours: number;
+ cleanWholeRecordingAudio: boolean;
};
export const DIARIZATION_SETTINGS_FIELD_DOCS: FieldDocs<DiarizationSettings> = {
@@ -435,6 +439,44 @@ export const DIARIZATION_SETTINGS_FIELD_DOCS: FieldDocs<DiarizationSettings> = {
"lands: windowing divides per-window n by the window count, so the " +
"matrix falls by its square, and the cap stops being needed rather than" +
" being tuned.",
+ cleanAfterCapture:
+ "Delete a video's audio as soon as the Speakers lane has captured it.\n\n" +
+ "When ON, a diarization unit that finishes with a complete set of voice " +
+ "fingerprints (diarization.json `voiceprints`) is followed at once by the " +
+ "per-video half of Clean audio, with every one of its gates: a " +
+ "transcript.json, outside the keep-latest window, not marked do-not-clean, " +
+ "and the availability check (a video gone upstream is pinned, not " +
+ "deleted). The bytes freed are logged and counted in the speakers " +
+ "readout. OFF by default: nothing deletes audio until the operator says " +
+ "so.",
+ requireVoiceprints:
+ "Hold a video's audio until its diarization.json carries voice " +
+ "fingerprints.\n\n" +
+ "A fingerprint is the one part of a diarization that cannot be made " +
+ "again once the audio is gone, so with this ON (the default) Clean audio " +
+ "skips a diarized video whose sidecar has none, saying \"awaiting voice " +
+ "fingerprint\", and the Speakers lane adds them from the existing turns. " +
+ "Applies only while diarization is enabled, like the diarization guard " +
+ "itself.",
+ cleanVerdictMaxAgeHours:
+ "How old the channel's last listing may be for clean-after-capture to " +
+ "trust it.\n\n" +
+ "Clean after capture asks NOTHING of the network: it reads the channel's " +
+ "availability verdict (availability-verdict.json, written by the quick " +
+ "availability check) — a video named in a listing younger than this is " +
+ "cleaned, one not named is held (maybe missing). With no fresh listing the " +
+ "video is held and ONE quick check of the channel is queued on its " +
+ "platform's queue, at most once per this many hours, never while the " +
+ "platform is held. The manual Clean audio sweep keeps its own live check.",
+ cleanWholeRecordingAudio:
+ "Let clean-after-capture delete the audio of channels on " +
+ "`clips.wholeRecordingPlatforms` (Rumble by default).\n\n" +
+ "OFF by default, and the reason is the recording clock: on those " +
+ "platforms the cues are the transcription of audio.<ext>, and every clip " +
+ "is cut from another file of the recording through a time map fitted " +
+ "against that audio (common/lib/recordingClock.mjs). Deleting it as each " +
+ "video is captured leaves those recordings with no map to make later. " +
+ "The manual Clean audio sweep is unaffected.",
};
// Configuration for the derived-corpus digest layer. Local-first by decision:
@@ -1558,6 +1600,10 @@ export function defaultDiarization(): DiarizationSettings {
// stays honest about what it does, for a machine smaller than this one or a
// recording longer than anything measured here.
maxAudioHours: 0,
+ cleanAfterCapture: false,
+ requireVoiceprints: true,
+ cleanVerdictMaxAgeHours: 24,
+ cleanWholeRecordingAudio: false,
};
}
@@ -1600,6 +1646,16 @@ export function sanitizeDiarization(value: unknown): DiarizationSettings {
r.maxAudioHours >= 0
? r.maxAudioHours
: d.maxAudioHours,
+ cleanAfterCapture: r.cleanAfterCapture === true,
+ // ON unless explicitly switched off: the safe direction is to keep audio.
+ requireVoiceprints: r.requireVoiceprints !== false,
+ cleanVerdictMaxAgeHours:
+ typeof r.cleanVerdictMaxAgeHours === "number" &&
+ Number.isFinite(r.cleanVerdictMaxAgeHours) &&
+ r.cleanVerdictMaxAgeHours > 0
+ ? r.cleanVerdictMaxAgeHours
+ : d.cleanVerdictMaxAgeHours,
+ cleanWholeRecordingAudio: r.cleanWholeRecordingAudio === true,
};
}
diff --git a/common/lib/spaceOrder.test.ts b/common/lib/spaceOrder.test.ts
@@ -0,0 +1,17 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { audioBytesPerHour, spaceComparator } from "./spaceOrder";
+
+test("space order: corpus-disk channels first, then the most bytes freed per audio-hour; unknown last; ties stable", () => {
+ const external = new Set(["x1", "x2"]);
+ const rate: Record<string, number | null> = { a: 10, b: 50, c: null, d: 50, x1: 900, x2: null };
+ const cmp = spaceComparator({ external: (id) => external.has(id), bytesPerHour: (id) => rate[id] ?? null });
+ assert.deepEqual(["c", "x1", "a", "b", "x2", "d"].sort(cmp), ["b", "d", "a", "c", "x1", "x2"]);
+});
+
+test("audioBytesPerHour: bytes over hours; nothing to say without both", () => {
+ assert.equal(audioBytesPerHour(3_600_000, 1800), 7_200_000);
+ assert.equal(audioBytesPerHour(0, 1800), null);
+ assert.equal(audioBytesPerHour(100, null), null);
+ assert.equal(audioBytesPerHour(100, 0), null);
+});
diff --git a/common/lib/spaceOrder.ts b/common/lib/spaceOrder.ts
@@ -0,0 +1,38 @@
+// The Speakers lane's "space" order (AutoQueueOrder): which video to capture
+// next so the disk frees fastest.
+//
+// Two keys, in this order:
+// 1. a channel whose media is on the CORPUS disk (no `mediaDir`) before one
+// whose media lives on another drive — the operator's ruling: internal
+// disk first, because that is the disk that fills;
+// 2. bytes of held audio per audio-hour, descending — the space one hour of
+// diarization CPU frees (the CPU cost is ~proportional to duration, the
+// space to the file's size).
+// A video whose rate is unknown (no duration on disk) sorts after every known
+// one within its disk class. Equal keys compare 0, so the sort is stable and
+// keeps the listed order between them.
+//
+// Pure: the runner (controller/autoRunner.ts recencyOrdering) supplies the two
+// lookups; nothing here touches the disk.
+
+export function audioBytesPerHour(bytes: number, seconds: number | null): number | null {
+ if (!(bytes > 0) || seconds === null || !(seconds > 0)) return null;
+ return bytes / (seconds / 3600);
+}
+
+export function spaceComparator(look: {
+ external: (id: string) => boolean;
+ bytesPerHour: (id: string) => number | null;
+}): (a: string, b: string) => number {
+ return (a, b) => {
+ const ea = look.external(a) ? 1 : 0;
+ const eb = look.external(b) ? 1 : 0;
+ if (ea !== eb) return ea - eb;
+ const ra = look.bytesPerHour(a);
+ const rb = look.bytesPerHour(b);
+ if (ra === rb) return 0;
+ if (ra === null) return 1;
+ if (rb === null) return -1;
+ return rb - ra;
+ };
+}
diff --git a/common/lib/speakersLedger-server.ts b/common/lib/speakersLedger-server.ts
@@ -0,0 +1,102 @@
+// What the Speakers lane has freed since it was last started: the "freed this
+// run" half of the speakers readout (controller/speakersReadout.ts).
+//
+// A file, not a counter in the runner: the lane runs for weeks across editor
+// restarts, and a number that resets on every restart would say "freed 0 GB"
+// the morning after a night that freed forty. One small JSON at the corpus
+// root, read-modify-written under the in-process file lock; the lane runs at
+// concurrency 1 and the per-channel batch shares its queue, so there is one
+// writer at a time anyway.
+//
+// "This run" begins when the operator presses Work through speakers on a lane
+// that was paused or disarmed (startSpeakersRun); Pause does not reset it, so a
+// paused-then-resumed night is still one run.
+
+import path from "node:path";
+import type { Paths } from "./paths";
+import {
+ readJsonFile,
+ withJsonFileLock,
+ writeJsonAtomic,
+} from "./jsonFile-server";
+
+// A dot path, like the corpus root's other runtime state (.x-runs, .x-session,
+// .auto-queue): state, not corpus data.
+export const SPEAKERS_LEDGER_FILENAME = ".speakers-run.json";
+
+export type SpeakersLedger = {
+ version: 1;
+ // ISO 8601: when this run began (null before the first one).
+ startedAt: string | null;
+ // Audio removed by clean-after-capture this run.
+ freedBytes: number;
+ freedVideos: number;
+ // ISO 8601 of the last change.
+ updatedAt: string | null;
+};
+
+export function emptySpeakersLedger(): SpeakersLedger {
+ return { version: 1, startedAt: null, freedBytes: 0, freedVideos: 0, updatedAt: null };
+}
+
+export function speakersLedgerPath(paths: Pick<Paths, "transcriptsDir">): string {
+ return path.join(paths.transcriptsDir, SPEAKERS_LEDGER_FILENAME);
+}
+
+function coerce(value: unknown): SpeakersLedger {
+ const v = value as Partial<SpeakersLedger> | null;
+ const n = (x: unknown) => (typeof x === "number" && Number.isFinite(x) && x >= 0 ? x : 0);
+ const s = (x: unknown) => (typeof x === "string" ? x : null);
+ if (!v || typeof v !== "object") return emptySpeakersLedger();
+ return {
+ version: 1,
+ startedAt: s(v.startedAt),
+ freedBytes: n(v.freedBytes),
+ freedVideos: n(v.freedVideos),
+ updatedAt: s(v.updatedAt),
+ };
+}
+
+export async function readSpeakersLedger(
+ paths: Pick<Paths, "transcriptsDir">,
+): Promise<SpeakersLedger> {
+ const read = await readJsonFile(speakersLedgerPath(paths));
+ return read.ok ? coerce(read.value) : emptySpeakersLedger();
+}
+
+async function update(
+ paths: Pick<Paths, "transcriptsDir">,
+ fn: (l: SpeakersLedger) => SpeakersLedger,
+): Promise<SpeakersLedger> {
+ const file = speakersLedgerPath(paths);
+ return withJsonFileLock(file, async () => {
+ const next = fn(await readSpeakersLedger(paths));
+ await writeJsonAtomic(file, next, { indent: 2 });
+ return next;
+ });
+}
+
+// A new run: the freed tally starts again from zero.
+export function startSpeakersRun(
+ paths: Pick<Paths, "transcriptsDir">,
+ now: Date = new Date(),
+): Promise<SpeakersLedger> {
+ const at = now.toISOString();
+ return update(paths, () => ({ ...emptySpeakersLedger(), startedAt: at, updatedAt: at }));
+}
+
+// One video's audio freed by clean-after-capture.
+export function recordSpeakersFreed(
+ paths: Pick<Paths, "transcriptsDir">,
+ bytes: number,
+ now: Date = new Date(),
+): Promise<SpeakersLedger> {
+ const at = now.toISOString();
+ return update(paths, (l) => ({
+ ...l,
+ startedAt: l.startedAt ?? at,
+ freedBytes: l.freedBytes + Math.max(0, bytes),
+ freedVideos: l.freedVideos + 1,
+ updatedAt: at,
+ }));
+}
diff --git a/common/lib/speakersReadout.ts b/common/lib/speakersReadout.ts
@@ -0,0 +1,70 @@
+// The speakers readout — what the Speakers lane is holding, what it has freed,
+// how fast it goes and how long is left. Client-safe types and the one line
+// every surface prints (the lane deck, /cleanup, `pnpm ops get speakers`), so
+// the three can never word or round it differently. Built server-side by
+// controller/speakersReadout.ts from the channel snapshots and the ledger.
+
+import { formatBytes } from "./format";
+
+export type SpeakersChannelRow = {
+ slug: string;
+ // Media on another drive (the channel names a mediaDir).
+ external: boolean;
+ // Audio held for the lane that it WILL clear (the hold minus what it never
+ // clears), bytes and videos.
+ waitingBytes: number;
+ waitingVideos: number;
+ // Audio held at the speakers gate that the lane will never clear (over the
+ // duration cap, no input, the operation unconfigured).
+ neverClearsBytes: number;
+ neverClearsVideos: number;
+ remainingAudioHours: number;
+ unmeasuredVideos: number;
+ voiceprinted: number;
+ noFingerprintPossible: number;
+};
+
+export type SpeakersReadout = {
+ waitingBytes: number;
+ waitingVideos: number;
+ neverClearsBytes: number;
+ neverClearsVideos: number;
+ // This run (.speakers-run.json).
+ freedBytes: number;
+ freedVideos: number;
+ runStartedAt: string | null;
+ // Measured engine cost: wall seconds per audio-hour over `measured` sidecars.
+ secondsPerAudioHour: number | null;
+ measured: number;
+ // Remaining work. Videos with no recorded duration are estimated at the mean
+ // duration of the measured ones (and counted in unmeasuredVideos).
+ remainingAudioHours: number;
+ unmeasuredVideos: number;
+ // Wall-clock days at concurrency 1, or null when nothing measured the rate.
+ etaDays: number | null;
+ voiceprinted: number;
+ noFingerprintPossible: number;
+ // Channels whose snapshot predates the readout's fields: their numbers are
+ // missing until the next regeneration.
+ staleSnapshots: number;
+ channels: SpeakersChannelRow[];
+};
+
+function days(d: number): string {
+ if (d < 1) return "under a day";
+ const n = d < 10 ? Math.round(d * 10) / 10 : Math.round(d);
+ return `${n} day${n === 1 ? "" : "s"}`;
+}
+
+// "waiting: 368.78 GB in 3,634 videos · freed this run: 0 B · about 41 days left"
+export function speakersReadoutLine(r: SpeakersReadout): string {
+ const waiting = `waiting: ${formatBytes(r.waitingBytes)} in ${r.waitingVideos.toLocaleString("en-US")} video${r.waitingVideos === 1 ? "" : "s"}`;
+ const freed = `freed this run: ${formatBytes(r.freedBytes)}`;
+ const left =
+ r.waitingVideos === 0
+ ? "nothing left"
+ : r.etaDays === null
+ ? "time left not yet measured"
+ : `about ${days(r.etaDays)} left`;
+ return `${waiting} · ${freed} · ${left}`;
+}
diff --git a/common/views/channelGroupSections.ts b/common/views/channelGroupSections.ts
@@ -14,7 +14,7 @@ import {
import {
DIGEST_OPERATION_ID,
allOperations,
- backfillLaneOperations,
+ backfillLaneDispatchOperations,
backfillLaneEntriesOf,
operationsGroupLabel,
reachableOperationWork,
@@ -102,7 +102,7 @@ export function laneOffFor(
if (station === "digest") {
return !allOperations(settings).some((k) => k.id === DIGEST_OPERATION_ID);
}
- if (station === "speakers") return backfillLaneOperations(settings).length === 0;
+ if (station === "speakers") return backfillLaneDispatchOperations(settings).length === 0;
return false;
}
@@ -328,7 +328,7 @@ export function buildChannelGroupSections(
digest: station("digest"),
speakers: station("speakers"),
speakersLabel: operationsGroupLabel(
- backfillLaneOperations(settings).map((k) => k.id),
+ backfillLaneDispatchOperations(settings).map((k) => k.id),
),
};
});
diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts
@@ -14,6 +14,7 @@ import {
// three client components (AttentionStrip, NextAction, OverviewPanel) for its
// types. A type import is erased, a value import would not be.
import type { ChannelMediaLocation } from "../../lib/channelMedia";
+import { formatBytes } from "../../lib/format";
export type SnapshotBuckets = ChannelSnapshot["buckets"];
@@ -565,6 +566,16 @@ export function computeStageStatuses(
),
);
}
+ // Audio held for the Speakers lane. Not pending work for THIS stage (Clean
+ // audio cannot take it yet), but the reason the disk is not freed — the
+ // summary used to say "Nothing to clean." with gigabytes held.
+ const heldForSpeakers = snapshot.heldAudioBytes?.awaitingDiarization ?? 0;
+ const heldForSpeakersCount = snapshot.heldAudioCounts?.awaitingDiarization ?? 0;
+ if (heldForSpeakers > 0) {
+ cleanupParts.push(
+ `${formatBytes(heldForSpeakers)} held for speakers (${pluralize(heldForSpeakersCount, "video", "videos")})`,
+ );
+ }
const cleanup: StageStatus = {
id: "cleanup",
title: "Cleanup",
diff --git a/common/views/widgetSync.ts b/common/views/widgetSync.ts
@@ -1,10 +1,13 @@
import type { SiteSettings } from "../lib/settings";
import { digestCountOf, type ChannelBrief } from "../controller/channels";
import { digestWorkOf } from "../controller/channelSnapshot";
+import { buildSpeakersReadout } from "../controller/speakersReadout";
+import { emptySpeakersLedger, type SpeakersLedger } from "../lib/speakersLedger-server";
+import { speakersReadoutLine } from "../lib/speakersReadout";
import { isGateHeld } from "../lib/pauseGates";
import {
- backfillLaneOperations,
backfillLaneOperationEntriesOf,
+ backfillLaneDispatchOperations,
operationCostBasis,
operationLabel,
operationsGroupLabel,
@@ -114,6 +117,16 @@ export type WidgetSyncPayload = {
// word survives only on the controls that genuinely act on the shared queue,
// and even there the card now lists what is in it.
groupLabel: string;
+ // THE SPEAKERS READOUT, as the lane card prints it (lib/speakersReadout.ts):
+ // the one line, and the four numbers it leads with. Optional: a payload
+ // from before it reads as no readout.
+ speakers?: {
+ line: string;
+ waitingBytes: number;
+ waitingVideos: number;
+ freedBytes: number;
+ etaDays: number | null;
+ };
// The same numbers, kept apart by kind — which is the only form of them that
// means anything. Summed, this lane reads "77,952 reachable · 77,134 need
// media": both correct, and together a figure in no unit, since 99.5% of the
@@ -166,6 +179,9 @@ export type WidgetSyncInputs = {
// polls — which is why the briefs arrive as an argument rather than being
// read here: the caller already has them, memoized per request.
briefs: readonly ChannelBrief[];
+ // The Speakers lane's "freed this run" (lib/speakersLedger-server.ts). Absent
+ // reads as an empty run.
+ speakersLedger?: SpeakersLedger;
};
// Build the widget sync payload. Both the HTTP route and the dashboard cockpit's
@@ -240,6 +256,8 @@ export function buildWidgetSyncPayload(
// below — no extra read.
let digestBlocked = 0;
let digestDeferred = 0;
+ const narrowed = settings.autoQueue.backfill.operations;
+ const narrowedTo = narrowed && narrowed.length > 0 ? narrowed : null;
for (const c of channels) {
videos += c.snapshot?.totals.videos ?? 0;
const n = digestCountOf(c.snapshot);
@@ -259,6 +277,9 @@ export function buildWidgetSyncPayload(
// only ever meant diarization plus attribution — the digest coverage figure
// it shows beside this one is computed separately, from digestCountOf above.
for (const [id, entry] of backfillLaneOperationEntriesOf(c.snapshot?.backfill)) {
+ // A lane narrowed to some operations (autoQueue.backfill.operations)
+ // counts only those: the rest is not this lane's work while it is.
+ if (narrowedTo && !narrowedTo.includes(id)) continue;
backfillReachable += reachableOperationWork(entry);
backfillNeedsMedia += entry.missingInput;
const acc = backfillByKind.get(id) ?? {
@@ -310,14 +331,27 @@ export function buildWidgetSyncPayload(
armed: settings.autoQueue.digest.enabled,
},
backfill: {
+ speakers: (() => {
+ const r = buildSpeakersReadout(channels, inputs.speakersLedger ?? emptySpeakersLedger());
+ return {
+ line: speakersReadoutLine(r),
+ waitingBytes: r.waitingBytes,
+ waitingVideos: r.waitingVideos,
+ freedBytes: r.freedBytes,
+ etaDays: r.etaDays,
+ };
+ })(),
reachable: backfillReachable,
needsMedia: backfillNeedsMedia,
videos,
held: isGateHeld(settings, "backfill"),
armed: settings.autoQueue.backfill.enabled,
- anyKind: backfillLaneOperations(settings).length > 0,
+ // What the lane DISPATCHES (backfillLaneDispatchOperations: its `operations`
+ // narrowing applied), so a speakers-only lane is named and broken down as
+ // what it runs.
+ anyKind: backfillLaneDispatchOperations(settings).length > 0,
groupLabel: operationsGroupLabel(
- backfillLaneOperations(settings).map((k) => k.id),
+ backfillLaneDispatchOperations(settings).map((k) => k.id),
),
kinds: [...backfillByKind]
.map(([id, counts]) => ({
diff --git a/editor/app/api/ops/_renderMode.test.ts b/editor/app/api/ops/_renderMode.test.ts
@@ -19,18 +19,28 @@ const { getWorkerPool } = await import("yt-dlp-transcript-common/jobs/workerPool
const { renderModeReapTick } = await import("../../operations/renderMode");
test.after(() => corpus.cleanup());
-const held = (lane: "transcription" | "download") => getSettings().autoQueue[lane].held === true;
+const held = (lane: "transcription" | "download" | "backfill") => getSettings().autoQueue[lane].held === true;
test("on holds the lanes not already held (and says so), off releases only those", async () => {
- await corpus.writeSettings({ minFreeDiskGB: 0, autoQueue: { ...getSettings().autoQueue, download: { ...getSettings().autoQueue.download, held: true } } });
+ // The Speakers (backfill) lane running: a render takes its cores too.
+ await corpus.writeSettings({
+ minFreeDiskGB: 0,
+ autoQueue: {
+ ...getSettings().autoQueue,
+ download: { ...getSettings().autoQueue.download, held: true },
+ backfill: { ...getSettings().autoQueue.backfill, held: false },
+ },
+ });
assert.equal(held("download"), true);
assert.equal(held("transcription"), false);
+ assert.equal(held("backfill"), false);
const on = await callPost(POST!, { on: true, for: "90m", note: "the Ember cut" });
assert.equal(on.status, 200, JSON.stringify(on.body));
const state = on.body.state as { token: string; lanesHeld: string[]; lanesSkipped: string[]; until: string; editor: string };
- assert.deepEqual(state.lanesHeld, ["transcription"]);
+ assert.deepEqual(state.lanesHeld, ["transcription", "backfill"]);
assert.deepEqual(state.lanesSkipped, ["download"]);
+ assert.equal(held("backfill"), true);
assert.match(String(on.body.join), /^RENDER_PRIORITY_TOKEN=[0-9a-f]{16}$/);
assert.match(state.editor, /^http:\/\/localhost:\d+$/);
assert.equal(held("transcription"), true);
@@ -45,12 +55,13 @@ test("on holds the lanes not already held (and says so), off releases only those
assert.equal(got.status, 200);
assert.equal(got.body.held, true);
assert.equal(got.body.token, undefined, "the read side carries no token");
- assert.deepEqual(got.body.lanesHeld, ["transcription"]);
+ assert.deepEqual(got.body.lanesHeld, ["transcription", "backfill"]);
const off = await callPost(POST!, { on: false });
assert.equal(off.status, 200, JSON.stringify(off.body));
- assert.deepEqual(off.body.released, ["transcription"]);
+ assert.deepEqual(off.body.released, ["transcription", "backfill"]);
assert.equal(held("transcription"), false);
+ assert.equal(held("backfill"), false);
assert.equal(getWorkerPool().isPaused(), false);
assert.equal(held("download"), true, "someone else's hold stays");
assert.equal(existsSync(STATE), false);
diff --git a/editor/app/api/ops/_speakers.test.ts b/editor/app/api/ops/_speakers.test.ts
@@ -0,0 +1,104 @@
+// Run with:
+// pnpm -C editor exec tsx --test "app/api/ops/_speakers.test.ts"
+//
+// `pnpm ops lane` for the Speakers lane — its `operations` narrowing, its
+// `order`, its one control (`speakers`: work | pause) — and `pnpm ops get
+// speakers`, against the route handlers over a temp corpus. Never the live
+// editor's settings.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { writeFileSync } from "node:fs";
+import path from "node:path";
+import { callGet, callPost, setupOpsCorpus } from "./_testCorpus";
+
+const corpus = await setupOpsCorpus(null);
+const RENDER_STATE = path.join(corpus.root, "render-priority.json");
+process.env.RENDER_PRIORITY_FILE = RENDER_STATE;
+const { POST } = await import("./lane/route");
+const { GET } = await import("./speakers/route");
+const { getSettings } = await import("yt-dlp-transcript-common/lib/settings");
+test.after(() => corpus.cleanup());
+
+const DIARIZATION = {
+ enabled: true,
+ segModel: "/m/seg.onnx",
+ embModel: "/m/emb.onnx",
+};
+
+test("lane: operations narrows the Speakers lane (and null widens it), order takes \"space\"; bad values are 400s", async () => {
+ await corpus.writeSettings({ minFreeDiskGB: 0, diarization: DIARIZATION, attribution: { enabled: true, textOnlyEnabled: true, diarizedEnabled: true } });
+ const ok = await callPost(POST!, { lane: "backfill", operations: ["diarization"], order: "space" });
+ assert.equal(ok.status, 200, JSON.stringify(ok.body));
+ assert.deepEqual(getSettings().autoQueue.backfill.operations, ["diarization"]);
+ assert.equal(getSettings().autoQueue.backfill.order, "space");
+
+ const unknown = await callPost(POST!, { lane: "backfill", operations: ["no-such-op"] });
+ assert.equal(unknown.status, 400);
+ assert.match(String(unknown.body.error), /Not an enabled operation on the backfill lane: no-such-op/);
+ assert.equal((await callPost(POST!, { lane: "backfill", order: "biggest" })).status, 400);
+ assert.equal((await callPost(POST!, { lane: "backfill", operations: "diarization" })).status, 400);
+ assert.equal((await callPost(POST!, { lane: "digest", speakers: "work" })).status, 400);
+
+ const widened = await callPost(POST!, { lane: "backfill", operations: null });
+ assert.equal(widened.status, 200, JSON.stringify(widened.body));
+ assert.equal(getSettings().autoQueue.backfill.operations, undefined);
+ assert.equal(getSettings().autoQueue.backfill.order, "space", "order untouched by an operations write");
+});
+
+// `speakers: "work" | "pause"` goes through the lane actions, which revalidate
+// pages and so need a request: the e2e suite drives them (speakers-run.spec,
+// backfill.spec). Here: what `get speakers` says about a held lane.
+test("get speakers: the line, the lane's state and the two capture settings", async () => {
+ await corpus.writeSettings({
+ minFreeDiskGB: 0,
+ diarization: { ...DIARIZATION, cleanAfterCapture: true },
+ autoQueue: { ...getSettings().autoQueue, backfill: { ...getSettings().autoQueue.backfill, enabled: false, held: true } },
+ });
+ const got = await callGet(GET!, "http://localhost/api/ops/speakers");
+ assert.equal(got.status, 200, JSON.stringify(got.body));
+ const lane = got.body.lane as { held: boolean; armed: boolean; cleanAfterCapture: boolean; requireVoiceprints: boolean };
+ assert.deepEqual(
+ { held: lane.held, armed: lane.armed, cleanAfterCapture: lane.cleanAfterCapture, requireVoiceprints: lane.requireVoiceprints },
+ { held: true, armed: false, cleanAfterCapture: true, requireVoiceprints: true },
+ );
+ assert.equal(got.body.line, "waiting: 0 B in 0 videos · freed this run: 0 B · nothing left");
+ assert.deepEqual(got.body.channels, []);
+});
+
+test("lane speakers:work refuses an un-narrowed lane, and a lane a render holds — writing nothing", async () => {
+ await corpus.writeSettings({
+ minFreeDiskGB: 0,
+ diarization: DIARIZATION,
+ attribution: { enabled: true, textOnlyEnabled: true, diarizedEnabled: true },
+ autoQueue: { ...getSettings().autoQueue, backfill: { ...getSettings().autoQueue.backfill, enabled: false, held: true, operations: undefined } },
+ });
+ const wide = await callPost(POST!, { lane: "backfill", speakers: "work" });
+ assert.equal(wide.status, 400);
+ assert.match(String(wide.body.error), /not narrowed to speaker diarization/);
+ assert.match(String(wide.body.error), /"operations":\["diarization"\]/);
+ assert.equal(getSettings().autoQueue.backfill.held, true);
+ assert.equal(getSettings().autoQueue.backfill.enabled, false);
+
+ await corpus.writeSettings({
+ minFreeDiskGB: 0,
+ diarization: DIARIZATION,
+ autoQueue: { ...getSettings().autoQueue, backfill: { ...getSettings().autoQueue.backfill, enabled: false, held: true, operations: ["diarization"] } },
+ });
+ writeFileSync(
+ RENDER_STATE,
+ JSON.stringify({
+ version: 1,
+ token: "tok",
+ since: new Date().toISOString(),
+ until: null,
+ holder: { pid: process.pid, cmd: "umtool take ember --id t1" },
+ lanesHeld: ["backfill"],
+ editor: "http://localhost:3001",
+ }),
+ );
+ const rendering = await callPost(POST!, { lane: "backfill", speakers: "work" });
+ assert.equal(rendering.status, 400);
+ assert.match(String(rendering.body.error), /A render holds the Speakers lane \(umtool take ember --id t1\)/);
+ assert.equal(getSettings().autoQueue.backfill.held, true, "the render's hold stands");
+});
+
diff --git a/editor/app/api/ops/diarize/route.ts b/editor/app/api/ops/diarize/route.ts
@@ -0,0 +1,18 @@
+import { diarizeChannelAction } from "../../../channels/[slug]/whisperActions";
+import { jobResponse, ops, reqSlug } from "../_lib";
+
+export const dynamic = "force-dynamic";
+
+// POST { slug } — the Cleanup stage's "Diarize speakers", as a job on the
+// channel's queue ({ ok, jobId }; --wait follows it): diarize every video of
+// the channel that still holds audio and has no current diarization.json, and
+// give an existing one its voice fingerprints from its own turns (no
+// re-clustering) — the voiceprint backfill, one channel at a time. Runs whether
+// or not the Speakers lane is paused; `lane {"lane":"backfill","speakers":"work"}`
+// is the whole-corpus way.
+export async function POST(request: Request) {
+ return ops(request, ["slug"], async (body) => {
+ const slug = reqSlug(body, "slug");
+ return jobResponse(await diarizeChannelAction(slug));
+ });
+}
diff --git a/editor/app/api/ops/lane/route.ts b/editor/app/api/ops/lane/route.ts
@@ -20,6 +20,13 @@ import {
stopPublishLaneAction,
} from "../../../sites/lib/publishActions";
import { OpsInputError, okResponse, ops, oneOf, optBool } from "../_lib";
+import {
+ pauseSpeakersAction,
+ workThroughSpeakersAction,
+} from "../../../jobs/actions";
+import { setLaneScopeAction } from "../../../operations/actions";
+import { AUTO_QUEUE_ORDERS } from "yt-dlp-transcript-common/lib/autoQueueSchema";
+import type { AutoQueueOrder } from "yt-dlp-transcript-common/lib/autoQueueTypes";
export const dynamic = "force-dynamic";
@@ -37,6 +44,17 @@ export const dynamic = "force-dynamic";
// `action` mirrors /api/auto-queue/control's body — same three verbs, same
// meanings — so a caller that already drives that route needs nothing new.
//
+// THE SPEAKERS LANE'S SCOPE AND ITS ONE CONTROL (the backfill lane):
+// operations: ["diarization"] | null narrow the lane to these operations
+// (null widens it again) — speakers only;
+// order: "listed"|"newest"|"oldest"|"space" its order ("space": corpus-disk
+// channels first, then the most audio
+// bytes per audio-hour);
+// speakers: "work" | "pause" the lane deck's Work through speakers
+// (arm + lift the hold + start a run) and
+// Pause (hold; stays armed).
+// `operations` and `order` apply first, then `speakers`, then the rest.
+//
// THE PUBLISH LANE (release 19, A4) is a pipeline lane, not a LANES entry: its
// switch is `settings.publish.enabled` (the /operations/publish form's, saved
// through that form's own action with every other field as stored), its gate
@@ -63,7 +81,7 @@ function publishForm(enabled: boolean): FormData {
}
export async function POST(request: Request) {
- return ops(request, ["lane", "held", "enabled", "action"], async (body) => {
+ return ops(request, ["lane", "held", "enabled", "action", "operations", "order", "speakers"], async (body) => {
const lane = oneOf(body, "lane", ALL_LANES);
const enabled = optBool(body, "enabled");
const held = optBool(body, "held");
@@ -76,9 +94,39 @@ export async function POST(request: Request) {
) {
throw new OpsInputError('"action" must be "start", "stop" or "drain"');
}
- if (enabled === undefined && held === undefined && action === undefined) {
+ const speakers = body.speakers;
+ if (speakers !== undefined && speakers !== "work" && speakers !== "pause") {
+ throw new OpsInputError('"speakers" must be "work" or "pause"');
+ }
+ const operations = body.operations;
+ if (
+ operations !== undefined &&
+ operations !== null &&
+ !(Array.isArray(operations) && operations.every((o) => typeof o === "string"))
+ ) {
+ throw new OpsInputError('"operations" must be an array of operation ids, or null');
+ }
+ const order = body.order;
+ if (order !== undefined && !AUTO_QUEUE_ORDERS.includes(order as AutoQueueOrder)) {
+ throw new OpsInputError(`"order" must be one of ${AUTO_QUEUE_ORDERS.join(", ")}`);
+ }
+ if ((speakers !== undefined || operations !== undefined || order !== undefined) &&
+ !(LANES as readonly string[]).includes(lane)) {
+ throw new OpsInputError('"speakers", "operations" and "order" are for an auto-queue lane');
+ }
+ if (speakers !== undefined && lane !== "backfill") {
+ throw new OpsInputError('"speakers" is the backfill (Speakers) lane\'s');
+ }
+ if (
+ enabled === undefined &&
+ held === undefined &&
+ action === undefined &&
+ speakers === undefined &&
+ operations === undefined &&
+ order === undefined
+ ) {
throw new OpsInputError(
- 'nothing to do — send at least one of "enabled", "held" or "action"',
+ 'nothing to do — send at least one of "enabled", "held", "action", "speakers", "operations" or "order"',
);
}
// THE RECURRING REPORTS' LANE (umtool R5) has a gate and nothing else: its
@@ -87,6 +135,17 @@ export async function POST(request: Request) {
if (lane === "report-schedule" && (enabled !== undefined || action !== undefined)) {
throw new OpsInputError('the report-schedule lane takes only "held" — pause a schedule with report-schedule {"action":"pause"}');
}
+ if (operations !== undefined || order !== undefined) {
+ const scoped = await setLaneScopeAction(lane as AutoQueueKind, {
+ ...(operations !== undefined ? { operations: operations as string[] | null } : {}),
+ ...(order !== undefined ? { order: order as AutoQueueOrder } : {}),
+ });
+ if (!scoped.ok) return okResponse(scoped);
+ }
+ if (speakers !== undefined) {
+ const done = speakers === "work" ? await workThroughSpeakersAction() : await pauseSpeakersAction();
+ if (!done.ok) return okResponse(done);
+ }
if (enabled !== undefined) {
if (lane === "publish") {
const saved = await savePublishSettingsAction(undefined, publishForm(enabled));
diff --git a/editor/app/api/ops/render-mode/route.ts b/editor/app/api/ops/render-mode/route.ts
@@ -14,7 +14,7 @@ export const dynamic = "force-dynamic";
// RENDER MODE (common/lib/renderPriority.mjs; AGENTS.md "Render mode"): a
// render the operator is waiting for gets the machine — every other heavy job
-// waits at the heavy slot's door, and this editor's transcription and download
+// waits at the heavy slot's door, and this editor's transcription, download and Speakers (backfill)
// lanes are held (only the ones not held already; only those are released).
// The same switch as `umtool render-mode`, for a session that has only `pnpm ops`.
//
diff --git a/editor/app/api/ops/speakers/route.ts b/editor/app/api/ops/speakers/route.ts
@@ -0,0 +1,42 @@
+import { getPaths } from "yt-dlp-transcript-common/lib/paths";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
+import { operationsForLane } from "yt-dlp-transcript-common/lib/operations";
+import { loadSpeakersReadout } from "yt-dlp-transcript-common/controller/speakersReadout";
+import { speakersReadoutLine } from "yt-dlp-transcript-common/lib/speakersReadout";
+import { readRoute } from "../_read";
+
+export const dynamic = "force-dynamic";
+
+// GET /api/ops/speakers — `pnpm ops get speakers`
+//
+// The speakers readout, as the lane deck and /cleanup print it: `line`
+// ("waiting: X GB in N videos · freed this run: Y GB · about D days left"),
+// then the numbers it is made of — waiting (the audio held for the Speakers
+// lane that it WILL clear), neverClears (held there and never cleared by it),
+// freed this run (.speakers-run.json), the measured rate (seconds of engine per
+// audio-hour, from the sidecars' durationMs/audioSeconds), the audio-hours
+// left and the days at concurrency 1, voiceprinted and noFingerprintPossible
+// (diarized, the audio already gone) — and per channel, corpus disk first.
+// `lane` is the backfill lane's state: armed, held, the operations it
+// dispatches, its order, and the two capture settings.
+export async function GET(request: Request) {
+ return readRoute(request, [], async () => {
+ const settings = getSettings();
+ const readout = await loadSpeakersReadout(getPaths());
+ const policy = settings.autoQueue.backfill;
+ return {
+ line: speakersReadoutLine(readout),
+ lane: {
+ armed: policy.enabled,
+ held: isGateHeld(settings, "backfill"),
+ operations: operationsForLane("backfill", settings).map((o) => o.id),
+ narrowedTo: policy.operations ?? null,
+ order: policy.order ?? "listed",
+ cleanAfterCapture: settings.diarization.cleanAfterCapture,
+ requireVoiceprints: settings.diarization.requireVoiceprints,
+ },
+ ...readout,
+ };
+ });
+}
diff --git a/editor/app/channels/[slug]/components/stages/CleanupStage.tsx b/editor/app/channels/[slug]/components/stages/CleanupStage.tsx
@@ -89,7 +89,7 @@ export function CleanupStage({
<div className="flex flex-col gap-2">
<Heading
title="Diarize speakers"
- desc="Capture who is speaking when, to diarization.json beside each transcript, for every video here that still has audio. This is the half of the decision that has a deadline: Clean audio below deletes the audio, and nothing can reconstruct it afterwards. While diarization is on, that sweep holds back any transcribed video without a sidecar — so running this is what releases the audio it is protecting."
+ desc="This channel, now — even while the Speakers lane is paused: who is speaking when (diarization.json) and each speaker's voice fingerprint, for every video here that still has audio; a video already diarized only gets its fingerprints. Clean audio below holds a transcribed video's audio until both exist, so running this is what releases it. The whole corpus, one video at a time, is Work through speakers on the Speakers lane."
/>
<StreamActionLog
trigger={() => diarizeChannelAction(slug, cleanQueue)}
@@ -112,7 +112,7 @@ export function CleanupStage({
<div className="flex flex-col gap-2">
<Heading
title="Clean audio for transcribed videos"
- 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."
+ 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
diff --git a/editor/app/channels/[slug]/components/stages/SpeakersStage.tsx b/editor/app/channels/[slug]/components/stages/SpeakersStage.tsx
@@ -26,6 +26,8 @@ import { StreamActionLog } from "yt-dlp-transcript-common/components/StreamActio
import { QueueControl } from "../../../../components/QueueControl";
import { cancelJobAction } from "../../../../jobs/actions";
import { backfillChannelAction } from "../../backfillActions";
+import { LaneActionButton } from "../../../../components/lanes/LaneActionButton";
+import { workThroughSpeakersAction } from "../../../../jobs/actions";
import { OperationWork } from "./OperationWork";
export type OperationRowView = {
@@ -78,6 +80,10 @@ type Props = {
// No backfill feature is switched on at all. The card still renders (the rail
// is fixed) but says so rather than reporting an empty work list as "done".
anyEnabled: boolean;
+ // The Speakers lane's gate is shut. A run here waits on it (backfillLaneLimit
+ // holds at zero), so the card says so and offers the lane's own control
+ // rather than leaving "Run speaker work" to idle at "holding".
+ laneHeld?: boolean;
};
export function SpeakersStage({
@@ -89,6 +95,7 @@ export function SpeakersStage({
anyEnabled,
groupLabel,
actionLabel,
+ laneHeld = false,
}: Props) {
// "speaker work" → "Speaker work". Sentence case, not title case: it is a
// phrase, and "Speaker Work" is a proper noun this system does not have.
@@ -152,6 +159,29 @@ export function SpeakersStage({
</>
),
},
+ ...(anyEnabled && laneHeld
+ ? [
+ {
+ key: "lane-paused",
+ ariaLabel: "speakers lane paused",
+ node: (
+ <span className="flex flex-wrap items-center gap-2">
+ <span>
+ The Speakers lane is paused, so {runLabel} waits for it.
+ </span>
+ <LaneActionButton
+ label="Work through speakers"
+ glyph="⟳"
+ ariaLabel="work through speakers"
+ title="Arm the Speakers lane and lift its hold: every channel's speakers and voice fingerprints, one video at a time."
+ variant="idle"
+ action={() => workThroughSpeakersAction()}
+ />
+ </span>
+ ),
+ },
+ ]
+ : []),
...(missingInput > 0
? [
{
@@ -252,6 +282,7 @@ export function SpeakersStage({
buttonLabel={runLabel}
runningLabel="Running…"
label={runLabel}
+ title={`This channel only, now: ${operations.map((k) => k.label.toLowerCase()).join(", ") || "nothing enabled"} for the videos listed below, one at a time on the Speakers lane's queue.`}
extraControls={
<QueueControl
value={queue}
diff --git a/editor/app/channels/[slug]/page.tsx b/editor/app/channels/[slug]/page.tsx
@@ -67,6 +67,7 @@ import { countPlaylist } from "yt-dlp-transcript-common/controller/channels";
import { loadFailedTranscriptions } from "yt-dlp-transcript-common/controller/failedTranscriptions";
import { savedVideoTotals } from "yt-dlp-transcript-common/controller/savedVideoInventory";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
import { locationLabelOfDataDir } from "yt-dlp-transcript-common/lib/storageLocations";
import { probeAllLocations } from "yt-dlp-transcript-common/controller/storageLocations";
import { STORAGE_STATUS_LABEL } from "yt-dlp-transcript-common/views/storage";
@@ -133,7 +134,7 @@ import { MirrorStage } from "./components/stages/MirrorStage";
import { readMirrorScan } from "yt-dlp-transcript-common/lib/mirrors/scanFile-server";
import {
getOperation,
- backfillLaneOperations,
+ backfillLaneDispatchOperations,
operationsActionLabel,
operationsGroupLabel,
OPERATION_GROUP_ORDER,
@@ -444,10 +445,11 @@ export default async function ChannelDetailPage({
buckets.downloadedNoTranscript.filter((id) => !excludedDownloadIds.has(id));
// Enabled lane backfills. A settings read, no I/O.
//
- // backfillLaneOperations, still: this is the BACKFILL lane's list, and the snapshot
- // now carries an entry for every catalog operation including digest, which has
- // its own station and its own queue key.
- const laneOperations = backfillLaneOperations(settings);
+ // The BACKFILL lane's list as it DISPATCHES (backfillLaneDispatchOperations): the snapshot
+ // carries an entry for every catalog operation including digest, which has its
+ // own station and queue key, and a lane narrowed by `autoQueue.backfill.
+ // operations` (speakers only) runs — and so names — only those.
+ const laneOperations = backfillLaneDispatchOperations(settings);
// A mirror channel's last scan (release 31, lane D): one small file, read
// only for a channel whose config has `mirror`.
const mirrorOf = config.mirror?.of ?? [];
@@ -734,6 +736,7 @@ export default async function ChannelDetailPage({
// The lane's name comes from what it HOLDS, not from its queue key.
groupLabel={operationsGroupLabel(laneOperations.map((k) => k.id))}
actionLabel={operationsActionLabel(laneOperations.map((k) => k.id))}
+ laneHeld={isGateHeld(settings, "backfill")}
/>
);
case "cleanup": {
diff --git a/editor/app/cleanup/components/HoldSieve.tsx b/editor/app/cleanup/components/HoldSieve.tsx
@@ -97,7 +97,7 @@ export function HoldSieve({ summary }: { summary: CleanupSummary }) {
{
n: 4,
label: "awaiting diarization",
- clears: "run: Diarize",
+ clears: "run: Work through speakers",
bytes: heldBytes.awaitingDiarization,
count: heldCounts.awaitingDiarization,
neverClears: heldBytes.diarizationNeverClears,
diff --git a/editor/app/cleanup/lib/loadCleanup.ts b/editor/app/cleanup/lib/loadCleanup.ts
@@ -7,6 +7,8 @@ import {
type HeldAudio,
} from "yt-dlp-transcript-common/controller/channelSnapshot";
import { loadFailedTranscriptions } from "yt-dlp-transcript-common/controller/failedTranscriptions";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
// One channel's row in the cleanup ledger. The three reclaim estimates come
// straight from the snapshot's precomputed `cleanupBytes` (already net of
@@ -191,6 +193,17 @@ export async function loadCleanupSummary(
}
}
+ // A PAUSED SPEAKERS LANE CLEARS NOTHING ON ITS OWN. The snapshot's
+ // diarizationNeverClears is what the lane would never clear even when it
+ // runs; while it is held or disarmed, ALL of the awaiting-speakers hold is
+ // stuck until somebody presses Work through speakers. Applied here, at read
+ // time, because the lane's state is not in any snapshot.
+ const lane = getSettings();
+ if (!lane.autoQueue.backfill.enabled || isGateHeld(lane, "backfill")) {
+ heldBytes.diarizationNeverClears = heldBytes.awaitingDiarization;
+ heldCounts.diarizationNeverClears = heldCounts.awaitingDiarization;
+ }
+
return {
rows,
includedReclaimBytes,
diff --git a/editor/app/cleanup/page.tsx b/editor/app/cleanup/page.tsx
@@ -10,6 +10,13 @@ import { ReleaseLedger } from "./components/ReleaseLedger";
import { ChannelWorkTable } from "../components/channelWork/ChannelWorkTable";
import { sectionsFor } from "../components/channelWork/sections";
import { getActionableSummary } from "../lib/actionable/loadActionable";
+import { getChannelBriefs } from "../lib/requestCache";
+import { loadSpeakersReadout } from "yt-dlp-transcript-common/controller/speakersReadout";
+import { speakersReadoutLine } from "yt-dlp-transcript-common/lib/speakersReadout";
+import { getSettings } from "yt-dlp-transcript-common/lib/settings";
+import { isGateHeld } from "yt-dlp-transcript-common/lib/pauseGates";
+import { LaneActionButton } from "../components/lanes/LaneActionButton";
+import { workThroughSpeakersAction } from "../jobs/actions";
export const dynamic = "force-dynamic";
@@ -22,6 +29,12 @@ export default async function CleanupPage() {
// second way. The two cleanup sections are the only channel-work sections
// that belong to no operation: they are bytes, and bytes are this page.
const actionable = await getActionableSummary(paths);
+ // The Speakers lane's readout — the same line the lane card prints — beside
+ // the hold it is working down (the sieve's gate 4).
+ const speakers = await loadSpeakersReadout(paths, await getChannelBriefs(paths));
+ const settings = getSettings();
+ const speakersWorking =
+ settings.autoQueue.backfill.enabled && !isGateHeld(settings, "backfill");
const {
rows,
includedReclaimBytes,
@@ -120,6 +133,31 @@ export default async function CleanupPage() {
The hero answers "how much can I reclaim right now"; these two answer
the question an operator with weeks of queued GPU work actually has. */}
<HoldSieve summary={summary} />
+ <section
+ aria-label="speakers readout"
+ className="flex flex-wrap items-center gap-x-3 gap-y-2 rounded-xl border border-border bg-card px-5 py-3 text-sm"
+ >
+ <span className="font-medium">Speakers</span>
+ <span className="tabular-nums text-muted-foreground">
+ {speakersReadoutLine(speakers)}
+ </span>
+ {speakers.noFingerprintPossible > 0 && (
+ <span className="text-xs text-muted-foreground">
+ {speakers.noFingerprintPossible.toLocaleString("en-US")} diarized before
+ fingerprints, audio already gone: no fingerprint possible
+ </span>
+ )}
+ {!speakersWorking && speakers.waitingVideos > 0 && (
+ <LaneActionButton
+ label="Work through speakers"
+ glyph="⟳"
+ ariaLabel="work through speakers"
+ title="Arm the Speakers lane and lift its hold: every channel's speakers and voice fingerprints, one video at a time."
+ variant="idle"
+ action={workThroughSpeakersAction}
+ />
+ )}
+ </section>
<ReleaseLedger ledger={buildCleanupLedger(summary)} />
{!hasAnything ? (
diff --git a/editor/app/components/lanes/LaneDeck.tsx b/editor/app/components/lanes/LaneDeck.tsx
@@ -10,7 +10,12 @@ import { useSectionFrame } from "../../widget/components/WidgetSection";
import { LaneCard, type LaneControl } from "./LaneCard";
import { deriveLaneState, formatCount } from "yt-dlp-transcript-common/views/laneState";
import { pauseLaneControl } from "./pauseControl";
-import { armLaneAction, disarmLaneAction } from "../../jobs/actions";
+import {
+ armLaneAction,
+ disarmLaneAction,
+ pauseSpeakersAction,
+ workThroughSpeakersAction,
+} from "../../jobs/actions";
// The four lanes, and the ONLY place lane → server-action wiring lives. Rendered
// identically by the dashboard band and the monitor widget's controls section,
@@ -360,36 +365,40 @@ export function LaneDeck({
// queue key; it survives below only on the two controls that genuinely act on
// the shared queue, and the card now says what is in it.
const backfillGroup = backfill?.groupLabel ?? "Derived data";
+ // ONE CONTROL, for the operator's one decision about this lane: work through
+ // the speakers, or not now. It used to be a Run/Stop switch beside a
+ // Hold/Resume gate, and the two together had a state — armed and held — that
+ // read "running" while doing nothing, which is where "Run speaker work" went
+ // to idle at "holding". Work through speakers arms the lane AND lifts the
+ // hold; Pause holds it (the video in flight finishes) and leaves it armed, so
+ // pressing Work through speakers again — or a restart — resumes it. Disarming
+ // outright is the lane console's Stop, on its operation pages.
+ const backfillWorking = backfillArmed && !backfillHeld;
const backfillControls: LaneControl[] = backfillAvailable
? [
- backfillArmed
+ backfillWorking
? {
- key: "backfill-arm",
- label: "Stop the lane",
- glyph: "■",
- ariaLabel: "disarm backfill lane",
+ key: "speakers",
+ label: "Pause",
+ glyph: "❙❙",
+ ariaLabel: "pause speakers",
title:
- "Switch the backfill lane off and let its runner finish what it is holding. The video in flight completes; nothing already written is lost, and the lane's rules are left alone.",
+ "Hold the Speakers lane: the video in flight finishes and nothing new starts. It stays armed — Work through speakers picks up where it was.",
variant: "active",
- action: () => disarmLaneAction("backfill"),
+ action: () => pauseSpeakersAction(),
onChange: onSynced,
}
: {
- key: "backfill-arm",
- label: "Run the lane",
+ key: "speakers",
+ label: "Work through speakers",
glyph: "⟳",
- ariaLabel: "arm backfill lane",
+ ariaLabel: "work through speakers",
title:
- "Switch the backfill lane on and start its runner, on whatever its rules claim — every channel and every operation unless somebody has narrowed them. Survives a restart. The rules are on any of its operation pages.",
+ "Capture each video's speakers and voice fingerprints while its audio is still on disk, one video at a time beside transcription — and, with Clean after capture on, delete that audio once both are stored. Arms the lane and lifts its hold.",
variant: "idle",
- action: () => armLaneAction("backfill"),
+ action: () => workThroughSpeakersAction(),
onChange: onSynced,
},
- pauseLaneControl({
- lane: "backfill",
- held: backfillHeld,
- onChange: onSynced,
- }),
]
: [];
@@ -476,8 +485,19 @@ export function LaneDeck({
aria-label="backfill lane members"
className="block text-xs text-muted-foreground"
>
- {laneOperations.length} operations share one backfill queue and one
- pause: {laneOperations.map((k) => k.label).join(", ")}.
+ {laneOperations.length} operations share the Speakers lane and its
+ one control: {laneOperations.map((k) => k.label).join(", ")}.
+ </span>
+ )}
+ {backfillAvailable && backfill?.speakers && (
+ // THE READOUT, where the button is: what the lane is holding, what
+ // it has freed, how long is left (lib/speakersReadout.ts — the same
+ // line /cleanup and `pnpm ops get speakers` print).
+ <span
+ aria-label="speakers readout"
+ className="block text-xs tabular-nums text-muted-foreground"
+ >
+ {backfill.speakers.line}
</span>
)}
{backfillArmed && backfillHeld && (
diff --git a/editor/app/jobs/actions.ts b/editor/app/jobs/actions.ts
@@ -4,6 +4,10 @@ import { revalidatePath } from "next/cache";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { saveSettings } from "../settings/saveSettings";
+import { startSpeakersRun } from "yt-dlp-transcript-common/lib/speakersLedger-server";
+import { pauseLaneAction, resumeLaneAction } from "../operations/actions";
+import { readRenderPriority } from "yt-dlp-transcript-common/lib/renderPriority.mjs";
+import { renderModeFile } from "../operations/renderMode";
import { laneRootFromScope } from "yt-dlp-transcript-common/lib/laneMigration";
import { isDefaultChannelPriority } from "yt-dlp-transcript-common/lib/channelPriority";
import { operationsForLane } from "yt-dlp-transcript-common/lib/operations";
@@ -332,3 +336,61 @@ export async function endRenderModeAction(): Promise<{ ok: boolean; error?: stri
? { ok: false, error: `not released: ${r.failed.map((f) => `${f.lane} (${f.error})`).join(", ")}` }
: { ok: true };
}
+
+// THE SPEAKERS LANE'S ONE CONTROL (the lane deck's "Work through speakers").
+//
+// Arms the backfill lane AND lifts its hold, in that order of need — the two
+// switches the deck used to draw as a separate Run and Hold pair, which left a
+// lane that read "running" while held, and a "Run speaker work" that idled at
+// "holding". Pressed on a lane that was not already working (disarmed or held)
+// it also starts a new speakers run: the readout's "freed this run" counts from
+// here (lib/speakersLedger-server.ts).
+export async function workThroughSpeakersAction(): Promise<ArmLaneResult> {
+ try {
+ const refusal = speakersWorkRefusal();
+ if (refusal) return { ok: false, error: refusal };
+ const before = getSettings().autoQueue.backfill;
+ const wasWorking = before.enabled && before.held !== true;
+ if (before.held === true) {
+ const resumed = await resumeLaneAction("backfill");
+ if (!resumed.ok) return { ok: false, error: resumed.error };
+ }
+ const armed = await armLaneAction("backfill");
+ if (!armed.ok) return armed;
+ if (!wasWorking) await startSpeakersRun(getPaths());
+ revalidatePath("/cleanup");
+ return armed;
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
+
+// WHY THE ONE CONTROL MAY NOT START THE LANE, or null. Two refusals, both
+// one sentence (review): an un-narrowed backfill lane is every speaker
+// operation — the text-only naming pass over ~97,000 videos on the local model
+// among them — so "Work through speakers" must mean speakers only, and says how
+// to narrow it; and a lane render mode holds is the render's, released when the
+// render ends — lifting it here would take the cores back from the render.
+function speakersWorkRefusal(): string | null {
+ const ops = getSettings().autoQueue.backfill.operations ?? [];
+ if (!(ops.length === 1 && ops[0] === "diarization")) {
+ return (
+ "The Speakers lane is not narrowed to speaker diarization, so it would also run the naming passes — narrow it first: " +
+ `pnpm ops lane --json '{"lane":"backfill","operations":["diarization"]}' (autoQueue.backfill.operations).`
+ );
+ }
+ const render = readRenderPriority(renderModeFile());
+ if (render.held && render.state?.lanesHeld?.includes("backfill")) {
+ const by = render.state.holder?.cmd ?? render.state.note ?? "render mode";
+ return `A render holds the Speakers lane (${by}); it is released when the render ends — see umtool render-mode status.`;
+ }
+ return null;
+}
+
+// "Pause": the gate, not the switch. The video in flight finishes; the lane
+// stays armed, so Work through speakers (or a restart) resumes where it was.
+export async function pauseSpeakersAction(): Promise<ArmLaneResult> {
+ const out = await pauseLaneAction("backfill");
+ revalidatePath("/cleanup");
+ return out.ok ? { ok: true } : { ok: false, error: out.error };
+}
diff --git a/editor/app/operations/actions.ts b/editor/app/operations/actions.ts
@@ -23,6 +23,7 @@ import {
type AutoQueueOrder,
} from "yt-dlp-transcript-common/jobs/autoQueuePolicy";
import { isDefaultChannelPriority } from "yt-dlp-transcript-common/lib/channelPriority";
+import { operationsForLane } from "yt-dlp-transcript-common/lib/operations";
import { prioritizeChannelDownloadPriorityAction } from "../channels/actions";
// EVERY OPERATIONS SURFACE, not just the board. The console is a board plus one
@@ -105,6 +106,11 @@ export async function saveAutoQueueAction(
order: input.order,
snoozeUntil: current.autoQueue[kind].snoozeUntil ?? null,
held: current.autoQueue[kind].held,
+ // The lane-wide operation narrowing is set in settings (ops settings),
+ // not by this form: carried like `held`, never dropped by a save.
+ ...(current.autoQueue[kind].operations
+ ? { operations: current.autoQueue[kind].operations }
+ : {}),
root: compiled ? current.autoQueue[kind].root : input.root,
},
},
@@ -277,3 +283,62 @@ export async function prioritizeChannelDownloadAction(
revalidateOperations();
return { ok: true };
}
+
+// A lane's DISPATCH SCOPE outside its tree: the operation narrowing
+// (`autoQueue.<lane>.operations`, null clears it) and the `order`. Written
+// through the stored policy, every other field as stored — the tree is not
+// touched, so this works while a channel-priority document compiles the roots.
+// The narrowing names operations this lane dispatches, or it is refused: a
+// lane narrowed to nothing would hold at zero forever.
+export async function setLaneScopeAction(
+ kind: AutoQueueKind,
+ input: { operations?: string[] | null; order?: AutoQueueOrder },
+): Promise<{ ok: boolean; error?: string }> {
+ try {
+ const current = getSettings();
+ const policy = current.autoQueue[kind];
+ let operations = policy.operations;
+ if (input.operations !== undefined) {
+ if (input.operations === null || input.operations.length === 0) {
+ operations = undefined;
+ } else {
+ // Against the lane's operations WITHOUT the stored narrowing, so a
+ // narrowed lane can be widened again.
+ const known = new Set(
+ operationsForLane(kind, {
+ ...current,
+ autoQueue: { ...current.autoQueue, [kind]: { ...policy, operations: undefined } },
+ }).map((o) => o.id),
+ );
+ const unknown = input.operations.filter((id) => !known.has(id));
+ if (unknown.length > 0) {
+ return {
+ ok: false,
+ error: `Not an enabled operation on the ${kind} lane: ${unknown.join(", ")} (it has ${[...known].join(", ") || "none"}).`,
+ };
+ }
+ operations = [...new Set(input.operations)];
+ }
+ }
+ const { operations: _drop, ...rest } = policy;
+ void _drop;
+ await saveSettings({
+ autoQueue: {
+ ...current.autoQueue,
+ [kind]: {
+ ...rest,
+ ...(operations ? { operations } : {}),
+ ...(input.order !== undefined ? { order: input.order } : {}),
+ },
+ },
+ });
+ try {
+ revalidateOperations();
+ } catch {
+ /* outside a request (a unit test of the ops route): nothing to revalidate */
+ }
+ return { ok: true };
+ } catch (e) {
+ return { ok: false, error: (e as Error).message };
+ }
+}
diff --git a/editor/app/operations/components/dispatch.ts b/editor/app/operations/components/dispatch.ts
@@ -76,6 +76,9 @@ export const ORDER_LABEL: Record<AutoQueueOrder, string> = {
// The digest lane's shortest-first. Named by DURATION, not by date, which is
// why it is not a third arm of the recency axis.
cheapest: "Shortest first",
+ // The Speakers lane's: corpus-disk channels first, then the most audio freed
+ // per hour of work.
+ space: "Most space freed first",
};
// THE ORDERS A DATE-KEYED LANE OFFERS — the three this control has always
@@ -104,7 +107,7 @@ export const LANE_ORDERS: Record<
transcription: RECENCY_ORDERS,
download: RECENCY_ORDERS,
digest: [...RECENCY_ORDERS, "cheapest"],
- backfill: RECENCY_ORDERS,
+ backfill: [...RECENCY_ORDERS, "space"],
};
// The runner console's heading, per lane. PINNED: the e2e suite scopes whole
@@ -123,7 +126,7 @@ export function orderTradeoff(
): string | null {
// Neither of these reorders by upload date, so neither costs a retry or a
// partial download its head start.
- if (order === "listed" || order === "cheapest") return null;
+ if (order === "listed" || order === "cheapest" || order === "space") return null;
// The trade-off named below is a DOWNLOAD/TRANSCRIPTION one — a retry or a
// partial losing its head start. The operation lanes have no retry bucket and
// no partial state to lose, so there is nothing to warn about.
diff --git a/editor/app/operations/components/settings/DiarizationSettingsForm.tsx b/editor/app/operations/components/settings/DiarizationSettingsForm.tsx
@@ -75,15 +75,57 @@ export function DiarizationSettingsForm({
</span>
<span className="text-xs text-muted-foreground">
Off by default, from measurement rather than caution. On this box
- transcription runs at ~221 s per audio-hour on the GPU (16× real
- time, over 3,602 videos); diarization runs on the CPU at roughly
- 500–680, because no diarization model has been ported to ggml and
- neither ONNX nor PyTorch has a Vulkan path on Linux. Inline
- therefore makes the whole pipeline ~3–4× slower and idles the GPU.
+ transcription runs at ~221 s per audio-hour on the GPU; the
+ sherpa-onnx engine diarizes on the CPU at roughly 500–680, so
+ inline makes the whole pipeline ~3–4× slower and idles the GPU.
For a large batch, leave this off, let transcription run at full
speed with the box above holding the audio, and catch up
- afterwards with <strong>Diarize speakers</strong> on each channel.
- Turn it on for steady state.
+ beside it with <strong>Work through speakers</strong> on the
+ Speakers lane. Turn it on for steady state.
+ </span>
+ </span>
+ </label>
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="checkbox"
+ name="diarizationRequireVoiceprints"
+ defaultChecked={seedChecked(
+ state,
+ "diarizationRequireVoiceprints",
+ initial.requireVoiceprints,
+ )}
+ className="mt-1"
+ />
+ <span className="flex flex-col gap-1">
+ <span className="font-medium">
+ Keep the audio until its voice fingerprints are stored
+ </span>
+ <span className="text-xs text-muted-foreground">
+ A fingerprint (one per speaker, in <code>diarization.json</code>)
+ cannot be made once the audio is gone, so Clean audio skips a
+ diarized video without them — "awaiting voice
+ fingerprint" — until the Speakers lane adds them.
+ </span>
+ </span>
+ </label>
+ <label className="flex items-start gap-2 text-sm">
+ <input
+ type="checkbox"
+ name="diarizationCleanAfterCapture"
+ defaultChecked={seedChecked(
+ state,
+ "diarizationCleanAfterCapture",
+ initial.cleanAfterCapture,
+ )}
+ className="mt-1"
+ />
+ <span className="flex flex-col gap-1">
+ <span className="font-medium">Clean after capture</span>
+ <span className="text-xs text-muted-foreground">
+ Delete a video's audio as soon as the Speakers lane has stored
+ its speakers and fingerprints — through every Clean audio gate
+ (keep-latest, do not clean, the availability check). The bytes
+ freed show on the Speakers lane and on /cleanup.
</span>
</span>
</label>
diff --git a/editor/app/operations/renderMode.ts b/editor/app/operations/renderMode.ts
@@ -28,7 +28,7 @@ import { saveSettings } from "../settings/saveSettings";
// this checkout's git common dir (the editor runs from editor/), or
// RENDER_PRIORITY_FILE — the e2e servers set their own.
-type RenderLane = "transcription" | "download";
+type RenderLane = "transcription" | "download" | "backfill";
export function renderModeFile(): string {
return renderPriorityFile(process.env, { root: process.cwd() });
diff --git a/editor/app/operations/settingsActions.ts b/editor/app/operations/settingsActions.ts
@@ -155,6 +155,9 @@ export async function saveDiarizationSettingsAction(
enabled: formData.get("diarizationEnabled") === "on",
inlineAfterTranscribe:
formData.get("diarizationInlineAfterTranscribe") === "on",
+ requireVoiceprints:
+ formData.get("diarizationRequireVoiceprints") === "on",
+ cleanAfterCapture: formData.get("diarizationCleanAfterCapture") === "on",
threshold: num(formData, "diarizationThreshold", dDiar.threshold),
threads: num(formData, "diarizationThreads", dDiar.threads),
concurrency: num(formData, "diarizationConcurrency", dDiar.concurrency),
diff --git a/editor/app/widget/lib/syncInputs.ts b/editor/app/widget/lib/syncInputs.ts
@@ -3,6 +3,7 @@ import { getSettings } from "yt-dlp-transcript-common/lib/settings";
import { readSchedulerState } from "yt-dlp-transcript-common/jobs/syncSchedulerState";
import type { WidgetSyncInputs } from "yt-dlp-transcript-common/views/widgetSync";
import { getChannelBriefs } from "../../lib/requestCache";
+import { readSpeakersLedger } from "yt-dlp-transcript-common/lib/speakersLedger-server";
// THE READS BEHIND THE WIDGET'S SYNC STRIP.
//
@@ -18,9 +19,10 @@ import { getChannelBriefs } from "../../lib/requestCache";
// of the three.
export async function widgetSyncInputs(): Promise<WidgetSyncInputs> {
const paths = getPaths();
- const [state, briefs] = await Promise.all([
+ const [state, briefs, speakersLedger] = await Promise.all([
readSchedulerState(paths),
getChannelBriefs(paths),
+ readSpeakersLedger(paths),
]);
- return { settings: getSettings(), now: Date.now(), state, briefs };
+ return { settings: getSettings(), now: Date.now(), state, briefs, speakersLedger };
}
diff --git a/editor/e2e/backfill.spec.ts b/editor/e2e/backfill.spec.ts
@@ -97,6 +97,12 @@ function backfillSettings(over: {
};
}
+// The Speakers lane narrowed to diarization — what Work through speakers
+// requires before it will start the lane (it refuses an un-narrowed one).
+function speakersOnly<T extends { autoQueue: { backfill: Record<string, unknown> } }>(s: T): T {
+ return { ...s, autoQueue: { ...s.autoQueue, backfill: { ...s.autoQueue.backfill, operations: ["diarization"] } } };
+}
+
async function seedTranscript(videoId: string): Promise<void> {
await writeFile(
resolvePath(dataRel(videoId, "transcript.json")),
@@ -136,6 +142,22 @@ async function laneArmed(): Promise<boolean> {
return (await backfillLane()).enabled ?? false;
}
+async function laneHeldNow(): Promise<boolean> {
+ return ((await backfillLane()) as { held?: boolean }).held ?? false;
+}
+
+// Disarm through `pnpm ops lane`, so an armed lane does not bleed into the next
+// spec. The deck no longer draws a disarm: its one control is Work through
+// speakers / Pause, and switching the lane off is the console's (and ops').
+async function disarmLane(request: APIRequestContext): Promise<void> {
+ const res = await request.post(`${baseUrl}/api/ops/lane`, {
+ headers: { authorization: "Bearer test-worker-token" },
+ data: { lane: "backfill", enabled: false },
+ });
+ expect(res.status()).toBe(200);
+ await expect.poll(laneArmed, { timeout: 30_000 }).toBe(false);
+}
+
const SLOW = 120_000;
// (1) The stage card reports the two populations SEPARATELY.
@@ -396,40 +418,36 @@ test("the disk floor refuses to re-acquire anything", async ({ page }) => {
// in the same settings write as the switch — so what has to be pinned instead is
// the other half of that: disarming must NOT clear the tree, because an operator
// authored it and switching a lane off is not throwing it away.
-test("the lane arms from the dashboard and disarms without losing its rules", async ({
+test("Work through speakers arms the lane AND lifts its hold, keeping its rules", async ({
page,
+ request,
}) => {
test.setTimeout(SLOW);
await resetData("one-transcribe-channel-with-audio");
- await writeSettings(backfillSettings());
+ // Disarmed AND held — the state the live lane shipped in, two switches off.
+ await writeSettings({ ...backfillSettings(), autoQueue: { backfill: { held: true, operations: ["diarization"] } } });
await page.goto("/");
- const arm = page.getByRole("button", { name: "arm backfill lane" });
- await expect(arm).toBeEnabled({ timeout: 30_000 });
- await arm.click();
+ const work = page.getByRole("button", { name: "work through speakers" });
+ await expect(work).toBeEnabled({ timeout: 30_000 });
+ // ONE control: the Run/Hold pair is gone from the deck.
+ for (const name of ["arm backfill lane", "disarm backfill lane", "pause backfill", "resume backfill"]) {
+ await expect(page.getByRole("button", { name })).toHaveCount(0);
+ }
+ await work.click();
- await expect.poll(laneArmed, { timeout: 30_000 }).toBe(true);
- // An unscoped arm is one catch-all leaf — what an empty `sweepChannels` meant.
+ await expect
+ .poll(async () => ({ armed: await laneArmed(), held: await laneHeldNow() }), { timeout: 30_000 })
+ .toEqual({ armed: true, held: false });
+ // An unscoped arm keeps the one catch-all leaf — what an empty `sweepChannels` meant.
expect(
(await backfillLane()).root?.children?.map((c) => c.match),
).toEqual([{ type: "all" }]);
+ // And the control becomes its reverse.
+ await expect(page.getByRole("button", { name: "pause speakers" })).toBeEnabled({ timeout: 30_000 });
- const disarm = page.getByRole("button", { name: "disarm backfill lane" });
- await expect(disarm).toBeEnabled({ timeout: 30_000 });
- await disarm.click();
-
- await expect
- .poll(
- async () => {
- const lane = await backfillLane();
- return {
- enabled: lane.enabled ?? false,
- rules: lane.root?.children?.length ?? 0,
- };
- },
- { timeout: 30_000 },
- )
- .toEqual({ enabled: false, rules: 1 });
+ await disarmLane(request);
+ expect((await backfillLane()).root?.children?.length ?? 0).toBe(1);
// The sweep's own controls are gone from this surface, not merely relabelled
// — BOTH halves, and both aria-labels, because the deck drew whichever half
@@ -540,10 +558,10 @@ test("a lane can be scoped to one operation from its console, and the scope is a
test("an armed lane comes back after a restart", async ({ page, request }) => {
test.setTimeout(SLOW);
await resetData("one-transcribe-channel-with-audio");
- await writeSettings(backfillSettings());
+ await writeSettings(speakersOnly(backfillSettings()));
await page.goto("/");
- const arm = page.getByRole("button", { name: "arm backfill lane" });
+ const arm = page.getByRole("button", { name: "work through speakers" });
await expect(arm).toBeEnabled({ timeout: 30_000 });
await arm.click();
await expect.poll(laneArmed, { timeout: 30_000 }).toBe(true);
@@ -561,11 +579,7 @@ test("an armed lane comes back after a restart", async ({ page, request }) => {
expect(body.resumed).not.toBe(body.cancelled);
// Clean up, so an armed lane does not bleed into the next spec.
- await page.goto("/");
- const disarm = page.getByRole("button", { name: "disarm backfill lane" });
- await expect(disarm).toBeEnabled({ timeout: 30_000 });
- await disarm.click();
- await expect.poll(laneArmed, { timeout: 30_000 }).toBe(false);
+ await disarmLane(request);
});
// (9) THE WHOLE POINT OF THE SEPARATE QUEUE KEY: a backfill job and a
@@ -795,39 +809,33 @@ test("the diarization page shows the channel and both populations", async ({
// not just the label, for exactly that reason. It also asserts the button
// renders WITHOUT a sweep armed — an operator pauses a hand-clicked
// backfill-channel job too, not only an armed lane.
-test("the dashboard pauses and resumes the backfill lane", async ({ page }) => {
+test("the dashboard's one control: Pause holds the lane and leaves it armed; Work through speakers lifts the hold", async ({
+ page,
+ request,
+}) => {
test.setTimeout(SLOW);
await resetData("one-transcribe-channel-with-audio");
- await writeSettings(backfillSettings());
-
- // THE LANE'S GATE, on the lane. Slice 1.4 moved it off the inverted
- // `backfill.enabled` (deleted by S0-pause) and onto
- // `autoQueue.backfill.held`, so the polarity here is the plain one: held
- // means held.
- const laneHeld = async () =>
- (
- await readJson<{ autoQueue?: { backfill?: { held?: boolean } } }>(
- testPaths().settingsFile,
- ).catch(() => ({}) as { autoQueue?: { backfill?: { held?: boolean } } })
- ).autoQueue?.backfill?.held ?? false;
+ await writeSettings(speakersOnly(backfillSettings()));
await page.goto("/");
- const pause = page.getByRole("button", { name: "pause backfill" });
+ await page.getByRole("button", { name: "work through speakers" }).click();
+ await expect.poll(laneArmed, { timeout: 30_000 }).toBe(true);
+
+ const pause = page.getByRole("button", { name: "pause speakers" });
await expect(pause).toBeEnabled({ timeout: 30_000 });
await pause.click();
-
- await expect.poll(laneHeld, { timeout: 30_000 }).toBe(true);
-
- // THE LANE'S ARM SWITCH IS UNTOUCHED: pausing must not disarm the lane, or
- // "pause" would quietly become "stop" and days of queued work would need
- // re-arming. (The fixture leaves it disarmed, so `false` is what "unchanged"
- // looks like here.)
- expect(await laneArmed()).toBe(false);
-
- const resume = page.getByRole("button", { name: "resume backfill" });
- await expect(resume).toBeEnabled({ timeout: 30_000 });
- await resume.click();
- await expect.poll(laneHeld, { timeout: 30_000 }).toBe(false);
+ // THE LANE'S GATE (`autoQueue.backfill.held`), not its switch: a pause is
+ // not a stop, or days of queued work would need re-arming.
+ await expect.poll(laneHeldNow, { timeout: 30_000 }).toBe(true);
+ expect(await laneArmed()).toBe(true);
+
+ const work = page.getByRole("button", { name: "work through speakers" });
+ await expect(work).toBeEnabled({ timeout: 30_000 });
+ await work.click();
+ await expect.poll(laneHeldNow, { timeout: 30_000 }).toBe(false);
+ expect(await laneArmed()).toBe(true);
+
+ await disarmLane(request);
});
// ONE GATE, TWO SURFACES. /operations/diarization and the dashboard draw the
@@ -841,10 +849,11 @@ test("the dashboard pauses and resumes the backfill lane", async ({ page }) => {
// surfaces disagreeing about which lane they hold.
test("an operation page holds the same lane the dashboard does", async ({
page,
+ request,
}) => {
test.setTimeout(SLOW);
await resetData("one-transcribe-channel-with-audio");
- await writeSettings(backfillSettings());
+ await writeSettings(speakersOnly(backfillSettings()));
// THE LANE'S GATE, on the lane. Slice 1.4 moved it off the inverted
// `backfill.enabled` (deleted by S0-pause) and onto
@@ -870,14 +879,16 @@ test("an operation page holds the same lane the dashboard does", async ({
// A hold is not a stop: the lane's arm switch is untouched.
expect(await laneArmed()).toBe(false);
- // The dashboard shows the same lane held, and releases it.
+ // The dashboard shows the same lane NOT working, and its one control lifts
+ // the hold (and arms the lane: the deck has one switch for both).
await page.goto("/");
- const resumeOnDashboard = page.getByRole("button", {
- name: "resume backfill",
+ const workOnDashboard = page.getByRole("button", {
+ name: "work through speakers",
});
- await expect(resumeOnDashboard).toBeEnabled({ timeout: 30_000 });
- await resumeOnDashboard.click();
+ await expect(workOnDashboard).toBeEnabled({ timeout: 30_000 });
+ await workOnDashboard.click();
await expect.poll(laneHeld, { timeout: 30_000 }).toBe(false);
+ await disarmLane(request);
});
// (11) THE RE-DOWNLOAD ON A SUBTITLE CHANNEL: audio, not captions.
diff --git a/editor/e2e/cleanup-holds.spec.ts b/editor/e2e/cleanup-holds.spec.ts
@@ -90,7 +90,16 @@ test("the sieve attributes every held byte to exactly one gate, and names the ho
await seedTranscript("vidD");
await writeFile(
resolvePath(dataRel("vidD", "diarization.json")),
- JSON.stringify({ segments: [], engine: "test", createdAt: "2026-01-01" }),
+ // A COMPLETE sidecar — turns and voice fingerprints — which is what the
+ // sweep's gate (and so the snapshot's) needs to call a video diarized.
+ JSON.stringify({
+ videoId: "vidD",
+ generatedAt: "2026-01-01T00:00:00.000Z",
+ speakers: 1,
+ turns: [{ start: 0, end: 1, speaker: 0 }],
+ engine: { engine: "test" },
+ voiceprints: [{ speaker: 0, seconds: 1, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "t" }],
+ }),
);
await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
diff --git a/editor/e2e/diarization.spec.ts b/editor/e2e/diarization.spec.ts
@@ -34,7 +34,13 @@ async function seedTranscript(videoId: string): Promise<void> {
);
}
-async function seedDiarization(videoId: string): Promise<void> {
+// With voice fingerprints by default (what "diarized" means since
+// diarization.requireVoiceprints); `voiceprints: false` is a sidecar written
+// before they existed.
+async function seedDiarization(
+ videoId: string,
+ { voiceprints = true }: { voiceprints?: boolean } = {},
+): Promise<void> {
await writeFile(
resolvePath(dataRel(videoId, "diarization.json")),
JSON.stringify({
@@ -43,6 +49,13 @@ async function seedDiarization(videoId: string): Promise<void> {
speakers: 1,
turns: [{ start: 0, end: 10, speaker: 0 }],
engine: { engine: "fake-diarize", threshold: 0.5 },
+ ...(voiceprints
+ ? {
+ voiceprints: [
+ { speaker: 0, seconds: 10, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "null" },
+ ],
+ }
+ : {}),
}) + "\n",
);
}
diff --git a/editor/e2e/fixtures/bin/fake-diarize.mjs b/editor/e2e/fixtures/bin/fake-diarize.mjs
@@ -18,7 +18,14 @@
// vidC is the designated failing id because it is already in the shared
// one-transcribe-channel-with-audio fixture's archive; a spec can exercise the
// failure path without renaming dirs into ids the batch would never pick up.
-import { writeFile } from "node:fs/promises";
+//
+// VOICEPRINTS, as the real wrapper now writes them: one per speaker, with the
+// embedding model's basename. A dir containing "novoiceprint" gets a record
+// WITHOUT them (what every sidecar written before them looks like).
+// `--voiceprints-only <record>` is the wrapper's voiceprint step: it adds them
+// to the record it is given, keeping everything else, and writes --output (or
+// the record itself).
+import { readFile, writeFile } from "node:fs/promises";
import path from "node:path";
import { installFixtureWatchdog } from "./_watchdog.mjs";
@@ -31,7 +38,8 @@ function arg(flag) {
return i < 0 ? undefined : argv[i + 1];
}
-const out = arg("--output") ?? arg("-o");
+const voiceprintsOnly = arg("--voiceprints-only");
+const out = arg("--output") ?? arg("-o") ?? voiceprintsOnly;
const videoId = arg("--video-id") ?? path.basename(process.cwd());
const seg = arg("--seg");
const emb = arg("--emb");
@@ -52,6 +60,24 @@ if (
process.exit(3);
}
+const voiceprintsFor = (turns) =>
+ [...new Set(turns.map((t) => t.speaker))].sort((a, b) => a - b).map((speaker) => ({
+ speaker,
+ seconds: turns.filter((t) => t.speaker === speaker).reduce((s, t) => s + (t.end - t.start), 0),
+ embedded: 1,
+ centroid: Array.from({ length: 192 }, (_, i) => (i === speaker ? 1 : 0)),
+ embeddingModel: emb ? path.basename(emb) : "fake.onnx",
+ }));
+
+if (voiceprintsOnly) {
+ const record = JSON.parse(await readFile(voiceprintsOnly, "utf8"));
+ record.voiceprints = voiceprintsFor(record.turns ?? []);
+ record.voiceprintsAt = new Date().toISOString();
+ await writeFile(out, JSON.stringify(record) + "\n");
+ process.stderr.write(`[fake-diarize] voiceprints for ${record.voiceprints.length} speaker(s) -> ${out}\n`);
+ process.exit(0);
+}
+
const turns = [
{ start: 0, end: 4.5, speaker: 0 },
{ start: 4.5, end: 7.25, speaker: 1 },
@@ -74,6 +100,9 @@ await writeFile(
version: "e2e",
threshold,
},
+ ...(cwd.toLowerCase().includes("novoiceprint")
+ ? {}
+ : { voiceprints: voiceprintsFor(turns), voiceprintsAt: new Date().toISOString() }),
}) + "\n",
);
process.stderr.write(
diff --git a/editor/e2e/maybe-missing.spec.ts b/editor/e2e/maybe-missing.spec.ts
@@ -124,6 +124,14 @@ test("quick check flags videos missing from the fresh playlist", async ({
`${channelRoot}/maybe-missing.json`,
);
expect(record.ids.sort()).toEqual(["viddeleted1", "vidunlisted1"].sort());
+ // …and what the listing NAMED, with when: the verdict cache
+ // clean-after-capture reads instead of listing the channel itself.
+ const verdict = await readJson<{ checkedAt: string; ids: string[] }>(
+ `${channelRoot}/availability-verdict.json`,
+ );
+ expect(verdict.ids).toContain(BASELINE_IDS.find((id) => id !== "viddeleted1")!);
+ expect(verdict.ids).not.toContain("viddeleted1");
+ expect(Date.now() - Date.parse(verdict.checkedAt)).toBeLessThan(10 * 60_000);
// The job arms a debounced (~1s) snapshot regen that re-surfaces the
// maybe-missing set into snapshot.json. Wait for it before reloading.
diff --git a/editor/e2e/speakers-run.spec.ts b/editor/e2e/speakers-run.spec.ts
@@ -0,0 +1,238 @@
+import { writeFile } from "node:fs/promises";
+import { test, expect } from "@playwright/test";
+import {
+ channelStage,
+ generateReport,
+ pathExists,
+ readJson,
+ resetData,
+ resolvePath,
+ writeSettings,
+ testPaths,
+} from "./helpers";
+import { baseUrl } from "./baseUrl";
+
+// "Work through speakers" (lane/speakers-run): the Speakers lane's one
+// control, the voice fingerprints a sidecar must carry before its audio may go,
+// clean-after-capture, and the readout on the lane card, the Cleanup stage and
+// /cleanup. The engine is the fake DIARIZE_BIN (e2e/fixtures/bin/
+// fake-diarize.mjs): voiceprints by default, `--voiceprints-only` as the
+// wrapper's voiceprint step.
+
+const SLUG = "test-transcribe";
+const AUTH = { authorization: "Bearer test-worker-token" };
+const SLOW = 120_000;
+
+function dataRel(videoId: string, file: string): string {
+ return `${testPaths().transcriptsDir}/channels/${SLUG}/data/${videoId}/${file}`;
+}
+
+// The channel's availability verdict (availability-verdict.json beside its
+// config) — what the Quick check writes after a listing, and the only thing
+// clean after capture trusts: `ids` named by a listing at `checkedAt`, and the
+// last check it asked for.
+async function seedVerdict(v: { checkedAt: string | null; ids: string[]; requestedAt?: string }): Promise<void> {
+ await writeFile(
+ resolvePath(`${testPaths().transcriptsDir}/channels/${SLUG}/availability-verdict.json`),
+ JSON.stringify({ version: 1, ...v }) + "\n",
+ );
+}
+
+async function seedTranscript(videoId: string): Promise<void> {
+ await writeFile(resolvePath(dataRel(videoId, "transcript.json")), '{"transcription":[{"text":"hi"}]}\n');
+}
+
+// A FRESH sidecar (the identity the settings below produce) from before
+// voiceprints existed.
+async function seedPlainDiarization(videoId: string): Promise<void> {
+ await writeFile(
+ resolvePath(dataRel(videoId, "diarization.json")),
+ JSON.stringify({
+ videoId,
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ audioSeconds: 10,
+ durationMs: 1000,
+ speakers: 1,
+ turns: [{ start: 0, end: 10, speaker: 0 }],
+ engine: { engine: "fake-diarize", segmentationModel: "null", embeddingModel: "null", threshold: 0.5 },
+ }) + "\n",
+ );
+}
+
+function settings(over: { held?: boolean; narrowed?: boolean; diarization?: Record<string, unknown> } = {}) {
+ return {
+ adminTitle: "Test Admin",
+ maxTranscriptPageBytes: 8388608,
+ sleepBetweenDownloadsSeconds: 0,
+ minFreeDiskGB: 0,
+ verifyAvailabilityBeforeClean: false,
+ syncScheduler: { fullSweepIntervalMinutes: 0 },
+ diarization: {
+ enabled: true,
+ inlineAfterTranscribe: false,
+ threshold: 0.5,
+ threads: 1,
+ python: "python3",
+ segModel: "/dev/null",
+ embModel: "/dev/null",
+ concurrency: 1,
+ ...over.diarization,
+ },
+ backfill: { concurrency: 1, allowRedownload: false },
+ autoQueue: { backfill: { held: over.held ?? false, ...(over.narrowed === false ? {} : { operations: ["diarization"] }) } },
+ };
+}
+
+type Lane = { enabled?: boolean; held?: boolean };
+async function lane(): Promise<Lane> {
+ const s = await readJson<{ autoQueue?: { backfill?: Lane } }>(testPaths().settingsFile).catch(
+ () => ({}) as { autoQueue?: { backfill?: Lane } },
+ );
+ return s.autoQueue?.backfill ?? {};
+}
+
+test.afterEach(async ({ request }) => {
+ // Never leave an armed lane for the next spec.
+ await request.post(`${baseUrl}/api/ops/lane`, { headers: AUTH, data: { lane: "backfill", enabled: false } });
+});
+
+test("a paused Speakers lane: the stage says Run speaker work waits for it, and offers the lane's one control", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings({ held: true }));
+ await seedTranscript("vidA");
+ await generateReport(page, SLUG);
+
+ await page.goto(channelStage(SLUG, "speakers"));
+ const paused = page.getByLabel("speakers lane paused");
+ await expect(paused).toContainText("The Speakers lane is paused, so Run speaker work waits for it.", { timeout: 30_000 });
+ const work = paused.getByRole("button", { name: "work through speakers" });
+ await expect(work).toBeEnabled({ timeout: 30_000 });
+ await work.click();
+ await expect.poll(async () => ({ held: (await lane()).held, armed: (await lane()).enabled }), { timeout: 30_000 }).toEqual({ held: false, armed: true });
+});
+
+test("a sidecar without voice fingerprints keeps its audio until Diarize speakers adds them from its own turns", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings());
+ await seedTranscript("vidA");
+ await seedPlainDiarization("vidA");
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+ await generateReport(page, SLUG);
+
+ await page.goto(channelStage(SLUG, "cleanup"));
+ await page.getByRole("button", { name: "Clean audio", exact: true }).click();
+ await expect(page.getByLabel("Clean audio output")).toContainText("awaiting voice fingerprint", { timeout: 30_000 });
+ expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(true);
+
+ await page.getByRole("button", { name: "Diarize speakers", exact: true }).click();
+ await expect
+ .poll(
+ async () => {
+ const r = await readJson<{ generatedAt: string; voiceprints?: unknown[] }>(dataRel("vidA", "diarization.json")).catch(() => null);
+ return r ? { generatedAt: r.generatedAt, voiceprints: r.voiceprints?.length ?? 0 } : null;
+ },
+ { timeout: 60_000 },
+ )
+ // The same turns' sidecar — generatedAt kept — now with its fingerprint.
+ .toEqual({ generatedAt: "2026-08-07T00:00:00.000Z", voiceprints: 1 });
+
+ await page.goto(channelStage(SLUG, "cleanup"));
+ await page.getByRole("button", { name: "Clean audio", exact: true }).click();
+ await expect(page.getByLabel("Clean audio output")).toContainText("Cleaned 1 audio file", { timeout: 30_000 });
+ expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(false);
+});
+
+test("clean after capture: Run speaker work removes a captured video's audio at once, and the readout counts it", async ({ page, request }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings({ diarization: { cleanAfterCapture: true } }));
+ await seedTranscript("vidA");
+ // The channel was listed an hour ago by its Quick check, and the listing named
+ // vidA: the one verdict clean after capture deletes on.
+ await seedVerdict({ checkedAt: new Date(Date.now() - 3_600_000).toISOString(), ids: ["vidA", "vidB", "vidC"] });
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+ await generateReport(page, SLUG);
+
+ const before = await request.get(`${baseUrl}/api/ops/speakers`, { headers: AUTH });
+ expect(before.status()).toBe(200);
+ const freedBefore = ((await before.json()) as { freedVideos: number }).freedVideos;
+
+ await page.goto(channelStage(SLUG, "speakers"));
+ await page.getByRole("button", { name: "Run speaker work", exact: true }).click();
+ await expect.poll(async () => pathExists(dataRel("vidA", "diarization.json")), { timeout: 60_000 }).toBe(true);
+ await expect.poll(async () => pathExists(dataRel("vidA", "audio.m4a")), { timeout: 60_000 }).toBe(false);
+ await expect(page.getByLabel("Run speaker work output")).toContainText("after capture", { timeout: 30_000 });
+
+ const after = await request.get(`${baseUrl}/api/ops/speakers`, { headers: AUTH });
+ const body = (await after.json()) as { freedVideos: number; line: string; lane: { cleanAfterCapture: boolean } };
+ expect(body.freedVideos).toBe(freedBefore + 1);
+ expect(body.lane.cleanAfterCapture).toBe(true);
+ expect(body.line).toMatch(/^waiting: .* · freed this run: .* · /);
+});
+
+test("clean after capture with no fresh listing: the captured video keeps its audio, awaiting an availability check", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings({ diarization: { cleanAfterCapture: true } }));
+ await seedTranscript("vidA");
+ // The last listing is two days old (older than cleanVerdictMaxAgeHours, 24),
+ // and a check was asked for an hour ago — so nothing new is requested here,
+ // and nothing may be deleted on the old listing.
+ await seedVerdict({
+ checkedAt: new Date(Date.now() - 48 * 3_600_000).toISOString(),
+ ids: ["vidA", "vidB", "vidC"],
+ requestedAt: new Date(Date.now() - 3_600_000).toISOString(),
+ });
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+ await generateReport(page, SLUG);
+
+ await page.goto(channelStage(SLUG, "speakers"));
+ await page.getByRole("button", { name: "Run speaker work", exact: true }).click();
+ await expect.poll(async () => pathExists(dataRel("vidA", "diarization.json")), { timeout: 60_000 }).toBe(true);
+ const output = page.getByLabel("Run speaker work output");
+ await expect(output).toContainText("awaiting an availability check", { timeout: 60_000 });
+ await expect(output).toContainText("a check was requested at");
+ expect(await pathExists(dataRel("vidA", "audio.m4a"))).toBe(true);
+});
+
+test("the readout: the Cleanup stage names the audio held for speakers; /cleanup and the lane card print the line", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ // Held: nothing is dispatched, and the paused lane is what /cleanup's gate 4
+ // must call a hold that will not clear on its own.
+ await writeSettings(settings({ held: true }));
+ await seedTranscript("vidA");
+ await fetch(`${baseUrl}/api/test/invalidate-cache`).catch(() => {});
+ await generateReport(page, SLUG);
+
+ await page.goto(`/channels/${SLUG}`);
+ await expect(page.getByText(/held for speakers \(1 video\)/).first()).toBeVisible({ timeout: 30_000 });
+
+ await page.goto("/cleanup");
+ const readout = page.getByLabel("speakers readout");
+ await expect(readout).toContainText("waiting:", { timeout: 30_000 });
+ await expect(readout).toContainText("in 1 video");
+ await expect(readout.getByRole("button", { name: "work through speakers" })).toBeVisible();
+ await expect(page.getByLabel("audio hold sieve").locator('li[data-gate="4"]')).toContainText("will not clear on its own");
+
+ await page.goto("/");
+ await expect(page.getByLabel("speakers readout")).toContainText("waiting:", { timeout: 30_000 });
+});
+
+test("Work through speakers refuses an un-narrowed lane, in one sentence naming the command", async ({ page }) => {
+ test.setTimeout(SLOW);
+ await resetData("one-transcribe-channel-with-audio");
+ await writeSettings(settings({ held: true, narrowed: false }));
+ await seedTranscript("vidA");
+ await generateReport(page, SLUG);
+ await page.goto(channelStage(SLUG, "speakers"));
+ const paused = page.getByLabel("speakers lane paused");
+ await paused.getByRole("button", { name: "work through speakers" }).click();
+ await expect(page.getByText(/is not narrowed to speaker diarization/).first()).toBeVisible({ timeout: 30_000 });
+ await expect(page.getByText(/"operations":\["diarization"\]/).first()).toBeVisible();
+ expect((await lane()).held).toBe(true);
+ expect((await lane()).enabled ?? false).toBe(false);
+});
+
diff --git a/editor/e2e/widget.spec.ts b/editor/e2e/widget.spec.ts
@@ -798,7 +798,12 @@ test("backfill=1 alone renders the Backfill strip", async ({ page }) => {
test("the widget's controls hold and release the backfill lane", async ({
page,
}) => {
- await writeSettings({ ...TWO_WORKERS, ...BACKFILL_SETTINGS });
+ // Narrowed to diarization: Work through speakers refuses an un-narrowed lane.
+ await writeSettings({
+ ...TWO_WORKERS,
+ ...BACKFILL_SETTINGS,
+ autoQueue: { backfill: { held: false, operations: ["diarization"] } },
+ });
// Assert the KEY, not just the label: the button writes the same
// `autoQueue.backfill.held` the "Run the backfill lane" checkbox does, and
@@ -813,16 +818,24 @@ test("the widget's controls hold and release the backfill lane", async ({
).autoQueue?.backfill?.held ?? false;
await page.goto("/widget?controls=1&backfill=1");
- const pause = page.getByRole("button", { name: "pause backfill" });
- await expect(pause).toBeEnabled({ timeout: 30_000 });
- await pause.click();
+ // The Speakers lane's one control (the deck's): Work through speakers arms
+ // the lane and lifts its hold; Pause holds it.
+ const work = page.getByRole("button", { name: "work through speakers" });
+ await expect(work).toBeEnabled({ timeout: 30_000 });
+ await work.click();
+ await expect.poll(laneHeld, { timeout: 30_000 }).toBe(false);
- await expect.poll(laneHeld, { timeout: 30_000 }).toBe(true);
// The label flips immediately, because the click refetches the payload it
// reads rather than waiting out the 15s poll floor.
- const resume = page.getByRole("button", { name: "resume backfill" });
- await expect(resume).toBeVisible({ timeout: 15_000 });
+ const pause = page.getByRole("button", { name: "pause speakers" });
+ await expect(pause).toBeVisible({ timeout: 15_000 });
+ await pause.click();
+ await expect.poll(laneHeld, { timeout: 30_000 }).toBe(true);
- await resume.click();
- await expect.poll(laneHeld, { timeout: 30_000 }).toBe(false);
+ // Disarm, so an armed lane does not bleed into the next spec.
+ const off = await page.request.post(`${baseUrl}/api/ops/lane`, {
+ headers: { authorization: "Bearer test-worker-token" },
+ data: { lane: "backfill", enabled: false },
+ });
+ expect(off.status()).toBe(200);
});
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -99,6 +99,11 @@
// pnpm ops channel-rank --json '{"slug":"x","after":"other-channel"}'
// pnpm ops channel-rank --json '{"slug":"x","rank":null}'
// pnpm ops lane --json '{"lane":"download","held":true}'
+// pnpm ops lane --json '{"lane":"backfill","operations":["diarization"],"order":"space"}'
+// pnpm ops lane --json '{"lane":"backfill","speakers":"work"}'
+// pnpm ops get speakers
+// pnpm ops diarize --json '{"slug":"x"}' --wait
+// pnpm ops settings --json '{"patch":{"diarization":{"cleanAfterCapture":true}}}'
// pnpm ops render-mode --json '{"on":true,"for":"90m","note":"the Ember cut"}'
// pnpm ops render-mode --json '{"on":false}'
// pnpm ops get render-mode
@@ -306,6 +311,8 @@ const GETTERS = {
"x-run": (run) => (run ? `/api/ops/x-run?run=${encodeURIComponent(run)}` : "/api/ops/x-run"),
// One channel's cleanup row: what each sweep would reclaim, what holds the rest.
cleanup: (slug) => `/api/ops/cleanup/${encodeURIComponent(slug)}`,
+ // The speakers readout: waiting, freed this run, rate, days left, per channel.
+ speakers: () => "/api/ops/speakers",
// What a channel holds, by date, and its gaps (release 19 A9): each video
// dated by its recorded date when the channel has a title rule, else upload.
coverage: (slug) => `/api/ops/coverage?slug=${encodeURIComponent(slug)}`,
@@ -357,6 +364,7 @@ const GET_ARG_OPTIONAL = new Set([
"x-run",
"generation-usage",
"render-mode",
+ "speakers",
]);
// The flags each noun takes beyond the shared ones; any other is refused.
@@ -576,6 +584,9 @@ const ACTIONS = [
"do-not-clean",
"drop-saved-alternate",
"cleanup",
+ // The Cleanup stage's "Diarize speakers" for one channel: diarization and
+ // voice fingerprints for the videos still holding audio.
+ "diarize",
// WEB READS (release 27 S3): a DuckDuckGo search ({query, n?}) and one
// page as text ({url, maxChars?}), read only, through the editor's one
// paced web queue. Synchronous; no job.
@@ -1072,6 +1083,7 @@ export function usage() {
" pnpm ops get x-session [<slug>]",
" pnpm ops get x-run [<run id>]",
" pnpm ops get cleanup <slug>",
+ " pnpm ops get speakers",
" pnpm ops get remote-listing <slug> [--wait-timeout <seconds>]",
" pnpm ops get transcript <videoId> [--slug <slug>]",
" pnpm ops get coverage <slug>",
@@ -1157,6 +1169,14 @@ export function usage() {
" rank, slug), \"jar\" (its age, social.x.maxCookieAgeMinutes, staleAt:",
" when it passes the limit, and whether an X job would start now),",
" gapSeconds (X's queue gap) and maxPosts. Nothing is asked of X.",
+ "get speakers is the speakers readout the lane deck and /cleanup print",
+ " (\"line\": waiting: X GB in N videos · freed this run: Y GB · about D",
+ " days left) and its numbers: waiting (audio held for the Speakers lane",
+ " that it will clear), neverClears, freed this run, the measured seconds",
+ " of engine per audio-hour, audio-hours and days left, voiceprinted and",
+ " noFingerprintPossible (diarized, audio already gone), per channel with",
+ " corpus-disk channels first; and the lane: armed, held, the operations",
+ " it dispatches, its order, cleanAfterCapture and requireVoiceprints.",
"get cleanup <slug> is one channel's /cleanup row: what each sweep would",
" reclaim (they overlap — never add them), what holds the rest, and the",
" failed-transcriptions count. measured: false means unknown, not zero.",
@@ -1235,12 +1255,18 @@ export function usage() {
'lane takes {"lane": "transcription"|"download"|"digest"|"backfill"|',
' "publish", "enabled"?, "held"?, "action"?: "start"|"stop"|"drain"}, or',
' {"lane": "report-schedule", "held"}: the recurring reports\' gate, its only key.',
+ ' An auto-queue lane also takes "operations": [ids] | null (dispatch only',
+ ' these — ["diarization"] is speakers only; null widens it again) and',
+ ' "order" ("space" on backfill: corpus-disk channels first, then the most',
+ ' audio bytes per audio-hour). The backfill (Speakers) lane takes',
+ ' "speakers": "work" (the deck\'s Work through speakers: arm, lift the hold,',
+ ' start a run) | "pause" (hold; stays armed).',
"",
'render-mode gives a render the operator is waiting for the machine:',
' {"on": true, "for"?: "90m" | <minutes>, "note"?} opens a window (default',
' 2h) in which every other heavy job — e2e suites, next builds, the publish',
' stages, other renders — waits at the heavy slot\'s door, and holds the',
- ' transcription and download lanes (only the ones not already held; only',
+ ' transcription, download and Speakers lanes (only the ones not already held; only',
' those are released). The answer\'s "join" (RENDER_PRIORITY_TOKEN=…) lets a',
' render in, on the floor 4000 MB and the cap 10240 MB; every `umtool take`',
' joins by itself. {"on": false} ends it ("force": true ends a running',
@@ -1323,6 +1349,12 @@ export function usage() {
' gone is cleaned from the pointer ("existed": false). "dryRun": true',
' answers the same and changes nothing. No undo.',
"",
+ '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.',
+ "",
'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',
diff --git a/scripts/diarize-sherpa.py b/scripts/diarize-sherpa.py
@@ -43,9 +43,25 @@ Usage:
[--threads N] [--ffmpeg PATH] [--ffprobe PATH]
[--window-minutes M] [--window-after-minutes M]
<audioFile>
+ diarize-sherpa.py --voiceprints-only <diarization.json> --emb <model.onnx>
+ [--threads N] [--ffmpeg PATH] <audioFile>
Output: {"turns":[{"start":s,"end":s,"speaker":i}], "audioSeconds":f,
- "version":"...", "sampleRate":n, "windowing":{...}|null}
+ "version":"...", "sampleRate":n, "windowing":{...}|null,
+ "voiceprints":[{"speaker":i,"seconds":f,"embedded":n,
+ "centroid":[192 floats]|null}]}
+ --voiceprints-only prints {"voiceprints":[...], "version":"..."} for the
+ turns of an EXISTING record: no segmentation, no clustering, the turns are
+ not touched.
+
+VOICEPRINTS, AND WHY THEY ARE KEPT
+----------------------------------
+A voiceprint is one TitaNet embedding per FINAL speaker: the robust mean of
+that speaker's longest turns (see speaker_voiceprints). It is the one thing a
+diarization cannot recompute once the audio is deleted, and the cleanup sweep
+deletes the audio, so it is captured here, while the samples are in memory.
+It is computed AFTER the turns are final and never feeds back into them: the
+turns a file produced before voiceprints existed are the turns it produces now.
"""
import argparse, json, subprocess, sys, time
@@ -60,6 +76,18 @@ EMB_MIN_SEC = 0.5
# does not leave a visible split that the same audio processed whole would not
# have had.
MERGE_GAP_SEC = 0.5
+# A voiceprint embeds a speaker's VP_MAX_SEGMENTS longest turns, each capped at
+# VP_MAX_SEC, and drops the ones more than VP_TRIM under the median similarity to
+# the first mean before taking the mean again -- the same robust centroid as
+# common/lib/montage/voiceMatch.mjs's robustCentroid (REFERENCE_TRIM 0.15), so a
+# voiceprint and a voice-match reference mean the same thing.
+VP_MAX_SEGMENTS = 8
+VP_MAX_SEC = 10.0
+VP_TRIM = 0.15
+# 4 decimals: a cosine between two rounded unit vectors moves by < 1e-3, far
+# under any threshold that reads them (0.30 / 0.42), and a 192-float centroid
+# stays ~1.5 KB on disk.
+VP_DECIMALS = 4
def decode_whole_file(np, ffmpeg, audio, sample_rate):
@@ -195,10 +223,140 @@ def speaker_centroid(np, extractor, samples, sample_rate, segments):
if norm > 0:
vecs.append(v / norm)
if not vecs:
- return None
+ return None, 0
mean = np.mean(np.stack(vecs), axis=0)
norm = float(np.linalg.norm(mean))
- return mean / norm if norm > 0 else None
+ return (mean / norm if norm > 0 else None), len(vecs)
+
+
+def unit(np, v):
+ n = float(np.linalg.norm(v))
+ return v / n if n > 0 else None
+
+
+def robust_centroid(np, vecs, trim=VP_TRIM):
+ """voiceMatch.mjs's robustCentroid: the mean, then every vector more than
+ `trim` under the median similarity to it dropped, then the mean of the rest.
+ Fewer than three vectors are simply averaged (no median worth trusting)."""
+ if not vecs:
+ return None
+ first = unit(np, np.mean(np.stack(vecs), axis=0))
+ if first is None or len(vecs) < 3:
+ return first
+ sims = [float(np.dot(v, first)) for v in vecs]
+ floor = float(np.median(sims)) - trim
+ kept = [v for v, s in zip(vecs, sims) if s >= floor]
+ return unit(np, np.mean(np.stack(kept), axis=0)) if kept else first
+
+
+def embed_samples(np, extractor, sample_rate, x):
+ """One L2-normalized embedding of a stretch of samples, or None."""
+ if x.size < int(EMB_MIN_SEC * sample_rate):
+ return None
+ stream = extractor.create_stream()
+ stream.accept_waveform(sample_rate, x)
+ stream.input_finished()
+ if not extractor.is_ready(stream):
+ return None
+ return unit(np, np.asarray(extractor.compute(stream), dtype=np.float32))
+
+
+def voiceprint_spans(turns):
+ """{speaker: [(start, end)]}: the excerpts a voiceprint embeds. A speaker's
+ longest turns, each cut to VP_MAX_SEC from its start; spans under
+ EMB_MIN_SEC are not worth an embedding and are left out here."""
+ by_speaker = {}
+ for t in turns:
+ by_speaker.setdefault(int(t["speaker"]), []).append((float(t["start"]), float(t["end"])))
+ out = {}
+ for spk, spans in by_speaker.items():
+ picked = sorted(spans, key=lambda s: (s[0] - s[1], s[0]))[:VP_MAX_SEGMENTS]
+ out[spk] = [(a, min(b, a + VP_MAX_SEC)) for a, b in picked
+ if min(b, a + VP_MAX_SEC) - a >= EMB_MIN_SEC]
+ return out
+
+
+def speaker_seconds(turns):
+ """{speaker: talk seconds}, from the FINAL turns."""
+ out = {}
+ for t in turns:
+ spk = int(t["speaker"])
+ out[spk] = out.get(spk, 0.0) + max(0.0, float(t["end"]) - float(t["start"]))
+ return out
+
+
+def voiceprint_records(turns, vectors):
+ """The `voiceprints` array: one entry per speaker in `turns`, in speaker
+ order. `vectors` is {speaker: (unit vector or None, excerpts embedded)}; a
+ speaker with nothing embeddable gets centroid null -- present and honest,
+ so "no voiceprint for this one" is a recorded fact, not a missing field."""
+ secs = speaker_seconds(turns)
+ out = []
+ for spk in sorted(secs):
+ vec, n = vectors.get(spk, (None, 0))
+ out.append({
+ "speaker": spk,
+ "seconds": round(secs[spk], 3),
+ "embedded": int(n),
+ "centroid": None if vec is None
+ else [round(float(e), VP_DECIMALS) for e in vec],
+ })
+ return out
+
+
+class VoiceprintRefused(Exception):
+ """The audio does not match the turns it is asked to fingerprint (exit 6):
+ nothing is written, so a fingerprint is never recorded from the wrong
+ stretches of a recording."""
+
+
+# An excerpt that comes back with less than this share of its samples was cut
+# from past the end of the file (or a truncated one): the turns were not made
+# from this audio.
+VP_MIN_FILL = 0.9
+
+
+def check_excerpt(x, a, b, sample_rate, strict):
+ if strict and x.size < VP_MIN_FILL * (b - a) * sample_rate:
+ raise VoiceprintRefused(
+ f"excerpt {a:.2f}-{b:.2f}s decoded {x.size / sample_rate:.2f}s of "
+ f"{b - a:.2f}s — the turns were not made from this file"
+ )
+
+
+def voiceprints_from_samples(np, extractor, samples, sample_rate, turns, strict=False):
+ """Voiceprints for a recording whose samples are in memory (the whole-file
+ path): each speaker's excerpts sliced out and embedded. `strict` (the
+ voiceprints-only mode) refuses a short excerpt."""
+ vectors = {}
+ for spk, spans in voiceprint_spans(turns).items():
+ vecs = []
+ for a, b in spans:
+ i, j = int(a * sample_rate), min(int(b * sample_rate), samples.size)
+ x = samples[i:j] if j > i else samples[0:0]
+ check_excerpt(x, a, b, sample_rate, strict)
+ v = embed_samples(np, extractor, sample_rate, x)
+ if v is not None:
+ vecs.append(v)
+ vectors[spk] = (robust_centroid(np, vecs), len(vecs))
+ return voiceprint_records(turns, vectors)
+
+
+def voiceprints_from_file(np, extractor, ffmpeg, audio, sample_rate, turns, strict=True):
+ """Voiceprints for an EXISTING record's turns, decoding only the excerpts
+ (an input seek per excerpt, as the windowed path does), so a nine-hour file
+ costs a few hundred seconds of audio, not nine hours of memory."""
+ vectors = {}
+ for spk, spans in voiceprint_spans(turns).items():
+ vecs = []
+ for a, b in spans:
+ x = decode_window(np, ffmpeg, audio, sample_rate, a, b - a)
+ check_excerpt(x, a, b, sample_rate, strict)
+ v = embed_samples(np, extractor, sample_rate, x)
+ if v is not None:
+ vecs.append(v)
+ vectors[spk] = (robust_centroid(np, vecs), len(vecs))
+ return voiceprint_records(turns, vectors)
def merge_and_renumber(turns):
@@ -246,7 +404,7 @@ def merge_and_renumber(turns):
merged.append({"start": cur_start, "end": cur_end, "speaker": speaker})
merged.sort(key=lambda t: (t["start"], t["end"], t["speaker"]))
- return merged
+ return merged, order
def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
@@ -268,6 +426,7 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
kept = [] # {"start","end","key"} in ABSOLUTE seconds
centroids = [] # parallel to keys
keys = [] # (window index, local speaker)
+ embedded = {} # key -> excerpts its centroid was made from
decoded_sec = 0.0
for wi, (ws, dur, own_s, own_e) in enumerate(windows):
@@ -296,11 +455,12 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
# every turn belongs to the neighbouring window would otherwise add a
# cluster that names nothing.
for spk, spk_segs in owned_by_speaker.items():
- c = speaker_centroid(np, extractor, samples, sample_rate, spk_segs)
+ c, n = speaker_centroid(np, extractor, samples, sample_rate, spk_segs)
if c is None:
continue
centroids.append(c)
keys.append((wi, spk))
+ embedded[(wi, spk)] = n
elapsed = time.time() - t0
print(
@@ -312,7 +472,7 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
del samples, result, segs
if not kept:
- return [], decoded_sec, len(windows)
+ return [], [], decoded_sec, len(windows)
# Cross-window identity. Same clusterer and same threshold as within a
# window, so "these two are the same person" means the same thing at both
@@ -338,13 +498,138 @@ def run_windowed(np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec):
t["speaker"] = global_of[t["key"]]
del t["key"]
- return merge_and_renumber(kept), decoded_sec, len(windows)
+ merged, order = merge_and_renumber(kept)
+
+ # ONE voiceprint per FINAL speaker: the robust mean of the local centroids
+ # that clustered into it. Those centroids are what decided the identity
+ # across seams, so they are the voiceprint of exactly that identity. A
+ # spare (a local speaker with no usable centroid) has none.
+ by_label = {}
+ for key, c in zip(keys, centroids):
+ by_label.setdefault(global_of[key], []).append((c, embedded.get(key, 0)))
+ vectors = {}
+ for label, final in order.items():
+ members = by_label.get(label, [])
+ vectors[final] = (
+ robust_centroid(np, [c for c, _ in members]),
+ sum(n for _, n in members),
+ )
+ return merged, vectors, decoded_sec, len(windows)
+
+
+def print_voiceprint_line(voiceprints, elapsed):
+ # Not "window i/n": common/jobs/progressParsers.ts reads those lines as a bar.
+ have = sum(1 for v in voiceprints if v["centroid"] is not None)
+ print(
+ f"diarize-sherpa: voiceprints for {have} of {len(voiceprints)} speaker(s) "
+ f"in {elapsed:.1f}s",
+ file=sys.stderr, flush=True,
+ )
+
+
+def run_voiceprints_only(args):
+ """Voiceprints for an existing record's turns. No segmentation model, no
+ clustering: the turns are read, never changed."""
+ try:
+ import numpy as np
+ import sherpa_onnx
+ except ImportError as e:
+ print(f"diarize-sherpa: missing dependency: {e}", file=sys.stderr)
+ return 3
+ try:
+ with open(args.voiceprints_only, "r", encoding="utf8") as f:
+ record = json.load(f)
+ turns = record["turns"]
+ except Exception as e:
+ print(f"diarize-sherpa: cannot read turns from {args.voiceprints_only}: {e}",
+ file=sys.stderr)
+ return 2
+ cfg = sherpa_onnx.SpeakerEmbeddingExtractorConfig(
+ model=args.emb, num_threads=args.threads
+ )
+ if not cfg.validate():
+ print("diarize-sherpa: invalid embedding model config", file=sys.stderr)
+ return 2
+ extractor = sherpa_onnx.SpeakerEmbeddingExtractor(cfg)
+ t0 = time.time()
+ sample_rate = 16000
+ # A file the whole-file path would have taken is decoded whole here too, so
+ # its voiceprints are the very numbers a fresh diarization would record (an
+ # mp3 input seek is not sample-exact, and a short turn's embedding moves
+ # with a few ms of offset). Longer files seek per excerpt, as windowing does.
+ total_sec = probe_duration(args.ffprobe, args.audio)
+ # THE SAME RECORDING, OR NOTHING (review B3). A record's turns are seconds on
+ # the clock of the file they were made from; another file of the same video
+ # (a re-download, a container, a truncated copy) can run seconds apart, and
+ # centroids cut from it would be other people's voices.
+ recorded = record.get("audioSeconds")
+ if total_sec is not None and (
+ not isinstance(recorded, (int, float)) or abs(total_sec - recorded) > 1.0
+ ):
+ print(
+ f"diarize-sherpa: refused: the file is {total_sec:.3f}s, the record's audio "
+ f"{recorded if recorded is not None else 'unknown'}s — not the audio these "
+ "turns were made from",
+ file=sys.stderr,
+ )
+ return 6
+ whole = (
+ total_sec is not None
+ and total_sec <= args.window_after_minutes * 60.0
+ )
+ try:
+ if whole:
+ samples = decode_whole_file(np, args.ffmpeg, args.audio, sample_rate)
+ if samples is None or samples.size == 0:
+ print("diarize-sherpa: decoded zero samples", file=sys.stderr)
+ return 5 if samples is not None else 4
+ voiceprints = voiceprints_from_samples(
+ np, extractor, samples, sample_rate, turns, strict=True
+ )
+ del samples
+ elif total_sec is None:
+ # ffprobe cannot read it: neither can ffmpeg, and seeking into it
+ # would only produce silence to embed.
+ print("diarize-sherpa: cannot measure the audio (unreadable?)",
+ file=sys.stderr)
+ return 4
+ else:
+ voiceprints = voiceprints_from_file(
+ np, extractor, args.ffmpeg, args.audio, sample_rate, turns
+ )
+ except VoiceprintRefused as e:
+ print(f"diarize-sherpa: refused: {e}", file=sys.stderr)
+ return 6
+ except RuntimeError as e:
+ print(f"diarize-sherpa: {e}", file=sys.stderr)
+ return 4
+ # A speaker with a turn long enough to embed MUST come out with a centroid:
+ # a null there is a fingerprint that was not made, and recording it as done
+ # would let the audio go.
+ spans = voiceprint_spans(turns)
+ missing = [v["speaker"] for v in voiceprints if v["centroid"] is None and spans.get(v["speaker"])]
+ if missing:
+ print(
+ f"diarize-sherpa: refused: no embedding for speaker(s) {missing} "
+ "although their turns are long enough",
+ file=sys.stderr,
+ )
+ return 6
+ print_voiceprint_line(voiceprints, time.time() - t0)
+ json.dump(
+ {"voiceprints": voiceprints,
+ "probedSeconds": round(total_sec, 3) if total_sec is not None else None,
+ "version": getattr(sherpa_onnx, "__version__", None)},
+ sys.stdout,
+ )
+ return 0
def main():
ap = argparse.ArgumentParser()
ap.add_argument("audio")
- ap.add_argument("--seg", required=True)
+ ap.add_argument("--seg")
+ ap.add_argument("--voiceprints-only", metavar="DIARIZATION_JSON")
ap.add_argument("--emb", required=True)
ap.add_argument("--threshold", type=float, default=0.5)
ap.add_argument("--threads", type=int, default=4)
@@ -363,6 +648,11 @@ def main():
ap.add_argument("--window-overlap-seconds", type=float, default=30.0)
args = ap.parse_args()
+ if args.voiceprints_only:
+ return run_voiceprints_only(args)
+ if not args.seg:
+ ap.error("--seg is required")
+
try:
import numpy as np
import sherpa_onnx
@@ -409,7 +699,7 @@ def main():
# to separate them.
t0 = time.time()
try:
- turns, audio_seconds, window_count = run_windowed(
+ turns, vectors, audio_seconds, window_count = run_windowed(
np, sherpa_onnx, sd, args, total_sec, window_sec, overlap_sec
)
except RuntimeError as e:
@@ -448,6 +738,19 @@ def main():
for s in result
]
windowing = None
+ # After the turns are final and outside the engine timing above, so
+ # `elapsed` keeps meaning what plans/ recorded it as.
+ t1 = time.time()
+ extractor = sherpa_onnx.SpeakerEmbeddingExtractor(
+ sherpa_onnx.SpeakerEmbeddingExtractorConfig(
+ model=args.emb, num_threads=args.threads
+ )
+ )
+ voiceprints = voiceprints_from_samples(
+ np, extractor, samples, sd.sample_rate, turns
+ )
+ vp_elapsed = time.time() - t1
+ del samples
if windowed:
turns = [
@@ -455,6 +758,8 @@ def main():
"speaker": int(t["speaker"])}
for t in turns
]
+ voiceprints = voiceprint_records(turns, vectors)
+ vp_elapsed = 0.0
speakers = len({t["speaker"] for t in turns})
print(
@@ -463,6 +768,8 @@ def main():
file=sys.stderr, flush=True,
)
+ print_voiceprint_line(voiceprints, vp_elapsed)
+
json.dump(
{
"turns": turns,
@@ -470,6 +777,7 @@ def main():
"sampleRate": sd.sample_rate,
"version": getattr(sherpa_onnx, "__version__", None),
"windowing": windowing,
+ "voiceprints": voiceprints,
},
sys.stdout,
)
diff --git a/scripts/diarize-sherpa.test.mjs b/scripts/diarize-sherpa.test.mjs
@@ -0,0 +1,300 @@
+// scripts/diarize-sherpa.py's voiceprints, through scripts/diarize.mjs.
+//
+// Two engines run these tests. The STUB (scripts/fixtures/sherpa-stub, on the
+// system python with numpy) is the default: a "voice" is a pure tone, so the
+// test can say who speaks when, and every number is exact. The REAL engine
+// (sherpa-onnx + TitaNet-small) runs the last test when DIARIZE_PYTHON,
+// DIARIZE_SEG_MODEL and DIARIZE_EMB_MODEL name it, on two espeak-ng voices.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { execFileSync, spawnSync } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+
+const HERE = import.meta.dirname;
+const SCRIPT = path.join(HERE, "diarize-sherpa.py");
+const WRAPPER = path.join(HERE, "diarize.mjs");
+const STUB = path.join(HERE, "fixtures", "sherpa-stub");
+
+function has(cmd, args) {
+ return spawnSync(cmd, args, { stdio: "ignore" }).status === 0;
+}
+const hasFfmpeg = has("ffmpeg", ["-version"]) && has("ffprobe", ["-version"]);
+const hasNumpy = has("python3", ["-c", "import numpy"]);
+const skip = !(hasFfmpeg && hasNumpy) && "needs ffmpeg, ffprobe and python3 with numpy";
+
+const SR = 16000;
+// [start, end, hz]: who is speaking when. 300 Hz and 1000 Hz are two voices;
+// the 2000 Hz blip is a third whose only turn is too short to embed.
+const PLAN = [
+ [0, 4, 300],
+ [4.5, 8, 1000],
+ [8.5, 11, 300],
+ [11.5, 13, 1000],
+ [13.5, 13.75, 2000],
+];
+
+function writeWav(file, plan, total = 14) {
+ const n = Math.round(total * SR);
+ const pcm = Buffer.alloc(n * 2);
+ for (const [a, b, hz] of plan) {
+ for (let i = Math.round(a * SR); i < Math.round(b * SR); i += 1) {
+ pcm.writeInt16LE(Math.round(0.5 * 32767 * Math.sin((2 * Math.PI * hz * i) / SR)), i * 2);
+ }
+ }
+ const h = Buffer.alloc(44);
+ h.write("RIFF", 0);
+ h.writeUInt32LE(36 + pcm.length, 4);
+ h.write("WAVEfmt ", 8);
+ h.writeUInt32LE(16, 16);
+ h.writeUInt16LE(1, 20);
+ h.writeUInt16LE(1, 22);
+ h.writeUInt32LE(SR, 24);
+ h.writeUInt32LE(SR * 2, 28);
+ h.writeUInt16LE(2, 32);
+ h.writeUInt16LE(16, 34);
+ h.write("data", 36);
+ h.writeUInt32LE(pcm.length, 40);
+ writeFileSync(file, Buffer.concat([h, pcm]));
+}
+
+const env = { ...process.env, PYTHONPATH: STUB, PYTHONDONTWRITEBYTECODE: "1" };
+
+function engine(args) {
+ return JSON.parse(execFileSync("python3", [SCRIPT, ...args], { env, stdio: ["ignore", "pipe", "pipe"] }).toString());
+}
+
+const dot = (a, b) => a.reduce((s, x, i) => s + x * b[i], 0);
+
+function withDir(fn) {
+ const dir = mkdtempSync(path.join(os.tmpdir(), "diarize-sherpa-test-"));
+ try {
+ return fn(dir);
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+test("whole file: one voiceprint per speaker, unit length, voices apart; a too-short speaker is recorded with a null centroid", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const out = engine(["--seg", "seg.onnx", "--emb", "emb.onnx", wav]);
+ // The turns are the engine's own, untouched by the voiceprint pass.
+ assert.deepEqual(
+ out.turns.map((t) => [t.start, t.end, t.speaker]),
+ [[0, 4, 0], [4.5, 8, 1], [8.5, 11, 0], [11.5, 13, 1], [13.5, 13.75, 2]],
+ );
+ assert.equal(out.windowing, null);
+ assert.deepEqual(out.voiceprints.map((v) => [v.speaker, v.seconds, v.embedded]), [[0, 6.5, 2], [1, 5, 2], [2, 0.25, 0]]);
+ const [a, b, c] = out.voiceprints;
+ assert.equal(a.centroid.length, 192);
+ assert.ok(Math.abs(dot(a.centroid, a.centroid) - 1) < 1e-3);
+ assert.ok(dot(a.centroid, b.centroid) < 0.2, "two voices are apart");
+ assert.equal(c.centroid, null);
+ // Rounded to 4 decimals, so the same input prints the same bytes.
+ assert.ok(a.centroid.every((x) => Math.round(x * 1e4) / 1e4 === x));
+ }));
+
+test("windowed: one voiceprint per FINAL cluster, and it is the same voice as the whole-file one", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN.slice(0, 4));
+ const whole = engine(["--seg", "s", "--emb", "e", wav]);
+ const win = engine(["--seg", "s", "--emb", "e", "--window-minutes", "0.1", "--window-after-minutes", "0", "--window-overlap-seconds", "1", wav]);
+ assert.equal(win.windowing.windows, 3);
+ const speakers = [...new Set(win.turns.map((t) => t.speaker))].sort();
+ assert.deepEqual(speakers, [0, 1]);
+ assert.deepEqual(win.voiceprints.map((v) => v.speaker), [0, 1]);
+ for (const v of win.voiceprints) {
+ assert.ok(v.embedded >= 2, `speaker ${v.speaker} was embedded from more than one window's turns`);
+ const same = whole.voiceprints.find((w) => w.speaker === v.speaker);
+ assert.ok(dot(v.centroid, same.centroid) > 0.99, `speaker ${v.speaker} matches its whole-file voiceprint`);
+ }
+ assert.equal(
+ win.voiceprints.find((v) => v.speaker === 0).seconds,
+ whole.voiceprints.find((v) => v.speaker === 0).seconds,
+ );
+ }));
+
+test("diarize.mjs records the voiceprints with the embedding model's basename, outside `engine`", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const out = path.join(dir, "diarization.json");
+ execFileSync(process.execPath, [WRAPPER, "--python", "python3", "--seg", "/m/seg.onnx", "--emb", "/m/titanet.onnx", "--threshold", "0.9", "--output", out, "--video-id", "v1", wav], { env, stdio: "ignore" });
+ const rec = JSON.parse(readFileSync(out, "utf8"));
+ assert.equal(rec.voiceprints.length, 3);
+ assert.ok(rec.voiceprints.every((v) => v.embeddingModel === "titanet.onnx"));
+ assert.equal(typeof rec.voiceprintsAt, "string");
+ assert.deepEqual(Object.keys(rec.voiceprintsFrom).sort(), ["bytes", "durationSeconds", "file"]);
+ assert.equal(rec.voiceprintsFrom.file, "a.wav");
+ assert.equal(rec.engine.embeddingModel, "titanet.onnx");
+ assert.equal("voiceprints" in rec.engine, false);
+ }));
+
+test("--voiceprints-only adds voiceprints to an existing record from its own turns, keeping turns and generatedAt", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const whole = engine(["--seg", "s", "--emb", "e", wav]);
+ const rec = path.join(dir, "diarization.json");
+ const before = {
+ videoId: "v1",
+ generatedAt: "2026-08-07T00:00:00.000Z",
+ audioSeconds: whole.audioSeconds,
+ speakers: 3,
+ turns: whole.turns,
+ engine: { engine: "sherpa-onnx", embeddingModel: "titanet.onnx", threshold: 0.9 },
+ };
+ writeFileSync(rec, JSON.stringify(before) + "\n");
+ execFileSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/titanet.onnx", wav], { env, stdio: "ignore" });
+ const after = JSON.parse(readFileSync(rec, "utf8"));
+ assert.equal(after.generatedAt, before.generatedAt);
+ assert.deepEqual(after.turns, before.turns);
+ assert.deepEqual(after.engine, before.engine);
+ assert.deepEqual(
+ after.voiceprints.map((v) => [v.speaker, v.seconds, v.embedded, v.embeddingModel]),
+ [[0, 6.5, 2, "titanet.onnx"], [1, 5, 2, "titanet.onnx"], [2, 0.25, 0, "titanet.onnx"]],
+ );
+ // Decoded per excerpt rather than whole, and the same voice either way.
+ for (const v of after.voiceprints.filter((x) => x.centroid)) {
+ assert.ok(dot(v.centroid, whole.voiceprints[v.speaker].centroid) > 0.999);
+ }
+ // Which file they were cut from.
+ assert.equal(after.voiceprintsFrom.file, "a.wav");
+ assert.equal(after.voiceprintsFrom.bytes, readFileSync(wav).length);
+ assert.ok(Math.abs(after.voiceprintsFrom.durationSeconds - 14) < 0.01);
+ }));
+
+test("--voiceprints-only on a zero-byte audio fails and leaves the record exactly as it was", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "empty.mp3");
+ writeFileSync(wav, "");
+ const rec = path.join(dir, "diarization.json");
+ const body = JSON.stringify({ videoId: "v1", generatedAt: "x", speakers: 1, turns: [{ start: 0, end: 3, speaker: 0 }], engine: { engine: "sherpa-onnx" } }) + "\n";
+ writeFileSync(rec, body);
+ const r = spawnSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/t.onnx", wav], { env, stdio: "ignore" });
+ assert.notEqual(r.status, 0);
+ assert.equal(readFileSync(rec, "utf8"), body);
+ }));
+
+const REAL = (() => {
+ const python = process.env.DIARIZE_PYTHON;
+ const seg = process.env.DIARIZE_SEG_MODEL;
+ const emb = process.env.DIARIZE_EMB_MODEL;
+ if (!python || !seg || !emb || ![python, seg, emb].every(existsSync)) return null;
+ if (!has("espeak-ng", ["--version"]) || !hasFfmpeg) return null;
+ return { python, seg, emb };
+})();
+
+test("the real engine (sherpa-onnx + TitaNet-small): two espeak voices, a 192-float voiceprint per speaker", { skip: !REAL && "set DIARIZE_PYTHON, DIARIZE_SEG_MODEL and DIARIZE_EMB_MODEL (and install espeak-ng) to run it" }, () =>
+ withDir((dir) => {
+ const parts = [
+ ["en-us", "The quick brown fox jumps over the lazy dog while the band plays on into the night."],
+ ["en+f4", "Nobody expected the committee to vote that way, but here we are again this morning."],
+ ["en-us", "Then the fox came back and asked whether anyone had seen his other shoe, which was red."],
+ ];
+ const files = parts.map(([voice, text], i) => {
+ const f = path.join(dir, `p${i}.wav`);
+ execFileSync("espeak-ng", ["-v", voice, "-s", "150", "-w", f, text]);
+ return f;
+ });
+ const list = path.join(dir, "list.txt");
+ writeFileSync(list, files.map((f) => `file '${f}'`).join("\n"));
+ const wav = path.join(dir, "talk.wav");
+ execFileSync("ffmpeg", ["-v", "error", "-f", "concat", "-safe", "0", "-i", list, "-ar", "16000", "-ac", "1", wav]);
+ const out = path.join(dir, "diarization.json");
+ execFileSync(process.execPath, [WRAPPER, "--python", REAL.python, "--seg", REAL.seg, "--emb", REAL.emb, "--threshold", "0.9", "--output", out, "--video-id", "real", wav], { stdio: "ignore" });
+ const rec = JSON.parse(readFileSync(out, "utf8"));
+ const speakers = new Set(rec.turns.map((t) => t.speaker));
+ assert.ok(speakers.size >= 1);
+ assert.equal(rec.voiceprints.length, speakers.size);
+ const real = rec.voiceprints.filter((v) => v.centroid);
+ assert.ok(real.length >= 1);
+ for (const v of real) {
+ assert.equal(v.centroid.length, 192);
+ assert.ok(Math.abs(dot(v.centroid, v.centroid) - 1) < 1e-2);
+ }
+ }));
+
+// ---- review B3: refuse rather than record a fingerprint from the wrong audio --
+
+function vpOnly(dir, wav, record, extraEnv = {}) {
+ const rec = path.join(dir, "diarization.json");
+ const body = JSON.stringify(record) + "\n";
+ writeFileSync(rec, body);
+ const r = spawnSync(process.execPath, [WRAPPER, "--voiceprints-only", rec, "--python", "python3", "--emb", "/m/t.onnx", wav], {
+ env: { ...env, ...extraEnv },
+ encoding: "utf8",
+ });
+ return { status: r.status, stderr: r.stderr, untouched: readFileSync(rec, "utf8") === body };
+}
+
+const base = (over) => ({
+ videoId: "v1",
+ generatedAt: "x",
+ audioSeconds: 14,
+ speakers: 2,
+ turns: [
+ { start: 0, end: 4, speaker: 0 },
+ { start: 4.5, end: 8, speaker: 1 },
+ ],
+ engine: { engine: "sherpa-onnx" },
+ ...over,
+});
+
+test("voiceprints-only refuses a file whose duration is not the record's (> 1 s apart), or a record with none", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const off = vpOnly(dir, wav, base({ audioSeconds: 99 }));
+ assert.equal(off.status, 6);
+ assert.ok(off.untouched);
+ assert.match(off.stderr, /not the audio these turns were made from/);
+ const none = vpOnly(dir, wav, base({ audioSeconds: undefined }));
+ assert.equal(none.status, 6);
+ assert.ok(none.untouched);
+ assert.equal(vpOnly(dir, wav, base({ audioSeconds: 14.6 })).status, 0, "under a second apart is the same file");
+ }));
+
+test("voiceprints-only refuses when an excerpt comes back short (a turn past the file's end)", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const r = vpOnly(dir, wav, base({ turns: [{ start: 0, end: 4, speaker: 0 }, { start: 12, end: 18, speaker: 1 }] }));
+ assert.equal(r.status, 6);
+ assert.ok(r.untouched);
+ assert.match(r.stderr, /were not made from this file/);
+ }));
+
+test("voiceprints-only refuses when a speaker with long turns gets no embedding, though the audio decodes", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const r = vpOnly(dir, wav, base(), { STUB_NOT_READY: "1" });
+ assert.equal(r.status, 6);
+ assert.ok(r.untouched);
+ assert.match(r.stderr, /no embedding for speaker/);
+ // The full diarization still writes the record — with null centroids, which
+ // the cleanup gate (hasVoiceprints) reads as NOT fingerprinted.
+ const out = engine(["--seg", "s", "--emb", "e", wav].concat([]));
+ assert.ok(out.voiceprints.length > 0);
+ const notReady = JSON.parse(
+ execFileSync("python3", [SCRIPT, "--seg", "s", "--emb", "e", wav], { env: { ...env, STUB_NOT_READY: "1" }, stdio: ["ignore", "pipe", "pipe"] }).toString(),
+ );
+ assert.ok(notReady.voiceprints.every((v) => v.centroid === null));
+ }));
+
+test("a voiceprint step that succeeds drops a refusal recorded against an earlier file", { skip }, () =>
+ withDir((dir) => {
+ const wav = path.join(dir, "a.wav");
+ writeWav(wav, PLAN);
+ const r = vpOnly(dir, wav, base({ voiceprintsRefused: { file: "audio.mp3", size: 1, mtime: 1, reason: "old", at: "x" } }));
+ assert.equal(r.status, 0);
+ const after = JSON.parse(readFileSync(path.join(dir, "diarization.json"), "utf8"));
+ assert.equal("voiceprintsRefused" in after, false);
+ assert.equal(after.voiceprints.length, 2);
+ }));
+
diff --git a/scripts/diarize.mjs b/scripts/diarize.mjs
@@ -58,8 +58,20 @@
// (DIARIZE_WINDOW_MINUTES, 45)
// --window-after-minutes <m> only window files longer than this
// (DIARIZE_WINDOW_AFTER_MINUTES, 90)
+// --voiceprints-only <record.json>
+// add voiceprints to an EXISTING record from its own
+// turns (sherpa's embedder; no segmentation, no
+// clustering) and write it to --output (default: back
+// over <record.json>). Turns, generatedAt and engine are
+// kept byte-for-byte; only voiceprints/voiceprintsAt land.
// -h, --help
//
+// VOICEPRINTS: the sherpa engine prints one TitaNet centroid per final speaker
+// (scripts/diarize-sherpa.py), and they land on the record as `voiceprints`,
+// each carrying the embedding model's basename. Like `windowing` they are
+// OUTSIDE `engine` and outside the freshness identity: a sidecar written before
+// they existed is not stale, it is merely without them (hasVoiceprints).
+//
// WINDOWING IS RECORDED BUT IS NOT PART OF THE FRESHNESS IDENTITY. It lands on
// the record as a top-level `windowing` field, deliberately OUTSIDE `engine` —
// isDiarizationFresh compares engine/models/threshold, and the target it
@@ -70,7 +82,7 @@
// See common/lib/diarization.ts, which says so in as many words.
import { spawn } from "node:child_process";
-import { rename, writeFile } from "node:fs/promises";
+import { readFile, rename, stat, writeFile } from "node:fs/promises";
import path from "node:path";
const HELP = `diarize.mjs [options] <audioFile>
@@ -126,6 +138,118 @@ const windowAfterMinutes = arg(
process.env.DIARIZE_WINDOW_AFTER_MINUTES ?? "90",
);
+const voiceprintsOnly = arg("--voiceprints-only", "");
+
+// The engine's voiceprints as the record stores them. Anything malformed is
+// dropped rather than written: a voiceprint is read by cosine, and a wrong
+// length or a NaN would make every comparison against it quietly meaningless.
+function recordVoiceprints(raw, embeddingModel) {
+ if (!Array.isArray(raw)) return undefined;
+ const out = [];
+ for (const v of raw) {
+ const speaker = Number(v?.speaker);
+ if (!Number.isInteger(speaker)) continue;
+ const centroid =
+ Array.isArray(v.centroid) &&
+ v.centroid.length > 0 &&
+ v.centroid.every((x) => Number.isFinite(x))
+ ? v.centroid.map(Number)
+ : null;
+ out.push({
+ speaker,
+ seconds: Number.isFinite(v.seconds) ? v.seconds : 0,
+ embedded: Number.isInteger(v.embedded) ? v.embedded : 0,
+ centroid,
+ embeddingModel,
+ });
+ }
+ return out;
+}
+
+// WHICH FILE the fingerprints were cut from: the cleanup gate and a later
+// voiceprint step can tell one recording's file from another's (review B3).
+async function voiceprintsFrom(file, durationSeconds) {
+ const bytes = await stat(file).then((st) => st.size, () => null);
+ return {
+ file: path.basename(file),
+ ...(bytes !== null ? { bytes } : {}),
+ ...(Number.isFinite(durationSeconds) ? { durationSeconds } : {}),
+ };
+}
+
+async function writeAtomic(file, json) {
+ // Atomic: a half-written sidecar must never be what convinces the cleanup
+ // sweep it is safe to delete the only copy of the audio.
+ const tmp = `${file}.tmp-${process.pid}`;
+ await writeFile(tmp, json);
+ await rename(tmp, file);
+}
+
+async function runVoiceprintsOnly() {
+ if (!emb) fail("missing --emb (or DIARIZE_EMB_MODEL)");
+ let existing;
+ try {
+ existing = JSON.parse(await readFile(voiceprintsOnly, "utf8"));
+ } catch (e) {
+ fail(`cannot read ${voiceprintsOnly}: ${e.message}`);
+ }
+ if (!Array.isArray(existing?.turns)) fail(`${voiceprintsOnly} has no \`turns\``);
+ const started = Date.now();
+ const child = spawn(
+ python,
+ [
+ path.join(import.meta.dirname, "diarize-sherpa.py"),
+ "--voiceprints-only", voiceprintsOnly,
+ "--emb", emb,
+ "--threads", String(threads),
+ "--ffmpeg", ffmpeg,
+ "--ffprobe", ffprobe,
+ "--window-after-minutes", String(windowAfterMinutes),
+ audio,
+ ],
+ { stdio: ["ignore", "pipe", "inherit"] },
+ );
+ let out = "";
+ child.stdout.setEncoding("utf8");
+ child.stdout.on("data", (d) => (out += d));
+ const code = await new Promise((resolve) => {
+ child.on("error", (err) => fail(`failed to run ${python}: ${err.message}`, 3));
+ child.on("close", resolve);
+ });
+ if (code !== 0) fail(`engine exited ${code}`, code ?? 1);
+ let raw;
+ try {
+ raw = JSON.parse(out);
+ } catch {
+ fail("engine produced no parseable JSON on stdout");
+ }
+ const voiceprints = recordVoiceprints(raw?.voiceprints, path.basename(emb));
+ if (!voiceprints) fail("engine output has no `voiceprints` array");
+ // Everything already on the record stays as it was -- generatedAt above
+ // all: attribution-diarized's freshness names it, so touching it would make
+ // every name already put to these clusters stale for no change in them.
+ // A refusal recorded against an earlier file is answered by these.
+ const { voiceprintsRefused: _refused, ...kept } = existing;
+ const record = {
+ ...kept,
+ voiceprints,
+ voiceprintsAt: new Date().toISOString(),
+ voiceprintsMs: Date.now() - started,
+ voiceprintsFrom: await voiceprintsFrom(audio, raw?.probedSeconds),
+ };
+ const target = output ?? voiceprintsOnly;
+ await writeAtomic(target, JSON.stringify(record) + "\n");
+ const have = voiceprints.filter((v) => v.centroid).length;
+ process.stderr.write(
+ `diarize: voiceprints for ${have} of ${voiceprints.length} speaker(s) -> ${target}\n`,
+ );
+}
+
+if (voiceprintsOnly) {
+ await runVoiceprintsOnly();
+ process.exit(0);
+}
+
const engineCmd = arg("--engine", process.env.DIARIZE_ENGINE_CMD ?? "");
const engineKind = arg(
"--engine-kind",
@@ -227,6 +351,14 @@ child.on("close", async (code) => {
: {}),
speakers: new Set(turns.map((t) => t.speaker)).size,
turns,
+ // Outside `engine`, like `windowing`. Only the sherpa engine embeds; a
+ // sortformer or `--engine` record has none, and says so by omission.
+ ...(() => {
+ const vp = usingSortformer
+ ? undefined
+ : recordVoiceprints(raw.voiceprints, emb ? path.basename(emb) : "");
+ return vp ? { voiceprints: vp, voiceprintsAt: new Date().toISOString() } : {};
+ })(),
// Provenance is per-engine, and the fields a given engine CANNOT have are
// left off rather than written empty. Recording sherpa's threshold on a
// sortformer record would be a lie that isDiarizationFresh then acts on: it
@@ -253,16 +385,15 @@ child.on("close", async (code) => {
},
};
+ if (record.voiceprints) {
+ record.voiceprintsFrom = await voiceprintsFrom(audio, raw.audioSeconds);
+ }
const json = JSON.stringify(record) + "\n";
if (!output) {
process.stdout.write(json);
return;
}
- // Atomic: a half-written sidecar must never be what convinces the cleanup
- // sweep it is safe to delete the only copy of the audio.
- const tmp = `${output}.tmp-${process.pid}`;
- await writeFile(tmp, json);
- await rename(tmp, output);
+ await writeAtomic(output, json);
process.stderr.write(
`diarize: ${record.turns.length} turns, ${record.speakers} speakers -> ${output}\n`,
);
diff --git a/scripts/fixtures/sherpa-stub/sherpa_onnx.py b/scripts/fixtures/sherpa-stub/sherpa_onnx.py
@@ -0,0 +1,132 @@
+"""A stand-in for sherpa_onnx, for scripts/diarize-sherpa.test.mjs.
+
+Same surface as the calls scripts/diarize-sherpa.py makes, none of the models:
+a "voice" is a pure tone, so a test can say who is speaking when by writing a
+wav. Segmentation labels each voiced 0.25 s frame by its dominant frequency;
+an embedding is a smooth bump on a 192-bin frequency axis, so two tones of one
+pitch embed alike and two pitches embed apart; clustering is greedy cosine.
+The real engine is tested by the same file when DIARIZE_PYTHON /
+DIARIZE_SEG_MODEL / DIARIZE_EMB_MODEL name it.
+"""
+import numpy as np
+
+__version__ = "stub-1"
+SR = 16000
+FRAME = 0.25
+
+
+class _Cfg:
+ def __init__(self, **kw):
+ self.__dict__.update(kw)
+
+ def validate(self):
+ return True
+
+
+OfflineSpeakerDiarizationConfig = _Cfg
+OfflineSpeakerSegmentationModelConfig = _Cfg
+OfflineSpeakerSegmentationPyannoteModelConfig = _Cfg
+SpeakerEmbeddingExtractorConfig = _Cfg
+FastClusteringConfig = _Cfg
+
+
+def _pitch(x):
+ if x.size == 0:
+ return 0.0
+ spec = np.abs(np.fft.rfft(x * np.hanning(x.size)))
+ return float(np.argmax(spec)) * SR / x.size
+
+
+class _Seg:
+ def __init__(self, start, end, speaker):
+ self.start, self.end, self.speaker = start, end, speaker
+
+
+class _Result(list):
+ def sort_by_start_time(self):
+ return _Result(sorted(self, key=lambda s: s.start))
+
+
+class OfflineSpeakerDiarization:
+ sample_rate = SR
+
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def process(self, samples):
+ n = int(FRAME * SR)
+ labels = {}
+ segs = []
+ cur = None
+ for i in range(0, samples.size - n + 1, n):
+ x = samples[i:i + n]
+ if float(np.sqrt(np.mean(x * x))) < 0.01:
+ cur = None
+ continue
+ # Pitch to the nearest 100 Hz is the "speaker".
+ key = int(round(_pitch(x) / 100.0))
+ spk = labels.setdefault(key, len(labels))
+ t = i / SR
+ if cur is not None and cur.speaker == spk and abs(cur.end - t) < 1e-6:
+ cur.end = t + FRAME
+ else:
+ cur = _Seg(t, t + FRAME, spk)
+ segs.append(cur)
+ return _Result(segs)
+
+
+class _Stream:
+ def __init__(self):
+ self.x = np.zeros(0, dtype=np.float32)
+
+ def accept_waveform(self, sr, x):
+ self.x = np.concatenate([self.x, np.asarray(x, dtype=np.float32)])
+
+ def input_finished(self):
+ pass
+
+
+class SpeakerEmbeddingExtractor:
+ dim = 192
+
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def create_stream(self):
+ return _Stream()
+
+ def is_ready(self, stream):
+ # STUB_NOT_READY: an embedder that never has enough (audio that decodes,
+ # and still no fingerprint).
+ import os
+ if os.environ.get("STUB_NOT_READY"):
+ return False
+ return stream.x.size >= int(0.5 * SR)
+
+ def compute(self, stream):
+ f = _pitch(stream.x)
+ axis = np.arange(self.dim, dtype=np.float64)
+ centre = min(self.dim - 1, f / 20.0)
+ v = np.exp(-((axis - centre) ** 2) / 18.0) + 0.01
+ return list(v)
+
+
+class FastClustering:
+ def __init__(self, cfg):
+ self.cfg = cfg
+
+ def __call__(self, arr):
+ cents = []
+ out = []
+ for v in np.asarray(arr, dtype=np.float64):
+ v = v / np.linalg.norm(v)
+ best = -1
+ for k, c in enumerate(cents):
+ if float(np.dot(v, c)) > 0.5:
+ best = k
+ break
+ if best < 0:
+ cents.append(v)
+ best = len(cents) - 1
+ out.append(best)
+ return out
diff --git a/settings.json.example b/settings.json.example
@@ -183,7 +183,11 @@
"sortformerBin": "",
"sortformerModel": "",
"concurrency": 1,
- "maxAudioHours": 0
+ "maxAudioHours": 0,
+ "cleanAfterCapture": false,
+ "requireVoiceprints": true,
+ "cleanVerdictMaxAgeHours": 24,
+ "cleanWholeRecordingAudio": false
},
"backfill": {
"concurrency": 1,
diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md
@@ -76,7 +76,7 @@ Inbox cannot disagree about what is wrong with one.
| `take <project> --id <id> --preview [--from <take>] [--at S --dur S \| --full] [--priority] [--json]` | the take's **preview**: the take as stored (a draft too, from its walked patch) composed exactly as its render is -- the same 1920×1080 layout, segments, chrome frames and sound -- with only its final picture encoded smaller and faster (`render.preview`: 1280×720, x264 veryfast, crf 26) into `takes/<id>/out/<slug>.preview.mp4`; its build, schedule and record (`render.json`, `render.log`) in `takes/<id>/out/preview/`. The full render (`preview.mp4`, `out/<slug>.mp4`, `out/sourced/`, `take.json`, `render.json`) is never touched. Reuses this take's own full render, and `--from`'s full render and preview ([report-video.md](report-video.md#fast-feedback-preview-and-changes-renders), [knobs.md](knobs.md#fast-feedback-a-preview-and-a-reel-of-the-changes)) |
| `take <project> --id <id> --changes [--from <take>] [--pad 3] [--no-preview] [--priority] [--json]` | the take's **changes reel**: only what changed against `--from` (default: the take's own `from`, or the take a draft was made from) -- each added, re-read, re-picked, re-voiced, trimmed, held, fx'd, … item with a neighbour either side, rendered in one build (`takes/<id>/out/changes/`), cut to the item ± `--pad` s, a label burned in (`21:19 · p-2116831815466193102 · re-voiced`: its time in the FULL cut), joined into `takes/<id>/out/<slug>.changes.mp4`; a removed item shows as the join it leaves. `takes/<id>/changes.json` lists the pieces with their full-cut times and how exact they are (`times.basis`: `measured` -- the base's measured schedule plus the changed items' measured lengths -- or `estimate`). Preview quality unless `--no-preview`. Nothing changed: no reel, and the list says so |
| `take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \| --before <entry>] [--as <id>] [--dry-run] [--json]` | **items of another project into a take** -- deprecated, saying so in one line on stderr: edits land in the draft, so open the take there and use `timeline <p> import-item` (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\|updated\|unchanged\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage** |
-| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
+| `take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]` | **render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription, download and Speakers lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, "Render mode") |
| `take status <project> [--id <take>] [--json] [--log] [--tail N]` | a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare "exited 1") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A "running" whose process is gone reads **failed** ("the render process is gone"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render |
| `queue add [--after <qid>\|last] [--label T] [--timeout <minutes>] [--json] -- <umtool subcommand argv…>` | a **step** of the durable queue: the argv of a umtool command, one word per argument (no shell), stored under `<reports root>/.umtool-queue/` and run by the **umtool app** (its systemd unit), one step at a time, in order — so it survives the session that queued it, an app restart and a ship. Prints the qid (`q<N>`) alone on stdout. `--after` waits for that step to be **done**; when it fails or is cancelled this one is **blocked** (and so is whatever waits on it). `--timeout`: the step's limit (default 720 minutes). A step does not start while the app's own job runner is busy (a Takes-page job), and a heavy step still takes the machine's heavy slot and render mode by itself |
| `queue ls [--all] [--json]` · `queue status <qid> [--json]` · `queue wait <qid> [--timeout <s>]` · `queue log <qid> [--tail N]` · `queue cancel <qid>` · `queue retry <qid>` | the queue: `ls` the runner (is the app running it) and the steps not finished or finished in the last 24 h; `status` one step (**exit 0 done · 3 queued or running · 1 failed, blocked or cancelled**); `wait` the same after up to `<s>` seconds (default 90); `log` its FULL log (`logs/<qid>.log`; earlier attempts kept as `<qid>.<n>.log`); `cancel` a queued or blocked step at once, a running one stopped (its process group); `retry` a failed or cancelled step back in the queue with every step blocked behind it. A step that was running when the app died reads **failed** ("the step's process is gone"), its log kept — it is never re-run on its own |
diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md
@@ -2406,7 +2406,7 @@ render holds the machine.
While render mode is on, every other heavy job waits at the heavy slot's door (e2e suites,
`next build`s, the publish stages, other renders); the render is admitted on the floor
-4000 MB and the cap 10240 MB; the editor's transcription and download lanes are held — only
+4000 MB and the cap 10240 MB; the editor's transcription, download and Speakers lanes are held — only
the ones that were not held already, and only those are let go. A take's hold ends with the
take: done, failed, or stopped (Ctrl-C, the job's Stop). A window ends at its `until`
(2 h unless `--for`), or with `off`. A hold whose process died is no hold: the gate ignores
diff --git a/umtool/lib/cli/groups.mjs b/umtool/lib/cli/groups.mjs
@@ -585,7 +585,7 @@ export const GROUPS = [
["`take <project> --id <id> --import-item <project>:<item>[,<item>…] [--import-item …] [--after <entry> \\| --before <entry>] [--as <id>] [--dry-run] [--json]`",
"**items of another project into a take** -- deprecated, saying so in one line on stderr: edits land in the draft, so open the take there and use `timeline <p> import-item` (`takeImport.mjs`): each entry CLONED from the source's manifest as it is now (its card, context, knobs, narration with its takes and its pick) into the take's timeline -- one write, an undo point of the take's (`timeline <p> --take <id> undo`); the files it names (narration takes and their `take-<n>.*` sidecars, the parts' cache files, attachments, a context post's media, the picture of each author it draws that the take lacks, added to the take's `postAvatars`) **hard-linked** into this project's dir at the same path, so the render and the lint find them (copied across filesystems; the same file already there is left; ANOTHER file at the path: linked under `imports/<source>/<path>` and the clone names that). The source project and this project's manifest are only read. **Placed** `--after`/`--before` an entry of the take (several items in the order named, one after another), else by the post's date when the take's posts are in date order, else at the end. **Again**: updated in place from the source (moved only with `--after`/`--before`), `unchanged` with no write when nothing differs. `--as`: one item under another id (a second copy). `--dry-run`: the plan and the placement, nothing linked or written. `--json`: `items[] {id, action added\\|updated\\|unchanged\\|moved, at {index, after, before}, narration {takes, pick, file}, files[], avatars[]}`, `revision`. Refused while the take renders. **Exit 0 · 1 refused (no such item, take or entry; a link out of the project) · 2 usage**"],
["`take … --priority` · `takes make … --priority` · `render-mode on [--for 90m] [--note T] [--json \\| --print-token]` · `render-mode on [--for 90m] [--note T] [--print-token] -- <cmd …>` · `render-mode off [--force] [--json]` · `render-mode status [--json]`",
- "**render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription and download lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, \"Render mode\")"],
+ "**render mode**: a render the operator waits for gets the machine. `--priority` turns it on for the take's (or the batch's) lifetime — on at the start, off at the end, on a failure and on a signal; the Takes page's **Give renders the machine** is the same flag. While it is on, every other heavy job (e2e suites, `next build`s, the publish stages, other renders) waits at the heavy slot's door (`queue-lock: held for a render (…) — waiting`), the render runs on the floor 4000 MB and the cap 10240 MB, and the editor's transcription, download and Speakers lanes are held through its ops (`lane`; only the ones not already held, and only those are released at off). `render-mode on` is a window (default 2h) for a chain of renders: every `umtool take` started in it renders in it, another command joins with the `RENDER_PRIORITY_TOKEN` it prints (`--print-token`: the token alone on stdout, the rest on stderr). **`on … -- <cmd …>` is the form for a script**: the command is spawned with the token in its environment, the hold is the command's pid, and it is released when the command exits — done, failed, or umtool signalled (the signal is passed on); umtool exits with the command's code, and inside a manual window the command joins it. A bare `on` in a script leaves the window behind (the chain trap). `off` ends it (a running take's hold only with `--force`, else it ends with the take); `status` says what holds it and releases a stale hold's lanes. A hold whose process is gone or whose window is over is no hold. Needs WORKER_TOKEN and the editor at ARCHILYZER_EDITOR_URL for the lanes; without them it still holds the door. **Exit 1** when it is already on, or a lane could not be released ([report-video.md](report-video.md#render-mode-giving-a-render-the-machine); WORKTREES.md, \"Render mode\")"],
["`take status <project> [--id <take>] [--json] [--log] [--tail N]`",
"a take's **render record** (`takes/<take>/render.json`, written by every render whoever started it — a terminal, the Takes page, the queue): `state` (`running`, `waiting` at the heavy slot, `done`, `failed`, `cancelled`; `queued` or `blocked` while a queue step waits to render it), `stage` and a rough `percent`, the `error` (the first error line, not a bare \"exited 1\") and the log's last 40 lines (`tail`), on done the `mp4` and its measured `seconds`; `--log` prints the FULL `takes/<take>/render.log`. A \"running\" whose process is gone reads **failed** (\"the render process is gone\"); a done whose mp4 is missing or 0 bytes reads **failed**. **Exit 0 done · 3 queued, waiting or running · 1 failed, cancelled, blocked or none.** Without `--id`: every take with a record, the newest's exit ([queue and poll](#queue-and-poll-instead-of-scripting)); and its fast-feedback renders beside it, `preview` and `changes` (each one's state, mp4, seconds, log; a changes reel's piece count, its base and its list), a queued `--preview`/`--changes` step said as such -- never as the take's own render"],
],
diff --git a/umtool/lib/report/renderMode.mjs b/umtool/lib/report/renderMode.mjs
@@ -11,7 +11,7 @@
// umtool render-mode status [--json]
//
// On: the state file (beside the heavy slot's lock), then the editor's
-// transcription and download lanes held through its ops — the `lane` action
+// transcription, download and Speakers lanes held through its ops — the `lane` action
// `pnpm ops lane` posts — each only if it was not held already, and recorded,
// so off releases only those. The editor is ARCHILYZER_EDITOR_URL with
// WORKER_TOKEN, read as `pnpm ops` reads them (fetchWindows.mjs editorConfig).
diff --git a/umtool/lib/report/renderMode.test.mjs b/umtool/lib/report/renderMode.test.mjs
@@ -21,8 +21,11 @@ function tmpFile() {
return path.join(mkdtempSync(path.join(tmpdir(), "render-mode-")), "heavy.lock.render.json");
}
-/** A fake editor's lanes: `held` what it holds, `calls` what was asked. */
-function fakeLanes(held = {}) {
+/** A fake editor's lanes: `held` what it holds, `calls` what was asked. The
+ * Speakers (backfill) lane starts held, as it ships — so these tests' calls are
+ * the two lanes a render actually takes from a fresh install. */
+function fakeLanes(initial = {}) {
+ const held = { backfill: true, ...initial };
const calls = [];
return {
held,
@@ -108,7 +111,7 @@ await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => co
const code = await new Promise((r) => child.on("exit", (c) => r(c)));
assert.equal(code, 143);
assert.equal(existsSync(file), false);
- assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nrelease transcription\nrelease download\n");
+ assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n");
});
test("a take inside a manual window joins it (flag or not) and leaves it on; beside another render it takes nothing", async () => {
@@ -159,7 +162,7 @@ test("umtool render-mode on | status | off, with --json; off of a running take's
assert.equal(out.at(-1), "render mode is off");
assert.equal(await renderModeCommand(["on", "--for", "soon"], io), 2);
assert.equal(await renderModeCommand(["on", "--for", "90m"], io), 0);
- assert.match(out.join("\n"), /render mode ON until \d\d:\d\d — lanes held: transcription \(download already held — left alone\)/);
+ assert.match(out.join("\n"), /render mode ON until \d\d:\d\d — lanes held: transcription \(download, backfill already held — left alone\)/);
assert.match(out.join("\n"), /export RENDER_PRIORITY_TOKEN=[0-9a-f]{16}/);
assert.equal(await renderModeCommand(["on"], io), 1, "already on");
out.length = 0;
@@ -362,7 +365,7 @@ process.exit(await renderModeCommand(["on", "--", process.execPath, "-e", child]
const code = await new Promise((r) => proc.on("exit", (c) => r(c)));
assert.equal(code, 143);
assert.equal(existsSync(file), false);
- assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nrelease transcription\nrelease download\n");
+ assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n");
for (let i = 0; i < 100 && !readFileSync(childLog, "utf8").includes("TERM"); i += 1) await new Promise((r) => setTimeout(r, 20));
assert.equal(readFileSync(childLog, "utf8"), "ready\nTERM\n", "the command got the signal");
});