commit 507a04d310f2662c8304da32f6cf6c0c9edd8199
parent 90281df8d30d2d89613363e52cc3f57c2e054c3d
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 03:24:13 -0500
stored text, review fixes F3-F5: the restore, the walk, one-form delete
F3. `compress-text {restore: true}` puts every stored chat back into its plain
form, verified the same way in reverse: decoded beside (where the bytes are,
`wx`, no mkdir), fsynced, read back against a FRESH decode of the .zst, given
its times (the index key is unchanged), linked into place with no clobber,
its tier link with the stored link's times, and only then the .zst removed
through removeMediaFile. Killable at every step with one whole copy left; the
next restore or compress finishes from either side. dryRun answers the
stored files and their exact plain bytes; limit and one job per channel as
for a compress; person-started.
F4. The job's walk visits every dir a stopped run left: the plain form at all
(a dangling tier link too), or a leftover (temp, set-aside), or for a restore
the stored form. A leftover's name carries the pid AND the process's start
token (boot id + start time): one named with this process's pid is dead
(the per-file lock, now shared by compress, restore, settle and the files
card, excludes a live one), one of another live pid is alive only with the
same start token. A restore's unlinked copy in media/ is cleaned by a compress.
F5. The files card's delete of one named form removes both only when the two
hold the same content; otherwise only the named one, and the answer says the
other is still there (a note on the card and in delete-file's JSON).
Also: the quiet period asks max(mtime, ctime) (N4); a writer that replaced
the file mid-run keeps the new file and the older stored copy goes, also
when it lands after the set-aside (N6, the one-form rule); pinned: a stored
file missing its last 1-4 bytes decodes whole and right (N7), a 0-byte chat,
an abort and an appending writer, a kernel nanosecond mtime (mtimeMs exact,
mtimeNs within a microsecond).
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
13 files changed, 1332 insertions(+), 101 deletions(-)
diff --git a/common/controller/compressText.test.ts b/common/controller/compressText.test.ts
@@ -93,6 +93,7 @@ test("a real run with a limit compresses that many, smallest first; a re-run con
const waits: number[] = [];
const first = await compressText({
paths,
+ quietMs: 0,
slugs: ["alpha"],
limit: 1,
onLog: () => {},
@@ -107,7 +108,7 @@ test("a real run with a limit compresses that many, smallest first; a re-run con
assert.equal(await readStoredText(a2, CHAT, "utf8"), A.a2);
assert.equal(waits.length, 1, "render mode was asked before the file");
- const rest = await compressText({ paths, onLog: () => {} });
+ const rest = await compressText({ paths, quietMs: 0, slugs: ["alpha", "beta"], onLog: () => {} });
assert.equal(rest.stopped, undefined);
const byslug = Object.fromEntries(rest.channels.map((c) => [c.slug, c]));
assert.equal(byslug.alpha.compressed, 1);
@@ -118,10 +119,10 @@ test("a real run with a limit compresses that many, smallest first; a re-run con
assert.equal(await readStoredText(path.join(paths.channelsDir, slug, "data", id), CHAT, "utf8"), chat, `${slug}/${id}`);
}
}
- const again = await compressText({ paths, onLog: () => {} });
+ const again = await compressText({ paths, quietMs: 0, slugs: ["alpha", "beta"], onLog: () => {} });
assert.equal(again.channels.reduce((a, c) => a + (c.compressed ?? 0), 0), 0);
- const check = await compressText({ paths, verify: true, onLog: () => {} });
+ const check = await compressText({ paths, verify: true, slugs: ["alpha", "beta"], onLog: () => {} });
assert.deepEqual(
check.channels.map((c) => [c.slug, c.verified, c.problems?.length]),
[["alpha", 2, 0], ["beta", 1, 0]],
@@ -154,3 +155,101 @@ test("the pace: a token bucket over bytes, at whatever rate is asked each time (
await throttle(8 * 1024 * 1024);
assert.deepEqual(slept, [1000, 1000, 1000]);
});
+
+// REVIEW-1 F4(a): THE JOB VISITS EVERY DIR A STOPPED RUN LEFT, not only the
+// ones where the plain file opens. A kill after the original was set aside
+// leaves the name absent (the stored form only) beside the set-aside; a kill
+// inside the original's removal leaves a dangling tier link. Through the job
+// (compressText), each is finished: the stored form only, no leftover.
+const { CompressKill } = await import("../lib/storedText-write-server");
+const killAt = (point: string) => (p: string) => {
+ if (p === point) throw new CompressKill(p as never);
+};
+const leftovers = async (slug: string, id: string) =>
+ (await readdir(path.join(paths.channelsDir, slug, "data", id))).filter((e) => e.startsWith("."));
+
+test("the job finishes a run killed after the set-aside, and one killed inside the original's removal", async () => {
+ await channel("delta", { d1: body("d1", 500) });
+ await channel("epsilon", { e1: body("e1", 500) }, { tiered: true });
+ // A run killed at "retired" (a dead pid).
+ await assert.rejects(
+ compressText({ paths, slugs: ["delta"], quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_997, crashAt: killAt("retired") } }),
+ CompressKill,
+ );
+ const d1 = path.join(paths.channelsDir, "delta", "data", "d1");
+ assert.ok(!(await readdir(d1)).includes(CHAT), "the name is absent: the stored form only");
+ assert.equal((await leftovers("delta", "d1")).length, 1, "the set-aside original");
+ // The dry run sees the dir as work (the action starts a job for it).
+ const plan = await compressText({ paths, slugs: ["delta"], dryRun: true, onLog: () => {} });
+ assert.equal(plan.channels[0].pending, 1);
+ assert.equal(plan.channels[0].plainFiles, 0);
+ const r = await compressText({ paths, slugs: ["delta"], quietMs: 0, onLog: () => {} });
+ assert.deepEqual(await leftovers("delta", "d1"), [], "finished by the job");
+ assert.deepEqual((await readdir(d1)).sort(), ["metadata.info.json", `${CHAT}.zst`]);
+ assert.equal(await readStoredText(d1, CHAT, "utf8"), body("d1", 500));
+ assert.ok((r.channels[0].compressed ?? 0) + (r.channels[0].already ?? 0) >= 1);
+
+ // Tiered: compressed, then the plain link put back dangling (what a kill
+ // between the bytes' removal and the link's leaves).
+ assert.equal((await compressText({ paths, slugs: ["epsilon"], quietMs: 0, onLog: () => {} })).channels[0].compressed, 1);
+ const e1 = path.join(paths.channelsDir, "epsilon", "data", "e1");
+ await symlink(path.join("..", "..", "media", "e1", CHAT), path.join(e1, CHAT));
+ const before = await compressText({ paths, slugs: ["epsilon"], dryRun: true, onLog: () => {} });
+ assert.equal(before.channels[0].pending, 1, "a dangling plain link is work");
+ await compressText({ paths, slugs: ["epsilon"], quietMs: 0, onLog: () => {} });
+ assert.deepEqual((await readdir(e1)).sort(), ["metadata.info.json", `${CHAT}.zst`], "the dangling link is gone");
+ assert.equal(await readStoredText(e1, CHAT, "utf8"), body("e1", 500));
+});
+
+// REVIEW-1 F4(b), through the job: this process's pid, an earlier start.
+test("the job treats this pid's leftovers from an earlier process start as dead: a set-aside and a temp", async () => {
+ await channel("zeta", { z1: body("z1", 400), z2: body("z2", 400) });
+ await assert.rejects(
+ compressText({ paths, slugs: ["zeta"], quietMs: 0, onLog: () => {}, compressOpts: { pid: process.pid, token: "earlier0", crashAt: killAt("retired") } }),
+ CompressKill,
+ );
+ // z2: a partial temp of this pid from an earlier start, beside its plain file.
+ const z2 = path.join(paths.channelsDir, "zeta", "data", "z2");
+ await writeFile(path.join(z2, `.${CHAT}.zst.compressing-${process.pid}-earlier0`), "partial");
+ await writeFile(path.join(z2, `.${CHAT}.zst.compressing-${process.pid}`), "partial, a name from before the token");
+ await compressText({ paths, slugs: ["zeta"], quietMs: 0, onLog: () => {} });
+ for (const id of ["z1", "z2"]) {
+ assert.deepEqual(await leftovers("zeta", id), [], id);
+ assert.equal(await readStoredText(path.join(paths.channelsDir, "zeta", "data", id), CHAT, "utf8"), body(id, 400), id);
+ }
+});
+
+// REVIEW-1 F3, through the job: the restore.
+test("restore through the job: a dry run touches nothing; a restore with a limit, killed, re-run — the plain files with their times", async () => {
+ const before: Record<string, number> = {};
+ await channel("eta", { h1: body("h1", 300), h2: body("h2", 600) });
+ await channel("theta", { t1: body("t1", 300) }, { tiered: true });
+ for (const [slug, id] of [["eta", "h1"], ["eta", "h2"], ["theta", "t1"]]) {
+ before[`${slug}/${id}`] = (await lstat(path.join(paths.channelsDir, slug, "data", id, CHAT))).mtimeMs;
+ }
+ await compressText({ paths, slugs: ["eta", "theta"], quietMs: 0, onLog: () => {} });
+
+ const tr = await tree(path.join(paths.channelsDir, "eta"));
+ const plan = await compressText({ paths, slugs: ["eta"], restore: true, dryRun: true, onLog: () => {} });
+ assert.deepEqual(await tree(path.join(paths.channelsDir, "eta")), tr, "the restore's dry run touches nothing");
+ assert.equal(plan.channels[0].storedFiles, 2);
+ assert.equal(plan.channels[0].estimateAfterBytes, body("h1", 300).length + body("h2", 600).length, "exact, from the headers");
+ assert.equal(plan.channels[0].pending, 2);
+
+ const one = await compressText({ paths, slugs: ["eta"], restore: true, limit: 1, onLog: () => {} });
+ assert.equal(one.stopped, "limit");
+ assert.equal(one.channels[0].restored, 1);
+ // A run killed mid-restore (after the plain copy is placed), then re-run.
+ await assert.rejects(
+ compressText({ paths, slugs: ["eta", "theta"], restore: true, onLog: () => {}, compressOpts: { pid: 999_999_996, crashAt: killAt("restore-placed") } }),
+ CompressKill,
+ );
+ await compressText({ paths, slugs: ["eta", "theta"], restore: true, onLog: () => {} });
+ for (const [slug, id, lines] of [["eta", "h1", 300], ["eta", "h2", 600], ["theta", "t1", 300]] as const) {
+ const d = path.join(paths.channelsDir, slug, "data", id);
+ assert.deepEqual((await readdir(d)).sort(), ["metadata.info.json", CHAT], `${slug}/${id}`);
+ assert.equal(await readFile(path.join(d, CHAT), "utf8"), body(id, lines), `${slug}/${id}`);
+ assert.equal((await lstat(path.join(d, CHAT))).mtimeMs, before[`${slug}/${id}`], `${slug}/${id}: the index key`);
+ }
+ assert.deepEqual(await readdir(path.join(paths.channelsDir, "theta", "media", "t1")), [CHAT]);
+});
diff --git a/common/controller/compressText.ts b/common/controller/compressText.ts
@@ -21,6 +21,19 @@
// headers — 18 bytes each), the estimate after (labelled an estimate, at the
// ratio measured on a sample) and the free space of the disks they are on.
// `verify` decodes every stored file in full and writes nothing.
+//
+// THE WALK VISITS EVERY DIR A RUN MAY HAVE TO FINISH: one holding the plain
+// form (a dangling tier link too — an interrupted removal), or the stored form
+// (the restore), or a leftover of a stopped run (a temp, a set-aside original)
+// — so "the next run finishes it" is true through the job, not only of the
+// compressor.
+//
+// `restore: true` IS THE ROLLBACK: every stored chat put back into its plain
+// form (lib/storedText-write-server.ts restoreStoredText — decoded beside,
+// fsynced, read back against a fresh decode, the same times, and only then the
+// stored file removed). With `dryRun` it answers the stored files, the bytes
+// they will take, and the free space. Run it BEFORE reverting or running an
+// older checkout (OPERATING.md).
import path from "node:path";
import { open, readdir, stat, statfs } from "node:fs/promises";
@@ -30,9 +43,12 @@ import { storedFormsIn, storedNameOf } from "../lib/storedText";
import { frameContentSize } from "../lib/storedText-server";
import {
compressStoredText,
+ hasStoredTextLeftover,
+ restoreStoredText,
verifyStoredText,
type CompressOutcome,
type CompressSkipReason,
+ type RestoreOutcome,
} from "../lib/storedText-write-server";
import { inspectChannelMedia } from "../lib/channelMedia";
import { onDrive } from "../lib/storageHealth";
@@ -54,6 +70,8 @@ export type CompressTextOptions = {
slugs?: string[];
dryRun?: boolean;
verify?: boolean;
+ // The rollback: stored → plain (with `dryRun`: the plan).
+ restore?: boolean;
limit?: number;
quietMs?: number;
onLog: (line: string) => void;
@@ -81,7 +99,12 @@ export type ChannelLine = {
storedFiles: number;
storedLogicalBytes: number;
storedBytes: number;
- // Dry run only: what the plain files would take at the estimated ratio.
+ // The dirs a run in this mode visits (a compress: the plain form or a
+ // stopped run's leftover; a restore: the stored form or a leftover) — a
+ // dir with only a leftover still has work.
+ pending?: number;
+ // Dry run only: what the plain files would take at the estimated ratio
+ // (a restore's dry run: the stored files' logical bytes — exact).
estimateAfterBytes?: number;
// Dry run only: free space now on the disk(s) holding this channel's chats.
free?: { corpus?: number; media?: number };
@@ -93,6 +116,8 @@ export type ChannelLine = {
changed?: number;
skipped?: Partial<Record<CompressSkipReason, number>>;
failed?: { id: string; error: string }[];
+ // A restore.
+ restored?: number;
// Verify.
verified?: number;
problems?: { id: string; status: string; detail?: string }[];
@@ -101,11 +126,14 @@ export type ChannelLine = {
export type CompressTextResult = {
dryRun: boolean;
verify: boolean;
+ restore: boolean;
channels: ChannelLine[];
stopped?: "drained" | "cancelled" | "limit";
lines: string[];
};
+// A dir with work for a run: `size` is the plain file's (0 when it does not
+// open — a dangling link, or only a leftover).
type Candidate = { id: string; videoDir: string; size: number };
function fmtBytes(n: number): string {
@@ -163,11 +191,21 @@ async function storedLogicalSize(file: string): Promise<number | null> {
async function surveyChannel(
channelDir: string,
drive: string | undefined,
-): Promise<{ plain: Candidate[]; stored: { id: string; videoDir: string; bytes: number; logical: number }[] }> {
+): Promise<{
+ plain: Candidate[];
+ stored: { id: string; videoDir: string; bytes: number; logical: number }[];
+ // Every dir a compress run visits: the plain form, present at all (a
+ // dangling link included), or a stopped run's leftover.
+ work: Candidate[];
+ // Every dir a restore visits: the stored form, or a leftover.
+ restoreWork: Candidate[];
+}> {
const dataDir = path.join(channelDir, "data");
const ids = (await readdir(dataDir).catch(() => [] as string[])).sort();
const plain: Candidate[] = [];
const stored: { id: string; videoDir: string; bytes: number; logical: number }[] = [];
+ const work: Candidate[] = [];
+ const restoreWork: Candidate[] = [];
const sizeOf = (p: string) =>
(drive ? onDrive(drive, () => stat(p)) : stat(p)).then((s) => s.size, () => null);
for (const id of ids) {
@@ -175,10 +213,14 @@ async function surveyChannel(
const entries = await readdir(videoDir).catch(() => null);
if (!entries) continue;
const forms = storedFormsIn(entries, LIVE_CHAT_FILENAME);
+ const leftover = hasStoredTextLeftover(entries, LIVE_CHAT_FILENAME);
+ let size: number | null = null;
if (forms === "plain" || forms === "both") {
- const size = await sizeOf(path.join(videoDir, LIVE_CHAT_FILENAME));
+ size = await sizeOf(path.join(videoDir, LIVE_CHAT_FILENAME));
if (size !== null) plain.push({ id, videoDir, size });
}
+ if (forms === "plain" || forms === "both" || leftover) work.push({ id, videoDir, size: size ?? 0 });
+ if (forms === "zst" || forms === "both" || leftover) restoreWork.push({ id, videoDir, size: 0 });
if (forms === "zst" || forms === "both") {
const zp = path.join(videoDir, storedNameOf(LIVE_CHAT_FILENAME));
const bytes = await sizeOf(zp);
@@ -188,14 +230,17 @@ async function surveyChannel(
if (bytes !== null) stored.push({ id, videoDir, bytes, logical: logical ?? 0 });
}
}
- // Smallest first: the early files are the cheap ones.
- plain.sort((a, b) => a.size - b.size || (a.id < b.id ? -1 : 1));
- return { plain, stored };
+ // Smallest first: the early files are the cheap ones (a dir to repair, 0).
+ const bySize = (a: Candidate, b: Candidate) => a.size - b.size || (a.id < b.id ? -1 : 1);
+ plain.sort(bySize);
+ work.sort(bySize);
+ return { plain, stored, work, restoreWork };
}
export async function compressText(opts: CompressTextOptions): Promise<CompressTextResult> {
const dryRun = opts.dryRun === true;
- const verify = !dryRun && opts.verify === true;
+ const restore = opts.restore === true;
+ const verify = !dryRun && !restore && opts.verify === true;
const lines: string[] = [];
const say = (line: string) => {
lines.push(line);
@@ -206,7 +251,8 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
const throttle = byteThrottle(opts.rate ?? (() => COMPRESS_RATE_BYTES), sleep, now, opts.signal);
const slugs = opts.slugs ?? (await listChannelSlugs(opts.paths)).sort();
const channels: ChannelLine[] = [];
- let compressedThisRun = 0;
+ // Files compressed (or restored) this run: what `limit` counts.
+ let doneThisRun = 0;
let stopped: CompressTextResult["stopped"];
for (const slug of slugs) {
@@ -233,12 +279,90 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
continue;
}
const drive = media.status === "ok" ? media.target : undefined;
- const { plain, stored } = await surveyChannel(channelDir, drive);
+ const { plain, stored, work, restoreWork } = await surveyChannel(channelDir, drive);
line.plainFiles = plain.length;
line.plainBytes = plain.reduce((a, c) => a + c.size, 0);
line.storedFiles = stored.length;
line.storedBytes = stored.reduce((a, c) => a + c.bytes, 0);
line.storedLogicalBytes = stored.reduce((a, c) => a + c.logical, 0);
+ line.pending = (restore ? restoreWork : work).length;
+
+ if (dryRun && restore) {
+ // Exact, from the frame headers: what the plain files will take again.
+ line.estimateAfterBytes = line.storedLogicalBytes;
+ const freeOf = (p: string) =>
+ statfs(p).then((f) => f.bavail * f.bsize, () => undefined);
+ line.free = {
+ corpus: await freeOf(path.join(channelDir, "data")),
+ ...(drive ? { media: await onDrive(drive, () => freeOf(drive)).catch(() => undefined) } : {}),
+ };
+ if (line.storedFiles > 0) {
+ say(
+ `${slug}: ${line.storedFiles} stored chat(s), ${fmtBytes(line.storedBytes)} → ${fmtBytes(line.storedLogicalBytes)} ` +
+ `as plain files; free on ${drive ? "the media drive" : "the corpus disk"} ` +
+ `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}`,
+ );
+ }
+ continue;
+ }
+
+ if (restore) {
+ line.restored = 0;
+ line.bytesBefore = 0;
+ line.bytesAfter = 0;
+ line.already = 0;
+ line.changed = 0;
+ line.skipped = {};
+ line.failed = [];
+ for (const c of restoreWork) {
+ if (opts.signal?.aborted) { stopped = "cancelled"; break; }
+ if (opts.drainSignal?.aborted) { stopped = "drained"; break; }
+ if (opts.limit !== undefined && doneThisRun >= opts.limit) { stopped = "limit"; break; }
+ if (opts.waitForRender) {
+ const waited = await opts.waitForRender();
+ if (waited === null) { stopped = "cancelled"; break; }
+ }
+ let out: RestoreOutcome;
+ try {
+ out = await restoreStoredText(c.videoDir, LIVE_CHAT_FILENAME, {
+ isBusy: opts.isBusy ? () => opts.isBusy!(slug, c.id) : undefined,
+ throttle,
+ ...(opts.signal ? { signal: opts.signal } : {}),
+ onLog: (l) => opts.onLog(`${l}\n`),
+ ...opts.compressOpts,
+ });
+ } catch (err) {
+ if ((err as Error).name === "CompressKill") throw err;
+ line.failed.push({ id: c.id, error: (err as Error).message });
+ say(`${slug}/${c.id}: failed — ${(err as Error).message} (the stored file is untouched)`);
+ continue;
+ }
+ if (out.status === "restored") {
+ doneThisRun += 1;
+ line.restored += 1;
+ line.bytesBefore += out.before;
+ line.bytesAfter += out.after;
+ opts.onLog(`${slug}/${c.id}: ${fmtBytes(out.before)} → ${fmtBytes(out.after)} (restored)${out.tiered ? " (media tier)" : ""}\n`);
+ } else if (out.status === "already") {
+ line.already += 1;
+ } else if (out.status === "changed") {
+ line.changed += 1;
+ } else if (out.status === "skipped") {
+ line.skipped[out.reason] = (line.skipped[out.reason] ?? 0) + 1;
+ if (out.reason === "both-differ" || out.reason === "stored-corrupt" || out.reason === "retired-kept") {
+ say(`${slug}/${c.id}: refused — ${out.reason}${out.detail ? ` (${out.detail})` : ""}; both files are kept`);
+ }
+ }
+ }
+ const skippedText = Object.entries(line.skipped).map(([r, n]) => `${n} ${r}`).join(", ");
+ if (restoreWork.length > 0) {
+ say(
+ `${slug}: restored ${line.restored} (${fmtBytes(line.bytesBefore)} → ${fmtBytes(line.bytesAfter)}), ` +
+ `already plain ${line.already}, changed ${line.changed}, skipped ${skippedText || "0"}, failed ${line.failed.length}`,
+ );
+ }
+ continue;
+ }
if (dryRun) {
line.estimateAfterBytes = Math.round(line.plainBytes * CHAT_RATIO_ESTIMATE);
@@ -280,14 +404,17 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
line.compressed = 0;
line.bytesBefore = 0;
line.bytesAfter = 0;
- line.already = line.storedFiles;
+ // A stored dir with nothing to finish is "already"; one in `work` says so
+ // itself.
+ const inWork = new Set(work.map((c) => c.id));
+ line.already = stored.filter((z) => !inWork.has(z.id)).length;
line.changed = 0;
line.skipped = {};
line.failed = [];
- for (const c of plain) {
+ for (const c of work) {
if (opts.signal?.aborted) { stopped = "cancelled"; break; }
if (opts.drainSignal?.aborted) { stopped = "drained"; break; }
- if (opts.limit !== undefined && compressedThisRun >= opts.limit) { stopped = "limit"; break; }
+ if (opts.limit !== undefined && doneThisRun >= opts.limit) { stopped = "limit"; break; }
if (opts.waitForRender) {
const waited = await opts.waitForRender();
if (waited === null) { stopped = "cancelled"; break; }
@@ -310,7 +437,7 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
continue;
}
if (out.status === "compressed") {
- compressedThisRun += 1;
+ doneThisRun += 1;
line.compressed += 1;
line.bytesBefore += out.before;
line.bytesAfter += out.after;
@@ -329,7 +456,7 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
const skippedText = Object.entries(line.skipped)
.map(([r, n]) => `${n} ${r}`)
.join(", ");
- if (line.plainFiles + line.storedFiles > 0) {
+ if (work.length + line.storedFiles > 0) {
say(
`${slug}: compressed ${line.compressed} (${fmtBytes(line.bytesBefore)} → ${fmtBytes(line.bytesAfter)}), ` +
`already ${line.already}, changed ${line.changed}, skipped ${skippedText || "0"}, failed ${line.failed.length}`,
@@ -337,7 +464,15 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
}
}
- if (dryRun) {
+ if (dryRun && restore) {
+ const tot = channels.reduce((a, c) => a + c.storedLogicalBytes, 0);
+ const n = channels.reduce((a, c) => a + c.storedFiles, 0);
+ say(`Dry run (restore): ${n} stored chat(s) → ${fmtBytes(tot)} as plain files. Nothing was written.`);
+ } else if (restore) {
+ const r = channels.reduce((a, l) => a + (l.restored ?? 0), 0);
+ const f = channels.reduce((a, l) => a + (l.bytesAfter ?? 0), 0);
+ say(`Restored ${r} raw chat(s) to their plain form (${fmtBytes(f)})${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`);
+ } else if (dryRun) {
const tot = channels.reduce((a, c) => a + c.plainBytes, 0);
const n = channels.reduce((a, c) => a + c.plainFiles, 0);
say(`Dry run: ${n} raw chat(s), ${fmtBytes(tot)} → ~${fmtBytes(Math.round(tot * CHAT_RATIO_ESTIMATE))} (estimate). Nothing was written.`);
@@ -347,5 +482,5 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
const f = channels.reduce((a, l) => a + (l.bytesAfter ?? 0), 0);
say(`Compressed ${c} raw chat(s): ${fmtBytes(b)} → ${fmtBytes(f)}${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`);
}
- return { dryRun, verify, channels, ...(stopped ? { stopped } : {}), lines };
+ return { dryRun, verify, restore, channels, ...(stopped ? { stopped } : {}), lines };
}
diff --git a/common/controller/storedText.delete.test.ts b/common/controller/storedText.delete.test.ts
@@ -78,3 +78,83 @@ test("the superseded-auto-caption purge removes a caption's stored sibling too",
assert.equal(r.removedFiles, 1);
assert.deepEqual((await readdir(d)).sort(), ["transcript.json"]);
});
+
+// REVIEW-1 F5: THE FILES CARD'S DELETE OF ONE NAMED FORM
+// (`removeStoredTextForm`, what deleteVideoFileAction and `pnpm ops
+// delete-file` run). Before: a click on the plain name removed BOTH forms
+// (`removeStoredText`), even when the stored one held different content — the
+// only whole capture, maybe. Now: the same content, both go; different content
+// (or a form that cannot be read whole), only the named one, and the answer
+// names the other.
+const { removeStoredTextForm } = await import("../lib/storedText-write-server");
+
+test("delete one named form: the same content takes both; different content takes only the named one", async () => {
+ const ZST = `${CHAT}.zst`;
+ // Same content, either name clicked.
+ for (const clicked of [CHAT, ZST]) {
+ const d = await videoDir("f5same", clicked);
+ await writeFile(path.join(d, CHAT), "SAME\n");
+ await storeFixture(d, CHAT, { keepPlain: true });
+ const out = await removeStoredTextForm(d, clicked);
+ assert.notEqual(out, "busy");
+ assert.deepEqual(out !== "busy" && out.removed.sort(), [CHAT, ZST]);
+ assert.deepEqual(await readdir(d), [], `${clicked}: both gone`);
+ }
+ // Different content: the plain one clicked — the stored one is kept, and read.
+ {
+ const d = await videoDir("f5diff", "plain");
+ await writeFile(path.join(d, CHAT), "OLD WHOLE CAPTURE\n");
+ await storeFixture(d, CHAT);
+ await writeFile(path.join(d, CHAT), "NEWER, TRIMMED\n");
+ const out = await removeStoredTextForm(d, CHAT);
+ assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, why: "differs" } });
+ assert.deepEqual(await readdir(d), [ZST]);
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "OLD WHOLE CAPTURE\n");
+ }
+ // Different content: the stored one clicked — the plain one is kept.
+ {
+ const d = await videoDir("f5diff", "stored");
+ await writeFile(path.join(d, CHAT), "OLD\n");
+ await storeFixture(d, CHAT);
+ await writeFile(path.join(d, CHAT), "NEW\n");
+ const out = await removeStoredTextForm(d, ZST);
+ assert.deepEqual(out, { removed: [ZST], kept: { name: CHAT, why: "differs" } });
+ assert.deepEqual(await readdir(d), [CHAT]);
+ }
+ // One form only: it goes.
+ {
+ const d = await videoDir("f5one", "v");
+ await writeFile(path.join(d, CHAT), "ONLY\n");
+ await storeFixture(d, CHAT);
+ assert.deepEqual(await removeStoredTextForm(d, ZST), { removed: [ZST] });
+ assert.deepEqual(await readdir(d), []);
+ }
+});
+
+test("delete one named form through tier links: the same content takes both forms' bytes; a dangling plain link never takes the stored copy", async () => {
+ const ZST = `${CHAT}.zst`;
+ const d = await videoDir("f5t", "v5");
+ const media = path.join(ROOT, "channels", "f5t", "media", "v5");
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, CHAT), "TIERED\n");
+ await symlink(path.join("..", "..", "media", "v5", CHAT), path.join(d, CHAT));
+ await storeFixture(d, CHAT, { keepPlain: true });
+ assert.deepEqual((await removeStoredTextForm(d, CHAT)) !== "busy" && "ok", "ok");
+ assert.deepEqual(await readdir(d), []);
+ assert.equal(await exists(path.join(media, CHAT)), false);
+ assert.equal(await exists(path.join(media, ZST)), false);
+
+ // The plain link's bytes gone (an interrupted removal): clicking the plain
+ // name removes only that link — the stored copy cannot be compared, so it
+ // stays, and is what readers read.
+ const e = await videoDir("f5t", "v6");
+ const media6 = path.join(ROOT, "channels", "f5t", "media", "v6");
+ await mkdir(media6, { recursive: true });
+ await writeFile(path.join(media6, CHAT), "ONLY COPY\n");
+ await symlink(path.join("..", "..", "media", "v6", CHAT), path.join(e, CHAT));
+ await storeFixture(e, CHAT);
+ await symlink(path.join("..", "..", "media", "v6", CHAT), path.join(e, CHAT));
+ const out = await removeStoredTextForm(e, CHAT);
+ assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, why: "unreadable" } });
+ assert.equal(await readStoredText(e, CHAT, "utf8"), "ONLY COPY\n");
+});
diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts
@@ -16,8 +16,9 @@
import path from "node:path";
import { createHash } from "node:crypto";
-import { createReadStream, type Stats } from "node:fs";
+import { createReadStream, readFileSync, type Stats } from "node:fs";
import {
+ link,
lstat,
lutimes,
open,
@@ -41,7 +42,7 @@ import {
} from "./mediaTier-server";
import { onDrive, stalledLocationForPath } from "./storageHealth";
import { LIVE_RECORDING_FILENAME } from "./liveCapture";
-import { isStoredTextName, storedNameOf } from "./storedText";
+import { isStoredTextName, plainNameOf, storedNameOf } from "./storedText";
import {
StoredTextCorruptError,
createStoredTextCompressor,
@@ -80,12 +81,23 @@ export async function removeStoredText(videoDir: string, name: string): Promise<
// writer that replaced P meanwhile is put back: outcome `changed`.
// 6. A real Z on a channel with a media tier is tiered by the hook.
//
-// A RUN AFTER A KILL AT ANY STEP finishes or undoes it: a dead pid's temp is
+// A RUN AFTER A KILL AT ANY STEP finishes or undoes it: a dead run's temp is
// discarded; a Z beside P is verified against P before P goes; a retired P
// whose name is free is renamed back (and then verified like any P); a
// dangling P beside a whole Z is removed. BOTH FORMS PRESENT WITH DIFFERENT
// CONTENT is refused and reported — nothing is touched, and readers keep
// reading the plain one.
+//
+// A LEFTOVER IS DEAD unless the process that named it is running NOW: its
+// name carries the pid and that process's START TOKEN (boot id + start time,
+// `processStartToken`), so a pid reused by a later process — an editor
+// container that comes back with the same pid — does not keep a dead run's
+// set-aside alive. A leftover named with THIS process's pid is dead too: the
+// per-file lock below means no run of ours is on this file at this moment.
+//
+// A WRITER THAT REPLACED P DURING A RUN (`changed`): the new P is the truth
+// and is kept; the stored form beside it is OLDER content and is removed, so
+// one form is left (THE ONE-FORM RULE, `settleStoredTextAfterWrite`).
export type CompressSkipReason =
| "not-declared"
@@ -118,7 +130,13 @@ export type CompressKillPoint =
| "verified" // T verified, not renamed
| "placed" // Z in place (tiered: no link yet)
| "linked" // Z's tier link placed
- | "retired"; // P set aside, not removed
+ | "retired" // P set aside, not removed
+ // The restore (`restoreStoredText`), in its order:
+ | "restoring" // R (the plain temp) partly written
+ | "restore-written" // R whole and fsynced, not verified
+ | "restore-verified" // R verified against a fresh decode of Z, not placed
+ | "restore-placed" // P in place (tiered: in media/<id>/, no link yet)
+ | "restore-linked"; // P's tier link placed; Z not yet removed
export class CompressKill extends Error {
constructor(readonly point: CompressKillPoint) {
@@ -137,8 +155,10 @@ export type CompressOptions = {
throttle?: (bytes: number) => Promise<void>;
// Free space the disk must keep beyond the temp (default 2 GiB).
reserveBytes?: number;
- // The pid temps are named for (tests: a dead one, to stand for a kill).
+ // The pid and start token temps are named for (tests: a dead pid, to stand
+ // for a kill).
pid?: number;
+ token?: string;
crashAt?: (point: CompressKillPoint) => void;
signal?: AbortSignal;
onLog?: (line: string) => void;
@@ -154,7 +174,6 @@ function errCode(err: unknown): string | undefined {
}
function processAlive(pid: number): boolean {
- if (pid === process.pid) return true;
try {
process.kill(pid, 0);
return true;
@@ -163,6 +182,61 @@ function processAlive(pid: number): boolean {
}
}
+// ── WHO NAMED A LEFTOVER, AND IS IT STILL RUNNING ───────────────────────────
+//
+// A process's START TOKEN: the kernel's boot id (8 hex) and the process's
+// start time in clock ticks since boot (`/proc/<pid>/stat` field 22), base
+// 36. Two processes that ever had the same pid on this machine have different
+// tokens. Where there is no /proc, this process's token is its time origin and
+// another's is unknown (null).
+function bootIdPrefix(): string {
+ try {
+ return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").replace(/[^0-9a-f]/g, "").slice(0, 8);
+ } catch {
+ return "";
+ }
+}
+
+export function processStartToken(pid: number = process.pid): string | null {
+ try {
+ const s = readFileSync(`/proc/${pid}/stat`, "utf8");
+ // After the command's ")" the fields start at field 3; field 22 is the
+ // start time.
+ const ticks = s.slice(s.lastIndexOf(")") + 2).split(" ")[19];
+ if (ticks && /^\d+$/.test(ticks)) return `${bootIdPrefix()}${Number(ticks).toString(36)}`;
+ } catch {
+ /* no /proc, or the process is gone */
+ }
+ return pid === process.pid ? `t${Math.floor(performance.timeOrigin).toString(36)}` : null;
+}
+
+let ownToken: string | undefined;
+function selfToken(): string {
+ return (ownToken ??= processStartToken(process.pid) ?? "t0");
+}
+
+// A leftover's suffix: `-<pid>-<token>` (a name from before the token,
+// `-<pid>`, is still read).
+const LEFTOVER_SUFFIX = "-(\\d+)(?:-([0-9a-z]+))?";
+
+type Owner = { pid: number; token?: string };
+
+// Is the run that named this leftover running now? Never this process's own
+// (`self`): the per-file lock means none of ours is on the file. Another pid:
+// alive AND (when the name carries a token) the same process start.
+function ownerRunning(owner: Owner, self: number): boolean {
+ if (owner.pid === self) return false;
+ if (!processAlive(owner.pid)) return false;
+ if (owner.token === undefined) return true; // a pid-only name: cannot tell, so alive
+ const now = processStartToken(owner.pid);
+ return now === null || now === owner.token;
+}
+
+function ownerOf(m: RegExpExecArray | null): Owner | null {
+ if (!m) return null;
+ return { pid: Number(m[1]), ...(m[2] ? { token: m[2] } : {}) };
+}
+
const lstatOrNull = (p: string) => lstat(p).catch(() => null);
async function fsyncDir(dir: string): Promise<void> {
@@ -321,66 +395,114 @@ async function storedPathOf(videoDir: string, name: string): Promise<string | nu
return null;
}
-// One compression per file in this process at a time (the migration and a
-// finalise could otherwise meet on one file and remove each other's temp).
+// ONE RUN PER FILE in this process at a time — the compressor, the restore,
+// the one-form settle and the files card's delete. Two of them on one file
+// could remove each other's temp; and because of this lock, a leftover named
+// with this process's pid is never a run in progress.
const active = new Set<string>();
-export async function compressStoredText(
- videoDir: string,
- name: string,
- opts: CompressOptions = {},
-): Promise<CompressOutcome> {
- if (!isStoredTextName(name)) return { status: "skipped", reason: "not-declared" };
+async function withFileLock<T>(videoDir: string, name: string, busy: T, fn: () => Promise<T>): Promise<T> {
const key = path.resolve(videoDir, name);
- if (active.has(key)) return { status: "skipped", reason: "busy", detail: "being compressed" };
+ if (active.has(key)) return busy;
active.add(key);
try {
- return await compressOne(videoDir, name, opts);
+ return await fn();
} finally {
active.delete(key);
}
}
-async function compressOne(videoDir: string, name: string, opts: CompressOptions): Promise<CompressOutcome> {
- const pid = opts.pid ?? process.pid;
- const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
- const log = opts.onLog ?? (() => {});
+export async function compressStoredText(
+ videoDir: string,
+ name: string,
+ opts: CompressOptions = {},
+): Promise<CompressOutcome> {
+ if (!isStoredTextName(name)) return { status: "skipped", reason: "not-declared" };
+ return withFileLock(videoDir, name, { status: "skipped", reason: "busy", detail: "being compressed" } as CompressOutcome, () =>
+ compressOne(videoDir, name, opts),
+ );
+}
+
+// The leftovers a run of the compressor or the restore leaves in a dir, by
+// name: temps (never a copy) and the compressor's set-aside original.
+function leftoverRes(name: string) {
const stored = storedNameOf(name);
+ return {
+ // `.X.zst.compressing-…`, `.X.zst.tierlink-…`, `.X.restoring-…`, `.X.tierlink-…`
+ temp: new RegExp(
+ `^\\.(?:${escapeRe(stored)}\\.(?:compressing|tierlink)|${escapeRe(name)}\\.(?:restoring|tierlink))${LEFTOVER_SUFFIX}$`,
+ ),
+ retire: new RegExp(`^\\.${escapeRe(name)}\\.retire${LEFTOVER_SUFFIX}$`),
+ };
+}
+
+// Does this listing hold a leftover of a run on `name`? (What the job's
+// survey visits even when neither form is there.)
+export function hasStoredTextLeftover(entries: readonly string[], name: string): boolean {
+ const re = leftoverRes(name);
+ return entries.some((e) => re.temp.test(e) || re.retire.test(e));
+}
+
+type RunCtx = {
+ pid: number;
+ token: string;
+ log: (line: string) => void;
+ reachable: () => Promise<"yes" | "no" | "none">;
+};
+
+function runCtx(videoDir: string, opts: CompressOptions): RunCtx {
const channelDir = path.dirname(path.dirname(videoDir));
+ let reach: "yes" | "no" | "none" | undefined;
+ return {
+ pid: opts.pid ?? process.pid,
+ token: opts.token ?? selfToken(),
+ log: opts.onLog ?? (() => {}),
+ reachable: async () => (reach ??= await mediaReachable(channelDir)),
+ };
+}
+
+// Dead runs' temps in `dir` removed — scratch, never a copy.
+async function removeDeadTemps(dir: string, name: string, ctx: RunCtx): Promise<"ok" | "live"> {
+ const re = leftoverRes(name);
+ let live = false;
+ for (const e of await readdir(dir).catch(() => [] as string[])) {
+ const owner = ownerOf(re.temp.exec(e));
+ if (!owner) continue;
+ if (ownerRunning(owner, ctx.pid)) live = true;
+ else await rm(path.join(dir, e), { force: true });
+ }
+ return live ? "live" : "ok";
+}
+
+// REPAIR, BEFORE ANY RUN ON A FILE (the compressor's and the restore's): a dead
+// run's leftovers in the video dir, each finished or undone. A live one of
+// another process: "busy". Null: carry on.
+async function repairLeftovers(
+ videoDir: string,
+ name: string,
+ entries: readonly string[],
+ ctx: RunCtx,
+): Promise<CompressOutcome | null> {
const skip = (reason: CompressSkipReason, detail?: string): CompressOutcome => ({
status: "skipped",
reason,
...(detail ? { detail } : {}),
});
-
- // ── refusals: nothing is touched ──────────────────────────────────────────
- if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
- const entries = await readdir(videoDir).catch(() => [] as string[]);
- if (entries.some((e) => e.startsWith(`${name}.part`))) return skip("partial");
- if (await recordingNow(videoDir)) return skip("recording");
- if (opts.isBusy?.()) return skip("busy");
-
- let reach: "yes" | "no" | "none" | undefined;
- const reachable = async () => (reach ??= await mediaReachable(channelDir));
-
- // ── repair: a dead run's leftovers in the video dir ───────────────────────
- const tempRe = new RegExp(`^\\.${escapeRe(stored)}\\.(?:compressing|tierlink)-(\\d+)$`);
- const retireRe = new RegExp(`^\\.${escapeRe(name)}\\.retire-(\\d+)$`);
- const dead = (m: RegExpExecArray | null) => !!m && Number(m[1]) !== pid && !processAlive(Number(m[1]));
- for (const e of entries) {
- // Scratch of a run that is gone (a temp, a temp link): never a copy.
- if (dead(tempRe.exec(e))) await rm(path.join(videoDir, e), { force: true });
- }
+ if ((await removeDeadTemps(videoDir, name, ctx)) === "live") return skip("busy", "another process is on this file");
+ const re = leftoverRes(name);
for (const e of entries) {
- if (!dead(retireRe.exec(e))) continue;
+ const owner = ownerOf(re.retire.exec(e));
+ if (!owner) continue;
+ if (ownerRunning(owner, ctx.pid)) return skip("busy", "another process is on this file");
const r = await entryAt(videoDir, e);
- if (r.kind === "link" && (await reachable()) !== "yes") return skip("unreachable");
+ if (r.kind === "none") continue;
+ if (r.kind === "link" && (await ctx.reachable()) !== "yes") return skip("unreachable");
const p = await entryAt(videoDir, name);
if (p.kind === "none") {
// The original was set aside and not removed: it is the file again,
- // and is verified below like any plain file.
+ // and is verified like any plain file.
await rename(path.join(videoDir, e), path.join(videoDir, name));
- log(` restored ${e} as ${name}`);
+ ctx.log(` restored ${e} as ${name}`);
continue;
}
if (r.kind === "link" && p.kind === "link" && r.target !== "" && r.target === p.target) {
@@ -404,6 +526,59 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
if (!removable) return skip("retired-kept", e);
await removeMediaFile(videoDir, e);
}
+ return null;
+}
+
+// A plain file in media/<id>/ with no link to it, beside a stored form's
+// bytes there: what a restore killed between placing and linking leaves.
+// Removed when it is the stored content exactly (a copy; the stored form
+// stays whole), else kept for a person.
+async function leftoverPlainInMedia(
+ videoDir: string,
+ name: string,
+ zTarget: string,
+ ctx: RunCtx,
+): Promise<CompressOutcome | null> {
+ const mediaDir = path.dirname(zTarget);
+ if ((await removeDeadTemps(mediaDir, name, ctx)) === "live") {
+ return { status: "skipped", reason: "busy", detail: "another process is on this file" };
+ }
+ const beside = path.join(mediaDir, name);
+ if (!(await lstatOrNull(beside))?.isFile()) return null;
+ const [bd, zd] = await Promise.all([
+ digestOf(beside).catch(() => null),
+ digestOf(zTarget, { decode: true }).catch(() => null),
+ ]);
+ if (bd && zd && bd.sha === zd.sha && bd.bytes === zd.bytes) {
+ await rm(beside);
+ ctx.log(` removed an unlinked copy of ${name} in media/ (a restore that was stopped)`);
+ return null;
+ }
+ return { status: "skipped", reason: "retired-kept", detail: `media/${path.basename(mediaDir)}/${name}` };
+}
+
+async function compressOne(videoDir: string, name: string, opts: CompressOptions): Promise<CompressOutcome> {
+ const ctx = runCtx(videoDir, opts);
+ const { pid, token, log, reachable } = ctx;
+ const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
+ const stored = storedNameOf(name);
+ const channelDir = path.dirname(path.dirname(videoDir));
+ const skip = (reason: CompressSkipReason, detail?: string): CompressOutcome => ({
+ status: "skipped",
+ reason,
+ ...(detail ? { detail } : {}),
+ });
+
+ // ── refusals: nothing is touched ──────────────────────────────────────────
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.some((e) => e.startsWith(`${name}.part`))) return skip("partial");
+ if (await recordingNow(videoDir)) return skip("recording");
+ if (opts.isBusy?.()) return skip("busy");
+
+ // ── repair: a dead run's leftovers in the video dir ───────────────────────
+ const repaired = await repairLeftovers(videoDir, name, entries, ctx);
+ if (repaired) return repaired;
// ── the plain file ────────────────────────────────────────────────────────
const p = await entryAt(videoDir, name);
@@ -411,6 +586,13 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
if (zEntry.kind === "other") return skip("not-a-file", stored);
if (p.kind === "none") {
if (zEntry.kind === "none") return { status: "absent" };
+ if (zEntry.kind === "link" && zEntry.inMedia) {
+ if ((await reachable()) !== "yes") return skip("unreachable");
+ // A restore killed after it placed the plain bytes in media/<id>/ and
+ // before their link: a copy of the stored content, which is kept.
+ const left = await leftoverPlainInMedia(videoDir, name, zEntry.target, ctx);
+ if (left) return left;
+ }
if (zEntry.kind === "real") await tierMediaFile(videoDir, stored, { onLog: log });
const z = await storedPathOf(videoDir, name);
return { status: "already", after: z ? ((await stat(z).catch(() => null))?.size ?? 0) : 0 };
@@ -443,17 +625,17 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
}
if (!s.isFile()) return skip("not-a-file");
const now = opts.now ?? Date.now;
- if (opts.quietMs && now() - s.mtimeMs < opts.quietMs) return skip("recent");
+ // The later of mtime and ctime: a backdated mtime (`touch -d`, a copy
+ // that kept its times) is no proof the file is not being written.
+ if (opts.quietMs && now() - Math.max(s.mtimeMs, s.ctimeMs) < opts.quietMs) return skip("recent");
const tiered = p.kind === "link";
const workDir = tiered ? path.dirname(p.target) : videoDir;
const bytesPath = tiered ? p.target : p.path;
const first = identOf(s);
- if (workDir !== videoDir) {
- for (const e of await readdir(workDir).catch(() => [] as string[])) {
- if (dead(tempRe.exec(e))) await rm(path.join(workDir, e), { force: true });
- }
+ if (workDir !== videoDir && (await removeDeadTemps(workDir, name, ctx)) === "live") {
+ return skip("busy", "another process is on this file");
}
// ── the stored form: already there (a run killed after it landed), or made ─
@@ -489,7 +671,7 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
() => Infinity,
);
if (free < s.size * 0.3 + (opts.reserveBytes ?? 2 * 1024 ** 3)) return skip("low-space");
- const made = await makeStored(bytesPath, workDir, stored, s, first, pid, opts);
+ const made = await makeStored(bytesPath, workDir, stored, s, first, `${pid}-${token}`, opts);
if (made !== "ok") return made;
zPath = path.join(workDir, stored);
crash("placed");
@@ -497,7 +679,7 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
// ── its tier link ─────────────────────────────────────────────────────────
if (tiered && zKind === "none") {
- const tmpLink = path.join(videoDir, `.${stored}.tierlink-${pid}`);
+ const tmpLink = path.join(videoDir, `.${stored}.tierlink-${pid}-${token}`);
await rm(tmpLink, { force: true });
await symlink(path.relative(videoDir, zPath), tmpLink);
// The PLAIN LINK's times: what an `lstat` of the name answered.
@@ -514,7 +696,7 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
// rule): the original stays — the stored form beside it is the same
// content, and the next run finishes.
if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
- const retired = `.${name}.retire-${pid}`;
+ const retired = `.${name}.retire-${pid}-${token}`;
const retiredPath = path.join(videoDir, retired);
await rename(p.path, retiredPath);
crash("retired");
@@ -522,6 +704,7 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
const nowS = await stat(retiredPath).catch(() => null);
if (!(nowL && nowS && nowL.ino === p.l.ino && sameIdent(identOf(nowS), first))) {
// A writer replaced the file after it was read: it is the truth again.
+ let kept = false;
if (!(await lstatOrNull(p.path))) {
await rename(retiredPath, p.path);
} else {
@@ -536,14 +719,35 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
const zd = await digestOf(zPath, { decode: true }).catch(() => null);
const rd = await digestOf(retiredPath).catch(() => null);
if (zd && rd && zd.sha === rd.sha && zd.bytes === rd.bytes) await removeMediaFile(videoDir, retired);
- else log(` kept ${retired} beside the newer ${name}: it is neither`);
+ else {
+ kept = true;
+ log(` kept ${retired} beside the newer ${name}: it is neither`);
+ }
}
}
- log(` ${name} changed while it was being compressed: left for the next run`);
+ // THE ONE-FORM RULE: the plain file now under the name is the newer
+ // write; the stored form beside it holds the content it replaced, and
+ // goes — one form is left, and the next run compresses the new file.
+ // Not when a set-aside was kept for a person: nothing more is touched.
+ if (!kept && (await wholePlainAt(videoDir, name))) {
+ await removeMediaFile(videoDir, stored);
+ await fsyncDir(videoDir);
+ }
+ log(` ${name} changed while it was being compressed: the new file is kept, the older stored copy removed; the next run compresses it`);
return { status: "changed" };
}
await removeMediaFile(videoDir, retired);
await fsyncDir(videoDir);
+ // A writer that landed a new file under the name after the original was
+ // set aside: the one-form rule, as for `changed` above. (Only when the new
+ // file opens whole — never the stored form removed beside a name whose
+ // bytes are gone.)
+ if (await wholePlainAt(videoDir, name)) {
+ await removeMediaFile(videoDir, stored);
+ await fsyncDir(videoDir);
+ log(` ${name} was written again while it was being compressed: the new file is kept, the older stored copy removed`);
+ return { status: "changed" };
+ }
// ── a real stored file on a channel with a media tier: the hook ───────────
let nowTiered = tiered && zKind !== "real";
@@ -554,6 +758,11 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
class ChangedError extends Error {}
+// A plain file under the name that opens as a regular file (through its link).
+async function wholePlainAt(videoDir: string, name: string): Promise<boolean> {
+ return stat(path.join(videoDir, name)).then((st) => st.isFile(), () => false);
+}
+
// Steps 1–3: S → T (verified) → Z. "ok", or the outcome that stops the file.
async function makeStored(
bytesPath: string,
@@ -561,10 +770,10 @@ async function makeStored(
stored: string,
s: Stats,
first: Ident,
- pid: number,
+ owner: string, // `<pid>-<token>`
opts: CompressOptions,
): Promise<"ok" | CompressOutcome> {
- const tmp = path.join(workDir, `.${stored}.compressing-${pid}`);
+ const tmp = path.join(workDir, `.${stored}.compressing-${owner}`);
const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
try {
const fh = await open(tmp, "wx");
@@ -670,3 +879,347 @@ export async function verifyStoredText(
}
return { status: "ok", bytes: zd.bytes };
}
+
+// ── THE RESTORE ─────────────────────────────────────────────────────────────
+//
+// `restoreStoredText(videoDir, name)` puts ONE stored file back into its plain
+// form — the compressor in reverse, for a rollback (OPERATING.md: restore
+// BEFORE reverting or running an older checkout, which cannot read a `.zst`).
+// Where the bytes are, never across disks, no `mkdir`:
+//
+// 1. Z is decoded into a temp R (`.<name>.restoring-<pid>-<token>`, `wx`,
+// in the dir that holds Z's bytes) through sha256; R is fsynced, and its
+// length must be the frame header's content size.
+// 2. R is read back from disk through sha256 and must equal a FRESH decode
+// of Z (a second read of Z, not the first stream), and Z must be
+// unchanged (inode, size, mtime).
+// 3. R is given Z's times (numeric seconds: Z carries the original's) and
+// linked to P with no clobber (`link`: a P that appeared meanwhile is
+// never replaced), R's name removed, the dir fsynced.
+// 4. Tiered: P's link is placed with Z's link's own times (the name's
+// `lstat` answers what it did), no clobber, the dir fsynced.
+// 5. Z goes, through `removeMediaFile` (its link and its bytes).
+//
+// A kill at any step leaves Z whole and untouched until step 5, and from step
+// 3 on a whole P beside it with the same content; the next run (a restore, or
+// a compress) finishes from either. Plain beside stored with the same content
+// is finished by removing Z; with different content it is refused.
+
+export type RestoreOutcome =
+ | { status: "restored"; before: number; after: number; tiered: boolean }
+ | { status: "already" } // the plain form only
+ | { status: "absent" }
+ | { status: "changed" }
+ | { status: "skipped"; reason: CompressSkipReason; detail?: string };
+
+export async function restoreStoredText(
+ videoDir: string,
+ name: string,
+ opts: CompressOptions = {},
+): Promise<RestoreOutcome> {
+ if (!isStoredTextName(name)) return { status: "skipped", reason: "not-declared" };
+ return withFileLock(videoDir, name, { status: "skipped", reason: "busy", detail: "being compressed or restored" } as RestoreOutcome, () =>
+ restoreOne(videoDir, name, opts),
+ );
+}
+
+async function restoreOne(videoDir: string, name: string, opts: CompressOptions): Promise<RestoreOutcome> {
+ const ctx = runCtx(videoDir, opts);
+ const { pid, token, log, reachable } = ctx;
+ const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
+ const stored = storedNameOf(name);
+ const channelDir = path.dirname(path.dirname(videoDir));
+ const skip = (reason: CompressSkipReason, detail?: string): RestoreOutcome => ({
+ status: "skipped",
+ reason,
+ ...(detail ? { detail } : {}),
+ });
+
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.some((e) => e.startsWith(`${name}.part`))) return skip("partial");
+ if (await recordingNow(videoDir)) return skip("recording");
+ if (opts.isBusy?.()) return skip("busy");
+ const repaired = await repairLeftovers(videoDir, name, entries, ctx);
+ if (repaired) return repaired as RestoreOutcome;
+
+ const z = await entryAt(videoDir, stored);
+ let p = await entryAt(videoDir, name);
+ if (z.kind === "none") return p.kind === "none" ? { status: "absent" } : { status: "already" };
+ if (z.kind === "other") return skip("not-a-file", stored);
+ if (z.kind === "link" && !z.inMedia) return skip("foreign-link", stored);
+ if (p.kind === "other") return skip("not-a-file");
+ if ((z.kind === "link" || p.kind === "link") && (await reachable()) !== "yes") return skip("unreachable");
+ const zPath = await storedPathOf(videoDir, name);
+
+ // A plain link whose bytes are gone (a compress stopped inside the
+ // original's removal): with a whole stored form, the link goes and the
+ // restore proceeds.
+ if (p.kind === "link" && !(await stat(p.path).then((st) => st.isFile(), () => false))) {
+ if (!zPath) return skip("dangling");
+ try {
+ await digestOf(zPath, { decode: true });
+ } catch (e) {
+ return skip("stored-corrupt", (e as Error).message);
+ }
+ await removeMediaFile(videoDir, name);
+ p = { kind: "none" };
+ }
+ if (!zPath) {
+ // A stored link whose bytes are gone: with a plain file, only the link.
+ if (p.kind === "none") return skip("dangling", stored);
+ await removeMediaFile(videoDir, stored);
+ return { status: "already" };
+ }
+
+ let zd: Digest;
+ try {
+ zd = await digestOf(zPath, { decode: true, throttle: opts.throttle });
+ } catch (e) {
+ return skip("stored-corrupt", (e as Error).message);
+ }
+ const zStat = await stat(zPath);
+ const zFirst = identOf(zStat);
+ const tiered = z.kind === "link";
+ const workDir = tiered ? path.dirname(zPath) : videoDir;
+
+ // ── both forms: the plain one is a whole copy, or it is not ───────────────
+ if (p.kind !== "none") {
+ const pd = await digestOf(p.path, { throttle: opts.throttle }).catch(() => null);
+ if (!pd || pd.sha !== zd.sha || pd.bytes !== zd.bytes) {
+ return skip("both-differ", `${name} and ${stored} differ`);
+ }
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ await removeMediaFile(videoDir, stored);
+ await fsyncDir(videoDir);
+ return { status: "restored", before: zStat.size, after: zd.bytes, tiered: p.kind === "link" };
+ }
+
+ if (tiered && (await removeDeadTemps(workDir, name, ctx)) === "live") {
+ return skip("busy", "another process is on this file");
+ }
+ const placed = path.join(workDir, name);
+ const besideL = tiered ? await lstatOrNull(placed) : null;
+ if (besideL && !besideL.isFile()) return skip("not-a-file", `media/${path.basename(workDir)}/${name}`);
+ if (besideL) {
+ // Placed by a run that was stopped before its link: verified, then linked.
+ const bd = await digestOf(placed, { throttle: opts.throttle }).catch(() => null);
+ if (!bd || bd.sha !== zd.sha || bd.bytes !== zd.bytes) {
+ return skip("both-differ", `media/${path.basename(workDir)}/${name} and ${stored} differ`);
+ }
+ } else {
+ const free = await statfs(workDir).then(
+ (f) => f.bavail * f.bsize,
+ () => Infinity,
+ );
+ if (free < zd.bytes + (opts.reserveBytes ?? 2 * 1024 ** 3)) return skip("low-space");
+ const made = await makePlain(zPath, workDir, name, zStat, zFirst, zd, `${pid}-${token}`, opts);
+ if (made !== "ok") return made;
+ crash("restore-placed");
+ }
+
+ // ── its tier link ─────────────────────────────────────────────────────────
+ if (tiered) {
+ const tmpLink = path.join(videoDir, `.${name}.tierlink-${pid}-${token}`);
+ await rm(tmpLink, { force: true });
+ await symlink(path.relative(videoDir, placed), tmpLink);
+ await lutimes(tmpLink, z.l.atimeMs / 1000, z.l.mtimeMs / 1000);
+ try {
+ // No clobber: a link to the symlink itself, then the temp name goes.
+ await link(tmpLink, path.join(videoDir, name));
+ } catch (err) {
+ await rm(tmpLink, { force: true });
+ if (errCode(err) !== "EEXIST") throw err;
+ // A writer put a plain file here meanwhile: it is the truth. The copy
+ // this run placed goes; the stored form is the next run's to settle.
+ await rm(placed, { force: true });
+ log(` ${name} appeared while it was being restored: the new file is kept`);
+ return { status: "changed" };
+ }
+ await rm(tmpLink, { force: true });
+ await fsyncDir(videoDir);
+ crash("restore-linked");
+ }
+
+ // ── the stored form goes ──────────────────────────────────────────────────
+ if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
+ await removeMediaFile(videoDir, stored);
+ await fsyncDir(videoDir);
+ return { status: "restored", before: zStat.size, after: zd.bytes, tiered };
+}
+
+// Steps 1–3 of the restore: Z → R (verified) → P. "ok", or the outcome that
+// stops the file.
+async function makePlain(
+ zPath: string,
+ workDir: string,
+ name: string,
+ zStat: Stats,
+ zFirst: Ident,
+ zd: Digest,
+ owner: string,
+ opts: CompressOptions,
+): Promise<"ok" | RestoreOutcome> {
+ const tmp = path.join(workDir, `.${name}.restoring-${owner}`);
+ const crash = (p: CompressKillPoint) => opts.crashAt?.(p);
+ try {
+ const fh = await open(tmp, "wx");
+ const { sink: hashSink, result } = digestSink();
+ try {
+ let chunks = 0;
+ const sink = new Writable({
+ write(chunk: Buffer, _enc, cb) {
+ fh.write(chunk).then(
+ () => {
+ hashSink.write(chunk);
+ chunks += 1;
+ try {
+ if (chunks === 1) crash("restoring");
+ cb();
+ } catch (err) {
+ cb(err as Error);
+ }
+ },
+ (err: Error) => cb(err),
+ );
+ },
+ });
+ await pipeline(
+ createReadStream(zPath),
+ paced(opts.throttle),
+ createStoredTextDecompressor(),
+ sink,
+ ...(opts.signal ? [{ signal: opts.signal }] : []),
+ );
+ await fh.sync();
+ } finally {
+ await fh.close().catch(() => {});
+ }
+ const written = result();
+ crash("restore-written");
+ if (written.bytes !== zd.bytes || written.sha !== zd.sha) {
+ throw new Error(`the plain copy of ${name} did not decode the same as before`);
+ }
+ // R from disk against a FRESH decode of Z.
+ const [back, fresh] = await Promise.all([
+ digestOf(tmp, { throttle: opts.throttle }),
+ digestOf(zPath, { decode: true, throttle: opts.throttle }),
+ ]);
+ if (back.sha !== fresh.sha || back.bytes !== fresh.bytes || back.sha !== zd.sha) {
+ throw new Error(`the plain copy of ${name} did not read back the same as its stored form`);
+ }
+ if (!sameIdent(identOf(await stat(zPath)), zFirst)) throw new ChangedError();
+ crash("restore-verified");
+ await utimes(tmp, zStat.atimeMs / 1000, zStat.mtimeMs / 1000);
+ try {
+ await link(tmp, path.join(workDir, name));
+ } catch (err) {
+ if (errCode(err) === "EEXIST") throw new ChangedError();
+ throw err;
+ }
+ await rm(tmp, { force: true });
+ await fsyncDir(workDir);
+ return "ok";
+ } catch (err) {
+ if (err instanceof CompressKill) throw err;
+ await rm(tmp, { force: true }).catch(() => {});
+ if (err instanceof ChangedError) return { status: "changed" };
+ if (err instanceof StoredTextCorruptError) {
+ return { status: "skipped", reason: "stored-corrupt", detail: err.message };
+ }
+ throw err;
+ }
+}
+
+// ── THE ONE-FORM RULE, AFTER A DELIBERATE RE-FETCH ──────────────────────────
+//
+// No pass fetches a declared file that is on disk in either form (the
+// chat-only pass is skipped, the caption passes leave the chat out of
+// `--sub-langs`, fetch-chat normalizes what is here). The one pass that does
+// is a DELIBERATE re-fetch — `fetch-chat {replace: true}`, over a chat stored
+// compressed (yt-dlp does not see the `.zst`, so it writes the plain name).
+// When that pass has landed a whole plain file (no `.part`; not the file that
+// was there before — `plainIdentity` taken before the pass), the stored form
+// beside it is OLDER content and goes, through `removeMediaFile`: ONE form is
+// left, the new one, and the next compress run stores it. A pass that landed
+// nothing, failed or left a `.part` changes nothing: the stored form stays.
+//
+// Not called after any other pass: a plain file that some other path left
+// beside a stored one is `both-differ`, refused by the compressor and shown
+// on the files card, for a person — never settled by guessing which is right.
+
+export type PlainIdentity = { ino: number; size: number; mtimeMs: number } | null;
+
+export async function plainIdentity(videoDir: string, name: string): Promise<PlainIdentity> {
+ const s = await stat(path.join(videoDir, name)).catch(() => null);
+ return s && s.isFile() ? { ino: s.ino, size: s.size, mtimeMs: s.mtimeMs } : null;
+}
+
+export type SettleOutcome =
+ | "one-form" // the new plain file only (the older stored form removed, or none was there)
+ | "unchanged" // the pass wrote no plain file: nothing touched
+ | "partial" // a `.part` beside it: nothing touched
+ | "busy";
+
+export async function settleStoredTextAfterWrite(
+ videoDir: string,
+ name: string,
+ before: PlainIdentity,
+ onLog: (line: string) => void = () => {},
+): Promise<SettleOutcome> {
+ if (!isStoredTextName(name)) return "unchanged";
+ return withFileLock(videoDir, name, "busy" as SettleOutcome, async () => {
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.some((e) => e.startsWith(`${name}.part`))) return "partial";
+ const now = await plainIdentity(videoDir, name);
+ if (!now) return "unchanged";
+ if (before && before.ino === now.ino && before.size === now.size && before.mtimeMs === now.mtimeMs) {
+ return "unchanged";
+ }
+ if (await lstatOrNull(path.join(videoDir, storedNameOf(name)))) {
+ await removeMediaFile(videoDir, storedNameOf(name));
+ await fsyncDir(videoDir);
+ onLog(`The re-fetched ${name} replaces the stored copy (${storedNameOf(name)} removed): one form is left.`);
+ }
+ return "one-form";
+ });
+}
+
+// ── THE FILES CARD'S DELETE OF ONE NAMED FORM ───────────────────────────────
+//
+// A person deleting `X` or `X.zst` on the files card. When the other form is
+// there too: the SAME content (both decode and hash equal) — both go, or the
+// other would come back as the file; DIFFERENT content, or a form that cannot
+// be read whole — only the named one goes, and the answer says the other is
+// still there (it is then what readers read). Each through `removeMediaFile`.
+
+export type RemoveFormOutcome = {
+ removed: string[];
+ kept?: { name: string; why: "differs" | "unreadable" };
+};
+
+export async function removeStoredTextForm(videoDir: string, filename: string): Promise<RemoveFormOutcome | "busy"> {
+ const plain = plainNameOf(filename) ?? filename;
+ if (!isStoredTextName(plain)) {
+ await removeMediaFile(videoDir, filename);
+ return { removed: [filename] };
+ }
+ return withFileLock<RemoveFormOutcome | "busy">(videoDir, plain, "busy", async () => {
+ const other = filename === plain ? storedNameOf(plain) : plain;
+ if (!(await lstatOrNull(path.join(videoDir, other)))) {
+ await removeMediaFile(videoDir, filename);
+ return { removed: [filename] };
+ }
+ const z = await storedPathOf(videoDir, plain);
+ const [pd, zd] = await Promise.all([
+ digestOf(path.join(videoDir, plain)).catch(() => null),
+ z ? digestOf(z, { decode: true }).catch(() => null) : Promise.resolve(null),
+ ]);
+ if (pd && zd && pd.sha === zd.sha && pd.bytes === zd.bytes) {
+ await removeStoredText(videoDir, plain);
+ return { removed: [storedNameOf(plain), plain] };
+ }
+ await removeMediaFile(videoDir, filename);
+ return { removed: [filename], kept: { name: other, why: pd && zd ? "differs" : "unreadable" } };
+ });
+}
diff --git a/common/lib/storedText.compress.test.ts b/common/lib/storedText.compress.test.ts
@@ -170,7 +170,7 @@ for (const tiered of [false, true]) {
assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWER\n", "the plain one is read");
});
- test(`${how}: a writer that replaces the file mid-run wins — "changed", the new file kept`, async () => {
+ test(`${how}: a writer that replaces the file mid-run wins — "changed", the new file kept, the older stored copy gone`, async () => {
// The seam is synchronous: the new file lands by rename, as yt-dlp's do,
// between the stored form landing and the original being set aside.
const g = await fixture(tiered);
@@ -186,6 +186,16 @@ for (const tiered of [false, true]) {
assert.equal(await readFile(path.join(g.videoDir, CHAT), "utf8"), "REWRITTEN\n");
assert.equal(await readStoredText(g.videoDir, CHAT, "utf8"), "REWRITTEN\n");
assert.deepEqual((await readdir(g.videoDir)).filter((e) => e.includes(".retire-")), []);
+ // The one-form rule (REVIEW-1 N6): the stored copy of the replaced
+ // content is not left beside the new file.
+ assert.deepEqual((await readdir(g.videoDir)).sort(), ["metadata.info.json", CHAT]);
+ // Its bytes in media/ too. (The replaced original's bytes stay there: a
+ // writer that puts a real file over a tier link orphans them, as before
+ // this lane — the tier hook's next move of the name overwrites them.)
+ if (tiered) assert.deepEqual((await readdir(g.mediaDir)).filter((e) => e.endsWith(".zst")), [], "its bytes in media/ too");
+ // And the next run compresses the new file.
+ assert.equal((await run(g)).status, "compressed");
+ assert.equal(await readStoredText(g.videoDir, CHAT, "utf8"), "REWRITTEN\n");
});
test(`${how}: skipped, touching nothing — a .part, a recording, a move, a job, a recent write, a full disk`, async () => {
@@ -235,11 +245,14 @@ for (const tiered of [false, true]) {
if (p === "retired") writeFileSync(path.join(f.videoDir, CHAT), "NEWEST\n");
},
});
- assert.equal(out.status, "compressed", JSON.stringify(out));
+ assert.equal(out.status, "changed", JSON.stringify(out));
assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWEST\n", "the newer file is the truth");
assert.deepEqual((await readdir(f.videoDir)).filter((e) => e.includes(".retire-")), []);
+ // One form: the newer file; the older stored copy is gone (REVIEW-1 N6).
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT]);
const again = await run(f);
- assert.equal(again.status === "skipped" && again.reason, "both-differ", "refused, both kept");
+ assert.equal(again.status, "compressed", "the next run stores the newer file");
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWEST\n");
});
}
@@ -299,6 +312,127 @@ test("a set-aside original of a dead run that is NOT the stored content is kept
assert.equal(await readFile(path.join(f.videoDir, `.${CHAT}.retire-${DEAD}`), "utf8"), "SOMETHING ELSE\n");
});
+// REVIEW-1 F4(b): a leftover is dead unless the process that named it runs NOW
+// — the pid AND its start token. An editor that comes back with the same pid
+// (a container) finds its own earlier run's set-aside: dead, finished. A live
+// process of another pid with the same start: alive, nothing touched. A pid
+// reused by a later process (another start token): dead.
+for (const tiered of [false, true]) {
+ const how = tiered ? "tiered" : "real";
+ const { processStartToken } = await import("./storedText-write-server");
+ const killRetired = (p: string) => {
+ if (p === "retired") throw new CompressKill(p as never);
+ };
+
+ test(`${how}: this pid's leftover from an EARLIER process start is dead — the next run finishes`, async () => {
+ for (const token of ["oldstart1", undefined]) {
+ const f = await fixture(tiered);
+ await assert.rejects(run(f, { pid: process.pid, ...(token ? { token } : {}), crashAt: killRetired }), CompressKill);
+ const left = (await readdir(f.videoDir)).filter((e) => e.includes(".retire-"));
+ assert.equal(left.length, 1);
+ assert.match(left[0], new RegExp(`retire-${process.pid}-`));
+ await assertWhole(f, "after the kill");
+ const out = await run(f);
+ assert.equal(out.status, "compressed", JSON.stringify(out));
+ await assertFinal(f, `own pid, ${token ?? "this start"}`);
+ }
+ });
+
+ test(`${how}: a leftover of ANOTHER live process (same pid, same start) is left alone; a reused pid's is dead`, async () => {
+ const other = process.ppid;
+ const live = processStartToken(other);
+ assert.ok(live, "the parent's start token is readable");
+ const f = await fixture(tiered);
+ await assert.rejects(run(f, { pid: other, token: live!, crashAt: killRetired }), CompressKill);
+ const before = await tree(f.channelDir);
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "busy", JSON.stringify(out));
+ assert.deepEqual(await tree(f.channelDir), before, "nothing touched");
+
+ const g = await fixture(tiered);
+ await assert.rejects(run(g, { pid: other, token: "reused0", crashAt: killRetired }), CompressKill);
+ const again = await run(g);
+ assert.equal(again.status, "compressed", JSON.stringify(again));
+ await assertFinal(g, "a reused pid");
+ });
+}
+
+test("the quiet period asks the later of mtime and ctime: a backdated mtime is still recent (REVIEW-1 N4)", async () => {
+ const f = await fixture(false);
+ // The fixture's mtime is days old; its ctime is now (the utimes itself).
+ const out = await run(f, { quietMs: 600_000 });
+ assert.equal(out.status === "skipped" && out.reason, "recent", JSON.stringify(out));
+ const later = await run(f, { quietMs: 600_000, now: () => Date.now() + 3_600_000 });
+ assert.equal(later.status, "compressed");
+});
+
+// A KERNEL-WRITTEN mtime has nanoseconds; `utimes` takes a double of seconds.
+// Measured (Node 22.23.5, ext4): `mtimeMs` round-trips EXACTLY — the number
+// the index compares (buildIndex: `mtimeMs !==`) — while `mtimeNs` may move by
+// a few hundred ns. Pinned both ways: the index sees no change; the
+// nanoseconds are not promised.
+test("a nanosecond kernel mtime: the stored form's mtimeMs equals the original's exactly (the index key)", async () => {
+ for (const tiered of [false, true]) {
+ const f = await fixture(tiered);
+ const bytes = tiered ? path.join(f.mediaDir, CHAT) : path.join(f.videoDir, CHAT);
+ // Rewrite in place so the kernel stamps the time (no utimes).
+ await writeFile(bytes, ORIGINAL);
+ const name = path.join(f.videoDir, CHAT);
+ const lBefore = await lstat(name, { bigint: true });
+ const sBefore = await stat(name, { bigint: true });
+ const msL = (await lstat(name)).mtimeMs;
+ const msS = (await stat(name)).mtimeMs;
+ assert.notEqual(sBefore.mtimeNs % 1_000_000n, 0n, "a sub-millisecond kernel time");
+ assert.equal((await run(f)).status, "compressed");
+ assert.equal((await statStoredText(f.videoDir, CHAT, { link: true })).stats.mtimeMs, msL, "lstat mtimeMs");
+ assert.equal((await statStoredText(f.videoDir, CHAT)).stats.mtimeMs, msS, "stat mtimeMs");
+ const zs = await stat(path.join(f.videoDir, ZST), { bigint: true });
+ const drift = zs.mtimeNs - sBefore.mtimeNs;
+ assert.ok(drift > -1000n && drift < 1000n, `mtimeNs within a microsecond (drift ${drift} ns)`);
+ void lBefore;
+ }
+});
+
+test("a stored file missing its last 1-4 bytes (the checksum) still decodes whole and right: pinned (REVIEW-1 N7)", async () => {
+ const f = await fixture(false);
+ assert.equal((await run(f)).status, "compressed");
+ const z = path.join(f.videoDir, ZST);
+ const whole = await readFile(z);
+ for (const cut of [1, 4]) {
+ await writeFile(z, whole.subarray(0, whole.length - cut));
+ // Without its checksum the frame is not checked, but every byte of the
+ // content is there, and the length matches the header: the text is right.
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `cut ${cut}`);
+ assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "ok", `cut ${cut}`);
+ }
+ // One byte more and content is missing: never read as the file.
+ await writeFile(z, whole.subarray(0, whole.length - 5 - 100));
+ await assert.rejects(readStoredText(f.videoDir, CHAT, "utf8"));
+});
+
+test("a 0-byte chat compresses and reads back as 0 bytes", async () => {
+ const f = await fixture(false);
+ await writeFile(path.join(f.videoDir, CHAT), "");
+ assert.equal((await run(f)).status, "compressed");
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "");
+ assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "ok");
+});
+
+test("an abort mid-write and an appending writer: the original is untouched, no temp is left", async () => {
+ const f = await fixture(false);
+ const ac = new AbortController();
+ await assert.rejects(run(f, { signal: ac.signal, crashAt: (p) => { if (p === "compressing") ac.abort(); } }));
+ assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL);
+ assert.deepEqual((await readdir(f.videoDir)).sort(), [CHAT, "metadata.info.json"].sort());
+
+ const g = await fixture(false);
+ const { appendFileSync } = await import("node:fs");
+ const out = await run(g, { crashAt: (p) => { if (p === "compressing") appendFileSync(path.join(g.videoDir, CHAT), "MORE\n"); } });
+ assert.equal(out.status, "changed", JSON.stringify(out));
+ assert.equal(await readFile(path.join(g.videoDir, CHAT), "utf8"), ORIGINAL + "MORE\n", "the writer's file is kept");
+ assert.deepEqual((await readdir(g.videoDir)).sort(), [CHAT, "metadata.info.json"].sort(), "no temp, no stored form");
+});
+
test("not a declared name: refused", async () => {
const f = await fixture(false);
const out = await compressStoredText(f.videoDir, "transcript.en.vtt");
diff --git a/common/lib/storedText.restore.test.ts b/common/lib/storedText.restore.test.ts
@@ -0,0 +1,171 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { lstat, lutimes, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.restore.test.ts
+//
+// THE RESTORE (REVIEW-1 F3): a stored chat put back into its plain form, the
+// compressor in reverse — the rollback an older checkout needs. Every case is a
+// temp channel tree, real files and tier links. Kill points are the `crashAt`
+// seam (it throws and nothing after it runs, as a SIGKILL). After each: ONE
+// WHOLE COPY is always readable, and the next run finishes with the plain form
+// only, the same bytes and the same times (an `lstat` and a `stat` of the
+// name answer what they did before the file was ever compressed).
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-restore-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { compressStoredText, restoreStoredText, CompressKill } = await import("./storedText-write-server");
+const { readStoredText, readdirLogical } = await import("./storedText-server");
+
+const CHAT = "transcript.live_chat.json";
+const ZST = `${CHAT}.zst`;
+const DEAD = 999_999_998;
+const KILLS = ["restoring", "restore-written", "restore-verified", "restore-placed", "restore-linked"] as const;
+
+const ORIGINAL = Array.from({ length: 9_000 }, (_, i) =>
+ JSON.stringify({ replayChatItemAction: { actions: [{ text: `m${i} ${createHash("md5").update(String(i)).digest("hex")}` }], videoOffsetTimeMsec: String(i * 1000) } }),
+).join("\n") + "\n";
+
+let n = 0;
+type F = { channelDir: string; videoDir: string; mediaDir: string; tiered: boolean; lstatMs: number; statMs: number };
+
+// A compressed chat, as the compressor leaves it (real or tiered), and the
+// times the plain name answered before.
+async function compressed(tiered: boolean): Promise<F> {
+ const slug = `r${++n}`;
+ const channelDir = path.join(ROOT, "channels", slug);
+ const id = "vid00000002";
+ const videoDir = path.join(channelDir, "data", id);
+ const mediaRoot = path.join(ROOT, "drive", slug, "media");
+ const mediaDir = path.join(mediaRoot, id);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(videoDir, "metadata.info.json"), "{}");
+ if (tiered) {
+ await mkdir(mediaDir, { recursive: true });
+ await symlink(mediaRoot, path.join(channelDir, "media"));
+ await writeFile(path.join(mediaDir, CHAT), ORIGINAL);
+ await utimes(path.join(mediaDir, CHAT), 1763700100.25, 1763700100.333337);
+ await symlink(path.join("..", "..", "media", id, CHAT), path.join(videoDir, CHAT));
+ await lutimes(path.join(videoDir, CHAT), 1763700200.5, 1763700200.777779);
+ } else {
+ await writeFile(path.join(videoDir, CHAT), ORIGINAL);
+ await utimes(path.join(videoDir, CHAT), 1763700100.25, 1763700100.987651);
+ }
+ const lstatMs = (await lstat(path.join(videoDir, CHAT))).mtimeMs;
+ const statMs = (await stat(path.join(videoDir, CHAT))).mtimeMs;
+ const out = await compressStoredText(videoDir, CHAT, { reserveBytes: 0 });
+ assert.equal(out.status, "compressed", JSON.stringify(out));
+ return { channelDir, videoDir, mediaDir, tiered, lstatMs, statMs };
+}
+
+async function assertWhole(f: F, why: string): Promise<void> {
+ assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: the read path`);
+ assert.ok((await readdirLogical(f.videoDir)).includes(CHAT), `${why}: listed`);
+}
+
+async function assertPlainFinal(f: F, why: string): Promise<void> {
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT], `${why}: data/<id>`);
+ assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, `${why}: the plain bytes`);
+ assert.equal((await lstat(path.join(f.videoDir, CHAT))).mtimeMs, f.lstatMs, `${why}: the lstat key`);
+ assert.equal((await stat(path.join(f.videoDir, CHAT))).mtimeMs, f.statMs, `${why}: the stat`);
+ if (f.tiered) {
+ assert.ok((await lstat(path.join(f.videoDir, CHAT))).isSymbolicLink(), `${why}: a tier link`);
+ assert.equal(await readlink(path.join(f.videoDir, CHAT)), path.join("..", "..", "media", "vid00000002", CHAT));
+ assert.deepEqual(await readdir(f.mediaDir), [CHAT], `${why}: media/<id>`);
+ }
+}
+
+const run = (f: F, extra: Parameters<typeof restoreStoredText>[2] = {}) =>
+ restoreStoredText(f.videoDir, CHAT, { reserveBytes: 0, ...extra });
+
+for (const tiered of [false, true]) {
+ const how = tiered ? "tiered" : "real";
+
+ test(`${how}: restored with the same bytes and times, then idempotent; a compress after it is the same as before`, async () => {
+ const f = await compressed(tiered);
+ const out = await run(f);
+ assert.equal(out.status, "restored", JSON.stringify(out));
+ await assertPlainFinal(f, "restored");
+ assert.equal((await run(f)).status, "already");
+ // Round trip: compress again, restore again — the same plain file.
+ assert.equal((await compressStoredText(f.videoDir, CHAT, { reserveBytes: 0 })).status, "compressed");
+ assert.equal((await run(f)).status, "restored");
+ await assertPlainFinal(f, "second round trip");
+ });
+
+ for (const point of KILLS.filter((p) => tiered || p !== "restore-linked")) {
+ test(`${how}: killed at "${point}" — one whole copy remains, and the next run (a restore, or a compress) finishes`, async () => {
+ for (const next of ["restore", "compress"] as const) {
+ const f = await compressed(tiered);
+ await assert.rejects(
+ run(f, { pid: DEAD, crashAt: (p) => { if (p === point) throw new CompressKill(p); } }),
+ CompressKill,
+ );
+ await assertWhole(f, `after the kill at ${point}`);
+ if (next === "restore") {
+ const out = await run(f);
+ assert.equal(out.status, "restored", `${point}: ${JSON.stringify(out)}`);
+ await assertPlainFinal(f, `${point}, then restore`);
+ } else {
+ const out = await compressStoredText(f.videoDir, CHAT, { reserveBytes: 0 });
+ assert.ok(["already", "compressed"].includes(out.status), `${point}: ${JSON.stringify(out)}`);
+ await assertWhole(f, `${point}, then compress`);
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", ZST], `${point}: stored form only`);
+ if (tiered) assert.deepEqual(await readdir(f.mediaDir), [ZST], `${point}: media/<id>`);
+ }
+ }
+ });
+ }
+
+ test(`${how}: a stored file that does not decode is refused and left as it is`, async () => {
+ const f = await compressed(tiered);
+ const zBytes = f.tiered ? path.join(f.mediaDir, ZST) : path.join(f.videoDir, ZST);
+ const whole = await readFile(zBytes);
+ await writeFile(zBytes, whole.subarray(0, Math.floor(whole.length / 2)));
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "stored-corrupt", JSON.stringify(out));
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", ZST]);
+ assert.equal((await readFile(zBytes)).length, Math.floor(whole.length / 2), "untouched");
+ });
+
+ test(`${how}: a plain file beside the stored one with DIFFERENT content is refused; with the same content the stored one goes`, async () => {
+ const f = await compressed(tiered);
+ await writeFile(path.join(f.videoDir, CHAT), "NEWER\n");
+ const out = await run(f);
+ assert.equal(out.status === "skipped" && out.reason, "both-differ", JSON.stringify(out));
+ assert.ok(await lstat(path.join(f.videoDir, ZST)));
+ await writeFile(path.join(f.videoDir, CHAT), ORIGINAL);
+ assert.equal((await run(f)).status, "restored");
+ assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT]);
+ });
+
+ test(`${how}: skipped, touching nothing — a move, a recording, a full disk`, async () => {
+ for (const [reason, arrange] of [
+ ["relocating", async (f: F) => (await writeFile(path.join(f.channelDir, ".relocating.json"), "{}"), {})],
+ ["recording", async (f: F) => (await writeFile(path.join(f.videoDir, "live-recording.json"), JSON.stringify({ status: "recording" })), {})],
+ ["low-space", async () => ({ reserveBytes: Number.MAX_SAFE_INTEGER })],
+ ] as const) {
+ const f = await compressed(tiered);
+ const extra = await arrange(f);
+ const before = (await readdir(f.videoDir)).sort();
+ const out = await restoreStoredText(f.videoDir, CHAT, extra);
+ assert.equal(out.status === "skipped" && out.reason, reason, `${reason}: ${JSON.stringify(out)}`);
+ assert.deepEqual((await readdir(f.videoDir)).sort(), before, `${reason}: nothing touched`);
+ await assertWhole(f, reason);
+ }
+ });
+}
+
+test("a plain chat that was never compressed is `already`; no chat at all is `absent`", async () => {
+ const d = path.join(ROOT, "channels", "plain-only", "data", "v");
+ await mkdir(d, { recursive: true });
+ assert.equal((await restoreStoredText(d, CHAT)).status, "absent");
+ await writeFile(path.join(d, CHAT), "x\n");
+ assert.equal((await restoreStoredText(d, CHAT)).status, "already");
+ assert.equal(await readFile(path.join(d, CHAT), "utf8"), "x\n");
+});
diff --git a/editor/app/api/ops/compress-text/route.test.ts b/editor/app/api/ops/compress-text/route.test.ts
@@ -42,6 +42,8 @@ test("refusals before any job", async () => {
[{ limit: 0 }, /limit/],
[{ limit: 5 }, /"limit" is per channel: name exactly one in "slugs"/],
[{ dryRun: true, verify: true }, /two different runs/],
+ [{ restore: true, verify: true }, /two different runs/],
+ [{ restore: "yes" }, /restore/],
];
for (const [body, re] of cases) {
const r = await post(body);
@@ -61,3 +63,14 @@ test("a dry run answers per channel and writes nothing", async () => {
assert.deepEqual(await readdir(videoDir), ["transcript.live_chat.json"]);
assert.equal((await stat(path.join(videoDir, "transcript.live_chat.json"))).mtimeMs, before);
});
+
+test("a restore's dry run answers the stored files and writes nothing", async () => {
+ const r = await post({ dryRun: true, restore: true });
+ assert.equal(r.status, 200, JSON.stringify(r.json));
+ const result = r.json.result as { restore: boolean; channels: { slug: string; storedFiles: number; pending: number }[] };
+ assert.equal(result.restore, true);
+ const synth = result.channels.find((c) => c.slug === "synth");
+ assert.equal(synth?.storedFiles, 0, "nothing is stored here");
+ assert.equal(synth?.pending, 0);
+ assert.deepEqual(await readdir(videoDir), ["transcript.live_chat.json"]);
+});
diff --git a/editor/app/api/ops/compress-text/route.ts b/editor/app/api/ops/compress-text/route.ts
@@ -4,7 +4,7 @@ import { OpsInputError, ops, opsFail, optBool, optPositiveInt, reqSlugs, type Op
export const dynamic = "force-dynamic";
-// POST { slugs?, kinds?, dryRun?, limit?, verify? }
+// POST { slugs?, kinds?, dryRun?, limit?, verify?, restore? }
// dryRun -> { ok: true, dryRun: true, result: { channels: [{ slug, plainFiles,
// plainBytes, storedFiles, storedBytes, storedLogicalBytes,
// estimateAfterBytes, free }], lines } }
@@ -23,7 +23,13 @@ export const dynamic = "force-dynamic";
// `verify` decodes every stored file and writes nothing; `limit` counts files
// compressed by the job, and takes exactly one channel in `slugs`. One job per
// channel with work, on the machine-wide `compress-text` queue (one file at a
-// time); a re-run continues.
+// time); a re-run continues. Started by a person only: a restart never
+// re-queues or resumes one.
+// `restore: true` is the ROLLBACK: every stored chat put back into its plain
+// form, verified the same way in reverse (decoded beside, fsynced, read back
+// against a fresh decode, the same times, then the stored file removed); with
+// `dryRun` it answers the stored files, their plain bytes and the free space.
+// Run it BEFORE reverting or running an older checkout (OPERATING.md).
// `kinds`: what to compress. Only the raw live chat is a stored name today.
function optKinds(body: OpsBody): void {
if (body.kinds === undefined) return;
@@ -33,16 +39,19 @@ function optKinds(body: OpsBody): void {
}
export async function POST(request: Request) {
- return ops(request, ["slugs", "kinds", "dryRun", "limit", "verify"], async (body) => {
+ return ops(request, ["slugs", "kinds", "dryRun", "limit", "verify", "restore"], async (body) => {
optKinds(body);
const dryRun = optBool(body, "dryRun") ?? false;
const verify = optBool(body, "verify") ?? false;
+ const restore = optBool(body, "restore") ?? false;
if (dryRun && verify) return opsFail('"dryRun" and "verify" are two different runs: ask one');
+ if (restore && verify) return opsFail('"restore" and "verify" are two different runs: ask one');
const limit = optPositiveInt(body, "limit");
const result = await compressTextAction({
...(body.slugs !== undefined ? { slugs: reqSlugs(body, "slugs") } : {}),
dryRun,
verify,
+ restore,
...(limit !== undefined ? { limit } : {}),
});
if (!result.ok) return opsFail(result.error);
diff --git a/editor/app/api/ops/delete-file/route.ts b/editor/app/api/ops/delete-file/route.ts
@@ -12,7 +12,10 @@ export const dynamic = "force-dynamic";
// the button refuses: a name that is not one entry of the directory, a file on
// a media drive that is not mounted or not answering (nothing is deleted), a
// channel whose drive is not answering, something that is not a regular file.
-// The channel's report is refreshed after. No undo.
+// The channel's report is refreshed after. No undo. A stored text file
+// (`transcript.live_chat.json` / `.zst`, lib/storedText.ts) named in one form
+// while the other is there: both go when they hold the same content; only the
+// named one when they differ, and `note` says the other is still there.
export async function POST(request: Request) {
return ops(request, ["slug", "id", "file"], async (body) => {
const res = await deleteVideoFileAction(
@@ -21,6 +24,6 @@ export async function POST(request: Request) {
reqString(body, "file"),
);
if (!res.ok) return opsFail(res.error);
- return NextResponse.json({ ok: true });
+ return NextResponse.json({ ok: true, ...(res.note ? { note: res.note } : {}) });
});
}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx
@@ -76,6 +76,7 @@ function DeleteFileButton({
}) {
const [pending, startTransition] = useTransition();
const [error, setError] = useState<string | null>(null);
+ const [note, setNote] = useState<string | null>(null);
return (
<div className="flex items-center gap-2">
<button
@@ -85,9 +86,11 @@ function DeleteFileButton({
onClick={() => {
if (!confirm(`Delete ${filename}?`)) return;
setError(null);
+ setNote(null);
startTransition(async () => {
const res = await deleteVideoFileAction(slug, videoId, filename);
if (!res.ok) setError(res.error);
+ else if (res.note) setNote(res.note);
});
}}
className="self-start px-2 py-1 rounded border border-destructive/30 text-destructive text-xs hover:bg-destructive-soft disabled:opacity-50"
@@ -102,6 +105,11 @@ function DeleteFileButton({
{error}
</span>
)}
+ {note && (
+ <span className="text-xs text-muted-foreground" aria-label={`delete note ${filename}`}>
+ {note}
+ </span>
+ )}
</div>
);
}
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -60,8 +60,7 @@ import {
} from "yt-dlp-transcript-common/lib/channelMedia";
import { onDrive } from "yt-dlp-transcript-common/lib/storageHealth";
import { isTierable } from "yt-dlp-transcript-common/lib/mediaTier";
-import { isStoredTextName } from "yt-dlp-transcript-common/lib/storedText";
-import { removeStoredText } from "yt-dlp-transcript-common/lib/storedText-write-server";
+import { removeStoredTextForm } from "yt-dlp-transcript-common/lib/storedText-write-server";
import { setExcludedFromTruncatedCheck } from "yt-dlp-transcript-common/lib/excludeTruncatedCheck-server";
import { pinTranscript } from "yt-dlp-transcript-common/lib/transcriptPin-server";
import { readVideoTracks } from "yt-dlp-transcript-common/lib/captionTracks-server";
@@ -1014,7 +1013,7 @@ export async function deleteVideoFileAction(
slug: string,
videoId: string,
filename: string,
-): Promise<{ ok: true } | { ok: false; error: string }> {
+): Promise<{ ok: true; note?: string } | { ok: false; error: string }> {
const videoDir = videoDirOf(slug, videoId);
const target = safeJoinUnderDir(videoDir, filename);
if (!target) {
@@ -1075,15 +1074,26 @@ export async function deleteVideoFileAction(
}
// Through its link when the file is tiered (release 17): the bytes on the
// media tier go too, never orphaned behind a removed link. A declared stored
- // name (lib/storedText.ts) is one file in two forms: the plain one deleted
- // takes its stored copy with it, which would otherwise come back as the
- // file. The stored form clicked by its own name goes alone.
- const name = path.basename(target);
- if (isStoredTextName(name)) await removeStoredText(videoDir, name);
- else await removeMediaFile(videoDir, name);
+ // name (lib/storedText.ts) is one file in two forms: either named, when the
+ // other is there with the SAME content both go (the other would come back as
+ // the file); with DIFFERENT content only the named one goes, and the answer
+ // says the other is still there — it is what readers read now.
+ const out = await removeStoredTextForm(videoDir, path.basename(target));
+ if (out === "busy") {
+ return { ok: false, error: `${filename} not deleted: it is being compressed or restored right now. Try again in a moment.` };
+ }
revalidatePath(`/channels/${slug}/videos/${videoId}`);
requestChannelSnapshot(getPaths(), slug);
- return { ok: true };
+ if (out.kept) {
+ return {
+ ok: true,
+ note:
+ out.kept.why === "differs"
+ ? `Deleted ${filename}. ${out.kept.name} is still here with different content, and is now the file readers read.`
+ : `Deleted ${filename}. ${out.kept.name} is still here (it could not be read whole to compare).`,
+ };
+ }
+ return out.removed.length > 1 ? { ok: true, note: `Deleted ${out.removed.join(" and ")} (the same content).` } : { ok: true };
}
// Promote a transcript.<lang>.vtt track to the canonical transcript.en.vtt so
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -634,6 +634,7 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
return compressTextJobAction(spec.slug, {
...(limit !== undefined ? { limit } : {}),
...(p.verify === true ? { verify: true } : {}),
+ ...(p.restore === true ? { restore: true } : {}),
});
},
"compact-saved-videos": (spec) => {
diff --git a/editor/app/storage/compressTextActions.ts b/editor/app/storage/compressTextActions.ts
@@ -23,9 +23,10 @@ import { waitWhileRenderHeld } from "yt-dlp-transcript-common/lib/renderHold";
// channel. Per channel because the job is a media writer of THAT channel —
// the media guard asks it before the job starts, and a move of the channel's
// media refuses while it runs (`channelMediaWriters` finds it by its slug).
-// So `limit` is per job, and is taken only with one channel named. Never
-// resumed by the boot pass — it removes originals; the job's Retry (a person)
-// re-runs it, and a re-run continues.
+// So `limit` is per job, and is taken only with one channel named. STARTED BY
+// A PERSON ONLY (jobKinds.ts `startedByPerson`): a restart closes a queued one
+// and resumes no interrupted one — it removes originals (a restore: stored
+// copies); the job's Retry (a person) re-runs it, and a re-run continues.
const COMPRESS_QUEUE = "compress-text";
export type CompressTextActionResult =
@@ -35,6 +36,7 @@ export type CompressTextActionResult =
ok: true;
dryRun: false;
verify: boolean;
+ restore: boolean;
jobs: { slug: string; jobId: string }[];
jobIds: string[];
skipped: { slug: string; reason: string }[];
@@ -76,7 +78,7 @@ const sleep = (ms: number, signal?: AbortSignal) =>
export async function compressTextJobAction(
slug: string,
- opts: { limit?: number; verify?: boolean } = {},
+ opts: { limit?: number; verify?: boolean; restore?: boolean } = {},
): Promise<StreamActionResult> {
const paths = getPaths();
return runManagedFunction({
@@ -90,6 +92,7 @@ export async function compressTextJobAction(
params: {
...(opts.limit !== undefined ? { limit: opts.limit } : {}),
...(opts.verify ? { verify: true } : {}),
+ ...(opts.restore ? { restore: true } : {}),
},
},
fn: async (onLog, signal, _progress, ctx) => {
@@ -98,6 +101,7 @@ export async function compressTextJobAction(
slugs: [slug],
...(opts.limit !== undefined ? { limit: opts.limit } : {}),
...(opts.verify ? { verify: true } : {}),
+ ...(opts.restore ? { restore: true } : {}),
onLog,
signal,
drainSignal: ctx.drainSignal,
@@ -115,12 +119,14 @@ export async function compressTextJobAction(
}
// `slugs` (default: every channel). A dry run answers with the plan and
-// writes nothing; a real run (or a check) starts one job per channel that has
-// a raw chat to compress (or a stored one to check).
+// writes nothing; a real run (a check, a restore) starts one job per channel
+// that has a raw chat to compress or a stopped run to finish (a stored one to
+// check, or to restore).
export async function compressTextAction(input: {
slugs?: string[];
dryRun?: boolean;
verify?: boolean;
+ restore?: boolean;
limit?: number;
}): Promise<CompressTextActionResult> {
const paths = getPaths();
@@ -131,7 +137,7 @@ export async function compressTextAction(input: {
return { ok: false, error: '"limit" is per channel: name exactly one in "slugs"' };
}
const slugs = input.slugs ?? all;
- const plan = await compressText({ paths, slugs, dryRun: true, onLog: () => {} });
+ const plan = await compressText({ paths, slugs, dryRun: true, ...(input.restore ? { restore: true } : {}), onLog: () => {} });
if (input.dryRun) return { ok: true, dryRun: true, result: plan };
const jobs: { slug: string; jobId: string }[] = [];
const skipped: { slug: string; reason: string }[] = [];
@@ -140,14 +146,23 @@ export async function compressTextAction(input: {
skipped.push({ slug: line.slug, reason: line.refused });
continue;
}
- const work = input.verify ? line.storedFiles : line.plainFiles;
+ const work = input.verify ? line.storedFiles : (line.pending ?? 0);
if (work === 0) continue;
const r = await compressTextJobAction(line.slug, {
...(input.limit !== undefined ? { limit: input.limit } : {}),
...(input.verify ? { verify: true } : {}),
+ ...(input.restore ? { restore: true } : {}),
});
if (r.ok) jobs.push({ slug: line.slug, jobId: r.jobId });
else skipped.push({ slug: line.slug, reason: r.error });
}
- return { ok: true, dryRun: false, verify: input.verify === true, jobs, jobIds: jobs.map((j) => j.jobId), skipped };
+ return {
+ ok: true,
+ dryRun: false,
+ verify: input.verify === true,
+ restore: input.restore === true,
+ jobs,
+ jobIds: jobs.map((j) => j.jobId),
+ skipped,
+ };
}