commit d2d1373879b93d859eff1bb67b48d60885dc3e37
parent f07ebb8aef20fc53d1f905067891be4ca837767d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 14:20:11 -0500
verify before clean: a rate-limited listing verifies the candidates it returned
A checked clean whose channel listing the source rate-limited part-way
cleaned nothing: every candidate went unverified, even those the listing
had already returned. Now:
- EnumerationIncompleteError carries the entries printed before the 429.
- verifyBeforeClean verifies the candidates those entries name (exact id
match; on Rumble the metadata's embed id against embed entries only,
never across id kinds or by substring) and leaves the rest unverified.
- The sweep cleans the verified ones; the job's sentence and log say
"verified N from a partial listing of M entries; K unverified remain".
A candidate the prefix does not name is not a suspect and is never
probed or cleaned in that run. Tests: verifyPartialListing.test.ts.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
8 files changed, 319 insertions(+), 7 deletions(-)
diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts
@@ -110,6 +110,9 @@ export type CleanAudioResult = {
// (`rate-limit`) or it failed (`error`) — and so cleaned nothing it could
// not verify (verifyBeforeClean's CleanVerdicts.stopped).
stopped?: CleanVerifyStop;
+ // The gate was rate-limited part-way through the listing and cleaned the
+ // candidates the partial listing named (CleanVerdicts.partial).
+ partial?: { verified: number; entries: number; unverified: number };
};
type CleanCandidate = {
@@ -277,6 +280,7 @@ export async function cleanAudioFromTranscribed({
let pinned = 0;
let unverified = 0;
let stopped: CleanVerifyStop | undefined;
+ let partial: CleanAudioResult["partial"];
if (verify && candidates.length > 0 && !signal?.aborted) {
const verdicts = await verifyBeforeClean({
channelSlug,
@@ -290,6 +294,7 @@ export async function cleanAudioFromTranscribed({
pinned = verdicts.pinned.size;
unverified = verdicts.unverified.size;
stopped = verdicts.stopped;
+ partial = verdicts.partial;
// A video already pinned by someone else is protected, not newly pinned.
protectedCount += verdicts.alreadyGone.size;
}
@@ -368,6 +373,7 @@ export async function cleanAudioFromTranscribed({
prunedBytes: prune.bytesFreed,
...(notInPlan !== undefined ? { notInPlan, planNoLongerEligible } : {}),
...(stopped ? { stopped } : {}),
+ ...(partial ? { partial } : {}),
};
}
diff --git a/common/controller/cleanAudioJob.ts b/common/controller/cleanAudioJob.ts
@@ -272,7 +272,12 @@ export async function runCleanAudioJob({
const stop = result.stopped;
if (!stop) return { end: "done", result };
- const counts = `${result.cleanedDirs} cleaned, ${result.unverified} left unverified`;
+ // A partial listing (verifyBeforeClean): what it verified is cleaned, and
+ // the sentence says how much of the listing that came from.
+ const partial = result.partial
+ ? `verified ${result.partial.verified} from a partial listing of ${result.partial.entries} entries; ${result.partial.unverified} unverified remain; `
+ : "";
+ const counts = `${partial}${result.cleanedDirs} cleaned, ${result.unverified} left unverified`;
if (stop.kind === "error") {
return {
end: "failed",
diff --git a/common/controller/listingMatch.ts b/common/controller/listingMatch.ts
@@ -0,0 +1,80 @@
+import { extractVideoId } from "../lib/videoId";
+import { recordIdOfVideoDir } from "../lib/videoDir-server.mjs";
+
+// WHICH CANDIDATES A LISTING NAMES (lane verify-resume). The pre-clean check
+// (verifyBeforeClean) may clean a candidate only when a listing ACTUALLY
+// RETURNED it, so the match is exact and by id, never by substring:
+//
+// - every platform: the canonical id of each returned URL (extractVideoId,
+// the id the quick availability check diffs against data-dir names) equals
+// the candidate's directory name — the full check's own rule;
+// - Rumble also has a second id per video (AGENTS.md: the archive keys by
+// the EMBED id, a directory is named for the URL SLUG). A returned
+// `rumble.com/embed/<id>/` URL names the embed id, which is matched against
+// the candidate's metadata.info.json `id` — and only against that: an
+// embed id is never compared with a directory (slug) name, nor a slug with
+// an embed id, so two different videos whose two kinds of id happen to be
+// spelled alike can never vouch for each other.
+
+export type ListingIndex = {
+ // Canonical ids of the returned page (watch) URLs.
+ ids: Set<string>;
+ // Rumble only: ids of returned embed URLs.
+ embedIds: Set<string>;
+ // How many entries were returned (de-duplicated by id).
+ entries: number;
+};
+
+function isRumbleEmbedUrl(url: string): boolean {
+ try {
+ const u = new URL(url);
+ return u.hostname.toLowerCase().endsWith("rumble.com") && u.pathname.split("/").filter(Boolean)[0] === "embed";
+ } catch {
+ return false;
+ }
+}
+
+export function indexListing(urls: Iterable<string>): ListingIndex {
+ const ids = new Set<string>();
+ const embedIds = new Set<string>();
+ for (const url of urls) {
+ const id = extractVideoId(url);
+ if (!id) continue;
+ (isRumbleEmbedUrl(url) ? embedIds : ids).add(id);
+ }
+ return { ids, embedIds, entries: ids.size + embedIds.size };
+}
+
+// A candidate's ids: its directory, and on Rumble its embed id when the
+// metadata names one that is not the directory's own.
+export type CandidateIds = { dir: string; embed?: string };
+
+export async function candidateIdsOf(
+ channelsDir: string,
+ slug: string,
+ dirId: string,
+ platform: string | null,
+): Promise<CandidateIds> {
+ if (platform !== "rumble") return { dir: dirId };
+ const record = await recordIdOfVideoDir(channelsDir, slug, dirId, { platform }).catch(() => dirId);
+ return record && record !== dirId ? { dir: dirId, embed: record } : { dir: dirId };
+}
+
+export function isListed(index: ListingIndex, c: CandidateIds): boolean {
+ if (index.ids.has(c.dir)) return true;
+ return c.embed !== undefined && index.embedIds.has(c.embed);
+}
+
+// The candidates (by directory id) a listing names.
+export async function listedCandidates(
+ opts: { channelsDir: string; slug: string; platform: string | null },
+ candidateIds: readonly string[],
+ index: ListingIndex,
+): Promise<Set<string>> {
+ const out = new Set<string>();
+ if (index.entries === 0) return out;
+ for (const id of candidateIds) {
+ if (isListed(index, await candidateIdsOf(opts.channelsDir, opts.slug, id, opts.platform))) out.add(id);
+ }
+ return out;
+}
diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts
@@ -9,6 +9,7 @@ import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck";
import { recordDownloadBackoff } from "../jobs/downloadBackoff";
import { detectPlatform } from "../lib/platform";
import { EnumerationIncompleteError } from "../ytdlp/runYtdlp";
+import { indexListing, listedCandidates } from "./listingMatch";
// Availability gate for the transcribed-audio cleanup sweep.
//
@@ -48,6 +49,10 @@ export type CleanVerdicts = {
// failed for another reason (`error`). Absent when every tier answered —
// a per-video `error` / `needs_auth` verdict is not a stop.
stopped?: CleanVerifyStop;
+ // A RATE-LIMITED LISTING THAT STILL RETURNED ENTRIES (lane verify-resume):
+ // `verified` candidates were named by the `entries` it printed before the
+ // 429 and are cleanable; `unverified` remain (also in `unverified` above).
+ partial?: { verified: number; entries: number; unverified: number };
};
export type CleanVerifyStop = {
@@ -160,13 +165,35 @@ export async function verifyBeforeClean({
});
maybeMissing = new Set(quick.ids);
} catch (err) {
- // We know this channel is checkable and we got no answer (network, rate
- // limit, extractor break). Fail CLOSED — decision #4 at channel granularity.
+ // We know this channel is checkable and we got no complete answer
+ // (network, rate limit, extractor break). Fail CLOSED — decision #4 at
+ // channel granularity — for everything the source did not name.
const reason = (err as Error)?.message ?? String(err);
- for (const id of remaining) verdicts.unverified.add(id);
- log(
- `Verify before clean: could not verify availability (${reason}) — nothing cleaned this run.`,
- );
+ // A PARTIAL LISTING (lane verify-resume, operator 21 Nov 2026: "take a
+ // partial result and clean files that were found live in the partial").
+ // The entries a rate-limited listing printed before the 429 were returned
+ // by the source in THIS attempt: a candidate among them is as listed as in
+ // a complete listing, and is verified. Matched by id exactly as the full
+ // check matches (listingMatch.ts: both of Rumble's ids, never a substring).
+ // A candidate the prefix does not name is NOT a suspect — the listing
+ // simply never reached it — and stays unverified and untouched.
+ const partial =
+ err instanceof EnumerationIncompleteError && err.urls.length > 0 ? indexListing(err.urls) : null;
+ const listed = partial
+ ? await listedCandidates({ channelsDir: paths.channelsDir, slug: channelSlug, platform }, remaining, partial)
+ : new Set<string>();
+ for (const id of remaining) if (!listed.has(id)) verdicts.unverified.add(id);
+ if (partial) {
+ verdicts.partial = { verified: listed.size, entries: partial.entries, unverified: verdicts.unverified.size };
+ log(
+ `Verify before clean: verified ${listed.size} from a partial listing of ${partial.entries} entries; ` +
+ `${verdicts.unverified.size} unverified remain (${reason}) — only the verified are cleaned this run.`,
+ );
+ } else {
+ log(
+ `Verify before clean: could not verify availability (${reason}) — nothing cleaned this run.`,
+ );
+ }
// A 429 on the listing (runYtdlp's EnumerationIncompleteError) is a rate
// limit: the platform's cooldown is recorded, as Sync records it, so the
// downloads and the retry of this clean both stay away for it.
diff --git a/common/controller/verifyPartialListing.test.ts b/common/controller/verifyPartialListing.test.ts
@@ -0,0 +1,174 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { access, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import { excludedIds, verifyBeforeClean, type VerifyProbes } from "./verifyBeforeClean";
+import { cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed";
+import { runCleanAudioJob, type CleanRetry } from "./cleanAudioJob";
+import { indexListing, isListed } from "./listingMatch";
+import { EnumerationIncompleteError } from "../ytdlp/runYtdlp";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/verifyPartialListing.test.ts
+//
+// A LISTING THE SOURCE RATE-LIMITED PART-WAY (lane verify-resume, operator 21
+// Nov 2026: "take a partial result and clean files that were found live in
+// the partial"). The entries printed before the 429 verify the candidates
+// among them; every other candidate stays unverified and keeps its audio.
+// Temp corpus, a stub lister that rate-limits after N entries; no yt-dlp.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "verify-partial-"));
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await writeFile(process.env.SETTINGS_FILE, JSON.stringify({ verifyAvailabilityBeforeClean: true }));
+process.on("exit", () => void rm(ROOT, { recursive: true, force: true }));
+
+const T0 = Date.parse("2026-11-21T03:00:00.000Z");
+let n = 0;
+
+// A Rumble channel whose candidates are transcribed and hold audio. `embed`
+// gives a candidate a metadata.info.json naming its second (embed) id.
+async function corpus(ids: string[], embed: Record<string, string> = {}): Promise<Paths> {
+ const dir = path.join(ROOT, `c${n++}`);
+ const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: path.join(dir, "no-ytdlp") } as unknown as Paths;
+ await mkdir(path.join(paths.channelsDir, "ch", "data"), { recursive: true });
+ await writeFile(
+ path.join(paths.channelsDir, "ch", "config.json"),
+ JSON.stringify({ handling: "transcribe", name: "ch", url: "https://rumble.com/c/example" }),
+ );
+ for (const id of ids) {
+ const v = path.join(paths.channelsDir, "ch", "data", id);
+ await mkdir(v, { recursive: true });
+ await writeFile(path.join(v, "transcript.json"), "{}");
+ await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(100));
+ if (embed[id]) await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id: embed[id], title: "t" }));
+ }
+ return paths;
+}
+
+const hasAudio = (paths: Paths, id: string) =>
+ access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false);
+
+const watch = (id: string) => `https://rumble.com/${id}-a-title.html`;
+
+// The stub lister: the source returns `urls`, then answers 429.
+function rateLimitedAfter(urls: string[]) {
+ const calls = { quick: 0, full: 0, backoff: 0 };
+ const probes: VerifyProbes = {
+ quick: async () => {
+ calls.quick++;
+ throw new EnumerationIncompleteError(1, "rumble", 3, urls.length, urls);
+ },
+ full: async () => {
+ calls.full++;
+ throw new Error("no per-video probe after a rate-limited listing");
+ },
+ recordBackoff: async () => {
+ calls.backoff++;
+ },
+ };
+ return { calls, probes };
+}
+
+test("a partial listing verifies the candidates it returned; the rest stay unverified", async () => {
+ const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc", "v1dddd"]);
+ const { calls, probes } = rateLimitedAfter([watch("v1aaaa"), watch("v9zzzz"), watch("v1cccc")]);
+ const lines: string[] = [];
+ const v = await verifyBeforeClean({
+ channelSlug: "ch",
+ paths,
+ candidateIds: ["v1aaaa", "v1bbbb", "v1cccc", "v1dddd"],
+ onLog: (m) => lines.push(m),
+ probes,
+ });
+ assert.equal(calls.quick, 1);
+ assert.equal(calls.full, 0, "no confirmation probe: a candidate the prefix did not reach is not a suspect");
+ assert.equal(calls.backoff, 1, "the cooldown is recorded");
+ assert.deepEqual([...v.unverified].sort(), ["v1bbbb", "v1dddd"]);
+ assert.deepEqual([...excludedIds(v)].sort(), ["v1bbbb", "v1dddd"]);
+ assert.equal(v.pinned.size, 0);
+ assert.equal(v.stopped?.kind, "rate-limit");
+ assert.deepEqual(v.partial, { verified: 2, entries: 3, unverified: 2 });
+ assert.ok(
+ lines.some((l) => l.includes("verified 2 from a partial listing of 3 entries; 2 unverified remain")),
+ lines.join("\n"),
+ );
+});
+
+test("the sweep cleans what the partial listing verified and never a video outside it", async () => {
+ const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc"]);
+ const { probes } = rateLimitedAfter([watch("v1aaaa")]);
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: () => {}, probes, assertReachable: async () => {} });
+ assert.equal(await hasAudio(paths, "v1aaaa"), false, "listed in the partial: cleaned");
+ assert.equal(await hasAudio(paths, "v1bbbb"), true, "not in any listing: kept");
+ assert.equal(await hasAudio(paths, "v1cccc"), true, "not in any listing: kept");
+ assert.equal(r.cleanedDirs, 1);
+ assert.equal(r.unverified, 2);
+ assert.deepEqual(r.partial, { verified: 1, entries: 1, unverified: 2 });
+ assert.equal(r.stopped?.kind, "rate-limit");
+});
+
+test("a rate limit before any entry still cleans nothing", async () => {
+ const paths = await corpus(["v1aaaa", "v1bbbb"]);
+ const { probes } = rateLimitedAfter([]);
+ const lines: string[] = [];
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} });
+ assert.equal(r.cleanedDirs, 0);
+ assert.equal(r.unverified, 2);
+ assert.equal(r.partial, undefined);
+ assert.ok(lines.some((l) => l.includes("nothing cleaned this run")));
+});
+
+test("Rumble's two ids: an embed entry verifies the candidate whose metadata names it, never by a substring or across id kinds", async () => {
+ const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc", "v1dddd"], {
+ v1aaaa: "v8embd1", // listed below by its embed URL
+ v1bbbb: "v8embd2", // its embed id is spelled like another video's SLUG entry below
+ });
+ const { probes } = rateLimitedAfter([
+ "https://rumble.com/embed/v8embd1/",
+ // A slug entry spelled like v1bbbb's EMBED id: a different video's page.
+ watch("v8embd2"),
+ // A longer id containing a candidate's id, and a title naming one.
+ watch("v1ccccx"),
+ "https://rumble.com/v2eeee-about-v1dddd-and-more.html",
+ ]);
+ const v = await verifyBeforeClean({ channelSlug: "ch", paths, candidateIds: ["v1aaaa", "v1bbbb", "v1cccc", "v1dddd"], onLog: () => {}, probes });
+ assert.deepEqual([...v.unverified].sort(), ["v1bbbb", "v1cccc", "v1dddd"]);
+ assert.equal(v.partial?.verified, 1);
+});
+
+test("isListed matches a directory against page ids and an embed id against embed ids only", () => {
+ const idx = indexListing([watch("v1aaaa"), "https://rumble.com/embed/v8embd1/", "not a url"]);
+ assert.equal(idx.entries, 2);
+ assert.equal(isListed(idx, { dir: "v1aaaa" }), true);
+ assert.equal(isListed(idx, { dir: "v1zzzz", embed: "v8embd1" }), true);
+ assert.equal(isListed(idx, { dir: "v8embd1" }), false, "a directory name is never matched against an embed id");
+ assert.equal(isListed(idx, { dir: "v1zzzz", embed: "v1aaaa" }), false, "an embed id is never matched against a page id");
+ assert.equal(isListed(idx, { dir: "v1aaa" }), false, "no prefix match");
+});
+
+test("the job: a partial listing ends deferred and says what it verified, cleaned and left", async () => {
+ const paths = await corpus(["v1aaaa", "v1bbbb"]);
+ const { probes } = rateLimitedAfter([watch("v1aaaa"), watch("v5other")]);
+ const scheduled: CleanRetry[] = [];
+ const out = await runCleanAudioJob({
+ channelSlug: "ch",
+ paths,
+ jobId: "job-1",
+ onLog: () => {},
+ deps: {
+ probes,
+ assertReachable: async () => {},
+ now: () => T0,
+ cooldownRemainingMs: async () => 0,
+ scheduleRetry: async (r) => (scheduled.push(r), { ok: true as const, id: "job-1.retry1" }),
+ },
+ });
+ assert.equal(out.end, "deferred");
+ if (out.end !== "deferred") return;
+ assert.match(out.sentence, /verified 1 from a partial listing of 2 entries; 1 unverified remain; 1 cleaned, 1 left unverified/);
+ assert.equal(await hasAudio(paths, "v1aaaa"), false);
+ assert.equal(await hasAudio(paths, "v1bbbb"), true);
+ assert.equal(scheduled.length, 1, "the unverified remainder is retried");
+});
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -491,15 +491,23 @@ export function dataDirIdForUrl(url: string): string | null {
// share (`detectPlatform(url) ?? "unknown"`); `pagesReached` is the last
// `Downloading page N` the extractor logged (null for an extractor that does
// not log pages); `count` is how many entries were printed before the cut.
+//
+// `urls` ARE THOSE ENTRIES (lane verify-resume): what the source actually
+// returned before it refused. Never a listing — nothing may be judged MISSING
+// from it — but each entry in it was listed at the time of this attempt, which
+// is what the pre-clean check (verifyBeforeClean) needs to clean the
+// candidates among them instead of nothing.
export class EnumerationIncompleteError extends Error {
readonly platform: string;
readonly pagesReached: number | null;
readonly count: number;
+ readonly urls: readonly string[];
constructor(
exitCode: number | undefined,
platform: string,
pagesReached: number | null,
count: number,
+ urls: readonly string[] = [],
) {
super(
`yt-dlp exited with code ${exitCode} (rate-limited${
@@ -510,6 +518,7 @@ export class EnumerationIncompleteError extends Error {
this.platform = platform;
this.pagesReached = pagesReached;
this.count = count;
+ this.urls = urls;
}
}
@@ -596,6 +605,7 @@ async function enumeratePlaylistUrls(
cooldownPlatformKey(opts.channelConfig),
lastListingPage(stderr),
urls.length,
+ urls,
);
}
throw new Error(`yt-dlp exited with code ${result.exitCode}`);
diff --git a/common/ytdlp/sweepIncomplete.test.ts b/common/ytdlp/sweepIncomplete.test.ts
@@ -68,6 +68,8 @@ test("a 429 mid-listing throws EnumerationIncompleteError with page and count",
assert.equal(err.platform, "rumble");
assert.equal(err.pagesReached, 3);
assert.equal(err.count, 15);
+ // The entries printed before the cut travel with it (lane verify-resume).
+ assert.deepEqual(err.urls, URLS);
assert.match(err.message, /^yt-dlp exited with code 1/);
return true;
});
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -1,6 +1,14 @@
# Changelog
## [Unreleased]
+- **Clean audio cleans what a rate-limited listing did return.**
+ - Before, a checked Clean audio whose channel listing was rate-limited part-way cleaned nothing: a Rumble channel of
+ about 8,000 videos stopped after 408 entries and left all 350 candidates unverified.
+ - Now the entries the source returned before the 429 verify the candidates among them, and those are cleaned. A
+ candidate the partial listing does not name stays unverified, keeps its audio and goes to the retry.
+ - Matching is by id, the same way the full check matches, never by part of a name. On Rumble a video's embed id
+ counts too, and only against embed entries.
+ - The job says "verified N from a partial listing of M entries; K unverified remain".
- **A clip window past the end of a saved recording is cut from the saved video, clamped at the end.**
- Before, the last clip of a recording asked for a window that ended past the saved container (its cut plus a
3 s pad). The window was "not-covering" and went to the platform's download queue: a network fetch for footage