// 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, readFile, readdir } from "node:fs/promises"; import { INSTAGRAM_QUEUE_KEY, isInstagramPostsChannelConfig, type InstagramChannelSigns } from "../lib/instagram/channel"; 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; // Why an interrupted Instagram job is left: one on Instagram's queue, or — a // queue key is only where the job ran — one whose channel is an Instagram // posts channel by the one predicate (lib/instagram/channel.ts). export { INSTAGRAM_QUEUE_KEY }; async function isInstagramChannel(paths: Paths, slug: string | undefined): Promise { if (!slug || !paths.channelsDir) return false; try { const raw = JSON.parse(await readFile(path.join(paths.channelsDir, slug, "config.json"), "utf8")) as InstagramChannelSigns; return isInstagramPostsChannelConfig(raw); } catch { return false; } } export const INSTAGRAM_NOT_RESUMED = "an Instagram job is not started by a restart — its place is saved, and the next scheduled sync (or a press) continues from it"; // 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 = { "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 { 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(); 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; } // AN INSTAGRAM JOB IS NEVER STARTED BY A RESTART (lane instagram): every // one is a logged-in read, and a boot that re-queued it would ask // Instagram at a moment nobody chose. Its resume point is on disk; the // next scheduled sync, or a press, continues from it. if (meta.queueKey === INSTAGRAM_QUEUE_KEY || (await isInstagramChannel(opts.paths, meta.channelSlug ?? meta.spec?.slug))) { await decline(meta, "not-resumable", INSTAGRAM_NOT_RESUMED); 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>; 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 => 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): Promise { 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 */ } } }