// Preparing the walk ahead of time (benchPrep.mjs): the same excerpt the bench // would cut on first open, at the same path; fresh work skipped; the bench's // serve path taking the prepared file; the triggers queueing without holding a // writer. // // Run with: node --test lib/report/benchPrep.test.mjs import assert from "node:assert/strict"; import test from "node:test"; import path from "node:path"; import os from "node:os"; import { execFileSync, spawn } from "node:child_process"; import { existsSync } from "node:fs"; import { mkdir, mkdtemp, readFile, rm, stat, utimes, writeFile } from "node:fs/promises"; const root = await mkdtemp(path.join(os.tmpdir(), "bench-prep-")); // The roots are read when paths.mjs loads. process.env.MIX_ROOTS = root; process.env.REPORTS_DIR = path.join(root, "reports"); process.env.CHANNELS_DIR = path.join(root, "channels"); process.env.SAVED_VIDEOS_DIR = path.join(root, "saved"); process.env.UMTOOL_CACHE_DIR = path.join(root, "cache"); delete process.env.UMTOOL_BENCH_PREP; const serve = await import("./serve.mjs"); const prep = await import("./benchPrep.mjs"); const trigger = await import("./benchPrepTrigger.mjs"); const { updateClip, insertEntry } = await import("./manifest.mjs"); const { analysisCacheFile, analyseFile } = await import("../analyse.mjs"); const { MIX_CACHE } = await import("../paths.mjs"); test.after(() => rm(root, { recursive: true, force: true })); const dir = path.join(root, "reports", "p"); const project = { id: "p", dir }; const raw = path.join(dir, "out", "clips-raw"); /** A clip on a "recording" (its window is 700 s by its name: longer than EXCERPT_OVER_S), one on a short window, one with nothing fetched. */ const MANIFEST = { slug: "p", timeline: [ { type: "clip", id: "long", video: "vid", start: 18, end: 22 }, { type: "clip", id: "short", video: "vs", start: 2, end: 5 }, { type: "clip", id: "none", video: "zzz", start: 1, end: 2 }, ], }; const media = (file, seconds) => execFileSync("ffmpeg", [ "-v", "error", "-y", "-f", "lavfi", "-i", `testsrc2=size=160x120:rate=10:duration=${seconds}`, "-f", "lavfi", "-i", `sine=frequency=440:duration=${seconds}`, "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", file, ]); async function fresh() { await rm(dir, { recursive: true, force: true }); await rm(MIX_CACHE, { recursive: true, force: true }); await mkdir(raw, { recursive: true }); await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(MANIFEST, null, 2)}\n`); // A file whose NAME says 0–700: the window listing reads windows from names. media(path.join(raw, "vid_0.00-700.00.mp4"), 40); media(path.join(raw, "vs_0.00-10.00.mp4"), 10); } /** What the bench opens for a clip: the clip route's own windowsFor, first. */ async function benchWindow(id) { const clip = MANIFEST.timeline.find((e) => e.id === id); return (await serve.windowsFor(project, clip, await serve.projectCache(project)))[0] ?? null; } test("the plan: the long window is an excerpt to cut, the short one a waveform to make, the unfetched one nothing", async () => { await fresh(); const plan = await prep.benchPrepPlan(project); const by = Object.fromEntries(plan.items.map((i) => [i.id, i])); assert.equal(by.long.state, "todo"); assert.equal(by.long.excerpt, true); assert.equal(by.long.cut, false); assert.equal(by.short.state, "todo"); assert.equal(by.short.excerpt, false); assert.equal(by.short.cut, true); assert.equal(by.short.peaks, false); assert.equal(by.none.state, "no-window"); assert.deepEqual(plan.counts, { clips: 3, ready: 0, todo: 2, failed: 0, noWindow: 1, excerpts: 1 }); }); test("prep makes the excerpt at the path the bench's excerptOf names, and the waveform the peaks route reads; a second run skips both", async () => { await fresh(); const events = []; const slots = []; const r = await prep.runBenchPrep(project, { slot: async (cmd, fn) => { slots.push(cmd); return fn(); }, onEvent: (e) => events.push(e), }); assert.deepEqual(r.done.sort(), ["long", "short"]); assert.deepEqual(r.failed, []); // One clip per slot, in the plan's order. assert.deepEqual(slots, [["umtool-prep", "p", "long"], ["umtool-prep", "p", "short"]]); const win = await benchWindow("long"); assert.ok(win.excerptOf, "the bench's window for a recording is an excerpt"); const named = serve.excerptOf( { name: "vid_0.00-700.00.mp4", path: path.join(raw, "vid_0.00-700.00.mp4"), from: 0, to: 700 }, MANIFEST.timeline[0], dir, ); assert.equal(win.path, named.path); assert.equal(win.path, path.join(dir, "out", "bench-excerpts", "vid", "0.00-75.00.excerpt.mp4")); const st = await stat(win.path); assert.ok(st.size > 0); assert.equal(await serve.windowFileFresh(win), true); for (const id of ["long", "short"]) { const w = await benchWindow(id); const abs = serve.absOf(w); assert.ok(existsSync(analysisCacheFile(abs, await stat(abs))), `${id}: the waveform is cached`); } const plan = await prep.benchPrepPlan(project); assert.equal(plan.counts.ready, 2); assert.equal(plan.counts.todo, 0); const again = await prep.runBenchPrep(project, { slot: () => assert.fail("nothing to do takes no slot") }); assert.deepEqual(again.done, []); assert.equal(again.skipped, 3); assert.equal((await stat(win.path)).mtimeMs, st.mtimeMs, "not cut again"); const status = await prep.readPrepStatus(dir); assert.equal(status.state, "done"); assert.equal(status.pid, process.pid); assert.deepEqual(events.map((e) => e.ev).filter((e) => e !== "clip"), ["start", "clip-done", "clip-done", "end"]); }); test("the bench's serve path takes a prepared file: no cut, and the cached waveform", async () => { // Continues from the run above: everything is prepared. const win = await benchWindow("long"); // An ffmpeg that cannot run: a cut would throw. await serve.ensureWindowFile(win, { ffmpeg: "/nonexistent/ffmpeg" }); const abs = serve.absOf(win); const file = analysisCacheFile(abs, await stat(abs)); const cached = JSON.parse(await readFile(file, "utf8")); await writeFile(file, JSON.stringify({ ...cached, label: "from-the-cache" })); assert.equal((await analyseFile(abs)).label, "from-the-cache", "the peaks route's analysis reads the prepared file"); }); test("a recording changed since its excerpt was cut is prepared again; a cut in flight in another process is waited for, not repeated", async () => { const win = await benchWindow("long"); const src = path.join(raw, "vid_0.00-700.00.mp4"); const later = new Date(Date.now() + 5000); await utimes(src, later, later); const plan = await prep.benchPrepPlan(project, null, { clips: ["long"] }); assert.equal(plan.items[0].state, "todo"); assert.equal(plan.items[0].cut, false); // Another process (a live pid) has marked the cut; it lands 300 ms later. const other = spawn(process.execPath, ["-e", "setTimeout(() => {}, 5000)"]); try { await writeFile(serve.cutMarkOf(win.path), JSON.stringify({ pid: other.pid, at: Date.now() })); const done = (async () => { await new Promise((r) => setTimeout(r, 300)); const t = new Date(Date.now() + 10_000); await utimes(win.path, t, t); // What the other process's cut leaves beside its excerpt: the source it was cut from. await writeFile(serve.excerptSourceOf(win.path), JSON.stringify(await serve.sourceIdentity(src))); await rm(serve.cutMarkOf(win.path)); })(); // A real cut would need ffmpeg: this one must wait for the other process instead. await serve.ensureWindowFile(win, { ffmpeg: "/nonexistent/ffmpeg", pollMs: 50 }); await done; assert.equal(await serve.windowFileFresh(win), true); } finally { other.kill(); } }); test("a manifest write queues prep for the clips it moved or added, and returns without waiting for it", async () => { await fresh(); const calls = []; let release; const held = new Promise((r) => { release = r; }); trigger.setBenchPrepQueue(async (p, clips, opts) => { calls.push({ p, clips, opts }); await held; // a queue that never finishes on its own }); try { const t0 = Date.now(); const res = await updateClip(dir, "long", { start: 100, end: 104 }); assert.equal(res.entry.start, 100); assert.ok(Date.now() - t0 < 2000, "the writer did not wait"); await new Promise((r) => setTimeout(r, 50)); assert.equal(calls.length, 1); assert.deepEqual(calls[0].p, { id: "p", dir }); assert.deepEqual(calls[0].clips, ["long"]); assert.deepEqual(calls[0].opts, { excerptsOnly: true }); // Only the cut moved: the extent (and so any excerpt) is where it was. await updateClip(dir, "long", { cutStart: 101, cutEnd: 103 }); await new Promise((r) => setTimeout(r, 50)); assert.equal(calls.length, 1, "a cut inside the extent needs no new excerpt"); const ins = await insertEntry(dir, "long", "chan/vid@300-310"); await new Promise((r) => setTimeout(r, 50)); assert.equal(calls.length, 2); assert.deepEqual(calls[1].clips, [ins.id]); } finally { release(); await trigger.settleBenchPrepTriggers(); trigger.setBenchPrepQueue(null); } }); test("queueing: only the clips that need it, a runner started once, none while one is alive; off with UMTOOL_BENCH_PREP=0", async () => { await fresh(); const started = []; const start = (p) => { started.push(p.id); return 4242; }; const excerpts = await prep.queueBenchPrep(project, null, { excerptsOnly: true, start }); assert.deepEqual(excerpts.queued, ["long"], "a trigger queues the excerpt, not a short window's waveform"); assert.equal(excerpts.started, true); const all = await prep.queueBenchPrep(project, null, { start }); assert.deepEqual(all.queued.sort(), ["long", "short"]); assert.deepEqual(started, ["p", "p"]); // A live runner holds the lock: the request is queued, no second runner. assert.equal(prep.tryLock(dir), true); try { const q = await prep.queueBenchPrep(project, ["short"], { start }); assert.deepEqual(q.queued, ["short"]); assert.equal(q.started, false); assert.equal(q.pid, process.pid); assert.equal(started.length, 2); } finally { prep.unlock(dir); } const reqs = await prep.takePrepRequests(dir); // The clips each ask resolved to, merged into one request. assert.deepEqual({ ...reqs, clips: [...reqs.clips].sort() }, { clips: ["long", "short"], retry: false }); assert.deepEqual(prep.mergeRequests([{ clips: ["a"] }, { clips: null, retry: true }]), { clips: null, retry: true }, "one ask for all is all"); assert.equal(await prep.takePrepRequests(dir), null); process.env.UMTOOL_BENCH_PREP = "0"; try { const off = await prep.queueBenchPrep(project, null, { start }); assert.equal(off.off, true); assert.equal(started.length, 2); } finally { delete process.env.UMTOOL_BENCH_PREP; } }); test("the runner drains the queue under its lock, and lets go", async () => { await fresh(); await prep.appendPrepRequest(dir, { clips: ["short"] }); const r = await prep.drainPrepQueue(project, { slot: (_c, fn) => fn() }); assert.deepEqual(r.done, ["short"]); assert.equal(r.held, false); assert.equal(prep.lockHolder(dir), null, "the lock is released"); // A busy lock: a background runner leaves the queue to its holder. assert.equal(prep.tryLock(dir), true); try { await prep.appendPrepRequest(dir, { clips: ["long"] }); const held = await prep.drainPrepQueue(project, { slot: (_c, fn) => fn() }); assert.equal(held.held, true); assert.deepEqual(held.done, []); } finally { prep.unlock(dir); } }); test("a failed clip reads failed until its window changes; an explicit ask tries it again", async () => { await fresh(); const r = await prep.runBenchPrep(project, { clips: ["short"], analyse: async () => { throw new Error("no audio"); } }); assert.deepEqual(r.failed, ["short"]); let plan = await prep.benchPrepPlan(project, null, { clips: ["short"] }); assert.equal(plan.items[0].state, "failed"); assert.match(plan.items[0].error, /no audio/); const trig = await prep.queueBenchPrep(project, ["short"], { start: () => 1 }); assert.deepEqual(trig.queued, [], "a trigger leaves a failed clip alone"); await prep.takePrepRequests(dir); const again = await prep.runBenchPrep(project, { clips: ["short"], retry: true }); assert.deepEqual(again.done, ["short"]); plan = await prep.benchPrepPlan(project, null, { clips: ["short"] }); assert.equal(plan.items[0].state, "ready"); }); test("the runner's command: niced and idle-I/O when the tools are there", () => { const argv = prep.runnerArgv("folder/p", { has: () => true }); assert.deepEqual(argv.slice(0, 5), ["nice", "-n", "19", "ionice", "-c3"]); assert.equal(argv[5], process.execPath); assert.ok(argv[6].endsWith(path.join("bin", "umtool.mjs"))); assert.deepEqual(argv.slice(7), ["prep", "folder/p", "--run"]); const bare = prep.runnerArgv("p", { has: () => false, wait: true, clips: ["a", "b"], retry: true }); assert.deepEqual(bare.slice(2), ["prep", "p", "--run", "--wait", "--clips", "a,b", "--retry"]); assert.equal(bare[0], process.execPath); }); test("a project directory is one of REPORTS_ROOT's, or not one at all", () => { assert.deepEqual(prep.projectOfDir(path.join(root, "reports", "a", "b")), { id: "a/b", dir: path.join(root, "reports", "a", "b") }); assert.equal(prep.projectOfDir(path.join(root, "elsewhere")), null); assert.equal(prep.projectOfDir(path.join(root, "reports")), null); });