Archilyzer · Source

archilyzer

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

commit 553bb861f255b9340514da63bdf72650d85a2e94
parent a7a48b349b170ac7a05a6b41faa920a1adb16655
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 27 Oct 2026 17:58:13 -0400

Take prune: the model -- each take's work files, counted by inode, kept or prunable by policy

lib/report/takePrune.mjs names a take's WORK (under out/: segments,
chrome/*-frames and work-*, xfade-batches, chunks and the hash memo, the
rail's prerail cache, .keep-frames, a real clips-raw) and leaves every other
file FINAL. Bytes are allocated blocks counted by inode: a file hard-linked
into two takes (umtool take --from) counts once, and is freed only when every
link is among the paths removed; a plan over several takes counts the union.

The policy keeps a take's work while it is being built (a live
.building.json lock, or a pipeline process naming it) or is the base of a
take being built -- never overridden -- and, as policy: picked, current (the
project's manifest is its), pinned in takes/prune.json, the newest K of its
group (2), modified within D days (3), or the --from base of a kept take.
Settings: defaults < UMTOOL_PRUNE_* < takes/prune.json < flags.

Deletion lstat's every work path (a link is never work, never followed)
and requires its real path inside the take (or its media-root mirror);
chrome layers are recorded in chrome/pruned.json first (prune-frames
recordPrunedSequences), and each prune is appended to pruned-work.json.
The disk guard (diskGuard) is here too. busy.mjs scans /proc once
(pipelineProcesses) for a caller asking about many directories.

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

Diffstat:
Mumtool/lib/report/busy.mjs | 46+++++++++++++++++++++++++++++++---------------
Aumtool/lib/report/takePrune.mjs | 1052+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Aumtool/lib/report/takePrune.test.mjs | 395+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/report-to-video/prune-frames.mjs | 31+++++++++++++++++++++++++++++++
4 files changed, 1509 insertions(+), 15 deletions(-)

diff --git a/umtool/lib/report/busy.mjs b/umtool/lib/report/busy.mjs @@ -55,25 +55,19 @@ export function namesProject(args, cwd, project) { } /** - * The pids of pipeline processes working in `project` (see the top of the file). - * @param {{ dir: string, id?: string, name?: string }} project + * Every pipeline process running now (the scripts above, by argv), with its + * argv and working directory -- read from /proc once, for a caller that asks + * about many directories (takePrune.mjs asks about every take of a project). * @param {{ procRoot?: string, selfPid?: number }} [opts] - * @returns {number[]} + * @returns {{ pid: number, args: string[], cwd: string | null }[]} */ -export function pipelineProcessesFor(project, { procRoot = "/proc", selfPid = process.pid } = {}) { - let realDir = project.dir; - try { - realDir = realpathSync(project.dir); - } catch { - /* gone: nothing can be running in it */ - } - const ref = { ...project, realDir }; - const pids = []; +export function pipelineProcesses({ procRoot = "/proc", selfPid = process.pid } = {}) { + const out = []; let entries = []; try { entries = readdirSync(procRoot).filter((n) => /^\d+$/.test(n)); } catch { - return pids; + return out; } for (const pid of entries) { if (Number(pid) === selfPid) continue; @@ -90,7 +84,29 @@ export function pipelineProcessesFor(project, { procRoot = "/proc", selfPid = pr } catch { /* another user's process, or gone */ } - if (namesProject(args, cwd, ref)) pids.push(Number(pid)); + out.push({ pid: Number(pid), args, cwd }); } - return pids; + return out; +} + +/** `project` with its real directory beside it, for namesProject. */ +export function projectRefOf(project) { + let realDir = project.dir; + try { + realDir = realpathSync(project.dir); + } catch { + /* gone: nothing can be running in it */ + } + return { ...project, realDir }; +} + +/** + * The pids of pipeline processes working in `project` (see the top of the file). + * @param {{ dir: string, id?: string, name?: string }} project + * @param {{ procRoot?: string, selfPid?: number }} [opts] + * @returns {number[]} + */ +export function pipelineProcessesFor(project, opts = {}) { + const ref = projectRefOf(project); + return pipelineProcesses(opts).filter((p) => namesProject(p.args, p.cwd, ref)).map((p) => p.pid); } diff --git a/umtool/lib/report/takePrune.mjs b/umtool/lib/report/takePrune.mjs @@ -0,0 +1,1052 @@ +// PRUNING TAKES' WORK FILES (2026-10-27): what a take's build leaves behind to +// make the next build faster, removed when no take is likely to need it. +// +// On 2026-10-27 /home reached 100 % (5.4 GB free of 1.5 TB): 131 GB of it was +// report-video takes' build work, kept forever -- each full take's chrome +// frames (~12 GB for a 34-minute cut, kept on purpose by `--keep-frames` so a +// `--from` twin reuses them), its crossfade batches and its clip segments. +// +// FINAL AND WORK. Everything under `takes/<id>/` is FINAL -- never touched -- +// except the WORK this file names, all of it under the take's `out/`: +// +// out/.keep-frames/ layers kept aside for a --from (takeFrom.mjs) +// out/clips-raw/ a real directory of raw clip copies (the +// usual one is a LINK to the project's: not work) +// out/<variant>/segments/ each clip's encoded segment and its records +// out/<variant>/xfade-batches/ the crossfade batches +// out/<variant>/chunks/ the final encode's chunks (chunked-encode.mjs) +// out/<variant>/.content-hashes.json that encode's content-hash memo +// out/<variant>/chrome/*-frames/ each chrome layer's PNG sequence +// out/<variant>/chrome/work-*/ a render's leftovers, --from's work-from-* +// out/<variant>/<slug>.prerail*.mp4 the rail's cached base (--rail-only), and +// its .segments record +// +// So the renders (out/<slug>.mp4, its ladder rungs, the trailer), preview.mp4, +// take.json, the manifests, schedule.json, sync.json, the chapters, the cards, +// the QRs, the chrome compositions and every small record stay. A name not on +// that list is FINAL by default: an unknown file is never removed. +// +// HARD LINKS ARE COUNTED, NOT SUMMED. `umtool take --from` links the other +// take's segments and frames in, so two takes may hold the same inodes and a +// `du` of each counts them twice. A file's bytes are freed only when EVERY link +// to it goes: a file with st_nlink 1 is freed by removing it; one with more is +// freed only when all its links are among the paths removed (counted by inode, +// over the whole set being removed). A take's "work" is its unique inodes' +// bytes; "frees" is what removing that take's work alone gives back; a plan +// over several takes counts the union. Bytes are allocated blocks (st_blocks × +// 512, what df sees), directories included. +// +// WHAT IS KEPT (the policy). A take keeps its work when it is: +// - being built: a live build lock (`takes/<id>/.building.json`, written by +// the take maker; `<out>/.building.json`, by build-video for its --out), or +// a pipeline process naming a path in it (busy.mjs) -- never pruned, not +// even by name; +// - the base of a take being built (its lock's `from`) -- never pruned either; +// - picked in its group (verdicts.json), or the project's manifest is its +// manifest (the deliverable is built from it); +// - pinned in the project's `takes/prune.json` (`"pin": ["<take>"]`); +// - one of the newest K of its group (by builtAt; default 2); +// - modified within D days (take.json, preview.mp4, builtAt; default 3); +// - the `--from` base of a take kept for any reason above (take.json's +// `from`, a lock's, xfade-batches/.from.json's), transitively. +// Everything else's work is prunable. Naming a take (`--take X`) with +// `--anyway` (the UI's "free anyway") overrides the reasons that are policy, +// never the two that are a running build. +// +// THE SETTINGS, lowest first: the defaults; UMTOOL_PRUNE_KEEP, +// UMTOOL_PRUNE_DAYS, UMTOOL_PRUNE_AFTER_BUILD=0; the project's +// `takes/prune.json` ({ keep, olderThanDays, pin, afterBuild }); the CLI's +// --keep / --older-than. The disk guard: UMTOOL_DISK_GUARD=0, +// UMTOOL_DISK_GUARD_GB (30), UMTOOL_DISK_FLOOR_GB (10). docs/report-video.md. +// +// DELETION never leaves the take. Each WORK path is lstat'ed (a symlink is not +// work: never followed, never removed) and its REAL path must be inside the +// take's real directory -- or, when the take's out/ is the media root's link +// (storage.mjs), inside that link's own mirror target. The walk under it +// unlinks files and symlinks (a link, not what it points at) and descends only +// into real directories. A clip copy that links into the corpus loses the +// link, never the corpus file. +// +// Plain ESM: the CLI runs it with bare node, the app imports it. Every path is +// a parameter or from paths.mjs. + +import { lstat, readdir, readFile, realpath, rename, rmdir, stat, statfs, unlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; +import { MEDIA_ROOT, REPORTS_ROOT, inside, mediaMirror } from "../paths.mjs"; +import { namesProject, pipelineProcesses } from "./busy.mjs"; +import { TAKES_DIR, isTakeId, parseTake, readVerdicts, takesDirOf } from "./takes.mjs"; + +/** The project's prune settings: `takes/prune.json`. */ +export const POLICY_FILE = "prune.json"; +/** A build's lock: `takes/<id>/.building.json` (the take maker), `<out>/.building.json` (build-video). */ +export const BUILD_LOCK = ".building.json"; +/** What was pruned from a take, newest last: `takes/<id>/pruned-work.json`. */ +export const PRUNE_RECORD = "pruned-work.json"; +const PRUNE_RECORD_KEEP = 20; + +export const DEFAULT_POLICY = Object.freeze({ keep: 2, olderThanDays: 3, afterBuild: true }); +export const DISK_GUARD_DEFAULTS = Object.freeze({ thresholdGB: 30, floorGB: 10 }); + +// The writers' names (checked against their constants in takePrune.test.mjs; +// not imported, so the CLI need not load build-video.mjs to prune). +export const KEEP_FRAMES_DIR = ".keep-frames"; // takeFrom.mjs +export const XFADE_FROM_FILE = ".from.json"; // build-video.mjs +const NOT_VARIANTS = new Set(["clips-raw", "narration", "bench-excerpts", "posts-media", KEEP_FRAMES_DIR]); +const IN_VARIANT = [ + { name: "segments", kind: "dir", what: "clip segments" }, + { name: "xfade-batches", kind: "dir", what: "crossfade batches" }, + { name: "chunks", kind: "dir", what: "the final encode's chunks" }, + { name: ".content-hashes.json", kind: "file", what: "the encode's content-hash memo" }, +]; +const PRERAIL = /\.prerail(-hardcut)?\.mp4(\.segments)?$/; + +/** The reasons a take is kept that no `--anyway` overrides. */ +export const HARD_REASONS = new Set(["building", "base-of-building", "just-built", "link"]); + +const GiB = 1024 ** 3; + +/** Bytes for a person: `12.3 GiB`, `840 MiB`, `0 B`. */ +export function fmtBytes(n) { + const v = Number(n) || 0; + if (v < 1024) return `${v} B`; + const units = ["KiB", "MiB", "GiB", "TiB"]; + let x = v / 1024; + let i = 0; + while (x >= 1024 && i < units.length - 1) { + x /= 1024; + i += 1; + } + return `${x.toFixed(x >= 100 || i < 2 ? 0 : 1)} ${units[i]}`; +} + +/** + * An age in days: `3d`, `12h`, `90m`, `2.5` (days), `0`. + * @returns {number} + */ +export function parseAge(v) { + if (typeof v === "number" && Number.isFinite(v) && v >= 0) return v; + const m = /^\s*(\d+(?:\.\d+)?)\s*(d|h|m)?\s*$/i.exec(String(v ?? "")); + if (!m) throw new Error(`"${v}" is not an age: a number of days, or 3d, 12h, 90m`); + const n = Number(m[1]); + const unit = (m[2] ?? "d").toLowerCase(); + return unit === "d" ? n : unit === "h" ? n / 24 : n / (24 * 60); +} + +const keepCount = (v, where) => { + const n = Number(v); + if (!Number.isInteger(n) || n < 0) throw new Error(`${where}: keep is a whole number ≥ 0, not ${JSON.stringify(v)}`); + return n; +}; + +/** + * The project's `takes/prune.json`, checked: `{}` when there is none. One that + * does not parse, or says something that is not the shape, is an ERROR -- + * pruning on a policy nobody wrote would delete what it meant to keep. + */ +export async function readPolicyFile(projectDir) { + const file = path.join(/* turbopackIgnore: true */ takesDirOf(projectDir), POLICY_FILE); + let text; + try { + text = await readFile(/* turbopackIgnore: true */ file, "utf8"); + } catch { + return {}; + } + let raw; + try { + raw = JSON.parse(text); + } catch (err) { + throw new Error(`${TAKES_DIR}/${POLICY_FILE} does not parse (${err instanceof Error ? err.message : err}): not pruning on a guess`); + } + if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error(`${TAKES_DIR}/${POLICY_FILE} is not an object`); + const out = {}; + const where = `${TAKES_DIR}/${POLICY_FILE}`; + if (raw.keep !== undefined) out.keep = keepCount(raw.keep, where); + if (raw.olderThanDays !== undefined) { + try { + out.olderThanDays = parseAge(raw.olderThanDays); + } catch (err) { + throw new Error(`${where}: olderThanDays — ${err instanceof Error ? err.message : err}`); + } + } + if (raw.pin !== undefined) { + if (!Array.isArray(raw.pin) || !raw.pin.every((t) => isTakeId(t))) throw new Error(`${where}: pin is a list of take ids`); + out.pin = [...raw.pin]; + } + if (raw.afterBuild !== undefined) { + if (typeof raw.afterBuild !== "boolean") throw new Error(`${where}: afterBuild is true or false`); + out.afterBuild = raw.afterBuild; + } + return out; +} + +/** + * The policy in force: the defaults, then the environment, then the project's + * file, then the command line. `from` says where each value came from. + * + * @param {{ file?: Record<string, any>, env?: NodeJS.ProcessEnv, flags?: { keep?: unknown, olderThan?: unknown } }} [src] + */ +export function resolvePolicy({ file = {}, env = process.env, flags = {} } = {}) { + const p = { keep: DEFAULT_POLICY.keep, olderThanDays: DEFAULT_POLICY.olderThanDays, afterBuild: DEFAULT_POLICY.afterBuild, pin: /** @type {string[]} */ ([]) }; + const from = { keep: "default", olderThanDays: "default", afterBuild: "default" }; + if (env.UMTOOL_PRUNE_KEEP !== undefined && env.UMTOOL_PRUNE_KEEP !== "") { + p.keep = keepCount(env.UMTOOL_PRUNE_KEEP, "UMTOOL_PRUNE_KEEP"); + from.keep = "UMTOOL_PRUNE_KEEP"; + } + if (env.UMTOOL_PRUNE_DAYS !== undefined && env.UMTOOL_PRUNE_DAYS !== "") { + p.olderThanDays = parseAge(env.UMTOOL_PRUNE_DAYS); + from.olderThanDays = "UMTOOL_PRUNE_DAYS"; + } + if (env.UMTOOL_PRUNE_AFTER_BUILD === "0") { + p.afterBuild = false; + from.afterBuild = "UMTOOL_PRUNE_AFTER_BUILD"; + } + if (file.keep !== undefined) [p.keep, from.keep] = [file.keep, POLICY_FILE]; + if (file.olderThanDays !== undefined) [p.olderThanDays, from.olderThanDays] = [file.olderThanDays, POLICY_FILE]; + if (file.afterBuild !== undefined) [p.afterBuild, from.afterBuild] = [file.afterBuild, POLICY_FILE]; + if (file.pin) p.pin = [...file.pin]; + if (flags.keep !== undefined) [p.keep, from.keep] = [keepCount(flags.keep, "--keep"), "--keep"]; + if (flags.olderThan !== undefined) [p.olderThanDays, from.olderThanDays] = [parseAge(flags.olderThan), "--older-than"]; + return { ...p, from }; +} + +/** The policy as one line. */ +export function policyLine(p) { + const days = p.olderThanDays >= 1 ? `${+p.olderThanDays.toFixed(2)} d` : `${+(p.olderThanDays * 24).toFixed(1)} h`; + return ( + `keeps: running builds and their bases, the picked or current take, ` + + `the newest ${p.keep} per group, anything modified within ${days}` + + `${p.pin?.length ? `, pinned (${p.pin.join(", ")})` : ""}, and the --from bases of those` + ); +} + +// --------------------------------------------------------------------------- +// Build locks +// --------------------------------------------------------------------------- + +/** Is a process with this pid alive here? EPERM (another user's) is alive. */ +export function pidAlive(pid) { + if (!Number.isInteger(pid) || pid <= 0) return false; + try { + process.kill(pid, 0); + return true; + } catch (err) { + return /** @type {NodeJS.ErrnoException} */ (err)?.code === "EPERM"; + } +} + +/** A build lock, read: null when there is none or it does not parse. */ +export async function readBuildLock(file) { + try { + const j = JSON.parse(await readFile(/* turbopackIgnore: true */ file, "utf8")); + return j && typeof j === "object" && !Array.isArray(j) ? j : null; + } catch { + return null; + } +} + +/** + * Is this lock a build running now? A lock from another host is taken as + * running (this machine cannot tell); one from here whose pid is gone is stale. + */ +export function lockIsLive(lock, { host = os.hostname(), alive = pidAlive } = {}) { + if (!lock) return false; + if (lock.host && lock.host !== host) return true; + return alive(Number(lock.pid)); +} + +/** + * Write a build lock in `dir` (which must exist): `{ pid, host, startedAt, ...info }`. + * @returns {Promise<string>} the lock's path + */ +export async function writeBuildLock(dir, info = {}, { now = () => new Date() } = {}) { + const file = path.join(/* turbopackIgnore: true */ dir, BUILD_LOCK); + const doc = { pid: process.pid, host: os.hostname(), startedAt: now().toISOString(), ...info }; + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc) + "\n", "utf8"); + await rename(tmp, file); + return file; +} + +/** Remove a lock this process wrote (another process's is left). */ +export async function removeBuildLock(file) { + const lock = await readBuildLock(file); + if (lock && Number(lock.pid) === process.pid && (!lock.host || lock.host === os.hostname())) await unlink(file).catch(() => {}); +} + +/** + * Run `fn` holding a build lock in `dir`. With no `dir` (or one that is not + * there), just runs it: the lock is a marker for the pruner, not a mutex. + * @template T + * @param {string | null | undefined} dir + * @param {Record<string, unknown>} info + * @param {() => Promise<T>} fn + * @returns {Promise<T>} + */ +export async function withBuildLock(dir, info, fn) { + let file = null; + if (dir && (await stat(/* turbopackIgnore: true */ dir).then((s) => s.isDirectory(), () => false))) { + file = await writeBuildLock(dir, info).catch(() => null); + } + try { + return await fn(); + } finally { + if (file) await removeBuildLock(file); + } +} + +// --------------------------------------------------------------------------- +// One take's WORK, found and measured +// --------------------------------------------------------------------------- + +/** + * The directories a WORK path's real path may be in: the take's own, and -- + * when its out/ is the media root's link -- that link's mirror target. + */ +async function allowedRootsOf(takeDir, { reportsRoot, mediaRoot }) { + const notes = []; + const realTake = await realpath(/* turbopackIgnore: true */ takeDir).catch(() => null); + if (!realTake) return { allowed: [], out: null, notes: ["the take's directory is not readable"] }; + const out = path.join(/* turbopackIgnore: true */ takeDir, "out"); + const st = await lstat(/* turbopackIgnore: true */ out).catch(() => null); + if (!st) return { allowed: [realTake], out: null, notes }; + if (st.isDirectory()) return { allowed: [realTake], out, notes }; + if (!st.isSymbolicLink()) return { allowed: [realTake], out: null, notes }; + const target = await realpath(/* turbopackIgnore: true */ out).catch(() => null); + // Untiered (the media root IS the reports root), out/'s "mirror" is out/ itself: no link is the media root's. + const mirror = mediaMirror(out, { reportsRoot, mediaRoot }); + const tiered = !!mirror && path.resolve(/* turbopackIgnore: true */ mirror) !== path.resolve(/* turbopackIgnore: true */ out); + const realMirror = tiered ? await realpath(/* turbopackIgnore: true */ /** @type {string} */ (mirror)).catch(() => null) : null; + if (target && realMirror && target === realMirror) return { allowed: [realTake, target], out, notes }; + notes.push(`out/ is a link${target ? ` to ${target}` : " that does not resolve"}, not this take's media-root mirror: not followed`); + return { allowed: [realTake], out: null, notes }; +} + +/** + * The WORK paths of one take (see the top of the file), each checked: a real + * directory or file (never a link), whose real path is inside an allowed root. + * + * @param {string} takeDir + * @param {{ reportsRoot?: string, mediaRoot?: string }} [opts] + * @returns {Promise<{ roots: { abs: string, rel: string, kind: "dir" | "file", what: string }[], allowed: string[], notes: string[] }>} + */ +export async function workPathsOf(takeDir, { reportsRoot = REPORTS_ROOT, mediaRoot = MEDIA_ROOT } = {}) { + const { allowed, out, notes } = await allowedRootsOf(takeDir, { reportsRoot, mediaRoot }); + const roots = []; + if (!out) return { roots, allowed, notes }; + const add = async (abs, kind, what) => { + const st = await lstat(/* turbopackIgnore: true */ abs).catch(() => null); + if (!st || st.isSymbolicLink()) return; + if (kind === "dir" ? !st.isDirectory() : !st.isFile()) return; + const real = await realpath(/* turbopackIgnore: true */ abs).catch(() => null); + if (!real || !allowed.some((a) => real !== a && inside(a, real))) { + notes.push(`${path.relative(takeDir, abs)} resolves outside the take: not touched`); + return; + } + roots.push({ abs, rel: path.relative(takeDir, abs), kind, what }); + }; + const names = async (dir) => readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []); + await add(path.join(/* turbopackIgnore: true */ out, KEEP_FRAMES_DIR), "dir", "chrome frames kept aside for --from"); + await add(path.join(/* turbopackIgnore: true */ out, "clips-raw"), "dir", "raw clip copies"); + for (const v of await names(out)) { + if (!v.isDirectory() || v.name.startsWith(".") || NOT_VARIANTS.has(v.name)) continue; + const vdir = path.join(/* turbopackIgnore: true */ out, v.name); + const inV = await names(vdir); + for (const w of IN_VARIANT) if (inV.some((e) => e.name === w.name)) await add(path.join(/* turbopackIgnore: true */ vdir, w.name), w.kind, w.what); + for (const e of inV) if (e.isFile() && PRERAIL.test(e.name)) await add(path.join(/* turbopackIgnore: true */ vdir, e.name), "file", "the rail's cached base"); + for (const c of await names(path.join(/* turbopackIgnore: true */ vdir, "chrome"))) { + if (!c.isDirectory()) continue; + if (c.name.endsWith("-frames")) await add(path.join(/* turbopackIgnore: true */ vdir, "chrome", c.name), "dir", `chrome frames (${c.name.replace(/-frames$/, "")})`); + else if (c.name.startsWith("work-")) await add(path.join(/* turbopackIgnore: true */ vdir, "chrome", c.name), "dir", "a chrome render's work"); + } + } + roots.sort((a, b) => a.rel.localeCompare(b.rel)); + return { roots, allowed, notes }; +} + +const blocksOf = (st) => (typeof st.blocks === "number" ? st.blocks * 512 : st.size); + +/** + * Measure WORK paths: every entry lstat'ed, nothing followed. Inodes with one + * link are summed at once; those with more are returned by `dev:ino` with + * their link count and how many of their paths are in these roots. + * + * @param {{ abs: string, kind: "dir" | "file" }[]} roots + * @returns {Promise<{ single: number, files: number, multi: Map<string, { nlink: number, bytes: number, n: number }>, perRoot: { bytes: number, files: number }[] }>} + */ +export async function measurePaths(roots) { + let single = 0; + let files = 0; + const multi = new Map(); + const perRoot = []; + const seen = new Set(); + for (const root of roots) { + let rb = 0; + let rf = 0; + const take = (st) => { + if (st.isDirectory()) { + single += blocksOf(st); + rb += blocksOf(st); + return; + } + files += 1; + rf += 1; + const b = blocksOf(st); + if (st.nlink <= 1) { + single += b; + rb += b; + return; + } + const key = `${st.dev}:${st.ino}`; + const m = multi.get(key); + if (m) m.n += 1; + else multi.set(key, { nlink: st.nlink, bytes: b, n: 1 }); + if (!seen.has(key)) { + seen.add(key); + rb += b; + } + }; + const top = await lstat(/* turbopackIgnore: true */ root.abs).catch(() => null); + if (!top || top.isSymbolicLink()) { + perRoot.push({ bytes: 0, files: 0 }); + continue; + } + take(top); + const stack = top.isDirectory() ? [root.abs] : []; + while (stack.length) { + const dir = /** @type {string} */ (stack.pop()); + const entries = await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []); + for (let i = 0; i < entries.length; i += 256) { + const batch = entries.slice(i, i + 256); + const sts = await Promise.all(batch.map((e) => lstat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, e.name)).catch(() => null))); + batch.forEach((e, k) => { + const st = sts[k]; + if (!st) return; + take(st); + if (st.isDirectory() && !st.isSymbolicLink()) stack.push(path.join(/* turbopackIgnore: true */ dir, e.name)); + }); + } + } + perRoot.push({ bytes: rb, files: rf }); + } + return { single, files, multi, perRoot }; +} + +/** Work bytes (unique inodes) and what removing these paths alone frees. */ +function sizesOf(m) { + let work = m.single; + let freed = m.single; + for (const v of m.multi.values()) { + work += v.bytes; + if (v.n >= v.nlink) freed += v.bytes; + } + return { workBytes: work, freedBytes: freed }; +} + +/** What removing every set in `measures` together frees: inodes counted over the union. */ +export function unionFreed(measures) { + let freed = 0; + const multi = new Map(); + for (const m of measures) { + freed += m.single; + for (const [k, v] of m.multi) { + const u = multi.get(k); + if (u) u.n += v.n; + else multi.set(k, { ...v }); + } + } + for (const v of multi.values()) if (v.n >= v.nlink) freed += v.bytes; + return freed; +} + +/** The bytes the sets in `measures` hold between them: each inode once (a `du` of them all). */ +export function unionWork(measures) { + let work = 0; + const seen = new Set(); + for (const m of measures) { + work += m.single; + for (const [k, v] of m.multi) { + if (seen.has(k)) continue; + seen.add(k); + work += v.bytes; + } + } + return work; +} + +// --------------------------------------------------------------------------- +// The plan +// --------------------------------------------------------------------------- + +const readJson = (file) => readFile(/* turbopackIgnore: true */ file, "utf8").then((t) => JSON.parse(t), () => null); +const mtimeOf = (file) => lstat(/* turbopackIgnore: true */ file).then((s) => s.mtimeMs, () => 0); + +/** The takes a take was started from: take.json's `from`, and xfade-batches/.from.json's. */ +async function basesOf(takeDir, raw) { + const out = new Set(); + if (isTakeId(raw?.from)) out.add(raw.from); + const outDir = path.join(/* turbopackIgnore: true */ takeDir, "out"); + for (const v of await readdir(/* turbopackIgnore: true */ outDir, { withFileTypes: true }).catch(() => [])) { + if (!v.isDirectory()) continue; + const j = await readJson(path.join(/* turbopackIgnore: true */ outDir, v.name, "xfade-batches", XFADE_FROM_FILE)); + if (isTakeId(j?.take)) out.add(j.take); + } + return [...out]; +} + +/** + * Every directory under `takes/`, read: take.json (parsed, or why not), its + * group and times, its bases, its build locks. + */ +async function readTakeDirs(projectDir, { host, alive }) { + const root = takesDirOf(projectDir); + const entries = await readdir(/* turbopackIgnore: true */ root, { withFileTypes: true }).catch(() => []); + const out = []; + for (const e of entries) { + if (e.name.startsWith(".")) continue; + if (!e.isDirectory() && !e.isSymbolicLink()) continue; + const dir = path.join(/* turbopackIgnore: true */ root, e.name); + if (e.isSymbolicLink()) { + const isDir = await stat(/* turbopackIgnore: true */ dir).then((s) => s.isDirectory(), () => false); + if (isDir) out.push({ id: e.name, dir, link: true, take: null, raw: null, why: "the take's directory is a link", modifiedMs: 0, builtMs: 0, bases: [], locks: [] }); + continue; + } + const raw = await readJson(path.join(/* turbopackIgnore: true */ dir, "take.json")); + const parsed = raw ? parseTake(e.name, raw) : null; + const take = parsed && "take" in parsed ? parsed.take : null; + const builtMs = take?.builtAt ? Date.parse(take.builtAt) || 0 : 0; + const modifiedMs = Math.max( + builtMs, + await mtimeOf(path.join(/* turbopackIgnore: true */ dir, "take.json")), + await mtimeOf(path.join(/* turbopackIgnore: true */ dir, take?.preview ?? "preview.mp4")), + // A take with no take.json yet (a build that never finished): its out/. + take ? 0 : await mtimeOf(path.join(/* turbopackIgnore: true */ dir, "out")), + ); + const locks = []; + for (const f of [path.join(/* turbopackIgnore: true */ dir, BUILD_LOCK), path.join(/* turbopackIgnore: true */ dir, "out", BUILD_LOCK)]) { + const lock = await readBuildLock(f); + if (lock) locks.push({ file: path.relative(projectDir, f), lock, live: lockIsLive(lock, { host, alive }) }); + } + out.push({ + id: e.name, + dir, + link: false, + take, + raw, + why: raw ? (take ? null : /** @type {any} */ (parsed).error) : "no take.json", + modifiedMs, + builtMs, + bases: await basesOf(dir, raw), + locks, + }); + } + return out.sort((a, b) => a.id.localeCompare(b.id)); +} + +/** + * @typedef {{ code: string, why: string, hard: boolean }} KeepReason + * @typedef {{ + * id: string, group: string | null, label: string | null, listed: boolean, + * builtAt: string | null, modifiedAt: string | null, bases: string[], + * status: "prunable" | "kept" | "no-work", + * keep: KeepReason[], overridden: KeepReason[], + * roots: { rel: string, kind: "dir" | "file", what: string, bytes: number | null, files: number | null }[], + * workBytes: number | null, freedBytes: number | null, files: number | null, + * notes: string[], pruned: { at: string, freedBytes: number } | null, + * }} TakePlan + */ + +/** + * WHAT PRUNING A PROJECT'S TAKES WOULD DO. Reads only. + * + * @param {{ id: string, dir: string }} project + * @param {{ + * policy?: ReturnType<typeof resolvePolicy>, flags?: { keep?: unknown, olderThan?: unknown }, env?: NodeJS.ProcessEnv, + * takes?: string[] | null, anyway?: boolean, protect?: string[], measure?: "all" | "prunable" | "none", + * now?: () => Date, reportsRoot?: string, mediaRoot?: string, + * procRoot?: string, processes?: { pid: number, args: string[], cwd: string | null }[], + * host?: string, alive?: (pid: number) => boolean, + * }} [opts] + * `takes`: only these (the CLI's --take, the UI's per-take button); `anyway`: + * their policy reasons are overridden; `protect`: kept as just built. + */ +export async function planPrune(project, opts = {}) { + const now = (opts.now ?? (() => new Date()))().getTime(); + const policy = opts.policy ?? resolvePolicy({ file: await readPolicyFile(project.dir), env: opts.env ?? process.env, flags: opts.flags ?? {} }); + const host = opts.host ?? os.hostname(); + const alive = opts.alive ?? pidAlive; + const roots = { reportsRoot: opts.reportsRoot ?? REPORTS_ROOT, mediaRoot: opts.mediaRoot ?? MEDIA_ROOT }; + const dirs = await readTakeDirs(project.dir, { host, alive }); + const notes = []; + for (const id of opts.takes ?? []) if (!dirs.some((d) => d.id === id)) throw new Error(`${project.id} has no take ${id}`); + + const [verdicts, projectManifest] = await Promise.all([ + readVerdicts(project.dir), + readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null), + ]); + const procs = opts.processes ?? pipelineProcesses({ procRoot: opts.procRoot ?? "/proc" }); + + /** @type {Map<string, KeepReason[]>} */ + const reasons = new Map(dirs.map((d) => [d.id, []])); + const why = (id, code, text) => { + const list = reasons.get(id); + if (list && !list.some((r) => r.code === code)) list.push({ code, why: text, hard: HARD_REASONS.has(code) }); + }; + + // Running builds, and the takes they build from. + for (const d of dirs) { + if (d.link) { + why(d.id, "link", "its directory is a link: its files are not this project's to prune"); + continue; + } + for (const l of d.locks) { + if (l.live) { + why(d.id, "building", `a build is running (${l.file}, pid ${l.lock.pid}${l.lock.host && l.lock.host !== host ? ` on ${l.lock.host}` : ""})`); + if (isTakeId(l.lock.from)) why(l.lock.from, "base-of-building", `take ${d.id} is being built from it`); + } else notes.push(`${l.file}: a build lock whose process (pid ${l.lock.pid}) is gone — ignored`); + } + const ref = { dir: d.dir, realDir: await realpath(/* turbopackIgnore: true */ d.dir).catch(() => d.dir) }; + const pids = procs.filter((p) => namesProject(p.args, p.cwd, ref)).map((p) => p.pid); + if (pids.length) why(d.id, "building", `a build process is working in it (pid ${pids.join(", ")})`); + } + for (const id of opts.protect ?? []) why(id, "just-built", "just built"); + + // The picked take, and the take whose manifest the project's is. + for (const d of dirs) { + if (d.link) continue; + if (verdicts[d.id]?.picked) why(d.id, "picked", `picked in group "${d.take?.group ?? "?"}"`); + if (projectManifest !== null) { + const mine = await readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ d.dir, "video.manifest.json"), "utf8").catch(() => null); + if (mine !== null && mine === projectManifest) why(d.id, "current", "the project's manifest is this take's"); + } + if (policy.pin.includes(d.id)) why(d.id, "pinned", `pinned in ${TAKES_DIR}/${POLICY_FILE}`); + } + for (const id of policy.pin) if (!dirs.some((d) => d.id === id)) notes.push(`${TAKES_DIR}/${POLICY_FILE} pins ${id}, which is not a take`); + + // The newest K of each group. + const groups = new Map(); + for (const d of dirs) { + if (!d.take) continue; + if (!groups.has(d.take.group)) groups.set(d.take.group, []); + groups.get(d.take.group).push(d); + } + for (const [group, list] of groups) { + list.sort((a, b) => (b.builtMs || b.modifiedMs) - (a.builtMs || a.modifiedMs) || a.id.localeCompare(b.id)); + list.slice(0, policy.keep).forEach((d, i) => why(d.id, "newest", `the ${i === 0 ? "newest" : `${ordinal(i + 1)} newest`} of group "${group}" (keeps ${policy.keep})`)); + } + + // Modified within D days. + const horizon = now - policy.olderThanDays * 24 * 3600 * 1000; + for (const d of dirs) { + if (d.link || !d.modifiedMs || d.modifiedMs < horizon) continue; + const ago = (now - d.modifiedMs) / 3600000; + why(d.id, "recent", `modified ${ago < 48 ? `${Math.max(0, Math.round(ago))} h` : `${(ago / 24).toFixed(1)} d`} ago (keeps ${policyAge(policy.olderThanDays)})`); + } + + // The --from bases of a kept take, transitively. + const byId = new Map(dirs.map((d) => [d.id, d])); + for (let changed = true; changed; ) { + changed = false; + for (const d of dirs) { + if (!(reasons.get(d.id) ?? []).length) continue; + for (const b of d.bases) { + if (!byId.has(b) || (reasons.get(b) ?? []).some((r) => r.code === "base")) continue; + why(b, "base", `the --from base of ${d.id}, which is kept`); + changed = true; + } + } + } + + const named = opts.takes ? new Set(opts.takes) : null; + const measure = opts.measure ?? "all"; + /** @type {TakePlan[]} */ + const takes = []; + /** @type {Map<string, Awaited<ReturnType<typeof measurePaths>>>} */ + const measured = new Map(); + for (const d of dirs) { + if (named && !named.has(d.id)) continue; + let keep = reasons.get(d.id) ?? []; + let overridden = []; + if (named && opts.anyway) { + overridden = keep.filter((r) => !r.hard); + keep = keep.filter((r) => r.hard); + } + const work = d.link ? { roots: [], notes: [] } : await workPathsOf(d.dir, roots); + const status = work.roots.length === 0 ? "no-work" : keep.length ? "kept" : "prunable"; + let m = null; + if (work.roots.length && (measure === "all" || (measure === "prunable" && status === "prunable"))) { + m = await measurePaths(work.roots); + measured.set(d.id, m); + } + const sizes = m ? sizesOf(m) : null; + const record = await readJson(path.join(/* turbopackIgnore: true */ d.dir, PRUNE_RECORD)); + const last = Array.isArray(record?.prunes) ? record.prunes[record.prunes.length - 1] : null; + takes.push({ + id: d.id, + group: d.take?.group ?? null, + label: d.take?.label ?? null, + listed: !!d.take, + builtAt: d.take?.builtAt ?? null, + modifiedAt: d.modifiedMs ? new Date(d.modifiedMs).toISOString() : null, + bases: d.bases, + status, + keep, + overridden, + roots: work.roots.map((r, i) => ({ rel: r.rel, kind: r.kind, what: r.what, bytes: m ? m.perRoot[i].bytes : null, files: m ? m.perRoot[i].files : null })), + workBytes: sizes?.workBytes ?? null, + freedBytes: sizes?.freedBytes ?? null, + files: m ? m.files : null, + notes: [ + ...(d.take || d.link ? [] : [d.why === "no take.json" ? "no take.json (a build that never finished?)" : `not listed on the Takes page: ${d.why}`]), + ...work.notes, + ], + pruned: last && typeof last.at === "string" ? { at: last.at, freedBytes: Number(last.freedBytes) || 0 } : null, + }); + } + const prunable = takes.filter((t) => t.status === "prunable"); + const kept = takes.filter((t) => t.status === "kept"); + const sum = (list, k) => list.reduce((s, t) => s + (t[k] ?? 0), 0); + const of = (list) => list.map((t) => measured.get(t.id)).filter((m) => !!m); + const keptMeasured = kept.some((t) => measured.has(t.id)); + return { + project: { id: project.id, dir: project.dir }, + policy, + at: new Date(now).toISOString(), + takes, + // Bytes over several takes count each inode once (`du` of them together). + totals: { + takes: takes.length, + workBytes: measure === "all" ? unionWork([...measured.values()]) : null, + prunable: { takes: prunable.length, workBytes: unionWork(of(prunable)), freedBytes: unionFreed(of(prunable)), files: sum(prunable, "files") }, + kept: { takes: kept.length, workBytes: keptMeasured ? unionWork(of(kept)) : null }, + }, + notes, + /** Not serialised: the measurements, for pruneProject. */ + measured, + }; +} + +const ordinal = (n) => `${n}${n % 10 === 1 && n % 100 !== 11 ? "st" : n % 10 === 2 && n % 100 !== 12 ? "nd" : n % 10 === 3 && n % 100 !== 13 ? "rd" : "th"}`; +const policyAge = (d) => (d >= 1 ? `${+d.toFixed(2)} d` : `${+(d * 24).toFixed(1)} h`); + +/** The plan without its measurements: what --json and the route answer. */ +export function planView(plan) { + const { measured: _m, ...rest } = plan; + return rest; +} + +/** + * The plan as the delete routes answer one (lib/delete-plan.ts), so the Takes + * page's "Free work files" is components/DeletePlan.tsx: what goes (each + * prunable take, its work paths as parts), what is kept and why, and -- for + * a take named alone -- the policy's reasons as refusals "free anyway" + * answers, a running build as one nothing does. + * + * @param {Awaited<ReturnType<typeof planPrune>>} plan + * @param {{ take?: string | null }} [o] + */ +export function deleteViewOf(plan, { take = null } = {}) { + const refusals = []; + if (take) { + const t = plan.takes.find((x) => x.id === take); + if (t?.status === "no-work") refusals.push({ reason: `take ${take} has no work files${t.pruned ? ` (pruned ${t.pruned.at.slice(0, 10)})` : ""}`, forceable: false }); + for (const r of t?.keep ?? []) { + refusals.push(r.hard ? { reason: `kept: ${r.why}`, forceable: false } : { reason: `kept by the policy: ${r.why}`, forceable: true }); + } + } + const prunable = plan.takes.filter((t) => t.status === "prunable"); + if (!take && !prunable.length) refusals.push({ reason: "nothing to free: every take's work files are kept, or there are none", forceable: false }); + const remove = prunable.map((t) => ({ + path: `${TAKES_DIR}/${t.id}/`, + label: `${t.id}/`, + what: `work files${t.overridden.length ? " (freed anyway)" : ""}${t.workBytes !== null && t.freedBytes !== null && t.workBytes > t.freedBytes ? ` — ${fmtBytes(t.workBytes - t.freedBytes)} of it is also linked elsewhere (another take, the project's out/) and stays` : ""}`, + kind: /** @type {const} */ ("dir"), + bytes: t.freedBytes ?? 0, + files: t.files ?? 0, + parts: t.roots.map((r) => ({ name: r.rel, bytes: r.bytes ?? 0 })), + })); + const kept = [ + ...plan.takes + .filter((t) => t.status === "kept" && (!take || t.id === take)) + .map((t) => ({ what: `take ${t.id}${t.workBytes !== null ? ` (${fmtBytes(t.workBytes)} of work)` : ""}`, path: `${TAKES_DIR}/${t.id}/`, why: t.keep.map((r) => r.why).join("; ") })), + { what: "every take's renders, preview.mp4, take.json, manifests, schedule, sync and chapters", why: "final: never pruned" }, + ]; + return { + refusals, + steps: prunable.some((t) => t.roots.some((r) => /chrome\/[^/]+-frames$/.test(r.rel))) ? ["each pruned chrome layer's frame count and key go into its chrome/pruned.json first, so the cut stays verifiable"] : [], + remove, + kept, + bytes: plan.totals.prunable.freedBytes, + files: plan.totals.prunable.files, + }; +} + +// --------------------------------------------------------------------------- +// Removing +// --------------------------------------------------------------------------- + +/** + * Remove one WORK path: refused (a reason returned, nothing removed) when it + * is a link or its real path is not inside `allowed`. Files and links are + * unlinked; only real directories are descended into. + * @returns {Promise<string | null>} why not, or null when removed + */ +export async function removeWorkPath(abs, allowed) { + const st = await lstat(/* turbopackIgnore: true */ abs).catch(() => null); + if (!st) return null; + if (st.isSymbolicLink()) return "a link: not followed, not removed"; + const real = await realpath(/* turbopackIgnore: true */ abs).catch(() => null); + if (!real || !allowed.some((a) => real !== a && inside(a, real))) return "resolves outside the take: not removed"; + if (!st.isDirectory()) { + await unlink(/* turbopackIgnore: true */ abs); + return null; + } + await removeTree(abs); + return null; +} + +async function removeTree(dir) { + const entries = await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }); + for (let i = 0; i < entries.length; i += 256) { + const batch = entries.slice(i, i + 256); + await Promise.all( + batch.map(async (e) => { + const p = path.join(/* turbopackIgnore: true */ dir, e.name); + // withFileTypes is lstat's view: a link to a directory is not a directory. + if (e.isDirectory()) await removeTree(p); + else await unlink(/* turbopackIgnore: true */ p); + }), + ); + } + await rmdir(/* turbopackIgnore: true */ dir); +} + +async function appendPruneRecord(takeDir, entry) { + const file = path.join(/* turbopackIgnore: true */ takeDir, PRUNE_RECORD); + const prev = await readJson(file); + const prunes = Array.isArray(prev?.prunes) ? prev.prunes : []; + const doc = { format: "umtool-pruned-work", version: 1, prunes: [...prunes, entry].slice(-PRUNE_RECORD_KEEP) }; + const tmp = `${file}.${process.pid}.tmp`; + await writeFile(/* turbopackIgnore: true */ tmp, JSON.stringify(doc, null, 2) + "\n", "utf8"); + await rename(tmp, file); +} + +/** + * PRUNE A PROJECT'S TAKES: the plan made (or made again), then each prunable + * take's work removed -- after its build state is read once more, so a build + * that started since the plan keeps its take and the take it builds from. + * Each pruned take's chrome frames are recorded first (chrome/pruned.json, + * so verify-build can still check its cut), and what went is appended to + * `takes/<id>/pruned-work.json`. + * + * @param {{ id: string, dir: string }} project + * @param {Parameters<typeof planPrune>[1] & { by?: string, log?: (line: string) => void }} [opts] + */ +export async function pruneProject(project, opts = {}) { + const plan = await planPrune(project, { ...opts, measure: "prunable" }); + const roots = { reportsRoot: opts.reportsRoot ?? REPORTS_ROOT, mediaRoot: opts.mediaRoot ?? MEDIA_ROOT }; + const { recordPrunedSequences } = await import("umtool-report-to-video/prune-frames"); + const removed = []; + const failed = []; + const pruned = []; + let freedBytes = 0; + const host = opts.host ?? os.hostname(); + const alive = opts.alive ?? pidAlive; + for (const t of plan.takes) { + if (t.status !== "prunable") continue; + const takeDir = path.join(/* turbopackIgnore: true */ takesDirOf(project.dir), t.id); + // Once more, now: a build started since the plan, here or from here. + const fresh = await readTakeDirs(project.dir, { host, alive }); + const realTake = await realpath(/* turbopackIgnore: true */ takeDir).catch(() => takeDir); + const busy = + fresh.find((d) => d.id === t.id)?.locks.some((l) => l.live) || + fresh.some((d) => d.locks.some((l) => l.live && l.lock.from === t.id)) || + (opts.processes ?? pipelineProcesses({ procRoot: opts.procRoot ?? "/proc" })).some((p) => + namesProject(p.args, p.cwd, { dir: takeDir, realDir: realTake }), + ); + if (busy) { + failed.push({ path: `${TAKES_DIR}/${t.id}/`, error: "a build started in it (or from it) since the plan: kept" }); + continue; + } + const work = await workPathsOf(takeDir, roots); + // Frames first in the record, so a verified cut stays verifiable. + const byChrome = new Map(); + for (const r of work.roots) { + if (r.kind !== "dir" || !/\/chrome\/[^/]+-frames$/.test(r.abs)) continue; + const c = path.dirname(r.abs); + byChrome.set(c, [...(byChrome.get(c) ?? []), path.basename(r.abs)]); + } + for (const [chromeDir, names] of byChrome) await recordPrunedSequences(chromeDir, names).catch(() => {}); + const gone = []; + for (const r of work.roots) { + try { + const no = await removeWorkPath(r.abs, work.allowed); + if (no) failed.push({ path: `${TAKES_DIR}/${t.id}/${r.rel}`, error: no }); + else gone.push(r.rel); + } catch (err) { + failed.push({ path: `${TAKES_DIR}/${t.id}/${r.rel}`, error: err instanceof Error ? err.message : String(err) }); + } + } + const takeFreed = t.freedBytes ?? 0; + if (gone.length) { + removed.push(...gone.map((g) => `${TAKES_DIR}/${t.id}/${g}`)); + await appendPruneRecord(takeDir, { at: new Date().toISOString(), by: opts.by ?? "cli", workBytes: t.workBytes ?? 0, freedBytes: takeFreed, paths: gone }).catch(() => {}); + pruned.push({ id: t.id, freedBytes: takeFreed, paths: gone }); + } + } + // The union: two prunable takes sharing inodes free them together. + freedBytes = unionFreed(pruned.map((p) => plan.measured.get(p.id)).filter(Boolean)); + return { plan, pruned, removed, failed, freedBytes }; +} + +/** One line for a log: what a prune freed and what it kept. */ +export function pruneSummary(r, projectId) { + const kept = r.plan.takes.filter((t) => t.status === "kept").length; + const head = r.pruned.length + ? `freed ${fmtBytes(r.freedBytes)} of work files from ${r.pruned.length} take(s): ${r.pruned.map((p) => p.id).join(", ")}` + : "nothing to free"; + const tail = kept ? `; ${kept} take(s) keep theirs (\`umtool prune ${projectId}\` says why)` : ""; + const fails = r.failed.length ? `; ${r.failed.length} path(s) not removed: ${r.failed.map((f) => `${f.path} (${f.error})`).join("; ")}` : ""; + return `prune: ${head}${tail}${fails}`; +} + +// --------------------------------------------------------------------------- +// After a take's build, and before a render +// --------------------------------------------------------------------------- + +/** A project's id from its directory: its path under the reports root, else its name. */ +export function projectIdOfDir(dir, reportsRoot = REPORTS_ROOT) { + const rel = path.relative(reportsRoot, dir); + return rel && !rel.startsWith("..") && !path.isAbsolute(rel) ? rel.split(path.sep).join("/") : path.basename(dir); +} + +/** + * The take maker's hook (takeMaker.mjs makeTake): after a take is built, the + * policy over its project, the take just built kept. Off with + * UMTOOL_PRUNE_AFTER_BUILD=0 or `"afterBuild": false` in takes/prune.json. + * Never throws: a prune that fails says so and the build stands. + * + * @returns {Promise<string | null>} the line it logged, or null when off + */ +export async function pruneAfterBuild(projectDir, { built, log = () => {}, env = process.env, ...rest } = {}) { + try { + if (env.UMTOOL_PRUNE_AFTER_BUILD === "0") return null; + const file = await readPolicyFile(projectDir); + const policy = resolvePolicy({ file, env }); + if (!policy.afterBuild) return null; + const project = { id: projectIdOfDir(projectDir, rest.reportsRoot), dir: projectDir }; + const r = await pruneProject(project, { ...rest, policy, protect: built ? [built] : [], by: "after-build" }); + const line = pruneSummary(r, project.id); + log(line); + return line; + } catch (err) { + const line = `prune: not run — ${err instanceof Error ? err.message : err}`; + log(line); + return line; + } +} + +/** + * Every project under `reportsRoot` that has a takes/ directory, pruned by its + * own policy. Returns the total and each project's result. + */ +export async function pruneAllProjects({ reportsRoot = REPORTS_ROOT, dryRun = false, by = "cli", ...rest } = {}) { + const { walkProjects } = await import("../projects/walk.mjs"); + const refs = await walkProjects(reportsRoot); + const results = []; + for (const p of refs) { + const has = await stat(/* turbopackIgnore: true */ takesDirOf(p.dir)).then((s) => s.isDirectory(), () => false); + if (!has) continue; + const project = { id: p.id, dir: p.dir }; + try { + if (dryRun) results.push({ project, plan: await planPrune(project, { reportsRoot, ...rest }) }); + else results.push({ project, ...(await pruneProject(project, { reportsRoot, by, ...rest })) }); + } catch (err) { + results.push({ project, error: err instanceof Error ? err.message : String(err) }); + } + } + const freedBytes = results.reduce((s, r) => s + (dryRun ? r.plan?.totals.prunable.freedBytes ?? 0 : r.freedBytes ?? 0), 0); + return { results, freedBytes }; +} + +/** Free bytes for an unprivileged writer on the filesystem holding `dir` (null when unreadable). */ +export async function freeBytesAt(dir) { + const s = await statfs(/* turbopackIgnore: true */ dir).catch(() => null); + return s ? Number(s.bavail) * Number(s.bsize) : null; +} + +/** The disk guard's settings, from the environment. */ +export function guardSettings(env = process.env) { + const gb = (name, dflt) => { + const v = env[name]; + if (v === undefined || v === "") return dflt; + const n = Number(v); + if (!Number.isFinite(n) || n < 0) throw new Error(`${name}=${v} is not a number of GB`); + return n; + }; + return { + enabled: env.UMTOOL_DISK_GUARD !== "0", + thresholdBytes: gb("UMTOOL_DISK_GUARD_GB", DISK_GUARD_DEFAULTS.thresholdGB) * GiB, + floorBytes: gb("UMTOOL_DISK_FLOOR_GB", DISK_GUARD_DEFAULTS.floorGB) * GiB, + }; +} + +export class DiskGuardRefused extends Error {} + +/** + * THE DISK GUARD, before a render starts: under the threshold, the prune + * policy across every project (what it freed said); still under the floor, + * refused with a sentence (DiskGuardRefused). `dirs` are where the render + * writes and the projects root; the least free of them decides. + * + * @param {{ dirs: string[], env?: NodeJS.ProcessEnv, say?: (line: string) => void, + * free?: (dir: string) => Promise<number | null>, pruneAll?: () => Promise<{ freedBytes: number, results: any[] }> }} o + * @returns {Promise<{ checked: boolean, freeBefore: number | null, freeAfter: number | null, freedBytes: number }>} + */ +export async function diskGuard({ dirs, env = process.env, say = () => {}, free = freeBytesAt, pruneAll = () => pruneAllProjects({ by: "disk-guard" }) }) { + const s = guardSettings(env); + if (!s.enabled) return { checked: false, freeBefore: null, freeAfter: null, freedBytes: 0 }; + const least = async () => { + let min = null; + let at = null; + for (const d of [...new Set(dirs.filter(Boolean))]) { + const f = await free(d); + if (f !== null && (min === null || f < min)) [min, at] = [f, d]; + } + return { min, at }; + }; + const before = await least(); + if (before.min === null || before.min >= s.thresholdBytes) return { checked: true, freeBefore: before.min, freeAfter: before.min, freedBytes: 0 }; + say(`disk guard: ${fmtBytes(before.min)} free under ${before.at} (under ${fmtBytes(s.thresholdBytes)}): freeing takes' work files by each project's prune policy`); + let freedBytes = 0; + try { + const r = await pruneAll(); + freedBytes = r.freedBytes; + const n = r.results.reduce((k, x) => k + (x.pruned?.length ?? 0), 0); + say(`disk guard: freed ${fmtBytes(freedBytes)} from ${n} take(s) in ${r.results.filter((x) => x.pruned?.length).length} project(s)`); + } catch (err) { + say(`disk guard: the prune failed — ${err instanceof Error ? err.message : err}`); + } + const after = await least(); + if (after.min !== null && after.min < s.floorBytes) { + throw new DiskGuardRefused( + `disk guard: only ${fmtBytes(after.min)} free under ${after.at}, under the ${fmtBytes(s.floorBytes)} a render needs — nothing was rendered. ` + + "`umtool prune --all` says what is kept and why; free space, or set UMTOOL_DISK_FLOOR_GB (UMTOOL_DISK_GUARD=0 turns the guard off).", + ); + } + if (after.min !== null) say(`disk guard: ${fmtBytes(after.min)} free now`); + return { checked: true, freeBefore: before.min, freeAfter: after.min, freedBytes }; +} + +/** For build-video's CLI: the guard over its --out (or its manifest's directory) and the projects root. */ +export async function guardBeforeRender({ out, manifestPath, env = process.env, say }) { + const where = out ? path.resolve(/* turbopackIgnore: true */ out) : path.dirname(/* turbopackIgnore: true */ path.resolve(/* turbopackIgnore: true */ manifestPath)); + // The out dir may not exist yet: its nearest existing parent's filesystem. + let dir = where; + while (!(await stat(/* turbopackIgnore: true */ dir).then(() => true, () => false))) { + const up = path.dirname(/* turbopackIgnore: true */ dir); + if (up === dir) break; + dir = up; + } + return diskGuard({ dirs: [dir, REPORTS_ROOT], env, say }); +} diff --git a/umtool/lib/report/takePrune.test.mjs b/umtool/lib/report/takePrune.test.mjs @@ -0,0 +1,395 @@ +// The takes' work-file pruner (takePrune.mjs): what is work and what is final, +// hard links counted by inode, the retention rules, the build lock, the disk +// guard, the symlink-escape guard, the CLI and the take maker's prune after a +// take is made. Every project is a temp directory. +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import { link, lstat, mkdir, mkdtemp, readFile, readdir, stat, symlink, utimes, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { + BUILD_LOCK, + DiskGuardRefused, + KEEP_FRAMES_DIR, + PRUNE_RECORD, + XFADE_FROM_FILE, + deleteViewOf, + diskGuard, + measurePaths, + parseAge, + planPrune, + pruneProject, + readBuildLock, + removeWorkPath, + resolvePolicy, + unionFreed, + workPathsOf, + writeBuildLock, +} from "./takePrune.mjs"; +import { framesOf, frameKeyOf } from "umtool-report-to-video/prune-frames"; + +const DAY = 24 * 3600 * 1000; +const KiB = 1024; +// A clock ten days on: nothing on disk is "recent" to it. +const later = () => new Date(Date.now() + 10 * DAY); +// No pipeline processes, and only this process's pid alive. +const quiet = { processes: [], alive: (pid) => pid === process.pid }; + +async function root() { + const r = await mkdtemp(path.join(tmpdir(), "takeprune-")); + const reports = path.join(r, "reports"); + const dir = path.join(reports, "proj"); + await mkdir(path.join(dir, "takes"), { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify({ slug: "fx", timeline: [] }) + "\n"); + return { r, reports, dir, project: { id: "proj", dir }, opts: { reportsRoot: reports, mediaRoot: reports, ...quiet } }; +} + +const bytes = (n, ch = "x") => Buffer.alloc(n, ch); + +/** + * A take with final files and work: segments, two chrome layers' frames, a + * crossfade batch, encode chunks, the hash memo -- each `kib` KiB a file. + */ +async function mkTake(dir, id, { group = "takes", builtAt = "2026-10-01T00:00:00Z", from, manifest, kib = 64, frames = 3, work = true } = {}) { + const t = path.join(dir, "takes", id); + const v = path.join(t, "out", "sourced"); + await mkdir(v, { recursive: true }); + await writeFile(path.join(t, "take.json"), JSON.stringify({ id, group, order: 1, label: id, kind: "different", preview: "preview.mp4", builtAt, ...(from ? { from } : {}) }) + "\n"); + await writeFile(path.join(t, "preview.mp4"), bytes(kib * KiB, "p")); + await link(path.join(t, "preview.mp4"), path.join(t, "out", "fx.mp4")); + await writeFile(path.join(t, "out", "fx.720p.mp4"), bytes(8 * KiB, "r")); + await writeFile(path.join(t, "video.manifest.json"), manifest ?? JSON.stringify({ slug: "fx", take: id }) + "\n"); + for (const f of ["schedule.json", "sync.json", "chapters.ffmeta"]) await writeFile(path.join(v, f), "{}\n"); + await mkdir(path.join(v, "cards"), { recursive: true }); + await writeFile(path.join(v, "cards", "c1.png"), bytes(4 * KiB)); + await mkdir(path.join(v, "chrome", "deck"), { recursive: true }); + await writeFile(path.join(v, "chrome", "deck", "index.html"), "<html></html>"); + if (!work) return t; + await mkdir(path.join(v, "segments"), { recursive: true }); + await writeFile(path.join(v, "segments", "s01.mp4"), bytes(kib * KiB, "1")); + await writeFile(path.join(v, "segments", "s01.cut.json"), "{}"); + for (const layer of ["deck", "feed"]) { + const fd = path.join(v, "chrome", `${layer}-frames`); + await mkdir(fd, { recursive: true }); + await writeFile(path.join(fd, ".key"), `key-${layer}-${id}\n`); + for (let i = 1; i <= frames; i++) await writeFile(path.join(fd, `frame_${String(i).padStart(6, "0")}.png`), bytes(kib * KiB, "f")); + } + await mkdir(path.join(v, "xfade-batches"), { recursive: true }); + await writeFile(path.join(v, "xfade-batches", "batch-abc.mov"), bytes(kib * KiB, "b")); + if (from) await writeFile(path.join(v, "xfade-batches", XFADE_FROM_FILE), JSON.stringify({ take: from }) + "\n"); + await mkdir(path.join(v, "chunks"), { recursive: true }); + await writeFile(path.join(v, "chunks", "chunk-0a.mp4"), bytes(kib * KiB, "c")); + await writeFile(path.join(v, ".content-hashes.json"), "{}"); + return t; +} + +const exists = (p) => lstat(p).then(() => true, () => false); +const byId = (plan, id) => plan.takes.find((t) => t.id === id); +const codes = (plan, id) => byId(plan, id).keep.map((r) => r.code).sort(); + +test("work and final: the work is the named build files under out/; the renders, preview, records and cards are not", async () => { + const { dir, opts } = await root(); + const t = await mkTake(dir, "a"); + // A shared link to the project's clips-raw is not work; a real one is. + await mkdir(path.join(dir, "out", "clips-raw"), { recursive: true }); + await symlink(path.join(dir, "out", "clips-raw"), path.join(t, "out", "clips-raw")); + await writeFile(path.join(t, "out", "sourced", "fx.prerail-hardcut.mp4"), bytes(KiB)); + const { roots } = await workPathsOf(t, opts); + assert.deepEqual(roots.map((r) => r.rel), [ + "out/sourced/.content-hashes.json", + "out/sourced/chrome/deck-frames", + "out/sourced/chrome/feed-frames", + "out/sourced/chunks", + "out/sourced/fx.prerail-hardcut.mp4", + "out/sourced/segments", + "out/sourced/xfade-batches", + ]); + + const r = await pruneProject({ id: "proj", dir }, { ...opts, flags: { keep: 0 }, now: later }); + assert.deepEqual(r.pruned.map((p) => p.id), ["a"]); + for (const f of ["take.json", "preview.mp4", "out/fx.mp4", "out/fx.720p.mp4", "video.manifest.json", "out/sourced/schedule.json", "out/sourced/sync.json", "out/sourced/chapters.ffmeta", "out/sourced/cards/c1.png", "out/sourced/chrome/deck/index.html"]) { + assert.ok(await exists(path.join(t, f)), `${f} is final and stays`); + } + for (const f of ["out/sourced/segments", "out/sourced/chrome/deck-frames", "out/sourced/xfade-batches", "out/sourced/chunks", "out/sourced/.content-hashes.json"]) { + assert.equal(await exists(path.join(t, f)), false, `${f} is work and goes`); + } + assert.ok((await lstat(path.join(t, "out", "clips-raw"))).isSymbolicLink(), "the shared clips-raw link stays"); + // A pruned chrome layer stays verifiable: its count and key were recorded. + const deck = path.join(t, "out", "sourced", "chrome", "deck-frames"); + assert.equal(await framesOf(deck), 3); + assert.equal(await frameKeyOf(deck), "key-deck-a"); + const rec = JSON.parse(await readFile(path.join(t, PRUNE_RECORD), "utf8")); + assert.equal(rec.prunes.length, 1); + assert.equal(rec.prunes[0].by, "cli"); + assert.ok(rec.prunes[0].freedBytes > 0); + // Pruned once, a take has no work: the plan says so, and when. + const again = await planPrune({ id: "proj", dir }, { ...opts, flags: { keep: 0 }, now: later }); + assert.equal(byId(again, "a").status, "no-work"); + assert.ok(byId(again, "a").pruned); +}); + +test("hard links: a take built --from another shares its inodes; pruning one frees only what is its own, and the other keeps its bytes", async () => { + const { dir, project, opts } = await root(); + const a = await mkTake(dir, "a", { builtAt: "2026-10-01T00:00:00Z" }); + const b = await mkTake(dir, "b", { builtAt: "2026-10-02T00:00:00Z" }); + // b's segment and deck frames ARE a's (takeFrom.mjs links them in). + const va = path.join(a, "out", "sourced"); + const vb = path.join(b, "out", "sourced"); + const { rm } = await import("node:fs/promises"); + for (const f of ["s01.mp4", "s01.cut.json"]) { + await rm(path.join(vb, "segments", f)); + await link(path.join(va, "segments", f), path.join(vb, "segments", f)); + } + await rm(path.join(vb, "chrome", "deck-frames"), { recursive: true }); + await mkdir(path.join(vb, "chrome", "deck-frames")); + for (const f of await readdir(path.join(va, "chrome", "deck-frames"))) await link(path.join(va, "chrome", "deck-frames", f), path.join(vb, "chrome", "deck-frames", f)); + + // Measured alone, each take's work counts the shared inodes; its "frees" does not. + const ma = await measurePaths((await workPathsOf(a, opts)).roots); + const mb = await measurePaths((await workPathsOf(b, opts)).roots); + const sharedKeys = [...ma.multi.keys()].filter((k) => mb.multi.has(k)); + assert.ok(sharedKeys.length >= 5, "the segment, its record, three frames and the key are shared"); + const plan = await planPrune(project, { ...opts, policy: resolvePolicy({ env: {}, flags: { keep: 0, olderThan: "0" } }), now: later }); + const pa = byId(plan, "a"); + assert.ok(pa.workBytes > pa.freedBytes, "a's work includes what b also holds"); + const shared = [...ma.multi.values()].reduce((s, v) => s + v.bytes, 0); + assert.equal(pa.workBytes - pa.freedBytes, shared); + // Both prunable: the union frees the shared inodes too -- more than the two alone. + assert.equal(plan.totals.prunable.freedBytes, unionFreed([ma, mb])); + assert.equal(plan.totals.prunable.freedBytes, pa.freedBytes + byId(plan, "b").freedBytes + shared); + assert.equal(plan.totals.prunable.workBytes, plan.totals.prunable.freedBytes, "nothing outside the two holds a link"); + + // Prune a alone (b pinned): b's files are whole, and the freed count is a's own. + await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ keep: 0, olderThanDays: 0, pin: ["b"] })); + const seg = await readFile(path.join(vb, "segments", "s01.mp4")); + const r = await pruneProject(project, { ...opts, now: later }); + assert.deepEqual(r.pruned.map((p) => p.id), ["a"]); + assert.equal(r.freedBytes, pa.freedBytes); + assert.equal(await exists(path.join(va, "segments")), false); + assert.deepEqual(await readFile(path.join(vb, "segments", "s01.mp4")), seg); + assert.equal((await stat(path.join(vb, "segments", "s01.mp4"))).nlink, 1, "b holds the last link now"); + assert.equal((await readdir(path.join(vb, "chrome", "deck-frames"))).length, 4); + // b, measured again, now frees all of its work. + const after = await planPrune(project, { ...opts, now: later }); + const pb = byId(after, "b"); + assert.equal(pb.status, "kept"); + assert.equal(pb.workBytes, pb.freedBytes); +}); + +test("the policy: picked, current, pinned, newest K per group, modified within D days, and the --from bases of kept takes", async () => { + const { dir, project, opts } = await root(); + const manifest = await readFile(path.join(dir, "video.manifest.json"), "utf8"); + await mkTake(dir, "old-1", { builtAt: "2026-09-01T00:00:00Z" }); + await mkTake(dir, "old-2", { builtAt: "2026-09-02T00:00:00Z" }); + await mkTake(dir, "picked", { builtAt: "2026-09-03T00:00:00Z" }); + await mkTake(dir, "current", { builtAt: "2026-09-04T00:00:00Z", manifest }); + await mkTake(dir, "base-of-base", { builtAt: "2026-09-05T00:00:00Z" }); + await mkTake(dir, "base", { builtAt: "2026-09-06T00:00:00Z", from: "base-of-base" }); + await mkTake(dir, "n2", { builtAt: "2026-09-07T00:00:00Z" }); + await mkTake(dir, "n1", { builtAt: "2026-09-08T00:00:00Z", from: "base" }); + await mkTake(dir, "other", { group: "intro", builtAt: "2026-09-01T00:00:00Z" }); + await mkTake(dir, "pinned", { group: "intro", builtAt: "2026-08-01T00:00:00Z" }); + await mkTake(dir, "nothing", { work: false, builtAt: "2026-08-01T00:00:00Z" }); + await writeFile(path.join(dir, "takes", "verdicts.json"), JSON.stringify({ picked: { verdict: null, note: "", at: "", picked: true } })); + await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ pin: ["pinned"] })); + + const plan = await planPrune(project, { ...opts, now: later }); + assert.deepEqual(plan.policy.pin, ["pinned"]); + assert.equal(plan.policy.keep, 2); + assert.deepEqual(codes(plan, "n1"), ["newest"]); + assert.deepEqual(codes(plan, "n2"), ["newest"]); + assert.deepEqual(codes(plan, "base"), ["base"], "n1 is built from it"); + assert.deepEqual(codes(plan, "base-of-base"), ["base"], "transitively"); + assert.deepEqual(codes(plan, "picked"), ["picked"]); + assert.deepEqual(codes(plan, "current"), ["current"]); + assert.deepEqual(codes(plan, "other"), ["newest"], "the newest of its own group"); + assert.deepEqual(codes(plan, "pinned"), ["newest", "pinned"]); + assert.equal(byId(plan, "old-1").status, "prunable"); + assert.equal(byId(plan, "old-2").status, "prunable"); + assert.equal(byId(plan, "nothing").status, "no-work"); + assert.equal(byId(plan, "pinned").keep.find((r) => r.code === "newest").why, 'the 2nd newest of group "intro" (keeps 2)'); + + // Today's clock: everything was modified just now. + const today = await planPrune(project, opts); + assert.ok(codes(today, "old-1").includes("recent")); + assert.equal(today.totals.prunable.takes, 0); + // --keep and --older-than on the command line beat the file and the defaults. + const keep0 = await planPrune(project, { ...opts, flags: { keep: 0, olderThan: "12h" }, now: later }); + assert.equal(byId(keep0, "n1").status, "prunable"); + assert.equal(byId(keep0, "base").status, "prunable", "its child is not kept now, so neither is it"); + assert.equal(byId(keep0, "pinned").status, "kept"); + assert.equal(keep0.policy.from.keep, "--keep"); + // A named take with --anyway: the policy's reasons are overridden. + const named = await planPrune(project, { ...opts, takes: ["picked"], anyway: true, now: later }); + assert.deepEqual(named.takes.map((t) => t.id), ["picked"]); + assert.equal(byId(named, "picked").status, "prunable"); + assert.deepEqual(byId(named, "picked").overridden.map((r) => r.code), ["picked"]); + // The route's view: without force, a forceable refusal; with it, the take goes. + const view = deleteViewOf(await planPrune(project, { ...opts, takes: ["picked"], now: later }), { take: "picked" }); + assert.deepEqual(view.refusals.map((r) => r.forceable), [true]); + assert.equal(deleteViewOf(named, { take: "picked" }).refusals.length, 0); + await assert.rejects(planPrune(project, { ...opts, takes: ["nope"] }), /has no take nope/); +}); + +test("the settings: parseAge, the environment, and a prune.json that does not parse refuses", async () => { + assert.equal(parseAge("3d"), 3); + assert.equal(parseAge("12h"), 0.5); + assert.equal(parseAge("2"), 2); + assert.throws(() => parseAge("soon"), /not an age/); + const p = resolvePolicy({ env: { UMTOOL_PRUNE_KEEP: "4", UMTOOL_PRUNE_DAYS: "1d", UMTOOL_PRUNE_AFTER_BUILD: "0" }, file: { keep: 3 } }); + assert.equal(p.keep, 3); + assert.equal(p.olderThanDays, 1); + assert.equal(p.afterBuild, false); + assert.deepEqual(p.from, { keep: "prune.json", olderThanDays: "UMTOOL_PRUNE_DAYS", afterBuild: "UMTOOL_PRUNE_AFTER_BUILD" }); + assert.throws(() => resolvePolicy({ env: { UMTOOL_PRUNE_KEEP: "-1" } }), /whole number/); + const { dir, project, opts } = await root(); + await mkTake(dir, "a"); + await writeFile(path.join(dir, "takes", "prune.json"), "{ nope"); + await assert.rejects(planPrune(project, opts), /does not parse/); + await writeFile(path.join(dir, "takes", "prune.json"), JSON.stringify({ pin: "a" })); + await assert.rejects(planPrune(project, opts), /pin is a list/); +}); + +test("a running build: its take and the take it builds from are never pruned, not even by name; a dead lock is ignored", async () => { + const { dir, project, opts } = await root(); + await mkTake(dir, "base", { builtAt: "2026-09-01T00:00:00Z" }); + const twin = await mkTake(dir, "twin", { builtAt: "2026-09-02T00:00:00Z" }); + const other = await mkTake(dir, "other", { builtAt: "2026-09-03T00:00:00Z" }); + await mkTake(dir, "loose", { builtAt: "2026-09-04T00:00:00Z" }); + const flags = { keep: 0, olderThan: "0" }; + await writeBuildLock(twin, { take: "twin", from: "base" }); + // A lock of a process that is gone. + await writeFile(path.join(other, BUILD_LOCK), JSON.stringify({ pid: 999999999, host: (await import("node:os")).hostname(), startedAt: "x" })); + // build-video writing into loose's out/ by hand. + const processes = [{ pid: 4242, args: ["node", "/x/build-video.mjs", "m.json", "--out", path.join(dir, "takes", "loose", "out")], cwd: "/" }]; + + const plan = await planPrune(project, { ...opts, processes, flags, now: later }); + assert.deepEqual(codes(plan, "twin"), ["building"]); + assert.deepEqual(codes(plan, "base"), ["base-of-building"]); + assert.deepEqual(codes(plan, "loose"), ["building"]); + assert.match(byId(plan, "loose").keep[0].why, /pid 4242/); + assert.equal(byId(plan, "other").status, "prunable"); + assert.ok(plan.notes.some((n) => /pid 999999999\) is gone/.test(n))); + const anyway = await planPrune(project, { ...opts, processes, flags, takes: ["twin", "base"], anyway: true, now: later }); + assert.equal(byId(anyway, "twin").status, "kept"); + assert.equal(byId(anyway, "base").status, "kept"); + const view = deleteViewOf(anyway, { take: "twin" }); + assert.deepEqual(view.refusals.map((r) => r.forceable), [false]); + + const r = await pruneProject(project, { ...opts, processes, flags, now: later }); + assert.deepEqual(r.pruned.map((p) => p.id), ["other"]); + assert.ok(await exists(path.join(twin, "out", "sourced", "segments"))); + assert.ok(await exists(path.join(dir, "takes", "base", "out", "sourced", "segments"))); + assert.ok(await exists(path.join(dir, "takes", "loose", "out", "sourced", "segments"))); + // The lock is this process's: removed, and the twin is prunable again. + const { removeBuildLock } = await import("./takePrune.mjs"); + await removeBuildLock(path.join(twin, BUILD_LOCK)); + assert.equal(await readBuildLock(path.join(twin, BUILD_LOCK)), null); +}); + +test("the symlink guard: a link is never work and never followed; a path resolving outside the take is not removed", async () => { + const { r, dir, project, opts } = await root(); + const outside = path.join(r, "corpus"); + await mkdir(outside, { recursive: true }); + await writeFile(path.join(outside, "window.mp4"), bytes(2 * KiB, "w")); + await writeFile(path.join(outside, "frame.png"), bytes(KiB, "o")); + const t = await mkTake(dir, "a"); + const v = path.join(t, "out", "sourced"); + const { rm } = await import("node:fs/promises"); + // segments/ is a link to the corpus: not work. + await rm(path.join(v, "segments"), { recursive: true }); + await symlink(outside, path.join(v, "segments")); + // A real clips-raw holding a link into the corpus: the link goes, the corpus file stays. + await mkdir(path.join(t, "out", "clips-raw")); + await symlink(path.join(outside, "window.mp4"), path.join(t, "out", "clips-raw", "window.mp4")); + // A frame that is a link out of the take. + await symlink(path.join(outside, "frame.png"), path.join(v, "chrome", "deck-frames", "frame_000099.png")); + const { roots } = await workPathsOf(t, opts); + assert.equal(roots.some((x) => x.rel.endsWith("segments")), false); + assert.ok(roots.some((x) => x.rel === "out/clips-raw")); + + const pr = await pruneProject(project, { ...opts, flags: { keep: 0 }, now: later }); + assert.deepEqual(pr.pruned.map((p) => p.id), ["a"]); + assert.ok(await exists(path.join(outside, "window.mp4")), "the corpus file is whole"); + assert.ok(await exists(path.join(outside, "frame.png"))); + assert.ok((await lstat(path.join(v, "segments"))).isSymbolicLink(), "the link itself was not touched"); + assert.equal(await exists(path.join(t, "out", "clips-raw")), false); + assert.equal(await exists(path.join(v, "chrome", "deck-frames")), false); + + // removeWorkPath refuses a link and a path outside the allowed roots. + await symlink(outside, path.join(v, "work-link")); + assert.match(await removeWorkPath(path.join(v, "work-link"), [t]), /a link/); + assert.match(await removeWorkPath(path.join(outside, "window.mp4"), [t]), /outside the take/); + assert.ok(await exists(path.join(outside, "window.mp4"))); + + // A take whose out/ is a link anywhere but the media root's mirror: nothing in it is work. + const b = path.join(dir, "takes", "b"); + await mkdir(b, { recursive: true }); + await writeFile(path.join(b, "take.json"), JSON.stringify({ id: "b", group: "g", order: 1, label: "b", kind: "different", preview: "preview.mp4" })); + const elsewhere = path.join(r, "elsewhere"); + await mkdir(path.join(elsewhere, "sourced", "segments"), { recursive: true }); + await writeFile(path.join(elsewhere, "sourced", "segments", "s.mp4"), "s"); + await symlink(elsewhere, path.join(b, "out")); + const wb = await workPathsOf(b, opts); + assert.equal(wb.roots.length, 0); + assert.match(wb.notes[0], /not this take's media-root mirror/); + // ... while out/ linked to its media-root mirror is followed. + const media = path.join(r, "media"); + const c = path.join(dir, "takes", "c"); + await mkdir(c, { recursive: true }); + const mirror = path.join(media, "proj", "takes", "c", "out"); + await mkdir(path.join(mirror, "sourced", "segments"), { recursive: true }); + await writeFile(path.join(mirror, "sourced", "segments", "s.mp4"), "s"); + await symlink(mirror, path.join(c, "out")); + const wc = await workPathsOf(c, { ...opts, mediaRoot: media }); + assert.deepEqual(wc.roots.map((x) => x.rel), ["out/sourced/segments"]); +}); + +test("the disk guard: above the threshold nothing happens; under it the policy runs; still under the floor the render is refused", async () => { + const GB = 1024 ** 3; + let calls = 0; + const said = []; + const pruneAll = async () => { + calls += 1; + return { freedBytes: 5 * GB, results: [{ pruned: [{ id: "a" }, { id: "b" }] }] }; + }; + // Plenty of room. + let free = 100 * GB; + let r = await diskGuard({ dirs: ["/x"], env: {}, free: async () => free, pruneAll, say: (l) => said.push(l) }); + assert.equal(calls, 0); + assert.equal(r.freedBytes, 0); + // Under 30 GB: pruned, said, and the render goes on above the floor. + const seq = [20 * GB, 25 * GB]; + r = await diskGuard({ dirs: ["/x", "/y"], env: {}, free: async () => seq[Math.min(calls, 1)], pruneAll, say: (l) => said.push(l) }); + assert.equal(calls, 1); + assert.equal(r.freedBytes, 5 * GB); + assert.ok(said.some((l) => /freed 5\.0 GiB from 2 take\(s\) in 1 project/.test(l)), said.join("\n")); + // Under the floor after the prune: refused, with a sentence. + free = 6 * GB; + await assert.rejects( + diskGuard({ dirs: ["/x"], env: {}, free: async () => free, pruneAll, say: () => {} }), + (err) => err instanceof DiskGuardRefused && /only 6\.0 GiB free under \/x, under the 10\.0 GiB a render needs — nothing was rendered/.test(err.message), + ); + // The settings: thresholds from the environment, and off. + calls = 0; + r = await diskGuard({ dirs: ["/x"], env: { UMTOOL_DISK_GUARD_GB: "5", UMTOOL_DISK_FLOOR_GB: "1" }, free: async () => 6 * GB, pruneAll }); + assert.equal(calls, 0); + r = await diskGuard({ dirs: ["/x"], env: { UMTOOL_DISK_GUARD: "0" }, free: async () => 1, pruneAll }); + assert.equal(r.checked, false); + assert.equal(calls, 0); + await assert.rejects(diskGuard({ dirs: ["/x"], env: { UMTOOL_DISK_GUARD_GB: "lots" }, free: async () => 1, pruneAll }), /not a number/); +}); + +test("the names it prunes by are its writers' names", async () => { + const bv = await import("umtool-report-to-video/build-video"); + const ce = await import("umtool-report-to-video/chunked-encode"); + const tf = await import("./takeFrom.mjs"); + assert.equal(XFADE_FROM_FILE, bv.XFADE_FROM_FILE); + assert.equal(KEEP_FRAMES_DIR, tf.KEEP_FRAMES_DIR); + assert.equal(bv.DEFAULT_VARIANT, "sourced"); + assert.equal(ce.CHUNKS_DIR, "chunks"); + assert.equal(ce.HASH_MEMO_FILE, ".content-hashes.json"); +}); diff --git a/umtool/report-to-video/prune-frames.mjs b/umtool/report-to-video/prune-frames.mjs @@ -84,6 +84,37 @@ export async function pruneChromeFrames(variantDir, { now = () => new Date() } = return { sequences, work, bytes }; } +/** + * Record `names` (sequences in `chromeDir` about to be removed by somebody + * else -- `umtool prune`, lib/report/takePrune.mjs) in `chrome/pruned.json`, + * MERGED over what an earlier prune recorded: each sequence's frame count and + * key as of now. A name with no directory is left as it was recorded. + * + * @param {string} chromeDir + * @param {string[]} names `<layer>-frames` directory names + * @returns {Promise<string[]>} the names recorded + */ +export async function recordPrunedSequences(chromeDir, names, { now = () => new Date() } = {}) { + const prev = await readRecord(chromeDir); + const dirs = { ...(prev?.dirs && typeof prev.dirs === "object" ? prev.dirs : {}) }; + const recorded = []; + for (const name of [...names].sort()) { + if (!name.endsWith("-frames")) continue; + const dir = path.join(chromeDir, name); + const files = await readdir(dir).catch(() => null); + if (!files) continue; + const key = await readFile(path.join(dir, ".key"), "utf8").then((s) => s.trim(), () => null); + dirs[name] = { frames: files.filter((f) => FRAME_RE.test(f)).length, key }; + recorded.push(name); + } + if (!recorded.length) return recorded; + const record = { format: "umtool-pruned-frames", version: 1, prunedAt: now().toISOString(), dirs }; + const tmp = path.join(chromeDir, `.${PRUNED_RECORD}.${process.pid}.tmp`); + await writeFile(tmp, `${JSON.stringify(record, null, 2)}\n`, "utf8"); + await rename(tmp, path.join(chromeDir, PRUNED_RECORD)); + return recorded; +} + // The record's entry for a pruned sequence -- unless the cut was written AFTER // the prune (`since`: the final file's mtime in ms), which means a later build // that rendered no chrome (`--no-chrome`) made it, and the record is not about