commit 6fe2edc5f2fac068640319251c6266c040debfe0
parent 71465bd8b6a50ccddff76550d66e0998eb955fcc
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 14:04:31 -0500
stored text, captions review-2 nits: durable before replace, refusal on a full disk, keep on overwrite, retry an unreadable sub track
N1. The refetch settle fsyncs the new plain caption and its directory before
it removes the stored copy: yt-dlp never fsyncs, and a power cut must not
leave a zero-length caption and no stored form.
N2. The lock's temp is made inside the try whose finally removes it, so a
completely full disk leaks no empty temp per file. A lock that cannot be
made (LockUnavailableError) is a refusal for the deleters: removeStoredText
and removeStoredTextForm return {refused} and remove nothing; the purge logs
"Kept …", the clear-transcript fix reports the video as not cleared, the
files card answers the reason.
N3. When the original vanishes just before its set-aside — outside every
in-app lock, so yt-dlp's own overwrite in a re-download — the verified
stored copy is KEPT (it is the caption if that fetch fails).
N5. An unreadable stored sub track is retried on every later index build
(subsMs stored null) and counted and logged each time, its earlier cues
kept meanwhile.
Tests, red before: ytdlp/captionsRefetch.test.ts ("replaced: the new file is
synced…"), compressText.captions.test.ts ("the original vanishes…", "a
deleter that cannot make its lock refuses…"), buildIndex.test.ts (x).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
9 files changed, 211 insertions(+), 32 deletions(-)
diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts
@@ -1090,6 +1090,31 @@ test("(w) REVIEW-1 F3: a stored caption that does not decode — the record keep
assert.deepEqual(all().cues, before.cues);
});
+test("(x) REVIEW-2 N5: an unreadable stored SUB track keeps its earlier cues AND is read again, and said, on every build", async () => {
+ resetCorpus();
+ seedVideo("c1", CHANNEL, { subs: true });
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(videoDir("c1"), "transcript.de.vtt");
+ const subsOf = () => withIndex((db) => [...db("subs").getRange()].map(({ key, value }) => [key, value]));
+ const subsMs = () => withIndex((db) => [...db("mtimes").getRange()].map(({ value }) => (value as { subsMs: number | null }).subsMs));
+ await runIndex();
+ const before = subsOf();
+ assert.equal(before.length, 1, "the German track was read");
+ const good = readFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst"));
+ writeFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst"), Buffer.concat([good.subarray(0, 12), Buffer.alloc(good.length - 12, 7)]));
+ seedVideo("c1", CHANNEL, { title: "Retitled" });
+ for (let build = 1; build <= 2; build++) {
+ const r = await runIndex();
+ assert.ok(r.log.some((l) => /^UNREADABLE STORED TEXT: 1 file\(s\).*transcript\.de\.vtt/.test(l)), `build ${build}: ${r.log.join("\n")}`);
+ assert.deepEqual(subsOf(), before, `build ${build}: the earlier cues are kept`);
+ assert.deepEqual(subsMs(), [null], `build ${build}: not pinned as read`);
+ }
+ writeFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst"), good);
+ const fixed = await runIndex();
+ assert.ok(!fixed.log.some((l) => /UNREADABLE/.test(l)));
+ assert.notDeepEqual(subsMs(), [null]);
+});
+
test("(z) no write this file caused landed outside its temp root", () => {
// LMDB writes natively, past the spy: its file must be under the root too.
assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath);
diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts
@@ -1360,7 +1360,9 @@ export async function buildIndex({
unreadableStored.push(`${s.channelSlug}/${s.videoDir}/${t.filename}: ${(err as Error).message}`);
const kept = prevSubs?.find((x) => x.track === t.track);
if (kept) parsedSubs.push(kept);
- else retrySubs = true;
+ // Retried on EVERY later build, kept cues or not — never
+ // pinned as read (REVIEW-2 N5): `subsMs` is stored null.
+ retrySubs = true;
}
// Skip unreadable / malformed sub tracks; the rest of the
// video's data is still useful.
diff --git a/common/controller/compressText.captions.test.ts b/common/controller/compressText.captions.test.ts
@@ -3,6 +3,7 @@ import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
+import { rmSync } from "node:fs";
import path from "node:path";
// Run with:
@@ -338,3 +339,59 @@ test("both forms differ: refused ONCE and recorded; later runs list it as waitin
assert.equal(settled.channels[0].compressed, 1);
assert.equal(await readStoredText(dirOf("mu", "m1"), "transcript.en.vtt", "utf8"), vtt("new", 21));
});
+
+// REVIEW-2 N3: the original removed OUTSIDE the lock between the compressor's
+// last look and its set-aside — yt-dlp's own overwrite deletes the plain
+// caption and fetches after. The verified stored copy is KEPT: if the fetch
+// fails it is the caption.
+test("the original vanishes just before its set-aside (yt-dlp's overwrite): the verified stored copy is kept", async () => {
+ await channel("nu", { n1: { "transcript.en.vtt": vtt("n1", 20) } });
+ const plain = path.join(dirOf("nu", "n1"), "transcript.en.vtt");
+ const lines: string[] = [];
+ const r = await compressText({
+ paths,
+ slugs: ["nu"],
+ kinds: CAPTIONS,
+ quietMs: 0,
+ onLog: (l) => lines.push(l),
+ compressOpts: {
+ crashAt: (p) => {
+ if (p === "placed") rmSync(plain);
+ },
+ },
+ });
+ assert.equal(r.channels[0].byKind!.captions!.changed, 1);
+ assert.deepEqual(await names("nu", "n1"), ["metadata.info.json", "transcript.en.vtt.zst"]);
+ assert.equal(await readStoredText(dirOf("nu", "n1"), "transcript.en.vtt", "utf8"), vtt("n1", 20));
+ assert.match(lines.join(""), /was removed while it was being compressed: the verified stored copy is kept/);
+});
+
+// REVIEW-2 N2: a deleter that cannot make the file's lock (a full disk, a
+// read-only dir) REFUSES, removes nothing, throws nothing, leaves no temp.
+test("a deleter that cannot make its lock refuses: nothing removed, no throw, no lock temp left", async () => {
+ const { chmod } = await import("node:fs/promises");
+ const { removeStoredText, removeStoredTextForm } = await import("../lib/storedText-write-server");
+ const { purgeSupersededAutoSubs } = await import("./purgeSupersededAutoSubs");
+ const ASR =
+ "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:05.000 align:start position:0%\n" +
+ "First<00:00:01.000><c> caption</c>\n\n00:01:00.000 --> 00:01:50.000 align:start position:0%\n" +
+ "Second<00:01:10.000><c> caption</c>\n";
+ await channel("xi", { x1: { "transcript.en.vtt": ASR, "transcript.json": JSON.stringify({ transcription: [{ text: "ours" }] }) } });
+ await compressText({ paths, slugs: ["xi"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ const d = dirOf("xi", "x1");
+ const before = await names("xi", "x1");
+ await chmod(d, 0o555);
+ try {
+ const a = await removeStoredText(d, "transcript.en.vtt");
+ assert.ok("refused" in a && /not deleted: the stored-text lock cannot be made/.test(a.refused), JSON.stringify(a));
+ const b = await removeStoredTextForm(d, "transcript.en.vtt.zst");
+ assert.ok(typeof b === "object" && "refused" in b, JSON.stringify(b));
+ const logs: string[] = [];
+ const p = await purgeSupersededAutoSubs({ channelSlug: "xi", paths, onLog: (m) => logs.push(m) });
+ assert.equal(p.removedFiles, 0);
+ assert.match(logs.join("\n"), /Kept x1\/transcript\.en\.vtt — transcript\.en\.vtt not deleted/);
+ } finally {
+ await chmod(d, 0o755);
+ }
+ assert.deepEqual(await names("xi", "x1"), before, "nothing removed, no lock temp left");
+});
diff --git a/common/controller/purgeSupersededAutoSubs.ts b/common/controller/purgeSupersededAutoSubs.ts
@@ -106,7 +106,13 @@ export async function purgeSupersededAutoSubs({
}
// Both forms (lib/storedText-write-server.ts): a stored copy left behind
// would bring the captions back. Each through removeMediaFile.
- await removeStoredText(videoDir, name);
+ const out = await removeStoredText(videoDir, name);
+ if ("refused" in out) {
+ // Nothing was removed (a full disk, or a run holding the file).
+ log(`Kept ${id}/${name} — ${out.refused}`);
+ skipped++;
+ continue;
+ }
log(`Removed ${id}/${name}`);
removedFiles++;
removedHere++;
diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts
@@ -64,17 +64,29 @@ import {
// file's lock, so no run of ours is between its steps while the file goes;
// a run that holds it is waited for (a few seconds), then this throws and
// nothing is removed. Missing is not an error.
-export async function removeStoredText(videoDir: string, name: string): Promise<void> {
+//
+// A REFUSAL, NEVER A THROW, when it cannot take the lock (REVIEW-2 N2): a run
+// that holds it past the wait, or a disk so full the lock's few bytes do not
+// fit. Then NOTHING is removed and `{refused}` says why; the caller reports it.
+export type RemoveStoredTextOutcome = { removed: true } | { refused: string };
+
+export async function removeStoredText(videoDir: string, name: string): Promise<RemoveStoredTextOutcome> {
for (let attempt = 0; ; attempt++) {
- const done = await withFileLock(videoDir, name, false, async () => {
- await removeMediaFile(videoDir, storedNameOf(name));
- await removeMediaFile(videoDir, name);
- await removeLeftoversOf(videoDir, name);
- return true;
- });
- if (done) return;
+ let done: boolean;
+ try {
+ done = await withFileLock(videoDir, name, false, async () => {
+ await removeMediaFile(videoDir, storedNameOf(name));
+ await removeMediaFile(videoDir, name);
+ await removeLeftoversOf(videoDir, name);
+ return true;
+ });
+ } catch (err) {
+ if (err instanceof LockUnavailableError) return { refused: `${name} not deleted: ${err.message}` };
+ throw err;
+ }
+ if (done) return { removed: true };
if (attempt >= 40) {
- throw new Error(`${name} is being compressed or restored right now: not deleted — try again in a moment`);
+ return { refused: `${name} not deleted: it is being compressed or restored right now — try again in a moment` };
}
await new Promise((r) => setTimeout(r, 250));
}
@@ -456,18 +468,30 @@ function lockHolderRunning(owner: Owner): boolean {
}
// The dir lock, or null when a live run holds it. Returns its release.
+// The dir lock could not be made at all — a full disk (ENOSPC), a read-only
+// one. Nothing was done; a deleter answers it as a refusal (REVIEW-2 N2).
+export class LockUnavailableError extends Error {
+ constructor(videoDir: string, cause: Error) {
+ super(`the stored-text lock cannot be made in ${path.basename(videoDir)} (${(cause as NodeJS.ErrnoException).code ?? cause.message})`);
+ this.name = "LockUnavailableError";
+ }
+}
+
async function takeDirLock(videoDir: string): Promise<(() => Promise<void>) | null> {
const lock = path.join(videoDir, STORED_TEXT_DIR_LOCK);
const me = { pid: process.pid, token: selfToken() };
const tmp = path.join(videoDir, `${STORED_TEXT_DIR_LOCK}.${me.pid}-${me.token}-${Math.random().toString(36).slice(2, 8)}`);
try {
- await writeFile(tmp, JSON.stringify(me), { flag: "wx" });
- } catch (err) {
- // No video dir: nothing to lock and nothing to do.
- if (errCode(err) === "ENOENT") return async () => {};
- throw err;
- }
- try {
+ // Inside the try whose `finally` removes it: on a FULL disk `wx` creates
+ // the file and then fails to write it, and the empty temp must not stay
+ // behind, one per file visited (REVIEW-2 N2).
+ try {
+ await writeFile(tmp, JSON.stringify(me), { flag: "wx" });
+ } catch (err) {
+ // No video dir: nothing to lock and nothing to do.
+ if (errCode(err) === "ENOENT") return async () => {};
+ throw new LockUnavailableError(videoDir, err as Error);
+ }
for (let attempt = 0; attempt < 3; attempt++) {
try {
await link(tmp, lock);
@@ -851,11 +875,13 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
await rename(p.path, retiredPath);
} catch (err) {
if (errCode(err) !== "ENOENT") throw err;
- // The original was removed since its last look — a deleter outside the
- // lock, or a writer replacing it. A stored form THIS run made would
- // outlive a deletion (REVIEW-1 F2): it goes; an older one is not ours.
- if (zKind === "none") await removeMediaFile(videoDir, stored);
- log(` ${name} was removed while it was being compressed: ${zKind === "none" ? "the stored copy this run made is removed too" : "left as it is"}`);
+ // The original was removed since its last look. Every in-app deleter
+ // holds this file's lock, so what removed it is OUTSIDE the lock —
+ // yt-dlp's own overwrite in a re-download, which deletes the plain file
+ // and fetches after. The verified stored copy is KEPT (REVIEW-2 N3): if
+ // that fetch fails (a 429, a video gone) it is the caption; a new plain
+ // file landing later is `same` or `both-differ`, both safe.
+ log(` ${name} was removed while it was being compressed: the verified stored copy is kept`);
return { status: "changed" };
}
crash("retired");
@@ -1515,6 +1541,13 @@ export async function bothDifferRecorded(record: DiffersRecord, videoDir: string
//
// Each outcome is a line in the job log.
+// A test's seam: called after the new plain file and its dir are fsynced and
+// before the stored copy is removed (the order is what REVIEW-2 N1 asks).
+let syncedForTest: ((videoDir: string, name: string) => Promise<void> | void) | undefined;
+export function setRefetchSyncedHookForTest(fn: typeof syncedForTest): void {
+ syncedForTest = fn;
+}
+
export type RefetchedCaptionOutcome = {
track: string;
name: string;
@@ -1591,7 +1624,18 @@ async function settleOne(videoDir: string, track: string, name: string): Promise
return { ...base, status: "dropped-empty", detail: `${fresh.length} bytes` };
}
// The new track is whole (yt-dlp has exited; no `.part`) and a caption: it
- // is the track, as an overwrite was on main. Only now the stored one goes.
+ // is the track, as an overwrite was on main. Its data and its name are made
+ // DURABLE first — yt-dlp never fsyncs, and a power cut after the stored
+ // copy's removal must not leave a zero-length caption (REVIEW-2 N1). Only
+ // then the stored one goes.
+ const fh = await open(path.join(videoDir, name), "r");
+ try {
+ await fh.sync();
+ } finally {
+ await fh.close();
+ }
+ await fsyncDir(videoDir);
+ await syncedForTest?.(videoDir, name);
await removeMediaFile(videoDir, storedNameOf(name));
await fsyncDir(videoDir);
return { ...base, status: "replaced", detail: `${cues} cues, ${fresh.length} bytes` };
@@ -1613,12 +1657,25 @@ export type RemoveFormOutcome = {
unpinned?: boolean;
};
-export async function removeStoredTextForm(videoDir: string, filename: string): Promise<RemoveFormOutcome | "busy"> {
+export async function removeStoredTextForm(
+ videoDir: string,
+ filename: string,
+): Promise<RemoveFormOutcome | "busy" | { refused: string }> {
const plain = plainNameOf(filename) ?? filename;
if (!isStoredTextName(plain)) {
await removeMediaFile(videoDir, filename);
return { removed: [filename] };
}
+ try {
+ return await removeStoredTextFormLocked(videoDir, filename, plain);
+ } catch (err) {
+ // No lock could be made (a full disk): nothing was removed (REVIEW-2 N2).
+ if (err instanceof LockUnavailableError) return { refused: `${filename} not deleted: ${err.message}` };
+ throw err;
+ }
+}
+
+async function removeStoredTextFormLocked(videoDir: string, filename: string, plain: string): Promise<RemoveFormOutcome | "busy"> {
return withFileLock<RemoveFormOutcome | "busy">(videoDir, plain, "busy", async () => {
const other = filename === plain ? storedNameOf(plain) : plain;
// A stopped run's leftovers on the name go with any form deleted: a
diff --git a/common/ytdlp/captionsRefetch.test.ts b/common/ytdlp/captionsRefetch.test.ts
@@ -206,3 +206,27 @@ test("replaceAutoSubs's audio download (transcribe handling) asks for no caption
await r.cleanup();
}
});
+
+// REVIEW-2 N1: the new plain file and its dir are fsynced BEFORE the stored
+// copy goes (yt-dlp never fsyncs; a power cut must not leave a zero-length
+// caption and no stored form). The seam runs between the two.
+test("replaced: the new file is synced while the stored copy is still there; only then the stored copy goes", async () => {
+ const { setRefetchSyncedHookForTest, settleRefetchedCaptions } = await import("../lib/storedText-write-server");
+ const { mkdtemp: mk } = await import("node:fs/promises");
+ const dir = path.join(await mk(path.join(tmpdir(), "settle-order-")), "channels", "c", "data", "v1");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, EN), OLD);
+ await storeFixture(dir, EN);
+ await writeFile(path.join(dir, EN), vtt("new words"));
+ const seen: string[][] = [];
+ setRefetchSyncedHookForTest(async (d) => void seen.push((await readdir(d)).sort()));
+ try {
+ const out = await settleRefetchedCaptions(dir, ["en"]);
+ assert.equal(out[0].status, "replaced");
+ } finally {
+ setRefetchSyncedHookForTest(undefined);
+ }
+ assert.deepEqual(seen, [[".stored-text.lock", EN, `${EN}.zst`]], "synced with both forms on disk (under the file's lock)");
+ assert.deepEqual((await readdir(dir)).sort(), [EN]);
+ await rm(path.dirname(path.dirname(path.dirname(path.dirname(dir)))), { recursive: true, force: true });
+});
diff --git a/editor/app/channels/[slug]/incompleteTranscriptActions.ts b/editor/app/channels/[slug]/incompleteTranscriptActions.ts
@@ -198,8 +198,11 @@ export async function clearIncompleteTranscriptsAction(
let succeeded = 0;
for (const id of cleaned) {
try {
- await clearIncompleteTranscriptOne({ slug, videoId: id, paths });
- succeeded++;
+ const r = await clearIncompleteTranscriptOne({ slug, videoId: id, paths });
+ // A caption that could not be locked (a full disk) was refused, not
+ // removed: the video is not cleared, and says why.
+ if (r.refused?.length) failures.push({ videoId: id, error: r.refused.join("; ") });
+ else succeeded++;
} catch (e) {
failures.push({ videoId: id, error: (e as Error).message });
}
diff --git a/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts
@@ -133,7 +133,7 @@ export async function clearIncompleteTranscriptOne(opts: {
slug: string;
videoId: string;
paths: Paths;
-}): Promise<{ removed: number }> {
+}): Promise<{ removed: number; refused?: string[] }> {
const { slug, videoId, paths } = opts;
const videoDir = videoDirOf(paths, slug, videoId);
const dataDir = path.resolve(paths.channelsDir, slug, "data");
@@ -154,12 +154,16 @@ export async function clearIncompleteTranscriptOne(opts: {
name === "transcript.json" ||
name === "transcript.cues.json",
);
+ const refused: string[] = [];
for (const name of toRemove) {
// Through its link when tiered (release 17): the bytes go too. A caption
// track in both forms (lib/storedText-write-server.ts): a stored copy left
- // behind would bring the cleared transcript back.
- if (isTranscriptVtt(name)) await removeStoredText(resolved, name);
- else await removeMediaFile(resolved, name);
+ // behind would bring the cleared transcript back. One that cannot be
+ // locked (a full disk, a run holding it) is refused, nothing removed.
+ if (isTranscriptVtt(name)) {
+ const out = await removeStoredText(resolved, name);
+ if ("refused" in out) refused.push(out.refused);
+ } else await removeMediaFile(resolved, name);
}
- return { removed: toRemove.length };
+ return { removed: toRemove.length - refused.length, ...(refused.length ? { refused } : {}) };
}
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -1083,6 +1083,7 @@ export async function deleteVideoFileAction(
if (out === "busy") {
return { ok: false, error: `${filename} not deleted: it is being compressed or restored right now. Try again in a moment.` };
}
+ if ("refused" in out) return { ok: false, error: out.refused };
// The pick deleted beside a stored `en` of other content: the pin went with
// it (removeStoredTextForm; REVIEW-1 N1, captions lane).
const unpinned = out.unpinned === true;