// RENDER MODE — a render the operator is waiting for gets the machine.
//
// The heavy slot (scripts/queue-lock.mjs) admits by MEMORY. A render the
// operator is watching is slowed by CPU, not memory: measured 2026-10-30, the
// render peaked under 1 GB in its scope while cutting and ~200 MB per Chromium
// worker while capturing, and what dragged it was parakeet ASR from the
// transcription lane, the editor, and e2e servers and browsers beside it. So
// render mode is a machine-global flag, one small JSON file, that:
//
// - makes every OTHER heavy job wait at the slot's door (queue-lock.mjs
// withHeavy: e2e suites, `next build`s, the publish stages, other renders)
// with `queue-lock: held for a render (umtool take
--id , since
// 13:31) — waiting`; a job carrying the hold's token (the render and its
// subprocesses: RENDER_PRIORITY_TOKEN) is admitted, with the floor 4000 MB
// and the cap 10240 MB unless HEAVY_MIN_FREE_MB / HEAVY_CAP_MB say
// otherwise;
// - holds the editor's transcription, download and Speakers lanes, remembering which
// ones IT held (`lanesHeld`), so ending it releases only those — a lane
// someone else held before stays held.
//
// Turned on by `umtool take … --priority` (for the take's lifetime),
// `umtool render-mode on [--for 90m]` (a window, e.g. a chain of renders) or
// `pnpm ops render-mode {"on": true}`; AGENTS.md "Render mode".
//
// THE FILE sits beside the heavy slot's lock: `.render.json`, i.e.
// `/heavy-queue.lock.render.json` on this machine (one for
// every worktree), beside a HEAVY_LOCK_FILE when one is set (so the gate's
// tests have their own), or wherever RENDER_PRIORITY_FILE says. Its shape:
//
// { version: 1, token, since, until | null, by, note | null,
// holder: { pid, pidStart, cmd, project, take } | null,
// lanesHeld: ["transcription", …], lanesSkipped: [...], editor | null }
//
// LIVENESS, so a crash never leaves a hold: a holder whose pid is gone (or
// reused: pidStart), or an `until` in the past, is NOT held — queue-lock
// ignores it at once. Its lanes are released by whoever next looks with an
// editor in hand (`reapRenderMode`: the editor's heartbeat, /jobs, `render-mode
// status`, the next `on`). A manual window always carries an `until` (2 h by
// default), so a forgotten one ends by itself.
//
// Plain JS with JSDoc, no dependencies: queue-lock.mjs runs it under bare node,
// umtool's CLI and app and the editor import it as it is.
import { execFileSync } from "node:child_process";
import { randomBytes } from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { tmpPathFor } from "./atomicFile.mjs";
/** The memory floor a render in render mode is admitted on, absent HEAVY_MIN_FREE_MB. */
export const RENDER_PRIORITY_FLOOR_MB = 4000;
/** The render's heavy cap (MemoryMax) in render mode, absent HEAVY_CAP_MB. */
export const RENDER_PRIORITY_CAP_MB = 10240;
/** The editor lanes render mode holds: the GPU transcription lane, downloads, and
* the Speakers (backfill) lane — CPU diarization, ~4 cores, which a render wants. */
export const RENDER_MODE_LANES = Object.freeze(["transcription", "download", "backfill"]);
/** A manual window with no --for ends after this. */
export const DEFAULT_RENDER_MODE_WINDOW_MS = 2 * 60 * 60 * 1000;
/** The env var a render (and everything under it) carries the hold's token in. */
export const RENDER_PRIORITY_TOKEN_ENV = "RENDER_PRIORITY_TOKEN";
/** The one line said to the operator when render mode goes on. */
export const RENDER_MODE_REMINDER = "close Firefox and other heavy apps while this renders";
const HEAVY_LOCK_NAME = "heavy-queue.lock";
const STATE_SUFFIX = ".render.json";
/**
* @typedef {{ pid: number, pidStart?: string | null, cmd?: string | null, project?: string | null, take?: string | null }} RenderHolder
* @typedef {{
* version: 1, token: string, since: string, until: string | null, by: string | null, note: string | null,
* holder: RenderHolder | null, lanesHeld: string[], lanesSkipped?: string[], lanesError?: string | null,
* editor?: string | null, ended?: boolean,
* }} RenderPriorityState
* @typedef {{ held: boolean, state: RenderPriorityState | null, stale: null | "expired" | "holder-gone" | "no-end" }} RenderPriorityStatus
* @typedef {{ isHeld: (lane: string) => Promise, hold: (lane: string) => Promise, release: (lane: string) => Promise }} RenderModeLanes
*/
// ---------------------------------------------------------------- the file
/** The git common dir of `cwd` (one for every worktree), or null. */
function gitCommonDir(cwd) {
try {
const out = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
return out || null;
} catch {
return null;
}
}
/**
* Where render mode's state lives: RENDER_PRIORITY_FILE; else beside the heavy
* slot's lock — `heavyLock` (queue-lock hands its own), HEAVY_LOCK_FILE, or the
* one in the git common dir of `root` (default: the cwd; a CLI run from a
* report workspace passes its checkout) — as queue-lock.mjs finds it, a tmpdir
* outside a git checkout (a container).
* @param {Record} [env]
* @param {{ heavyLock?: string | null, root?: string }} [opts]
*/
export function renderPriorityFile(env = process.env, { heavyLock = null, root = process.cwd() } = {}) {
if (env.RENDER_PRIORITY_FILE) return env.RENDER_PRIORITY_FILE;
return `${heavyLock ?? heavyLockFile(env, { root })}${STATE_SUFFIX}`;
}
/**
* The heavy slot's lock, as queue-lock.mjs finds it: HEAVY_LOCK_FILE, else
* `heavy-queue.lock` in the git common dir of `root` (one for every
* worktree), a tmpdir outside a git checkout. Its running and waiting
* tickets sit beside it (common/lib/heavyQueue.mjs reads them).
* @param {Record} [env]
* @param {{ root?: string }} [opts]
*/
export function heavyLockFile(env = process.env, { root = process.cwd() } = {}) {
return env.HEAVY_LOCK_FILE ?? path.join(/* turbopackIgnore: true */ gitCommonDir(root) ?? os.tmpdir(), HEAVY_LOCK_NAME);
}
/** The file's JSON, or null (missing, half-written, not ours). */
export function readRenderPriorityState(file) {
try {
const s = JSON.parse(fs.readFileSync(/* turbopackIgnore: true */ file, "utf8"));
return s && typeof s === "object" && typeof s.token === "string" ? /** @type {RenderPriorityState} */ (s) : null;
} catch {
return null;
}
}
/** tmp + rename, so a reader never sees half a file. */
function writeState(file, state) {
fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
const tmp = tmpPathFor(file);
fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`);
fs.renameSync(tmp, file);
}
/**
* Create the file only if there is none: a hard link of a written temp file
* fails with EEXIST when another hold got there first, so two `on`s at once
* cannot both win. True when created.
*/
function createState(file, state) {
fs.mkdirSync(/* turbopackIgnore: true */ path.dirname(file), { recursive: true });
const tmp = tmpPathFor(file);
fs.writeFileSync(/* turbopackIgnore: true */ tmp, `${JSON.stringify(state, null, 2)}\n`);
try {
fs.linkSync(tmp, file);
return true;
} catch (err) {
if (/** @type {NodeJS.ErrnoException} */ (err).code === "EEXIST") return false;
throw err;
} finally {
fs.rmSync(/* turbopackIgnore: true */ tmp, { force: true });
}
}
/** Remove the file only while it is still the hold `token` names. */
function removeIfToken(file, token) {
const cur = readRenderPriorityState(file);
if (cur && cur.token !== token) return false;
fs.rmSync(/* turbopackIgnore: true */ file, { force: true });
return true;
}
// ---------------------------------------------------------------- liveness
/** /proc//stat's start time (field 22), so a reused pid is not the holder. Null off Linux. */
export function pidStartTime(pid) {
try {
const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19] ?? null;
} catch {
return null;
}
}
/** Whether the holder's process is still the one that took the hold. */
export function holderAlive(holder) {
if (!holder || !Number.isInteger(holder.pid)) return false;
try {
process.kill(holder.pid, 0);
} catch (err) {
if (/** @type {NodeJS.ErrnoException} */ (err).code !== "EPERM") return false;
}
return holder.pidStart == null || pidStartTime(holder.pid) === holder.pidStart;
}
/**
* Whether a state is a hold now, pure but for `isAlive`. A holder pid that is
* gone, an `until` in the past, or a state with neither (a hold nothing would
* ever end) is not held — `stale` says which.
* @param {RenderPriorityState | null} state
* @param {{ now?: number, isAlive?: (h: RenderHolder) => boolean }} [opts]
* @returns {RenderPriorityStatus}
*/
export function renderPriorityStatus(state, { now = Date.now(), isAlive = holderAlive } = {}) {
if (!state) return { held: false, state: null, stale: null };
const untilMs = state.until ? Date.parse(state.until) : NaN;
if (Number.isFinite(untilMs) && untilMs <= now) return { held: false, state, stale: "expired" };
if (state.holder && state.holder.pid != null) {
if (!isAlive(state.holder)) return { held: false, state, stale: "holder-gone" };
} else if (!Number.isFinite(untilMs)) {
return { held: false, state, stale: "no-end" };
}
return { held: true, state, stale: null };
}
/**
* Render mode as it stands: `{held, state, stale}`.
* @param {string} file
* @param {{ now?: number, isAlive?: (h: RenderHolder) => boolean }} [opts]
*/
export function readRenderPriority(file, opts = {}) {
return renderPriorityStatus(readRenderPriorityState(file), opts);
}
// ------------------------------------------------------- what the gate asks
/**
* Whether render mode makes a heavy job wait: it is held, the job does not
* carry its token, and nobody said RENDER_PRIORITY=0. `urgent` (a live
* stream's few seconds of browser) never waits.
* @param {RenderPriorityStatus} status
* @param {Record} [env]
* @param {{ urgent?: boolean }} [opts]
*/
export function renderPriorityBlocks(status, env = process.env, { urgent = false } = {}) {
if (!status?.held || !status.state || urgent || env.RENDER_PRIORITY === "0") return false;
return env[RENDER_PRIORITY_TOKEN_ENV] !== status.state.token;
}
/** Whether `env` carries the token of the hold `status` names (the render itself). */
export function carriesRenderPriority(status, env = process.env) {
return Boolean(status?.held && status.state && env[RENDER_PRIORITY_TOKEN_ENV] === status.state.token);
}
/**
* The render's own defaults, into `env` where it leaves them unset: the floor
* 4000 MB, the cap 10240 MB. Returns the names it set.
* @param {Record} env
*/
export function applyRenderPriorityDefaults(env) {
const set = [];
if (env.HEAVY_MIN_FREE_MB == null || env.HEAVY_MIN_FREE_MB === "") {
env.HEAVY_MIN_FREE_MB = String(RENDER_PRIORITY_FLOOR_MB);
set.push("HEAVY_MIN_FREE_MB");
}
if (env.HEAVY_CAP_MB == null || env.HEAVY_CAP_MB === "") {
env.HEAVY_CAP_MB = String(RENDER_PRIORITY_CAP_MB);
set.push("HEAVY_CAP_MB");
}
return set;
}
/** "13:31", local time, or "?". */
export function clockOf(iso) {
const ms = Date.parse(String(iso ?? ""));
if (!Number.isFinite(ms)) return "?";
const d = new Date(ms);
return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
}
/**
* What the hold is, in a waiter's words: "umtool take --id , since
* 13:31" or "render mode on (by umtool) — a chain, since 13:31, until 15:31".
* @param {RenderPriorityState} state
*/
export function describeRenderPriority(state) {
const h = state.holder;
const what = h?.cmd
? String(h.cmd).slice(0, 100)
: h?.project
? `umtool take ${h.project}${h.take ? ` --id ${h.take}` : ""}`
: h
? `pid ${h.pid}`
: `render mode on${state.by ? ` (by ${state.by})` : ""}`;
const note = state.note ? ` — ${state.note}` : "";
const until = state.until ? `, until ${clockOf(state.until)}` : "";
return `${what}${note}, since ${clockOf(state.since)}${until}`;
}
// ------------------------------------------------------------ on and off
/**
* "90m", "2h", "1h30m", "45s", or a number of minutes -> ms; null when it is
* none of those.
* @param {unknown} v
*/
export function parseDurationMs(v) {
if (typeof v === "number") return Number.isFinite(v) && v > 0 ? Math.round(v * 60_000) : null;
const s = String(v ?? "").trim().toLowerCase();
if (/^\d+(\.\d+)?$/.test(s)) return parseDurationMs(Number(s));
const m = /^(?:(\d+(?:\.\d+)?)h)?(?:(\d+(?:\.\d+)?)m)?(?:(\d+(?:\.\d+)?)s)?$/.exec(s);
if (!s || !m || (!m[1] && !m[2] && !m[3])) return null;
const ms = (Number(m[1] ?? 0) * 3600 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0)) * 1000;
return ms > 0 ? Math.round(ms) : null;
}
/**
* Release each of `lanes` through the editor; the ones that would not be.
* @param {string[]} names
* @param {RenderModeLanes | null} lanes
*/
async function releaseLanes(names, lanes) {
const released = [];
const failed = [];
for (const lane of names ?? []) {
if (!lanes) {
failed.push({ lane, error: "no editor to release it through" });
continue;
}
try {
await lanes.release(lane);
released.push(lane);
} catch (err) {
failed.push({ lane, error: err instanceof Error ? err.message : String(err) });
}
}
return { released, failed };
}
/**
* Turn render mode on. `holder` is the render's process (`umtool take
* --priority`: the hold ends with it); null is a manual window, which ends at
* `forMs` (default 2 h). A hold already on is NOT taken over: `{ok: false,
* held}`. A stale one is ended first (its lanes released). Then each of
* RENDER_MODE_LANES the editor does not already hold is held, and recorded as
* ours — the record is written after each, so a crash never forgets one.
*
* @param {{ file: string, holder?: RenderHolder | null, forMs?: number | null, note?: string | null,
* by?: string | null, editor?: string | null, lanes?: RenderModeLanes | null, now?: () => number,
* isAlive?: (h: RenderHolder) => boolean, token?: string }} o
*/
export async function renderModeOn({
file,
holder = null,
forMs = null,
note = null,
by = null,
editor = null,
lanes = null,
now = Date.now,
isAlive = holderAlive,
token = randomBytes(8).toString("hex"),
}) {
let reaped = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
const cur = readRenderPriority(file, { now: now(), isAlive });
if (cur.held && cur.state) return { ok: false, held: cur.state, reaped };
// A stale hold is ended first. A lane it could not release (no editor
// answering) is still render mode's: this hold inherits it, to release at
// its own end, rather than leave a record nothing will ever clear.
let inherited = [];
if (cur.state) {
reaped = await renderModeOff({ file, token: cur.state.token, lanes });
inherited = reaped.failed.map((f) => f.lane);
if (inherited.length) removeIfToken(file, cur.state.token);
}
const t = now();
const ms = forMs ?? (holder ? null : DEFAULT_RENDER_MODE_WINDOW_MS);
/** @type {RenderPriorityState} */
const state = {
version: 1,
token,
since: new Date(t).toISOString(),
until: ms ? new Date(t + ms).toISOString() : null,
by,
note: note ? String(note).slice(0, 200) : null,
holder: holder ? { pidStart: pidStartTime(holder.pid), ...holder } : null,
lanesHeld: [...inherited],
lanesSkipped: [],
editor,
};
if (!createState(file, state)) continue; // another `on` won the race: look again
const failed = [];
for (const lane of lanes ? RENDER_MODE_LANES : []) {
if (state.lanesHeld.includes(lane)) continue; // inherited: ours already
try {
if (await /** @type {RenderModeLanes} */ (lanes).isHeld(lane)) {
state.lanesSkipped?.push(lane); // someone else's hold: never ours to release
} else {
await /** @type {RenderModeLanes} */ (lanes).hold(lane);
state.lanesHeld.push(lane);
}
} catch (err) {
failed.push(`${lane}: ${err instanceof Error ? err.message : String(err)}`);
}
writeState(file, state);
}
if (!lanes) state.lanesError = "no editor: the lanes were not held";
else if (failed.length) state.lanesError = failed.join("; ");
writeState(file, state);
return { ok: true, state, reaped };
}
const cur = readRenderPriority(file, { now: now(), isAlive });
return { ok: false, held: cur.state, reaped };
}
/**
* Turn render mode off: release the lanes IT held (only those), then remove
* the file. `token` names the hold being ended — a different one is left alone
* (`{ok: false, notOurs}`) unless `force`. A lane the editor would not release
* keeps the record, ended (`until` now, no holder): not a hold any more, and
* the next reaper with an editor releases it.
*
* @param {{ file: string, token?: string | null, lanes?: RenderModeLanes | null, force?: boolean, now?: () => number }} o
*/
export async function renderModeOff({ file, token = null, lanes = null, force = false, now = Date.now }) {
const state = readRenderPriorityState(file);
if (!state) return { ok: true, was: null, released: [], failed: [] };
if (token && state.token !== token && !force) return { ok: false, notOurs: state, released: [], failed: [] };
const { released, failed } = await releaseLanes(state.lanesHeld, lanes);
if (failed.length) {
const cur = readRenderPriorityState(file);
if (!cur || cur.token === state.token) {
writeState(file, {
...state,
holder: null,
until: new Date(now()).toISOString(),
ended: true,
lanesHeld: failed.map((f) => f.lane),
lanesError: failed.map((f) => `${f.lane}: ${f.error}`).join("; "),
});
}
} else {
removeIfToken(file, state.token);
}
return { ok: true, was: state, released, failed };
}
/**
* End a hold that is no longer one (its holder gone, its window over): its
* lanes released, its file removed. Null when there is nothing stale. Called
* by whoever has an editor to release through. `owns(state)`, when given, says
* whether the lanes it records are that editor's (its `editor`): another
* editor's stale hold is left for that one.
* @param {{ file: string, lanes: RenderModeLanes | null, now?: () => number, isAlive?: (h: RenderHolder) => boolean, owns?: (s: RenderPriorityState) => boolean }} o
*/
export async function reapRenderMode({ file, lanes, now = Date.now, isAlive = holderAlive, owns }) {
const s = readRenderPriority(file, { now: now(), isAlive });
if (!s.state || s.held) return null;
if (owns && s.state.lanesHeld?.length && !owns(s.state)) return null;
return renderModeOff({ file, token: s.state.token, lanes, now });
}
/**
* Whether an `editor` a hold records (the URL its lanes were held through) is
* the editor listening on `port` here: a loopback host and that port.
* @param {string | null | undefined} editor
* @param {string | number} port
*/
export function isLocalEditor(editor, port) {
try {
const u = new URL(String(editor ?? ""));
const host = u.hostname.replace(/^\[|\]$/g, "");
const p = u.port || (u.protocol === "https:" ? "443" : "80");
return ["localhost", "127.0.0.1", "::1", "0.0.0.0"].includes(host) && p === String(port);
} catch {
return false;
}
}