Archilyzer · Source

archilyzer

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

commit 571c1a96d4ba203d9742a01cff86a77eca29eabd
parent 04e6d1de9f19db6b8a4538c459cc45c11a2d08a6
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Mon,  2 Nov 2026 13:43:52 -0500

umtool prep --take: a take's clips prepared for its walk from its manifest as the walk reads it (a draft's too, no render), with its own status, queue, lock and log under out/bench-excerpts/takes/<id>/ so a take's clip of the cut's id never shares the cut's state; a save on the take's walk queues the take's prep; the take's walk page carries "Prepare clips for the walk"

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

Diffstat:
Mumtool/app/api/report/prep/route.ts | 27+++++++++++++++++++++------
Mumtool/components/projects/TakeWalkPage.tsx | 3+++
Mumtool/components/projects/report/BenchPrepPanel.tsx | 13++++++++-----
Mumtool/lib/report/benchPrep.mjs | 189++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
Aumtool/lib/report/benchPrepTake.test.mjs | 175+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mumtool/lib/report/benchPrepTrigger.mjs | 15++++++++++-----
Mumtool/lib/report/prepCli.mjs | 38+++++++++++++++++++++++++++++++-------
Mumtool/lib/report/takeEdit.mjs | 6+++++-
8 files changed, 374 insertions(+), 92 deletions(-)

diff --git a/umtool/app/api/report/prep/route.ts b/umtool/app/api/report/prep/route.ts @@ -1,5 +1,6 @@ import { projectRef } from "@/lib/projects"; import { benchPrepState, queueBenchPrep } from "@/lib/report/benchPrep.mjs"; +import { isTakeId } from "@/lib/report/takes.mjs"; export const dynamic = "force-dynamic"; @@ -8,16 +9,28 @@ export const dynamic = "force-dynamic"; // by a runner in the background (`umtool prep <project> --run`), one clip at a // time in the machine's heavy slot. The Cut tab's "Prepare clips for the walk". // -// GET ?project=<id> ready / to prepare / failed / not fetched, and the runner when one is alive -// POST { project, clips? } queue them (all when none are named); returns at once +// GET ?project=<id>[&take=<id>] ready / to prepare / failed / not fetched, and the runner when one is alive +// POST { project, take?, clips? } queue them (all when none are named); returns at once +// +// `take`: a take's clips (the take's walk), its manifest as the walk reads it +// (a draft's too), its own status and runner (`umtool prep <p> --take <id>`). const headers = { "cache-control": "no-store" }; +/** The take named, or null; an error string when it is not a take id. */ +function takeOf(v: unknown): string | null | { error: string } { + if (v === undefined || v === null || v === "") return null; + const t = String(v); + return isTakeId(t) ? t : { error: `"${t}" is not a take id` }; +} + export async function GET(request: Request) { const url = new URL(request.url); const project = await projectRef(url.searchParams.get("project") ?? ""); if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); + const take = takeOf(url.searchParams.get("take")); + if (take && typeof take === "object") return Response.json(take, { status: 400, headers }); try { - const s = await benchPrepState({ id: project.id, dir: project.dir }); + const s = await benchPrepState({ id: project.id, dir: project.dir }, { take }); return Response.json({ ...s, items: undefined }, { headers }); } catch (e) { return Response.json({ error: e instanceof Error ? e.message : String(e) }, { status: 500, headers }); @@ -25,15 +38,17 @@ export async function GET(request: Request) { } export async function POST(request: Request) { - const b = (await request.json().catch(() => null)) as { project?: unknown; clips?: unknown } | null; + const b = (await request.json().catch(() => null)) as { project?: unknown; clips?: unknown; take?: unknown } | null; if (!b || typeof b !== "object") return Response.json({ error: "bad json" }, { status: 400, headers }); const project = await projectRef(String(b.project ?? "")); if (!project) return Response.json({ error: "no such project" }, { status: 404, headers }); const clips = Array.isArray(b.clips) ? b.clips.map(String).filter(Boolean) : null; + const take = takeOf(b.take); + if (take && typeof take === "object") return Response.json(take, { status: 400, headers }); const ref = { id: project.id, dir: project.dir }; try { - const q = await queueBenchPrep(ref, clips, { retry: true }); - const s = await benchPrepState(ref); + const q = await queueBenchPrep(ref, clips, { retry: true, take }); + const s = await benchPrepState(ref, { take }); // A runner just started may not hold its lock yet: it is running all the same. return Response.json( { ...s, running: s.running || q.started, items: undefined, queued: q.queued.length, started: q.started, off: !!q.off }, diff --git a/umtool/components/projects/TakeWalkPage.tsx b/umtool/components/projects/TakeWalkPage.tsx @@ -9,6 +9,7 @@ import { walkOf } from "@/lib/report/walkData.mjs"; import type { ProjectRef } from "@/lib/project-types"; import { BenchBody, BenchFrame, BenchTop } from "./bench/BenchShell"; import TakeActions from "./TakeActions"; +import BenchPrepPanel from "./report/BenchPrepPanel"; // `/projects/<project>/takes/<take>/walk` -- WALK A TAKE: the take's clips // (the project's manifest with the take's patch applied, a draft too) in walk @@ -79,6 +80,8 @@ export default async function TakeWalkPage({ {all ? "walk only the clips needing a verdict" : "walk every clip (judged ones too)"} </Link> </div> + {/* The take's own prep: its clips' excerpts and waveforms made before the walk opens them. */} + <BenchPrepPanel project={project.id} take={take} /> {w.take?.editable && ( <TakeActions project={project.id} take={take} draft={!!w.take?.draft} walkHref={null} edited compact /> )} diff --git a/umtool/components/projects/report/BenchPrepPanel.tsx b/umtool/components/projects/report/BenchPrepPanel.tsx @@ -7,6 +7,7 @@ import { buttonVariants } from "@/components/ui/button"; // first-open work -- a long recording's excerpt, the waveform -- made by a // runner in the background, one clip at a time in the heavy slot, so opening // a clip on the walk does not wait on ffmpeg. A status line and one button. +// With `take` (the take's walk): the take's clips, its own runner. type PrepState = { counts: { clips: number; ready: number; todo: number; failed: number; noWindow: number; excerpts: number }; @@ -19,20 +20,22 @@ type PrepState = { const POLL_MS = 2500; -export default function BenchPrepPanel({ project }: { project: string }) { +export default function BenchPrepPanel({ project, take = null }: { project: string; take?: string | null }) { const [s, setS] = useState<PrepState | null>(null); const [asking, setAsking] = useState(false); const [err, setErr] = useState<string | null>(null); const load = useCallback(async () => { - const r = await fetch(`/api/report/prep?project=${encodeURIComponent(project)}`, { cache: "no-store" }); + const q = new URLSearchParams({ project }); + if (take) q.set("take", take); + const r = await fetch(`/api/report/prep?${q.toString()}`, { cache: "no-store" }); const j = (await r.json().catch(() => ({}))) as PrepState; if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`); else { setErr(null); setS(j); } - }, [project]); + }, [project, take]); useEffect(() => { void load(); @@ -56,7 +59,7 @@ export default function BenchPrepPanel({ project }: { project: string }) { const r = await fetch("/api/report/prep", { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ project }), + body: JSON.stringify({ project, ...(take ? { take } : {}) }), }); const j = (await r.json().catch(() => ({}))) as PrepState; if (!r.ok) setErr(j.error ?? `HTTP ${r.status}`); @@ -69,7 +72,7 @@ export default function BenchPrepPanel({ project }: { project: string }) { const run = s?.runner; return ( - <div className="flex flex-wrap items-center gap-2" data-bench-prep="" data-bench-prep-state={s?.running ? "running" : left ? "todo" : "ready"}> + <div className="flex flex-wrap items-center gap-2" data-bench-prep={take ?? ""} data-bench-prep-state={s?.running ? "running" : left ? "todo" : "ready"}> {left > 0 && !s?.running && ( <button type="button" diff --git a/umtool/lib/report/benchPrep.mjs b/umtool/lib/report/benchPrep.mjs @@ -54,6 +54,7 @@ import { MIX_CACHE, REPORTS_ROOT, inside } from "../paths.mjs"; import { analysisCacheFile } from "../analyse.mjs"; import { clipsOf, readManifest } from "../projects/report.mjs"; import { UMTOOL_DIR } from "./driver.mjs"; +import { isTakeId } from "./takes.mjs"; import { absOf, ensureWindowFile, projectCache, windowFileFresh, windowsFor } from "./serve.mjs"; /** An excerpt cut's resident set (234 MB, measured: a 2-minute 720p excerpt of a 1080p stream) plus the runner. */ @@ -61,11 +62,44 @@ export const PREP_ESTIMATE_MB = 400; /** Where the prep keeps its state: beside the excerpts it makes. */ export const prepDirOf = (projectDir) => path.join(/* turbopackIgnore: true */ projectDir, "out", "bench-excerpts"); -const statusFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), "prep-status.json"); -const pendingFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), ".prep-pending"); -const lockFile = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), ".prep-run.lock"); + +// A TAKE'S PREP (`umtool prep <p> --take <id>`, the take's walk) keeps its own +// status, queue, lock and log, under out/bench-excerpts/takes/<id>/: a take's +// clip may carry the cut's id with other bounds (a widened kf3), and a +// failure, a queued request or a runner of one must never read as the +// other's. The excerpts themselves are shared -- named by their seconds of the +// source, so one cut serves every clip that opens the same seconds. +/** + * The directory a prep's state lives in: the project's, or a take's. + * @param {string} projectDir + * @param {string | null} [take] + */ +export function prepStateDirOf(projectDir, take = null) { + if (!take) return prepDirOf(projectDir); + if (!isTakeId(take)) throw new Error(`"${take}" is not a take id`); + return path.join(/* turbopackIgnore: true */ prepDirOf(projectDir), "takes", take); +} +const statusFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), "prep-status.json"); +const pendingFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), ".prep-pending"); +const lockFile = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), ".prep-run.lock"); /** The runner's stdout and stderr (the heavy slot's waiting lines land here). */ -export const prepLogOf = (dir) => path.join(/* turbopackIgnore: true */ prepDirOf(dir), "prep.log"); +export const prepLogOf = (dir, take = null) => path.join(/* turbopackIgnore: true */ prepStateDirOf(dir, take), "prep.log"); + +/** + * The manifest a prep reads: the project's, or -- with `take` -- the take's as + * its walk reads it (takeManifest.mjs resolveTakeManifest: the project's + * manifest now, the style's patch, then the take's, merged). A DRAFT take + * (recorded, nothing rendered) has one too: nothing here waits for a render, + * and the windows prepared are the ones the take's bench will open. + * + * @param {{ dir: string }} project + * @param {string | null} [take] + */ +export async function prepManifestOf(project, take = null) { + if (!take) return readManifest(project.dir); + const { resolveTakeManifest } = await import("./takeManifest.mjs"); + return (await resolveTakeManifest(project.dir, take)).manifest; +} const alive = (pid) => { if (!Number.isInteger(pid) || pid <= 0) return false; @@ -104,17 +138,19 @@ const alive = (pid) => { * of THIS window failed reads `failed` until the window changes (an explicit * prep tries it again; a trigger does not). * + * `take`: the take's clips (prepManifestOf), its failures from its own status. + * * @param {{ id: string, dir: string }} project * @param {any} [manifest] - * @param {{ clips?: string[] | null, cache?: any, mixCache?: string }} [opts] + * @param {{ clips?: string[] | null, cache?: any, mixCache?: string, take?: string | null }} [opts] * @returns {Promise<{ items: PrepItem[], counts: { clips: number, ready: number, todo: number, failed: number, noWindow: number, excerpts: number } }>} */ -export async function benchPrepPlan(project, manifest = null, { clips = null, cache = null, mixCache = MIX_CACHE } = {}) { - const m = manifest ?? (await readManifest(project.dir)); +export async function benchPrepPlan(project, manifest = null, { clips = null, cache = null, mixCache = MIX_CACHE, take = null } = {}) { + const m = manifest ?? (await prepManifestOf(project, take)); const want = clips && clips.length ? new Set(clips) : null; const all = clipsOf(m).filter((c) => !want || want.has(c.id)); const c = cache ?? (await projectCache(project, m)); - const failures = (await readPrepStatus(project.dir))?.failed ?? {}; + const failures = (await readPrepStatus(project.dir, take))?.failed ?? {}; /** @type {PrepItem[]} */ const items = []; for (const clip of all) { @@ -185,21 +221,21 @@ export const publicItem = ({ win, ...rest }) => rest; * }} PrepStatus */ -/** @param {string} dir @returns {Promise<PrepStatus | null>} */ -export async function readPrepStatus(dir) { +/** @param {string} dir @param {string | null} [take] @returns {Promise<PrepStatus | null>} */ +export async function readPrepStatus(dir, take = null) { try { - return JSON.parse(await readFile(statusFile(dir), "utf8")); + return JSON.parse(await readFile(statusFile(dir, take), "utf8")); } catch { return null; } } -/** @param {string} dir @param {PrepStatus} st */ -async function writePrepStatus(dir, st) { - await mkdir(prepDirOf(dir), { recursive: true }); - const tmp = `${statusFile(dir)}.tmp-${process.pid}`; +/** @param {string} dir @param {PrepStatus} st @param {string | null} [take] */ +async function writePrepStatus(dir, st, take = null) { + await mkdir(prepStateDirOf(dir, take), { recursive: true }); + const tmp = `${statusFile(dir, take)}.tmp-${process.pid}`; await writeFile(tmp, `${JSON.stringify(st, null, 1)}\n`); - await rename(tmp, statusFile(dir)); + await rename(tmp, statusFile(dir, take)); } /** @@ -208,15 +244,16 @@ async function writePrepStatus(dir, st) { * runner that was killed: it reads as stopped). * * @param {{ id: string, dir: string }} project - * @param {{ clips?: string[] | null, plan?: Awaited<ReturnType<typeof benchPrepPlan>> }} [opts] + * @param {{ clips?: string[] | null, plan?: Awaited<ReturnType<typeof benchPrepPlan>>, take?: string | null }} [opts] */ -export async function benchPrepState(project, { clips = null, plan = null } = {}) { - const p = plan ?? (await benchPrepPlan(project, null, { clips })); - const st = await readPrepStatus(project.dir); - const holder = lockHolder(project.dir); +export async function benchPrepState(project, { clips = null, plan = null, take = null } = {}) { + const p = plan ?? (await benchPrepPlan(project, null, { clips, take })); + const st = await readPrepStatus(project.dir, take); + const holder = lockHolder(project.dir, take); const running = !!holder || (st?.state === "running" && alive(Number(st.pid))); return { project: project.id, + take, counts: p.counts, running, runner: running @@ -244,12 +281,14 @@ export async function benchPrepState(project, { clips = null, plan = null } = {} * analyse?: (abs: string) => Promise<unknown>, * onEvent?: (ev: Record<string, unknown>) => void, * mixCache?: string, + * take?: string | null, * }} [opts] * @returns {Promise<{ done: string[], failed: string[], skipped: number }>} */ export async function runBenchPrep(project, { clips = null, retry = false, + take = null, slot = (_cmd, fn) => fn(), ensure = (win) => ensureWindowFile(win), analyse = null, @@ -257,9 +296,10 @@ export async function runBenchPrep(project, { mixCache = MIX_CACHE, } = {}) { const analyseOne = analyse ?? (async (abs) => (await import("../analyse.mjs")).analyseFile(abs, { cacheDir: mixCache })); - const plan = await benchPrepPlan(project, null, { clips, mixCache }); + const plan = await benchPrepPlan(project, null, { clips, mixCache, take }); const todo = plan.items.filter((i) => i.state === "todo" || (retry && i.state === "failed")); - const prev = await readPrepStatus(project.dir); + const prev = await readPrepStatus(project.dir, take); + const put = (st) => writePrepStatus(project.dir, st, take); /** @type {PrepStatus} */ const status = { pid: process.pid, @@ -276,26 +316,26 @@ export async function runBenchPrep(project, { const it = plan.items.find((i) => i.id === id); if (it && it.window?.name !== status.failed[id].window) delete status.failed[id]; } - await writePrepStatus(project.dir, status); - onEvent({ ev: "start", project: project.id, total: todo.length, ready: plan.counts.ready, noWindow: plan.counts.noWindow }); + await put(status); + onEvent({ ev: "start", project: project.id, ...(take ? { take } : {}), total: todo.length, ready: plan.counts.ready, noWindow: plan.counts.noWindow }); const done = []; const failed = []; for (const it of todo) { const t0 = Date.now(); status.current = { id: it.id, step: "waiting" }; - await writePrepStatus(project.dir, status); + await put(status); onEvent({ ev: "clip", id: it.id, step: "waiting", n: done.length + failed.length + 1, total: todo.length }); try { - await slot(["umtool-prep", project.id, it.id], async () => { + await slot(["umtool-prep", project.id, ...(take ? ["--take", take] : []), it.id], async () => { if (!it.cut) { status.current = { id: it.id, step: "cutting" }; - await writePrepStatus(project.dir, status); + await put(status); onEvent({ ev: "clip", id: it.id, step: "cutting", window: it.window?.name }); await ensure(it.win); } if (!it.peaks) { status.current = { id: it.id, step: "analysing" }; - await writePrepStatus(project.dir, status); + await put(status); onEvent({ ev: "clip", id: it.id, step: "analysing" }); const abs = absOf(it.win); if (!abs) throw new Error("the window is outside the roots"); @@ -312,12 +352,12 @@ export async function runBenchPrep(project, { onEvent({ ev: "clip-failed", id: it.id, error }); } status.done = done.length + failed.length; - await writePrepStatus(project.dir, status); + await put(status); } status.current = null; status.state = failed.length ? "failed" : "done"; status.endedAt = new Date().toISOString(); - await writePrepStatus(project.dir, status); + await put(status); onEvent({ ev: "end", done: done.length, failed: failed.length, skipped: plan.items.length - todo.length }); return { done, failed, skipped: plan.items.length - todo.length }; } @@ -326,45 +366,45 @@ export async function runBenchPrep(project, { // The queue and the run lock. // --------------------------------------------------------------------------- -/** The live runner's pid, or null (a lock naming a dead pid is dropped). @param {string} dir */ -export function lockHolder(dir) { +/** The live runner's pid, or null (a lock naming a dead pid is dropped). @param {string} dir @param {string | null} [take] */ +export function lockHolder(dir, take = null) { let raw; try { - raw = readFileSync(/* turbopackIgnore: true */ lockFile(dir), "utf8"); + raw = readFileSync(/* turbopackIgnore: true */ lockFile(dir, take), "utf8"); } catch { return null; } const pid = Number(String(raw).trim()); if (alive(pid)) return pid; try { - unlinkSync(/* turbopackIgnore: true */ lockFile(dir)); + unlinkSync(/* turbopackIgnore: true */ lockFile(dir, take)); } catch { /* somebody else dropped it */ } return null; } -/** Take the run lock, or false when a live runner holds it. @param {string} dir */ -export function tryLock(dir) { +/** Take the run lock, or false when a live runner holds it. @param {string} dir @param {string | null} [take] */ +export function tryLock(dir, take = null) { for (let i = 0; i < 2; i += 1) { try { - const fd = openSync(/* turbopackIgnore: true */ lockFile(dir), "wx"); + const fd = openSync(/* turbopackIgnore: true */ lockFile(dir, take), "wx"); writeSync(fd, `${process.pid}\n`); closeSync(fd); return true; } catch (e) { if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EEXIST") throw e; - if (lockHolder(dir)) return false; + if (lockHolder(dir, take)) return false; } } return false; } -/** @param {string} dir */ -export function unlock(dir) { +/** @param {string} dir @param {string | null} [take] */ +export function unlock(dir, take = null) { try { - if (Number(readFileSync(/* turbopackIgnore: true */ lockFile(dir), "utf8").trim()) === process.pid) { - unlinkSync(/* turbopackIgnore: true */ lockFile(dir)); + if (Number(readFileSync(/* turbopackIgnore: true */ lockFile(dir, take), "utf8").trim()) === process.pid) { + unlinkSync(/* turbopackIgnore: true */ lockFile(dir, take)); } } catch { /* not ours, or gone */ @@ -375,10 +415,11 @@ export function unlock(dir) { * Add a request to the project's queue. `clips: null` is every clip. * @param {string} dir * @param {{ clips: string[] | null, retry?: boolean }} req + * @param {string | null} [take] */ -export async function appendPrepRequest(dir, req) { - await mkdir(prepDirOf(dir), { recursive: true }); - await appendFile(pendingFile(dir), `${JSON.stringify({ clips: req.clips ?? null, retry: !!req.retry, at: Date.now() })}\n`); +export async function appendPrepRequest(dir, req, take = null) { + await mkdir(prepStateDirOf(dir, take), { recursive: true }); + await appendFile(pendingFile(dir, take), `${JSON.stringify({ clips: req.clips ?? null, retry: !!req.retry, at: Date.now() })}\n`); } /** @@ -387,12 +428,13 @@ export async function appendPrepRequest(dir, req) { * asks for all), `retry` if any does. Null when the queue is empty. * * @param {string} dir + * @param {string | null} [take] * @returns {Promise<{ clips: string[] | null, retry: boolean } | null>} */ -export async function takePrepRequests(dir) { - const taking = `${pendingFile(dir)}.${process.pid}`; +export async function takePrepRequests(dir, take = null) { + const taking = `${pendingFile(dir, take)}.${process.pid}`; try { - await rename(pendingFile(dir), taking); + await rename(pendingFile(dir, take), taking); } catch { return null; } @@ -429,24 +471,28 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); * instead of leaving the queue to the runner that holds it. * * @param {{ id: string, dir: string }} project + * `take`: the take's queue, under the take's lock (prepStateDirOf). + * + * @param {{ id: string, dir: string }} project * @param {Parameters<typeof runBenchPrep>[1] & { initial?: { clips: string[] | null, retry?: boolean } | null, wait?: boolean, pollMs?: number }} [opts] * @returns {Promise<{ runs: number, done: string[], failed: string[], held: boolean }>} */ export async function drainPrepQueue(project, { initial = null, wait = false, pollMs = 2000, ...run } = {}) { - await mkdir(prepDirOf(project.dir), { recursive: true }); + const take = run.take ?? null; + await mkdir(prepStateDirOf(project.dir, take), { recursive: true }); const done = []; const failed = []; let runs = 0; let own = initial; for (;;) { - if (!tryLock(project.dir)) { + if (!tryLock(project.dir, take)) { if (!wait) return { runs, done, failed, held: true }; await sleep(pollMs); continue; } try { for (;;) { - const queued = await takePrepRequests(project.dir); + const queued = await takePrepRequests(project.dir, take); const req = own && queued ? mergeRequests([own, queued]) : own ?? queued; own = null; if (!req) break; @@ -456,11 +502,11 @@ export async function drainPrepQueue(project, { initial = null, wait = false, po failed.push(...r.failed); } } finally { - unlock(project.dir); + unlock(project.dir, take); } // A request appended after the last look and before the unlock saw a live // runner and started none: look once more, now that the lock is free. - if (!existsSync(/* turbopackIgnore: true */ pendingFile(project.dir))) return { runs, done, failed, held: false }; + if (!existsSync(/* turbopackIgnore: true */ pendingFile(project.dir, take))) return { runs, done, failed, held: false }; wait = false; } } @@ -483,9 +529,9 @@ function onPath(name) { * both. Pure apart from the PATH probe. * * @param {string} projectId - * @param {{ wait?: boolean, clips?: string[] | null, retry?: boolean, ndjson?: boolean, has?: (name: string) => boolean }} [opts] + * @param {{ wait?: boolean, clips?: string[] | null, retry?: boolean, ndjson?: boolean, take?: string | null, has?: (name: string) => boolean }} [opts] */ -export function runnerArgv(projectId, { wait = false, clips = null, retry = false, ndjson = false, has = onPath } = {}) { +export function runnerArgv(projectId, { wait = false, clips = null, retry = false, ndjson = false, take = null, has = onPath } = {}) { const prefix = [ ...(has("nice") ? ["nice", "-n", "19"] : []), ...(has("ionice") ? ["ionice", "-c3"] : []), @@ -496,6 +542,7 @@ export function runnerArgv(projectId, { wait = false, clips = null, retry = fals path.join(/* turbopackIgnore: true */ UMTOOL_DIR, "bin", "umtool.mjs"), "prep", projectId, + ...(take ? ["--take", take] : []), "--run", ...(wait ? ["--wait"] : []), ...(clips && clips.length ? ["--clips", clips.join(",")] : []), @@ -504,18 +551,22 @@ export function runnerArgv(projectId, { wait = false, clips = null, retry = fals ]; } -/** Start a detached runner, its output appended to prep.log. @param {{ id: string, dir: string }} project */ -export function spawnPrepRunner(project) { - const argv = runnerArgv(project.id); +/** + * Start a detached runner, its output appended to prep.log (the take's, for a take). + * @param {{ id: string, dir: string }} project + * @param {{ take?: string | null }} [opts] + */ +export function spawnPrepRunner(project, { take = null } = {}) { + const argv = runnerArgv(project.id, { take }); // The log is the last runs', not a history: past 1 MB it starts again. const big = (() => { try { - return statSync(/* turbopackIgnore: true */ prepLogOf(project.dir)).size > 1024 * 1024; + return statSync(/* turbopackIgnore: true */ prepLogOf(project.dir, take)).size > 1024 * 1024; } catch { return false; } })(); - const fd = openSync(/* turbopackIgnore: true */ prepLogOf(project.dir), big ? "w" : "a"); + const fd = openSync(/* turbopackIgnore: true */ prepLogOf(project.dir, take), big ? "w" : "a"); try { const child = spawn(argv[0], argv.slice(1), { cwd: UMTOOL_DIR, @@ -541,23 +592,25 @@ export function spawnPrepRunner(project) { * then prepares each queued clip whole. `retry` also takes clips whose last * prep failed (an explicit ask; a trigger leaves them). * + * `take`: the take's clips, queued for the take's own runner (`umtool prep <p> --take <id> --run`). + * * @param {{ id: string, dir: string }} project * @param {string[] | null} [clips] - * @param {{ excerptsOnly?: boolean, retry?: boolean, start?: (project: { id: string, dir: string }) => number | null, plan?: any }} [opts] + * @param {{ excerptsOnly?: boolean, retry?: boolean, take?: string | null, start?: (project: { id: string, dir: string }, opts: { take: string | null }) => number | null, plan?: any }} [opts] * @returns {Promise<{ queued: string[], started: boolean, pid: number | null, off?: boolean }>} */ -export async function queueBenchPrep(project, clips = null, { excerptsOnly = false, retry = false, start = spawnPrepRunner, plan = null } = {}) { +export async function queueBenchPrep(project, clips = null, { excerptsOnly = false, retry = false, take = null, start = spawnPrepRunner, plan = null } = {}) { if (process.env.UMTOOL_BENCH_PREP === "0") return { queued: [], started: false, pid: null, off: true }; - const p = plan ?? (await benchPrepPlan(project, null, { clips })); + const p = plan ?? (await benchPrepPlan(project, null, { clips, take })); const queued = p.items .filter((i) => i.state === "todo" || (retry && i.state === "failed")) .filter((i) => !excerptsOnly || (i.excerpt && !i.cut)) .map((i) => i.id); - if (!queued.length) return { queued, started: false, pid: lockHolder(project.dir) }; - await appendPrepRequest(project.dir, { clips: queued, retry }); - const holder = lockHolder(project.dir); + if (!queued.length) return { queued, started: false, pid: lockHolder(project.dir, take) }; + await appendPrepRequest(project.dir, { clips: queued, retry }, take); + const holder = lockHolder(project.dir, take); if (holder) return { queued, started: false, pid: holder }; - return { queued, started: true, pid: start(project) }; + return { queued, started: true, pid: start(project, { take }) }; } /** diff --git a/umtool/lib/report/benchPrepTake.test.mjs b/umtool/lib/report/benchPrepTake.test.mjs @@ -0,0 +1,175 @@ +// A TAKE'S PREP (`umtool prep <p> --take <id>`, the take's walk): the take's +// clips planned from its manifest as the walk reads it -- a DRAFT's too, no +// render -- with its own status, queue and runner, so a take's clip that +// carries the cut's id with other bounds never shares the cut's state. And +// the plan does not depend on the process's working directory (2 Nov: run +// from the project's directory it planned every clip no-window). +// +// Run with: pnpm test:scripts +import assert from "node:assert/strict"; +import test from "node:test"; +import path from "node:path"; +import os from "node:os"; +import { execFileSync } from "node:child_process"; +import { existsSync } from "node:fs"; +import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { fileURLToPath } from "node:url"; + +const root = await mkdtemp(path.join(os.tmpdir(), "bench-prep-take-")); +// The roots are read when paths.mjs loads. +const ENV = { + MIX_ROOTS: root, + REPORTS_DIR: path.join(root, "reports"), + CHANNELS_DIR: path.join(root, "channels"), + SAVED_VIDEOS_DIR: path.join(root, "saved"), + UMTOOL_CACHE_DIR: path.join(root, "cache"), +}; +Object.assign(process.env, ENV); +delete process.env.UMTOOL_BENCH_PREP; + +const prep = await import("./benchPrep.mjs"); +const trigger = await import("./benchPrepTrigger.mjs"); +const { updateTakeClip } = await import("./takeEdit.mjs"); + +test.after(() => rm(root, { recursive: true, force: true })); + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const dir = path.join(root, "reports", "folder", "p"); +const project = { id: "folder/p", dir }; +const raw = path.join(dir, "out", "clips-raw"); + +const clip = (id, video, start, end, extra = {}) => ({ type: "clip", id, video, channel: "chan", start, end, ...extra }); +/** The cut: kf3 on vid at 10-14; kr1 on vs. */ +const MANIFEST = { slug: "p", provenance: { channelSlug: "chan" }, timeline: [clip("kf3", "vid", 10, 14), clip("kr1", "vs", 2, 5)] }; +/** + * A DRAFT take whose patch replaces the timeline (its own timeline): kf3 + * WIDENED to 8-20 (the cut's id, other bounds), and ke1 -- a clip only the + * take has, on a recording the cut never cites, held only in the corpus. + */ +const TAKE = { + id: "spin", + group: "takes", + order: 1, + label: "Spin-off", + kind: "different", + summary: "", + changes: [], + preview: "preview.mp4", + seconds: null, + builtAt: null, + style: null, + patch: { timeline: [clip("kf3", "vid", 8, 20), clip("ke1", "vnew", 12, 18)] }, + window: null, + draft: true, + draftedAt: "2026-11-02T12:00:00.000Z", +}; + +async function fresh() { + await rm(dir, { recursive: true, force: true }); + await mkdir(raw, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), `${JSON.stringify(MANIFEST, null, 2)}\n`); + await mkdir(path.join(dir, "takes", "spin"), { recursive: true }); + await writeFile(path.join(dir, "takes", "spin", "take.json"), `${JSON.stringify(TAKE, null, 2)}\n`); + // Windows by NAME (the listing reads seconds from names; nothing here decodes them). + await writeFile(path.join(raw, "vid_0.00-30.00.mp4"), "x"); + await writeFile(path.join(raw, "vs_0.00-10.00.mp4"), "x"); + // ke1's window: in the CORPUS (the editor's fetch lands there), not in the project. + const corpus = path.join(root, "channels", "chan", "data", "vnew", "clips"); + await mkdir(corpus, { recursive: true }); + await writeFile(path.join(corpus, "10.00-30.00.mp4"), "x"); + await rm(path.join(root, "cache"), { recursive: true, force: true }); +} + +test("a draft take's plan is its own timeline: the take-only clip found in the corpus, the widened clip on its own bounds", async () => { + await fresh(); + const cut = await prep.benchPrepPlan(project); + assert.deepEqual(cut.items.map((i) => i.id), ["kf3", "kr1"]); + const take = await prep.benchPrepPlan(project, null, { take: "spin" }); + assert.deepEqual(take.items.map((i) => [i.id, i.state, i.window?.name]), [ + ["kf3", "todo", "vid_0.00-30.00.mp4"], + ["ke1", "todo", "10.00-30.00.mp4"], + ]); + assert.equal(take.counts.noWindow, 0); + // The state of each lives apart. + assert.equal(prep.prepStateDirOf(dir), path.join(dir, "out", "bench-excerpts")); + assert.equal(prep.prepStateDirOf(dir, "spin"), path.join(dir, "out", "bench-excerpts", "takes", "spin")); + assert.throws(() => prep.prepStateDirOf(dir, "../x"), /not a take id/); + await assert.rejects(prep.benchPrepPlan(project, null, { take: "nope" }), /no take nope/); +}); + +test("a take's failure is the take's: the cut's clip of the same id stays as it was", async () => { + await fresh(); + const r = await prep.runBenchPrep(project, { + take: "spin", + clips: ["kf3"], + analyse: async () => { + throw new Error("the take's kf3 would not decode"); + }, + }); + assert.deepEqual(r.failed, ["kf3"]); + const takeStatus = await prep.readPrepStatus(dir, "spin"); + assert.equal(takeStatus.failed.kf3.window, "vid_0.00-30.00.mp4"); + assert.match(takeStatus.failed.kf3.error, /would not decode/); + assert.equal(await prep.readPrepStatus(dir), null, "the cut's status file is not written"); + const cut = await prep.benchPrepPlan(project); + assert.equal(cut.items.find((i) => i.id === "kf3").state, "todo"); + const take = await prep.benchPrepState(project, { take: "spin" }); + assert.equal(take.take, "spin"); + assert.equal(take.items.find((i) => i.id === "kf3").state, "failed"); + // A take's runner is its own lock: the cut's is free while it holds the take's. + assert.equal(prep.tryLock(dir, "spin"), true); + assert.equal(prep.lockHolder(dir), null); + assert.equal(prep.lockHolder(dir, "spin"), process.pid); + prep.unlock(dir, "spin"); + assert.equal(prep.lockHolder(dir, "spin"), null); +}); + +test("queueing a take's prep writes the take's queue and starts the take's runner; the argv carries --take", async () => { + await fresh(); + const started = []; + const q = await prep.queueBenchPrep(project, null, { take: "spin", start: (p, o) => (started.push([p.id, o.take]), 4242) }); + assert.deepEqual(q, { queued: ["kf3", "ke1"], started: true, pid: 4242 }); + assert.deepEqual(started, [["folder/p", "spin"]]); + assert.ok(existsSync(path.join(dir, "out", "bench-excerpts", "takes", "spin", ".prep-pending"))); + assert.ok(!existsSync(path.join(dir, "out", "bench-excerpts", ".prep-pending")), "nothing in the cut's queue"); + assert.deepEqual(await prep.takePrepRequests(dir, "spin"), { clips: ["kf3", "ke1"], retry: false }); + const argv = prep.runnerArgv("folder/p", { take: "spin", has: () => false }); + assert.deepEqual(argv.slice(-5), ["prep", "folder/p", "--take", "spin", "--run"]); +}); + +test("a save on the take's walk queues the take's prep for that clip, never the cut's", async () => { + await fresh(); + const asked = []; + trigger.setBenchPrepQueue(async (p, clips, opts) => { + asked.push([p.id, clips, opts.take ?? null]); + }); + try { + await updateTakeClip(dir, "spin", "kf3", { end: 21 }); + await trigger.settleBenchPrepTriggers(); + } finally { + trigger.setBenchPrepQueue(null); + } + assert.deepEqual(asked, [["folder/p", ["kf3"], "spin"]]); + const doc = JSON.parse(await readFile(path.join(dir, "takes", "spin", "take.json"), "utf8")); + assert.equal(doc.patch.timeline[0].end, 21); + assert.equal(JSON.parse(await readFile(path.join(dir, "video.manifest.json"), "utf8")).timeline[0].end, 14); +}); + +test("the plan is the same from any working directory: the project's own, umtool's, the filesystem root", async () => { + await fresh(); + const probe = path.join(root, "probe.mjs"); + await writeFile( + probe, + `const p = await import(${JSON.stringify(new URL("./benchPrep.mjs", import.meta.url).href)});\n` + + `const r = await p.benchPrepPlan(${JSON.stringify(project)}, null, { take: process.argv[2] || null });\n` + + "console.log(JSON.stringify(r.items.map((i) => [i.id, i.state, i.window?.name ?? null])));\n", + ); + const env = { ...process.env, ...ENV }; + const runs = []; + for (const cwd of [dir, path.join(HERE, "..", ".."), "/"]) { + for (const take of ["", "spin"]) runs.push([cwd, take, execFileSync(process.execPath, [probe, take], { cwd, env, encoding: "utf8" }).trim()]); + } + for (const [cwd, take, got] of runs) { + assert.equal(got, take ? '[["kf3","todo","vid_0.00-30.00.mp4"],["ke1","todo","10.00-30.00.mp4"]]' : '[["kf3","todo","vid_0.00-30.00.mp4"],["kr1","todo","vs_0.00-10.00.mp4"]]', `from ${cwd}${take ? ` --take ${take}` : ""}`); + } +}); diff --git a/umtool/lib/report/benchPrepTrigger.mjs b/umtool/lib/report/benchPrepTrigger.mjs @@ -1,6 +1,7 @@ // The bench prep's TRIGGER: after a write that may need a new excerpt (a // window moved, a clip inserted, split, merged, duplicated, restored) and -// after a fetch lands, queue prep for the clips it touched (benchPrep.mjs). +// after a fetch lands, queue prep for the clips it touched (benchPrep.mjs) -- +// of the cut, or of a take (a write to its patch, a fetch for it). // // Never holds the writer: the writer has already written when this is called, // it returns at once, and the work -- a plan of a few stats, then at most a @@ -15,7 +16,7 @@ const inFlight = new Set(); /** - * @typedef {(project: { id: string, dir: string }, clips: string[] | null, opts: { excerptsOnly: boolean }) => Promise<unknown>} QueueFn + * @typedef {(project: { id: string, dir: string }, clips: string[] | null, opts: { excerptsOnly: boolean, take?: string | null }) => Promise<unknown>} QueueFn */ /** @type {QueueFn | null} a test's stand-in for queueBenchPrep */ let queueOverride = null; @@ -32,18 +33,22 @@ export function setBenchPrepQueue(fn) { * in a walk) starts a runner only when an excerpt is missing; a FETCH that * landed passes false, so the new windows' waveforms are made too. * + * `take`: a write to a TAKE's patch (its walk's save, `umtool window + * --take`), or a fetch for one -- the take's clips, queued for the take's + * own runner (benchPrep.mjs prepStateDirOf). + * * @param {string} dir the project directory (the manifest's) * @param {string[] | null} clips null: every clip - * @param {{ excerptsOnly?: boolean }} [opts] + * @param {{ excerptsOnly?: boolean, take?: string | null }} [opts] */ -export function benchPrepAfterWrite(dir, clips, { excerptsOnly = true } = {}) { +export function benchPrepAfterWrite(dir, clips, { excerptsOnly = true, take = null } = {}) { if (process.env.UMTOOL_BENCH_PREP === "0") return; const p = (async () => { const m = await import("./benchPrep.mjs"); const project = m.projectOfDir(dir); if (!project) return; const queue = queueOverride ?? m.queueBenchPrep; - await queue(project, clips, { excerptsOnly }); + await queue(project, clips, { excerptsOnly, ...(take ? { take } : {}) }); })().catch(() => { /* a trigger never fails a write */ }); diff --git a/umtool/lib/report/prepCli.mjs b/umtool/lib/report/prepCli.mjs @@ -4,6 +4,8 @@ // umtool prep <project> [--clips a,b] [--json] queue it; a runner starts in the background // umtool prep <project> [--clips a,b] --wait run it here and wait (the same runner, niced) // umtool prep <project> --status [--json] what is ready, what is not, the runner if one is alive +// … --take <id> a TAKE's clips (its walk's manifest -- a draft's too), +// its own status, queue and runner // // `--run` is the runner itself (what the queue starts): it takes the // project's run lock and drains the queue, one clip at a time, each in the @@ -25,6 +27,8 @@ export const PREP_USAGE = [ "usage: umtool prep <project> [--clips a,b] [--json] queue the clips' excerpts and waveforms for the walk; returns at once", " umtool prep <project> [--clips a,b] --wait the same, here, until it is done", " umtool prep <project> --status [--json] ready / to prepare / not fetched, and the runner", + " … --take <id> a take's clips instead of the cut's: the take's manifest as its walk reads it (a draft's", + " too, nothing rendered), its own status, queue and runner (out/bench-excerpts/takes/<id>/)", "", "One clip at a time, each in the heavy slot (estimate " + PREP_ESTIMATE_MB + " MB), under nice -n 19 and ionice -c3.", "A clip already prepared (its excerpt cut from its recording as it is now, its waveform cached) is skipped.", @@ -42,13 +46,14 @@ export function stateLine(s) { const cur = s.runner.current; parts.push(`preparing ${Math.min(s.runner.done + 1, s.runner.total)} of ${s.runner.total}${cur ? ` — ${cur.id}, ${cur.step === "waiting" ? "waiting for the heavy slot" : cur.step}` : ""} (pid ${s.runner.pid})`); } - return `${s.project}: ${parts.join(" · ")}`; + return `${s.project}${s.take ? ` take ${s.take}` : ""}: ${parts.join(" · ")}`; } const stamp = () => new Date().toISOString().slice(11, 19); /** The runner's progress as lines (stderr, and prep.log when it runs detached). */ export function eventLine(project, ev) { + if (ev.ev === "start" && ev.take) project = `${project} take ${ev.take}`; switch (ev.ev) { case "start": return `${stamp()} prep ${project}: ${ev.total} to prepare (${ev.ready} ready${ev.noWindow ? `, ${ev.noWindow} not fetched` : ""})`; @@ -76,10 +81,18 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons const json = args.includes("--json"); const words = []; let clips = null; + let take = null; for (let i = 0; i < args.length; i += 1) { if (args[i] === "--clips") { clips = String(args[i + 1] ?? "").split(",").map((s) => s.trim()).filter(Boolean); i += 1; + } else if (args[i] === "--take") { + take = String(args[i + 1] ?? ""); + i += 1; + if (!take || take.startsWith("--")) { + err(`--take needs a take id\n${PREP_USAGE}`); + return 2; + } } else if (!args[i].startsWith("--")) words.push(args[i]); } const [projectArg] = words; @@ -97,12 +110,23 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons return 1; } const project = { id: r.project.id, dir: r.project.dir }; + if (take) { + // The take must resolve (recorded, or named by a recipe), before anything is queued. + try { + const { prepManifestOf } = await import("./benchPrep.mjs"); + await prepManifestOf(project, take); + } catch (e) { + err(`${project.id}: ${e instanceof Error ? e.message : String(e)}`); + return 1; + } + } // ---- the runner ---------------------------------------------------------- if (args.includes("--run")) { const ndjson = args.includes("--ndjson"); const { withRenderSlot } = await import("../../report-to-video/heavy-gate.mjs"); const res = await drainPrepQueue(project, { + take, initial: args.includes("--wait") ? { clips, retry: args.includes("--retry") } : null, wait: args.includes("--wait"), slot: (cmd, fn) => withRenderSlot(cmd, fn, { estimateMb: PREP_ESTIMATE_MB }), @@ -115,7 +139,7 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons } if (args.includes("--status")) { - const s = await benchPrepState(project, { clips }); + const s = await benchPrepState(project, { clips, take }); if (json) out(JSON.stringify(s, null, 2)); else { out(stateLine(s)); @@ -126,7 +150,7 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons // ---- --wait: the runner, here -------------------------------------------- if (args.includes("--wait")) { - const argv = runnerArgv(project.id, { wait: true, clips, retry: true }); + const argv = runnerArgv(project.id, { wait: true, clips, retry: true, take }); const code = await new Promise((resolve) => { const child = spawn(argv[0], argv.slice(1), { cwd: UMTOOL_DIR, stdio: ["ignore", "inherit", "inherit"], env: process.env }); child.on("error", (e) => { @@ -135,20 +159,20 @@ export async function prepCommand(args, { root = REPORTS_ROOT, out = (s) => cons }); child.on("exit", (c, sig) => resolve(sig ? 1 : (c ?? 1))); }); - const s = await benchPrepState(project, { clips }); + const s = await benchPrepState(project, { clips, take }); if (json) out(JSON.stringify(s, null, 2)); else out(stateLine(s)); return Number(code) === 0 ? 0 : 1; } // ---- queue it -------------------------------------------------------------- - const q = await queueBenchPrep(project, clips, { retry: true }); - const s = await benchPrepState(project, { clips }); + const q = await queueBenchPrep(project, clips, { retry: true, take }); + const s = await benchPrepState(project, { clips, take }); if (json) out(JSON.stringify({ ...s, queued: q.queued, started: q.started, pid: q.pid, ...(q.off ? { off: true } : {}) }, null, 2)); else { out(stateLine(s)); if (q.off) out(" UMTOOL_BENCH_PREP=0: nothing queued"); - else if (q.queued.length) out(` queued ${q.queued.length}: ${q.started ? `runner started (pid ${q.pid})` : `the runner already going takes them (pid ${q.pid})`}; its log is out/bench-excerpts/prep.log`); + else if (q.queued.length) out(` queued ${q.queued.length}: ${q.started ? `runner started (pid ${q.pid})` : `the runner already going takes them (pid ${q.pid})`}; its log is out/bench-excerpts/${take ? `takes/${take}/` : ""}prep.log`); else out(" nothing to prepare"); } return 0; diff --git a/umtool/lib/report/takeEdit.mjs b/umtool/lib/report/takeEdit.mjs @@ -46,6 +46,7 @@ import { replaceManifest, } from "./manifest.mjs"; import { withEditNotes } from "./edit-guard.mjs"; +import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; import { resolveTakeManifest } from "./takeManifest.mjs"; import { isTakeId, listTakes, setTakePicked, takesDirOf, TAKE_FILE } from "./takes.mjs"; import { stampOf } from "./snapshots.mjs"; @@ -188,7 +189,7 @@ async function editTakeTimeline(projectDir, id, op, token, mutate, { now = new D */ export async function updateTakeClip(projectDir, id, clipId, patch, { token = null, edit = "trim", now = new Date() } = {}) { if (!isObj(patch)) throw new Error("a clip patch is an object"); - return editTakeTimeline( + const r = await editTakeTimeline( projectDir, id, edit === "trim" ? "clip" : edit, @@ -196,6 +197,9 @@ export async function updateTakeClip(projectDir, id, clipId, patch, { token = nu (m) => patchClipEntry(m, clipId, patch, { edit, now: now.toISOString(), dir: projectDir }), { now }, ); + // A moved extent may need a new bench excerpt -- the take's (its own prep): queued, never waited for. + if (r.entry?.start !== r.before?.start || r.entry?.end !== r.before?.end) benchPrepAfterWrite(projectDir, [clipId], { take: id }); + return r; } /**