// A render's memory estimate (render-estimate.mjs) and what the heavy slot // (scripts/queue-lock.mjs) does with it: a render declares one, so a capped // site build is admitted beside it while MemAvailable allows, and waits for it // when not. // // The real machine-wide lock is never taken: every run names its own // HEAVY_LOCK_FILE in a temp dir and reads a fake /proc/meminfo. // // Run with: pnpm test:scripts import assert from "node:assert/strict"; import { spawn } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import test from "node:test"; import { CHROME_AUTO_MAX, CHROME_LAYERS_DEFAULT, CHROME_MEMORY_MB, chromeEstimateMb, chromeLayers, chromeWorkers, LADDER_ESTIMATE_MB, manifestEstimateMb, manifestSegments, openSegments, RENDER_CHROME_BASE_MB, RENDER_CHROME_PER_WORKER_MB, RENDER_ENCODE_BASE_MB, RENDER_ENCODE_PER_SEGMENT_MB, renderEstimateMb, XFADE_BATCH, } from "./render-estimate.mjs"; import { checkoutRoot, withRenderSlot } from "./heavy-gate.mjs"; import { cliEstimateMb, XFADE_BATCH_DEFAULT } from "./build-video.mjs"; import { renderArgv, takeEstimateMb } from "../lib/report/takeRender.mjs"; const QUEUE_LOCK = path.join(checkoutRoot(), "scripts", "queue-lock.mjs"); const { admissionDecision, DEFAULT_MIN_FREE_MB, memoryCapMb, resolveJob } = await import(QUEUE_LOCK); const RENDER = renderEstimateMb("render", {}); const FLOOR = DEFAULT_MIN_FREE_MB; // The capped site build an operator runs by hand (WORKTREES.md, the heavy slot). const BUILD_WORDS = ["systemd-run", "--user", "--scope", "-q", "-p", "MemoryMax=5G", "-p", "MemorySwapMax=0", "--"]; const BUILD_MB = memoryCapMb(BUILD_WORDS); const encode = (n) => RENDER_ENCODE_BASE_MB + RENDER_ENCODE_PER_SEGMENT_MB * n; const chrome = (w, layers = 1) => RENDER_CHROME_BASE_MB * layers + RENDER_CHROME_PER_WORKER_MB * w; // This machine's chrome capture, as a render on it declares it. const CHROME = chromeEstimateMb({}); test("the estimate: the larger of the widest crossfade pass and the chrome capture", () => { assert.equal(XFADE_BATCH, XFADE_BATCH_DEFAULT, "build-video's batch size, mirrored"); // The budget: one and a half per core, at least 2, at most CHROME_AUTO_MAX, within the chrome's memory. assert.equal(chromeWorkers({}, 8), 12, "an 8-core machine: 12"); assert.equal(chromeWorkers({}, 4), 6); assert.equal(chromeWorkers({}, 1), 2, "never fewer than 2"); assert.equal(chromeWorkers({}, 64), CHROME_AUTO_MAX, "a big machine: the cap"); assert.ok(chrome(CHROME_AUTO_MAX, CHROME_LAYERS_DEFAULT) <= CHROME_MEMORY_MB, "the cap fits the chrome's memory"); assert.equal(chromeWorkers({ UMTOOL_CHROME_LAYERS: "8" }, 64), Math.floor((CHROME_MEMORY_MB - 8 * RENDER_CHROME_BASE_MB) / RENDER_CHROME_PER_WORKER_MB), "more renders at once: fewer workers fit"); assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "7" }, 8), 7, "the override wins"); assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "99" }), 16, "clamped as build-video clamps it"); assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "junk" }, 6), 9, "junk: the machine's"); assert.equal(chromeLayers({}), CHROME_LAYERS_DEFAULT); assert.equal(chromeLayers({ UMTOOL_CHROME_LAYERS: "1" }), 1); assert.equal(chromeLayers({ UMTOOL_CHROME_LAYERS: "0" }), CHROME_LAYERS_DEFAULT); // The capture's memory: its renders' bases (never more renders than workers) and its workers. assert.equal(chromeEstimateMb({}, 8), chrome(12, 3)); assert.equal(chromeEstimateMb({ UMTOOL_CHROME_WORKERS: "2" }, 8), chrome(2, 2)); assert.equal(chromeEstimateMb({ UMTOOL_CHROME_LAYERS: "1" }, 8), chrome(12, 1)); // Segments: a pass opens at most a batch; unknown is a full batch; batch 0 never batches. assert.equal(openSegments(68), 24); assert.equal(openSegments(5), 5); assert.equal(openSegments(null), 24); assert.equal(openSegments(68, 0), 68); assert.equal(openSegments(68, 12), 12); assert.equal(RENDER, encode(24), "unknown segments: a full batch"); assert.equal(renderEstimateMb("render", {}, { segments: 4, cores: 8 }), Math.max(encode(4), chrome(12, 3))); assert.equal(renderEstimateMb("render", {}, { segments: 1, cores: 8 }), Math.max(encode(1), chrome(12, 3))); // Chrome workers dominate a short run once there are enough of them. assert.equal(renderEstimateMb("render", { UMTOOL_CHROME_WORKERS: "16" }, { segments: 1 }), chrome(16, 3)); assert.ok(chrome(16, 3) > encode(1)); assert.equal(renderEstimateMb("ladder", {}), LADDER_ESTIMATE_MB); assert.ok(LADDER_ESTIMATE_MB < RENDER, "the ladder's one ffmpeg is smaller than a render"); // The measured peaks sit under what is declared (render-estimate.mjs's table). assert.ok(encode(23) >= 4906 * 1.15, "a 23-segment crossfade batch peaked at 4906 MB"); assert.ok(encode(4) >= 2019 * 1.15, "a 4-entry window's pass peaked at 2019 MB"); assert.ok(chrome(7) >= 2218 * 1.1, "the full deck's 7-worker capture peaked at 2218 MB"); assert.ok(LADDER_ESTIMATE_MB >= 760 * 1.25, "the ladder peaked at 760 MB"); // Every default stays under the default cap: the estimate admits, the cap limits. assert.ok(RENDER <= 8192 && chrome(16, 3) <= 8192 && LADDER_ESTIMATE_MB <= 8192); }); test("a manifest's estimate: its segments (and the intro's), one when nothing crossfades or the run is one clip", () => { const m = { timeline: Array.from({ length: 4 }, (_, i) => ({ id: `c${i}` })), render: {} }; assert.equal(manifestSegments(m), 4); assert.equal(manifestSegments({ ...m, render: { intro: { style: "boot" } } }), 5); assert.equal(manifestSegments({}), null); assert.equal(manifestEstimateMb(m, {}), Math.max(encode(4), CHROME)); assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}), encode(24), "a long cut: one full batch"); assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { batch: 0 }), encode(67), "never batched: every segment"); assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { xfade: false }), Math.max(encode(1), CHROME)); assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}), render: { transition: 0 } }, {}), Math.max(encode(1), CHROME)); assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { single: true }), Math.max(encode(1), CHROME)); assert.equal(manifestEstimateMb(null, {}), RENDER, "unreadable: a full batch"); assert.equal(manifestEstimateMb(m, { UMTOOL_RENDER_ESTIMATE_MB: "0" }), null); }); test("build-video's CLI and a take read the estimate off the manifest they render", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "render-estimate-m-")); try { const file = path.join(dir, "video.manifest.json"); fs.writeFileSync(file, JSON.stringify({ timeline: Array(30).fill({ type: "clip" }), render: { xfadeBatch: 10 } })); assert.equal(await cliEstimateMb(file, {}, {}), Math.max(encode(10), CHROME), "render.xfadeBatch sizes the pass"); assert.equal(await cliEstimateMb(file, {}, { REPORT_VIDEO_XFADE_BATCH: "16" }), Math.max(encode(16), CHROME), "the env's batch wins, as in build-video"); assert.equal(await cliEstimateMb(file, { clipPreview: "c1" }, {}), Math.max(encode(1), CHROME)); assert.equal(await cliEstimateMb(file, { noXfade: true }, {}), Math.max(encode(1), CHROME)); assert.equal(await cliEstimateMb(path.join(dir, "absent.json"), {}, {}), RENDER); assert.equal(await takeEstimateMb({ manifestPath: file, xfade: true }, {}), Math.max(encode(10), CHROME)); assert.equal(await takeEstimateMb({ manifestPath: file, xfade: false }, {}), Math.max(encode(1), CHROME)); assert.equal(await takeEstimateMb({ manifestPath: path.join(dir, "absent.json"), xfade: true }, {}), RENDER); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("the overrides: a size wins, 0 declares nothing (runs alone), junk keeps the default", () => { assert.equal(renderEstimateMb("render", { UMTOOL_RENDER_ESTIMATE_MB: "2500" }), 2500); assert.equal(renderEstimateMb("render", { UMTOOL_RENDER_ESTIMATE_MB: "2500", UMTOOL_CHROME_WORKERS: "16" }), 2500); assert.equal(renderEstimateMb("render", { UMTOOL_RENDER_ESTIMATE_MB: "0" }), null); assert.equal(renderEstimateMb("render", { UMTOOL_RENDER_ESTIMATE_MB: "lots" }), RENDER); assert.equal(renderEstimateMb("render", { UMTOOL_RENDER_ESTIMATE_MB: "" }), RENDER); assert.equal(renderEstimateMb("ladder", { UMTOOL_LADDER_ESTIMATE_MB: "900" }), 900); assert.equal(renderEstimateMb("ladder", { UMTOOL_LADDER_ESTIMATE_MB: "0" }), null); assert.equal(renderEstimateMb("ladder", { UMTOOL_RENDER_ESTIMATE_MB: "900" }), LADDER_ESTIMATE_MB, "each kind its own knob"); assert.throws(() => renderEstimateMb("podcast", {}), /no kind 'podcast'/); }); test("a take's render declares its estimate to queue-lock; none declared, it runs alone", () => { const base = { manifestPath: "/m.json", outDir: "/o", full: true, xfade: true, queueLock: "/q/queue-lock.mjs" }; const argv = renderArgv({ ...base, estimateMb: 3600 }); const sep = argv.indexOf("--"); assert.deepEqual(argv.slice(1, sep), ["/q/queue-lock.mjs", "--heavy", "--estimate", "3600"]); assert.match(argv[sep + 2], /build-video\.mjs$/); // What queue-lock makes of it: a weighted job, admitted by memory beside others. assert.deepEqual(resolveJob({ estimateMb: 3600 }, argv.slice(sep + 1)), { estimateMb: 3600, build: false, exclusive: false }); assert.ok(!renderArgv({ ...base, estimateMb: null }).includes("--estimate"), "an override of 0: alone, as before"); assert.ok(!renderArgv({ ...base, queueLock: null, estimateMb: 3600 }).includes("--estimate"), "no gate: build-video takes the slot itself"); // The default is the measured one, from this process's environment. const saved = process.env.UMTOOL_RENDER_ESTIMATE_MB; delete process.env.UMTOOL_RENDER_ESTIMATE_MB; try { const d = renderArgv(base); assert.equal(d[d.indexOf("--estimate") + 1], String(renderEstimateMb("render"))); } finally { if (saved !== undefined) process.env.UMTOOL_RENDER_ESTIMATE_MB = saved; } }); /** Run `fn` with process.env patched, restoring every key after. */ async function withEnv(patch, fn) { const saved = Object.fromEntries(Object.keys(patch).map((k) => [k, process.env[k]])); for (const [k, v] of Object.entries(patch)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } try { return await fn(); } finally { for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } } } const tmpDir = () => fs.mkdtempSync(path.join(os.tmpdir(), "render-estimate-")); const tickets = (lock) => { const dir = `${lock}.jobs`; return fs.existsSync(dir) ? fs.readdirSync(dir).filter((n) => n.endsWith(".json")).map((n) => JSON.parse(fs.readFileSync(path.join(dir, n), "utf8"))) : []; }; test("withRenderSlot declares the estimate in the slot's ticket; without one the render runs alone", async () => { const dir = tmpDir(); const lock = path.join(dir, "heavy-queue.lock"); try { const env = { HEAVY: undefined, HEAVY_HELD: undefined, HEAVY_LOCK_FILE: lock, HEAVY_MIN_FREE_MB: "0" }; const declared = await withEnv(env, () => withRenderSlot(["build-video", "m.json"], async () => tickets(lock), { estimateMb: RENDER })); assert.equal(declared.length, 1); assert.equal(declared[0].estimateMb, RENDER); assert.equal(declared[0].exclusive, false); const alone = await withEnv(env, () => withRenderSlot(["build-video", "m.json"], async () => tickets(lock), { estimateMb: null })); assert.equal(alone[0].estimateMb, null); assert.equal(alone[0].exclusive, true); assert.deepEqual(tickets(lock), [], "the ticket goes with the slot"); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("admission: two declared renders together under the floor; a render and a capped build when MemAvailable allows", () => { const mem = (availableMb) => ({ availableMb, totalMb: 16_000 }); const render = { estimateMb: RENDER, build: false, exclusive: false }; const build = resolveJob({}, [...BUILD_WORDS, "pnpm", "exec", "next", "build"]); assert.deepEqual(build, { estimateMb: BUILD_MB, build: true, exclusive: false }, "a capped build declares its cap"); // Two renders: the second is admitted while MemAvailable − the first's estimate ≥ the floor. assert.equal(admissionDecision({ mem: mem(FLOOR + RENDER), minMb: FLOOR, running: [render], job: render }).admit, true); assert.equal(admissionDecision({ mem: mem(FLOOR + RENDER - 1), minMb: FLOOR, running: [render], job: render }).wait, "memory"); // A build arriving beside a render, and a render arriving beside a build. assert.equal(admissionDecision({ mem: mem(FLOOR + RENDER), minMb: FLOOR, running: [render], job: build }).admit, true); assert.equal(admissionDecision({ mem: mem(FLOOR + RENDER - 1), minMb: FLOOR, running: [render], job: build }).wait, "memory"); assert.equal(admissionDecision({ mem: mem(FLOOR + BUILD_MB), minMb: FLOOR, running: [build], job: render }).admit, true); assert.equal(admissionDecision({ mem: mem(FLOOR + BUILD_MB - 1), minMb: FLOOR, running: [build], job: render }).wait, "memory"); // An undeclared render still runs alone, however roomy the machine. const alone = resolveJob({}, ["node", "build-video.mjs"]); assert.equal(admissionDecision({ mem: mem(60_000), minMb: FLOOR, running: [{ ...alone, estimateMb: null }], job: build }).wait, "exclusive"); }); // ------------------------------------------------- the real CLI, side by side // A fake systemd-run: runs what follows `--` (the build's cap is in its words). function fakeSystemdRun(dir) { const bin = path.join(dir, "bin"); fs.mkdirSync(bin); fs.writeFileSync( path.join(bin, "systemd-run"), `#!/bin/sh\nwhile [ "$1" != "--" ] && [ $# -gt 0 ]; do shift; done\n[ "$1" = "--" ] && shift\nexec "$@"\n`, { mode: 0o755 }, ); return bin; } function meminfo(file, availableMb, totalMb = 32_000) { fs.writeFileSync(file, `MemTotal: ${totalMb * 1024} kB\nMemFree: 1024 kB\nMemAvailable: ${availableMb * 1024} kB\n`); } // Records "S" at its start and "E" once `gate` exists (or 20 s pass). function gateCmd(log, id, gate) { return [ process.execPath, "-e", `const fs=require("fs");fs.appendFileSync(${JSON.stringify(log)},"S${id}");const t0=Date.now();` + `const tick=()=>{if(fs.existsSync(${JSON.stringify(gate)})||Date.now()-t0>20000)fs.appendFileSync(${JSON.stringify(log)},"E${id}");else setTimeout(tick,20);};tick();`, ]; } function start(argv, env) { const out = { ...process.env, HEAVY: "1", HEAVY_CAP: "0", HEAVY_POLL_MS: "50", ...env }; for (const k of ["HEAVY_HELD", "QUEUE_LOCK_HELD", "HEAVY_MIN_FREE_MB"]) if (!(k in env)) delete out[k]; const child = spawn(argv[0], argv.slice(1), { env: out, stdio: ["ignore", "pipe", "pipe"] }); let stderr = ""; const waiters = []; child.stderr.on("data", (d) => { stderr += d; for (const w of waiters) if (w.re.test(stderr)) w.resolve(); }); const done = new Promise((resolve) => child.on("exit", (code) => resolve({ code, stderr }))); const waitFor = (re) => new Promise((resolve, reject) => { if (re.test(stderr)) return resolve(); waiters.push({ re, resolve }); done.then(() => reject(new Error(`exited before stderr matched ${re}: ${stderr}`))); }); return { done, waitFor }; } async function until(check, ms = 10_000) { const t0 = Date.now(); while (!check()) { if (Date.now() - t0 > ms) throw new Error("timed out waiting"); await new Promise((r) => setTimeout(r, 20)); } } /** A take's render argv (its real queue-lock prefix), running `cmd` in place of build-video. */ function renderTakeArgv(cmd) { const argv = renderArgv({ manifestPath: "/m.json", outDir: "/o", full: true, xfade: true, queueLock: QUEUE_LOCK, estimateMb: RENDER }); return [...argv.slice(0, argv.indexOf("--") + 1), ...cmd]; } async function renderThenBuild(availableMb) { const dir = tmpDir(); try { const log = path.join(dir, "order.log"); const gate = path.join(dir, "gate"); const lock = path.join(dir, "heavy.lock"); const mem = path.join(dir, "meminfo"); meminfo(mem, availableMb); const env = { HEAVY_LOCK_FILE: lock, HEAVY_MEMINFO_FILE: mem, PATH: `${fakeSystemdRun(dir)}:${process.env.PATH}` }; const render = start(renderTakeArgv(gateCmd(log, "r", gate)), env); await until(() => tickets(lock).length === 1 && fs.existsSync(log)); assert.equal(tickets(lock)[0].estimateMb, RENDER, "the render's ticket carries its estimate"); const build = start([process.execPath, QUEUE_LOCK, "--heavy", "--", ...BUILD_WORDS, ...gateCmd(log, "b", gate)], env); // Either the build has started beside the render, or it says what it waits for. let waited = false; await Promise.race([ until(() => fs.readFileSync(log, "utf8").includes("Sb")), build.waitFor(/waiting for memory/).then(() => (waited = true), () => {}), ]); openGate(gate); const [rr, rb] = await Promise.all([render.done, build.done]); assert.equal(rr.code, 0, rr.stderr); assert.equal(rb.code, 0, rb.stderr); return { order: fs.readFileSync(log, "utf8"), waited, buildErr: rb.stderr }; } finally { fs.rmSync(dir, { recursive: true, force: true }); } } const openGate = (gate) => fs.writeFileSync(gate, ""); test("a declared render and a capped build run side by side when MemAvailable allows", async () => { const { order, waited, buildErr } = await renderThenBuild(FLOOR + RENDER + 500); assert.equal(waited, false, buildErr); assert.match(order, /^SrSb/, `the build did not start beside the render: ${order}`); assert.match(buildErr, new RegExp(`admitted beside 1 running job \\(${FLOOR + RENDER + 500} MB available, ${RENDER} MB promised to them`)); }); test("…and the build waits for the render when MemAvailable minus its estimate is under the floor", async () => { const { order, waited, buildErr } = await renderThenBuild(FLOOR + RENDER - 500); assert.equal(waited, true, buildErr); assert.equal(order, "SrErSbEb", "serialized: the build starts once the render is done"); assert.match(buildErr, new RegExp(`waiting for memory — ${FLOOR + RENDER - 500} MB available, ${RENDER} MB promised to 1 running job, the floor is ${FLOOR} MB`)); });