commit 7f3c9c2b205733cda3fad0d8fd17132dd16ddc8f
parent ff2035cdf9ff0a9e3a9a5b2f3ff2701560a68d87
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 11:30:10 -0500
stored text, slice 5: `pnpm ops compress-text` kind "captions" (and its restore)
compress-text takes `kinds`: "live-chat" (the default, as before) and
"captions" — every caption track, transcript.<lang>.vtt -> .zst, compressed
only when named. Both named: the live chat first, then the captions. The
same compressor and the same rules as the chat: one file at a time, verified
before the original goes, the quiet period (mtime or ctime), the .part and
recording refusals, the per-directory lock, person-started only, one job per
channel on the machine-wide queue, paced, drainable; verify and restore
(the rollback) per kind.
- The survey finds caption names by listing (either form) and by a stopped
run's leftovers (storedTextLeftoverNames): a run killed after it set the
original aside leaves neither form under the name, and the job still
finishes it. Every kill point tested through the job.
- The dry run reports per channel and kind (byKind; the channel's totals are
the kinds asked — with the live chat alone, exactly the old figures), the
estimate at ~20 % for captions, and counts the en / en-orig pairs of equal
LOGICAL size: each is compressed as it is, never deduped.
- Two forms of different content (a plain caption a re-fetch or Set as
transcript landed beside an older stored one) are refused, both kept, and
listed (byKind.refused, a line each, the closing count): nothing removes a
stored caption because a different one arrived.
- Captions on the real corpus are real files in data/<id>/ (counted by name:
every one, no links, no legacy data/ links); a caption that is a link into
media/ is handled as a tiered chat is (tested).
- The index sees no change: buildIndex (v) runs the real index, the migration
over every caption, the index again — zero mutations.
- The ops route accepts kinds live-chat and captions; the job spec carries
kinds and its replay passes them on. OPERATING.md has the captions recipe
and the captions rollback; the ops help and COMMANDS.md say both kinds.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
13 files changed, 841 insertions(+), 265 deletions(-)
diff --git a/COMMANDS.md b/COMMANDS.md
@@ -161,7 +161,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `review-compacted-original` | review-compacted-original records a person's review of one compacted copy (watch it first: get compaction-review's "watch"): {"slug", "id", "note"?}. It names the copy it is for ("watched", its sha256) and counts for that copy only; it changes nothing on disk. It is what lets drop-saved-alternate ("confirmOriginal": true) drop the original of a video not freshly checked on its platform. "formerOriginal": "<file>" reviews the active copy that replaced a former original instead. | |
| `compaction-markers` | compaction-markers lists the "being compacted" markers (.compacting.json), each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale one; a live one is refused (cancel its job). Stale ones are also swept at editor boot and at the start of every compaction run. | |
| `kept-failed-encodes` | kept-failed-encodes lists the encodes kept after a failed check (in each video's .compact-scratch, never active: chunks and the joined copy, their size, what failed): {}. {"clear": {"slug", "id"}} removes one (refused while its compaction runs). compact-saved-videos "reverify": true re-checks one without encoding. | |
-| `compress-text` | compress-text stores the raw live-chat replays compressed (zstd, level 9): transcript.live\_chat.json becomes transcript.live\_chat.json.zst, read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat"\], "dryRun"?, "limit"?, "verify"?, "restore"?}. One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it (it visits every dir a stopped run left). Left alone and counted: a file written (mtime or ctime) in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused and both kept. A file a writer replaces during the run is kept and read; the earlier content's stored copy is kept beside it. The dry run lists earlier chat captures a re-fetch kept (chat-capture-kept.\*.json.zst), which nothing removes automatically. "dryRun": true answers per channel the raw chats, their bytes, the stored ones, the estimate after (about 5 %, an estimate) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed 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), waiting while render mode holds the machine and slower while a live recording runs. Started by a person only: a restart closes a queued one and resumes no interrupted one (it removes originals) -- a re-run continues. "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 .zst removed); with "dryRun" it answers the stored files, their plain bytes and the free space. Run it BEFORE reverting or running an older checkout, which cannot read a stored chat (OPERATING.md). | |
+| `compress-text` | compress-text stores big text files compressed (zstd, level 9): the raw live-chat replays (transcript.live\_chat.json -> .zst, kind live-chat, the default) and the caption tracks (every transcript.<lang>.vtt -> .zst, on the corpus disk: "kinds": \["captions"\], only when named). Read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat", "captions"\], "dryRun"?, "limit"?, "verify"?, "restore"?}. A caption's dry run also counts the en / en-orig pairs of equal size (compressed each as it is, never deduped). One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it (it visits every dir a stopped run left). Left alone and counted: a file written (mtime or ctime) in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused, both kept and listed: nothing removes a stored copy because a different one arrived. A file a writer replaces during the run is kept and read; the earlier content's stored copy is kept beside it. The dry run lists earlier chat captures a re-fetch kept (chat-capture-kept.\*.json.zst), which nothing removes automatically. "dryRun": true answers per channel and kind the files, their bytes, the stored ones, the estimate after (about 5 % for a chat, 20 % for a caption: estimates) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed 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), waiting while render mode holds the machine and slower while a live recording runs. Started by a person only: a restart closes a queued one and resumes no interrupted one (it removes originals) -- a re-run continues. "restore": true is the rollback: every stored file of the kinds 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 .zst removed); with "dryRun" it answers the stored files, their plain bytes and the free space. Run it BEFORE reverting or running an older checkout, which cannot read a stored chat or caption (OPERATING.md). | |
| `build-cues` | build-cues writes each video's transcript.cues.json from its raw transcript (the caption-track rule for VTTs), as the digest card's Normalize button does: {"slug"}, "ids": \[...\] for those videos only (every one held), "force": true to rewrite a fresh one. A job on the channel's queue. The file every reader without an index build wants. | `pnpm ops build-cues --json '{"slug":"demo-yt","ids":["<videoId>"]}' --wait` |
| `feed-metadata` | feed-metadata completes a podcast channel's records from its RSS feed: one fetch of the channel's url, then title, date, description and duration into each record that lacks them: {"slug"}. "dryRun": true counts matched, unmatched and already complete, and writes nothing. | `pnpm ops feed-metadata --json '{"slug":"demo-podcast","dryRun":true}' --wait` |
| `refresh-report` | refresh-report regenerates a channel's report (the buckets and counts its page shows) on the one serial report queue: {"slug"} answers the job queued, or the one already waiting ("started": false); {"all": true} queues every channel and answers {queued, jobIds, skipped}. | `pnpm ops refresh-report --json '{"all":true}'` |
diff --git a/OPERATING.md b/OPERATING.md
@@ -1754,6 +1754,37 @@ pnpm ops compress-text --json '{"restore":true}' --wait # the roll
see the chat; with different content, the other is what readers read).
- **By hand:** `zstdcat transcript.live_chat.json.zst` reads one.
+### Compress the caption tracks
+
+```sh
+pnpm ops compress-text --json '{"kinds":["captions"],"dryRun":true}' # per channel: caption files, bytes, ~20 % after, equal-size en/en-orig pairs, free space
+pnpm ops compress-text --json '{"kinds":["captions"],"slugs":["example"],"limit":20}' --wait # a first batch
+pnpm ops compress-text --json '{"kinds":["captions"],"verify":true}' --wait # decode every stored caption; writes nothing
+pnpm ops compress-text --json '{"kinds":["captions"]}' --wait # the rest; a re-run continues
+pnpm ops compress-text --json '{"kinds":["captions"],"restore":true}' --wait # the rollback for captions
+```
+
+- **What it does.** Every caption track, `transcript.<lang>.vtt` (`en`, `en-orig`, regional, translated, foreign), is
+ stored as `transcript.<lang>.vtt.zst` beside where it was: about 20 % of its size. Captions are text on the CORPUS
+ disk (real files in `data/<id>/`, never tiered), so this is what frees that disk. Only when named: `kinds` defaults
+ to the live chat alone; `["live-chat","captions"]` does both, the chat first.
+- **Every reader reads either form** with the same times: the index (it sees no change), normalize, the snapshot's
+ buckets, the provenance sniff (it decodes the head), compose, the remote worker's inputs (sent plain), umtool's cue
+ source. A stored track is "on disk" to every skip: no download fetches it again (it is left out of `--sub-langs`),
+ and no audio is downloaded or transcribed because of it.
+- **The same rules as the chat**: one file at a time, verified, the original removed last; the quiet period, the
+ `.part` and recording refusals, the per-directory lock, person-started only, one job per channel.
+- **Two forms with different content are refused and both kept, and listed** ("refused — both-differ"): a plain
+ caption a re-fetch, a forced re-download or "Set as transcript" landed beside an older stored one. The plain one
+ is what readers read. Nothing removes a stored caption because a different one arrived: a video deleted on its
+ platform cannot give its captions again. Settle a pair on the video's files card.
+- **The en / en-orig pairs** of equal size (on samples, byte-identical) are compressed each as it is; the dry run
+ counts them (`pairsEqualSize`) for a person deciding whether to dedupe — nothing here dedupes.
+- **The tier migration's reclaim** takes a platter copy of a caption whose twin on the corpus disk is stored only
+ when the stored form decodes to exactly its bytes; otherwise it keeps and reports it.
+- **Deleting a caption**: the files card (only the file named goes), the auto-caption purge and the clear-transcript
+ fix (both forms; the purge keeps both when they differ). By hand: `zstdcat transcript.en.vtt.zst`.
+
#### Rollback: restore BEFORE reverting
An older checkout, an image built before this, or a revert of the lane cannot read a `.zst`: to it, every stored
@@ -1765,8 +1796,15 @@ first, then revert or run the older code**:
pnpm ops compress-text --json '{"restore":true,"dryRun":true}' # the plain bytes it needs, and the free space per disk
pnpm ops compress-text --json '{"restore":true}' --wait # every channel; "slugs" and "limit" as for a compress
pnpm ops compress-text --json '{"verify":true}' --wait # afterwards: "verified 0 stored chat(s)" on every channel
+pnpm ops compress-text --json '{"kinds":["captions"],"restore":true,"dryRun":true}' # the same for captions:
+pnpm ops compress-text --json '{"kinds":["captions"],"restore":true}' --wait # an older checkout sees a stored caption as no transcript at all
```
+For captions an older checkout is worse than for the chat: a video whose only captions are stored reads as having no
+transcript, so its download lane fetches the captions again and the no-subs fallback downloads the audio and
+transcribes it. Restore the captions first: they take their plain size again on the corpus disk (about 5 times the
+stored size; the dry run says how much).
+
The restore is the compressor in reverse: each stored chat is decoded beside itself (on the same drive), fsynced,
read back and hashed against a fresh decode of the `.zst`, given the same times, put in place without replacing
anything (a hard link: the drive must support them — ext4 does; on exFAT or a CIFS mount the restore refuses each
diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts
@@ -1027,6 +1027,34 @@ test("(u) lane text-compress-captions: every caption track compressed — the in
assert.deepEqual(now.alts, before.alts, "the alternate is read from the stored en-orig");
});
+test("(v) lane text-compress-captions: THE MIGRATION (compress-text, kinds captions) — the real index sees no change", async () => {
+ resetCorpus();
+ seedVideo("c1", CHANNEL, { subs: true });
+ seedVideo("c2");
+ writeFileSync(path.join(videoDir("c1"), "transcript.en-orig.vtt"), VTT.replace("First", "Original"));
+ const { utimesSync } = await import("node:fs");
+ for (const id of ["c1", "c2"]) {
+ for (const n of readdirSync(videoDir(id)).filter((x) => x.endsWith(".vtt"))) {
+ utimesSync(path.join(videoDir(id), n), 1763700000.5, 1763700000.000003);
+ }
+ }
+ const all = () =>
+ withIndex((db) => ({
+ mtimes: [...db("mtimes").getRange()].map(({ key, value }) => [key, value]),
+ cues: [...db("cues").getRange()].map(({ key, value }) => [key, value]),
+ subs: [...db("subs").getRange()].map(({ key, value }) => [key, value]),
+ alts: [...db("alts").getRange()].map(({ key, value }) => [key, value]),
+ }));
+ await runIndex();
+ const before = all();
+ const { compressText } = await import("./compressText");
+ const r = await compressText({ paths, slugs: [CHANNEL], kinds: ["captions"], quietMs: 0, compressOpts: { reserveBytes: 0 }, onLog: () => {} });
+ assert.equal(r.channels[0].compressed, 4, JSON.stringify(r.channels[0]));
+ const after = await runIndex();
+ assert.equal(after.res.changed, 0, after.log.join("\n"));
+ assert.deepEqual(all(), before);
+});
+
test("(z) no write this file caused landed outside its temp root", () => {
// LMDB writes natively, past the spy: its file must be under the root too.
assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath);
diff --git a/common/controller/compressText.captions.test.ts b/common/controller/compressText.captions.test.ts
@@ -0,0 +1,260 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createHash } from "node:crypto";
+import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rm, stat, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/compressText.captions.test.ts
+//
+// THE MIGRATION OVER CAPTIONS (lane text-compress-captions, slice 5):
+// `compress-text {kinds: ["captions"]}` over a temp corpus — a dry run that
+// touches nothing and counts the equal-size en / en-orig pairs, a real run,
+// its limit, the refusals (two forms of different content listed and both
+// kept, a recent file, a `.part`, a recording), every kill point finished by
+// the job, the check, and the restore. The live chat is left alone unless it
+// is asked for, and captions unless they are. Synthetic names only.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "compress-captions-"));
+process.env.TRANSCRIPTS_DIR = path.join(ROOT, "transcripts");
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(process.env.TRANSCRIPTS_DIR, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { compressText } = await import("./compressText");
+const { readStoredText } = await import("../lib/storedText-server");
+const { CompressKill } = await import("../lib/storedText-write-server");
+
+const paths = getPaths();
+const CAPTIONS = ["captions"] as const;
+const vtt = (seed: string, cues: number) =>
+ "WEBVTT\nKind: captions\nLanguage: en\n\n" +
+ Array.from({ length: cues }, (_, i) => {
+ const s = String(i).padStart(2, "0");
+ return `00:00:${s}.000 --> 00:00:${s}.900 align:start position:0%\n${seed} ${i} ${createHash("md5").update(seed + i).digest("hex")}\n`;
+ }).join("\n");
+const CHAT = "transcript.live_chat.json";
+const OLD = 1_700_000_000;
+
+type Videos = Record<string, Record<string, string>>;
+
+async function channel(slug: string, videos: Videos): Promise<void> {
+ const channelDir = path.join(paths.channelsDir, slug);
+ await mkdir(path.join(channelDir, "data"), { recursive: true });
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube", url: `https://www.youtube.com/@${slug}` }));
+ for (const [id, files] of Object.entries(videos)) {
+ const dir = path.join(channelDir, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id }));
+ for (const [name, text] of Object.entries(files)) {
+ await writeFile(path.join(dir, name), text);
+ // Old enough for the quiet period; sub-millisecond times.
+ await utimes(path.join(dir, name), OLD, OLD + 0.123457);
+ }
+ }
+}
+
+const dirOf = (slug: string, id: string) => path.join(paths.channelsDir, slug, "data", id);
+const names = async (slug: string, id: string) => (await readdir(dirOf(slug, id))).sort();
+const leftovers = async (slug: string, id: string) => (await readdir(dirOf(slug, id))).filter((e) => e.startsWith("."));
+
+async function tree(dir: string): Promise<string[]> {
+ const out: string[] = [];
+ async function walk(d: string): Promise<void> {
+ for (const e of (await readdir(d).catch(() => [] as string[])).sort()) {
+ const p = path.join(d, e);
+ const l = await lstat(p);
+ if (l.isSymbolicLink()) out.push(`${p} -> ${await readlink(p)} ${l.mtimeMs}`);
+ else if (l.isDirectory()) {
+ out.push(`${p}/ ${l.mtimeMs}`);
+ await walk(p);
+ } else out.push(`${p} ${l.size} ${l.mtimeMs} ${createHash("sha256").update(await readFile(p)).digest("hex")}`);
+ }
+ }
+ await walk(dir);
+ return out;
+}
+
+const PAIR = vtt("pair", 40);
+const A: Videos = {
+ a1: { "transcript.en.vtt": PAIR, "transcript.en-orig.vtt": PAIR, "transcript.es.vtt": vtt("es", 30) },
+ a2: { "transcript.en.vtt": vtt("served", 20), "transcript.en-orig.vtt": vtt("spoken", 25), [CHAT]: '{"replayChatItemAction":{}}\n'.repeat(50) },
+};
+await channel("alpha", A);
+
+test("a dry run over captions: per channel and kind, ~20 %, the equal-size pairs — and touches NOTHING", async () => {
+ const before = await tree(ROOT);
+ const lines: string[] = [];
+ const r = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, dryRun: true, onLog: (l) => lines.push(l) });
+ assert.deepEqual(await tree(ROOT), before, "not one entry changed, not one mtime");
+ assert.deepEqual(r.kinds, ["captions"]);
+ const alpha = r.channels[0];
+ const c = alpha.byKind!.captions!;
+ assert.equal(c.plainFiles, 5);
+ const bytes = Object.values(A).flatMap((v) => Object.entries(v)).filter(([n]) => n.endsWith(".vtt")).reduce((a, [, t]) => a + t.length, 0);
+ assert.equal(c.plainBytes, bytes);
+ assert.equal(c.estimateAfterBytes, Math.round(bytes * 0.2));
+ assert.equal(c.pairsEqualSize, 1, "a1's pair; a2's differ in size");
+ assert.equal(c.pairsEqualSizeBytes, PAIR.length);
+ assert.equal(alpha.byKind!["live-chat"], undefined, "the chat is not asked");
+ assert.equal(alpha.plainFiles, 5, "the channel's totals are the kinds asked");
+ assert.match(lines.join(""), /caption file\(s\).*estimate, 20 %.*en \/ en-orig pairs of equal size: 1/);
+ assert.match(lines.join(""), /Nothing was written/);
+ // And with no kinds: the live chat alone, as before captions were a kind.
+ const chatOnly = await compressText({ paths, slugs: ["alpha"], dryRun: true, onLog: () => {} });
+ assert.deepEqual(chatOnly.kinds, ["live-chat"]);
+ assert.equal(chatOnly.channels[0].plainFiles, 1);
+});
+
+test("a real run: every caption compressed, read back the same, with the same times; the chat untouched; a limit; a re-run", async () => {
+ const mt = async (id: string, n: string) => (await stat(path.join(dirOf("alpha", id), n))).mtimeMs;
+ const times: Record<string, number> = {};
+ for (const [id, files] of Object.entries(A)) for (const n of Object.keys(files)) times[`${id}/${n}`] = await mt(id, n);
+ const first = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, quietMs: 0, limit: 2, onLog: () => {} });
+ assert.equal(first.stopped, "limit");
+ assert.equal(first.channels[0].compressed, 2);
+ const rest = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ assert.equal(rest.channels[0].compressed, 3);
+ assert.equal(rest.channels[0].already, 2);
+ for (const [id, files] of Object.entries(A)) {
+ for (const [n, text] of Object.entries(files)) {
+ if (n === CHAT) continue;
+ assert.equal(await readStoredText(dirOf("alpha", id), n, "utf8"), text, `${id}/${n}`);
+ assert.equal(await mt(id, `${n}.zst`), times[`${id}/${n}`], `${id}/${n}: the same mtimeMs`);
+ }
+ }
+ assert.deepEqual(await names("alpha", "a1"), ["metadata.info.json", "transcript.en-orig.vtt.zst", "transcript.en.vtt.zst", "transcript.es.vtt.zst"]);
+ assert.ok((await names("alpha", "a2")).includes(CHAT), "the chat is not a caption: left as it was");
+ const again = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ assert.equal(again.channels[0].compressed, 0);
+ const check = await compressText({ paths, slugs: ["alpha"], kinds: CAPTIONS, verify: true, onLog: () => {} });
+ assert.equal(check.channels[0].verified, 5);
+ assert.deepEqual(check.channels[0].problems, []);
+});
+
+test("two forms of DIFFERENT content: refused, both kept, and listed — nothing removes a stored copy because another arrived", async () => {
+ await channel("beta", { b1: { "transcript.en.vtt": vtt("old", 20) } });
+ await compressText({ paths, slugs: ["beta"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ // A re-fetch (or Set as transcript) lands a new plain file beside it.
+ await writeFile(path.join(dirOf("beta", "b1"), "transcript.en.vtt"), vtt("new", 21));
+ await utimes(path.join(dirOf("beta", "b1"), "transcript.en.vtt"), OLD, OLD);
+ const lines: string[] = [];
+ const r = await compressText({ paths, slugs: ["beta"], kinds: CAPTIONS, quietMs: 0, onLog: (l) => lines.push(l) });
+ const c = r.channels[0].byKind!.captions!;
+ assert.equal(c.compressed, 0);
+ assert.deepEqual(c.refused?.map((x) => [x.id, x.name, x.reason]), [["b1", "transcript.en.vtt", "both-differ"]]);
+ assert.match(lines.join(""), /b1\/transcript\.en\.vtt: refused — both-differ.*both files are kept/);
+ assert.match(lines.join(""), /1 refused with both forms kept/);
+ assert.deepEqual(await names("beta", "b1"), ["metadata.info.json", "transcript.en.vtt", "transcript.en.vtt.zst"]);
+ assert.equal(await readStoredText(dirOf("beta", "b1"), "transcript.en.vtt", "utf8"), vtt("new", 21), "plain is the truth");
+ const check = await compressText({ paths, slugs: ["beta"], kinds: CAPTIONS, verify: true, onLog: () => {} });
+ assert.deepEqual(check.channels[0].problems?.map((p) => p.status), ["differs"]);
+});
+
+test("left alone and counted: a recent file, a `.part` beside it, a video recording", async () => {
+ await channel("gamma", {
+ g1: { "transcript.en.vtt": vtt("recent", 10) },
+ g2: { "transcript.en.vtt": vtt("partial", 10), "transcript.es.vtt.part": "half" },
+ g3: { "transcript.en.vtt": vtt("live", 10), "live-recording.json": JSON.stringify({ status: "recording" }) },
+ g4: { "transcript.en.vtt": vtt("refetch", 10), "transcript.en.vtt.part": "a download of the same track" },
+ });
+ // The quiet period asks the later of mtime and ctime: every file here was
+ // just made (ctime now), so the run's clock is 20 minutes on, and g1's
+ // mtime 15 minutes on — written 5 minutes before the run, by its clock.
+ const t0 = Date.now();
+ await utimes(path.join(dirOf("gamma", "g1"), "transcript.en.vtt"), (t0 + 15 * 60_000) / 1000, (t0 + 15 * 60_000) / 1000);
+ const r = await compressText({ paths, slugs: ["gamma"], kinds: CAPTIONS, now: () => t0 + 20 * 60_000, onLog: () => {} });
+ const c = r.channels[0].byKind!.captions!;
+ assert.equal(c.compressed, 1, "g2's en track only");
+ assert.deepEqual(c.skipped, { recent: 1, recording: 1, partial: 1 });
+ // The `.part` is of another track: the en track itself is not partial, and
+ // the es one has no plain form (only its partial): nothing to compress.
+ assert.equal((await names("gamma", "g2")).includes("transcript.en.vtt.zst"), true);
+ for (const id of ["g1", "g3", "g4"]) assert.equal((await names("gamma", id)).includes("transcript.en.vtt"), true, id);
+});
+
+const killAt = (point: string) => (p: string) => {
+ if (p === point) throw new CompressKill(p as never);
+};
+
+test("every kill point, then a job run: a whole copy at each point, and the job finishes it", async () => {
+ const points = ["compressing", "written", "verified", "placed", "retired"] as const;
+ // One channel per point: a run over a channel would first finish a video an
+ // earlier point left, and stop there.
+ for (const p of points) {
+ const slug = `delta-${p}`;
+ await channel(slug, { k1: { "transcript.en-orig.vtt": vtt(p, 30) } });
+ await assert.rejects(
+ compressText({ paths, slugs: [slug], kinds: CAPTIONS, quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_990, crashAt: killAt(p) } }),
+ CompressKill,
+ p,
+ );
+ // A whole copy, readable, whatever was left.
+ assert.equal(await readStoredText(dirOf(slug, "k1"), "transcript.en-orig.vtt", "utf8"), vtt(p, 30), `${p}: read back`);
+ if (p === "retired") {
+ assert.ok(!(await names(slug, "k1")).includes("transcript.en-orig.vtt"), "retired: the plain name is absent");
+ assert.equal((await leftovers(slug, "k1")).length, 1, "the set-aside original");
+ }
+ // The job's survey sees the file as work, whatever the point.
+ const plan = await compressText({ paths, slugs: [slug], kinds: CAPTIONS, dryRun: true, onLog: () => {} });
+ assert.equal(plan.channels[0].pending, 1, `${p}: work for the job`);
+ const r = await compressText({ paths, slugs: [slug], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ assert.deepEqual(r.channels[0].failed, [], p);
+ assert.deepEqual(await leftovers(slug, "k1"), [], `${p}: no leftover`);
+ assert.deepEqual(await names(slug, "k1"), ["metadata.info.json", "transcript.en-orig.vtt.zst"], p);
+ assert.equal(await readStoredText(dirOf(slug, "k1"), "transcript.en-orig.vtt", "utf8"), vtt(p, 30), p);
+ }
+});
+
+test("restore over captions: the dry run is exact and touches nothing; a restore, killed, re-run — the plain files with their times", async () => {
+ await channel("eta", { h1: { "transcript.en.vtt": vtt("h1", 30), "transcript.de.vtt": vtt("de", 12) } });
+ const before: Record<string, number> = {};
+ for (const n of ["transcript.en.vtt", "transcript.de.vtt"]) before[n] = (await stat(path.join(dirOf("eta", "h1"), n))).mtimeMs;
+ await compressText({ paths, slugs: ["eta"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ const tr = await tree(dirOf("eta", "h1"));
+ const plan = await compressText({ paths, slugs: ["eta"], kinds: CAPTIONS, restore: true, dryRun: true, onLog: () => {} });
+ assert.deepEqual(await tree(dirOf("eta", "h1")), tr);
+ assert.equal(plan.channels[0].estimateAfterBytes, vtt("h1", 30).length + vtt("de", 12).length);
+ await assert.rejects(
+ compressText({ paths, slugs: ["eta"], kinds: CAPTIONS, restore: true, onLog: () => {}, compressOpts: { pid: 999_999_991, crashAt: killAt("restore-placed") } }),
+ CompressKill,
+ );
+ const r = await compressText({ paths, slugs: ["eta"], kinds: CAPTIONS, restore: true, onLog: () => {} });
+ assert.ok((r.channels[0].restored ?? 0) >= 1);
+ assert.deepEqual(await names("eta", "h1"), ["metadata.info.json", "transcript.de.vtt", "transcript.en.vtt"]);
+ for (const n of ["transcript.en.vtt", "transcript.de.vtt"]) {
+ assert.equal((await stat(path.join(dirOf("eta", "h1"), n))).mtimeMs, before[n], `${n}: the index key`);
+ }
+ assert.equal(await readFile(path.join(dirOf("eta", "h1"), "transcript.en.vtt"), "utf8"), vtt("h1", 30));
+});
+
+test("both kinds: the live chat first, then the captions — each counted under its own kind", async () => {
+ await channel("theta", { t1: { "transcript.en.vtt": vtt("t1", 10), [CHAT]: '{"replayChatItemAction":{}}\n'.repeat(80) } });
+ const lines: string[] = [];
+ const r = await compressText({ paths, slugs: ["theta"], kinds: ["captions", "live-chat"], quietMs: 0, onLog: (l) => lines.push(l) });
+ assert.deepEqual(r.kinds, ["live-chat", "captions"], "the walk's order whatever was asked");
+ assert.equal(r.channels[0].byKind!["live-chat"]!.compressed, 1);
+ assert.equal(r.channels[0].byKind!.captions!.compressed, 1);
+ assert.equal(r.channels[0].compressed, 2);
+ const text = lines.join("");
+ assert.ok(text.indexOf("[live-chat]") < text.indexOf("[captions]"), text);
+ assert.deepEqual(await names("theta", "t1"), ["metadata.info.json", "transcript.en.vtt.zst", `${CHAT}.zst`]);
+});
+
+test("a caption that is a link into media/ (none on this corpus: the classifier never tiers one) is handled like a tiered chat", async () => {
+ const { symlink } = await import("node:fs/promises");
+ await channel("iota", { i1: {} });
+ const channelDir = path.join(paths.channelsDir, "iota");
+ await mkdir(path.join(channelDir, "media", "i1"), { recursive: true });
+ await writeFile(path.join(channelDir, "media", "i1", "transcript.en.vtt"), vtt("linked", 15));
+ await symlink(path.join("..", "..", "media", "i1", "transcript.en.vtt"), path.join(dirOf("iota", "i1"), "transcript.en.vtt"));
+ const r = await compressText({ paths, slugs: ["iota"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ assert.equal(r.channels[0].compressed, 1);
+ // The stored bytes beside the original's, on the same drive, with a link of their own.
+ assert.deepEqual(await readdir(path.join(channelDir, "media", "i1")), ["transcript.en.vtt.zst"]);
+ assert.equal(await readlink(path.join(dirOf("iota", "i1"), "transcript.en.vtt.zst")), path.join("..", "..", "media", "i1", "transcript.en.vtt.zst"));
+ assert.equal(await readStoredText(dirOf("iota", "i1"), "transcript.en.vtt", "utf8"), vtt("linked", 15));
+});
diff --git a/common/controller/compressText.ts b/common/controller/compressText.ts
@@ -1,9 +1,18 @@
-// COMPRESS TEXT — the migration that puts the existing raw live-chat replays
-// into their stored form (lib/storedText.ts): `transcript.live_chat.json` →
-// `transcript.live_chat.json.zst`, one file at a time, through the compressor
+// COMPRESS TEXT — the migration that puts existing big text files into their
+// stored form (lib/storedText.ts), one file at a time, through the compressor
// in lib/storedText-write-server.ts (write beside, fsync, read back and hash,
-// then the original removed through removeMediaFile). Lane text-compress,
-// slice 2; `pnpm ops compress-text` posts it.
+// then the original removed through removeMediaFile). `pnpm ops compress-text`
+// posts it. Two KINDS:
+//
+// live-chat the raw live-chat replay, `transcript.live_chat.json` → `.zst`
+// (lane text-compress, slice 2) — mostly on the media drive;
+// captions every caption track, `transcript.<lang>.vtt` → `.zst` (lane
+// text-compress-captions, slice 5) — on the CORPUS disk, real
+// files in `data/<id>/` (the classifier never tiers one; a link,
+// if one were there, is handled as the chat's are).
+//
+// `kinds` defaults to the live chat alone: captions are compressed only when a
+// person names them. Both named: the live chat first, then the captions.
//
// SAFE BY CONSTRUCTION, RESUMABLE BY RE-WALKING. Every file is "already",
// "compressed", skipped with a reason, or repaired by the compressor's crash
@@ -16,36 +25,46 @@
// recording or has a job running, one on a drive that does not answer, is
// left alone and counted.
//
-// `dryRun` WRITES NOTHING AND READS NO CONTENT: per channel, the plain files
-// and their bytes, the stored files and their logical bytes (from the frame
-// 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.
+// `dryRun` WRITES NOTHING AND READS NO CONTENT: per channel and per kind, the
+// plain files and their bytes, the stored files and their logical bytes (from
+// the frame 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. For captions it also counts the en / en-orig PAIRS OF EQUAL
+// SIZE (by the logical size): each is compressed as it is — never deduped —
+// and the count says how much of the caption bytes are the pair twice.
// `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.
+// THE WALK VISITS EVERY FILE A RUN MAY HAVE TO FINISH: one whose plain form is
+// there (a dangling tier link too — an interrupted removal), or whose stored
+// form is (the restore), or a stopped run's leftover for it (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).
+// TWO FORMS WITH DIFFERENT CONTENT — a plain caption a re-fetch or "Set as
+// transcript" landed beside an older stored one — ARE REFUSED AND BOTH KEPT,
+// and listed (`both-differ`, with the file): nothing removes a stored copy
+// because a different one arrived. A video deleted on its platform cannot give
+// its captions again.
+//
+// `restore: true` IS THE ROLLBACK: every stored file of the named kinds 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";
import type { Paths } from "../lib/paths";
-import { LIVE_CHAT_FILENAME } from "../lib/videoStatus";
-import { storedFormsIn, storedNameOf } from "../lib/storedText";
+import { LIVE_CHAT_FILENAME, ORIG_VTT_FILENAME, VTT_FILENAME } from "../lib/videoStatus";
+import { isStoredCaptionName, logicalEntries, storedFormsIn, storedNameOf } from "../lib/storedText";
import { isKeptChatCapture } from "../lib/mediaTier";
import { frameContentSize } from "../lib/storedText-server";
import {
compressStoredText,
hasStoredTextLeftover,
restoreStoredText,
+ storedTextLeftoverNames,
verifyStoredText,
type CompressOutcome,
type CompressSkipReason,
@@ -55,12 +74,21 @@ import { inspectChannelMedia } from "../lib/channelMedia";
import { onDrive } from "../lib/storageHealth";
import { readChannelConfig, listChannelSlugs } from "./channels";
-export const COMPRESS_TEXT_KINDS = ["live-chat"] as const;
+export const COMPRESS_TEXT_KINDS = ["live-chat", "captions"] as const;
export type CompressTextKind = (typeof COMPRESS_TEXT_KINDS)[number];
+export const DEFAULT_COMPRESS_TEXT_KINDS: readonly CompressTextKind[] = ["live-chat"];
+
+export function isCompressTextKind(k: unknown): k is CompressTextKind {
+ return typeof k === "string" && (COMPRESS_TEXT_KINDS as readonly string[]).includes(k);
+}
-// Measured on a sample (lane text-compress design §1): a raw chat at level 9
-// is ~5 % of its size. An estimate, and every line that uses it says so.
+// Measured on samples (lane text-compress design §1): a raw chat at level 9
+// is ~5 % of its size, a caption track ~20 %. Estimates, and every line that
+// uses one says so.
export const CHAT_RATIO_ESTIMATE = 0.05;
+export const CAPTION_RATIO_ESTIMATE = 0.2;
+const RATIO: Record<CompressTextKind, number> = { "live-chat": CHAT_RATIO_ESTIMATE, captions: CAPTION_RATIO_ESTIMATE };
+const NOUN: Record<CompressTextKind, string> = { "live-chat": "raw chat(s)", captions: "caption file(s)" };
export const COMPRESS_QUIET_MS = 10 * 60_000;
export const COMPRESS_RATE_BYTES = 40 * 1024 * 1024;
export const COMPRESS_RATE_RECORDING_BYTES = 8 * 1024 * 1024;
@@ -69,6 +97,8 @@ export type CompressTextOptions = {
paths: Paths;
// Default: every channel.
slugs?: string[];
+ // Default: the live chat alone (DEFAULT_COMPRESS_TEXT_KINDS).
+ kinds?: readonly CompressTextKind[];
dryRun?: boolean;
verify?: boolean;
// The rollback: stored → plain (with `dryRun`: the plan).
@@ -91,18 +121,49 @@ export type CompressTextOptions = {
compressOpts?: Parameters<typeof compressStoredText>[2];
};
+// One kind's figures for one channel (the same fields as the channel line).
+export type KindLine = {
+ plainFiles: number;
+ plainBytes: number;
+ storedFiles: number;
+ storedLogicalBytes: number;
+ storedBytes: number;
+ // The files 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).
+ pending: number;
+ // Captions only: dirs whose `transcript.en.vtt` and `transcript.en-orig.vtt`
+ // are both here, in either form, with the same LOGICAL size (on samples of
+ // this corpus every such pair was byte-identical). Compressed each as it
+ // is; the count is for a person deciding on a dedupe.
+ pairsEqualSize?: number;
+ pairsEqualSizeBytes?: number;
+ estimateAfterBytes?: number;
+ compressed?: number;
+ restored?: number;
+ bytesBefore?: number;
+ bytesAfter?: number;
+ already?: number;
+ changed?: number;
+ skipped?: Partial<Record<CompressSkipReason, number>>;
+ failed?: { id: string; name: string; error: string }[];
+ // Files left with BOTH forms of different content (or a stored form that
+ // does not decode): kept, both, for a person — listed.
+ refused?: { id: string; name: string; reason: CompressSkipReason; detail?: string }[];
+ verified?: number;
+ problems?: { id: string; name: string; status: string; detail?: string }[];
+};
+
export type ChannelLine = {
slug: string;
// Why the channel was not walked, when it was not.
refused?: string;
+ // The totals over the kinds asked (with the live chat alone, exactly its
+ // figures, as before captions were a kind).
plainFiles: number;
plainBytes: number;
storedFiles: number;
storedLogicalBytes: number;
storedBytes: number;
- // 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;
// Earlier chat captures kept by a re-fetch (`chat-capture-kept.*.json.zst`,
// lib/mediaTier.ts): never removed automatically — counted so a person sees
@@ -112,7 +173,7 @@ export type ChannelLine = {
// 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.
+ // Dry run only: free space now on the disk(s) holding this channel's files.
free?: { corpus?: number; media?: number };
// A real run.
compressed?: number;
@@ -121,26 +182,30 @@ export type ChannelLine = {
already?: number;
changed?: number;
skipped?: Partial<Record<CompressSkipReason, number>>;
- failed?: { id: string; error: string }[];
+ failed?: { id: string; error: string; name?: string }[];
// A restore.
restored?: number;
// Verify.
verified?: number;
- problems?: { id: string; status: string; detail?: string }[];
+ problems?: { id: string; status: string; detail?: string; name?: string }[];
+ // Per kind asked.
+ byKind?: Partial<Record<CompressTextKind, KindLine>>;
};
export type CompressTextResult = {
dryRun: boolean;
verify: boolean;
restore: boolean;
+ kinds: CompressTextKind[];
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
+// A file 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 };
+type Candidate = { id: string; videoDir: string; name: string; size: number };
+type Stored = { id: string; videoDir: string; name: string; bytes: number; logical: number };
function fmtBytes(n: number): string {
if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;
@@ -192,67 +257,124 @@ async function storedLogicalSize(file: string): Promise<number | null> {
}
}
-// One channel's chats, by what is on disk. Sizes are `stat`s (through a tier
-// link, under the drive's watchdog); no content is read.
-async function surveyChannel(
- channelDir: string,
- drive: string | undefined,
-): Promise<{
+// The declared names of one kind in one dir's PHYSICAL listing: either form,
+// or a stopped run's leftover for it.
+function namesOfKind(kind: CompressTextKind, entries: readonly string[]): string[] {
+ if (kind === "live-chat") return [LIVE_CHAT_FILENAME];
+ const names = new Set(logicalEntries(entries).filter(isStoredCaptionName));
+ for (const n of storedTextLeftoverNames(entries)) if (isStoredCaptionName(n)) names.add(n);
+ return [...names].sort();
+}
+
+type KindSurvey = {
plain: Candidate[];
- stored: { id: string; videoDir: string; bytes: number; logical: number }[];
- // Every dir a compress run visits: the plain form, present at all (a
+ stored: Stored[];
+ // Every file 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.
+ // Every file a restore visits: the stored form, or a leftover.
restoreWork: Candidate[];
- kept: { files: number; bytes: number };
-}> {
+ pairsEqualSize: number;
+ pairsEqualSizeBytes: number;
+};
+
+// One channel's files of the kinds asked, by what is on disk. Sizes are
+// `stat`s (through a tier link, under the drive's watchdog); no content is
+// read beyond a stored file's 18-byte frame header.
+async function surveyChannel(
+ channelDir: string,
+ drive: string | undefined,
+ kinds: readonly CompressTextKind[],
+): Promise<{ byKind: Partial<Record<CompressTextKind, KindSurvey>>; kept: { files: number; bytes: number } }> {
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 byKind: Partial<Record<CompressTextKind, KindSurvey>> = {};
+ for (const k of kinds) {
+ byKind[k] = { plain: [], stored: [], work: [], restoreWork: [], pairsEqualSize: 0, pairsEqualSizeBytes: 0 };
+ }
const kept = { files: 0, bytes: 0 };
const sizeOf = (p: string) =>
(drive ? onDrive(drive, () => stat(p)) : stat(p)).then((s) => s.size, () => null);
+ const logicalOf = (p: string) => (drive ? onDrive(drive, () => storedLogicalSize(p)) : storedLogicalSize(p)).catch(() => null);
for (const id of ids) {
const videoDir = path.join(dataDir, id);
const entries = await readdir(videoDir).catch(() => null);
if (!entries) continue;
- const forms = storedFormsIn(entries, LIVE_CHAT_FILENAME);
- const leftover = hasStoredTextLeftover(entries, LIVE_CHAT_FILENAME);
- for (const k of entries.filter(isKeptChatCapture)) {
- kept.files += 1;
- kept.bytes += (await sizeOf(path.join(videoDir, k))) ?? 0;
- }
- let size: number | null = null;
- if (forms === "plain" || forms === "both") {
- size = await sizeOf(path.join(videoDir, LIVE_CHAT_FILENAME));
- if (size !== null) plain.push({ id, videoDir, size });
+ if (kinds.includes("live-chat")) {
+ for (const k of entries.filter(isKeptChatCapture)) {
+ kept.files += 1;
+ kept.bytes += (await sizeOf(path.join(videoDir, k))) ?? 0;
+ }
}
- 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);
- const logical = bytes === null ? null : await (drive
- ? onDrive(drive, () => storedLogicalSize(zp))
- : storedLogicalSize(zp)).catch(() => null);
- if (bytes !== null) stored.push({ id, videoDir, bytes, logical: logical ?? 0 });
+ for (const kind of kinds) {
+ const s = byKind[kind]!;
+ const logicalSize: Record<string, number | null> = {};
+ for (const name of namesOfKind(kind, entries)) {
+ const forms = storedFormsIn(entries, name);
+ const leftover = hasStoredTextLeftover(entries, name);
+ let size: number | null = null;
+ if (forms === "plain" || forms === "both") {
+ size = await sizeOf(path.join(videoDir, name));
+ if (size !== null) s.plain.push({ id, videoDir, name, size });
+ logicalSize[name] = size;
+ }
+ if (forms === "plain" || forms === "both" || leftover) s.work.push({ id, videoDir, name, size: size ?? 0 });
+ if (forms === "zst" || forms === "both" || leftover) s.restoreWork.push({ id, videoDir, name, size: 0 });
+ if (forms === "zst" || forms === "both") {
+ const zp = path.join(videoDir, storedNameOf(name));
+ const bytes = await sizeOf(zp);
+ const logical = bytes === null ? null : await logicalOf(zp);
+ if (bytes !== null) s.stored.push({ id, videoDir, name, bytes, logical: logical ?? 0 });
+ // The plain form, when it is here, is the truth (lib/storedText.ts).
+ if (forms === "zst") logicalSize[name] = logical;
+ }
+ }
+ if (kind === "captions") {
+ const en = logicalSize[VTT_FILENAME];
+ const orig = logicalSize[ORIG_VTT_FILENAME];
+ if (typeof en === "number" && en === orig) {
+ s.pairsEqualSize += 1;
+ s.pairsEqualSizeBytes += en;
+ }
+ }
}
}
// 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, kept };
+ const bySize = (a: Candidate, b: Candidate) =>
+ a.size - b.size || (a.id < b.id ? -1 : a.id > b.id ? 1 : a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
+ for (const s of Object.values(byKind)) {
+ s!.plain.sort(bySize);
+ s!.work.sort(bySize);
+ }
+ return { byKind, kept };
+}
+
+function emptyKindLine(s: KindSurvey, restore: boolean): KindLine {
+ return {
+ plainFiles: s.plain.length,
+ plainBytes: s.plain.reduce((a, c) => a + c.size, 0),
+ storedFiles: s.stored.length,
+ storedBytes: s.stored.reduce((a, c) => a + c.bytes, 0),
+ storedLogicalBytes: s.stored.reduce((a, c) => a + c.logical, 0),
+ pending: (restore ? s.restoreWork : s.work).length,
+ };
+}
+
+const sum = (lines: KindLine[], f: (l: KindLine) => number | undefined) => lines.reduce((a, l) => a + (f(l) ?? 0), 0);
+
+function mergeSkipped(into: Partial<Record<CompressSkipReason, number>>, from: Partial<Record<CompressSkipReason, number>> | undefined) {
+ for (const [r, n] of Object.entries(from ?? {})) {
+ into[r as CompressSkipReason] = (into[r as CompressSkipReason] ?? 0) + (n ?? 0);
+ }
}
export async function compressText(opts: CompressTextOptions): Promise<CompressTextResult> {
const dryRun = opts.dryRun === true;
const restore = opts.restore === true;
const verify = !dryRun && !restore && opts.verify === true;
+ // In the walk's order: the live chat first (the media drive), then captions.
+ const asked = opts.kinds && opts.kinds.length > 0 ? opts.kinds : DEFAULT_COMPRESS_TEXT_KINDS;
+ const kinds = COMPRESS_TEXT_KINDS.filter((k) => asked.includes(k));
const lines: string[] = [];
const say = (line: string) => {
lines.push(line);
@@ -266,6 +388,7 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
// Files compressed (or restored) this run: what `limit` counts.
let doneThisRun = 0;
let stopped: CompressTextResult["stopped"];
+ const label = (k: CompressTextKind) => (kinds.length > 1 ? ` [${k}]` : "");
for (const slug of slugs) {
if (stopped) break;
@@ -291,216 +414,253 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT
continue;
}
const drive = media.status === "ok" ? media.target : undefined;
- const { plain, stored, work, restoreWork, kept } = await surveyChannel(channelDir, drive);
- line.keptCaptures = kept.files;
- line.keptCaptureBytes = kept.bytes;
+ const { byKind: survey, kept } = await surveyChannel(channelDir, drive, kinds);
+ if (kinds.includes("live-chat")) {
+ line.keptCaptures = kept.files;
+ line.keptCaptureBytes = kept.bytes;
+ }
const keptText = kept.files ? `; earlier captures kept: ${kept.files} (${fmtBytes(kept.bytes)})` : "";
- 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);
+ const kl: Partial<Record<CompressTextKind, KindLine>> = {};
+ for (const k of kinds) kl[k] = emptyKindLine(survey[k]!, restore);
+ line.byKind = kl;
+ const all = kinds.map((k) => kl[k]!);
+ line.plainFiles = sum(all, (l) => l.plainFiles);
+ line.plainBytes = sum(all, (l) => l.plainBytes);
+ line.storedFiles = sum(all, (l) => l.storedFiles);
+ line.storedBytes = sum(all, (l) => l.storedBytes);
+ line.storedLogicalBytes = sum(all, (l) => l.storedLogicalBytes);
+ line.pending = sum(all, (l) => l.pending);
+ if (kinds.includes("captions")) {
+ kl.captions!.pairsEqualSize = survey.captions!.pairsEqualSize;
+ kl.captions!.pairsEqualSizeBytes = survey.captions!.pairsEqualSizeBytes;
+ }
+ const freeOf = (p: string) => statfs(p).then((f) => f.bavail * f.bsize, () => undefined);
+ const freeLine = async () => {
line.free = {
corpus: await freeOf(path.join(channelDir, "data")),
...(drive ? { media: await onDrive(drive, () => freeOf(drive)).catch(() => undefined) } : {}),
};
- if (line.storedFiles + kept.files > 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)}${keptText}`,
- );
- }
- continue;
- }
+ };
+ // Which disk a kind's files are on: the chat on the media drive when the
+ // channel has one, captions on the corpus disk (never tiered).
+ const freeText = (k: CompressTextKind) =>
+ k === "live-chat" && drive
+ ? `free on the media drive ${fmtBytes(line.free?.media ?? 0)}`
+ : `free on the corpus disk ${fmtBytes(line.free?.corpus ?? 0)}`;
+ const pairsText = (k: CompressTextKind) => {
+ const c = kl[k]!;
+ return k === "captions" && c.pairsEqualSize
+ ? `; en / en-orig pairs of equal size: ${c.pairsEqualSize} (${fmtBytes(c.pairsEqualSizeBytes ?? 0)} each side — compressed each as it is, not deduped)`
+ : "";
+ };
- 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`);
- }
+ if (dryRun && restore) {
+ // Exact, from the frame headers: what the plain files will take again.
+ line.estimateAfterBytes = line.storedLogicalBytes;
+ await freeLine();
+ for (const k of kinds) {
+ const c = kl[k]!;
+ c.estimateAfterBytes = c.storedLogicalBytes;
+ if (c.storedFiles + (k === "live-chat" ? kept.files : 0) > 0) {
+ say(
+ `${slug}${label(k)}: ${c.storedFiles} stored ${k === "live-chat" ? "chat(s)" : "caption file(s)"}, ` +
+ `${fmtBytes(c.storedBytes)} → ${fmtBytes(c.storedLogicalBytes)} as plain files; ${freeText(k)}` +
+ `${k === "live-chat" ? keptText : ""}`,
+ );
}
}
- 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);
- 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.plainFiles + line.storedFiles + kept.files > 0) {
- say(
- `${slug}: ${line.plainFiles} raw chat(s), ${fmtBytes(line.plainBytes)} → ~${fmtBytes(line.estimateAfterBytes)} ` +
- `(estimate, ${Math.round(CHAT_RATIO_ESTIMATE * 100)} %); already stored ${line.storedFiles} ` +
- `(${fmtBytes(line.storedBytes)} holding ${fmtBytes(line.storedLogicalBytes)}); ` +
- `free on ${drive ? "the media drive" : "the corpus disk"} ` +
- `${fmtBytes((drive ? line.free.media : line.free.corpus) ?? 0)}${keptText}`,
- );
+ await freeLine();
+ for (const k of kinds) {
+ const c = kl[k]!;
+ c.estimateAfterBytes = Math.round(c.plainBytes * RATIO[k]);
+ if (c.plainFiles + c.storedFiles + (k === "live-chat" ? kept.files : 0) > 0) {
+ say(
+ `${slug}${label(k)}: ${c.plainFiles} ${NOUN[k]}, ${fmtBytes(c.plainBytes)} → ~${fmtBytes(c.estimateAfterBytes)} ` +
+ `(estimate, ${Math.round(RATIO[k] * 100)} %); already stored ${c.storedFiles} ` +
+ `(${fmtBytes(c.storedBytes)} holding ${fmtBytes(c.storedLogicalBytes)}); ${freeText(k)}` +
+ `${pairsText(k)}${k === "live-chat" ? keptText : ""}`,
+ );
+ }
}
+ line.estimateAfterBytes = sum(all, (l) => l.estimateAfterBytes);
continue;
}
if (verify) {
line.verified = 0;
line.problems = [];
- for (const s of stored) {
- if (opts.signal?.aborted) { stopped = "cancelled"; break; }
- if (opts.drainSignal?.aborted) { stopped = "drained"; break; }
- const v = await verifyStoredText(s.videoDir, LIVE_CHAT_FILENAME, { throttle });
- if (v.status === "ok") line.verified += 1;
- else {
- line.problems.push({ id: s.id, status: v.status, ...("detail" in v ? { detail: v.detail } : {}) });
- say(`${slug}/${s.id}: ${v.status}${"detail" in v ? ` — ${v.detail}` : ""}`);
+ for (const k of kinds) {
+ const c = kl[k]!;
+ c.verified = 0;
+ c.problems = [];
+ for (const s of survey[k]!.stored) {
+ if (opts.signal?.aborted) { stopped = "cancelled"; break; }
+ if (opts.drainSignal?.aborted) { stopped = "drained"; break; }
+ const v = await verifyStoredText(s.videoDir, s.name, { throttle });
+ if (v.status === "ok") {
+ c.verified += 1;
+ line.verified += 1;
+ } else {
+ const p = { id: s.id, name: s.name, status: v.status, ...("detail" in v ? { detail: v.detail } : {}) };
+ c.problems.push(p);
+ line.problems.push(p);
+ say(`${slug}/${s.id}/${s.name}: ${v.status}${"detail" in v ? ` — ${v.detail}` : ""}`);
+ }
}
+ say(`${slug}${label(k)}: verified ${c.verified} stored ${k === "live-chat" ? "chat(s)" : "caption file(s)"}, ${c.problems.length} problem(s)`);
+ if (stopped) break;
}
- say(`${slug}: verified ${line.verified} stored chat(s), ${line.problems.length} problem(s)`);
continue;
}
- line.compressed = 0;
+ // ── a real run: compress, or restore ────────────────────────────────────
line.bytesBefore = 0;
line.bytesAfter = 0;
- // 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.already = 0;
line.changed = 0;
line.skipped = {};
line.failed = [];
- for (const c of work) {
- 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; }
+ if (restore) line.restored = 0;
+ else line.compressed = 0;
+ for (const k of kinds) {
+ const c = kl[k]!;
+ const s = survey[k]!;
+ c.bytesBefore = 0;
+ c.bytesAfter = 0;
+ c.changed = 0;
+ c.skipped = {};
+ c.failed = [];
+ c.refused = [];
+ const work = restore ? s.restoreWork : s.work;
+ if (restore) {
+ c.restored = 0;
+ c.already = 0;
+ } else {
+ c.compressed = 0;
+ // A stored file with nothing to finish is "already"; one in `work`
+ // says so itself.
+ const inWork = new Set(work.map((w) => `${w.id}/${w.name}`));
+ c.already = s.stored.filter((z) => !inWork.has(`${z.id}/${z.name}`)).length;
}
- let out: CompressOutcome;
- try {
- out = await compressStoredText(c.videoDir, LIVE_CHAT_FILENAME, {
- quietMs: opts.quietMs ?? COMPRESS_QUIET_MS,
- now,
- isBusy: opts.isBusy ? () => opts.isBusy!(slug, c.id) : undefined,
+ for (const w of work) {
+ 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; }
+ }
+ const runOpts = {
+ isBusy: opts.isBusy ? () => opts.isBusy!(slug, w.id) : undefined,
throttle,
...(opts.signal ? { signal: opts.signal } : {}),
- onLog: (l) => opts.onLog(`${l}\n`),
+ onLog: (l: string) => 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 original is untouched)`);
- continue;
- }
- if (out.status === "compressed") {
- doneThisRun += 1;
- line.compressed += 1;
- line.bytesBefore += out.before;
- line.bytesAfter += out.after;
- opts.onLog(`${slug}/${c.id}: ${fmtBytes(out.before)} → ${fmtBytes(out.after)}${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`);
+ };
+ let out: CompressOutcome | RestoreOutcome;
+ try {
+ out = restore
+ ? await restoreStoredText(w.videoDir, w.name, runOpts)
+ : await compressStoredText(w.videoDir, w.name, {
+ quietMs: opts.quietMs ?? COMPRESS_QUIET_MS,
+ now,
+ ...runOpts,
+ });
+ } catch (err) {
+ if ((err as Error).name === "CompressKill") throw err;
+ c.failed.push({ id: w.id, name: w.name, error: (err as Error).message });
+ say(
+ `${slug}/${w.id}/${w.name}: failed — ${(err as Error).message} ` +
+ `(${restore ? "the stored file" : "the original"} is untouched)`,
+ );
+ continue;
+ }
+ const where = k === "live-chat" ? `${slug}/${w.id}` : `${slug}/${w.id}/${w.name}`;
+ if (out.status === "compressed" || out.status === "restored") {
+ doneThisRun += 1;
+ if (out.status === "compressed") c.compressed! += 1;
+ else c.restored! += 1;
+ c.bytesBefore += out.before;
+ c.bytesAfter += out.after;
+ opts.onLog(
+ `${where}: ${fmtBytes(out.before)} → ${fmtBytes(out.after)}${restore ? " (restored)" : ""}${out.tiered ? " (media tier)" : ""}\n`,
+ );
+ } else if (out.status === "already") {
+ c.already += 1;
+ } else if (out.status === "changed") {
+ c.changed += 1;
+ } else if (out.status === "skipped") {
+ c.skipped[out.reason] = (c.skipped[out.reason] ?? 0) + 1;
+ if (out.reason === "both-differ" || out.reason === "stored-corrupt" || out.reason === "retired-kept") {
+ c.refused.push({ id: w.id, name: w.name, reason: out.reason, ...(out.detail ? { detail: out.detail } : {}) });
+ say(`${where}: refused — ${out.reason}${out.detail ? ` (${out.detail})` : ""}; both files are kept`);
+ }
}
}
- }
- const skippedText = Object.entries(line.skipped)
- .map(([r, n]) => `${n} ${r}`)
- .join(", ");
- 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}`,
- );
+ // The channel's totals.
+ line.bytesBefore += c.bytesBefore;
+ line.bytesAfter += c.bytesAfter;
+ line.already += c.already;
+ line.changed += c.changed;
+ mergeSkipped(line.skipped, c.skipped);
+ line.failed.push(...c.failed);
+ if (restore) line.restored! += c.restored!;
+ else line.compressed! += c.compressed!;
+ const skippedText = Object.entries(c.skipped).map(([r, n]) => `${n} ${r}`).join(", ");
+ if (restore && work.length > 0) {
+ say(
+ `${slug}${label(k)}: restored ${c.restored} (${fmtBytes(c.bytesBefore)} → ${fmtBytes(c.bytesAfter)}), ` +
+ `already plain ${c.already}, changed ${c.changed}, skipped ${skippedText || "0"}, failed ${c.failed.length}`,
+ );
+ } else if (!restore && work.length + c.storedFiles > 0) {
+ say(
+ `${slug}${label(k)}: compressed ${c.compressed} (${fmtBytes(c.bytesBefore)} → ${fmtBytes(c.bytesAfter)}), ` +
+ `already ${c.already}, changed ${c.changed}, skipped ${skippedText || "0"}, failed ${c.failed.length}`,
+ );
+ }
+ if (stopped) break;
}
}
+ const kindsText = kinds.map((k) => NOUN[k]).join(" and ");
+ const storedNoun = kinds.map((k) => (k === "live-chat" ? "chat(s)" : "caption file(s)")).join(" and ");
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.`);
+ say(`Dry run (restore): ${n} stored ${storedNoun} → ${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` : ""}.`);
+ say(`Restored ${r} ${kindsText} 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);
+ const parts = kinds.map((k) => {
+ const n = channels.reduce((a, c) => a + (c.byKind?.[k]?.plainFiles ?? 0), 0);
+ const b = channels.reduce((a, c) => a + (c.byKind?.[k]?.plainBytes ?? 0), 0);
+ return `${n} ${NOUN[k]}, ${fmtBytes(b)} → ~${fmtBytes(Math.round(b * RATIO[k]))}`;
+ });
const kf = channels.reduce((a, c) => a + (c.keptCaptures ?? 0), 0);
const kb = channels.reduce((a, c) => a + (c.keptCaptureBytes ?? 0), 0);
+ const pf = channels.reduce((a, c) => a + (c.byKind?.captions?.pairsEqualSize ?? 0), 0);
+ const pb = channels.reduce((a, c) => a + (c.byKind?.captions?.pairsEqualSizeBytes ?? 0), 0);
say(
- `Dry run: ${n} raw chat(s), ${fmtBytes(tot)} → ~${fmtBytes(Math.round(tot * CHAT_RATIO_ESTIMATE))} (estimate)` +
+ `Dry run: ${parts.join("; ")} (estimate)` +
+ `${pf ? `; en / en-orig pairs of equal size: ${pf} (${fmtBytes(pb)} each side), compressed each as it is` : ""}` +
`${kf ? `; earlier captures kept: ${kf} (${fmtBytes(kb)}), never removed automatically` : ""}. Nothing was written.`,
);
} else if (!verify) {
const c = channels.reduce((a, l) => a + (l.compressed ?? 0), 0);
const b = channels.reduce((a, l) => a + (l.bytesBefore ?? 0), 0);
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` : ""}.`);
+ const refused = channels.reduce((a, l) => a + kinds.reduce((x, k) => x + (l.byKind?.[k]?.refused?.length ?? 0), 0), 0);
+ say(
+ `Compressed ${c} ${kindsText}: ${fmtBytes(b)} → ${fmtBytes(f)}` +
+ `${refused ? `; ${refused} refused with both forms kept (listed above)` : ""}` +
+ `${stopped ? ` — stopped (${stopped}); a re-run continues` : ""}.`,
+ );
}
- return { dryRun, verify, restore, channels, ...(stopped ? { stopped } : {}), lines };
+ return { dryRun, verify, restore, kinds: [...kinds], channels, ...(stopped ? { stopped } : {}), lines };
}
diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts
@@ -526,6 +526,20 @@ export function hasStoredTextLeftover(entries: readonly string[], name: string):
return entries.some((e) => re.temp.test(e) || re.retire.test(e));
}
+// The declared names a listing holds a stopped run's leftover FOR — a caption
+// killed after its original was set aside has neither form under its name,
+// only `.transcript.en.vtt.retire-<pid>-<token>`, and the job's survey must
+// still visit it (`compress-text` captions, which finds names by listing).
+export function storedTextLeftoverNames(entries: readonly string[]): string[] {
+ const out = new Set<string>();
+ for (const e of entries) {
+ const m = /^\.(.+?)(?:\.zst)?\.(?:compressing|stlink|restoring|retire)-\d+(?:-[0-9a-z]+)?$/.exec(e);
+ if (!m || !isStoredTextName(m[1])) continue;
+ if (hasStoredTextLeftover([e], m[1])) out.add(m[1]);
+ }
+ return [...out].sort();
+}
+
type RunCtx = {
pid: number;
token: string;
diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts
@@ -56,6 +56,11 @@ const ALLOWED: { file: string; code: RegExp; why: string }[] = [
why: "the migration's own survey: each form's PHYSICAL size, after storedFormsIn said which are there",
},
{
+ file: "common/controller/compressText.ts",
+ code: /if \(kind === "live-chat"\) return \[LIVE_CHAT_FILENAME\];/,
+ why: "the migration's kind → declared names table; every read of the name it returns is the survey's storedFormsIn or the compressor's",
+ },
+ {
file: "common/controller/normalizeLiveChat.ts",
code: /^\s*`Failed to parse \$\{LIVE_CHAT_FILENAME\} for /,
why: "a message (its path.basename is the video id, not a path to the chat)",
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -91,6 +91,13 @@
same bytes.
- The video page lists and labels a stored track under its own name; the files card shows the `.zst` as a file
and previews its decoded text.
+ - **`pnpm ops compress-text --json '{"kinds":["captions"]}'` compresses them** (zstd, about 20 % of the size), on
+ the corpus disk, with the chat's rules: one file at a time, verified before the original goes, the next run
+ finishes a stopped one, person-started only. Captions only when named: `kinds` still defaults to the live chat.
+ The dry run reports per channel and kind, and counts the en / en-orig pairs of equal size (compressed each as it
+ is, not deduped). A plain caption beside a stored one of other content is refused, both kept and listed.
+ `"restore": true` with the same `kinds` is the rollback; restore before running an older checkout, which reads a
+ stored caption as no transcript at all.
- **Clean audio without checking, and a rate-limited clean that says so.**
- The channel page's Cleanup stage has **Clean without checking…** beside Clean audio. It first counts what it would
remove (files, bytes, videos, and what it keeps; no request to the source) and asks: "Remove N audio files (X)
diff --git a/editor/app/api/ops/compress-text/route.test.ts b/editor/app/api/ops/compress-text/route.test.ts
@@ -38,7 +38,9 @@ test("refusals before any job", async () => {
[{ force: true }, /unknown key\(s\): force/],
[{ slugs: ["../x"] }, /not a valid channel slug/],
[{ slugs: ["nope"], dryRun: true }, /Channel\(s\) not found: nope/],
- [{ kinds: ["captions"] }, /"kinds" must be a list of: live-chat/],
+ [{ kinds: ["metadata"] }, /"kinds" must be a list of: live-chat, captions/],
+ [{ kinds: [] }, /"kinds" must be a list of: live-chat, captions/],
+ [{ kinds: "captions" }, /"kinds" must be a list of: live-chat, captions/],
[{ limit: 0 }, /limit/],
[{ limit: 5 }, /"limit" is per channel: name exactly one in "slugs"/],
[{ dryRun: true, verify: true }, /two different runs/],
@@ -74,3 +76,25 @@ test("a restore's dry run answers the stored files and writes nothing", async ()
assert.equal(synth?.pending, 0);
assert.deepEqual(await readdir(videoDir), ["transcript.live_chat.json"]);
});
+
+test("kinds captions: a dry run answers the caption files per channel, the pairs of equal size, and writes nothing", async () => {
+ const vtt = "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nwords\n";
+ await writeFile(path.join(videoDir, "transcript.en.vtt"), vtt);
+ await writeFile(path.join(videoDir, "transcript.en-orig.vtt"), vtt);
+ try {
+ const r = await post({ dryRun: true, kinds: ["captions"] });
+ assert.equal(r.status, 200, JSON.stringify(r.json));
+ const result = r.json.result as {
+ kinds: string[];
+ channels: { slug: string; plainFiles: number; byKind: { captions?: { plainFiles: number; pairsEqualSize?: number } } }[];
+ };
+ assert.deepEqual(result.kinds, ["captions"]);
+ const synth = result.channels.find((c) => c.slug === "synth");
+ assert.equal(synth?.plainFiles, 2, "the captions only: the chat is not asked");
+ assert.equal(synth?.byKind.captions?.pairsEqualSize, 1);
+ assert.deepEqual((await readdir(videoDir)).sort(), ["transcript.en-orig.vtt", "transcript.en.vtt", "transcript.live_chat.json"]);
+ } finally {
+ await rm(path.join(videoDir, "transcript.en.vtt"));
+ await rm(path.join(videoDir, "transcript.en-orig.vtt"));
+ }
+});
diff --git a/editor/app/api/ops/compress-text/route.ts b/editor/app/api/ops/compress-text/route.ts
@@ -1,18 +1,27 @@
import { NextResponse } from "next/server";
import { compressTextAction } from "../../../storage/compressTextActions";
+import {
+ COMPRESS_TEXT_KINDS,
+ isCompressTextKind,
+ type CompressTextKind,
+} from "yt-dlp-transcript-common/controller/compressText";
import { OpsInputError, ops, opsFail, optBool, optPositiveInt, reqSlugs, type OpsBody } from "../_lib";
export const dynamic = "force-dynamic";
// POST { slugs?, kinds?, dryRun?, limit?, verify?, restore? }
-// dryRun -> { ok: true, dryRun: true, result: { channels: [{ slug, plainFiles,
-// plainBytes, storedFiles, storedBytes, storedLogicalBytes,
-// estimateAfterBytes, free }], lines } }
+// dryRun -> { ok: true, dryRun: true, result: { kinds, channels: [{ slug,
+// plainFiles, plainBytes, storedFiles, storedBytes,
+// storedLogicalBytes, estimateAfterBytes, free, byKind: { <kind>:
+// { …the same, pairsEqualSize? } } }], lines } }
// else -> { ok: true, dryRun: false, verify, jobs: [{ slug, jobId }], jobIds,
// jobId (one job only), skipped: [{ slug, reason }] }
//
-// The raw live-chat replays put into their stored form, `transcript.live_chat.json`
-// → `transcript.live_chat.json.zst` (lib/storedText.ts; lane text-compress):
+// Big text files put into their stored form (lib/storedText.ts): the raw
+// live-chat replays, `transcript.live_chat.json` → `.zst` (lane text-compress),
+// and with `kinds: ["captions"]` every caption track, `transcript.<lang>.vtt` →
+// `.zst` (lane text-compress-captions; a dry run also counts the en / en-orig
+// pairs of equal size, each compressed as it is):
// one file at a time — written beside, fsynced, read back and hashed against
// the original, the original then removed through removeMediaFile. A crash at
// any step leaves a whole copy and the next run finishes. Paced (render mode
@@ -30,17 +39,21 @@ export const dynamic = "force-dynamic";
// 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;
- if (!Array.isArray(body.kinds) || body.kinds.length === 0 || body.kinds.some((k) => k !== "live-chat")) {
- throw new OpsInputError('"kinds" must be a list of: live-chat');
+// `kinds`: what to compress — "live-chat" (the raw live-chat replays, the
+// default) and "captions" (every caption track, `transcript.<lang>.vtt` →
+// `.zst`, on the corpus disk; lane text-compress-captions). Captions are
+// compressed only when named.
+function optKinds(body: OpsBody): CompressTextKind[] | undefined {
+ if (body.kinds === undefined) return undefined;
+ if (!Array.isArray(body.kinds) || body.kinds.length === 0 || body.kinds.some((k) => !isCompressTextKind(k))) {
+ throw new OpsInputError(`"kinds" must be a list of: ${COMPRESS_TEXT_KINDS.join(", ")}`);
}
+ return [...new Set(body.kinds as CompressTextKind[])];
}
export async function POST(request: Request) {
return ops(request, ["slugs", "kinds", "dryRun", "limit", "verify", "restore"], async (body) => {
- optKinds(body);
+ const kinds = optKinds(body);
const dryRun = optBool(body, "dryRun") ?? false;
const verify = optBool(body, "verify") ?? false;
const restore = optBool(body, "restore") ?? false;
@@ -49,6 +62,7 @@ export async function POST(request: Request) {
const limit = optPositiveInt(body, "limit");
const result = await compressTextAction({
...(body.slugs !== undefined ? { slugs: reqSlugs(body, "slugs") } : {}),
+ ...(kinds ? { kinds } : {}),
dryRun,
verify,
restore,
diff --git a/editor/app/jobs/jobReplayRegistry.ts b/editor/app/jobs/jobReplayRegistry.ts
@@ -22,6 +22,7 @@ import { isSourceVideoQuality } from "yt-dlp-transcript-common/ytdlp/downloadFor
import { isPersistReplacePolicy } from "yt-dlp-transcript-common/controller/persistVideos";
import { compactChannelVideosAction } from "../saved-videos/compactActions";
import { compressTextJobAction } from "../storage/compressTextActions";
+import { isCompressTextKind } from "yt-dlp-transcript-common/controller/compressText";
import {
downloadAction,
downloadMissingAction,
@@ -649,10 +650,14 @@ export const JOB_REPLAY_HANDLERS: Record<string, ReplayHandler> = {
"compress-text": (spec) => {
const { p } = params(spec);
const limit = num(p.limit);
+ // The kinds it ran over (a spec from before captions were a kind has
+ // none: the live chat alone, the default).
+ const kinds = (strings(p.kinds) ?? []).filter(isCompressTextKind);
return compressTextJobAction(spec.slug, {
...(limit !== undefined ? { limit } : {}),
...(p.verify === true ? { verify: true } : {}),
...(p.restore === true ? { restore: true } : {}),
+ ...(kinds.length ? { kinds } : {}),
});
},
"compact-saved-videos": (spec) => {
diff --git a/editor/app/storage/compressTextActions.ts b/editor/app/storage/compressTextActions.ts
@@ -6,6 +6,7 @@ import {
COMPRESS_RATE_BYTES,
COMPRESS_RATE_RECORDING_BYTES,
compressText,
+ type CompressTextKind,
type CompressTextResult,
} from "yt-dlp-transcript-common/controller/compressText";
import { getRegistry } from "yt-dlp-transcript-common/jobs/registry";
@@ -78,7 +79,7 @@ const sleep = (ms: number, signal?: AbortSignal) =>
export async function compressTextJobAction(
slug: string,
- opts: { limit?: number; verify?: boolean; restore?: boolean } = {},
+ opts: { limit?: number; verify?: boolean; restore?: boolean; kinds?: CompressTextKind[] } = {},
): Promise<StreamActionResult> {
const paths = getPaths();
return runManagedFunction({
@@ -93,6 +94,7 @@ export async function compressTextJobAction(
...(opts.limit !== undefined ? { limit: opts.limit } : {}),
...(opts.verify ? { verify: true } : {}),
...(opts.restore ? { restore: true } : {}),
+ ...(opts.kinds?.length ? { kinds: opts.kinds } : {}),
},
},
fn: async (onLog, signal, _progress, ctx) => {
@@ -102,6 +104,7 @@ export async function compressTextJobAction(
...(opts.limit !== undefined ? { limit: opts.limit } : {}),
...(opts.verify ? { verify: true } : {}),
...(opts.restore ? { restore: true } : {}),
+ ...(opts.kinds?.length ? { kinds: opts.kinds } : {}),
onLog,
signal,
drainSignal: ctx.drainSignal,
@@ -124,6 +127,8 @@ export async function compressTextJobAction(
// check, or to restore).
export async function compressTextAction(input: {
slugs?: string[];
+ // Default: the live chat alone (controller/compressText.ts).
+ kinds?: CompressTextKind[];
dryRun?: boolean;
verify?: boolean;
restore?: boolean;
@@ -137,7 +142,14 @@ 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, ...(input.restore ? { restore: true } : {}), onLog: () => {} });
+ const plan = await compressText({
+ paths,
+ slugs,
+ dryRun: true,
+ ...(input.restore ? { restore: true } : {}),
+ ...(input.kinds?.length ? { kinds: input.kinds } : {}),
+ onLog: () => {},
+ });
if (input.dryRun) return { ok: true, dryRun: true, result: plan };
const jobs: { slug: string; jobId: string }[] = [];
const skipped: { slug: string; reason: string }[] = [];
@@ -152,6 +164,7 @@ export async function compressTextAction(input: {
...(input.limit !== undefined ? { limit: input.limit } : {}),
...(input.verify ? { verify: true } : {}),
...(input.restore ? { restore: true } : {}),
+ ...(input.kinds?.length ? { kinds: input.kinds } : {}),
});
if (r.ok) jobs.push({ slug: line.slug, jobId: r.jobId });
else skipped.push({ slug: line.slug, reason: r.error });
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -2512,36 +2512,44 @@ export function usage() {
' while its compaction runs). compact-saved-videos "reverify": true re-checks',
" one without encoding.",
"",
- 'compress-text stores the raw live-chat replays compressed (zstd, level 9):',
- ' transcript.live_chat.json becomes transcript.live_chat.json.zst, read',
- " back by every reader as the same file, with the same times (the index",
- ' sees no change): {"slugs"?: [...], "kinds"?: ["live-chat"], "dryRun"?,',
- ' "limit"?, "verify"?, "restore"?}. One file at a time: written beside the',
- " original, fsynced, read back and hashed against it, and only then the",
- " original removed; a crash at any step leaves a whole copy, and the next",
- " run finishes it (it visits every dir a stopped run left). Left alone and",
- " counted: a file written (mtime or ctime) in the last 10 minutes, one with",
- " a .part beside it, a video recording or with a job running, a drive that",
- " does not answer, a channel whose media is moving. Both forms present with",
- " different content are refused and both kept. A file a writer replaces",
- " during the run is kept and read; the earlier content's stored copy is",
- " kept beside it. The dry run lists earlier chat captures a re-fetch kept",
- " (chat-capture-kept.*.json.zst), which nothing removes automatically.",
- ' "dryRun": true answers per channel the raw chats, their bytes, the',
- " stored ones, the estimate after (about 5 %, an estimate) and the free",
- ' space, and writes nothing; "verify": true decodes every stored file in',
+ 'compress-text stores big text files compressed (zstd, level 9): the raw',
+ " live-chat replays (transcript.live_chat.json -> .zst, kind live-chat,",
+ ' the default) and the caption tracks (every',
+ ' transcript.<lang>.vtt -> .zst, on the corpus disk: "kinds": ["captions"],',
+ " only when named). Read back by every reader as the same file, with the",
+ " same times (the index sees no change): {\"slugs\"?: [...], \"kinds\"?:",
+ ' ["live-chat", "captions"], "dryRun"?, "limit"?, "verify"?, "restore"?}.',
+ " A caption's dry run also counts the en / en-orig pairs of equal size",
+ " (compressed each as it is, never deduped). One file at a time: written",
+ " beside the original, fsynced, read back and hashed against it, and only",
+ " then the original removed; a crash at any step leaves a whole copy, and",
+ " the next run finishes it (it visits every dir a stopped run left). Left",
+ " alone and counted: a file written (mtime or ctime) in the last 10",
+ " minutes, one with a .part beside it, a video recording or with a job",
+ " running, a drive that does not answer, a channel whose media is moving.",
+ " Both forms present with different content are refused, both kept and",
+ " listed: nothing removes a stored copy because a different one arrived.",
+ " A file a writer replaces during the run is kept and read; the earlier",
+ " content's stored copy is kept beside it. The dry run lists earlier chat",
+ " captures a re-fetch kept (chat-capture-kept.*.json.zst), which nothing",
+ " removes automatically.",
+ ' "dryRun": true answers per channel and kind the files, their bytes, the',
+ " stored ones, the estimate after (about 5 % for a chat, 20 % for a",
+ " caption: estimates) and the free space, and writes nothing;",
+ ' "verify": true decodes every stored file in',
' full and writes nothing; "limit" counts files compressed 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), waiting while",
" render mode holds the machine and slower while a live recording runs.",
" Started by a person only: a restart closes a queued one and resumes no",
" interrupted one (it removes originals) -- a re-run continues.",
- ' "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 .zst removed);",
+ ' "restore": true is the rollback: every stored file of the kinds 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 .zst removed);",
' with "dryRun" it answers the stored files, their plain bytes and the free',
" space. Run it BEFORE reverting or running an older checkout, which cannot",
- " read a stored chat (OPERATING.md).",
+ " read a stored chat or caption (OPERATING.md).",
"",
'compaction-markers lists the "being compacted" markers (.compacting.json),',
' each live or stale and why: {}. {"clear": {"slug", "id"}} removes a stale',