import { test } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import { existsSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { DEFAULT_RENDER_MODE_WINDOW_MS, RENDER_PRIORITY_TOKEN_ENV, applyRenderPriorityDefaults, carriesRenderPriority, describeRenderPriority, holderAlive, isLocalEditor, parseDurationMs, readRenderPriority, readRenderPriorityState, reapRenderMode, renderModeOff, renderModeOn, renderPriorityBlocks, renderPriorityFile, renderPriorityStatus, type RenderModeLanes, type RenderPriorityState, } from "./renderPriority.mjs"; // Run with: // pnpm --filter yt-dlp-transcript-common test // // Render mode's state file and its lanes, all against temp files and a fake // editor — nothing here touches the machine's state or a live editor's lanes. function tmpFile() { return path.join(mkdtempSync(path.join(os.tmpdir(), "render-priority-")), "heavy.lock.render.json"); } /** A fake editor's lanes: `held` is what it holds; `calls` what was asked. */ // The Speakers (backfill) lane starts held, as it ships. function fakeLanes(initial: Record = {}, { failRelease = false } = {}) { const held: Record = { backfill: true, ...initial }; const calls: string[] = []; const lanes: RenderModeLanes = { async isHeld(lane) { return held[lane] === true; }, async hold(lane) { calls.push(`hold ${lane}`); held[lane] = true; }, async release(lane) { calls.push(`release ${lane}`); if (failRelease) throw new Error("editor gone"); held[lane] = false; }, }; return { lanes, held, calls }; } function state(over: Partial = {}): RenderPriorityState { return { version: 1, token: "tok", since: new Date(0).toISOString(), until: null, by: null, note: null, holder: null, lanesHeld: [], ...over, }; } test("renderPriorityFile: RENDER_PRIORITY_FILE, else beside the heavy slot's lock", () => { assert.equal(renderPriorityFile({ RENDER_PRIORITY_FILE: "/x/state.json", HEAVY_LOCK_FILE: "/y/heavy.lock" }), "/x/state.json"); assert.equal(renderPriorityFile({ HEAVY_LOCK_FILE: "/y/heavy.lock" }), "/y/heavy.lock.render.json"); assert.equal(renderPriorityFile({}, { heavyLock: "/z/heavy-queue.lock" }), "/z/heavy-queue.lock.render.json"); // A git checkout: its common dir, the heavy lock's own place. assert.match(renderPriorityFile({}, { root: process.cwd() }), /heavy-queue\.lock\.render\.json$/); }); test("liveness: a gone holder, a past until, or no end at all is not a hold", () => { const now = Date.parse("2026-10-30T12:00:00Z"); const alive = () => true; const dead = () => false; assert.deepEqual(renderPriorityStatus(null), { held: false, state: null, stale: null }); const take = state({ holder: { pid: 123 } }); assert.equal(renderPriorityStatus(take, { now, isAlive: alive }).held, true); assert.equal(renderPriorityStatus(take, { now, isAlive: dead }).stale, "holder-gone"); const window = state({ until: "2026-10-30T13:00:00Z" }); assert.equal(renderPriorityStatus(window, { now, isAlive: dead }).held, true); assert.equal(renderPriorityStatus(window, { now: Date.parse("2026-10-30T13:00:01Z") }).stale, "expired"); // A take's hold with an until past it is over too, holder or not. assert.equal(renderPriorityStatus(state({ holder: { pid: 1 }, until: "2026-10-30T11:00:00Z" }), { now, isAlive: alive }).stale, "expired"); assert.equal(renderPriorityStatus(state(), { now }).stale, "no-end"); }); test("holderAlive: this process is; a dead pid, or a live pid that started at another time, is not", async () => { assert.equal(holderAlive({ pid: process.pid }), true); assert.equal(holderAlive({ pid: process.pid, pidStart: "not-its-start" }), os.platform() !== "linux"); const child = spawn(process.execPath, ["-e", ""]); const pid = child.pid as number; await new Promise((r) => child.on("exit", r)); assert.equal(holderAlive({ pid }), false); }); test("the gate's question: held, the token not carried, no bypass", () => { const held = { held: true, state: state(), stale: null } as const; assert.equal(renderPriorityBlocks(held, {}), true); assert.equal(renderPriorityBlocks(held, { [RENDER_PRIORITY_TOKEN_ENV]: "tok" }), false); assert.equal(renderPriorityBlocks(held, { [RENDER_PRIORITY_TOKEN_ENV]: "other" }), true); assert.equal(renderPriorityBlocks(held, { RENDER_PRIORITY: "0" }), false); assert.equal(renderPriorityBlocks(held, {}, { urgent: true }), false); assert.equal(renderPriorityBlocks({ held: false, state: state(), stale: "expired" }, {}), false); assert.equal(carriesRenderPriority(held, { [RENDER_PRIORITY_TOKEN_ENV]: "tok" }), true); assert.equal(carriesRenderPriority(held, {}), false); }); test("the render's own defaults fill only what the environment leaves unset", () => { const env: Record = { HEAVY_CAP_MB: "9000" }; assert.deepEqual(applyRenderPriorityDefaults(env), ["HEAVY_MIN_FREE_MB"]); assert.equal(env.HEAVY_MIN_FREE_MB, "4000"); assert.equal(env.HEAVY_CAP_MB, "9000"); const bare: Record = {}; applyRenderPriorityDefaults(bare); assert.deepEqual(bare, { HEAVY_MIN_FREE_MB: "4000", HEAVY_CAP_MB: "10240" }); }); test("describeRenderPriority and parseDurationMs", () => { assert.match(describeRenderPriority(state({ holder: { pid: 1, cmd: "umtool take ember --id t1" } })), /^umtool take ember --id t1, since \d\d:\d\d$/); assert.match(describeRenderPriority(state({ by: "umtool render-mode", note: "a chain", until: new Date(0).toISOString() })), /^render mode on \(by umtool render-mode\) — a chain, since \d\d:\d\d, until \d\d:\d\d$/); assert.equal(parseDurationMs("90m"), 90 * 60_000); assert.equal(parseDurationMs("2h"), 2 * 3_600_000); assert.equal(parseDurationMs("1h30m"), 90 * 60_000); assert.equal(parseDurationMs("45"), 45 * 60_000); assert.equal(parseDurationMs(10), 10 * 60_000); assert.equal(parseDurationMs("soon"), null); assert.equal(parseDurationMs("0m"), null); assert.equal(parseDurationMs(""), null); }); test("on holds only the lanes not held already, and off releases only those", async () => { const file = tmpFile(); // Someone else's hold on download; the Speakers (backfill) lane running — // a render takes its cores too (RENDER_MODE_LANES). const ed = fakeLanes({ download: true, backfill: false }); const on = await renderModeOn({ file, holder: { pid: process.pid, cmd: "umtool take p --id t", project: "p", take: "t" }, lanes: ed.lanes, editor: "http://localhost:3001" }); assert.equal(on.ok, true); assert.deepEqual(on.state?.lanesHeld, ["transcription", "backfill"]); assert.deepEqual(on.state?.lanesSkipped, ["download"]); assert.equal(on.state?.until, null); // a take's hold ends with its process assert.deepEqual(ed.calls, ["hold transcription", "hold backfill"]); const onDisk = readRenderPriorityState(file); assert.equal(onDisk?.token, on.state?.token); assert.equal(readRenderPriority(file).held, true); // A second `on` does not take it over. const again = await renderModeOn({ file, lanes: ed.lanes }); assert.equal(again.ok, false); assert.equal(again.held?.token, on.state?.token); // Another hold's token is not ours to end. const notOurs = await renderModeOff({ file, token: "someone-else", lanes: ed.lanes }); assert.equal(notOurs.ok, false); assert.equal(existsSync(file), true); const off = await renderModeOff({ file, token: on.state?.token, lanes: ed.lanes }); assert.deepEqual(off.released, ["transcription", "backfill"]); assert.deepEqual(ed.calls, ["hold transcription", "hold backfill", "release transcription", "release backfill"]); assert.equal(ed.held.download, true, "the hold it found stays"); assert.equal(existsSync(file), false); }); test("a manual window has an until (2 h by default, or --for); with no editor it still holds the door", async () => { const file = tmpFile(); const t0 = Date.parse("2026-10-30T13:31:00Z"); const on = await renderModeOn({ file, now: () => t0, note: "a chain" }); assert.equal(on.ok, true); assert.equal(Date.parse(on.state!.until!) - t0, DEFAULT_RENDER_MODE_WINDOW_MS); assert.deepEqual(on.state!.lanesHeld, []); assert.match(on.state!.lanesError ?? "", /no editor/); assert.equal(readRenderPriority(file, { now: t0 + 60_000 }).held, true); assert.equal(readRenderPriority(file, { now: t0 + DEFAULT_RENDER_MODE_WINDOW_MS + 1 }).held, false); await renderModeOff({ file }); const sized = await renderModeOn({ file, now: () => t0, forMs: 90 * 60_000 }); assert.equal(Date.parse(sized.state!.until!) - t0, 90 * 60_000); }); test("a stale hold (its render killed) is reaped: its lanes released, its file gone; a live one is left", async () => { const file = tmpFile(); const ed = fakeLanes(); writeFileSync(file, JSON.stringify(state({ holder: { pid: 999_999_999 }, lanesHeld: ["transcription", "download"], editor: "http://localhost:3001" }))); assert.equal(readRenderPriority(file).stale, "holder-gone"); // Another editor's stale hold is left for that editor. assert.equal(await reapRenderMode({ file, lanes: ed.lanes, owns: (s) => isLocalEditor(s.editor, 3101) }), null); assert.deepEqual(ed.calls, []); const r = await reapRenderMode({ file, lanes: ed.lanes, owns: (s) => isLocalEditor(s.editor, 3001) }); assert.deepEqual(r?.released, ["transcription", "download"]); assert.equal(existsSync(file), false); await renderModeOn({ file, holder: { pid: process.pid }, lanes: ed.lanes }); assert.equal(await reapRenderMode({ file, lanes: ed.lanes }), null); assert.equal(existsSync(file), true); }); test("a lane the editor would not release stays recorded, ended — and the next hold inherits it", async () => { const file = tmpFile(); const broken = fakeLanes({}, { failRelease: true }); const on = await renderModeOn({ file, holder: { pid: process.pid }, lanes: broken.lanes }); const off = await renderModeOff({ file, token: on.state!.token, lanes: broken.lanes }); assert.equal(off.failed.length, 2); const ended = readRenderPriorityState(file)!; assert.equal(ended.ended, true); assert.deepEqual(ended.lanesHeld, ["transcription", "download"]); assert.equal(readRenderPriority(file).held, false, "not a hold any more: the gate ignores it"); // Still no editor: the next `on` takes the lanes over rather than strand them. const next = await renderModeOn({ file, holder: { pid: process.pid }, lanes: broken.lanes }); assert.equal(next.ok, true); assert.deepEqual(next.state!.lanesHeld, ["transcription", "download"]); // The editor is back: the next off releases them. const fixed = fakeLanes({ transcription: true, download: true }); const done = await renderModeOff({ file, token: next.state!.token, lanes: fixed.lanes }); assert.deepEqual(done.released, ["transcription", "download"]); assert.equal(existsSync(file), false); }); test("isLocalEditor: a loopback host on that port", () => { assert.equal(isLocalEditor("http://localhost:3001", 3001), true); assert.equal(isLocalEditor("http://127.0.0.1:3001/", "3001"), true); assert.equal(isLocalEditor("http://localhost:3101", 3001), false); assert.equal(isLocalEditor("https://editor.example:3001", 3001), false); assert.equal(isLocalEditor(null, 3001), false); }); test("two `on`s at once: one wins, the other is told", async () => { const file = tmpFile(); const [a, b] = await Promise.all([ renderModeOn({ file, holder: { pid: process.pid } }), renderModeOn({ file, holder: { pid: process.pid } }), ]); assert.equal([a.ok, b.ok].filter(Boolean).length, 1); assert.equal(JSON.parse(readFileSync(file, "utf8")).token, (a.ok ? a : b).state!.token); });