commit 2e53bd0294066008f078c8f2331e99d2af6141c3 parent 31a948b6357fd72f522b4345b0035de0df569293 Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st> Date: Sun, 25 Oct 2026 01:50:59 -0400 Merge lane/umtool-night: the build preflight never probes what is held on disk and paces the rest per platform (Rumble 120 s; a refusal leaves the rest unchecked); a windowed take keeps only the markers and claim checks inside its window; the play engine marks a painted frame and drafts arrive with their provenance (two e2e flakes); bounded one-entry-per-path memos for umtool's idle heap Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Diffstat:
34 files changed, 888 insertions(+), 135 deletions(-)
diff --git a/common/controller/fetchWindows.ts b/common/controller/fetchWindows.ts @@ -55,6 +55,8 @@ import { configForVideoUrl, } from "../ytdlp/channelArgs"; import { + CLIP_WINDOW_MIN_GAP_SECONDS, + CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS, platformMinGapSeconds, staticSleepRequestsSeconds, } from "../ytdlp/platformArgs.mjs"; @@ -160,19 +162,12 @@ import { findVideoSourceUrl } from "./undownloadedVideos"; // item on a channel whose text is not readable fails as `unreachable` (its // clips/ directory lives in that text), and the rest carry on. -// The least a batch waits between two clip-window fetches on one platform. -// A window is a short request, which is exactly why a loop of them looks like -// a scraper: 20 s apart was enough for YouTube to answer 403 (2026-10-07). -export const CLIP_WINDOW_MIN_GAP_SECONDS = 30; - -// A platform whose windows must be further apart than that. Rumble's -// Cloudflare puts the whole IP behind a JS challenge ("Just a moment…", 403 to -// every rumble.com request, impersonated or not) after a handful of requests -// in a few minutes, and a window costs three (page, embed JSON, HLS manifest): -// on 2026-10-07 windows 30–45 s apart drew it within four, and it lifted again -// in about five minutes of quiet. -export const CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS: Readonly<Record<string, number>> = - Object.freeze({ rumble: 120 }); +// The least a batch waits between two clip-window fetches on one platform, and +// the platforms (Rumble) that must be further apart: the table lives beside +// PLATFORM_MIN_GAP_SECONDS in ytdlp/platformArgs.mjs, where umtool's +// availability probe reads it too. Re-exported for the callers that import it +// from here. +export { CLIP_WINDOW_MIN_GAP_SECONDS, CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS }; // TEST-ONLY: E2E_CLIP_WINDOW_GAP_MS replaces the batch gap above, so the e2e // suite sees the one owed pause without waiting 30–45 s for it diff --git a/common/ytdlp/platformArgs.mjs b/common/ytdlp/platformArgs.mjs @@ -94,6 +94,39 @@ export const PLATFORM_MIN_GAP_SECONDS = Object.freeze({ bitchute: 60, }); +// THE LEAST A RUN WAITS BETWEEN TWO CLIP-WINDOW REQUESTS on one platform, in +// seconds — a clip fetch (common/controller/fetchWindows.ts) and umtool's +// availability probe (report-to-video/check-availability.mjs) alike. A window +// is a short request, which is exactly why a loop of them looks like a +// scraper: 20 s apart was enough for YouTube to answer 403 (2026-10-07). +export const CLIP_WINDOW_MIN_GAP_SECONDS = 30; + +// A platform whose clip-window requests must be further apart than that. +// Rumble's Cloudflare puts the whole IP behind a JS challenge ("Just a +// moment…", 403 to every rumble.com request, impersonated or not) after a +// handful of requests in a few minutes, and a window costs three (page, embed +// JSON, HLS manifest): on 2026-10-07 windows 30–45 s apart drew it within four, +// and it lifted again in about five minutes of quiet. +/** @type {Readonly<Record<string, number>>} */ +export const CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS = Object.freeze({ rumble: 120 }); + +/** + * The floor between two clip-window requests on `platform`, in seconds: the + * larger of CLIP_WINDOW_MIN_GAP_SECONDS, the batch floor and the platform's + * own clip floor. + * @param {string | null | undefined} platform + * @returns {number} + */ +export function clipWindowMinGapSeconds(platform) { + /** @type {Record<string, number | undefined>} */ + const table = CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS; + return Math.max( + CLIP_WINDOW_MIN_GAP_SECONDS, + platformMinGapSeconds(platform), + platform ? table[platform] ?? 0 : 0, + ); +} + // THE FLOOR UNDER THE GAP BETWEEN TWO ONE-OFF IMPORTS on a platform, in // seconds, where it must be higher than the batch floor above. Each import is // its own job, so nothing else spaces them: Odysee's API answered HTTP 429 to diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -2,6 +2,9 @@ ## [Unreleased] - **A Transcribe holds the platform's queue only while it downloads.** The video page's Audio + Whisper and `pnpm ops transcribe-one` used to keep YouTube's (or any platform's) download queue for the whole transcription, so nothing else downloaded on that platform while it waited for a worker and transcribed. Now the audio download runs on the platform's queue and the transcription runs as its own job on the video's queue (`transcribe-one:<slug>:<id>`); with the audio already on disk it starts there at once. The run panel and `pnpm ops … --wait` follow both jobs to the end of the transcription, and the first job's log names the second. `pnpm ops transcribe-one` with `"file"` now runs on the video's own queue unless a download is owed, takes `"queueKey"`, and for a YouTube video whose captions are listed and that has no audio fetches the captions instead (says so, and refuses when the captions are already on disk) unless `"asr": true` is passed. Needs a restart of the editor. +- **umtool's memory no longer creeps up while it sits open.** Its in-memory copies of cue files, track analyses, loudness numbers, media probes, ASR word lists, plans and post archives each keep one copy per file (a changed file replaces its old copy) and a bounded number of files, instead of a new copy beside the old every time a file changed. Needs a restart of umtool. +- **A take of part of a cut (`--at`) no longer refuses to build over the on-screen deck's markers and claim checks.** The take keeps the markers and claims that follow clips inside its window and drops the rest; a goalpost whose steps cross the window's edge keeps the steps inside it. Needs a restart of umtool. +- **umtool's "check every source" step no longer asks for what is already on disk, and no longer bursts a platform.** A source whose clips are all held locally (the build's cache, the editor's window cache, a saved recording) is marked **held locally** and costs no request. The rest are probed one at a time per platform, at least 30 s apart (Rumble 120 s), the same floor the editor's clip fetches keep. When a platform refuses a probe (403, 429, a bot check) umtool stops asking it and marks its remaining sources **not checked**, an info card in the Inbox ("Re-check later"), never "can't be fetched", and it does not stop the build. Needs a restart of umtool. - **A report video can set a subject's own claims against the record on its timeline.** A count claim (`“less than ten” in a year`) draws a band over the dates it is about on the on-screen panel's timeline, dims the rest of the timeline, lights each clip that carries the counter's stamps in date order with its count under it, and counts up to the total under his words in the panel (`19 seizures on camera`). With a **per** (a day, a week, a month) it lights every span that holds that many or more instead (`12 in a day`, `4 in a week`). A goalpost (`“3–5 weeks”` → `“6–8 weeks”`) draws a hollow bracket over the dates each deadline implies; when he moves it, the old one stays dashed and a copy of it moves to the new dates, off the timeline's end with the dates written when they are past its last clip. The finale's large timeline shows every claim at the end. A stamp can be dated by the day the event happened rather than the clip's day (**happened** in the clip editor's Marks). In umtool: the On-screen section's **claim checks** (beside the markers), with **use the playhead** and the build's own checks shown as each field is typed. From a terminal: `umtool look <project> deck.claims='[…]'` and `umtool set <project> <clip> claim.eventDate=2026-09-22`. When the record does not contradict a claim the build prints a note. A video without claims builds exactly as before. Needs a restart of umtool and a rebuild of the video. - **umtool plays a whole report video, or one take of it, in the browser without rendering it, and takes timecoded notes as it plays.** The Cut tab's **Play the cut** (and **Play** beside each take on the takes page) opens `/projects/<project>/play`: every clip plays in order from its fetched window, with the on-screen panel, the tally, the stamps, the markers and the finale drawn over it as the live preview draws them, on one clock across the whole cut, the next clip loaded behind the one playing. A take plays the project's video as it is now with the take's changes, including a take with its own clip list and one a recipe names that was never rendered; **Blurred clips: uncensored** on a take plays its clips as recorded. Under the picture, the **reel strip** shows the whole cut at once: a cell per clip or card as wide as it plays, shaded by the recording's date, hatched when its media is not fetched, the sections' boundaries with their first date, the counter (the tally) drawn as a staircase with its total at the end and at the playhead, and each note as a pin; click or drag on it to move through the cut. Under the strip, **Now** shows what the clip on screen says with the spoken line lit, and which clip comes next. Space plays and pauses, J K L go back, pause and play (L again is faster, at the voice's own pitch), ← and → move 5 seconds, N and P move between clips, [ and ] between notes, and ? lists the keys. A line under the picture lists what it does not do: each crossfade is a hard cut at its middle, cards and teasers are placeholders with their heading, edges are not snapped to silence, and the sound is the recording's. A clip with nothing fetched says "No media for this clip — fetch it" and the video plays on. M (or **Note at 09:44**) saves a note at that second of the cut, naming the clip on screen, its second in the recording, the take, and what it asks for (Trim, Cut, Move, Fact, Look or Other); playback pauses while you write and goes on when it is saved (**Pause while I write**). The notes list in cut order (open, all or resolved), a timecode plays from there, `umtool notes <project>` prints each with where it was taken and what it asks for, and **Send to the assistant** on a note (or **Send N open notes to the assistant**) asks the video assistant, whose reply lands on the note and whose edits wait for **Apply all**. With no assistant configured the button says why. Needs a restart of umtool. - **A download over a copy already saved keeps both, and flags them for a check.** An import, an attach or a live recording that was as long as a later download used to make that download be thrown away, so asking for a 720p copy of a stream already held as a 360p capture (`pnpm ops persist-videos` with `"format": "video_720"`) downloaded it and then discarded it. Now no copy is deleted. **Persist source video**, `persist-videos` and a whole-recording fetch make the download the copy everything uses; any other download keeps the saved copy in use unless it is longer. The other copy stays beside it in the saved-video store as `source-media.alt-<height>p-<date>.<ext>`, which no reader takes for the source, and the log says so: "Kept both copies: the download (720p, 4696.5 s) is now the active source; the landed one (360p, 4696.6 s) stays as source-media.alt-360p-20261023172312.mp4. Flagged for a check." A pinned video stays pinned, and `"replace": "above-height"` keeps the taller copy beside the new one rather than removing it. /saved-videos lists every video with two copies, with both copies' height, length and origin, and counts both in its sizes; `pnpm ops get saved-alternates [<slug>]` lists the same. The keep-latest prune leaves such a video alone. Needs a restart of the editor. diff --git a/umtool/app/api/report/build/route.ts b/umtool/app/api/report/build/route.ts @@ -6,6 +6,7 @@ import { clipsOf, readManifest } from "@/lib/projects/report.mjs"; import { projectRef } from "@/lib/projects"; import { recordBuildSnapshot } from "@/lib/report/snapshots.mjs"; import { renderSeconds } from "@/lib/report/onscreen.mjs"; +import { sourceCountOf } from "umtool-report-to-video/manifest-sources"; import { DEFAULT_VARIANT, VARIANTS, variantPaths } from "umtool-report-to-video/build-video"; import { refuseCaller } from "@/lib/report/caller"; @@ -137,7 +138,9 @@ export async function POST(request: Request) { } // A cut that renders its on-screen chrome is budgeted by its length too (driver.mjs buildTimeoutMs). const seconds = renderSeconds(manifest, options.variant ?? null); - const steps = buildSteps(project, { preset, only, skipFetch, clipCount, seconds, options }); + // The paced preflight is budgeted by how many sources it may probe (driver.mjs availabilityTimeoutMs). + const sources = sourceCountOf(manifest); + const steps = buildSteps(project, { preset, only, skipFetch, clipCount, sources, seconds, options }); const view = { project: project.id, preset, diff --git a/umtool/app/api/report/check-sources/route.ts b/umtool/app/api/report/check-sources/route.ts @@ -2,7 +2,8 @@ import { stat } from "node:fs/promises"; import path from "node:path"; import { runningJob, jobView, startJob } from "@/lib/jobs"; import { projectRef } from "@/lib/projects"; -import { MANIFEST_NAME } from "@/lib/projects/report.mjs"; +import { MANIFEST_NAME, readManifest } from "@/lib/projects/report.mjs"; +import { sourceCountOf } from "umtool-report-to-video/manifest-sources"; import { checkSourcesSteps } from "@/lib/report/driver.mjs"; export const dynamic = "force-dynamic"; @@ -29,7 +30,8 @@ export async function POST(request: Request) { if (!(await stat(path.join(p.dir, MANIFEST_NAME)).then((s) => s.isFile(), () => false))) { return Response.json({ error: `${id} has no ${MANIFEST_NAME} to check` }, { status: 400 }); } - refs.push(p); + // How many sources it cites budgets its paced preflight (driver.mjs availabilityTimeoutMs). + refs.push({ ...p, sources: sourceCountOf(await readManifest(p.dir)) }); } const steps = checkSourcesSteps(refs); diff --git a/umtool/app/api/report/drafts/route.ts b/umtool/app/api/report/drafts/route.ts @@ -2,6 +2,7 @@ import { invalidateProjects } from "@/lib/projects"; import { withEditNotes } from "@/lib/report/guard"; import { StaleToken, StructureRefused, manifestToken, writeDraftedField } from "@/lib/report/manifest.mjs"; import { alternativeById, draftsView } from "@/lib/report/drafts.mjs"; +import { readFieldProvenance } from "@/lib/report/draft-provenance.mjs"; import { currentFieldValue, valueFromEdit } from "@/lib/report/draftEdit.mjs"; import { readManifest } from "@/lib/projects/report.mjs"; import { resolveReport } from "@/lib/report/serve.mjs"; @@ -30,6 +31,11 @@ export const dynamic = "force-dynamic"; // // Verdicts live in <project>/drafts.review.json (report-to-video's // drafts-review.mjs); a final build refuses a drafted field not approved. +// +// Every answer carries `provenance` (lib/report/draft-provenance.mjs) beside +// the rows: a field's draft file, its attempts and the rules they broke. A +// Media tab that re-reads its rows after a draft then has the whole row at +// once, instead of a row now and its provenance after the page refreshes. type Body = Record<string, unknown>; const noStore = { "cache-control": "no-store" }; @@ -38,7 +44,12 @@ export async function GET(request: Request) { const url = new URL(request.url); const r = await resolveReport(url.searchParams.get("project") ?? ""); if ("error" in r) return Response.json({ error: r.error }, { status: r.status }); - return Response.json({ ...(await draftsView(r.project.dir, r.manifest)), token: await manifestToken(r.project.dir) }, { headers: noStore }); + const [view, provenance, token] = await Promise.all([ + draftsView(r.project.dir, r.manifest), + readFieldProvenance(r.project.dir, r.manifest), + manifestToken(r.project.dir), + ]); + return Response.json({ ...view, provenance, token }, { headers: noStore }); } export async function POST(request: Request) { @@ -102,5 +113,6 @@ export async function POST(request: Request) { } const fresh = await resolveReport(String(body.project)); const manifest = "error" in fresh ? r.manifest : fresh.manifest; - return Response.json({ ok: true, ...(await draftsView(dir, manifest)), token: await manifestToken(dir), editNotes }, { headers: noStore }); + const [view, provenance, token] = await Promise.all([draftsView(dir, manifest), readFieldProvenance(dir, manifest), manifestToken(dir)]); + return Response.json({ ok: true, ...view, provenance, token, editNotes }, { headers: noStore }); } diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -95,6 +95,7 @@ import { updateClip, updateStorage } from "../lib/report/manifest.mjs"; import { withEditNotes } from "../lib/report/edit-guard.mjs"; import { hms } from "umtool-report-to-video/attribution"; import { buildSteps, checkSourcesSteps, PRESETS } from "../lib/report/driver.mjs"; +import { sourceCountOf } from "umtool-report-to-video/manifest-sources"; import { runBuildOverHttp, umtoolBase } from "../lib/report/buildRun.mjs"; import { CHAIN_STEP_NAMES, chainStepsOf, planChain } from "../lib/report/chain.mjs"; import { spawn } from "node:child_process"; @@ -677,6 +678,8 @@ async function cmdCheckSources() { }); if (!refs.length) return console.log("every source was checked in the last 30 days"); } + // How many sources each cites budgets its paced preflight (driver.mjs availabilityTimeoutMs). + for (const r of refs) r.sources = sourceCountOf(await readManifest(r.dir)); const steps = checkSourcesSteps(refs); if (json) return out({ projects: refs.map((p) => p.id), steps }); console.log(`# re-check sources of ${refs.length} project(s)`); @@ -1030,6 +1033,7 @@ async function cmdBuild() { only: val("--only") ?? null, skipFetch: has("--skip-fetch"), clipCount, + sources: sourceCountOf(manifest), }); if (json && !has("--run")) return out({ project: p.id, preset, steps }); diff --git a/umtool/components/projects/MediaDrafts.tsx b/umtool/components/projects/MediaDrafts.tsx @@ -17,7 +17,7 @@ import { citationText } from "@/lib/research/facets.mjs"; import type { DraftRowView, DraftRunSummary, ProjectIteration } from "@/lib/articles/projectDraft"; import { awaitingReview } from "@/lib/inbox/drafts.mjs"; import { DraftControl, modelsFor, usePolicy } from "./DraftPanel"; -import { DraftAlternatives, announceDraftsChanged, useDrafts, type DraftAct, type DraftRow, type DraftsView } from "./drafts"; +import { DraftAlternatives, announceDraftsChanged, useDrafts, type DraftAct, type DraftRow, type DraftsView, type FieldProvenance } from "./drafts"; import { announceManifestChanged } from "./timelineApi"; import { BenchBody, VerdictBar } from "./bench/BenchShell"; import CopyCitation from "./bench/CopyCitation"; @@ -38,16 +38,8 @@ import CopyCitation from "./bench/CopyCitation"; // first). Signal is the lit field's Approve draft only. // --------------------------------------------------------------------------- -export type FieldProvenance = { - file: string; - model: string | null; - at: string | null; - attempts: number; - chosen: number | null; - repaired: boolean; - failed: { attempt: number; hard: string[] }[]; - soft: string[]; -}; +// Where a drafted field came from: declared beside the drafts view, which carries it from the route. +export type { FieldProvenance } from "./drafts"; /** The sections, in Draft everything's order: a field's address starts with its section's task. */ export const MEDIA_SECTIONS: { task: string; label: string }[] = [ @@ -416,7 +408,7 @@ export function ApproveAll({ view, act, provenance }: { view: DraftsView; act: D export default function MediaDrafts({ project, initial, - provenance, + provenance: pageProvenance, link, rows, runs: initialRuns, @@ -434,6 +426,8 @@ export default function MediaDrafts({ const router = useRouter(); const drafts = useDrafts(project, initial); const view = drafts.view ?? initial; + // The route's, re-read with the rows; the page's until the first re-read. + const provenance = view.provenance ?? pageProvenance; const linked = link.ok && link.status === "done"; const { policy, error: policyError } = usePolicy(linked); const [runs, setRuns] = useState(initialRuns); @@ -610,7 +604,7 @@ export type FieldEvidence = { export function MediaReview({ project, initial, - provenance, + provenance: pageProvenance, evidence, deckHref, }: { @@ -623,6 +617,7 @@ export function MediaReview({ }) { const drafts = useDrafts(project, initial); const view = drafts.view ?? initial; + const provenance = view.provenance ?? pageProvenance; const [lit, setLit] = useState<string | null>(null); const hydrated = useHydrated(); const row = view.rows.find((r) => r.address === lit) ?? null; diff --git a/umtool/components/projects/drafts.tsx b/umtool/components/projects/drafts.tsx @@ -42,6 +42,18 @@ export type DraftAlternative = { reason: string; inUse: boolean; }; +/** Where a drafted field came from (lib/report/draft-provenance.mjs): its draft file, the attempts, the rules broken. */ +export type FieldProvenance = { + file: string; + model: string | null; + at: string | null; + attempts: number; + chosen: number | null; + repaired: boolean; + failed: { attempt: number; hard: string[] }[]; + soft: string[]; +}; + export type DraftsView = { file: string; exists: boolean; @@ -52,6 +64,12 @@ export type DraftsView = { drafted: number; gate: { errors: string[]; warnings: string[] }; token?: string | null; + /** + * Every drafted field's provenance, by address, as /api/report/drafts reads it beside the rows -- so a row + * re-read after a draft is complete on first paint, with no wait on the page's own refresh. + * Absent on a view the page rendered (the page passes its own). + */ + provenance?: Record<string, FieldProvenance>; }; export const DRAFTS_CHANGED = "umtool:drafts-changed"; diff --git a/umtool/components/projects/report/SourcesTab.tsx b/umtool/components/projects/report/SourcesTab.tsx @@ -111,8 +111,13 @@ export default async function SourcesTab({ project, detail }: ReportTabProps) { </td> <td className="num px-1.5 py-1"> {a ? ( - <span className={a.ok ? "text-[var(--color-dim)]" : "text-[var(--color-bad)]"} title={a.error ?? undefined}> - {a.state} · {days(a.checkedAtMs)} d ago + <span + className={ + a.ok ? "text-[var(--color-dim)]" : a.ok === null ? "text-[var(--color-dirty)]" : "text-[var(--color-bad)]" + } + title={a.error ?? undefined} + > + {a.state === "held-locally" ? "held locally" : a.state === "unchecked" ? "not checked" : a.state} · {days(a.checkedAtMs)} d ago </span> ) : ( <span className="text-[var(--color-dim)]">never checked</span> diff --git a/umtool/components/projects/review/playEngine/engine.ts b/umtool/components/projects/review/playEngine/engine.ts @@ -624,12 +624,15 @@ export class PlayEngine { if (!el) return; const items = this.plan.items; const out: FootageLayer[] = []; + // Which clip's frame each drawn layer is, and its media second: what data-play-drawn says. + const drawn: { i: number; mediaTime: number }[] = []; let missing = false; for (const l of layers) { if (!l.source || !(l.w > 0)) { missing = true; continue; } + drawn.push({ i: l.i, mediaTime: l.source instanceof HTMLVideoElement ? l.source.currentTime : (l.source as VideoFrame).timestamp / 1e6 }); const it = items[l.i]; const e = this.entries.get(it.id); const src = sourceAt(it, t); @@ -648,6 +651,11 @@ export class PlayEngine { el.dataset.playLayers = String(out.length); drawFootageLayers(el, out, this.bg); this.shown = out.length > 0; + // A frame is ON the canvas now: "<itemId>:<media second>" of the current clip's layer (else the first drawn), + // set only after it is painted, so a reader (the e2e) can wait for the picture rather than poll its pixels. + const mine = drawn.find((d) => d.i === this.cur) ?? drawn[0]; + if (mine) el.dataset.playDrawn = `${items[mine.i]?.id}:${mine.mediaTime.toFixed(3)}`; + else delete el.dataset.playDrawn; } private publish() { diff --git a/umtool/docs/inbox.md b/umtool/docs/inbox.md @@ -62,6 +62,7 @@ on (`decisionTab`, `songTabOfSection`). | `manifest-invalid` | blocking | a `localhost`/private `siteOrigin`; a missing one only when a QR the cut draws is built from it (its count and first ids named — lint.mjs `originQrsOf`); missing `channelSlug`, duplicate ids, `section` out of range | Fix the manifest | | `clip-no-cues` | blocking | no `transcript.cues.json` — the build dies there | Fix the cue source | | `clip-unfetchable` | blocking | the last preflight says the source is gone | Replace the source | +| `clip-unchecked` | info | the last preflight could not ask: the platform refused a probe (403, 429, a bot check), so it and the platform's other sources were left `unchecked` | Re-check later | | `clip-mid-sentence` | open | the cut lands inside a cue that does not close a sentence, and `lockEnd` is unset | Trim to the sentence | | `window-overlap` | open/info | two clips from one source overlap | Fix the windows | | `no-punctuation` | info | a source's ASR has no terminators — one row per project | Check the windows | diff --git a/umtool/e2e/play-cut.spec.ts b/umtool/e2e/play-cut.spec.ts @@ -136,14 +136,20 @@ test("a note at the playhead: its kind, the cut second, the clip and its source await expect(page.locator("[data-play-note-add]")).toHaveText("Note at 00:08.0"); // Paused, the clip's frame is in the picture (the fixture's window is dark green), not a black box -- // half of it: c04's first shown second is the middle of its crossfade from c03 (no media: the ground). + // The engine says when c04's frame is painted (data-play-drawn, set after the draw): under load its + // decode can take a while, so the wait is on that, and the pixels are read once it is there. + const footage = page.locator("[data-play-footage]"); + // (A short poll after it only covers a canvas resized between the paint and the read, which clears it + // until the next frame redraws.) + await expect(footage).toHaveAttribute("data-play-drawn", /^c04:/, { timeout: 30_000 }); await expect .poll( () => - page.locator("[data-play-footage]").evaluate((c: HTMLCanvasElement) => { + footage.evaluate((c: HTMLCanvasElement) => { const [r, g, b] = c.getContext("2d")!.getImageData(Math.floor(c.width / 2), Math.floor(c.height / 2), 1, 1).data; return g > 35 && g > r + 20 && g > b + 20; }), - { timeout: 15_000 }, + { timeout: 2_000 }, ) .toBe(true); await page.keyboard.press("m"); diff --git a/umtool/lib/articles/article.ts b/umtool/lib/articles/article.ts @@ -13,6 +13,7 @@ import { readAllPosts } from "yt-dlp-transcript-common/lib/posts-server"; import type { Post } from "yt-dlp-transcript-common/lib/posts"; import { readCues } from "@/lib/projects/report.mjs"; import { CHANNELS_DIR } from "@/lib/paths"; +import { pathCache } from "@/lib/pathCache.mjs"; // A report's PAGE VIEW, built the way the export site builds it // (common/lib/report/views.ts buildReportPageView) but resolved against what @@ -40,7 +41,8 @@ export const recordDir = (channel: string, id: string) => type RecordMeta = { title?: string; date?: string; channelTitle?: string; webpageUrl?: string }; -const metaMemo = new Map<string, { key: string; value: RecordMeta | null }>(); +// One entry per metadata file, a bounded number of them (lib/pathCache.mjs). +const metaMemo = pathCache<RecordMeta | null>({ max: 4096 }); /** What a record says about itself; null when its directory holds neither file. */ export async function recordMeta(channel: string, id: string): Promise<RecordMeta | null> { @@ -56,8 +58,7 @@ export async function recordMeta(channel: string, id: string): Promise<RecordMet const st = await stat(/* turbopackIgnore: true */ file).catch(() => null); if (!st) return null; const key = `${Math.round(st.mtimeMs)}-${st.size}`; - const hit = metaMemo.get(file); - if (hit?.key === key) return hit.value; + if (metaMemo.has(file, key)) return metaMemo.get(file, key) ?? null; let value: RecordMeta | null = null; try { const m = JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); @@ -70,20 +71,22 @@ export async function recordMeta(channel: string, id: string): Promise<RecordMet } catch { value = null; } - metaMemo.set(file, { key, value }); + metaMemo.set(file, key, value); return value; } // A channel's posts, by id. A big X archive is thousands of posts, so one read -// per channel per minute. -const postsMemo = new Map<string, { at: number; value: Promise<Map<string, Post>> }>(); +// per channel per minute -- and at most 8 channels held (lib/pathCache.mjs), +// least recently read out first, so a minute-old archive nobody asks for again +// is not kept for the life of the process. +const postsMemo = pathCache<{ at: number; value: Promise<Map<string, Post>> }>({ max: 8 }); export function channelPosts(channel: string, o: { fresh?: boolean } = {}): Promise<Map<string, Post>> { const hit = postsMemo.get(channel); if (hit && !o.fresh && Date.now() - hit.at < 60_000) return hit.value; const value = readAllPosts(path.join(/* turbopackIgnore: true */ CHANNELS_DIR, channel)) .then((list) => new Map(list.map((p) => [p.id, p]))) .catch(() => new Map<string, Post>()); - postsMemo.set(channel, { at: Date.now(), value }); + postsMemo.set(channel, "", { at: Date.now(), value }); return value; } diff --git a/umtool/lib/browse.ts b/umtool/lib/browse.ts @@ -8,6 +8,7 @@ import { songIdsUnder } from "./projects/song-ids.mjs"; import { REPORTS_ROOT } from "./paths"; import type { CutName } from "./project-types"; import { acceptedFor, readThumbAccepted, type ThumbDoc } from "./thumbs"; +import { fileSig, pathCache } from "./pathCache.mjs"; // --------------------------------------------------------------------------- // The deliverables tree, read as a browsable thing. @@ -415,7 +416,9 @@ export function summarise(s: Song): SongSummary { // else inherits a staleness it did not ask for. // --------------------------------------------------------------------------- -const probes = new Map<string, MediaInfo>(); +// One probe per file (lib/pathCache.mjs): a re-rendered file replaces its old +// answer rather than keeping it beside the new one. +const probes = pathCache<MediaInfo>({ max: 2048 }); export async function probeCached(abs: string): Promise<MediaInfo | null> { let st; @@ -424,12 +427,12 @@ export async function probeCached(abs: string): Promise<MediaInfo | null> { } catch { return null; } - const key = `${abs}|${Math.round(st.mtimeMs)}|${st.size}`; - const hit = probes.get(key); + const sig = fileSig(st); + const hit = probes.get(abs, sig); if (hit) return hit; try { const info = await probeMedia(abs); - probes.set(key, info); + probes.set(abs, sig, info); return info; } catch { return null; diff --git a/umtool/lib/clips.ts b/umtool/lib/clips.ts @@ -9,6 +9,7 @@ import { clipWindow } from "../song/clipwindow.mjs"; import { stripTrailingPop } from "../song/deplosive.mjs"; import { scoreWith } from "../song/orderfeat.mjs"; import { DELIBERATE_CODES } from "../song/reasons.mjs"; +import { pathCache } from "./pathCache.mjs"; export const keyOf = (c: { video: string; start: number }) => `${c.video}@${(+c.start).toFixed(2)}`; @@ -66,7 +67,11 @@ async function loadManifest(): Promise<Map<string, ManifestItem>> { return new Map((m.items ?? []).map((it) => [it.k, it])); } -const asrCache = new Map<string, AsrWord[]>(); +// An episode's ASR words, by video: at most 48 episodes and ~64 MB of words +// (lib/pathCache.mjs), least recently read out first -- a walk over every +// episode (the phrase index, a find across the song) no longer keeps every +// word list for the life of the process. +const asrCache = pathCache<AsrWord[]>({ max: 48, maxBytes: 64 * 1024 * 1024, sizeOf: (w) => w.length * 96 }); export async function wordsFor(video: string): Promise<AsrWord[]> { const hit = asrCache.get(video); @@ -89,7 +94,7 @@ export async function wordsFor(video: string): Promise<AsrWord[]> { */ export function primeWords(video: string, words: AsrWord[]): AsrWord[] { const sorted = words.slice().sort((a, b) => a.start - b.start); - asrCache.set(video, sorted); + asrCache.set(video, "", sorted); return sorted; } diff --git a/umtool/lib/inbox/groups.mjs b/umtool/lib/inbox/groups.mjs @@ -120,6 +120,7 @@ const ACTION_LABEL = { "claim-incoherent": "Rule on the flag", "clip-no-cues": "Fix the cue source", "clip-unfetchable": "Replace the source", + "clip-unchecked": "Re-check later", "clip-mid-sentence": "Trim to the sentence", "clip-cue-gap": "Fix the window", "clip-cut-outside": "Fix the cut", diff --git a/umtool/lib/inbox/what.mjs b/umtool/lib/inbox/what.mjs @@ -25,6 +25,7 @@ export const WHAT = { "claim-incoherent": "claims that don't hold together", "clip-no-cues": "clips with no cues", "clip-unfetchable": "clips can't be fetched", + "clip-unchecked": "sources not checked", "clip-mid-sentence": "clips end mid-sentence", "clip-cue-gap": "clips over a cue gap", "clip-cut-outside": "cuts outside the window", diff --git a/umtool/lib/loudness.ts b/umtool/lib/loudness.ts @@ -4,6 +4,7 @@ import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { CACHE_DIR, labelFor } from "./paths"; import type { Loudness } from "./loudness-types"; +import { pathCache } from "./pathCache.mjs"; export * from "./loudness-types"; @@ -112,7 +113,10 @@ const cacheKey = (abs: string, mtimeMs: number, size: number) => createHash("sha1").update(`${abs}|${Math.round(mtimeMs)}|${size}|loud-v1`).digest("hex").slice(0, 16); const LOUD_CACHE = path.join(CACHE_DIR, "loudness"); -const memo = new Map<string, Loudness>(); +// One measurement per file (lib/pathCache.mjs), its signature the cache key +// (which hashes the file's mtime and size): a re-rendered file replaces its +// old numbers rather than keeping them beside the new ones. +const memo = pathCache<Loudness>({ max: 512 }); async function cacheFileFor(abs: string): Promise<{ key: string; file: string } | null> { let st; @@ -135,11 +139,11 @@ async function cacheFileFor(abs: string): Promise<{ key: string; file: string } export async function cachedLoudness(abs: string): Promise<Loudness | null> { const c = await cacheFileFor(abs); if (!c) return null; - const hit = memo.get(c.key); + const hit = memo.get(abs, c.key); if (hit) return hit; try { const cached = JSON.parse(await readFile(c.file, "utf8")) as Loudness; - memo.set(c.key, cached); + memo.set(abs, c.key, cached); return cached; } catch { return null; @@ -162,7 +166,7 @@ export async function measureLoudness(abs: string): Promise<Loudness> { const tmp = `${c.file}.tmp-${process.pid}`; await writeFile(tmp, JSON.stringify(out)); await rename(tmp, c.file).catch(() => {}); - memo.set(c.key, out); + memo.set(abs, c.key, out); } return out; } diff --git a/umtool/lib/media.ts b/umtool/lib/media.ts @@ -7,6 +7,7 @@ import { existsSync } from "node:fs"; import path from "node:path"; import { MEDIA_ROOT, MEDIA_ROOTS, MEDIA_TIERED, MIX_CACHE, REPORTS_ROOT, SONG_REPORTS, inside, labelFor } from "./paths"; import { brightnessCurve, brightnessSteps } from "../song/flatness.mjs"; +import { fileSig, pathCache } from "./pathCache.mjs"; const run = promisify(execFile); @@ -273,20 +274,26 @@ async function decodeMono(abs: string): Promise<Float32Array> { const cacheKey = (abs: string, mtimeMs: number, size: number) => createHash("sha1").update(`${abs}|${Math.round(mtimeMs)}|${size}|v3`).digest("hex").slice(0, 16); -const memo = new Map<string, Analysis>(); +// In memory: ONE analysis per file (lib/pathCache.mjs), its signature the +// file's mtime and size -- a re-rendered track replaces its old analysis +// rather than keeping it beside the new one -- and at most 64 MB of curves (a +// number is 8 bytes) across 64 tracks. The disk cache below is the long one. +const analysisBytes = (a: Analysis) => 8 * (a.peak.length + a.ratio.length + a.flux.length + 2 * a.steps.length) + 256; +const memo = pathCache<Analysis>({ max: 64, maxBytes: 64 * 1024 * 1024, sizeOf: analysisBytes }); /** Envelope + brightness for a whole track. Cached on disk, keyed by mtime. */ export async function analyseMedia(abs: string): Promise<Analysis> { const st = await stat(abs); const key = cacheKey(abs, st.mtimeMs, st.size); - const hit = memo.get(key); + const sig = fileSig(st); + const hit = memo.get(abs, sig); if (hit) return hit; const file = path.join(MIX_CACHE, `${key}.json`); if (existsSync(file)) { try { const cached = JSON.parse(await readFile(file, "utf8")) as Analysis; - memo.set(key, cached); + memo.set(abs, sig, cached); return cached; } catch { /* rewrite it below */ @@ -357,6 +364,6 @@ export async function analyseMedia(abs: string): Promise<Analysis> { const tmp = `${file}.tmp-${process.pid}`; await writeFile(tmp, JSON.stringify(out)); await rename(tmp, file).catch(() => {}); - memo.set(key, out); + memo.set(abs, sig, out); return out; } diff --git a/umtool/lib/pathCache.mjs b/umtool/lib/pathCache.mjs @@ -0,0 +1,101 @@ +// pathCache — the one shape for a module-level memo of something read from a +// file: ONE entry per key (a path, a video id), bounded by count and by bytes, +// least recently used first out. +// +// Why it exists (umtool's idle heap kept growing): the memos keyed themselves +// by `path|mtime|size`, so every change to a file ADDED an entry beside the +// old one and nothing ever let go -- a corpus that keeps moving (re-synced +// captions, a manifest saved from the bench) left every stale version of +// every cue file parsed in the heap until a restart. Here the key is the path +// and the file's signature (`mtime|size`) is a field of the entry: a new +// signature REPLACES the entry, a read with a stale one is a miss that frees +// it, and the count/byte bounds keep even a walk over the whole corpus from +// holding all of it. +// +// Plain ESM with JSDoc types: node --test, the CLI and the Next server all +// import it. + +/** + * @template V + * @typedef {{ + * get(key: string, sig?: string): V | undefined, + * has(key: string, sig?: string): boolean, + * set(key: string, sig: string, value: V, bytes?: number): V, + * delete(key: string): void, + * clear(): void, + * readonly size: number, + * readonly bytes: number, + * }} PathCache + */ + +/** + * @template V + * @param {{ max?: number, maxBytes?: number, sizeOf?: (value: V) => number }} [opts] + * `max` entries at most (default 256); `maxBytes` of their sizes at most + * (default unbounded) -- each entry's size is the `bytes` given to `set`, + * else `sizeOf(value)`, else 0. The newest entry is kept even when it alone + * is over `maxBytes`: a cache that cannot hold the file it was just asked + * for would read it again on every call. + * @returns {PathCache<V>} + */ +export function pathCache({ max = 256, maxBytes = Infinity, sizeOf } = {}) { + /** @type {Map<string, { sig: string, value: V, bytes: number }>} */ + const entries = new Map(); + let bytes = 0; + /** @param {string} key */ + const drop = (key) => { + const e = entries.get(key); + if (!e) return; + bytes -= e.bytes; + entries.delete(key); + }; + /** @param {string} key @param {string} sig */ + const live = (key, sig) => { + const e = entries.get(key); + if (!e) return undefined; + // A stale signature is the file changed under us: the old value is let go now. + if (e.sig !== sig) { + drop(key); + return undefined; + } + // Most recently used last, so the first key is the one to evict. + entries.delete(key); + entries.set(key, e); + return e; + }; + return { + get(key, sig = "") { + return live(key, sig)?.value; + }, + has(key, sig = "") { + return live(key, sig) !== undefined; + }, + set(key, sig, value, size) { + drop(key); + const n = Number(size ?? (sizeOf ? sizeOf(value) : 0)); + const b = Number.isFinite(n) && n > 0 ? n : 0; + entries.set(key, { sig, value, bytes: b }); + bytes += b; + while (entries.size > max || (bytes > maxBytes && entries.size > 1)) { + const oldest = entries.keys().next().value; + if (oldest === undefined || oldest === key) break; + drop(oldest); + } + return value; + }, + delete: drop, + clear() { + entries.clear(); + bytes = 0; + }, + get size() { + return entries.size; + }, + get bytes() { + return bytes; + }, + }; +} + +/** A file's signature for a pathCache entry: its mtime (ms, rounded) and size. */ +export const fileSig = (/** @type {{ mtimeMs: number, size: number }} */ st) => `${Math.round(st.mtimeMs)}|${st.size}`; diff --git a/umtool/lib/pathCache.test.mjs b/umtool/lib/pathCache.test.mjs @@ -0,0 +1,65 @@ +// lib/pathCache.mjs: one entry per key, a new signature replaces the old, and +// the count and byte bounds evict the least recently used. And the memo it +// was made for: report.mjs readCues keeps ONE parse per cue file however often +// the file changes. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import { mkdtemp, rm, utimes, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +import { fileSig, pathCache } from "./pathCache.mjs"; +import { cueMemoStats, readCues } from "./projects/report.mjs"; + +test("a new signature replaces the entry; a stale read is a miss that frees it", () => { + const c = pathCache(); + c.set("/a.json", "1|10", "first", 10); + assert.equal(c.get("/a.json", "1|10"), "first"); + c.set("/a.json", "2|10", "second", 10); + assert.equal(c.size, 1, "one entry per path, never one per version"); + assert.equal(c.bytes, 10); + assert.equal(c.get("/a.json", "1|10"), undefined); + assert.equal(c.size, 0, "the stale version is let go"); + assert.equal(c.bytes, 0); +}); + +test("bounded by count and by bytes, least recently used out first; the newest is always kept", () => { + const c = pathCache({ max: 3, maxBytes: 100 }); + c.set("a", "", 1, 10); + c.set("b", "", 2, 10); + c.set("c", "", 3, 10); + c.get("a"); // a is now the most recent + c.set("d", "", 4, 10); + assert.deepEqual(["a", "b", "c", "d"].filter((k) => c.has(k)), ["a", "c", "d"], "b, the least recent, went"); + c.set("big", "", 5, 95); + assert.deepEqual(["a", "c", "d", "big"].filter((k) => c.has(k)), ["big"], "evicted down to the byte bound"); + c.set("huge", "", 6, 500); + assert.equal(c.get("huge"), 6, "one entry over the bound alone is still kept"); + assert.equal(c.size, 1); + const s = pathCache({ sizeOf: (v) => v.length }); + s.set("x", "", "abcd"); + assert.equal(s.bytes, 4); +}); + +test("fileSig is mtime (rounded) and size", () => { + assert.equal(fileSig({ mtimeMs: 1234.6, size: 9 }), "1235|9"); +}); + +test("readCues holds one parse per cue file across many changes to it", async () => { + const dir = await mkdtemp(path.join(os.tmpdir(), "cue-memo-")); + try { + const file = path.join(dir, "transcript.cues.json"); + const before = cueMemoStats().size; + for (let i = 0; i < 25; i++) { + await writeFile(file, JSON.stringify({ title: `v${i}`, cues: [{ start: 0, end: 1, text: `line ${i}.` }] })); + await utimes(file, 1_700_000_000 + i, 1_700_000_000 + i); + const doc = await readCues(file); + assert.equal(doc.title, `v${i}`, "the current version, never a stale one"); + } + assert.equal(cueMemoStats().size - before, 1, "25 versions of one file: one entry"); + } finally { + await rm(dir, { recursive: true, force: true }); + } +}); diff --git a/umtool/lib/projects/report.mjs b/umtool/lib/projects/report.mjs @@ -38,6 +38,7 @@ const segmentDirs = (outDir) => [ ]; import { adjudicationGaps, ledgerTotals, unadjudicatedOf } from "umtool-report-to-video/ledger-totals"; import { widen } from "umtool-report-to-video/resolve-windows"; +import { fileSig, pathCache } from "../pathCache.mjs"; // widen() and the cache's window naming are IMPORTED, never reimplemented. The // bench's "extend to sentence end" has to be the same function the CLI runs, or @@ -503,15 +504,16 @@ export const clipWindowDirs = async ( return out; }; -// The container's own answer, for a record whose cues carry no duration. -const containerMemo = new Map(); +// The container's own answer, for a record whose cues carry no duration. One +// entry per file (lib/pathCache.mjs): a changed file replaces its answer. +const containerMemo = pathCache({ max: 1024 }); async function probeContainerMemo(file) { const st = await stat0(file); if (!st) return null; - const key = `${file}|${Math.round(st.mtimeMs)}|${st.size}`; - if (containerMemo.has(key)) return containerMemo.get(key); + const sig = fileSig(st); + if (containerMemo.has(file, sig)) return containerMemo.get(file, sig); const info = await ffprobeSource(file); - containerMemo.set(key, info); + containerMemo.set(file, sig, info); return info; } @@ -526,16 +528,28 @@ export const cuePathFor = (m, e, channelsDir) => { // Cue files are the expensive input: a nine-hour stream's cues run to megabytes, // and six reports citing thirteen videos each would be a hundred-odd megabytes of // JSON on every index load. So the DERIVED answers are memoised against the -// file's own mtime and size -- a cue file is an archive artefact and does not -// change under us, so a hit is permanent in practice. +// file's own mtime and size -- a cue file is an archive artefact and rarely +// changes under us, so a hit is nearly permanent. +// +// ONE ENTRY PER FILE, and a bounded number of them (lib/pathCache.mjs): the +// memo used to key by path+mtime, so every re-synced cue file kept its old +// parse beside the new one for the life of the process -- the idle heap +// growing with nothing open. Now a changed file replaces its entry, and the +// least recently read go first past CUE_MEMO_BYTES of cue files (the parsed +// cues run a few times their file's bytes). // --------------------------------------------------------------------------- -const cueMemo = new Map(); +export const CUE_MEMO_MAX = 512; +export const CUE_MEMO_BYTES = 32 * 1024 * 1024; +const cueMemo = pathCache({ max: CUE_MEMO_MAX, maxBytes: CUE_MEMO_BYTES }); + +/** How many cue files the memo holds, and their bytes on disk (for the tests and a heap check). */ +export const cueMemoStats = () => ({ size: cueMemo.size, bytes: cueMemo.bytes }); export async function readCues(file) { const st = await stat0(file); if (!st) return null; - const key = `${file}|${Math.round(st.mtimeMs)}|${st.size}`; - const hit = cueMemo.get(key); + const sig = fileSig(st); + const hit = cueMemo.get(file, sig); if (hit) return hit; let doc; try { @@ -563,7 +577,7 @@ export async function readCues(file) { ? 0 : cues.filter((c) => ENDS_SENTENCE.test(c.text ?? "")).length / cues.length, }; - cueMemo.set(key, value); + cueMemo.set(file, sig, value, st.size); return value; } @@ -710,7 +724,7 @@ const fmtDur = (s) => { * key: string, channel: string|null, video: string, clips: string[], * cues: "present"|"missing"|"no-punctuation", cueFile: string|null, * cuesEnd: number|null, latestClipEnd: number, coverageGap: null | { clip: string, needs: number, cuesEnd: number }, - * availability: null | { state: string, ok: boolean, checkedAtMs: number, title: string|null, url: string|null, error: string|null }, + * availability: null | { state: string, ok: boolean | null, checkedAtMs: number, title: string|null, url: string|null, error: string|null }, * cite: { derived: string, override: string|null, differs: boolean }, * title: string|null, * }>, checkedAtMs: number|null, channelsDir: string }>} @@ -765,7 +779,8 @@ export async function sourcesOf(dir, { manifest = null } = {}) { availability: a ? { state: a.state ?? (a.ok ? "ok" : "unknown"), - ok: !!a.ok, + // null: not checked (the platform refused the probe) -- no verdict. + ok: a.ok === null ? null : !!a.ok, checkedAtMs: Date.parse(a.checkedAt ?? "") || avail.checkedAtMs, title: a.title ?? null, url: a.url ?? null, @@ -805,7 +820,7 @@ export async function summariseReport(ctx) { // the record is cached in the index against the signature -- so the first // load of a project pays for its cue files once, and no page does again. const src = m ? await sourcesOf(dir, { manifest: m }) : { rows: [], checkedAtMs: null }; - const sourcesDead = src.rows.filter((r) => r.availability && !r.availability.ok && r.availability.state !== "no-cues").length; + const sourcesDead = src.rows.filter((r) => r.availability && r.availability.ok === false && r.availability.state !== "no-cues").length; const sourcesMissing = src.rows.filter((r) => r.cues === "missing").length; const cueGaps = src.rows.filter((r) => r.coverageGap).length; // The codes a missing or dead origin would break (deadOriginQrsOf): the @@ -905,6 +920,11 @@ export const REPORT_DECISION_KINDS = [ "manifest-invalid", "clip-no-cues", "clip-unfetchable", + // The preflight could not ask: the platform refused a probe (403, 429, a bot + // check) and the rest of its sources were left unprobed rather than burst. + // `info`: no verdict about the source, and the build's own fetches go + // through the editor's paced queue. + "clip-unchecked", "clip-mid-sentence", "window-overlap", "no-punctuation", @@ -1041,7 +1061,17 @@ export async function reportDecisions(ctx, summary) { ); if (avail) { for (const src of avail.sources ?? []) { + // `ok` and `held-locally` (every clip is on disk: never probed) are fine. if (src.ok) continue; + if (src.ok === null || src.state === "unchecked") { + add( + "clip-unchecked", + src.key, + `not checked — ${src.error ?? "the platform refused the probe"}. Re-check later; nothing says it is gone`, + "info", + ); + continue; + } // SEVERITY FOLLOWS THE CLIPS, not the source. // // The probe covers ledger sources as well as clip sources now, and most diff --git a/umtool/lib/provenance.ts b/umtool/lib/provenance.ts @@ -4,6 +4,7 @@ import { songDir } from "./browse"; import { readState, readJson, type SongState } from "./state"; import { stateFile } from "./paths"; import { archiveMomentUrl } from "./archive"; +import { fileSig, pathCache } from "./pathCache.mjs"; // --------------------------------------------------------------------------- // Where every note in a finished cut came from. @@ -81,7 +82,9 @@ const clipIdOf = (video: string, srcStart: number) => `${video}@${srcStart.toFix // writer and a cached pile would show judgements that have since moved. // --------------------------------------------------------------------------- -const parsed = new Map<string, ProvRow[]>(); +// One parse per plan (lib/pathCache.mjs): a re-rendered plan replaces its old +// rows instead of keeping them beside the new ones, and at most 16 plans. +const parsed = pathCache<ProvRow[]>({ max: 16 }); async function memo(abs: string, parse: (text: string) => ProvRow[]): Promise<ProvRow[]> { let st; @@ -90,8 +93,8 @@ async function memo(abs: string, parse: (text: string) => ProvRow[]): Promise<Pr } catch { return []; } - const key = `${abs}|${Math.round(st.mtimeMs)}|${st.size}`; - const hit = parsed.get(key); + const sig = fileSig(st); + const hit = parsed.get(abs, sig); if (hit) return hit; let rows: ProvRow[] = []; try { @@ -100,7 +103,7 @@ async function memo(abs: string, parse: (text: string) => ProvRow[]): Promise<Pr rows = []; } rows.sort((a, b) => a.songTime - b.songTime); - parsed.set(key, rows); + parsed.set(abs, sig, rows); return rows; } diff --git a/umtool/lib/report/driver.mjs b/umtool/lib/report/driver.mjs @@ -11,6 +11,10 @@ import { existsSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { + CLIP_WINDOW_MIN_GAP_SECONDS, + CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS, +} from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; /** * This package's own root (umtool/): bin/ lives here, and so does @@ -111,24 +115,46 @@ export const buildTimeoutMs = (clipCount, xfade, seconds = 0) => * @typedef {{ variant?: string, xfade?: boolean, chaptersOnly?: boolean, chromeOnly?: boolean, preview?: { at: number, dur: number } | null, narrate?: boolean, podcast?: boolean }} BuildOptions */ -/** The step-1 preflight alone, reused by the check-sources job. */ -export function availabilityStep(project, env = {}) { +/** + * The preflight's timeout, for a manifest citing `sources` sources + * (report-to-video/manifest-sources.mjs sourceCountOf). The preflight paces + * its probes per platform (check-availability.mjs): up to the widest + * clip-window gap (Rumble's 120 s) plus half again between two, so a manifest + * whose sources are all on one slow platform takes n gaps. Budgeted for that + * worst case, plus a minute per probe; never under ten minutes. A source held + * on disk costs no probe, so this is a ceiling, not an estimate. + */ +export const PROBE_BUDGET_MS = 60_000; +export function availabilityTimeoutMs(sources = 0) { + const widestGapMs = Math.max(CLIP_WINDOW_MIN_GAP_SECONDS, ...Object.values(CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS)) * 1500; + const n = Number.isFinite(sources) && sources > 0 ? sources : 0; + return Math.max(10 * 60_000, Math.round(n * (widestGapMs + PROBE_BUDGET_MS))); +} + +/** + * The step-1 preflight alone, reused by the check-sources job. `sources` is + * how many sources the manifest cites (sourceCountOf), for the timeout; a + * project ref may carry it as `project.sources`. + */ +export function availabilityStep(project, env = {}, { sources = project.sources ?? 0 } = {}) { const manifest = path.join(project.dir, "video.manifest.json"); return { cwd: PIPELINE_DIR, env, label: `check every source of ${project.id} is still fetchable`, argv: ["node", script("check-availability.mjs"), manifest, "--out", path.join(project.dir, "out"), "--allow-missing"], - timeoutMs: 10 * 60_000, + timeoutMs: availabilityTimeoutMs(sources), }; } /** + * `sources` is how many sources the manifest cites (sourceCountOf), which + * budgets the paced preflight; absent, the clip count stands in for it. * @param {{ id: string, dir: string }} project - * @param {{ preset?: string, only?: string | null, skipFetch?: boolean, env?: Record<string,string>, clipCount?: number, seconds?: number, options?: BuildOptions }} [opts] + * @param {{ preset?: string, only?: string | null, skipFetch?: boolean, env?: Record<string,string>, clipCount?: number, sources?: number, seconds?: number, options?: BuildOptions }} [opts] * @returns {import("../trim").Step[]} */ -export function buildSteps(project, { preset = "fast", only = null, skipFetch = false, env = {}, clipCount = 20, seconds = 0, options = {} } = {}) { +export function buildSteps(project, { preset = "fast", only = null, skipFetch = false, env = {}, clipCount = 20, sources = clipCount, seconds = 0, options = {} } = {}) { const p = PRESETS[preset] ?? PRESETS.fast; const manifest = path.join(project.dir, "video.manifest.json"); const outDir = path.join(project.dir, "out"); @@ -149,7 +175,7 @@ export function buildSteps(project, { preset = "fast", only = null, skipFetch = ...base, label: "check every source is still fetchable", argv: ["node", script("check-availability.mjs"), manifest, "--out", outDir], - timeoutMs: 10 * 60_000, + timeoutMs: availabilityTimeoutMs(sources), }, { ...base, diff --git a/umtool/lib/report/driver.test.mjs b/umtool/lib/report/driver.test.mjs @@ -113,3 +113,15 @@ test("the pipeline is found from the module, whatever the cwd", async () => { rmSync(elsewhere, { recursive: true, force: true }); } }); + +test("the preflight's timeout allows for its pacing: n sources, n of the widest gap", async () => { + const { availabilityTimeoutMs, availabilityStep } = await import("./driver.mjs"); + assert.equal(availabilityTimeoutMs(0), 10 * 60_000); + assert.equal(availabilityTimeoutMs(2), 10 * 60_000, "a few sources keep the ten-minute floor"); + // 40 Rumble sources: 40 × (120 s × 1.5 + a minute) = 160 min. + assert.equal(availabilityTimeoutMs(40), 40 * (180_000 + 60_000)); + const pre = buildSteps(project, { preset: "fast", clipCount: 3, sources: 40 })[0]; + assert.match(pre.label, /check every source/); + assert.equal(pre.timeoutMs, availabilityTimeoutMs(40)); + assert.equal(availabilityStep({ ...project, sources: 40 }).timeoutMs, availabilityTimeoutMs(40)); +}); diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -286,14 +286,41 @@ export function windowEntries(timeline, win, schedule = null) { /** * The manifest a window renders: `manifest` with only `ids` in its timeline - * (the sourced ones), and the posts attached to a clip outside it dropped -- - * a post's `attachTo` must name a clip of the timeline. + * (the sourced ones), and everything that names a clip outside it dropped -- + * the build refuses a reference to a clip its timeline does not hold: + * + * - a post whose `attachTo` is outside; + * - a deck marker (`render.chrome.deck.markers`) whose `after` is outside; + * - a deck claim check (`render.chrome.deck.claims`): a count claim whose + * `at` is outside. A goalpost whose steps STRADDLE the window's edge is + * CLIPPED to the steps inside it -- the window keeps a straddling clip + * (windowEntries), so it keeps the part of the claim that clip carries; + * a goalpost with no step inside is dropped. + * + * The kept ones need no re-timing: each names a clip by id, and its `t` is a + * source second of that clip, which the window renders whole. */ export function windowManifest(manifest, ids) { const keep = new Set(ids); const m = clone(manifest); m.timeline = sourcedEntries(m.timeline).filter((e) => keep.has(e.id)); if (Array.isArray(m.posts)) m.posts = m.posts.filter((p) => !p?.attachTo || keep.has(p.attachTo)); + const deck = m.render?.chrome?.deck; + if (isObj(deck)) { + const inside = (id) => typeof id === "string" && keep.has(id.trim()); + if (Array.isArray(deck.markers)) deck.markers = deck.markers.filter((mk) => !isObj(mk) || inside(mk.after)); + if (Array.isArray(deck.claims)) { + deck.claims = deck.claims.flatMap((c) => { + if (!isObj(c)) return [c]; + if (c.kind === "goalpost" && Array.isArray(c.steps)) { + const steps = c.steps.filter((st) => !isObj(st) || inside(st.at)); + return steps.length ? [{ ...c, steps }] : []; + } + if (c.at !== undefined) return inside(c.at) ? [c] : []; + return [c]; + }); + } + } return m; } diff --git a/umtool/lib/report/takeMaker.test.mjs b/umtool/lib/report/takeMaker.test.mjs @@ -26,8 +26,10 @@ import { takeSteps, uniqueTakeId, windowEntries, + windowManifest, } from "./takeMaker.mjs"; import { listTakes, readVerdicts, setTakeVerdict } from "./takes.mjs"; +import { validateDeckClaims, validateDeckMarkers } from "umtool-report-to-video/deck"; import { PROJECT_KINDS } from "../projects/kinds.mjs"; // The kind takes are made of, from the registry (never its id spelled here). @@ -490,3 +492,49 @@ test("takeSteps: each button is one job running the CLI, checked before it start assert.equal(lastGroup([{ group: "a", builtAt: "2026-01-01" }, { group: "b", builtAt: "2026-02-01" }]), "b"); assert.equal(lastGroup([]), "takes"); }); + +test("windowManifest: markers and claim checks outside the window are dropped; a goalpost straddling its edge is clipped", () => { + const manifest = { + ...MANIFEST, + render: { + ...MANIFEST.render, + chrome: { + engine: "hyperframes", + layout: "deck", + deck: { + markers: [ + { after: "s02", label: "inside" }, + { after: "s04", label: "outside" }, + ], + claims: [ + { kind: "count", at: "s01", t: 2, said: "“in”", window: { from: "2026-01-01", to: "2026-12-31" }, tally: "CONTRADICTED" }, + { kind: "count", at: "s04", t: 1, said: "“out”", window: { from: "2026-01-01", to: "2026-12-31" }, tally: "CONTRADICTED" }, + { + kind: "goalpost", label: "straddles", + steps: [{ at: "s02", t: 21, said: "“3 weeks”", due: ["P3W", "P5W"] }, { at: "s04", t: 2, said: "“6 weeks”", due: ["P6W", "P8W"] }], + }, + { kind: "goalpost", label: "all outside", steps: [{ at: "s04", t: 2, said: "“6 weeks”", due: ["P6W", "P8W"] }] }, + ], + }, + }, + }, + }; + const before = JSON.stringify(manifest); + const m = windowManifest(manifest, ["s01", "s02"]); + assert.deepEqual(m.timeline.map((e) => e.id), ["s01", "s02"]); + assert.deepEqual(m.render.chrome.deck.markers.map((x) => x.label), ["inside"]); + assert.deepEqual(m.render.chrome.deck.claims.map((c) => c.label ?? c.said), ["“in”", "straddles"]); + // Clipped to the step inside the window, its seconds as written (the clip renders whole). + assert.deepEqual(m.render.chrome.deck.claims[1].steps, [{ at: "s02", t: 21, said: "“3 weeks”", due: ["P3W", "P5W"] }]); + assert.equal(JSON.stringify(manifest), before, "the project's manifest is not touched"); + // What the build refuses with: the whole manifest windowed as-was names clips it does not hold. + const naive = { ...manifest, timeline: m.timeline }; + assert.ok(validateDeckMarkers(naive).length + validateDeckClaims(naive).length > 0); + assert.deepEqual(validateDeckMarkers(m), []); + assert.deepEqual(validateDeckClaims(m), []); + // The full window keeps every one. + const all = windowManifest(manifest, ["s01", "s02", "s03", "k1", "s04"]); + assert.equal(all.render.chrome.deck.markers.length, 2); + assert.equal(all.render.chrome.deck.claims.length, 4); + assert.equal(all.render.chrome.deck.claims[2].steps.length, 2); +}); diff --git a/umtool/playwright.config.ts b/umtool/playwright.config.ts @@ -30,10 +30,20 @@ import { portFor } from "yt-dlp-transcript-common/lib/ports.mjs"; // E2E_UMTOOL_CLIP_RENDER_SCRIPT set below on the app server: Render this // clip's renderer (the live preview; // lib/report/clipRender.mjs), stubbed +// E2E_AVAILABILITY_GAP_MS set below for the whole run (the app server and +// the CLIs specs spawn): the gap between two +// availability probes on one platform +// (report-to-video/check-availability.mjs), in +// place of the real 30–180 s, against the stub yt-dlp // The ports are common/lib/ports.mjs's (offset per worktree by // scripts/worktree.mjs), not test-only, and keep their names. const PORT = portFor("UMTOOL_E2E_PORT"); +// The preflight's per-platform pacing, against the fixture's stub yt-dlp: 50 ms, +// not the 30 s a real YouTube probe waits. On process.env, so the app server +// and every worker (and the CLIs they spawn) inherit it. +process.env.E2E_AVAILABILITY_GAP_MS ??= "50"; + // START MODE BY DEFAULT, as the editor suite (plans/e2e-speed.md, S1): `next // dev` compiles each route on first use and again after a change, and the // suite was 26.5 min under it in release 19's gate. The build is its OWN diff --git a/umtool/report-to-video/check-availability.mjs b/umtool/report-to-video/check-availability.mjs @@ -11,6 +11,22 @@ // resolves formats without downloading a byte: a few seconds for a whole // manifest against twenty-odd minutes for the build it protects. // +// WHAT IS ON DISK IS NEVER ASKED OF THE NETWORK. A source every one of whose +// clips the build can cut from a file already held -- the build's raw cache, +// the editor's window cache, a saved recording; build-video.mjs fetchSpan and +// planLocalSources, the build's own answer -- is `held-locally` (ok) and costs +// no request. Only what the build would have to fetch is probed. +// +// AND WHAT IS PROBED IS PACED, per platform, exactly as the editor paces a +// clip-window fetch: at least clipWindowMinGapSeconds(platform) between two +// probes on one platform (30 s; Rumble 120 s -- common/ytdlp/platformArgs.mjs), +// plus up to half again at random. Probes on different platforms interleave. +// A probe that draws a refusal (HTTP 403 / 429, Cloudflare's "Just a moment", +// YouTube's bot check) STOPS probing that platform: that source and the rest +// of the platform's are `unchecked` (ok: null) -- not a verdict about the +// source, and not a reason to refuse the build, whose fetches go through the +// editor's own paced queue. +// // On the CLI: // node umtool/report-to-video/check-availability.mjs <manifest.json> [--json] // @@ -22,7 +38,7 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; -import { readFile, writeFile } from "node:fs/promises"; +import { readFile, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { DEFAULT_CHANNELS_DIR } from "./cues.mjs"; @@ -30,7 +46,16 @@ import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mj import { ensureWriteDir } from "../lib/report/storage.mjs"; // The per-platform yt-dlp args (Rumble's `--impersonate chrome`): the ONE table, // in common, plain JS so bare `node` can load it. -import { platformArgsForUrl } from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; +import { + clipWindowMinGapSeconds, + platformArgsForUrl, +} from "yt-dlp-transcript-common/ytdlp/platformArgs.mjs"; +import { detectPlatform } from "yt-dlp-transcript-common/lib/detectPlatform.mjs"; +import { fetchSpan, localSources } from "./build-video.mjs"; +import { SHADOW_CHANNELS, audioUse, channelsDirFor } from "./sources.mjs"; +import { manifestSources } from "./manifest-sources.mjs"; + +export { manifestSources }; const execFileP = promisify(execFile); @@ -44,8 +69,19 @@ const CHANNELS_DIR = DEFAULT_CHANNELS_DIR; // blip needs a retry. Anything unrecognised stays `maybe_missing` rather than // being called deleted -- claiming a source is gone when it is not is the more // expensive mistake, because it invites deleting a citation. -function classify(stderr) { +// A REFUSAL is about us, not the source: the platform turned the probe away +// (rate limit, Cloudflare's JS challenge, YouTube's bot check). Asked first, +// because "Sign in to confirm you're not a bot" would otherwise read as an +// age restriction below. +export function isRefusal(stderr) { + return /HTTP Error 403|HTTP Error 429|Too Many Requests|Just a moment|cf-challenge|Cloudflare|not a bot|rate.?limit/i.test( + String(stderr ?? ""), + ); +} + +export function classify(stderr) { const t = String(stderr ?? ""); + if (isRefusal(t)) return "unchecked"; if (/Private video|private/i.test(t)) return "private"; if (/removed by the uploader|has been removed|no longer available|Video unavailable|does not exist|410/i.test(t)) return "deleted"; @@ -73,36 +109,71 @@ export async function cueMeta(videoId, channelSlug) { return { title: d.title, webpageUrl: d.webpageUrl, duration: d.duration }; } -export async function checkAvailability(manifestPath, { outDir, maxAgeDays = 0 } = {}) { +/** A source's verdict, as the inbox, the CLI and the build read it: true, false, or null (not checked). */ +const verdictOf = (state) => (state === "ok" || state === "held-locally" ? true : state === "unchecked" ? null : false); + +/** + * Can the build cut every clip of this source from disk? The build's own + * question (fetchSpan + the local tiers), asked with the network on: a clip + * that plays from its sound because it has no picture to fetch counts, a + * picture that would be fetched does not. A source with no clips (ledger only) + * has nothing on disk to answer for it. + */ +async function heldLocally(w, render, local) { + if (!w.entries.length) return false; + for (const entry of w.entries) { + const span = fetchSpan(entry, render, {}); + const audio = audioUse({ entry, render, network: true }) !== null; + if (!(await local.resolve(entry, span, { audio }))) return false; + } + return true; +} + +const realSleep = (ms) => new Promise((r) => setTimeout(r, ms)); + +// TEST-ONLY: E2E_AVAILABILITY_GAP_MS replaces the gap between two probes on a +// platform, so the e2e suite (a stub yt-dlp) does not wait 30 s per source. +// Unset everywhere but the e2e run (umtool/playwright.config.ts). +function testGapMs() { + const raw = Number(process.env.E2E_AVAILABILITY_GAP_MS); + return Number.isFinite(raw) && raw > 0 ? raw : undefined; +} + +/** + * @param {string} manifestPath + * @param {{ outDir?: string, maxAgeDays?: number, channelsDir?: string, + * ytdlp?: string, now?: () => number, sleep?: (ms: number) => Promise<void>, + * random?: () => number, log?: (m: string) => void }} [opts] + * `now`, `sleep` and `random` are the clock the pacing runs on (tests pass a + * fake one); `channelsDir` is where held media is looked for (default: the + * tree the build reads, sources.mjs channelsDirFor). + */ +export async function checkAvailability(manifestPath, { + outDir, maxAgeDays = 0, channelsDir = null, ytdlp = YTDLP, + now = Date.now, sleep = realSleep, random = Math.random, log = () => {}, +} = {}) { const manifest = JSON.parse(await readFile(manifestPath, "utf8")); - const slug = manifest.provenance?.channelSlug; - const dir = outDir ?? path.join(path.dirname(path.resolve(manifestPath)), "out"); + const manifestDir = path.dirname(path.resolve(manifestPath)); + const dir = outDir ?? path.join(manifestDir, "out"); const file = path.join(dir, "availability.json"); + const iso = () => new Date(now()).toISOString(); // A clip may name its own channel: the same streamer's VODs are mirrored // across more than one archive, and the same id under a different slug is a // different file. So the unit of work is (channel, video), never video alone. - const wanted = new Map(); - const want = (channel, video) => { - const key = `${channel}/${video}`; - if (!wanted.has(key)) wanted.set(key, { key, channel, video, clips: [], claims: [] }); - return wanted.get(key); - }; - for (const e of manifest.timeline ?? []) { - // A clip with its own `src` is a file beside the manifest, on no platform: - // the build checks it is there. - if (e.type !== "clip" || e.src != null) continue; - want(e.channel ?? slug, e.video).clips.push(e.id); - } - // LEDGER SOURCES TOO, not just the clipped ones. A cut that stacks its - // unclipped claims onto cards has to say WHY each one is a line of text - // rather than footage, and "the upload is gone" and "we did not cut it" are - // different sentences. Guessing which is which is how a live source ends up - // labelled deleted on screen. - for (const c of manifest.ledger ?? []) { - if (!c.video) continue; - want(c.channel ?? slug, c.video).claims.push(c.id); - } + const wanted = manifestSources(manifest); + + // Where the build would find media on disk: the same raw cache and channels + // tree build-video.mjs reads (variantPaths' clips-raw, channelsDirFor). + const local = localSources({ + rawDir: path.join(dir, "clips-raw"), + channelsDir: channelsDir ?? channelsDirFor(manifestDir, manifest, { + shadowExists: await stat(path.join(manifestDir, SHADOW_CHANNELS)).then((st) => st.isDirectory(), () => false), + fallback: CHANNELS_DIR, + }), + channelSlug: manifest.provenance?.channelSlug ?? null, + }); + const render = manifest.render ?? {}; const prev = await readFile(file, "utf8").then( (s) => JSON.parse(s), @@ -111,11 +182,16 @@ export async function checkAvailability(manifestPath, { outDir, maxAgeDays = 0 } const prevBy = new Map((prev.sources ?? []).map((s) => [s.key, s])); const freshMs = maxAgeDays * 86400_000; - const sources = []; - for (const w of wanted.values()) { + // Each source's row, in manifest order; the probes are filled in below. + const rows = new Array(wanted.length); + const probes = []; + const strip = ({ entries: _entries, ...w }) => w; + for (const [i, wFull] of wanted.entries()) { + const w = strip(wFull); const was = prevBy.get(w.key); - if (freshMs > 0 && was?.checkedAt && Date.now() - Date.parse(was.checkedAt) < freshMs) { - sources.push({ ...was, clips: w.clips, claims: w.claims, reused: true }); + // An `unchecked` row is not a verdict, so it is never reused. + if (freshMs > 0 && was?.checkedAt && was.state !== "unchecked" && now() - Date.parse(was.checkedAt) < freshMs) { + rows[i] = { ...was, clips: w.clips, claims: w.claims, reused: true }; continue; } @@ -127,33 +203,69 @@ export async function checkAvailability(manifestPath, { outDir, maxAgeDays = 0 } // the Rumble two-ids trap produces: the manifest names the MCP video id // while the cues live under the URL slug. Build would die here too, so it // is reported here rather than discovered twenty minutes in. - sources.push({ - ...w, ok: false, state: "no-cues", checkedAt: new Date().toISOString(), + rows[i] = { + ...w, ok: false, state: "no-cues", checkedAt: iso(), error: `no transcript.cues.json under ${w.channel}/data/${w.video}`, - }); + }; + continue; + } + + if (await heldLocally(wFull, render, local)) { + rows[i] = { + ...w, ok: true, state: "held-locally", title: meta.title, url: meta.webpageUrl, + checkedAt: iso(), error: null, + }; continue; } + probes.push({ i, w, meta, platform: detectPlatform(meta.webpageUrl) ?? "other" }); + } + + // THE PACED PROBES. Each platform has its own clock: the next probe on it is + // due a gap after the last one ended. The probe made next is always the one due + // soonest, so two platforms interleave instead of one waiting on the other. + const testGap = testGapMs(); + const floorMs = (platform) => testGap ?? clipWindowMinGapSeconds(platform === "other" ? null : platform) * 1000; + const dueAt = new Map(); // platform -> when its next probe may start, in ms + const refused = new Map(); // platform -> the refusal that stopped it + const pending = [...probes]; + while (pending.length) { + let k = 0; + const due = (p) => dueAt.get(p.platform) ?? -Infinity; + for (let j = 1; j < pending.length; j++) if (due(pending[j]) < due(pending[k])) k = j; + const p = pending.splice(k, 1)[0]; + const { i, w, meta, platform } = p; + if (refused.has(platform)) { + rows[i] = { + ...w, ok: null, state: "unchecked", title: meta.title, url: meta.webpageUrl, checkedAt: iso(), + error: `not probed: ${platform} refused an earlier probe this run (${refused.get(platform)})`, + }; + continue; + } + + const wait = due(p) - now(); + if (wait > 0) { + log(`waiting ${Math.round(wait / 1000)} s before the next ${platform} probe`); + await sleep(wait); + } + const checkedAt = iso(); try { - await execFileP( - YTDLP, - simulateArgs(meta.webpageUrl), - { maxBuffer: 1 << 24 }, - ); - sources.push({ - ...w, ok: true, state: "ok", title: meta.title, url: meta.webpageUrl, - checkedAt: new Date().toISOString(), error: null, - }); + await execFileP(ytdlp, simulateArgs(meta.webpageUrl), { maxBuffer: 1 << 24 }); + rows[i] = { ...w, ok: true, state: "ok", title: meta.title, url: meta.webpageUrl, checkedAt, error: null }; } catch (err) { - const stderr = err?.stderr ?? err?.message ?? ""; - sources.push({ - ...w, ok: false, state: classify(stderr), title: meta.title, url: meta.webpageUrl, - checkedAt: new Date().toISOString(), error: String(stderr).trim().split("\n").slice(-3).join(" "), - }); + const stderr = err?.stderr || err?.message || ""; + const error = String(stderr).trim().split("\n").slice(-3).join(" "); + const state = classify(stderr); + if (state === "unchecked") refused.set(platform, error.slice(0, 160)); + rows[i] = { ...w, ok: verdictOf(state), state, title: meta.title, url: meta.webpageUrl, checkedAt, error }; } + // The gap runs from the END of a probe (a --simulate is several requests), + // the floor plus up to half again so a run never settles into a beat. + dueAt.set(platform, now() + (testGap ?? floorMs(platform) * (1 + 0.5 * random()))); } - const report = { manifest: path.resolve(manifestPath), checkedAt: new Date().toISOString(), sources }; + const sources = rows; + const report = { manifest: path.resolve(manifestPath), checkedAt: iso(), sources }; // ensureWriteDir, not mkdir: a project's out/ may belong on the media root. await ensureWriteDir(dir); await writeFile(file, JSON.stringify(report, null, 2) + "\n", "utf8"); @@ -174,24 +286,33 @@ async function main() { const report = await checkAvailability(manifestPath, { outDir: flag("--out"), maxAgeDays: Number(flag("--max-age") ?? 0), + log: (m) => console.error(m), }); if (argv.includes("--json")) { console.log(JSON.stringify(report, null, 2)); } else { for (const s of report.sources) { - const mark = s.ok ? "ok " : "GONE"; + const mark = s.ok ? "ok " : s.ok === null ? "?? " : "GONE"; console.log( `${mark} ${s.key.padEnd(40)} ${String(s.state).padEnd(14)} ` + `${s.clips.length} clip(s)${s.reused ? " (cached)" : ""}`, ); if (!s.ok && s.error) console.log(` ${s.error}`); } - const bad = report.sources.filter((s) => !s.ok).length; - console.log(`\n${report.sources.length} source(s), ${bad} unavailable -> ${report.file}`); + const bad = report.sources.filter((s) => s.ok === false).length; + const held = report.sources.filter((s) => s.state === "held-locally").length; + const unchecked = report.sources.filter((s) => s.ok === null).length; + console.log( + `\n${report.sources.length} source(s), ${bad} unavailable` + + (held ? `, ${held} held locally (not probed)` : "") + + (unchecked ? `, ${unchecked} not checked (the platform refused a probe)` : "") + + ` -> ${report.file}`, + ); } - if (report.sources.some((s) => !s.ok) && !argv.includes("--allow-missing")) process.exit(1); + // `unchecked` is no verdict: only a source known to be gone stops the chain. + if (report.sources.some((s) => s.ok === false) && !argv.includes("--allow-missing")) process.exit(1); } if (import.meta.url === `file://${process.argv[1]}`) { diff --git a/umtool/report-to-video/check-availability.test.mjs b/umtool/report-to-video/check-availability.test.mjs @@ -11,6 +11,8 @@ import path from "node:path"; const ROOT = await mkdtemp(path.join(os.tmpdir(), "check-availability-")); process.env.CHANNELS_DIR = ROOT; +// The real pacing is under test here, not the e2e stub gap. +delete process.env.E2E_AVAILABILITY_GAP_MS; const { cueMeta } = await import("./check-availability.mjs"); test.after(() => rm(ROOT, { recursive: true, force: true })); @@ -31,3 +33,155 @@ test("cueMeta reads a Twitch v<n> record from data/<n>/", async () => { await writeFile(path.join(ROOT, "example-twitch", "config.json"), JSON.stringify({ handling: "youtube", platform: "youtube" })); await assert.rejects(() => cueMeta(`v${n}`, "example-twitch"), /ENOENT/); }); + +// ---- the preflight never bursts a platform, and never asks for what is held ---- +// +// A fake yt-dlp records each invocation; the pacing runs on a fake clock (the +// injected `now`/`sleep`), so a 120 s Rumble gap costs the test nothing. + +const { checkAvailability, classify } = await import("./check-availability.mjs"); +const { rawWindowName } = await import("./sources.mjs"); +const { chmod, readFile } = await import("node:fs/promises"); +const { CLIP_WINDOW_MIN_GAP_SECONDS, CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS } = await import( + "yt-dlp-transcript-common/ytdlp/platformArgs.mjs" +); + +/** A fake yt-dlp: appends its last arg (the URL) to `log`; a URL with "blocked" draws a 403. */ +async function fakeYtdlp(dir) { + const bin = path.join(dir, "fake-yt-dlp.sh"); + const log = path.join(dir, "invocations.log"); + await writeFile( + bin, + `#!/bin/sh\nfor a; do last="$a"; done\necho "$last" >> "${log}"\n` + + `case "$last" in *blocked*) echo "ERROR: [Rumble] x: Unable to download webpage: HTTP Error 403: Forbidden" >&2; exit 1;; esac\nexit 0\n`, + ); + await chmod(bin, 0o755); + const calls = async () => (await readFile(log, "utf8").catch(() => "")).split("\n").filter(Boolean); + return { bin, calls }; +} + +/** A fake clock: `sleep` advances it and records what was asked. */ +function fakeClock(start = Date.parse("2026-10-25T00:00:00Z")) { + let t = start; + const sleeps = []; + return { + now: () => t, + sleep: async (ms) => { + sleeps.push(ms); + t += ms; + }, + random: () => 0, + sleeps, + }; +} + +/** A channel with one video's cue file, its page at `url`. */ +async function cueFile(slug, id, url) { + await mkdir(path.join(ROOT, slug, "data", id), { recursive: true }); + await writeFile(path.join(ROOT, slug, "config.json"), JSON.stringify({ handling: "youtube" })); + await writeFile( + path.join(ROOT, slug, "data", id, "transcript.cues.json"), + JSON.stringify({ id, title: `video ${id}`, webpageUrl: url, duration: 600, cues: [] }), + ); +} + +async function project(name, timeline, ledger = []) { + const dir = path.join(ROOT, "projects", name); + await mkdir(dir, { recursive: true }); + const manifest = path.join(dir, "video.manifest.json"); + await writeFile( + manifest, + JSON.stringify({ slug: name, provenance: { channelSlug: "chan" }, render: { fetchPad: 3 }, timeline, ledger }), + ); + return { dir, manifest, out: path.join(dir, "out") }; +} + +test("classify: a refusal is unchecked, never an age restriction or a death", () => { + assert.equal(classify("ERROR: HTTP Error 403: Forbidden"), "unchecked"); + assert.equal(classify("ERROR: HTTP Error 429: Too Many Requests"), "unchecked"); + assert.equal(classify("Sign in to confirm you're not a bot"), "unchecked"); + assert.equal(classify("Just a moment..."), "unchecked"); + assert.equal(classify("Sign in to confirm your age"), "restricted"); + assert.equal(classify("Video unavailable"), "deleted"); +}); + +test("every clip held on disk: held-locally, and yt-dlp is never run", async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), "ca-held-")); + const fake = await fakeYtdlp(tmp); + await cueFile("chan", "held1", "https://rumble.com/v111-held.html"); + await cueFile("chan", "held2", "https://www.youtube.com/watch?v=held2xxxxxx"); + const p = await project("all-local", [ + { id: "c1", type: "clip", video: "held1", start: 10, end: 20 }, + { id: "c2", type: "clip", video: "held2", start: 30, end: 40 }, + ]); + await mkdir(path.join(p.out, "clips-raw"), { recursive: true }); + // c1 in the build's raw cache (its exact padded span), c2 in the editor's window cache. + await writeFile(path.join(p.out, "clips-raw", rawWindowName("held1", 7, 23)), "x"); + await mkdir(path.join(ROOT, "chan", "data", "held2", "clips"), { recursive: true }); + await writeFile(path.join(ROOT, "chan", "data", "held2", "clips", "20-50.mp4"), "x"); + const clock = fakeClock(); + const report = await checkAvailability(p.manifest, { outDir: p.out, ytdlp: fake.bin, ...clock }); + assert.deepEqual(report.sources.map((s) => [s.key, s.state, s.ok]), [ + ["chan/held1", "held-locally", true], + ["chan/held2", "held-locally", true], + ]); + assert.deepEqual(await fake.calls(), [], "no probe at all"); + assert.deepEqual(clock.sleeps, []); +}); + +test("two Rumble sources: the second probe starts at least 120 s after the first ends", async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), "ca-paced-")); + const fake = await fakeYtdlp(tmp); + await cueFile("chan", "r1", "https://rumble.com/v201-one.html"); + await cueFile("chan", "r2", "https://rumble.com/v202-two.html"); + await cueFile("chan", "y1", "https://www.youtube.com/watch?v=y1xxxxxxxxx"); + const p = await project("paced", [ + { id: "c1", type: "clip", video: "r1", start: 10, end: 20 }, + { id: "c2", type: "clip", video: "r2", start: 10, end: 20 }, + { id: "c3", type: "clip", video: "y1", start: 10, end: 20 }, + ]); + const clock = fakeClock(); + const report = await checkAvailability(p.manifest, { outDir: p.out, ytdlp: fake.bin, ...clock }); + assert.equal(CLIP_WINDOW_PLATFORM_MIN_GAP_SECONDS.rumble, 120); + const at = Object.fromEntries(report.sources.map((s) => [s.video, Date.parse(s.checkedAt)])); + assert.ok(at.r2 - at.r1 >= 120_000, `rumble probes ${at.r2 - at.r1} ms apart`); + // The YouTube probe does not wait behind Rumble's gap: it interleaves. + assert.ok(at.y1 < at.r2, "youtube probed inside rumble's gap"); + assert.deepEqual(clock.sleeps, [120_000]); + assert.equal((await fake.calls()).length, 3); + assert.ok(report.sources.every((s) => s.state === "ok")); + assert.ok(CLIP_WINDOW_MIN_GAP_SECONDS >= 30); +}); + +test("a 403 stops that platform: its remaining sources are unchecked, never unavailable", async () => { + const tmp = await mkdtemp(path.join(os.tmpdir(), "ca-refused-")); + const fake = await fakeYtdlp(tmp); + await cueFile("chan", "b1", "https://rumble.com/v301-blocked.html"); + await cueFile("chan", "b2", "https://rumble.com/v302-next.html"); + await cueFile("chan", "b3", "https://rumble.com/v303-later.html"); + await cueFile("chan", "y2", "https://www.youtube.com/watch?v=y2xxxxxxxxx"); + const p = await project( + "refused", + [ + { id: "c1", type: "clip", video: "b1", start: 10, end: 20 }, + { id: "c2", type: "clip", video: "b2", start: 10, end: 20 }, + { id: "c4", type: "clip", video: "y2", start: 10, end: 20 }, + ], + [{ id: "k1", video: "b3" }], + ); + const clock = fakeClock(); + const report = await checkAvailability(p.manifest, { outDir: p.out, ytdlp: fake.bin, ...clock }); + const by = Object.fromEntries(report.sources.map((s) => [s.video, s])); + assert.equal(by.b1.state, "unchecked"); + assert.equal(by.b1.ok, null); + assert.equal(by.b2.state, "unchecked"); + assert.equal(by.b3.state, "unchecked"); + assert.match(by.b2.error, /rumble refused an earlier probe/); + assert.equal(by.y2.state, "ok", "another platform is still probed"); + const calls = await fake.calls(); + assert.equal(calls.filter((u) => u.includes("rumble.com")).length, 1, "one Rumble request, then none"); + assert.equal(calls.length, 2); + // On disk too: what the inbox reads. + const disk = JSON.parse(await readFile(path.join(p.out, "availability.json"), "utf8")); + assert.ok(disk.sources.every((s) => s.ok !== false), JSON.stringify(disk.sources.map((s) => s.state))); +}); diff --git a/umtool/report-to-video/manifest-sources.mjs b/umtool/report-to-video/manifest-sources.mjs @@ -0,0 +1,43 @@ +// manifest-sources.mjs — the (channel, video) sources a manifest cites, as the +// availability preflight counts them. A LEAF (no imports), so the preflight, +// the driver that budgets its timeout, and the routes that build its step all +// count the same thing without pulling the build into a request handler. + +/** + * Every clip without its own `src` (a `src` clip is a file beside the + * manifest, on no platform: the build checks it is there), and every ledger + * claim with a video. A clip may name its own channel: the same id under a + * different slug is a different file, so the unit is (channel, video). + * + * LEDGER SOURCES TOO, not just the clipped ones. A cut that stacks its + * unclipped claims onto cards has to say WHY each one is a line of text rather + * than footage, and "the upload is gone" and "we did not cut it" are different + * sentences. Guessing which is which is how a live source ends up labelled + * deleted on screen. + * + * @param {any} manifest + * @returns {{ key: string, channel: string, video: string, clips: string[], claims: string[], entries: any[] }[]} + */ +export function manifestSources(manifest) { + const slug = manifest?.provenance?.channelSlug; + const wanted = new Map(); + const want = (channel, video) => { + const key = `${channel}/${video}`; + if (!wanted.has(key)) wanted.set(key, { key, channel, video, clips: [], claims: [], entries: [] }); + return wanted.get(key); + }; + for (const e of manifest?.timeline ?? []) { + if (e?.type !== "clip" || e.src != null) continue; + const w = want(e.channel ?? slug, e.video); + w.clips.push(e.id); + w.entries.push(e); + } + for (const c of manifest?.ledger ?? []) { + if (!c?.video) continue; + want(c.channel ?? slug, c.video).claims.push(c.id); + } + return [...wanted.values()]; +} + +/** How many sources the preflight may have to probe. */ +export const sourceCountOf = (manifest) => manifestSources(manifest).length; diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -39,6 +39,7 @@ "./montage-styles": "./montage-styles.mjs", "./montage-rulings": "./montage-rulings.mjs", "./lint": "./lint.mjs", + "./manifest-sources": "./manifest-sources.mjs", "./local-media": "./local-media.mjs", "./join-preview": "./join-preview.mjs", "./look": "./look.mjs", diff --git a/umtool/report-to-video/render-cards.mjs b/umtool/report-to-video/render-cards.mjs @@ -1008,6 +1008,9 @@ export const ledgerSeconds = (n) => LEDGER_LEAD + LEDGER_STEP * n + LEDGER_TAIL */ export const SOURCE_TAG = { ok: "not clipped", + "held-locally": "not clipped", + // Not checked is no verdict: the card never says a source is gone unasked. + unchecked: "not clipped", deleted: "source deleted", private: "source private", "members-only": "members only",