Archilyzer · Source

archilyzer

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

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

Jobs: a restart resumes the jobs it interrupted whose kind continues on a re-run (resumeOnBoot, jobs/resumeInterrupted.ts); pnpm ops job resume-interrupted [--dry-run]; a started job's meta says running

- jobKinds: resumeOnBoot on import-archive-org, import-one, download-missing,
  fetch-posts, persist-videos, fetch-windows, whisper-all / whisper-bucket-*,
  capture-posts, normalize-transcripts and refresh-report (now registered).
- import-archive-org, import-one, normalize-transcripts and refresh-report
  carry a JobSpec and a replay handler; an ad-hoc transcribe-bucket selection
  replays as its ids.
- The resume chain rides an async context into makeJob (jobs/resumeTag.ts),
  so a job interrupted twice in a row is not resumed again.
- settings.jobs.resumeInterruptedOnBoot (default true); SETTINGS.md and
  settings.json.example regenerated.

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

Diffstat:
MOPERATING.md | 19+++++++++++++++++++
MSETTINGS.md | 19+++++++++++++++++++
Mcommon/jobs/bootQueuedJobs.ts | 15++++++++++-----
Mcommon/jobs/jobKinds.ts | 62++++++++++++++++++++++++++++++++++++++++++++++++++------------
Mcommon/jobs/jobMeta.ts | 17+++++++++++++++++
Mcommon/jobs/registry.ts | 9+++++++++
Acommon/jobs/resumeInterrupted.test.ts | 237+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/resumeInterrupted.ts | 250+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acommon/jobs/resumeTag.ts | 47+++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/jobs/snapshotScheduler.ts | 3+++
Mcommon/jobs/streamCommand.test.ts | 36++++++++++++++++++++++++++++++++++++
Mcommon/jobs/streamCommand.ts | 24++++++++++++++++++++++++
Acommon/lib/jobsSettings.ts | 33+++++++++++++++++++++++++++++++++
Mcommon/lib/settingsDocs.ts | 8++++++++
Mcommon/lib/settingsSchema.test.ts | 6+++++-
Mcommon/lib/settingsSchema.ts | 5+++++
Meditor/CHANGELOG.md | 1+
Meditor/app/api/ops/job/route.test.ts | 27+++++++++++++++++++++++++++
Meditor/app/api/ops/job/route.ts | 63++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-----
Meditor/app/api/ops/transcribe-bucket/route.ts | 3++-
Meditor/app/channels/[slug]/normalizeActions.ts | 12++++++++++++
Meditor/app/channels/[slug]/pipelineActions.ts | 20++++++++++++++++++++
Meditor/app/channels/[slug]/whisperActions.ts | 14+++++++++++---
Meditor/app/jobs/jobReplayRegistry.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/instrumentation.ts | 66++++++++++++++++++++++++++++++++++++++++++++++++++----------------
Mscripts/archilyzer-ops.mjs | 26+++++++++++++++++++++++++-
Mscripts/archilyzer-ops.test.mjs | 14++++++++++++++
Msettings.json.example | 3+++
28 files changed, 1052 insertions(+), 44 deletions(-)

diff --git a/OPERATING.md b/OPERATING.md @@ -18,6 +18,25 @@ Recipes for running an archive from a shell or an agent. Every command named her - Every fetch goes through the editor (paced per platform, cookie-aware, provenanced). Never run yt-dlp, whisper or parakeet by hand, and never edit `transcripts/**` by hand: each file has one writer, named below. +### When the editor restarts + +```sh +pnpm ops job resume-interrupted --dry-run +pnpm ops job resume-interrupted +``` + +- A job that was waiting in its queue is re-queued at boot (never a sync: the scheduler re-derives those). +- A job that was RUNNING is closed "interrupted" and, when its kind continues on a re-run, resumed: 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, a chat backlog (`resumeOnBoot` in `common/jobs/jobKinds.ts`). Its log + opens with `[resume] Resumes … job <id>`, and the old job's says which job resumed it. +- Not resumed, each with its reason on the old job: a kind that does not continue (Retry is one click), a job + interrupted twice in a row, a dry run, a full posts re-walk (`"full": true` starts over), one superseded by a + newer job with the same request, one whose re-queue was refused (a held platform). +- `jobs.resumeInterruptedOnBoot: false` turns the boot's resume off; an idle boot (`ARCHILYZER_IDLE_BOOT=1`) never + resumes. `pnpm ops job resume-interrupted` does it by hand over the last 24 hours (or the ids named); + `--dry-run` lists `wouldResume` and `notResumed` and changes nothing. + ## Add a channel ```sh diff --git a/SETTINGS.md b/SETTINGS.md @@ -54,6 +54,7 @@ A copied example PINS every default it spells — including each lane's `autoQue | [`tts`](#tts) | object — see below | | [`generation`](#generation) | object — see below | | [`clips`](#clips) | object — see below | +| [`jobs`](#jobs) | object — see below | ## `adminTitle` @@ -1240,3 +1241,21 @@ Default: ] } ``` + +## `jobs` + +What the job system does on its own across a restart: whether the jobs the previous process left interrupted are resumed at boot (common/jobs/resumeInterrupted.ts). See JobsSettings. + +#### `jobs` + +| Key | Default | Description | +|---|---|---| +| `resumeInterruptedOnBoot` | `true` | When the editor starts, re-queue the jobs the previous process left RUNNING (closed "interrupted") whose kind resumes on a re-run — it skips what the first run finished: an archive.org import, a download-missing, a posts fetch, a persist, a clip-window fetch, a transcription batch, a post capture, a cues pass, a report, a chat backlog (`resumeOnBoot` in common/jobs/jobKinds.ts). Each resumed job's log says which job it resumes. A job interrupted twice in a row is not resumed again, a dry run or a full re-walk never is, and an idle boot (ARCHILYZER_IDLE_BOOT) resumes nothing. `pnpm ops job resume-interrupted [--dry-run]` does the same by hand. Default true. | + +Default: + +```json +{ + "resumeInterruptedOnBoot": true +} +``` diff --git a/common/jobs/bootQueuedJobs.ts b/common/jobs/bootQueuedJobs.ts @@ -39,9 +39,12 @@ import { isPublishStageJobKind } from "./jobKinds"; // writer is gone (`writerIsGone`: another live process — `archilyzer run` — // writes into the same `.jobs/`) are touched: the storage boot pass can // enqueue a job of its own while this runs. `running` metas are not re-queued -// — whether a job that was mid-flight should be re-run is not a decision a -// boot pass can make — but they are CLOSED, by the second pass below -// (`settleRunningJobMetas`, release 17 slice D0). A malformed meta +// here; they are CLOSED, by the second pass below (`settleRunningJobMetas`, +// release 17 slice D0), and the resume pass (jobs/resumeInterrupted.ts, +// 2026-10-26) re-queues the ones whose kind continues on a re-run. A meta is +// rewritten `running` when its job starts (streamCommand.ts openJobLog), so a +// job that waited in its queue and then died mid-run is no longer read here +// as one that never started. A malformed meta // (readJobMeta → null) is skipped. // // Best-effort throughout: a meta that cannot be read or written is skipped, @@ -400,8 +403,10 @@ async function closeMeta( // read `running`. // // Each is CLOSED as the queued pass closes one — `cancelled`, with -// INTERRUPTED_REASON — never re-run (whether a half-finished job should run -// again is the operator's call; Retry is one click). There is no separate +// INTERRUPTED_REASON. This pass re-runs nothing: the resume pass +// (jobs/resumeInterrupted.ts) re-queues the ones whose kind declares +// `resumeOnBoot` — a re-run continues them — and every other one is the +// operator's call (Retry is one click). There is no separate // `interrupted` status: `cancelled` + `cancelReason` is the terminal state this // file already writes for "the server went down under it", and every reader of // a meta (listJobs, /jobs, Retry) already handles it. `endedAt` is the job diff --git a/common/jobs/jobKinds.ts b/common/jobs/jobKinds.ts @@ -48,8 +48,8 @@ export type JobKindMeta = { // // ABSENT MEANS FALSE, and that is deliberate rather than lazy. The guard is // opt-in so a kind that is not listed keeps exactly its current behavior, and - // so that `refresh-report` — which is not in this table at all — still runs - // and lets the snapshot generator itself report the reason it refused. A kind + // so that `refresh-report` — which declares neither — still runs and lets + // the snapshot generator itself report the reason it refused. A kind // that genuinely never opens a video dir (store playlist, clear markers) must // not be refused for a drive it does not read. // @@ -85,6 +85,17 @@ export type JobKindMeta = { // a platform queue says which it is — jobKinds.test.ts holds that, so a new // platform kind cannot slip in unpaced. network?: boolean; + // Whether a job of this kind that a restart INTERRUPTED is re-queued when + // the editor starts again (jobs/resumeInterrupted.ts, 2026-10-26). Only a + // kind that is replayable AND resumes on a re-run — it skips what the first + // run finished (what is held, imported, fetched, transcribed or captured), + // so running it again continues it rather than repeating it. Never a + // one-shot, a destructive or a move kind: whether one of those should run + // twice is not a decision a boot can make. Absent means false; the boot pass + // says each one it resumes in the resumed job's log, refuses a job + // interrupted twice in a row, and is off with `jobs.resumeInterruptedOnBoot` + // or on an idle boot. + resumeOnBoot?: boolean; }; // One entry per kind known to the system. `label` is included only where the @@ -172,6 +183,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "custom", needsMedia: true, + resumeOnBoot: true, }, "whisper-bucket-downloaded-no-transcript": { kind: "whisper-bucket-downloaded-no-transcript", @@ -180,6 +192,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "custom", needsMedia: true, + resumeOnBoot: true, }, // Replace-auto-captions lane, transcribe half: whisper over videos whose only // transcript is a YouTube ASR VTT (the downloadedAutoSubsOnly bucket). Same @@ -192,6 +205,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "custom", needsMedia: true, + resumeOnBoot: true, }, // Delete the superseded English ASR VTTs kept as backups next to a finished // whisper transcript. Manual only — never auto-queued — and the single @@ -251,9 +265,10 @@ const JOB_KINDS: Record<string, JobKindMeta> = { // // Not drainable: the walk honours the cancel signal (which is what stops it) // but has no drain-aware inner loop, and the unit of work is a single file - // write, so "let the in-flight one finish" is already how it behaves. Not - // replayable either — that would need a JobSpec and a jobReplayRegistry - // handler, and the button is one click from the card that reports the count. + // write, so "let the in-flight one finish" is already how it behaves. The + // per-channel pass is replayable (2026-10-26: its spec is the ids and + // `force`) and resumed after a restart — a re-run leaves every fresh + // cues.json alone. The corpus-wide pass on /sites carries no spec. // needsText (release 17; needsMedia before it): it walks `data/<id>/` for // every video and writes a sidecar into each — text, on the corpus disk. // Against an unreadable text tier (a `legacy` channel whose drive is @@ -263,10 +278,11 @@ const JOB_KINDS: Record<string, JobKindMeta> = { kind: "normalize-transcripts", label: "Normalize transcripts", drainable: false, - replayable: false, + replayable: true, queueKeyStrategy: "custom", needsMedia: false, needsText: true, + resumeOnBoot: true, }, "redownload-incomplete-bucket": { kind: "redownload-incomplete-bucket", @@ -294,6 +310,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "platform", network: true, needsMedia: true, + resumeOnBoot: true, }, "download-missing-subs": { kind: "download-missing-subs", @@ -309,23 +326,26 @@ const JOB_KINDS: Record<string, JobKindMeta> = { kind: "import-one", label: "Import video", drainable: false, - replayable: false, + replayable: true, queueKeyStrategy: "custom", network: true, needsMedia: true, + resumeOnBoot: true, }, // CHOSEN FILES OF ONE archive.org ITEM, imported one at a time on // archive.org's own queue (controller/archiveOrgImport.ts). Drainable: a // drain lets the file in flight finish and starts no more; re-running the - // same command resumes, skipping what landed. + // same command resumes, skipping what landed — so it is replayable (its spec + // is the request) and resumed after a restart (2026-10-26). "import-archive-org": { kind: "import-archive-org", label: "Import from archive.org", drainable: true, - replayable: false, + replayable: true, queueKeyStrategy: "platform", network: true, needsMedia: true, + resumeOnBoot: true, }, // AN ODYSEE OR BITCHUTE CHANNEL'S LISTING, diffed against what is held // (release 19 A6, controller/remoteListing.ts): one flat-playlist read on the @@ -375,6 +395,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { network: true, needsMedia: false, needsText: true, + resumeOnBoot: true, }, "redownload-archive": { kind: "redownload-archive", @@ -430,9 +451,9 @@ const JOB_KINDS: Record<string, JobKindMeta> = { needsMedia: true, }, // The corpus-wide corrupt-media scan and its per-channel twin. Registered - // properly, unlike check-availability / refresh-report / detect-duplicates, - // which have no entry here and fall back to their raw machine kind in the UI — - // that absence is a gap, not a pattern worth copying. + // properly, unlike detect-duplicates, which has no entry here and falls back + // to its raw machine kind in the UI — that absence is a gap, not a pattern + // worth copying. "scan-media": { kind: "scan-media", label: "Scan media for corruption", @@ -484,6 +505,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { queueKeyStrategy: "custom", network: true, needsMedia: true, + resumeOnBoot: true, }, "backup-saved-videos": { kind: "backup-saved-videos", @@ -630,6 +652,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "platform", network: true, + resumeOnBoot: true, }, // Forum thread pages the operator saved from a browser, imported into a // forum-thread channel (controller/importForumPages.ts). Offline — nothing is @@ -714,6 +737,7 @@ const JOB_KINDS: Record<string, JobKindMeta> = { replayable: true, queueKeyStrategy: "platform", network: true, + resumeOnBoot: true, }, // A WAYBACK PAGES CHANNEL'S SCAN (release 37 S2, controller/waybackScan.ts): // the CDX listings of its targets into `wayback-scan.json`, no bodies, on @@ -1320,6 +1344,20 @@ const JOB_KINDS: Record<string, JobKindMeta> = { needsMedia: false, needsText: true, }, + // ONE CHANNEL'S REPORT (snapshot.json) regenerated (jobs/snapshotScheduler.ts + // startRefreshReport), on the one refresh-report queue. Registered on + // 2026-10-26 to be replayable and resumed after a restart: a regeneration + // the restart cut short is one more walk, and the lanes read their work from + // what it writes. No label — /jobs has always shown it by its raw kind and + // hides it by default (jobsFilterStorage.ts). Neither guard: the snapshot + // generator reports an unreadable channel itself. + "refresh-report": { + kind: "refresh-report", + drainable: false, + replayable: true, + queueKeyStrategy: "custom", + resumeOnBoot: true, + }, // Replayable kinds that never had a JOB_KIND_LABELS entry: label omitted so // jobKindLabel() keeps falling back to the raw kind (unchanged behavior). "store-playlist": { diff --git a/common/jobs/jobMeta.ts b/common/jobs/jobMeta.ts @@ -37,6 +37,13 @@ export type JobMeta = { pid?: number; // The job this one handed its work on to (JobRecord.handedOffTo). handedOffTo?: string; + // A resume of a job a restart interrupted (JobRecord.resumedFrom, + // resumeCount; jobs/resumeInterrupted.ts). + resumedFrom?: string; + resumeCount?: number; + // On an interrupted job's meta: the job that resumed it. Written only by the + // resume pass, so it is never resumed twice. + resumedAs?: string; }; export function metaPath(paths: Paths, id: string): string { @@ -65,6 +72,8 @@ export async function writeJobMeta( spec: record.spec, pid: process.pid, ...(record.handedOffTo ? { handedOffTo: record.handedOffTo } : {}), + ...(record.resumedFrom ? { resumedFrom: record.resumedFrom } : {}), + ...(record.resumeCount ? { resumeCount: record.resumeCount } : {}), }; await writeFile(metaPath(paths, record.id), JSON.stringify(meta), "utf8"); } catch { @@ -94,6 +103,14 @@ export async function readJobMeta( // can't surface an un-runnable Retry. meta.spec = m.spec === undefined ? undefined : (parseJobSpec(m.spec) ?? undefined); if (m.handedOffTo !== undefined && typeof m.handedOffTo !== "string") delete meta.handedOffTo; + if (m.resumedFrom !== undefined && typeof m.resumedFrom !== "string") delete meta.resumedFrom; + if (m.resumedAs !== undefined && typeof m.resumedAs !== "string") delete meta.resumedAs; + if ( + m.resumeCount !== undefined && + !(typeof m.resumeCount === "number" && Number.isInteger(m.resumeCount) && m.resumeCount > 0) + ) { + delete meta.resumeCount; + } return meta; } catch { return null; diff --git a/common/jobs/registry.ts b/common/jobs/registry.ts @@ -166,6 +166,15 @@ export type JobRecord = { // waits for the work rather than the job follows it (researchRuns.ts // jobOfPaths, `pnpm ops --wait`). handedOffTo?: string; + // THE JOB A RESTART INTERRUPTED THAT THIS ONE RESUMES (jobs/resumeInterrupted.ts, + // 2026-10-26), and how many resumes in a row it is (1 for the first). Set + // only by the boot's resume pass and `pnpm ops job resume-interrupted`; a + // Retry starts a fresh chain. The pass reads `resumeCount` to refuse a job + // interrupted twice in a row. + resumedFrom?: string; + resumeCount?: number; + // The line the job's log opens with when it is a resume (what it resumes). + resumeNote?: string; }; // Store a progress snapshot on the record, stamping `progressAt` only when the diff --git a/common/jobs/resumeInterrupted.test.ts b/common/jobs/resumeInterrupted.test.ts @@ -0,0 +1,237 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import type { Paths } from "../lib/paths"; +import type { JobMeta } from "./jobMeta"; +import type { JobSpec } from "./jobSpec"; +import { INTERRUPTED_REASON, settleRunningJobMetas, type RequeueFn } from "./bootQueuedJobs"; +import { getRegistry } from "./registry"; +import { runManagedFunction } from "./streamCommand"; +import { + MAX_RESUMES_IN_A_ROW, + RESUME_WINDOW_MS, + resumeInterruptedJobs, + resumeSpecFor, +} from "./resumeInterrupted"; + +// Run with: +// pnpm --filter yt-dlp-transcript-common exec tsx --test jobs/resumeInterrupted.test.ts +// +// RESUME WHAT A RESTART INTERRUPTED (2026-10-26), over a temp .jobs dir. A +// kind that declares `resumeOnBoot` is re-queued through the injected re-queue +// (the editor's is runJobSpec), once; everything else is said and left. +// Never run against a real corpus. + +const NOW = 2_000_000_000_000; + +async function fixture(metas: Partial<JobMeta>[]) { + const root = await mkdtemp(path.join(tmpdir(), "resume-interrupted-")); + const jobsDir = path.join(root, ".jobs"); + await mkdir(jobsDir, { recursive: true }); + for (const m of metas) { + const meta = { + queueKey: "platform:archiveorg", + status: "cancelled", + cancelReason: INTERRUPTED_REASON, + queuedAt: NOW - 3_600_000, + endedAt: NOW - 60_000, + ...m, + }; + await writeFile(path.join(jobsDir, `${meta.id}.meta.json`), JSON.stringify(meta)); + } + const paths = { jobsDir } as Paths; + return { + paths, + root, + read: async (id: string) => JSON.parse(await readFile(path.join(jobsDir, `${id}.meta.json`), "utf8")) as JobMeta, + log: (id: string) => readFile(path.join(jobsDir, `${id}.log`), "utf8").catch(() => ""), + }; +} + +function recorder(answer: (spec: JobSpec, n: number) => Awaited<ReturnType<RequeueFn>> = (_s, n) => ({ ok: true, jobId: `NEW${n}` })) { + const calls: JobSpec[] = []; + const requeue: RequeueFn = async (spec) => { + calls.push(spec); + return answer(spec, calls.length); + }; + return { calls, requeue }; +} + +const importSpec: JobSpec = { kind: "import-archive-org", slug: "h3", params: { item: "h3-episodes", match: "\\.mp3$" } }; + +test("an interrupted archive.org import is re-queued once, and its meta says by whom", async () => { + const fx = await fixture([{ id: "A1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec }]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["A1"], now: NOW }); + assert.deepEqual(out, [{ id: "A1", kind: "import-archive-org", channelSlug: "h3", action: "resumed", newId: "NEW1" }]); + assert.deepEqual(calls, [importSpec]); + const meta = await fx.read("A1"); + assert.equal(meta.resumedAs, "NEW1"); + assert.equal(meta.cancelReason, `${INTERRUPTED_REASON}; resumed as NEW1`); + assert.match(await fx.log("A1"), /\[resume\] resumed as NEW1/); + // Never twice: the second pass finds it resumed. + const again = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["A1"], now: NOW }); + assert.deepEqual(again, []); + assert.equal(calls.length, 1); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("the resumed job carries the chain, and its log opens with what it resumes", async () => { + const fx = await fixture([ + { id: "R1", kind: "refresh-report", queueKey: "refresh-report", channelSlug: "h3", spec: { kind: "refresh-report", slug: "h3" } }, + ]); + try { + let newId = ""; + const requeue: RequeueFn = async (spec) => { + const res = await runManagedFunction({ + kind: spec.kind, + queueKey: "test-resume-chain", + paths: fx.paths, + channelSlug: spec.slug, + spec, + fn: async (onLog) => onLog("walked"), + }); + if (!res.ok) return { ok: false, error: res.error }; + newId = res.jobId; + await res.done; + return { ok: true, jobId: res.jobId }; + }; + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["R1"], now: NOW }); + assert.equal(out[0].action, "resumed"); + const record = getRegistry().get(newId); + assert.equal(record?.resumedFrom, "R1"); + assert.equal(record?.resumeCount, 1); + const log = await fx.log(newId); + assert.match(log.split("\n")[0], /^\[resume\] Resumes refresh-report job R1 on h3, interrupted when the process running it stopped: the channel's report is regenerated\.$/); + // On disk too, for the next boot. + for (let i = 0; i < 50; i++) { + const m = await fx.read(newId).catch(() => null); + if (m?.status === "done") { + assert.equal(m.resumedFrom, "R1"); + assert.equal(m.resumeCount, 1); + return; + } + await new Promise((r) => setTimeout(r, 20)); + } + assert.fail("the resumed job's meta never reached done"); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("interrupted twice in a row is not resumed a third time, and says why", async () => { + assert.equal(MAX_RESUMES_IN_A_ROW, 1); + const fx = await fixture([ + { id: "B2", kind: "download-missing", channelSlug: "h3-feed", spec: { kind: "download-missing", slug: "h3-feed" }, resumedFrom: "B1", resumeCount: 1 }, + ]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["B2"], now: NOW }); + assert.equal(calls.length, 0); + assert.equal(out[0].action, "not-resumed"); + assert.equal(out[0].action === "not-resumed" && out[0].category, "repeat"); + const meta = await fx.read("B2"); + assert.match(meta.cancelReason ?? "", /; not resumed: interrupted twice in a row \(it resumed B1 and was interrupted again\) — Retry it by hand$/); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("a kind that does not resume is left exactly as the boot closed it", async () => { + const fx = await fixture([{ id: "C1", kind: "relocate-channel-media", channelSlug: "h3" }]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, ids: ["C1"], now: NOW }); + assert.equal(calls.length, 0); + assert.equal(out[0].action === "not-resumed" && out[0].category, "kind"); + assert.equal((await fx.read("C1")).cancelReason, INTERRUPTED_REASON); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("a dry run lists and changes nothing", async () => { + const fx = await fixture([{ id: "D1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec }]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, dryRun: true, now: NOW }); + assert.deepEqual(out, [{ id: "D1", kind: "import-archive-org", channelSlug: "h3", action: "would-resume" }]); + assert.equal(calls.length, 0); + assert.equal((await fx.read("D1")).cancelReason, INTERRUPTED_REASON); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("by hand: only the last 24 h, and never one superseded by a newer job with the same request", async () => { + const fx = await fixture([ + { id: "E1", kind: "import-archive-org", channelSlug: "h3", spec: importSpec, endedAt: NOW - RESUME_WINDOW_MS - 1 }, + { id: "E2", kind: "fetch-posts", channelSlug: "kf", spec: { kind: "fetch-posts", slug: "kf", params: {} } }, + // Re-queued by hand after the restart. + { id: "E3", kind: "fetch-posts", channelSlug: "kf", status: "done", cancelReason: undefined, queuedAt: NOW - 30_000, spec: { kind: "fetch-posts", slug: "kf", params: {} } }, + ]); + try { + const { calls, requeue } = recorder(); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue, now: NOW }); + assert.equal(calls.length, 0); + assert.deepEqual( + out.map((o) => [o.id, o.action === "not-resumed" ? o.category : o.action]), + [["E2", "superseded"]], + ); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("a refused re-queue is said on the meta, and the by-hand command asks again", async () => { + const fx = await fixture([{ id: "F1", kind: "persist-videos", channelSlug: "h3", spec: { kind: "persist-videos", slug: "h3", params: { ids: ["a"] } } }]); + try { + const refused = recorder(() => ({ ok: false, error: "youtube is held" })); + const out = await resumeInterruptedJobs({ paths: fx.paths, requeue: refused.requeue, ids: ["F1"], now: NOW }); + assert.equal(out[0].action === "not-resumed" && out[0].category, "refused"); + assert.match((await fx.read("F1")).cancelReason ?? "", /not resumed: the re-queue was refused: youtube is held/); + const later = recorder(); + const again = await resumeInterruptedJobs({ paths: fx.paths, requeue: later.requeue, now: NOW }); + assert.equal(again[0].action, "resumed"); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); + +test("resumeSpecFor: a dry run and a full posts re-walk are not resumed; an older walk drops its start date", () => { + assert.ok("skip" in resumeSpecFor({ kind: "import-archive-org", slug: "x", params: { item: "i", dryRun: true } })); + assert.ok("skip" in resumeSpecFor({ kind: "fetch-posts", slug: "x", params: { full: true } })); + assert.deepEqual(resumeSpecFor({ kind: "fetch-posts", slug: "x", params: { older: true, from: "2020-01-01" } }), { + spec: { kind: "fetch-posts", slug: "x", params: { older: true } }, + }); + assert.deepEqual(resumeSpecFor(importSpec), { spec: importSpec }); +}); + +test("the boot's running pass then the resume: what it closed is what it resumes", async () => { + const fx = await fixture([ + { id: "G1", kind: "download-missing", channelSlug: "feed", status: "running", cancelReason: undefined, endedAt: undefined, queuedAt: NOW - 10_000, spec: { kind: "download-missing", slug: "feed" } }, + ]); + try { + const running = await settleRunningJobMetas({ paths: fx.paths, bootedAt: NOW, isProcessAlive: () => false, selfPid: -1 }); + assert.deepEqual(running.interrupted.map((j) => j.id), ["G1"]); + const { calls, requeue } = recorder(); + const lines: string[] = []; + const out = await resumeInterruptedJobs({ + paths: fx.paths, + requeue, + ids: running.interrupted.map((j) => j.id), + prefix: "[boot]", + log: (l) => lines.push(l), + }); + assert.equal(out[0].action, "resumed"); + assert.equal(calls[0].kind, "download-missing"); + assert.deepEqual(lines, ["[boot] resumed download-missing feed: G1 -> NEW1"]); + } finally { + await rm(fx.root, { recursive: true, force: true }); + } +}); diff --git a/common/jobs/resumeInterrupted.ts b/common/jobs/resumeInterrupted.ts @@ -0,0 +1,250 @@ +// RESUME WHAT A RESTART INTERRUPTED (2026-10-26). +// +// The boot pass (bootQueuedJobs.ts settleRunningJobMetas) closes every job a +// dead process left `running` as `cancelled` with INTERRUPTED_REASON, and +// before this nothing ran it again: during the Ethanalyzer archive one restart +// killed an archive.org import (89 files), a feed download-missing (28 +// episodes) and a forum catch-up, and each was re-queued by hand — though each +// kind is BUILT to continue on a re-run (it skips what is held). +// +// This re-queues exactly those: a kind that declares `resumeOnBoot` +// (jobs/jobKinds.ts — replayable, and a re-run continues rather than repeats), +// through the path Retry uses (runJobSpec), on its own queue, each resumed +// job's log opening with what it resumes. It runs from the boot (not on an +// idle boot, not on the e2e test server, not with +// `jobs.resumeInterruptedOnBoot` off) over the jobs THAT boot closed, and by +// hand as `pnpm ops job resume-interrupted [--dry-run]` over the jobs +// interrupted in the last 24 hours. +// +// WHAT IS NOT RESUMED, each said with its reason: +// - a kind that does not resume on a re-run (no `resumeOnBoot`): closed, as +// before — whether a half-finished one-shot should run again is the +// operator's call (Retry is one click); +// - a job with no replay descriptor; +// - a job interrupted TWICE IN A ROW: it was itself a resume +// (`resumeCount` ≥ MAX_RESUMES_IN_A_ROW) and was interrupted again — a job +// that takes the process down with it must not do so on every boot; +// - a dry run (it writes nothing), and a FULL posts re-walk (it starts over +// from the top; a plain fetch is what continues from the saved position); +// - one superseded by a newer job with the same spec (re-queued by hand, or +// resumed already); +// - one whose re-queue the action refused (a held platform, a channel not +// reachable) — by hand later, the same command asks again. +// A job resumed is never resumed twice: its interrupted meta records +// `resumedAs`. + +import path from "node:path"; +import { appendFile, readdir } from "node:fs/promises"; +import { writeFileAtomic } from "../lib/jsonFile-server"; +import type { Paths } from "../lib/paths"; +import { INTERRUPTED_REASON, specKey, type RequeueFn } from "./bootQueuedJobs"; +import { metaPath, readJobMeta, type JobMeta } from "./jobMeta"; +import type { JobSpec } from "./jobSpec"; +import { getJobKind, jobKindLabel } from "./jobKinds"; +import { runWithResumeTag } from "./resumeTag"; + +// One resume per interruption chain: a resumed job that is interrupted again +// is "interrupted twice in a row" and is left for the operator. +export const MAX_RESUMES_IN_A_ROW = 1; + +// How far back the by-hand command looks (the boot looks only at what it just +// closed). +export const RESUME_WINDOW_MS = 24 * 60 * 60 * 1000; + +export type ResumeCategory = "kind" | "no-spec" | "repeat" | "not-resumable" | "superseded" | "refused"; + +export type ResumeOutcome = { id: string; kind: string; channelSlug?: string } & ( + | { action: "resumed"; newId: string } + | { action: "would-resume" } + | { action: "not-resumed"; category: ResumeCategory; reason: string } +); + +// What a re-run of each kind skips, for the resumed job's first log line. +const RESUMES_BY: Record<string, string> = { + "import-archive-org": "files already held are skipped", + "import-one": "a file already on disk is not fetched again, and a partial download continues", + "download-missing": "videos already downloaded are skipped", + "fetch-posts": "the walk continues from its saved position", + "persist-videos": "videos already saved are skipped", + "fetch-windows": "windows already fetched are skipped", + "whisper-all": "videos already transcribed are skipped", + "whisper-bucket-downloaded-no-transcript": "videos already transcribed are skipped", + "whisper-bucket-auto-subs": "videos already transcribed are skipped", + "capture-posts": "posts already captured are skipped", + "normalize-transcripts": "fresh cues files are left alone", + "refresh-report": "the channel's report is regenerated", + "fetch-chat-backlog": "chats already fetched, and streams that have none, are skipped", +}; + +// The spec a resume re-queues, or why the job is not resumed. Usually the spec +// as it was; a posts fetch that started an older walk at a date (`from`) +// drops it — its saved position is what continues the walk, and `from` would +// start it afresh. +export function resumeSpecFor(spec: JobSpec): { spec: JobSpec } | { skip: string } { + const p = spec.params ?? {}; + if (p.dryRun === true) return { skip: "a dry run writes nothing; it is not resumed" }; + if (spec.kind === "fetch-posts") { + if (p.full === true) { + return { + skip: "a full re-walk starts over from the top, so it is not resumed — Retry it to walk again", + }; + } + if (p.from !== undefined) { + const { from: _from, ...rest } = p; + return { spec: { ...spec, params: rest } }; + } + } + return { spec }; +} + +export function resumeNote(meta: JobMeta, count: number): string { + const what = RESUMES_BY[meta.kind] ?? "it skips what the first run finished"; + return ( + `Resumes ${jobKindLabel(meta.kind)} job ${meta.id}${meta.channelSlug ? ` on ${meta.channelSlug}` : ""}, ` + + `interrupted when the process running it stopped${count > 1 ? ` (resume ${count} in a row)` : ""}: ${what}.` + ); +} + +export type ResumeInterruptedOpts = { + paths: Paths; + requeue: RequeueFn; + // List what would be re-queued; change nothing. + dryRun?: boolean; + // Only these jobs (the boot: what its running pass just closed). Absent: + // every job interrupted within `windowMs` of `now`. + ids?: readonly string[]; + windowMs?: number; + now?: number; + log?: (line: string) => void; + // The prefix of each log line ("[boot]" from the boot). + prefix?: string; +}; + +function isInterrupted(meta: JobMeta): boolean { + return meta.status === "cancelled" && typeof meta.cancelReason === "string" && meta.cancelReason.startsWith(INTERRUPTED_REASON); +} + +export async function resumeInterruptedJobs(opts: ResumeInterruptedOpts): Promise<ResumeOutcome[]> { + const log = opts.log ?? (() => {}); + const prefix = opts.prefix ?? "[resume]"; + const now = opts.now ?? Date.now(); + const windowMs = opts.windowMs ?? RESUME_WINDOW_MS; + let names: string[]; + try { + names = await readdir(opts.paths.jobsDir); + } catch { + return []; + } + const metas: JobMeta[] = []; + for (const n of names.filter((x) => x.endsWith(".meta.json")).sort()) { + const meta = await readJobMeta(opts.paths, n.slice(0, -".meta.json".length)); + if (meta) metas.push(meta); + } + const only = opts.ids ? new Set(opts.ids) : null; + const candidates = metas + .filter((m) => isInterrupted(m) && !m.resumedAs) + .filter((m) => (only ? only.has(m.id) : (m.endedAt ?? 0) >= now - windowMs)) + .sort((a, b) => (a.queuedAt ?? 0) - (b.queuedAt ?? 0) || a.id.localeCompare(b.id)); + + // Every job by what it would DO, for "superseded by a newer one". + const byKey = new Map<string, JobMeta[]>(); + for (const m of metas) { + if (!m.spec) continue; + const k = specKey(m.spec); + byKey.set(k, [...(byKey.get(k) ?? []), m]); + } + const newerWith = (meta: JobMeta, keys: string[]): JobMeta | undefined => { + for (const k of keys) { + const hit = (byKey.get(k) ?? []).find( + (o) => o.id !== meta.id && (o.queuedAt ?? 0) > (meta.queuedAt ?? 0), + ); + if (hit) return hit; + } + return undefined; + }; + + const outcomes: ResumeOutcome[] = []; + const base = (m: JobMeta) => ({ id: m.id, kind: m.kind, ...(m.channelSlug ? { channelSlug: m.channelSlug } : {}) }); + const decline = async (meta: JobMeta, category: ResumeCategory, reason: string) => { + outcomes.push({ ...base(meta), action: "not-resumed", category, reason }); + // A kind that never resumes is left exactly as the boot closed it. + if (category === "kind" || opts.dryRun) return; + await rewrite(opts.paths, meta, { cancelReason: `${INTERRUPTED_REASON}; not resumed: ${reason}` }); + }; + + for (const meta of candidates) { + if (!getJobKind(meta.kind)?.resumeOnBoot) { + await decline(meta, "kind", `${jobKindLabel(meta.kind)} does not resume on a re-run`); + continue; + } + if (!meta.spec) { + await decline(meta, "no-spec", "it has no replay descriptor"); + continue; + } + const count = meta.resumeCount ?? 0; + if (count >= MAX_RESUMES_IN_A_ROW) { + await decline( + meta, + "repeat", + `interrupted twice in a row (it resumed ${meta.resumedFrom ?? "an interrupted job"} and was interrupted again) — Retry it by hand`, + ); + continue; + } + const resumable = resumeSpecFor(meta.spec); + if ("skip" in resumable) { + await decline(meta, "not-resumable", resumable.skip); + continue; + } + const newer = newerWith(meta, [...new Set([specKey(meta.spec), specKey(resumable.spec)])]); + if (newer) { + await decline(meta, "superseded", `superseded by a newer job with the same request (${newer.id}, ${newer.status})`); + continue; + } + if (opts.dryRun) { + outcomes.push({ ...base(meta), action: "would-resume" }); + continue; + } + let res: Awaited<ReturnType<RequeueFn>>; + try { + res = await runWithResumeTag( + { kind: meta.kind, resumedFrom: meta.id, resumeCount: count + 1, note: resumeNote(meta, count + 1) }, + () => opts.requeue(resumable.spec), + ); + } catch (err) { + res = { ok: false, error: (err as Error).message }; + } + if (!res.ok) { + await decline(meta, "refused", `the re-queue was refused: ${res.error}`); + continue; + } + await rewrite(opts.paths, meta, { + cancelReason: `${INTERRUPTED_REASON}; resumed as ${res.jobId}`, + resumedAs: res.jobId, + }); + outcomes.push({ ...base(meta), action: "resumed", newId: res.jobId }); + } + + const resumed = outcomes.filter((o) => o.action === "resumed"); + const declined = outcomes.filter( + (o): o is Extract<ResumeOutcome, { action: "not-resumed" }> => o.action === "not-resumed" && o.category !== "kind", + ); + const where = (o: ResumeOutcome) => `${o.kind}${o.channelSlug ? ` ${o.channelSlug}` : ""}`; + for (const o of resumed) if (o.action === "resumed") log(`${prefix} resumed ${where(o)}: ${o.id} -> ${o.newId}`); + for (const o of declined) log(`${prefix} not resumed ${where(o)} ${o.id}: ${o.reason}`); + return outcomes; +} + +async function rewrite(paths: Paths, meta: JobMeta, patch: Partial<JobMeta>): Promise<void> { + try { + await writeFileAtomic(metaPath(paths, meta.id), JSON.stringify({ ...meta, ...patch })); + } catch { + return; + } + if (patch.cancelReason) { + try { + await appendFile(path.join(paths.jobsDir, `${meta.id}.log`), `[resume] ${patch.cancelReason.slice(INTERRUPTED_REASON.length + 2)}\n`); + } catch { + /* the meta is the record; the log line is a courtesy */ + } + } +} diff --git a/common/jobs/resumeTag.ts b/common/jobs/resumeTag.ts @@ -0,0 +1,47 @@ +// WHICH INTERRUPTED JOB A NEW ONE RESUMES, carried through the action that +// makes it (jobs/resumeInterrupted.ts, 2026-10-26). +// +// The resume pass re-queues a job the way Retry does — runJobSpec(spec), which +// calls the kind's server action, which calls runManagedFunction — so nothing +// in that path can be handed "this one resumes job X". An async context can: +// the pass runs the re-queue inside `runWithResumeTag`, and the first job of +// the tagged kind made inside it (makeJob in streamCommand.ts) claims the tag +// and records `resumedFrom` / `resumeCount` on its record — before its first +// meta write, so a second crash still finds the count on disk. Claimed once: +// a sub-job the resumed job itself starts (a hand-off, a refresh) is not a +// resume. +// +// SERVER-ONLY (node:async_hooks). One storage per process, on globalThis, the +// house pattern (lib/jobContext.ts). + +import { AsyncLocalStorage } from "node:async_hooks"; + +export type ResumeTag = { + kind: string; + resumedFrom: string; + resumeCount: number; + // The first line of the resumed job's log. + note: string; +}; + +type Held = ResumeTag & { claimed: boolean }; + +const KEY = Symbol.for("archilyzer.resumeTag"); + +function storage(): AsyncLocalStorage<Held> { + const g = globalThis as unknown as Record<symbol, AsyncLocalStorage<Held> | undefined>; + return (g[KEY] ??= new AsyncLocalStorage<Held>()); +} + +export function runWithResumeTag<T>(tag: ResumeTag, fn: () => T): T { + return storage().run({ ...tag, claimed: false }, fn); +} + +// The tag for a job of `kind` being made now, once; else null. +export function claimResumeTag(kind: string): ResumeTag | null { + const held = storage().getStore(); + if (!held || held.claimed || held.kind !== kind) return null; + held.claimed = true; + const { claimed: _claimed, ...tag } = held; + return tag; +} diff --git a/common/jobs/snapshotScheduler.ts b/common/jobs/snapshotScheduler.ts @@ -222,6 +222,9 @@ export async function startRefreshReport( queueKey: REFRESH_REPORT_QUEUE, paths, channelSlug: slug, + // Replayable (2026-10-26): a Retry, or the boot's resume of a + // regeneration a restart interrupted, is one more walk of the channel. + spec: { kind: "refresh-report", slug }, fn: async (onLog) => { onLog(`Regenerating report for ${slug}…`); const snap = await generateChannelSnapshot(paths, slug); diff --git a/common/jobs/streamCommand.test.ts b/common/jobs/streamCommand.test.ts @@ -314,3 +314,39 @@ test("at shutdown a queued job's sidecar stays queued, for the boot pass", async await rm(root, { recursive: true, force: true }); } }); + +// A JOB THAT WAITED IN ITS QUEUE IS `running` ON DISK ONCE IT STARTS +// (2026-10-26). Its sidecar was written only at enqueue and at the end, so one +// that died mid-run read `queued`, and the next boot re-queued it as a job that +// never started. Now the boot closes it as interrupted, and the resume pass +// decides. +test("a queued job's sidecar says running once its queue starts it", async () => { + const { paths, root } = await jobsDir(); + const queueKey = `test:running-meta:${newJobId()}`; + const holder = await hold(paths, queueKey); + let finish!: () => void; + const finished = new Promise<void>((r) => { + finish = r; + }); + try { + const job = ok( + await runManagedFunction({ + kind: "test-waits-then-runs", + queueKey, + paths, + fn: () => finished, + }), + ); + assert.equal((await metaReaches(paths, job.jobId, "queued"))?.status, "queued"); + await holder.release(); + const running = await metaReaches(paths, job.jobId, "running"); + assert.equal(running?.status, "running"); + assert.equal(typeof running?.startedAt, "number"); + finish(); + assert.equal((await job.done).status, "done"); + assert.equal((await metaReaches(paths, job.jobId, "done"))?.status, "done"); + } finally { + finish(); + await rm(root, { recursive: true, force: true }); + } +}); diff --git a/common/jobs/streamCommand.ts b/common/jobs/streamCommand.ts @@ -33,6 +33,7 @@ import { mediaHoldText } from "../lib/channelMediaHold"; import { runInJobContext, type JobContext } from "../lib/jobContext"; import { serviceStoppedLine } from "../lib/serviceCookies"; import { configuredCookieBrowser } from "../lib/serviceCookies-server"; +import { claimResumeTag } from "./resumeTag"; // Mark a job's channel report dirty so the debounced scheduler regenerates the // snapshot — called both on each completed sub-operation and on the job's @@ -154,6 +155,14 @@ function makeJob( queuedAt: Date.now(), logPath, }; + // A RESUME OF A JOB A RESTART INTERRUPTED (jobs/resumeTag.ts): recorded + // before the first meta write, so a second crash finds the count on disk. + const resume = claimResumeTag(kind); + if (resume) { + record.resumedFrom = resume.resumedFrom; + record.resumeCount = resume.resumeCount; + record.resumeNote = resume.note; + } getRegistry().register(record); return { id, logPath, record }; } @@ -185,6 +194,19 @@ function makeDoneDeferred(jobId: string): { return { done, settle }; } +// THE MOMENT A JOB STARTS. Its sidecar is rewritten `running` (2026-10-26): +// it was written only at enqueue and at the end, so a job that waited in its +// queue and then died mid-run read `queued` on disk, and the next boot took it +// for one that never started — re-queueing a half-finished job blind, where +// one that started at once read `running` and was closed interrupted. Both +// are `running` now, and the resume pass (jobs/resumeInterrupted.ts) is the +// one place that decides whether either runs again. A resumed job's log opens +// with what it resumes. +function openJobLog(record: JobRecord, log: WriteStream, persistMeta: () => void): void { + if (record.resumeNote) log.write(`[resume] ${record.resumeNote}\n`); + persistMeta(); +} + // ONE WRITER PER JOB, IN ORDER — DEFENSIVE. A job's sidecar is written at // least twice (at enqueue, then with its terminal state) and each write is // async. writeJobMeta snapshots the record before its first await, so two @@ -255,6 +277,7 @@ export async function runManagedCommand( } fileStream = createWriteStream(logPath); ignoreFileStreamErrors(fileStream); + openJobLog(record, fileStream, persistMeta); const child = execa(opts.command, opts.args, { cwd: opts.cwd, env: opts.env, @@ -437,6 +460,7 @@ export async function runManagedFunction( } fileStream = createWriteStream(logPath); ignoreFileStreamErrors(fileStream); + openJobLog(record, fileStream, persistMeta); const abort = new AbortController(); record.abortController = abort; const drain = new AbortController(); diff --git a/common/lib/jobsSettings.ts b/common/lib/jobsSettings.ts @@ -0,0 +1,33 @@ +// settings.jobs — what the job system does on its own across a restart +// (jobs/resumeInterrupted.ts). Pure: the type, its defaults, the sanitizer +// settingsSchema.ts runs it through and the per-field docs SETTINGS.md renders. + +import type { FieldDocs } from "./fieldDocs"; + +export type JobsSettings = { + resumeInterruptedOnBoot: boolean; +}; + +// ON BY DEFAULT (operator, 2026-10-26): a restart during the Ethanalyzer +// archive killed an archive.org import, a feed download and a forum catch-up, +// each already built to skip what it held on a re-run, and each was re-queued +// by hand. +export const DEFAULT_JOBS_SETTINGS: JobsSettings = { + resumeInterruptedOnBoot: true, +}; + +export const JOBS_SETTINGS_FIELD_DOCS: FieldDocs<JobsSettings> = { + resumeInterruptedOnBoot: + "When the editor starts, re-queue the jobs the previous process left RUNNING (closed \"interrupted\") whose kind " + + "resumes on a re-run — it skips what the first run finished: an archive.org import, a download-missing, a " + + "posts fetch, a persist, a clip-window fetch, a transcription batch, a post capture, a cues pass, a report, " + + "a chat backlog (`resumeOnBoot` in common/jobs/jobKinds.ts). Each resumed job's log says which job it resumes. " + + "A job interrupted twice in a row is not resumed again, a dry run or a full re-walk never is, and an idle boot " + + "(ARCHILYZER_IDLE_BOOT) resumes nothing. `pnpm ops job resume-interrupted [--dry-run]` does the same by hand. " + + "Default true.", +}; + +export function sanitizeJobs(value: unknown): JobsSettings { + const r = (value && typeof value === "object" && !Array.isArray(value) ? value : {}) as Record<string, unknown>; + return { resumeInterruptedOnBoot: r.resumeInterruptedOnBoot !== false }; +} diff --git a/common/lib/settingsDocs.ts b/common/lib/settingsDocs.ts @@ -14,6 +14,7 @@ import { ARCHIVE_ORG_SETTINGS_FIELD_DOCS, ARCHIVES_SETTINGS_FIELD_DOCS, CLIPS_SETTINGS_FIELD_DOCS, + JOBS_SETTINGS_FIELD_DOCS, ARCHIVE_STORAGE_SETTINGS_FIELD_DOCS, ATTRIBUTION_SETTINGS_FIELD_DOCS, BACKFILL_SETTINGS_FIELD_DOCS, @@ -326,6 +327,13 @@ export function blockTables(d: SiteSettings): Partial<Record<keyof SiteSettings, defaults: fromObject(d.clips), }, ], + jobs: [ + { + path: "jobs", + docs: JOBS_SETTINGS_FIELD_DOCS, + defaults: fromObject(d.jobs), + }, + ], }; } diff --git a/common/lib/settingsSchema.test.ts b/common/lib/settingsSchema.test.ts @@ -34,6 +34,7 @@ import type { SeederSettings } from "./seederSettings"; import type { TtsSettings } from "./ttsSettings"; import type { ArchivesSettings } from "./archives/settings"; import type { ClipsSettings } from "./clipSettings"; +import type { JobsSettings } from "./jobsSettings"; import type { GenerationSettings } from "./generationSettings"; import type { AttributionSettings, @@ -120,13 +121,15 @@ type PreSchemaSiteSettings = { generation: GenerationSettings; // How clip windows are fetched: the whole-recording platforms. clips: ClipsSettings; + // What the job system does across a restart (2026-10-26). + jobs: JobsSettings; }; // Bracketed so the conditional does not distribute (see commit 8c43231). type Same<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false; const shapeUnchanged: Same<SiteSettings, PreSchemaSiteSettings> = true; -test("SiteSettings keeps its 41 fields, in file order", () => { +test("SiteSettings keeps its 43 fields, in file order", () => { assert.equal(shapeUnchanged, true); assert.deepEqual(Object.keys(siteSettingsSchema.shape), [ "adminTitle", @@ -171,6 +174,7 @@ test("SiteSettings keeps its 41 fields, in file order", () => { "tts", "generation", "clips", + "jobs", ]); // A parsed object carries every key, in that order — writeSettings writes // exactly this, so the order is the on-disk order. diff --git a/common/lib/settingsSchema.ts b/common/lib/settingsSchema.ts @@ -82,6 +82,7 @@ export { SEEDER_SETTINGS_FIELD_DOCS, type SeederSettings } from "./seederSetting import { sanitizeTts, type TtsSettings } from "./ttsSettings"; import { sanitizeArchives, type ArchivesSettings } from "./archives/settings"; import { sanitizeClips, type ClipsSettings } from "./clipSettings"; +import { sanitizeJobs, type JobsSettings } from "./jobsSettings"; import { sanitizeGeneration, type GenerationSettings } from "./generationSettings"; export { GENERATION_CAPS_FIELD_DOCS, @@ -101,6 +102,7 @@ export { export { ORPHEUS_TTS_SETTINGS_FIELD_DOCS, TTS_SETTINGS_FIELD_DOCS, type TtsSettings } from "./ttsSettings"; export { ARCHIVES_SETTINGS_FIELD_DOCS, type ArchivesSettings } from "./archives/settings"; export { CLIPS_SETTINGS_FIELD_DOCS, type ClipsSettings } from "./clipSettings"; +export { JOBS_SETTINGS_FIELD_DOCS, type JobsSettings } from "./jobsSettings"; import { DEFAULT_COOKIE_MODE, isCookieMode, @@ -1953,6 +1955,9 @@ export const siteSettingsSchema = z.object({ clips: settingsField((v): ClipsSettings => sanitizeClips(v)).describe( "How clip windows are fetched (controller/fetchWindows.ts): the platforms whose windows are cut from the saved WHOLE recording rather than by a remote seek — Rumble by default, because its HLS seek put the picture 1–4 s off the sound (lib/clipWindowSync.ts). See ClipsSettings.", ), + jobs: settingsField((v): JobsSettings => sanitizeJobs(v)).describe( + "What the job system does on its own across a restart: whether the jobs the previous process left interrupted are resumed at boot (common/jobs/resumeInterrupted.ts). See JobsSettings.", + ), }); export type SiteSettings = z.infer<typeof siteSettingsSchema>; diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **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. - **A take of part of a cut (`--at`) now shows the clips its own changes add.** The window is timed against the project's cut so every take of a group covers the same clips, and a clip only the take adds (a montage line, an extra beat) was never in it: the Huck cut's pitch-count take rendered seven of its eight pitches. A clip the take adds right after one the window covers now renders with it. Needs a restart of umtool for takes made from the app (the `umtool take` command has it now). diff --git a/editor/app/api/ops/job/route.test.ts b/editor/app/api/ops/job/route.test.ts @@ -210,3 +210,30 @@ test("job verbs: an unknown verb, missing ids, ids on retry-failed and a bad id // Nothing was cancelled by any of them. assert.equal(getRegistry().get("WAIT1")?.status, "queued"); }); + +test("job resume-interrupted: a dry run lists the interrupted job it would re-queue; a stray id or dryRun elsewhere is refused", async () => { + await writeFile( + path.join(JOBS, "RESUMEA1.meta.json"), + JSON.stringify({ + id: "RESUMEA1", + kind: "import-archive-org", + queueKey: "platform:archiveorg", + channelSlug: "demo", + status: "cancelled", + cancelReason: "interrupted: the process running it stopped before it finished", + queuedAt: Date.now() - 60_000, + endedAt: Date.now() - 30_000, + spec: { kind: "import-archive-org", slug: "demo", params: { item: "demo-item", match: "." } }, + }), + ); + const dry = await post({ verb: "resume-interrupted", dryRun: true }); + assert.equal(dry.status, 200); + assert.deepEqual(dry.json.wouldResume, [{ id: "RESUMEA1", kind: "import-archive-org", channelSlug: "demo" }]); + assert.deepEqual(dry.json.jobIds, []); + const stray = await post({ verb: "resume-interrupted", ids: ["NOTAJOB1"], dryRun: true }); + assert.equal(stray.status, 400); + assert.match(String(stray.json.error), /not an interrupted job that was not resumed already: NOTAJOB1/); + const elsewhere = await post({ verb: "cancel", ids: ["RESUMEA1"], dryRun: true }); + assert.equal(elsewhere.status, 400); + assert.match(String(elsewhere.json.error), /"dryRun" goes with "resume-interrupted"/); +}); diff --git a/editor/app/api/ops/job/route.ts b/editor/app/api/ops/job/route.ts @@ -7,13 +7,17 @@ import { retryAllFailedAction, retryJobAction, } from "../../../jobs/actions"; -import { OpsInputError, oneOf, ops, opsFail, reqStringArray } from "../_lib"; +import { OpsInputError, oneOf, ops, opsFail, optBool, reqStringArray } from "../_lib"; +import { getPaths } from "yt-dlp-transcript-common/lib/paths"; +import { resumeInterruptedJobs } from "yt-dlp-transcript-common/jobs/resumeInterrupted"; +import { runJobSpec } from "../../../jobs/runJobSpec"; export const dynamic = "force-dynamic"; // POST { verb: "cancel" | "drain" | "promote" | "force-release" | "retry", // ids: [<jobId>, …] } // | { verb: "retry-failed" } +// | { verb: "resume-interrupted", ids?: [<jobId>, …], dryRun? } // // The buttons on a /jobs row, over HTTP — each verb is the row's server action // and nothing more (`editor/app/jobs/actions.ts`), so a job cancelled here and @@ -29,6 +33,14 @@ export const dynamic = "force-dynamic"; // queue; the new job's id is returned (`jobIds`). // retry-failed every failed job still in the registry that has one — // the /jobs page's Retry all. Takes no ids. +// resume-interrupted +// what the boot does on its own (jobs/resumeInterrupted.ts): +// re-queue the jobs a restart interrupted in the last 24 h +// whose kind resumes on a re-run — each once, never one +// interrupted twice in a row, a dry run or a full posts +// re-walk — or only the `ids` named. `dryRun` lists what it +// would re-queue and changes nothing. Answers `resumed`, +// `wouldResume` and `notResumed` (each with its reason). // // Every id is acted on in turn and answered in `results` ({id, ok, jobId?, // error?}); one that could not be (an unknown id, a job no longer queued for a @@ -42,20 +54,22 @@ const VERBS = [ "force-release", "retry", "retry-failed", + "resume-interrupted", ] as const; type Verb = (typeof VERBS)[number]; type Result = { id: string; ok: boolean; jobId?: string; error?: string }; // What a row action's `false` means, per verb — the action itself only says no. -const REFUSED: Record<Exclude<Verb, "retry" | "retry-failed">, string> = { +type RowVerb = Exclude<Verb, "retry" | "retry-failed" | "resume-interrupted">; +const REFUSED: Record<RowVerb, string> = { cancel: "not queued or running (or unknown)", drain: "not queued or running (or unknown)", promote: "not queued, or already at the front of its queue", "force-release": "", }; -const DONE: Record<Exclude<Verb, "retry-failed">, string> = { +const DONE: Record<Exclude<Verb, "retry-failed" | "resume-interrupted">, string> = { cancel: "cancelled", drain: "drained", promote: "promoted", @@ -75,14 +89,53 @@ async function act(verb: Verb, id: string): Promise<Result> { drain: drainJobAction, promote: promoteJobAction, "force-release": forceReleaseJobAction, - }[verb as Exclude<Verb, "retry" | "retry-failed">]; + }[verb as RowVerb]; const { ok } = await run(id); return ok ? { id, ok } : { id, ok, error: REFUSED[verb as keyof typeof REFUSED] }; } +// The re-queue the boot uses: the path Retry takes. +async function requeue(spec: Parameters<typeof runJobSpec>[0]) { + const res = await runJobSpec(spec); + if (!res.ok) return { ok: false as const, error: res.error }; + void res.stream.cancel(); + return { ok: true as const, jobId: res.jobId }; +} + export async function POST(request: Request) { - return ops(request, ["verb", "ids"], async (body) => { + return ops(request, ["verb", "ids", "dryRun"], async (body) => { const verb = oneOf(body, "verb", VERBS); + if (verb !== "resume-interrupted" && body.dryRun !== undefined) { + throw new OpsInputError(`"dryRun" goes with "resume-interrupted", not "${verb}"`); + } + if (verb === "resume-interrupted") { + const ids = body.ids === undefined ? undefined : [...new Set(reqStringArray(body, "ids"))]; + const dryRun = optBool(body, "dryRun") ?? false; + const outcomes = await resumeInterruptedJobs({ + paths: getPaths(), + requeue, + dryRun, + ...(ids ? { ids } : {}), + }); + const resumed = outcomes.flatMap((o) => + o.action === "resumed" ? [{ id: o.id, kind: o.kind, channelSlug: o.channelSlug, jobId: o.newId }] : [], + ); + const wouldResume = outcomes.flatMap((o) => + o.action === "would-resume" ? [{ id: o.id, kind: o.kind, channelSlug: o.channelSlug }] : [], + ); + const notResumed = outcomes.flatMap((o) => + o.action === "not-resumed" + ? [{ id: o.id, kind: o.kind, channelSlug: o.channelSlug, category: o.category, reason: o.reason }] + : [], + ); + // A named id that is not an interrupted job is said, not ignored. + const unknown = ids ? ids.filter((id) => !outcomes.some((o) => o.id === id)) : []; + const answer = { verb, dryRun, resumed, wouldResume, notResumed, jobIds: resumed.map((r) => r.jobId) }; + if (unknown.length) { + return opsFail(`not an interrupted job that was not resumed already: ${unknown.join(", ")}`, 400, answer); + } + return NextResponse.json({ ok: true, ...answer }); + } if (verb === "retry-failed") { if (body.ids !== undefined) { throw new OpsInputError('"retry-failed" takes no "ids" — it retries every failed job'); diff --git a/editor/app/api/ops/transcribe-bucket/route.ts b/editor/app/api/ops/transcribe-bucket/route.ts @@ -24,7 +24,8 @@ export const dynamic = "force-dynamic"; // it would skip every video in this bucket. // // `ids` NARROWS THE BUCKET, it never widens it (optSubset). With `ids` the job -// carries no bucket key and is not replayable, as an ad-hoc selection is not. +// carries no bucket key and replays as those ids (a re-run skips the ones +// transcribed since). export async function POST(request: Request) { return ops( request, diff --git a/editor/app/channels/[slug]/normalizeActions.ts b/editor/app/channels/[slug]/normalizeActions.ts @@ -59,6 +59,18 @@ export async function normalizeChannelAction( queueKey: resolveQueueKey(channelQueueKey(slug), queueKey), paths, channelSlug: slug, + // Replayable (2026-10-26): a re-run leaves every fresh cues.json alone, + // so a Retry — or the boot's resume of a pass a restart interrupted — + // writes only what is still missing or stale. + spec: { + kind: "normalize-transcripts", + slug, + params: { + queueKey, + ...(opts.ids ? { ids: opts.ids } : {}), + ...(opts.force ? { force: true } : {}), + }, + }, fn: async (onLog, signal) => { const result = await normalizeChannelTranscripts({ paths, diff --git a/editor/app/channels/[slug]/pipelineActions.ts b/editor/app/channels/[slug]/pipelineActions.ts @@ -660,6 +660,10 @@ export async function importVideoAction( paths, channelSlug: slug, videoId, + // Replayable (2026-10-26): the URL as asked, so a Retry — or the boot's + // resume of an import a restart interrupted — asks this action again, + // which re-resolves it and refuses a file already on disk. + spec: { kind: "import-one", slug, params: { url, queueKey } }, fn: async (onLog, signal, _setProgress, ctx) => { const task = makeTaskTracker(ctx, onLog).start({ id: videoId ?? videoUrl, @@ -871,6 +875,22 @@ export async function importArchiveOrgAction( queueKey: platformQueueKey("archiveorg"), paths, channelSlug: slug, + // Replayable (2026-10-26): the request as asked. A re-run skips every file + // already held, so a Retry — or the boot's resume of an import a restart + // interrupted — continues where it stopped. + spec: { + kind: "import-archive-org", + slug, + params: { + ...(opts.item !== undefined ? { item: opts.item } : {}), + ...(opts.items !== undefined ? { items: opts.items } : {}), + ...(opts.query !== undefined ? { query: opts.query } : {}), + ...(opts.limit !== undefined ? { limit: opts.limit } : {}), + ...(opts.files !== undefined ? { files: opts.files } : {}), + ...(opts.match !== undefined ? { match: opts.match } : {}), + ...(opts.dryRun ? { dryRun: true } : {}), + }, + }, fn: async (onLog, signal, _setProgress, ctx) => { let items = requests; if (opts.query !== undefined) { diff --git a/editor/app/channels/[slug]/whisperActions.ts b/editor/app/channels/[slug]/whisperActions.ts @@ -103,8 +103,8 @@ export async function transcribeBucketAction( audioFormat?: AudioFormat, strictAudioFormat?: boolean, // The snapshot bucket these ids came from (downloadedNoTranscript). Passed by - // the named bucket control so the job is replayable; omitted by ad-hoc - // selections. + // the named bucket control so a replay re-derives the bucket; omitted by + // ad-hoc selections, which replay as their own ids. bucketKey?: ReplayBucket, ): Promise<StreamActionResult> { const paths = getPaths(); @@ -118,6 +118,10 @@ export async function transcribeBucketAction( queueKey: resolveQueueKey(TRANSCRIPTION_QUEUE, queueKey), paths, channelSlug: slug, + // A named bucket replays as the bucket's CURRENT members; an ad-hoc + // selection (2026-10-26) as its own ids — a re-run skips every one already + // transcribed, so a Retry, or the boot's resume of a batch a restart + // interrupted, continues it. spec: bucketKey ? { kind: "whisper-bucket-downloaded-no-transcript", @@ -125,7 +129,11 @@ export async function transcribeBucketAction( bucket: bucketKey, params: { queueKey, audioFormat, strictAudioFormat }, } - : undefined, + : { + kind: "whisper-bucket-downloaded-no-transcript", + slug, + params: { queueKey, audioFormat, strictAudioFormat, ids: cleaned }, + }, fn: async (onLog, signal, setProgress, ctx) => { const stat = await readChannelStat(paths, slug); if (stat) { diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts @@ -20,7 +20,10 @@ import { downloadAction, downloadMissingAction, downloadMissingSubsAction, + importArchiveOrgAction, + importVideoAction, retryBucketAction, + type ArchiveOrgImportEntry, storePlaylistAction, runMetadataScanAction, syncAction, @@ -61,6 +64,8 @@ import { } from "../channels/[slug]/videos/[id]/videoActions"; import { fetchWindowsJobAction } from "../channels/[slug]/videos/fetchWindowsAction"; import { browserLookupAction } from "../channels/[slug]/browserLookupActions"; +import { normalizeChannelAction } from "../channels/[slug]/normalizeActions"; +import { startRefreshReport } from "yt-dlp-transcript-common/jobs/snapshotScheduler"; import type { FetchWindowsItem } from "yt-dlp-transcript-common/controller/fetchWindows"; import { reportsPrepareAction } from "../sites/lib/reportsPrepareAction"; import { reportsExportAction } from "../sites/lib/reportsExportAction"; @@ -280,6 +285,18 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { }, "whisper-bucket-downloaded-no-transcript": async (spec) => { const { p, queueKey } = params(spec); + // An ad-hoc selection (`transcribe-bucket` with ids, a bulk selection) + // replays as its own ids; the batch skips the ones transcribed since. + const own = strings(p.ids); + if (!spec.bucket && own?.length) { + return transcribeBucketAction( + spec.slug, + own, + queueKey, + str(p.audioFormat) as AudioFormat | undefined, + bool(p.strictAudioFormat), + ); + } if (!spec.bucket) return { ok: false, error: "Job spec is missing its bucket." }; const ids = await idsForBucket(spec.slug, spec.bucket); if (ids.length === 0) { @@ -491,6 +508,46 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = { const { queueKey } = params(spec); return checkKeptDeletedAction(spec.slug, queueKey); }, + // The URL as asked: the action re-resolves it, and refuses an archive.org or + // BitChute file already on disk (2026-10-26). + "import-one": (spec) => { + const { p, queueKey } = params(spec); + const url = str(p.url); + if (!url) return Promise.resolve({ ok: false, error: "Job spec is missing its URL." }); + return importVideoAction(spec.slug, url, queueKey); + }, + // The archive.org request as asked; the batch skips every file already held, + // so a replay continues an import that stopped (2026-10-26). + "import-archive-org": (spec) => { + const { p } = params(spec); + const items = Array.isArray(p.items) + ? p.items.filter( + (e): e is ArchiveOrgImportEntry => + typeof e === "string" || (!!e && typeof e === "object" && typeof (e as { item?: unknown }).item === "string"), + ) + : undefined; + return importArchiveOrgAction(spec.slug, { + ...(str(p.item) !== undefined ? { item: str(p.item) } : {}), + ...(items ? { items } : {}), + ...(str(p.query) !== undefined ? { query: str(p.query) } : {}), + ...(num(p.limit) !== undefined ? { limit: num(p.limit) } : {}), + ...(strings(p.files) ? { files: strings(p.files) } : {}), + ...(str(p.match) !== undefined ? { match: str(p.match) } : {}), + ...(bool(p.dryRun) ? { dryRun: true } : {}), + }); + }, + // A cues pass: the ids it was narrowed to, and `force`; a re-run leaves + // every fresh cues.json alone (2026-10-26). + "normalize-transcripts": (spec) => { + const { p, queueKey } = params(spec); + const ids = strings(p.ids); + return normalizeChannelAction(spec.slug, queueKey, { + ...(ids?.length ? { ids } : {}), + ...(bool(p.force) ? { force: true } : {}), + }); + }, + // One channel's report, regenerated on the refresh-report queue. + "refresh-report": async (spec) => startRefreshReport(getPaths(), spec.slug), "persist-kept": (spec) => { const { queueKey } = params(spec); return persistKeptAction(spec.slug, queueKey); diff --git a/editor/instrumentation.ts b/editor/instrumentation.ts @@ -155,34 +155,68 @@ export async function register() { ); const testServer = process.env.E2E_TEST_ROUTES === "1"; // STALE `running` METAS FROM A DEAD PROCESS (release 17 slice D0): closed - // `cancelled` as interrupted, never re-run — on every boot, idle and test - // server included, because closing one starts nothing. Does not wait for + // `cancelled` as interrupted — on every boot, idle and test server + // included, because closing one starts nothing. Only the resume pass + // below runs any of them again. Does not wait for // the storage pass: it touches no channel. A meta another live process // still owns (`archilyzer run`) is left alone — see writerIsGone. - void settleRunningJobMetas({ + const runningPass = settleRunningJobMetas({ paths: getPaths(), bootedAt, isLive: (id) => getRegistry().get(id) !== undefined, log: (line) => console.log(line), - }).catch(() => {}); + }); + runningPass.catch(() => {}); const cancelOnly = idle || testServer; - void settleAfterStoragePass(storagePass, { + const requeue = async (spec: import("yt-dlp-transcript-common/jobs/jobSpec").JobSpec) => { + const { runJobSpec } = await import("./app/jobs/runJobSpec"); + const res = await runJobSpec(spec); + if (!res.ok) return { ok: false as const, error: res.error }; + // Nobody reads this stream; release it as the ops routes do. + void res.stream.cancel(); + return { ok: true as const, jobId: res.jobId }; + }; + const queuedPass = settleAfterStoragePass(storagePass, { paths: getPaths(), bootedAt, isLive: (id) => getRegistry().get(id) !== undefined, log: (line) => console.log(line), idleReason: idle ? "idle boot" : testServer ? "test server" : undefined, - requeue: cancelOnly - ? null - : async (spec) => { - const { runJobSpec } = await import("./app/jobs/runJobSpec"); - const res = await runJobSpec(spec); - if (!res.ok) return { ok: false, error: res.error }; - // Nobody reads this stream; release it as the ops routes do. - void res.stream.cancel(); - return { ok: true, jobId: res.jobId }; - }, - }).catch(() => {}); + requeue: cancelOnly ? null : requeue, + }); + queuedPass.catch(() => {}); + // RESUME WHAT THE RESTART INTERRUPTED (2026-10-26): the jobs the running + // pass just closed whose kind resumes on a re-run (`resumeOnBoot`, + // jobs/jobKinds.ts) are re-queued through the path Retry uses, after the + // queued pass (so a channel being re-pointed is reachable, and what was + // waiting keeps its place ahead of them). Never on an idle boot or the + // test server, and not with `jobs.resumeInterruptedOnBoot` off. See + // common/jobs/resumeInterrupted.ts. + if (!cancelOnly) { + void (async () => { + const running = await runningPass; + await queuedPass.catch(() => null); + if (running.interrupted.length === 0) return; + const { getSettings } = await import("yt-dlp-transcript-common/lib/settings"); + if (!getSettings().jobs.resumeInterruptedOnBoot) { + console.log( + `[boot] ${running.interrupted.length} interrupted job(s) not resumed: jobs.resumeInterruptedOnBoot is off ` + + "(pnpm ops job resume-interrupted resumes them by hand)", + ); + return; + } + const { resumeInterruptedJobs } = await import( + "yt-dlp-transcript-common/jobs/resumeInterrupted" + ); + await resumeInterruptedJobs({ + paths: getPaths(), + ids: running.interrupted.map((j) => j.id), + requeue, + prefix: "[boot]", + log: (line) => console.log(line), + }); + })().catch(() => {}); + } } catch { /* a boot pass that fails to start must not block server readiness */ } diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -20,6 +20,7 @@ // pnpm ops get coverage <slug> // pnpm ops job <cancel|drain|promote|force-release|retry> <id>... [--wait] // pnpm ops job retry-failed | job wait <id>... +// pnpm ops job resume-interrupted [<id>...] [--dry-run] // pnpm ops list // // ARCHILYZER_EDITOR_URL editor base URL (default http://localhost:3001) @@ -336,6 +337,7 @@ export const JOB_VERBS = [ "force-release", "retry", "retry-failed", + "resume-interrupted", "wait", ]; @@ -640,6 +642,8 @@ export function parseArgs(argv) { let counts = false; let leads = false; let tail = 0; + // `job resume-interrupted` only: list what would be re-queued. + let dryRun = false; const jobs = {}; // The noun-specific flags seen, checked against GET_FLAGS once the noun is // known: a flag a read does not take is refused, never ignored. @@ -672,6 +676,8 @@ export function parseArgs(argv) { if (err) return err; } else if (arg === "--quiet") { quiet = true; + } else if (arg === "--dry-run") { + dryRun = true; } else if (arg === "--counts") { counts = true; used.add("counts"); @@ -733,6 +739,9 @@ export function parseArgs(argv) { } } if (positional.length === 0) return { help: true }; + if (dryRun && !(positional[0] === "job" && positional[1] === "resume-interrupted")) { + return { error: '--dry-run goes with "job resume-interrupted" (elsewhere, a body\'s "dryRun": true)' }; + } if (json !== null && file !== null) { return { error: "--json and --file are mutually exclusive" }; } @@ -809,6 +818,8 @@ export function parseArgs(argv) { const ids = positional.slice(2); if (verb === "retry-failed") { if (ids.length) return { error: "job retry-failed takes no ids" }; + } else if (verb === "resume-interrupted") { + // Ids are optional: none is every job interrupted in the last 24 h. } else if (ids.length === 0) { return { error: `job ${verb}: needs one or more job ids` }; } @@ -822,7 +833,12 @@ export function parseArgs(argv) { return { method: "POST", path: "/api/ops/job", - body: verb === "retry-failed" ? { verb } : { verb, ids }, + body: + verb === "retry-failed" + ? { verb } + : verb === "resume-interrupted" + ? { verb, ...(ids.length ? { ids } : {}), ...(dryRun ? { dryRun: true } : {}) } + : { verb, ids }, wait, quiet, waitTimeout, @@ -939,6 +955,7 @@ export function usage() { " [--limit <n>]", " pnpm ops job cancel|drain|promote|force-release|retry <id>... [--wait]", " pnpm ops job retry-failed [--wait]", + " pnpm ops job resume-interrupted [<id>...] [--dry-run] [--wait]", " pnpm ops job wait <id>... [--wait-timeout <seconds>]", " pnpm ops get settings [<key>]", " pnpm ops get storage | sites | workers | auto-queue | scheduler", @@ -976,6 +993,13 @@ export function usage() { " Each id is answered in \"results\"; one that could not be acted on makes", " the answer ok: false without stopping the rest. --wait follows the jobs a", " retry started. job wait <id>... follows jobs already running.", + "job resume-interrupted does by hand what the editor does at boot: re-queues", + " the jobs a restart interrupted (the last 24 h, or the ids named) whose kind", + " resumes on a re-run — an archive.org import, a download-missing, a posts", + " fetch, a persist, a transcription batch… Each once; never one interrupted", + " twice in a row, a dry run or a full posts re-walk; one superseded by a", + " newer job is left. --dry-run lists what it would re-queue (wouldResume)", + " and why the rest are not (notResumed), and changes nothing.", "", "get settings [<key>] is settings.json as the editor reads it (migrated and", " defaulted; a secret is \"<redacted>\"), or one top-level key of it.", diff --git a/scripts/archilyzer-ops.test.mjs b/scripts/archilyzer-ops.test.mjs @@ -803,6 +803,20 @@ test("job <verb> <id...> posts the verb and the ids to /api/ops/job", () => { assert.match(parseArgs(["job", "cancel", "A1", "--json", "{}"]).error, /not a body/); }); +test("job resume-interrupted: ids optional, --dry-run in the body, and nowhere else", () => { + assert.deepEqual(parseArgs(["job", "resume-interrupted"]).body, { verb: "resume-interrupted" }); + assert.deepEqual(parseArgs(["job", "resume-interrupted", "--dry-run"]).body, { + verb: "resume-interrupted", + dryRun: true, + }); + const p = parseArgs(["job", "resume-interrupted", "A1", "--wait"]); + assert.deepEqual(p.body, { verb: "resume-interrupted", ids: ["A1"] }); + assert.equal(p.wait, true); + assert.match(parseArgs(["job", "cancel", "A1", "--dry-run"]).error, /--dry-run goes with "job resume-interrupted"/); + assert.match(parseArgs(["sync", "--dry-run"]).error, /--dry-run goes with/); + assert.match(usage(), /pnpm ops job resume-interrupted \[<id>\.\.\.\] \[--dry-run\]/); +}); + test("job wait <id...> sends nothing and follows the ids", () => { const p = parseArgs(["job", "wait", "A1", "B2", "--wait-timeout", "60"]); assert.deepEqual(p.waitFor, ["A1", "B2"]); diff --git a/settings.json.example b/settings.json.example @@ -332,5 +332,8 @@ "wholeRecordingPlatforms": [ "rumble" ] + }, + "jobs": { + "resumeInterruptedOnBoot": true } }