Archilyzer · Source

archilyzer

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

commit de7807f0024a1e0a1bf59c38db5fe29cdadc29c7
parent beb91321f334118c90f7397a499c1dba7be51466
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 17:51:50 -0500

Merge lane/verify-resume: the pre-clean check keeps what it learned and cleans what it verified

A rate-limited listing counts for the candidates among the entries it returned; sightings and probes are
stored per channel and trusted for a window (24 h by default, 72 at most) unless something newer from the
source contradicts them; a newer complete listing that omits a video sends it to an individual check.
With few candidates each is checked alone. Nothing unverified is removed.

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

Diffstat:
MOPERATING.md | 53+++++++++++++++++++++++++++++++++++++++++++++++++++++
MSETTINGS.md | 7+++++++
Mcommon/controller/checkAvailability.ts | 5++++-
Mcommon/controller/cleanAudioFromTranscribed.ts | 28+++++++++++++++++++++++++++-
Mcommon/controller/cleanAudioJob.ts | 14+++++++++++++-
Acommon/controller/listingEvidence.test.ts | 411+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/listingEvidence.ts | 518+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/listingMatch.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/quickAvailabilityCheck.ts | 58++++++++++++++++++++++++++++++++++++++++++++++++++--------
Mcommon/controller/verifyBeforeClean.ts | 479+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--------
Acommon/controller/verifyNewerEvidence.test.ts | 419+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/verifyPartialListing.test.ts | 216+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/availability-server.ts | 18++++++++++++++++--
Mcommon/lib/settingsSchema.test.ts | 17+++++++++++++++++
Mcommon/lib/settingsSchema.ts | 24++++++++++++++++++++++++
Mcommon/ytdlp/manualDownloads.test.ts | 43++++++++++++++++++++++++++++++++++++++++++-
Mcommon/ytdlp/runYtdlp.ts | 126++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Mcommon/ytdlp/sweepIncomplete.test.ts | 2++
Meditor/CHANGELOG.md | 32++++++++++++++++++++++++++++++++
Msettings.json.example | 1+
20 files changed, 2483 insertions(+), 68 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -1247,6 +1247,59 @@ pnpm ops do-not-clean --json '{"slug":"example","id":"<id>","keep":true}' retries the next rate limit ends the job **failed**: "Gave up: rate-limited … It needs a person". A failure that is not a rate limit (a network error, an extractor break) ends failed, "Could not verify availability …", and retries nothing. +- **What a checked Clean audio guarantees.** Before this change, a video's audio was removed only when a listing taken + in the same job named it, or a probe in the same job found it. Now the audio is removed when the video was listed + by its source, or confirmed by a per-video probe, within `verifyBeforeCleanMaxAgeHours` (24 hours by default, + at most 72), and nothing newer from the source contradicts it. **So a video removed from its source inside that + window, after its last sighting and before any newer listing, can have its audio cleaned** (and on a keep-latest + channel, its rolled-out saved video pruned). Setting `verifyBeforeCleanMaxAgeHours` to 0 restores "always ask". +- **What a checked clean accepts as "still there"**, cheapest first. A video is cleaned only when one of these vouches + for it; anything else keeps its audio and is "unverified": + - **Stored evidence, nothing asked**: a listing that returned the video within `verifyBeforeCleanMaxAgeHours`. That + is Sync's full sweep or paged walk, Store playlist, the Quick check, or an earlier clean's listing, including the + entries a rate-limited listing returned before it stopped. A per-video probe that found the video public or + unlisted in that window counts too: `availability.json` with `checkedBy: "check"`, and no download since that + found anything else (the same rule saved-video compaction uses). The listings are kept in + `channels/<slug>/listing-evidence.json`: each id with the time of the newest listing that returned it, and the + shape of the last 20 listings. The file applies to the channel URL they were taken from. A changed channel URL + starts it again. `roster.json`'s `lastListedAt` is not used, because its seed stamps the stored `playlist` as + listed. + - **Newer beats older**: a sighting or probe does not count if a newer complete listing in the window does not name + the video. Such a video is asked about by itself, with no second listing. The same applies when the clean's own + listing does not name it. + - **Which listing**: the newest complete one, by any actor: Sync's full sweep, Store playlist or the Quick check. + It is kept as `lastComplete` in `listing-evidence.json`, with the ids it named, so any number of later listings + cannot push it out; only the window ages it. + - **Dated from its end**: a sighting made while that listing was still running counts as older than it. + - **The shrink guard**: a full sweep the guard holds back still counts as a complete listing here. The guard + still keeps Sync from applying it. Its omissions only send videos to be asked about, never pin or clean them. + - **A listing cut short** overrules older evidence only over the stretch it covered, judged by upload time. + Outside that stretch, the older evidence still counts, by the window. If the listing's entries are not in + upload order (several tabs, a re-ordered playlist), it covers nothing beyond what it returned. + - **The clean's own listings only**: a Quick check or full sweep cut short by another actor does not overrule + older sightings, even over the stretch it covered. That cost is part of the window. + - **Complete means it ended normally**: a cancel, a restart part-way or an early stop (exit 101) leaves a partial + listing. + - **The prune**: while any video overruled this way stays unconfirmed, the saved-video retention prune does not + run. + - **A wrong clock**: a listing time in the future is dropped. + - **A listing**: the videos it returns are verified. If the source rate-limits it part-way, the videos among the + entries it did return are still cleaned, and the job says "verified N from a partial listing of M entries; K + unverified remain". A video the partial listing did not reach is not judged and keeps its audio. + - **Where the next listing starts**: on Odysee and BitChute, the next attempt continues two pages before where the + last one stopped (`-I <start>:`). yt-dlp's extractor there pages by offset, so the pages before are not fetched + again. Rumble, YouTube, Twitch and Kick list page after page from the top, so `-I` cannot skip anything; there a + retry starts at entry 1 again and keeps what the earlier attempts verified. A listing that moved by more than the + overlap between attempts is noted in the log. A video neither attempt returned is never cleaned on the listing. + - **Few candidates**: when asking each remaining video costs fewer requests than listing the channel would (the + channel's size divided by its page size, e.g. ~320 pages for 8,000 Rumble videos), each video is asked by + itself, paced, and no listing is made. Every answer is kept, so a rate limit part-way loses nothing and the next + attempt asks only the rest. This needs every candidate to have a `webpage_url`; otherwise the listing is used. + - **The pace**: every request runs at the platform's adaptive pace (yt-dlp `--sleep-requests`), which a recorded + rate limit widens (a Rumble 429 took it from 1.05 s to 4.59 s). The job log states the pace in use. Probes also + wait `AVAILABILITY_PROBE_GAP_MS` (3 s, plus jitter) between them. + - **Each retry makes progress**: its log says "Retry N of 2: started with S verdict(s) earlier attempts and stored + listings had earned, added A; U unverified remain". ## Record a live stream; import a file diff --git a/SETTINGS.md b/SETTINGS.md @@ -32,6 +32,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`inlineTranscribeOnFallback`](#inlinetranscribeonfallback) | `false` | | [`skipLiveDownloads`](#skiplivedownloads) | `true` | | [`verifyAvailabilityBeforeClean`](#verifyavailabilitybeforeclean) | `true` | +| [`verifyBeforeCleanMaxAgeHours`](#verifybeforecleanmaxagehours) | `24` | | [`buildArchives`](#buildarchives) | `true` | | [`archiveStorage`](#archivestorage) | object — see below | | [`reportDebouncePreset`](#reportdebouncepreset) | `"fast"` | @@ -352,6 +353,12 @@ Whether the transcribed-audio cleanup sweep checks each candidate is still avail Default: `true` +## `verifyBeforeCleanMaxAgeHours` + +How long (hours) stored evidence vouches for a video in the pre-clean availability check (verifyBeforeClean). THE GUARANTEE THIS SETS: a checked Clean audio removes a video's audio only when the video was listed by its source, or confirmed by a per-video probe, within this many hours, with nothing newer from the source contradicting it (a newer complete listing that does not name it, or a listing of the check that covered its place and did not name it). So a video removed from its source inside this window, after its last sighting and before any newer listing, CAN have its audio cleaned (and, on a keep-latest channel, its rolled-out saved video pruned). 0 restores "always ask": only a listing or probe taken by the clean itself counts. Evidence: a listing that RETURNED the video (Sync's full sweep or paged walk, Store playlist, the Quick check, or an earlier clean's listing, including the entries a rate-limited listing returned before it stopped — channels/<slug>/listing-evidence.json, taken from the channel's current URL only), or a probe that found it public or unlisted (availability.json, checkedBy "check", with no download since finding otherwise). Default 24 (clean after capture's window, diarization.cleanVerdictMaxAgeHours), max 72. + +Default: `24` + ## `buildArchives` Whether site builds generate downloadable transcript/live-chat archive zips (into public/archives, linked on the Downloads page). Global default; a site can opt out via site.json `archives: false`, and a single build can skip via the "Skip archive zips" build control. Opt-out: default true. 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/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts @@ -128,6 +128,14 @@ 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 }; + // THE CHAIN'S PROGRESS (lane verify-resume): verdicts this run started with + // (cached gone verdicts and stored evidence — earlier attempts' work) and + // verdicts it added by asking the source. Absent when nothing was asked. + verdictsAtStart?: number; + verdictsAdded?: number; }; type CleanCandidate = { @@ -345,6 +353,9 @@ export async function cleanAudioFromTranscribed({ let pinned = 0; let unverified = 0; let stopped: CleanVerifyStop | undefined; + let partial: CleanAudioResult["partial"]; + let chain: { verdictsAtStart: number; verdictsAdded: number } | undefined; + let contradictedUnresolved = 0; if (verify && candidates.length > 0 && !signal?.aborted) { const verdicts = await verifyBeforeClean({ channelSlug, @@ -359,6 +370,17 @@ export async function cleanAudioFromTranscribed({ pinned = verdicts.pinned.size; unverified = verdicts.unverified.size; stopped = verdicts.stopped; + partial = verdicts.partial; + contradictedUnresolved = [...(verdicts.contradicted ?? [])].filter((id) => verdicts.unverified.has(id)).length; + if (verdicts.fromEvidence !== undefined) { + const atStart = (verdicts.fromCache ?? 0) + verdicts.fromEvidence; + const resolved = candidates.length - verdicts.unverified.size; + chain = { verdictsAtStart: atStart, verdictsAdded: Math.max(0, resolved - atStart) }; + log( + `Verify before clean: of ${candidates.length} candidate(s), started with ${atStart} verdict(s) (cached or stored evidence), ` + + `added ${chain.verdictsAdded} by asking the source; ${verdicts.unverified.size} unverified remain.`, + ); + } // A video already pinned by someone else is protected, not newly pinned. protectedCount += verdicts.alreadyGone.size; } @@ -465,7 +487,9 @@ export async function cleanAudioFromTranscribed({ ? "a clean without checking never touches a saved video container (a checked Clean audio runs it)" : stopped ? `the availability check did not complete (${stopped.kind === "rate-limit" ? `rate-limited by ${stopped.platform}` : "it failed"}), so a video gone from the source may not be pinned yet` - : null; + : contradictedUnresolved > 0 + ? `${contradictedUnresolved} video(s) a newer listing does not name could not be confirmed, so one gone from the source may not be pinned yet` + : null; const prune = pruneSkipped ? (log(`Saved-video retention prune skipped: ${pruneSkipped}.`), { pruned: 0, bytesFreed: 0 }) : await pruneSavedVideos({ channelSlug, paths, onLog: log, signal }); @@ -485,6 +509,8 @@ export async function cleanAudioFromTranscribed({ ...(notInPlan !== undefined ? { notInPlan, planNoLongerEligible } : {}), ...(sourceGoneRemoved ? { sourceGoneRemoved } : {}), ...(stopped ? { stopped } : {}), + ...(partial ? { partial } : {}), + ...(chain ?? {}), }; } diff --git a/common/controller/cleanAudioJob.ts b/common/controller/cleanAudioJob.ts @@ -298,10 +298,22 @@ export async function runCleanAudioJob({ ...(deps.assertReachable ? { assertReachable: deps.assertReachable } : {}), }); if (signal?.aborted) return { end: "cancelled" }; + // The chain makes progress each attempt, and says how much. + if (retry && result.verdictsAtStart !== undefined) { + onLog( + `Retry ${retry.attempt} of ${CLEAN_RATE_LIMIT_MAX_RETRIES}: started with ${result.verdictsAtStart} verdict(s) earlier attempts and stored listings had earned, ` + + `added ${result.verdictsAdded ?? 0}; ${result.unverified} unverified remain.`, + ); + } 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/listingEvidence.test.ts b/common/controller/listingEvidence.test.ts @@ -0,0 +1,411 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { access, chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { VerifyProbes } from "./verifyBeforeClean"; +import { verifyBeforeClean } from "./verifyBeforeClean"; +import { cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed"; +import { + LISTING_EVIDENCE_RETAIN_MS, + foldListing, + freshCompleteListing, + freshListingIndex, + listingResumeStart, + normalizeListingEvidence, + readListingEvidence, + recordListing, + type ListingEvidence, +} from "./listingEvidence"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/listingEvidence.test.ts +// +// THE PRE-CLEAN CHECK KEEPS WHAT IT LEARNED AND CONTINUES (lane verify-resume, +// operator 21 Nov 2026: "retrying from start is horrible because it will just +// keep failing"). A fake yt-dlp lists a temp channel and answers 429 after N +// entries; it honours `-I <start>:` the way a PagedList extractor does. + +const ROOT = await mkdtemp(path.join(tmpdir(), "listing-evidence-")); +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 H = 3_600_000; +const T0 = Date.parse("2026-11-21T03:00:00.000Z"); +const iso = (ms: number) => new Date(ms).toISOString(); +const empty = (): ListingEvidence => normalizeListingEvidence(null); +const RU = "https://rumble.com/c/example"; +const YT = "https://www.youtube.com/@ch/videos"; + +// --------------------------------------------------------------------------- +// The record + +test("an id is dated to the start of the newest listing that returned it; embed ids are kept apart", () => { + let r = foldListing(empty(), { at: iso(T0 - 2 * H), source: "sync-full", urls: ["https://rumble.com/v1aaaa-t.html"], complete: true, platform: "rumble", url: RU }, T0); + r = foldListing(r, { at: iso(T0 - H), source: "quick-check", urls: ["https://rumble.com/v1aaaa-t.html", "https://rumble.com/embed/v8embd1/"], complete: false, pagesReached: 2, platform: "rumble", url: RU }, T0); + // An older listing folded later does not move a date back. + r = foldListing(r, { at: iso(T0 - 5 * H), source: "sync-paged", urls: ["https://rumble.com/v1aaaa-t.html"], complete: false, platform: "rumble", url: RU }, T0); + assert.equal(r.seen.v1aaaa, iso(T0 - H)); + assert.equal(r.embedSeen.v8embd1, iso(T0 - H)); + assert.equal(r.seen.v8embd1, undefined, "an embed id never lands among page ids"); + assert.deepEqual(r.attempts.map((a) => [a.source, a.complete, a.count, a.start]), [ + ["sync-full", true, 1, 1], + ["quick-check", false, 2, 1], + ["sync-paged", false, 1, 1], + ]); + assert.equal(r.attempts[1].pagesReached, 2); +}); + +test("ids not listed for the retention period are dropped, and attempts are capped", () => { + let r = foldListing(empty(), { at: iso(T0 - LISTING_EVIDENCE_RETAIN_MS - H), source: "sync-full", urls: ["https://www.youtube.com/watch?v=old00000001"], complete: true, platform: "youtube", url: YT }, T0 - LISTING_EVIDENCE_RETAIN_MS); + for (let i = 0; i < 25; i++) { + r = foldListing(r, { at: iso(T0), source: "sync-paged", urls: ["https://www.youtube.com/watch?v=new00000001"], complete: false, platform: "youtube", url: YT }, T0); + } + assert.equal(r.seen.old00000001, undefined); + assert.equal(r.seen.new00000001, iso(T0)); + assert.equal(r.attempts.length, 20); +}); + +test("only ids listed inside the window are fresh; 0 h uses nothing; a date in the future is not evidence", () => { + const r: ListingEvidence = { + version: 2, + url: RU, + absent: {}, + lastComplete: null, + seen: { fresh: iso(T0 - 23 * H), stale: iso(T0 - 25 * H), future: iso(T0 + 2 * H) }, + embedSeen: {}, + attempts: [], + }; + assert.deepEqual([...freshListingIndex(r, T0, 24).ids], ["fresh"]); + assert.equal(freshListingIndex(r, T0, 0).entries, 0); +}); + +test("a hand-broken record reads as what is valid in it", () => { + const r = normalizeListingEvidence({ seen: { a: iso(T0), b: 3, c: "not a date" }, attempts: [{ at: "x" }, { at: iso(T0), source: "quick-check", complete: false, start: 1, count: 4, platform: "odysee", url: RU }] }); + assert.deepEqual(Object.keys(r.seen), ["a"]); + assert.equal(r.attempts.length, 1); +}); + +test("the resume start: a continuation only where the extractor pages by offset, after a fresh cut-short attempt", () => { + const cut = (platform: string, at = iso(T0 - H)): ListingEvidence => ({ + version: 2, + url: RU, + absent: {}, + lastComplete: null, + seen: {}, + embedSeen: {}, + attempts: [{ at, source: "quick-check", complete: false, start: 1, count: 408, platform, url: RU }], + }); + // Odysee (LBRY OnDemandPagedList, 50 a page): continue 2 pages before the cut. + assert.deepEqual( + { ...listingResumeStart(cut("odysee"), "odysee", T0, 24), after: null }, + { start: 309, after: null, overlap: 100 }, + ); + assert.equal(listingResumeStart(cut("bitchute"), "bitchute", T0, 24).start, 359); + // Rumble, YouTube, Twitch: generators — `-I N:` would fetch pages 1..N anyway. + for (const p of ["rumble", "youtube", "twitch", "kick"]) assert.equal(listingResumeStart(cut(p), p, T0, 24).start, 1, p); + // Outside the window, or after a complete listing: from the top. + assert.equal(listingResumeStart(cut("odysee", iso(T0 - 25 * H)), "odysee", T0, 24).start, 1); + const done = cut("odysee"); + done.attempts.push({ at: iso(T0 - H / 2), source: "clean-check", complete: true, start: 309, count: 50, platform: "odysee", url: RU }); + assert.equal(listingResumeStart(done, "odysee", T0, 24).start, 1); + // Sync's paged walk is a prefix by design, not an attempt to continue. + const paged = cut("odysee"); + paged.attempts[0].source = "sync-paged"; + assert.equal(listingResumeStart(paged, "odysee", T0, 24).start, 1); +}); + +test("the newest complete whole listing is kept as lastComplete; a paged walk or a continuation never is one", () => { + let r = empty(); + r = foldListing(r, { at: iso(T0 - 2 * H), endedAt: iso(T0 - 2 * H + 600_000), source: "sync-full", urls: ["https://rumble.com/v1aaaa-t.html", "https://rumble.com/embed/v8embd1/"], complete: true, platform: "rumble", url: RU }, T0); + r = foldListing(r, { at: iso(T0 - H), source: "sync-paged", urls: ["https://rumble.com/v1bbbb-t.html"], complete: true, platform: "rumble", url: RU }, T0); + r = foldListing(r, { at: iso(T0 - H), source: "clean-check", urls: ["https://rumble.com/v1cccc-t.html"], complete: true, start: 309, platform: "rumble", url: RU }, T0); + const c = freshCompleteListing(r, T0, 24); + assert.equal(c?.source, "sync-full"); + assert.equal(c?.endedAt, iso(T0 - 2 * H + 600_000)); + assert.deepEqual(c?.ids, ["v1aaaa"]); + assert.deepEqual(c?.embedIds, ["v8embd1"]); + assert.equal(freshCompleteListing(r, T0, 1), null, "outside the window"); +}); + +// --------------------------------------------------------------------------- +// The check, over a fake lister + +let n = 0; +type Source = { paths: Paths; dir: string; calls: () => Promise<string[]>; setListing: (urls: string[]) => Promise<void>; setLimit: (k: number) => Promise<void>; setFail: () => Promise<void> }; + +// A channel on `channelUrl` whose candidates (`ids`) are transcribed and hold +// audio, and a fake yt-dlp that prints the listing file from `-I <start>:` (1 +// without it), at most `limit` entries, then a 429 when more remain. +async function source(channelUrl: string, ids: string[]): Promise<Source> { + const dir = path.join(ROOT, `s${n++}`); + await mkdir(dir, { recursive: true }); + const bin = path.join(dir, "fake-ytdlp.sh"); + await writeFile( + bin, + [ + "#!/bin/sh", + `d='${dir}'`, + "start=1; prev=''", + 'for a in "$@"; do if [ "$prev" = "-I" ]; then start="${a%%:*}"; fi; prev="$a"; done', + 'echo "$start" >> "$d/calls"', + // A listing that prints what it has, then fails for a reason that is not a rate limit. + 'if [ -f "$d/fail" ]; then cat "$d/listing.txt" 2>/dev/null; echo "ERROR: [x] x: Unsupported URL" >&2; exit 1; fi', + 'lim=$(cat "$d/limit" 2>/dev/null || echo 0)', + 'awk -v s="$start" -v lim="$lim" \'NR>=s { if (lim>0 && c>=lim) exit; print; c++ }\' "$d/listing.txt"', + 'left=$(awk -v s="$start" \'NR>=s\' "$d/listing.txt" | wc -l)', + 'if [ "$lim" -gt 0 ] && [ "$left" -gt "$lim" ]; then echo "ERROR: [x] x: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2; exit 1; fi', + "exit 0", + "", + ].join("\n"), + ); + await chmod(bin, 0o755); + const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: bin, jobsDir: path.join(dir, ".jobs") } 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: channelUrl })); + 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(10)); + } + return { + paths, + dir, + calls: async () => (await readFile(path.join(dir, "calls"), "utf8").catch(() => "")).split("\n").filter(Boolean), + setListing: (urls) => writeFile(path.join(dir, "listing.txt"), urls.join("\n") + "\n"), + setLimit: (k) => writeFile(path.join(dir, "limit"), String(k)), + setFail: () => writeFile(path.join(dir, "fail"), "1"), + }; +} + +const hasAudio = (paths: Paths, id: string) => + access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false); + +// No per-video probe in these runs unless a test says so: a suspect is +// recorded and left unprobed (so unverified). +function probesRecording() { + const asked: string[][] = []; + const probes: VerifyProbes = { + recordBackoff: async () => {}, + full: async (opts) => (asked.push([...(opts.onlyIds ?? [])]), { attempted: 0, checked: 0, skipped: 0, byStatus: {} as never, blocked: false, probedIds: [] }), + }; + return { asked, probes }; +} + +const odysee = (k: number) => `https://odysee.com/@ch:1/video-${k}:od${String(k).padStart(4, "0")}`; +const odId = (k: number) => `od${String(k).padStart(4, "0")}`; +const rumble = (k: number) => `https://rumble.com/v${(100000 + k).toString(36)}-title-${k}.html`; +const ruId = (k: number) => `v${(100000 + k).toString(36)}`; + +test("Rumble (no offset paging): each attempt starts at entry 1 but keeps what earlier attempts verified, and makes progress", async () => { + const ids = [ruId(5), ruId(150), ruId(290)]; + const s = await source("https://rumble.com/c/example", ids); + await s.setListing(Array.from({ length: 300 }, (_, i) => rumble(i + 1))); + const { probes } = probesRecording(); + const run = () => cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); + let lines: string[] = []; + + // Attempt 1: the source stops it after 100 entries. + await s.setLimit(100); + let r = await run(); + assert.equal(r.cleanedDirs, 1); + assert.equal(await hasAudio(s.paths, ruId(5)), false); + assert.equal(r.unverified, 2); + // The partial listing is saved as evidence, marked incomplete. + const ev = await readListingEvidence(s.paths, "ch"); + assert.equal(ev.attempts.at(-1)?.complete, false); + assert.equal(ev.attempts.at(-1)?.count, 100); + assert.ok(ev.seen[ruId(5)]); + + // Attempt 2: further this time (200 entries). The pace has risen meanwhile + // in production; here the fake simply lets more through. + lines = []; + await s.setLimit(200); + r = await run(); + assert.equal(await hasAudio(s.paths, ruId(150)), false, "attempt 2 adds the candidate it reached"); + assert.equal(await hasAudio(s.paths, ruId(290)), true, "never listed: kept"); + assert.equal(r.unverified, 1); + // Rumble's extractor cannot start at an offset: both attempts asked from 1. + assert.deepEqual(await s.calls(), ["1", "1"]); + assert.ok(lines.some((l) => l.includes("started with 0 of 2 candidate(s) verified by stored evidence")), lines.join("\n")); +}); + +test("Odysee (offset paging): the next attempt continues two pages before the cut, and a complete continuation clears the rest", async () => { + const ids = [odId(10), odId(150), odId(280)]; + const s = await source("https://odysee.com/@ch:1", ids); + await s.setListing(Array.from({ length: 300 }, (_, i) => odysee(i + 1))); + const { asked, probes } = probesRecording(); + const lines: string[] = []; + const run = () => cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); + + await s.setLimit(200); + let r = await run(); + assert.equal(r.cleanedDirs, 2, "entries 1–200 verify od0010 and od0150"); + assert.equal(await hasAudio(s.paths, odId(280)), true); + + r = await run(); + assert.equal(await hasAudio(s.paths, odId(280)), false, "the continuation (entries 101–300) verified it"); + assert.deepEqual(await s.calls(), ["1", "101"]); + assert.equal(r.stopped, undefined, "the continuation ran to the end"); + assert.deepEqual(asked, [], "nothing missing, nothing to probe"); + assert.ok(lines.some((l) => l.includes("from entry 101, 100 entries of overlap")), lines.join("\n")); + assert.ok(lines.some((l) => l.includes("overlaps the last attempt by 100 entries")), lines.join("\n")); +}); + +test("a listing that moved by more than the overlap between attempts: what neither attempt returned is never cleaned", async () => { + const ids = [odId(10), odId(220)]; + const s = await source("https://odysee.com/@ch:1", ids); + await s.setListing(Array.from({ length: 400 }, (_, i) => odysee(i + 1))); + const { asked, probes } = probesRecording(); + const lines: string[] = []; + const run = () => cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); + + await s.setLimit(200); + await run(); // entries 1–200: od0010 cleaned + assert.equal(await hasAudio(s.paths, odId(10)), false); + // 150 videos near the top are removed before the next attempt: entry 220 + // moves up to 70, before the continuation's start (101). + await s.setListing(Array.from({ length: 400 }, (_, i) => i + 1).filter((k) => k < 11 || k > 160).map(odysee)); + await s.setLimit(0); + await run(); + assert.equal(await hasAudio(s.paths, odId(220)), true, "never returned by either attempt: kept"); + assert.deepEqual(asked, [[odId(220)]], "it goes to the per-video confirmation instead"); + assert.ok(lines.some((l) => l.includes("moved by more than the overlap")), lines.join("\n")); +}); + +test("stored evidence: fresh Sync listings and fresh probes verify with no request; stale ones, a backfill and an unknown writer do not", async () => { + const s = await source("https://rumble.com/c/example", ["v1aaaa", "v1bbbb", "v1cccc", "v1dddd", "v1eeee"]); + await s.setListing([]); + await s.setFail(); // any listing fails at once, answering nothing + const now = Date.now(); + await recordListing(s.paths, "ch", { at: iso(now - 2 * H), source: "sync-paged", urls: ["https://rumble.com/v1aaaa-t.html"], complete: false, platform: "rumble", url: RU }); + await recordListing(s.paths, "ch", { at: iso(now - 30 * H), source: "sync-full", urls: ["https://rumble.com/v1bbbb-t.html"], complete: true, platform: "rumble", url: RU }); + const av = (id: string, rec: Record<string, unknown>) => + writeFile(path.join(s.paths.channelsDir, "ch", "data", id, "availability.json"), JSON.stringify(rec)); + await av("v1cccc", { checkedAt: iso(now - H), checkedBy: "check", availability: "public" }); + await av("v1dddd", { checkedAt: iso(now - H), checkedBy: "backfill", availability: "public" }); + await av("v1eeee", { checkedAt: iso(now - H), availability: "public" }); + const { probes } = probesRecording(); + const lines: string[] = []; + const v = await verifyBeforeClean({ channelSlug: "ch", paths: s.paths, candidateIds: ["v1aaaa", "v1bbbb", "v1cccc", "v1dddd", "v1eeee"], onLog: (m) => lines.push(m), probes }); + assert.deepEqual([...v.unverified].sort(), ["v1bbbb", "v1dddd", "v1eeee"]); + assert.equal(v.fromEvidence, 2); + assert.ok(lines.some((l) => l.includes("started with 2 of 5 candidate(s) verified by stored evidence (1 listed, 1 probed, within 24 h); 3 to ask the source")), lines.join("\n")); +}); + +test("everything vouched for by stored evidence: nothing is asked at all", async () => { + const s = await source("https://rumble.com/c/example", ["v1aaaa"]); + await recordListing(s.paths, "ch", { at: iso(Date.now() - H), source: "sync-paged", urls: ["https://rumble.com/v1aaaa-t.html"], complete: false, platform: "rumble", url: RU }); + const r = await cleanAudioFromTranscribed({ channelSlug: "ch", paths: s.paths, onLog: () => {}, probes: probesRecording().probes, assertReachable: async () => {} }); + assert.equal(r.cleanedDirs, 1); + assert.deepEqual(await s.calls(), [], "no listing spawned"); +}); + +test("a complete listing inside the window sends what it does not name straight to the per-video confirmation", async () => { + const s = await source("https://rumble.com/c/example", ["v1aaaa", "v1bbbb"]); + await recordListing(s.paths, "ch", { at: iso(Date.now() - H), source: "sync-full", urls: ["https://rumble.com/v1aaaa-t.html"], complete: true, platform: "rumble", url: RU }); + const { asked, probes } = probesRecording(); + const v = await verifyBeforeClean({ channelSlug: "ch", paths: s.paths, candidateIds: ["v1aaaa", "v1bbbb"], onLog: () => {}, probes }); + assert.deepEqual(await s.calls(), [], "no second listing"); + assert.deepEqual(asked, [["v1bbbb"]]); + assert.deepEqual([...v.unverified], ["v1bbbb"], "unprobed: kept"); +}); + +test("verifyBeforeCleanMaxAgeHours 0: stored evidence is never used", async () => { + const s = await source("https://rumble.com/c/example", ["v1aaaa"]); + await s.setListing([]); + await s.setLimit(1); + await recordListing(s.paths, "ch", { at: iso(Date.now() - 60_000), source: "sync-full", urls: ["https://rumble.com/v1aaaa-t.html"], complete: true, platform: "rumble", url: RU }); + const v = await verifyBeforeClean({ channelSlug: "ch", paths: s.paths, candidateIds: ["v1aaaa"], onLog: () => {}, probes: probesRecording().probes, maxAgeHours: 0 }); + 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", url: RU }); + 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 @@ -0,0 +1,518 @@ +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import { readJsonFile, withJsonFileLock, writeJsonAtomic } from "../lib/jsonFile-server"; +import { indexListing, type ListingIndex } from "./listingMatch"; + +// WHAT A CHANNEL'S SOURCE HAS ACTUALLY LISTED, AND WHEN (lane verify-resume). +// `channels/<slug>/listing-evidence.json`. +// +// The pre-clean availability check (verifyBeforeClean) may clean a candidate +// only on evidence that the source still has it. Before this file, nothing +// recorded "the source listed id X at time T" across attempts: +// - availability-verdict.json does, but only for the Quick check's COMPLETE +// listing, and each check overwrites it whole; +// - roster.json's `lastListedAt` cannot be trusted for it: the roster's +// seed (seedRosterIfAbsent) stamps every id of the stored `playlist` file, +// of any age, with the seed's time as a "listing"; +// - `playlist` has no time, and maybe-missing.json is negative evidence. +// So a listing the platform rate-limited part-way lost what it had read, and +// every retry began again at entry 1. +// +// THE ONE RULE OF THIS FILE: an id is written only from an entry a source +// RETURNED — what yt-dlp printed in a listing (a complete one, the prefix +// before a 429, or a page of the paged sync). Nothing derived, seeded or +// assumed. Each id is dated to the START of the listing that returned it (the +// earlier time, so its freshness runs out sooner), and the newest such date +// wins. `attempts` keeps the last listings' shape, so a listing cut short can +// be continued (verifyBeforeClean's resume) rather than restarted. + +export const LISTING_EVIDENCE_FILENAME = "listing-evidence.json"; +// An id not listed for this long is dropped from the file (no window may be +// longer: verifyBeforeCleanMaxAgeHours is capped well below it). +export const LISTING_EVIDENCE_RETAIN_MS = 30 * 24 * 3_600_000; +export const LISTING_ATTEMPTS_KEPT = 20; + +export type ListingSource = + // The Quick availability check (one whole-channel listing). + | "quick-check" + // The pre-clean check's own listing, possibly continued from an offset. + | "clean-check" + // Sync's periodic full sweep (one whole-channel listing). + | "sync-full" + // The channel's Store playlist (one whole-channel listing). + | "store-playlist" + // A page of Sync's newest-first walk (a prefix of the listing by design). + | "sync-paged"; + +export type ListingAttempt = { + // ISO time the listing started; every id it returned is dated to it. + at: string; + source: ListingSource; + // True only when the lister ended NORMALLY at the channel's end from + // `start` (yt-dlp exit 0, not cancelled, no range end). A 429 part-way, a + // cancel, an early stop (exit 101) or a page range is false. + complete: boolean; + // The 1-based first entry asked for (`-I <start>:`), 1 for a whole listing. + start: number; + // Entries it returned. + count: number; + // The last `Downloading page N` the extractor logged, when it logs pages. + pagesReached?: number | null; + platform: string; + // The channel URL that was listed. + url: string; +}; + +export type ListingEvidence = { + version: 2; + // The channel URL every row and attempt below was taken from. Evidence for + // another URL than the channel's current one is not evidence (review 1, F5): + // a record whose URL differs, or that names none, reads as empty, and the + // first listing of the new URL starts the record again. + url: string | null; + // Canonical page id → ISO time of the newest listing that returned it. + seen: Record<string, string>; + // Rumble embed ids (rumble.com/embed/<id>/ entries) → time, kept apart so an + // embed id is never matched against a directory name (listingMatch.ts). + embedSeen: Record<string, string>; + // NEWER EVIDENCE BEATS OLDER (review 1, F1): a directory id → the time a + // listing that SHOULD have named it (it covered the video's place) did not. + // Written by the pre-clean check from its own listings. A sighting or a + // probe older than this does not vouch for the video. + absent: Record<string, string>; + // Newest last. + attempts: ListingAttempt[]; + // THE NEWEST COMPLETE WHOLE-CHANNEL LISTING, kept apart from the capped + // `attempts` (review 2, F1), so the omission it records can age out only by + // the trust window, never by how many listings came after. Written by any + // actor whose listing ended normally from entry 1 (Sync's full sweep, Store + // playlist, the Quick check; a paged walk never is one). Its id sets answer + // "did it name video X"; on a channel of 8,000 videos they are about 8,000 + // ids of ~11 characters, ~120 KB of the file. + lastComplete: CompleteListing | null; +}; + +export type CompleteListing = { + // When it started and when it ended (ISO). An omission is dated from the + // END (review 2, F4): the listing may have passed a video's place at any + // moment before it ended, so a sighting during the listing does not beat it. + at: string; + endedAt: string; + source: ListingSource; + url: string; + count: number; + // Canonical page ids and Rumble embed ids it returned, sorted. + ids: string[]; + embedIds: string[]; +}; + +export function listingEvidencePath(paths: Pick<Paths, "channelsDir">, slug: string): string { + return path.join(paths.channelsDir, slug, LISTING_EVIDENCE_FILENAME); +} + +export function emptyEvidence(url: string | null = null): ListingEvidence { + return { version: 2, url, seen: {}, embedSeen: {}, absent: {}, attempts: [], lastComplete: null }; +} + +function isCompleteListing(v: unknown): v is CompleteListing { + const c = v as Partial<CompleteListing> | null; + return ( + !!c && + typeof c.at === "string" && + Number.isFinite(Date.parse(c.at)) && + typeof c.endedAt === "string" && + Number.isFinite(Date.parse(c.endedAt)) && + typeof c.url === "string" && + typeof c.count === "number" && + Array.isArray(c.ids) && + c.ids.every((x) => typeof x === "string") && + Array.isArray(c.embedIds) && + c.embedIds.every((x) => typeof x === "string") + ); +} + +function stringMap(v: unknown): Record<string, string> { + const out: Record<string, string> = {}; + if (!v || typeof v !== "object") return out; + for (const [k, t] of Object.entries(v as Record<string, unknown>)) { + if (k && typeof t === "string" && Number.isFinite(Date.parse(t))) out[k] = t; + } + return out; +} + +function isAttempt(v: unknown): v is ListingAttempt { + const a = v as Partial<ListingAttempt> | null; + return ( + !!a && + typeof a.at === "string" && + Number.isFinite(Date.parse(a.at)) && + (a.source === "quick-check" || + a.source === "clean-check" || + a.source === "sync-full" || + a.source === "store-playlist" || + a.source === "sync-paged") && + typeof a.complete === "boolean" && + typeof a.start === "number" && + a.start >= 1 && + typeof a.count === "number" && + a.count >= 0 && + typeof a.platform === "string" && + typeof a.url === "string" + ); +} + +// A hand-edited or half-written file reads as what is valid in it, or empty: +// the worst case is evidence lost (the check then asks the source), never +// evidence invented. +export function normalizeListingEvidence(value: unknown): ListingEvidence { + const r = value as Partial<ListingEvidence> | null; + if (!r || typeof r !== "object") return emptyEvidence(); + return { + version: 2, + url: typeof r.url === "string" && r.url ? r.url : null, + seen: stringMap(r.seen), + embedSeen: stringMap(r.embedSeen), + absent: stringMap(r.absent), + attempts: Array.isArray(r.attempts) ? r.attempts.filter(isAttempt).slice(-LISTING_ATTEMPTS_KEPT) : [], + lastComplete: isCompleteListing(r.lastComplete) + ? { ...r.lastComplete, ids: [...r.lastComplete.ids].sort(), embedIds: [...r.lastComplete.embedIds].sort() } + : null, + }; +} + +export async function readListingEvidence( + paths: Pick<Paths, "channelsDir">, + slug: string, +): Promise<ListingEvidence> { + const read = await readJsonFile(listingEvidencePath(paths, slug)); + return read.ok ? normalizeListingEvidence(read.value) : emptyEvidence(); +} + +// The record as evidence for a channel listed at `url`: empty when it was +// taken from another URL, or names none. +export function evidenceForUrl(record: ListingEvidence, url: string): ListingEvidence { + return record.url === url ? record : emptyEvidence(url); +} + +export type RecordedListing = { + at: string; + source: ListingSource; + urls: readonly string[]; + complete: boolean; + start?: number; + pagesReached?: number | null; + platform: string; + // The channel URL that was listed. + url: string; + // When the listing ended (ISO); its start (`at`) when not given. + endedAt?: string; +}; + +// A time later than the clock (plus a minute) is a clock that was wrong when +// it was written: never a stamp (review 1, F3). +const FUTURE_SLACK_MS = 60_000; +function inFuture(at: string, nowMs: number): boolean { + const t = Date.parse(at); + return !Number.isFinite(t) || t > nowMs + FUTURE_SLACK_MS; +} + +// PURE: drop rows too old to keep and rows dated in the future. +function prune(map: Record<string, string>, nowMs: number): void { + for (const [id, t] of Object.entries(map)) { + if (inFuture(t, nowMs) || nowMs - Date.parse(t) > LISTING_EVIDENCE_RETAIN_MS) delete map[id]; + } +} + +// PURE: fold one listing into the record. A listing of another channel URL +// starts the record again. A listing dated in the future is refused whole. +export function foldListing(record: ListingEvidence, listing: RecordedListing, nowMs: number): ListingEvidence { + const base = record.url === listing.url ? record : emptyEvidence(listing.url); + const seen = { ...base.seen }; + const embedSeen = { ...base.embedSeen }; + const absent = { ...base.absent }; + prune(seen, nowMs); + prune(embedSeen, nowMs); + prune(absent, nowMs); + const attempts = base.attempts.filter((a) => !inFuture(a.at, nowMs)); + let lastComplete = base.lastComplete && !inFuture(base.lastComplete.endedAt, nowMs) ? base.lastComplete : null; + if (inFuture(listing.at, nowMs)) { + return { version: 2, url: listing.url, seen, embedSeen, absent, attempts, lastComplete }; + } + const idx = indexListing(listing.urls); + const stamp = (map: Record<string, string>, id: string) => { + const prev = map[id]; + if (!prev || Date.parse(prev) < Date.parse(listing.at)) map[id] = listing.at; + }; + for (const id of idx.ids) stamp(seen, id); + for (const id of idx.embedIds) stamp(embedSeen, id); + const attempt: ListingAttempt = { + at: listing.at, + source: listing.source, + complete: listing.complete, + start: Math.max(1, Math.floor(listing.start ?? 1)), + count: idx.entries, + ...(listing.pagesReached !== undefined ? { pagesReached: listing.pagesReached } : {}), + platform: listing.platform, + url: listing.url, + }; + const endedAt = listing.endedAt && !inFuture(listing.endedAt, nowMs) ? listing.endedAt : listing.at; + if ( + listing.complete && + attempt.start === 1 && + listing.source !== "sync-paged" && + (!lastComplete || Date.parse(lastComplete.endedAt) <= Date.parse(endedAt)) + ) { + lastComplete = { + at: listing.at, + endedAt, + source: listing.source, + url: listing.url, + count: idx.entries, + ids: [...idx.ids].sort(), + embedIds: [...idx.embedIds].sort(), + }; + } + return { + version: 2, + url: listing.url, + seen, + embedSeen, + absent, + attempts: [...attempts, attempt].slice(-LISTING_ATTEMPTS_KEPT), + lastComplete, + }; +} + +// Record what a listing returned. Callers treat a failure as best-effort: a +// lost write loses evidence (the next check asks again), never invents it. +export async function recordListing( + paths: Pick<Paths, "channelsDir">, + slug: string, + listing: RecordedListing, + nowMs: number = Date.now(), +): Promise<void> { + const file = listingEvidencePath(paths, slug); + await withJsonFileLock(file, async () => { + const cur = await readListingEvidence(paths, slug); + await writeJsonAtomic(file, foldListing(cur, listing, nowMs), { mkdir: true }); + }); +} + +// PURE: mark directory ids a listing of `url` at `at` should have named and +// did not (the newest such time wins). +export function foldAbsent(record: ListingEvidence, url: string, ids: Iterable<string>, at: string, nowMs: number): ListingEvidence { + const base = record.url === url ? record : emptyEvidence(url); + const absent = { ...base.absent }; + prune(absent, nowMs); + if (!inFuture(at, nowMs)) { + for (const id of ids) if (!absent[id] || Date.parse(absent[id]) < Date.parse(at)) absent[id] = at; + } + return { ...base, absent }; +} + +export async function recordAbsent( + paths: Pick<Paths, "channelsDir">, + slug: string, + url: string, + ids: readonly string[], + at: string, + nowMs: number = Date.now(), +): Promise<void> { + if (ids.length === 0) return; + const file = listingEvidencePath(paths, slug); + await withJsonFileLock(file, async () => { + const cur = await readListingEvidence(paths, slug); + await writeJsonAtomic(file, foldAbsent(cur, url, ids, at, nowMs), { mkdir: true }); + }); +} + +const HOUR = 3_600_000; + +// Fresh: listed no longer ago than the window, and not dated in the future +// (a clock that jumped is not evidence). +export function isFresh(at: string, nowMs: number, maxAgeHours: number): boolean { + const t = Date.parse(at); + return Number.isFinite(t) && t <= nowMs + FUTURE_SLACK_MS && nowMs - t <= maxAgeHours * HOUR; +} + +// NEWER EVIDENCE BEATS OLDER (review 1, F1; review 2, F1 and F4). When a +// video was last contradicted by the source, in ms (-Infinity: never): the +// END of the newest complete whole-channel listing inside the window when +// that listing does not name the video (`lastComplete`, kept apart from the +// capped attempts), or the video's absent mark (a listing of the pre-clean +// check that covered its place and did not name it). A sighting or a probe +// older than this does not vouch for it — one made while that listing was +// still running included: the listing may have passed the video's place after +// it. A video the complete listing named is never contradicted by it. +export function contradictedSince( + record: ListingEvidence, + c: { dir: string; embed?: string }, + nowMs: number, + maxAgeHours: number, +): number { + let t = Number.NEGATIVE_INFINITY; + const complete = freshCompleteListing(record, nowMs, maxAgeHours); + if (complete && !completeNames(complete, c)) t = Date.parse(complete.endedAt); + const mark = record.absent[c.dir]; + if (mark && !inFuture(mark, nowMs)) t = Math.max(t, Date.parse(mark)); + return t; +} + +// PURE: did the complete listing name this candidate (its directory id among +// page ids, its embed id among embed ids)? +export function completeNames(complete: CompleteListing, c: { dir: string; embed?: string }): boolean { + const has = (list: string[], id: string) => { + let lo = 0; + let hi = list.length - 1; + while (lo <= hi) { + const mid = (lo + hi) >> 1; + if (list[mid] === id) return true; + if (list[mid] < id) lo = mid + 1; + else hi = mid - 1; + } + return false; + }; + return has(complete.ids, c.dir) || (c.embed !== undefined && has(complete.embedIds, c.embed)); +} + +// PURE: the newest fresh stamp of a candidate (its directory id against page +// ids, its embed id against embed ids), in ms, or null. +export function freshStampOf( + record: ListingEvidence, + c: { dir: string; embed?: string }, + nowMs: number, + maxAgeHours: number, +): number | null { + if (maxAgeHours <= 0) return null; + let best: number | null = null; + for (const t of [record.seen[c.dir], c.embed !== undefined ? record.embedSeen[c.embed] : undefined]) { + if (t && isFresh(t, nowMs, maxAgeHours)) best = Math.max(best ?? Number.NEGATIVE_INFINITY, Date.parse(t)); + } + return best; +} + +// PURE: the ids listed inside the window, as a ListingIndex for listingMatch. +export function freshListingIndex(record: ListingEvidence, nowMs: number, maxAgeHours: number): ListingIndex { + const ids = new Set<string>(); + const embedIds = new Set<string>(); + if (maxAgeHours > 0) { + for (const [id, t] of Object.entries(record.seen)) if (isFresh(t, nowMs, maxAgeHours)) ids.add(id); + for (const [id, t] of Object.entries(record.embedSeen)) if (isFresh(t, nowMs, maxAgeHours)) embedIds.add(id); + } + return { ids, embedIds, entries: ids.size + embedIds.size }; +} + +// PURE: is there a COMPLETE whole-channel listing inside the window? Then a +// candidate it does not name is a suspect (unlisted or gone) to confirm by +// itself — no second listing is needed to learn that. The record's +// `lastComplete`, whatever has been listed since; fresh by its END, the moment it +// contradicts from, so a sighting made while it ran never outlives it (review 3). +export function freshCompleteListing( + record: ListingEvidence, + nowMs: number, + maxAgeHours: number, +): CompleteListing | null { + if (maxAgeHours <= 0) return null; + const c = record.lastComplete; + return c && isFresh(c.endedAt, nowMs, maxAgeHours) && !inFuture(c.endedAt, nowMs) ? c : null; +} + +// WHERE A CUT-SHORT LISTING CONTINUES, per platform — read from yt-dlp's +// channel extractors (the checkout the editor runs, 2026.07), not assumed: +// odysee LBRYChannelIE (LBRYBaseIE): OnDemandPagedList(_fetch_page, _PAGE_SIZE 50) +// bitchute BitChuteChannelIE returns OnDemandPagedList(page_func, PAGE_SIZE 25) +// PlaylistEntries reads a PagedList one index at a time and fetches only the +// page holding that index, so `--lazy-playlist -I <start>:` asks nothing for +// the pages before `start`. Every other channel extractor is a GENERATOR that +// yt-dlp wraps in a LazyList, and `-I <start>:` drives it through pages 1..N +// to reach entry N — the same requests as starting over: +// rumble RumbleChannelIE.entries: itertools.count(1) over `?page=N` (and +// _real_extract strips any `page` from the URL, so none can be passed) +// youtube YoutubeTabIE._entries: continuation tokens, page after page +// twitch TwitchPlaylistBaseIE._entries: a GraphQL cursor, page after page +// kick KickVideosIE._entries: one API answer holding every VOD (nothing +// to skip: the listing is one request) +// On those a retry starts at entry 1 again; what it gains is the saved +// evidence (each attempt's entries count) and the per-video path for the +// remainder (verifyBeforeClean). +export const LISTING_OFFSET_PAGE_SIZE: Readonly<Record<string, number>> = { odysee: 50, bitchute: 25 }; +// The continuation re-reads this many pages before where the last attempt +// stopped: uploads since then push entries down (an entry seen twice is the +// same id, counted once), and the overlap is how a shift is noticed. +export const LISTING_RESUME_OVERLAP_PAGES = 2; + +export type ListingResume = { start: number; after: ListingAttempt | null; overlap: number }; + +// PURE: the first entry the next listing of this channel asks for. +export function listingResumeStart( + record: ListingEvidence, + platform: string, + nowMs: number, + maxAgeHours: number, +): ListingResume { + const pageSize = LISTING_OFFSET_PAGE_SIZE[platform]; + if (!pageSize || maxAgeHours <= 0) return { start: 1, after: null, overlap: 0 }; + const chain = record.attempts.filter( + (a) => (a.source === "quick-check" || a.source === "clean-check") && a.platform === platform, + ); + const last = chain.at(-1); + if (!last || last.complete || last.count === 0 || !isFresh(last.at, nowMs, maxAgeHours)) { + return { start: 1, after: null, overlap: 0 }; + } + 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/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/quickAvailabilityCheck.ts b/common/controller/quickAvailabilityCheck.ts @@ -1,7 +1,9 @@ import path from "node:path"; import { readdir } from "node:fs/promises"; import { readChannelConfig } from "./channels"; -import { extractVideoId, fetchFlatPlaylistUrls } from "../ytdlp/runYtdlp"; +import { EnumerationIncompleteError, extractVideoId, fetchFlatPlaylist } from "../ytdlp/runYtdlp"; +import { detectPlatform } from "../lib/platform"; +import { recordListing } from "./listingEvidence"; import { diffMaybeMissing, writeMaybeMissing } from "./maybeMissingStore"; import { mergeRosterFile, @@ -63,13 +65,53 @@ export async function runQuickAvailabilityCheck({ onLog: (m) => log(m.trimEnd()), }); - const freshUrls = await fetchFlatPlaylistUrls({ - channelConfig: config, - paths, - channelSlug, - onLog: log, - signal, - }); + // What the source returns is evidence for the pre-clean check + // (listingEvidence.ts) — the whole listing, or the entries a rate-limited + // one printed before it stopped. Best-effort: a failed write loses evidence, + // never the check. + const platform = detectPlatform(config.url) ?? "unknown"; + const url = config.url; + const record = (urls: readonly string[], complete: boolean, pagesReached?: number | null) => + recordListing(paths, channelSlug, { + at: now, + endedAt: new Date().toISOString(), + source: "quick-check", + urls, + complete, + platform, + pagesReached, + url, + }).catch( + (err) => log(`Warning: could not record the listing evidence (${(err as Error).message}).`), + ); + let freshUrls: string[]; + try { + const listing = await fetchFlatPlaylist({ + channelConfig: config, + paths, + channelSlug, + onLog: log, + signal, + }); + freshUrls = listing.urls; + // A COMPLETE LISTING IS THE LISTER'S OWN NORMAL END (review 1, F2). A + // cancel (or a restart) part-way returns what was printed: a prefix, + // recorded as one, and no missing set is computed from it. + if (listing.ended !== "normal") { + await record(freshUrls, false); + throw new Error( + listing.ended === "cancelled" + ? `the listing was cancelled after ${freshUrls.length} entries` + : `the listing stopped early (exit 101) after ${freshUrls.length} entries`, + ); + } + } catch (err) { + if (err instanceof EnumerationIncompleteError && err.urls.length > 0) { + await record(err.urls, false, err.pagesReached); + } + throw err; + } + await record(freshUrls, true); // ADD-ONLY. This check computes a missing set, but only the on-disk one — // maybe-missing, whose meaning is unchanged below. It is not a sweep and may diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts @@ -1,14 +1,35 @@ import path from "node:path"; import type { Paths } from "../lib/paths"; import { isPermanentlyGone, type Availability } from "../lib/availability"; -import { resolveEffectiveAvailability } from "../lib/availability-server"; 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, readFile } from "node:fs/promises"; import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck"; import { recordDownloadBackoff } from "../jobs/downloadBackoff"; import { detectPlatform } from "../lib/platform"; -import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; +import { EnumerationIncompleteError, fetchFlatPlaylist, type ListingEnd } from "../ytdlp/runYtdlp"; +import { candidateIdsOf, indexListing, listedCandidates } from "./listingMatch"; +import { extractVideoId } from "../lib/videoId"; +import { + contradictedSince, + entriesPerRequest, + evidenceForUrl, + freshCompleteListing, + freshStampOf, + listingResumeStart, + preferPerVideo, + readListingEvidence, + recordAbsent, + recordListing, + type ListingEvidence, + type ListingResume, +} from "./listingEvidence"; +import { platformPresence, resolveEffectiveAvailability } from "../lib/availability-server"; +import { getSettings } from "../lib/settings"; +import { VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX } from "../lib/settingsSchema"; +import { channelPaceSeconds } from "../ytdlp/channelArgs"; // Availability gate for the transcribed-audio cleanup sweep. // @@ -17,21 +38,34 @@ import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; // NOT be cleaned: our copy has become the only copy. This module decides, per // candidate, whether the sweep is allowed to delete. // -// Three tiers, cheapest first, so a typical run costs ONE yt-dlp spawn per -// channel plus a handful for suspects — not one spawn per cleanable video: +// Four tiers, cheapest first, so a typical run costs at most ONE yt-dlp spawn +// per channel plus a handful for suspects — not one spawn per cleanable video: // // A. cached verdict resolveEffectiveAvailability() 0 spawns // Already-known-gone videos are pinned without touching the network. This // is also the only tier that catches members_only: a members-only video // stays listed in its channel's flat playlist, so tier B never flags it. +// E. stored evidence listing-evidence.json, … 0 spawns +// (lane verify-resume) A candidate a listing RETURNED, or a per-video +// probe found, inside verifyBeforeCleanMaxAgeHours is verified — unless +// something newer from the source contradicts it: a newer complete +// listing, or this run's own listing over the stretch it covered, that +// does not name it (then it is a suspect). A complete listing inside the +// window makes the rest suspects (tier C). // B. fresh listing runQuickAvailabilityCheck() 1 spawn/channel // Candidates absent from the channel's current flat playlist are suspects. +// Rate-limited part-way, the entries it returned verify the candidates +// among them (the rest stay unverified) and are saved for the next run, +// which CONTINUES the listing where the platform's extractor pages by +// offset (listingEvidence.ts, listingResumeStart). // C. confirm suspects runAvailabilityCheck(onlyIds) 1 spawn/suspect // Resolves deleted/private (pin) from unlisted (clean — an unlisted video // legitimately drops out of the listing but still resolves by URL). // // Anything the gate cannot resolve is `unverified`: skipped, NO marker written, -// retried on the next sweep. The sweep never deletes on incomplete information. +// retried on the next sweep. The sweep never deletes on incomplete information: +// only a candidate a listing returned (this run or inside the window) or a +// probe found is cleaned. export type CleanVerdicts = { // Newly marked do-not-clean this run (gone from source). @@ -48,6 +82,20 @@ 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 }; + // How many candidates stored evidence verified before anything was asked + // (tier E): with `fromCache` (tier A's cached gone verdicts), a retry's + // starting point. Absent when no source could be asked (a URL-less channel). + fromEvidence?: number; + fromCache?: number; + // NEWER EVIDENCE BEAT OLDER (review 1, F1): candidates a stored sighting or + // probe vouched for that a newer listing did not name. Each was asked by + // itself or left unverified; while one of them stays unverified the + // saved-video retention prune does not run. + contradicted?: Set<string>; }; export type CleanVerifyStop = { @@ -65,6 +113,8 @@ export type CleanVerifyStop = { export type VerifyProbes = { quick?: typeof runQuickAvailabilityCheck; full?: typeof runAvailabilityCheck; + // The continued listing (`-I <start>:`), on a platform that honours it. + list?: typeof fetchFlatPlaylist; recordBackoff?: (platform: string) => Promise<void>; }; @@ -75,10 +125,165 @@ export type VerifyBeforeCleanOptions = { onLog?: (msg: string) => void; signal?: AbortSignal; probes?: VerifyProbes; + // Test seams: the clock, and the freshness window (default: the setting + // verifyBeforeCleanMaxAgeHours). + now?: () => number; + maxAgeHours?: number; // The clean job this gate runs in, recorded on every mark it writes. jobId?: string; }; +// A per-video probe that found the video on its platform inside the window, +// by THE SAME RULE compaction's gone check uses (platformPresence: a real +// probe, `checkedBy: "check"`, public or unlisted, not older than the window, +// not dated in the future, and no download since that found anything else). +// Returns the probe's time in ms, or null. +async function freshProbeAt(videoDir: string, nowMs: number, maxAgeHours: number): Promise<number | null> { + const p = await platformPresence(videoDir, { maxAgeDays: maxAgeHours / 24, now: new Date(nowMs) }).catch(() => null); + if (!p?.onPlatform || !p.checkedAt) return null; + const t = Date.parse(p.checkedAt); + return Number.isFinite(t) ? t : null; +} + +// A video's upload time in ms from its metadata.info.json (`timestamp`, else +// `release_timestamp`, else `upload_date`), or null when none can be read. +async function videoTimeOf(videoDir: string): Promise<number | null> { + try { + const m = JSON.parse(await readFile(path.join(videoDir, "metadata.info.json"), "utf8")) as Record<string, unknown>; + for (const k of ["timestamp", "release_timestamp"]) { + const v = m[k]; + if (typeof v === "number" && Number.isFinite(v)) return v * 1000; + } + const d = typeof m.upload_date === "string" ? /^(\d{4})(\d{2})(\d{2})$/.exec(m.upload_date) : null; + return d ? Date.UTC(Number(d[1]), Number(d[2]) - 1, Number(d[3])) : null; + } catch { + return null; + } +} + +// WHICH VIDEOS A LISTING OF THIS RUN COVERED (review 1, F1c): those it would +// have returned, by their place, were they still there. A complete listing +// from entry 1 covered every video. Any other covered only its own stretch of +// the newest-first order: from the upload time of the oldest of its last +// entries we have on disk (the end it reached; none if it ran to the end) to +// that of the newest of its first ones (none if it started at entry 1). A +// candidate whose time cannot be read is counted as covered — the safe side: +// it is asked about, not cleaned on an older sighting. A listing that returned +// nothing and did not finish covered nothing. +// +// NOT IN UPLOAD ORDER, NOTHING ASSUMED (review 2, F3). The stretch is only +// meaningful for a newest-first listing. One that walks several tabs, or a +// re-ordered playlist, prints dates out of order: then a cut-short listing +// covers nothing beyond the entries it returned (they still count as seen), +// so no omission is read into it. Checked over up to ORDER_SAMPLE dated +// entries spread across the run, with ORDER_SLACK_MS of slack. +const COVERAGE_PROBE_ENTRIES = 20; +const ORDER_SAMPLE = 60; +const ORDER_SLACK_MS = 3_600_000; +async function coverageOf( + run: { urls: readonly string[]; complete: boolean; start: number }, + dataDir: string, + log: (m: string) => void, +): Promise<(id: string) => Promise<boolean>> { + if (run.complete && run.start === 1) return async () => true; + if (run.urls.length === 0) return async () => run.complete; + const dirs = new Set(await readdir(dataDir).catch(() => [] as string[])); + const onDisk = run.urls.map((u) => extractVideoId(u)).filter((id): id is string => !!id && dirs.has(id)); + const step = Math.max(1, Math.floor(onDisk.length / ORDER_SAMPLE)); + let prev: number | null = null; + for (let i = 0; i < onDisk.length; i += step) { + const t = await videoTimeOf(path.join(dataDir, onDisk[i])); + if (t === null) continue; + if (prev !== null && t > prev + ORDER_SLACK_MS) { + log( + "Verify before clean: this listing's entries are not in upload order (several tabs, or a re-ordered playlist) — " + + "nothing is read into what it did not return.", + ); + return async () => false; + } + prev = t; + } + const edge = async (ids: string[], pick: (a: number, b: number) => number): Promise<number | null> => { + let best: number | null = null; + let dated = 0; + for (const id of ids.slice(0, COVERAGE_PROBE_ENTRIES * 5)) { + const t = await videoTimeOf(path.join(dataDir, id)); + if (t === null) continue; + best = best === null ? t : pick(best, t); + if (++dated >= COVERAGE_PROBE_ENTRIES) break; + } + return best; + }; + const lo = run.complete ? Number.NEGATIVE_INFINITY : ((await edge([...onDisk].reverse(), Math.min)) ?? Number.NEGATIVE_INFINITY); + const hi = run.start === 1 ? Number.POSITIVE_INFINITY : ((await edge(onDisk, Math.max)) ?? Number.POSITIVE_INFINITY); + return async (id: string) => { + const t = await videoTimeOf(path.join(dataDir, id)); + return t === null || (t >= lo && t <= hi); + }; +} + +// 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 +// down, or removals pulled it up — and entries between the two attempts may +// have been read by neither. That loses nothing safety-wise (an entry never +// returned is never evidence: its candidate is confirmed individually or stays +// unverified); it is said, so a person reading the log knows why. +function noteShift( + urls: readonly string[], + resume: ListingResume, + evidence: ListingEvidence, + log: (m: string) => void, +): void { + if (!resume.after || urls.length === 0) return; + const since = Date.parse(resume.after.at); + const head = indexListing(urls.slice(0, resume.overlap)); + let known = 0; + for (const id of head.ids) { + const t = evidence.seen[id]; + if (t && Date.parse(t) >= since) known++; + } + if (known === 0) { + log( + `Verify before clean: none of the ${head.entries} overlapping entries was in the last attempt — the listing moved by more than the overlap since; ` + + `entries between the two attempts may be unread (their candidates are confirmed individually or stay unverified).`, + ); + } else { + log(`Verify before clean: the continuation overlaps the last attempt by ${known} entr${known === 1 ? "y" : "ies"} (de-duplicated by id).`); + } +} + function emptyVerdicts(): CleanVerdicts { return { pinned: new Map(), alreadyGone: new Set(), unverified: new Set() }; } @@ -99,6 +304,8 @@ export async function verifyBeforeClean({ onLog, signal, probes, + now, + maxAgeHours, jobId, }: VerifyBeforeCleanOptions): Promise<CleanVerdicts> { const log = onLog ?? ((m: string) => console.log(m)); @@ -142,9 +349,9 @@ export async function verifyBeforeClean({ } remaining.push(id); } + verdicts.fromCache = verdicts.pinned.size + verdicts.alreadyGone.size; if (remaining.length === 0 || signal?.aborted) return verdicts; - // --- Tier B: one flat-playlist spawn -------------------------------------- // A channel with no URL is structurally unverifiable — there is no source to // diff against and there never will be. Fail OPEN: cleaning an imported or // hand-built archive must not require flipping a global setting off. @@ -155,54 +362,238 @@ export async function verifyBeforeClean({ ); return verdicts; } - - // Ids known on disk but ABSENT from the channel's current flat playlist. const platform = detectPlatform(config.url) ?? "unknown"; - let maybeMissing: Set<string>; - try { - const quick = await (probes?.quick ?? runQuickAvailabilityCheck)({ - channelSlug, - paths, - onLog: log, - // runQuickAvailabilityCheck requires a signal; the sweep's is optional. - signal: signal ?? new AbortController().signal, - }); - 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. - const reason = (err as Error)?.message ?? String(err); - for (const id of remaining) verdicts.unverified.add(id); + const nowMs = (now ?? Date.now)(); + const maxAge = Math.min(VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX, maxAgeHours ?? getSettings().verifyBeforeCleanMaxAgeHours); + const match = { channelsDir: paths.channelsDir, slug: channelSlug, platform }; + const contradicted = new Set<string>(); + verdicts.contradicted = contradicted; + + // --- Tier E: stored evidence, no spawns (lane verify-resume) -------------- + // A candidate a listing RETURNED inside the window (listing-evidence.json: + // Sync, the Quick check, an earlier clean's listing or the prefix a + // rate-limited one printed), or a per-video probe found on its platform + // inside it, is verified without asking anything — UNLESS THE SOURCE HAS SAID + // OTHERWISE SINCE (review 1, F1): a sighting or a probe older than the newest + // complete listing inside the window that does not name the video, or than + // its absent mark, vouches for nothing. Evidence taken from another channel + // URL is not evidence (F5). + const stored = await readListingEvidence(paths, channelSlug); + const evidence = evidenceForUrl(stored, config.url); + if (stored.url && stored.url !== config.url) { + log(`Verify before clean: the stored listing evidence was taken from another channel URL (${stored.url}) — not used.`); + } + const vouched = new Set<string>(); + let listedStored = 0; + let probedStored = 0; + if (maxAge > 0) { + for (const id of remaining) { + const cand = await candidateIdsOf(paths.channelsDir, channelSlug, id, platform); + const since = contradictedSince(evidence, cand, nowMs, maxAge); + const stamp = freshStampOf(evidence, cand, nowMs, maxAge); + if (stamp !== null && stamp >= since) { + vouched.add(id); + listedStored++; + continue; + } + const probed = await freshProbeAt(path.join(dataDir, id), nowMs, maxAge); + if (probed !== null && probed >= since) { + vouched.add(id); + probedStored++; + continue; + } + if (stamp !== null || probed !== null) contradicted.add(id); + } + } + const needed = remaining.filter((id) => !vouched.has(id)); + verdicts.fromEvidence = vouched.size; + if (maxAge > 0) { log( - `Verify before clean: could not verify availability (${reason}) — nothing cleaned this run.`, + `Verify before clean: started with ${verdicts.fromEvidence} of ${remaining.length} candidate(s) verified by stored evidence ` + + `(${listedStored} listed, ${probedStored} probed, within ${maxAge} h); ${needed.length} to ask the source.` + + (contradicted.size ? ` ${contradicted.size} older sighting(s) or probe(s) were overruled by a newer listing that does not name them.` : ""), ); - // A 429 on the listing (runYtdlp's EnumerationIncompleteError) is a rate - // limit: the platform's cooldown is recorded, as Sync records it, so the - // downloads and the retry of this clean both stay away for it. - if (err instanceof EnumerationIncompleteError) { - await (probes?.recordBackoff ?? ((pf: string) => recordDownloadBackoff(pf, paths, "rate_limit")))( - err.platform, - ).catch(() => {}); - verdicts.stopped = { kind: "rate-limit", platform: err.platform, message: reason }; - } else if (!signal?.aborted) { - verdicts.stopped = { kind: "error", platform, message: reason }; - } - return verdicts; } + if (needed.length === 0 || signal?.aborted) return verdicts; + // THE PACE (kept, not changed here): every request below — the listing's + // pages and each probe — runs at the platform's ADAPTIVE pace, yt-dlp's + // --sleep-requests, which a recorded rate limit widens (lib/pacing, + // channelArgs.channelPaceSeconds: a Rumble 429 took it from 1.05 s to + // 4.59 s), plus the probe gap between probes (AVAILABILITY_PROBE_GAP_MS). + log(`Verify before clean: asking at ${channelPaceSeconds(config).toFixed(2)} s between requests (${platform}'s current pace).`); - const suspects = remaining.filter((id) => maybeMissing.has(id)); - if (suspects.length === 0) { + // A COMPLETE listing inside the window already says which candidates it does + // not name: those are suspects to confirm one by one, with no new listing. + const complete = freshCompleteListing(evidence, nowMs, maxAge); + 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: all ${remaining.length} candidate(s) still listed on the source.`, + `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 at = new Date(nowMs).toISOString(); + let run: { urls: readonly string[]; complete: boolean; start: number }; + let maybeMissing: Set<string> | null = null; + let failure: unknown = null; + try { + if (resume.start === 1) { + // Ids known on disk but ABSENT from the channel's current flat playlist. + const quick = await (probes?.quick ?? runQuickAvailabilityCheck)({ + channelSlug, + paths, + onLog: log, + // runQuickAvailabilityCheck requires a signal; the sweep's is optional. + signal: signal ?? new AbortController().signal, + }); + maybeMissing = new Set(quick.ids); + run = { urls: [], complete: true, start: 1 }; + } else { + log( + `Verify before clean: continuing the listing cut short at ${resume.after!.at} (entries ${resume.after!.start}–${resume.after!.start + resume.after!.count - 1}) from entry ${resume.start}, ${resume.overlap} entries of overlap.`, + ); + let listing: { urls: string[]; ended: ListingEnd }; + try { + listing = await (probes?.list ?? fetchFlatPlaylist)({ + channelConfig: config, + paths, + channelSlug, + onLog: log, + signal: signal ?? new AbortController().signal, + start: resume.start, + }); + } catch (err) { + if (err instanceof EnumerationIncompleteError && err.urls.length > 0) { + noteShift(err.urls, resume, evidence, log); + await recordListing(paths, channelSlug, { at, source: "clean-check", urls: err.urls, complete: false, start: resume.start, pagesReached: err.pagesReached, platform, url: config.url }, nowMs).catch(() => {}); + } + throw err; + } + noteShift(listing.urls, resume, evidence, log); + // Complete only at the lister's own normal end (review 1, F2). + const done = listing.ended === "normal"; + const endedAt = new Date().toISOString(); + await recordListing(paths, channelSlug, { at, endedAt, source: "clean-check", urls: listing.urls, complete: done, start: resume.start, platform, url: config.url }).catch( + (err) => log(`Warning: could not record the listing evidence (${(err as Error).message}).`), + ); + run = { urls: listing.urls, complete: done, start: resume.start }; + if (!done) failure = new Error(listing.ended === "cancelled" ? "the listing was cancelled" : "the listing stopped early (exit 101)"); + } + } catch (err) { + failure = err; + run = { + urls: err instanceof EnumerationIncompleteError ? err.urls : [], + complete: false, + start: resume.start, + }; + } + + // What this run's listing returned, and THE CANDIDATES IT CONTRADICTS: a + // candidate stored evidence vouched for that the listing covered (by its + // place) and did not name. Newer beats older: it is a suspect (asked by + // itself) after a finished listing, unverified after a cut-short one, and + // marked absent so no older sighting vouches for it next time. + const returned = maybeMissing + ? new Set(remaining.filter((id) => !maybeMissing!.has(id))) + : await listedCandidates(match, remaining, indexListing(run.urls)); + const covered = await coverageOf(run, dataDir, log); + const absentNow: string[] = []; + for (const id of remaining) { + if (returned.has(id) || !(await covered(id))) continue; + absentNow.push(id); + if (vouched.has(id)) { + vouched.delete(id); + contradicted.add(id); + } + } + verdicts.fromEvidence = vouched.size; + await recordAbsent(paths, channelSlug, config.url, absentNow, at, nowMs).catch(() => {}); + const neededSet = new Set(needed); + const overruled = remaining.filter((id) => contradicted.has(id) && !neededSet.has(id)); + if (overruled.length) { + log( + `Verify before clean: this run's listing covers ${overruled.length} candidate(s) stored evidence had vouched for and does not name them — newer beats older: ` + + (failure ? "left unverified." : "confirming them individually."), + ); + } + + if (failure) { + // We know this channel is checkable and we got no complete answer + // (network, rate limit, extractor break, a cancel). Fail CLOSED — + // decision #4 at channel granularity — for everything the source did + // not name. + const err = failure; + const reason = (err as Error)?.message ?? String(err); + // 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 = run.urls.length > 0 ? indexListing(run.urls) : null; + const listedPartial = new Set(needed.filter((id) => returned.has(id))); + for (const id of needed) if (!listedPartial.has(id)) verdicts.unverified.add(id); + for (const id of overruled) verdicts.unverified.add(id); + if (partial) { + verdicts.partial = { verified: listedPartial.size, entries: partial.entries, unverified: verdicts.unverified.size }; + log( + `Verify before clean: verified ${listedPartial.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}) — ` + + (verdicts.fromEvidence ? `only the ${verdicts.fromEvidence} verified by stored evidence are cleaned this run.` : "nothing cleaned this run."), + ); + } + // A 429 on the listing (runYtdlp's EnumerationIncompleteError) is a rate + // limit: the platform's cooldown is recorded, as Sync records it, so the + // downloads and the retry of this clean both stay away for it. + if (err instanceof EnumerationIncompleteError) { + await (probes?.recordBackoff ?? ((pf: string) => recordDownloadBackoff(pf, paths, "rate_limit")))( + err.platform, + ).catch(() => {}); + verdicts.stopped = { kind: "rate-limit", platform: err.platform, message: reason }; + } else if (!signal?.aborted) { + verdicts.stopped = { kind: "error", platform, message: reason }; + } + return verdicts; + } + suspects = [...needed.filter((id) => !returned.has(id)), ...overruled]; + if (suspects.length === 0) { + log( + `Verify before clean: all ${needed.length} candidate(s) still listed on the source.`, + ); + return verdicts; + } + log( + `Verify before clean: ${suspects.length} candidate(s) missing from the fresh listing — confirming individually…`, ); - return verdicts; } if (signal?.aborted) return verdicts; // --- Tier C: one spawn per suspect ---------------------------------------- - log( - `Verify before clean: ${suspects.length} candidate(s) missing from the fresh listing — confirming individually…`, - ); let check: Awaited<ReturnType<typeof runAvailabilityCheck>>; try { check = await (probes?.full ?? runAvailabilityCheck)({ diff --git a/common/controller/verifyNewerEvidence.test.ts b/common/controller/verifyNewerEvidence.test.ts @@ -0,0 +1,419 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { access, chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { VerifyProbes } from "./verifyBeforeClean"; +import { verifyBeforeClean } from "./verifyBeforeClean"; +import { cleanAudioFromTranscribed } from "./cleanAudioFromTranscribed"; +import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck"; +import { foldListing, normalizeListingEvidence, readListingEvidence, recordListing } from "./listingEvidence"; +import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/verifyNewerEvidence.test.ts +// +// NEWER EVIDENCE BEATS OLDER (lane verify-resume, review 1). A stored sighting +// or a "public" probe vouches for a video only while nothing newer from its +// source contradicts it; a cancelled listing is never a complete one; a stamp +// from a wrong clock, a probe a later download contradicts and evidence of +// another channel URL vouch for nothing. Temp corpus, a fake yt-dlp, stub +// per-video probes; no network. + +const ROOT = await mkdtemp(path.join(tmpdir(), "verify-newer-")); +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 H = 3_600_000; +const iso = (ms: number) => new Date(ms).toISOString(); +const RU = "https://rumble.com/c/example"; +const watch = (id: string) => `https://rumble.com/${id}-a-title.html`; +const DAY_S = 86_400; +const T_UPLOAD = 1_790_000_000; // seconds; upload times are relative to it + +let n = 0; +type Video = { id: string; uploadedDaysAgo?: number; url?: boolean }; + +// A channel on `channelUrl` whose videos are transcribed and hold audio, and a +// fake yt-dlp: the listing file from `-I <start>:`, at most `limit` entries +// then a 429; `mode` "fail" prints the listing then fails (not a rate limit), +// "sleep" prints it then hangs (to be cancelled), "stop" exits 101. +async function channel(channelUrl: string, videos: Video[]) { + const dir = path.join(ROOT, `c${n++}`); + await mkdir(dir, { recursive: true }); + const bin = path.join(dir, "fake-ytdlp.sh"); + await writeFile( + bin, + [ + "#!/bin/sh", + `d='${dir}'`, + "start=1; prev=''", + 'for a in "$@"; do if [ "$prev" = "-I" ]; then start="${a%%:*}"; fi; prev="$a"; done', + 'echo "$start" >> "$d/calls"', + 'mode=$(cat "$d/mode" 2>/dev/null)', + 'if [ "$mode" = fail ]; then cat "$d/listing.txt"; echo "ERROR: [x] x: Unsupported URL" >&2; exit 1; fi', + 'if [ "$mode" = sleep ]; then cat "$d/listing.txt"; exec sleep 30; fi', + 'if [ "$mode" = stop ]; then cat "$d/listing.txt"; exit 101; fi', + 'lim=$(cat "$d/limit" 2>/dev/null || echo 0)', + 'awk -v s="$start" -v lim="$lim" \'NR>=s { if (lim>0 && c>=lim) exit; print; c++ }\' "$d/listing.txt"', + 'left=$(awk -v s="$start" \'NR>=s\' "$d/listing.txt" | wc -l)', + 'if [ "$lim" -gt 0 ] && [ "$left" -gt "$lim" ]; then echo "ERROR: [x] x: Unable to download webpage: HTTP Error 429: Too Many Requests" >&2; exit 1; fi', + "exit 0", + "", + ].join("\n"), + ); + await chmod(bin, 0o755); + const paths = { channelsDir: path.join(dir, "channels"), transcriptsDir: dir, ytdlpBin: bin, jobsDir: path.join(dir, ".jobs") } 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: channelUrl })); + await writeFile(path.join(dir, "listing.txt"), ""); + for (const v of videos) { + const vd = path.join(paths.channelsDir, "ch", "data", v.id); + await mkdir(vd, { recursive: true }); + await writeFile(path.join(vd, "transcript.json"), "{}"); + await writeFile(path.join(vd, "audio.mp3"), Buffer.alloc(10)); + const meta: Record<string, unknown> = { id: v.id }; + if (v.uploadedDaysAgo !== undefined) meta.timestamp = T_UPLOAD - v.uploadedDaysAgo * DAY_S; + if (v.url) meta.webpage_url = watch(v.id); + await writeFile(path.join(vd, "metadata.info.json"), JSON.stringify(meta)); + } + const file = (name: string) => path.join(dir, name); + return { + paths, + videoDir: (id: string) => path.join(paths.channelsDir, "ch", "data", id), + calls: async () => (await readFile(file("calls"), "utf8").catch(() => "")).split("\n").filter(Boolean), + setListing: (urls: string[]) => writeFile(file("listing.txt"), urls.length ? urls.join("\n") + "\n" : ""), + setLimit: (k: number) => writeFile(file("limit"), String(k)), + setMode: (m: "fail" | "sleep" | "stop") => writeFile(file("mode"), m), + hasAudio: (id: string) => access(path.join(paths.channelsDir, "ch", "data", id, "audio.mp3")).then(() => true, () => false), + pinned: (id: string) => access(path.join(paths.channelsDir, "ch", "data", id, "do-not-clean.json")).then(() => true, () => false), + }; +} + +// Per-video probes: answer `verdict(id)` for each id asked (written as +// runAvailabilityCheck writes it), or leave it unprobed when undefined. +function probesAnswering(paths: Paths, verdict: (id: string) => string | undefined) { + const asked: string[] = []; + const probes: VerifyProbes = { + recordBackoff: async () => {}, + full: async (opts) => { + const probedIds: string[] = []; + for (const id of opts.onlyIds ?? []) { + asked.push(id); + const v = verdict(id); + if (!v) continue; + await writeFile( + path.join(paths.channelsDir, "ch", "data", id, "availability.json"), + JSON.stringify({ checkedAt: new Date().toISOString(), checkedBy: "check", availability: v }), + ); + probedIds.push(id); + } + return { attempted: probedIds.length, checked: probedIds.length, skipped: 0, byStatus: {} as never, blocked: false, probedIds }; + }, + }; + return { asked, probes }; +} + +const clean = (paths: Paths, probes: VerifyProbes, lines: string[] = []) => + cleanAudioFromTranscribed({ channelSlug: "ch", paths, onLog: (m) => lines.push(m), probes, assertReachable: async () => {} }); + +// --------------------------------------------------------------------------- +// Finding 1: newer evidence beats older + +test("F1a, the reviewer's scenario on stored evidence: seen 08:00, deleted 12:00, a complete listing at 18:05 omits it — probed, pinned, audio kept", async () => { + const c = await channel(RU, [{ id: "v1gone" }, { id: "v1here" }]); + const now = Date.now(); + // 08:00 (10 h ago): Sync's paged walk lists both. + await recordListing(c.paths, "ch", { at: iso(now - 10 * H), source: "sync-paged", urls: [watch("v1gone"), watch("v1here")], complete: false, platform: "rumble", url: RU }); + // 18:05 (just now): a complete whole listing names only v1here. + await recordListing(c.paths, "ch", { at: iso(now - 60_000), source: "sync-full", urls: [watch("v1here")], complete: true, platform: "rumble", url: RU }); + const { asked, probes } = probesAnswering(c.paths, () => "deleted"); + await clean(c.paths, probes); + assert.deepEqual(asked, ["v1gone"], "the older sighting does not vouch: it is asked about by itself"); + assert.equal(await c.hasAudio("v1gone"), true); + assert.equal(await c.pinned("v1gone"), true); + assert.equal(await c.hasAudio("v1here"), false, "named by the newest listing: cleaned"); + assert.deepEqual(await c.calls(), [], "no listing was needed"); +}); + +test("F1a: a 'public' probe older than the newest complete listing that omits the video does not vouch either", async () => { + const c = await channel(RU, [{ id: "v1gone" }, { id: "v1here" }]); + const now = Date.now(); + await writeFile( + path.join(c.videoDir("v1gone"), "availability.json"), + JSON.stringify({ checkedAt: iso(now - 20 * H), checkedBy: "check", availability: "public" }), + ); + await recordListing(c.paths, "ch", { at: iso(now - H), source: "quick-check", urls: [watch("v1here")], complete: true, platform: "rumble", url: RU }); + const { asked, probes } = probesAnswering(c.paths, () => "private"); + await clean(c.paths, probes); + assert.deepEqual(asked, ["v1gone"]); + assert.equal(await c.hasAudio("v1gone"), true); + assert.equal(await c.pinned("v1gone"), true); +}); + +test("F1b, the scenario in one job: seen 08:00, the job's own complete listing omits it — probed, pinned, audio kept", async () => { + const c = await channel(RU, [{ id: "v1gone" }, { id: "v1new" }]); + await recordListing(c.paths, "ch", { at: iso(Date.now() - 10 * H), source: "sync-paged", urls: [watch("v1gone")], complete: false, platform: "rumble", url: RU }); + // v1new needs a listing; the job's Quick check completes and names only it. + await c.setListing([watch("v1new"), watch("v1other")]); + const { asked, probes } = probesAnswering(c.paths, () => "deleted"); + const lines: string[] = []; + await clean(c.paths, probes, lines); + assert.deepEqual(await c.calls(), ["1"]); + assert.deepEqual(asked, ["v1gone"]); + assert.equal(await c.hasAudio("v1gone"), true); + assert.equal(await c.pinned("v1gone"), true); + assert.equal(await c.hasAudio("v1new"), false); +}); + +test("F1c: a partial listing of this job overrules older evidence only over the stretch it covered", async () => { + // Newest first: v1recent (1 day), v1listed (3 days), v1older (30 days). + const c = await channel(RU, [ + { id: "v1recent", uploadedDaysAgo: 1 }, + { id: "v1listed", uploadedDaysAgo: 3 }, + { id: "v1older", uploadedDaysAgo: 30 }, + { id: "v1unseen", uploadedDaysAgo: 2 }, + ]); + const now = Date.now(); + await recordListing(c.paths, "ch", { at: iso(now - 10 * H), source: "sync-paged", urls: [watch("v1recent"), watch("v1older")], complete: false, platform: "rumble", url: RU }); + // The listing returns v1listed and stops: it covered everything newer than + // v1listed's upload, where v1recent was — and did not name it. + await c.setListing([watch("v1listed"), watch("v1x1"), watch("v1x2")]); + await c.setLimit(1); + const { asked, probes } = probesAnswering(c.paths, () => "public"); + const r = await clean(c.paths, probes); + assert.equal(r.stopped?.kind, "rate-limit"); + assert.deepEqual(asked, [], "nothing is probed after a rate limit"); + assert.equal(await c.hasAudio("v1recent"), true, "inside the stretch, not named: older sighting overruled"); + assert.equal(await c.hasAudio("v1listed"), false, "named: cleaned"); + assert.equal(await c.hasAudio("v1older"), false, "outside the stretch: its sighting still counts"); + assert.equal(await c.hasAudio("v1unseen"), true); + // The overruling is kept: the next run (whose listing answers nothing) does + // not let the 10-hour-old sighting vouch for v1recent again. + const ev = await readListingEvidence(c.paths, "ch"); + assert.ok(ev.absent.v1recent); + await c.setMode("fail"); + await clean(c.paths, probes); + assert.equal(await c.hasAudio("v1recent"), true); +}); + +test("F1: the saved-video prune does not run while a video a newer listing overruled stays unconfirmed", async () => { + const c = await channel(RU, [{ id: "v1gone" }, { id: "v1here" }]); + const now = Date.now(); + await recordListing(c.paths, "ch", { at: iso(now - 10 * H), source: "sync-paged", urls: [watch("v1gone")], complete: false, platform: "rumble", url: RU }); + await recordListing(c.paths, "ch", { at: iso(now - H), source: "sync-full", urls: [watch("v1here")], complete: true, platform: "rumble", url: RU }); + const lines: string[] = []; + await clean(c.paths, probesAnswering(c.paths, () => undefined).probes, lines); + assert.equal(await c.hasAudio("v1gone"), true); + assert.ok(lines.some((l) => l.includes("prune skipped") && l.includes("a newer listing does not name")), lines.join("\n")); +}); + +test("the prune: skipped after a partial listing, run when stored evidence alone verified everything", async () => { + const c = await channel(RU, [{ id: "v1aaaa" }]); + await recordListing(c.paths, "ch", { at: iso(Date.now() - H), source: "sync-paged", urls: [watch("v1aaaa")], complete: false, platform: "rumble", url: RU }); + let lines: string[] = []; + await clean(c.paths, probesAnswering(c.paths, () => undefined).probes, lines); + assert.equal(await c.hasAudio("v1aaaa"), false); + assert.ok(!lines.some((l) => l.includes("prune skipped")), lines.join("\n")); + + const d = await channel(RU, [{ id: "v1bbbb" }, { id: "v1cccc" }]); + await d.setListing([watch("v1bbbb"), watch("v1zzzz")]); + await d.setLimit(1); + lines = []; + await clean(d.paths, probesAnswering(d.paths, () => undefined).probes, lines); + assert.ok(lines.some((l) => l.includes("prune skipped")), lines.join("\n")); +}); + +test("a candidate uploaded after a stored complete listing: probed public, cleaned; probed deleted, pinned", async () => { + const c = await channel(RU, [{ id: "v1okay" }, { id: "v1gone" }]); + await recordListing(c.paths, "ch", { at: iso(Date.now() - H), source: "sync-full", urls: [watch("v1older")], complete: true, platform: "rumble", url: RU }); + const { asked, probes } = probesAnswering(c.paths, (id) => (id === "v1okay" ? "public" : "deleted")); + await clean(c.paths, probes); + assert.deepEqual(asked.sort(), ["v1gone", "v1okay"]); + assert.equal(await c.hasAudio("v1okay"), false); + assert.equal(await c.hasAudio("v1gone"), true); + assert.equal(await c.pinned("v1gone"), true); +}); + +test("an empty complete listing from the Quick check: every candidate is probed, none pinned or cleaned unanswered", async () => { + const c = await channel(RU, [{ id: "v1aaaa" }, { id: "v1bbbb" }]); + await recordListing(c.paths, "ch", { at: iso(Date.now() - 2 * H), source: "sync-paged", urls: [watch("v1aaaa")], complete: false, platform: "rumble", url: RU }); + await c.setListing([]); + const { asked, probes } = probesAnswering(c.paths, () => undefined); + const r = await clean(c.paths, probes); + assert.deepEqual(asked.sort(), ["v1aaaa", "v1bbbb"], "the stored sighting is overruled by the newer empty listing"); + assert.equal(r.cleanedDirs, 0); + assert.equal(await c.pinned("v1aaaa"), false); +}); + +test("a listing that fails for another reason than a rate limit after printing entries: nothing verified, nothing recorded", async () => { + const c = await channel(RU, [{ id: "v1aaaa" }]); + await c.setListing([watch("v1aaaa")]); + await c.setMode("fail"); + const r = await clean(c.paths, probesAnswering(c.paths, () => "public").probes); + assert.equal(r.cleanedDirs, 0); + assert.equal(r.stopped?.kind, "error"); + assert.equal((await readListingEvidence(c.paths, "ch")).attempts.length, 0); +}); + +test("an unreadable listing-evidence.json is no evidence: the check lists", async () => { + const c = await channel(RU, [{ id: "v1aaaa" }]); + await writeFile(path.join(c.paths.channelsDir, "ch", "listing-evidence.json"), '{"version":2,"url":"https://rumble.com/c/exa'); + await c.setListing([watch("v1aaaa")]); + const r = await clean(c.paths, probesAnswering(c.paths, () => undefined).probes); + assert.deepEqual(await c.calls(), ["1"]); + assert.equal(r.cleanedDirs, 1); +}); + +test("ids match exactly: a listed 'AbC…' does not vouch for a directory 'abc…'", async () => { + const yt = "https://www.youtube.com/@ch/videos"; + const c = await channel(yt, [{ id: "abcdefghijk" }]); + await recordListing(c.paths, "ch", { at: iso(Date.now() - H), source: "sync-paged", urls: ["https://www.youtube.com/watch?v=AbCdefghijk"], complete: false, platform: "youtube", url: yt }); + await c.setMode("fail"); + const v = await verifyBeforeClean({ channelSlug: "ch", paths: c.paths, candidateIds: ["abcdefghijk"], onLog: () => {}, probes: probesAnswering(c.paths, () => undefined).probes }); + assert.equal(v.fromEvidence, 0); + assert.deepEqual([...v.unverified], ["abcdefghijk"]); +}); + +// --------------------------------------------------------------------------- +// Finding 2: complete only at the lister's own normal end + +test("F2: a Quick check cancelled part-way records a partial listing, never a complete one", async () => { + const c = await channel(RU, [{ id: "v1aaaa" }]); + await c.setListing([watch("v1aaaa"), watch("v1bbbb")]); + await c.setMode("sleep"); + const ac = new AbortController(); + setTimeout(() => ac.abort(), 1500); + await assert.rejects(runQuickAvailabilityCheck({ channelSlug: "ch", paths: c.paths, onLog: () => {}, signal: ac.signal })); + const ev = await readListingEvidence(c.paths, "ch"); + assert.equal(ev.attempts.length, 1); + assert.equal(ev.attempts[0].complete, false); + // Nothing was concluded from the prefix either. + await assert.rejects(readFile(path.join(c.paths.channelsDir, "ch", "maybe-missing.json"), "utf8")); +}); + +test("F2: a listing yt-dlp stopped early (exit 101) is not complete", async () => { + const c = await channel(RU, [{ id: "v1aaaa" }]); + await c.setListing([watch("v1aaaa")]); + await c.setMode("stop"); + await assert.rejects(runQuickAvailabilityCheck({ channelSlug: "ch", paths: c.paths, onLog: () => {}, signal: new AbortController().signal })); + assert.equal((await readListingEvidence(c.paths, "ch")).attempts[0]?.complete, false); +}); + +// --------------------------------------------------------------------------- +// Finding 3: a wrong clock, the probe rule, a changed URL + +test("F3: a stamp from a clock that was ahead is dropped by the next write and never becomes fresh", () => { + const now = Date.parse("2026-11-21T12:00:00.000Z"); + const ahead = now + 5 * 24 * H; + // Written by a clock five days ahead. + let r = foldListing(normalizeListingEvidence(null), { at: iso(ahead), source: "sync-paged", urls: [watch("v1aaaa")], complete: true, platform: "rumble", url: RU }, ahead); + assert.equal(r.seen.v1aaaa, iso(ahead)); + // The next write, by a right clock: the future stamp and attempt are gone. + r = foldListing(r, { at: iso(now), source: "sync-paged", urls: [watch("v1bbbb")], complete: false, platform: "rumble", url: RU }, now); + assert.equal(r.seen.v1aaaa, undefined); + assert.deepEqual(r.attempts.map((a) => a.at), [iso(now)]); + // A listing dated in the future is refused at write. + r = foldListing(r, { at: iso(now + 2 * H), source: "sync-paged", urls: [watch("v1cccc")], complete: false, platform: "rumble", url: RU }, now); + assert.equal(r.seen.v1cccc, undefined); + assert.equal(r.attempts.length, 1); +}); + +test("F3: a 'public' probe is evidence only by platformPresence's rule — not when a download since found it otherwise, nor dated in the future", async () => { + const c = await channel(RU, [{ id: "v1auth" }, { id: "v1ahead" }]); + const now = Date.now(); + await writeFile(path.join(c.videoDir("v1auth"), "availability.json"), JSON.stringify({ checkedAt: iso(now - 2 * H), checkedBy: "check", availability: "public" })); + await writeFile( + path.join(c.videoDir("v1auth"), "download-outcome.json"), + JSON.stringify({ + videoId: "v1auth", + webpageUrl: watch("v1auth"), + status: "failed", + startedAt: iso(now - H), + finishedAt: iso(now - H + 60_000), + attempts: [{ n: 0, kind: "download", handling: "youtube", usedCookies: false, ytdlpExitCode: 1, availabilityClass: "needs_auth" }], + }), + ); + await writeFile(path.join(c.videoDir("v1ahead"), "availability.json"), JSON.stringify({ checkedAt: iso(now + 3 * H), checkedBy: "check", availability: "public" })); + await c.setMode("fail"); + const v = await verifyBeforeClean({ channelSlug: "ch", paths: c.paths, candidateIds: ["v1auth", "v1ahead"], onLog: () => {}, probes: probesAnswering(c.paths, () => undefined).probes }); + assert.equal(v.fromEvidence, 0); + assert.deepEqual([...v.unverified].sort(), ["v1ahead", "v1auth"]); +}); + +test("F3: evidence taken from another channel URL is not used, and the new URL's first listing starts the record again", async () => { + const other = "https://rumble.com/c/previous"; + const c = await channel(RU, [{ id: "v1aaaa" }]); + await recordListing(c.paths, "ch", { at: iso(Date.now() - H), source: "sync-full", urls: [watch("v1aaaa")], complete: true, platform: "rumble", url: other }); + await c.setMode("fail"); + const lines: string[] = []; + const v = await verifyBeforeClean({ channelSlug: "ch", paths: c.paths, candidateIds: ["v1aaaa"], onLog: (m) => lines.push(m), probes: probesAnswering(c.paths, () => undefined).probes }); + assert.equal(v.fromEvidence, 0); + assert.deepEqual(await c.calls(), ["1"], "it listed the current URL"); + assert.ok(lines.some((l) => l.includes("another channel URL"))); + await recordListing(c.paths, "ch", { at: iso(Date.now()), source: "sync-paged", urls: [watch("v1bbbb")], complete: false, platform: "rumble", url: RU }); + const ev = await readListingEvidence(c.paths, "ch"); + assert.equal(ev.url, RU); + assert.deepEqual(Object.keys(ev.seen), ["v1bbbb"]); + assert.equal(ev.attempts.length, 1); +}); + +// Keep the import used: the partial-listing error is what the fake's 429 becomes. +void EnumerationIncompleteError; + +// --------------------------------------------------------------------------- +// Review 2 + +test("R2-1: the newest complete listing is kept apart from the capped attempts — 25 later paged pages do not age its omission out", async () => { + const c = await channel(RU, [{ id: "v1gone" }, { id: "v1here" }]); + const now = Date.now(); + await recordListing(c.paths, "ch", { at: iso(now - 10 * H), source: "sync-full", urls: [watch("v1gone"), watch("v1here")], complete: true, platform: "rumble", url: RU }); + await recordListing(c.paths, "ch", { at: iso(now - 8 * H), source: "quick-check", urls: [watch("v1here")], complete: true, platform: "rumble", url: RU }); + for (let i = 0; i < 25; i++) { + await recordListing(c.paths, "ch", { at: iso(now - 7 * H + i * 60_000), source: "sync-paged", urls: [watch("v1here")], complete: false, platform: "rumble", url: RU }); + } + const { asked, probes } = probesAnswering(c.paths, () => "deleted"); + await clean(c.paths, probes); + assert.deepEqual(asked, ["v1gone"], "still contradicted: probed"); + assert.equal(await c.pinned("v1gone"), true); + assert.equal(await c.hasAudio("v1gone"), true); + const ev = await readListingEvidence(c.paths, "ch"); + assert.equal(ev.attempts.length, 20); + assert.equal(ev.lastComplete?.source, "quick-check"); + assert.deepEqual(ev.lastComplete?.ids, ["v1here"]); +}); + +test("R2-3: a complete listing contradicts from its END — a sighting while it was still running does not vouch", async () => { + const c = await channel(RU, [{ id: "v1gone" }, { id: "v1here" }]); + const now = Date.now(); + // The listing ran from 40 to 20 minutes ago; a paged page saw v1gone 30 + // minutes ago, while it ran; the listing did not name it. + await recordListing(c.paths, "ch", { at: iso(now - 30 * 60_000), source: "sync-paged", urls: [watch("v1gone")], complete: false, platform: "rumble", url: RU }); + await recordListing(c.paths, "ch", { at: iso(now - 40 * 60_000), endedAt: iso(now - 20 * 60_000), source: "store-playlist", urls: [watch("v1here")], complete: true, platform: "rumble", url: RU }); + const { asked, probes } = probesAnswering(c.paths, () => "deleted"); + await clean(c.paths, probes); + assert.deepEqual(asked, ["v1gone"]); + assert.equal(await c.hasAudio("v1gone"), true); + // A sighting AFTER the end does vouch (here: v1here, named by it, is cleaned). + assert.equal(await c.hasAudio("v1here"), false); +}); + +test("R2-3: a partial listing whose upload dates are not in order covers nothing beyond what it returned", async () => { + const c = await channel(RU, [ + { id: "v1aaaa", uploadedDaysAgo: 1 }, + { id: "v1bbbb", uploadedDaysAgo: 40 }, + { id: "v1cccc", uploadedDaysAgo: 2 }, + { id: "v1seen", uploadedDaysAgo: 10 }, + ]); + await recordListing(c.paths, "ch", { at: iso(Date.now() - 5 * H), source: "sync-paged", urls: [watch("v1seen")], complete: false, platform: "rumble", url: RU }); + // Returned out of date order (1, 40, 2 days), then a 429. + await c.setListing([watch("v1aaaa"), watch("v1bbbb"), watch("v1cccc"), watch("v1more")]); + await c.setLimit(3); + const lines: string[] = []; + await clean(c.paths, probesAnswering(c.paths, () => undefined).probes, lines); + assert.equal(await c.hasAudio("v1aaaa"), false, "returned: cleaned"); + assert.equal(await c.hasAudio("v1seen"), false, "nothing is assumed about an omission: its sighting still counts"); + assert.ok(lines.some((l) => l.includes("not in upload order")), lines.join("\n")); +}); diff --git a/common/controller/verifyPartialListing.test.ts b/common/controller/verifyPartialListing.test.ts @@ -0,0 +1,216 @@ +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> = {}, times: Record<string, number> = {}): 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] || times[id] !== undefined) { + await writeFile( + path.join(v, "metadata.info.json"), + JSON.stringify({ id: embed[id] ?? id, title: "t", ...(times[id] !== undefined ? { timestamp: times[id] } : {}) }), + ); + } + } + 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"); +}); + +test("a retry says how many verdicts it started with and how many it added", async () => { + const { recordListing } = await import("./listingEvidence"); + // Upload times: v1bbbb newest, v1aaaa a week older. This attempt's partial + // listing (newest first) reached v1bbbb only, so it did not cover v1aaaa's + // place: the earlier attempt's sighting of v1aaaa still counts. + const day = 86_400; + const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc"], {}, { v1aaaa: 1_790_000_000 - 7 * day, v1bbbb: 1_790_000_000, v1cccc: 1_790_000_000 - 30 * day }); + // The attempt before this one listed v1aaaa before the source stopped it. + await recordListing(paths, "ch", { at: new Date(Date.now() - 3_600_000).toISOString(), source: "quick-check", urls: [watch("v1aaaa")], complete: false, platform: "rumble", url: "https://rumble.com/c/example" }); + const { calls, probes } = rateLimitedAfter([watch("v1bbbb")]); + const lines: string[] = []; + const out = await runCleanAudioJob({ + channelSlug: "ch", + paths, + jobId: "job-2", + retry: { attempt: 1, of: "job-1", notBefore: T0 - 1, platform: "rumble", id: "job-1.retry1" }, + onLog: (m) => lines.push(m), + deps: { + probes, + assertReachable: async () => {}, + now: () => T0, + cooldownRemainingMs: async () => 0, + scheduleRetry: async () => ({ ok: true as const, id: "job-1.retry2" }), + }, + }); + assert.equal(calls.quick, 1); + assert.equal(out.end, "deferred"); + assert.equal(await hasAudio(paths, "v1aaaa"), false, "verified by the earlier attempt's entries"); + assert.equal(await hasAudio(paths, "v1bbbb"), false, "verified by this attempt's"); + assert.equal(await hasAudio(paths, "v1cccc"), true); + assert.ok( + lines.includes("Retry 1 of 2: started with 1 verdict(s) earlier attempts and stored listings had earned, added 1; 1 unverified remain."), + lines.join("\n"), + ); + assert.ok(lines.some((l) => /asking at \d+\.\d\d s between requests \(rumble's current pace\)/.test(l)), lines.join("\n")); +}); diff --git a/common/lib/availability-server.ts b/common/lib/availability-server.ts @@ -286,7 +286,7 @@ async function loadDownloadOutcomeAvailability( export async function platformPresence( videoDir: string, opts: { maxAgeDays: number; now?: Date }, -): Promise<{ onPlatform: boolean; availability: Availability | null; why: string }> { +): Promise<{ onPlatform: boolean; availability: Availability | null; why: string; checkedAt?: string }> { const now = opts.now ?? new Date(); const record = await loadAvailability(videoDir); const effective = await resolveEffectiveAvailability(videoDir).catch(() => null); @@ -300,6 +300,15 @@ export async function platformPresence( }; } const age = (now.getTime() - Date.parse(record.checkedAt)) / 86_400_000; + // A check dated in the future (more than a minute) was written by a wrong + // clock: not a fresh check (lane verify-resume, review 1 F3). + if (Number.isFinite(age) && age < -60_000 / 86_400_000) { + return { + onPlatform: false, + availability: record.availability, + why: `its last check (${record.checkedAt}) is dated in the future — ${refresh}`, + }; + } if (!Number.isFinite(age) || age > opts.maxAgeDays) { return { onPlatform: false, @@ -313,5 +322,10 @@ export async function platformPresence( if (record.availability !== "public" && record.availability !== "unlisted") { return { onPlatform: false, availability: record.availability, why: `its check says ${record.availability}` }; } - return { onPlatform: true, availability: record.availability, why: `checked ${record.availability} on ${record.checkedAt.slice(0, 10)}` }; + return { + onPlatform: true, + availability: record.availability, + why: `checked ${record.availability} on ${record.checkedAt.slice(0, 10)}`, + checkedAt: record.checkedAt, + }; } diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -103,6 +103,7 @@ type PreSchemaSiteSettings = { inlineTranscribeOnFallback: boolean; skipLiveDownloads: boolean; verifyAvailabilityBeforeClean: boolean; + verifyBeforeCleanMaxAgeHours: number; buildArchives: boolean; archiveStorage: { bucket: string; publicBaseUrl: string }; reportDebouncePreset: ReportDebouncePreset; @@ -179,6 +180,7 @@ test("SiteSettings keeps its 50 fields, in file order", () => { "inlineTranscribeOnFallback", "skipLiveDownloads", "verifyAvailabilityBeforeClean", + "verifyBeforeCleanMaxAgeHours", "buildArchives", "archiveStorage", "reportDebouncePreset", @@ -349,6 +351,21 @@ test("resumeMarginGB: 0 disables the hysteresis, capped at the max", () => { ]); }); +test("verifyBeforeCleanMaxAgeHours: 24 by default, 0 = always ask, capped at 72 hours", () => { + checkField("verifyBeforeCleanMaxAgeHours", [ + [-1, 0], + [0, 0], + [1.5, 1.5], + [S.VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX + 1, S.VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX], + [NaN, S.VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_DEFAULT], + ["24", S.VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_DEFAULT], + [null, S.VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_DEFAULT], + ]); + assert.equal(S.VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_DEFAULT, 24); + assert.equal(S.VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX, 72); + checkField("verifyBeforeCleanMaxAgeHours", [[168, 72]]); +}); + test("parallelTranscriptions: floored at 1, capped at the max", () => { checkField("parallelTranscriptions", [ [0, 1], diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -1039,6 +1039,17 @@ export const MIN_FREE_DISK_GB_MAX = 100000; export const RESUME_MARGIN_GB_DEFAULT = 2; export const RESUME_MARGIN_GB_MAX = 1000; +// The pre-clean check's freshness window (lane verify-resume): how long a +// listing that named a video, or a probe that found it, still vouches for it. +// 24 h is clean after capture's window (diarization.cleanVerdictMaxAgeHours): +// the same risk — a video removed since that listing — the archive already +// accepts for an automatic delete, and long enough that a day's Sync or Quick +// check lands inside it. Capped at 72 hours (review 1, operator): a video +// removed inside the window can lose its audio, and three days bounds that. +// 0 = never use stored evidence (always ask, the behaviour before the lane). +export const VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_DEFAULT = 24; +export const VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX = 72; + export const PARALLEL_TRANSCRIPTIONS_MAX = 16; export const PARALLEL_TRANSCRIPTIONS_DEFAULT = 2; @@ -1795,6 +1806,16 @@ export function clampResumeMarginGB(value: unknown): number { return n; } +export function clampVerifyBeforeCleanMaxAgeHours(value: unknown): number { + const n = + typeof value === "number" && Number.isFinite(value) + ? value + : VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_DEFAULT; + if (n < 0) return 0; + if (n > VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX) return VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX; + return n; +} + export function clampParallelTranscriptions(value: unknown): number { const n = typeof value === "number" && Number.isFinite(value) @@ -2048,6 +2069,9 @@ export const siteSettingsSchema = z.object({ verifyAvailabilityBeforeClean: settingsField((v): boolean => v !== false).describe( "Whether the transcribed-audio cleanup sweep checks each candidate is still available upstream before deleting its audio, pinning (do-not-clean) any video found permanently gone. The delete is irreversible and a gone video's audio is irreplaceable, so this defaults to true. Turn it off for an offline or URL-less setup, where the check can never resolve and cleanup would otherwise never delete anything. See verifyBeforeClean.ts.", ), + verifyBeforeCleanMaxAgeHours: settingsField((v): number => clampVerifyBeforeCleanMaxAgeHours(v)).describe( + "How long (hours) stored evidence vouches for a video in the pre-clean availability check (verifyBeforeClean). THE GUARANTEE THIS SETS: a checked Clean audio removes a video's audio only when the video was listed by its source, or confirmed by a per-video probe, within this many hours, with nothing newer from the source contradicting it (a newer complete listing that does not name it, or a listing of the check that covered its place and did not name it). So a video removed from its source inside this window, after its last sighting and before any newer listing, CAN have its audio cleaned (and, on a keep-latest channel, its rolled-out saved video pruned). 0 restores \"always ask\": only a listing or probe taken by the clean itself counts. Evidence: a listing that RETURNED the video (Sync's full sweep or paged walk, Store playlist, the Quick check, or an earlier clean's listing, including the entries a rate-limited listing returned before it stopped — channels/<slug>/listing-evidence.json, taken from the channel's current URL only), or a probe that found it public or unlisted (availability.json, checkedBy \"check\", with no download since finding otherwise). Default 24 (clean after capture's window, diarization.cleanVerdictMaxAgeHours), max 72.", + ), buildArchives: settingsField((v): boolean => v !== false).describe( "Whether site builds generate downloadable transcript/live-chat archive zips (into public/archives, linked on the Downloads page). Global default; a site can opt out via site.json `archives: false`, and a single build can skip via the \"Skip archive zips\" build control. Opt-out: default true.", ), diff --git a/common/ytdlp/manualDownloads.test.ts b/common/ytdlp/manualDownloads.test.ts @@ -48,13 +48,19 @@ process.env.YTDLP_BIN = BIN; const MANUAL = { handling: "transcribe", url: "https://www.youtube.com/@manual/videos", downloadMode: "manual" } as const; const AUTO = { handling: "transcribe", url: "https://www.youtube.com/@auto/videos" } as const; -for (const [slug, config] of [["manual", MANUAL], ["auto", AUTO]] as const) { +// A channel whose stored playlist lists a hundred videos, of which the fake's +// listing (two) is far less than the shrink guard lets Sync accept. +const SHRINK = { handling: "transcribe", url: "https://www.youtube.com/@shrink/videos", downloadMode: "manual" } as const; +for (const [slug, config] of [["manual", MANUAL], ["auto", AUTO], ["shrink", SHRINK]] as const) { mkdirSync(path.join(ROOT, "channels", slug, "data"), { recursive: true }); writeFileSync(path.join(ROOT, "channels", slug, "config.json"), JSON.stringify(config)); // An empty saved playlist: an automatic download-missing has nothing to fetch. writeFileSync(path.join(ROOT, "channels", slug, "playlist"), ""); } +const SHRINK_PLAYLIST = Array.from({ length: 100 }, (_, i) => `https://www.youtube.com/watch?v=shrink${String(i).padStart(5, "0")}`); +writeFileSync(path.join(ROOT, "channels", "shrink", "playlist"), SHRINK_PLAYLIST.join("\n") + "\n"); + const { runYtdlp } = await import("./runYtdlp"); const { getPaths } = await import("../lib/paths"); @@ -109,6 +115,14 @@ test("a manual channel's sync records the newest page and downloads nothing", as const roster = readFileSync(path.join(ROOT, "channels", "manual", "roster.json"), "utf8"); assert.match(roster, /aaaaaaaaaaa/); assert.match(roster, /bbbbbbbbbbb/); + // And it is evidence for the pre-clean check (lane verify-resume): what + // the page returned, dated, never a complete listing. + const ev = JSON.parse(readFileSync(path.join(ROOT, "channels", "manual", "listing-evidence.json"), "utf8")); + assert.ok(ev.seen.aaaaaaaaaaa && ev.seen.bbbbbbbbbbb); + assert.deepEqual( + ev.attempts.map((a: { source: string; complete: boolean; count: number }) => [a.source, a.complete, a.count]), + [["sync-paged", false, 2]], + ); // And the sync is a sync: its stamp is written. const cfg = JSON.parse(readFileSync(path.join(ROOT, "channels", "manual", "config.json"), "utf8")); assert.ok(cfg.lastSyncedAt); @@ -124,6 +138,12 @@ test("a manual channel's full sweep refreshes the playlist and downloads nothing const playlist = readFileSync(path.join(ROOT, "channels", "manual", "playlist"), "utf8"); assert.match(playlist, /aaaaaaaaaaa/); assert.match(playlist, /bbbbbbbbbbb/); + // The accepted whole listing is evidence, and complete. + const ev = JSON.parse(readFileSync(path.join(ROOT, "channels", "manual", "listing-evidence.json"), "utf8")); + const full = ev.attempts.filter((a: { source: string }) => a.source === "sync-full"); + assert.equal(full.length, 1); + assert.equal(full[0].complete, true); + assert.equal(full[0].count, 2); }); test("a single video still downloads on a manual channel", async () => { @@ -136,3 +156,24 @@ test("a single video still downloads on a manual channel", async () => { "the one video was asked for", ); }); + +test("a normally ended full listing the shrink guard holds back: Sync does not apply it, but it is complete evidence", async () => { + await runYtdlp({ + channelSlug: "shrink", + mode: "sync", + channelConfig: SHRINK as never, + paths: getPaths(), + onLog: () => {}, + signal: new AbortController().signal, + forceFullSweep: true, + }); + // The guard's own behaviour is unchanged: the stored playlist is not cut. + const playlist = readFileSync(path.join(ROOT, "channels", "shrink", "playlist"), "utf8").split("\n").filter(Boolean); + assert.deepEqual(playlist, SHRINK_PLAYLIST); + // But the listing really did end normally and omit 98 videos: it is the + // complete listing every older sighting must answer to. + const ev = JSON.parse(readFileSync(path.join(ROOT, "channels", "shrink", "listing-evidence.json"), "utf8")); + const full = ev.attempts.filter((a: { source: string }) => a.source === "sync-full"); + assert.equal(full.at(-1).complete, true); + assert.deepEqual(ev.lastComplete.ids, ["aaaaaaaaaaa", "bbbbbbbbbbb"]); +}); diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -79,6 +79,7 @@ import { type Roster, } from "../controller/rosterStore"; import { acceptListing, type ListingDecision } from "../controller/acceptListing"; +import { recordListing, type RecordedListing } from "../controller/listingEvidence"; import { deriveChannelSets } from "../controller/channelSets"; import { resolveShardItems } from "../controller/shard"; import { @@ -491,15 +492,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 +519,7 @@ export class EnumerationIncompleteError extends Error { this.platform = platform; this.pagesReached = pagesReached; this.count = count; + this.urls = urls; } } @@ -532,12 +542,29 @@ function cooldownPlatformKey(config: ChannelConfig): string { // Enumerate a channel's video URLs via `--flat-playlist --print url` (metadata // only, no downloads). Pass `range` to fetch a single newest-first page via -// `-I start:end`; sync uses this to walk the channel incrementally. +// `-I start:end`; sync uses this to walk the channel incrementally. A range +// with no `end` reads from `start` to the channel's end (`-I start:`) — the +// pre-clean check's continuation of a listing cut short (listingEvidence.ts +// says on which platforms that skips the pages before `start`). async function enumeratePlaylistUrls( opts: RunYtdlpOpts, root: string, - range?: { start: number; end: number }, + range?: { start: number; end?: number }, ): Promise<string[]> { + return (await enumeratePlaylist(opts, root, range)).urls; +} + +// HOW A LISTING ENDED (lane verify-resume, review 1 F2): "normal" only for the +// lister's own normal end, exit 0, not cancelled. A cancel returns what was +// printed (as it always has) but is "cancelled"; exit 101 (yt-dlp stopped on +// an existing entry or a max) is "stopped". Neither is a complete listing. +export type ListingEnd = "normal" | "stopped" | "cancelled"; + +async function enumeratePlaylist( + opts: RunYtdlpOpts, + root: string, + range?: { start: number; end?: number }, +): Promise<{ urls: string[]; ended: ListingEnd }> { const args: string[] = [ "--flat-playlist", "--skip-download", @@ -545,7 +572,7 @@ async function enumeratePlaylistUrls( "url", ]; if (range) { - args.push("--lazy-playlist", "-I", `${range.start}:${range.end}`); + args.push("--lazy-playlist", "-I", `${range.start}:${range.end ?? ""}`); } // Cookie mode "always" covers enumeration too (a members-only or otherwise // gated channel may not even list without cookies). @@ -596,6 +623,7 @@ async function enumeratePlaylistUrls( cooldownPlatformKey(opts.channelConfig), lastListingPage(stderr), urls.length, + urls, ); } throw new Error(`yt-dlp exited with code ${result.exitCode}`); @@ -604,7 +632,60 @@ async function enumeratePlaylistUrls( opts.onLog(`yt-dlp stopped on existing entry (exit 101).\n`); } - return urls; + const ended: ListingEnd = opts.signal.aborted ? "cancelled" : result.exitCode === 0 ? "normal" : "stopped"; + return { urls, ended }; +} + +// EVIDENCE FOR THE PRE-CLEAN CHECK (lane verify-resume): what a listing of +// this channel RETURNED — a whole listing, a page of the paged walk, or the +// entries a rate-limited one printed before it stopped — dated to when it +// started (controller/listingEvidence.ts). Best-effort: a failed write loses +// evidence (the check then asks the source), and must not fail a sync. +async function noteListingEvidence( + opts: RunYtdlpOpts, + listing: Omit<RecordedListing, "platform" | "url"> & { url?: string }, +): Promise<void> { + if (listing.urls.length === 0 && !listing.complete) return; + if (!opts.channelConfig.url) return; + try { + await recordListing(opts.paths, opts.channelSlug, { + endedAt: new Date().toISOString(), + ...listing, + url: opts.channelConfig.url, + platform: cooldownPlatformKey(opts.channelConfig), + }); + } catch (err) { + opts.onLog( + `Warning: could not record the listing evidence (${err instanceof Error ? err.message : String(err)}).\n`, + ); + } +} + +// enumeratePlaylistUrls, with what it returned noted as evidence — the +// entries printed before a 429 too (then rethrown, unchanged). +async function enumerateNoting( + opts: RunYtdlpOpts, + root: string, + source: RecordedListing["source"], + range?: { start: number; end?: number }, +): Promise<{ urls: string[]; at: string; ended: ListingEnd }> { + const at = new Date().toISOString(); + try { + return { ...(await enumeratePlaylist(opts, root, range)), at }; + } catch (err) { + if (err instanceof EnumerationIncompleteError) { + await noteListingEvidence(opts, { + at, + source, + urls: err.urls, + complete: false, + start: range?.start ?? 1, + pagesReached: err.pagesReached, + url: opts.channelConfig.url ?? "", + }); + } + throw err; + } } // Thin exported wrapper over the module-private enumeratePlaylistUrls for @@ -612,17 +693,29 @@ async function enumeratePlaylistUrls( // flat-playlist fetch and shouldn't have to fabricate a full RunYtdlpOpts. // enumeratePlaylistUrls only reads channelConfig, paths.ytdlpBin, onLog and // signal — never mode/tracker — so the cast is safe. -export async function fetchFlatPlaylistUrls(opts: { +export type FlatPlaylistOpts = { channelConfig: ChannelConfig; paths: Paths; channelSlug: string; onLog: (s: string) => void; signal: AbortSignal; -}): Promise<string[]> { + // 1-based first entry; > 1 reads `-I <start>:` (see enumeratePlaylistUrls). + start?: number; +}; + +export async function fetchFlatPlaylistUrls(opts: FlatPlaylistOpts): Promise<string[]> { + return (await fetchFlatPlaylist(opts)).urls; +} + +// The same, with how the lister ended (ListingEnd): only "normal" is a +// complete listing. +export async function fetchFlatPlaylist(opts: FlatPlaylistOpts): Promise<{ urls: string[]; ended: ListingEnd }> { const root = path.join(opts.paths.channelsDir, opts.channelSlug); - return enumeratePlaylistUrls( + const start = opts.start && opts.start > 1 ? Math.floor(opts.start) : undefined; + return enumeratePlaylist( { ...opts, mode: "store-playlist" } as RunYtdlpOpts, root, + start ? { start } : undefined, ); } @@ -768,8 +861,16 @@ async function acceptEnumeration( async function storePlaylist(opts: RunYtdlpOpts): Promise<void> { const root = channelRoot(opts); await mkdir(root, { recursive: true }); - const urls = await enumeratePlaylistUrls(opts, root); + const { urls, at, ended } = await enumerateNoting(opts, root, "store-playlist"); const { decision } = await acceptEnumeration(opts, root, urls); + // Complete when the lister ended normally (a cancelled one is a prefix), + // WHETHER OR NOT THE SHRINK GUARD ACCEPTS IT (review 2, F2): the guard + // keeps a sudden shrink from rewriting the playlist and the missing sets, + // which it still does; as evidence, a listing that really omitted the + // videos must contradict older sightings of them — that omission is the + // mass-removal case — and an omission here only sends a video to be asked + // about by itself, never pins or cleans it. + await noteListingEvidence(opts, { at, source: "store-playlist", urls, complete: ended === "normal" }); if (!decision.accept) { opts.onLog(`Store playlist: ${decision.reason}.\n`); return; @@ -2068,8 +2169,9 @@ async function syncPaged(opts: RunYtdlpOpts): Promise<void> { ) { const start = page * SYNC_PAGE_SIZE + 1; const end = start + SYNC_PAGE_SIZE - 1; - const pageUrls = await enumeratePlaylistUrls(opts, root, { start, end }); + const { urls: pageUrls, at: pageAt } = await enumerateNoting(opts, root, "sync-paged", { start, end }); if (pageUrls.length === 0) break; + await noteListingEvidence(opts, { at: pageAt, source: "sync-paged", urls: pageUrls, complete: false, start }); // ADD-ONLY: a page is a real (if partial) sighting of the listing, so the // ids on it belong in the roster — but a paged walk sees only the newest @@ -2168,8 +2270,10 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> { // the roster (additive, so this is safe unconditionally) and decide // whether the listing itself may be acted on. let urls: string[]; + let listedAt: string; + let listingEnd: ListingEnd; try { - urls = await enumeratePlaylistUrls(opts, root); + ({ urls, at: listedAt, ended: listingEnd } = await enumerateNoting(opts, root, "sync-full")); } catch (err) { if (!(err instanceof EnumerationIncompleteError)) throw err; // A 429 part-way through the listing: what was printed is a prefix, not a @@ -2203,6 +2307,8 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> { urls, ); opts.onLog(`Full sweep: ${decision.reason}.\n`); + // Complete when it ended normally, accepted or not (see storePlaylist). + await noteListingEvidence(opts, { at: listedAt, source: "sync-full", urls, complete: listingEnd === "normal" }); // A rejected listing must not truncate the stored playlist, must not flag // videos missing, and must not stamp lastFullSweepAt — so the next sync 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 @@ -42,6 +42,38 @@ a mark and when: "Do not clean: on (availability check, 3 Nov; the source was gone)" or "(you, 20 Nov)". - The opt-in's removal runs under the mark's lock. `"expectSourceGone"` makes the dry run's count binding. The backfill's proof is one-sided in time, and `marks-backfill {"undo": true}` returns inferred labels. +- **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 rate-limited Clean audio keeps what it learned, and its retry continues instead of starting over.** + - Before, every retry listed the whole channel again from entry 1 and threw away what the earlier attempt had read. + After 3 attempts the chain gave up with 350 audio files unverified. + - What each listing returned is now kept in `channels/<slug>/listing-evidence.json`. That covers Sync's full sweep + and paged walk, Store playlist, the Quick check, the clean's own listing, and the entries a rate-limited listing + returned before it stopped. + - A candidate listed within `verifyBeforeCleanMaxAgeHours` is cleaned without asking the source. So is one a + per-video probe found in that window, unless something newer from the source contradicts it. The setting is + new: 24 h by default, at most 72, 0 = always ask (SETTINGS.md). + - The guarantee changed. Before, a video was cleaned only when a listing or probe in the same job found it. Now a + listing or probe within the window is enough when nothing newer contradicts it. So a video removed from its + source inside the window, after its last sighting and before any newer listing, can have its audio cleaned. + - Newer beats older: a newer complete listing that does not name the video overrules an older sighting or probe, + and so does the clean's own listing. The video is then asked about by itself. A listing counts as complete only + when it ended normally: a cancelled one is a prefix. + - The newest complete listing is kept apart from the 20 recent listings, so later Sync pages cannot push its + omissions out. It is dated from its end. A full sweep the shrink guard holds back still counts as one (Sync + still does not apply it). + - On Odysee and BitChute the next listing continues two pages before where the last one stopped. Elsewhere yt-dlp + cannot skip pages, so a retry keeps the earlier verdicts and asks only for the rest. + - When few candidates remain against a large channel, each one is asked about by itself (paced, every answer kept) + instead of listing the channel. + - Each retry's log says how many verdicts it started with and how many it added. The log also states the + request pace in use. - **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 diff --git a/settings.json.example b/settings.json.example @@ -35,6 +35,7 @@ "inlineTranscribeOnFallback": false, "skipLiveDownloads": true, "verifyAvailabilityBeforeClean": true, + "verifyBeforeCleanMaxAgeHours": 24, "buildArchives": true, "archiveStorage": { "bucket": "",