Archilyzer · Source

archilyzer

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

commit f9c62e5b1bc1b986ca5001b494a17886f301fb20
parent 5e5cffc5908cce5b4308ec0ee351e58171dcc3f7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 16:36:37 -0500

verify before clean: newer evidence beats older (review 1, F1-F3)

F1 (blocking). A stored sighting or a "public" probe now vouches for a
video only while nothing newer from its source contradicts it:
- it must not be older than the newest complete listing inside the window
  that does not name the video (contradictedSince);
- after a complete listing in this job, every candidate it omits is a
  suspect and is asked about by itself, whatever stored evidence said;
- a cut-short listing of this job overrules older evidence only over the
  stretch it covered, judged by upload time (coverageOf); there the video
  is left unverified and marked absent in listing-evidence.json so the
  older sighting does not vouch next time;
- the saved-video prune does not run while an overruled video stays
  unconfirmed.

F2. A listing is complete only at the lister's own normal end: enumerate
reports how it ended (fetchFlatPlaylist, ListingEnd); a cancel or exit 101
is recorded partial, and the Quick check computes no missing set from it.
Store playlist and the full sweep check the same.

F3. A stamp or attempt dated in the future is refused at write and
dropped by the next write; the probe rule is platformPresence (now also
refusing a check dated in the future); evidence records the channel URL
it was taken from and is not used for another.

Tests (run RED on the previous code first, 11 of 16):
verifyNewerEvidence.test.ts, with the review's missing cases. Existing
fixtures gain the channel URL.

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

Diffstat:
Mcommon/controller/cleanAudioFromTranscribed.ts | 6+++++-
Mcommon/controller/listingEvidence.test.ts | 55+++++++++++++++++++++++++++++++++----------------------
Mcommon/controller/listingEvidence.ts | 139+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/controller/quickAvailabilityCheck.ts | 19++++++++++++++++---
Mcommon/controller/verifyBeforeClean.ts | 245++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---------------------
Acommon/controller/verifyNewerEvidence.test.ts | 364+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/verifyPartialListing.test.ts | 17+++++++++++++----
Mcommon/lib/availability-server.ts | 18++++++++++++++++--
Mcommon/ytdlp/runYtdlp.ts | 54+++++++++++++++++++++++++++++++++++++++++-------------
9 files changed, 792 insertions(+), 125 deletions(-)

diff --git a/common/controller/cleanAudioFromTranscribed.ts b/common/controller/cleanAudioFromTranscribed.ts @@ -287,6 +287,7 @@ export async function cleanAudioFromTranscribed({ 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, @@ -301,6 +302,7 @@ export async function cleanAudioFromTranscribed({ 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; @@ -369,7 +371,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 }); diff --git a/common/controller/listingEvidence.test.ts b/common/controller/listingEvidence.test.ts @@ -36,15 +36,17 @@ 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" }, 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); + 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" }, T0); + 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"); @@ -57,9 +59,9 @@ test("an id is dated to the start of the newest listing that returned it; embed }); 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); + 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" }, T0); + 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)); @@ -68,7 +70,9 @@ test("ids not listed for the retention period are dropped, and attempts are capp 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, + version: 2, + url: RU, + absent: {}, seen: { fresh: iso(T0 - 23 * H), stale: iso(T0 - 25 * H), future: iso(T0 + 2 * H) }, embedSeen: {}, attempts: [], @@ -78,17 +82,19 @@ test("only ids listed inside the window are fresh; 0 h uses nothing; a date in t }); 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" }] }); + 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: 1, + version: 2, + url: RU, + absent: {}, seen: {}, embedSeen: {}, - attempts: [{ at, source: "quick-check", complete: false, start: 1, count: 408, platform }], + 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( @@ -101,7 +107,7 @@ test("the resume start: a continuation only where the extractor pages by offset, // 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" }); + 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"); @@ -111,13 +117,15 @@ test("the resume start: a continuation only where the extractor pages by offset, test("a complete whole listing inside the window is found; a paged walk or a continuation is not one", () => { const r: ListingEvidence = { - version: 1, + version: 2, + url: RU, + absent: {}, 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" }, + { at: iso(T0 - 2 * H), source: "sync-full", complete: true, start: 1, count: 8000, platform: "rumble", url: RU }, + { at: iso(T0 - H), source: "sync-paged", complete: true, start: 1, count: 30, platform: "rumble", url: RU }, + { at: iso(T0 - H), source: "clean-check", complete: true, start: 309, count: 30, platform: "rumble", url: RU }, ], }; assert.equal(freshCompleteListing(r, T0, 24)?.source, "sync-full"); @@ -128,7 +136,7 @@ test("a complete whole listing inside the window is found; a paged walk or a con // 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> }; +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 @@ -145,6 +153,8 @@ async function source(channelUrl: string, ids: string[]): Promise<Source> { "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)', @@ -169,6 +179,7 @@ async function source(channelUrl: string, ids: string[]): Promise<Source> { 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"), }; } @@ -270,10 +281,10 @@ test("a listing that moved by more than the overlap between attempts: what neith 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 + 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" }); - await recordListing(s.paths, "ch", { at: iso(now - 30 * H), source: "sync-full", urls: ["https://rumble.com/v1bbbb-t.html"], complete: true, platform: "rumble" }); + 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" }); @@ -289,7 +300,7 @@ test("stored evidence: fresh Sync listings and fresh probes verify with no reque 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" }); + 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"); @@ -297,7 +308,7 @@ test("everything vouched for by stored evidence: nothing is asked at all", async 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" }); + 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"); @@ -309,7 +320,7 @@ 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" }); + 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); @@ -328,7 +339,7 @@ test("the few-candidates rule: fewer probes than listing requests; Kick's one-an 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" }); + 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); }); diff --git a/common/controller/listingEvidence.ts b/common/controller/listingEvidence.ts @@ -48,8 +48,9 @@ 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. + // 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; @@ -58,15 +59,27 @@ export type ListingAttempt = { // 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: 1; + 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[]; }; @@ -75,8 +88,8 @@ export function listingEvidencePath(paths: Pick<Paths, "channelsDir">, slug: str return path.join(paths.channelsDir, slug, LISTING_EVIDENCE_FILENAME); } -function emptyEvidence(): ListingEvidence { - return { version: 1, seen: {}, embedSeen: {}, attempts: [] }; +export function emptyEvidence(url: string | null = null): ListingEvidence { + return { version: 2, url, seen: {}, embedSeen: {}, absent: {}, attempts: [] }; } function stringMap(v: unknown): Record<string, string> { @@ -104,7 +117,8 @@ function isAttempt(v: unknown): v is ListingAttempt { a.start >= 1 && typeof a.count === "number" && a.count >= 0 && - typeof a.platform === "string" + typeof a.platform === "string" && + typeof a.url === "string" ); } @@ -115,9 +129,11 @@ export function normalizeListingEvidence(value: unknown): ListingEvidence { const r = value as Partial<ListingEvidence> | null; if (!r || typeof r !== "object") return emptyEvidence(); return { - version: 1, + 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) : [], }; } @@ -130,6 +146,12 @@ export async function readListingEvidence( 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; @@ -138,12 +160,39 @@ export type RecordedListing = { start?: number; pagesReached?: number | null; platform: string; + // The channel URL that was listed. + url: string; }; -// PURE: fold one listing into the record. +// 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 seen = { ...record.seen }; - const embedSeen = { ...record.embedSeen }; + 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)); + if (inFuture(listing.at, nowMs)) { + return { version: 2, url: listing.url, seen, embedSeen, absent, attempts }; + } const idx = indexListing(listing.urls); const stamp = (map: Record<string, string>, id: string) => { const prev = map[id]; @@ -151,11 +200,6 @@ export function foldListing(record: ListingEvidence, listing: RecordedListing, n }; 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, @@ -164,8 +208,9 @@ export function foldListing(record: ListingEvidence, listing: RecordedListing, n count: idx.entries, ...(listing.pagesReached !== undefined ? { pagesReached: listing.pagesReached } : {}), platform: listing.platform, + url: listing.url, }; - return { version: 1, seen, embedSeen, attempts: [...record.attempts, attempt].slice(-LISTING_ATTEMPTS_KEPT) }; + return { version: 2, url: listing.url, seen, embedSeen, absent, attempts: [...attempts, attempt].slice(-LISTING_ATTEMPTS_KEPT) }; } // Record what a listing returned. Callers treat a failure as best-effort: a @@ -183,13 +228,73 @@ export async function recordListing( }); } +// 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 + 60_000 && nowMs - t <= maxAgeHours * HOUR; + return Number.isFinite(t) && t <= nowMs + FUTURE_SLACK_MS && nowMs - t <= maxAgeHours * HOUR; +} + +// NEWER EVIDENCE BEATS OLDER (review 1, F1). When a video was last +// contradicted by the source, in ms (-Infinity: never): the newest COMPLETE +// whole-channel listing inside the window — it stamps every id it returned +// with its own start, so a video it named carries a stamp at least that new, +// and one it did not name carries an older one or none — 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. +export function contradictedSince(record: ListingEvidence, dirId: string, nowMs: number, maxAgeHours: number): number { + let t = Number.NEGATIVE_INFINITY; + const complete = freshCompleteListing(record, nowMs, maxAgeHours); + if (complete) t = Date.parse(complete.at); + const mark = record.absent[dirId]; + if (mark && !inFuture(mark, nowMs)) t = Math.max(t, Date.parse(mark)); + return t; +} + +// 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. diff --git a/common/controller/quickAvailabilityCheck.ts b/common/controller/quickAvailabilityCheck.ts @@ -1,7 +1,7 @@ import path from "node:path"; import { readdir } from "node:fs/promises"; import { readChannelConfig } from "./channels"; -import { EnumerationIncompleteError, 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"; @@ -70,19 +70,32 @@ export async function runQuickAvailabilityCheck({ // 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, source: "quick-check", urls, complete, platform, pagesReached }).catch( + recordListing(paths, channelSlug, { at: now, 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 { - freshUrls = await fetchFlatPlaylistUrls({ + 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); diff --git a/common/controller/verifyBeforeClean.ts b/common/controller/verifyBeforeClean.ts @@ -5,27 +5,30 @@ import { loadDoNotClean, setDoNotClean } from "../lib/doNotClean-server"; import { readChannelConfig } from "./channels"; import { readWebpageUrl, runAvailabilityCheck } from "./checkAvailability"; import { loadRoster } from "./rosterStore"; -import { readdir } from "node:fs/promises"; +import { readdir, readFile } from "node:fs/promises"; import { runQuickAvailabilityCheck } from "./quickAvailabilityCheck"; import { recordDownloadBackoff } from "../jobs/downloadBackoff"; import { detectPlatform } from "../lib/platform"; -import { EnumerationIncompleteError, fetchFlatPlaylistUrls } from "../ytdlp/runYtdlp"; -import { indexListing, listedCandidates } from "./listingMatch"; +import { EnumerationIncompleteError, fetchFlatPlaylist, type ListingEnd } from "../ytdlp/runYtdlp"; +import { candidateIdsOf, indexListing, listedCandidates } from "./listingMatch"; +import { extractVideoId } from "../lib/videoId"; import { + contradictedSince, entriesPerRequest, - preferPerVideo, + evidenceForUrl, freshCompleteListing, - freshListingIndex, - isFresh, + freshStampOf, listingResumeStart, + preferPerVideo, readListingEvidence, + recordAbsent, recordListing, type ListingEvidence, type ListingResume, } from "./listingEvidence"; -import { readAvailabilityVerdict } from "./availabilityVerdict"; -import { loadAvailability, resolveEffectiveAvailability } from "../lib/availability-server"; +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. @@ -44,8 +47,11 @@ import { channelPaceSeconds } from "../ytdlp/channelArgs"; // 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). +// 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 @@ -85,6 +91,11 @@ export type CleanVerdicts = { // 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 = { @@ -103,7 +114,7 @@ export type VerifyProbes = { quick?: typeof runQuickAvailabilityCheck; full?: typeof runAvailabilityCheck; // The continued listing (`-I <start>:`), on a platform that honours it. - list?: typeof fetchFlatPlaylistUrls; + list?: typeof fetchFlatPlaylist; recordBackoff?: (platform: string) => Promise<void>; }; @@ -120,18 +131,69 @@ export type VerifyBeforeCleanOptions = { 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 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. +const COVERAGE_PROBE_ENTRIES = 20; +async function coverageOf( + run: { urls: readonly string[]; complete: boolean; start: number }, + dataDir: string, +): 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 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 @@ -269,36 +331,53 @@ export async function verifyBeforeClean({ } const platform = detectPlatform(config.url) ?? "unknown"; const nowMs = (now ?? Date.now)(); - const maxAge = maxAgeHours ?? getSettings().verifyBeforeCleanMaxAgeHours; + 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; 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>(); + // 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) { - if (!listedStored.has(id) && (await freshProbeSaysAvailable(path.join(dataDir, id), nowMs, maxAge))) probedStored.add(id); + const since = contradictedSince(evidence, id, nowMs, maxAge); + const stamp = freshStampOf(evidence, await candidateIdsOf(paths.channelsDir, channelSlug, id, platform), 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) => !listedStored.has(id) && !probedStored.has(id)); - verdicts.fromEvidence = listedStored.size + probedStored.size; + const needed = remaining.filter((id) => !vouched.has(id)); + verdicts.fromEvidence = vouched.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.`, + `(${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.` : ""), ); } if (needed.length === 0 || signal?.aborted) return verdicts; @@ -311,8 +390,7 @@ export async function verifyBeforeClean({ // 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); + 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 @@ -339,7 +417,10 @@ export async function verifyBeforeClean({ // 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. - let listed: Set<string>; + 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. @@ -350,16 +431,15 @@ export async function verifyBeforeClean({ // 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))); + 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.`, ); - const at = new Date(nowMs).toISOString(); - let urls: string[]; + let listing: { urls: string[]; ended: ListingEnd }; try { - urls = await (probes?.list ?? fetchFlatPlaylistUrls)({ + listing = await (probes?.list ?? fetchFlatPlaylist)({ channelConfig: config, paths, channelSlug, @@ -370,24 +450,63 @@ export async function verifyBeforeClean({ } 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(() => {}); + 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(urls, resume, evidence, log); - await recordListing(paths, channelSlug, { at, source: "clean-check", urls, complete: true, start: resume.start, platform }, nowMs).catch( + noteShift(listing.urls, resume, evidence, log); + // Complete only at the lister's own normal end (review 1, F2). + const done = listing.ended === "normal"; + await recordListing(paths, channelSlug, { at, source: "clean-check", urls: listing.urls, complete: done, start: resume.start, platform, url: config.url }, nowMs).catch( (err) => log(`Warning: could not record the listing evidence (${(err as Error).message}).`), ); - // This attempt's entries; what the attempts before it listed inside - // the window was already taken out of `needed` (tier E). An entry the - // shift made us miss is in neither, and its candidate is confirmed - // individually below. - listed = await listedCandidates(match, needed, indexListing(urls)); + 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); + 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). Fail CLOSED — decision #4 at - // channel granularity — for everything the source did not name. + // (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"). @@ -397,10 +516,10 @@ export async function verifyBeforeClean({ // 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>(); + 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( @@ -426,7 +545,7 @@ export async function verifyBeforeClean({ } return verdicts; } - suspects = needed.filter((id) => !listed.has(id)); + 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.`, diff --git a/common/controller/verifyNewerEvidence.test.ts b/common/controller/verifyNewerEvidence.test.ts @@ -0,0 +1,364 @@ +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; diff --git a/common/controller/verifyPartialListing.test.ts b/common/controller/verifyPartialListing.test.ts @@ -29,7 +29,7 @@ let n = 0; // A Rumble channel whose candidates are transcribed and hold audio. `embed` // gives a candidate a metadata.info.json naming its second (embed) id. -async function corpus(ids: string[], embed: Record<string, string> = {}): Promise<Paths> { +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 }); @@ -42,7 +42,12 @@ async function corpus(ids: string[], embed: Record<string, string> = {}): Promis await mkdir(v, { recursive: true }); await writeFile(path.join(v, "transcript.json"), "{}"); await writeFile(path.join(v, "audio.mp3"), Buffer.alloc(100)); - if (embed[id]) await writeFile(path.join(v, "metadata.info.json"), JSON.stringify({ id: embed[id], title: "t" })); + 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; } @@ -175,9 +180,13 @@ test("the job: a partial listing ends deferred and says what it verified, cleane test("a retry says how many verdicts it started with and how many it added", async () => { const { recordListing } = await import("./listingEvidence"); - const paths = await corpus(["v1aaaa", "v1bbbb", "v1cccc"]); + // 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" }); + 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({ diff --git a/common/lib/availability-server.ts b/common/lib/availability-server.ts @@ -282,7 +282,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); @@ -296,6 +296,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, @@ -309,5 +318,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/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts @@ -551,6 +551,20 @@ async function enumeratePlaylistUrls( root: string, 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", @@ -618,7 +632,8 @@ 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 @@ -628,12 +643,14 @@ async function enumeratePlaylistUrls( // evidence (the check then asks the source), and must not fail a sync. async function noteListingEvidence( opts: RunYtdlpOpts, - listing: Omit<RecordedListing, "platform">, + 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, { ...listing, + url: opts.channelConfig.url, platform: cooldownPlatformKey(opts.channelConfig), }); } catch (err) { @@ -650,10 +667,10 @@ async function enumerateNoting( root: string, source: RecordedListing["source"], range?: { start: number; end?: number }, -): Promise<{ urls: string[]; at: string }> { +): Promise<{ urls: string[]; at: string; ended: ListingEnd }> { const at = new Date().toISOString(); try { - return { urls: await enumeratePlaylistUrls(opts, root, range), at }; + return { ...(await enumeratePlaylist(opts, root, range)), at }; } catch (err) { if (err instanceof EnumerationIncompleteError) { await noteListingEvidence(opts, { @@ -663,6 +680,7 @@ async function enumerateNoting( complete: false, start: range?.start ?? 1, pagesReached: err.pagesReached, + url: opts.channelConfig.url ?? "", }); } throw err; @@ -674,7 +692,7 @@ async function enumerateNoting( // 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; @@ -682,10 +700,18 @@ export async function fetchFlatPlaylistUrls(opts: { signal: AbortSignal; // 1-based first entry; > 1 reads `-I <start>:` (see enumeratePlaylistUrls). start?: number; -}): Promise<string[]> { +}; + +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); const start = opts.start && opts.start > 1 ? Math.floor(opts.start) : undefined; - return enumeratePlaylistUrls( + return enumeratePlaylist( { ...opts, mode: "store-playlist" } as RunYtdlpOpts, root, start ? { start } : undefined, @@ -834,11 +860,12 @@ async function acceptEnumeration( async function storePlaylist(opts: RunYtdlpOpts): Promise<void> { const root = channelRoot(opts); await mkdir(root, { recursive: true }); - const { urls, at } = await enumerateNoting(opts, root, "store-playlist"); + const { urls, at, ended } = await enumerateNoting(opts, root, "store-playlist"); const { decision } = await acceptEnumeration(opts, root, urls); - // Complete only when accepted: a shrink the guard holds is not trusted to - // say what is missing (its entries were still returned). - await noteListingEvidence(opts, { at, source: "store-playlist", urls, complete: decision.accept }); + // Complete only when the lister ended normally and the listing was + // accepted: a shrink the guard holds is not trusted to say what is missing + // (its entries were still returned), and a cancelled one is a prefix. + await noteListingEvidence(opts, { at, source: "store-playlist", urls, complete: decision.accept && ended === "normal" }); if (!decision.accept) { opts.onLog(`Store playlist: ${decision.reason}.\n`); return; @@ -2239,8 +2266,9 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> { // whether the listing itself may be acted on. let urls: string[]; let listedAt: string; + let listingEnd: ListingEnd; try { - ({ urls, at: listedAt } = await enumerateNoting(opts, root, "sync-full")); + ({ 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 @@ -2275,7 +2303,7 @@ async function syncFullSweep(opts: RunYtdlpOpts): Promise<void> { ); opts.onLog(`Full sweep: ${decision.reason}.\n`); // Complete only when accepted (see storePlaylist). - await noteListingEvidence(opts, { at: listedAt, source: "sync-full", urls, complete: decision.accept }); + await noteListingEvidence(opts, { at: listedAt, source: "sync-full", urls, complete: decision.accept && 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