Archilyzer · Source

archilyzer

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

commit 84bbd4beccc6168ce9ce3d793a65e4585f04f7b2
parent b08a6ca150b3d78710efa3bbef483b83bf9e1c66
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 01:09:47 -0500

common: clean audio without checking, the channel key, and a deferred end for a rate-limited clean

- cleanAudioFromTranscribed takes `unchecked` ("button" | "channel-setting"): every availability
  tier is skipped and nothing is asked of the source; every other gate holds. Its discover pass is
  shared with planAudioClean, the dry plan (videos, files, bytes, holds; no network).
- Channel key cleanAudioWithoutChecking (default absent = checked); clean after capture honours it.
- verifyBeforeClean says why it stopped (rate-limit / error); a rate-limited listing records the
  platform cooldown, as Sync does.
- controller/cleanAudioJob.ts: a rate-limited checked clean ends deferred and queues one retry on the
  channel queue after max(15 min, the platform cooldown), at most 2; the third gives up; any other
  failure to verify retries nothing.

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

Diffstat:
Mcommon/controller/cleanAudioFromTranscribed.ts | 184+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------------
Acommon/controller/cleanAudioJob.test.ts | 314+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/cleanAudioJob.ts | 186+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/cleanUnchecked.test.ts | 302++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/verifyBeforeClean.ts | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/lib/channelConfig.ts | 6++++++
Mcommon/lib/channelConfigSchema.test.ts | 2+-
Mcommon/lib/channelConfigSchema.ts | 1+
8 files changed, 1015 insertions(+), 35 deletions(-)

diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts @@ -22,7 +22,12 @@ import { audioFilesToRemove } from "../lib/videoStatus"; import { readChannelConfig } from "./channels"; import { computeKeptVideoIds } from "./keptVideos"; import { pruneSavedVideos } from "./pruneSavedVideos"; -import { excludedIds, verifyBeforeClean } from "./verifyBeforeClean"; +import { + excludedIds, + verifyBeforeClean, + type CleanVerifyStop, + type VerifyProbes, +} from "./verifyBeforeClean"; const { pathExists, readdir, stat } = fs; @@ -33,10 +38,28 @@ export type CleanAudioOptions = { // (see verifyBeforeClean). Omitted → the global // SiteSettings.verifyAvailabilityBeforeClean, which defaults to true. verifyAvailability?: boolean; + // CLEAN WITHOUT CHECKING (lane clean-unverified): the availability verdict — + // every tier of verifyBeforeClean, the cached one included — is skipped and + // nothing is asked of the source; every other gate below holds. Why it is + // unchecked: the one-off button, or the channel's `cleanAudioWithoutChecking` + // (read by the caller that names the job, so the job's title is truthful). + unchecked?: UncheckedReason; + // Test seam for the availability probes (verifyBeforeClean). + probes?: VerifyProbes; onLog?: (msg: string) => void; signal?: AbortSignal; }; +export type UncheckedReason = "button" | "channel-setting"; + +// The first line of an unchecked clean's log, in both of its forms. +export function uncheckedLogLine(reason: UncheckedReason): string { + return ( + "Clean without checking: the source is not asked, so the audio of videos no longer available anywhere is removed too" + + (reason === "channel-setting" ? " (this channel's cleanAudioWithoutChecking is on)." : ".") + ); +} + export type CleanAudioResult = { inspected: number; cleanedDirs: number; @@ -65,6 +88,10 @@ export type CleanAudioResult = { // window (the retention prune runs alongside the audio sweep). prunedSavedVideos: number; prunedBytes: number; + // Set when the availability gate stopped short — the source rate-limited it + // (`rate-limit`) or it failed (`error`) — and so cleaned nothing it could + // not verify (verifyBeforeClean's CleanVerdicts.stopped). + stopped?: CleanVerifyStop; }; type CleanCandidate = { @@ -169,6 +196,8 @@ export async function cleanAudioFromTranscribed({ channelSlug, paths, verifyAvailability, + unchecked, + probes, onLog, signal, }: CleanAudioOptions): Promise<CleanAudioResult> { @@ -191,46 +220,26 @@ export async function cleanAudioFromTranscribed({ }; } const dirs = await readdir(dataDir); - - // The rolling keep-latest window is protected from cleanup just like the - // explicit do-not-clean marker (the source media of recent videos is kept). - const config = await readChannelConfig(paths, channelSlug); - const keptIds = await computeKeptVideoIds({ - paths, - channelSlug, - keepLatest: config?.keepLatest ?? 0, - }); + if (unchecked) log(uncheckedLogLine(unchecked)); let cleanedDirs = 0; let removedFiles = 0; let bytesFreed = 0; - let protectedCount = 0; - let awaitingDiarization = 0; - let awaitingVoiceprint = 0; - - const diarization = getSettings().diarization; // --- Discover ------------------------------------------------------------- - // Nothing is deleted in this pass. Protected videos are filtered out here, so - // the availability gate never spends a spawn on a video we would keep anyway. - const candidates: CleanCandidate[] = []; - for (const id of dirs) { - if (signal?.aborted) break; - const videoDir = path.join(dataDir, id); - const { gate, audioFiles } = await audioCleanGate(videoDir, id, { keptIds, diarization }); - if (gate === "no-transcript" || gate === "no-audio") continue; - if (gate !== "candidate") log(`Skipped ${id} (${SKIP_LOG[gate]})`); - if (gate === "keep-latest" || gate === "do-not-clean") protectedCount++; - else if (gate === "awaiting-diarization") awaitingDiarization++; - else if (gate === "awaiting-voiceprint") awaitingVoiceprint++; - else candidates.push({ id, videoDir, audioFiles }); - } + const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log, signal }); + const candidates = found.candidates; + let protectedCount = found.protectedCount; + const { awaitingDiarization, awaitingVoiceprint } = found; // --- Verify --------------------------------------------------------------- - const verify = verifyAvailability ?? getSettings().verifyAvailabilityBeforeClean; + const verify = unchecked + ? false + : (verifyAvailability ?? getSettings().verifyAvailabilityBeforeClean); let excluded = new Set<string>(); let pinned = 0; let unverified = 0; + let stopped: CleanVerifyStop | undefined; if (verify && candidates.length > 0 && !signal?.aborted) { const verdicts = await verifyBeforeClean({ channelSlug, @@ -238,10 +247,12 @@ export async function cleanAudioFromTranscribed({ candidateIds: candidates.map((c) => c.id), onLog: log, signal, + ...(probes ? { probes } : {}), }); excluded = excludedIds(verdicts); pinned = verdicts.pinned.size; unverified = verdicts.unverified.size; + stopped = verdicts.stopped; // A video already pinned by someone else is protected, not newly pinned. protectedCount += verdicts.alreadyGone.size; } @@ -294,6 +305,108 @@ export async function cleanAudioFromTranscribed({ bytesFreed, prunedSavedVideos: prune.pruned, prunedBytes: prune.bytesFreed, + ...(stopped ? { stopped } : {}), + }; +} + +// THE DISCOVER PASS of the channel sweep, shared with the dry plan below so +// the two can never disagree about what a clean would remove. Nothing is +// deleted here. Protected videos are filtered out, so the availability gate +// never spends a spawn on a video we would keep anyway. +async function discoverAudioCandidates({ + paths, + channelSlug, + dataDir, + dirs, + log, + signal, +}: { + paths: Paths; + channelSlug: string; + dataDir: string; + dirs: string[]; + log: (m: string) => void; + signal?: AbortSignal; +}): Promise<{ + candidates: CleanCandidate[]; + protectedCount: number; + awaitingDiarization: number; + awaitingVoiceprint: number; +}> { + // The rolling keep-latest window is protected from cleanup just like the + // explicit do-not-clean marker (the source media of recent videos is kept). + const config = await readChannelConfig(paths, channelSlug); + const keptIds = await computeKeptVideoIds({ + paths, + channelSlug, + keepLatest: config?.keepLatest ?? 0, + }); + const diarization = getSettings().diarization; + let protectedCount = 0; + let awaitingDiarization = 0; + let awaitingVoiceprint = 0; + const candidates: CleanCandidate[] = []; + for (const id of dirs) { + if (signal?.aborted) break; + const videoDir = path.join(dataDir, id); + const { gate, audioFiles } = await audioCleanGate(videoDir, id, { keptIds, diarization }); + if (gate === "no-transcript" || gate === "no-audio") continue; + if (gate !== "candidate") log(`Skipped ${id} (${SKIP_LOG[gate]})`); + if (gate === "keep-latest" || gate === "do-not-clean") protectedCount++; + else if (gate === "awaiting-diarization") awaitingDiarization++; + else if (gate === "awaiting-voiceprint") awaitingVoiceprint++; + else candidates.push({ id, videoDir, audioFiles }); + } + return { candidates, protectedCount, awaitingDiarization, awaitingVoiceprint }; +} + +export type AudioCleanPlan = { + inspected: number; + // What an unchecked clean would remove now: the videos, their audio files + // and the bytes those free (through tier links: the bytes on the media tier). + videos: number; + files: number; + bytes: number; + // What it would keep: do-not-clean or keep-latest, and the two speaker holds. + protected: number; + awaitingDiarization: number; + awaitingVoiceprint: number; +}; + +// THE DRY PLAN of a clean without checking — the confirmation's numbers and +// `cleanup {"unchecked": true, "dryRun": true}`'s. The sweep's own discover +// pass, then a stat of each audio file; no network, no deletes, no markers. A +// channel whose media is not reachable (an unmounted drive, a move in flight) +// is refused with the guard's sentence rather than read as empty. +export async function planAudioClean({ + channelSlug, + paths, + signal, +}: { + channelSlug: string; + paths: Paths; + signal?: AbortSignal; +}): Promise<AudioCleanPlan> { + await assertChannelMediaReachable(paths, channelSlug); + const dataDir = path.join(paths.channelsDir, channelSlug, "data"); + const dirs = (await pathExists(dataDir)) ? await readdir(dataDir) : []; + const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log: () => {}, signal }); + let files = 0; + let bytes = 0; + for (const c of found.candidates) { + for (const f of c.audioFiles) { + files++; + bytes += await stat(path.join(c.videoDir, f)).then((st) => st.size, () => 0); + } + } + return { + inspected: dirs.length, + videos: found.candidates.length, + files, + bytes, + protected: found.protectedCount, + awaitingDiarization: found.awaitingDiarization, + awaitingVoiceprint: found.awaitingVoiceprint, }; } @@ -390,8 +503,15 @@ export async function cleanAudioForVideo({ } // ALWAYS, whatever verifyAvailabilityBeforeClean says: that setting governs // the manual sweep the operator presses. An automatic delete is never - // unverified — only a URL-less channel's explicit opt-in skips this. - if (!unverifiedOptIn) { + // unverified — only a URL-less channel's explicit opt-in skips this, and a + // channel whose config says `cleanAudioWithoutChecking` (lane + // clean-unverified: an expiring-VOD platform, where "gone from the source" + // is the normal state) — no cached verdict, no listing, no check requested. + const withoutChecking = config?.cleanAudioWithoutChecking === true; + if (withoutChecking && !unverifiedOptIn) { + log(`Cleaning ${videoId}'s audio without checking (this channel's cleanAudioWithoutChecking is on).`); + } + if (!unverifiedOptIn && !withoutChecking) { const cached = await resolveEffectiveAvailability(videoDir); if (isPermanentlyGone(cached)) { if (!(await loadDoNotClean(videoDir))) { diff --git a/common/controller/cleanAudioJob.test.ts b/common/controller/cleanAudioJob.test.ts @@ -0,0 +1,314 @@ +import { test, mock } from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { VerifyProbes } from "./verifyBeforeClean"; +import { + CLEAN_RATE_LIMIT_MAX_RETRIES, + CLEAN_RETRY_PAUSE_MS, + runCleanAudioJob, + type CleanRetry, +} from "./cleanAudioJob"; +import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanAudioJob.test.ts +// +// A CHECKED CLEAN THE SOURCE RATE-LIMITED (lane clean-unverified, ruling 2): +// it cleans nothing it could not verify, ends DEFERRED with one retry queued +// on the channel's queue after the pause, at most twice; the third rate limit +// in a row gives up for a person. Any other failure to verify retries nothing. +// Temp corpus, stub probes, injected clock / fake timers. + +const ROOT = await mkdtemp(path.join(tmpdir(), "clean-audio-job-")); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true })); + +const T0 = Date.parse("2026-11-21T03:00:00.000Z"); + +let n = 0; +async function corpus() { + const dir = path.join(ROOT, `c${n++}`); + const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: path.join(dir, "no-ytdlp") } as unknown as Paths; + await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); + await writeFile( + path.join(paths.channelsDir, "ch", "config.json"), + JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/example" }), + ); + for (const id of ["a", "b"]) { + const v = path.join(paths.channelsDir, "ch", "data", id); + await mkdir(v, { recursive: true }); + await writeFile(path.join(v, "transcript.json"), "{}"); + await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(100)); + } + return paths; +} + +const audioLeft = async (paths: Paths) => { + let left = 0; + for (const id of ["a", "b"]) { + left += await access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => 1, () => 0); + } + return left; +}; + +function rateLimitedListing() { + const calls = { quick: 0, full: 0 }; + const probes: VerifyProbes = { + quick: async () => { + calls.quick++; + throw new EnumerationIncompleteError(1, "rumble", null, 0); + }, + full: async () => { + calls.full++; + throw new Error("tier C is not reached"); + }, + recordBackoff: async () => {}, + }; + return { calls, probes }; +} + +function retryRecorder() { + const queued: CleanRetry[] = []; + return { + queued, + enqueueRetry: async (r: CleanRetry) => { + queued.push(r); + return { ok: true as const, jobId: `retry-${queued.length}` }; + }, + }; +} + +test("a rate-limited listing: 0 cleaned, a DEFERRED end, exactly one retry at now + 15 min", async () => { + const paths = await corpus(); + const { calls, probes } = rateLimitedListing(); + const r = retryRecorder(); + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-1", + onLog: () => {}, + deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(calls.quick, 1); + assert.equal(await audioLeft(paths), 2, "nothing unverified was cleaned"); + assert.equal(out.end, "deferred"); + assert.equal(CLEAN_RETRY_PAUSE_MS, 15 * 60_000); + assert.deepEqual(r.queued, [{ attempt: 1, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS }]); + if (out.end !== "deferred") return; + assert.equal(out.until, T0 + CLEAN_RETRY_PAUSE_MS); + assert.equal(out.retryJobId, "retry-1"); + assert.match(out.sentence, /rate-limited/); + assert.match(out.sentence, /0 cleaned/); + assert.match(out.sentence, /2 left unverified/); + assert.match(out.sentence, /retry 1 of 2/); +}); + +test("the retry never lands inside the platform's cooldown: a longer cooldown moves it later", async () => { + const paths = await corpus(); + const { probes } = rateLimitedListing(); + const r = retryRecorder(); + await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-1", + onLog: () => {}, + deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 25 * 60_000 }, + }); + assert.deepEqual(r.queued, [{ attempt: 1, of: "job-1", notBefore: T0 + 25 * 60_000 }]); +}); + +test("a rate-limited confirmation probe (tier C blocked) defers the same way", async () => { + const paths = await corpus(); + const r = retryRecorder(); + const probes: VerifyProbes = { + quick: async () => ({ knownCount: 2, freshCount: 1, maybeMissingCount: 1, ids: ["b"] }), + full: async () => ({ + attempted: 1, + checked: 0, + skipped: 1, + byStatus: { public: 0, unlisted: 0, private: 0, members_only: 0, needs_auth: 0, deleted: 0, error: 0 }, + blocked: true, + blockMessage: "HTTP Error 429", + probedIds: [], + }), + }; + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-1", + onLog: () => {}, + deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "deferred"); + assert.equal(await audioLeft(paths), 1, "the listed video was cleaned; the unprobed suspect was not"); + assert.equal(r.queued.length, 1); + if (out.end === "deferred") assert.match(out.sentence, /1 cleaned/); +}); + +test("the third rate limit in a row (retry 2 of 2) gives up for a person: no further retry", async () => { + const paths = await corpus(); + const { probes } = rateLimitedListing(); + const r = retryRecorder(); + assert.equal(CLEAN_RATE_LIMIT_MAX_RETRIES, 2); + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-3", + retry: { attempt: 2, of: "job-1", notBefore: T0 - 1 }, + onLog: () => {}, + deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "failed"); + if (out.end === "failed") assert.match(out.sentence, /^Gave up: rate-limited/); + assert.equal(r.queued.length, 0); + assert.equal(await audioLeft(paths), 2); +}); + +test("a retry that is rate-limited again queues the next one, keeping the original request's id", async () => { + const paths = await corpus(); + const { probes } = rateLimitedListing(); + const r = retryRecorder(); + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-2", + retry: { attempt: 1, of: "job-1", notBefore: T0 - 1 }, + onLog: () => {}, + deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "deferred"); + assert.deepEqual(r.queued, [{ attempt: 2, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS }]); +}); + +test("a listing that failed for another reason: 'could not verify', nothing scheduled", async () => { + const paths = await corpus(); + const r = retryRecorder(); + const probes: VerifyProbes = { + quick: async () => { + throw new Error("yt-dlp exited with code 1"); + }, + }; + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-1", + onLog: () => {}, + deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "failed"); + if (out.end === "failed") assert.match(out.sentence, /^Could not verify availability/); + assert.equal(r.queued.length, 0); + assert.equal(await audioLeft(paths), 2); +}); + +test("a verified clean ends plain done and schedules nothing", async () => { + const paths = await corpus(); + const r = retryRecorder(); + const probes: VerifyProbes = { quick: async () => ({ knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }) }; + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-1", + onLog: () => {}, + deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "done"); + assert.equal(r.queued.length, 0); + assert.equal(await audioLeft(paths), 0); +}); + +test("an unchecked job has no retry logic: it asks nothing and ends done", async () => { + const paths = await corpus(); + const { calls, probes } = rateLimitedListing(); + const r = retryRecorder(); + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-1", + unchecked: "button", + onLog: () => {}, + deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 }, + }); + assert.equal(out.end, "done"); + assert.equal(calls.quick, 0); + assert.equal(r.queued.length, 0); + assert.equal(await audioLeft(paths), 0); +}); + +test("fake timers: the queued retry waits until its time, then verifies; cancelling the wait cancels the retry", async () => { + mock.timers.enable({ apis: ["Date", "setTimeout"], now: T0 }); + try { + // 1. It waits. + const paths = await corpus(); + let quick = 0; + const probes: VerifyProbes = { + quick: async () => (quick++, { knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }), + }; + let paced: (() => void) | null = null; + const pacedOnce = new Promise<void>((resolve) => (paced = resolve)); + const pacedCalls: Array<{ until: number; reason: string } | undefined> = []; + const r = retryRecorder(); + const run = runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-2", + retry: { attempt: 1, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS }, + onLog: () => {}, + deps: { + probes, + enqueueRetry: r.enqueueRetry, + cooldownRemainingMs: async () => 0, + setPaced: (w) => { + pacedCalls.push(w); + if (w) paced?.(); + }, + }, + }); + await pacedOnce; + assert.equal(quick, 0, "nothing asked before its time"); + assert.deepEqual(pacedCalls[0]?.until, T0 + CLEAN_RETRY_PAUSE_MS); + mock.timers.tick(CLEAN_RETRY_PAUSE_MS - 1000); + await new Promise((res) => setImmediate(res)); + assert.equal(quick, 0, "still waiting a second before"); + mock.timers.tick(1000); + const out = await run; + assert.equal(out.end, "done"); + assert.equal(quick, 1); + assert.equal(pacedCalls.at(-1), undefined, "the wait is cleared"); + + // 2. Cancelled while waiting: no clean, no retry. + const paths2 = await corpus(); + const abort = new AbortController(); + let paced2: (() => void) | null = null; + const pacedOnce2 = new Promise<void>((resolve) => (paced2 = resolve)); + let quick2 = 0; + const run2 = runCleanAudioJob({ + channelSlug: "ch", + paths: paths2, + jobId: "job-2", + retry: { attempt: 1, of: "job-1", notBefore: Date.now() + CLEAN_RETRY_PAUSE_MS }, + onLog: () => {}, + signal: abort.signal, + deps: { + probes: { quick: async () => (quick2++, { knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }) }, + enqueueRetry: r.enqueueRetry, + cooldownRemainingMs: async () => 0, + setPaced: (w) => { + if (w) paced2?.(); + }, + }, + }); + await pacedOnce2; + abort.abort(); + const out2 = await run2; + assert.equal(out2.end, "cancelled"); + assert.equal(quick2, 0); + assert.equal(r.queued.length, 0); + assert.equal(await audioLeft(paths2), 2); + } finally { + mock.timers.reset(); + } +}); diff --git a/common/controller/cleanAudioJob.ts b/common/controller/cleanAudioJob.ts @@ -0,0 +1,186 @@ +import type { Paths } from "../lib/paths"; +import type { ChannelConfig } from "../lib/channelConfig"; +import { detectPlatform } from "../lib/platform"; +import { platformCooldownRemainingMs } from "../jobs/downloadBackoff"; +import { + cleanAudioFromTranscribed, + type CleanAudioResult, + type UncheckedReason, +} from "./cleanAudioFromTranscribed"; +import { readChannelConfig } from "./channels"; +import type { VerifyProbes } from "./verifyBeforeClean"; + +// THE CLEAN-AUDIO JOB'S BODY (lane clean-unverified): what the channel sweep +// does inside its job, and how that job ENDS. +// +// A CHECKED CLEAN THE SOURCE RATE-LIMITED (operator ruling, 21 Nov 2026). The +// gate fails closed — nothing it could not verify is deleted — and the job +// used to end a plain `done` that did nothing (a Rumble listing answered 429: +// 0 of 350 cleaned, `done`). Now: +// - rate-limited, retries left: the job ends DEFERRED (JobRecord.deferred, +// the job system's own state, drawn "deferred" on /jobs) with the counts, +// and ONE retry is queued on the channel's queue, not before +// max(now + CLEAN_RETRY_PAUSE_MS, the platform's recorded cooldown end); +// - the third rate limit in a row (the request and its 2 retries): FAILED, +// "Gave up: rate-limited …" — a person decides; +// - any other failure to verify (a network error, an extractor break): +// FAILED, "Could not verify availability …", no retry (only a rate limit +// is retried — nothing else here suggests waiting helps). +// The queued retry waits out its time INSIDE its job once the queue starts it +// (re-reading the platform cooldown so it never adds to a burst), shown on +// /jobs as a paced wait; cancelling it cancels the retry. A person's Retry of +// any of these jobs starts a fresh chain. +// +// An UNCHECKED clean asks nothing, so none of this applies to it. + +// The pause before a rate-limited clean is retried. The repo's per-platform +// cooldown (jobs/platformBackoff.ts) starts at 1 minute and doubles — a floor +// for downloads, too short to be a pause for a cleanup nobody is waiting on — +// so the retry waits whichever is later: this, or that cooldown's end. +export const CLEAN_RETRY_PAUSE_MS = 15 * 60_000; +// Automatic retries per original request; the next rate limit gives up. +export const CLEAN_RATE_LIMIT_MAX_RETRIES = 2; + +// A queued retry of a rate-limited clean, carried in its job's spec params. +// `of` is the ORIGINAL request's job id (the chain's), `attempt` 1-based. +export type CleanRetry = { attempt: number; of: string; notBefore: number }; + +export type CleanJobOutcome = + | { end: "done"; result: CleanAudioResult } + | { end: "deferred"; until: number; sentence: string; retryJobId: string; result: CleanAudioResult } + | { end: "failed"; sentence: string; result?: CleanAudioResult } + | { end: "cancelled" }; + +export type CleanJobDeps = { + // Queue the retry (the action: a clean-audio-transcribed job on the + // channel's queue with `retry` in its spec). + enqueueRetry: (retry: CleanRetry) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>; + now?: () => number; + cooldownRemainingMs?: (platform: string) => Promise<number>; + // The job's paced wait (JobRecord.pacedUntil / pacedReason); undefined clears it. + setPaced?: (w?: { until: number; reason: string }) => void; + probes?: VerifyProbes; +}; + +// The channel key's verdict for a sweep the operator did not explicitly ask to +// run unchecked: "channel-setting" when `cleanAudioWithoutChecking` is on. +export function uncheckedReasonFor(config: ChannelConfig | null | undefined): UncheckedReason | undefined { + return config?.cleanAudioWithoutChecking === true ? "channel-setting" : undefined; +} + +function sleep(ms: number, signal?: AbortSignal): Promise<void> { + return new Promise((resolve) => { + if (signal?.aborted) return resolve(); + const t = setTimeout(done, ms); + function done() { + clearTimeout(t); + signal?.removeEventListener("abort", done); + resolve(); + } + signal?.addEventListener("abort", done, { once: true }); + }); +} + +function clock(ms: number): string { + return new Date(ms).toISOString().slice(11, 16) + " UTC"; +} + +export async function runCleanAudioJob({ + channelSlug, + paths, + jobId, + unchecked, + retry, + onLog, + signal, + deps, +}: { + channelSlug: string; + paths: Paths; + jobId: string; + unchecked?: UncheckedReason; + retry?: CleanRetry; + onLog: (m: string) => void; + signal?: AbortSignal; + deps: CleanJobDeps; +}): Promise<CleanJobOutcome> { + const now = deps.now ?? (() => Date.now()); + const cooldown = deps.cooldownRemainingMs ?? ((pf: string) => platformCooldownRemainingMs(pf, paths)); + const config = await readChannelConfig(paths, channelSlug); + const platform = detectPlatform(config?.url ?? "") ?? "unknown"; + + // --- A queued retry waits for its time, then for the platform's cooldown --- + if (retry && !unchecked) { + onLog( + `Retry ${retry.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} of rate-limited clean ${retry.of}: not before ${clock(retry.notBefore)}.`, + ); + // Bounded: a cooldown that keeps moving later is waited out a few times, + // then the check runs and meets it (and is judged as a rate limit again). + for (let i = 0; i < 8; i++) { + if (signal?.aborted) break; + const t = now(); + const until = Math.max(retry.notBefore, t + (await cooldown(platform).catch(() => 0))); + if (until <= t) break; + deps.setPaced?.({ until, reason: `retrying a clean the source rate-limited (retry ${retry.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES})` }); + await sleep(until - t, signal); + } + deps.setPaced?.(undefined); + if (signal?.aborted) { + onLog("Cancelled while waiting: nothing was asked or cleaned, and no further retry is queued."); + return { end: "cancelled" }; + } + } + + const result = await cleanAudioFromTranscribed({ + channelSlug, + paths, + onLog, + signal, + ...(unchecked ? { unchecked } : {}), + ...(deps.probes ? { probes: deps.probes } : {}), + }); + if (signal?.aborted) return { end: "cancelled" }; + const stop = result.stopped; + if (!stop) return { end: "done", result }; + + const counts = `${result.cleanedDirs} cleaned, ${result.unverified} left unverified`; + if (stop.kind === "error") { + return { + end: "failed", + sentence: + `Could not verify availability (${stop.message}): ${counts}. Nothing unverified was deleted, and no retry is queued ` + + `(only a rate limit is retried) — run Clean audio again once the source answers.`, + result, + }; + } + const attempt = retry?.attempt ?? 0; + if (attempt >= CLEAN_RATE_LIMIT_MAX_RETRIES) { + return { + end: "failed", + sentence: + `Gave up: rate-limited by ${stop.platform} ${attempt + 1} times in a row (this request and ${CLEAN_RATE_LIMIT_MAX_RETRIES} automatic retries; ` + + `${counts}). Nothing unverified was deleted. It needs a person: run Clean audio again later, or Clean without checking.`, + result, + }; + } + const t = now(); + const notBefore = Math.max(t + CLEAN_RETRY_PAUSE_MS, t + (await cooldown(stop.platform).catch(() => 0))); + const next: CleanRetry = { attempt: attempt + 1, of: retry?.of ?? jobId, notBefore }; + const queued = await deps.enqueueRetry(next); + if (!queued.ok) { + return { + end: "failed", + sentence: `Rate-limited by ${stop.platform} (${counts}); the retry could not be queued: ${queued.error}`, + result, + }; + } + return { + end: "deferred", + until: notBefore, + retryJobId: queued.jobId, + sentence: + `Rate-limited by ${stop.platform} (${stop.message}): ${counts}; nothing unverified was deleted. ` + + `retry ${next.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} queued as job ${queued.jobId}, not before ${clock(notBefore)} — cancel that job to cancel it.`, + result, + }; +} diff --git a/common/controller/cleanUnchecked.test.ts b/common/controller/cleanUnchecked.test.ts @@ -0,0 +1,302 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { access, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { + cleanAudioForVideo, + cleanAudioFromTranscribed, + planAudioClean, +} from "./cleanAudioFromTranscribed"; +import type { VerifyProbes } from "./verifyBeforeClean"; +import type { CheckRequestDeps } from "./availabilityVerdict"; +import { uncheckedReasonFor } from "./cleanAudioJob"; +import { parseChannelConfig } from "../lib/channelConfig"; +import { channelConfigSchema } from "../lib/channelConfigSchema"; +import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanUnchecked.test.ts +// +// CLEAN WITHOUT CHECKING (lane clean-unverified). The availability verdict is +// the ONE gate skipped; every other protection holds. Temp corpus, temp +// settings; every probe is a stub that throws, so a test that reaches the +// network fails loudly — and each asserts its probe was never called. + +const ROOT = await mkdtemp(path.join(tmpdir(), "clean-unchecked-")); +process.env.SETTINGS_FILE = path.join(ROOT, "settings.json"); +process.env.E2E_AVAILABILITY_PROBE_GAP_MS = "0"; + +async function settings(diarization: Record<string, unknown>, over: Record<string, unknown> = {}) { + await writeFile( + process.env.SETTINGS_FILE!, + JSON.stringify({ + verifyAvailabilityBeforeClean: true, + diarization: { enabled: true, segModel: "/m/seg.onnx", embModel: "/m/emb.onnx", ...diarization }, + ...over, + }), + ); +} + +const VOICEPRINTS = [{ speaker: 0, seconds: 4, embedded: 1, centroid: Array.from({ length: 192 }, (_, i) => (i === 0 ? 1 : 0)), embeddingModel: "emb.onnx" }]; +function sidecar(voiceprints: boolean): string { + return JSON.stringify({ + videoId: "v", + generatedAt: "2026-08-07T00:00:00.000Z", + speakers: 1, + turns: [{ start: 0, end: 4, speaker: 0 }], + engine: { engine: "sherpa-onnx", segmentationModel: "seg.onnx", embeddingModel: "emb.onnx", threshold: 0.9 }, + ...(voiceprints ? { voiceprints: VOICEPRINTS } : {}), + }); +} + +// Probes that count their calls and throw — the source "rate-limits" every ask. +function throwingProbes() { + const calls = { quick: 0, full: 0, backoff: 0 }; + const probes: VerifyProbes = { + quick: async () => { + calls.quick++; + throw new Error("HTTP Error 429: Too Many Requests"); + }, + full: async () => { + calls.full++; + throw new Error("HTTP Error 429: Too Many Requests"); + }, + recordBackoff: async () => { + calls.backoff++; + }, + }; + return { calls, probes }; +} + +const NO_CHECK: CheckRequestDeps = { + start: async () => { + throw new Error("a test asked for a real availability check"); + }, + platformRefusal: async () => null, + serviceAlert: async () => null, +}; + +let n = 0; +async function corpus(config: Record<string, unknown> = {}) { + const dir = path.join(ROOT, `c${n++}`); + const paths = { + channelsDir: path.join(dir, "channels"), + transcriptsDir: dir, + ytdlpBin: path.join(dir, "no-such-ytdlp"), + } as unknown as Paths; + await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true }); + await writeFile( + path.join(paths.channelsDir, "ch", "config.json"), + JSON.stringify({ handling: "transcribe", name: "ch", url: "https://www.twitch.tv/example", ...config }), + ); + const video = async ( + id: string, + o: { transcript?: boolean; diarization?: "plain" | "voiceprints"; doNotClean?: boolean; gone?: boolean; bytes?: number } = {}, + ) => { + 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", note: "deleted from source (pre-clean check): deleted" })); + } + if (o.gone) { + await writeFile(path.join(v, "availability.json"), JSON.stringify({ checkedAt: new Date().toISOString(), availability: "deleted" })); + } + return v; + }; + return { paths, video }; +} + +const exists = (f: string) => access(f).then(() => true, () => false); + +async function seed(video: Awaited<ReturnType<typeof corpus>>["video"]) { + return { + expired: await video("expired", { diarization: "voiceprints", gone: true, bytes: 3000 }), + plain: await video("listed", { diarization: "voiceprints", bytes: 2000 }), + pinned: await video("pinned", { diarization: "voiceprints", doNotClean: true }), + noprint: await video("noprint", { diarization: "plain" }), + nodiar: await video("nodiar"), + untranscribed: await video("untranscribed", { transcript: false, diarization: "voiceprints" }), + }; +} + +test("unchecked: removes transcribed audio though every probe would throw, asks none, keeps every other protection", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await seed(video); + const { calls, probes } = throwingProbes(); + const logs: string[] = []; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m), unchecked: "button", probes }); + + assert.deepEqual(calls, { quick: 0, full: 0, backoff: 0 }, "the source was never asked"); + // Gone from source and expired VODs go too: that is what was asked for. + assert.equal(await exists(path.join(v.expired, "audio.mp3")), false); + assert.equal(await exists(path.join(v.plain, "audio.mp3")), false); + assert.equal(await exists(path.join(v.expired, "do-not-clean.json")), false, "no pin written"); + // Every other protection holds. + assert.equal(await exists(path.join(v.pinned, "audio.mp3")), true, "do-not-clean"); + assert.equal(await exists(path.join(v.noprint, "audio.mp3")), true, "awaiting voice fingerprint"); + assert.equal(await exists(path.join(v.nodiar, "audio.mp3")), true, "awaiting diarization"); + assert.equal(await exists(path.join(v.untranscribed, "audio.mp3")), true, "not transcribed"); + assert.equal(r.cleanedDirs, 2); + assert.equal(r.bytesFreed, 5000); + assert.equal(r.unverified, 0); + assert.equal(r.pinned, 0); + assert.equal(r.stopped, undefined); + assert.ok(logs[0]?.startsWith("Clean without checking:"), logs.join("\n")); +}); + +test("the dry plan counts exactly what the unchecked clean removes, and asks nothing", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await seed(video); + const plan = await planAudioClean({ channelSlug: "ch", paths }); + assert.deepEqual(plan, { + inspected: 6, + videos: 2, + files: 2, + bytes: 5000, + protected: 1, + awaitingDiarization: 1, + awaitingVoiceprint: 1, + }); + // Nothing was deleted by the plan. + assert.equal(await exists(path.join(v.plain, "audio.mp3")), true); + const { probes } = throwingProbes(); + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, unchecked: "button", probes }); + assert.equal(r.removedFiles, plan.files); + assert.equal(r.bytesFreed, plan.bytes); + assert.equal(r.cleanedDirs, plan.videos); +}); + +test("checked: unchanged — the same gate runs, pins the gone, cleans the listed, and logs as before", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await seed(video); + let quick = 0; + const probes: VerifyProbes = { + quick: async () => { + quick++; + return { knownCount: 6, freshCount: 6, maybeMissingCount: 0, ids: [] }; + }, + full: async () => { + throw new Error("no suspects: tier C is not reached"); + }, + }; + const logs: string[] = []; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m), probes }); + assert.equal(quick, 1); + assert.equal(await exists(path.join(v.expired, "audio.mp3")), true, "tier A pins the cached gone"); + assert.equal(await exists(path.join(v.expired, "do-not-clean.json")), true); + assert.equal(await exists(path.join(v.plain, "audio.mp3")), false); + assert.equal(r.pinned, 1); + assert.equal(r.stopped, undefined); + assert.ok(!logs.some((l) => l.includes("without checking")), logs.join("\n")); + assert.ok(logs.includes("Verify before clean: all 1 candidate(s) still listed on the source."), logs.join("\n")); + assert.ok( + logs.includes( + "Cleaned 1 audio file(s) from 1 of 6 video dir(s). Skipped 4 (1 protected, 1 gone-from-source pinned, 0 unverified, 1 awaiting diarization, 1 awaiting voice fingerprint).", + ), + logs.join("\n"), + ); +}); + +test("checked: a rate-limited listing cleans nothing unverified and says why it stopped", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await seed(video); + const { calls, probes } = throwingProbes(); + // A rate-limited listing is what runYtdlp throws for a 429 on it. + probes.quick = async () => { + calls.quick++; + throw new EnumerationIncompleteError(1, "twitch", null, 0); + }; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, probes }); + assert.equal(calls.quick, 1); + assert.equal(calls.backoff, 1, "the platform cooldown is recorded, as Sync does"); + assert.equal(r.cleanedDirs, 0); + assert.equal(await exists(path.join(v.plain, "audio.mp3")), true); + assert.deepEqual(r.stopped && { kind: r.stopped.kind, platform: r.stopped.platform }, { kind: "rate-limit", platform: "twitch" }); +}); + +test("checked: a listing that fails for another reason is an error stop, not a rate limit, and records no cooldown", async () => { + await settings({}); + const { paths, video } = await corpus(); + await seed(video); + const { calls, probes } = throwingProbes(); + probes.quick = async () => { + calls.quick++; + throw new Error("yt-dlp exited with code 1"); + }; + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, probes }); + assert.equal(r.cleanedDirs, 0); + assert.equal(r.stopped?.kind, "error"); + assert.equal(calls.backoff, 0); +}); + +test("the channel key: absent = checked (no reason), true = unchecked by the channel setting", () => { + assert.equal(uncheckedReasonFor(parseChannelConfig({ handling: "transcribe", name: "a" })), undefined); + assert.equal(uncheckedReasonFor(parseChannelConfig({ handling: "transcribe", name: "a", cleanAudioWithoutChecking: false })), undefined); + assert.equal(uncheckedReasonFor(parseChannelConfig({ handling: "transcribe", name: "a", cleanAudioWithoutChecking: true })), "channel-setting"); + assert.equal(uncheckedReasonFor(null), undefined); + // The schema keeps it (true) and omits anything else. + assert.equal(channelConfigSchema.parse({ handling: "transcribe", cleanAudioWithoutChecking: true })?.cleanAudioWithoutChecking, true); + assert.equal("cleanAudioWithoutChecking" in (channelConfigSchema.parse({ handling: "transcribe", cleanAudioWithoutChecking: "yes" }) ?? {}), false); +}); + +test("key on: the sweep the action runs asks nothing and keeps the protections", async () => { + await settings({}); + const { paths, video } = await corpus({ cleanAudioWithoutChecking: true }); + const v = await seed(video); + const config = JSON.parse(await readFile(path.join(paths.channelsDir, "ch", "config.json"), "utf8")); + const { calls, probes } = throwingProbes(); + const r = await cleanAudioFromTranscribed({ + channelSlug: "ch", + paths, + onLog: () => {}, + unchecked: uncheckedReasonFor(parseChannelConfig(config)), + probes, + }); + assert.deepEqual(calls, { quick: 0, full: 0, backoff: 0 }); + assert.equal(r.cleanedDirs, 2); + assert.equal(await exists(path.join(v.pinned, "audio.mp3")), true); + assert.equal(await exists(path.join(v.noprint, "audio.mp3")), true); + assert.equal(await exists(path.join(v.untranscribed, "audio.mp3")), true); +}); + +test("key on: clean after capture asks no check, reads no verdict, and cleans an expired VOD — protections still hold", async () => { + await settings({}); + const { paths, video } = await corpus({ cleanAudioWithoutChecking: true }); + const v = await seed(video); + const logs: string[] = []; + const one = (id: string) => cleanAudioForVideo({ channelSlug: "ch", paths, videoId: id, onLog: (m) => logs.push(m), checkDeps: NO_CHECK }); + assert.equal((await one("expired")).outcome, "cleaned"); + assert.equal(await exists(path.join(v.expired, "audio.mp3")), false); + assert.equal((await one("listed")).outcome, "cleaned"); + assert.equal((await one("pinned")).gate, "do-not-clean"); + assert.equal((await one("noprint")).gate, "awaiting-voiceprint"); + assert.equal((await one("untranscribed")).gate, "no-transcript"); + assert.ok(logs.some((l) => l.includes("without checking")), logs.join("\n")); +}); + +test("key off: clean after capture is unchanged — no verdict, held awaiting a check", async () => { + await settings({}); + const { paths, video } = await corpus(); + const v = await video("v1", { diarization: "voiceprints" }); + let started = 0; + const out = await cleanAudioForVideo({ + channelSlug: "ch", + paths, + videoId: "v1", + onLog: () => {}, + checkDeps: { start: async () => (started++, { ok: true, jobId: "x" }) as never, platformRefusal: async () => null, serviceAlert: async () => null }, + }); + assert.equal(out.gate, "awaiting-availability"); + assert.equal(started, 1); + assert.equal(await exists(path.join(v, "audio.mp3")), true); +}); diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts @@ -6,6 +6,9 @@ import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; import { readChannelConfig } from "./channels"; import { runAvailabilityCheck } from "./checkAvailability"; import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck"; +import { recordDownloadBackoff } from "../jobs/downloadBackoff"; +import { detectPlatform } from "../lib/platform"; +import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; // Availability gate for the transcribed-audio cleanup sweep. // @@ -39,6 +42,30 @@ export type CleanVerdicts = { alreadyGone: Set<string>; // Probe inconclusive (error / needs_auth / never resolved). Skip, no marker. unverified: Set<string>; + // WHY THE GATE STOPPED SHORT, when a whole tier gave no answer (lane + // clean-unverified, ruling 2): the listing or the confirmation was + // rate-limited by the source (`rate-limit` — a retry later may succeed), or + // failed for another reason (`error`). Absent when every tier answered — + // a per-video `error` / `needs_auth` verdict is not a stop. + stopped?: CleanVerifyStop; +}; + +export type CleanVerifyStop = { + kind: "rate-limit" | "error"; + // The cooldown key (detectPlatform(url) ?? "unknown"), as Sync and the + // download lane use it. + platform: string; + message: string; +}; + +// THE PROBES, as a test seam: production passes nothing. `recordBackoff` is +// how a rate-limited LISTING records the platform's cooldown — the one a +// download's 429 and Sync's record (jobs/downloadBackoff.ts); a rate-limited +// confirmation records it inside runAvailabilityCheck. +export type VerifyProbes = { + quick?: typeof runQuickAvailabilityCheck; + full?: typeof runAvailabilityCheck; + recordBackoff?: (platform: string) => Promise<void>; }; export type VerifyBeforeCleanOptions = { @@ -47,6 +74,7 @@ export type VerifyBeforeCleanOptions = { candidateIds: string[]; onLog?: (msg: string) => void; signal?: AbortSignal; + probes?: VerifyProbes; }; function emptyVerdicts(): CleanVerdicts { @@ -68,6 +96,7 @@ export async function verifyBeforeClean({ candidateIds, onLog, signal, + probes, }: VerifyBeforeCleanOptions): Promise<CleanVerdicts> { const log = onLog ?? ((m: string) => console.log(m)); const verdicts = emptyVerdicts(); @@ -119,9 +148,10 @@ export async function verifyBeforeClean({ } // Ids known on disk but ABSENT from the channel's current flat playlist. + const platform = detectPlatform(config.url) ?? "unknown"; let maybeMissing: Set<string>; try { - const quick = await runQuickAvailabilityCheck({ + const quick = await (probes?.quick ?? runQuickAvailabilityCheck)({ channelSlug, paths, onLog: log, @@ -137,6 +167,17 @@ export async function verifyBeforeClean({ log( `Verify before clean: could not verify availability (${reason}) — nothing cleaned this run.`, ); + // A 429 on the listing (runYtdlp's EnumerationIncompleteError) is a rate + // limit: the platform's cooldown is recorded, as Sync records it, so the + // downloads and the retry of this clean both stay away for it. + if (err instanceof EnumerationIncompleteError) { + await (probes?.recordBackoff ?? ((pf: string) => recordDownloadBackoff(pf, paths, "rate_limit")))( + err.platform, + ).catch(() => {}); + verdicts.stopped = { kind: "rate-limit", platform: err.platform, message: reason }; + } else if (!signal?.aborted) { + verdicts.stopped = { kind: "error", platform, message: reason }; + } return verdicts; } @@ -155,7 +196,7 @@ export async function verifyBeforeClean({ ); let check: Awaited<ReturnType<typeof runAvailabilityCheck>>; try { - check = await runAvailabilityCheck({ + check = await (probes?.full ?? runAvailabilityCheck)({ channelSlug, paths, mode: "recheck-all", @@ -180,6 +221,7 @@ export async function verifyBeforeClean({ log( `Verify before clean: confirmation probe failed (${reason}) — leaving ${suspects.length} candidate(s) unverified.`, ); + if (!signal?.aborted) verdicts.stopped = { kind: "error", platform, message: reason }; return verdicts; } @@ -203,6 +245,15 @@ export async function verifyBeforeClean({ `${unprobed.size} suspect(s) it did not reach are left unverified, not judged on an old record.`, ); } + // The source rate-limited the confirmation (runAvailabilityCheck recorded + // the cooldown): a retry later may reach what this run could not. + if (check.blocked && unprobed.size > 0 && !signal?.aborted) { + verdicts.stopped = { + kind: "rate-limit", + platform, + message: check.blockMessage ?? "rate-limited", + }; + } for (const id of suspects) { if (signal?.aborted) break; diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts @@ -280,6 +280,9 @@ export type ChannelConfig = { excludeFromCleanup?: boolean; excludeFromCompaction?: boolean; cleanAfterCaptureUnverified?: boolean; + // Lane clean-unverified: every clean of this channel's audio runs WITHOUT + // the availability check (see CHANNEL_CONFIG_FIELD_DOCS). Absent = checked. + cleanAudioWithoutChecking?: boolean; syncIntervalMinutes?: number; fullSweepIntervalMinutes?: number; skipLiveDownloads?: boolean; @@ -370,6 +373,8 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = { "Keep this channel's saved videos out of compaction (`compact-saved-videos`, a re-encode to AV1 that becomes the active copy): neither the selector nor an explicit list touches them. For a channel whose stored bytes are kept as evidence. Absent = false.", cleanAfterCaptureUnverified: "Let clean-after-capture (settings `diarization.cleanAfterCapture`) delete this channel's audio with NO availability check. Only for a channel with no `url`: with no source there is nothing to list, so the automatic per-video clean holds every such channel (\"no source to check: clean by hand\") unless this is true. The manual Clean audio sweep is unaffected. Absent/false = held.", + cleanAudioWithoutChecking: + "Every clean of this channel's transcribed audio runs WITHOUT the availability check: the Clean audio button, the /cleanup row, `pnpm ops cleanup` and clean after capture alike ask the source nothing, so the audio of a video no longer available anywhere is removed too (it is no longer pinned do-not-clean). Every other protection holds: do-not-clean marks, the keep-latest window, the speaker holds (awaiting diarization / voice fingerprint), untranscribed videos, an unreachable or moving media drive. Those jobs run as \"Clean audio without checking\". For a platform whose VODs expire by design (Twitch, Kick), where \"gone from the source\" is the normal state; never set by platform. Absent/false = checked. Set on the channel's Cleanup stage or with `pnpm ops channel-config {\"cleanAudioWithoutChecking\": true}`.", syncIntervalMinutes: "Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. AN INSTAGRAM CHANNEL is synced seldom, because every sync is a logged-in read: absent = every 12 hours at the most often (the global default when that is longer), and a value of its own is never under 240 (4 hours); 0 still turns it off (`common/jobs/syncScheduler.ts`).", fullSweepIntervalMinutes: @@ -601,6 +606,7 @@ export const CHANNEL_CONFIG_COERCIONS: { excludeFromCleanup: bool, excludeFromCompaction: bool, cleanAfterCaptureUnverified: bool, + cleanAudioWithoutChecking: (v) => (v === true ? true : undefined), syncIntervalMinutes: zeroOrClamped(SYNC_INTERVAL_MIN_MINUTES, SYNC_INTERVAL_MAX_MINUTES), fullSweepIntervalMinutes: zeroOrClamped( SYNC_INTERVAL_MIN_MINUTES, diff --git a/common/lib/channelConfigSchema.test.ts b/common/lib/channelConfigSchema.test.ts @@ -39,7 +39,7 @@ test("one key list: docs = coercions = schema shape, sync-state keys inside it", assert.deepEqual(Object.keys(CHANNEL_CONFIG_COERCIONS), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(channelConfigObjectSchema.shape), [...CHANNEL_CONFIG_KEYS]); assert.deepEqual(Object.keys(CHANNEL_CONFIG_FIELD_DOCS), [...CHANNEL_CONFIG_KEYS]); - assert.equal(CHANNEL_CONFIG_KEYS.length, 49); // lane x-trending: `xTrending`; 2026-11-13: `excludeFromCompaction`; 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl` + assert.equal(CHANNEL_CONFIG_KEYS.length, 50); // lane clean-unverified: `cleanAudioWithoutChecking`; lane x-trending: `xTrending`; 2026-11-13: `excludeFromCompaction`; 2026-11-11: `cleanAfterCaptureUnverified`; lane/local-media: opt-in `localMedia`; demo epic D1: `remoteOnly`, `remoteArchive`, `remoteUrl` assert.equal(sameKeys, true); assert.equal(fits, true); for (const k of CHANNEL_SYNC_STATE_KEYS) assert.ok(CHANNEL_CONFIG_KEYS.includes(k), k); diff --git a/common/lib/channelConfigSchema.ts b/common/lib/channelConfigSchema.ts @@ -74,6 +74,7 @@ export const channelConfigObjectSchema = z.object({ excludeFromCleanup: field("excludeFromCleanup"), excludeFromCompaction: field("excludeFromCompaction"), cleanAfterCaptureUnverified: field("cleanAfterCaptureUnverified"), + cleanAudioWithoutChecking: field("cleanAudioWithoutChecking"), syncIntervalMinutes: field("syncIntervalMinutes"), fullSweepIntervalMinutes: field("fullSweepIntervalMinutes"), skipLiveDownloads: field("skipLiveDownloads"),