// THE DURABLE QUEUE (operator, 4 Nov 2026: "it'd be better to have Archilyzer // or umtool handle it and you simply poll them"; "we want the plain apps to do // as much heavy lifting as possible so cheaper models can more easily do these // tasks without having to improvise shell scripts and instead call real tools"). // // DESIGN NOTE (lane/run-queue, slice A of the apps-do-the-work plan) // // What it replaces: `until grep -q DONE …; do sleep; done` chains that ran // `umtool take … | grep | tail` and printed DONE whatever the exit code. A // step here is a umtool subcommand's ARGV (never a shell string), stored as // one JSON file; the umtool APP runs the steps, one at a time, so the queue // outlives the AI session that filled it, and an app restart or a ship. // // / UMTOOL_QUEUE_DIR, else /.umtool-queue // seq the last qid's number // steps/.json one step (below), written atomically // logs/.log its latest attempt's FULL log (lib/jobs.ts Step.logFile) // logs/..log attempt n's, kept when it is retried // runner.json the runner's lease: { pid, pidStart, host, since, beat } // renders/~.json pointers to take render records (renderRecord.mjs), for `umtool jobs` // .lock read-modify-write of steps/ (O_EXCL, its pid inside; a dead holder's is broken) // // step: { qid, seq, label, argv, cwd, after, target: { project, take } | null, // state, createdAt, by, startedAt, endedAt, exitCode, signal, pid, pidStart, // host, runnerPid, runnerStart, jobId, attempts, error, blockedBy, cancelRequested, timeoutMin } // // state queued waits for its turn (and for `after`, when it names a step) // running the app's runner started it (its pid is the step's process) // done it exited 0 // failed a non-zero exit or a signal -- or the app died while it ran: a // running step the runner does not hold and whose process is gone // reads, and is then written, failed ("the step's process is gone"). // (Not while the runner that started it is alive: a step whose // process has just exited is running until that runner records its end.) // It is NEVER re-run on its own: `umtool queue retry ` does that. // blocked `after` names a step that failed, was cancelled or is blocked; // `blockedBy` and `error` say which and why. A retry of that step // puts this one back in the queue. // cancelled `umtool queue cancel` (a running one is stopped: its process group // TERM then KILL, by lib/jobs.ts) // // ORDER: the oldest queued step whose `after` is done (or that names none) runs // next, and only when nothing else of the queue runs AND the app's own job // runner is idle (lib/jobs.ts: one job at a time, so a step and a Takes-page // job never interleave in one out/). A step's heavy work still goes through // the machine's heavy slot and render mode, by itself (a take's render does). // "after" is explicit: a step added without it does not wait for the one // before, and a failure blocks only the steps that named it (directly or // through a blocked step). // // The pure parts (planQueue, resolveStep) are tested alone; the runner loop // is queueTick, with the executor injected (lib/queue/runner.ts gives it the // app's job runner; the tests a plain spawn). // // Plain ESM: the CLI runs it under bare node. import { closeSync, openSync, writeSync } from "node:fs"; import { mkdir, open, readdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { firstErrorLine, procStartTime, processAlive, queueDirFor } from "../report/renderRecord.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const STEP_STATES = Object.freeze(["queued", "running", "done", "failed", "blocked", "cancelled"]); export const TERMINAL = new Set(["done", "failed", "cancelled"]); /** A queue step's default time limit (minutes): a whole cut's render runs hours. */ export const DEFAULT_TIMEOUT_MIN = 12 * 60; /** How stale a lease's heartbeat may be on another host before it is taken (ms). */ export const LEASE_STALE_MS = 60_000; /** Terminal steps older than this are pruned by the runner, with their logs (days). */ export const KEEP_DAYS = 30; export const QID = /^q[1-9][0-9]{0,8}$/; /** @param {unknown} v @returns {v is string} */ export const isQid = (v) => typeof v === "string" && QID.test(v); /** * The queue's directory. * @param {{ reportsRoot: string, env?: Record }} o */ export const queueDirOf = ({ reportsRoot, env = process.env }) => queueDirFor(reportsRoot, env); const stepsDir = (dir) => path.join(dir, "steps"); export const stepFile = (dir, qid) => path.join(stepsDir(dir), `${qid}.json`); /** @param {string} dir @param {string} qid @param {number | null} [attempt] */ export const logFileOf = (dir, qid, attempt = null) => path.join(dir, "logs", attempt ? `${qid}.${attempt}.log` : `${qid}.log`); const leaseFile = (dir) => path.join(dir, "runner.json"); async function writeJson(file, doc) { const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } const readJson = (file) => readFile(/* turbopackIgnore: true */ file, "utf8").then((t) => JSON.parse(t), () => null); const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); /** * Run `fn` holding the queue's lock (`.lock`, O_EXCL with the holder's pid). * A lock whose holder is gone, or older than 30 s, is broken. * @template T * @param {string} dir * @param {() => Promise} fn * @returns {Promise} */ export async function withQueueLock(dir, fn, { timeoutMs = 15_000 } = {}) { await mkdir(stepsDir(dir), { recursive: true }); await mkdir(path.join(dir, "logs"), { recursive: true }); const file = path.join(dir, ".lock"); const deadline = Date.now() + timeoutMs; for (;;) { try { const fd = openSync(/* turbopackIgnore: true */ file, "wx"); writeSync(fd, `${process.pid} ${os.hostname()} ${Date.now()}\n`); closeSync(fd); break; } catch (err) { if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EEXIST") throw err; /** @type {NodeJS.ErrnoException | null} */ let readError = null; const text = await readFile(/* turbopackIgnore: true */ file, "utf8").catch((e) => { if (e?.code === "ENOENT") return null; readError = e; return null; }); if (text === null && !readError) continue; // released meanwhile: try again // A lock that cannot be read (EACCES, EIO…) is waited for up to the // deadline like a held one — never spun on, never broken. const [pid, host, at] = (text ?? "").trim().split(" "); // An EMPTY lock is one another process has created and not yet written // its pid into (open, then write): it was broken at once, and both held // the lock. It is a dead holder's only once it has stayed empty a while — // either way: an mtime in the future is a clock stepped back. const emptyFor = text === "" ? await stat(/* turbopackIgnore: true */ file).then((st) => Date.now() - st.mtimeMs, () => 0) : 0; const stale = text !== null && ((host === os.hostname() && !processAlive(Number(pid))) || (Number(at) > 0 && Date.now() - Number(at) > 30_000) || Math.abs(emptyFor) > 5_000); if (stale) { await unlink(file).catch(() => {}); continue; } if (Date.now() > deadline) { throw new Error( readError ? `the queue lock cannot be read (${/** @type {NodeJS.ErrnoException} */ (readError).code ?? readError}) (${file})` : `the queue is locked by pid ${pid} (${file})`, ); } await sleep(25 + Math.random() * 50); } } try { return await fn(); } finally { await unlink(file).catch(() => {}); } } /** Every step, oldest first. */ export async function listSteps(dir) { const names = await readdir(stepsDir(dir)).catch(() => []); const steps = []; for (const n of names) { if (!n.endsWith(".json")) continue; const s = await readJson(path.join(stepsDir(dir), n)); if (s && isQid(s.qid) && STEP_STATES.includes(s.state)) steps.push(s); } return steps.sort((a, b) => a.seq - b.seq); } export const getStep = (dir, qid) => (isQid(qid) ? readJson(stepFile(dir, qid)) : Promise.resolve(null)); const putStep = (dir, step) => writeJson(stepFile(dir, step.qid), step); /** * A step as it reads NOW: running on this host, not held by the reader's * runner (`owned`), its process gone -> failed. Pure but for `alive`. * * @param {Record} step * @param {{ host?: string, alive?: (pid: number, start?: number | null) => boolean, owned?: Set, self?: number | null }} [o] */ export function resolveStep(step, { host = os.hostname(), alive = processAlive, owned = new Set(), self = null } = {}) { if (step.state !== "running" || owned.has(step.qid)) return step; if (step.host && step.host !== host) return step; if (step.pid && alive(Number(step.pid), step.pidStart ?? null)) return step; // Its process has exited and the runner that started it is alive — and is // not the reader: the runner is recording the end (the log's tail, under the // lock) and the step is running until it has. A reader used to call it // failed in that moment ("the process is gone"), so `queue wait` could exit 1 // on a step that then read done. Only a runner whose start time was recorded // counts (a reused pid is not the runner); the runner itself (`self`) knows // what it holds, so one it does not hold is gone. if ( step.pid && step.runnerPid && step.runnerStart != null && Number(step.runnerPid) !== self && alive(Number(step.runnerPid), step.runnerStart) ) return step; // Marked running a moment ago, its pid not written yet, by a runner that is alive: running. if (!step.pid && step.runnerPid && alive(Number(step.runnerPid)) && Date.now() - Date.parse(step.startedAt ?? 0) < 30_000) return step; // A step marked running whose process never started (the app died between the // two writes) has no pid: gone too. return { ...step, state: "failed", gone: true, error: goneError(step) }; } const goneError = (step) => `the step's process is gone${step.pid ? ` (pid ${step.pid})` : ""} — the umtool app stopped or restarted while it ran; ` + `nothing re-ran it. Its log is kept: \`umtool queue log ${step.qid}\`; \`umtool queue retry ${step.qid}\` runs it again`; /** `umtool queue status`'s exit code: 0 done, 3 queued or running, 1 failed, blocked or cancelled. */ export function stepExitCode(state) { if (state === "done") return 0; if (state === "queued" || state === "running") return 3; return 1; } /** * Pure: what the queue should do now. * - `block`: queued steps whose `after` failed, was cancelled or is blocked (in * seq order, so a chain blocks in one pass), each with its reason * - `start`: the step to start, or null (a step runs; none is ready) * * @param {Array>} steps resolved (resolveStep) * @returns {{ start: Record | null, block: Array<{ qid: string, blockedBy: string, error: string }>, running: Record | null }} */ export function planQueue(steps) { const byId = new Map(steps.map((s) => [s.qid, { ...s }])); const block = []; for (const s of [...byId.values()].sort((a, b) => a.seq - b.seq)) { if (s.state !== "queued" || !s.after) continue; const dep = byId.get(s.after); if (!dep) { s.state = "blocked"; const error = `it waits on ${s.after}, which is not in the queue`; block.push({ qid: s.qid, blockedBy: s.after, error }); continue; } if (dep.state === "failed" || dep.state === "cancelled" || dep.state === "blocked") { s.state = "blocked"; const why = dep.state === "blocked" ? `is blocked (${dep.blockedBy ? `by ${dep.blockedBy}` : "upstream"})` : dep.state === "cancelled" ? "was cancelled" : "failed"; const error = `it waits on ${dep.qid}, which ${why} — \`umtool queue retry ${dep.qid}\` puts both back`; s.blockedBy = dep.qid; block.push({ qid: s.qid, blockedBy: dep.qid, error }); } } const all = [...byId.values()].sort((a, b) => a.seq - b.seq); const running = all.find((s) => s.state === "running") ?? null; if (running) return { start: null, block, running }; const start = all.find((s) => s.state === "queued" && (!s.after || byId.get(s.after)?.state === "done")) ?? null; return { start, block, running: null }; } /** * Add a step. * * @param {string} dir * @param {{ argv: string[], label?: string | null, after?: string | null, cwd?: string, by?: string, * target?: { project: string | null, take: string | null } | null, timeoutMin?: number, now?: () => Date }} o * `after`: a qid, or "last" (the newest step in the queue now). */ export async function addStep(dir, o) { if (!Array.isArray(o.argv) || !o.argv.length || o.argv.some((a) => typeof a !== "string")) throw new Error("a step is a umtool subcommand's argv: `umtool queue add -- take --id …`"); const now = o.now ?? (() => new Date()); return withQueueLock(dir, async () => { let after = o.after ?? null; const steps = await listSteps(dir); if (after === "last") { after = steps.length ? steps[steps.length - 1].qid : null; if (!after) throw new Error("--after last: the queue is empty"); } if (after !== null && !steps.some((s) => s.qid === after)) throw new Error(`--after ${after}: no such step (\`umtool queue ls --all\`)`); const seqFile = path.join(dir, "seq"); const last = Number((await readFile(/* turbopackIgnore: true */ seqFile, "utf8").catch(() => "0")).trim()) || 0; const seq = Math.max(last, ...steps.map((s) => s.seq)) + 1; await writeFile(/* turbopackIgnore: true */ seqFile, `${seq}\n`, "utf8"); const step = { qid: `q${seq}`, seq, label: o.label?.trim() || labelOf(o.argv), argv: o.argv, // Where it was queued from (relative paths in its argv resolve there); the runner's own dir when unsaid. cwd: o.cwd ?? null, after, target: o.target ?? null, state: "queued", createdAt: now().toISOString(), by: o.by ?? "umtool queue add", startedAt: null, endedAt: null, exitCode: null, signal: null, pid: null, pidStart: null, host: null, runnerPid: null, jobId: null, attempts: 0, error: null, blockedBy: null, cancelRequested: null, timeoutMin: Number(o.timeoutMin) > 0 ? Number(o.timeoutMin) : DEFAULT_TIMEOUT_MIN, }; await putStep(dir, step); return step; }); } /** A step's default label: its argv, shortened. */ const labelOf = (argv) => { const text = argv.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(" "); return text.length > 100 ? `${text.slice(0, 99)}…` : text; }; /** The steps that wait on `qid`, directly or through each other (seq order). */ function dependentsOf(steps, qid) { const out = []; const seen = new Set([qid]); let grew = true; while (grew) { grew = false; for (const s of steps) { if (!seen.has(s.qid) && s.after && seen.has(s.after)) { seen.add(s.qid); out.push(s); grew = true; } } } return out.sort((a, b) => a.seq - b.seq); } /** * Cancel a step: a queued or blocked one at once; a running one is asked (the * runner stops its process group and writes cancelled). Its dependents block. * @returns {Promise<{ step: Record, said: string }>} */ export async function cancelStep(dir, qid, { by = "umtool queue cancel", now = () => new Date() } = {}) { return withQueueLock(dir, async () => { const step = await getStep(dir, qid); if (!step) throw new Error(`no step ${qid}`); if (TERMINAL.has(step.state)) throw new Error(`${qid} is ${step.state} already`); if (step.state === "running") { step.cancelRequested = { at: now().toISOString(), by }; await putStep(dir, step); return { step, said: `${qid}: asked to stop (the runner stops its process group; it reads cancelled once it has)` }; } step.state = "cancelled"; step.endedAt = now().toISOString(); step.error = `cancelled by ${by}`; await putStep(dir, step); await blockDependents(dir, step); return { step, said: `${qid}: cancelled` }; }); } async function blockDependents(dir, step) { const steps = await listSteps(dir); for (const d of dependentsOf(steps, step.qid)) { if (d.state !== "queued") continue; d.state = "blocked"; d.blockedBy = d.after; d.error = d.after === step.qid ? `it waits on ${step.qid}, which ${step.state === "cancelled" ? "was cancelled" : step.state} — \`umtool queue retry ${step.qid}\` puts both back` : `it waits on ${d.after}, which is blocked (by ${step.qid})`; await putStep(dir, d); } } /** * Retry: a failed or cancelled step goes back in the queue (its log kept as * logs/..log), and every step blocked behind it with it. A * blocked step goes back only when what it waits on is not failed itself. * @returns {Promise<{ step: Record, requeued: string[], said: string }>} */ export async function retryStep(dir, qid) { return withQueueLock(dir, async () => { const steps = await listSteps(dir); const step = steps.find((s) => s.qid === qid); if (!step) throw new Error(`no step ${qid}`); const resolved = resolveStep(step); if (resolved.state === "queued" || resolved.state === "running") throw new Error(`${qid} is ${resolved.state}: nothing to retry`); if (resolved.state === "done") throw new Error(`${qid} is done: add it again (\`umtool queue add\`) to run it again`); if (resolved.state === "blocked") { const dep = steps.find((s) => s.qid === step.after); const depState = dep ? resolveStep(dep).state : null; if (depState && depState !== "done" && depState !== "queued" && depState !== "running") { throw new Error(`${qid} waits on ${step.after}, which is ${depState}: retry ${step.after} (it puts ${qid} back too)`); } } const requeued = []; const requeue = async (s) => { const was = resolveStep(s); if (was.state === "failed" || was.state === "cancelled") { const logs = path.join(dir, "logs"); await rename(logFileOf(dir, s.qid), path.join(logs, `${s.qid}.${s.attempts || 1}.log`)).catch(() => {}); } Object.assign(s, { state: "queued", error: null, blockedBy: null, cancelRequested: null, exitCode: null, signal: null, pid: null, pidStart: null, endedAt: null, startedAt: null, jobId: null }); await putStep(dir, s); requeued.push(s.qid); }; await requeue(step); for (const d of dependentsOf(steps, qid)) if (d.state === "blocked") await requeue(d); return { step, requeued, said: `${requeued.join(", ")} back in the queue` }; }); } /** Mark a step started (the runner, holding the lock). */ async function markStarted(dir, step, { pid, runnerPid, jobId, now }) { Object.assign(step, { state: "running", startedAt: now().toISOString(), endedAt: null, pid: pid ?? null, pidStart: pid ? procStartTime(pid) : null, host: os.hostname(), runnerPid, runnerStart: runnerPid ? procStartTime(runnerPid) : null, jobId: jobId ?? null, attempts: (step.attempts ?? 0) + 1, error: null, }); await putStep(dir, step); } /** The last ~64 KB of a log, as lines. */ export async function logTail(file, maxBytes = 64 * 1024) { try { const st = await stat(/* turbopackIgnore: true */ file); const fh = await open(/* turbopackIgnore: true */ file, "r"); try { const len = Math.min(st.size, maxBytes); const buf = Buffer.alloc(len); await fh.read(buf, 0, len, st.size - len); const lines = buf.toString("utf8").split("\n"); if (st.size > maxBytes) lines.shift(); return lines.filter((l) => l.trim()); } finally { await fh.close(); } } catch { return []; } } /** * Pure: the step's end state from how its process ended. A failed step's * error is the LAST line of its log that reads as an error (a umtool command * says why it stopped last), else its last line, with the exit after it. * @param {{ exitCode: number | null, signal?: string | null, cancelled?: boolean, error?: string | null }} end * @param {string[]} tail the log's last lines */ export function endOf(end, tail) { if (end.cancelled) return { state: "cancelled", error: "cancelled — its process group was stopped" }; if (end.exitCode === 0) return { state: "done", error: null }; const how = end.exitCode === null ? `killed${end.signal ? ` by ${end.signal}` : ""}` : `exit ${end.exitCode}`; const lines = tail.filter((l) => !/^\*\* (exit |killed after|cancelled)/.test(l) && !/^[$#] /.test(l)); const said = firstErrorLine([...lines].reverse()) ?? lines[lines.length - 1] ?? null; return { state: "failed", error: said ? `${said} (${how})` : `it ended with ${how}` }; } /** * Take the runner's lease, or renew it. False when another live process holds it. * @param {string} dir */ export async function acquireLease(dir, { pid = process.pid, host = os.hostname(), now = () => new Date(), alive = processAlive, url = null } = {}) { await mkdir(dir, { recursive: true }); const cur = await readJson(leaseFile(dir)); const mine = cur && Number(cur.pid) === pid && cur.host === host; if (cur && !mine) { const live = cur.host === host ? alive(Number(cur.pid), cur.pidStart ?? null) : now().getTime() - Date.parse(cur.beat ?? 0) < LEASE_STALE_MS; if (live) return false; } const at = now().toISOString(); await writeJson(leaseFile(dir), { pid, pidStart: procStartTime(pid), host, since: mine ? cur.since : at, beat: at, ...(url ? { url } : {}) }); return true; } /** The runner's lease as it reads: `{ live, pid, host, since, beat }` or null. */ export async function readLease(dir, { host = os.hostname(), alive = processAlive, now = () => new Date() } = {}) { const cur = await readJson(leaseFile(dir)); if (!cur) return null; const live = cur.host === host ? alive(Number(cur.pid), cur.pidStart ?? null) : now().getTime() - Date.parse(cur.beat ?? 0) < LEASE_STALE_MS; return { ...cur, live }; } /** Let the lease go (the runner, stopping). */ export async function releaseLease(dir, { pid = process.pid } = {}) { const cur = await readJson(leaseFile(dir)); if (cur && Number(cur.pid) === pid) await unlink(leaseFile(dir)).catch(() => {}); } /** * One turn of the runner. The executor: * busy() a reason the app cannot start a step now (its job runner is busy), or null * start(step, { logFile, onEnd }) -> { pid, jobId, cancel() }; onEnd({ exitCode, signal, cancelled, error }) * describe?(step) a better error for a failed step (a take's render record's), or null * * `held`: the runner's own map qid -> handle, kept between turns. * * @param {string} dir * @param {{ busy: () => string | null, start: (step: any, o: { logFile: string, onEnd: (end: any) => void }) => { pid: number | null, jobId?: string | null, cancel: () => void }, * describe?: (step: any) => Promise }} exec * @param {{ held: Map, now?: () => Date, runnerPid?: number, alive?: (pid: number, start?: number | null) => boolean, * onChange?: () => void, * endWrite?: { tries?: number, pauseMs?: number, before?: (qid: string, attempt: number) => void | Promise } }} state * `endWrite`: how recording a step's end is retried (`before`, a test's fault, runs ahead of each try) * @returns {Promise<{ started: string | null, recovered: string[], blocked: string[], waiting: string | null }>} */ export async function queueTick(dir, exec, state) { const now = state.now ?? (() => new Date()); const runnerPid = state.runnerPid ?? process.pid; const alive = state.alive ?? processAlive; const out = { started: null, recovered: [], blocked: [], waiting: null }; /** @type {any} */ let toStart = null; await withQueueLock(dir, async () => { const steps = await listSteps(dir); const owned = new Set(state.held.keys()); // Recovery: a running step this runner does not hold, its process gone, is failed -- never re-run. for (const s of steps) { const r = resolveStep(s, { owned, alive, self: runnerPid }); if (r !== s && r.state === "failed") { Object.assign(s, { state: "failed", endedAt: now().toISOString(), error: r.error, exitCode: null }); await putStep(dir, s); await appendLog(dir, s.qid, `** ${r.error}`); out.recovered.push(s.qid); } } // A cancel asked of a step this runner holds. for (const s of steps) { if (s.state === "running" && s.cancelRequested && state.held.has(s.qid)) { const h = state.held.get(s.qid); if (!h.cancelling) { h.cancelling = true; h.cancel(); } } } const plan = planQueue(steps); for (const b of plan.block) { const s = steps.find((x) => x.qid === b.qid); if (!s) continue; Object.assign(s, { state: "blocked", blockedBy: b.blockedBy, error: b.error }); await putStep(dir, s); out.blocked.push(s.qid); } if (plan.running || state.held.size || !plan.start) return; const busy = exec.busy(); if (busy) { out.waiting = `${plan.start.qid} waits for the app's runner: ${busy}`; return; } toStart = plan.start; // Marked running BEFORE it is started, so a crash between the two reads failed (gone), never queued again. await markStarted(dir, toStart, { pid: null, runnerPid, jobId: null, now }); }); if (!toStart) return out; const step = toStart; const logFile = logFileOf(dir, step.qid); await appendLog(dir, step.qid, `# queue ${step.qid} attempt ${step.attempts}: ${step.label}\n# started ${step.startedAt} by the umtool app (pid ${runnerPid}), cwd ${step.cwd}\n# argv: umtool ${step.argv.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(" ")}`); const handle = { cancelling: false, cancel: () => {} }; state.held.set(step.qid, handle); let started; try { started = exec.start(step, { logFile, onEnd: (end) => { void recordEnd(dir, step.qid, end, exec, state).catch(() => {}); }, }); } catch (e) { await recordEnd(dir, step.qid, { exitCode: null, error: e instanceof Error ? e.message : String(e) }, exec, state, { notStarted: true }).catch(() => {}); return out; } handle.cancel = started.cancel; await withQueueLock(dir, async () => { const s = await getStep(dir, step.qid); if (!s || s.state !== "running") return; s.pid = started.pid ?? null; s.pidStart = started.pid ? procStartTime(started.pid) : null; s.jobId = started.jobId ?? null; await putStep(dir, s); }); out.started = step.qid; state.onChange?.(); return out; } async function appendLog(dir, qid, text) { await mkdir(path.join(dir, "logs"), { recursive: true }); const fh = await open(/* turbopackIgnore: true */ logFileOf(dir, qid), "a"); try { await fh.write(text.endsWith("\n") ? text : `${text}\n`); } finally { await fh.close(); } } async function finishStep(dir, qid, end, exec, state, { notStarted = false } = {}) { const now = state.now ?? (() => new Date()); const tail = await logTail(logFileOf(dir, qid)); await withQueueLock(dir, async () => { const s = await getStep(dir, qid); if (!s) return; const r = endOf({ ...end, cancelled: !!end.cancelled || (!!s.cancelRequested && end.exitCode !== 0) }, tail); let error = notStarted ? `it could not be started: ${end.error}` : r.error; if (r.state === "failed" && exec.describe) { const better = await exec.describe(s).catch(() => null); if (better) error = `${better} (${end.exitCode === null ? "killed" : `exit ${end.exitCode}`})`; } Object.assign(s, { state: r.state, endedAt: now().toISOString(), exitCode: end.exitCode ?? null, signal: end.signal ?? null, error }); await putStep(dir, s); if (r.state !== "done") await blockDependents(dir, s); }); } export const END_WRITE_TRIES = 3; export const END_WRITE_PAUSE_MS = 2_000; /** * Record a step's end (finishStep), a few times if writing it fails (the queue * lock's timeout on a loaded machine) — and, whatever happens, let go of the * step: a step this runner no longer holds and whose process is gone is the * runner's own recovery's to mark failed on its next turn. It used to stay * held when the write threw, reading running until the app restarted. */ async function recordEnd(dir, qid, end, exec, state, opts = {}) { const tries = state.endWrite?.tries ?? END_WRITE_TRIES; const pauseMs = state.endWrite?.pauseMs ?? END_WRITE_PAUSE_MS; try { for (let attempt = 1; ; attempt += 1) { try { await state.endWrite?.before?.(qid, attempt); await finishStep(dir, qid, end, exec, state, opts); return; } catch (e) { if (attempt >= tries) throw e; await sleep(pauseMs); } } } finally { state.held.delete(qid); state.onChange?.(); } } /** * Prune terminal steps (and their logs) older than `days`. Blocked steps whose * reason went with them are kept: they still say why. */ export async function pruneSteps(dir, { days = KEEP_DAYS, now = () => new Date() } = {}) { const cutoff = now().getTime() - days * 86_400_000; const removed = []; await withQueueLock(dir, async () => { for (const s of await listSteps(dir)) { if (!TERMINAL.has(s.state) || !s.endedAt || Date.parse(s.endedAt) > cutoff) continue; await rm(stepFile(dir, s.qid), { force: true }); const logs = await readdir(path.join(dir, "logs")).catch(() => []); for (const n of logs) if (n === `${s.qid}.log` || n.startsWith(`${s.qid}.`)) await rm(path.join(dir, "logs", n), { force: true }); removed.push(s.qid); } }); return removed; }