commit 7ff826dc971a70fc50e38b4118edb1b481b21d6e
parent 2147a99ac4bce7651eb2898a45cb7415c051a7d7
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Wed, 14 Oct 2026 03:22:52 -0400
umtool: research's held counts kept 5 min per source and channel, with Refresh and their age; the track census persisted per source build, stale when the build changes
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
13 files changed, 394 insertions(+), 40 deletions(-)
diff --git a/umtool/app/api/research/coverage/route.ts b/umtool/app/api/research/coverage/route.ts
@@ -4,16 +4,18 @@ import { fail, ok } from "../_respond";
export const dynamic = "force-dynamic";
-// GET ?source=&channels=a,b -> CoverageResponse (lib/research/types.ts)
+// GET ?source=&channels=a,b[&fresh=1] -> CoverageResponse (lib/research/types.ts)
//
// Channels × years: what the source publishes (its summaries, by upload year
// and state), what the editor holds on disk (channel_coverage, through its
// GET /api/ops/coverage; for the local corpus, on disk when the editor cannot
// be asked -- and the answer says why), gaps over 60 days, and transcripts vs
-// captions where a search has counted a channel whole.
+// captions where a search has counted a channel whole. The held counts are
+// kept five minutes per source and channel; `fresh=1` (Refresh) asks again.
export async function GET(request: Request) {
try {
- return ok(await coverageOf(scopeFrom(new URL(request.url).searchParams)));
+ const q = new URL(request.url).searchParams;
+ return ok(await coverageOf(scopeFrom(q), { fresh: q.get("fresh") === "1" }));
} catch (e) {
return fail(e);
}
diff --git a/umtool/app/research/archive/page.tsx b/umtool/app/research/archive/page.tsx
@@ -56,7 +56,7 @@ export default async function ArchivePage({ searchParams }: { searchParams: Prom
{error}
</p>
) : data ? (
- <ArchiveInventory data={data} />
+ <ArchiveInventory data={data} source={scope.source} />
) : null}
</div>
</div>
diff --git a/umtool/components/research/ArchiveInventory.tsx b/umtool/components/research/ArchiveInventory.tsx
@@ -1,10 +1,12 @@
"use client";
-import { useRef, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { VIDEO_STATE_LABELS, type VideoState } from "yt-dlp-transcript-common/lib/availability";
import { badgeVariants } from "@/components/ui/badge";
import { buttonVariants } from "@/components/ui/button";
import { Table, TD, TH } from "@/components/ui/table";
+import { useHydrated } from "@/components/ui/use-hydrated";
+import { researchCoverageApi } from "@/lib/research/hrefs";
import { cn } from "@/lib/utils";
import type { CoverageResponse, CoverageRow } from "@/lib/research/types";
@@ -51,7 +53,40 @@ function tipOf(r: CoverageRow, m: Measure, y: string): string {
return parts.join(" · ");
}
-export default function ArchiveInventory({ data }: { data: CoverageResponse }) {
+/** "just now", "3 min ago", "1 h ago". */
+export function ago(ms: number): string {
+ const s = Math.max(0, Math.round(ms / 1000));
+ if (s < 45) return "just now";
+ const m = Math.round(s / 60);
+ return m < 60 ? `${m} min ago` : `${Math.round(m / 60)} h ago`;
+}
+
+export default function ArchiveInventory({ data: initial, source }: { data: CoverageResponse; source: string }) {
+ const hydrated = useHydrated();
+ const [data, setData] = useState(initial);
+ const [refreshing, setRefreshing] = useState(false);
+ const [refreshError, setRefreshError] = useState<string | null>(null);
+ // The age line re-reads the clock; the counts themselves change only on Refresh.
+ const [now, setNow] = useState(() => Date.now());
+ useEffect(() => {
+ const id = setInterval(() => setNow(Date.now()), 30_000);
+ return () => clearInterval(id);
+ }, []);
+ const refresh = async () => {
+ setRefreshing(true);
+ setRefreshError(null);
+ try {
+ const r = await fetch(researchCoverageApi({ source }, { fresh: true }), { cache: "no-store" });
+ const body = await r.json().catch(() => null);
+ if (!r.ok) throw new Error(body?.error ?? `HTTP ${r.status}`);
+ setData(body as CoverageResponse);
+ setNow(Date.now());
+ } catch (e) {
+ setRefreshError((e as Error).message);
+ } finally {
+ setRefreshing(false);
+ }
+ };
const [measure, setMeasure] = useState<Measure>(data.held.via === "none" ? "published" : "held");
const [table, setTable] = useState(false);
const [tip, setTip] = useState<{ text: string; x: number; y: number } | null>(null);
@@ -116,11 +151,23 @@ export default function ArchiveInventory({ data }: { data: CoverageResponse }) {
</button>
</div>
- {data.held.note && (
- <p data-held-note={data.held.via} className="mb-3 text-[12px] text-text-2">
- Held: {data.held.note}.
- </p>
- )}
+ <p data-held-age="" className="mb-3 flex flex-wrap items-center gap-x-3 gap-y-1 text-[12px] text-text-2">
+ <span>
+ Held counts from <span data-held-ago="">{ago(now - data.held.at)}</span>
+ {data.held.cached ? " (kept 5 min)" : ""}
+ {data.held.note ? (
+ <span data-held-note={data.held.via}> · {data.held.note}</span>
+ ) : null}
+ </span>
+ <button type="button" disabled={!hydrated || refreshing} className={buttonVariants({ variant: "quiet", size: "sm" })} onClick={refresh}>
+ {refreshing ? "Refreshing…" : "Refresh"}
+ </button>
+ {refreshError && (
+ <span role="alert" className="text-reject-text">
+ {refreshError}
+ </span>
+ )}
+ </p>
{rows.length === 0 ? (
<p className="text-[13px] text-text-2">This source lists no channels.</p>
diff --git a/umtool/components/research/ScopeBar.tsx b/umtool/components/research/ScopeBar.tsx
@@ -196,7 +196,10 @@ export default function ScopeBar({
{tracks.counted < tracks.of ? ` (${tracks.counted} of ${tracks.of} channels counted)` : ""}
</span>
) : (
- <span> · transcripts vs captions: counted by the first full search</span>
+ <span data-tracks-stale={summary.tracksStale ? "" : undefined}>
+ {" "}
+ · transcripts vs captions: {summary.tracksStale ?? "counted by the first full search"}
+ </span>
)}
{summary.aliases > 0 ? " · aliases on" : ""}
{summary.warnings.length > 0 && <span className="text-doubt-text"> · {summary.warnings.join("; ")}</span>}
diff --git a/umtool/e2e/research.spec.ts b/umtool/e2e/research.spec.ts
@@ -248,6 +248,11 @@ test("the archive inventory: channels × years, held vs published, gaps, keys, a
await expect(heat).toBeVisible();
// No editor answers coverage here (the stub has no such route): read on disk, and said so.
await expect(page.locator("[data-held-note=disk]")).toContainText("read on disk instead");
+ // The held counts are kept five minutes (the warm-up read them): the age says so, Refresh asks again.
+ await expect(page.locator("[data-held-age]")).toContainText(/Held counts from (just now|\d+ min ago) \(kept 5 min\)/);
+ await page.getByRole("button", { name: "Refresh" }).click();
+ await expect(page.locator("[data-held-age]")).not.toContainText("kept 5 min");
+ await expect(page.getByRole("button", { name: "Refresh" })).toBeEnabled();
await expect(heat.locator("thead th")).toHaveCount(1 + 8 + 1);
const hr = heat.locator('tr[data-row="harbor-radio"]');
await expect(hr.locator('td[data-year="2022"]')).toHaveText("1");
diff --git a/umtool/lib/research/census.mjs b/umtool/lib/research/census.mjs
@@ -0,0 +1,105 @@
+// THE TRACK CENSUS, persisted: transcripts vs captions per channel, as far as
+// a search has read each channel whole (lib/research/corpus.ts). Nothing
+// published counts it per scope, so it is learned by searching, and kept here
+// so a restart does not forget it.
+//
+// REPORTS_ROOT/.umtool/research/census/<sha1(handle), 16 hex>.json
+// { format: "umtool-research-census", version: 1, handle, identity,
+// updatedAt, channels: { "<channel key>": { total, transcript, captions,
+// unknown, byYear } } }
+//
+// KEYED BY THE SOURCE AND ITS BUILD. `identity` is the source's build stamp
+// (sources.ts buildIdentity: corpus.json's generatedAt, and for a local dir its
+// mtime too). A file whose identity is not the source's current one is STALE:
+// its counts describe another build, so they are not used, and the scope says
+// so until a full search counts again and overwrites it.
+//
+// Umtool-side state, never in the corpus. Writes are lib/lifecycle.mjs's: one
+// writer, serialised; a whole file to a temp name and a rename.
+import { createHash } from "node:crypto";
+import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
+import path from "node:path";
+
+export const CENSUS_FORMAT = "umtool-research-census";
+export const CENSUS_VERSION = 1;
+
+/** The file for one source handle under a reports root. */
+export function censusFile(reportsRoot, handle) {
+ const id = createHash("sha1").update(String(handle)).digest("hex").slice(0, 16);
+ return path.join(/* turbopackIgnore: true */ reportsRoot, ".umtool", "research", "census", `${id}.json`);
+}
+
+const num = (v) => (typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : 0);
+function cleanCounts(c) {
+ return { transcript: num(c?.transcript), captions: num(c?.captions), unknown: num(c?.unknown) };
+}
+
+/**
+ * The census for a source at a build. `{ channels, updatedAt }` when the file
+ * is this build's; `{ stale: { identity, updatedAt } }` when it is another
+ * build's; `{}` when there is none (or it cannot be read: `error` says why).
+ *
+ * @param {string} reportsRoot
+ * @param {string} handle
+ * @param {string} identity
+ * @returns {Promise<{ channels?: Record<string, any>, updatedAt?: string, stale?: { identity: string, updatedAt: string }, error?: string }>}
+ */
+export async function readCensus(reportsRoot, handle, identity) {
+ let raw;
+ try {
+ raw = JSON.parse(await readFile(/* turbopackIgnore: true */ censusFile(reportsRoot, handle), "utf8"));
+ } catch (err) {
+ if (err?.code === "ENOENT") return {};
+ return { error: `the census cannot be read: ${err?.message ?? err}` };
+ }
+ if (!raw || raw.format !== CENSUS_FORMAT || raw.handle !== handle || typeof raw.channels !== "object" || !raw.channels) {
+ return { error: "not a umtool-research-census file for this source" };
+ }
+ const updatedAt = typeof raw.updatedAt === "string" ? raw.updatedAt : "";
+ if (raw.identity !== identity) return { stale: { identity: String(raw.identity ?? ""), updatedAt } };
+ const channels = {};
+ for (const [k, c] of Object.entries(raw.channels)) {
+ if (!c || typeof c !== "object") continue;
+ const byYear = {};
+ for (const [y, v] of Object.entries(c.byYear ?? {})) byYear[y] = cleanCounts(v);
+ channels[k] = { total: num(c.total), ...cleanCounts(c), byYear };
+ }
+ return { channels, updatedAt };
+}
+
+let chain = Promise.resolve();
+
+/**
+ * Replace the census for a source at a build (the whole map the caller holds).
+ *
+ * @param {string} reportsRoot
+ * @param {string} handle
+ * @param {string} identity
+ * @param {Record<string, unknown>} channels
+ * @param {{ now?: Date }} [opts]
+ */
+export function writeCensus(reportsRoot, handle, identity, channels, { now } = {}) {
+ const run = chain.then(async () => {
+ const file = censusFile(reportsRoot, handle);
+ const doc = {
+ format: CENSUS_FORMAT,
+ version: CENSUS_VERSION,
+ handle,
+ identity,
+ updatedAt: (now ?? new Date()).toISOString(),
+ channels: Object.fromEntries(Object.entries(channels).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))),
+ };
+ await mkdir(/* turbopackIgnore: true */ path.dirname(/* turbopackIgnore: true */ file), { recursive: true });
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
+ try {
+ await writeFile(/* turbopackIgnore: true */ tmp, `${JSON.stringify(doc, null, 2)}\n`);
+ await rename(/* turbopackIgnore: true */ tmp, file);
+ } catch (err) {
+ await rm(/* turbopackIgnore: true */ tmp, { force: true }).catch(() => {});
+ throw err;
+ }
+ return doc;
+ });
+ chain = run.catch(() => {});
+ return run;
+}
diff --git a/umtool/lib/research/census.test.mjs b/umtool/lib/research/census.test.mjs
@@ -0,0 +1,44 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdtemp, readFile, rm, readdir } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { CENSUS_FORMAT, censusFile, readCensus, writeCensus } from "./census.mjs";
+
+const H = "local:/x/export/public";
+const C = { "ch-a": { total: 3, transcript: 1, captions: 2, unknown: 0, byYear: { 2024: { transcript: 1, captions: 2, unknown: 0 } } } };
+
+test("a census round-trips for its build, and is stale for another", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-census-"));
+ try {
+ assert.deepEqual(await readCensus(root, H, "b1"), {});
+ await writeCensus(root, H, "b1", C, { now: new Date("2026-10-14T00:00:00Z") });
+ const r = await readCensus(root, H, "b1");
+ assert.deepEqual(r.channels, C);
+ assert.equal(r.updatedAt, "2026-10-14T00:00:00.000Z");
+ assert.deepEqual(await readCensus(root, H, "b2"), { stale: { identity: "b1", updatedAt: "2026-10-14T00:00:00.000Z" } });
+ const doc = JSON.parse(await readFile(censusFile(root, H), "utf8"));
+ assert.equal(doc.format, CENSUS_FORMAT);
+ assert.equal(doc.handle, H);
+ assert.ok(censusFile(root, H).includes(`${path.sep}.umtool${path.sep}research${path.sep}census${path.sep}`));
+ // another source, another file
+ assert.notEqual(censusFile(root, H), censusFile(root, "remote:https://a.example"));
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
+
+test("writes are serialised and leave no temp file; bad files are reported, never trusted", async () => {
+ const root = await mkdtemp(path.join(os.tmpdir(), "umtool-census-"));
+ try {
+ await Promise.all(Array.from({ length: 10 }, (_, i) => writeCensus(root, H, `b${i}`, C)));
+ assert.equal((await readCensus(root, H, "b9")).channels["ch-a"].total, 3);
+ assert.deepEqual(await readdir(path.dirname(censusFile(root, H))), [path.basename(censusFile(root, H))]);
+ await writeCensus(root, "other", "b1", C);
+ const { writeFile } = await import("node:fs/promises");
+ await writeFile(censusFile(root, "other"), "{nope");
+ assert.match((await readCensus(root, "other", "b1")).error, /cannot be read/);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});
diff --git a/umtool/lib/research/corpus.ts b/umtool/lib/research/corpus.ts
@@ -16,6 +16,7 @@ import { REPORTS_ROOT } from "../paths.mjs";
import { citationText, facetsOf, hitKey, isoDate, trackOf, yearOf } from "./facets.mjs";
import { sessionKey } from "./session.mjs";
import { readLog } from "./log.mjs";
+import { writeCensus } from "./census.mjs";
import { markRanges } from "./query.mjs";
import { isLocalOnly } from "./rules.mjs";
import { localMediaFor } from "./media";
@@ -153,6 +154,9 @@ export async function scopeOf(scope: Scope): Promise<ScopeSummary> {
first,
last,
tracks: censusOf(opened, [...keys]),
+ ...(opened.censusStale && !censusOf(opened, [...keys])
+ ? { tracksStale: `counted on an earlier build (${opened.censusStale.updatedAt.slice(0, 10) || "date unknown"}); the next full search counts again` }
+ : {}),
aliases: aliases.length,
warnings: [
...parsed.warnings,
@@ -167,6 +171,7 @@ export async function scopeOf(scope: Scope): Promise<ScopeSummary> {
type Seen = { fmt: unknown; duration: number; year: string };
async function recordCensus(opened: Opened, channels: ChannelRef[], seen: Map<string, Map<string, Seen>>): Promise<void> {
+ let counted = 0;
for (const ch of channels) {
const recs = seen.get(ch.key);
if (!recs) continue;
@@ -186,6 +191,16 @@ async function recordCensus(opened: Opened, channels: ChannelRef[], seen: Map<st
y[t]++;
}
opened.census.set(ch.key, c);
+ counted++;
+ }
+ // Kept umtool-side for this build (census.mjs), so a restart does not forget it.
+ if (counted > 0 && opened.identity) {
+ try {
+ await writeCensus(REPORTS_ROOT, opened.option.handle, opened.identity, Object.fromEntries(opened.census));
+ opened.censusStale = null;
+ } catch {
+ /* the counts still serve this process; the file is a convenience */
+ }
}
}
diff --git a/umtool/lib/research/coverage.ts b/umtool/lib/research/coverage.ts
@@ -81,7 +81,22 @@ async function fromDisk(slug: string): Promise<Held | null> {
}
}
-export async function coverageOf(scope: Scope): Promise<CoverageResponse> {
+// ── the held counts, memoised ──
+//
+// Each channel's held count is a walk of the editor's disk (every held
+// video's metadata), and the editor has stalled on the external drive before:
+// a page load must not cost a walk per channel. So a channel's answer --
+// the editor's, the disk's, or "not known" with the reason -- is kept
+// HELD_TTL_MS per source and channel, on globalThis (one copy for every route
+// bundle). `fresh` (the page's Refresh) asks again. The editor is still asked
+// four at a time.
+export const HELD_TTL_MS = 5 * 60_000;
+type HeldMemo = { at: number; held: Held | null; via: CoverageResponse["held"]["via"]; note?: string };
+const g = globalThis as { __umtoolResearchHeld?: Map<string, HeldMemo> };
+const heldMemo = (g.__umtoolResearchHeld ??= new Map());
+
+export async function coverageOf(scope: Scope, opts: { fresh?: boolean; now?: () => number } = {}): Promise<CoverageResponse> {
+ const now = opts.now ?? Date.now;
const opened = await openSource(scope.source);
const { source } = opened;
const sel = await resolveSelectedChannels(source, { channels: scope.channels });
@@ -110,31 +125,44 @@ export async function coverageOf(scope: Scope): Promise<CoverageResponse> {
if (p.total === 0 && ch.videoCount) p.total = ch.videoCount;
}
- // Held: the editor, else (local corpus) the disk.
- let via: CoverageResponse["held"]["via"] = "editor";
- let note: string | undefined;
- let stopped = false;
- const held = new Map<string, Held | null>();
- await mapConcurrent(channels, 4, async (ch) => {
- if (stopped) return;
- const a = await askEditor(ch.slug);
- if (a.ok) held.set(ch.key, heldOf(a.body));
- else if (a.stop) {
- stopped = true;
- note ??= a.why;
- } else held.set(ch.key, null);
+ // Held: the memo, else the editor, else (local corpus) the disk.
+ const memoKey = (ch: ChannelRef) => `${opened.option.handle}\u0000${ch.key}`;
+ const t = now();
+ const todo = channels.filter((ch) => {
+ const m = heldMemo.get(memoKey(ch));
+ return opts.fresh || !m || t - m.at >= HELD_TTL_MS;
});
- if (stopped) {
- held.clear();
- if (opened.option.kind === "local") {
- via = "disk";
- note = `${note}; read on disk instead`;
- await mapConcurrent(channels, 8, async (ch) => held.set(ch.key, await fromDisk(ch.slug)));
+ if (todo.length > 0) {
+ let note: string | undefined;
+ let stopped = false;
+ const fromEditor = new Map<string, Held | null>();
+ await mapConcurrent(todo, 4, async (ch) => {
+ if (stopped) return;
+ const a = await askEditor(ch.slug);
+ if (a.ok) fromEditor.set(ch.key, heldOf(a.body));
+ else if (a.stop) {
+ stopped = true;
+ note ??= a.why;
+ } else fromEditor.set(ch.key, null);
+ });
+ const at = now();
+ if (!stopped) {
+ for (const ch of todo) heldMemo.set(memoKey(ch), { at, held: fromEditor.get(ch.key) ?? null, via: "editor" });
+ } else if (opened.option.kind === "local") {
+ const why = `${note}; read on disk instead`;
+ await mapConcurrent(todo, 8, async (ch) => heldMemo.set(memoKey(ch), { at, held: await fromDisk(ch.slug), via: "disk", note: why }));
} else {
- via = "none";
- note = `${note}; held counts need the editor for a published source`;
+ const why = `${note}; held counts need the editor for a published source`;
+ for (const ch of todo) heldMemo.set(memoKey(ch), { at, held: null, via: "none", note: why });
}
}
+ const memos = channels.map((ch) => heldMemo.get(memoKey(ch))!).filter(Boolean);
+ const held = new Map(channels.map((ch) => [ch.key, heldMemo.get(memoKey(ch))?.held ?? null]));
+ // The page says where the counts came from, and how old the oldest is.
+ const odd = memos.find((m) => m.via === "disk") ?? memos.find((m) => m.via === "none");
+ const via: CoverageResponse["held"]["via"] = odd?.via ?? "editor";
+ const note = odd?.note;
+ const at = memos.length ? Math.min(...memos.map((m) => m.at)) : t;
const years = new Set<string>();
const rows: CoverageRow[] = channels.map((ch) => {
@@ -157,5 +185,11 @@ export async function coverageOf(scope: Scope): Promise<CoverageResponse> {
const span: string[] = [];
for (let y = ys[0]; ys.length && y <= ys[ys.length - 1]; y++) span.push(String(y));
rows.sort((a, b) => (b.held?.total ?? b.published.total) - (a.held?.total ?? a.published.total) || a.name.localeCompare(b.name));
- return { source: opened.option, years: span, rows, held: { via, ...(note ? { note } : {}) }, gapDays: GAP_DAYS };
+ return {
+ source: opened.option,
+ years: span,
+ rows,
+ held: { via, ...(note ? { note } : {}), at, cached: todo.length === 0, asked: todo.length },
+ gapDays: GAP_DAYS,
+ };
}
diff --git a/umtool/lib/research/hrefs.ts b/umtool/lib/research/hrefs.ts
@@ -37,8 +37,8 @@ export function researchScopeApi(s: Partial<Scope>): string {
}
/** GET /api/research/coverage for a scope. */
-export function researchCoverageApi(s: Partial<Scope>): string {
- return withQuery("/api/research/coverage", scopeQuery(s));
+export function researchCoverageApi(s: Partial<Scope>, opts: { fresh?: boolean } = {}): string {
+ return withQuery("/api/research/coverage", { ...scopeQuery(s), fresh: opts.fresh === true });
}
/** GET /api/research/window: the transcript ±span around a cue. */
diff --git a/umtool/lib/research/parity.test.ts b/umtool/lib/research/parity.test.ts
@@ -152,4 +152,52 @@ test("the inventory: no WORKER_TOKEN, so the local corpus is read on disk, and t
assert.deepEqual(hr.published.missingByYear, { "2024": { deleted: 1 }, "2026": { unlisted: 1 } });
assert.deepEqual(hr.tracks?.["2022"], { transcript: 1, captions: 1, unknown: 0 });
assert.equal(c.rows.find((r) => r.slug === "harbor-radio-rumble")!.held, null);
+ assert.equal(c.held.asked, 4);
+ assert.equal(c.held.cached, false);
+});
+
+test("the held counts are kept five minutes per source and channel; fresh asks again", async () => {
+ let t = Date.now() + 1000;
+ const now = () => t;
+ const kept = await lib.coverage.coverageOf({ source: "" }, { now });
+ assert.equal(kept.held.cached, true);
+ assert.equal(kept.held.asked, 0);
+ const firstAt = kept.held.at;
+ assert.ok(firstAt <= t);
+ // One channel past the memo is asked again; the others stay kept.
+ t += lib.coverage.HELD_TTL_MS;
+ const later = await lib.coverage.coverageOf({ source: "", channels: ["night-desk"] }, { now });
+ assert.equal(later.held.asked, 1);
+ assert.equal(later.held.at, t);
+ const fresh = await lib.coverage.coverageOf({ source: "" }, { fresh: true, now });
+ assert.equal(fresh.held.asked, 4);
+ assert.equal(fresh.rows.find((r) => r.slug === "harbor-radio")!.held?.total, 5);
+});
+
+test("the track census is kept per source and build: it survives a restart, and another build's is stale", async () => {
+ const { censusFile, readCensus, writeCensus } = await import("./census.mjs");
+ const sources = await import("./sources");
+ const handle = `local:${pub}`;
+ const id = await sources.buildIdentity({ handle, kind: "local", label: "Local corpus" });
+ assert.ok(id);
+ // The searches above wrote it for this build.
+ const kept = await readCensus(process.env.REPORTS_DIR!, handle, id!);
+ assert.equal(Object.keys(kept.channels ?? {}).length, 4);
+ // A restart: the process's sources forgotten, the counts read back.
+ (globalThis as { __umtoolResearchSources?: Map<string, unknown> }).__umtoolResearchSources!.clear();
+ const again = await lib.corpus.scopeOf({ source: "" });
+ assert.deepEqual(again.tracks, { transcript: 5, captions: 7, unknown: 0, counted: 4, of: 4 });
+ assert.equal(again.tracksStale, undefined);
+ // Another build's census is not used, and the scope says so.
+ await writeCensus(process.env.REPORTS_DIR!, handle, "an-older-build", kept.channels!, { now: new Date("2026-10-01T00:00:00Z") });
+ (globalThis as { __umtoolResearchSources?: Map<string, unknown> }).__umtoolResearchSources!.clear();
+ const stale = await lib.corpus.scopeOf({ source: "" });
+ assert.equal(stale.tracks, null);
+ assert.match(stale.tracksStale ?? "", /earlier build \(2026-10-01\)/);
+ // The next full search counts again, for this build.
+ await lib.corpus.runSearch({ source: "", query: "the", fresh: true });
+ const recounted = await lib.corpus.scopeOf({ source: "" });
+ assert.equal(recounted.tracks?.counted, 4);
+ assert.equal(recounted.tracksStale, undefined);
+ assert.equal(JSON.parse((await import("node:fs")).readFileSync(censusFile(process.env.REPORTS_DIR!, handle), "utf8")).identity, id);
});
diff --git a/umtool/lib/research/sources.ts b/umtool/lib/research/sources.ts
@@ -1,7 +1,8 @@
import { readdir, readFile, stat } from "node:fs/promises";
import path from "node:path";
import { SourceRegistry, type ShardSource, type SourceSpec } from "yt-dlp-transcript-mcp/research";
-import { REPO_ROOT, SITES_DIR } from "../paths.mjs";
+import { REPO_ROOT, REPORTS_ROOT, SITES_DIR } from "../paths.mjs";
+import { readCensus } from "./census.mjs";
import type { SourceOption } from "./types";
// ---------------------------------------------------------------------------
@@ -113,8 +114,39 @@ export type Opened = {
source: ShardSource;
/** By channel key; only channels a full scan has counted. */
census: Map<string, ChannelCensus>;
+ /** The source's build (buildIdentity); null when it cannot be told, and then nothing is persisted. */
+ identity: string | null;
+ /** A persisted census from another build: not used, and said so. */
+ censusStale: { identity: string; updatedAt: string } | null;
};
+const IDENTITY_TIMEOUT_MS = 10_000;
+
+/**
+ * Which BUILD a source is, for the persisted census (census.mjs): a published
+ * site's or a hub's corpus.json `generatedAt`; for the local dir that and the
+ * file's mtime and size (a recomposed export/public changes both). Null when
+ * it cannot be told -- then the census is counted but not kept.
+ */
+export async function buildIdentity(option: SourceOption): Promise<string | null> {
+ if (option.kind === "local") {
+ const file = path.join(/* turbopackIgnore: true */ option.handle.slice("local:".length), "corpus.json");
+ const st = await stat(/* turbopackIgnore: true */ file).catch(() => null);
+ if (!st) return null;
+ const corpus = await readJson<{ generatedAt?: unknown }>(file);
+ return `${typeof corpus?.generatedAt === "string" ? corpus.generatedAt : "-"}|${st.mtimeMs}|${st.size}`;
+ }
+ const url = option.handle.replace(/^(remote|hub):/, "").replace(/#.*$/, "");
+ try {
+ const res = await fetch(`${url}/corpus.json`, { signal: AbortSignal.timeout(IDENTITY_TIMEOUT_MS) });
+ if (!res.ok) return null;
+ const j = (await res.json()) as { generatedAt?: unknown };
+ return typeof j.generatedAt === "string" && j.generatedAt ? j.generatedAt : null;
+ } catch {
+ return null;
+ }
+}
+
type Entry = { opened: Opened; stamp: string; at: number };
const g = globalThis as { __umtoolResearchSources?: Map<string, Entry> };
const cache = (g.__umtoolResearchSources ??= new Map());
@@ -148,7 +180,16 @@ export async function openSource(handle: string | null | undefined): Promise<Ope
} catch (e) {
throw new SourceError(`${option.label} cannot be read: ${(e as Error).message}`, 502);
}
- const opened: Opened = { option, source, census: new Map() };
+ // What a search counted for this source before, when it was this build.
+ const identity = await buildIdentity(option);
+ const census = new Map<string, ChannelCensus>();
+ let censusStale: Opened["censusStale"] = null;
+ if (identity) {
+ const kept = await readCensus(REPORTS_ROOT, option.handle, identity);
+ for (const [k, c] of Object.entries(kept.channels ?? {})) census.set(k, c as ChannelCensus);
+ if (kept.stale) censusStale = kept.stale;
+ }
+ const opened: Opened = { option, source, census, identity, censusStale };
cache.set(option.handle, { opened, stamp, at: Date.now() });
return opened;
}
diff --git a/umtool/lib/research/types.ts b/umtool/lib/research/types.ts
@@ -61,6 +61,8 @@ export type ScopeSummary = {
last: string | null;
/** Counted only when a search has read the scope's channels whole. */
tracks: TrackCensus | null;
+ /** A kept count from another build of this source: not used, said so. */
+ tracksStale?: string;
/** Curated aliases the source ships (a plain query expands through them). */
aliases: number;
/** Tokens that matched nothing, and other things the filters said. */
@@ -213,6 +215,14 @@ export type CoverageResponse = {
years: string[];
rows: CoverageRow[];
/** Where `held` came from, and why not the editor when it did not. */
- held: { via: "editor" | "disk" | "none"; note?: string };
+ held: {
+ via: "editor" | "disk" | "none";
+ note?: string;
+ /** When the oldest of these held counts was read (ms since the epoch): they are kept 5 minutes. */
+ at: number;
+ /** Every count came from the memo; `asked` channels were read this time. */
+ cached: boolean;
+ asked: number;
+ };
gapDays: number;
};