Archilyzer · Source

archilyzer

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

commit cbf5620cf16e0e58d526d4abe71d2c07587aebd9
parent 586fe504ffbcea9ed803da2bc5d54061f8dc0290
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon, 26 Oct 2026 07:30:49 -0400

Reports: a job that adds items refreshes its channel's report as they land (ctx.itemLanded, makeLandedThrottle); transcribe-bucket regenerates a report behind the disk before it answers

An archive.org import, an attach of local media and a persist ask for the
channel's report on the first item at once, then at least every 10 items or
2 minutes, through the refresh-report queue; the lanes read their work from
it (readChannelSnapshotShared re-reads on mtime), so imports are transcribed
while the import still runs.

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

Diffstat:
MOPERATING.md | 4+++-
Mcommon/controller/attachMedia.ts | 4++++
Mcommon/controller/persistVideos.ts | 5+++++
Mcommon/jobs/snapshotScheduler.test.ts | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/snapshotScheduler.ts | 70++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/streamCommand.ts | 11+++++++++++
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/transcribe-bucket/route.test.ts | 68++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/transcribe-bucket/route.ts | 49+++++++++++++++++++++++++++++++++++++++++++++++--
Meditor/app/channels/[slug]/attachMediaActions.ts | 1+
Meditor/app/channels/[slug]/persistActions.ts | 1+
Meditor/app/channels/[slug]/pipelineActions.ts | 7++++++-
12 files changed, 289 insertions(+), 4 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -355,7 +355,9 @@ pnpm ops transcribe --json '{"path":"/abs/clip.mp4","start":120,"end":150 off disk (the MCP's `get_transcript` does the same through the editor), and `pnpm ops build-cues --json '{"slug":"<slug>","ids":["<videoId>"]}' --wait` writes its `transcript.cues.json`. - The transcription lane takes every channel's downloaded, untranscribed audio; `transcribe-bucket` runs one - channel's now. + channel's now. Both read the channel's report: a job that adds items (an import, an attach, a persist, a download) + regenerates it as they land, and `transcribe-bucket` regenerates a report that is behind the disk before it + answers. - `transcribe` runs one local file (or a window of it) through the corpus's own engine and model; the result JSON (cues, text, and with `"words": true` the word timings parakeet keeps) is printed on stdout with `--wait`. `"out"` writes it to a file outside the corpus. diff --git a/common/controller/attachMedia.ts b/common/controller/attachMedia.ts @@ -254,6 +254,9 @@ export type AttachMediaOptions = { fillDates?: boolean; dryRun?: boolean; onLog: (line: string) => void; + // A video's media landed (its record new or held): the job's itemLanded, + // so the channel's report — and the lanes reading it — see it at once. + onAttached?: (id: string) => void; signal?: AbortSignal; drainSignal?: AbortSignal; deps?: { @@ -558,6 +561,7 @@ export async function attachMedia(opts: AttachMediaOptions): Promise<AttachMedia onLog(`${id}: the replaced container ${previous.file} removed`); } result.attached.push(id); + opts.onAttached?.(id); onLog(`${id}: attached ${pointer.file} (${formatBytes(pointer.bytes)}, sha256 ${copied.sha256.slice(0, 12)}…)`); } catch (err) { await rm(staging, { force: true }).catch(() => {}); diff --git a/common/controller/persistVideos.ts b/common/controller/persistVideos.ts @@ -332,6 +332,7 @@ export async function persistVideos({ minFreeMemMb = 0, dryRun = false, onLog, + onPersisted, signal, drainSignal, deps: depsOverride, @@ -348,6 +349,9 @@ export async function persistVideos({ minFreeMemMb?: number; dryRun?: boolean; onLog?: (line: string) => void; + // A video persisted (its record may be new): the job's itemLanded, so the + // channel's report sees it while the run goes on. + onPersisted?: (item: { slug: string; id: string }) => void; signal?: AbortSignal; drainSignal?: AbortSignal; deps?: Partial<PersistVideosDeps>; @@ -519,6 +523,7 @@ export async function persistVideos({ result.replaced.push({ slug: p.slug, id: p.id }); } result.persisted.push({ slug: p.slug, id: p.id }); + onPersisted?.({ slug: p.slug, id: p.id }); } log( diff --git a/common/jobs/snapshotScheduler.test.ts b/common/jobs/snapshotScheduler.test.ts @@ -183,3 +183,75 @@ test("a failed walk is a failure with its sentence, for the click that found it release(); } }); + +// NEW ITEMS ARE VISIBLE TO THE LANES AT ONCE (2026-10-26): an import that adds +// items asks for its channel's report as they land, not only when it ends. +test("the landed throttle: the first item at once, then every N items or M ms, a waiting one flushed by its timer", async () => { + const { makeLandedThrottle } = await import("./snapshotScheduler"); + let now = 0; + const timers: { fn: () => void; at: number; cleared: boolean }[] = []; + let asks = 0; + const t = makeLandedThrottle(() => asks++, { + everyItems: 3, + everyMs: 1000, + now: () => now, + setTimer: (fn, ms) => { + const timer = { fn, at: now + ms, cleared: false }; + timers.push(timer); + return { clear: () => (timer.cleared = true) }; + }, + }); + t.note(); + assert.equal(asks, 1, "the first item asks at once"); + now = 100; + t.note(); + t.note(); + assert.equal(asks, 1, "two more, inside the window: waiting"); + t.note(); + assert.equal(asks, 2, "the third since the last ask asks"); + now = 200; + t.note(); + assert.equal(asks, 2); + const pending = timers.filter((x) => !x.cleared).at(-1)!; + assert.equal(pending.at, 100 + 1000, "flushed M ms after the last ask"); + now = pending.at; + pending.fn(); + assert.equal(asks, 3, "the waiting item is flushed by the timer"); + now = 5000; + t.note(); + assert.equal(asks, 4, "an item past the window asks at once"); + t.note(); + t.stop(); + for (const x of timers.filter((y) => !y.cleared)) x.fn(); + assert.equal(asks, 4, "nothing after stop: the job's end asks for the rest"); +}); + +test("a job's itemLanded asks for its channel's report while it runs; the regenerated report is what the lanes read next", async () => { + const { runManagedFunction } = await import("./streamCommand"); + const { readChannelSnapshotShared } = await import("../controller/channels"); + const { flushChannelSnapshotsNow } = await import("./snapshotScheduler"); + const paths = getPaths(); + let release!: () => void; + const held = new Promise<void>((r) => (release = r)); + let landedAt = 0; + const job = await runManagedFunction({ + kind: "import-archive-org-test", + queueKey: `test-landed:${newJobId()}`, + paths, + channelSlug: "gamma", + fn: async (_onLog, _signal, _progress, ctx) => { + ctx.itemLanded(); + landedAt = Date.now(); + await held; + }, + }); + assert.ok(job.ok); + while (!landedAt) await new Promise((r) => setTimeout(r, 5)); + await flushChannelSnapshotsNow(); + const snap = await readChannelSnapshotShared(paths, "gamma"); + assert.ok(snap, "the report was written while the job still runs"); + assert.ok(Date.parse(snap.generatedAt) >= landedAt - 1000); + assert.equal(getRegistry().get(job.jobId)?.status, "running"); + release(); + await job.done; +}); diff --git a/common/jobs/snapshotScheduler.ts b/common/jobs/snapshotScheduler.ts @@ -136,6 +136,76 @@ function resolveWindow(): { debounceMs: number; maxWaitMs: number | null } { } } +// NEW ITEMS ARE VISIBLE TO THE LANES AT ONCE (2026-10-26). A job that ADDS +// items to a channel — an archive.org import, an attach with new records, a +// chat backlog — and does not report per-item tasks (whose end already asks +// for a regeneration, ctx.recordTaskDone) refreshed the channel's report only +// when it ENDED. On 2026-10-26 an import-archive-org added 64 items over +// hours while the report kept the 32 it had at 01:10: the transcription lane +// and `transcribe-bucket` read their work out of the report, so 64 imports sat +// untranscribed and the GPU went to another site's backlog. +// +// `ctx.itemLanded()` (streamCommand.ts) feeds this: the FIRST item asks for a +// regeneration at once, then at least every `everyItems` items or `everyMs` +// after the last ask, whichever comes first — a timer flushes an item still +// waiting when no further one arrives. Every ask goes through +// requestChannelSnapshot, so it is debounced, deduped and run on the one +// refresh-report queue like every other. `stop()` at the job's end (whose own +// ask covers what is left). +export const LANDED_REFRESH_EVERY_ITEMS = 10; +export const LANDED_REFRESH_EVERY_MS = 2 * 60 * 1000; + +export type LandedThrottle = { note: () => void; stop: () => void }; + +export function makeLandedThrottle( + ask: () => void, + opts: { + everyItems?: number; + everyMs?: number; + now?: () => number; + setTimer?: (fn: () => void, ms: number) => { clear: () => void }; + } = {}, +): LandedThrottle { + const everyItems = opts.everyItems ?? LANDED_REFRESH_EVERY_ITEMS; + const everyMs = opts.everyMs ?? LANDED_REFRESH_EVERY_MS; + const now = opts.now ?? Date.now; + const setTimer = + opts.setTimer ?? + ((fn: () => void, ms: number) => { + const t = setTimeout(fn, ms); + t.unref?.(); + return { clear: () => clearTimeout(t) }; + }); + let lastAskAt: number | null = null; + let pending = 0; + let timer: { clear: () => void } | null = null; + let stopped = false; + const flush = () => { + timer?.clear(); + timer = null; + if (stopped || pending === 0) return; + pending = 0; + lastAskAt = now(); + ask(); + }; + return { + note() { + if (stopped) return; + pending++; + if (lastAskAt === null || pending >= everyItems || now() - lastAskAt >= everyMs) { + flush(); + return; + } + if (!timer) timer = setTimer(flush, Math.max(0, lastAskAt + everyMs - now())); + }, + stop() { + stopped = true; + timer?.clear(); + timer = null; + }, + }; +} + // Mark a channel's report dirty and (re)arm the global debounce timer. // Synchronous and non-throwing — safe to call from job completion handlers and // request-scoped server actions without awaiting or try/catch. diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -14,6 +14,7 @@ import { import type { Paths } from "../lib/paths"; import { makeSafeController } from "../lib/safeStreamController"; import { + makeLandedThrottle, requestChannelSnapshot, shouldRequestSnapshot, } from "./snapshotScheduler"; @@ -113,6 +114,13 @@ export type JobRunContext = { ) => void; removeTask: (taskId: string) => void; recordTaskDone: (durationMs: number, audioSeconds?: number) => void; + // AN ITEM THIS JOB ADDED TO ITS CHANNEL landed (an imported file, a new + // record, a fetched chat): the channel's report is regenerated for the first + // one at once and then at least every few items or minutes, so the lanes + // and `transcribe-bucket` see new work while the job is still running + // (snapshotScheduler.ts makeLandedThrottle). A job that reports per-item + // tasks (recordTaskDone) need not call it: each task's end already asks. + itemLanded: () => void; // This job's work goes on in another job (`jobId`), which this one queued: // recorded on the record and its sidecar as `handedOffTo`, so a caller // waiting for the work follows it there. @@ -476,6 +484,7 @@ export async function runManagedFunction( noteProgress(record, snap); }; + const landed = makeLandedThrottle(() => requestSnapshotOnFinish(id, opts)); const ctx: JobRunContext = { jobId: id, drainSignal: drain.signal, @@ -490,6 +499,7 @@ export async function runManagedFunction( // coalesces sub-operations that finish close together. requestSnapshotOnFinish(id, opts); }, + itemLanded: () => landed.note(), handOff: (jobId) => { record.handedOffTo = jobId; persistMeta(); @@ -594,6 +604,7 @@ export async function runManagedFunction( fileStream.end(() => resolve()); }); safe.safeClose(); + landed.stop(); requestSnapshotOnFinish(id, opts); // Persist terminal state (status/endedAt/exitCode now set by finalize). persistMeta(); diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **What an import adds is work for the lanes at once, not when the import ends.** On 2026-10-26 an archive.org import added 64 recordings over several hours while the channel's report still listed the 32 it had at 01:10; the transcription lane reads its work from that report, so the 64 waited untranscribed and the GPU went to another site's backlog, and `pnpm ops transcribe-bucket` answered "64 of ids not in the downloadedNoTranscript bucket". An archive.org import, an attach of local media and a persist now regenerate the channel's report as items land (the first at once, then at least every 10 items or 2 minutes), and `transcribe-bucket` regenerates a report that is behind the disk before it answers. Needs a restart of the editor. - **A restart no longer kills the long jobs it interrupts: they resume.** On 2026-10-25/26 one restart stopped an archive.org import (89 files), a feed download-missing (28 episodes) and a forum catch-up, each closed "interrupted" and re-queued by hand. At boot the editor now re-queues every job the previous process left running whose kind continues on a re-run — an archive.org import, an import, a download-missing, a posts fetch, a persist, a clip-window fetch, a transcription batch, a post capture, a cues pass, a report — and its log opens with the job it resumes. A job interrupted twice in a row, a dry run and a full posts re-walk are not resumed, and the old job says why. `pnpm ops job resume-interrupted [--dry-run]` does the same by hand; `jobs.resumeInterruptedOnBoot: false` turns the boot's resume off, and an idle boot never resumes. A job that waited in its queue and then died mid-run is now closed as interrupted too, instead of being re-queued as if it had never started. An archive.org import, a single import and a cues pass gained Retry. Needs a restart of the editor. - **A new caption download is ready for a umtool build the moment it lands.** A YouTube video whose captions were downloaded (the-quartering, 2026-10-23/24) had its `transcript.en-orig.vtt` but no `transcript.cues.json` — only a transcription wrote one, and every older video got its file from the normalize pass — so umtool refused it ("clip-no-cues") until `pnpm ops build-cues` was run by hand. Every successful download, and the Download missing subs pass, now writes the cues file the normalize pass would. Needs a restart of the editor. - **An interrupted catch-up no longer sends a finished forum thread back through its whole history.** When an editor restart cut a thread's catch-up short, the next run saw the page the catch-up still owed as a hole in the history, marked the history unfinished and re-read every held page below it (on 2026-10-26 it re-read 150 pages of the Ethan Klein thread before it was stopped; left alone, every sync would have gone on doing it). The page an unfinished catch-up owes is now its own, and the history stays complete. Needs a restart of the editor. diff --git a/editor/app/api/ops/transcribe-bucket/route.test.ts b/editor/app/api/ops/transcribe-bucket/route.test.ts @@ -0,0 +1,68 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/transcribe-bucket/route.test.ts" +// +// A REPORT BEHIND THE DISK IS REGENERATED FIRST (2026-10-26): 64 archive.org +// imports sat untranscribed because the channel's report predated them, and +// `transcribe-bucket` answered "N of ids not in the downloadedNoTranscript +// bucket". The route now regenerates the report once and reads the bucket +// again. The job it starts waits behind a held queue and is cancelled: nothing +// is transcribed. + +const corpus = await setupOpsCorpus(null); +await corpus.writeSettings(); +await corpus.writeChannelConfig("demo-audio", { handling: "transcribe", url: "https://archive.org/details/demo" }); +const CHANNEL = path.join(corpus.transcripts, "channels", "demo-audio"); +// A report from before the import: no videos at all. +await writeFile( + path.join(CHANNEL, "snapshot.json"), + JSON.stringify({ generatedAt: "2026-10-26T01:10:00.000Z", totals: { videos: 0 }, buckets: { downloadedNoTranscript: [] } }), +); +// What the import landed since. +const dir = path.join(CHANNEL, "data", "imported0001"); +await mkdir(dir, { recursive: true }); +await writeFile( + path.join(dir, "metadata.info.json"), + JSON.stringify({ id: "imported0001", title: "Episode 1", upload_date: "20200101", duration: 60 }), +); +await writeFile(path.join(dir, "audio.mp3"), Buffer.alloc(4096, 1)); + +const { POST } = await import("./route"); +const { getRegistry, newJobId } = await import("yt-dlp-transcript-common/jobs/registry"); +test.after(() => corpus.cleanup()); + +test("ids the stale report does not hold: the report is regenerated, and the job starts", async () => { + const registry = getRegistry(); + const queueKey = `test-hold-${newJobId()}`; + const holder = { + id: newJobId(), + kind: "test-holder", + queueKey, + status: "queued" as const, + queuedAt: Date.now(), + logPath: "/dev/null", + }; + registry.register(holder); + registry.enqueue(holder, { start: () => {}, onCancel: () => {} }); + try { + const res = await callPost(POST, { slug: "demo-audio", ids: ["imported0001"], queueKey }); + assert.equal(res.status, 200, JSON.stringify(res.body)); + const jobId = String(res.body.jobId); + assert.equal(registry.get(jobId)?.kind, "whisper-bucket-downloaded-no-transcript"); + assert.deepEqual(registry.get(jobId)?.spec?.params?.ids, ["imported0001"], "an ad-hoc selection replays as its ids"); + registry.cancel(jobId); + } finally { + registry.finalize(holder.id, "done"); + } +}); + +test("an id no report holds is still refused, after the one regeneration", async () => { + const res = await callPost(POST, { slug: "demo-audio", ids: ["notavideo01"] }); + assert.equal(res.status, 400); + assert.match(String(res.body.error), /1 of "ids" not in the "downloadedNoTranscript" bucket of demo-audio: notavideo01/); +}); diff --git a/editor/app/api/ops/transcribe-bucket/route.ts b/editor/app/api/ops/transcribe-bucket/route.ts @@ -1,5 +1,10 @@ import { getPaths } from "yt-dlp-transcript-common/lib/paths"; -import { readChannelSnapshot } from "yt-dlp-transcript-common/controller/channels"; +import { channelExists, readChannelSnapshot } from "yt-dlp-transcript-common/controller/channels"; +import { + refreshReportWaitNotice, + requestRefreshReport, + waitForRefreshReport, +} from "yt-dlp-transcript-common/jobs/snapshotScheduler"; import { AUDIO_FORMAT_VALUES } from "yt-dlp-transcript-common/lib/channelConfig"; import { transcribeBucketAction } from "../../../channels/[slug]/whisperActions"; import { @@ -7,6 +12,7 @@ import { OpsInputError, oneOf, ops, + opsFail, optBool, optString, optSubset, @@ -26,19 +32,58 @@ export const dynamic = "force-dynamic"; // `ids` NARROWS THE BUCKET, it never widens it (optSubset). With `ids` the job // carries no bucket key and replays as those ids (a re-run skips the ones // transcribed since). +// +// A REPORT BEHIND THE DISK IS REGENERATED FIRST, once (2026-10-26). The bucket +// is the report's, and a report written before an import landed says "No +// video ids supplied" (an empty bucket) or "64 of ids not in the bucket" for +// audio that is right there. When the bucket is empty, or `ids` names videos +// outside it, the route asks for the channel's report on the refresh-report +// queue, waits for it (REGEN_WAIT_MS), and reads the bucket again; a report +// still regenerating when the wait runs out is said, with its job id. +const REGEN_WAIT_MS = 90_000; + +function bucketMisses(bucketIds: readonly string[], ids: unknown): boolean { + if (bucketIds.length === 0) return true; + if (!Array.isArray(ids)) return false; + const known = new Set(bucketIds); + return ids.some((id) => typeof id === "string" && !known.has(id)); +} + export async function POST(request: Request) { return ops( request, ["slug", "ids", "queueKey", "audioFormat", "strictAudioFormat"], async (body) => { const slug = reqSlug(body, "slug"); - const snapshot = await readChannelSnapshot(getPaths(), slug); + const paths = getPaths(); + let snapshot = await readChannelSnapshot(paths, slug); + if (bucketMisses(snapshot?.buckets.downloadedNoTranscript ?? [], body.ids) && (await channelExists(paths, slug))) { + const asked = await requestRefreshReport(paths, slug); + if (asked.ok) { + const wait = await waitForRefreshReport(paths, asked.jobId, { timeoutMs: REGEN_WAIT_MS }); + if (wait.state === "waiting") { + throw new OpsInputError( + `${slug}'s report is behind what is on disk and is being regenerated: ${refreshReportWaitNotice(wait)} ` + + "Ask again when it ends.", + ); + } + if (wait.state === "failed") throw new OpsInputError(`${slug}'s report could not be regenerated: ${wait.error}`); + snapshot = await readChannelSnapshot(paths, slug); + } + } if (!snapshot) { throw new OpsInputError( `Channel "${slug}" has no report yet — run /api/ops/refresh-report first.`, ); } const bucketIds = snapshot.buckets.downloadedNoTranscript ?? []; + if (bucketIds.length === 0) { + return opsFail( + `Nothing to transcribe on ${slug}: its report, read again from disk, holds no downloaded, untranscribed audio.`, + 400, + { info: true }, + ); + } const subset = optSubset( body, "ids", diff --git a/editor/app/channels/[slug]/attachMediaActions.ts b/editor/app/channels/[slug]/attachMediaActions.ts @@ -73,6 +73,7 @@ export async function attachMediaAction( ...(opts.fillDates ? { fillDates: true } : {}), ...(opts.dryRun ? { dryRun: true } : {}), onLog, + onAttached: () => ctx.itemLanded(), signal, drainSignal: ctx.drainSignal, }); diff --git a/editor/app/channels/[slug]/persistActions.ts b/editor/app/channels/[slug]/persistActions.ts @@ -115,6 +115,7 @@ export async function persistChannelVideosAction( gapMs, minFreeMemMb, onLog, + onPersisted: () => ctx.itemLanded(), signal, drainSignal: ctx.drainSignal, }); diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts @@ -917,7 +917,12 @@ export async function importArchiveOrgAction( drainSignal: ctx.drainSignal, dryRun: opts.dryRun, deps: { - onImported: (id) => safeRevalidate([`/channels/${slug}/videos/${id}`]), + onImported: (id) => { + safeRevalidate([`/channels/${slug}/videos/${id}`]); + // The channel's report (and the lanes reading it) see each file + // as it lands, not hours later when the import ends (2026-10-26). + ctx.itemLanded(); + }, }, }); const summary = summarizeArchiveOrgBatch(batch);