Archilyzer · Source

archilyzer

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

commit 63a60efdf254b4903d20d138b4f2e3523fc832f8
parent d2d1373879b93d859eff1bb67b48d60885dc3e37
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 14:30:20 -0500

verify before clean: keep what each listing returned and continue, never restart

The pre-clean check now keeps evidence across attempts instead of
throwing away what a rate-limited listing had read:

- channels/<slug>/listing-evidence.json (controller/listingEvidence.ts):
  per id, the start time of the newest listing that RETURNED it, plus the
  last listings' shape. Written only from entries yt-dlp printed. The
  Quick check records its listing, complete or the prefix before a 429.
  (roster.json's lastListedAt cannot serve: its seed stamps the stored
  playlist of any age as listed now.)
- Tier E in verifyBeforeClean, before anything is asked: a candidate
  listed, or found public/unlisted by a per-video probe (checkedBy
  "check"), inside the new setting verifyBeforeCleanMaxAgeHours (default
  24, clean after capture's window; 0 = always ask) is verified. A
  complete listing inside the window sends the rest straight to the
  per-video confirmation, with no second listing.
- The next listing CONTINUES where the extractor pages by offset (yt-dlp
  OnDemandPagedList: Odysee/LBRY, BitChute): `--lazy-playlist -I <start>:`
  two pages before the cut, de-duplicated by id. Rumble, YouTube, Twitch
  and Kick list through generators, where -I N fetches pages 1..N anyway:
  they start at 1, and keep what earlier attempts verified. A listing that
  moved by more than the overlap is said; what neither attempt returned is
  never cleaned.

Tests: listingEvidence.test.ts (fake lister that rate-limits after N
entries and honours -I), settingsSchema.test.ts. SETTINGS.md regenerated.

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

Diffstat:
MSETTINGS.md | 7+++++++
Acommon/controller/listingEvidence.test.ts | 316+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/controller/listingEvidence.ts | 260+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/quickAvailabilityCheck.ts | 36++++++++++++++++++++++++++++--------
Mcommon/controller/verifyBeforeClean.ts | 292+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------
Mcommon/lib/settingsSchema.test.ts | 15+++++++++++++++
Mcommon/lib/settingsSchema.ts | 22++++++++++++++++++++++
Mcommon/ytdlp/runYtdlp.ts | 13++++++++++---
Msettings.json.example | 1+
9 files changed, 885 insertions(+), 77 deletions(-)

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"` | @@ -348,6 +349,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): a listing that RETURNED the video (Sync's full sweep or paged walk, 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), or a per-video probe that found it public or unlisted (availability.json, checkedBy "check"). A candidate vouched for inside the window is cleaned without asking the source; anything else is asked, and whatever stays unanswered is left unverified and never deleted. Default 24 (clean after capture's window, diarization.cleanVerdictMaxAgeHours), max 168; 0 = always ask. + +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/listingEvidence.test.ts b/common/controller/listingEvidence.test.ts @@ -0,0 +1,316 @@ +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); + +// --------------------------------------------------------------------------- +// 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" }, 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" }, 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" }, 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" }, 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" }, 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: 1, + 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" }] }); + 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: 1, + seen: {}, + embedSeen: {}, + attempts: [{ at, source: "quick-check", complete: false, start: 1, count: 408, platform }], + }); + // 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" }); + 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("a complete whole listing inside the window is found; a paged walk or a continuation is not one", () => { + const r: ListingEvidence = { + version: 1, + seen: {}, + embedSeen: {}, + attempts: [ + { at: iso(T0 - 2 * H), source: "sync-full", complete: true, start: 1, count: 8000, platform: "rumble" }, + { at: iso(T0 - H), source: "sync-paged", complete: true, start: 1, count: 30, platform: "rumble" }, + { at: iso(T0 - H), source: "clean-check", complete: true, start: 309, count: 30, platform: "rumble" }, + ], + }; + assert.equal(freshCompleteListing(r, T0, 24)?.source, "sync-full"); + assert.equal(freshCompleteListing(r, T0, 1), null); +}); + +// --------------------------------------------------------------------------- +// 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> }; + +// 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"', + '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)), + }; +} + +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.setLimit(1); // any listing would be refused at once + 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" }); + await recordListing(s.paths, "ch", { at: iso(now - 30 * H), source: "sync-full", urls: ["https://rumble.com/v1bbbb-t.html"], complete: true, platform: "rumble" }); + 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" }); + 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" }); + 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" }); + 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); +}); diff --git a/common/controller/listingEvidence.ts b/common/controller/listingEvidence.ts @@ -0,0 +1,260 @@ +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" + // 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 listing ran to the channel's end from `start` (exit 0, + // no range end). A 429 part-way, 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; +}; + +export type ListingEvidence = { + version: 1; + // 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>; + // Newest last. + attempts: ListingAttempt[]; +}; + +export function listingEvidencePath(paths: Pick<Paths, "channelsDir">, slug: string): string { + return path.join(paths.channelsDir, slug, LISTING_EVIDENCE_FILENAME); +} + +function emptyEvidence(): ListingEvidence { + return { version: 1, seen: {}, embedSeen: {}, attempts: [] }; +} + +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 === "sync-paged") && + typeof a.complete === "boolean" && + typeof a.start === "number" && + a.start >= 1 && + typeof a.count === "number" && + a.count >= 0 && + typeof a.platform === "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: 1, + seen: stringMap(r.seen), + embedSeen: stringMap(r.embedSeen), + attempts: Array.isArray(r.attempts) ? r.attempts.filter(isAttempt).slice(-LISTING_ATTEMPTS_KEPT) : [], + }; +} + +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(); +} + +export type RecordedListing = { + at: string; + source: ListingSource; + urls: readonly string[]; + complete: boolean; + start?: number; + pagesReached?: number | null; + platform: string; +}; + +// PURE: fold one listing into the record. +export function foldListing(record: ListingEvidence, listing: RecordedListing, nowMs: number): ListingEvidence { + const seen = { ...record.seen }; + const embedSeen = { ...record.embedSeen }; + 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 keep = (map: Record<string, string>) => { + for (const [id, t] of Object.entries(map)) if (nowMs - Date.parse(t) > LISTING_EVIDENCE_RETAIN_MS) delete map[id]; + }; + keep(seen); + keep(embedSeen); + 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, + }; + return { version: 1, seen, embedSeen, attempts: [...record.attempts, attempt].slice(-LISTING_ATTEMPTS_KEPT) }; +} + +// 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 }); + }); +} + +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 + 60_000 && nowMs - t <= maxAgeHours * HOUR; +} + +// 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. +export function freshCompleteListing( + record: ListingEvidence, + nowMs: number, + maxAgeHours: number, +): ListingAttempt | null { + if (maxAgeHours <= 0) return null; + for (let i = record.attempts.length - 1; i >= 0; i--) { + const a = record.attempts[i]; + if (a.complete && a.start === 1 && a.source !== "sync-paged" && isFresh(a.at, nowMs, maxAgeHours)) return a; + } + return 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 }; +} 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, fetchFlatPlaylistUrls } from "../ytdlp/runYtdlp"; +import { detectPlatform } from "../lib/platform"; +import { recordListing } from "./listingEvidence"; import { diffMaybeMissing, writeMaybeMissing } from "./maybeMissingStore"; import { mergeRosterFile, @@ -63,13 +65,31 @@ 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 record = (urls: readonly string[], complete: boolean, pagesReached?: number | null) => + recordListing(paths, channelSlug, { at: now, source: "quick-check", urls, complete, platform, pagesReached }).catch( + (err) => log(`Warning: could not record the listing evidence (${(err as Error).message}).`), + ); + let freshUrls: string[]; + try { + freshUrls = await fetchFlatPlaylistUrls({ + channelConfig: config, + paths, + channelSlug, + onLog: log, + signal, + }); + } 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,15 +1,27 @@ 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 { runQuickAvailabilityCheck } from "./quickAvailabilityCheck"; import { recordDownloadBackoff } from "../jobs/downloadBackoff"; import { detectPlatform } from "../lib/platform"; -import { EnumerationIncompleteError } from "../ytdlp/runYtdlp"; +import { EnumerationIncompleteError, fetchFlatPlaylistUrls } from "../ytdlp/runYtdlp"; import { indexListing, listedCandidates } from "./listingMatch"; +import { + freshCompleteListing, + freshListingIndex, + isFresh, + listingResumeStart, + readListingEvidence, + recordListing, + type ListingEvidence, + type ListingResume, +} from "./listingEvidence"; +import { readAvailabilityVerdict } from "./availabilityVerdict"; +import { loadAvailability, resolveEffectiveAvailability } from "../lib/availability-server"; +import { getSettings } from "../lib/settings"; // Availability gate for the transcribed-audio cleanup sweep. // @@ -18,21 +30,31 @@ import { indexListing, listedCandidates } from "./listingMatch"; // 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. 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). @@ -53,6 +75,9 @@ export type CleanVerdicts = { // `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): a retry's starting point. + fromEvidence?: number; }; export type CleanVerifyStop = { @@ -70,6 +95,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 fetchFlatPlaylistUrls; recordBackoff?: (platform: string) => Promise<void>; }; @@ -80,8 +107,57 @@ 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; }; +// A per-video probe (runAvailabilityCheck, `checkedBy: "check"`) that found +// the video public or unlisted inside the window. A `backfill` record is an +// assumption made from a listing, and a record that does not say who wrote it +// says nothing: neither is evidence. +async function freshProbeSaysAvailable(videoDir: string, nowMs: number, maxAgeHours: number): Promise<boolean> { + const rec = await loadAvailability(videoDir).catch(() => null); + return ( + !!rec && + rec.checkedBy === "check" && + (rec.availability === "public" || rec.availability === "unlisted") && + isFresh(rec.checkedAt, nowMs, maxAgeHours) + ); +} + +// 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() }; } @@ -102,6 +178,8 @@ export async function verifyBeforeClean({ onLog, signal, probes, + now, + maxAgeHours, }: VerifyBeforeCleanOptions): Promise<CleanVerdicts> { const log = onLog ?? ((m: string) => console.log(m)); const verdicts = emptyVerdicts(); @@ -140,7 +218,6 @@ export async function verifyBeforeClean({ } 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. @@ -151,76 +228,159 @@ 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 complete answer - // (network, rate limit, extractor break). Fail CLOSED — decision #4 at - // channel granularity — for everything the source did not name. - const reason = (err as Error)?.message ?? String(err); - // A PARTIAL LISTING (lane verify-resume, operator 21 Nov 2026: "take a - // partial result and clean files that were found live in the partial"). - // The entries a rate-limited listing printed before the 429 were returned - // by the source in THIS attempt: a candidate among them is as listed as in - // a complete listing, and is verified. Matched by id exactly as the full - // check matches (listingMatch.ts: both of Rumble's ids, never a substring). - // A candidate the prefix does not name is NOT a suspect — the listing - // simply never reached it — and stays unverified and untouched. - const partial = - err instanceof EnumerationIncompleteError && err.urls.length > 0 ? indexListing(err.urls) : null; - const listed = partial - ? await listedCandidates({ channelsDir: paths.channelsDir, slug: channelSlug, platform }, remaining, partial) - : new Set<string>(); - for (const id of remaining) if (!listed.has(id)) verdicts.unverified.add(id); - if (partial) { - verdicts.partial = { verified: listed.size, entries: partial.entries, unverified: verdicts.unverified.size }; - log( - `Verify before clean: verified ${listed.size} from a partial listing of ${partial.entries} entries; ` + - `${verdicts.unverified.size} unverified remain (${reason}) — only the verified are cleaned this run.`, - ); - } else { - log( - `Verify before clean: could not verify availability (${reason}) — nothing cleaned this run.`, - ); - } - // A 429 on the listing (runYtdlp's EnumerationIncompleteError) is a rate - // limit: the platform's cooldown is recorded, as Sync records it, so the - // downloads and the retry of this clean both stay away for it. - 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 }; + const nowMs = (now ?? Date.now)(); + const maxAge = maxAgeHours ?? getSettings().verifyBeforeCleanMaxAgeHours; + const match = { channelsDir: paths.channelsDir, slug: channelSlug, platform }; + + // --- 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; availability-verdict.json: a Quick check from + // before that file), or a per-video probe found public/unlisted inside it, + // is verified without asking anything. This is how a retry continues: it + // starts from every verdict the attempts before it earned. + const evidence = await readListingEvidence(paths, channelSlug); + const verdictRecord = await readAvailabilityVerdict(paths, channelSlug).catch(() => null); + const verdictFresh = + verdictRecord?.checkedAt && isFresh(verdictRecord.checkedAt, nowMs, maxAge) && maxAge > 0 ? verdictRecord : null; + const storedIndex = freshListingIndex(evidence, nowMs, maxAge); + if (verdictFresh) for (const id of verdictFresh.ids) storedIndex.ids.add(id); + storedIndex.entries = storedIndex.ids.size + storedIndex.embedIds.size; + const listedStored = await listedCandidates(match, remaining, storedIndex); + const probedStored = new Set<string>(); + if (maxAge > 0) { + for (const id of remaining) { + if (!listedStored.has(id) && (await freshProbeSaysAvailable(path.join(dataDir, id), nowMs, maxAge))) probedStored.add(id); } - return verdicts; } + const needed = remaining.filter((id) => !listedStored.has(id) && !probedStored.has(id)); + verdicts.fromEvidence = listedStored.size + probedStored.size; + if (maxAge > 0) { + log( + `Verify before clean: started with ${verdicts.fromEvidence} of ${remaining.length} candidate(s) verified by stored evidence ` + + `(${listedStored.size} listed, ${probedStored.size} probed, within ${maxAge} h); ${needed.length} to ask the source.`, + ); + } + if (needed.length === 0 || signal?.aborted) return verdicts; - 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) ?? (verdictFresh ? { at: verdictFresh.checkedAt as string } : null); + let suspects: string[]; + 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 { + // --- Tier B: one flat-playlist spawn ------------------------------------ + // From entry 1 through the Quick check; or, on a platform whose listing + // can start at an offset (listingEvidence.ts, LISTING_OFFSET_PAGE_SIZE), + // CONTINUED from where the last attempt inside the window stopped, less an + // overlap of two pages. + const resume = listingResumeStart(evidence, platform, nowMs, maxAge); + let listed: Set<string>; + try { + if (resume.start === 1) { + // 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, + }); + const maybeMissing = new Set(quick.ids); + listed = new Set(needed.filter((id) => !maybeMissing.has(id))); + } 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.`, + ); + const at = new Date(nowMs).toISOString(); + let urls: string[]; + try { + urls = await (probes?.list ?? fetchFlatPlaylistUrls)({ + 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 }, nowMs).catch(() => {}); + } + throw err; + } + noteShift(urls, resume, evidence, log); + await recordListing(paths, channelSlug, { at, source: "clean-check", urls, complete: true, start: resume.start, platform }, nowMs).catch( + (err) => log(`Warning: could not record the listing evidence (${(err as Error).message}).`), + ); + // This attempt's entries, with what the attempts before it listed + // inside the window: an entry the shift made us miss is simply not in + // either, and its candidate is confirmed individually below. + listed = await listedCandidates(match, needed, indexListing(urls)); + } + } catch (err) { + // We know this channel is checkable and we got no complete answer + // (network, rate limit, extractor break). Fail CLOSED — decision #4 at + // channel granularity — for everything the source did not name. + const reason = (err as Error)?.message ?? String(err); + // A PARTIAL LISTING (lane verify-resume, operator 21 Nov 2026: "take a + // partial result and clean files that were found live in the partial"). + // The entries a rate-limited listing printed before the 429 were returned + // by the source in THIS attempt: a candidate among them is as listed as in + // a complete listing, and is verified. Matched by id exactly as the full + // check matches (listingMatch.ts: both of Rumble's ids, never a substring). + // A candidate the prefix does not name is NOT a suspect — the listing + // simply never reached it — and stays unverified and untouched. + const partial = + err instanceof EnumerationIncompleteError && err.urls.length > 0 ? indexListing(err.urls) : null; + const listedPartial = partial ? await listedCandidates(match, needed, partial) : new Set<string>(); + for (const id of needed) if (!listedPartial.has(id)) 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) => !listed.has(id)); + 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/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,19 @@ test("resumeMarginGB: 0 disables the hysteresis, capped at the max", () => { ]); }); +test("verifyBeforeCleanMaxAgeHours: 24 by default, 0 = always ask, capped at a week", () => { + 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); +}); + 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 @@ -1017,6 +1017,15 @@ 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 a week; 0 = never use stored evidence. +export const VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_DEFAULT = 24; +export const VERIFY_BEFORE_CLEAN_MAX_AGE_HOURS_MAX = 168; + export const PARALLEL_TRANSCRIPTIONS_MAX = 16; export const PARALLEL_TRANSCRIPTIONS_DEFAULT = 2; @@ -1773,6 +1782,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) @@ -2026,6 +2045,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): a listing that RETURNED the video (Sync's full sweep or paged walk, 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), or a per-video probe that found it public or unlisted (availability.json, checkedBy \"check\"). A candidate vouched for inside the window is cleaned without asking the source; anything else is asked, and whatever stays unanswered is left unverified and never deleted. Default 24 (clean after capture's window, diarization.cleanVerdictMaxAgeHours), max 168; 0 = always ask.", + ), 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/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -541,11 +541,14 @@ 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[]> { const args: string[] = [ "--flat-playlist", @@ -554,7 +557,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). @@ -628,11 +631,15 @@ export async function fetchFlatPlaylistUrls(opts: { channelSlug: string; onLog: (s: string) => void; signal: AbortSignal; + // 1-based first entry; > 1 reads `-I <start>:` (see enumeratePlaylistUrls). + start?: number; }): Promise<string[]> { const root = path.join(opts.paths.channelsDir, opts.channelSlug); + const start = opts.start && opts.start > 1 ? Math.floor(opts.start) : undefined; return enumeratePlaylistUrls( { ...opts, mode: "store-playlist" } as RunYtdlpOpts, root, + start ? { start } : undefined, ); } 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": "",