// The render pool (render-pool.mjs): put and fetch by hard link, hits and // misses, the cap's least-recently-used eviction that never takes a linked // object, verify, where the pool is -- and the KEYS: every input that changes // a unit's pixels, sound or timing changes the key the pool files it under // (each field of a fixture mutated in turn). // // Run with: node --test umtool/report-to-video/render-pool.test.mjs import assert from "node:assert/strict"; import { existsSync, linkSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import test from "node:test"; import { POOL_KINDS, objectPath, poolFetch, poolFor, poolFrame, poolId, poolPrune, poolPut, poolPutFrames, poolStats, poolVerify, } from "./render-pool.mjs"; const tmp = (p) => mkdtempSync(path.join(tmpdir(), p)); test("put links a unit in; fetch links it out (the same inode); a miss is a miss; hits and misses counted", async () => { const dir = tmp("pool-"); try { const pool = path.join(dir, "pool"); const a = path.join(dir, "a"); mkdirSync(a); writeFileSync(path.join(a, "seg.mp4"), "picture"); writeFileSync(path.join(a, "rec.json"), "{}"); assert.equal(await poolFetch(pool, "clip", "k1", { "seg.mp4": path.join(a, "x.mp4") }), false); assert.equal(await poolPut(pool, "clip", "k1", { "seg.mp4": path.join(a, "seg.mp4"), "cut.json": path.join(a, "rec.json") }), true); const b = path.join(dir, "b"); mkdirSync(b); writeFileSync(path.join(b, "seg.mp4"), "an older build"); // replaced, through a rename assert.equal(await poolFetch(pool, "clip", "k1", { "seg.mp4": path.join(b, "seg.mp4"), "cut.json": path.join(b, "cut.json") }), true); assert.equal(statSync(path.join(b, "seg.mp4")).ino, statSync(path.join(a, "seg.mp4")).ino, "one inode: the pool costs no disk"); assert.equal(readFileSync(path.join(b, "seg.mp4"), "utf8"), "picture"); // Another kind, the same key: another object. assert.notEqual(poolId("post", "k1"), poolId("clip", "k1")); assert.equal(await poolFetch(pool, "post", "k1", { "seg.mp4": path.join(b, "p.mp4") }), false); const st = await poolStats(pool); assert.equal(st.kinds.clip.hits, 1); assert.equal(st.kinds.clip.misses, 1); assert.equal(st.kinds.post.misses, 1); assert.equal(st.kinds.clip.objects, 1); assert.equal(st.onlyPool, 0, "both takes link it"); assert.deepEqual((await poolVerify(pool, { all: true })).problems, []); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("frames: one file per frame key, linked; a second put of a key keeps the first", async () => { const dir = tmp("pool-f-"); try { const pool = path.join(dir, "pool"); const f1 = path.join(dir, "f1.png"); writeFileSync(f1, Buffer.from("89504e470d0a1a0a00", "hex")); const f2 = path.join(dir, "f2.png"); writeFileSync(f2, Buffer.from("89504e470d0a1a0a01", "hex")); assert.equal(await poolFrame(pool, "fk1"), null); assert.equal(await poolPutFrames(pool, [["fk1", f1], ["fk1", f2]]), 1); const got = await poolFrame(pool, "fk1"); assert.equal(statSync(got).ino, statSync(f1).ino); assert.deepEqual((await poolVerify(pool, { all: true })).problems, []); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("prune: least recently used first, only what no take links, down to the cap; verify finds changed bytes", async () => { const dir = tmp("pool-p-"); try { const pool = path.join(dir, "pool"); const src = path.join(dir, "src"); mkdirSync(src); const put = async (k, bytes) => { const f = path.join(src, `${k}.mp4`); writeFileSync(f, "x".repeat(bytes)); await poolPut(pool, "chunk", k, { "chunk.mp4": f }); return f; }; const fa = await put("a", 1000); const fb = await put("b", 1000); const fc = await put("c", 1000); // Only the pool holds a and b; c is still linked by a "take". rmSync(fa); rmSync(fb); void fc; const old = new Date(Date.now() - 3600_000); utimesSync(objectPath(pool, "chunk", "a"), old, old); // a used longest ago const dry = await poolPrune(pool, { maxBytes: 1500, dryRun: true }); assert.equal(dry.evicted, 1); assert.match(dry.gone[0].path, new RegExp(poolId("chunk", "a"))); const done = await poolPrune(pool, { maxBytes: 0 }); assert.equal(done.evicted, 2, "a and b go; c, linked, never"); assert.ok(existsSync(objectPath(pool, "chunk", "c"))); // A file changed under the pool: verify says so. const c = path.join(objectPath(pool, "chunk", "c"), "chunk.mp4"); rmSync(c); writeFileSync(c, "y"); assert.equal((await poolVerify(pool, { all: true })).problems.length, 1); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("poolFor: the named pool, off with 0, and none for an out/ outside the media root", async () => { assert.equal(await poolFor("/x/out", { UMTOOL_RENDER_POOL: "/p" }), "/p"); assert.equal(await poolFor("/x/out", { UMTOOL_RENDER_POOL: "0" }), null); assert.equal(await poolFor(path.join(tmpdir(), "nowhere"), {}), null, "a test's or a scratch copy's build never writes the operator's pool"); assert.deepEqual(Object.keys(POOL_KINDS).sort(), ["chunk", "clip", "frame", "post", "sound"]); }); // ---- the keys: every field that changes a unit changes its key ---------------- /** Every leaf path of an object: [["a"], ["b", "c"], …]. */ function leaves(o, at = []) { if (o === null || typeof o !== "object") return [at]; const ks = Object.keys(o); if (!ks.length) return [at]; return ks.flatMap((k) => leaves(o[k], [...at, k])); } function mutate(o, at) { const c = structuredClone(o); let p = c; for (const k of at.slice(0, -1)) p = p[k]; const k = at[at.length - 1]; const v = p[k]; p[k] = typeof v === "number" ? v + 1 : typeof v === "boolean" ? !v : v === null ? "x" : `${v}~`; return c; } test("post key: every field of the entry, the box, the render's palette, fonts and fps, the encode, the files' stamps", async () => { const { postSegmentKey, postSegmentKeyOf } = await import("./post-render.mjs"); const base = { entry: { type: "post", id: "p1", post: "a/1", platform: "x", author: "A", handle: "a", date: "2026-10-19T12:00:00Z", text: "words", media: [{ src: "m.png", type: "image", crop: { top: 0.1 } }], narration: { rate: 1.1, takes: [{ file: "t.wav", lufs: -20 }], pick: 0 }, hold: 12, follow: { dim: 0.7 }, thread: { dim: 0.5 }, }, box: { width: 1600, height: 880 }, place: ["pad=1920:1080"], render: { palette: { bg: "#000", fg: "#fff" }, fontRegular: "/f/r.ttf", fontBold: "/f/b.ttf", fps: 30, postNarration: { rate: 1.08, linger: 0.85 } }, encode: ["-crf", "21", "-preset", "slow"], stamps: ["/p/m.png:100:1", "/p/t.wav:200:2"], plan: { narration: { at: 0.25, seconds: 10 }, follow: { blocks: [1] } }, }; const key = (f) => postSegmentKey(postSegmentKeyOf({ ...f, take: { file: "t.wav" } })); const k0 = key(base); const fields = ["entry", "box", "place", "encode", "stamps", "plan"].flatMap((top) => leaves(base[top]).map((p) => [top, ...p])); fields.push(["render", "palette", "bg"], ["render", "fontRegular"], ["render", "fontBold"], ["render", "fps"], ["render", "postNarration", "linger"]); const missed = fields.filter((at) => key(mutate(base, at)) === k0).map((at) => at.join(".")); assert.deepEqual(missed, [], "a post segment's key covers every input that draws or times it"); assert.ok(fields.length > 25, `${fields.length} fields mutated`); }); test("chunk key: the segment, the chrome's frames, the overlay's place, the encode settings, the span's length", async () => { const { chunkVideoArgs } = await import("./build-video.mjs"); const { chunkKey } = await import("./chunked-encode.mjs"); const render = { width: 64, height: 36, fps: 30, transition: 0, preset: "slow", crf: 21, audioRate: 48000, audioChannels: 2 }; const region = { name: "deck", frames: "/c/deck-frames", x: 0, y: 20, width: 64, height: 16 }; const keyOf = ({ r = render, reg = region, segId = "s1", seqId = "d1", durs = [10, 12], span = { a: 300, b: 660 } } = {}) => { const starts = [0, durs[0]]; const proto = chunkVideoArgs({ segments: ["/x/a.mp4", "/x/b.mp4"], durs, starts, span, D: 0, render: r, chrome: { regions: [reg] }, totalFrames: Math.round((durs[0] + durs[1]) * 30), outPath: "" }); const ids = proto.inputs.map((x) => (x.kind === "seg" ? { seg: segId } : { seq: seqId })); return chunkKey({ keyArgv: proto.keyArgv, inputs: ids, ffmpeg: "ff" }); }; const k0 = keyOf(); const changed = { segment: keyOf({ segId: "s2" }), frames: keyOf({ seqId: "d2" }), crf: keyOf({ r: { ...render, crf: 22 } }), preset: keyOf({ r: { ...render, preset: "medium" } }), fps: keyOf({ r: { ...render, fps: 25 } }), x: keyOf({ reg: { ...region, x: 2 } }), y: keyOf({ reg: { ...region, y: 2 } }), length: keyOf({ span: { a: 300, b: 650 }, durs: [10, 11.6667] }), }; for (const [what, k] of Object.entries(changed)) assert.notEqual(k, k0, `${what} changes the chunk's key`); // A segment before it grew: the chunk moved, its key the same (position-free). assert.equal(keyOf({ durs: [11, 12], span: { a: 330, b: 690 } }), k0); }); test("sound key: each segment's length in the cut, its joins, the rate, the channels, the bitrate", async () => { const { hardCutSoundArgs, withCutEdits } = await import("./build-video.mjs"); const render = { fps: 30, audioRate: 48000, audioChannels: 2, audioBitrate: "160k" }; const argv = ({ durs = [10, 12], joins = null, r = render } = {}) => { const a = hardCutSoundArgs({ durs, joins, render: r }); return JSON.stringify([a.pin(0, "", ""), a.pin(1, "", ""), a.encode("", "")]); }; const k0 = argv(); assert.notEqual(argv({ durs: [10, 12.0333] }), k0); assert.notEqual(argv({ joins: withCutEdits(null, 2, { mutes: new Map([[0, 3]]) }) }), k0); assert.notEqual(argv({ r: { ...render, audioRate: 44100 } }), k0); assert.notEqual(argv({ r: { ...render, audioChannels: 1 } }), k0); assert.notEqual(argv({ r: { ...render, audioBitrate: "128k" } }), k0); }); test("clip key: its ffmpeg argv, each input file's contents, its cut record, the ffmpeg binary", async () => { const { segmentKey } = await import("./segment-cache.mjs"); const dir = tmp("pool-k-"); try { const f = path.join(dir, "in.mp4"); writeFileSync(f, "source"); const key = (o = {}) => segmentKey({ argv: ["-i", f, "-crf", "21"], record: { id: "c1", snap: 1.2 }, outDir: dir, ffmpeg: "ffmpeg", ...o }); const k0 = await key(); assert.notEqual(await key({ argv: ["-i", f, "-crf", "22"] }), k0); assert.notEqual(await key({ record: { id: "c1", snap: 1.3 } }), k0); writeFileSync(f, "source2"); assert.notEqual(await key(), k0, "an input's bytes"); // Two takes' out dirs: the same key (the out dir is `` in it). writeFileSync(f, "source"); const other = tmp("pool-k2-"); linkSync(f, path.join(other, "in.mp4")); assert.equal(await segmentKey({ argv: ["-i", f, "-crf", "21"], record: { id: "c1", snap: 1.2 }, outDir: other, ffmpeg: "ffmpeg" }), k0); rmSync(other, { recursive: true, force: true }); } finally { rmSync(dir, { recursive: true, force: true }); } }); test("umtool pool stats|prune|verify --json", async () => { const { poolCommand } = await import("../lib/report/poolCli.mjs"); const dir = tmp("pool-cli-"); try { const pool = path.join(dir, "pool"); const f = path.join(dir, "c.mp4"); writeFileSync(f, "chunk"); await poolPut(pool, "chunk", "k", { "chunk.mp4": f }); const out = []; assert.equal(await poolCommand(["stats", "--pool", pool, "--json"], { log: (l) => out.push(l) }), 0); assert.equal(JSON.parse(out[0]).kinds.chunk.objects, 1); out.length = 0; assert.equal(await poolCommand(["prune", "--pool", pool, "--max-gb", "0", "--dry-run", "--json"], { log: (l) => out.push(l) }), 0); assert.equal(JSON.parse(out[0]).evicted, 0, "a linked object is never evicted"); out.length = 0; assert.equal(await poolCommand(["verify", "--pool", pool, "--all"], { log: (l) => out.push(l) }), 0); assert.match(out[0], /checked 1 of 1 object\(s\): all as put in/); assert.equal(await poolCommand(["bogus", "--pool", pool], { log: () => {} }), 2); } finally { rmSync(dir, { recursive: true, force: true }); } });