Archilyzer · Source

archilyzer

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

commit a9fd81a09899fce946ddb07db50a6652f8c0e89e
parent 6a675ac9a398b7620f81e2feb902267eebece9ad
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  9 Nov 2026 23:20:02 -0500

report-to-video: a shard page is cached by its manifest's generation -- an archive rebuild is fetched again

~/.cache/archilyzer-report-to-video/<sha1(url)>.json kept page-NNNN.json forever while the channel's
transcripts manifest moved on (linkCheck refreshes manifests), so the cue walk could cut from cues a rebuild
had rewritten. createJsonCache's getJson takes a `version`: the copy on disk is stored with it
({__umtoolCacheVersion, body}, still one file per URL) and a copy of any other version is a miss, fetched
again and overwritten. The cue walk (fromHttp, resolveSiteId) and linkCheck's page reads pass
pagesVersionOf(manifest) -- its generatedAt; a manifest without one caches by URL as before. A read with no
version takes either form, so post-links and any other reader are unchanged.

Test: cues.test.mjs fills a disk cache against generation 1, bumps the fake manifest's generatedAt with
rewritten cues, refreshes the manifest as linkCheck does, and the walk fetches exactly that page again and
reads the new cues (it fails on the old code); and an unversioned read of a versioned copy.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
Mumtool/lib/report/linkCheck.mjs | 9++++++---
Mumtool/report-to-video/cues.mjs | 76+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----------------
Mumtool/report-to-video/cues.test.mjs | 55+++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 120 insertions(+), 20 deletions(-)

diff --git a/umtool/lib/report/linkCheck.mjs b/umtool/lib/report/linkCheck.mjs @@ -28,7 +28,7 @@ // Plain ESM: the CLI runs it under bare node. import { mkdir, readFile, rename, writeFile } from "node:fs/promises"; import path from "node:path"; -import { createJsonCache, DEFAULT_CACHE_DIR, pageUrlFrom } from "umtool-report-to-video/cues"; +import { createJsonCache, DEFAULT_CACHE_DIR, pagesVersionOf, pageUrlFrom } from "umtool-report-to-video/cues"; import { qrsOf } from "umtool-report-to-video/lint"; import { jitterUp } from "yt-dlp-transcript-common/lib/jitter.mjs"; @@ -247,9 +247,12 @@ export async function checkLinks( let found = false; let error = null; try { - found = has(await getJson(pageUrl)); + // Keyed by the manifest's generation (cues.mjs pagesVersionOf), so a shard cached from an older deploy is + // fetched again rather than read. + const version = pagesVersionOf(man.doc); + found = has(await getJson(pageUrl, { version })); // A cached shard older than the deploy: read it again, once. - if (!found) found = has(await getJson(pageUrl, { refresh: true })); + if (!found) found = has(await getJson(pageUrl, { refresh: true, version })); } catch (e) { error = errText(e); } diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs @@ -53,8 +53,10 @@ // manifests through createJsonCache below, the same files on disk, and on a // post it cannot find it fetches them again and rewrites them. The cue walk // never refreshes, but it can read a corpus.json post-links rewrote: newer, so -// a channel the stale copy lacked is found. Manifest and shard URLs carry no -// version, so a cue window does not move because of it. +// a channel the stale copy lacked is found. Shard pages are cached by the +// generation of the transcripts manifest that named them (its generatedAt), so +// when linkCheck refreshes a manifest after an archive rebuild, the walk fetches +// that channel's pages again instead of reading the old build's forever. import { readFile, writeFile, mkdir, lstat, readlink, readdir, stat } from "node:fs/promises"; import path from "node:path"; @@ -78,12 +80,33 @@ export const DEFAULT_CACHE_DIR = // A shard page is capped at 8 MB and holds ~100 videos, so refetching one per // clip — across two separate processes, resolve-windows then build-video — is -// the difference between usable and painful. Cached by URL on disk; archives are -// rebuilt rarely and a stale page only matters if the cues themselves changed. +// the difference between usable and painful. Cached by URL on disk, and a page +// by the generation of the manifest that named it (pagesVersionOf): an archive +// rebuild bumps the manifest's generatedAt, and its pages are fetched again. function cacheKey(url) { return createHash("sha1").update(url).digest("hex") + ".json"; } +// The key a versioned copy on disk carries its version under (createJsonCache, +// `version`). No published document has a key like it. +export const CACHE_VERSION_KEY = "__umtoolCacheVersion"; + +/** A document as the disk cache holds it -> `{ version, body }` (version null when unversioned). */ +function unwrapCached(doc) { + if (doc && typeof doc === "object" && !Array.isArray(doc) && CACHE_VERSION_KEY in doc) { + return { version: doc[CACHE_VERSION_KEY], body: doc.body }; + } + return { version: null, body: doc }; +} + +/** + * The generation a channel's shard pages belong to: its transcripts manifest's + * `generatedAt` (every published manifest carries one), or null for a manifest + * without it -- whose pages are then cached by URL alone, as before. + */ +export const pagesVersionOf = (manifest) => + typeof manifest?.generatedAt === "string" && manifest.generatedAt ? manifest.generatedAt : null; + export function pageFileName(pageNumber) { return `page-${String(pageNumber).padStart(4, "0")}.json`; } @@ -170,6 +193,17 @@ export class CueLookupError extends Error { * `refreshAfterMs` ago. The default, Infinity, makes that "at most once per * process": a build re-reads a stale cached document once, never twice. A * long-lived server passes a window instead. + * + * `getJson(url, { version })` is for a document whose URL never changes but + * whose content belongs to a generation of something else -- a shard page to + * the `generatedAt` of the channel manifest that named it. The copy on disk is + * then stored with that version beside it (`{ [CACHE_VERSION_KEY]: v, body }`, + * the same one file per URL), and a cached copy of any other version (or of + * none) is a miss: the page is fetched again and the old generation's copy + * overwritten. Without this a page was kept forever while its manifest moved on + * (linkCheck refreshes manifests), so the walk could read a record from a page + * the new manifest no longer puts it on, or cues an archive rebuild rewrote. + * A read with no `version` takes either form. */ export function createJsonCache({ cacheDir = DEFAULT_CACHE_DIR, @@ -177,51 +211,59 @@ export function createJsonCache({ log = () => {}, refreshAfterMs = Infinity, } = {}) { + /** URL -> { version, body }: version null for a document cached without one. */ const mem = new Map(); /** URL -> when this cache last fetched it from the network (ms). */ const fetchedAt = new Map(); - /** URL -> the network fetch of it in progress. */ + /** URL (+ version) -> the network fetch of it in progress. */ const inflight = new Map(); - async function getJson(url, { refresh = false } = {}) { + const fits = (have, version) => version == null || have === version; + + async function getJson(url, { refresh = false, version = null } = {}) { const recent = fetchedAt.has(url) && Date.now() - fetchedAt.get(url) < refreshAfterMs; const useCache = !refresh || recent; - if (useCache && mem.has(url)) return mem.get(url); + const held = mem.get(url); + if (useCache && held && fits(held.version, version)) return held.body; const disk = cacheDir ? path.join(cacheDir, cacheKey(url)) : null; if (useCache && disk) { try { - const cached = JSON.parse(await readFile(disk, "utf8")); - mem.set(url, cached); - return cached; + const cached = unwrapCached(JSON.parse(await readFile(disk, "utf8"))); + if (fits(cached.version, version)) { + mem.set(url, cached); + return cached.body; + } + log(`stale ${url}: cached for ${cached.version ?? "no version"}, wanted ${version}`); } catch { /* cold cache */ } } // Callers that ask for the same URL while it is on its way share the one // fetch (umtool's preview routes run side by side). - if (inflight.has(url)) return inflight.get(url); + const flight = version == null ? url : `${url}\0${version}`; + if (inflight.has(flight)) return inflight.get(flight); const pending = (async () => { log(`fetch ${url}`); const res = await fetchImpl(url); if (!res.ok) throw new Error(`GET ${url} -> ${res.status}`); const json = await res.json(); - mem.set(url, json); + mem.set(url, { version, body: json }); fetchedAt.set(url, Date.now()); if (disk) { try { await mkdir(path.dirname(disk), { recursive: true }); - await writeFile(disk, JSON.stringify(json)); + await writeFile(disk, JSON.stringify(version == null ? json : { [CACHE_VERSION_KEY]: version, body: json })); } catch { // A cache we cannot write is a slow run, not a failed one. } } return json; })(); - inflight.set(url, pending); + inflight.set(flight, pending); try { return await pending; } finally { - inflight.delete(url); + inflight.delete(flight); } } @@ -285,7 +327,7 @@ export function createCueSource({ const manifest = await getJson(entry.manifests.transcripts); log(`resolving "${wanted}" by scanning ${manifest.pageCount} shard(s) of ${entry.slug}`); for (let n = 0; n < manifest.pageCount; n += 1) { - const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n)); + const page = await getJson(pageUrlFrom(entry.manifests.transcripts, n), { version: pagesVersionOf(manifest) }); const hit = page.find( (r) => r.id === wanted || r.slug === wanted || String(r.webpageUrl ?? "").includes(wanted), ); @@ -327,7 +369,7 @@ export function createCueSource({ ); } - const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber)); + const page = await getJson(pageUrlFrom(entry.manifests.transcripts, pageNumber), { version: pagesVersionOf(manifest) }); const record = page.find((r) => r.id === siteVideo || r.slug === siteVideo); if (!record) { throw new CueLookupError( diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs @@ -14,6 +14,7 @@ import path from "node:path"; import { CAPTION_TRACK_RULE_VERSION, createCueSource, + createJsonCache, pageFileName, pageUrlFrom, siteOriginFromManifest, @@ -122,6 +123,60 @@ test("fetches each URL once, however many videos are read", async () => { ]); }); +// --- the disk cache follows the manifest's generation ---------------------- + +test("a shard page cached on disk is fetched again when its channel manifest's generatedAt moves", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "cues-shard-cache-")); + try { + const MAN = `${ORIGIN}/transcripts/chan/manifest.json`; + const PAGE = `${ORIGIN}/transcripts/chan/page-0000.json`; + const gen1 = { ...ROUTES, [MAN]: { ...ROUTES[MAN], generatedAt: "2026-08-07T00:00:00.000Z" } }; + // A run against the first deploy fills the disk cache. + const seen1 = []; + const first = await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen1, seen1) }).load("chan", "vid1"); + assert.equal(first.cues[1].text, "second line."); + assert.ok(seen1.includes(PAGE)); + + // A second process with the same generation reads everything from disk. + const seen2 = []; + await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen1, seen2) }).load("chan", "vid1"); + assert.deepEqual(seen2, []); + + // The archive is rebuilt: the cues were rewritten and the manifest carries a new generatedAt. Something + // refreshes the manifest on disk (linkCheck does, with refresh: true) ... + const rewritten = { ...RECORD, cues: [{ start: 0, end: 3.1, text: "first line, re-transcribed" }, { start: 3.1, end: 5, text: "second." }] }; + const gen2 = { ...gen1, [MAN]: { ...gen1[MAN], generatedAt: "2026-11-01T00:00:00.000Z" }, [PAGE]: [rewritten] }; + await createJsonCache({ cacheDir, fetchImpl: stubFetch(gen2) }).getJson(MAN, { refresh: true }); + + // ... and the cue walk, which never refreshes, follows it: the page of the old generation is a miss. + const seen3 = []; + const after = await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen2, seen3) }).load("chan", "vid1"); + assert.deepEqual(seen3, [PAGE]); + assert.equal(after.cues[0].text, "first line, re-transcribed"); + + // And the refetched page is the one on disk now: a third run fetches nothing. + const seen4 = []; + await createCueSource({ channelsDir: path.join(tmpdir(), "definitely-no-corpus-here"), siteOrigin: ORIGIN, cacheDir, fetchImpl: stubFetch(gen2, seen4) }).load("chan", "vid1"); + assert.deepEqual(seen4, []); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + +test("a versioned copy on disk still reads as the document to a caller that asks with no version", async () => { + const cacheDir = await mkdtemp(path.join(tmpdir(), "cues-shard-cache-")); + try { + const PAGE = `${ORIGIN}/transcripts/chan/page-0000.json`; + await createJsonCache({ cacheDir, fetchImpl: stubFetch(ROUTES) }).getJson(PAGE, { version: "g1" }); + const seen = []; + const doc = await createJsonCache({ cacheDir, fetchImpl: stubFetch(ROUTES, seen) }).getJson(PAGE); + assert.deepEqual(doc, [RECORD]); + assert.deepEqual(seen, []); + } finally { + await rm(cacheDir, { recursive: true, force: true }); + } +}); + // --- local wins ------------------------------------------------------------- test("a local corpus is preferred over the network", async () => {