// THE LANES' SIDE OF A SOURCE GROUP (lane cross-source-dupes, slice 1): the // plan read from settings.sourceGroups, the scan's files and the decisions // file, each other copy's work read off its own files, and // lib/copies/laneHold.ts applied. Called by the runner tick AND by // computeLeafPending (controller/autoRunner.ts), right after the in-flight set // and the completed set are taken out, so the panel's numbers are the // runner's numbers. // // NO GROUP, NO READ. `loadCopyPlan` answers null before touching the disk // when no group has `lanes` on, and the caller then leaves its pending lists // exactly as they were: no group configured is today's lane, byte for byte. // // OFF THE HOT PATH. What a partner copy holds is read once and kept, keyed by // the size and mtime of the files that decide it; a tick answers from that // cache, and a cached answer older than COPY_DONE_REVALIDATE_MS is re-checked // in the background (one stat per file, single-flight per video) — the file // itself is re-read only when its size or mtime moved. Only a copy never seen // before is read inline, once. // // Only the transcription and Speakers (backfill) lanes act on copies. The // download lane is untouched in slice 1 — the fallback copy keeps downloading // exactly as before, because it is the copy that survives a takedown — and so // is the digest lane. import path from "node:path"; import { readdir, readFile, stat } from "node:fs/promises"; import type { Paths } from "../lib/paths"; import type { SiteSettings } from "../lib/settings"; import { isGroup, type AutoQueueKind, type AutoQueueNode, type AutoQueuePolicy } from "../lib/autoQueueTypes"; import { mapConcurrent } from "../lib/concurrency"; import { isTranscriptVtt, readVideoFiles, resolvePrimaryVtt, WHISPER_FILENAME } from "../lib/videoStatus"; import { parseVtt } from "../lib/vtt"; import { isStoredTextName, logicalEntries, storedNameOf } from "../lib/storedText"; import { isStoredTextReadError, readStoredText } from "../lib/storedText-server"; import { resolveCaptionsProvenance } from "../lib/subtitleProvenance"; import { operationsForLane } from "../lib/operations"; import { DIARIZATION_FILENAME } from "../lib/videoStatus"; import { ATTRIBUTION_FILENAME } from "../lib/attribution"; import { AUDIO_INTEGRITY_FILENAME } from "../lib/audioIntegrity"; import { copyVideoKey } from "../lib/copies/file"; import { copiesDecisionsPath, copiesPath, readCopiesDecisions, readCopiesFile } from "../lib/copies/file-server"; import { applyCopyHolds, copyPartnersToRead, type CopyHoldDecision, type CopyPartner, type CopyPlan, } from "../lib/copies/laneHold"; import type { SourceGroup } from "../lib/copies/settings"; export const COPY_LANES: readonly AutoQueueKind[] = ["transcription", "backfill"]; export function laneActsOnCopies(kind: AutoQueueKind): boolean { return COPY_LANES.includes(kind); } // What each lane calls its work, in a hold's reason. const LANE_WORK: Partial> = { transcription: "transcript", backfill: "speakers work", }; // A TRANSCRIPT THAT IS REAL WORK: at least this many words of speech, and // this many per minute of runtime. Speech runs 120–160 words a minute; a // stream that is mostly gameplay still averages far above 10. A file under it // is headers only, music only ([Music] cues), or a failed track — not the // recording transcribed. export const COPY_DONE_MIN_WORDS = 50; export const COPY_DONE_WORDS_PER_MINUTE = 10; export const COPY_DONE_REVALIDATE_MS = 30_000; const DONE_READ_CONCURRENCY = 16; // The disk calls this module makes, one seam so a test can count them. export type CopiesLaneIo = { readFile: (p: string) => Promise; readdir: (p: string) => Promise; stat: (p: string) => Promise<{ mtimeMs: number; size: number }>; // A caption's text in either form (lib/storedText.ts). A test's seam may // leave it out: the plain file is read through `readFile` then. readCaption?: (dir: string, name: string) => Promise; }; const realIo: CopiesLaneIo = { readFile: (p) => readFile(p, "utf8"), readdir: (p) => readdir(p), stat: (p) => stat(p), readCaption: (dir, name) => readStoredText(dir, name, "utf8"), }; let io: CopiesLaneIo = realIo; // Stored captions this process found unreadable (REVIEW-1 F3): counted. let unreadableStoredCaptions = 0; export function unreadableStoredCaptionCount(): number { return unreadableStoredCaptions; } let revalidateMs = COPY_DONE_REVALIDATE_MS; // What the lanes need to know about a video of a group, beyond its pairs. export type CopyFacts = { duration: number; captionsCountAsDone: boolean }; export type LaneCopyPlan = { plan: CopyPlan; facts: Map }; type PlanCacheEntry = { key: string; value: LaneCopyPlan }; let planCache: PlanCacheEntry | null = null; type DoneEntry = { sig: string; done: boolean; checkedAt: number; refreshing: Promise | null }; const doneCache = new Map(); const firstReads = new Map>(); export function resetCopiesLaneCacheForTest(): void { planCache = null; doneCache.clear(); firstReads.clear(); } export function setCopiesLaneIoForTest(next: CopiesLaneIo | null, opts: { revalidateMs?: number } = {}): void { io = next ?? realIo; revalidateMs = opts.revalidateMs ?? COPY_DONE_REVALIDATE_MS; } /** Resolves once every background re-check started so far has settled. */ export async function copiesLaneSettledForTest(): Promise { await Promise.all([...doneCache.values()].map((e) => e.refreshing ?? Promise.resolve())); } async function stampOf(file: string): Promise { return io.stat(file).then( (st) => `${st.mtimeMs}:${st.size}`, () => "-", ); } /** * The lanes' copy plan: every cross-channel pair of every group whose `lanes` * is on that is CONFIRMED (by text and runtime, or by copies-confirm) or * METADATA-only, oriented by the group's CURRENT order, minus the rejected * pairs, and the released videos. Null — with no I/O at all — when no group * acts. A pair whose channel has since left its group is dropped, so removing * a channel (or the group) restores the lane at once. Cached on the files' * sizes and mtimes. */ export async function loadCopyPlan( paths: Paths, settings: Pick, ): Promise { const groups: SourceGroup[] = (settings.sourceGroups ?? []).filter((g) => g.lanes); if (groups.length === 0) return null; const stamps = await Promise.all( groups.map(async (g) => [ await stampOf(copiesPath(paths.transcriptsDir, g.id)), await stampOf(copiesDecisionsPath(paths.transcriptsDir, g.id)), ]), ); const key = JSON.stringify([paths.transcriptsDir, groups, stamps]); if (planCache?.key === key) return planCache.value; const byVideo = new Map(); const released = new Set(); const facts = new Map(); const add = (k: string, p: CopyPartner) => { const list = byVideo.get(k); if (list) list.push(p); else byVideo.set(k, [p]); }; for (const g of groups) { const [file, decisions] = await Promise.all([ readCopiesFile(paths.transcriptsDir, g.id), readCopiesDecisions(paths.transcriptsDir, g.id), ]); for (const k of Object.keys(decisions.released)) released.add(k); if (!file) continue; const rank = new Map(g.channels.map((c, i) => [c, i])); for (const pair of file.pairs) { if (pair.withinChannel || pair.a.channel === pair.b.channel) continue; if (decisions.rejected[pair.key]) continue; const confirmedBy = pair.link === "metadata" ? decisions.confirmed[pair.key]?.by : undefined; const link = pair.link === "confirmed" || confirmedBy ? "confirmed" : pair.link === "metadata" ? "metadata" : null; // A part-of or overlapping pair is reported, never acted on. if (!link) continue; const ra = rank.get(pair.a.channel); const rb = rank.get(pair.b.channel); if (ra === undefined || rb === undefined) continue; const common = { group: g.id, pair: pair.key, link, ...(confirmedBy ? { confirmedBy } : {}), firstSeenAt: pair.firstSeenAt, waitDays: g.waitDays, } as const; const ka = copyVideoKey(pair.a.channel, pair.a.dir); const kb = copyVideoKey(pair.b.channel, pair.b.dir); add(ka, { ...common, channel: pair.b.channel, dir: pair.b.dir, rank: rb, selfRank: ra }); add(kb, { ...common, channel: pair.a.channel, dir: pair.a.dir, rank: ra, selfRank: rb }); facts.set(ka, { duration: pair.a.duration, captionsCountAsDone: g.captionsCountAsDone }); facts.set(kb, { duration: pair.b.duration, captionsCountAsDone: g.captionsCountAsDone }); } } const value: LaneCopyPlan = { plan: { byVideo, released }, facts }; planCache = { key, value }; return value; } // Whether the transcription lane would redo a YouTube ASR caption track: the // replace-auto-captions switch, or any rule drawing the auto-captions buckets. export function policyReplacesAutoSubs(policy: Pick | undefined): boolean { if (!policy) return false; if (policy.replaceAutoSubs) return true; const walk = (n: AutoQueueNode): boolean => isGroup(n) ? n.children.some(walk) : n.match?.bucket === "autoSubsOnly" || n.match?.bucket === "downloadedAutoSubsOnly"; return policy.root ? walk(policy.root) : false; } // Words of speech in a cue's text: bracketed non-speech ([Music], (applause)) // and music notes left out. export function speechWords(text: string): number { const cleaned = text.replace(/\[[^\]]*\]|\([^)]*\)|<[^>]*>|[♪♫]/g, " "); let n = 0; for (const t of cleaned.split(/\s+/)) if (/[\p{L}\p{N}]/u.test(t)) n++; return n; } export function minDoneWords(durationSeconds: number): number { const minutes = durationSeconds > 0 ? durationSeconds / 60 : 0; return Math.max(COPY_DONE_MIN_WORDS, Math.ceil(COPY_DONE_WORDS_PER_MINUTE * minutes)); } type DoneRules = { facts: CopyFacts; replaceAutoSubs: boolean; // Backfill only: the operations' targets, fingerprinted. targets?: string; }; // The files that decide a video's done state for the lane, with their sizes // and mtimes: equal signatures, equal answers. async function signatureOf(kind: AutoQueueKind, videoDir: string): Promise<{ sig: string; entries: string[] }> { // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is listed under // its plain name, and stamped by the form that is there. const physical = await io.readdir(videoDir).catch(() => [] as string[]); const entries = logicalEntries(physical).sort(); const decisive = kind === "transcription" ? entries.filter((e) => e === WHISPER_FILENAME || isTranscriptVtt(e)) : entries.filter( (e) => e === WHISPER_FILENAME || isTranscriptVtt(e) || e === DIARIZATION_FILENAME || e === ATTRIBUTION_FILENAME || e === AUDIO_INTEGRITY_FILENAME, ); const stamps = await Promise.all( decisive.map((e) => stampOf(path.join(videoDir, physical.includes(e) || !isStoredTextName(e) ? e : storedNameOf(e))), ), ); // The Speakers states also turn on which other files are there (audio, a // container), so the backfill signature carries the whole listing. return { sig: JSON.stringify([kind === "backfill" ? entries : decisive, stamps]), entries }; } // THE TRANSCRIPTION, DONE: a transcript this lane would not itself redo, with // real words for its length. Our own engine's transcript.json counts; platform // captions only with the group's captionsCountAsDone, and a YouTube ASR track // never while the lane would replace it. async function transcriptDone(videoDir: string, entries: readonly string[], rules: DoneRules): Promise { const min = minDoneWords(rules.facts.duration); if (entries.includes(WHISPER_FILENAME)) { try { const parsed = JSON.parse(await io.readFile(path.join(videoDir, WHISPER_FILENAME))) as { transcription?: { text?: unknown }[]; }; if (Array.isArray(parsed.transcription)) { let words = 0; for (const seg of parsed.transcription) if (typeof seg?.text === "string") words += speechWords(seg.text); if (words >= min) return true; } } catch { // unreadable: not done by this file } } if (!rules.facts.captionsCountAsDone) return false; const vtt = resolvePrimaryVtt(entries); if (!vtt) return false; if (rules.replaceAutoSubs && (await resolveCaptionsProvenance(videoDir, entries)) === "asr") return false; try { let words = 0; const text = io.readCaption ? await io.readCaption(videoDir, vtt) : await io.readFile(path.join(videoDir, vtt)); for (const cue of parseVtt(text)) words += speechWords(cue.text); return words >= min; } catch (err) { // A stored caption that does not decode is not "no transcript" (REVIEW-1 // F3): computeDone answers it. if (isStoredTextReadError(err)) throw err; return false; } } // THE SPEAKERS, DONE: every one of the lane's operations has its output on // the video (state `present`), at least one, none still to do — a video none // of them applies to (no transcript) is not done. async function speakersDone(paths: Paths, settings: SiteSettings, channel: string, dir: string): Promise { const ops = operationsForLane("backfill", settings); if (ops.length === 0) return false; const videoDir = path.join(paths.channelsDir, channel, "data", dir); const files = await readVideoFiles(videoDir, { checkUntranscribable: true }); let present = 0; for (const op of ops) { const target = await op.resolveTarget({ settings, paths, channelSlug: channel }); const state = await op.state({ videoDir, videoId: dir, files, target, settings }); if (state === "present") present++; else if (state !== "not-applicable") return false; } return present > 0; } async function computeDone( kind: AutoQueueKind, paths: Paths, settings: SiteSettings, key: string, rules: DoneRules, entries: readonly string[], ): Promise { const slash = key.indexOf("/"); const channel = key.slice(0, slash); const dir = key.slice(slash + 1); try { if (kind === "transcription") return await transcriptDone(path.join(paths.channelsDir, channel, "data", dir), entries, rules); if (kind === "backfill") return await speakersDone(paths, settings, channel, dir); } catch (err) { // A STORED CAPTION THAT DOES NOT DECODE is an error, never "not done" // (REVIEW-1 F3, captions lane): "not done" would send the lane to // transcribe the video's copy over it. Counted as done (no work made // from it), and said, with the path. if (isStoredTextReadError(err)) { unreadableStoredCaptions += 1; console.warn(`[copies] ${key}: a stored caption cannot be read — ${(err as Error).message}; not counted as work`); return true; } // unreadable: not done } return false; } // Exported for its test ONLY (controller/storedText.unreadable.test.ts). export const __computeDoneForTest = computeDone; /** * Whether each `/` has this lane's work done and readable. A copy * seen before answers from the cache at once; one never seen is read now. */ export async function readCopyDone( kind: AutoQueueKind, paths: Paths, settings: SiteSettings, keys: Iterable, facts: ReadonlyMap, now: number = Date.now(), ): Promise> { const list = [...keys]; const out = new Map(); if (list.length === 0) return out; const replaceAutoSubs = kind === "transcription" && policyReplacesAutoSubs(settings.autoQueue?.transcription); const targetsByChannel = new Map(); const targetsOf = async (channel: string): Promise => { if (kind !== "backfill") return undefined; const hit = targetsByChannel.get(channel); if (hit !== undefined) return hit; const ops = operationsForLane("backfill", settings); const ts = await Promise.all(ops.map(async (op) => [op.id, await op.resolveTarget({ settings, paths, channelSlug: channel })])); const fp = JSON.stringify(ts); targetsByChannel.set(channel, fp); return fp; }; await mapConcurrent(list, DONE_READ_CONCURRENCY, async (k) => { const channel = k.slice(0, k.indexOf("/")); const rules: DoneRules = { facts: facts.get(k) ?? { duration: 0, captionsCountAsDone: false }, replaceAutoSubs, ...(kind === "backfill" ? { targets: await targetsOf(channel) } : {}), }; const cacheKey = JSON.stringify([kind, paths.channelsDir, k, rules]); const videoDir = path.join(paths.channelsDir, channel, "data", k.slice(k.indexOf("/") + 1)); const hit = doneCache.get(cacheKey); if (hit) { out.set(k, hit.done); // In the background, never on this tick: a stat of the deciding files, // and a re-read only when one of them moved. if (!hit.refreshing && now - hit.checkedAt >= revalidateMs) { hit.refreshing = (async () => { try { const { sig, entries } = await signatureOf(kind, videoDir); if (sig !== hit.sig) { hit.done = await computeDone(kind, paths, settings, k, rules, entries); hit.sig = sig; } hit.checkedAt = Date.now(); } catch { // keep the last answer; the next tick tries again } finally { hit.refreshing = null; } })(); } return; } let first = firstReads.get(cacheKey); if (!first) { first = (async () => { const { sig, entries } = await signatureOf(kind, videoDir); const done = await computeDone(kind, paths, settings, k, rules, entries); const entry: DoneEntry = { sig, done, checkedAt: now, refreshing: null }; doneCache.set(cacheKey, entry); return entry; })().finally(() => firstReads.delete(cacheKey)); firstReads.set(cacheKey, first); } out.set(k, (await first).done); }); return out; } /** * The lane's pending lists with its copies skipped or held, or null when this * lane does not act on copies or no group acts (the caller keeps its lists). */ export async function copyHoldsForLane(opts: { kind: AutoQueueKind; paths: Paths; settings: SiteSettings; pending: Record; owner: ReadonlyMap; inFlight: Iterable<{ videoId: string; channelSlug: string }>; now?: number; }): Promise<{ pending: Record; decisions: CopyHoldDecision[] } | null> { if (!laneActsOnCopies(opts.kind)) return null; const loaded = await loadCopyPlan(opts.paths, opts.settings); if (!loaded || loaded.plan.byVideo.size === 0) return null; const { plan, facts } = loaded; const now = opts.now ?? Date.now(); const toRead = copyPartnersToRead(opts.pending, opts.owner, plan); const done = await readCopyDone(opts.kind, opts.paths, opts.settings, toRead, facts, now); const inFlight = new Set(); for (const u of opts.inFlight) inFlight.add(copyVideoKey(u.channelSlug, u.videoId)); return applyCopyHolds({ lane: opts.kind, work: LANE_WORK[opts.kind] ?? "work", pending: opts.pending, owner: opts.owner, plan, inFlight, done, now, }); }