// Render mode from umtool (renderMode.mjs): `umtool take … --priority`'s // lifetime hold, `umtool render-mode on|off|status`, and the editor lanes over // ops. Every test uses a temp state file and a fake editor — never the // machine's render mode or a live editor's lanes. Run with: pnpm test:scripts import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { fileURLToPath } from "node:url"; import { readRenderPriority, readRenderPriorityState } from "yt-dlp-transcript-common/lib/renderPriority.mjs"; import { editorLanes, renderModeCommand, withTakePriority } from "./renderMode.mjs"; import { takeCommand } from "./takeCli.mjs"; import { takeSteps } from "./takeMaker.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); function tmpFile() { return path.join(mkdtempSync(path.join(tmpdir(), "render-mode-")), "heavy.lock.render.json"); } /** A fake editor's lanes: `held` what it holds, `calls` what was asked. The * Speakers (backfill) lane starts held, as it ships — so these tests' calls are * the two lanes a render actually takes from a fresh install. */ function fakeLanes(initial = {}) { const held = { backfill: true, ...initial }; const calls = []; return { held, calls, lanes: { isHeld: async (lane) => held[lane] === true, hold: async (lane) => { calls.push(`hold ${lane}`); held[lane] = true; }, release: async (lane) => { calls.push(`release ${lane}`); held[lane] = false; }, }, }; } test("take --priority: on for the take (its lanes held, its token in the env), off at its end", async () => { const file = tmpFile(); const ed = fakeLanes({ download: true }); const env = {}; const lines = []; let during = null; const r = await withTakePriority({ priority: true, project: "ember", take: "t1", log: (l) => lines.push(l), env, file, lanes: ed.lanes, signals: false }, async () => { during = { status: readRenderPriority(file), token: env.RENDER_PRIORITY_TOKEN }; return "made"; }); assert.equal(r, "made"); assert.equal(during.status.held, true); assert.equal(during.status.state.holder.pid, process.pid); assert.equal(during.status.state.holder.cmd, "umtool take ember --id t1"); assert.equal(during.token, during.status.state.token, "the render inherits the token"); assert.deepEqual(ed.calls, ["hold transcription", "release transcription"], "download was held already: left alone"); assert.equal(ed.held.download, true); assert.equal(existsSync(file), false); assert.equal(env.RENDER_PRIORITY_TOKEN, undefined); assert.ok(lines.some((l) => /close Firefox and other heavy apps/.test(l))); assert.ok(lines.some((l) => /render mode off — lanes released: transcription/.test(l))); }); test("take --priority: a failed take lets go too", async () => { const file = tmpFile(); const ed = fakeLanes(); await assert.rejects( withTakePriority({ priority: true, project: "ember", take: "t1", log: () => {}, env: {}, file, lanes: ed.lanes, signals: false }, async () => { throw new Error("build-video exited 1"); }), /build-video exited 1/, ); assert.deepEqual(ed.calls, ["hold transcription", "hold download", "release transcription", "release download"]); assert.equal(existsSync(file), false); }); /** * A `take --priority` in a child process over fake lanes that log to a file. * `slowLane`: that lane's hold prints `holding ` and takes 400 ms — a * signal sent then lands mid-claim. The child is killed whatever the test does * (`stop`), so a failed assertion cannot leave it holding the runner open. */ function spawnTake({ slowLane = null, slowRelease = null } = {}) { const dir = mkdtempSync(path.join(tmpdir(), "render-mode-sig-")); const file = path.join(dir, "state.json"); const log = path.join(dir, "lanes.log"); const script = path.join(dir, "take.mjs"); writeFileSync( script, `import { appendFileSync } from "node:fs"; import { withTakePriority } from ${JSON.stringify(path.join(HERE, "renderMode.mjs"))}; const slow = ${JSON.stringify(slowLane)}; const slowRelease = ${JSON.stringify(slowRelease)}; const lanes = { isHeld: async () => false, hold: async (l) => { appendFileSync(${JSON.stringify(log)}, "hold " + l + "\\n"); if (l === slow) { console.log("holding " + l); await new Promise((r) => setTimeout(r, 400)); } }, release: async (l) => { if (l === slowRelease) { console.log("releasing " + l); await new Promise((r) => setTimeout(r, 400)); } appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"); }, }; await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => console.log(l), env: {}, file: ${JSON.stringify(file)}, lanes }, async () => { console.log("rendering"); await new Promise(() => setInterval(() => {}, 1000)); }); `, ); const child = spawn(process.execPath, [script], { stdio: ["ignore", "pipe", "pipe"] }); let out = ""; child.stdout.on("data", (d) => (out += d)); child.stderr.on("data", (d) => (out += d)); const exited = new Promise((r) => child.on("exit", (c, sig) => r({ code: c, signal: sig }))); return { file, log, child, exited, out: () => out, // A loaded machine can take many seconds to start node and import the // module; this is a backstop against a child that never gets there, not // a measure of how fast it should. async waitFor(re, ms = 90_000) { const t0 = Date.now(); while (!re.test(out)) { if (child.exitCode !== null || child.signalCode !== null) throw new Error(`exited before ${re}: ${out}`); if (Date.now() - t0 > ms) throw new Error(`no ${re} after ${ms} ms: ${out}`); await new Promise((r) => setTimeout(r, 20)); } }, async stop() { if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL"); await exited; await rm(dir, { recursive: true, force: true }); }, }; } test("take --priority killed by a signal: the hold ends before the process does", { timeout: 180_000 }, async () => { const take = spawnTake(); try { await take.waitFor(/render mode on for this take/); assert.equal(readRenderPriority(take.file).held, true); take.child.kill("SIGTERM"); const { code, signal } = await take.exited; assert.equal(code, 143, `exited ${code ?? signal}: ${take.out()}`); assert.equal(existsSync(take.file), false); assert.equal(readFileSync(take.log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); } finally { await take.stop(); } }); test("take --priority signalled twice: the second signal waits for the first's release, and the exit is the first's", { timeout: 180_000 }, async () => { // The second signal used to find the release begun, return at once and // exit — mid-way through letting the lanes go. const take = spawnTake({ slowRelease: "download" }); try { await take.waitFor(/rendering/); take.child.kill("SIGTERM"); await take.waitFor(/releasing download/); take.child.kill("SIGINT"); const { code, signal } = await take.exited; assert.equal(code, 143, `exited ${code ?? signal}: ${take.out()}`); assert.equal(existsSync(take.file), false, "the state file is gone"); assert.equal(readFileSync(take.log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); assert.equal(take.out().match(/render mode off/g)?.length, 1, `released once: ${take.out()}`); } finally { await take.stop(); } }); test("take --priority signalled while it claims: the claim finishes, is let go, and the take never starts", { timeout: 180_000 }, async () => { // The window the old order left open: the handlers went on only after the // claim, so a signal while the lanes were being held killed the process // with its state file and lanes still held. const take = spawnTake({ slowLane: "download" }); try { await take.waitFor(/holding download/); take.child.kill("SIGTERM"); const { code, signal } = await take.exited; assert.equal(code, 143, `exited ${code ?? signal}: ${take.out()}`); assert.equal(existsSync(take.file), false, "the state file is gone"); assert.equal(readFileSync(take.log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); assert.doesNotMatch(take.out(), /rendering/, "the take's work never started"); } finally { await take.stop(); } }); test("a take inside a manual window joins it (flag or not) and leaves it on; beside another render it takes nothing", async () => { const file = tmpFile(); const ed = fakeLanes(); assert.equal(await renderModeCommand(["on", "--for", "30m", "--note", "a chain"], { log: () => {}, err: () => {}, env: {}, file, lanes: ed.lanes }), 0); const window = readRenderPriorityState(file); for (const priority of [false, true]) { const env = {}; const lines = []; await withTakePriority({ priority, project: "p", take: "t", log: (l) => lines.push(l), env, file, lanes: ed.lanes, signals: false }, async () => { assert.equal(env.RENDER_PRIORITY_TOKEN, window.token); }); assert.match(lines[0], /render mode is on \(render mode on \(by umtool render-mode\) — a chain, since/); } assert.equal(readRenderPriority(file).held, true, "the window outlives the takes"); assert.deepEqual(ed.calls, ["hold transcription", "hold download"]); // A different render's hold: a --priority take renders without a token; nothing changes. const other = tmpFile(); writeFileSync(other, JSON.stringify({ version: 1, token: "theirs", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "umtool take x --id y" }, lanesHeld: [] })); const env = {}; const lines = []; await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => lines.push(l), env, file: other, lanes: ed.lanes, signals: false }, async () => { assert.equal(env.RENDER_PRIORITY_TOKEN, undefined); }); assert.match(lines[0], /held by another render \(umtool take x --id y/); assert.equal(readRenderPriorityState(other).token, "theirs"); }); test("without --priority and no window, a take is untouched", async () => { const file = tmpFile(); const ed = fakeLanes(); const env = {}; await withTakePriority({ priority: false, project: "p", take: "t", log: () => {}, env, file, lanes: ed.lanes, signals: false }, async () => {}); assert.deepEqual(ed.calls, []); assert.equal(existsSync(file), false); assert.equal(env.RENDER_PRIORITY_TOKEN, undefined); }); test("umtool render-mode on | status | off, with --json; off of a running take's hold needs --force", async () => { const file = tmpFile(); const ed = fakeLanes({ download: true }); const out = []; const err = []; const io = { log: (l) => out.push(l), err: (l) => err.push(l), env: {}, file, lanes: ed.lanes }; assert.equal(await renderModeCommand(["status"], io), 0); assert.equal(out.at(-1), "render mode is off"); assert.equal(await renderModeCommand(["on", "--for", "soon"], io), 2); assert.equal(await renderModeCommand(["on", "--for", "90m"], io), 0); assert.match(out.join("\n"), /render mode ON until \d\d:\d\d — lanes held: transcription \(download, backfill already held — left alone\)/); assert.match(out.join("\n"), /export RENDER_PRIORITY_TOKEN=[0-9a-f]{16}/); assert.equal(await renderModeCommand(["on"], io), 1, "already on"); out.length = 0; assert.equal(await renderModeCommand(["status", "--json"], io), 0); const st = JSON.parse(out.join("\n")); assert.equal(st.held, true); assert.deepEqual(st.state.lanesHeld, ["transcription"]); assert.equal(await renderModeCommand(["off"], io), 0); assert.deepEqual(ed.calls, ["hold transcription", "release transcription"]); assert.equal(ed.held.download, true); assert.equal(existsSync(file), false); // A running take's hold (this process) ends with the take, unless --force. writeFileSync(file, JSON.stringify({ version: 1, token: "take", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "umtool take p --id t" }, lanesHeld: [] })); assert.equal(await renderModeCommand(["off"], io), 1); assert.match(err.at(-1), /held by a running render .* --force ends it now/); assert.equal(await renderModeCommand(["off", "--force"], io), 0); assert.equal(existsSync(file), false); // A stale hold's lanes are released by the next status. writeFileSync(file, JSON.stringify({ version: 1, token: "dead", since: new Date().toISOString(), until: null, holder: { pid: 999999999 }, lanesHeld: ["transcription"] })); ed.held.transcription = true; out.length = 0; assert.equal(await renderModeCommand(["status"], io), 0); assert.match(out[0], /a stale render mode was ended — lanes released: transcription/); assert.equal(ed.held.transcription, false); assert.equal(await renderModeCommand(["bogus"], io), 2); }); test("editorLanes asks the editor's ops: settings?key=autoQueue to read, lane to hold and release; none without a token", async () => { assert.equal(editorLanes({ url: "http://e", token: "" }), null); const asked = []; const fetch = async (url, init) => { asked.push(`${init.method} ${url} ${init.body ?? ""} ${init.headers.authorization}`); if (String(url).includes("settings")) return new Response(JSON.stringify({ ok: true, key: "autoQueue", value: { download: { held: true }, transcription: { held: false } } })); return new Response(JSON.stringify({ ok: true })); }; const lanes = editorLanes({ url: "http://e", token: "tok", fetch }); assert.equal(await lanes.isHeld("download"), true); assert.equal(await lanes.isHeld("transcription"), false); await lanes.hold("transcription"); await lanes.release("transcription"); assert.deepEqual(asked, [ "GET http://e/api/ops/settings?key=autoQueue Bearer tok", "GET http://e/api/ops/settings?key=autoQueue Bearer tok", 'POST http://e/api/ops/lane {"lane":"transcription","held":true} Bearer tok', 'POST http://e/api/ops/lane {"lane":"transcription","held":false} Bearer tok', ]); const refusing = editorLanes({ url: "http://e", token: "tok", fetch: async () => new Response(JSON.stringify({ ok: false, error: "nope" }), { status: 400 }) }); await assert.rejects(refusing.hold("download"), /the editor refused \(HTTP 400\): nope/); }); test("takeSteps: priority runs every kind of take job with --priority", () => { const proj = { id: "reports/proj" }; const ctx = { styles: { flash: { label: "Flash" } }, existing: [{ id: "flash", window: "full" }], clipCount: 3 }; assert.ok(takeSteps(proj, { take: { label: "P" }, priority: true }, ctx).steps[0].argv.includes("--priority")); assert.ok(!takeSteps(proj, { take: { label: "P" } }, ctx).steps[0].argv.includes("--priority")); assert.ok(takeSteps(proj, { rebuild: "flash", priority: true }, ctx).steps[0].argv.includes("--priority")); assert.ok(takeSteps(proj, { allStyles: { group: "m" }, priority: true }, ctx).steps[0].argv.includes("--priority")); }); test("umtool take --priority: the take is made inside render mode, and render mode ends with it — done or failed", async () => { const root = mkdtempSync(path.join(tmpdir(), "render-mode-take-")); const dir = path.join(root, "reports", "proj"); await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true }); await writeFile( path.join(dir, "video.manifest.json"), JSON.stringify({ slug: "proj", render: { crf: 30 }, timeline: [{ id: "s01", type: "clip", channel: "c", video: "v", start: 0, end: 13 }] }, null, 2) + "\n", ); const file = path.join(root, "state.json"); const ed = fakeLanes(); let heldDuring = null; const render = async (job) => { heldDuring = readRenderPriority(file).held; const out = path.join(job.outDir, `${job.slug}.mp4`); await writeFile(out, "render"); return { file: out }; }; const io = { reportsRoot: path.join(root, "reports"), log: () => {}, err: () => {}, deps: { render, styles: {}, probe: async () => 1 }, renderMode: { file, lanes: ed.lanes, signals: false } }; try { assert.equal(await takeCommand(["proj", "--id", "p1", "--label", "P", "--set", "render.crf=31", "--full", "--priority"], io), 0); assert.equal(heldDuring, true); assert.equal(existsSync(file), false); assert.deepEqual(ed.calls, ["hold transcription", "hold download", "release transcription", "release download"]); const failing = { ...io, deps: { ...io.deps, render: async () => { throw new Error("cut failed"); } } }; assert.equal(await takeCommand(["proj", "--id", "p2", "--label", "P2", "--set", "render.crf=32", "--full", "--priority"], failing), 1); assert.equal(existsSync(file), false); assert.equal(ed.calls.length, 8); assert.ok(JSON.parse(await readFile(path.join(dir, "takes", "p1", "take.json"), "utf8"))); } finally { await rm(root, { recursive: true, force: true }); } }); test("render-mode on -- : held while the command runs (its pid the holder, its env the token), released at its exit, its code returned", async () => { const dir = mkdtempSync(path.join(tmpdir(), "render-mode-chain-")); const file = path.join(dir, "state.json"); const seen = path.join(dir, "seen.json"); const ed = fakeLanes({ download: true }); const out = []; const err = []; // The command waits for the hold (its lanes recorded), then records what it // saw — its env's token, the state file, its own pid — and exits 3. const waitThen = `const fs = require("node:fs"); const t0 = Date.now(); (function look() { try { const s = JSON.parse(fs.readFileSync(${JSON.stringify(file)}, "utf8")); if (s.lanesHeld && s.lanesHeld.length) { fs.writeFileSync(${JSON.stringify(seen)}, JSON.stringify({ token: process.env.RENDER_PRIORITY_TOKEN, state: s, pid: process.pid })); process.exit(3); } } catch {} if (Date.now() - t0 > 10000) process.exit(9); setTimeout(look, 20); })();`; const code = await renderModeCommand(["on", "--note", "the cut", "--", process.execPath, "-e", waitThen], { log: (l) => out.push(l), err: (l) => err.push(l), env: { PATH: process.env.PATH }, file, lanes: ed.lanes, signals: false, }); assert.equal(code, 3, "the command's exit code"); const s = JSON.parse(readFileSync(seen, "utf8")); assert.equal(s.token, s.state.token, "the command carries the hold's token"); assert.equal(s.state.holder.pid, s.pid, "the hold is the command's pid"); assert.equal(s.state.note, "the cut"); assert.equal(s.state.until, null, "no window: it ends with the command"); assert.match(s.state.holder.cmd, /-e/); assert.equal(existsSync(file), false, "released at the command's exit"); assert.deepEqual(ed.calls, ["hold transcription", "release transcription"], "download was held already: left alone"); assert.match(out.join("\n"), /render mode ON for [\s\S]* \(pid \d+\) — lanes held: transcription/); assert.match(out.join("\n"), /render mode off — lanes released: transcription/); }); test("render-mode on -- : --print-token puts the token alone on stdout; a failing spawn returns 127 and holds nothing", async () => { const file = tmpFile(); const ed = fakeLanes(); const out = []; const err = []; const io = { log: (l) => out.push(l), err: (l) => err.push(l), env: { PATH: process.env.PATH }, file, lanes: ed.lanes, signals: false }; assert.equal(await renderModeCommand(["on", "--print-token", "--", process.execPath, "-e", "process.exit(0)"], io), 0); assert.equal(out.length, 1); assert.match(out[0], /^[0-9a-f]{16}$/); assert.ok(err.some((l) => /render mode ON for/.test(l))); assert.equal(existsSync(file), false); assert.equal(await renderModeCommand(["on", "--", path.join(tmpdir(), "no-such-command-render-mode")], io), 127); assert.equal(existsSync(file), false); assert.equal(await renderModeCommand(["on", "--"], io), 2, "no command"); assert.equal(await renderModeCommand(["off", "--", "true"], io), 2, "only on runs a command"); // The window form with --print-token: the token alone on stdout, and it is the window's. out.length = 0; assert.equal(await renderModeCommand(["on", "--for", "10m", "--print-token"], io), 0); assert.deepEqual(out, [readRenderPriorityState(file).token]); assert.equal(await renderModeCommand(["on", "--print-token", "--json"], io), 2); // Inside that window a chained command joins it: the window's token, the window left on. const seen = path.join(path.dirname(file), "seen.txt"); const code = await renderModeCommand(["on", "--", process.execPath, "-e", `require("node:fs").writeFileSync(${JSON.stringify(seen)}, process.env.RENDER_PRIORITY_TOKEN || "")`], io); assert.equal(code, 0); assert.equal(readFileSync(seen, "utf8"), readRenderPriorityState(file).token); assert.equal(readRenderPriority(file).held, true, "the window outlives the command"); assert.equal(await renderModeCommand(["off"], io), 0); }); test("render-mode on -- signalled: the signal reaches the command and the hold ends", { timeout: 240_000 }, async () => { const dir = mkdtempSync(path.join(tmpdir(), "render-mode-chain-sig-")); const file = path.join(dir, "state.json"); const log = path.join(dir, "lanes.log"); const childLog = path.join(dir, "child.log"); const script = path.join(dir, "chain.mjs"); writeFileSync( script, `import { appendFileSync } from "node:fs"; import { renderModeCommand } from ${JSON.stringify(path.join(HERE, "renderMode.mjs"))}; const lanes = { isHeld: async () => false, hold: async (l) => appendFileSync(${JSON.stringify(log)}, "hold " + l + "\\n"), release: async (l) => appendFileSync(${JSON.stringify(log)}, "release " + l + "\\n"), }; const child = 'process.on("SIGTERM",()=>{require("node:fs").appendFileSync(${JSON.stringify(childLog)},"TERM\\\\n");process.exit(0)});require("node:fs").appendFileSync(${JSON.stringify(childLog)},"ready\\\\n");setInterval(()=>{},1000)'; process.exit(await renderModeCommand(["on", "--", process.execPath, "-e", child], { log: (l) => console.log(l), err: (l) => console.error(l), env: { PATH: process.env.PATH }, file: ${JSON.stringify(file)}, lanes })); `, ); const proc = spawn(process.execPath, [script], { stdio: ["ignore", "pipe", "pipe"] }); let out = ""; proc.stdout.on("data", (d) => (out += d)); proc.stderr.on("data", (d) => (out += d)); const exited = new Promise((r) => proc.on("exit", (c, sig) => r({ code: c, signal: sig }))); let commandPid = null; try { // Backstops, not measures: a loaded machine can take many seconds to start // two node processes, and as long again for the command to log its TERM. const t0 = Date.now(); while (!/render mode ON for/.test(out) || !existsSync(childLog)) { if (proc.exitCode !== null || proc.signalCode !== null) throw new Error(`exited before it went on: ${out}`); if (Date.now() - t0 > 90_000) throw new Error(`never went on: ${out}`); await new Promise((r) => setTimeout(r, 20)); } const held = readRenderPriority(file); assert.equal(held.held, true); commandPid = held.state.holder.pid; assert.notEqual(commandPid, proc.pid, "the holder is the command, not umtool"); proc.kill("SIGTERM"); const { code, signal } = await exited; assert.equal(code, 143, `exited ${code ?? signal}: ${out}`); assert.equal(existsSync(file), false); assert.equal(readFileSync(log, "utf8"), "hold transcription\nhold download\nhold backfill\nrelease transcription\nrelease download\nrelease backfill\n"); const t1 = Date.now(); while (!readFileSync(childLog, "utf8").includes("TERM") && Date.now() - t1 < 60_000) await new Promise((r) => setTimeout(r, 20)); assert.equal(readFileSync(childLog, "utf8"), "ready\nTERM\n", "the command got the signal"); } finally { // Whatever failed, neither process is left running (the command would // otherwise outlive the suite, holding nothing but a CPU slot). if (proc.exitCode === null && proc.signalCode === null) proc.kill("SIGKILL"); await exited; // (Only one that never logged its TERM: one that did has exited, and its pid is not ours to signal.) if (commandPid && !(existsSync(childLog) && readFileSync(childLog, "utf8").includes("TERM"))) { try { process.kill(commandPid, "SIGKILL"); } catch { /* gone already */ } } await rm(dir, { recursive: true, force: true }); } }); test("a take started under render-mode on -- … is part of that hold (no 'waits for it')", async () => { const file = tmpFile(); writeFileSync(file, JSON.stringify({ version: 1, token: "chain", since: new Date().toISOString(), until: null, holder: { pid: process.pid, cmd: "sh render-all.sh" }, lanesHeld: [] })); const lines = []; const env = { RENDER_PRIORITY_TOKEN: "chain" }; await withTakePriority({ priority: true, project: "p", take: "t", log: (l) => lines.push(l), env, file, lanes: null, signals: false }, async () => { assert.equal(env.RENDER_PRIORITY_TOKEN, "chain"); }); assert.match(lines[0], /this take is part of it/); assert.equal(readRenderPriorityState(file).token, "chain"); });