commit 9b3d0cc52586add89dbf9c7d9ab024e7f0d304f5
parent 9f36696bc2d2cf2f007aff0dbee525c472ead096
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 14:36:26 -0500
verify before clean: few candidates are asked one by one instead of listing
When the candidates still unverified are few against the channel's
listing, the pre-clean check now skips the listing and confirms each
candidate by itself (the tier C probe, paced, concurrency 1):
- the rule (listingEvidence.ts, preferPerVideo): probe when K candidates
cost fewer requests than the pages still to list, ceil((L - start + 1)
/ P); L = the larger of the roster, the data directories and the
longest complete listing; P = the extractor's page size (LBRY 50,
BitChute 25, Twitch 100, YouTube ~30, Rumble 25 until a listing that
logs its pages measures it; Kick's single answer always lists);
- only when every candidate has a webpage_url to probe by (exported from
checkAvailability): otherwise the listing serves them all;
- each verdict is written as it comes (availability.json, checkedBy
"check") and is stored evidence for the window, so a rate limit
part-way loses nothing and the next run asks only the remainder.
Tests: listingEvidence.test.ts (rule, measured page size, rate-limited
probes making progress across runs, the no-URL fallback to listing).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
4 files changed, 194 insertions(+), 3 deletions(-)
diff --git a/common/controller/checkAvailability.ts b/common/controller/checkAvailability.ts
@@ -126,7 +126,10 @@ function emptyByStatus(): Record<Availability, number> {
};
}
-async function readWebpageUrl(videoDir: string): Promise<string | null> {
+// The URL a probe asks by; null = this video cannot be probed (the check
+// skips it). Exported so the pre-clean check sends to the per-video path only
+// what this check can actually ask about.
+export async function readWebpageUrl(videoDir: string): Promise<string | null> {
try {
const raw = await readFile(
path.join(videoDir, "metadata.info.json"),
diff --git a/common/controller/listingEvidence.test.ts b/common/controller/listingEvidence.test.ts
@@ -314,3 +314,89 @@ test("verifyBeforeCleanMaxAgeHours 0: stored evidence is never used", async () =
assert.deepEqual(await s.calls(), ["1"], "it listed");
assert.equal(v.fromEvidence, 0);
});
+
+// ---------------------------------------------------------------------------
+// Few candidates: ask each by itself instead of listing
+
+test("the few-candidates rule: fewer probes than listing requests; Kick's one-answer listing always lists", async () => {
+ const { preferPerVideo, entriesPerRequest } = await import("./listingEvidence");
+ assert.deepEqual(preferPerVideo({ candidates: 150, listingSize: 8000, entriesPerRequest: 25 }), { perVideo: true, listingRequests: 320 });
+ assert.equal(preferPerVideo({ candidates: 350, listingSize: 8000, entriesPerRequest: 25 }).perVideo, false);
+ assert.equal(preferPerVideo({ candidates: 1, listingSize: 30, entriesPerRequest: 30 }).perVideo, false, "one page beats any probe run");
+ assert.equal(preferPerVideo({ candidates: 2, listingSize: 1000, entriesPerRequest: Number.POSITIVE_INFINITY }).perVideo, false);
+ // A continuation only has the pages after its start left to list.
+ assert.equal(preferPerVideo({ candidates: 30, listingSize: 2000, entriesPerRequest: 50, start: 1001 }).listingRequests, 20);
+ // Measured from a listing that logged its pages.
+ const r = empty();
+ r.attempts.push({ at: iso(T0), source: "quick-check", complete: false, start: 1, count: 408, pagesReached: 17, platform: "rumble" });
+ assert.equal(entriesPerRequest(r, "rumble"), 24);
+ assert.equal(entriesPerRequest(r, "youtube"), 30);
+});
+
+// A probe stub that answers `public` (as runAvailabilityCheck records it) for
+// the first `limit` ids it is asked about, then reports the source blocked.
+function probesAnswering(paths: Paths, limit: number) {
+ const asked: string[][] = [];
+ const probes: VerifyProbes = {
+ recordBackoff: async () => {},
+ full: async (opts) => {
+ const ids = [...(opts.onlyIds ?? [])];
+ asked.push(ids);
+ const probed = ids.slice(0, limit);
+ for (const id of probed) {
+ await writeFile(
+ path.join(paths.channelsDir, "ch", "data", id, "availability.json"),
+ JSON.stringify({ checkedAt: new Date().toISOString(), checkedBy: "check", availability: "public" }),
+ );
+ }
+ const blocked = probed.length < ids.length;
+ return { attempted: probed.length, checked: probed.length, skipped: 0, byStatus: {} as never, blocked, ...(blocked ? { blockMessage: "HTTP Error 429" } : {}), probedIds: probed };
+ },
+ };
+ return { asked, probes };
+}
+
+async function bigRoster(paths: Paths, size: number): Promise<void> {
+ const entries: Record<string, unknown> = {};
+ for (let i = 0; i < size; i++) entries[`r${i}`] = { url: "", firstSeenAt: iso(T0), lastListedAt: iso(T0), source: "listing" };
+ await writeFile(path.join(paths.channelsDir, "ch", "roster.json"), JSON.stringify({ version: 1, updatedAt: iso(T0), lastSweep: null, entries }));
+}
+
+async function withUrl(paths: Paths, id: string): Promise<void> {
+ await writeFile(path.join(paths.channelsDir, "ch", "data", id, "metadata.info.json"), JSON.stringify({ id, webpage_url: `https://www.youtube.com/watch?v=${id}` }));
+}
+
+test("few candidates on a big channel: no listing, each asked by itself; a rate limit keeps what was answered and the next run asks only the rest", async () => {
+ const ids = ["yt000000001", "yt000000002", "yt000000003", "yt000000004", "yt000000005"];
+ const s = await source("https://www.youtube.com/@ch/videos", ids);
+ for (const id of ids) await withUrl(s.paths, id);
+ await bigRoster(s.paths, 3000); // ~100 listing requests at 30 a page
+ const { asked, probes } = probesAnswering(s.paths, 2);
+ const lines: string[] = [];
+ const run = () => cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} });
+
+ let r = await run();
+ assert.deepEqual(await s.calls(), [], "no listing");
+ assert.equal(r.cleanedDirs, 2, "the two answered before the rate limit are cleaned");
+ assert.equal(r.unverified, 3);
+ assert.equal(r.stopped?.kind, "rate-limit");
+ assert.ok(lines.some((l) => l.includes("asking each one by itself instead (5 requests, paced)")), lines.join("\n"));
+
+ r = await run();
+ assert.deepEqual(asked, [ids, ids.slice(2)], "the retry asks only the unverified remainder");
+ assert.equal(r.cleanedDirs, 2);
+ assert.equal(r.unverified, 1);
+});
+
+test("few candidates, but one has nothing to probe it by: the listing serves them all", async () => {
+ const ids = ["yt000000001", "yt000000002"];
+ const s = await source("https://www.youtube.com/@ch/videos", ids);
+ await withUrl(s.paths, ids[0]); // the second has no metadata, so no webpage_url
+ await bigRoster(s.paths, 3000);
+ await s.setListing(ids.map((id) => `https://www.youtube.com/watch?v=${id}`));
+ const { asked, probes } = probesAnswering(s.paths, 10);
+ const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: () => {}, probes, assertReachable: async () => {} });
+ assert.deepEqual(await s.calls(), ["1"], "listed");
+ assert.deepEqual(asked, []);
+ assert.equal(r.cleanedDirs, 2);
+});
diff --git a/common/controller/listingEvidence.ts b/common/controller/listingEvidence.ts
@@ -264,3 +264,57 @@ export function listingResumeStart(
const overlap = LISTING_RESUME_OVERLAP_PAGES * pageSize;
return { start: Math.max(1, last.start + last.count - overlap), after: last, overlap };
}
+
+// HOW MANY ENTRIES ONE LISTING REQUEST RETURNS, per platform — the size of a
+// page of the channel extractor (yt-dlp, 2026.07): LBRY _PAGE_SIZE 50,
+// BitChute PAGE_SIZE 25, Twitch's channel videos _PAGE_LIMIT 100, a YouTube
+// tab continuation about 30. Rumble's channel page sets none in the extractor
+// (an HTML page of its own size): 25 until measured. Kick lists every VOD in
+// one answer. A listing that logged its pages measures it instead
+// (count / pagesReached), which is what a Rumble listing does.
+export const LISTING_ENTRIES_PER_REQUEST: Readonly<Record<string, number>> = {
+ youtube: 30,
+ rumble: 25,
+ odysee: 50,
+ bitchute: 25,
+ twitch: 100,
+ kick: Number.POSITIVE_INFINITY,
+};
+const DEFAULT_ENTRIES_PER_REQUEST = 30;
+
+// PURE: entries per listing request on this platform, measured when the
+// record has a listing that logged its pages.
+export function entriesPerRequest(record: ListingEvidence, platform: string): number {
+ for (let i = record.attempts.length - 1; i >= 0; i--) {
+ const a = record.attempts[i];
+ if (a.platform === platform && a.start === 1 && a.pagesReached && a.pagesReached > 0 && a.count > 0) {
+ return Math.max(1, a.count / a.pagesReached);
+ }
+ }
+ return LISTING_ENTRIES_PER_REQUEST[platform] ?? DEFAULT_ENTRIES_PER_REQUEST;
+}
+
+// THE FEW-CANDIDATES RULE (lane verify-resume): ask each remaining candidate
+// by itself, instead of listing the channel, when that costs FEWER requests —
+// K probes against the pages still to be listed, ceil((L - start + 1) / P),
+// where L is the channel's size (the larger of the roster, the data
+// directories and the longest complete listing), P the entries per request
+// and start the listing's first entry (a continuation's on Odysee/BitChute).
+// Each probe's verdict is kept (availability.json, checkedBy "check") and
+// counts as evidence for the window, so a rate limit part-way loses nothing:
+// the next run asks only the unverified remainder. A channel of a few hundred
+// videos always lists (one or two pages are cheaper than any probe run); an
+// 8,000-video Rumble channel (~320 pages at 25 a page) with 350 candidates
+// lists, and with the 150 a partial listing left, probes.
+export function preferPerVideo(opts: {
+ candidates: number;
+ listingSize: number;
+ entriesPerRequest: number;
+ start?: number;
+}): { perVideo: boolean; listingRequests: number } {
+ const left = Math.max(0, opts.listingSize - (opts.start ?? 1) + 1);
+ const listingRequests = Number.isFinite(opts.entriesPerRequest)
+ ? Math.max(1, Math.ceil(left / Math.max(1, opts.entriesPerRequest)))
+ : 1;
+ return { perVideo: opts.candidates > 0 && opts.candidates < listingRequests, listingRequests };
+}
diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts
@@ -3,13 +3,17 @@ import type { Paths } from "../lib/paths";
import { isPermanentlyGone, type Availability } from "../lib/availability";
import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server";
import { readChannelConfig } from "./channels";
-import { runAvailabilityCheck } from "./checkAvailability";
+import { readWebpageUrl, runAvailabilityCheck } from "./checkAvailability";
+import { loadRoster } from "./rosterStore";
+import { readdir } from "node:fs/promises";
import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck";
import { recordDownloadBackoff } from "../jobs/downloadBackoff";
import { detectPlatform } from "../lib/platform";
import { EnumerationIncompleteError, fetchFlatPlaylistUrls } from "../ytdlp/runYtdlp";
import { indexListing, listedCandidates } from "./listingMatch";
import {
+ entriesPerRequest,
+ preferPerVideo,
freshCompleteListing,
freshListingIndex,
isFresh,
@@ -127,6 +131,37 @@ async function freshProbeSaysAvailable(videoDir: string, nowMs: number, maxAgeHo
);
}
+// The few-candidates decision's inputs: the channel's size (the larger of
+// the roster, the data directories and the longest complete listing on
+// record), the platform's entries per request, and whether every candidate
+// can be probed.
+async function fewCandidatesPlan(
+ paths: Paths,
+ slug: string,
+ dataDir: string,
+ needed: readonly string[],
+ evidence: ListingEvidence,
+ platform: string,
+ start: number,
+): Promise<{ perVideo: boolean; listingRequests: number; listingSize: number; entriesPerRequest: number }> {
+ const roster = await loadRoster(paths, slug).catch(() => null);
+ const dirs = await readdir(dataDir).catch(() => [] as string[]);
+ const listed = Math.max(0, ...evidence.attempts.filter((a) => a.complete && a.start === 1).map((a) => a.count));
+ const listingSize = Math.max(roster ? Object.keys(roster.entries).length : 0, dirs.length, listed);
+ const perRequest = entriesPerRequest(evidence, platform);
+ const rule = preferPerVideo({ candidates: needed.length, listingSize, entriesPerRequest: perRequest, start });
+ let perVideo = rule.perVideo;
+ if (perVideo) {
+ for (const id of needed) {
+ if (!(await readWebpageUrl(path.join(dataDir, id)))) {
+ perVideo = false;
+ break;
+ }
+ }
+ }
+ return { perVideo, listingRequests: rule.listingRequests, listingSize, entriesPerRequest: perRequest };
+}
+
// A continued listing re-reads `overlap` entries the last attempt had read.
// If none of them is an id that attempt (or a later listing) returned, the
// channel's listing moved by more than the overlap since — uploads pushed it
@@ -269,18 +304,31 @@ export async function verifyBeforeClean({
const complete =
freshCompleteListing(evidence, nowMs, maxAge) ?? (verdictFresh ? { at: verdictFresh.checkedAt as string } : null);
let suspects: string[];
+ const resume = listingResumeStart(evidence, platform, nowMs, maxAge);
+ // THE FEW-CANDIDATES PATH (listingEvidence.ts, preferPerVideo): when asking
+ // each remaining candidate costs fewer requests than the listing would, ask
+ // them one by one — paced, each verdict kept — and list nothing. Only when
+ // every one of them CAN be probed (a webpage_url to ask by): one that cannot
+ // needs the listing, and the listing then serves them all.
+ const few = complete ? null : await fewCandidatesPlan(paths, channelSlug, dataDir, needed, evidence, platform, resume.start);
if (complete) {
suspects = needed;
log(
`Verify before clean: the complete listing of ${complete.at} does not name ${needed.length} candidate(s) — confirming them individually.`,
);
+ } else if (few?.perVideo) {
+ suspects = needed;
+ log(
+ `Verify before clean: ${needed.length} candidate(s) left against a listing of about ${few.listingSize} entries ` +
+ `(~${few.listingRequests} requests at ${Math.round(few.entriesPerRequest)} a request) — asking each one by itself instead ` +
+ `(${needed.length} requests, paced); every answer is kept for the next run.`,
+ );
} else {
// --- Tier B: one flat-playlist spawn ------------------------------------
// From entry 1 through the Quick check; or, on a platform whose listing
// can start at an offset (listingEvidence.ts, LISTING_OFFSET_PAGE_SIZE),
// CONTINUED from where the last attempt inside the window stopped, less an
// overlap of two pages.
- const resume = listingResumeStart(evidence, platform, nowMs, maxAge);
let listed: Set<string>;
try {
if (resume.start === 1) {