// 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//` 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/ladder/chunks/ the variant ladder's encoded rung chunks // (ladder-chunks.mjs; ladder.json stays) // out/clips-raw/ a real directory of raw clip copies (the // usual one is a LINK to the project's: not work) // out//segments/*.mp4 each clip's encoded segment -- its records // (.cut.json, .teaser.json, …) stay: a // trailer (`umtool trailer`) maps beats through // them, verify-build reads a teaser's // out//xfade-batches/*.mov the crossfade batches (.from.json stays) // out//chunks/ the final encode's chunks (chunked-encode.mjs) // out//.content-hashes.json that encode's content-hash memo // out//chrome/*-frames/ each chrome layer's PNG sequence // out//chrome/work-*/ a render's leftovers, --from's work-from-* // out//.prerail*.mp4 the rail's cached base (--rail-only), and // its .segments record // // So the renders (out/.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//.building.json`, written by // the take maker; `/.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": [""]`); // - 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. // // AN IDLE PROJECT (`--idle-work `, housekeeping, 2026-11-06). A project // nothing has touched for that long (projectActivity: every take's builtAt, // take.json and preview, the project's manifest and takes/verdicts.json, a live // build lock) is not being worked on, so the newest, picked and current takes' // work goes too -- what the 6 Nov cleanup did by hand with `--take X --anyway` // over every take. Overridden as `--anyway` is: never a running build or the // take one builds from, and never a pin in takes/prune.json (a pin is a person // saying "keep this take's work"). The renders, preview.mp4, take.json and the // manifests stay, as always. // // 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, readVerdictsStrict, takesDirOf } from "./takes.mjs"; import { tmpPathFor } from "yt-dlp-transcript-common/lib/atomicFile.mjs"; /** The project's prune settings: `takes/prune.json`. */ export const POLICY_FILE = "prune.json"; /** A build's lock: `takes//.building.json` (the take maker), `/.building.json` (build-video). */ export const BUILD_LOCK = ".building.json"; /** What was pruned from a take, newest last: `takes//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 export const LADDER_DIR = "ladder"; // ladder-chunks.mjs const NOT_VARIANTS = new Set(["clips-raw", "narration", "bench-excerpts", "posts-media", KEEP_FRAMES_DIR, LADDER_DIR]); // kind "files": the files in that directory whose names match, never the // directory or anything else in it. const IN_VARIANT = [ { name: "segments", kind: "files", match: /^[^.].*\.mp4$/, glob: "*.mp4", what: "clip segments (the encodes; their records stay)" }, { name: "xfade-batches", kind: "files", match: /^batch-.*\.mov$/, glob: "batch-*.mov", 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, 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} 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 = tmpPathFor(file); 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} info * @param {() => Promise} fn * @returns {Promise} */ 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" | "files", what: string, match?: RegExp }[], 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 = []; const names = async (dir) => readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []); if (!out) return { roots, allowed, notes }; const add = async (abs, kind, what, w = null) => { const st = await lstat(/* turbopackIgnore: true */ abs).catch(() => null); if (!st || st.isSymbolicLink()) return; if (kind === "file" ? !st.isFile() : !st.isDirectory()) 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; } if (kind === "files") { // Only when one is there: a directory of records alone holds no work. const files = (await names(abs)).filter((e) => e.isFile() && w.match.test(e.name)); if (!files.length) return; roots.push({ abs, rel: `${path.relative(takeDir, abs)}/${w.glob}`, kind, what, match: w.match }); return; } roots.push({ abs, rel: path.relative(takeDir, abs), kind, what }); }; 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"); await add(path.join(/* turbopackIgnore: true */ out, LADDER_DIR, "chunks"), "dir", "the variant ladder's encoded chunks"); 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, w); 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" | "files", match?: RegExp }[]} roots * @returns {Promise<{ single: number, files: number, multi: Map, 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; } if (root.kind === "files") { // The matching files only: the directory and its records stay. const entries = (await readdir(/* turbopackIgnore: true */ root.abs, { withFileTypes: true }).catch(() => [])).filter((e) => e.isFile() && root.match?.test(e.name)); const sts = await Promise.all(entries.map((e) => lstat(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ root.abs, e.name)).catch(() => null))); for (const st of sts) if (st?.isFile()) take(st); perRoot.push({ bytes: rb, files: rf }); 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" | "files", 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, flags?: { keep?: unknown, olderThan?: unknown }, env?: NodeJS.ProcessEnv, * takes?: string[] | null, anyway?: boolean, protect?: string[], measure?: "all" | "prunable" | "none", * idleWorkDays?: number | string | null, * 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; * `idleWorkDays`: a project idle that long has every policy reason but a pin * overridden (the top of the file, "An idle project"). */ 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 [verdictsRead, projectManifest] = await Promise.all([ readVerdictsStrict(project.dir).then( (v) => ({ v, error: null }), (e) => ({ v: /** @type {Record} */ ({}), error: e instanceof Error ? e.message : String(e) }), ), readFile(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ project.dir, "video.manifest.json"), "utf8").catch(() => null), ]); const verdicts = verdictsRead.v; const procs = opts.processes ?? pipelineProcesses({ procRoot: opts.procRoot ?? "/proc" }); /** @type {Map} */ 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. A // verdicts.json that cannot be read keeps every take: which one is picked is // unknown (fail closed; an idle project's override never passes it). if (verdictsRead.error) notes.push(`${verdictsRead.error}: every take keeps its work until it is fixed`); for (const d of dirs) { if (d.link) continue; if (verdictsRead.error) why(d.id, "verdicts-unreadable", `${TAKES_DIR}/verdicts.json cannot be read: which take is picked is unknown`); 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; } } } // An idle project: its newest, picked and current takes' work goes too. let idle = null; if (opts.idleWorkDays !== undefined && opts.idleWorkDays !== null) { const days = parseAge(opts.idleWorkDays); const act = await projectActivity(project.dir, { now: () => new Date(now), host, alive, dirs }); const isIdle = act.ms > 0 && now - act.ms >= days * DAY_MS; idle = { days, idle: isIdle, lastActivityAt: act.at, lastActivity: act.what }; if (isIdle) notes.push(`idle ${agoWords(now - act.ms)} (since ${act.what}; --idle-work ${policyAge(days)}): every take's work goes but a running build's, its base's and a pin's`); } const named = opts.takes ? new Set(opts.takes) : null; const measure = opts.measure ?? "all"; /** @type {TakePlan[]} */ const takes = []; /** @type {Map>>} */ 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); } else if (idle?.idle) { const stays = (r) => r.hard || r.code === "pinned" || r.code === "verdicts-unreadable"; overridden = keep.filter((r) => !stays(r)); keep = keep.filter(stays); } 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(), ...(idle ? { idle } : {}), 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, }; } /** What projectActivity does not walk: render scratch and fetched media, re-made by machines, not a person. */ const ACTIVITY_SKIP = new Set(["takes", "out", "clips", "clips-raw", "node_modules", ".git", "posts-media", "bench-excerpts", ".cache", "cache"]); const ACTIVITY_DEPTH = 4; const ACTIVITY_MAX_ENTRIES = 50000; /** * WHEN A PROJECT WAS LAST WORKED ON (housekeeping's idle test), the newest of: * - every take's builtAt and its own top-level files (take.json -- a take's * patch, `umtool set --take` --, its video.manifest.json, its preview, its * undo points; not pruned-work.json, the pruner's own record), and a * take with no take.json: its out/; * - a live build lock, as now; * - the project's own files: every top-level file (video.manifest.json, * notes.json, cuts.json, the play state, logs) and the files of every * subdirectory but the render scratch and fetched media (ACTIVITY_SKIP, * share-*): drafts, revisions, takes/verdicts.json and the rest. * Links are not followed. `what` names the newest. Reads only. A walk past * ACTIVITY_MAX_ENTRIES stops there and counts as now (fail closed). * * @param {string} projectDir * @param {{ now?: () => Date, host?: string, alive?: (pid: number) => boolean, dirs?: Awaited> }} [opts] * @returns {Promise<{ ms: number, at: string | null, what: string | null }>} */ export async function projectActivity(projectDir, opts = {}) { const now = (opts.now ?? (() => new Date()))().getTime(); const dirs = opts.dirs ?? (await readTakeDirs(projectDir, { host: opts.host ?? os.hostname(), alive: opts.alive ?? pidAlive })); let best = { ms: 0, what: /** @type {string | null} */ (null) }; const see = (ms, what) => { if (ms > best.ms) best = { ms, what }; }; const filesIn = async (dir) => readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true }).catch(() => []); for (const d of dirs) { if (d.locks.some((l) => l.live)) see(now, `take ${d.id} is being built`); see(d.modifiedMs, `take ${d.id}`); if (d.link) continue; for (const e of await filesIn(d.dir)) { if (!e.isFile() || e.name === PRUNE_RECORD) continue; see(await mtimeOf(path.join(/* turbopackIgnore: true */ d.dir, e.name)), `takes/${d.id}/${e.name}`); } } see(await mtimeOf(path.join(/* turbopackIgnore: true */ takesDirOf(projectDir), "verdicts.json")), "takes/verdicts.json (a pick or a verdict)"); for (const e of await filesIn(takesDirOf(projectDir))) { if (e.isFile()) see(await mtimeOf(path.join(/* turbopackIgnore: true */ takesDirOf(projectDir), e.name)), `takes/${e.name}`); } let seen = 0; const stack = [{ dir: projectDir, rel: "", depth: 0 }]; while (stack.length) { const { dir, rel, depth } = /** @type {{ dir: string, rel: string, depth: number }} */ (stack.pop()); for (const e of await filesIn(dir)) { if (++seen > ACTIVITY_MAX_ENTRIES) { see(now, `the project has over ${ACTIVITY_MAX_ENTRIES} files outside its render scratch: taken as active`); return { ms: best.ms, at: new Date(best.ms).toISOString(), what: best.what }; } const r = rel ? `${rel}/${e.name}` : e.name; if (e.isFile()) see(await mtimeOf(path.join(/* turbopackIgnore: true */ dir, e.name)), r === "video.manifest.json" ? "the project's video.manifest.json" : r); else if (e.isDirectory() && depth < ACTIVITY_DEPTH && !ACTIVITY_SKIP.has(e.name) && !e.name.startsWith("share-")) stack.push({ dir: path.join(/* turbopackIgnore: true */ dir, e.name), rel: r, depth: depth + 1 }); } } return { ms: best.ms, at: best.ms ? new Date(best.ms).toISOString() : null, what: best.what }; } const DAY_MS = 24 * 3600 * 1000; /** An age for a person: `5 h`, `3.2 d`. */ export const agoWords = (ms) => (ms < 48 * 3600000 ? `${Math.max(0, Math.round(ms / 3600000))} h` : `${(ms / DAY_MS).toFixed(1)} d`); 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>} 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} 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; } /** * Remove the files in `dir` whose names match (a "files" work path): files * only, never a link or a directory, never `dir` itself; `dir` must resolve * inside `allowed`. * @returns {Promise} why not, or null when done */ export async function removeWorkFiles(dir, match, allowed) { const st = await lstat(/* turbopackIgnore: true */ dir).catch(() => null); if (!st) return null; if (st.isSymbolicLink()) return "a link: not followed, not removed"; const real = await realpath(/* turbopackIgnore: true */ dir).catch(() => null); if (!real || !allowed.some((a) => real !== a && inside(a, real))) return "resolves outside the take: not removed"; for (const e of await readdir(/* turbopackIgnore: true */ dir, { withFileTypes: true })) { if (e.isFile() && match.test(e.name)) await unlink(/* turbopackIgnore: true */ path.join(/* turbopackIgnore: true */ dir, e.name)); } 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 = tmpPathFor(file); 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//pruned-work.json`. * * @param {{ id: string, dir: string }} project * @param {Parameters[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) { // Kept, as the plan would keep it now: an outcome, not a failure (`raced`). failed.push({ path: `${TAKES_DIR}/${t.id}/`, error: "a build started in it (or from it) since the plan: kept", raced: true }); 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 = r.kind === "files" ? await removeWorkFiles(r.abs, /** @type {RegExp} */ (r.match), work.allowed) : 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} 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 { sharedWalk } = await import("../projects/walk.mjs"); const refs = await sharedWalk(reportsRoot, { since: Date.now() }); 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, 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" }), prunePool = poolDeficitPrune }) { 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}`); } let after = await least(); // Still under: the render pool gives back what only it holds, least recently used first. if (after.min !== null && after.min < s.thresholdBytes) { const r = await prunePool({ dirs, env, deficit: s.thresholdBytes - after.min }).catch(() => null); if (r?.evicted) { say(`disk guard: the render pool evicted ${r.evicted} object(s), ${fmtBytes(r.bytes)}`); freedBytes += r.bytes; 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 }; } /** * The disk guard's last resort before refusing: the render pool (render-pool.mjs) * of the first of `dirs` it serves, pruned by `deficit` bytes of what only it holds. */ async function poolDeficitPrune({ dirs, env, deficit }) { const { poolFor, poolPrune, poolStats } = await import("umtool-report-to-video/render-pool"); for (const d of dirs) { const pool = d ? await poolFor(d, env) : null; if (!pool) continue; const st = await poolStats(pool); return poolPrune(pool, { maxBytes: Math.max(0, st.onlyPool - deficit) }); } return null; } /** 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 }); }