Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 19ab80fe4924cc5a83c31e00e2b45a8307616a57
parent 53bae5a6ed747588bf1494941c63473c164acce2
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Wed, 28 Oct 2026 22:43:15 -0400

Merge lane/render-estimate: renders declare a memory estimate to the heavy slot, so a capped site build can run beside one

- report-to-video/render-estimate.mjs: a render's estimate from its widest
  ffmpeg (crossfade batch) and its chrome capture, measured on the Huck cut
  (whole cut 6020 MB, 4-entry window 2420, one clip 1880, ladder 1000).
- umtool take passes queue-lock --heavy --estimate; build-video's own heavy
  runs and variants.mjs pass estimateMb to withRenderSlot.
- UMTOOL_RENDER_ESTIMATE_MB / UMTOOL_LADDER_ESTIMATE_MB override; 0 runs alone.
- Docs: AGENTS.md, WORKTREES.md, umtool report-video.md, CHANGELOG.

Conflicts:
- editor/CHANGELOG.md: both sides' Unreleased bullets kept.
- heavy-gate.mjs: main already had bench-prep's estimateMb option; kept one
  option typed `number | null`, the doc naming both declarers (a render via
  render-estimate.mjs, the bench's prep).
- build-video.mjs main(): take-prune's guardedRender (disk guard inside the
  slot) and this lane's cliEstimateMb estimate, both kept.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Diffstat:
MAGENTS.md | 12++++++++----
MWORKTREES.md | 72++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Meditor/CHANGELOG.md | 1+
Mumtool/docs/report-video.md | 30+++++++++++++++++++++++++++++-
Mumtool/lib/report/takeMaker.mjs | 2+-
Mumtool/lib/report/takeRender.mjs | 56+++++++++++++++++++++++++++++++++++++++++++++-----------
Mumtool/report-to-video/build-video.mjs | 38+++++++++++++++++++++++++++++++++++---
Mumtool/report-to-video/heavy-gate.mjs | 7++++---
Mumtool/report-to-video/package.json | 1+
Aumtool/report-to-video/render-estimate.mjs | 133+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/report-to-video/render-estimate.test.mjs | 304+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/variants.mjs | 9++++++---
12 files changed, 633 insertions(+), 32 deletions(-)

diff --git a/AGENTS.md b/AGENTS.md @@ -61,10 +61,14 @@ spec. machine-global slot that admits by memory (two OOMs took the desktop session down). A job that declares an estimate — an e2e suite 1.5 GB (`--estimate`), a build capped by `systemd-run -p MemoryMax=5G` its cap — runs beside others while MemAvailable minus the -running jobs' estimates stays ≥ 6000 MB, and **one `next build` at a time stays hard**. A -job that declares nothing (a render, a hand `pnpm heavy -- <cmd>`, an uncapped publish -build) runs ALONE above the 6000 MB floor, as before. e2e and the builds take it on their -own; a render or any other heavy command runs as `pnpm heavy -- <cmd>`. `queue-lock: waiting +running jobs' estimates stays ≥ 6000 MB, and **one `next build` at a time stays hard**. **A +report-video render declares one too** (`umtool/report-to-video/render-estimate.mjs`): a take, +build-video's own rendering runs and the encode ladder (`umtool variants`) — so a capped +build runs beside a render when memory allows. A job that declares nothing (a hand `pnpm +heavy -- <cmd>`, an uncapped publish-stage build, a podcast or intro render) runs ALONE above +the 6000 MB floor, as before. e2e, the builds and the renders take it on their own — run +`umtool take` / build-video bare, **not** under `pnpm heavy --`, which makes the outer job an +undeclared one again; any other heavy command runs as `pnpm heavy -- <cmd>`. `queue-lock: waiting for the heavy slot — held by …`, `heavy: waiting for memory …` or `heavy: waiting for the build slot …` is the gate working, not a hang. **An admitted `--heavy` command runs in a capped scope of its own by default** (`systemd-run --user --scope`, MemoryMax 8G, diff --git a/WORKTREES.md b/WORKTREES.md @@ -201,19 +201,21 @@ through ONE more machine-global gate, the **heavy slot**, which admits a job **b An e2e suite declares 1.5 GB (`--estimate 1500` in each package's script — the editor's per worker, `--scale-by E2E_WORKERS`, `auto` counting as 3); a `next build` run under `systemd-run … -p MemoryMax=5G` declares its cap (the e2e build does). +- **A report-video render declares one** (`umtool/report-to-video/render-estimate.mjs`), so + a capped build is admitted beside it when memory allows — see "A render's estimate" below. - **One `next build` at a time stays a hard rule**, whatever the memory: a build waits for the build slot, including one started from inside an admitted run. - A job that **declares nothing runs ALONE**, once MemAvailable is at least the floor — as - every heavy job did before release 24: a render, a hand `pnpm heavy -- <cmd>`, a publish - stage's (uncapped) build. It waits for the running jobs to finish, and none is admitted - beside it. + every heavy job did before release 24: a hand `pnpm heavy -- <cmd>`, a publish stage's + (uncapped) build, a podcast or intro render. It waits for the running jobs to finish, and + none is admitted beside it. ```sh pnpm heavy -- <cmd…> # alone (no estimate) pnpm heavy -- systemd-run --user --scope -p MemoryMax=5G -p MemorySwapMax=0 \ pnpm --filter editor exec next build # a build, 5 GB: beside suites, never beside a build node scripts/queue-lock.mjs --heavy --estimate 2000 -- <cmd…> # declare an estimate by hand -pnpm heavy -- node umtool/report-to-video/build-video.mjs <manifest> … # a render (alone) +node umtool/report-to-video/build-video.mjs <manifest> … # a render: takes the slot itself, with its estimate ``` **An admitted `pnpm heavy` / `queue-lock --heavy` command is capped by default.** It runs in @@ -246,7 +248,10 @@ Who takes it, and in what order: stage's log, and a Cancel still stops the build (the gate forwards SIGTERM). In a docker-runner container the slot is the container's own; the floor still reads the host's memory, which throttles a fan-out when the host runs low. -- **A render**, by hand, as above. +- **A render**, on its own: `umtool take` (its `queue-lock --heavy --estimate <MB>`), + build-video's rendering runs and `umtool variants` (heavy-gate.mjs), each with its estimate. + Do not wrap one in `pnpm heavy --`: the wrapper is then the job, undeclared, and runs alone + (the render inside passes straight through). Waiting is in one line, so nobody slips in ahead: the job at the head keeps its place while it waits for memory. A waiter is told what it waits behind: @@ -275,6 +280,61 @@ alone — it is a safety net, not a correctness lock. | `HEAVY_TIMEOUT=<seconds>` | Give up waiting (line, slot, memory) after N seconds; an e2e run uses `E2E_QUEUE_TIMEOUT` | | `HEAVY_CAP=0` | Run a `--heavy` command without the default memory cap | | `HEAVY_CAP_MB=<MB>` / `HEAVY_CAP_SWAP_MB=<MB>` | Size the cap (8192 / 2048) | +| `UMTOOL_RENDER_ESTIMATE_MB=<MB>` | What a render declares (`0`: nothing — it runs alone) | +| `UMTOOL_LADDER_ESTIMATE_MB=<MB>` | What the encode ladder declares (`0`: nothing) | + +### A render's estimate + +A report-video render declares its memory (`umtool/report-to-video/render-estimate.mjs`). +Measured 2026-10-26 on the Huck cut (1080p30, x264 slow, 68 segments) as the process tree's +PSS, Chromium included, sampled every 3 s: + +| Phase | Measured peak | +|---|---| +| a crossfade batch: 23 segments open in one ffmpeg | 4.9 GB | +| the last join: 3 batch files + 4 chrome layers | 1.4 GB | +| a 120 s window's one pass: 4 entries + the chrome over them | 2.0 GB | +| one clip segment's encode | 0.85 GB | +| the whole deck's capture, 7 Chromium workers | 2.2 GB | +| a window's capture, 4 / 7 workers | 0.8 / 1.15 GB | +| the ladder (`umtool variants`), one x264 re-encode at a time | 0.76 GB | + +The phases run one after another, so a render declares the larger of its widest ffmpeg and +its chrome capture, with about 20 % on top: + +- the crossfade pass: 1700 MB + 180 MB per segment it holds open — the segments the run + joins (a window's, a whole cut's), at most a batch (`REPORT_VIDEO_XFADE_BATCH` / + `render.xfadeBatch`, default 24), one when nothing is crossfaded (`--no-xfade`, a + transition of 0) or the run is one clip (`--clip-preview`, `--short`): **6020 MB** for a + whole cut, 2420 MB for a 4-entry window, 1880 MB for one clip; +- the chrome capture: 400 MB + 320 MB per `UMTOOL_CHROME_WORKERS` (default 4): 1680 MB, 2640 + at 7, 5520 at 16; +- the ladder: 1000 MB. + +So a capped 5 GB build joins a whole-cut render only while `MemAvailable − 6020 ≥ 6000`, and +a window take while `MemAvailable − 2420 ≥ 6000`; under that it waits for the render, as +before. On a 16 GB machine a whole cut and a build together is rare — the 23-segment batch +alone took MemAvailable to about 450 MB here, with the desktop and the live apps running. + +The estimate is for admission; **the cap is the hard limit**, and it is unchanged: the +render still runs in its capped scope (MemoryMax 8G, swap 2G; an estimate over 8192 MB — a +cut never batched — raises the cap to it). An estimate under the cap is safe because +admission already leaves the floor: a build joins a running render only while +`MemAvailable − the render's estimate ≥ 6000 MB`, the same room a job that runs alone is +given — and MemAvailable at that moment already excludes what the render holds, so the +render's estimate is counted on top of its own use, not instead of it. A render that ran +over its estimate would eat into the build's room, and its node and ffmpeg still stop at the +cap. + +**Chromium is not under the cap.** hyperframes' headless Chromium moves itself into a +systemd scope of its own (`app-org.chromium.Chromium-<pid>.scope`), out of the render's capped +scope, so the 8 GB cap bounds the render's node and ffmpeg but not its browser. The estimate +counts the browser (it measured the whole process tree); the cap cannot. + +**A publish stage's build still runs alone.** `common/publish/build.ts`'s `heavyGated` runs +`queue-lock --heavy -- pnpm exec next build`, uncapped and undeclared, so it waits for a +render to finish as before. A build that declares (`systemd-run … -p MemoryMax=5G … next +build`, or `--build`) is the one that runs beside a render. ### A render and the transcription lane @@ -284,7 +344,7 @@ Hold the lane for the render's duration, and release it whatever the render's ou ```sh pnpm ops lane --json '{"lane":"transcription","held":true}' -pnpm heavy -- node umtool/report-to-video/build-video.mjs <manifest> … ; \ +node umtool/report-to-video/build-video.mjs <manifest> … ; \ pnpm ops lane --json '{"lane":"transcription","held":false}' ``` diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -1,6 +1,7 @@ # Changelog ## [Unreleased] +- **A site build can now run beside a report-video render when there is memory for both.** A render declared nothing to the machine's heavy slot, so it always ran alone: a site build started while a take rendered waited out the whole render (an hour or more for a full cut). A render now says how much memory it will need — measured on the Huck cut: about 6 GB for a whole cut (its widest step, a crossfade over 23 clips at once, peaked at 4.9 GB), about 2.4 GB for a short take of part of a cut, more with more `UMTOOL_CHROME_WORKERS` — and the encode ladder (`umtool variants`) about 1 GB. A capped site build (one run under `systemd-run … -p MemoryMax=5G`) is let in beside it while the memory left after the render's share stays at or above the 6000 MB floor, and waits for it otherwise. On this 16 GB machine that is often for a short take and rare for a whole cut. A publish stage's own build is not capped, so it still waits for the render as before. `UMTOOL_RENDER_ESTIMATE_MB` / `UMTOOL_LADDER_ESTIMATE_MB` set the share by hand, and `0` makes a render run alone again. Start a take or a build-video run as it is, not under `pnpm heavy --`, which makes it run alone. Needs a restart of umtool for takes made from the app (the `umtool take` command has it now). - **Report-video takes no longer keep their build work forever.** On 2026-10-27 /home reached 100 % (5.4 GB free of 1.5 TB), and 131 GB of it was takes' build work: each full take's chrome frames (about 12 GB for the 34-minute Huck cut, kept with `--keep-frames` so a `--from` twin can reuse them), its crossfade batches and its clip segments, swept by hand. `umtool prune <project>` (or `--all`) now lists each take's work files — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — and what freeing them gives back, or why the take keeps them: a build running in it or from it (never freed), the picked take, the take the project's manifest is, a pin in `takes/prune.json`, the newest 2 of its group, anything modified in the last 3 days, and the `--from` bases of those. It is a dry run unless `--yes`. Files hard-linked between takes are counted once, and freed only when every take holding them lets them go, so the numbers are what the disk gets back, not a sum of `du`s. The renders, previews, take.json and manifests are never touched, and nothing is followed out of a take through a link. The Takes page says each take's work and why it is kept, with **Free work files** per take and for the project (the plan first, then **Free them**). A take that finishes building now prunes its project by the same rules and says what it freed in its log, and a render that starts with under 30 GB free does the same across every project, and refuses to start under 10 GB with a sentence saying so. `--keep`, `--older-than`, `takes/prune.json` and `UMTOOL_PRUNE_*` / `UMTOOL_DISK_GUARD*` change the rules or turn them off. A dry run over ~/reports on 2026-10-27, after the hand sweep: 27 GiB of work in 32 projects' takes, 4.0 GiB of it free to go (2.4 GiB in the Huck project, whose last three days of takes are all kept). Needs a restart of umtool for the Takes page and for takes made from it; the CLI has it at once. - **An X post's screenshot is of the post, not of a page in the middle of laying itself out.** On 2026-10-27 a forced capture of TheQuartering's post 2114859155022389342 came out shifted about 100 px: its left edge cut off, X's menu laid over its words and the gap beside the column showing; another post once came out as a strip of the post above it. The shot was a full-page capture, which resizes the page for the moment of the capture — in the X session profile the page saw its window go to 1×1 — and X laid itself out again for that size while it was being captured, so the shot was cut from a different layout than the one measured. A post is now shot from the window as it stands: scrolled into it, the window made taller first when the post is taller than it, so nothing is resized under the shot; and the post is measured again after the shot and shot again if it moved. An X Article's shot is taken the same way. Posts taller than the tallest window (16,384 px) are still shot from a full-page capture. Needs a restart of the editor. - **Use with AI is the homepage's.** A published site's header and slide-out menu no longer carry it (nor the hub's header); a site still reaches the homepage's AI and MCP doc from its footer and from Ask AI, and its corpus.json and llms.txt still name it. Rebuild a site to see it. diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -453,6 +453,33 @@ render plus a concat of the whole cut, not a seconds-long retitle. The pipeline's other two deck flags, `--no-chrome` and `--chrome-preview`, are CLI-only — the driver does not wire them up. +### The heavy slot: what a render declares + +A render takes the machine's heavy slot (`scripts/queue-lock.mjs`; WORKTREES.md, "The heavy +slot") and declares its memory, so a capped site build may run beside it while MemAvailable +minus the running estimates stays at or above the 6000 MB floor. Before, a render declared +nothing and ran alone. `report-to-video/render-estimate.mjs` holds the numbers, measured: + +- **a render** — a take (`--full` or a window), and every build-video run that takes the slot + (a full build, `--chrome-only`, `--chrome-preview`, `--rail-only`, `--no-chrome`, + `--clip-preview`, `--short`): the larger of its widest ffmpeg and its chrome capture. The + widest ffmpeg is the crossfade pass, which holds every segment of a batch open: 1700 MB + + 180 MB per segment, the run's segments (a window's entries, a whole cut's; the brand intro + is one) capped at the batch size (`REPORT_VIDEO_XFADE_BATCH` / `render.xfadeBatch`, 24), + one under `--no-xfade`, a transition of 0, `--clip-preview` or `--short`. The capture is + 400 MB + 320 MB per `UMTOOL_CHROME_WORKERS` (4). A whole cut declares 6020 MB, a 4-entry + window 2420 MB, one clip 1880 MB; +- **the encode ladder** (`umtool variants`, Deliver's **Make variants**): 1000 MB (it peaked at 0.76 GB). + +Measured on the Huck cut (WORKTREES.md, "A render's estimate"): a 23-segment crossfade batch +peaked at 4.9 GB, a 120 s window's pass at 2.0 GB, the deck's 7-worker capture at 2.2 GB. + +`UMTOOL_RENDER_ESTIMATE_MB` / `UMTOOL_LADDER_ESTIMATE_MB` override them; `0` declares nothing +and the job runs alone, as before. The estimate only admits: the render still runs in its +capped scope (MemoryMax 8G). The podcast and the intro's own `render` do not declare, and run +alone. Run `umtool take` and build-video bare — under `pnpm heavy --` the wrapper is the job, +undeclared. + ### Naming The app calls this **"On-screen"** everywhere a person reads it. The manifest @@ -859,7 +886,8 @@ A take (`lib/report/takeMaker.mjs`): line per leaf the patches change (`render.montage.cut: flash`, `render.crf: 34 (was 30)`, `render.montage.ramp: removed`) after `style: <label>`. No change at all is the `reference` kind; otherwise `different` (or `--kind similar`); -3. renders: build-video through the heavy slot (`queue-lock.mjs --heavy`), `--skip-fetch` +3. renders: build-video through the heavy slot (`queue-lock.mjs --heavy --estimate <MB>`, the + render's memory estimate — see "The heavy slot: what a render declares"), `--skip-fetch` (nothing is fetched: the take's `out/clips-raw` and `out/narration` are links to the project's, and the editor's corpus windows are found as for any build), `--no-xfade` unless the take sets `render.transition`, `--no-chapters` for a window. The manifest it renders sits diff --git a/umtool/lib/report/takeMaker.mjs b/umtool/lib/report/takeMaker.mjs @@ -404,7 +404,7 @@ export function normalizeWindow(w) { * * @typedef {{ * manifestPath: string, outDir: string, slug: string, full: boolean, xfade: boolean, - * keepFrames?: boolean, + * keepFrames?: boolean, estimateMb?: number | null, * emit: (ev: Record<string, unknown>) => void, log: (line: string) => void, * }} RenderJob * @typedef {(job: RenderJob) => Promise<{ file: string }>} RenderFn diff --git a/umtool/lib/report/takeRender.mjs b/umtool/lib/report/takeRender.mjs @@ -1,7 +1,7 @@ // A take's render (release 33): build-video.mjs over the take's render // manifest, into the take's own out/, through the machine's heavy slot. // -// node scripts/queue-lock.mjs --heavy -- node build-video.mjs <render manifest> +// node scripts/queue-lock.mjs --heavy --estimate <MB> -- node build-video.mjs <render manifest> // --out takes/<id>/out --progress ndjson --skip-fetch --continue-on-error // [--no-xfade] [--no-chapters] // @@ -13,16 +13,22 @@ // --no-xfade unless the take sets a transition (the `fast` preset's hard cuts); // --no-chapters for a window, which is not a deliverable. // -// queue-lock admits the render by memory, one heavy job machine-wide, and runs -// it in a memory-capped scope unless the caller is already capped (the live -// umtool unit). Inside a slot already held (HEAVY_HELD: an e2e run) it passes -// straight through. A copy of umtool without the checkout's scripts/ runs +// queue-lock admits the render by memory and runs it in a memory-capped scope +// unless the caller is already capped (the live umtool unit). The render +// declares its estimate (render-estimate.mjs: by the segments it crossfades and +// UMTOOL_CHROME_WORKERS; UMTOOL_RENDER_ESTIMATE_MB overrides), so a capped site +// build may run beside it while MemAvailable allows; an override of 0 declares +// none, and it runs alone. +// Inside a slot already held (HEAVY_HELD: an e2e run) it passes straight +// through. A copy of umtool without the checkout's scripts/ runs // build-video directly, which takes the slot itself (heavy-gate.mjs). import { execFile, spawn } from "node:child_process"; import { existsSync } from "node:fs"; import path from "node:path"; import { promisify } from "node:util"; -import { DEFAULT_VARIANT, variantPaths } from "umtool-report-to-video/build-video"; +import { readFile } from "node:fs/promises"; +import { DEFAULT_VARIANT, variantPaths, xfadeBatchSize } from "umtool-report-to-video/build-video"; +import { manifestEstimateMb, renderEstimateMb } from "umtool-report-to-video/render-estimate"; import { PIPELINE_DIR, UMTOOL_DIR } from "./driver.mjs"; const execFileP = promisify(execFile); @@ -35,9 +41,10 @@ export function queueLockScript() { /** * The argv of a take's render, pure. - * @param {{ manifestPath: string, outDir: string, full: boolean, xfade: boolean, keepFrames?: boolean, queueLock?: string | null }} job + * `estimateMb`: what the render declares to the heavy slot (null: nothing). + * @param {{ manifestPath: string, outDir: string, full: boolean, xfade: boolean, keepFrames?: boolean, queueLock?: string | null, estimateMb?: number | null }} job */ -export function renderArgv({ manifestPath, outDir, full, xfade, keepFrames = false, queueLock = queueLockScript() }) { +export function renderArgv({ manifestPath, outDir, full, xfade, keepFrames = false, queueLock = queueLockScript(), estimateMb = renderEstimateMb("render") }) { const build = [ process.execPath, path.join(/* turbopackIgnore: true */ PIPELINE_DIR, "build-video.mjs"), @@ -52,7 +59,34 @@ export function renderArgv({ manifestPath, outDir, full, xfade, keepFrames = fal ...(full ? [] : ["--no-chapters"]), ...(keepFrames ? ["--keep-frames"] : []), ]; - return queueLock ? [process.execPath, queueLock, "--heavy", "--", ...build] : build; + if (!queueLock) return build; + const estimate = Number(estimateMb) > 0 ? ["--estimate", String(Math.round(Number(estimateMb)))] : []; + return [process.execPath, queueLock, "--heavy", ...estimate, "--", ...build]; +} + +/** + * What a take's render declares to the heavy slot (render-estimate.mjs): the + * render manifest's segments (a window's entries, a whole cut's) in its + * batches, one when the take does not crossfade. A manifest it cannot read + * declares a full batch. + * + * @param {{ manifestPath: string, xfade: boolean }} job + * @param {Record<string, string | undefined>} [env] + */ +export async function takeEstimateMb({ manifestPath, xfade }, env = process.env) { + let manifest = null; + try { + manifest = JSON.parse(await readFile(/* turbopackIgnore: true */ manifestPath, "utf8")); + } catch { + return renderEstimateMb("render", env); + } + let batch; + try { + batch = xfadeBatchSize(manifest?.render ?? {}, env); + } catch { + batch = undefined; + } + return manifestEstimateMb(manifest, env, { xfade, batch }); } /** @@ -63,8 +97,8 @@ export function renderArgv({ manifestPath, outDir, full, xfade, keepFrames = fal * @param {import("./takeMaker.mjs").RenderJob} job * @returns {Promise<{ file: string }>} */ -export function renderTake(job) { - const argv = renderArgv(job); +export async function renderTake(job) { + const argv = renderArgv({ ...job, estimateMb: job.estimateMb !== undefined ? job.estimateMb : await takeEstimateMb(job) }); job.log(`$ ${argv.join(" ")}`); return new Promise((resolve, reject) => { const child = spawn(argv[0], argv.slice(1), { diff --git a/umtool/report-to-video/build-video.mjs b/umtool/report-to-video/build-video.mjs @@ -241,6 +241,7 @@ import { validateMontage, wallComposeArgs, WALL_ENTRY, clipStream, median, nearSilent, relocateBySound, shiftAllowed, speechEnvelope, loudnessGain, levelFilters, parseIntegratedLoudness, wallCells, wallTileLabel, WALL_LEAD, WALL_TAIL, wallPlan, wallTileArgs, wallTileClips, whisperWords, } from "./montage.mjs"; import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs"; +import { chromeWorkers, manifestEstimateMb } from "./render-estimate.mjs"; const execFileP = promisify(execFile); @@ -249,7 +250,9 @@ const FFMPEG = process.env.FFMPEG_BIN ?? "ffmpeg"; // Chromium workers for the 4-worker chrome regions (deck, feed, teaser): a // render on an idle 8-core machine is capture-bound, and 4 leaves cores idle. // UMTOOL_CHROME_WORKERS raises it for one run; absent, 4 as before. -const CHROME_WORKERS = Math.max(1, Math.min(16, Number(process.env.UMTOOL_CHROME_WORKERS) || 4)); +// (render-estimate.mjs reads it the same way: a render's memory estimate scales +// with it.) +const CHROME_WORKERS = chromeWorkers(process.env); // The 2-worker regions (posts, finale, stamps, stats, threads, flips): the same // knob raises them too when it is set; absent, 2 as before. const CHROME_WORKERS_SMALL = process.env.UMTOOL_CHROME_WORKERS ? CHROME_WORKERS : 2; @@ -6682,7 +6685,8 @@ export function chromeFlags(argv) { * Does this run take the machine's heavy slot (heavy-gate.mjs)? Every run that * renders the cut does -- a full build, --chrome-only, --chrome-preview, * --rail-only, a --no-chrome build, one clip's --clip-preview. A fetch, one `--only` segment, the - * chapters and the thumbnail do not. + * chapters and the thumbnail do not. A run that takes it declares a render's + * memory estimate (render-estimate.mjs), so a capped build may run beside it. */ export function takesHeavySlot({ opts = {}, only = null, fetchOnly = null } = {}) { // A short is a 1080x1920 encode of one clip: a render, in the slot. @@ -6690,6 +6694,32 @@ export function takesHeavySlot({ opts = {}, only = null, fetchOnly = null } = {} return !fetchOnly && !only && !opts.chaptersOnly && !opts.thumbnailOnly; } +/** + * What this CLI run declares to the heavy slot (render-estimate.mjs): the + * manifest's segments, in this build's batches; one clip for --clip-preview + * and --short; nothing crossfaded under --no-xfade. A manifest it cannot read + * declares a full batch (the build then says what is wrong with it). + */ +export async function cliEstimateMb(manifestPath, opts = {}, env = process.env) { + let manifest = null; + try { + manifest = JSON.parse(await readFile(manifestPath, "utf8")); + } catch { + manifest = null; + } + let batch; + try { + batch = xfadeBatchSize(manifest?.render ?? {}, env); + } catch { + batch = undefined; + } + return manifestEstimateMb(manifest, env, { + xfade: !opts.noXfade, + single: Boolean(opts.clipPreview || opts.short), + batch, + }); +} + // heavy-gate.mjs's withRenderSlot, loaded by a URL made at run time: the // umtool app imports this file, and the gate (and the checkout's // scripts/queue-lock.mjs behind it) must never reach its bundle. Only main() @@ -6812,7 +6842,9 @@ async function main() { const fetchOnly = flag("--fetch-only"); const build = () => buildVideo({ manifestPath, opts, out: flag("--out"), only, fetchOnly }); const { failures } = takesHeavySlot({ opts, only, fetchOnly }) - ? await (await renderSlot())(["build-video", ...argv], () => guardedRender(flag("--out"), manifestPath, build)) + ? await (await renderSlot())(["build-video", ...argv], () => guardedRender(flag("--out"), manifestPath, build), { + estimateMb: await cliEstimateMb(manifestPath, opts), + }) : await build(); // Non-zero on a partial run, so a caller that ignores the events still learns // the build did not produce what was asked for. diff --git a/umtool/report-to-video/heavy-gate.mjs b/umtool/report-to-video/heavy-gate.mjs @@ -47,13 +47,14 @@ export function heavyLockFile(root = checkoutRoot()) { * * `estimateMb` declares the job's memory (queue-lock's weighted admission): it * then runs BESIDE others while MemAvailable minus every running estimate stays - * at or above the floor, and waits otherwise. Without one it runs alone, as a - * render does. The bench's prep (lib/report/benchPrep.mjs) declares one. + * at or above the floor, and waits otherwise. Without one it runs alone. A + * render declares one (render-estimate.mjs), and so does the bench's prep + * (lib/report/benchPrep.mjs). * * @template T * @param {string[]} cmd * @param {() => Promise<T>} fn - * @param {{ env?: NodeJS.ProcessEnv, root?: string, say?: (line: string) => void, estimateMb?: number }} [opts] + * @param {{ env?: NodeJS.ProcessEnv, root?: string, say?: (line: string) => void, estimateMb?: number | null }} [opts] * @returns {Promise<T>} */ export async function withRenderSlot(cmd, fn, { env = process.env, root = checkoutRoot(), say, estimateMb } = {}) { diff --git a/umtool/report-to-video/package.json b/umtool/report-to-video/package.json @@ -52,6 +52,7 @@ "./post-links": "./post-links.mjs", "./prune-frames": "./prune-frames.mjs", "./render-cards": "./render-cards.mjs", + "./render-estimate": "./render-estimate.mjs", "./resolve-windows": "./resolve-windows.mjs", "./room": "./room.mjs", "./shoot-page": "./shoot-page.mjs", diff --git a/umtool/report-to-video/render-estimate.mjs b/umtool/report-to-video/render-estimate.mjs @@ -0,0 +1,133 @@ +// HOW MUCH MEMORY A RENDER DECLARES to the heavy slot (scripts/queue-lock.mjs). +// +// The slot admits by memory: a job that declares an estimate runs BESIDE +// others while MemAvailable minus every running job's estimate stays at or +// above the floor (HEAVY_MIN_FREE_MB, 6000); a job that declares nothing runs +// ALONE. A render used to declare nothing, so a capped site build (it declares +// its 5 GB MemoryMax) waited out the whole render. Now every render declares: +// +// a take (takeRender.mjs, `queue-lock --heavy --estimate <MB> -- build-video …`), +// build-video's own heavy runs (heavy-gate.mjs withRenderSlot), kind "render" +// the encode ladder (variants.mjs), kind "ladder" +// +// MEASURED (2026-10-26, the process tree's PSS -- Chromium included -- sampled +// every 3 s; the Huck cut, 1920x1080 30 fps, x264 slow, 68 segments): +// +// the crossfade pass, 23 segments open at once (one of 3 batches) 4.9 GB +// the last join (3 batch files + 4 chrome layers) 1.4 GB +// a 120 s window's one pass (4 segments, the chrome over them) 2.0 GB +// one segment's encode 0.85 GB +// the full deck's capture, 7 Chromium workers 2.2 GB +// a window's capture, 4 / 7 workers 0.8 / 1.15 GB +// the ladder's re-encode (x264 medium, one rung at a time) 0.76 GB +// +// So a render's peak is its widest ffmpeg -- the crossfade pass holds every +// segment of a batch open, about 200 MB each (build-video's xfadeBatches: +// REPORT_VIDEO_XFADE_BATCH / render.xfadeBatch, default 24) -- or its chrome +// capture, whichever is larger: the phases run one after another, so the peak +// is the larger of the two, not their sum. +// +// render: max(ENCODE_BASE + ENCODE_PER_SEGMENT × min(segments, batch), +// CHROME_BASE + CHROME_PER_WORKER × workers) +// +// `segments` is what the run joins (a window's entries, a whole cut's; unknown: +// a full batch); `workers` is UMTOOL_CHROME_WORKERS as build-video reads it +// (1-16, default 4). The constants carry about 20 % over the measured line. +// +// UMTOOL_RENDER_ESTIMATE_MB / UMTOOL_LADDER_ESTIMATE_MB override a kind's +// number; `0` declares nothing, and the job runs alone as before. +// +// The estimate is for ADMISSION; the cap is the hard limit. An admitted +// `--heavy` command still runs in its capped scope (MemoryMax 8G, swap 2G, +// queue-lock's heavyCapPlan; an estimate over the cap raises the cap to it). +// +// Pure and dependency-free: the umtool app bundles takeRender.mjs, which +// imports this, and build-video.mjs imports it too (no cycle). + +/** The crossfade / overlay pass's own memory, with no segment open. */ +export const RENDER_ENCODE_BASE_MB = 1700; +/** Each segment the pass holds open (a decoder and its frames). */ +export const RENDER_ENCODE_PER_SEGMENT_MB = 180; +/** One chrome region's capture: hyperframes' node, the browser and GPU processes. */ +export const RENDER_CHROME_BASE_MB = 400; +/** Each Chromium renderer page a region captures with. */ +export const RENDER_CHROME_PER_WORKER_MB = 320; +/** The ladder's one x264 re-encode at a time. */ +export const LADDER_ESTIMATE_MB = 1000; +/** build-video's XFADE_BATCH_DEFAULT: the segments one crossfade pass opens. */ +export const XFADE_BATCH = 24; + +/** The chrome workers a render uses: build-video's CHROME_WORKERS, read the same way. */ +export function chromeWorkers(env = process.env) { + return Math.max(1, Math.min(16, Number(env.UMTOOL_CHROME_WORKERS) || 4)); +} + +const OVERRIDE = { render: "UMTOOL_RENDER_ESTIMATE_MB", ladder: "UMTOOL_LADDER_ESTIMATE_MB" }; + +/** + * The segments one pass holds open: `segments` capped by the batch size + * (`batch` 0 never batches); unknown segments, a full batch. + */ +export function openSegments(segments, batch = XFADE_BATCH) { + const size = Number.isInteger(batch) && batch >= 0 ? batch : XFADE_BATCH; + const n = Number.isFinite(segments) && segments > 0 ? Math.ceil(segments) : null; + if (n == null) return size || XFADE_BATCH; + return size ? Math.min(n, size) : n; +} + +/** + * The estimate (MB) a render of `kind` declares, or null to declare nothing + * (an override of `0`: the job then runs alone). + * + * @param {"render" | "ladder"} [kind] + * @param {Record<string, string | undefined>} [env] + * @param {{ segments?: number | null, batch?: number }} [shape] what the run joins, and the batch size + * @returns {number | null} + */ +export function renderEstimateMb(kind = "render", env = process.env, { segments = null, batch = XFADE_BATCH } = {}) { + const name = OVERRIDE[kind]; + if (!name) throw new Error(`renderEstimateMb: no kind '${kind}' (render, ladder)`); + const raw = env[name]; + if (raw != null && String(raw).trim() !== "") { + const n = Number(raw); + if (n === 0) return null; + if (n > 0) return Math.round(n); + // Not a size: fall through to the measured default rather than run alone. + } + if (kind === "ladder") return LADDER_ESTIMATE_MB; + const encode = RENDER_ENCODE_BASE_MB + RENDER_ENCODE_PER_SEGMENT_MB * openSegments(segments, batch); + const chrome = RENDER_CHROME_BASE_MB + RENDER_CHROME_PER_WORKER_MB * chromeWorkers(env); + return Math.max(encode, chrome); +} + +/** + * The segments a manifest's render joins: its timeline's entries, and the + * brand intro's own segment when it has one. Null when it cannot tell. + * + * @param {any} manifest + * @returns {number | null} + */ +export function manifestSegments(manifest) { + const timeline = manifest?.timeline; + if (!Array.isArray(timeline)) return null; + return timeline.length + (manifest?.render?.intro ? 1 : 0); +} + +/** + * What a render of `manifest` declares (renderEstimateMb's "render"): its + * segments joined in batches of `batch`; one segment when nothing is + * crossfaded (`xfade` false: --no-xfade, a transition of 0 -- the concat + * stream-copies and one pass lays the chrome over it) or when the run is one + * clip (`single`: --clip-preview, --short). A manifest it cannot read: a full + * batch. + * + * @param {any} manifest + * @param {Record<string, string | undefined>} [env] + * @param {{ xfade?: boolean, single?: boolean, batch?: number }} [o] + * @returns {number | null} + */ +export function manifestEstimateMb(manifest, env = process.env, { xfade = true, single = false, batch = XFADE_BATCH } = {}) { + const crossfades = xfade && (manifest?.render?.transition ?? 0.5) !== 0; + const segments = single || (manifest && !crossfades) ? 1 : manifestSegments(manifest); + return renderEstimateMb("render", env, { segments, batch }); +} diff --git a/umtool/report-to-video/render-estimate.test.mjs b/umtool/report-to-video/render-estimate.test.mjs @@ -0,0 +1,304 @@ +// 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 { + 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) => RENDER_CHROME_BASE_MB + RENDER_CHROME_PER_WORKER_MB * w; + +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"); + assert.equal(chromeWorkers({}), 4, "build-video's default"); + assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "7" }), 7); + assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "99" }), 16, "clamped as build-video clamps it"); + assert.equal(chromeWorkers({ UMTOOL_CHROME_WORKERS: "junk" }), 4); + // 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 }), Math.max(encode(4), chrome(4))); + assert.equal(renderEstimateMb("render", {}, { segments: 1 }), Math.max(encode(1), chrome(4))); + // Chrome workers dominate a short run once there are enough of them. + assert.equal(renderEstimateMb("render", { UMTOOL_CHROME_WORKERS: "16" }, { segments: 1 }), chrome(16)); + assert.ok(chrome(16) > 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) <= 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(4))); + 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(4))); + assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}), render: { transition: 0 } }, {}), Math.max(encode(1), chrome(4))); + assert.equal(manifestEstimateMb({ ...m, timeline: Array(67).fill({}) }, {}, { single: true }), Math.max(encode(1), chrome(4))); + 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, {}, {}), encode(10), "render.xfadeBatch sizes the pass"); + assert.equal(await cliEstimateMb(file, {}, { REPORT_VIDEO_XFADE_BATCH: "16" }), encode(16), "the env's batch wins, as in build-video"); + assert.equal(await cliEstimateMb(file, { clipPreview: "c1" }, {}), Math.max(encode(1), chrome(4))); + assert.equal(await cliEstimateMb(file, { noXfade: true }, {}), Math.max(encode(1), chrome(4))); + assert.equal(await cliEstimateMb(path.join(dir, "absent.json"), {}, {}), RENDER); + assert.equal(await takeEstimateMb({ manifestPath: file, xfade: true }, {}), encode(10)); + assert.equal(await takeEstimateMb({ manifestPath: file, xfade: false }, {}), Math.max(encode(1), chrome(4))); + 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<id>" at its start and "E<id>" 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`)); +}); diff --git a/umtool/report-to-video/variants.mjs b/umtool/report-to-video/variants.mjs @@ -21,13 +21,15 @@ // // node umtool/report-to-video/variants.mjs <take out dir> [--slug s] [--only name,…] [--source file] // -// The CLI takes the machine's heavy slot (heavy-gate.mjs); encodeVariants -// itself does not -- umtool's job runner holds it for the UI. +// The CLI takes the machine's heavy slot (heavy-gate.mjs), declaring the +// ladder's memory estimate (render-estimate.mjs); encodeVariants itself does +// not -- umtool's job runner holds it for the UI. import { execFile } from "node:child_process"; import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { pathToFileURL } from "node:url"; import { promisify } from "node:util"; +import { renderEstimateMb } from "./render-estimate.mjs"; const execFileP = promisify(execFile); const FFMPEG = () => process.env.FFMPEG_BIN ?? "ffmpeg"; @@ -289,7 +291,8 @@ async function main() { // CLI loads it: never a module the umtool app's bundle traces. const gate = new URL("./heavy-gate.mjs", pathToFileURL(process.argv[1])).href; const { withRenderSlot } = await import(/* webpackIgnore: true */ gate); - const doc = await withRenderSlot(["variants", outDir], run); + // It declares the ladder's estimate, so a capped build may run beside it. + const doc = await withRenderSlot(["variants", outDir], run, { estimateMb: renderEstimateMb("ladder") }); process.stdout.write(JSON.stringify(doc, null, 2) + "\n"); }