commit f02fe660e73fdf26aab8b507352b4eb0c921220b
parent 55937d4fd642e761eeb3de6a9e60eaa9a1f7c16b
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 05:24:07 -0500
common: an unchecked clean never prunes saved videos, removes only its confirmed plan, and a rate-limited clean's retry waits off the queue
Review 1 of lane clean-unverified.
- An unchecked sweep no longer runs the saved-video retention prune: in a
checked sweep the availability gate pins a gone video before the prune,
so its rolled-out keep-latest container survives; unchecked, no pin was
written and the prune evicted it, uncounted (F1, blocking).
- The dry plan returns its video ids; a sweep given them (onlyIds) removes
the intersection with what is still eligible, and logs what became
protected since and what is newly eligible but not in the confirmed plan.
- The sweep asks the media guard again immediately before it removes
anything.
- runCleanAudioJob reads the channel key when the job starts (a key-driven
job whose key was turned off runs checked and says so); a "button" job
with no plan removes nothing and ends failed, "Confirmed plan lost;
confirm again"; a retry stays checked and never runs before its time.
- controller/cleanRetrySchedule.ts: the retry of a rate-limited clean is a
durable record (<jobsDir>/clean-retries.json) and a timer, queued as the
new kind clean-audio-retry only at its not-before time (later while the
platform cooldown runs). It survives restarts with its attempt and time;
the boot pass closes a queued one (kind.rescheduledOnBoot) and the
schedule re-arms it. Cancel by the deferred job's id, the slug, or the
retry's own job.
- cleanAudioRequestFor / cleanReplayFor: one rule for what a clean request
queues and how each clean kind is replayed.
- createChannel drops cleanAudioWithoutChecking: a new channel never starts
with it. Registry: isShuttingDown(). The in-job paced wait (setPaced) is
removed.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
18 files changed, 1259 insertions(+), 220 deletions(-)
diff --git a/common/controller/channels.ts b/common/controller/channels.ts
@@ -564,6 +564,13 @@ export async function patchChannelConfig(
});
}
+// A NEW CHANNEL NEVER STARTS CLEANING WITHOUT CHECKING (lane clean-unverified):
+// `cleanAudioWithoutChecking` deletes audio unverified from every clean,
+// automatic ones included, so it is a decision about THIS channel, made on its
+// Cleanup stage (or `channel-config`) after a confirmation — never carried in
+// by a config built or copied from elsewhere. Dropped here, the one door every
+// new channel comes through (the form, `create-channel`, a remote-only
+// registration, an X trending library).
export async function createChannel(
paths: Paths,
slug: string,
@@ -572,7 +579,8 @@ export async function createChannel(
if (await channelExists(paths, slug)) {
throw new Error(`Channel ${slug} already exists`);
}
- await writeChannelConfig(paths, slug, config);
+ const { cleanAudioWithoutChecking: _dropped, ...rest } = config;
+ await writeChannelConfig(paths, slug, rest as ChannelConfig);
}
// DELETING A RELOCATED CHANNEL HAS TO REACH THE OTHER DRIVE. `rm -r` on the
diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts
@@ -44,8 +44,19 @@ export type CleanAudioOptions = {
// unchecked: the one-off button, or the channel's `cleanAudioWithoutChecking`
// (read by the caller that names the job, so the job's title is truthful).
unchecked?: UncheckedReason;
+ // THE CONFIRMED PLAN (review 1, ruling 2): the video ids a person was shown
+ // and confirmed (planAudioClean's `ids`). When given, the sweep removes only
+ // the intersection of this list with what is still eligible NOW: an id that
+ // became protected since is skipped by its gate, and a video that became
+ // eligible since is left for the next run, counted as "not in the confirmed
+ // plan". Absent = discover at start (the checked clean, a channel-key clean
+ // nobody confirmed).
+ onlyIds?: readonly string[];
// Test seam for the availability probes (verifyBeforeClean).
probes?: VerifyProbes;
+ // Test seam for the media guard asked immediately before anything is
+ // removed (assertChannelMediaReachable).
+ assertReachable?: (paths: Paths, slug: string) => Promise<unknown>;
onLog?: (msg: string) => void;
signal?: AbortSignal;
};
@@ -85,9 +96,15 @@ export type CleanAudioResult = {
// Bytes of audio removed (through tier links: the bytes on the media tier).
bytesFreed: number;
// Saved-store containers evicted because they rolled out of the keep-latest
- // window (the retention prune runs alongside the audio sweep).
+ // window (the retention prune runs alongside the CHECKED audio sweep only —
+ // an unchecked one never touches a saved video container).
prunedSavedVideos: number;
prunedBytes: number;
+ // With a confirmed plan (`onlyIds`): eligible now but not in the plan, so
+ // left for the next run; and plan ids no longer eligible (protected or gone
+ // since the plan was made), skipped.
+ notInPlan?: number;
+ planNoLongerEligible?: number;
// Set when the availability gate stopped short — the source rate-limited it
// (`rate-limit`) or it failed (`error`) — and so cleaned nothing it could
// not verify (verifyBeforeClean's CleanVerdicts.stopped).
@@ -197,7 +214,9 @@ export async function cleanAudioFromTranscribed({
paths,
verifyAvailability,
unchecked,
+ onlyIds,
probes,
+ assertReachable = assertChannelMediaReachable,
onLog,
signal,
}: CleanAudioOptions): Promise<CleanAudioResult> {
@@ -228,10 +247,27 @@ export async function cleanAudioFromTranscribed({
// --- Discover -------------------------------------------------------------
const found = await discoverAudioCandidates({ paths, channelSlug, dataDir, dirs, log, signal });
- const candidates = found.candidates;
+ let candidates = found.candidates;
let protectedCount = found.protectedCount;
const { awaitingDiarization, awaitingVoiceprint } = found;
+ // --- The confirmed plan: never more than a person was shown ---------------
+ let notInPlan: number | undefined;
+ let planNoLongerEligible: number | undefined;
+ if (onlyIds) {
+ const plan = new Set(onlyIds);
+ const inPlan = candidates.filter((c) => plan.has(c.id));
+ notInPlan = candidates.length - inPlan.length;
+ planNoLongerEligible = plan.size - inPlan.length;
+ log(
+ `Confirmed plan: ${plan.size} video(s); ${inPlan.length} still eligible` +
+ (planNoLongerEligible > 0 ? `, ${planNoLongerEligible} protected or gone since (skipped)` : "") +
+ (notInPlan > 0 ? `; ${notInPlan} newly eligible video(s) left for the next run (not in the confirmed plan)` : "") +
+ ".",
+ );
+ candidates = inPlan;
+ }
+
// --- Verify ---------------------------------------------------------------
const verify = unchecked
? false
@@ -258,6 +294,14 @@ export async function cleanAudioFromTranscribed({
}
// --- Delete ---------------------------------------------------------------
+ // THE GUARDS AGAIN, IMMEDIATELY BEFORE ANYTHING IS REMOVED (review 1, F4):
+ // the job kind's needsMedia guard ran when the queue started the job, and a
+ // listing can take minutes. A drive that went away or a relocation that
+ // started since (its marker) stops the sweep here, removing nothing: a
+ // removed tier link on an absent drive strands its bytes there.
+ if (candidates.some((c) => !excluded.has(c.id)) && !signal?.aborted) {
+ await assertReachable(paths, channelSlug);
+ }
for (const candidate of candidates) {
if (signal?.aborted) break;
if (excluded.has(candidate.id)) continue;
@@ -291,7 +335,18 @@ export async function cleanAudioFromTranscribed({
// Retention prune of the saved-video store: evict any keep-latest containers
// that have rolled out of the window (pinned/manually-archived ones survive).
- const prune = await pruneSavedVideos({ channelSlug, paths, onLog: log, signal });
+ // NEVER IN AN UNCHECKED SWEEP (review 1, F1, BLOCKING). The prune keeps a
+ // rolled-out container only when the video is do-not-clean, and in the
+ // checked sweep that pin is written by the availability gate just above —
+ // for a video gone from the source, whose container may be its only copy
+ // anywhere. An unchecked sweep skips the gate, so no pin would exist and the
+ // prune would evict exactly those containers, uncounted by any plan.
+ const prune = unchecked
+ ? (log(
+ "Saved-video retention prune skipped: a clean without checking never touches a saved video container (a checked Clean audio runs it).",
+ ),
+ { pruned: 0, bytesFreed: 0 })
+ : await pruneSavedVideos({ channelSlug, paths, onLog: log, signal });
return {
inspected: dirs.length,
@@ -305,6 +360,7 @@ export async function cleanAudioFromTranscribed({
bytesFreed,
prunedSavedVideos: prune.pruned,
prunedBytes: prune.bytesFreed,
+ ...(notInPlan !== undefined ? { notInPlan, planNoLongerEligible } : {}),
...(stopped ? { stopped } : {}),
};
}
@@ -362,6 +418,9 @@ async function discoverAudioCandidates({
export type AudioCleanPlan = {
inspected: number;
+ // The video ids it would remove audio from — what a confirmed run carries
+ // (CleanAudioOptions.onlyIds) so it removes at most these.
+ ids: string[];
// What an unchecked clean would remove now: the videos, their audio files
// and the bytes those free (through tier links: the bytes on the media tier).
videos: number;
@@ -401,6 +460,7 @@ export async function planAudioClean({
}
return {
inspected: dirs.length,
+ ids: found.candidates.map((c) => c.id),
videos: found.candidates.length,
files,
bytes,
diff --git a/common/controller/cleanAudioJob.test.ts b/common/controller/cleanAudioJob.test.ts
@@ -1,4 +1,4 @@
-import { test, mock } from "node:test";
+import { test } from "node:test";
import assert from "node:assert/strict";
import { access, mkdir, mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
@@ -8,19 +8,25 @@ import type { VerifyProbes } from "./verifyBeforeClean";
import {
CLEAN_RATE_LIMIT_MAX_RETRIES,
CLEAN_RETRY_PAUSE_MS,
+ PLAN_LOST_SENTENCE,
+ cleanAudioRequestFor,
+ cleanReplayFor,
runCleanAudioJob,
type CleanRetry,
} from "./cleanAudioJob";
+import { parseChannelConfig } from "../lib/channelConfig";
import { EnumerationIncompleteError } from "../ytdlp/runYtdlp";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanAudioJob.test.ts
//
// A CHECKED CLEAN THE SOURCE RATE-LIMITED (lane clean-unverified, ruling 2):
-// it cleans nothing it could not verify, ends DEFERRED with one retry 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.
+// it cleans nothing it could not verify, ends DEFERRED with one retry
+// SCHEDULED (off-queue: cleanRetrySchedule.ts) after the pause, at most twice;
+// the third rate limit in a row gives up for a person. Any other failure to
+// verify retries nothing. And how the job decides, WHEN IT STARTS, whether it
+// runs unchecked and what it may remove (review 1, F2, F3, F5). Temp corpus,
+// stub probes, an injected clock.
const ROOT = await mkdtemp(path.join(tmpdir(), "clean-audio-job-"));
process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
@@ -29,15 +35,15 @@ await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBe
const T0 = Date.parse("2026-11-21T03:00:00.000Z");
let n = 0;
-async function corpus() {
+async function corpus(config: Record<string, unknown> = {}, ids = ["a", "b"]) {
const dir = path.join(ROOT, `c${n++}`);
const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: path.join(dir, "no-ytdlp") } as unknown as Paths;
await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true });
await writeFile(
path.join(paths.channelsDir, "ch", "config.json"),
- JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/example" }),
+ JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/example", ...config }),
);
- for (const id of ["a", "b"]) {
+ for (const id of ids) {
const v = path.join(paths.channelsDir, "ch", "data", id);
await mkdir(v, { recursive: true });
await writeFile(path.join(v, "transcript.json"), "{}");
@@ -46,16 +52,16 @@ async function corpus() {
return paths;
}
-const audioLeft = async (paths: Paths) => {
+const has = (paths: Paths, id: string) =>
+ access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false);
+const audioLeft = async (paths: Paths, ids = ["a", "b"]) => {
let left = 0;
- for (const id of ["a", "b"]) {
- left += await access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => 1, () => 0);
- }
+ for (const id of ids) left += (await has(paths, id)) ? 1 : 0;
return left;
};
function rateLimitedListing() {
- const calls = { quick: 0, full: 0 };
+ const calls = { quick: 0, full: 0, backoff: 0 };
const probes: VerifyProbes = {
quick: async () => {
calls.quick++;
@@ -65,45 +71,63 @@ function rateLimitedListing() {
calls.full++;
throw new Error("tier C is not reached");
},
- recordBackoff: async () => {},
+ recordBackoff: async () => {
+ calls.backoff++;
+ },
};
return { calls, probes };
}
+const allListed = () => {
+ const calls = { quick: 0 };
+ const probes: VerifyProbes = {
+ quick: async () => (calls.quick++, { knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }),
+ };
+ return { calls, probes };
+};
+
function retryRecorder() {
- const queued: CleanRetry[] = [];
+ const scheduled: CleanRetry[] = [];
return {
- queued,
- enqueueRetry: async (r: CleanRetry) => {
- queued.push(r);
- return { ok: true as const, jobId: `retry-${queued.length}` };
+ scheduled,
+ scheduleRetry: async (r: CleanRetry) => {
+ scheduled.push(r);
+ return { ok: true as const, id: `${r.of}.retry${r.attempt}` };
},
};
}
-test("a rate-limited listing: 0 cleaned, a DEFERRED end, exactly one retry at now + 15 min", async () => {
+const base = (paths: Paths, over: Partial<Parameters<typeof runCleanAudioJob>[0]> = {}) => ({
+ channelSlug: "ch",
+ paths,
+ jobId: "job-1",
+ onLog: () => {},
+ ...over,
+});
+
+test("a rate-limited listing: 0 cleaned, a DEFERRED end, exactly one retry scheduled at now + 15 min", async () => {
const paths = await corpus();
const { calls, probes } = rateLimitedListing();
const r = retryRecorder();
const out = await runCleanAudioJob({
- channelSlug: "ch",
- paths,
- jobId: "job-1",
- onLog: () => {},
- deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
+ ...base(paths),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
});
assert.equal(calls.quick, 1);
+ assert.equal(calls.backoff, 1, "the cooldown is recorded once for this step of the chain");
assert.equal(await audioLeft(paths), 2, "nothing unverified was cleaned");
assert.equal(out.end, "deferred");
assert.equal(CLEAN_RETRY_PAUSE_MS, 15 * 60_000);
- assert.deepEqual(r.queued, [{ attempt: 1, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS }]);
+ assert.deepEqual(r.scheduled, [{ attempt: 1, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS, platform: "rumble" }]);
if (out.end !== "deferred") return;
assert.equal(out.until, T0 + CLEAN_RETRY_PAUSE_MS);
- assert.equal(out.retryJobId, "retry-1");
- assert.match(out.sentence, /rate-limited/);
+ assert.equal(out.retryId, "job-1.retry1");
+ assert.match(out.sentence, /rate-limited/i);
assert.match(out.sentence, /0 cleaned/);
assert.match(out.sentence, /2 left unverified/);
- assert.match(out.sentence, /retry 1 of 2/);
+ assert.match(out.sentence, /Retry 1 of 2 is scheduled/);
+ assert.match(out.sentence, /waits off the queue/);
+ assert.match(out.sentence, /Cancel this job to cancel it/);
});
test("the retry never lands inside the platform's cooldown: a longer cooldown moves it later", async () => {
@@ -111,13 +135,10 @@ test("the retry never lands inside the platform's cooldown: a longer cooldown mo
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 },
+ ...base(paths),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 25 * 60_000 },
});
- assert.deepEqual(r.queued, [{ attempt: 1, of: "job-1", notBefore: T0 + 25 * 60_000 }]);
+ assert.equal(r.scheduled[0]?.notBefore, T0 + 25 * 60_000);
});
test("a rate-limited confirmation probe (tier C blocked) defers the same way", async () => {
@@ -136,15 +157,12 @@ test("a rate-limited confirmation probe (tier C blocked) defers the same way", a
}),
};
const out = await runCleanAudioJob({
- channelSlug: "ch",
- paths,
- jobId: "job-1",
- onLog: () => {},
- deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
+ ...base(paths),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
});
assert.equal(out.end, "deferred");
assert.equal(await audioLeft(paths), 1, "the listed video was cleaned; the unprobed suspect was not");
- assert.equal(r.queued.length, 1);
+ assert.equal(r.scheduled.length, 1);
if (out.end === "deferred") assert.match(out.sentence, /1 cleaned/);
});
@@ -154,33 +172,40 @@ test("the third rate limit in a row (retry 2 of 2) gives up for a person: no fur
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 },
+ ...base(paths, { jobId: "job-3", retry: { attempt: 2, of: "job-1", notBefore: T0 - 1, platform: "rumble" } }),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
});
assert.equal(out.end, "failed");
if (out.end === "failed") assert.match(out.sentence, /^Gave up: rate-limited/);
- assert.equal(r.queued.length, 0);
+ assert.equal(r.scheduled.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 () => {
+test("a retry that is rate-limited again schedules the next one, keeping the original request's id", async () => {
const paths = await corpus();
const { probes } = rateLimitedListing();
const r = retryRecorder();
const out = await runCleanAudioJob({
- 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 },
+ ...base(paths, { jobId: "job-2", retry: { attempt: 1, of: "job-1", notBefore: T0 - 1, platform: "rumble" } }),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
});
assert.equal(out.end, "deferred");
- assert.deepEqual(r.queued, [{ attempt: 2, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS }]);
+ assert.deepEqual(r.scheduled, [{ attempt: 2, of: "job-1", notBefore: T0 + CLEAN_RETRY_PAUSE_MS, platform: "rumble" }]);
+});
+
+test("a retry started before its not-before asks nothing and cleans nothing", async () => {
+ const paths = await corpus();
+ const { calls, probes } = rateLimitedListing();
+ const r = retryRecorder();
+ const out = await runCleanAudioJob({
+ ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 + 60_000, platform: "rumble" } }),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
+ });
+ assert.equal(out.end, "failed");
+ if (out.end === "failed") assert.match(out.sentence, /before its time/);
+ assert.equal(calls.quick, 0);
+ assert.equal(r.scheduled.length, 0);
+ assert.equal(await audioLeft(paths), 2);
});
test("a listing that failed for another reason: 'could not verify', nothing scheduled", async () => {
@@ -192,123 +217,140 @@ test("a listing that failed for another reason: 'could not verify', nothing sche
},
};
const out = await runCleanAudioJob({
- channelSlug: "ch",
- paths,
- jobId: "job-1",
- onLog: () => {},
- deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
+ ...base(paths),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
});
assert.equal(out.end, "failed");
if (out.end === "failed") assert.match(out.sentence, /^Could not verify availability/);
- assert.equal(r.queued.length, 0);
+ assert.equal(r.scheduled.length, 0);
assert.equal(await audioLeft(paths), 2);
});
test("a verified clean ends plain done and schedules nothing", async () => {
const paths = await corpus();
const r = retryRecorder();
- const probes: VerifyProbes = { quick: async () => ({ knownCount: 2, freshCount: 2, maybeMissingCount: 0, ids: [] }) };
+ const { probes } = allListed();
const out = await runCleanAudioJob({
- channelSlug: "ch",
- paths,
- jobId: "job-1",
- onLog: () => {},
- deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
+ ...base(paths),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
});
assert.equal(out.end, "done");
- assert.equal(r.queued.length, 0);
+ assert.equal(r.scheduled.length, 0);
assert.equal(await audioLeft(paths), 0);
});
-test("an unchecked job has no retry logic: it asks nothing and ends done", async () => {
+test("a confirmed unchecked job ('button') asks nothing and removes its plan only", async () => {
const paths = await corpus();
const { calls, probes } = rateLimitedListing();
const r = retryRecorder();
const out = await runCleanAudioJob({
- channelSlug: "ch",
- paths,
- jobId: "job-1",
- unchecked: "button",
- onLog: () => {},
- deps: { probes, enqueueRetry: r.enqueueRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
+ ...base(paths, { unchecked: "button", plan: ["a"] }),
+ deps: { probes, scheduleRetry: r.scheduleRetry, now: () => T0, cooldownRemainingMs: async () => 0 },
+ });
+ assert.equal(out.end, "done");
+ assert.equal(calls.quick, 0);
+ assert.equal(r.scheduled.length, 0);
+ assert.equal(await has(paths, "a"), false);
+ assert.equal(await has(paths, "b"), true, "not in the confirmed plan");
+});
+
+test("ruling 5: a 'button' job whose plan is missing removes nothing and ends failed, asking to confirm again", async () => {
+ const paths = await corpus();
+ const { calls, probes } = rateLimitedListing();
+ const out = await runCleanAudioJob({
+ ...base(paths, { unchecked: "button" }),
+ deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 },
+ });
+ assert.deepEqual(out, { end: "failed", sentence: PLAN_LOST_SENTENCE });
+ assert.match(PLAN_LOST_SENTENCE, /^Confirmed plan lost; confirm again/);
+ assert.equal(calls.quick, 0);
+ assert.equal(await audioLeft(paths), 2);
+});
+
+test("ruling 3: a key-driven job whose key was turned off after it was queued runs CHECKED and says so", async () => {
+ const paths = await corpus(); // the key is OFF now
+ const { calls, probes } = allListed();
+ const logs: string[] = [];
+ const out = await runCleanAudioJob({
+ ...base(paths, { unchecked: "channel-setting", onLog: (m) => logs.push(m) }),
+ deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 },
+ });
+ assert.equal(out.end, "done");
+ assert.equal(calls.quick, 1, "the source was asked: it ran checked");
+ assert.ok(logs.some((l) => /turned off after this clean was queued: it runs CHECKED/.test(l)), logs.join("\n"));
+ assert.ok(!logs.some((l) => l.startsWith("Clean without checking:")), logs.join("\n"));
+});
+
+test("ruling 3: a key-driven job whose key is still on runs unchecked, discovering at start", async () => {
+ const paths = await corpus({ cleanAudioWithoutChecking: true });
+ const { calls, probes } = rateLimitedListing();
+ const out = await runCleanAudioJob({
+ ...base(paths, { unchecked: "channel-setting" }),
+ deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 },
});
assert.equal(out.end, "done");
assert.equal(calls.quick, 0);
- assert.equal(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");
+test("a retry stays CHECKED even if the channel's key was turned on since (nobody confirmed an unchecked run)", async () => {
+ const paths = await corpus({ cleanAudioWithoutChecking: true });
+ const { calls, probes } = allListed();
+ await runCleanAudioJob({
+ ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 - 1, platform: "rumble" } }),
+ deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 },
+ });
+ assert.equal(calls.quick, 1);
+});
- // 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();
- }
+test("ruling 4: whatever runs after the wait re-asserts the media guard immediately before removing anything", async () => {
+ const paths = await corpus();
+ const { probes } = allListed();
+ // A relocation started during the wait: its marker stands.
+ await writeFile(
+ path.join(paths.channelsDir, "ch", ".relocating.json"),
+ JSON.stringify({ target: "/elsewhere/ch/media", direction: "out", startedAt: "now", phase: "copy", scope: "media" }),
+ );
+ await assert.rejects(
+ runCleanAudioJob({
+ ...base(paths, { retry: { attempt: 1, of: "job-0", notBefore: T0 - 1, platform: "rumble" } }),
+ deps: { probes, scheduleRetry: retryRecorder().scheduleRetry, now: () => T0 },
+ }),
+ /relocation/,
+ );
+ assert.equal(await audioLeft(paths), 2, "nothing removed under a relocation");
+});
+
+test("what a request queues: kind, unchecked reason and carried plan, from the key and the explicit flag", () => {
+ const off = parseChannelConfig({ handling: "transcribe", name: "a" });
+ const on = parseChannelConfig({ handling: "transcribe", name: "a", cleanAudioWithoutChecking: true });
+ assert.deepEqual(cleanAudioRequestFor(off), { kind: "clean-audio-transcribed" });
+ assert.deepEqual(cleanAudioRequestFor(on), { kind: "clean-audio-unchecked", unchecked: "channel-setting" });
+ assert.deepEqual(cleanAudioRequestFor(on, { plan: ["x"] }), { kind: "clean-audio-unchecked", unchecked: "channel-setting", plan: ["x"] });
+ assert.deepEqual(cleanAudioRequestFor(off, { explicit: "button", plan: ["x"] }), {
+ kind: "clean-audio-unchecked",
+ unchecked: "button",
+ plan: ["x"],
+ });
+ assert.deepEqual(cleanAudioRequestFor(null, { explicit: "button" }), { kind: "clean-audio-unchecked", unchecked: "button" });
+});
+
+test("replay: unchecked only with the explicit flag and its carried plan; a retry's replay is a fresh chain", () => {
+ assert.deepEqual(cleanReplayFor("clean-audio-transcribed", {}), { ok: true, call: "clean" });
+ assert.deepEqual(cleanReplayFor("clean-audio-transcribed", { plan: ["a"] }), { ok: true, call: "clean", plan: ["a"] });
+ assert.deepEqual(
+ cleanReplayFor("clean-audio-retry", { retry: { attempt: 1, of: "j", notBefore: 1, platform: "rumble" }, plan: ["a"] }),
+ { ok: true, call: "clean" },
+ "the retry's chain and count are the schedule's, never a replay's",
+ );
+ assert.deepEqual(cleanReplayFor("clean-audio-unchecked", { unchecked: "button", plan: ["a", "b"] }), {
+ ok: true,
+ call: "unchecked",
+ plan: ["a", "b"],
+ });
+ // No plan: replayed into a job that ends failed (PLAN_LOST_SENTENCE), never an unbounded run.
+ assert.deepEqual(cleanReplayFor("clean-audio-unchecked", { unchecked: "button" }), { ok: true, call: "unchecked" });
+ assert.deepEqual(cleanReplayFor("clean-audio-unchecked", { unchecked: "button", plan: "a" }), { ok: true, call: "unchecked" });
+ assert.deepEqual(cleanReplayFor("clean-audio-unchecked", { unchecked: "channel-setting" }), { ok: true, call: "clean" });
+ assert.equal(cleanReplayFor("clean-audio-unchecked", {}).ok, false);
});
diff --git a/common/controller/cleanAudioJob.ts b/common/controller/cleanAudioJob.ts
@@ -1,6 +1,5 @@
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
-import { detectPlatform } from "../lib/platform";
import { platformCooldownRemainingMs } from "../jobs/downloadBackoff";
import {
cleanAudioFromTranscribed,
@@ -19,17 +18,18 @@ import type { VerifyProbes } from "./verifyBeforeClean";
// 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
+// and ONE retry is scheduled (off-queue, below), not before
// max(now + CLEAN_RETRY_PAUSE_MS, the platform's recorded cooldown end);
// - the third rate limit in a row (the request and its 2 retries): FAILED,
// "Gave up: rate-limited …" — a person decides;
// - any other failure to verify (a network error, an extractor break):
// FAILED, "Could not verify availability …", no retry (only a rate limit
// is retried — nothing else here suggests waiting helps).
-// The 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.
+// The retry's wait is OFF-QUEUE (review 1 F4–F6): a durable record and a
+// timer (controller/cleanRetrySchedule.ts) that queues the retry job only at
+// its not-before time, so it holds no queue and no job slot meanwhile.
+// Cancelling the deferred job cancels the retry. A person's Retry of any of
+// these jobs starts a fresh chain.
//
// An UNCHECKED clean asks nothing, so none of this applies to it.
@@ -41,44 +41,101 @@ 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 };
+// A retry of a rate-limited clean, carried in its record and its job's spec
+// params. `of` is the ORIGINAL request's job id (the chain's), `attempt`
+// 1-based, `platform` the key the rate limit was recorded under (its cooldown),
+// `id` the schedule record's (cleanRetrySchedule.ts) once it has one.
+export type CleanRetry = { attempt: number; of: string; notBefore: number; platform: string; id?: string };
export type CleanJobOutcome =
| { end: "done"; result: CleanAudioResult }
- | { end: "deferred"; until: number; sentence: string; retryJobId: string; result: CleanAudioResult }
+ | { end: "deferred"; until: number; sentence: string; retryId: 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 }>;
+ // Schedule the retry OFF-QUEUE (the action: cleanRetrySchedule's record and
+ // timer, which queue a clean-audio-retry job at `notBefore`).
+ scheduleRetry: (retry: CleanRetry) => Promise<{ ok: true; id: string } | { ok: false; error: string }>;
now?: () => number;
cooldownRemainingMs?: (platform: string) => Promise<number>;
- // The job's paced wait (JobRecord.pacedUntil / pacedReason); undefined clears it.
- setPaced?: (w?: { until: number; reason: string }) => void;
probes?: VerifyProbes;
+ // Test seam for the sweep's guard immediately before it removes anything.
+ assertReachable?: (paths: Paths, slug: string) => Promise<unknown>;
};
+// THE SENTENCE OF A CONFIRMED UNCHECKED JOB WHOSE PLAN IS GONE (ruling 5): a
+// "Clean without checking" removes at most what a person confirmed, so a job
+// that has no plan to carry (a spec from before plans, or one a restart
+// re-queued without it) removes nothing and asks for the confirmation again.
+export const PLAN_LOST_SENTENCE =
+ "Confirmed plan lost; confirm again: this clean without checking carries no list of what a person confirmed, so it removed nothing. Run Clean without checking again and confirm its count.";
+
// The channel key's verdict for a sweep the operator did not explicitly ask to
// run unchecked: "channel-setting" when `cleanAudioWithoutChecking` is on.
export function uncheckedReasonFor(config: ChannelConfig | null | undefined): UncheckedReason | undefined {
return config?.cleanAudioWithoutChecking === true ? "channel-setting" : undefined;
}
-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 });
- });
+// WHAT A CLEAN REQUEST QUEUES — the job kind (so the job list's title is
+// truthful) and what its spec carries. The one rule the action, the ops twin
+// and replay share:
+// - "button" (a person confirmed a counted plan, or `cleanup {"unchecked":
+// true}` computed one at the call): unchecked, the plan carried;
+// - the channel's key on: unchecked by "channel-setting", with the plan when
+// a person confirmed one, else discovered at start; the key is re-read
+// when the job starts (runCleanAudioJob);
+// - otherwise the checked clean (bounded by a plan when one was confirmed).
+export type CleanAudioRequest = {
+ kind: "clean-audio-transcribed" | "clean-audio-unchecked";
+ unchecked?: UncheckedReason;
+ plan?: string[];
+};
+
+export function cleanAudioRequestFor(
+ config: ChannelConfig | null | undefined,
+ opts: { explicit?: "button"; plan?: readonly string[] } = {},
+): CleanAudioRequest {
+ const plan = opts.plan ? [...opts.plan] : undefined;
+ const reason: UncheckedReason | undefined = opts.explicit ?? uncheckedReasonFor(config);
+ if (reason) return { kind: "clean-audio-unchecked", unchecked: reason, ...(plan ? { plan } : {}) };
+ return { kind: "clean-audio-transcribed", ...(plan ? { plan } : {}) };
+}
+
+// A spec's carried plan, or undefined for anything that is not a list of ids.
+export function planFromParams(p: Record<string, unknown> | undefined): string[] | undefined {
+ const v = p?.plan;
+ return Array.isArray(v) && v.every((x) => typeof x === "string") ? (v as string[]) : undefined;
+}
+
+// HOW A CLEAN JOB IS REPLAYED (a person's Retry, and the boot's re-queue of a
+// job a restart caught queued):
+// - clean-audio-transcribed → Clean audio again (its plan, if it carried one);
+// - clean-audio-retry → Clean audio again: a FRESH chain (a scheduled retry
+// is re-armed at boot from its own record, never replayed);
+// - clean-audio-unchecked with "button" → unchecked again WITH ITS CARRIED
+// PLAN, removing at most that; a spec with no plan replays into a job that
+// ends failed, "Confirmed plan lost; confirm again" (PLAN_LOST_SENTENCE);
+// - clean-audio-unchecked with "channel-setting" → Clean audio, so the key
+// as it is now decides;
+// - anything else is refused.
+export type CleanReplay =
+ | { ok: true; call: "clean" | "unchecked"; plan?: string[] }
+ | { ok: false; error: string };
+
+export function cleanReplayFor(kind: string, params: Record<string, unknown> | undefined): CleanReplay {
+ const plan = planFromParams(params);
+ if (kind === "clean-audio-transcribed") return { ok: true, call: "clean", ...(plan ? { plan } : {}) };
+ if (kind === "clean-audio-retry") return { ok: true, call: "clean" };
+ if (kind === "clean-audio-unchecked") {
+ if (params?.unchecked === "button") return { ok: true, call: "unchecked", ...(plan ? { plan } : {}) };
+ if (params?.unchecked === "channel-setting") return { ok: true, call: "clean", ...(plan ? { plan } : {}) };
+ return {
+ ok: false,
+ error: "This clean without checking carries no unchecked flag to replay it with — run Clean audio or Clean without checking instead.",
+ };
+ }
+ return { ok: false, error: `not a clean-audio kind: ${kind}` };
}
function clock(ms: number): string {
@@ -90,6 +147,7 @@ export async function runCleanAudioJob({
paths,
jobId,
unchecked,
+ plan,
retry,
onLog,
signal,
@@ -98,7 +156,12 @@ export async function runCleanAudioJob({
channelSlug: string;
paths: Paths;
jobId: string;
+ // Why the job was queued unchecked. "button": a person confirmed a counted
+ // plan (`plan` required). "channel-setting": the channel's key — RE-READ
+ // HERE, when the job starts (ruling 3).
unchecked?: UncheckedReason;
+ // The confirmed plan's video ids: the run removes at most these.
+ plan?: readonly string[];
retry?: CleanRetry;
onLog: (m: string) => void;
signal?: AbortSignal;
@@ -107,28 +170,33 @@ export async function runCleanAudioJob({
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) {
+ // --- Unchecked, decided NOW --------------------------------------------------
+ let mode: UncheckedReason | undefined = unchecked;
+ if (mode === "button" && !plan) {
+ return { end: "failed", sentence: PLAN_LOST_SENTENCE };
+ }
+ if (mode === "channel-setting" && !uncheckedReasonFor(config)) {
onLog(
- `Retry ${retry.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} of rate-limited clean ${retry.of}: not before ${clock(retry.notBefore)}.`,
+ "This channel's cleanAudioWithoutChecking was turned off after this clean was queued: it runs CHECKED (the source is asked, as Clean audio does).",
);
- // 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" };
- }
+ mode = undefined;
+ }
+ // A retry is the continuation of a CHECKED request: it stays checked even if
+ // the channel's key was turned on since (nobody confirmed an unchecked run).
+ if (retry) mode = undefined;
+
+ // --- A retry never runs before its time --------------------------------------
+ // The schedule queues it only at its not-before; a spec replayed by hand
+ // earlier than that asks nothing.
+ if (retry && now() < retry.notBefore) {
+ return {
+ end: "failed",
+ sentence: `This retry was started before its time (not before ${clock(retry.notBefore)}): nothing was asked or cleaned.`,
+ };
+ }
+ if (retry) {
+ onLog(`Retry ${retry.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} of rate-limited clean ${retry.of}.`);
}
const result = await cleanAudioFromTranscribed({
@@ -136,8 +204,10 @@ export async function runCleanAudioJob({
paths,
onLog,
signal,
- ...(unchecked ? { unchecked } : {}),
+ ...(mode ? { unchecked: mode } : {}),
+ ...(plan ? { onlyIds: plan } : {}),
...(deps.probes ? { probes: deps.probes } : {}),
+ ...(deps.assertReachable ? { assertReachable: deps.assertReachable } : {}),
});
if (signal?.aborted) return { end: "cancelled" };
const stop = result.stopped;
@@ -165,22 +235,23 @@ export async function runCleanAudioJob({
}
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) {
+ const next: CleanRetry = { attempt: attempt + 1, of: retry?.of ?? jobId, notBefore, platform: stop.platform };
+ const scheduled = await deps.scheduleRetry(next);
+ if (!scheduled.ok) {
return {
end: "failed",
- sentence: `Rate-limited by ${stop.platform} (${counts}); the retry could not be queued: ${queued.error}`,
+ sentence: `Rate-limited by ${stop.platform} (${counts}); the retry could not be scheduled: ${scheduled.error}`,
result,
};
}
return {
end: "deferred",
until: notBefore,
- retryJobId: queued.jobId,
+ retryId: scheduled.id,
sentence:
`Rate-limited by ${stop.platform} (${stop.message}): ${counts}; nothing unverified was deleted. ` +
- `retry ${next.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} queued as job ${queued.jobId}, not before ${clock(notBefore)} — cancel that job to cancel it.`,
+ `Retry ${next.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES} is scheduled, not before ${clock(notBefore)}; it waits off the queue. ` +
+ `Cancel this job to cancel it (or Cancel retry on the channel's Cleanup stage).`,
result,
};
}
diff --git a/common/controller/cleanRetrySchedule.test.ts b/common/controller/cleanRetrySchedule.test.ts
@@ -0,0 +1,211 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import {
+ MAX_REARMS,
+ armCleanRetriesAtBoot,
+ cancelCleanRetries,
+ cleanRetriesFile,
+ finishCleanRetry,
+ readCleanRetries,
+ resetCleanRetryTimers,
+ scheduleCleanRetry,
+ startCleanRetry,
+ type CleanRetryDeps,
+ type ScheduledCleanRetry,
+} from "./cleanRetrySchedule";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanRetrySchedule.test.ts
+//
+// A RATE-LIMITED CLEAN'S RETRY WAITS OFF THE QUEUE (lane clean-unverified,
+// rulings 4 and 5): a durable record and a timer; nothing is queued until its
+// not-before time; a restart re-arms it with its attempt and time; Cancel
+// reaches it. A fake clock and a fake timer table: no real wait.
+
+const T0 = Date.parse("2026-11-21T03:00:00.000Z");
+const MIN = 60_000;
+
+let n = 0;
+async function jobsDir(): Promise<Pick<Paths, "jobsDir">> {
+ return { jobsDir: path.join(await mkdtemp(path.join(tmpdir(), "clean-retry-")), `j${n++}`) };
+}
+
+// A fake "process": a clock, a timer table, and recorders for what it queues
+// and cancels. `restart()` is a new process: every timer is gone.
+function fakeProcess(start = T0) {
+ let now = start;
+ let seq = 0;
+ const pending = new Map<number, { at: number; fn: () => Promise<unknown> }>();
+ const enqueued: ScheduledCleanRetry[] = [];
+ const cancelledJobs: string[] = [];
+ let cooldown = 0;
+ const deps: CleanRetryDeps = {
+ now: () => now,
+ setTimer: (fn, ms) => {
+ const id = ++seq;
+ pending.set(id, { at: now + ms, fn });
+ return id;
+ },
+ clearTimer: (h) => void pending.delete(h as number),
+ cooldownRemainingMs: async () => cooldown,
+ enqueue: async (e) => {
+ enqueued.push({ ...e });
+ return { ok: true, jobId: `job-${enqueued.length}` };
+ },
+ cancelJob: (id) => (cancelledJobs.push(id), true),
+ };
+ return {
+ deps,
+ enqueued,
+ cancelledJobs,
+ pending,
+ setCooldown: (ms: number) => void (cooldown = ms),
+ // Advance the clock, firing due timers (and letting their async work run).
+ async advance(ms: number) {
+ now += ms;
+ for (;;) {
+ const due = [...pending.entries()].filter(([, t]) => t.at <= now).sort((a, b) => a[1].at - b[1].at);
+ if (due.length === 0) break;
+ for (const [id, t] of due) {
+ pending.delete(id);
+ await t.fn();
+ }
+ }
+ },
+ restart() {
+ resetCleanRetryTimers({ clearTimer: (h) => void pending.delete(h as number) });
+ pending.clear();
+ },
+ };
+}
+
+const REQ = { slug: "ch", attempt: 1, of: "J0", deferredJobId: "J0", platform: "rumble", notBefore: T0 + 15 * MIN };
+
+test("a scheduled retry holds nothing while it waits: no job until its not-before, then exactly one", async () => {
+ const p = await jobsDir();
+ const proc = fakeProcess();
+ const entry = await scheduleCleanRetry(p, REQ, proc.deps);
+ assert.equal(entry.id, "J0.retry1");
+ assert.equal(entry.state, "scheduled");
+ // Durable: on disk, with its attempt and time.
+ const onDisk = JSON.parse(await readFile(cleanRetriesFile(p), "utf8"));
+ assert.deepEqual(
+ onDisk.retries.map((e: ScheduledCleanRetry) => [e.id, e.attempt, e.notBefore, e.state]),
+ [["J0.retry1", 1, T0 + 15 * MIN, "scheduled"]],
+ );
+ await proc.advance(15 * MIN - 1000);
+ assert.equal(proc.enqueued.length, 0, "nothing queued a second before its time");
+ await proc.advance(1000);
+ assert.equal(proc.enqueued.length, 1);
+ assert.equal(proc.enqueued[0].attempt, 1);
+ const [after] = await readCleanRetries(p);
+ assert.equal(after.state, "enqueued");
+ assert.equal(after.jobId, "job-1");
+ proc.restart();
+});
+
+test("a cooldown still running when the timer fires moves it to the cooldown's end, a bounded number of times", async () => {
+ const p = await jobsDir();
+ const proc = fakeProcess();
+ await scheduleCleanRetry(p, REQ, proc.deps);
+ proc.setCooldown(10 * MIN);
+ await proc.advance(15 * MIN);
+ assert.equal(proc.enqueued.length, 0, "not queued inside the cooldown");
+ const [moved] = await readCleanRetries(p);
+ assert.equal(moved.notBefore, T0 + 25 * MIN);
+ assert.equal(moved.rearms, 1);
+ // A cooldown that never ends is waited out MAX_REARMS times, then the retry
+ // is queued and meets it (judged a rate limit again).
+ for (let i = 0; i < MAX_REARMS; i++) await proc.advance(10 * MIN);
+ assert.equal(proc.enqueued.length, 1);
+ proc.restart();
+});
+
+test("restart: the record survives, keeps its attempt and time, and is never queued early", async () => {
+ const p = await jobsDir();
+ const first = fakeProcess();
+ await scheduleCleanRetry(p, { ...REQ, attempt: 2 }, first.deps);
+ await first.advance(5 * MIN);
+ first.restart(); // the server goes down; its timer is gone
+
+ const second = fakeProcess(T0 + 6 * MIN);
+ const boot = await armCleanRetriesAtBoot(p, second.deps);
+ assert.deepEqual(boot.armed, ["J0.retry2"]);
+ await second.advance(8 * MIN); // T0 + 14 min
+ assert.equal(second.enqueued.length, 0, "still before its not-before");
+ await second.advance(1 * MIN); // T0 + 15 min
+ assert.equal(second.enqueued.length, 1);
+ assert.equal(second.enqueued[0].attempt, 2, "the attempt count survived the restart");
+ second.restart();
+});
+
+test("restart: a retry caught queued is queued again by its schedule; one caught running is re-armed once, then dropped", async () => {
+ const p = await jobsDir();
+ const a = fakeProcess();
+ await scheduleCleanRetry(p, REQ, a.deps);
+ await a.advance(15 * MIN);
+ assert.equal((await readCleanRetries(p))[0].state, "enqueued");
+ a.restart();
+
+ // Caught queued: the boot pass closes the stale meta; the schedule re-queues.
+ const b = fakeProcess(T0 + 20 * MIN);
+ await armCleanRetriesAtBoot(p, b.deps);
+ await b.advance(0);
+ assert.equal(b.enqueued.length, 1);
+ assert.equal(b.enqueued[0].attempt, 1);
+
+ // Caught running, twice: re-armed the first time, dropped the second.
+ assert.ok(await startCleanRetry(p, "J0.retry1", "job-1"));
+ b.restart();
+ const c = fakeProcess(T0 + 30 * MIN);
+ const boot1 = await armCleanRetriesAtBoot(p, c.deps);
+ assert.deepEqual(boot1, { armed: ["J0.retry1"], dropped: [] });
+ await c.advance(0);
+ assert.ok(await startCleanRetry(p, "J0.retry1", "job-2"));
+ c.restart();
+ const d = fakeProcess(T0 + 40 * MIN);
+ const boot2 = await armCleanRetriesAtBoot(p, d.deps);
+ assert.deepEqual(boot2, { armed: [], dropped: ["J0.retry1"] });
+ assert.deepEqual(await readCleanRetries(p), []);
+ d.restart();
+});
+
+test("cancel by the deferred job's id removes the record and its timer; nothing is queued, and a late start is refused", async () => {
+ const p = await jobsDir();
+ const proc = fakeProcess();
+ await scheduleCleanRetry(p, REQ, proc.deps);
+ assert.equal(proc.pending.size, 1);
+ const removed = await cancelCleanRetries(p, { id: "J0" }, proc.deps);
+ assert.deepEqual(removed.map((e) => e.id), ["J0.retry1"]);
+ assert.equal(proc.pending.size, 0, "its timer is cleared");
+ await proc.advance(60 * MIN);
+ assert.equal(proc.enqueued.length, 0);
+ assert.equal(await startCleanRetry(p, "J0.retry1", "job-x"), null, "a job whose record is gone does not run");
+});
+
+test("cancel of a retry the schedule already queued cancels its job too", async () => {
+ const p = await jobsDir();
+ const proc = fakeProcess();
+ await scheduleCleanRetry(p, REQ, proc.deps);
+ await proc.advance(15 * MIN);
+ await cancelCleanRetries(p, { slug: "ch" }, proc.deps);
+ assert.deepEqual(proc.cancelledJobs, ["job-1"]);
+ assert.deepEqual(await readCleanRetries(p), []);
+});
+
+test("one retry per channel: a new one supersedes the old; another channel's is untouched; finish removes it", async () => {
+ const p = await jobsDir();
+ const proc = fakeProcess();
+ await scheduleCleanRetry(p, REQ, proc.deps);
+ await scheduleCleanRetry(p, { ...REQ, slug: "other", of: "J5", deferredJobId: "J5" }, proc.deps);
+ await scheduleCleanRetry(p, { ...REQ, of: "J9", deferredJobId: "J9" }, proc.deps);
+ assert.deepEqual((await readCleanRetries(p)).map((e) => e.id).sort(), ["J5.retry1", "J9.retry1"]);
+ assert.deepEqual((await readCleanRetries(p)).map((e) => e.slug).sort(), ["ch", "other"]);
+ await finishCleanRetry(p, "J9.retry1");
+ assert.deepEqual((await readCleanRetries(p)).map((e) => e.slug), ["other"]);
+ proc.restart();
+});
diff --git a/common/controller/cleanRetrySchedule.ts b/common/controller/cleanRetrySchedule.ts
@@ -0,0 +1,308 @@
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server";
+
+// THE OFF-QUEUE WAIT OF A RATE-LIMITED CLEAN'S RETRY (lane clean-unverified,
+// review 1 F4–F6, operator rulings 4 and 5).
+//
+// A checked Clean audio the source rate-limited ends deferred and asks for ONE
+// retry, not before `notBefore`. That wait used to happen inside a queued job:
+// it held the channel's queue (every other cleanup, diarize backfill, attach
+// media… and "Clean without checking" itself waited behind it) and, being only
+// in memory and in a queued job's spec, a restart either lost it or re-ran it
+// at once as a fresh request with two more retries.
+//
+// Now the wait is a RECORD and a TIMER, and holds no queue and no job slot:
+// - the record is durable, `<jobsDir>/clean-retries.json`: one entry per
+// scheduled retry, with its attempt, its chain's original job, and its
+// not-before time — so a chain never exceeds 2 retries and never runs
+// earlier than its not-before, whatever restarts happen;
+// - a timer in this process fires at not-before. If the platform's cooldown
+// is still running then (it is re-read), the record moves to the
+// cooldown's end and the timer is re-armed — at most MAX_REARMS times,
+// then the retry is queued anyway and meets the cooldown as a rate limit;
+// - only then is the retry QUEUED, as a `clean-audio-retry` job on the
+// channel's queue, which re-asserts every guard as any job does (and the
+// sweep again immediately before it removes anything);
+// - the boot arms every record again (an idle boot does not, and keeps them).
+// A retry that a restart caught queued is re-armed from its record (the
+// boot pass closes its stale meta: the kind is `rescheduledOnBoot`); one a
+// restart caught RUNNING is re-armed once, then dropped.
+// CANCEL reaches it three ways: `cancelCleanRetries` by the deferred job's id
+// (/jobs' and `pnpm ops job {"verb":"cancel"}`'s Cancel of that job, through
+// cancelJobAction), the channel's Cleanup stage ("Cancel retry"), and any
+// new clean of the channel a person starts, which supersedes it. A record
+// cancelled while its job is queued cancels that job too.
+
+export type ScheduledCleanRetry = {
+ // This retry's own id: `<of>.retry<attempt>`.
+ id: string;
+ slug: string;
+ // 1-based; at most CLEAN_RATE_LIMIT_MAX_RETRIES (cleanAudioJob.ts).
+ attempt: number;
+ // The ORIGINAL request's job id (the chain's).
+ of: string;
+ // The job that ended deferred and asked for this retry.
+ deferredJobId: string;
+ // The platform key the rate limit was recorded under (its cooldown).
+ platform: string;
+ // Never queued before this (epoch ms).
+ notBefore: number;
+ scheduledAt: number;
+ // scheduled: waiting off-queue. enqueued: its job is in the channel queue.
+ // running: its job started (removed when the job ends).
+ state: "scheduled" | "enqueued" | "running";
+ jobId?: string;
+ // Times the timer moved later for a platform cooldown still running.
+ rearms?: number;
+ // Times a restart caught it running and it was re-armed.
+ restarts?: number;
+};
+
+type StoreFile = { version: 1; retries: ScheduledCleanRetry[] };
+
+export const CLEAN_RETRIES_FILENAME = "clean-retries.json";
+export const MAX_REARMS = 8;
+// setTimeout's ceiling (~24.8 days); a longer wait is re-armed when it fires.
+const MAX_TIMER_MS = 2 ** 31 - 1;
+
+export function cleanRetriesFile(paths: Pick<Paths, "jobsDir">): string {
+ return path.join(paths.jobsDir, CLEAN_RETRIES_FILENAME);
+}
+
+function isEntry(v: unknown): v is ScheduledCleanRetry {
+ const e = v as Partial<ScheduledCleanRetry> | null;
+ return (
+ !!e &&
+ typeof e.id === "string" &&
+ typeof e.slug === "string" &&
+ typeof e.attempt === "number" &&
+ typeof e.of === "string" &&
+ typeof e.notBefore === "number" &&
+ (e.state === "scheduled" || e.state === "enqueued" || e.state === "running")
+ );
+}
+
+export async function readCleanRetries(paths: Pick<Paths, "jobsDir">): Promise<ScheduledCleanRetry[]> {
+ const r = await readJsonFile(cleanRetriesFile(paths));
+ if (!r.ok) return [];
+ const list = (r.value as Partial<StoreFile> | null)?.retries;
+ return Array.isArray(list) ? list.filter(isEntry) : [];
+}
+
+// Read-modify-write under the file's lock; `fn` returns the new list, or
+// `list: null` when nothing changed (no write: a clean with no retry
+// scheduled writes nothing).
+async function update<T>(
+ paths: Pick<Paths, "jobsDir">,
+ fn: (list: ScheduledCleanRetry[]) => { list: ScheduledCleanRetry[] | null; out: T },
+): Promise<T> {
+ const file = cleanRetriesFile(paths);
+ return withJsonFileLock(file, async () => {
+ const { list, out } = fn(await readCleanRetries(paths));
+ if (list) await writeJsonAtomic(file, { version: 1, retries: list } satisfies StoreFile, { mkdir: true });
+ return out;
+ });
+}
+
+export type CleanRetryDeps = {
+ now?: () => number;
+ // The timer's callback answers the fire's promise (a test awaits it).
+ setTimer?: (fn: () => Promise<unknown>, ms: number) => unknown;
+ clearTimer?: (handle: unknown) => void;
+ cooldownRemainingMs: (platform: string) => Promise<number>;
+ // Queue the retry's job on the channel's queue.
+ enqueue: (entry: ScheduledCleanRetry) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>;
+ // Cancel a queued job (the registry's cancel).
+ cancelJob?: (jobId: string) => boolean;
+ log?: (m: string) => void;
+};
+
+// The timers of this process, keyed by retry id; on globalThis like the
+// registry, so a reloaded module does not arm a second timer for one record.
+type TimerState = { timers: Map<string, unknown> };
+declare global {
+ // eslint-disable-next-line no-var
+ var __yttCleanRetryTimers__: TimerState | undefined;
+}
+function timers(): Map<string, unknown> {
+ return (globalThis.__yttCleanRetryTimers__ ??= { timers: new Map() }).timers;
+}
+
+function clearTimerFor(id: string, deps: CleanRetryDeps): void {
+ const t = timers().get(id);
+ if (t !== undefined) (deps.clearTimer ?? ((h) => clearTimeout(h as ReturnType<typeof setTimeout>)))(t);
+ timers().delete(id);
+}
+
+function arm(paths: Pick<Paths, "jobsDir">, entry: ScheduledCleanRetry, deps: CleanRetryDeps): void {
+ clearTimerFor(entry.id, deps);
+ const now = (deps.now ?? Date.now)();
+ const ms = Math.min(MAX_TIMER_MS, Math.max(0, entry.notBefore - now));
+ const set = deps.setTimer ?? ((fn: () => Promise<unknown>, d: number) => setTimeout(() => void fn(), d));
+ const handle = set(() => {
+ timers().delete(entry.id);
+ return fireCleanRetry(paths, entry.id, deps).catch((err) =>
+ deps.log?.(`[clean-retry] ${entry.id}: ${(err as Error).message}`),
+ );
+ }, ms);
+ timers().set(entry.id, handle);
+}
+
+// Schedule a retry: write its record, arm its timer. A channel has at most one
+// scheduled retry: a record already there for the slug is superseded.
+export async function scheduleCleanRetry(
+ paths: Pick<Paths, "jobsDir">,
+ req: Omit<ScheduledCleanRetry, "id" | "state" | "scheduledAt">,
+ deps: CleanRetryDeps,
+): Promise<ScheduledCleanRetry> {
+ const entry: ScheduledCleanRetry = {
+ ...req,
+ id: `${req.of}.retry${req.attempt}`,
+ state: "scheduled",
+ scheduledAt: (deps.now ?? Date.now)(),
+ };
+ const superseded = await update(paths, (list) => ({
+ list: [...list.filter((e) => e.slug !== req.slug), entry],
+ out: list.filter((e) => e.slug === req.slug),
+ }));
+ for (const old of superseded) {
+ clearTimerFor(old.id, deps);
+ if (old.state === "enqueued" && old.jobId) deps.cancelJob?.(old.jobId);
+ }
+ arm(paths, entry, deps);
+ return entry;
+}
+
+// The timer fired: queue the retry, or move it to the end of a cooldown that
+// is still running. A record cancelled meanwhile is simply not there.
+export async function fireCleanRetry(
+ paths: Pick<Paths, "jobsDir">,
+ id: string,
+ deps: CleanRetryDeps,
+): Promise<"enqueued" | "rearmed" | "gone" | "early" | "failed"> {
+ const now = (deps.now ?? Date.now)();
+ const entry = (await readCleanRetries(paths)).find((e) => e.id === id);
+ if (!entry || entry.state !== "scheduled") return "gone";
+ // Never before its time (a long wait is armed in setTimeout-sized steps).
+ if (now < entry.notBefore) {
+ arm(paths, entry, deps);
+ return "early";
+ }
+ const cooldown = await deps.cooldownRemainingMs(entry.platform).catch(() => 0);
+ if (cooldown > 0 && (entry.rearms ?? 0) < MAX_REARMS) {
+ const moved = await update(paths, (list) => {
+ const e = list.find((x) => x.id === id && x.state === "scheduled");
+ if (!e) return { list: null, out: null };
+ e.notBefore = now + cooldown;
+ e.rearms = (e.rearms ?? 0) + 1;
+ return { list, out: { ...e } };
+ });
+ if (!moved) return "gone";
+ deps.log?.(`[clean-retry] ${id}: ${entry.platform} is still cooling down; moved to ${new Date(moved.notBefore).toISOString()}.`);
+ arm(paths, moved, deps);
+ return "rearmed";
+ }
+ const res = await deps.enqueue(entry).catch((err) => ({ ok: false as const, error: (err as Error).message }));
+ if (!res.ok) {
+ await update(paths, (list) => ({ list: list.filter((e) => e.id !== id), out: null }));
+ deps.log?.(`[clean-retry] ${id}: could not be queued (${res.error}); dropped.`);
+ return "failed";
+ }
+ const kept = await update(paths, (list) => {
+ const e = list.find((x) => x.id === id);
+ if (!e) return { list: null, out: false };
+ // A Start that raced ahead of this write has already moved it on.
+ if (e.state === "scheduled") {
+ e.state = "enqueued";
+ e.jobId = res.jobId;
+ }
+ return { list, out: true };
+ });
+ // Cancelled between the enqueue and this write: cancel the job too.
+ if (!kept) deps.cancelJob?.(res.jobId);
+ return "enqueued";
+}
+
+// The retry's job started: mark it running. Null = the record is gone (it was
+// cancelled or superseded) and the job must not run.
+export async function startCleanRetry(
+ paths: Pick<Paths, "jobsDir">,
+ id: string,
+ jobId: string,
+): Promise<ScheduledCleanRetry | null> {
+ return update(paths, (list) => {
+ const e = list.find((x) => x.id === id);
+ if (!e) return { list: null, out: null };
+ e.state = "running";
+ e.jobId = jobId;
+ return { list, out: { ...e } };
+ });
+}
+
+// The retry's job ended, however it ended: its record goes.
+export async function finishCleanRetry(paths: Pick<Paths, "jobsDir">, id: string): Promise<void> {
+ await update(paths, (list) => ({ list: list.some((e) => e.id === id) ? list.filter((e) => e.id !== id) : null, out: null }));
+}
+
+// Cancel scheduled retries: by the slug, by a retry's own id, by the job that
+// ended deferred, or by the chain's original job. A record whose job is
+// queued cancels that job too; a RUNNING retry is the job's own Cancel's.
+export async function cancelCleanRetries(
+ paths: Pick<Paths, "jobsDir">,
+ match: { slug?: string; id?: string },
+ deps: Pick<CleanRetryDeps, "cancelJob" | "clearTimer">,
+): Promise<ScheduledCleanRetry[]> {
+ const hit = (e: ScheduledCleanRetry) =>
+ e.state !== "running" &&
+ ((match.slug !== undefined && e.slug === match.slug) ||
+ (match.id !== undefined && (e.id === match.id || e.deferredJobId === match.id || e.of === match.id || e.jobId === match.id)));
+ const removed = await update(paths, (list) => {
+ const out = list.filter(hit);
+ return { list: out.length ? list.filter((e) => !hit(e)) : null, out };
+ });
+ for (const e of removed) {
+ clearTimerFor(e.id, deps as CleanRetryDeps);
+ if (e.state === "enqueued" && e.jobId) deps.cancelJob?.(e.jobId);
+ }
+ return removed;
+}
+
+// THE BOOT: arm every record again. A retry a restart caught queued is
+// scheduled again (its time has passed, so it is queued at once — never
+// earlier than its not-before). One caught running is re-armed once; a second
+// time it is dropped, so a retry that takes the server down cannot loop.
+export async function armCleanRetriesAtBoot(
+ paths: Pick<Paths, "jobsDir">,
+ deps: CleanRetryDeps,
+): Promise<{ armed: string[]; dropped: string[] }> {
+ const out = await update(paths, (list) => {
+ const armed: ScheduledCleanRetry[] = [];
+ const dropped: string[] = [];
+ const next: ScheduledCleanRetry[] = [];
+ for (const e of list) {
+ if (e.state === "running") {
+ if ((e.restarts ?? 0) >= 1) {
+ dropped.push(e.id);
+ continue;
+ }
+ e.restarts = (e.restarts ?? 0) + 1;
+ }
+ e.state = "scheduled";
+ delete e.jobId;
+ next.push(e);
+ armed.push({ ...e });
+ }
+ return { list: list.length ? next : null, out: { armed, dropped } };
+ });
+ for (const e of out.armed) arm(paths, e, deps);
+ for (const id of out.dropped) {
+ deps.log?.(`[clean-retry] ${id}: a restart interrupted it twice while it ran; dropped (run Clean audio again).`);
+ }
+ return { armed: out.armed.map((e) => e.id), dropped: out.dropped };
+}
+
+// For tests: forget every timer of this process (clearing each).
+export function resetCleanRetryTimers(deps: Pick<CleanRetryDeps, "clearTimer"> = {}): void {
+ for (const id of [...timers().keys()]) clearTimerFor(id, deps as CleanRetryDeps);
+}
diff --git a/common/controller/cleanUnchecked.test.ts b/common/controller/cleanUnchecked.test.ts
@@ -1,6 +1,6 @@
import { test } from "node:test";
import assert from "node:assert/strict";
-import { access, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";
+import { access, mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { Paths } from "../lib/paths";
@@ -15,6 +15,8 @@ import { uncheckedReasonFor } from "./cleanAudioJob";
import { parseChannelConfig } from "../lib/channelConfig";
import { channelConfigSchema } from "../lib/channelConfigSchema";
import { EnumerationIncompleteError } from "../ytdlp/runYtdlp";
+import { loadSavedVideo, persistSourceVideo } from "../lib/savedVideo-server";
+import { createChannel, readChannelConfig } from "./channels";
// Run with:
// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/cleanUnchecked.test.ts
@@ -84,6 +86,7 @@ async function corpus(config: Record<string, unknown> = {}) {
const paths = {
channelsDir: path.join(dir, "channels"),
transcriptsDir: dir,
+ savedVideosDir: path.join(dir, "saved"),
ytdlpBin: path.join(dir, "no-such-ytdlp"),
} as unknown as Paths;
await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true });
@@ -93,10 +96,18 @@ async function corpus(config: Record<string, unknown> = {}) {
);
const video = async (
id: string,
- o: { transcript?: boolean; diarization?: "plain" | "voiceprints"; doNotClean?: boolean; gone?: boolean; bytes?: number } = {},
+ o: {
+ transcript?: boolean;
+ diarization?: "plain" | "voiceprints";
+ doNotClean?: boolean;
+ gone?: boolean;
+ bytes?: number;
+ uploadDate?: string;
+ } = {},
) => {
const v = path.join(paths.channelsDir, "ch", "data", id);
await mkdir(v, { recursive: true });
+ if (o.uploadDate) await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id, upload_date: o.uploadDate }));
if (o.transcript !== false) await writeFile(path.join(v, "transcript.json"), "{}");
await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(o.bytes ?? 1000));
if (o.diarization === "plain") await writeFile(path.join(v, "diarization.json"), sidecar(false));
@@ -158,6 +169,7 @@ test("the dry plan counts exactly what the unchecked clean removes, and asks not
const plan = await planAudioClean({ channelSlug: "ch", paths });
assert.deepEqual(plan, {
inspected: 6,
+ ids: ["expired", "listed"],
videos: 2,
files: 2,
bytes: 5000,
@@ -300,3 +312,180 @@ test("key off: clean after capture is unchanged — no verdict, held awaiting a
assert.equal(started, 1);
assert.equal(await exists(path.join(v, "audio.mp3")), true);
});
+
+// --- Review 1 -----------------------------------------------------------------
+
+test("F1 (BLOCKING): an unchecked sweep never prunes a saved video container — a rolled-out keep-latest container of an expired VOD survives", async () => {
+ await settings({ enabled: false });
+ const { paths, video } = await corpus({ keepLatest: 1 });
+ // The newest video is in the window; the old one rolled out of it, has a
+ // transcript, audio and a saved container kept by the window — and is gone
+ // from the source (its VOD expired). The container may be its only copy.
+ await video("new", { uploadDate: "20261101" });
+ const old = await video("old", { uploadDate: "20261001", gone: true });
+ await writeFile(path.join(old, "source-media.mp4"), "container-bytes");
+ await persistSourceVideo({
+ videoDir: old,
+ sourceFilename: "source-media.mp4",
+ storeDir: path.join(paths.savedVideosDir, "ch", "old"),
+ keepReason: "keep-latest",
+ });
+ const { calls, probes } = throwingProbes();
+ const logs: string[] = [];
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => logs.push(m), unchecked: "button", probes });
+ assert.deepEqual(calls, { quick: 0, full: 0, backoff: 0 });
+ assert.equal(await exists(path.join(old, "audio.mp3")), false, "its audio is what was asked to go");
+ assert.notEqual(await loadSavedVideo(old), null, "the saved container is untouched");
+ assert.equal(await exists(path.join(paths.savedVideosDir, "ch", "old", "source-media.mp4")), true);
+ assert.equal(r.prunedSavedVideos, 0);
+ assert.ok(logs.some((l) => l.startsWith("Saved-video retention prune skipped")), logs.join("\n"));
+ // The keep-latest window held its audio in the unchecked path too.
+ assert.equal(await exists(path.join(paths.channelsDir, "ch", "data", "new", "audio.mp3")), true, "in the keep-latest window");
+});
+
+test("the keep-latest window: the unchecked sweep and its plan both keep it", async () => {
+ await settings({ enabled: false });
+ const { paths, video } = await corpus({ keepLatest: 2 });
+ const a = await video("a", { uploadDate: "20261103" });
+ const b = await video("b", { uploadDate: "20261102" });
+ const c = await video("c", { uploadDate: "20261101" });
+ const plan = await planAudioClean({ channelSlug: "ch", paths });
+ assert.deepEqual(plan.ids, ["c"]);
+ assert.equal(plan.protected, 2);
+ const { probes } = throwingProbes();
+ await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, unchecked: "button", onlyIds: plan.ids, probes });
+ assert.equal(await exists(path.join(a, "audio.mp3")), true);
+ assert.equal(await exists(path.join(b, "audio.mp3")), true);
+ assert.equal(await exists(path.join(c, "audio.mp3")), false);
+});
+
+test("F2: plan, then the corpus changes, then the run — it removes only the intersection and leaves the newly eligible", async () => {
+ await settings({});
+ const { paths, video } = await corpus();
+ const p1 = await video("p1", { diarization: "voiceprints" });
+ const p2 = await video("p2", { diarization: "voiceprints" });
+ const later = await video("later", { diarization: "plain" }); // awaiting a fingerprint at plan time
+ const plan = await planAudioClean({ channelSlug: "ch", paths });
+ assert.deepEqual(plan.ids, ["p1", "p2"]);
+ assert.equal(plan.awaitingVoiceprint, 1);
+ // Meanwhile: p2 is marked do not clean; "later" gets its fingerprints.
+ await writeFile(path.join(p2, "do-not-clean.json"), JSON.stringify({ setAt: "now" }));
+ await writeFile(path.join(later, "diarization.json"), sidecar(true));
+ const { calls, probes } = throwingProbes();
+ const logs: string[] = [];
+ const r = await cleanAudioFromTranscribed({
+ channelSlug: "ch",
+ paths,
+ onLog: (m) => logs.push(m),
+ unchecked: "button",
+ onlyIds: plan.ids,
+ probes,
+ });
+ assert.deepEqual(calls, { quick: 0, full: 0, backoff: 0 });
+ assert.equal(await exists(path.join(p1, "audio.mp3")), false);
+ assert.equal(await exists(path.join(p2, "audio.mp3")), true, "became protected since: skipped");
+ assert.equal(await exists(path.join(later, "audio.mp3")), true, "newly eligible: not in the confirmed plan");
+ assert.equal(r.cleanedDirs, 1);
+ assert.equal(r.notInPlan, 1);
+ assert.equal(r.planNoLongerEligible, 1);
+ assert.ok(logs.some((l) => l.includes("left for the next run (not in the confirmed plan)")), logs.join("\n"));
+});
+
+test("tier-linked audio: the plan counts the bytes through the link, and the sweep removes link and bytes", async () => {
+ await settings({ enabled: false });
+ const { paths, video } = await corpus();
+ const v = await video("t1", { bytes: 1 });
+ // Tier the audio: the real file in channels/ch/media/t1/, a relative link in data/t1/.
+ const mediaDir = path.join(paths.channelsDir, "ch", "media", "t1");
+ await mkdir(mediaDir, { recursive: true });
+ await writeFile(path.join(mediaDir, "audio.mp3"), Buffer.alloc(4096));
+ await rm(path.join(v, "audio.mp3"));
+ await symlink("../../media/t1/audio.mp3", path.join(v, "audio.mp3"));
+ const plan = await planAudioClean({ channelSlug: "ch", paths });
+ assert.equal(plan.bytes, 4096);
+ const { probes } = throwingProbes();
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, unchecked: "button", onlyIds: plan.ids, probes });
+ assert.equal(r.bytesFreed, 4096);
+ assert.equal(await exists(path.join(mediaDir, "audio.mp3")), false, "the bytes on the media tier go with the link");
+});
+
+test("an unreachable drive or a relocation in flight: the plan refuses, and the sweep removes nothing", async () => {
+ await settings({ enabled: false });
+ for (const hold of ["relocating", "unmounted"] as const) {
+ const { paths, video } = await corpus(
+ hold === "unmounted" ? { mediaDir: "/nonexistent-drive/ch/media" } : {},
+ );
+ const v = await video("v1");
+ const channelDir = path.join(paths.channelsDir, "ch");
+ if (hold === "relocating") {
+ await writeFile(
+ path.join(channelDir, ".relocating.json"),
+ JSON.stringify({ target: "/elsewhere/ch/media", direction: "out", startedAt: "now", phase: "copy", scope: "media" }),
+ );
+ } else {
+ await symlink("/nonexistent-drive/ch/media", path.join(channelDir, "media"));
+ }
+ const why = hold === "relocating" ? /relocation/ : /does not exist/;
+ await assert.rejects(planAudioClean({ channelSlug: "ch", paths }), why);
+ const { probes } = throwingProbes();
+ await assert.rejects(
+ cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, unchecked: "button", onlyIds: ["v1"], probes }),
+ why,
+ );
+ assert.equal(await exists(path.join(v, "audio.mp3")), true, `${hold}: nothing removed`);
+ }
+});
+
+test("an empty transcript.json counts as transcribed in both paths alike (parity: the name decides, as before this lane)", async () => {
+ await settings({ enabled: false });
+ const { paths, video } = await corpus();
+ await video("e1"); // transcript.json is "{}"
+ const plan = await planAudioClean({ channelSlug: "ch", paths });
+ assert.deepEqual(plan.ids, ["e1"]);
+});
+
+test("key on: clean after capture still holds a whole-recording channel's audio and a URL-less channel's", async () => {
+ await settings({ enabled: false });
+ const whole = await corpus({ cleanAudioWithoutChecking: true, url: "https://rumble.com/c/example", platform: "rumble" });
+ const w = await whole.video("w1");
+ const out1 = await cleanAudioForVideo({ channelSlug: "ch", paths: whole.paths, videoId: "w1", onLog: () => {}, checkDeps: NO_CHECK });
+ assert.equal(out1.gate, "whole-recording");
+ assert.equal(await exists(path.join(w, "audio.mp3")), true);
+ const nourl = await corpus({ cleanAudioWithoutChecking: true, url: undefined });
+ const u = await nourl.video("u1");
+ const out2 = await cleanAudioForVideo({ channelSlug: "ch", paths: nourl.paths, videoId: "u1", onLog: () => {}, checkDeps: NO_CHECK });
+ assert.equal(out2.gate, "no-source-url");
+ assert.equal(await exists(path.join(u, "audio.mp3")), true);
+});
+
+test("no leak: a channel beside a key-on one is cleaned checked", async () => {
+ await settings({ enabled: false });
+ const { paths, video } = await corpus({ cleanAudioWithoutChecking: true });
+ await video("k1");
+ // A second channel in the same corpus, key absent.
+ const other = path.join(paths.channelsDir, "other", "data", "o1");
+ await mkdir(other, { recursive: true });
+ await writeFile(path.join(paths.channelsDir, "other", "config.json"), JSON.stringify({ handling: "transcribe", name: "o", url: "https://www.twitch.tv/other" }));
+ await writeFile(path.join(other, "transcript.json"), "{}");
+ await writeFile(path.join(other, "audio.mp3"), Buffer.alloc(10));
+ assert.equal(uncheckedReasonFor(await readChannelConfig(paths, "other")), undefined);
+ assert.equal(uncheckedReasonFor(await readChannelConfig(paths, "ch")), "channel-setting");
+ let started = 0;
+ const out = await cleanAudioForVideo({
+ channelSlug: "other",
+ paths,
+ videoId: "o1",
+ onLog: () => {},
+ checkDeps: { start: async () => (started++, { ok: true, jobId: "x" }) as never, platformRefusal: async () => null, serviceAlert: async () => null },
+ });
+ assert.equal(out.gate, "awaiting-availability", "the other channel is checked");
+ assert.equal(started, 1);
+});
+
+test("a new channel never starts with cleanAudioWithoutChecking: createChannel drops it", async () => {
+ const { paths } = await corpus();
+ await createChannel(paths, "fresh", parseChannelConfig({ handling: "transcribe", name: "f", cleanAudioWithoutChecking: true })!);
+ const cfg = JSON.parse(await readFile(path.join(paths.channelsDir, "fresh", "config.json"), "utf8"));
+ assert.equal("cleanAudioWithoutChecking" in cfg, false);
+ assert.equal(cfg.name, "f");
+});
diff --git a/common/jobs/bootQueuedJobs.test.ts b/common/jobs/bootQueuedJobs.test.ts
@@ -616,3 +616,30 @@ test("a queued x-run is cancelled as `person`, never re-queued", async () => {
await rm(f.root, { recursive: true, force: true });
}
});
+
+// Lane clean-unverified (review 1, F5): a rate-limited clean's retry left
+// QUEUED by a restart is never re-queued from its spec — that would run it at
+// once as a fresh request with two more retries. Its schedule's record
+// (controller/cleanRetrySchedule.ts) queues it again, attempt and not-before
+// kept. A queued unchecked clean IS re-queued, its carried plan in its spec.
+test("a queued clean-audio-retry is closed `rescheduled`; a queued unchecked clean is re-queued with its plan", async () => {
+ const retry: JobSpec = {
+ kind: "clean-audio-retry",
+ slug: "ch",
+ params: { retry: { attempt: 1, of: "J0", notBefore: BOOT - 1, platform: "rumble", id: "J0.retry1" } },
+ };
+ const unchecked: JobSpec = { kind: "clean-audio-unchecked", slug: "ch", params: { unchecked: "button", plan: ["a", "b"] } };
+ const f = await fixture([
+ { id: "R1", kind: "clean-audio-retry", queueKey: "channel:ch", spec: retry },
+ { id: "U1", kind: "clean-audio-unchecked", queueKey: "channel:ch", spec: unchecked },
+ ]);
+ try {
+ const rq = recordingRequeue();
+ const res = await settleQueuedJobMetas({ paths: f.paths, requeue: rq.fn, bootedAt: BOOT, log: () => {} });
+ assert.deepEqual(rq.calls, [unchecked]);
+ assert.deepEqual(res.cancelled.map((c) => [c.id, c.category]), [["R1", "rescheduled"]]);
+ assert.match((await f.read("R1")).cancelReason ?? "", /queued again by its schedule/);
+ } finally {
+ await rm(f.root, { recursive: true, force: true });
+ }
+});
diff --git a/common/jobs/bootQueuedJobs.ts b/common/jobs/bootQueuedJobs.ts
@@ -28,7 +28,8 @@ import { getJobKind, isPublishStageJobKind } from "./jobKinds";
// lane and Publish now re-derive stages from the stamps on disk, and a
// stage re-queued with its run's preconditions would wait on a run that
// is gone; nor is a kind that starts only on a person's click
-// (`startedByPerson`: the X run);
+// (`startedByPerson`: the X run); nor one its own durable schedule
+// queues again (`rescheduledOnBoot`: a rate-limited clean's retry);
// 3. a meta queued more than REQUEUE_MAX_AGE_MS before this boot is stale;
// 4. a meta with no replay spec cannot be re-queued;
// 5. of what is left, only the NEWEST meta per kind + channel + params is
@@ -56,7 +57,15 @@ export type RequeueFn = (
) => Promise<{ ok: true; jobId: string } | { ok: false; error: string }>;
export type CancelCategory =
- "idle" | "sync" | "publish" | "person" | "stale" | "no-spec" | "superseded" | "refused";
+ | "idle"
+ | "sync"
+ | "publish"
+ | "person"
+ | "rescheduled"
+ | "stale"
+ | "no-spec"
+ | "superseded"
+ | "refused";
export type BootQueuedResult = {
requeued: { id: string; newId: string }[];
@@ -300,6 +309,9 @@ export async function settleQueuedJobMetas(
} else if (getJobKind(meta.kind)?.startedByPerson) {
// An X run starts only on a person's click, never by a boot.
await cancel(meta, "person", PERSON_RESTART_REASON);
+ } else if (getJobKind(meta.kind)?.rescheduledOnBoot) {
+ // Its own durable schedule queues it again (a rate-limited clean's retry).
+ await cancel(meta, "rescheduled", getJobKind(meta.kind)!.rescheduledOnBoot!);
} else if (
typeof meta.queuedAt !== "number" ||
opts.bootedAt - meta.queuedAt > maxAgeMs
diff --git a/common/jobs/jobKinds.test.ts b/common/jobs/jobKinds.test.ts
@@ -212,6 +212,7 @@ const STILL_MEDIA = [
"scan-media-channel",
"clean-audio-transcribed",
"clean-audio-unchecked",
+ "clean-audio-retry",
"clean-extra-audio-formats",
"remove-wrong-format-audio",
"reports-prepare",
@@ -457,3 +458,17 @@ test("lane clean-unverified: the unchecked clean is its own kind, so its title s
assert.equal(isDrainableKind("clean-audio-unchecked"), false);
assert.equal(kindIsNetwork("clean-audio-unchecked"), false);
});
+
+test("lane clean-unverified: a rate-limited clean's retry is its own kind, queued again by its schedule at boot", () => {
+ const meta = getJobKind("clean-audio-retry");
+ assert.ok(meta, "registered");
+ assert.equal(jobKindLabel("clean-audio-retry"), "Clean audio (rate-limit retry)");
+ assert.equal(kindNeedsMedia("clean-audio-retry"), true);
+ assert.equal(meta.replayable, true);
+ assert.equal(meta.resumeOnBoot, undefined);
+ assert.match(meta.rescheduledOnBoot ?? "", /queued again by its schedule/);
+ // Neither of the other two clean kinds is rescheduled: the boot re-queues a
+ // queued one from its spec (an unchecked one with its carried plan).
+ assert.equal(getJobKind("clean-audio-unchecked")?.rescheduledOnBoot, undefined);
+ assert.equal(getJobKind("clean-audio-transcribed")?.rescheduledOnBoot, undefined);
+});
diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts
@@ -103,6 +103,13 @@ export type JobKindMeta = {
// as interrupted, and Resume on /review is the person's click. Absent
// means false.
startedByPerson?: boolean;
+ // Whether a job of this kind is queued by a DURABLE SCHEDULE of its own,
+ // which the boot re-arms: one left queued by a restart is closed by the
+ // boot pass with this sentence, never re-queued from its spec — the
+ // schedule queues it again (lane clean-unverified: a rate-limited clean's
+ // retry, controller/cleanRetrySchedule.ts, whose attempt count and
+ // not-before time live in its record). Absent = not.
+ rescheduledOnBoot?: string;
};
// One entry per kind known to the system. `label` is included only where the
@@ -443,6 +450,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = {
queueKeyStrategy: "custom",
needsMedia: true,
},
+ // The retry of a checked Clean audio the source rate-limited, queued on the
+ // channel's queue by its schedule at its not-before time (the wait itself is
+ // off-queue: controller/cleanRetrySchedule.ts). The same sweep, checked; the
+ // same media guard. A person's Retry of it is a fresh Clean audio.
+ "clean-audio-retry": {
+ kind: "clean-audio-retry",
+ label: "Clean audio (rate-limit retry)",
+ drainable: false,
+ replayable: true,
+ queueKeyStrategy: "custom",
+ needsMedia: true,
+ rescheduledOnBoot:
+ "server restarted; a rate-limited clean's retry is queued again by its schedule (its attempt and not-before time are kept), not re-queued from its spec",
+ },
// Speaker-diarization backfill over a channel's retained audio. The capture
// lane's catch-all: it picks up everything the post-transcribe hook missed
// (videos transcribed before the feature, or with the inline hook off — which
diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts
@@ -293,6 +293,11 @@ class JobRegistry {
this.shuttingDown = true;
}
+ // Whether the reaper has begun: a cancel now is nobody's decision.
+ isShuttingDown(): boolean {
+ return this.shuttingDown;
+ }
+
register(record: JobRecord): void {
this.jobs.set(record.id, record);
// Bound the registry. Drop oldest finished records past 100, but never
diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts
@@ -129,12 +129,6 @@ export type JobRunContext = {
// recorded on the record and its sidecar as `handedOffTo`, so a caller
// waiting for the work follows it there.
handOff: (jobId: string) => void;
- // A WAIT THIS JOB IS SITTING OUT after its queue started it, drawn on /jobs
- // as the queue gap's is ("waiting 4m12s: <reason>", JobRecord.pacedUntil /
- // pacedReason); undefined clears it. Used by a rate-limited clean's queued
- // retry (controller/cleanAudioJob.ts). Optional: a job's own test contexts
- // need not provide it.
- setPaced?: (wait?: { until: number; reason: string }) => void;
};
export type RunManagedFunctionOpts = CommonOpts & {
@@ -526,10 +520,6 @@ export async function runManagedFunction(
record.handedOffTo = jobId;
persistMeta();
},
- setPaced: (w) => {
- record.pacedUntil = w?.until;
- record.pacedReason = w?.reason;
- },
};
// THE GUARD AGAIN, NOW THAT THE QUEUE HAS STARTED THE JOB (see
diff --git a/common/lib/channelConfig.ts b/common/lib/channelConfig.ts
@@ -374,7 +374,7 @@ export const CHANNEL_CONFIG_FIELD_DOCS: FieldDocs<ChannelConfig> = {
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}`.",
+ "Every clean of this channel's transcribed audio runs WITHOUT the availability check: the Clean audio button, the /cleanup row, `pnpm ops cleanup` and clean after capture alike ask the source nothing, so the audio of a video no longer available anywhere is removed too (it is no longer pinned do-not-clean). Every other protection holds: do-not-clean marks, the keep-latest window, the speaker holds (awaiting diarization / voice fingerprint), untranscribed videos, an unreachable or moving media drive. Those jobs run as \"Clean audio without checking\"; the key is read again when each starts, and a saved video container is never pruned by them. A new channel never starts with it (createChannel drops it). For a platform whose VODs expire by design (Twitch, Kick), where \"gone from the source\" is the normal state; never set by platform. Absent/false = checked. Set on the channel's Cleanup stage or with `pnpm ops channel-config {\"cleanAudioWithoutChecking\": true}`.",
syncIntervalMinutes:
"Auto-sync cadence: the scheduler syncs this channel when `now - lastSyncedAt >= syncIntervalMinutes`. Absent = inherit the global default; 0 = auto-sync off (still manually syncable); positives clamp to [1, 44640] (~31 days). A missing `url`, or a `sync` tier of paused in the channel-priority document, also disables auto-sync. AN INSTAGRAM CHANNEL is synced seldom, because every sync is a logged-in read: absent = every 12 hours at the most often (the global default when that is longer), and a value of its own is never under 240 (4 hours); 0 still turns it off (`common/jobs/syncScheduler.ts`).",
fullSweepIntervalMinutes:
diff --git a/common/lib/cleanAudioConfirm.test.ts b/common/lib/cleanAudioConfirm.test.ts
@@ -0,0 +1,33 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { TURN_ON_CONFIRMATION, cleanConfirmationText } from "./cleanAudioConfirm";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/cleanAudioConfirm.test.ts
+//
+// THE ONE COUNTED CONFIRMATION every button that would clean without checking
+// shows (lane clean-unverified, ruling 6), word for word.
+
+test("the counted confirmation states what goes, that the source is not asked, and what is kept", () => {
+ const t = cleanConfirmationText({ files: 40, bytes: 3 * 1024 ** 3, videos: 38, protected: 12, awaitingDiarization: 3, awaitingVoiceprint: 1 });
+ assert.match(
+ t.ask,
+ /^Remove 40 audio files \(.+\) from 38 transcribed videos without checking\? The source is not asked, so the audio of videos no longer available anywhere is removed too\.$/,
+ );
+ assert.equal(
+ t.kept,
+ "Kept: 12 marked do not clean or in the keep-latest window, 3 awaiting diarization, 1 awaiting voice fingerprint. Videos with no transcript are not touched, and no saved video is.",
+ );
+ assert.equal(t.button, "Remove 40 files without checking");
+ const one = cleanConfirmationText({ files: 1, bytes: 10, videos: 1, protected: 0, awaitingDiarization: 0, awaitingVoiceprint: 0 });
+ assert.match(one.ask, /^Remove 1 audio file \(.+\) from 1 transcribed video without checking\?/);
+ assert.equal(one.button, "Remove 1 file without checking");
+ const none = cleanConfirmationText({ files: 0, bytes: 0, videos: 0, protected: 2, awaitingDiarization: 0, awaitingVoiceprint: 0 });
+ assert.match(none.ask, /^Nothing to remove/);
+});
+
+test("turning the channel key on states what it changes before it changes it", () => {
+ assert.match(TURN_ON_CONFIRMATION, /^Turn on cleaning without checking for this channel\?/);
+ assert.match(TURN_ON_CONFIRMATION, /without asking the source whether the video is still there/);
+ assert.match(TURN_ON_CONFIRMATION, /clean after capture does not ask/);
+});
diff --git a/common/lib/cleanAudioConfirm.ts b/common/lib/cleanAudioConfirm.ts
@@ -0,0 +1,42 @@
+// Client-safe: the counted confirmation of a clean WITHOUT CHECKING (lane
+// clean-unverified), the one text every button that would run unchecked shows
+// — the channel page's Cleanup stage (the one-off button, and Clean audio when
+// the channel's key is on), the /cleanup card and the dashboard's inline
+// buttons. Its numbers are planAudioClean's (no network, no deletes).
+import { formatBytes } from "./format";
+
+// The counts it states: the structural part of controller
+// cleanAudioFromTranscribed's AudioCleanPlan (lib may not import controller).
+export type CleanPlanCounts = {
+ files: number;
+ bytes: number;
+ videos: number;
+ protected: number;
+ awaitingDiarization: number;
+ awaitingVoiceprint: number;
+};
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+
+export function cleanConfirmationText(plan: CleanPlanCounts): { ask: string; kept: string; button: string } {
+ return {
+ ask:
+ plan.files === 0
+ ? "Nothing to remove: no transcribed video here holds audio a clean would take."
+ : `Remove ${plural(plan.files, "audio file")} (${formatBytes(plan.bytes)}) from ${plural(plan.videos, "transcribed video")} without checking? ` +
+ "The source is not asked, so the audio of videos no longer available anywhere is removed too.",
+ kept:
+ `Kept: ${plan.protected} marked do not clean or in the keep-latest window, ` +
+ `${plan.awaitingDiarization} awaiting diarization, ${plan.awaitingVoiceprint} awaiting voice fingerprint. ` +
+ "Videos with no transcript are not touched, and no saved video is.",
+ button: `Remove ${plural(plan.files, "file")} without checking`,
+ };
+}
+
+// The confirmation to turn the channel's key ON: what it changes, stated
+// before it changes it.
+export const TURN_ON_CONFIRMATION =
+ "Turn on cleaning without checking for this channel? From now on every clean of its audio — Clean audio here and on /cleanup, " +
+ "the dashboard's buttons, pnpm ops and clean after capture — deletes audio without asking the source whether the video is still there, " +
+ "so the audio of a video removed upstream is deleted too. The buttons still show a count before they run; clean after capture does not ask. " +
+ "Videos already marked do not clean, the keep-latest window and the speaker holds stay kept.";
diff --git a/common/views/cleanable.ts b/common/views/cleanable.ts
@@ -22,6 +22,10 @@ export type CleanableChannel = {
count: number;
// Reclaim estimate for the primary "clean audio" sweep, net of protection.
bytes: number;
+ // The channel's cleanAudioWithoutChecking: its Clean audio runs without
+ // checking (the button says so, and its click shows the counted
+ // confirmation). Absent = checked.
+ withoutChecking?: boolean;
};
export type CleanablePayload = {
diff --git a/common/views/pipeline/stageStatus.ts b/common/views/pipeline/stageStatus.ts
@@ -145,6 +145,7 @@ const JOB_KIND_TO_STAGE: Record<string, StageId> = {
"diarize-channel": "speakers",
"clean-audio-transcribed": "cleanup",
"clean-audio-unchecked": "cleanup",
+ "clean-audio-retry": "cleanup",
"purge-superseded-auto-subs": "cleanup",
"clean-extra-audio-formats": "cleanup",
"remove-wrong-format-audio": "cleanup",