// WHICH PENDING VIDEOS A LANE SKIPS OR HOLDS BECAUSE ANOTHER COPY OF THE SAME // RECORDING HAS (OR WILL GET) THE WORK (lane cross-source-dupes, slice 1). // Pure: the plan, the pending lists, what is in flight and what is done go in; // the trimmed lists and one decision per affected video come out. The runner // tick and the status panel's twin (controller/autoRunner.ts) both call it, // through controller/copiesLane.ts, so the two can never disagree. // // ONLY WHOLE COPIES ACT. The plan holds a group's cross-channel pairs that are // CONFIRMED (by text and runtime, or by a person's copies-confirm) or // METADATA-only (date and runtime, no words on one side). A part-of or // overlapping pair, a rejected one and a pair inside one channel never reach // a lane. THE RULES, per pending video X (not released) and each other copy P: // // CONFIRMED pair: // P's work is done (read off P's own files) → X is SKIPPED. // P is the PREFERRED copy (its channel earlier in the group) and P is in // flight, or queued and not itself held or skipped → X is HELD, until the // group's wait ends at the latest. Otherwise X runs (P gone, paused, never // downloaded, failed … never blocks X). // METADATA-only pair (3 % of them name the wrong copy): // the wait is over (or waitDays is 0) → nothing: X runs, WHATEVER P's // state — a metadata match is never a skip and never an open-ended hold. // Within the wait: P done → X HELD (a person's copies-confirm turns it // into a skip); P preferred and in flight or queued (not held) → X HELD. // // CHAINS RESOLVE. When P is itself held or skipped, X is judged against the // copy P resolved to — the one that actually has or will get the work — with // the weaker of the two links, so X never waits behind a copy that will not // run. A preferred copy whose job ended without the work (failed and retired // by the runner, its channel paused) is neither queued nor in flight, and the // copy held behind it runs on the next tick. // // WORK ALREADY DONE IS NEVER REDONE OR DISCARDED: a done P skips (or, for a // metadata match, holds within the wait) X whichever of the two is preferred. // The order only decides who gets NEW work. // // A skip or hold only takes the video off this lane's pending list. Nothing is // deleted, hidden, un-downloaded or published differently, and no time is // mapped between the copies. import { copyVideoKey } from "./file"; export const COPY_HOLD_HEAD = 20; // Chain resolution settles in as many passes as the longest chain; this caps // a pathological plan. const MAX_PASSES = 8; export type CopyLaneLink = "confirmed" | "metadata"; export type CopyPartner = { group: string; // The pair's key as the scan lists it (`|`). pair: string; // The other copy. channel: string; dir: string; link: CopyLaneLink; // Who confirmed it, when a person's (or an agent's) copies-confirm made a // metadata-only pair confirmed. confirmedBy?: string; // The partner's channel's rank in the group, and this video's (0 = preferred). rank: number; selfRank: number; // ISO-8601: when the scan first saw the pair; the wait runs from here. firstSeenAt: string; waitDays: number; }; export type CopyPlan = { // `/` → its other copies the lanes act on. byVideo: Map; // `/` released by a person: treated as if no group existed. released: Set; }; export type CopyHoldDecision = { channel: string; id: string; action: "skip" | "hold"; group: string; link: CopyLaneLink; // The copy that has or will get the work, `/`. partner: string; partnerRank: number; // When the chain ran through another copy: the direct partner. via?: string; // The direct pair (what copies-confirm and copies-reject name). pair: string; // Why, in the lane's words. reason: string; // A hold ends by itself: when (ISO-8601). until?: string; }; export type CopyHoldSummary = { skipped: number; held: number; // The first COPY_HOLD_HEAD decisions, skips first, in pending order. head: CopyHoldDecision[]; }; export type CopyHoldInput = { lane: string; // What the lane calls its work, for the reasons ("transcript", "speakers"). work: string; pending: Record; // videoId → channel slug (the projection's owner map). owner: ReadonlyMap; plan: CopyPlan; // `/` of every unit in flight on this lane. inFlight: ReadonlySet; // `/` → done (and readable) for this lane. A key absent is not done. done: ReadonlyMap; now: number; }; const DAY_MS = 86_400_000; function waitEnds(p: CopyPartner): number { const t = Date.parse(p.firstSeenAt); return (Number.isFinite(t) ? t : 0) + p.waitDays * DAY_MS; } function opsLine(action: string, body: Record): string { return `pnpm ops ${action} --json '${JSON.stringify(body)}'`; } /** The partners whose done state a decision needs: every partner of a pending video. */ export function copyPartnersToRead( pending: Record, owner: ReadonlyMap, plan: CopyPlan, ): Set { const out = new Set(); if (plan.byVideo.size === 0) return out; for (const ids of Object.values(pending)) { for (const id of ids) { const slug = owner.get(id); if (!slug) continue; const key = copyVideoKey(slug, id); if (plan.released.has(key)) continue; for (const p of plan.byVideo.get(key) ?? []) out.add(copyVideoKey(p.channel, p.dir)); } } return out; } // One partner as a decision sees it: the direct copy, or the copy a decided // direct partner resolved to. type Effective = { key: string; rank: number; link: CopyLaneLink; ends: number; via?: string; p: CopyPartner; }; type Ctx = { input: CopyHoldInput; // Every pending video's key, before any decision. pendingKeys: ReadonlySet; // The previous pass's decisions. prev: ReadonlyMap; }; function effective(key: string, p: CopyPartner, ctx: Ctx): Effective { const pk = copyVideoKey(p.channel, p.dir); const ends = waitEnds(p); const d = ctx.prev.get(pk); if (d && d.partner !== key) { return { key: d.partner, rank: d.partnerRank, link: p.link === "confirmed" && d.link === "confirmed" ? "confirmed" : "metadata", ends, via: pk, p, }; } return { key: pk, rank: p.rank, link: p.link, ends, p }; } function decideOne(key: string, slug: string, id: string, partners: readonly CopyPartner[], ctx: Ctx): CopyHoldDecision | null { const { input, pendingKeys, prev } = ctx; // DONE MEANS DONE ON DISK AND NOT STILL THE LANE'S WORK: a copy this lane // still lists (queued, held or not) or is running is not done, whatever its // files say — so two copies can never each skip the other. const isDone = (k: string) => input.done.get(k) === true && !pendingKeys.has(k) && !input.inFlight.has(k); // WILL RUN: in flight, or queued and not itself held or skipped. const state = (k: string): "in flight" | "queued" | null => input.inFlight.has(k) ? "in flight" : pendingKeys.has(k) && !prev.has(k) ? "queued" : null; let hold: CopyHoldDecision | null = null; for (const raw of partners) { const e = effective(key, raw, ctx); if (e.key === key) continue; const via = e.via ? ` (through ${e.via})` : ""; const base = { channel: slug, id, group: e.p.group, link: e.link, partner: e.key, partnerRank: e.rank, pair: e.p.pair, ...(e.via ? { via: e.via } : {}), }; const confirmHint = opsLine("copies-confirm", { group: e.p.group, pair: e.p.pair }); const releaseHint = opsLine("copies-release", { group: e.p.group, video: key }); if (e.link === "confirmed") { if (isDone(e.key)) { const how = e.p.confirmedBy ? `by the ${e.p.confirmedBy}'s word` : "by its words and runtime"; return { ...base, action: "skip", reason: `a confirmed copy (${how}) of ${e.key}${via}, whose ${input.work} is done — not done twice`, }; } if (hold || e.rank >= raw.selfRank || input.now >= e.ends) continue; const s = state(e.key); if (!s) continue; const until = new Date(e.ends).toISOString(); hold = { ...base, action: "hold", until, reason: `held: waiting for the preferred copy ${e.key}${via} (${s} on this lane), until ${until.slice(0, 10)} ` + `at the latest — release now: ${releaseHint}`, }; continue; } // METADATA ONLY: never past the wait, whatever the other copy's state. if (hold || input.now >= e.ends) continue; const until = new Date(e.ends).toISOString(); if (isDone(e.key)) { hold = { ...base, action: "hold", until, reason: `held until ${until.slice(0, 10)}: probably the same recording as ${e.key}${via} (date and runtime only, ` + `not confirmed by text), whose ${input.work} is done; then released by itself — confirm to skip it: ` + `${confirmHint}; release now: ${releaseHint}`, }; continue; } if (e.rank >= raw.selfRank) continue; const s = state(e.key); if (!s) continue; hold = { ...base, action: "hold", until, reason: `held until ${until.slice(0, 10)}: probably the same recording as the preferred copy ${e.key}${via} ` + `(date and runtime only; ${s} on this lane); then released by itself — confirm: ${confirmHint}; ` + `release now: ${releaseHint}`, }; } return hold; } const sameDecisions = (x: ReadonlyMap, y: ReadonlyMap) => { if (x.size !== y.size) return false; for (const [k, d] of x) { const e = y.get(k); if (!e || e.action !== d.action || e.partner !== d.partner || e.link !== d.link) return false; } return true; }; /** * The lane's pending lists with every skipped and held copy taken out, and a * decision for each. With an empty plan the lists come back untouched (the * same object) and no decision: no group configured is today's lane. */ export function applyCopyHolds(input: CopyHoldInput): { pending: Record; decisions: CopyHoldDecision[]; } { const { plan, owner } = input; if (plan.byVideo.size === 0) return { pending: input.pending, decisions: [] }; const pendingKeys = new Set(); // Pending videos with partners, in pending order. const subjects: { key: string; slug: string; id: string; partners: CopyPartner[] }[] = []; const seen = new Set(); for (const ids of Object.values(input.pending)) { for (const id of ids) { const slug = owner.get(id); if (!slug) continue; const key = copyVideoKey(slug, id); pendingKeys.add(key); if (seen.has(key)) continue; seen.add(key); if (plan.released.has(key)) continue; const partners = plan.byVideo.get(key); if (partners && partners.length > 0) subjects.push({ key, slug, id, partners }); } } let prev = new Map(); for (let pass = 0; pass < MAX_PASSES; pass++) { const ctx: Ctx = { input, pendingKeys, prev }; const next = new Map(); for (const s of subjects) { const d = decideOne(s.key, s.slug, s.id, s.partners, ctx); if (d) next.set(s.key, d); } const settled = sameDecisions(prev, next); prev = next; if (settled) break; } const decisions = subjects.map((s) => prev.get(s.key)).filter((d): d is CopyHoldDecision => !!d); const out: Record = {}; for (const [leaf, ids] of Object.entries(input.pending)) { out[leaf] = ids.filter((id) => { const slug = owner.get(id); return !slug || !prev.has(copyVideoKey(slug, id)); }); } return { pending: out, decisions }; } export function summarizeCopyHolds(decisions: readonly CopyHoldDecision[]): CopyHoldSummary { const skips = decisions.filter((d) => d.action === "skip"); const holds = decisions.filter((d) => d.action === "hold"); return { skipped: skips.length, held: holds.length, head: [...skips, ...holds].slice(0, COPY_HOLD_HEAD) }; }