// EVERY RENDER RECORDS ITSELF (operator, 4 Nov 2026, after mid-13's render // died at exit 1 behind a grep-filtered shell chain, and the next chain read // its unconditional "DONE" as success): a take's render writes its own record, // whoever started it -- a terminal, the Takes page's job, the durable queue // (lib/queue/) -- so a failure is never only in a scrollback somebody filtered. // // takes//render.json the LAST run's record, written atomically (tmp + rename) // takes//render.log that run's log, FULL and unfiltered: every line the // take maker said, every line build-video and // queue-lock wrote, every NDJSON event as it came // // The record: // // { version: 1, project, take, label, state, pid, pidStart, host, argv, // startedAt, updatedAt, endedAt, exitCode, // stage, percent, entries: { done, of }, from the build's NDJSON events // error, message, tail, on failed: the first error line // (or the thrown message), the // message itself, the log's last 40 lines // log: "render.log", // mp4, mp4Bytes, seconds } on done: the take's preview and // its measured length (ffprobe) // // state running the take process is setting up or rendering // waiting its render waits at the machine's heavy slot (queue-lock said so) // done exit 0 AND a non-empty mp4 -- never otherwise // failed anything else: a thrown error, a non-zero exit, an mp4 that is // missing or 0 bytes, or (on read) a "running" whose process is gone // cancelled stopped by `umtool takes cancel` / the Takes page's Cancel // ("queued" is not written here: a take step waiting in the durable queue is the // queue's, and `umtool take status` reads it from there.) // // ON READ (readRenderRecord), never trusted as written: a record that says // running or waiting on THIS host whose pid is gone -- or is another process now // (its start time, /proc//stat, differs) -- reads failed, "the render // process is gone"; a done whose mp4 is missing or empty reads failed too. // // Who writes it: makeTake (takeMaker.mjs), once the take's directory exists; a // refused rebuild of a take that exists records the refusal. A take whose first // render is refused before its directory is made leaves no directory (as before) // and so no record: the command's exit code and stderr say why. // // Beside it, for `umtool jobs` (lib/queue/cli.mjs): a pointer per take in the // queue dir's renders/ (`~.json`, overwritten per run), written // only for a project under the reports root -- a temp project in a test writes // none. // // Plain ESM: the CLI runs it under bare node. import { createWriteStream, readFileSync } from "node:fs"; import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; export const RENDER_FILE = "render.json"; export const RENDER_LOG = "render.log"; export const RENDER_STATES = Object.freeze(["queued", "waiting", "running", "done", "failed", "cancelled"]); /** How many of the log's last lines a failed record carries. */ export const TAIL_LINES = 40; /** The least time between two progress writes of the record (ms); a change of state writes at once. */ export const WRITE_EVERY_MS = 1000; /** * `umtool take status`'s exit code for a state: 0 done, 3 still going * (queued, waiting, running), 1 anything else (failed, cancelled, none). * @param {string | null | undefined} state */ export function statusExitCode(state) { if (state === "done") return 0; if (state === "queued" || state === "waiting" || state === "running") return 3; return 1; } /** * A process's start time (clock ticks since boot, /proc//stat field 22), * or null where there is no /proc (or no such process). With the pid it names * ONE process: a pid reused after a crash has another start time. * @param {number} pid */ export function procStartTime(pid) { if (!Number.isInteger(pid) || pid <= 0) return null; try { const text = readFileSync(/* turbopackIgnore: true */ `/proc/${pid}/stat`, "utf8"); // The command name (field 2) is in parentheses and may hold spaces: split after the last ')'. const rest = text.slice(text.lastIndexOf(")") + 2).split(" "); const v = Number(rest[19]); return Number.isFinite(v) ? v : null; } catch { return null; } } /** * Is the process this record names alive here? `start` (procStartTime when it * was written) must still match when both sides know it. * @param {number} pid * @param {number | null | undefined} [start] */ export function processAlive(pid, start = null) { if (!Number.isInteger(pid) || pid <= 0) return false; try { process.kill(pid, 0); } catch (err) { if (/** @type {NodeJS.ErrnoException} */ (err)?.code !== "EPERM") return false; } if (start == null) return true; const now = procStartTime(pid); return now == null || now === start; } const ERROR_LINE = /\b(error|errors|failed|fatal|refused|cannot|can't|could not|not found|no such|ENOENT|EACCES|Traceback|exited \d+|killed|out of memory|OOM)\b|^\s*\*\*/i; /** A thrown message that names no cause: the exit code alone. */ const BARE_EXIT = /^(build-video|node|\S+) exited \d+$/; /** * The first line of a log that reads as an error (not a JSON event), or null. * @param {string[]} lines */ export function firstErrorLine(lines) { for (const l of lines) { const t = String(l).trim(); if (!t || t.startsWith("{")) continue; if (ERROR_LINE.test(t)) return t.length > 400 ? `${t.slice(0, 400)}…` : t; } return null; } /** * The record's `error`: the thrown message when it names a cause; when it is a * bare "build-video exited 1", the first error line of the log, with the exit after it. * @param {string} message * @param {string[]} lines */ export function errorOf(message, lines) { const first = firstErrorLine(lines); if (!BARE_EXIT.test(message.trim())) return message; return first && !first.includes(message) ? `${first} — ${message}` : message; } /** * The stage and a rough percent from one of build-video's NDJSON events (its * protocol: start, card, clip, fetch, snap, segment, entry-failed, concat, * chapters, youtube, chrome, narrate, note, done) and the take maker's own * (`take`, phase render/done/failed). Rough on purpose: segments are 5-60 %, * the deck's chrome 60-85, the concat 90, the chapters and youtube file 95. * * @param {Record} ev * @param {{ stage: string | null, percent: number | null, entries: { done: number, of: number | null } }} prev */ export function progressOf(ev, prev) { const entries = { ...prev.entries }; let stage = prev.stage; let percent = prev.percent; const bump = (p) => { percent = Math.max(percent ?? 0, Math.min(99, Math.round(p))); }; switch (ev?.ev) { case "take": if (ev.phase === "render") { stage = "render"; bump(1); } break; case "start": stage = "cutting"; entries.of = Number.isFinite(Number(ev.entries)) ? Number(ev.entries) : entries.of; bump(3); break; case "fetch": case "clip": case "card": case "snap": case "pieces": case "narrate": stage = "cutting"; break; case "segment": stage = "cutting"; entries.done += 1; if (entries.of) bump(5 + (55 * Math.min(entries.done, entries.of)) / entries.of); break; case "chrome": stage = `chrome ${ev.phase ?? ""}`.trim(); bump(ev.phase === "render" ? 70 : ev.phase === "overlay" ? 85 : 62); break; case "concat": stage = "concat"; bump(90); break; case "chapters": case "youtube": stage = "finishing"; bump(95); break; case "done": stage = "muxed"; bump(99); break; default: break; } return { stage, percent, entries }; } /** A line of queue-lock (scripts/queue-lock.mjs) that says the render waits at the heavy slot's door. */ export const WAITING_LINE = /^(queue-lock|heavy):.*\b(waiting|held for a render)\b/i; /** A line that says it was let in. */ const ADMITTED_LINE = /^(queue-lock|heavy):.*\b(admitted|acquired|going on)\b/i; async function writeAtomic(file, doc) { const tmp = tmpPathFor(file); await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); await rename(tmp, file); } /** * The queue dir (lib/queue/store.mjs queueDirOf) without importing the queue: * UMTOOL_QUEUE_DIR, else `/.umtool-queue`. * @param {string} reportsRoot * @param {Record} [env] */ export const queueDirFor = (reportsRoot, env = process.env) => path.resolve(env.UMTOOL_QUEUE_DIR || path.join(reportsRoot, ".umtool-queue")); /** The pointer file of a project's take in the queue dir's renders/. */ export const renderPointerFile = (queueDir, project, take) => path.join(queueDir, "renders", `${encodeURIComponent(project)}~${take}.json`); /** * The project's id when its directory is under the reports root, else null. * @param {string} projectDir * @param {string} reportsRoot */ export function projectIdUnder(projectDir, reportsRoot) { const rel = path.relative(path.resolve(reportsRoot), path.resolve(projectDir)); if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return null; return rel.split(path.sep).join("/"); } /** * Open the record of a run of take `take` in `takeDir` (which exists): writes * `running` and truncates render.log. Returns the recorder the take maker feeds. * * @param {string} takeDir * @param {{ take: string, projectDir?: string, project?: string | null, label?: string | null, argv?: string[], * reportsRoot?: string | null, env?: Record, now?: () => Date, pid?: number, host?: string, * writeEveryMs?: number, earlier?: string[] }} o * `earlier`: lines said before the directory existed (written to the log first). */ export async function openRenderRecord(takeDir, o) { const now = o.now ?? (() => new Date()); const pid = o.pid ?? process.pid; const file = path.join(takeDir, RENDER_FILE); const logPath = path.join(takeDir, RENDER_LOG); const project = o.project ?? (o.projectDir && o.reportsRoot ? projectIdUnder(o.projectDir, o.reportsRoot) : null) ?? (o.projectDir ? path.basename(o.projectDir) : null); const startedAt = now().toISOString(); /** @type {Record} */ const doc = { version: 1, project, take: o.take, label: o.label ?? null, // A take's window preview (takePreview.mjs): the cut seconds it was asked for. ...(o.window ? { window: { at: o.window.at, dur: o.window.dur } } : {}), state: "running", pid, pidStart: procStartTime(pid), host: o.host ?? os.hostname(), argv: o.argv ?? process.argv.slice(2), startedAt, updatedAt: startedAt, endedAt: null, exitCode: null, stage: "setting up", percent: 0, entries: { done: 0, of: null }, error: null, message: null, tail: [], log: RENDER_LOG, mp4: null, mp4Bytes: null, seconds: null, }; const lines = []; const pushTail = (l) => { lines.push(l); if (lines.length > 4000) lines.splice(0, lines.length - 4000); }; const log = createWriteStream(/* turbopackIgnore: true */ logPath, { flags: "w" }); let logOk = true; log.on("error", () => { logOk = false; }); const writeLog = (s) => { if (logOk) log.write(s.endsWith("\n") ? s : `${s}\n`); }; writeLog(`# umtool take ${doc.argv.join(" ")}`); writeLog(`# pid ${pid} on ${doc.host}, ${startedAt}`); for (const l of o.earlier ?? []) { writeLog(l); pushTail(l); } // Writes are chained (one at a time) and progress is throttled; a state change writes at once. let chain = Promise.resolve(); let timer = null; let ended = false; const every = o.writeEveryMs ?? WRITE_EVERY_MS; const write = () => { doc.updatedAt = now().toISOString(); const snap = JSON.parse(JSON.stringify(doc)); chain = chain.then(() => writeAtomic(file, snap)).catch(() => {}); return chain; }; const soon = () => { if (timer || ended) return; timer = setTimeout(() => { timer = null; if (!ended) void write(); }, every); timer.unref?.(); }; await write(); // The pointer `umtool jobs` lists renders by (best effort: a render never fails for it). const root = o.reportsRoot ?? null; if (root && o.projectDir && projectIdUnder(o.projectDir, root)) { const ptr = renderPointerFile(queueDirFor(root, o.env), /** @type {string} */ (projectIdUnder(o.projectDir, root)), o.take); await mkdir(path.dirname(ptr), { recursive: true }) .then(() => writeAtomic(ptr, { project: projectIdUnder(o.projectDir ?? "", root), projectDir: path.resolve(o.projectDir ?? ""), take: o.take, startedAt, pid })) .catch(() => {}); } let built = false; const finish = async () => { ended = true; if (timer) clearTimeout(timer); timer = null; doc.endedAt = now().toISOString(); await write(); await new Promise((r) => { if (!logOk) return r(undefined); log.end(() => r(undefined)); }); }; return { file, logFile: logPath, get state() { return doc.state; }, /** One line of prose, as the take maker or the render said it. */ line(l) { const s = String(l); writeLog(s); for (const part of s.split("\n")) { if (!part.trim()) continue; pushTail(part); if (ended) continue; if (!built && doc.state === "running" && WAITING_LINE.test(part)) { doc.state = "waiting"; doc.stage = "waiting for the heavy slot"; void write(); } else if (doc.state === "waiting" && ADMITTED_LINE.test(part)) { doc.state = "running"; doc.stage = "render"; void write(); } } }, /** One NDJSON event (build-video's or the take maker's). */ event(ev) { writeLog(JSON.stringify(ev)); if (ended) return; if (ev?.ev !== "take") built = true; const p = progressOf(ev, doc); doc.stage = p.stage; doc.percent = p.percent; doc.entries = p.entries; if (doc.state === "waiting" && ev?.ev !== "take") { doc.state = "running"; void write(); } else soon(); }, /** * The render is done: `mp4` must be a non-empty file, or the record says failed. * @param {{ mp4: string, seconds?: number | null }} r */ async done({ mp4, seconds = null }) { if (ended) return doc; const st = await stat(/* turbopackIgnore: true */ mp4).catch(() => null); doc.mp4 = path.relative(takeDir, mp4) || path.basename(mp4); doc.mp4Bytes = st?.size ?? null; if (!st || !st.isFile() || st.size === 0) { doc.state = "failed"; doc.exitCode = 1; doc.message = !st ? `the render recorded no mp4: ${mp4} is not there` : `the render's mp4 is empty (0 bytes): ${mp4}`; doc.error = doc.message; doc.tail = lines.slice(-TAIL_LINES); } else { doc.state = "done"; doc.exitCode = 0; doc.stage = "done"; doc.percent = 100; doc.seconds = typeof seconds === "number" && Number.isFinite(seconds) ? seconds : null; if (doc.seconds === null) writeLog("# ffprobe could not measure the mp4: seconds is null"); } writeLog(`# ${doc.state}${doc.state === "done" ? ` — ${doc.mp4} (${doc.mp4Bytes} bytes${doc.seconds != null ? `, ${doc.seconds} s` : ""})` : ` — ${doc.error}`}`); await finish(); return doc; }, /** * The run failed (or was cancelled). * @param {unknown} err * @param {{ cancelled?: boolean, exitCode?: number }} [o2] */ async fail(err, { cancelled = false, exitCode = 1 } = {}) { if (ended) return doc; const message = err instanceof Error ? err.message : String(err); doc.state = cancelled ? "cancelled" : "failed"; doc.exitCode = exitCode; doc.message = message; doc.error = cancelled ? message : errorOf(message, lines); doc.tail = lines.slice(-TAIL_LINES); writeLog(`# ${doc.state} — ${doc.error}`); await finish(); return doc; }, /** Wait for the writes so far (tests). */ flush: () => chain, }; } /** * A record as written, read back and resolved -- or null when there is none. * * @param {string} takeDir * @param {{ host?: string, alive?: (pid: number, start?: number | null) => boolean }} [opts] * @returns {Promise | null>} */ export async function readRenderRecord(takeDir, opts = {}) { let raw; try { raw = JSON.parse(await readFile(/* turbopackIgnore: true */ path.join(takeDir, RENDER_FILE), "utf8")); } catch { return null; } if (!raw || typeof raw !== "object" || Array.isArray(raw) || !RENDER_STATES.includes(raw.state)) return null; const mp4Abs = raw.mp4 ? path.resolve(takeDir, raw.mp4) : null; const mp4 = raw.state === "done" && mp4Abs ? await stat(/* turbopackIgnore: true */ mp4Abs).catch(() => null) : null; return resolveRecord(raw, { ...opts, mp4: mp4 ? { size: mp4.size, isFile: mp4.isFile() } : null, takeDir }); } /** * Pure: what a record written as `raw` says now. A running/waiting record on * this host whose process is gone reads failed; a done whose mp4 is missing or * empty reads failed. * * @param {Record} raw * @param {{ host?: string, alive?: (pid: number, start?: number | null) => boolean, mp4?: { size: number, isFile: boolean } | null, takeDir?: string }} [o] * @returns {Record} */ export function resolveRecord(raw, { host = os.hostname(), alive = processAlive, mp4 = null, takeDir = "" } = {}) { /** @type {Record} */ const rec = { ...raw, gone: false }; const logRel = takeDir ? path.join(path.basename(takeDir), raw.log ?? RENDER_LOG) : raw.log ?? RENDER_LOG; if ((raw.state === "running" || raw.state === "waiting") && (!raw.host || raw.host === host) && !alive(Number(raw.pid), raw.pidStart ?? null)) { rec.state = "failed"; rec.gone = true; rec.message = `the render process is gone (pid ${raw.pid}) — it stopped without recording an end: killed, out of memory, or the machine restarted`; rec.error = `${rec.message}; its log: takes/${logRel}`; } else if (raw.state === "done" && (!mp4 || !mp4.isFile || mp4.size === 0)) { rec.state = "failed"; rec.message = !mp4 ? `done was recorded, but its mp4 (${raw.mp4 ?? "none named"}) is not there` : `done was recorded, but its mp4 (${raw.mp4}) is empty (0 bytes)`; rec.error = rec.message; } rec.exit = statusExitCode(rec.state); return rec; } /** * The record as lines, for `umtool take status` and `umtool jobs`. * @param {Record} rec resolved * @param {{ logPath?: string | null, tail?: number }} [o] */ export function recordLines(rec, { logPath = null, tail = 12 } = {}) { const out = []; const when = rec.endedAt ? `${String(rec.startedAt).slice(0, 19).replace("T", " ")} → ${String(rec.endedAt).slice(11, 19)}` : `since ${String(rec.startedAt).slice(0, 19).replace("T", " ")}`; const progress = rec.state === "running" || rec.state === "waiting" ? ` — ${rec.stage ?? "?"}${rec.percent != null ? ` ${rec.percent}%` : ""}${rec.entries?.of ? ` (${rec.entries.done}/${rec.entries.of} segments)` : ""}` : ""; out.push(`${rec.project ?? "?"} take ${rec.take}: ${rec.state.toUpperCase()}${progress} (${when}, pid ${rec.pid}${rec.exitCode != null ? `, exit ${rec.exitCode}` : ""})`); if (rec.state === "done") out.push(` mp4: takes/${rec.take}/${rec.mp4} (${rec.mp4Bytes} bytes${rec.seconds != null ? `, ${rec.seconds} s` : ", length not measured"})`); if (rec.error) out.push(` error: ${rec.error}`); if ((rec.state === "failed" || rec.state === "cancelled") && Array.isArray(rec.tail) && rec.tail.length && tail > 0) { out.push(` the log's last ${Math.min(tail, rec.tail.length)} lines:`); for (const l of rec.tail.slice(-tail)) out.push(` ${l}`); } if (logPath) out.push(` log: ${logPath}`); return out; }