commit 57c00a683ab1b4b65bf6a40a0c93beb78762bf0f
parent 1f3b4f9647b3ca6201f693c1ce842bed0325f195
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Mon, 9 Nov 2026 15:33:54 -0500
umtool: basic spans keyed by their window's size and mtime; the cut written through a temporary name
A window re-fetched under the same name made a stale span look current: the span cache key
now carries the resolved source's size and mtime. A failed span encode removes its
*.tmp.mp4, and the concat writes the cut through a temporary name, renamed on success.
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Diffstat:
2 files changed, 72 insertions(+), 10 deletions(-)
diff --git a/umtool/report-to-video/basic.mjs b/umtool/report-to-video/basic.mjs
@@ -33,7 +33,7 @@
// build-video.mjs, which imports this and hands `renderBasic` what it needs.
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
-import { mkdir, rename, stat, writeFile } from "node:fs/promises";
+import { mkdir, rename, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { promisify } from "node:util";
import { basicFadeOf, basicOn } from "yt-dlp-transcript-common/lib/report/look.mjs";
@@ -189,9 +189,13 @@ export function concatArgs(listFile, out) {
return ["-nostdin", "-v", "error", "-y", "-f", "concat", "-safe", "0", "-i", listFile, "-c", "copy", "-movflags", "+faststart", out];
}
-/** A span file's name: its order, its clip, its piece, and the hash of what makes it. */
-export function spanFileName(n, id, k, argv) {
- const key = createHash("sha256").update(JSON.stringify({ v: BASIC_SEGMENT_V, argv: argv.slice(0, -1) })).digest("hex").slice(0, 12);
+/**
+ * A span file's name: its order, its clip, its piece, and the hash of what makes it -- the argv (less its out
+ * path) AND the source's identity (`source`: its size and mtime), so a window re-fetched under the same name
+ * makes the span again rather than reusing one cut from the old bytes.
+ */
+export function spanFileName(n, id, k, argv, source = null) {
+ const key = createHash("sha256").update(JSON.stringify({ v: BASIC_SEGMENT_V, argv: argv.slice(0, -1), source })).digest("hex").slice(0, 12);
return `${String(n).padStart(3, "0")}-${String(id).replace(/[^A-Za-z0-9_-]/g, "_")}-${k}-${key}.mp4`;
}
@@ -265,13 +269,20 @@ export async function renderBasic({ manifest, dirs, only = null, deps }) {
const fades = spanFades({ seconds: dur, first: n === 0, last: n === located.length - 1, fade: plan.fade });
const at = l.span.from - Number(l.src.fetchStart ?? 0);
const draft = spanArgs({ file: l.src.path, at, seconds: dur, shape, fades, gain: l.it.gain, audio: p.hasAudio, audioRate: r.audioRate, encode, out: "<out>" });
- const out = path.join(work, spanFileName(n, l.it.id, l.k, draft));
+ const st = await stat(l.src.path);
+ const out = path.join(work, spanFileName(n, l.it.id, l.k, draft, { size: st.size, mtimeMs: Math.round(st.mtimeMs) }));
const argv = [...draft.slice(0, -1), out];
- const have = await stat(out).then((s) => s.isFile() && s.size > 0, () => false);
+ const have = await stat(out).then((x) => x.isFile() && x.size > 0, () => false);
if (!have) {
const tmp = `${out}.tmp.mp4`;
- await exec(ffmpeg, [...draft.slice(0, -1), tmp]);
- await rename(tmp, out);
+ try {
+ await exec(ffmpeg, [...draft.slice(0, -1), tmp]);
+ await rename(tmp, out);
+ } catch (e) {
+ // A failed encode leaves nothing a later render could take for a span.
+ await rm(tmp, { force: true });
+ throw e;
+ }
}
emit("fetch", { id: l.it.id, video: l.it.entry.video ?? l.it.entry.src, from: l.span.from, to: l.span.to, cached: true, source: l.src.source ?? "local", reuse: path.basename(l.src.path) });
emit("segment", { id: l.it.id, path: out, reused: have, argv });
@@ -282,7 +293,15 @@ export async function renderBasic({ manifest, dirs, only = null, deps }) {
await writeFile(list, files.map((f) => `file '${f.replace(/'/g, "'\\''")}'`).join("\n") + "\n");
emit("concat", { mode: "hardcut", n: files.length });
await mkdir(path.dirname(dirs.final), { recursive: true });
- await exec(ffmpeg, concatArgs(list, dirs.final));
+ // Through a temporary name: a concat that fails never leaves a half file at the deliverable's path.
+ const finalTmp = `${dirs.final}.tmp-${process.pid}.mp4`;
+ try {
+ await exec(ffmpeg, concatArgs(list, finalTmp));
+ await rename(finalTmp, dirs.final);
+ } catch (e) {
+ await rm(finalTmp, { force: true });
+ throw e;
+ }
const made = await probe(dirs.final).catch(() => null);
const size = await stat(dirs.final).then((s) => s.size, () => 0);
emit("done", { out: dirs.final, duration: made?.duration ?? Number(seconds.toFixed(3)), size, basic: true });
diff --git a/umtool/report-to-video/basic.test.mjs b/umtool/report-to-video/basic.test.mjs
@@ -6,7 +6,7 @@
// Run with: pnpm test:scripts
import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
-import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
import { rm, stat, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -94,6 +94,7 @@ test("spanArgs: the file's seconds, fitted into the first window's shape, its fa
assert.deepEqual(concatArgs("/l.txt", "/f.mp4").slice(-5), ["-c", "copy", "-movflags", "+faststart", "/f.mp4"]);
assert.equal(spanFileName(3, "c 1", 0, argv), spanFileName(3, "c 1", 0, [...argv.slice(0, -1), "/elsewhere.mp4"]), "the out path is not part of the key");
assert.match(spanFileName(3, "c 1", 0, argv), /^003-c_1-0-[0-9a-f]{12}\.mp4$/);
+ assert.notEqual(spanFileName(3, "c", 0, argv, { size: 1, mtimeMs: 1 }), spanFileName(3, "c", 0, argv, { size: 1, mtimeMs: 2 }), "a re-fetched window is another span");
});
test("the mode resolves last: a preset's basic wins its chrome, a patch's deck wins the preset; basic lays no intro or brand", () => {
@@ -174,6 +175,19 @@ test("a basic cut, rendered through buildVideo: the spans spliced at the window'
setProgressMode("human");
assert.ok(again.filter((e) => e.ev === "segment").every((e) => e.reused));
assert.ok((await stat(out)).size > 0);
+ // The window re-fetched under the same name: the spans are cut again, not reused from the old bytes.
+ const r2 = spawnSync("ffmpeg", [
+ "-v", "error", "-y", "-f", "lavfi", "-i", "color=c=red:s=320x180:r=25:d=10", "-f", "lavfi", "-i", "sine=frequency=220:sample_rate=48000:duration=10",
+ "-c:v", "libx264", "-preset", "ultrafast", "-c:a", "aac", "-shortest", raw,
+ ]);
+ assert.equal(r2.status, 0, String(r2.stderr));
+ const fresh = [];
+ setProgressMode((e) => fresh.push(e));
+ await buildVideo({ manifestPath, opts: { skipFetch: true } });
+ setProgressMode("human");
+ assert.ok(fresh.filter((e) => e.ev === "segment").every((e) => !e.reused), "a new window, new spans");
+ const { readdir } = await import("node:fs/promises");
+ assert.deepEqual((await readdir(path.join(root, "out"))).filter((n) => /\.tmp/.test(n)), [], "no temporary file left beside the cut");
// `--only` writes beside the spans, never over the cut.
const only = await buildVideo({ manifestPath, opts: { skipFetch: true }, only: "c2" });
assert.match(only.out, /out\/sourced\/basic\/only-c2\.mp4$/);
@@ -184,3 +198,32 @@ test("a basic cut, rendered through buildVideo: the spans spliced at the window'
await rm(root, { recursive: true, force: true });
}
});
+
+test("renderBasic: a span whose encode fails leaves no temporary file, and the cut's file is not touched", async () => {
+ const root = mkdtempSync(path.join(os.tmpdir(), "rtv-basic-fail-"));
+ try {
+ const src = path.join(root, "w.mp4");
+ writeFileSync(src, "bytes");
+ const { readdir } = await import("node:fs/promises");
+ await assert.rejects(
+ renderBasic({
+ manifest: { render: {}, timeline: [{ type: "clip", id: "c1", video: "v1", start: 1, end: 3 }] },
+ dirs: { dir: root, final: path.join(root, "final.mp4") },
+ deps: {
+ sourceOf: async () => ({ path: src, fetchStart: 0 }),
+ encodeArgs: () => [],
+ probe: async () => ({ width: 320, height: 180, sar: "1:1", fps: "25/1", hasVideo: true, hasAudio: true }),
+ exec: async (_bin, args) => {
+ writeFileSync(args.at(-1), "half");
+ throw new Error("ffmpeg died");
+ },
+ },
+ }),
+ /ffmpeg died/,
+ );
+ assert.deepEqual((await readdir(path.join(root, "basic"))).filter((n) => n.endsWith(".mp4")), []);
+ assert.equal(existsSync(path.join(root, "final.mp4")), false);
+ } finally {
+ await rm(root, { recursive: true, force: true });
+ }
+});