Archilyzer · Source

archilyzer

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

commit 7fd0d20d9920a0fc0dcd8ecde6982fc2a239ff45
parent 59805728981e85986864608f60e228f2683e8ee9
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Thu, 29 Oct 2026 10:53:22 -0400

Merge lane/evict-video: evict-clips targets one video, named windows, covered spans; umtool fetch --refetch

Conflict: editor/CHANGELOG.md -- the lane's bullet added under the one
[Unreleased] heading, after the others.

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

Diffstat:
MAGENTS.md | 5++++-
MCOMMANDS.md | 2+-
Mcommon/controller/evictClipWindows.test.ts | 156++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mcommon/controller/evictClipWindows.ts | 181++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-------
Meditor/CHANGELOG.md | 1+
Aeditor/app/api/ops/evict-clips/route.test.ts | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Meditor/app/api/ops/evict-clips/route.ts | 54++++++++++++++++++++++++++++++++++--------------------
Meditor/app/storage/actions.ts | 45++++++++++++++++++++++++++++++++++++++++++---
Meditor/app/storage/lib/evictClipsJob.ts | 41++++++++++++++++++++++++++++++++++-------
Mscripts/archilyzer-ops.mjs | 7++++++-
Mumtool/bin/umtool.mjs | 6++++--
Mumtool/docs/cli.md | 2+-
Mumtool/docs/report-video.md | 13+++++++++++++
Mumtool/lib/report/fetchCli.mjs | 53+++++++++++++++++++++++++++++++++++++++++++++++++----
Mumtool/lib/report/fetchWindows.mjs | 94+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++--
Mumtool/lib/report/fetchWindows.test.mjs | 76++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
16 files changed, 766 insertions(+), 58 deletions(-)

diff --git a/AGENTS.md b/AGENTS.md @@ -401,7 +401,10 @@ Seven things that are not optional: - **`data/<id>/clips/` is a cache, on the SSD, never tiered, and `evictClipWindows` is the only thing that prunes it — BY AGE.** Nothing in the editor can know whether a umtool report still cites a window (the manifests are in a umtool project), so there is no reference count and every - surface says so. An evicted window is re-fetchable: the cost is a fetch, not data. + surface says so. An evicted window is re-fetchable: the cost is a fetch, not data. Its one + other form is TARGETED, for windows known bad: `evict-clips {slug, id}` takes one video's + windows, narrowed by `windows` (`<from>-<to>` names) or `covering` (`{from, to}` spans, + any window overlapping) — what `umtool fetch --refetch <clipId>` asks before it fetches. - **A media file in `data/<id>/` may be a relative symlink into `channels/<slug>/media/`. Remove one with `removeMediaFile`, never `rm`/`remove`; tier one with the hook after every media finalisation, never by hand; a dirent `isFile()` filter over a video dir diff --git a/COMMANDS.md b/COMMANDS.md @@ -141,7 +141,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run) | `build-homepage` | build-homepage builds the homepage package into homepage/out; {"deploy": true} deploys it after (only if the build succeeded), and deploy-homepage ships the one already built. Both deploy to the Pages project archilyzer (https://archilyzer.pages.dev), production unless "preview" is given. | | | `relocate` | relocate moves channels' media to a location: {"slugs", "locationId" \| "root"}. "dryRun": true answers each channel's preview (bytes to copy, free space both sides) and moves nothing — though, as on the Storage panel, a channel never tiered is first tiered in place on the corpus disk. | `pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter"}'`<br>`pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter","dryRun":true}'` | | `relocate-back` | relocate-back moves channels' media back onto the corpus disk, one job per channel on the relocation queue: {"slugs"}. A busy channel is answered in "skipped"; --wait follows the jobs started. | | -| `evict-clips` | evict-clips deletes cached clip windows (data/&lt;id&gt;/clips/) older than a number of days, as /storage's button does: {"olderThanDays", "slug"?, "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a window; an evicted window is fetched again when asked for. | | +| `evict-clips` | evict-clips deletes cached clip windows (data/&lt;id&gt;/clips/) older than a number of days, as /storage's button does: {"olderThanDays", "slug"?, "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a window; an evicted window is fetched again when asked for. TARGETED, for windows known bad: {"slug", "id"} evicts every window of that video; "windows": \["&lt;from&gt;-&lt;to&gt;", ...\] only those named, "covering": \[{"from", "to"}, ...\] any window overlapping a span (umtool fetch --refetch asks this way); "olderThanDays" is then optional, "dryRun" only lists. | `pnpm ops evict-clips --json '{"slug":"x","id":"abc123","covering":[{"from":10,"to":40}],"dryRun":true}' --wait` | | `check-windows` | check-windows probes cached clip windows (data/&lt;id&gt;/clips/) for a picture that runs off the sound (a Rumble HLS seek) and sets each desynced one aside as &lt;from&gt;-&lt;to&gt;.desynced.&lt;ext&gt; (never deleted; no reader sees it, and evict-clips ages it out): {"slug"?, "video"?, "dryRun"?}. "video" needs "slug"; "dryRun" only lists. A fetch then fills the span again, from the saved video first. | | | `reports-prepare` | reports-prepare cuts every clip and copies every post capture a site's published reports cite into its report-media cache, before its build: {"siteId"}. The job fails, naming each one, when a citation lacks media. When nothing is missing it then exports the reports, as reports-export. {"articles": true} does it for the published articles (transcripts/ reports/, the homepage's); {"article": "&lt;id&gt;"} adds that one (a draft). | `pnpm ops reports-prepare --json '{"siteId":"demo-site"}' --wait`<br>`pnpm ops reports-prepare --json '{"articles":true}' --wait` | | `reports-export` | reports-export writes each published report as report.html, report.pdf, report.md, slides.html, slides.pdf and evidence-pack.zip for the site's build to publish: {"siteId", "reportId"?, "formats"?: \["html","pdf","md", "slides","slides-pdf","zip"\]}; {"articles": true, "reportId"?, …} the articles' (reportId: one article, published or a draft). | `pnpm ops reports-export --json '{"siteId":"demo-site","formats":["html","md"]}' --wait` | diff --git a/common/controller/evictClipWindows.test.ts b/common/controller/evictClipWindows.test.ts @@ -11,7 +11,11 @@ import { } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; -import { evictClipWindows, evictClipWindowsSummary } from "./evictClipWindows"; +import { + evictClipWindows, + evictClipWindowsSummary, + parseEvictTargets, +} from "./evictClipWindows"; import type { Paths } from "../lib/paths"; // `clips/` had no garbage collection at all before this: the retention sweep is @@ -25,8 +29,9 @@ async function seed( paths: Paths, slug: string, windows: Record<string, { ageDays: number; size: number; sidecar?: boolean }>, + video = "v1", ): Promise<string> { - const clipsDir = path.join(paths.channelsDir, slug, "data", "v1", "clips"); + const clipsDir = path.join(paths.channelsDir, slug, "data", video, "clips"); await mkdir(clipsDir, { recursive: true }); for (const [name, spec] of Object.entries(windows)) { const file = path.join(clipsDir, name); @@ -297,3 +302,150 @@ test("a set-aside (desynced) window is cache too: it ages out with its own sidec assert.equal(await exists(path.join(clipsDir, "50.00-60.00.desynced.json")), true); }); }); + +// --------------------------------------------------------------------------- +// Targeted eviction: one video, named windows, covered spans. +// --------------------------------------------------------------------------- + +// Three windows in the bad video, one in its neighbour. All recent: a targeted +// run is not by age, and a recent window is exactly what a bad fetch leaves. +async function seedTwo(paths: Paths): Promise<{ bad: string; good: string }> { + const bad = await seed(paths, "alpha", { + "10.00-40.00.mp4": { ageDays: 0, size: 100 }, + "100.00-130.00.mp4": { ageDays: 0, size: 200 }, + "200.00-230.00.mp4": { ageDays: 0, size: 300 }, + "300.00-310.00.desynced.mp4": { ageDays: 0, size: 50 }, + }, "bad"); + await writeFile(path.join(bad, "notes.txt"), "not a window"); + const good = await seed(paths, "alpha", { + "10.00-40.00.mp4": { ageDays: 0, size: 400 }, + }, "good"); + return { bad, good }; +} + +test("targeted: {slug, id} evicts every window of that one video and nothing else", async () => { + await withTmp(async (paths) => { + const { bad, good } = await seedTwo(paths); + const r = await evictClipWindows({ paths, slug: "alpha", id: "bad" }); + assert.equal(r.windows, 4); + assert.equal(r.bytes, 650); + assert.equal(r.kept, 0); + assert.equal(r.videos, 1); + assert.equal(r.targeted, true); + for (const n of ["10.00-40.00", "100.00-130.00", "200.00-230.00"]) { + assert.equal(await exists(path.join(bad, `${n}.mp4`)), false, n); + assert.equal(await exists(path.join(bad, `${n}.json`)), false, n); + } + assert.equal(await exists(path.join(bad, "300.00-310.00.desynced.json")), false); + // Not a window, and not another video's window. + assert.equal(await exists(path.join(bad, "notes.txt")), true); + assert.equal(await exists(path.join(good, "10.00-40.00.mp4")), true); + assert.match(evictClipWindowsSummary(r), /0 other window\(s\)/); + }); +}); + +test("targeted: windows names the cache's own stems; an unknown one is said, not an error", async () => { + await withTmp(async (paths) => { + const { bad, good } = await seedTwo(paths); + const t = parseEvictTargets({ windows: ["100-130", "200.00-230.00.mp4", "500.00-510.00"] }); + assert.ok(t.ok); + const r = await evictClipWindows({ paths, slug: "alpha", id: "bad", windows: t.windows }); + assert.equal(r.windows, 2); + assert.equal(r.bytes, 500); + assert.equal(r.kept, 2); + assert.deepEqual(r.unmatched, ["500.00-510.00"]); + assert.equal(await exists(path.join(bad, "10.00-40.00.mp4")), true); + assert.equal(await exists(path.join(bad, "100.00-130.00.mp4")), false); + assert.equal(await exists(path.join(bad, "200.00-230.00.json")), false); + assert.equal(await exists(path.join(good, "10.00-40.00.mp4")), true); + assert.match(evictClipWindowsSummary(r), /Not cached: 500\.00-510\.00/); + }); +}); + +test("targeted: covering takes every window that OVERLAPS a span (a wider window too), never one that only touches it", async () => { + await withTmp(async (paths) => { + const { bad } = await seedTwo(paths); + const r = await evictClipWindows({ + paths, + slug: "alpha", + id: "bad", + // Inside 100-130 (the dedup would have served it from there); touching + // 230 exactly; overlapping the set-aside 300-310. + covering: [{ from: 105, to: 110 }, { from: 230, to: 240 }, { from: 305, to: 320 }], + }); + assert.equal(r.windows, 2); + assert.equal(await exists(path.join(bad, "100.00-130.00.mp4")), false); + assert.equal(await exists(path.join(bad, "300.00-310.00.desynced.mp4")), false); + assert.equal(await exists(path.join(bad, "200.00-230.00.mp4")), true); + assert.equal(await exists(path.join(bad, "10.00-40.00.mp4")), true); + }); +}); + +test("targeted: a dry run names the same windows and deletes nothing; an age still narrows", async () => { + await withTmp(async (paths) => { + const { bad } = await seedTwo(paths); + const logs: string[] = []; + const r = await evictClipWindows({ + paths, slug: "alpha", id: "bad", covering: [{ from: 0, to: 1000 }], dryRun: true, + onLog: (m) => logs.push(m), + }); + assert.equal(r.windows, 4); + assert.equal(logs.filter((l) => l.startsWith("would evict alpha/bad/")).length, 4); + assert.equal(await exists(path.join(bad, "10.00-40.00.mp4")), true); + const aged = await evictClipWindows({ paths, slug: "alpha", id: "bad", olderThanDays: 30 }); + assert.equal(aged.windows, 0); + assert.equal(aged.kept, 4); + }); +}); + +test("targeted: a video that does not exist is a skip that says so; a Twitch v<n> finds its dir", async () => { + await withTmp(async (paths) => { + await seedTwo(paths); + const r = await evictClipWindows({ paths, slug: "alpha", id: "nope" }); + assert.equal(r.windows, 0); + assert.match(r.skipped.join(" "), /alpha\/nope: no such video/); + const tw = await seed(paths, "tw", { "1.00-2.00.mp4": { ageDays: 0, size: 10 } }, "2912435200"); + await writeFile( + path.join(paths.channelsDir, "tw", "config.json"), + JSON.stringify({ url: "https://www.twitch.tv/someone/videos" }), + ); + const v = await evictClipWindows({ paths, slug: "tw", id: "v2912435200" }); + assert.equal(v.windows, 1); + assert.equal(await exists(path.join(tw, "1.00-2.00.mp4")), false); + }); +}); + +test("targeted: refusals — the shapes, and the combinations that would widen a target", async () => { + await withTmp(async (paths) => { + const { bad } = await seedTwo(paths); + const span = [{ from: 0, to: 1000 }]; + await assert.rejects(() => evictClipWindows({ paths, id: "bad" }), /give its slug too/); + await assert.rejects(() => evictClipWindows({ paths, slug: "alpha", covering: span, olderThanDays: 0 }), /give its id too/); + await assert.rejects(() => evictClipWindows({ paths, slug: "alpha" }), /olderThanDays is required/); + await assert.rejects(() => evictClipWindows({ paths, slug: "alpha", id: "../alpha" }), /one path segment/); + await assert.rejects(() => evictClipWindows({ paths, slug: "alpha", id: "bad", olderThanDays: -1 }), /finite number of days/); + assert.equal(await exists(path.join(bad, "10.00-40.00.mp4")), true); + + const refused: [Record<string, unknown>, RegExp][] = [ + [{ windows: [] }, /non-empty array/], + [{ windows: "10-40" }, /non-empty array/], + [{ windows: ["10-40", "forty"] }, /"forty", which is not a window name/], + [{ windows: ["40-10"] }, /not a window name/], + [{ windows: [{ from: 10, to: 40 }] }, /not a window name/], + [{ covering: [] }, /non-empty array/], + [{ covering: [{ from: 10 }] }, /not a \{"from", "to"\} span/], + [{ covering: [{ from: 10, to: 5 }] }, /not a \{"from", "to"\} span/], + [{ covering: [{ from: -1, to: 5 }] }, /not a \{"from", "to"\} span/], + [{ covering: [{ from: 1, to: 5, slug: "x" }] }, /no other keys/], + [{ covering: ["1-5"] }, /not a \{"from", "to"\} span/], + ]; + for (const [raw, re] of refused) { + const t = parseEvictTargets(raw); + assert.equal(t.ok, false, JSON.stringify(raw)); + if (!t.ok) assert.match(t.error, re, JSON.stringify(raw)); + } + const both = parseEvictTargets({ windows: ["10-40"], covering: [{ from: 1, to: 2 }] }); + assert.deepEqual(both, { ok: true, windows: [{ from: 10, to: 40 }], covering: [{ from: 1, to: 2 }] }); + assert.deepEqual(parseEvictTargets({}), { ok: true }); + }); +}); diff --git a/common/controller/evictClipWindows.ts b/common/controller/evictClipWindows.ts @@ -4,12 +4,16 @@ import type { Paths } from "../lib/paths"; import { CLIPS_DIR_NAME, clipWindowDesyncedSidecar, + clipWindowName, clipWindowSidecar, parseClipWindowName, parseDesyncedClipWindowName, } from "../lib/clipWindow"; import { inspectChannelMedia } from "../lib/channelMedia"; import { formatBytes } from "../lib/format"; +import { readChannelConfig } from "./channels"; +import { channelConfigPlatform } from "../lib/videoId"; +import { resolveVideoDirId } from "../lib/videoDir-server.mjs"; // THE GARBAGE COLLECTION `clips/` NEVER HAD. // @@ -39,15 +43,37 @@ import { formatBytes } from "../lib/format"; // un-evictable forever, which is exactly backwards: an orphan is the single // most evictable thing in the directory. `rsync -a` preserves mtimes, so a // relocated channel's windows carry their real ages across a move. +// +// TARGETED EVICTION, for the case age cannot express: a window known to be BAD +// (cut from a saved video that turned out corrupt) wants to go now, and only +// it. `{slug, id}` names one video and evicts every window of it; `windows` +// narrows to windows named `<from>-<to>` (the cache's own file stem), and +// `covering` to every window that OVERLAPS a span — for a caller (umtool) that +// knows a clip's extent, not the name of the file that happens to hold it. The +// fetch dedup takes any window CONTAINING its ask, so a span's bytes may sit in +// a wider window fetched for something else; overlap, not equality, is what +// reaches that one. Both lists together evict the union. `olderThanDays` is +// optional here and, when given, still has to pass too. A set-aside +// `<from>-<to>.desynced.<ext>` of a targeted span goes with it. + +export type ClipWindowSpan = { from: number; to: number }; export type EvictClipWindowsOptions = { paths: Paths; // One channel, or every channel when absent. slug?: string; + // One video of `slug` (a record id; a Twitch v<n> resolves to its dir, as + // check-windows does). Every window of it, unless `windows`/`covering` narrow. + id?: string; + // Windows named exactly (`<from>-<to>`, parsed): needs `id`. + windows?: ClipWindowSpan[]; + // Any window overlapping one of these spans: needs `id`. + covering?: ClipWindowSpan[]; // A window is evicted when it has not been touched for this many days. // 0 means "everything", which is a legitimate ask (the operator is emptying - // a drive) and is why this is not clamped to a minimum. - olderThanDays: number; + // a drive) and is why this is not clamped to a minimum. Required unless + // `id` is given; with `id`, absent means "whatever its age". + olderThanDays?: number; // Report what WOULD go, delete nothing. The /storage control previews with // this before it commits, so the number the operator reads is produced by // the same walk that does the work. @@ -64,9 +90,13 @@ export type EvictClipWindowsResult = { videos: number; windows: number; bytes: number; - // Windows left alone because they are newer than the cutoff. + // Windows left alone: newer than the cutoff, or (targeted) not targeted. kept: number; keptBytes: number; + // A targeted run (`id` given): `kept` is then "the rest of the video". + targeted: boolean; + // Names in `windows` that matched no cached window (nothing to evict there). + unmatched: string[]; // `<slug>: <reason>` for every channel the walk refused to touch. A skip is // not a failure — it is the answer — so it travels in the result rather than // throwing. @@ -110,16 +140,37 @@ async function evictChannel( const dataDir = path.join(channelDir, "data"); let videoIds: string[]; - try { - videoIds = await readdir(dataDir); - } catch { - // Past the guard above this really is "no videos": a channel whose text - // tier is on the corpus disk and whose `data/` has never been created. + if (opts.id) { + // ONE VIDEO. A video named that does not exist is said, not counted as a + // clean zero: an agent that typoed an id must not read "nothing to evict". + const config = await readChannelConfig(opts.paths, slug).catch(() => null); + const dirId = await resolveVideoDirId(opts.paths.channelsDir, slug, opts.id, { + ...(config ? { platform: channelConfigPlatform(config) } : {}), + }); + const isDir = await stat(path.join(dataDir, dirId)).then( + (s) => s.isDirectory(), + () => false, + ); + out.channels += 1; + if (!isDir) { + out.skipped.push(`${slug}/${opts.id}: no such video — nothing was touched`); + return; + } + videoIds = [dirId]; + } else { + try { + videoIds = await readdir(dataDir); + } catch { + // Past the guard above this really is "no videos": a channel whose text + // tier is on the corpus disk and whose `data/` has never been created. + out.channels += 1; + return; + } out.channels += 1; - return; } - out.channels += 1; + const named = opts.windows ?? []; + const matchedNames = new Set<number>(); for (const id of videoIds) { if (opts.signal?.aborted) return; const clipsDir = path.join(dataDir, id, CLIPS_DIR_NAME); @@ -152,6 +203,16 @@ async function evictChannel( } if (!st.isFile()) continue; sawWindow = true; + if (opts.windows || opts.covering) { + const hits = named.flatMap((w, i) => (sameSpan(w, span) ? [i] : [])); + for (const i of hits) matchedNames.add(i); + const covered = (opts.covering ?? []).some((c) => overlaps(c, span)); + if (!hits.length && !covered) { + out.kept += 1; + out.keptBytes += st.size; + continue; + } + } if (st.mtimeMs > cutoffMs) { out.kept += 1; out.keptBytes += st.size; @@ -184,6 +245,73 @@ async function evictChannel( // invisible to every video-dir enumerator anyway (FACTS: the predicates are // anchored, so a directory named `clips` matches none of them). } + named.forEach((w, i) => { + if (!matchedNames.has(i)) out.unmatched.push(spanName(w)); + }); +} + +// A NAME IS TWO DECIMALS (clipWindowName), so two spans are the same window +// when they agree to within half a hundredth — "10-40" names `10.00-40.00`. +const sameSpan = (a: ClipWindowSpan, b: ClipWindowSpan) => + Math.abs(a.from - b.from) < 0.005 && Math.abs(a.to - b.to) < 0.005; +// Strictly: a window that only touches a span's edge holds none of its seconds. +const overlaps = (a: ClipWindowSpan, b: ClipWindowSpan) => + a.from < b.to && b.from < a.to; +const spanName = (w: ClipWindowSpan) => clipWindowName(w.from, w.to); + +const isSpanObj = (v: unknown): v is ClipWindowSpan => { + if (!v || typeof v !== "object" || Array.isArray(v)) return false; + const r = v as Record<string, unknown>; + if (Object.keys(r).some((k) => k !== "from" && k !== "to")) return false; + return ( + typeof r.from === "number" && + typeof r.to === "number" && + Number.isFinite(r.from) && + Number.isFinite(r.to) && + r.from >= 0 && + r.to > r.from + ); +}; + +// THE TARGET LISTS OFF THE WIRE, parsed once, for the action (the ops route is +// an adapter and holds no rule). `windows` is a non-empty array of +// `"<from>-<to>"` strings — the cache's own file stem, as a listing or a log +// line shows it (an `.mp4` on the end is tolerated); `covering` a non-empty +// array of `{from, to}` seconds. Anything else is refused with a sentence. +export function parseEvictTargets(raw: { + windows?: unknown; + covering?: unknown; +}): + | { ok: true; windows?: ClipWindowSpan[]; covering?: ClipWindowSpan[] } + | { ok: false; error: string } { + const out: { windows?: ClipWindowSpan[]; covering?: ClipWindowSpan[] } = {}; + if (raw.windows !== undefined) { + const v = raw.windows; + if (!Array.isArray(v) || v.length === 0) { + return { ok: false, error: '"windows" must be a non-empty array of "<from>-<to>" names (e.g. "1992.68-2013.56")' }; + } + const spans: ClipWindowSpan[] = []; + for (const name of v) { + const span = typeof name === "string" ? parseClipWindowName(name.trim()) : null; + if (!span) { + return { ok: false, error: `"windows" holds ${JSON.stringify(name)}, which is not a window name "<from>-<to>" (seconds, from < to)` }; + } + spans.push(span); + } + out.windows = spans; + } + if (raw.covering !== undefined) { + const v = raw.covering; + if (!Array.isArray(v) || v.length === 0) { + return { ok: false, error: '"covering" must be a non-empty array of {"from", "to"} spans in seconds' }; + } + const bad = v.find((s) => !isSpanObj(s)); + if (bad !== undefined) { + return { ok: false, error: `"covering" holds ${JSON.stringify(bad)}, which is not a {"from", "to"} span (seconds, 0 <= from < to, no other keys)` }; + } + out.covering = v as ClipWindowSpan[]; + } + return { ok: true, ...out }; } export async function evictClipWindows( @@ -197,6 +325,8 @@ export async function evictClipWindows( bytes: 0, kept: 0, keptBytes: 0, + targeted: Boolean(opts.id), + unmatched: [], skipped: [], }; // REFUSED, NOT CLAMPED, and NaN is why. `Math.max(0, NaN)` is NaN, the cutoff @@ -204,14 +334,36 @@ export async function evictClipWindows( // number would not have evicted nothing, it would have evicted EVERYTHING. // The action validates too, but this function is exported and the failure // mode is silent and total. - if (!Number.isFinite(opts.olderThanDays) || opts.olderThanDays < 0) { + // A video is named within a channel, and a window within a video: a + // target list with no video would otherwise widen to the corpus. + if (opts.id && !opts.slug) { + throw new Error("a video is named within a channel: give its slug too"); + } + // One path segment: the id is joined under `data/` before a walk that + // deletes, and the action checks it too — this function is exported. + if (opts.id !== undefined && (opts.id === "" || opts.id === "." || opts.id === ".." || /[/\\\0]/.test(opts.id))) { + throw new Error(`"${opts.id}" is not a video id (one path segment)`); + } + if ((opts.windows || opts.covering) && !opts.id) { + throw new Error('"windows" and "covering" name windows of one video: give its id too'); + } + // Untargeted, the age is the whole rule and has to be said. + if (opts.olderThanDays === undefined && !opts.id) { + throw new Error("olderThanDays is required unless one video (slug + id) is named"); + } + if ( + opts.olderThanDays !== undefined && + (!Number.isFinite(opts.olderThanDays) || opts.olderThanDays < 0) + ) { throw new Error( `olderThanDays must be a finite number of days, zero or more ` + `(got ${String(opts.olderThanDays)})`, ); } - const days = opts.olderThanDays; - const cutoffMs = Date.now() - days * DAY_MS; + const cutoffMs = + opts.olderThanDays === undefined + ? Number.POSITIVE_INFINITY + : Date.now() - opts.olderThanDays * DAY_MS; let slugs: string[]; if (opts.slug) { @@ -244,7 +396,8 @@ export function evictClipWindowsSummary(r: EvictClipWindowsResult): string { : `Evicted ${r.windows} window(s), ${formatBytes(r.bytes)}`; return ( `${head} across ${r.videos} video(s) in ${r.channels} channel(s); ` + - `${r.kept} newer window(s) (${formatBytes(r.keptBytes)}) left alone.` + + `${r.kept} ${r.targeted ? "other" : "newer"} window(s) (${formatBytes(r.keptBytes)}) left alone.` + + (r.unmatched.length ? ` Not cached: ${r.unmatched.join(", ")}.` : "") + (r.skipped.length ? ` Skipped: ${r.skipped.join("; ")}` : "") ); } diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -8,6 +8,7 @@ - **A site build can now run beside a report-video render when there is memory for both.** A render declared nothing to the machine's heavy slot, so it always ran alone: a site build started while a take rendered waited out the whole render (an hour or more for a full cut). A render now says how much memory it will need — measured on the Huck cut: about 6 GB for a whole cut (its widest step, a crossfade over 23 clips at once, peaked at 4.9 GB), about 2.4 GB for a short take of part of a cut, more with more `UMTOOL_CHROME_WORKERS` — and the encode ladder (`umtool variants`) about 1 GB. A capped site build (one run under `systemd-run … -p MemoryMax=5G`) is let in beside it while the memory left after the render's share stays at or above the 6000 MB floor, and waits for it otherwise. On this 16 GB machine that is often for a short take and rare for a whole cut. A publish stage's own build is not capped, so it still waits for the render as before. `UMTOOL_RENDER_ESTIMATE_MB` / `UMTOOL_LADDER_ESTIMATE_MB` set the share by hand, and `0` makes a render run alone again. Start a take or a build-video run as it is, not under `pnpm heavy --`, which makes it run alone. Needs a restart of umtool for takes made from the app (the `umtool take` command has it now). - **Report-video takes no longer keep their build work forever.** On 2026-10-27 /home reached 100 % (5.4 GB free of 1.5 TB), and 131 GB of it was takes' build work: each full take's chrome frames (about 12 GB for the 34-minute Huck cut, kept with `--keep-frames` so a `--from` twin can reuse them), its crossfade batches and its clip segments, swept by hand. `umtool prune <project>` (or `--all`) now lists each take's work files — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — and what freeing them gives back, or why the take keeps them: a build running in it or from it (never freed), the picked take, the take the project's manifest is, a pin in `takes/prune.json`, the newest 2 of its group, anything modified in the last 3 days, and the `--from` bases of those. It is a dry run unless `--yes`. Files hard-linked between takes are counted once, and freed only when every take holding them lets them go, so the numbers are what the disk gets back, not a sum of `du`s. The renders, previews, take.json and manifests are never touched, and nothing is followed out of a take through a link. The Takes page says each take's work and why it is kept, with **Free work files** per take and for the project (the plan first, then **Free them**). A take that finishes building now prunes its project by the same rules and says what it freed in its log, and a render that starts with under 30 GB free does the same across every project, and refuses to start under 10 GB with a sentence saying so. `--keep`, `--older-than`, `takes/prune.json` and `UMTOOL_PRUNE_*` / `UMTOOL_DISK_GUARD*` change the rules or turn them off. A dry run over ~/reports on 2026-10-27, after the hand sweep: 27 GiB of work in 32 projects' takes, 4.0 GiB of it free to go (2.4 GiB in the Huck project, whose last three days of takes are all kept). Needs a restart of umtool for the Takes page and for takes made from it; the CLI has it at once. - **The changelog page opens with its Cut and Amend forms, and pages its notes; the latest release can be amended.** `/changelog` rendered the whole of `editor/CHANGELOG.md` (760 KB of markdown, a 2.9 MB response) before the Cut release form at its bottom, so the form took 1 s to appear on an idle machine and 5-10 s on a busy one. The forms now come first (the Cut release button shows in about 0.35 s where it took 1 s) and the notes stream in after them a page at a time (`?page=N`: whole releases up to about 96 KB a page, `[Unreleased]` always on page 1, an index of every release under **All releases**); a link to an older release's anchor (`/changelog#2026-09-26`, or the new per-release `#v0.9.0`) goes to the page that holds it. **Amend the latest release** re-picks its bump (patch, minor or major, counted from the release before it), its date, folds the notes now under `[Unreleased]` into it, or moves it back under `[Unreleased]`; only the newest release, and a version change commits as that version's release (`Release editor 0.12.0`, the amend in the body). The same writer is `pnpm ops amend-release` and `archilyzer release amend`; `/sites` has the form for the export changelog. +- **Bad clip windows of one video can be evicted, and nothing else.** `evict-clips` only evicted by age, a channel at most, so the four windows cut from a corrupt saved video could not be removed without emptying the channel's cache. `pnpm ops evict-clips --json '{"slug": "<slug>", "id": "<video>"}'` now evicts every cached window of that one video; `"windows": ["<from>-<to>", …]` (the cache's own names) narrows it to those, and `"covering": [{"from": s, "to": s}, …]` to every window that overlaps a span, a wider window holding it included. A set-aside `.desynced` window of a targeted span goes with it, `"dryRun": true` only lists, and `"olderThanDays"` is optional here (still required for the by-age form). A video that does not exist is said in the run's summary, as is a named window that is not cached; an unknown shape is refused by name. umtool asks for it: `umtool fetch <project> --refetch <clipId>[,<clipId>…]` evicts the windows overlapping those clips' fetch spans, waits for that, then fetches as usual (`--refetch-video <slug>/<id>` for every window the project asks of a video; `--dry-run` evicts nothing), and records what went in `fetch-runs.json`. Needs a restart of the editor. ## [0.11.1] - 2026-10-28 - **An X post's screenshot is of the post, not of a page in the middle of laying itself out.** On 2026-10-27 a forced capture of TheQuartering's post 2114859155022389342 came out shifted about 100 px: its left edge cut off, X's menu laid over its words and the gap beside the column showing; another post once came out as a strip of the post above it. The shot was a full-page capture, which resizes the page for the moment of the capture — in the X session profile the page saw its window go to 1×1 — and X laid itself out again for that size while it was being captured, so the shot was cut from a different layout than the one measured. A post is now shot from the window as it stands: scrolled into it, the window made taller first when the post is taller than it, so nothing is resized under the shot; and the post is measured again after the shot and shot again if it moved. An X Article's shot is taken the same way. Posts taller than the tallest window (16,384 px) are still shot from a full-page capture. Needs a restart of the editor. diff --git a/editor/app/api/ops/evict-clips/route.test.ts b/editor/app/api/ops/evict-clips/route.test.ts @@ -0,0 +1,88 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { mkdir, stat, writeFile } from "node:fs/promises"; +import path from "node:path"; +import { setupOpsCorpus, callPost } from "../_testCorpus"; + +// Run with: +// pnpm -C editor exec tsx --test "app/api/ops/evict-clips/route.test.ts" +// +// Targeted eviction (controller/evictClipWindows.ts): `{slug, id}` evicts one +// video's windows, `windows`/`covering` narrow them; the by-age form still +// needs its age. Refusals answer 400 before any job. + +const corpus = await setupOpsCorpus(null); +await corpus.writeChannelConfig("demo-yt", { url: "https://www.youtube.com/@demo" }); +const DATA = path.join(corpus.transcripts, "channels", "demo-yt", "data"); +async function window(id: string, name: string) { + const dir = path.join(DATA, id, "clips"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, `${name}.mp4`), Buffer.alloc(64)); + await writeFile(path.join(dir, `${name}.json`), JSON.stringify({ requestedBy: "umtool" })); +} +await window("vid00000001", "10.00-40.00"); +await window("vid00000001", "100.00-130.00"); +await window("vid00000001", "200.00-230.00"); +await window("vid00000002", "10.00-40.00"); + +const { POST } = await import("./route"); +const { getRegistry } = await import("yt-dlp-transcript-common/jobs/registry"); +test.after(() => corpus.cleanup()); +const exists = (p: string) => stat(p).then(() => true, () => false); +const clip = (id: string, name: string) => path.join(DATA, id, "clips", name); + +async function settle(jobId: string): Promise<string | undefined> { + for (let i = 0; i < 200; i++) { + const s = getRegistry().get(jobId)?.status; + if (s === "done" || s === "failed") return s; + await new Promise((res) => setTimeout(res, 50)); + } + return getRegistry().get(jobId)?.status; +} + +test("evict-clips refusals: the shapes, the combinations, nothing queued", async () => { + const before = await corpus.listJobIds(); + const cases: [Record<string, unknown>, RegExp][] = [ + [{ slug: "demo-yt", video: "vid00000001" }, /unknown key\(s\): video/], + [{ slug: "demo-yt" }, /olderThanDays\) is required unless one video/], + [{ id: "vid00000001" }, /give its slug too/], + [{ slug: "demo-yt", covering: [{ from: 1, to: 2 }], olderThanDays: 0 }, /give its "slug" and "id" too/], + [{ slug: "demo-yt", id: "../x" }, /not a video id/], + [{ slug: "no-such", id: "vid00000001" }, /Channel "no-such" not found/], + [{ slug: "demo-yt", id: "vid00000001", windows: ["ten-forty"] }, /not a window name/], + [{ slug: "demo-yt", id: "vid00000001", windows: [] }, /non-empty array/], + [{ slug: "demo-yt", id: "vid00000001", covering: [{ from: 5, to: 1 }] }, /not a \{"from", "to"\} span/], + [{ slug: "demo-yt", id: "vid00000001", olderThanDays: "old" }, /number of days/], + ]; + for (const [body, re] of cases) { + const r = await callPost(POST, body); + assert.equal(r.status, 400, JSON.stringify(body)); + assert.match(r.body.error ?? "", re, JSON.stringify(body)); + } + assert.deepEqual(await corpus.listJobIds(), before); +}); + +test("evict-clips {slug, id, covering}: the overlapping windows of that video go; a dry run first deletes nothing", async () => { + const body = { slug: "demo-yt", id: "vid00000001", covering: [{ from: 20, to: 25 }, { from: 110, to: 140 }] }; + const dry = await callPost(POST, { ...body, dryRun: true }); + assert.equal(dry.status, 200, JSON.stringify(dry.body)); + assert.equal(await settle(dry.body.jobId as string), "done"); + assert.equal(await exists(clip("vid00000001", "10.00-40.00.mp4")), true); + + const r = await callPost(POST, body); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(await settle(r.body.jobId as string), "done"); + assert.equal(await exists(clip("vid00000001", "10.00-40.00.mp4")), false); + assert.equal(await exists(clip("vid00000001", "10.00-40.00.json")), false); + assert.equal(await exists(clip("vid00000001", "100.00-130.00.mp4")), false); + assert.equal(await exists(clip("vid00000001", "200.00-230.00.mp4")), true); + assert.equal(await exists(clip("vid00000002", "10.00-40.00.mp4")), true); +}); + +test("evict-clips {slug, id, windows}: the named window only", async () => { + const r = await callPost(POST, { slug: "demo-yt", id: "vid00000001", windows: ["200-230"] }); + assert.equal(r.status, 200, JSON.stringify(r.body)); + assert.equal(await settle(r.body.jobId as string), "done"); + assert.equal(await exists(clip("vid00000001", "200.00-230.00.mp4")), false); + assert.equal(await exists(clip("vid00000002", "10.00-40.00.mp4")), true); +}); diff --git a/editor/app/api/ops/evict-clips/route.ts b/editor/app/api/ops/evict-clips/route.ts @@ -1,31 +1,45 @@ import { evictClipWindowsAction } from "../../../storage/actions"; -import { jobResponse, ops, optBool, optString } from "../_lib"; +import { jobResponse, ops, optBool, optString, reqVideoId } from "../_lib"; export const dynamic = "force-dynamic"; // POST { olderThanDays: number, slug?: string, dryRun?: boolean } +// | { slug: string, id: string, windows?: ["<from>-<to>", …], +// covering?: [{from, to}, …], olderThanDays?: number, dryRun?: boolean } // -> { ok: true, jobId } // // AN ADAPTER, like every route here: one call to the action the /storage button -// posts. `olderThanDays` is required on purpose — there is no sensible default -// for a control that deletes, and a route that picked one would be a rule the -// UI does not have. +// posts. `olderThanDays` is required for a by-age run on purpose — there is no +// sensible default for a control that deletes, and a route that picked one +// would be a rule the UI does not have. // -// Eviction is BY AGE. Nothing in the editor can know whether a umtool report -// still cites a window, so a caller automating this should say so wherever it -// reports the result — see controller/evictClipWindows.ts. +// By age, nothing in the editor can know whether a umtool report still cites a +// window, so a caller automating this should say so wherever it reports the +// result — see controller/evictClipWindows.ts. TARGETED (`slug` + `id`), the +// caller knows which windows are bad: every window of that video, or those +// named in `windows` (the cache's `<from>-<to>` stems), or any overlapping a +// `covering` span — the form `umtool fetch --refetch` asks with. export async function POST(request: Request) { - return ops(request, ["olderThanDays", "slug", "dryRun"], async (body) => { - const raw = body.olderThanDays; - const olderThanDays = typeof raw === "number" ? raw : Number.NaN; - const slug = optString(body, "slug"); - const dryRun = optBool(body, "dryRun"); - return jobResponse( - await evictClipWindowsAction({ - ...(slug ? { slug } : {}), - olderThanDays, - ...(dryRun ? { dryRun: true } : {}), - }), - ); - }); + return ops( + request, + ["olderThanDays", "slug", "id", "windows", "covering", "dryRun"], + async (body) => { + const raw = body.olderThanDays; + const olderThanDays = + raw === undefined ? undefined : typeof raw === "number" ? raw : Number.NaN; + const slug = optString(body, "slug"); + const id = body.id === undefined ? undefined : reqVideoId(body, "id"); + const dryRun = optBool(body, "dryRun"); + return jobResponse( + await evictClipWindowsAction({ + ...(slug ? { slug } : {}), + ...(id ? { id } : {}), + ...(body.windows !== undefined ? { windows: body.windows } : {}), + ...(body.covering !== undefined ? { covering: body.covering } : {}), + ...(olderThanDays !== undefined ? { olderThanDays } : {}), + ...(dryRun ? { dryRun: true } : {}), + }), + ); + }, + ); } diff --git a/editor/app/storage/actions.ts b/editor/app/storage/actions.ts @@ -32,6 +32,7 @@ import { channelMediaBusyReason } from "../channels/lib/mediaBusy"; import { enqueueRepointJob } from "./lib/repointJob"; import { enqueueSavedVideosRelocation } from "./lib/savedVideosJob"; import { enqueueEvictClipWindows } from "./lib/evictClipsJob"; +import { parseEvictTargets } from "yt-dlp-transcript-common/controller/evictClipWindows"; import { enqueueCheckClipWindows } from "./lib/checkWindowsJob"; import { savedVideosStoreBusyReason } from "./lib/storeBusy"; import { refreshLocationHealth } from "yt-dlp-transcript-common/controller/storageWatch"; @@ -458,10 +459,35 @@ export async function clearSavedVideosMarkerAction(): Promise<LocationResult> { // A second opinion in an action is the thing the ops API's header warns about. export async function evictClipWindowsAction(opts: { slug?: string; - olderThanDays: number; + // One video of `slug`: every window of it, or those `windows`/`covering` + // name (controller/evictClipWindows.ts, "TARGETED EVICTION"). + id?: string; + windows?: unknown; + covering?: unknown; + olderThanDays?: number; dryRun?: boolean; }): Promise<StreamActionResult> { - if (!Number.isFinite(opts.olderThanDays) || opts.olderThanDays < 0) { + if (opts.id !== undefined && opts.slug === undefined) { + return { ok: false, error: "A video is named within a channel: give its slug too." }; + } + if ((opts.windows !== undefined || opts.covering !== undefined) && opts.id === undefined) { + return { + ok: false, + error: '"windows" and "covering" name windows of one video: give its "slug" and "id" too.', + }; + } + // The age is the whole rule of an untargeted run, so it is required there; + // a targeted one may still narrow by it. + if (opts.olderThanDays === undefined && opts.id === undefined) { + return { + ok: false, + error: "The age (olderThanDays) is required unless one video (slug + id) is named.", + }; + } + if ( + opts.olderThanDays !== undefined && + (!Number.isFinite(opts.olderThanDays) || opts.olderThanDays < 0) + ) { return { ok: false, error: "The age must be a number of days, zero or more.", @@ -482,9 +508,22 @@ export async function evictClipWindowsAction(opts: { return { ok: false, error: `Channel "${opts.slug}" not found` }; } } + if ( + opts.id !== undefined && + (opts.id === "" || opts.id === "." || opts.id === ".." || /[/\\\0]/.test(opts.id)) + ) { + return { ok: false, error: `"${opts.id}" is not a video id (one path segment)` }; + } + const targets = parseEvictTargets({ windows: opts.windows, covering: opts.covering }); + if (!targets.ok) return { ok: false, error: targets.error }; return enqueueEvictClipWindows({ ...(opts.slug ? { slug: opts.slug } : {}), - olderThanDays: Math.floor(opts.olderThanDays), + ...(opts.id ? { id: opts.id } : {}), + ...(targets.windows ? { windows: targets.windows } : {}), + ...(targets.covering ? { covering: targets.covering } : {}), + ...(opts.olderThanDays !== undefined + ? { olderThanDays: Math.floor(opts.olderThanDays) } + : {}), ...(opts.dryRun ? { dryRun: true } : {}), }); } diff --git a/editor/app/storage/lib/evictClipsJob.ts b/editor/app/storage/lib/evictClipsJob.ts @@ -7,7 +7,9 @@ import { import { evictClipWindows, evictClipWindowsSummary, + type ClipWindowSpan, } from "yt-dlp-transcript-common/controller/evictClipWindows"; +import { clipWindowName } from "yt-dlp-transcript-common/lib/clipWindow"; // ONE ENQUEUE OF THE CLIP-WINDOW EVICTION, for the callers that have one: the // control on /storage and the `/api/ops/evict-clips` adapter. @@ -29,9 +31,13 @@ import { // channel behind itself. export async function enqueueEvictClipWindows(opts: { slug?: string; - olderThanDays: number; + id?: string; + windows?: ClipWindowSpan[]; + covering?: ClipWindowSpan[]; + olderThanDays?: number; dryRun?: boolean; }): Promise<StreamActionResult> { + const spans = (l: ClipWindowSpan[]) => l.map((w) => clipWindowName(w.from, w.to)).join(", "); const paths = getPaths(); return runManagedFunction({ kind: "evict-clips", @@ -40,8 +46,24 @@ export async function enqueueEvictClipWindows(opts: { queueKey: "", paths, ...(opts.slug ? { channelSlug: opts.slug } : {}), + ...(opts.slug && opts.id ? { videoId: opts.id } : {}), fn: async (onLog, signal) => { - onLog( + // TARGETED (one video): the caller knows these windows are bad, so the + // age is not the rule and the log says what was asked for instead. + if (opts.id) { + onLog( + `${opts.dryRun ? "Previewing" : "Evicting"} clip windows of ` + + `${opts.slug}/${opts.id}` + + (opts.windows ? ` named ${spans(opts.windows)}` : "") + + (opts.windows && opts.covering ? " or" : "") + + (opts.covering ? ` overlapping ${spans(opts.covering)}` : "") + + (!opts.windows && !opts.covering ? " (every one)" : "") + + (opts.olderThanDays !== undefined + ? `, not touched for ${opts.olderThanDays} day(s)` + : "") + + ". An evicted window is re-fetchable; it costs a fetch, not data.", + ); + } else onLog( `${opts.dryRun ? "Previewing" : "Evicting"} clip windows ` + `${opts.slug ? `in ${opts.slug}` : "across every channel"} ` + `not touched for ${opts.olderThanDays} day(s).`, @@ -50,14 +72,19 @@ export async function enqueueEvictClipWindows(opts: { // window a umtool report still cites is indistinguishable from one // nothing wants — the manifests live in a umtool project the editor // cannot see — so eviction is by age and the record says so. - onLog( - "By age only: nothing here can know whether a report still cites a " + - "window. An evicted one is re-fetchable; it costs a fetch, not data.", - ); + if (!opts.id) { + onLog( + "By age only: nothing here can know whether a report still cites a " + + "window. An evicted one is re-fetchable; it costs a fetch, not data.", + ); + } const result = await evictClipWindows({ paths, ...(opts.slug ? { slug: opts.slug } : {}), - olderThanDays: opts.olderThanDays, + ...(opts.id ? { id: opts.id } : {}), + ...(opts.windows ? { windows: opts.windows } : {}), + ...(opts.covering ? { covering: opts.covering } : {}), + ...(opts.olderThanDays !== undefined ? { olderThanDays: opts.olderThanDays } : {}), ...(opts.dryRun ? { dryRun: true } : {}), onLog, signal, diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs @@ -86,6 +86,7 @@ // pnpm ops refresh-report --json '{"all":true}' // pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter"}' // pnpm ops relocate --json '{"slugs":["x"],"locationId":"platter","dryRun":true}' +// pnpm ops evict-clips --json '{"slug":"x","id":"abc123","covering":[{"from":10,"to":40}],"dryRun":true}' --wait // pnpm ops settings --json '{"patch":{"minFreeDiskGB":20}}' // pnpm ops lane --json '{"lane":"publish","action":"drain"}' // pnpm ops cleanup --json '{"slug":"x","sweep":"transcribed"}' --wait @@ -1255,7 +1256,11 @@ export function usage() { 'evict-clips deletes cached clip windows (data/<id>/clips/) older than a', ' number of days, as /storage\'s button does: {"olderThanDays", "slug"?,', ' "dryRun"?}. BY AGE: nothing knows whether a umtool report still cites a', - " window; an evicted window is fetched again when asked for.", + " window; an evicted window is fetched again when asked for. TARGETED, for", + ' windows known bad: {"slug", "id"} evicts every window of that video;', + ' "windows": ["<from>-<to>", ...] only those named, "covering": [{"from",', + ' "to"}, ...] any window overlapping a span (umtool fetch --refetch asks', + ' this way); "olderThanDays" is then optional, "dryRun" only lists.', "", 'check-windows probes cached clip windows (data/<id>/clips/) for a picture', ' that runs off the sound (a Rumble HLS seek) and sets each desynced one', diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs @@ -69,7 +69,8 @@ // umtool rulings <project> [import [--dry-run] | set <clip> <verdict> [--reason R] [--match M] | clear <clip>] // the clip deck's montage rulings (release 34) // umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] the clip windows, asked of -// the editor as one fetch-windows batch (release 35) +// the editor as one fetch-windows batch (release 35); [--refetch <clipId>,… | --refetch-video +// <slug>/<id>] evicts those cached windows first // umtool prep <project> [--clips a,b] [--wait | --status] [--json] the bench's excerpts and waveforms, // made before the walk (one clip at a time, in the heavy slot) // umtool prune [<project> [--take X] [--anyway] | --all] [--keep N] [--older-than 3d] [--yes] [--json] @@ -807,7 +808,8 @@ function usage() { " the clip deck's montage rulings (montage-rulings.json); a render leaves the ruled-out clips out", " umtool fetch <project> [--dry-run | --wait | --status | --body] [--reason R] [--json]", " the clip windows asked of the editor as one fetch-windows batch (one paced job per platform);", - " each run recorded in <project>/fetch-runs.json", + " each run recorded in <project>/fetch-runs.json; --refetch <clipId>[,…] / --refetch-video <slug>/<id>", + " evict those clips' cached windows first (the editor's evict-clips), then fetch", " umtool prep <project> [--clips a,b] [--wait | --status] [--json]", " what the clip bench makes on a clip's first open (a long recording's excerpt, the waveform),", " made before the walk: queued and run in the background, one clip at a time, in the heavy slot", diff --git a/umtool/docs/cli.md b/umtool/docs/cli.md @@ -52,7 +52,7 @@ Inbox cannot disagree about what is wrong with one. | `takes styles [--json]` · `takes effects <project> [--json]` · `takes pick <project> <take> [--anyway] [--json]` | the montage styles; the overlay effects the cut offers (`render.chrome.fx` presets: the Takes page's **Effect** list); **Use this take** — refused (exit 1) when the project changed since the take was made, until `--anyway` | | `trailer <project> --take <t> (--beats FILE \| --beats-json JSON) [--intro] [--finale S] [--xfade 0.3] [--out NAME] [--dry-run] [--json]` | a **trailer cut from the take's finished master**: spans of the master's own frames (the deck shows the whole timeline), clip beats in source seconds mapped by the take's build records, crossfaded, the take's encode, in the heavy slot; writes `takes/<t>/out/<slug>.trailer.mp4` and `.trailer.json`; **exit 1** on a refusal ([report-video.md](report-video.md#trailer-from-the-master)) | | `rulings <project> [--json]` · `rulings <project> import [--dry-run] [--json]` · `rulings <project> set <clip\|key> keep\|cut\|not-him\|read-aloud [--reason R] [--match M]` · `rulings <project> clear <clip\|key>` | a montage's **clip rulings** (`montage-rulings.json`, the clip deck's): each clip and its ruling and the next render's kept clips; the earlier rulings in the seed's `edits.json`, once; one ruling set or cleared. A render leaves out every clip ruled cut, not-him or read-aloud ([report-video.md](report-video.md#ruling-the-clips)) | -| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. Every run is recorded in `<project>/fetch-runs.json`. Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | +| `fetch <project> --body` · `fetch <project> --dry-run [--json]` · `fetch <project> [--wait] [--json]` · `fetch <project> --status [--json]` · `… [--reason R]` · `… --refetch <clipId>[,…]` · `… --refetch-video <slug>/<id>` | **Fetch windows** (the Cut tab's and the clip deck's button): every clip's window asked of the editor as ONE fetch-windows batch — `--body` prints the body and asks nobody; `--dry-run` the editor's plan (groups per platform, cached, in flight, unresolved); no flag starts it (one paced job per platform queue), `--wait` follows the jobs to their end and names each window a job failed; `--status` follows the last run's jobs once. Clips the montage rulings leave out are not asked for. `--refetch <clipId>[,<clipId>…]` evicts the cached windows that OVERLAP those clips' fetch spans first (the editor's `evict-clips` `{slug, id, covering}`, one job per video, waited for), then fetches as usual — for windows known bad (cut from a corrupt saved video); `--refetch-video <slug>/<id>` does it for every window the project asks of that video; with `--dry-run` the eviction is a dry run too and names what it would remove. Every run is recorded in `<project>/fetch-runs.json` (a refetch's evictions under `refetch`). Needs WORKER_TOKEN (else the editor's env files) and the editor at ARCHILYZER_EDITOR_URL. **Exit 1** when a job failed or the editor refused ([report-video.md](report-video.md#fetching-the-windows-and-stand-ins)) | | `prep <project> [--clips a,b] [--json]` · `prep <project> [--clips a,b] --wait` · `prep <project> --status [--json]` | **Prepare clips for the walk** (the Cut tab's): what the clip bench makes on a clip's first open — a long recording's excerpt, the waveform — made ahead ([clip-bench.md](clip-bench.md#prepared-before-you-open-it)). No flag queues it and returns (a runner starts in the background, its log `out/bench-excerpts/prep.log`); `--wait` runs it here to the end; `--status` prints ready / to prepare / failed / not fetched and the runner. One clip at a time, each in the heavy slot (estimate 400 MB), under `nice -n 19` and `ionice -c3`; a prepared clip is skipped. A fetch that lands and a write that moves or adds a clip queue it too (`UMTOOL_BENCH_PREP=0` turns that off). **Exit 1** when a clip failed (`--wait`) | | `prune <project> [--take X[,Y]] [--anyway] [--keep N] [--older-than 3d] [--yes] [--json]` · `prune --all [--keep N] [--older-than 3d] [--yes] [--json]` | **the takes' work files** (the Takes page's **Free work files**): per take its work — segments, chrome frames, crossfade batches, encode chunks, raw clip copies, `work-from-*` — counted by inode (a file hard-linked into two takes is counted once and freed only when both let it go), what freeing it gives back, or why it is kept: a running build or the take one builds from (never freed), the picked or current take, a pin in `takes/prune.json`, the newest `--keep` (2) of its group, anything modified within `--older-than` (3d), the `--from` bases of those. A dry run unless `--yes`; `--take X --anyway` frees a take the policy keeps. Renders, previews, take.json and manifests are never touched. **Exit 1** when a path could not be removed ([report-video.md](report-video.md#a-takes-work-files-and-pruning-them)) | | `fallback <project> --dry-run [--json]` · `fallback <project> [--clip <id> …] [--json]` · `fallback <project> --restore <clipId>` | **stand-ins** (the clip deck's **Use stand-in** / **Restore**): a montage clip whose window a fetch run says the editor refused, and is not on disk, switched to its phrase-scan instance's first public alternate (YouTube, then Odysee / cornbreadman, then the rest) — recorded on the clip as `fallbackFrom`, its ruling and voice-match row moved with it; `--restore` puts it back. An older `phrase-scan.json` with no `alternates` is scanned again. **Exit 1** when a named clip has no stand-in | diff --git a/umtool/docs/report-video.md b/umtool/docs/report-video.md @@ -1246,6 +1246,19 @@ cannot resolve); **Start** queues one paced job per platform and the panel follows them to their end, naming each window a job failed. Every run is recorded in `fetch-runs.json` beside the manifest. +A window on disk that is BAD (cut from a saved video that turned out corrupt) +is a cache hit all the same, so a plain fetch keeps it. `umtool fetch <project> +--refetch z01,w01` evicts first: each named clip's fetch span — the very +`from`–`to` the body asks for, pad included — goes to the editor's `evict-clips` +as `{slug, id, covering: [{from, to}]}`, which removes every cached window of +that video OVERLAPPING the span (a wider window the dedup would have served it +from included, and its `.desynced.*` twin), and only once that job has ended is +the fetch asked. `--refetch-video <slug>/<id>` does the same for every window +the project asks of one video. A window another project shares is evicted too: +it costs that project a fetch, not data. `--dry-run` makes the eviction a dry +run as well. The run's `fetch-runs.json` entry records what went, under +`refetch`. + Some windows are refused for good: a Rumble video whose embed lookup answers 403 on every try (per video — not the Cloudflare clearance), or a recording gone from its platform. The phrase scan knows the other uploads of each moment: every diff --git a/umtool/lib/report/fetchCli.mjs b/umtool/lib/report/fetchCli.mjs @@ -8,6 +8,8 @@ // umtool fetch <project> [--wait] [--json] start it: one job per platform queue; --wait follows them to the end // umtool fetch <project> --status [--json] the last run's jobs, followed once (what --wait polls) // … [--reason "…"] the provenance reason (default: "<title> montage", or the title) +// … --refetch <clipId>[,<clipId>…] evict those clips' cached windows first (the editor's evict-clips, +// --refetch-video <slug>/<id> `covering` their fetch spans), then fetch as usual import { REPORTS_ROOT, resolveProject } from "../projects/core.mjs"; import { EditorError, @@ -15,11 +17,16 @@ import { TERMINAL, editorConfig, followRun, + jobLog, + jobStatus, lastStartedRun, + parseEvictLog, + postEvictClips, postFetchWindows, projectFetchBody, readFetchRuns, recordFetchRun, + refetchEvictions, summarizeAnswer, } from "./fetchWindows.mjs"; import { benchPrepAfterWrite } from "./benchPrepTrigger.mjs"; @@ -30,6 +37,9 @@ export const FETCH_USAGE = [ " umtool fetch <project> [--wait] [--json] start it (one paced job per platform); --wait follows the jobs", " umtool fetch <project> --status [--json] the last run's jobs, and the windows they failed", " … [--reason \"…\"] the provenance reason (default \"<title> montage\" for a montage, else the title)", + " … --refetch <clipId>[,<clipId>…] evict the cached windows overlapping those clips' fetch spans first", + " … --refetch-video <slug>/<id> the same for every window this project asks of that video", + " (the editor's evict-clips; with --dry-run the eviction is a dry run too and nothing is deleted)", "", `Every run is recorded in <project>/${FETCH_RUNS_FILE}; \`umtool fallback\` reads it for the refused windows.`, "The editor: ARCHILYZER_EDITOR_URL (default http://localhost:3001), WORKER_TOKEN (else the editor's env files).", @@ -67,10 +77,20 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con const json = args.includes("--json"); const words = []; let reason = null; + const refetchClips = []; + const refetchVideos = []; for (let i = 0; i < args.length; i += 1) { if (args[i] === "--reason") { reason = args[i + 1] ?? ""; i += 1; + } else if (args[i] === "--refetch" || args[i] === "--refetch-video") { + const v = args[i + 1]; + if (!v || v.startsWith("--")) { + err(`${args[i]} needs a value\n${FETCH_USAGE}`); + return 2; + } + (args[i] === "--refetch" ? refetchClips : refetchVideos).push(...v.split(",").map((x) => x.trim()).filter(Boolean)); + i += 1; } else if (!args[i].startsWith("--")) words.push(args[i]); } try { @@ -111,11 +131,36 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con return 0; } const dryRun = args.includes("--dry-run"); + // A REFETCH EVICTS FIRST, and waits: the fetch takes a cache hit before + // anything else, so it must not be asked until the eviction has ended. + let refetch = null; + if (refetchClips.length || refetchVideos.length) { + const plan = refetchEvictions(body, skipped, { clipIds: refetchClips, videos: refetchVideos }); + if (!plan.ok) throw new CliError(plan.error); + refetch = []; + for (const req of plan.requests) { + const { jobId } = await postEvictClips(cfg, req, { dryRun }); + let status = "unknown"; + for (;;) { + status = String((await jobStatus(cfg, jobId))?.job?.status ?? "unknown"); + if (TERMINAL.has(status)) break; + await sleep(pollMs); + } + const { windows, summary: said } = parseEvictLog(await jobLog(cfg, jobId).catch(() => "")); + refetch.push({ slug: req.slug, id: req.id, clipIds: req.clipIds, covering: req.covering, dryRun, jobId, status, windows }); + if (!json) { + out(`${project.id}: ${dryRun ? "would evict" : "evicted"} for ${req.clipIds.join(",")} (${req.slug}/${req.id}, job ${jobId}): ${windows.length ? windows.join(" ") : "no cached window"}`); + if (said) out(` ${said}`); + } + if (status !== "done") throw new CliError(`the eviction of ${req.slug}/${req.id} ended ${status} (job ${jobId}) — nothing was fetched`); + } + if (dryRun && !json) out(" (a dry run evicts nothing, so those windows still read as cached below)"); + } const answer = await postFetchWindows(cfg, body, { dryRun }); - const run = await recordFetchRun(project.dir, { body, answer }); + const run = await recordFetchRun(project.dir, { body, answer, refetch }); const summary = summarizeAnswer(answer); if (!dryRun && !args.includes("--wait")) { - if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...summary }, null, 2)); + if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary }, null, 2)); else { out(`${project.id}: ${body.items.length} window(s) asked${skipped.length ? `, ${skipped.length} skipped` : ""}`); for (const l of summaryLines(summary)) out(l); @@ -123,7 +168,7 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con return summary.refused.length && !summary.jobs.length ? 1 : 0; } if (dryRun) { - if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...summary }, null, 2)); + if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary }, null, 2)); else { out(`${project.id}: ${body.items.length} window(s) — the dry run${skipped.length ? ` (${skipped.length} skipped: ${skipped.map((s) => `${s.clipId} ${s.why}`).join(", ")})` : ""}`); for (const l of summaryLines(summary)) out(l); @@ -152,7 +197,7 @@ export async function fetchCommand(args, { root = REPORTS_ROOT, out = (s) => con // What landed, prepared for the walk (a runner in the background; bin/umtool.mjs waits for the queueing only). if (states.some((st) => st.status === "done")) benchPrepAfterWrite(project.dir, null, { excerptsOnly: false }); const failed = states.flatMap((st) => st.failed ?? []); - if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...summary, jobsEnded: states }, null, 2)); + if (json) out(JSON.stringify({ project: project.id, items: body.items.length, skipped, ...(refetch ? { refetch } : {}), ...summary, jobsEnded: states }, null, 2)); else { for (const f of failed) out(` ✗ ${f.clipId ?? `${f.slug}/${f.id}`}: ${f.class} — ${f.message}`); if (failed.length) out(`${failed.length} window(s) failed — \`umtool fallback ${project.id} --dry-run\` finds a stand-in for each refused one`); diff --git a/umtool/lib/report/fetchWindows.mjs b/umtool/lib/report/fetchWindows.mjs @@ -20,6 +20,14 @@ // summary, jobs?: {<jobId>: {status, platform, failed: [...], at}}}]}, so the // stand-in step (standIns.mjs) can find the jobs and the windows they refused. // +// A REFETCH (`umtool fetch --refetch <clipId>`) evicts first: each named clip's +// fetch span — exactly the item this body asks for, pad included — goes to the +// editor's `evict-clips` as `{slug, id, covering: [{from, to}]}`, one request +// per video, which removes every cached window OVERLAPPING it (a wider window +// the dedup would have served the span from included). Then the fetch runs as +// usual and finds those seconds missing. The run records what was evicted +// (`refetch` on its fetch-runs.json entry). +// // The editor's URL and token are read where report-to-video/fetch-via-editor.mjs // reads them: ARCHILYZER_EDITOR_URL (default http://localhost:3001) and // WORKER_TOKEN (else the editor's own env files, lib/annotations/agentAuth.mjs). @@ -95,6 +103,55 @@ export function fetchWindowsBody(manifest, { manifestPath, project, rulings = nu }; } +// Twitch's record ids wear a `v` the directory does not: "v123" and "123" are one video. +const sameVideo = (a, b) => String(a).replace(/^v(?=\d+$)/, "") === String(b).replace(/^v(?=\d+$)/, ""); + +/** + * What a refetch evicts first: the named clips' fetch spans, and every span a + * named video is asked for, as one evict-clips request per video. Pure. + * + * @param {{ items: Record<string, any>[] }} body the fetch-windows body (fetchWindowsBody) + * @param {{ clipId: string, why: string }[]} skipped what the body left out, and why + * @param {{ clipIds?: string[], videos?: string[] }} want clip ids; videos as "<slug>/<id>" + * @returns {{ ok: true, requests: { slug: string, id: string, covering: { from: number, to: number }[], clipIds: string[] }[] } | { ok: false, error: string }} + */ +export function refetchEvictions(body, skipped, { clipIds = [], videos = [] }) { + const items = Array.isArray(body?.items) ? body.items : []; + /** @type {Map<string, { slug: string, id: string, covering: { from: number, to: number }[], clipIds: string[] }>} */ + const byVideo = new Map(); + const add = (it) => { + const key = `${it.slug}/${it.id}`; + const req = byVideo.get(key) ?? { slug: it.slug, id: it.id, covering: [], clipIds: [] }; + if (req.clipIds.includes(it.clipId)) return; + req.covering.push({ from: it.from, to: it.to }); + req.clipIds.push(it.clipId); + byVideo.set(key, req); + }; + for (const clipId of clipIds) { + const it = items.find((i) => i.clipId === clipId); + if (!it) { + const left = skipped.find((s) => s.clipId === clipId); + return { + ok: false, + error: left + ? `${clipId} is not fetched by this project (${left.why}), so there is nothing to refetch` + : `no clip "${clipId}" in the manifest's timeline`, + }; + } + add(it); + } + for (const v of videos) { + const at = String(v).indexOf("/"); + const slug = at > 0 ? v.slice(0, at) : ""; + const id = at > 0 ? v.slice(at + 1) : ""; + if (!slug || !id || id.includes("/")) return { ok: false, error: `--refetch-video takes <slug>/<id>, not "${v}"` }; + const its = items.filter((i) => i.slug === slug && sameVideo(i.id, id)); + if (!its.length) return { ok: false, error: `this project asks for no window of ${slug}/${id}` }; + for (const it of its) add(it); + } + return { ok: true, requests: [...byVideo.values()] }; +} + /** sha256 of the body with its keys sorted (key order never changes the hash). */ export function bodyHash(body) { const canon = (v) => @@ -176,6 +233,37 @@ export function postFetchWindows(cfg, body, { dryRun = false } = {}) { return ask(cfg, "/api/ops/fetch-windows", { method: "POST", body: dryRun ? { ...body, dryRun: true } : body }); } +/** + * POST /api/ops/evict-clips, targeted: `{slug, id, covering}` -> `{jobId}`. + * @param {{ url: string, token: string, fetch?: typeof fetch }} cfg + * @param {{ slug: string, id: string, covering: { from: number, to: number }[] }} req + * @param {{ dryRun?: boolean }} [opts] + */ +export function postEvictClips(cfg, { slug, id, covering }, { dryRun = false } = {}) { + return ask(cfg, "/api/ops/evict-clips", { method: "POST", body: { slug, id, covering, ...(dryRun ? { dryRun: true } : {}) } }); +} + +// `evicting <slug>/<id>/<name> (…)` / `would evict …` — the line +// common/controller/evictClipWindows.ts logs for each window. +const EVICT_LINE = /^\s*(?:would evict|evicting) [^/\s]+\/[^/\s]+\/(\S+) /; +const EVICT_SUMMARY = /^\s*((?:Would evict|Evicted) \d+ window.*)$/; + +/** + * The windows an evict-clips job named (evicted, or would have), and its summary sentence. + * @param {string} log + */ +export function parseEvictLog(log) { + const windows = []; + let summary = null; + for (const line of String(log ?? "").split("\n")) { + const m = EVICT_LINE.exec(line); + if (m) windows.push(m[1]); + const s = EVICT_SUMMARY.exec(line); + if (s) summary = s[1].trim(); + } + return { windows, summary }; +} + /** GET /api/ops/job/<id>: `{job: {id, status, progress?, queue?}}`. */ export function jobStatus(cfg, jobId) { return ask(cfg, `/api/ops/job/${encodeURIComponent(jobId)}`); @@ -270,9 +358,10 @@ async function writeRuns(projectDir, doc) { /** * Record a run (the dry run or the start). * @param {string} projectDir - * @param {{ body: Record<string, any>, answer: Record<string, any>, now?: Date }} r + * @param {{ body: Record<string, any>, answer: Record<string, any>, refetch?: Record<string, any>[] | null, now?: Date }} r + * `refetch`: what a `--refetch` evicted first (one entry per video). */ -export function recordFetchRun(projectDir, { body, answer, now = new Date() }) { +export function recordFetchRun(projectDir, { body, answer, refetch = null, now = new Date() }) { return withRunsLock(async () => { const doc = await readFetchRuns(projectDir); const summary = summarizeAnswer(answer); @@ -283,6 +372,7 @@ export function recordFetchRun(projectDir, { body, answer, now = new Date() }) { items: (body.items ?? []).length, jobIds: summary.jobs.map((j) => j.jobId), summary, + ...(refetch ? { refetch } : {}), }; doc.runs.push(run); doc.runs = doc.runs.slice(-FETCH_RUNS_KEPT); diff --git a/umtool/lib/report/fetchWindows.test.mjs b/umtool/lib/report/fetchWindows.test.mjs @@ -11,10 +11,12 @@ import { fetchWindowsBody, followRun, lastStartedRun, + parseEvictLog, parseFailedWindows, projectFetchBody, readFetchRuns, recordFetchRun, + refetchEvictions, summarizeAnswer, } from "./fetchWindows.mjs"; import { fetchCommand } from "./fetchCli.mjs"; @@ -197,3 +199,77 @@ test("projectFetchBody reads the rulings beside the manifest; summarizeAnswer na await rm(root, { recursive: true, force: true }); } }); + +test("refetchEvictions: a clip resolves to the very span the body fetches (pad included), grouped per video", () => { + const padded = { ...MANIFEST, render: { fetchPad: 2, transition: 0 }, timeline: [...MANIFEST.timeline, { type: "clip", id: "s04", channel: "synth-yt", video: "yt1", start: 200, end: 210 }] }; + const { body, skipped } = fetchWindowsBody(padded, { manifestPath: "/x/m.json", project: "p" }); + const r = refetchEvictions(body, skipped, { clipIds: ["s01", "s04", "s02"] }); + assert.ok(r.ok); + assert.deepEqual(r.requests, [ + { slug: "synth-yt", id: "yt1", covering: [{ from: 53.81, to: 65.87 }, { from: 198, to: 212 }], clipIds: ["s01", "s04"] }, + { slug: "synth-rumble", id: "v2abc", covering: [{ from: 0, to: 9.5 }], clipIds: ["s02"] }, + ]); + // --refetch-video: every span the project asks of that video, once. + const v = refetchEvictions(body, skipped, { clipIds: ["s01"], videos: ["synth-yt/yt1"] }); + assert.ok(v.ok); + assert.deepEqual(v.requests.map((q) => q.clipIds), [["s01", "s04"]]); + // A Twitch record id and its directory id are one video. + const tw = fetchWindowsBody({ timeline: [{ type: "clip", id: "z01", channel: "tw", video: "2912435200", start: 10, end: 20 }], render: { fetchPad: 0 } }, { manifestPath: "/x/m.json", project: "p" }); + assert.ok(refetchEvictions(tw.body, tw.skipped, { videos: ["tw/v2912435200"] }).ok); + // Refusals say why. + assert.match(refetchEvictions(body, skipped, { clipIds: ["nope"] }).error, /no clip "nope"/); + assert.match(refetchEvictions(body, [{ clipId: "s09", why: "ruled cut" }], { clipIds: ["s09"] }).error, /not fetched by this project \(ruled cut\)/); + assert.match(refetchEvictions(body, skipped, { videos: ["synth-yt"] }).error, /takes <slug>\/<id>/); + assert.match(refetchEvictions(body, skipped, { videos: ["synth-yt/other"] }).error, /asks for no window of synth-yt\/other/); +}); + +test("umtool fetch --refetch: evict-clips {slug, id, covering} first, waited for; then the fetch; the run records what went", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "umtool-fetch-")); + try { + const dir = path.join(root, "synth-oops"); + await mkdir(dir, { recursive: true }); + await writeFile(path.join(dir, "video.manifest.json"), JSON.stringify(MANIFEST, null, 2)); + let evictPolls = 0; + const ed = fakeEditor({ + "POST /api/ops/evict-clips": (b) => ({ ok: true, jobId: b.dryRun ? "E0" : "E1" }), + "GET /api/ops/job/E0": { ok: true, job: { id: "E0", status: "done" } }, + "GET /api/ops/job/E1": () => ({ ok: true, job: { id: "E1", status: ++evictPolls < 2 ? "running" : "done" } }), + "GET /api/jobs/E0/log": { content: "would evict synth-rumble/v2abc/0.00-9.00.mp4 (1 KB, last touched 2026-10-28)\nWould evict 1 window(s), 1 KB across 1 video(s) in 1 channel(s); 0 other window(s) (0 B) left alone.\n" }, + "GET /api/jobs/E1/log": { content: "evicting synth-rumble/v2abc/0.00-9.00.mp4 (1 KB, last touched 2026-10-28)\nEvicted 1 window(s), 1 KB across 1 video(s) in 1 channel(s); 0 other window(s) (0 B) left alone.\n" }, + "POST /api/ops/fetch-windows": (b) => ({ ok: true, dryRun: !!b.dryRun, groups: [], cached: [], inFlight: [], unresolved: [], refused: [], jobs: b.dryRun ? [] : [{ platform: "rumble", jobId: "J1", items: 1 }] }), + "GET /api/ops/job/J1": { ok: true, job: { id: "J1", status: "done" } }, + "GET /api/jobs/J1/log": { content: "" }, + }); + const cfg = { url: "http://editor.test", token: "tok", fetch: ed.fetch }; + const lines = []; + const run = (args) => fetchCommand(args, { root, out: (s) => lines.push(s), err: (s) => lines.push(s), cfg, pollMs: 1 }); + + assert.equal(await run(["synth-oops", "--refetch", "s02", "--dry-run"]), 0); + assert.deepEqual(ed.seen[0], { key: "POST /api/ops/evict-clips", body: { slug: "synth-rumble", id: "v2abc", covering: [{ from: 0, to: 7.5 }], dryRun: true }, auth: "Bearer tok" }); + assert.equal(ed.seen.at(-1).key, "POST /api/ops/fetch-windows"); + assert.equal(ed.seen.at(-1).body.dryRun, true); + assert.match(lines.join("\n"), /would evict for s02 \(synth-rumble\/v2abc, job E0\): 0\.00-9\.00\.mp4/); + + ed.seen.length = 0; + lines.length = 0; + assert.equal(await run(["synth-oops", "--refetch", "s02", "--wait"]), 0); + const keys = ed.seen.map((x) => x.key); + // The fetch is asked only after the eviction job has ended. + assert.equal(keys.indexOf("POST /api/ops/fetch-windows") > keys.lastIndexOf("GET /api/ops/job/E1"), true); + assert.equal("dryRun" in ed.seen[0].body, false); + const doc = await readFetchRuns(dir); + const last = doc.runs.at(-1); + assert.deepEqual(last.refetch, [{ slug: "synth-rumble", id: "v2abc", clipIds: ["s02"], covering: [{ from: 0, to: 7.5 }], dryRun: false, jobId: "E1", status: "done", windows: ["0.00-9.00.mp4"] }]); + assert.deepEqual(last.jobIds, ["J1"]); + + // An unknown clip is refused before the editor is asked. + ed.seen.length = 0; + lines.length = 0; + assert.equal(await run(["synth-oops", "--refetch", "zz9"]), 1); + assert.equal(ed.seen.length, 0); + assert.match(lines.join("\n"), /no clip "zz9"/); + assert.deepEqual(parseEvictLog("evicting a/b/1.00-2.00.desynced.mp4 (x)\n").windows, ["1.00-2.00.desynced.mp4"]); + } finally { + await rm(root, { recursive: true, force: true }); + } +});