commit ac431a1cbbc4332d99a688ec8605e9df86cf5b6c
parent 0c22ef9e240cd8693852c5a9a9e8fab143dca143
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 16:07:53 -0500
Merge main into lane/live-guard-2 (window-end, caption compression, copies-dates)
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
78 files changed, 4259 insertions(+), 466 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 once (recorded per channel; not visited again until a form changes): 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}'` |
@@ -236,7 +236,7 @@ Drives a running editor over HTTP (`/api/ops/*`, the same actions its pages run)
| `bench-verdicts` | bench-verdicts runs the verdict bench as a bench-verdicts job: {"models": \["…"\], "run"?, "reports"?: \["<article>"\], "window"? (seconds, default 60), "windowMode"? ("seconds" \| "turn": the cited speaker's turn, bounded by the window), "maxUsd"? (default 5), "limit"? (a stratified sample, by the operator's verdict), "itemsFrom"? (an earlier run's exact items; no reports, window, windowMode, limit or dedupe with it), "dedupe"? (true: a claim repeating an earlier one, the same text over the same cited spans, is asked once; default: every claim is asked)} -> {jobId, run}. Every claim of the registry's fact-checks (or of "reports") with the operator's verdict and a citation with cues is asked of each model, one claim per call (the report's title, the claim's section, the claim, its quotes, the transcript in the window; never the findings or the verdict), and scored against the rulings. On draft:local when any model is local (through the GPU arbiter; unloaded at the end), else draft:api; the run stops at maxUsd, and an API run is refused past caps.daily. A "run" that exists continues with this call's models only (answered pairs are skipped; refused under another prompt version). Results stay local, in .generation/bench/verdicts/<run>/ (umtool's /tools/bench). The log ends with @@bench-verdicts {run, status, items, skipped, spentUsd, stopped?}. | `pnpm ops bench-verdicts --json '{"models":["claude-sonnet-5-5","qwen3:8b"],"maxUsd":5}' --wait` |
| `frame-scan` | frame-scan reads a saved stream's frames for a profile's progress: {"slug", "id", "profile"? ("poker", the default), "everySeconds"? (default settings.generation.frames.everySeconds, 10), "from"?, "to"? (source seconds), "maxFrames"? (5000), "model"? (default the `frames` route's model), "maxUsd"? (default frames.maxUsd, at most caps.max), "hero"? (the hero's screen name, a hint), "framesPerAsk"? (1-8), "crop"? (\[x, y, w, h\] as fractions of the picture: the part read and hashed, e.g. the poker client beside a webcam), "fresh"? (read every frame again: another model or prompt), "evict"?, "rederive"?} -> {jobId, model, queueKey}. The video's saved container is sampled (keyframes, one ffmpeg a half hour) into a frame cache on the channel's media side; near-duplicate frames are skipped; the rest are read by the vision model and the numbers the streamer said are read from the transcript; frame-scan.<profile>.json beside the video gets the readings and the derived series, events, segments and flags (a frame and a spoken number that disagree). On `frames` (API) or draft:local (a local vision model, through the GPU arbiter). The same body again resumes: read frames are never asked again. Refused when the video is not saved (persist-videos first) or past caps.daily; the run stops before an ask that would pass maxUsd. {"evict": true} removes the frame cache and answers at once; {"rederive": true} works the derived timeline out again from the readings the sidecar holds (no model, no frame; refused while a scan of the video runs) and answers {rederived: {before, after, tournaments, eventsByKind}}. The log ends with @@frame-scan {slug, id, profile, file, frames, kept, read, failed, readings, spentUsd, totalUsd, events, tournaments, flags, stopped?}. | `pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","profile":"poker","maxUsd":2}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","hero":"DemoHero","crop":[0.02,0.1,0.7,0.68],"from":3000,"to":3600}' --wait`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","evict":true}'`<br>`pnpm ops frame-scan --json '{"slug":"demo-channel","id":"dQw4w9WgXcQ","rederive":true}'` |
| `mirror-scan` | mirror-scan pairs a mirror channel with the creator it copies: {"slug", "dryRun"?} -> {jobId}. The channel's config names the creator's channels (mirror.of; channel-config's "mirrorOf"); refused without them. Each of the mirror's videos, dated by its recorded date (else its upload date), is matched with the creator's videos uploaded one day before to two after, by title words and duration (the index's records; no media, no network); per video the matches and a status: only-copy (no creator platform has it public), creator-deleted (removed on one platform, public on another), never-uploaded (missing on one platform, public on the rest) or creator-public. The other way: the creator's removed (deleted or private) uploads dated inside the mirror's window, and which the mirror holds. Written to transcripts/mirrors/<slug>.json (private: never published); the channel page's Mirror stage shows it. dryRun writes nothing. The log ends with @@mirror-scan {slug, dryRun, file?, of, missing?, window, videos, matched, byStatus, byPlatform, creatorRemoved: {inWindow, held, byChannel}}. | `pnpm ops mirror-scan --json '{"slug":"demo-vod-archive","dryRun":true}' --wait`<br>`pnpm ops mirror-scan --json '{"slug":"demo-vod-archive"}' --wait` |
-| `copies-scan` | copies-scan pairs a source group's channels video by video: {"group", "dryRun"?} -> {jobId}. The group is settings.sourceGroups' (an ordered list of channels holding the same recordings, the preferred source first; pnpm ops settings sets it). Two videos are candidates when their recorded dates are at most dateWindowDays apart. Where both have a cue file their words decide, probed both ways (40 phrases each way, each counted once): each copy holding at least 75 % of the other AND runtimes within the group's tolerance is confirmed; one inside the other, or the words the same and the runtimes apart, is part-of; a shared stretch is overlaps; less is not a pair. Where one has no words, agreeing runtimes make a metadata-only pair. No media, no network. Written to transcripts/copies/<group>.json (private: never published), each pair with its link, its evidence and when it was first seen; a scan that finds what the file says leaves it as it was. With the group's lanes on, the transcription and Speakers lanes skip a confirmed copy whose other copy has the work done, and hold a metadata-only one (or one waiting on its preferred copy) for at most waitDays; part-of and overlapping pairs are reported only (get copies says each one's reason). Cancelling the job stops it with nothing written; dryRun writes nothing. The log ends with @@copies-scan {group, dryRun, unchanged, file?, channels, missing?, totals}. | |
+| `copies-scan` | copies-scan pairs a source group's channels video by video: {"group", "dryRun"?} -> {jobId}. The group is settings.sourceGroups' (an ordered list of channels holding the same recordings, the preferred source first; pnpm ops settings sets it). Two videos are candidates when their dates are at most dateWindowDays apart. A video is dated by the best evidence it has: its channel's recordedDate rule, else a live stream's own day, else (no rule set) a date the channel's titles carry in a shape the scan recognises, else its upload day. On a channel with no rule, a video with only an upload day (on a re-upload channel, the copy's day) or none, and no candidate by date, is looked for by runtime instead: its 8 nearest agreeing runtimes on the other channels, at most 2,000 such pairs a scan, decided by their words only (no words, no pair). The result's advice says what the scan could not date well, with the exact channel-config patch that sets a channel's rule. Where both have a cue file their words decide, probed both ways (40 phrases each way, each counted once): each copy holding at least 75 % of the other AND runtimes within the group's tolerance is confirmed; one inside the other, or the words the same and the runtimes apart, is part-of; a shared stretch is overlaps; less is not a pair. Where one has no words, agreeing runtimes make a metadata-only pair. No media, no network. Written to transcripts/copies/<group>.json (private: never published), each pair with its link, its evidence and when it was first seen; a scan that finds what the file says leaves it as it was. With the group's lanes on, the transcription and Speakers lanes skip a confirmed copy whose other copy has the work done, and hold a metadata-only one (or one waiting on its preferred copy) for at most waitDays; part-of and overlapping pairs are reported only (get copies says each one's reason). Cancelling the job stops it with nothing written; dryRun writes nothing. The log ends with @@copies-scan {group, dryRun, unchanged, file?, channels, missing?, totals, dating, advice?}. | |
| `copies-release` | copies-release releases copies to their lanes: {"group", "video": "<channel>/<dir>" \| "videos": \[...\], "undo"?, "note"?, "by"?} -> {group, action, undo, applied, unknown, skipped, now}. A released video is queued by its lanes as if it had no source group, whether it was held or skipped; undo takes the release back. A video may be named by its dir or its id (a Rumble video's differ); one the scan does not list is reported in unknown and not stored. by is "operator" or "agent" (the default), the caller's word, recorded with the time and the note in transcripts/copies/<group>.decisions.json, which the scan never touches. | |
| `copies-confirm` | copies-confirm confirms metadata-only pairs as the same recording: {"group", "pair": "<channel>/<dir>\|<channel>/<dir>" \| "pairs": \[...\], "undo"?, "note"?, "by"?} -> {group, action, undo, applied, unknown, skipped, now}. A confirmed pair acts as one confirmed by text: the copy is skipped once the other copy's work is done. Only a metadata-only pair takes it; a part-of or overlapping one is skipped with the reason. get copies lists the metadata pairs in their wait, with titles, dates and runtimes, for confirming in bulk. Recorded with who and when, as copies-release. | |
| `copies-reject` | copies-reject rejects pairs: the same body as copies-confirm. A rejected pair never holds or skips again, whatever its link; undo takes it back, and a later confirm replaces it. | |
diff --git a/OPERATING.md b/OPERATING.md
@@ -1836,6 +1836,52 @@ 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 audio is downloaded or transcribed because of it, and
+ Download missing subs (which fetches only what is missing) leaves it out of `--sub-langs`.
+- **A re-download fetches a stored track again, as it always did** (the video page's Download, the retry bucket,
+ `full: true`, Persist source video): YouTube's captions are asked again and the new file replaces the old one.
+ Per track, the job log says which: the same content keeps the stored form (the new copy is dropped; nothing
+ moves, the index sees nothing); new content with cues becomes the track, and the stored one is removed only once
+ the new file is whole; nothing fetched (a video that is gone), a `.part`, or an empty or cue-less file leaves the
+ stored track untouched.
+- **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. A refused pair is recorded in
+ the channel's `.stored-text-differs.json` (both forms' inode, size and mtime): later runs do not visit it again,
+ and the dry run lists it once as "waiting for a person" until either form changes.
+- **A stopped run never brings a deleted caption back.** Every deleter (the files card, the purge, the
+ clear-transcript fix, deleting the video) removes a stopped run's set-aside original with the forms; a set-aside
+ found with no stored form beside it is not adopted but listed ("retired-kept").
+- **A Node without zstd refuses to start** (the editor, every `archilyzer` CLI, umtool and its bare-node
+ readers), naming the Node needed (>= 22.15): it never runs with stored files unreadable. A stored file that does
+ not decode is an error, never "no text": the index keeps the record as the last build held it and says so
+ ("UNREADABLE STORED TEXT"), and `verify` lists it.
+- **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
@@ -1847,8 +1893,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/bin/_cli.ts b/common/bin/_cli.ts
@@ -7,6 +7,8 @@
import { realpathSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { parseArgv, type FlagValue } from "./_parseFlags";
+import path from "node:path";
+import { zstdSupportProblem } from "../lib/zstdSupport.mjs";
// A flag a command accepts. "boolean" never takes a value (`--nodata`),
// "string" always needs one (`--preview <branch>`).
@@ -201,6 +203,13 @@ export function runIfEntryPoint(
main: () => Promise<number | void>,
): void {
if (!isEntryPoint(metaUrl)) return;
+ // Every CLI may read the corpus, where captions and chats may be stored as
+ // `.zst`: on a Node without zstd it refuses to start (REVIEW-1 F3).
+ const zstd = zstdSupportProblem();
+ if (zstd) {
+ console.error(`${path.basename(fileURLToPath(metaUrl))} refuses to start: ${zstd}`);
+ process.exit(1);
+ }
main().then(
(code) => {
if (typeof code === "number") process.exitCode = code;
diff --git a/common/bin/migrate-media-tier.test.ts b/common/bin/migrate-media-tier.test.ts
@@ -410,6 +410,29 @@ test("--reclaim keeps a platter copy whose twin on the corpus disk is gone or di
assert.ok(lines.some((l) => /kept 2 entries on the drive with no same-size copy/.test(l)));
});
+test("--reclaim takes a platter caption whose twin was since COMPRESSED — only when the stored form holds its very bytes", async () => {
+ // Lane text-compress-captions: a caption brought home and then compressed
+ // is `transcript.en.vtt.zst` on the corpus disk. Its platter copy is taken
+ // when the stored form decodes to exactly its bytes; a stored form of OTHER
+ // content (or one that does not decode) keeps the copy, reported.
+ resetCorpus();
+ seedLegacy();
+ writeFileSync(path.join(oldTree(SLUG), "v3", "transcript.en.vtt"), VTT);
+ await run();
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ const data = (id: string) => path.join(channelDir(), "data", id);
+ await storeFixture(data("v1"), "transcript.en.vtt");
+ // v3: since the migration, the track was re-written with other words of
+ // the same size, then compressed — the stored form is not the platter copy.
+ writeFileSync(path.join(data("v3"), "transcript.en.vtt"), VTT.replace(/[a-z]/, "Z"));
+ await storeFixture(data("v3"), "transcript.en.vtt");
+ const res = await run({ reclaim: true });
+ assert.equal(res.exitCode, 0, res.channels[0].detail);
+ assert.deepEqual(res.channels[0].reclaimKept?.sort(), ["v3/transcript.en.vtt"]);
+ assert.throws(() => lstatSync(path.join(mediaTarget(), "v1", "transcript.en.vtt")), "its stored twin holds it: taken");
+ assert.ok(lstatSync(path.join(mediaTarget(), "v3", "transcript.en.vtt")).isFile(), "a stored twin of other content: kept");
+});
+
test("a reclaim killed after its deletes resumes from its marker and ends clean", async () => {
resetCorpus();
seedLegacy();
diff --git a/common/bin/migrate-media-tier.ts b/common/bin/migrate-media-tier.ts
@@ -68,6 +68,7 @@ import {
lutimes,
mkdir,
readdir,
+ readFile,
readlink,
rename,
rm,
@@ -83,6 +84,8 @@ import type { SiteSettings } from "../lib/settings";
import { formatBytes } from "../lib/format";
import { getFreeBytes } from "../lib/diskSpace";
import { classifyEntry, CLIPS_DIR, isTierable } from "../lib/mediaTier";
+import { STORED_TEXT_SUFFIX, isStoredTextName } from "../lib/storedText";
+import { decodeStoredBytes } from "../lib/storedText-server";
import {
channelMediaLink,
relocatedMediaDir,
@@ -935,7 +938,12 @@ async function reclaimTree(
try {
twin = await lstat(path.join(ssd, rel));
} catch {
- return false;
+ // A TWIN IN ITS STORED FORM (lib/storedText.ts): a caption brought home
+ // and since compressed is `<name>.zst` on the corpus disk. It is the
+ // twin only when it decodes whole (checksum, length) to exactly the
+ // platter copy's bytes — never by size alone, so a reclaim run after a
+ // compress-text run removes no copy the stored form does not hold.
+ return st.isFile() && isStoredTextName(path.basename(rel)) && (await storedTwinHolds(path.join(ssd, rel), path.join(mediaDir, rel)));
}
if (st.isDirectory()) return twin.isDirectory();
return !twin.isDirectory() && twin.size === st.size;
@@ -979,6 +987,22 @@ async function reclaimTree(
return { reclaimedFiles: files, reclaimedBytes: bytes, reclaimKept: kept };
}
+// Does `<plain>.zst` beside `plain` (a real file) hold exactly `copy`'s bytes?
+async function storedTwinHolds(plain: string, copy: string): Promise<boolean> {
+ const stored = `${plain}${STORED_TEXT_SUFFIX}`;
+ try {
+ const z = await lstat(stored);
+ if (!z.isFile()) return false;
+ const [decoded, bytes] = await Promise.all([
+ readFile(stored).then((b) => decodeStoredBytes(b, stored)),
+ readFile(copy),
+ ]);
+ return decoded.equals(bytes);
+ } catch {
+ return false;
+ }
+}
+
// --reclaim on a channel already on the media tier: only one this tool
// migrated (its reclaim note stands), whose media drive answers and whose
// `data/` is a real directory.
diff --git a/common/controller/adoptLocalMediaReference.ts b/common/controller/adoptLocalMediaReference.ts
@@ -11,6 +11,8 @@ import { openExternalMedia } from "../lib/externalMediaResolver-server";
import { localMediaFingerprint } from "../lib/localMediaScan";
import { EXTERNAL_MEDIA_FILENAME, coerceExternalMediaReference } from "../lib/localMedia";
import { writeExternalMediaReference } from "../lib/externalMedia-server";
+import { storedNameOf } from "../lib/storedText";
+import { decodeStoredBytes } from "../lib/storedText-server";
type Selection = { sourceToken: string; media: string; fingerprint: string };
export type LocalMediaAdoptionResult = { status: "ready" | "attached" | "already-linked" | "conflict"; stagingCleanupFailed?: boolean };
@@ -34,6 +36,17 @@ async function bytes(root: string, name: string, afterRead?: () => Promise<void>
} finally { await h.close(); }
}
+// A caption's exact bytes in either form (lib/storedText.ts): the plain file
+// by `bytes`, else its stored `.zst` by `bytes` (the same no-follow, bounded,
+// unchanged read), decoded — the frame's checksum and length checked. The
+// decoded bytes are the plain file's exactly.
+async function captionBytes(root: string, name: string): Promise<Buffer> {
+ if (await lstat(path.join(root, name)).then(() => true, () => false)) return bytes(root, name);
+ const stored = storedNameOf(name);
+ if (!(await lstat(path.join(root, stored)).then(() => true, () => false))) return bytes(root, name);
+ return decodeStoredBytes(await bytes(root, stored), path.join(root, stored));
+}
+
// Separate from import: occupied records are NEVER silently merged by scanning.
// This explicit operation requires exact existing metadata/transcript matches.
// It publishes only a new sidecar and never changes/removes prototype links.
@@ -68,7 +81,7 @@ export async function adoptLocalMediaReference(paths: Paths, slug: string,
});
const channel=path.join(paths.channelsDir,slug), data=path.join(channel,"data"), record=path.join(data,row.directoryId);
for(const dir of [channel,data,record]) { const s=await lstat(dir); if(!s.isDirectory() || s.isSymbolicLink()) throw new Error("Expected real archive directories"); }
- const metadata=await bytes(record,"metadata.info.json"), transcript=await bytes(record,"transcript.en.vtt");
+ const metadata=await bytes(record,"metadata.info.json"), transcript=await captionBytes(record,"transcript.en.vtt");
if(!metadata.equals(source.metadata) || !transcript.equals(source.transcript)) throw new Error("Existing metadata or transcript differs; manual review required");
// Repeat the configuration/relocation guards after the source reads too.
const after=await previewLocalMedia(paths,slug);
diff --git a/common/controller/archiveOrgDownload.ts b/common/controller/archiveOrgDownload.ts
@@ -48,6 +48,7 @@ import path from "node:path";
import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";
import { appendFile, mkdir, readdir, rename, rm, stat } from "node:fs/promises";
+import { readdirLogical } from "../lib/storedText-server";
import type { ManagedDownloadOpts } from "../ytdlp/downloadOneManaged";
import type { AudioFormat } from "../lib/channelConfig";
import type {
@@ -165,8 +166,9 @@ function extOf(name: string): string {
return m ? m[1].toLowerCase() : "";
}
+// LOGICAL (lib/storedText.ts): a caption stored as `.zst` is a transcript.
async function hasTranscriptOnDisk(videoDir: string): Promise<boolean> {
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const entries = await readdirLogical(videoDir);
return entries.some((e) => {
if (e === "transcript.json") return true;
const m = /^transcript\.([^.]+)\.(?:vtt|json|json3|srv1|srv2|srv3)$/.exec(e);
diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts
@@ -969,6 +969,152 @@ test("(t) lane text-compress: THE COMPRESSOR itself, over a real and a tiered ch
assert.deepEqual(mtimesOf(), before);
});
+test("(u) lane text-compress-captions: every caption track compressed — the index sees NO change, and reads the same cues, alternates and subs", async () => {
+ resetCorpus();
+ seedVideo("c1", CHANNEL, { subs: true });
+ seedVideo("c2");
+ // c1 carries an en-orig whose words differ from en (an alternate track), a
+ // German sub track, and sub-millisecond times a `Date` would lose.
+ const ORIG = VTT.replace("First", "Original").replace("Second", "Spoken");
+ writeFileSync(path.join(videoDir("c1"), "transcript.en-orig.vtt"), ORIG);
+ const { utimesSync } = await import("node:fs");
+ for (const [n, t] of [["transcript.en.vtt", 1763700000.123457], ["transcript.en-orig.vtt", 1763700002.000003], ["transcript.de.vtt", 1763700003.5]] as const) {
+ utimesSync(path.join(videoDir("c1"), n), t, t + 0.000001);
+ }
+ 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();
+ assert.ok(before.alts.length > 0, "the fixture has an alternate track");
+ assert.ok(before.subs.length > 0, "the fixture has a sub track");
+ assert.ok(before.cues.length >= 2);
+
+ // THE COMPRESSOR over every caption of both videos (c2 through the fixture
+ // helper, the way a run killed after its rename leaves it).
+ const { compressStoredText } = await import("../lib/storedText-write-server");
+ for (const n of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.de.vtt"]) {
+ const out = await compressStoredText(videoDir("c1"), n, { reserveBytes: 0 });
+ assert.equal(out.status, "compressed", `${n}: ${JSON.stringify(out)}`);
+ }
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(videoDir("c2"), "transcript.en.vtt");
+ assert.deepEqual(readdirSync(videoDir("c1")).filter((n) => n.endsWith(".vtt")), [], "no plain caption is left");
+
+ const after = await runIndex();
+ assert.equal(after.res.changed, 0, after.log.join("\n"));
+ assert.equal(after.res.added, 0);
+ assert.equal(after.res.removed, 0);
+ assert.deepEqual(all(), before, "the same mtimes, cues, subs and alternates");
+
+ // A change elsewhere re-reads both records: everything comes from the stored forms.
+ seedVideo("c1", CHANNEL, { title: "Retitled" });
+ seedVideo("c2", CHANNEL, { title: "Retitled" });
+ // seedVideo wrote a plain en.vtt again (the same bytes): what a re-fetch
+ // would leave beside the stored one — plain is read, and is the same.
+ rmSync(path.join(videoDir("c1"), "transcript.en.vtt"));
+ rmSync(path.join(videoDir("c1"), "transcript.de.vtt"), { force: true });
+ rmSync(path.join(videoDir("c2"), "transcript.en.vtt"));
+ const reread = await runIndex();
+ assert.equal(reread.res.changed, 2, reread.log.join("\n"));
+ const now = all();
+ assert.deepEqual(now.cues, before.cues, "the cues are read from the stored captions");
+ assert.deepEqual(now.subs, before.subs, "the German track is read from its stored form");
+ 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("(w) REVIEW-1 F3: a stored caption that does not decode — the record keeps what the last build held, is said, and is read again", async () => {
+ resetCorpus();
+ seedVideo("c1", CHANNEL, { subs: true });
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(videoDir("c1"), "transcript.en.vtt");
+ await storeFixture(videoDir("c1"), "transcript.de.vtt");
+ 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]),
+ sums: [...db("sums").getRange()].map(({ key, value }) => [key, value]),
+ }));
+ await runIndex();
+ const before = all();
+ assert.ok(before.cues.length === 1 && (before.cues[0][1] as unknown[]).length > 0, "the stored caption was read");
+ // The frame goes bad (a disk error) and the record changes (retitled).
+ const good = readFileSync(path.join(videoDir("c1"), "transcript.en.vtt.zst"));
+ writeFileSync(path.join(videoDir("c1"), "transcript.en.vtt.zst"), Buffer.concat([good.subarray(0, 12), Buffer.alloc(good.length - 12, 7)]));
+ seedVideo("c1", CHANNEL, { title: "Retitled" });
+ rmSync(path.join(videoDir("c1"), "transcript.en.vtt"));
+ const bad = await runIndex();
+ assert.ok(bad.log.some((l) => /^Unreadable stored text in test-channel\/c1: .*transcript\.en\.vtt\.zst/.test(l)), bad.log.join("\n"));
+ assert.ok(bad.log.some((l) => /^UNREADABLE STORED TEXT: 1 file\(s\)/.test(l)), bad.log.join("\n"));
+ const kept = all();
+ assert.deepEqual(kept.cues, before.cues, "never written with no cues");
+ assert.deepEqual(kept.sums, before.sums, "the record is the last build's");
+ assert.deepEqual(kept.mtimes, before.mtimes, "not marked read: the next build tries again");
+ // Fixed (restored from a good copy): read, the retitle lands.
+ writeFileSync(path.join(videoDir("c1"), "transcript.en.vtt.zst"), good);
+ const fixed = await runIndex();
+ assert.equal(fixed.res.changed, 1, fixed.log.join("\n"));
+ assert.deepEqual(all().cues, before.cues);
+});
+
+test("(x) REVIEW-2 N5: an unreadable stored SUB track keeps its earlier cues AND is read again, and said, on every build", async () => {
+ resetCorpus();
+ seedVideo("c1", CHANNEL, { subs: true });
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(videoDir("c1"), "transcript.de.vtt");
+ const subsOf = () => withIndex((db) => [...db("subs").getRange()].map(({ key, value }) => [key, value]));
+ const subsMs = () => withIndex((db) => [...db("mtimes").getRange()].map(({ value }) => (value as { subsMs: number | null }).subsMs));
+ await runIndex();
+ const before = subsOf();
+ assert.equal(before.length, 1, "the German track was read");
+ const good = readFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst"));
+ writeFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst"), Buffer.concat([good.subarray(0, 12), Buffer.alloc(good.length - 12, 7)]));
+ seedVideo("c1", CHANNEL, { title: "Retitled" });
+ for (let build = 1; build <= 2; build++) {
+ const r = await runIndex();
+ assert.ok(r.log.some((l) => /^UNREADABLE STORED TEXT: 1 file\(s\).*transcript\.de\.vtt/.test(l)), `build ${build}: ${r.log.join("\n")}`);
+ assert.deepEqual(subsOf(), before, `build ${build}: the earlier cues are kept`);
+ assert.deepEqual(subsMs(), [null], `build ${build}: not pinned as read`);
+ }
+ writeFileSync(path.join(videoDir("c1"), "transcript.de.vtt.zst"), good);
+ const fixed = await runIndex();
+ assert.ok(!fixed.log.some((l) => /UNREADABLE/.test(l)));
+ assert.notDeepEqual(subsMs(), [null]);
+});
+
test("(z) no write this file caused landed outside its temp root", () => {
// LMDB writes natively, past the spy: its file must be under the root too.
assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath);
diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts
@@ -100,7 +100,7 @@ import {
import { readChannelConfigFile } from "./channels";
import { inspectChannelMedia } from "../lib/channelMedia";
import { isTierable } from "../lib/mediaTier";
-import { readStoredText, statStoredText } from "../lib/storedText-server";
+import { isStoredTextReadError, readStoredText, statStoredText } from "../lib/storedText-server";
import { onDrive } from "../lib/storageHealth";
import {
HELD_WAYS_OUT,
@@ -575,7 +575,10 @@ async function scanSource(
: [picked.filename, ...captionInputs(files.entries)];
for (const name of inputs) {
try {
- const ms = (await stat(path.join(fullVideoDir, name))).mtimeMs;
+ // Either form (lib/storedText.ts): a caption stored compressed
+ // carries the plain file's mtime exactly, so the same
+ // `transcriptMs` — a compression re-ingests nothing.
+ const ms = (await statStoredText(fullVideoDir, name)).stats.mtimeMs;
if (transcriptMs === null || ms > transcriptMs) transcriptMs = ms;
} catch {
// ignore
@@ -1120,6 +1123,9 @@ export async function buildIndex({
const toProcess = [...added, ...changed];
let processed = 0;
+ // Stored files (captions, chats) that are there and do not decode, this
+ // build: each logged with its path, counted below (REVIEW-1 F3).
+ const unreadableStored: string[] = [];
const BATCH = 200;
for (let i = 0; i < toProcess.length; i += BATCH) {
const slice = toProcess.slice(i, i + BATCH);
@@ -1168,7 +1174,11 @@ export async function buildIndex({
? // The caption-track rule (lib/videoStatus.ts).
(await readEnglishVttCues(videoFullDir))?.cues
: parseTranscriptJson(await readFile(s.transcriptPath, "utf8"));
- } catch {
+ } catch (err) {
+ // A stored caption that does not decode is an ERROR: the
+ // record is not written (the last build's stays, and the next
+ // build retries) — never written with no cues (REVIEW-1 F3).
+ if (isStoredTextReadError(err)) throw err;
cueList = undefined;
}
}
@@ -1221,6 +1231,16 @@ export async function buildIndex({
summary.id,
];
+ // The other English tracks, where their words differ from the
+ // primary's (lib/captionTracks.ts). Only a record that can hold one
+ // reads anything. Read BEFORE anything of the record is written: a
+ // stored track that does not decode throws, and the record is then
+ // left exactly as the last build held it (REVIEW-1 F3).
+ const trackFields: TrackFields =
+ canHoldAltTracks(s) && s.transcriptKind
+ ? await readTrackFields(videoFullDir, s.transcriptKind, cueList)
+ : {};
+
const pk: PathKey = [s.channelSlug, s.videoDir];
const prev = mtimes.get(pk);
// What the last build held for this video's captions, for the
@@ -1245,13 +1265,6 @@ export async function buildIndex({
if (cueList) cues.put(indexKey, cueList);
else cues.remove(indexKey);
- // The other English tracks, where their words differ from the
- // primary's (lib/captionTracks.ts). Only a record that can hold one
- // reads anything.
- const trackFields: TrackFields =
- canHoldAltTracks(s) && s.transcriptKind
- ? await readTrackFields(videoFullDir, s.transcriptKind, cueList)
- : {};
if (trackFields.altTracks) {
alts.put(indexKey, trackFields);
altTrackRecords++;
@@ -1338,7 +1351,19 @@ export async function buildIndex({
if (trackCues.length > 0) {
parsedSubs.push({ track: t.track, cues: trackCues });
}
- } catch {
+ } catch (err) {
+ // A STORED sub track that does not decode: the cues the last
+ // build held are kept, and with none to keep the record is
+ // written with no sub-track time, so the next build retries —
+ // the tiered chat's rule (REVIEW-1 F3).
+ if (isStoredTextReadError(err)) {
+ unreadableStored.push(`${s.channelSlug}/${s.videoDir}/${t.filename}: ${(err as Error).message}`);
+ const kept = prevSubs?.find((x) => x.track === t.track);
+ if (kept) parsedSubs.push(kept);
+ // Retried on EVERY later build, kept cues or not — never
+ // pinned as read (REVIEW-2 N5): `subsMs` is stored null.
+ retrySubs = true;
+ }
// Skip unreadable / malformed sub tracks; the rest of the
// video's data is still useful.
}
@@ -1453,6 +1478,14 @@ export async function buildIndex({
cueFingerprint: cueFingerprint(cueList),
});
} catch (err) {
+ if (isStoredTextReadError(err)) {
+ unreadableStored.push(`${s.channelSlug}/${s.videoDir}: ${(err as Error).message}`);
+ log(
+ `Unreadable stored text in ${s.channelSlug}/${s.videoDir}: ${(err as Error).message} — ` +
+ `the record is kept as the last build held it, and read again next build`,
+ );
+ return;
+ }
log(`Failed to process ${s.channelSlug}/${s.videoDir}: ${String(err)}`);
}
}),
@@ -1463,6 +1496,15 @@ export async function buildIndex({
}
}
+ if (unreadableStored.length > 0) {
+ log(
+ `UNREADABLE STORED TEXT: ${unreadableStored.length} file(s) that do not decode — not read as empty; ` +
+ `their records keep what the last build held: ${unreadableStored.slice(0, 20).join("; ")}` +
+ `${unreadableStored.length > 20 ? `; … ${unreadableStored.length - 20} more` : ""}. ` +
+ `\`pnpm ops compress-text --json '{"kinds":["captions"],"verify":true}'\` lists them.`,
+ );
+ }
+
// What the caption-track pass changed, per channel (CAPTION_TRACK_KEY).
for (const [slug, r] of [...captionReport].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
log(
diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts
@@ -72,6 +72,7 @@ import {
heldReason,
} from "../lib/channelMediaHold";
import { getSettings } from "../lib/settings";
+import { storedTextMtimeMs } from "../lib/storedText-server";
import type { Paths } from "../lib/paths";
import {
channelsOnlyOnUnlistedSites,
@@ -271,7 +272,8 @@ async function resolveAcquisitionDates(
if (transcribedDate === null) {
const picked = pickIndexTranscript(await readVideoFiles(videoDir));
const mtime =
- (picked ? await fileMtimeMs(path.join(videoDir, picked.filename)) : null) ??
+ // Either form (lib/storedText.ts): a stored caption carries its mtime.
+ (picked ? await storedTextMtimeMs(videoDir, picked.filename) : null) ??
(await fileMtimeMs(path.join(videoDir, CUES_JSON_FILENAME)));
transcribedDate = (mtime != null ? ymdFromMs(mtime) : null) ?? downloadedDate;
}
diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts
@@ -658,6 +658,40 @@ test("a chat-only livestream whose chat is STORED compressed is still a corpus m
}
});
+test("videos whose captions are STORED compressed read exactly as before: downloaded, transcribed, ASR-only (lane text-compress-captions)", async () => {
+ // Missed, an ASR-only video would leave the replace lane's bucket, and a
+ // captioned one would read undownloaded — the download lane fetching it
+ // again. The byte walk counts the stored file as text, under its own name.
+ const ASR =
+ "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:05.000 align:start position:0%\n" +
+ "First<00:00:01.000><c> caption</c>\n\n00:01:00.000 --> 00:01:50.000 align:start position:0%\n" +
+ "Second<00:01:10.000><c> caption</c>\n";
+ const { dir, paths, channelDir } = await filteredChannel({ listed: ["aaaa0000001", "bbbb0000002"] });
+ try {
+ for (const id of ["aaaa0000001", "bbbb0000002"]) {
+ const videoDir = path.join(channelDir, "data", id);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id, title: `Synthetic ${id}` }));
+ await writeFile(path.join(videoDir, "transcript.en.vtt"), ASR);
+ }
+ const plain = await generateChannelSnapshot(paths, "alpha");
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ for (const id of ["aaaa0000001", "bbbb0000002"]) {
+ await storeFixture(path.join(channelDir, "data", id), "transcript.en.vtt");
+ }
+ const stored = await generateChannelSnapshot(paths, "alpha");
+ assert.deepEqual(stored.buckets.autoSubsOnly, ["aaaa0000001", "bbbb0000002"]);
+ assert.deepEqual(stored.buckets.autoSubsOnly, plain.buckets.autoSubsOnly);
+ assert.deepEqual(stored.undownloadedIds, plain.undownloadedIds);
+ assert.deepEqual(stored.undownloadedIds, []);
+ assert.equal(stored.totals.downloaded, plain.totals.downloaded);
+ assert.equal(stored.totals.transcribed, plain.totals.transcribed);
+ assert.equal(stored.totals.transcribed, 2);
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
test("before the chat lands it is chatOnlyPending — the download lane's bucket", async () => {
const { dir, paths } = await filteredChannel({
filter: { include: "keep", rejectedLivestreams: "chat-only" },
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -1046,7 +1046,9 @@ export async function generateChannelSnapshot(
let textBytes = 0;
let clipsBytes = 0;
const linked: string[] = [];
- for (const name of files.entries) {
+ // PHYSICAL: a stored `.zst` is a file of its own size (text unless
+ // its name is tierable — lib/mediaTier.ts).
+ for (const name of files.physicalEntries) {
try {
const st = await lstat(path.join(dir, name));
if (st.isSymbolicLink()) {
diff --git a/common/controller/compressText.captions.test.ts b/common/controller/compressText.captions.test.ts
@@ -0,0 +1,397 @@
+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 { rmSync } from "node:fs";
+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));
+});
+
+// REVIEW-1 F2: A DELETED CAPTION NEVER COMES BACK FROM A STOPPED RUN'S
+// SET-ASIDE. A run killed at "retired" leaves the stored form and
+// `.transcript.en.vtt.retire-<pid>-<token>` (the whole original). Every
+// deleter removes the set-aside with the forms; and a set-aside found with NO
+// stored form beside it (a deletion some other way) is not adopted: kept,
+// listed for a person.
+test("killed at retired, then the caption deleted by each deleter: the next captions run leaves it deleted", async () => {
+ const { purgeSupersededAutoSubs } = await import("./purgeSupersededAutoSubs");
+ const { removeStoredText, removeStoredTextForm } = await import("../lib/storedText-write-server");
+ const ASR =
+ "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:05.000 align:start position:0%\n" +
+ "First<00:00:01.000><c> caption</c>\n\n00:01:00.000 --> 00:01:50.000 align:start position:0%\n" +
+ "Second<00:01:10.000><c> caption</c>\n";
+ const deleters: Record<string, (dir: string, slug: string) => Promise<unknown>> = {
+ purge: (_dir, slug) => purgeSupersededAutoSubs({ channelSlug: slug, paths, onLog: () => {} }),
+ "removeStoredText (the clear-transcript fix)": (dir) => removeStoredText(dir, "transcript.en.vtt"),
+ "the files card (the stored form)": (dir) => removeStoredTextForm(dir, "transcript.en.vtt.zst"),
+ };
+ let n = 0;
+ for (const [who, del] of Object.entries(deleters)) {
+ const slug = `kappa-${n++}`;
+ await channel(slug, { k1: { "transcript.en.vtt": ASR, "transcript.json": JSON.stringify({ transcription: [{ text: "ours" }] }) } });
+ await assert.rejects(
+ compressText({ paths, slugs: [slug], kinds: CAPTIONS, quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_989, crashAt: killAt("retired") } }),
+ CompressKill,
+ );
+ assert.equal((await leftovers(slug, "k1")).length, 1, `${who}: the set-aside is there`);
+ await del(dirOf(slug, "k1"), slug);
+ assert.deepEqual(await leftovers(slug, "k1"), [], `${who}: the deleter took the set-aside too`);
+ await compressText({ paths, slugs: [slug], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ assert.deepEqual(
+ (await names(slug, "k1")).filter((f) => f.includes(".vtt")),
+ [],
+ `${who}: still deleted, in every form`,
+ );
+ }
+});
+
+test("a set-aside with no stored form beside it (deleted some other way) is NOT adopted: kept, listed for a person", async () => {
+ await channel("lambda", { l1: { "transcript.en.vtt": vtt("l1", 20) } });
+ await assert.rejects(
+ compressText({ paths, slugs: ["lambda"], kinds: CAPTIONS, quietMs: 0, onLog: () => {}, compressOpts: { pid: 999_999_988, crashAt: killAt("retired") } }),
+ CompressKill,
+ );
+ // Deleted by hand: the stored form only (the set-aside left).
+ await rm(path.join(dirOf("lambda", "l1"), "transcript.en.vtt.zst"));
+ const lines: string[] = [];
+ const r = await compressText({ paths, slugs: ["lambda"], kinds: CAPTIONS, quietMs: 0, onLog: (l) => lines.push(l) });
+ const c = r.channels[0].byKind!.captions!;
+ assert.deepEqual(c.refused?.map((x) => [x.name, x.reason]), [["transcript.en.vtt", "retired-kept"]]);
+ assert.match(lines.join(""), /not adopted \(no stored form\)/);
+ assert.equal((await names("lambda", "l1")).includes("transcript.en.vtt"), false, "not brought back");
+ assert.equal((await leftovers("lambda", "l1")).length, 1, "kept for a person");
+});
+
+// REVIEW-1 N2: a pair refused once is recorded — the next run's survey counts
+// it as waiting for a person (listed once by the dry run), not as work, and
+// it is work again as soon as either form changes.
+test("both forms differ: refused ONCE and recorded; later runs list it as waiting, not work, until a form changes", async () => {
+ await channel("mu", { m1: { "transcript.en.vtt": vtt("old", 20) } });
+ await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ await writeFile(path.join(dirOf("mu", "m1"), "transcript.en.vtt"), vtt("new", 21));
+ await utimes(path.join(dirOf("mu", "m1"), "transcript.en.vtt"), OLD, OLD);
+ const first = await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ assert.equal(first.channels[0].byKind!.captions!.refused?.length, 1);
+ const plan = await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, dryRun: true, onLog: () => {} });
+ assert.equal(plan.channels[0].pending, 0, "not work: the job is not started for it");
+ assert.deepEqual(plan.channels[0].byKind!.captions!.differs, [{ id: "m1", name: "transcript.en.vtt" }]);
+ assert.match(plan.lines.join("\n"), /both forms differ, waiting for a person \(settle on the files card\): 1 — m1\/transcript\.en\.vtt/);
+ const lines: string[] = [];
+ const again = await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, quietMs: 0, onLog: (l) => lines.push(l) });
+ assert.equal(again.channels[0].byKind!.captions!.refused?.length, 0, "not refused again");
+ assert.match(lines.join(""), /1 with both forms differing still wait for a person/);
+ // A person settles it (the older stored copy deleted): work again — compressed.
+ await rm(path.join(dirOf("mu", "m1"), "transcript.en.vtt.zst"));
+ const settled = await compressText({ paths, slugs: ["mu"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ assert.equal(settled.channels[0].compressed, 1);
+ assert.equal(await readStoredText(dirOf("mu", "m1"), "transcript.en.vtt", "utf8"), vtt("new", 21));
+});
+
+// REVIEW-2 N3: the original removed OUTSIDE the lock between the compressor's
+// last look and its set-aside — yt-dlp's own overwrite deletes the plain
+// caption and fetches after. The verified stored copy is KEPT: if the fetch
+// fails it is the caption.
+test("the original vanishes just before its set-aside (yt-dlp's overwrite): the verified stored copy is kept", async () => {
+ await channel("nu", { n1: { "transcript.en.vtt": vtt("n1", 20) } });
+ const plain = path.join(dirOf("nu", "n1"), "transcript.en.vtt");
+ const lines: string[] = [];
+ const r = await compressText({
+ paths,
+ slugs: ["nu"],
+ kinds: CAPTIONS,
+ quietMs: 0,
+ onLog: (l) => lines.push(l),
+ compressOpts: {
+ crashAt: (p) => {
+ if (p === "placed") rmSync(plain);
+ },
+ },
+ });
+ assert.equal(r.channels[0].byKind!.captions!.changed, 1);
+ assert.deepEqual(await names("nu", "n1"), ["metadata.info.json", "transcript.en.vtt.zst"]);
+ assert.equal(await readStoredText(dirOf("nu", "n1"), "transcript.en.vtt", "utf8"), vtt("n1", 20));
+ assert.match(lines.join(""), /was removed while it was being compressed: the verified stored copy is kept/);
+});
+
+// REVIEW-2 N2: a deleter that cannot make the file's lock (a full disk, a
+// read-only dir) REFUSES, removes nothing, throws nothing, leaves no temp.
+test("a deleter that cannot make its lock refuses: nothing removed, no throw, no lock temp left", async () => {
+ const { chmod } = await import("node:fs/promises");
+ const { removeStoredText, removeStoredTextForm } = await import("../lib/storedText-write-server");
+ const { purgeSupersededAutoSubs } = await import("./purgeSupersededAutoSubs");
+ const ASR =
+ "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:05.000 align:start position:0%\n" +
+ "First<00:00:01.000><c> caption</c>\n\n00:01:00.000 --> 00:01:50.000 align:start position:0%\n" +
+ "Second<00:01:10.000><c> caption</c>\n";
+ await channel("xi", { x1: { "transcript.en.vtt": ASR, "transcript.json": JSON.stringify({ transcription: [{ text: "ours" }] }) } });
+ await compressText({ paths, slugs: ["xi"], kinds: CAPTIONS, quietMs: 0, onLog: () => {} });
+ const d = dirOf("xi", "x1");
+ const before = await names("xi", "x1");
+ await chmod(d, 0o555);
+ try {
+ const a = await removeStoredText(d, "transcript.en.vtt");
+ assert.ok("refused" in a && /not deleted: the stored-text lock cannot be made/.test(a.refused), JSON.stringify(a));
+ const b = await removeStoredTextForm(d, "transcript.en.vtt.zst");
+ assert.ok(typeof b === "object" && "refused" in b, JSON.stringify(b));
+ const logs: string[] = [];
+ const p = await purgeSupersededAutoSubs({ channelSlug: "xi", paths, onLog: (m) => logs.push(m) });
+ assert.equal(p.removedFiles, 0);
+ assert.match(logs.join("\n"), /Kept x1\/transcript\.en\.vtt — transcript\.en\.vtt not deleted/);
+ } finally {
+ await chmod(d, 0o755);
+ }
+ assert.deepEqual(await names("xi", "x1"), before, "nothing removed, no lock temp left");
+});
diff --git a/common/controller/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,48 @@
// 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,
+ bothDifferRecorded,
+ readStoredTextDiffers,
restoreStoredText,
+ storedTextLeftoverNames,
verifyStoredText,
type CompressOutcome,
type CompressSkipReason,
@@ -55,12 +76,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 +99,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 +123,52 @@ 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;
+ // Both forms with different content, recorded and unchanged since: waiting
+ // for a person (the files card), not work — each listed once.
+ differs?: { id: string; name: string }[];
+ // 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 +178,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 +187,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 +262,135 @@ 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 };
-}> {
+ // Both forms present and recorded as differing, unchanged since: waiting
+ // for a person — never work (REVIEW-1 N2).
+ differs: Candidate[];
+ 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: [], differs: [], pairsEqualSize: 0, pairsEqualSizeBytes: 0 };
+ }
const kept = { files: 0, bytes: 0 };
- const sizeOf = (p: string) =>
+ const differs = await readStoredTextDiffers(channelDir);
+ const sizeOfMedia = (p: string) =>
(drive ? onDrive(drive, () => stat(p)) : stat(p)).then((s) => s.size, () => null);
+ const logicalOfMedia = (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 sizeOfMedia(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]!;
+ // Captions are on the corpus disk (never tiered): stat them directly,
+ // never under the media drive's watchdog (REVIEW-1 N4).
+ const sizeOf = kind === "live-chat" ? sizeOfMedia : (p: string) => stat(p).then((st) => st.size, () => null);
+ const logicalOf = kind === "live-chat" ? logicalOfMedia : (p: string) => storedLogicalSize(p);
+ 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;
+ }
+ const waiting = forms === "both" && !leftover && (await bothDifferRecorded(differs, videoDir, name));
+ if (waiting) s.differs.push({ id, videoDir, name, size: size ?? 0 });
+ else 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 {
+ differs: s.differs.map((d) => ({ id: d.id, name: d.name })),
+ 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 +404,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 +430,262 @@ 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 differsText = (k: CompressTextKind) => {
+ const d = kl[k]!.differs ?? [];
+ return d.length
+ ? `; both forms differ, waiting for a person (settle on the files card): ${d.length} — ` +
+ `${d.slice(0, 10).map((x) => `${x.id}/${x.name}`).join(", ")}${d.length > 10 ? `, … ${d.length - 10} more` : ""}`
+ : "";
+ };
+ 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 + (c.differs?.length ?? 0) + (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)}${differsText(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);
+ const waiting = channels.reduce((a, l) => a + kinds.reduce((x, k) => x + (l.byKind?.[k]?.differs?.length ?? 0), 0), 0);
+ say(
+ `Compressed ${c} ${kindsText}: ${fmtBytes(b)} → ${fmtBytes(f)}` +
+ `${refused ? `; ${refused} refused with both forms kept (listed above, and recorded: not work again until one changes)` : ""}` +
+ `${waiting ? `; ${waiting} with both forms differing still wait for a person (the dry run lists them)` : ""}` +
+ `${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/controller/copies.test.ts b/common/controller/copies.test.ts
@@ -103,21 +103,40 @@ function vtt(lines: number, text: (i: number) => string, asr = false): string {
return out;
}
-function channel(p: Paths, slug: string): void {
+function channel(p: Paths, slug: string, extra: Record<string, unknown> = {}): void {
mkdirSync(path.join(p.channelsDir, slug, "data"), { recursive: true });
- writeFileSync(path.join(p.channelsDir, slug, "config.json"), JSON.stringify({ url: `https://www.youtube.com/@${slug.replace(/-/g, "")}`, handling: "transcribe" }));
+ writeFileSync(path.join(p.channelsDir, slug, "config.json"), JSON.stringify({ url: `https://www.youtube.com/@${slug.replace(/-/g, "")}`, handling: "transcribe", ...extra }));
}
function video(
p: Paths,
slug: string,
dir: string,
- o: { date: string; duration: number; cues?: ReturnType<typeof cues>; transcript?: boolean | number; audio?: boolean; id?: string },
+ o: {
+ date: string;
+ duration: number;
+ cues?: ReturnType<typeof cues>;
+ transcript?: boolean | number;
+ audio?: boolean;
+ id?: string;
+ title?: string;
+ // A finished live stream (yt-dlp's live_status "was_live").
+ live?: boolean;
+ },
): void {
const d = path.join(p.channelsDir, slug, "data", dir);
mkdirSync(d, { recursive: true });
const id = o.id ?? dir;
- writeFileSync(path.join(d, "metadata.info.json"), JSON.stringify({ id, title: `Stream ${id}`, duration: o.duration, upload_date: o.date }));
+ writeFileSync(
+ path.join(d, "metadata.info.json"),
+ JSON.stringify({
+ id,
+ title: o.title ?? `Stream ${id}`,
+ duration: o.duration,
+ upload_date: o.date,
+ ...(o.live ? { live_status: "was_live", was_live: true } : {}),
+ }),
+ );
if (o.cues) writeFileSync(path.join(d, "transcript.cues.json"), JSON.stringify({ version: 2, id, cues: o.cues }));
// A real-length transcript by default: 20 words a minute of runtime.
if (o.transcript) writeFileSync(path.join(d, "transcript.json"), whisperJson(typeof o.transcript === "number" ? o.transcript : Math.ceil((o.duration / 60) * 20)));
@@ -262,6 +281,90 @@ test("a cancelled scan stops between pairs and writes nothing", async () => {
assert.deepEqual(readdirSync(p.transcriptsDir), ["channels"], "no copies file");
});
+// A RE-UPLOAD channel and a LIVE mirror of the same streams (the shape of the
+// first real scan's fault): the re-uploads went up months after the streams and
+// carry the stream's day only in their titles; the mirror's videos are the live
+// streams themselves, dated by their own day. No recordedDate rule is set.
+function reuploads(p: Paths, prefConfig: Record<string, unknown> = {}): void {
+ channel(p, "pref-chan", prefConfig);
+ channel(p, "mirror-chan");
+ video(p, "pref-chan", "p1", { date: "20260310", duration: 7200, title: "2023-04-05 the long stream", cues: cues(1) });
+ video(p, "pref-chan", "p2", { date: "20260311", duration: 7200, title: "2023 04 08 another stream" });
+ video(p, "pref-chan", "p3", { date: "20260312", duration: 3000, title: "2023 Apr 20 a short one" });
+ video(p, "mirror-chan", "m1", { date: "20230405", duration: 7260, live: true, title: "[Copy] stream", cues: cues(1, 45), audio: true });
+ video(p, "mirror-chan", "m2", { date: "20230408", duration: 7230, live: true, title: "[Copy] stream", cues: cues(2), audio: true });
+}
+
+test("a re-upload channel dated only in its titles is paired with the live copies (fails against upload-date dating)", async () => {
+ const p = corpus();
+ reuploads(p);
+ const out = await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true });
+ const f = out.file;
+ assert.deepEqual(
+ f.pairs.map((x) => [x.key, x.link, x.a.dateFrom, x.b.dateFrom]),
+ [
+ ["pref-chan/p1|mirror-chan/m1", "confirmed", "title", "live"],
+ ["pref-chan/p2|mirror-chan/m2", "metadata", "title", "live"],
+ ],
+ );
+ assert.deepEqual(f.pairs[0].a.date, "20230405", "the stream's day, not the upload's");
+ assert.equal(f.dating?.["pref-chan"].detectedPattern !== undefined, true);
+ assert.deepEqual(f.dating?.["pref-chan"].byFrom, { rule: 0, live: 0, title: 3, upload: 0, none: 0 });
+ assert.deepEqual(f.dating?.["mirror-chan"].byFrom, { rule: 0, live: 2, title: 0, upload: 0, none: 0 });
+ // The scan SAYS the channel lacks its rule, with the exact patch to set it.
+ const advice = (f.advice ?? []).join("\n");
+ assert.match(advice, /pref-chan: 3 of 3 videos are dated by a date their titles carry/);
+ const patch = /pnpm ops channel-config --json '(.*?)'/.exec(advice)?.[1];
+ assert.ok(patch, advice);
+ const body = JSON.parse(patch!);
+ assert.equal(body.slug, "pref-chan");
+ assert.equal(new RegExp(body.patch.recordedDateTitlePattern, "i").test("2023-04-05 the long stream"), true);
+ assert.doesNotMatch(advice, /mirror-chan/, "a live channel is dated by its streams: nothing to set");
+});
+
+test("the channel's own recordedDate rule dates its videos first, and no advice asks for one", async () => {
+ const p = corpus();
+ reuploads(p, { recordedDate: { titlePattern: "^(?<year>\\d{4})[- ](?<month>\\d{2})[- ](?<day>\\d{2})" } });
+ const f = (await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true })).file;
+ assert.deepEqual(
+ f.pairs.map((x) => [x.key, x.link, x.a.dateFrom]),
+ [
+ ["pref-chan/p1|mirror-chan/m1", "confirmed", "rule"],
+ ["pref-chan/p2|mirror-chan/m2", "metadata", "rule"],
+ ],
+ );
+ // p3's "2023 Apr 20" is not the rule's shape: the rule is the operator's word,
+ // so the scan does not guess past it — p3 keeps its upload date.
+ assert.deepEqual(f.dating?.["pref-chan"].byFrom, { rule: 2, live: 0, title: 0, upload: 1, none: 0 });
+ assert.equal(f.dating?.["pref-chan"].detectedPattern, undefined);
+ assert.doesNotMatch((f.advice ?? []).join("\n"), /recordedDateTitlePattern/);
+ // A ruled channel is never searched by runtime: the scan is main's.
+ assert.equal(f.totals.runtime, undefined);
+});
+
+test("with no date to go by, a copy is found by runtime and words, never held on runtime alone, and the search is bounded", async () => {
+ const p = corpus();
+ channel(p, "pref-chan");
+ channel(p, "mirror-chan");
+ // Re-uploads whose titles carry no date: their upload day is the copy's.
+ video(p, "pref-chan", "p1", { date: "20260310", duration: 7200, title: "Stream highlights", cues: cues(1) });
+ video(p, "pref-chan", "p2", { date: "20260311", duration: 7200, title: "Another stream" });
+ video(p, "mirror-chan", "m1", { date: "20230405", duration: 7260, live: true, cues: cues(1, 45), audio: true });
+ video(p, "mirror-chan", "m2", { date: "20230408", duration: 7230, live: true, cues: cues(2), audio: true });
+ video(p, "mirror-chan", "m3", { date: "20230409", duration: 7190, live: true, cues: cues(3), audio: true });
+ const f = (await runCopiesScan(p, settingsWith([GROUP]), "stream-copies", { dryRun: true })).file;
+ assert.deepEqual(
+ f.pairs.map((x) => [x.key, x.link, x.evidence.via]),
+ [["pref-chan/p1|mirror-chan/m1", "confirmed", "runtime"]],
+ "p2 has no words: a runtime alone is no evidence, so no pair (and no hold)",
+ );
+ assert.equal(f.totals.candidates, 0, "nothing was dated near anything");
+ assert.deepEqual(f.totals.runtime, { searched: 1, candidates: 3, rejected: 2, capped: 0 });
+ const advice = (f.advice ?? []).join("\n");
+ assert.match(advice, /pref-chan: 2 of 2 videos have only an upload date/);
+ assert.match(advice, /no two members' videos are dated within 1 day/);
+});
+
async function lane(p: Paths, kind: "transcription" | "backfill" = "transcription") {
resetCopiesLaneCacheForTest();
return computeLeafPending(kind, p, { state: emptyAutoQueueState() });
diff --git a/common/controller/copiesLane.ts b/common/controller/copiesLane.ts
@@ -30,6 +30,8 @@ import { isGroup, type AutoQueueKind, type AutoQueueNode, type AutoQueuePolicy }
import { mapConcurrent } from "../lib/concurrency";
import { isTranscriptVtt, readVideoFiles, resolvePrimaryVtt, WHISPER_FILENAME } from "../lib/videoStatus";
import { parseVtt } from "../lib/vtt";
+import { isStoredTextName, logicalEntries, storedNameOf } from "../lib/storedText";
+import { isStoredTextReadError, readStoredText } from "../lib/storedText-server";
import { resolveCaptionsProvenance } from "../lib/subtitleProvenance";
import { operationsForLane } from "../lib/operations";
import { DIARIZATION_FILENAME } from "../lib/videoStatus";
@@ -74,13 +76,22 @@ export type CopiesLaneIo = {
readFile: (p: string) => Promise<string>;
readdir: (p: string) => Promise<string[]>;
stat: (p: string) => Promise<{ mtimeMs: number; size: number }>;
+ // A caption's text in either form (lib/storedText.ts). A test's seam may
+ // leave it out: the plain file is read through `readFile` then.
+ readCaption?: (dir: string, name: string) => Promise<string>;
};
const realIo: CopiesLaneIo = {
readFile: (p) => readFile(p, "utf8"),
readdir: (p) => readdir(p),
stat: (p) => stat(p),
+ readCaption: (dir, name) => readStoredText(dir, name, "utf8"),
};
let io: CopiesLaneIo = realIo;
+// Stored captions this process found unreadable (REVIEW-1 F3): counted.
+let unreadableStoredCaptions = 0;
+export function unreadableStoredCaptionCount(): number {
+ return unreadableStoredCaptions;
+}
let revalidateMs = COPY_DONE_REVALIDATE_MS;
// What the lanes need to know about a video of a group, beyond its pairs.
@@ -224,7 +235,10 @@ type DoneRules = {
// The files that decide a video's done state for the lane, with their sizes
// and mtimes: equal signatures, equal answers.
async function signatureOf(kind: AutoQueueKind, videoDir: string): Promise<{ sig: string; entries: string[] }> {
- const entries = (await io.readdir(videoDir).catch(() => [] as string[])).sort();
+ // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is listed under
+ // its plain name, and stamped by the form that is there.
+ const physical = await io.readdir(videoDir).catch(() => [] as string[]);
+ const entries = logicalEntries(physical).sort();
const decisive =
kind === "transcription"
? entries.filter((e) => e === WHISPER_FILENAME || isTranscriptVtt(e))
@@ -236,7 +250,11 @@ async function signatureOf(kind: AutoQueueKind, videoDir: string): Promise<{ sig
e === ATTRIBUTION_FILENAME ||
e === AUDIO_INTEGRITY_FILENAME,
);
- const stamps = await Promise.all(decisive.map((e) => stampOf(path.join(videoDir, e))));
+ const stamps = await Promise.all(
+ decisive.map((e) =>
+ stampOf(path.join(videoDir, physical.includes(e) || !isStoredTextName(e) ? e : storedNameOf(e))),
+ ),
+ );
// The Speakers states also turn on which other files are there (audio, a
// container), so the backfill signature carries the whole listing.
return { sig: JSON.stringify([kind === "backfill" ? entries : decisive, stamps]), entries };
@@ -268,9 +286,13 @@ async function transcriptDone(videoDir: string, entries: readonly string[], rule
if (rules.replaceAutoSubs && (await resolveCaptionsProvenance(videoDir, entries)) === "asr") return false;
try {
let words = 0;
- for (const cue of parseVtt(await io.readFile(path.join(videoDir, vtt)))) words += speechWords(cue.text);
+ const text = io.readCaption ? await io.readCaption(videoDir, vtt) : await io.readFile(path.join(videoDir, vtt));
+ for (const cue of parseVtt(text)) words += speechWords(cue.text);
return words >= min;
- } catch {
+ } catch (err) {
+ // A stored caption that does not decode is not "no transcript" (REVIEW-1
+ // F3): computeDone answers it.
+ if (isStoredTextReadError(err)) throw err;
return false;
}
}
@@ -307,12 +329,24 @@ async function computeDone(
try {
if (kind === "transcription") return await transcriptDone(path.join(paths.channelsDir, channel, "data", dir), entries, rules);
if (kind === "backfill") return await speakersDone(paths, settings, channel, dir);
- } catch {
+ } catch (err) {
+ // A STORED CAPTION THAT DOES NOT DECODE is an error, never "not done"
+ // (REVIEW-1 F3, captions lane): "not done" would send the lane to
+ // transcribe the video's copy over it. Counted as done (no work made
+ // from it), and said, with the path.
+ if (isStoredTextReadError(err)) {
+ unreadableStoredCaptions += 1;
+ console.warn(`[copies] ${key}: a stored caption cannot be read — ${(err as Error).message}; not counted as work`);
+ return true;
+ }
// unreadable: not done
}
return false;
}
+// Exported for its test ONLY (controller/storedText.unreadable.test.ts).
+export const __computeDoneForTest = computeDone;
+
/**
* Whether each `<channel>/<dir>` has this lane's work done and readable. A copy
* seen before answers from the cache at once; one never seen is read now.
diff --git a/common/controller/copiesScan.ts b/common/controller/copiesScan.ts
@@ -26,16 +26,18 @@ import { CUES_JSON_FILENAME } from "../lib/videoStatus";
import { isRealAudioFile } from "../lib/mediaFiles";
import { inspectChannelMedia } from "../lib/channelMedia";
import { isMediaHeld } from "../lib/channelMediaHold";
-import { contentDate } from "../lib/mirrors/match";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import { readChannelConfig } from "./channels";
import { readChannelRecords } from "./mirrorScan";
import {
classifyCandidate,
copyCandidates,
+ COPY_RUNTIME_PER_VIDEO,
cuesToWords,
prepareCopyText,
+ runtimeCandidates,
textEvidence,
+ wantsRuntimeSearch,
type CopyRecord,
type CopyText,
type TextEvidence,
@@ -55,6 +57,7 @@ import {
} from "../lib/copies/file";
import { readCopiesDecisions, readCopiesFile, updateCopiesDecisions, writeCopiesFile } from "../lib/copies/file-server";
import { SOURCE_GROUP_ID_RE, type SourceGroup } from "../lib/copies/settings";
+import { dateChannel, datingAdvice, noCandidatesAdvice, type ChannelDating, type DatedChannel } from "../lib/copies/dating";
export const COPIES_SCAN_JOB_KIND = "copies-scan";
// One scan at a time, machine-wide: each reads thousands of cue files.
@@ -117,7 +120,22 @@ export class CopiesScanCancelled extends Error {
}
function member(r: CopyRecord): CopyMember {
- return { channel: r.channel, dir: r.dir, id: r.id, title: r.title, duration: r.duration, date: r.date };
+ return {
+ channel: r.channel,
+ dir: r.dir,
+ id: r.id,
+ title: r.title,
+ duration: r.duration,
+ date: r.date,
+ ...(r.dateFrom !== undefined ? { dateFrom: r.dateFrom } : {}),
+ };
+}
+
+async function hasCuesFile(paths: Paths, r: CopyRecord): Promise<boolean> {
+ return stat(path.join(paths.channelsDir, r.channel, "data", r.dir, CUES_JSON_FILENAME)).then(
+ (s) => s.isFile() && s.size > 0,
+ () => false,
+ );
}
export type CopiesScanOptions = {
@@ -138,7 +156,7 @@ export type CopiesScanOutcome = {
// The file's content without the per-run stamps, for "did anything change".
function contentOf(f: CopiesFile): string {
- return JSON.stringify([f.channels, f.missing ?? [], f.rules, f.pairs, f.totals]);
+ return JSON.stringify([f.channels, f.missing ?? [], f.rules, f.pairs, f.totals, f.dating ?? {}, f.advice ?? []]);
}
export async function runCopiesScan(
@@ -169,27 +187,78 @@ export async function runCopiesScan(
const missing: string[] = [];
const records: CopyRecord[] = [];
const videos: Record<string, number> = {};
+ const datings = new Map<string, DatedChannel<{ title: string; uploadDate: string; recordedDate?: string; wasLive: boolean }>>();
let undated = 0;
for (const slug of group.channels) {
checkCancel();
- if (!(await readChannelConfig(paths, slug))) {
+ const config = await readChannelConfig(paths, slug);
+ if (!config) {
missing.push(slug);
continue;
}
const c = await readChannelRecords(paths, slug);
videos[slug] = c.records.length;
- for (const r of c.records) {
- const date = contentDate(r);
+ // DATED BY THE BEST EVIDENCE EACH VIDEO HAS (lib/copies/dating.ts): the
+ // channel's rule, a live stream's own day, a date its titles carry, its upload.
+ const d = dateChannel(c.records, !!config.recordedDate);
+ datings.set(slug, d);
+ for (const { record: r, date, from } of d.dated) {
if (!date) undated++;
- records.push({ channel: slug, dir: r.dir ?? r.id, id: r.id, title: r.title, duration: r.duration, date });
+ records.push({ channel: slug, dir: r.dir ?? r.id, id: r.id, title: r.title, duration: r.duration, date, dateFrom: from });
}
- log(`${slug}: ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk)`);
+ const by = Object.entries(d.dating.byFrom)
+ .filter(([, n]) => n > 0)
+ .map(([k, n]) => `${n} by ${k === "none" ? "nothing (undated)" : k}`)
+ .join(", ");
+ log(`${slug}: ${c.records.length} videos (${c.fromIndex} from the index, ${c.fromDisk} from disk); dated ${by || "none"}`);
}
if (missing.length > 0) log(`not in this corpus, skipped: ${missing.join(", ")}`);
const candidates = copyCandidates(group, records);
log(`${candidates.length} candidate pairs dated within ${group.dateWindowDays} day(s)`);
+ // THE RUNTIME SEARCH for videos whose date cannot pair them (only an upload
+ // day, or none) and that found no candidate by date: bounded, and decided by
+ // the words only (lib/copies/match.ts runtimeCandidates).
+ const pairedByDate = new Set<string>();
+ for (const c of candidates) {
+ if (c.a.channel === c.b.channel) continue;
+ pairedByDate.add(`${c.a.channel}/${c.a.dir}`);
+ pairedByDate.add(`${c.b.channel}/${c.b.dir}`);
+ }
+ const ruled = new Set([...datings].filter(([, d]) => d.dating.ruleSet).map(([slug]) => slug));
+ const textKnown = new Set<string>();
+ if (wantsRuntimeSearch(records, ruled)) {
+ for (const r of records) {
+ await breathe();
+ if (r.duration > 0 && (await hasCuesFile(paths, r))) textKnown.add(`${r.channel}/${r.dir}`);
+ }
+ }
+ const search = await runtimeCandidates(group, records, {
+ hasText: (r) => textKnown.has(`${r.channel}/${r.dir}`),
+ dated: pairedByDate,
+ ruled,
+ breathe,
+ });
+ if (search.searched > 0 || search.capped > 0) {
+ log(
+ `${search.candidates.length} candidate pairs by runtime for ${search.searched} video(s) with no date to pair by` +
+ `${search.capped ? ` (${search.capped} more left unsearched: the scan's cap)` : ""}`,
+ );
+ }
+ const runtimeSentence =
+ search.searched > 0 || search.capped > 0
+ ? `Those with words were looked for by runtime instead (at most ${COPY_RUNTIME_PER_VIDEO} nearest each): ${search.searched} searched, ` +
+ `${search.candidates.length} compared${search.capped ? `, ${search.capped} left unsearched by the cap` : ""}.`
+ : null;
+ const advice: string[] = [];
+ for (const [slug, d] of datings) advice.push(...datingAdvice(slug, d, d.dating.byFrom.upload + d.dating.byFrom.none > 0 ? runtimeSentence : null));
+ const crossDated = candidates.some((c) => c.a.channel !== c.b.channel);
+ if (!crossDated && datings.size >= 2 && records.length > 0) {
+ advice.push(noCandidatesAdvice(group.dateWindowDays, [...datings].map(([slug, d]) => ({ slug, span: d.dating.span }))));
+ }
+ for (const a of advice) log(`note: ${a}`);
+
// A small cache of words and their phrase index: candidates come grouped
// by their `a` side, so each is built once per run of its candidates.
const cache = new Map<string, CopyText | null>();
@@ -219,16 +288,22 @@ export async function runCopiesScan(
overlaps: 0,
rejected: 0,
withinChannel: 0,
+ ...(search.searched > 0 || search.capped > 0
+ ? { runtime: { searched: search.searched, candidates: search.candidates.length, rejected: 0, capped: search.capped } }
+ : {}),
};
const pairs: CopyPairRecord[] = [];
- for (const c of candidates) {
+ for (const c of [...candidates, ...search.candidates]) {
await breathe();
const [wa, wb] = [await wordsOf(c.a), await wordsOf(c.b)];
const text: TextEvidence | null = wa && wb ? textEvidence(wa, wb) : null;
const usable = text && text.verdict !== "no-text" ? text : null;
const cls = classifyCandidate(c, usable);
if (!cls) {
- if (usable) totals.rejected++;
+ if (usable) {
+ if (c.via === "runtime") totals.runtime!.rejected++;
+ else totals.rejected++;
+ }
continue;
}
const { link } = cls;
@@ -246,6 +321,7 @@ export async function runCopiesScan(
withinChannel,
evidence: {
kind: usable ? "text" : "metadata",
+ via: c.via ?? "date",
dateDeltaDays: c.dateDeltaDays,
durationOk: c.durationOk,
...(usable ? { text: usable } : {}),
@@ -269,6 +345,8 @@ export async function runCopiesScan(
},
pairs,
totals,
+ dating: Object.fromEntries([...datings].map(([slug, d]) => [slug, d.dating])) as Record<string, ChannelDating>,
+ ...(advice.length > 0 ? { advice } : {}),
};
log(
`${totals.confirmed} confirmed by text and runtime, ${totals.metadata} metadata only, ${totals.partOf} part of ` +
@@ -293,6 +371,8 @@ export function copiesScanSummary(out: CopiesScanOutcome, dryRun: boolean) {
channels: f.channels,
...(f.missing ? { missing: f.missing } : {}),
totals: f.totals,
+ ...(f.dating ? { dating: f.dating } : {}),
+ ...(f.advice ? { advice: f.advice } : {}),
};
}
@@ -544,6 +624,8 @@ export type CopiesGroupReport = {
jobId?: string;
totals: CopiesTotals;
missing?: string[];
+ // What the scan said about its own inputs (CopiesFile.advice).
+ advice?: string[];
};
// Cross-channel pairs by link (a metadata pair a person confirmed counts as
// confirmed; a rejected pair counts nowhere but `rejected`); the pairs
@@ -631,7 +713,7 @@ export async function copiesReport(
key: p.key,
a: p.a,
b: p.b,
- dateDeltaDays: p.evidence.dateDeltaDays,
+ dateDeltaDays: p.evidence.dateDeltaDays ?? 0,
durationDifferenceSeconds: Math.round(Math.abs(p.a.duration - p.b.duration)),
firstSeenAt: p.firstSeenAt,
waitEnds: new Date(ends).toISOString(),
@@ -676,6 +758,7 @@ export async function copiesReport(
...(file.jobId ? { jobId: file.jobId } : {}),
totals: file.totals,
...(file.missing ? { missing: file.missing } : {}),
+ ...(file.advice ? { advice: file.advice } : {}),
}
: null,
pairs,
diff --git a/common/controller/duplicateShorts.ts b/common/controller/duplicateShorts.ts
@@ -49,6 +49,7 @@ import { STATS_SCHEMA_VERSION } from "../lib/stats";
import type { Cue } from "../lib/vtt";
import { parseTranscriptJson } from "../lib/whisper";
import { readVideoFiles, pickIndexTranscript } from "../lib/videoStatus";
+import { readStoredText } from "../lib/storedText-server";
import {
DEFAULT_ALIGNMENT_TOLERANCE_SECONDS,
DEFAULT_CONTAINMENT_THRESHOLD,
@@ -966,7 +967,8 @@ async function readRawCues(
if (!picked) return null;
let raw: string;
try {
- raw = await readFile(path.join(dir, picked.filename), "utf8");
+ // Either form (lib/storedText.ts): a caption stored as `.zst` is read.
+ raw = await readStoredText(dir, picked.filename, "utf8");
} catch {
return null;
}
diff --git a/common/controller/findClips.ts b/common/controller/findClips.ts
@@ -63,6 +63,7 @@ import { getSettings } from "../lib/settings";
import { assertChannelTextReadable } from "../lib/channelMedia";
import { findSourceMedia, isRealAudioFile, pickPreferredAudio } from "../lib/mediaFiles";
import { DIARIZATION_FILENAME, englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus";
+import { logicalEntries } from "../lib/storedText";
import { loadSavedVideo, resolveSavedVideo } from "../lib/savedVideo-server";
import { backfillLaneOperations, DIARIZATION_OPERATION_ID } from "../lib/operations";
import { isGateHeld } from "../lib/pauseGates";
@@ -201,7 +202,10 @@ export async function inspectFindClips(
const audio = pickPreferredAudio(entries.filter(isRealAudioFile));
let audioPath: string | null = audio ? path.join(videoDir, audio) : container ? path.join(videoDir, container) : null;
if (!audioPath && pointer) audioPath = await resolveSavedVideo(videoDir).catch(() => null);
- const transcript = entries.includes(WHISPER_FILENAME) ? WHISPER_FILENAME : (englishVttsByPreference(entries)[0] ?? null);
+ // LOGICAL for the transcript (lib/storedText.ts): a stored caption counts.
+ const transcript = entries.includes(WHISPER_FILENAME)
+ ? WHISPER_FILENAME
+ : (englishVttsByPreference(logicalEntries(entries))[0] ?? null);
const words = await loadWordTimings(videoDir).catch(() => null);
return {
saved: pointer !== null || container !== null,
diff --git a/common/controller/livePreclip.ts b/common/controller/livePreclip.ts
@@ -39,7 +39,7 @@
// machine.
import path from "node:path";
-import { mkdir, readdir, rm } from "node:fs/promises";
+import { mkdir, rm } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import type { ChannelConfig } from "../lib/channelConfig";
import { getSettings } from "../lib/settings";
@@ -51,6 +51,7 @@ import { savedVideoDir } from "../lib/savedVideo";
import { loadSavedVideo } from "../lib/savedVideo-server";
import { savedVideoPath } from "../lib/savedVideo";
import { englishVttsByPreference, WHISPER_FILENAME } from "../lib/videoStatus";
+import { readdirLogical } from "../lib/storedText-server";
import { umtoolUrl as resolveUmtoolUrl } from "../lib/umtoolUrl";
import { getWorkerToken } from "../lib/workerToken";
import {
@@ -290,7 +291,8 @@ export function umtoolMiner(umtool: string, token: string, doFetch: typeof fetch
}
export async function hasCorpusTranscript(videoDir: string): Promise<boolean> {
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is a transcript.
+ const entries = await readdirLogical(videoDir);
return entries.includes(WHISPER_FILENAME) || englishVttsByPreference(entries).length > 0;
}
diff --git a/common/controller/normalizeTranscript.ts b/common/controller/normalizeTranscript.ts
@@ -4,7 +4,13 @@
// shape that buildIndex would emit, plus a `source` marker.
import path from "node:path";
-import { open, readdir, readFile, stat } from "node:fs/promises";
+import { open, readFile, stat } from "node:fs/promises";
+import {
+ readStoredTextHead,
+ readdirLogical,
+ storedTextLogicalSize,
+ storedTextMtimeMs,
+} from "../lib/storedText-server";
import { writeJsonAtomic } from "../lib/jsonFile-server";
import { hasWordTiming, type Cue } from "../lib/vtt";
import {
@@ -300,14 +306,17 @@ export async function isCuesJsonFresh(
): Promise<{ fresh: boolean; reason: CuesFreshReason; cuesPath: string }> {
const cuesPath = path.join(videoDir, CUES_JSON_FILENAME);
const metaPath = path.join(videoDir, META_FILENAME);
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is an input under
+ // its plain name, and its mtime is the plain file's (the stored form carries
+ // it exactly), so a compression moves no cues.json to stale.
+ const entries = await readdirLogical(videoDir);
const whisperPath = path.join(videoDir, WHISPER_FILENAME);
const inputs = captionInputs(entries);
const [cuesMs, metaMs, whisperMs, ...inputMs] = await Promise.all([
mtimeMs(cuesPath),
mtimeMs(metaPath),
mtimeMs(whisperPath),
- ...inputs.map((n) => mtimeMs(path.join(videoDir, n))),
+ ...inputs.map((n) => storedTextMtimeMs(videoDir, n)),
]);
const vttMs = inputMs.reduce<number | null>(
(max, ms) => (ms !== null && (max === null || ms > max) ? ms : max),
@@ -383,18 +392,24 @@ async function followsCaptionTrackRule(
const vtts = englishVttsByPreference(entries);
if (vtts.length === 0) return true;
try {
- if (vtts.length === 1 && hasWordTiming(await readHead(path.join(videoDir, vtts[0])))) {
+ // The DECODED head of a stored track (lib/storedText-server.ts).
+ if (
+ vtts.length === 1 &&
+ hasWordTiming((await readStoredTextHead(videoDir, vtts[0], HEAD_BYTES)).toString("utf8"))
+ ) {
return true;
}
const m = (await readHead(cuesPath)).match(/"captionTrackRule"\s*:\s*(\d+)/);
if (m !== null && Number(m[1]) === CAPTION_TRACK_RULE_VERSION) return true;
if (/"cues"\s*:\s*\[\s*\]\s*\}\s*$/.test(await readTail(cuesPath))) return false;
if (!entries.includes(VTT_FILENAME) || !entries.includes(ORIG_VTT_FILENAME)) return true;
+ // LOGICAL sizes: a stored track's is its frame header's content size —
+ // never the compressed size, which differs between the two forms.
const [en, orig] = await Promise.all([
- stat(path.join(videoDir, VTT_FILENAME)),
- stat(path.join(videoDir, ORIG_VTT_FILENAME)),
+ storedTextLogicalSize(videoDir, VTT_FILENAME),
+ storedTextLogicalSize(videoDir, ORIG_VTT_FILENAME),
]);
- return en.size === orig.size;
+ return en === orig;
} catch {
return false;
}
diff --git a/common/controller/operationBatch.ts b/common/controller/operationBatch.ts
@@ -34,7 +34,7 @@
// share. Nothing new.
import path from "node:path";
-import { open, readFile, readdir } from "node:fs/promises";
+import { open, readdir } from "node:fs/promises";
import type { Paths } from "../lib/paths";
import { getSettings, type SiteSettings } from "../lib/settings";
import { isGateHeld } from "../lib/pauseGates";
@@ -49,6 +49,17 @@ import { runPool } from "../jobs/concurrentRunner";
import type { TaskTracker } from "../jobs/taskHooks";
import type { JobProgress } from "../jobs/registry";
import { readVideoFiles, CUES_JSON_FILENAME } from "../lib/videoStatus";
+import { readStoredText } from "../lib/storedText-server";
+
+// A remote unit's inputs, as the worker receives them: each under its LOGICAL
+// name with its PLAIN bytes (lib/storedText.ts) — a caption stored as `.zst`
+// is decoded here, so the worker protocol and an older worker see exactly what
+// they always did. Exported for its test.
+export async function readUnitInputFiles(videoDir: string, names: readonly string[]): Promise<Record<string, Buffer>> {
+ const files: Record<string, Buffer> = {};
+ for (const name of names) files[name] = await readStoredText(videoDir, name);
+ return files;
+}
import {
DIARIZATION_OPERATION_ID,
DIGEST_OPERATION_ID,
@@ -1311,9 +1322,7 @@ async function runViaTaggedRemote(
checkUntranscribable: true,
});
const files: Record<string, Buffer> = {};
- for (const name of unit.op.inputs(listing)) {
- files[name] = await readFile(path.join(videoDir, name));
- }
+ Object.assign(files, await readUnitInputFiles(videoDir, unit.op.inputs(listing)));
// The channel context is injected because a scratch corpus has no
// digest-context.md to read. Read per channel, memoized by the same map
// the targets use.
diff --git a/common/controller/purgeSupersededAutoSubs.ts b/common/controller/purgeSupersededAutoSubs.ts
@@ -1,4 +1,5 @@
-import { removeStoredText } from "../lib/storedText-write-server";
+import { removeStoredText, verifyStoredText } from "../lib/storedText-write-server";
+import { logicalEntries, storedFormsIn } from "../lib/storedText";
import path from "node:path";
import fs from "fs-extra";
import type { Paths } from "../lib/paths";
@@ -70,7 +71,10 @@ export async function purgeSupersededAutoSubs({
for (const id of dirs) {
if (signal?.aborted) break;
const videoDir = path.join(dataDir, id);
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ // PHYSICAL, then LOGICAL (lib/storedText.ts): a track stored as `.zst` is
+ // a track here under its plain name — and is purged in both forms.
+ const physical = await readdir(videoDir).catch(() => [] as string[]);
+ const entries = logicalEntries(physical);
// No transcript of our own yet — nothing has been superseded, so the VTT is
// still this video's only transcript. Never touch it.
if (!entries.includes(WHISPER_FILENAME)) continue;
@@ -89,9 +93,26 @@ export async function purgeSupersededAutoSubs({
skipped++;
continue;
}
+ // BOTH FORMS WITH DIFFERENT CONTENT: the sniff read the plain one, and
+ // the stored one is another capture this purge has not looked at (it
+ // may be the manual one) — kept, both, for a person.
+ if (storedFormsIn(physical, name) === "both") {
+ const v = await verifyStoredText(videoDir, name);
+ if (v.status !== "ok") {
+ log(`Kept ${id}/${name} (its plain and stored forms differ: ${v.status} — settle it on the files card)`);
+ skipped++;
+ continue;
+ }
+ }
// Both forms (lib/storedText-write-server.ts): a stored copy left behind
// would bring the captions back. Each through removeMediaFile.
- await removeStoredText(videoDir, name);
+ const out = await removeStoredText(videoDir, name);
+ if ("refused" in out) {
+ // Nothing was removed (a full disk, or a run holding the file).
+ log(`Kept ${id}/${name} — ${out.refused}`);
+ skipped++;
+ continue;
+ }
log(`Removed ${id}/${name}`);
removedFiles++;
removedHere++;
diff --git a/common/controller/reconcileVideoDirs.test.ts b/common/controller/reconcileVideoDirs.test.ts
@@ -193,6 +193,21 @@ test("a stored chat and a plain chat collide by their LOGICAL name; the loser is
);
});
+test("a stored caption and a plain caption collide by their LOGICAL name too (lane text-compress-captions)", async (t) => {
+ const channelDir = await makeChannel();
+ t.after(() => rm(channelDir, { recursive: true, force: true }));
+ await writeStrayDir(channelDir, "canonical01", { "transcript.en.vtt.zst": "destination stored caption" });
+ await writeStrayDir(channelDir, "v-canonical01", { "transcript.en.vtt": "source plain caption" });
+ await reconcileVideoDirs({ channelDir });
+ const dst = path.join(channelDir, "data", "canonical01");
+ const names = (await readdir(dst)).filter((n) => n.startsWith("transcript.")).sort();
+ assert.deepEqual(names, ["transcript.en.vtt", "transcript.en.vtt.zst.dup-v-canonical01"]);
+ assert.equal(
+ await readFile(path.join(dst, "transcript.en.vtt.zst.dup-v-canonical01"), "utf8"),
+ "destination stored caption",
+ );
+});
+
test("both forms on the source side move in together over a destination's stored chat", async (t) => {
const channelDir = await makeChannel();
t.after(() => rm(channelDir, { recursive: true, force: true }));
diff --git a/common/controller/reportRefresh.ts b/common/controller/reportRefresh.ts
@@ -22,7 +22,7 @@
// (current.json), else the newest done iteration that carries a report.
import { modelLogged } from "./jobModelLog";
-import { access, readdir, readFile } from "node:fs/promises";
+import { access, readFile } from "node:fs/promises";
import path from "node:path";
import { runManagedFunction, type StreamActionResult } from "../jobs/streamCommand";
import type { JobProgress } from "../jobs/registry";
@@ -40,6 +40,7 @@ import { resolveVideoDir } from "../lib/videoDir-server.mjs";
import { detectPlatform } from "../lib/detectPlatform.mjs";
import { WHISPER_FILENAME, englishVttsByPreference } from "../lib/videoStatus";
import { parseVtt } from "../lib/vtt";
+import { isStoredTextReadError, readStoredText, readdirLogical } from "../lib/storedText-server";
import { parseTranscriptJson } from "../lib/whisper";
import { isCuesJsonFresh, readNormalizedTranscript } from "./normalizeTranscript";
import { diskPostChannelOf } from "../lib/report/convert-server";
@@ -501,7 +502,8 @@ async function runRefreshJob(
export async function diskRecordOf(channelsDir: string, slug: string, id: string): Promise<RecordRead | null> {
const dir = await resolveVideoDir(channelsDir, slug, id).catch(() => null);
if (!dir) return null;
- const entries = await readdir(dir).catch(() => [] as string[]);
+ // LOGICAL (lib/storedText.ts): a stored caption is a track under its name.
+ const entries = await readdirLogical(dir);
if (!entries.length) return null;
const tracks: { name: string; cues: { start: number; end: number; text: string }[] }[] = [];
const fresh = await isCuesJsonFresh(dir).catch(() => ({ fresh: false as const }));
@@ -514,7 +516,14 @@ export async function diskRecordOf(channelsDir: string, slug: string, id: string
if (w.length) tracks.push({ name: WHISPER_FILENAME, cues: w });
}
for (const name of englishVttsByPreference(entries)) {
- const v = await readFile(path.join(dir, name), "utf8").then((t) => parseVtt(t), () => []);
+ // A stored track that does not decode is an error, never "no cues" (REVIEW-1 F3).
+ const v = await readStoredText(dir, name, "utf8").then(
+ (t) => parseVtt(t),
+ (err: unknown) => {
+ if (isStoredTextReadError(err)) throw err;
+ return [];
+ },
+ );
if (v.length) tracks.push({ name, cues: v });
}
const state = stateFromAvailability(await resolveEffectiveAvailability(dir).catch(() => null));
diff --git a/common/controller/storedText.captions.test.ts b/common/controller/storedText.captions.test.ts
@@ -0,0 +1,244 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, readdir, rm, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/storedText.captions.test.ts
+//
+// THE CAPTIONS ARE STILL FOUND BY EVERY READER AFTER THEY ARE COMPRESSED (lane
+// text-compress-captions, slice 4). Each case builds a video dir whose caption
+// tracks are `transcript.<lang>.vtt.zst` only and asks a reader of each class
+// what it sees: the listing (readVideoFiles), the cue read, the freshness
+// stat, the head sniff (provenance, word timing), the logical size, the
+// yt-dlp skip-if-exists checks (a miss there is a re-fetch, or an audio
+// download and a transcription), the cited record, the remote worker's
+// inputs. Before this slice each read a stored track as ABSENT — or, for a
+// head sniff, read zstd bytes and answered WRONG. Temp corpus, no network,
+// no yt-dlp. Synthetic names only.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-captions-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { readVideoFiles, readEnglishVttCues, pickIndexTranscript } = await import("../lib/videoStatus");
+const { normalizeTranscript, isCuesJsonFresh } = await import("./normalizeTranscript");
+const { readVttProvenance, resolveCaptionsProvenance, isAutoSubsOnly } = await import("../lib/subtitleProvenance");
+const { readVideoTracks } = await import("../lib/captionTracks-server");
+const { destinationExists, subLangsForVideo } = await import("../ytdlp/runYtdlp");
+const { youtubeHandlingArgs, __hasAnyTranscriptOnDiskForTest } = await import("../ytdlp/downloadOneManaged");
+const { readCitedRecord } = await import("../publish/composeReports");
+const { diskRecordOf } = await import("./reportRefresh");
+const { hasCorpusTranscript } = await import("./livePreclip");
+const { readUnitInputFiles } = await import("./operationBatch");
+const { storeFixture } = await import("../testing/storedTextFixture");
+
+const paths = getPaths();
+const SLUG = "synth-captions";
+const CONFIG = { handling: "youtube", url: "https://www.youtube.com/@synth/videos", name: "Synth" } as ChannelConfig;
+const channelDir = path.join(CORPUS, "channels", SLUG);
+const dataDir = path.join(channelDir, "data");
+
+// YouTube's rolling ASR shape (align + inline word timing) and a human track.
+const ASR =
+ "WEBVTT\nKind: captions\nLanguage: en\n\n" +
+ "00:00:00.000 --> 00:00:05.000 align:start position:0%\n" +
+ "First<00:00:01.000><c> caption</c><00:00:02.000><c> line.</c>\n\n" +
+ "00:01:00.000 --> 00:01:50.000 align:start position:0%\n" +
+ "Second<00:01:10.000><c> caption</c><00:01:20.000><c> line.</c>\n";
+const MANUAL =
+ "WEBVTT\n\n00:00:00.000 --> 00:00:04.000\nA human wrote this line.\n\n" +
+ "00:00:04.000 --> 00:00:09.000\nAnd this one, with care.\n\n00:00:09.000 --> 00:00:12.000\nThe end.\n";
+const ORIG = ASR.replace("First", "Original").replace("Second", "Spoken");
+
+async function video(id: string, tracks: Record<string, string>, extra: Record<string, string> = {}): Promise<string> {
+ const dir = path.join(dataDir, id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify(CONFIG));
+ await writeFile(
+ path.join(dir, "metadata.info.json"),
+ JSON.stringify({
+ id,
+ title: `Synth ${id}`,
+ upload_date: "20260101",
+ duration: 120,
+ webpage_url: `https://www.youtube.com/watch?v=${id}`,
+ extractor_key: "Youtube",
+ }),
+ );
+ for (const [name, body] of Object.entries({ ...tracks, ...extra })) await writeFile(path.join(dir, name), body);
+ // Sub-millisecond times: a `Date` round trip would lose them.
+ for (const name of Object.keys(tracks)) await utimes(path.join(dir, name), 1763700000.123457, 1763700000.987653);
+ return dir;
+}
+
+async function storeAll(dir: string): Promise<void> {
+ for (const n of await readdir(dir)) if (/^transcript\.[^.]+\.vtt$/.test(n)) await storeFixture(dir, n);
+ assert.equal((await readdir(dir)).some((n) => n.endsWith(".vtt")), false, "only stored captions are left");
+}
+
+test("the listing: readVideoFiles is LOGICAL — a stored track is listed, primary and all", async () => {
+ const dir = await video("list1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG, "transcript.es.vtt": MANUAL });
+ const before = await readVideoFiles(dir);
+ await storeAll(dir);
+ const after = await readVideoFiles(dir);
+ assert.equal(after.hasYtVtt, true);
+ assert.equal(after.ytVttFile, "transcript.en-orig.vtt");
+ assert.equal(after.hasNonCanonicalVtt, before.hasNonCanonicalVtt);
+ assert.deepEqual([...after.entries].sort(), [...before.entries].sort(), "the same logical names");
+ assert.ok(after.physicalEntries.includes("transcript.en.vtt.zst"));
+ assert.deepEqual(pickIndexTranscript(after), pickIndexTranscript(before));
+});
+
+test("the cue read: readEnglishVttCues reads the stored tracks, under their plain names", async () => {
+ const dir = await video("cues1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG });
+ const before = await readEnglishVttCues(dir);
+ await storeAll(dir);
+ assert.deepEqual(await readEnglishVttCues(dir), before);
+ // Given the caller's raw readdir, too.
+ assert.deepEqual(await readEnglishVttCues(dir, await readdir(dir)), before);
+ assert.equal(before?.filename, "transcript.en-orig.vtt");
+});
+
+test("normalize: a cues.json made before compression stays FRESH, and a forced one writes the same cues", async () => {
+ const dir = await video("norm1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG });
+ assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} })).status, "wrote");
+ const made = JSON.parse(await readFile(path.join(dir, "transcript.cues.json"), "utf8"));
+ await storeAll(dir);
+ assert.deepEqual(await isCuesJsonFresh(dir), { fresh: true, reason: "fresh", cuesPath: path.join(dir, "transcript.cues.json") });
+ assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} })).status, "fresh");
+ assert.equal((await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {}, force: true })).status, "wrote");
+ const again = JSON.parse(await readFile(path.join(dir, "transcript.cues.json"), "utf8"));
+ assert.deepEqual(again.cues, made.cues);
+ assert.equal(again.vttFile, "transcript.en-orig.vtt", "the record names the LOGICAL track");
+});
+
+test("normalize: the caption-track rule's head and size checks read the stored tracks as the plain ones", async () => {
+ // An unversioned cues.json (made before the rule had a version) with cues,
+ // en and en-orig of DIFFERENT content: stale — it was read from en, and
+ // en-orig is read now. Stored, the sizes compared must be the logical ones.
+ const dir = await video("rule1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG + "\n" });
+ await normalizeTranscript({ videoDir: dir, channelSlug: SLUG, log: () => {} });
+ const cuesPath = path.join(dir, "transcript.cues.json");
+ const rec = JSON.parse(await readFile(cuesPath, "utf8"));
+ delete rec.captionTrackRule;
+ await writeFile(cuesPath, JSON.stringify(rec));
+ assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "plain: stale");
+ await storeFixture(dir, "transcript.en.vtt");
+ assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "en stored, en-orig plain: still stale");
+ await storeFixture(dir, "transcript.en-orig.vtt");
+ assert.equal((await isCuesJsonFresh(dir)).reason, "stale", "both stored: still stale");
+
+ // A lone word-timed track with an empty unversioned cues.json: FRESH (its
+ // parse did not change) — read from the DECODED head.
+ const lone = await video("rule2", { "transcript.en.vtt": ASR });
+ await writeFile(path.join(lone, "transcript.cues.json"), JSON.stringify({ title: "x", cues: [] }));
+ assert.equal((await isCuesJsonFresh(lone)).fresh, true, "plain");
+ await storeFixture(lone, "transcript.en.vtt");
+ assert.equal((await isCuesJsonFresh(lone)).fresh, true, "stored: the head is decoded");
+});
+
+test("the head sniff: provenance reads the DECODED head — ASR stays ASR, manual stays manual", async () => {
+ const dir = await video("prov1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ASR, "transcript.es.vtt": MANUAL });
+ await storeAll(dir);
+ assert.equal(await readVttProvenance(dir, "transcript.en.vtt"), "asr");
+ assert.equal(await readVttProvenance(dir, "transcript.es.vtt"), "manual");
+ assert.equal(await resolveCaptionsProvenance(dir, await readdir(dir)), "asr");
+ const files = await readVideoFiles(dir);
+ assert.equal(await isAutoSubsOnly(dir, files), true, "the replace lane still sees an ASR-only video");
+ const human = await video("prov2", { "transcript.en.vtt": MANUAL });
+ await storeAll(human);
+ assert.equal(await resolveCaptionsProvenance(human, await readdir(human)), "manual", "a human track is never scheduled for replacement");
+});
+
+test("the alternate tracks: readVideoTracks reads stored tracks", async () => {
+ const dir = await video("alts1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG });
+ const before = await readVideoTracks(dir);
+ await storeAll(dir);
+ assert.deepEqual(await readVideoTracks(dir), before);
+ assert.equal(before?.tracks.length, 2);
+});
+
+test("destinationExists: a stored transcript.en.vtt is the destination — the URL is NOT fetched again", async () => {
+ await video("dest1", { "transcript.en.vtt": ASR });
+ await storeAll(path.join(dataDir, "dest1"));
+ assert.equal(await destinationExists(dataDir, "dest1", "youtube"), true);
+ // The replace-auto-captions run still sees it as ASR (the decoded sniff).
+ assert.equal(await destinationExists(dataDir, "dest1", "youtube", { replaceAutoSubs: true }), false);
+ await video("dest2", { "transcript.en.vtt": MANUAL });
+ await storeAll(path.join(dataDir, "dest2"));
+ assert.equal(await destinationExists(dataDir, "dest2", "youtube", { replaceAutoSubs: true }), true, "a human track suppresses it");
+});
+
+test("hasAnyTranscriptOnDisk: a stored caption is a transcript — no audio download, no transcription", async () => {
+ for (const name of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.es.vtt"]) {
+ const dir = await video(`any-${name.split(".")[1]}`, { [name]: ASR });
+ await storeAll(dir);
+ assert.equal(await __hasAnyTranscriptOnDiskForTest(dir), true, name);
+ }
+ // The control: a stored chat alone is not a transcript.
+ const chat = await video("any-chat", {}, { "transcript.live_chat.json": "{}\n" });
+ await storeFixture(chat, "transcript.live_chat.json");
+ assert.equal(await __hasAnyTranscriptOnDiskForTest(chat), false);
+});
+
+test("the missing-subs pass leaves every stored track out of --sub-langs (under --no-overwrites main skipped a present one)", async () => {
+ const dir = await video("subs1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG });
+ await storeFixture(dir, "transcript.en.vtt");
+ await storeFixture(dir, "transcript.en-orig.vtt");
+ const entries = await readdir(dir);
+ assert.equal(subLangsForVideo(entries, "en.*,live_chat"), "en.*,live_chat,-en,-en-orig");
+ // Both forms (the plain is there): yt-dlp's own skip sees it — unchanged.
+ assert.equal(subLangsForVideo(["transcript.en.vtt", "transcript.en.vtt.zst"], "en.*"), "en.*");
+ // A stored chat and a stored caption: the chat left out as for a `later`
+ // channel, the caption excluded by code.
+ assert.equal(subLangsForVideo(["transcript.live_chat.json.zst", "transcript.en.vtt.zst"], "en.*,live_chat"), "en.*,-en");
+ const langs = (args: string[]) => args[args.indexOf("--sub-langs") + 1];
+ // The managed download fetches a stored caption AGAIN (main's re-download
+ // rule, REVIEW-1 F1): no exclusion there; the pass is settled afterwards
+ // (ytdlp/captionsRefetch.test.ts). Only the stored chat is left out.
+ assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false)), "en.*,live_chat");
+ assert.equal(langs(youtubeHandlingArgs(CONFIG, false, true)), "en.*");
+});
+
+test("the cited record (compose, report refresh) reads stored tracks — cues and every English track", async () => {
+ const dir = await video("cite1", { "transcript.en.vtt": ASR, "transcript.en-orig.vtt": ORIG });
+ const before = await readCitedRecord(path.join(CORPUS, "channels"), SLUG, "cite1");
+ const beforeDisk = await diskRecordOf(path.join(CORPUS, "channels"), SLUG, "cite1");
+ await storeAll(dir);
+ const after = await readCitedRecord(path.join(CORPUS, "channels"), SLUG, "cite1");
+ assert.deepEqual(after?.cues, before?.cues);
+ assert.deepEqual(after?.tracks, before?.tracks);
+ assert.equal(after?.tracks.length, 2);
+ assert.deepEqual(await diskRecordOf(path.join(CORPUS, "channels"), SLUG, "cite1"), beforeDisk);
+});
+
+test("the live pre-clip's transcript check sees a stored caption", async () => {
+ const dir = await video("pre1", { "transcript.en.vtt": ASR });
+ await storeAll(dir);
+ assert.equal(await hasCorpusTranscript(dir), true);
+});
+
+test("the remote worker's inputs: the PLAIN bytes under the logical name", async () => {
+ const dir = await video("worker1", { "transcript.en-orig.vtt": ORIG });
+ await storeAll(dir);
+ const files = await readUnitInputFiles(dir, ["metadata.info.json", "transcript.en-orig.vtt"]);
+ assert.deepEqual(Object.keys(files), ["metadata.info.json", "transcript.en-orig.vtt"]);
+ assert.equal(files["transcript.en-orig.vtt"].toString("utf8"), ORIG);
+});
+
+test("with no caption in either form, every check says so (the control)", async () => {
+ const dir = await video("none1", {});
+ assert.equal(await destinationExists(dataDir, "none1", "youtube"), false);
+ assert.equal(await __hasAnyTranscriptOnDiskForTest(dir), false);
+ assert.equal((await readVideoFiles(dir)).hasYtVtt, false);
+ assert.equal(await readEnglishVttCues(dir), null);
+ assert.equal(paths.channelsDir, path.join(CORPUS, "channels"));
+});
diff --git a/common/controller/storedText.delete.test.ts b/common/controller/storedText.delete.test.ts
@@ -68,8 +68,9 @@ test("the superseded-auto-caption purge removes a caption's stored sibling too",
const d = await videoDir("p", "v3");
await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] }));
await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT);
- // What a later stored-captions slice would leave: an older stored copy.
- await writeFile(path.join(d, "transcript.en.vtt.zst"), "older stored copy");
+ // Both forms of the same track (a compression that stopped before the
+ // original went): purged in both.
+ await storeFixture(d, "transcript.en.vtt", { keepPlain: true });
const r = await purgeSupersededAutoSubs({
channelSlug: "p",
paths: { channelsDir: path.join(ROOT, "channels") } as never,
@@ -79,6 +80,48 @@ test("the superseded-auto-caption purge removes a caption's stored sibling too",
assert.deepEqual((await readdir(d)).sort(), ["transcript.json"]);
});
+test("the purge KEEPS both forms when they differ (or the stored one does not decode): it sniffed only the plain one", async () => {
+ // (Changed in lane text-compress-captions: slice 1 removed a stored sibling
+ // whatever it held. A stored copy with other content is another capture —
+ // it may be the manual track — and nothing removes a stored caption
+ // because a different one arrived.)
+ for (const [id, stored] of [["v4", "differs"], ["v5", "corrupt"]] as const) {
+ const d = await videoDir("p", id);
+ await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] }));
+ if (stored === "differs") {
+ await writeFile(path.join(d, "transcript.en.vtt"), "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nA human track.\n");
+ await storeFixture(d, "transcript.en.vtt");
+ } else {
+ await writeFile(path.join(d, "transcript.en.vtt.zst"), "not a zstd frame");
+ }
+ await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT);
+ const r = await purgeSupersededAutoSubs({
+ channelSlug: "p",
+ ids: [id],
+ paths: { channelsDir: path.join(ROOT, "channels") } as never,
+ onLog: () => {},
+ });
+ assert.equal(r.removedFiles, 0, stored);
+ assert.deepEqual((await readdir(d)).sort(), ["transcript.en.vtt", "transcript.en.vtt.zst", "transcript.json"], stored);
+ }
+});
+
+test("the purge finds a superseded ASR track stored ONLY compressed, and removes it", async () => {
+ const d = await videoDir("p", "v6");
+ await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] }));
+ await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT);
+ await storeFixture(d, "transcript.en.vtt");
+ assert.deepEqual((await readdir(d)).sort(), ["transcript.en.vtt.zst", "transcript.json"]);
+ const r = await purgeSupersededAutoSubs({
+ channelSlug: "p",
+ ids: ["v6"],
+ paths: { channelsDir: path.join(ROOT, "channels") } as never,
+ onLog: () => {},
+ });
+ assert.equal(r.removedFiles, 1, "the decoded head sniffs as ASR");
+ assert.deepEqual(await readdir(d), ["transcript.json"]);
+});
+
// REVIEW-1 F5 / REVIEW-2 R2: THE FILES CARD'S DELETE OF ONE NAMED FORM
// (`removeStoredTextForm`, what deleteVideoFileAction and `pnpm ops
// delete-file` run). A person asked for ONE file: only that one goes, never the
@@ -157,3 +200,26 @@ test("delete one named form through tier links: the named form's bytes go, the o
assert.deepEqual(out, { removed: [CHAT], kept: { name: ZST, same: "unreadable" } });
assert.equal(await readStoredText(e, CHAT, "utf8"), "ONLY COPY\n");
});
+
+// REVIEW-1 N1 (captions lane): "Set as transcript" over a stored `en` writes
+// the pick as a plain transcript.en.vtt beside it and pins it. Deleting the
+// plain pick must not leave the pin ranking YouTube's stored `en` first.
+test("the files card: the plain pick deleted beside a stored en of other content takes the pin with it", async () => {
+ const d = await videoDir("pin", "v1");
+ await writeFile(path.join(d, "transcript.en.vtt"), "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nyoutube's en\n");
+ await storeFixture(d, "transcript.en.vtt");
+ await writeFile(path.join(d, "transcript.en.vtt"), "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nthe picked track\n");
+ await writeFile(path.join(d, "transcript-pin.json"), JSON.stringify({ from: "transcript.en-US.vtt", pinnedAt: "2026-11-21T00:00:00.000Z" }));
+ const out = await removeStoredTextForm(d, "transcript.en.vtt");
+ assert.notEqual(out, "busy");
+ assert.equal((out as { unpinned?: boolean }).unpinned, true);
+ assert.deepEqual((await readdir(d)).sort(), ["transcript.en.vtt.zst"]);
+ // The same content beside it: nothing was picked over it — the pin stays.
+ const e = await videoDir("pin", "v2");
+ await writeFile(path.join(e, "transcript.en.vtt"), "WEBVTT\n\nsame\n");
+ await storeFixture(e, "transcript.en.vtt", { keepPlain: true });
+ await writeFile(path.join(e, "transcript-pin.json"), JSON.stringify({ from: "transcript.en.vtt", pinnedAt: "x" }));
+ const same = await removeStoredTextForm(e, "transcript.en.vtt");
+ assert.equal((same as { unpinned?: boolean }).unpinned, undefined);
+ assert.ok((await readdir(e)).includes("transcript-pin.json"));
+});
diff --git a/common/controller/storedText.unreadable.test.ts b/common/controller/storedText.unreadable.test.ts
@@ -0,0 +1,114 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/storedText.unreadable.test.ts
+//
+// REVIEW-1 F3 (captions lane): A STORED FILE THAT CANNOT BE READ IS AN ERROR
+// THAT SURFACES, NEVER "NO TEXT". On a Node without zstd every process refuses
+// to start, naming the Node it needs; and a stored caption whose frame does
+// not decode is thrown past the readers that skip a missing track — the copies
+// lane does not read it as "not done". (The index's side is buildIndex.test.ts
+// (w).) Temp dirs, synthetic names.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-unreadable-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+const COMMON = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+
+const { zstdSupportProblem, assertZstdSupport } = await import("../lib/zstdSupport.mjs");
+const { readEnglishVttCues } = await import("../lib/videoStatus");
+const { readVideoTracks } = await import("../lib/captionTracks-server");
+const { isStoredTextReadError } = await import("../lib/storedText-server");
+const { __computeDoneForTest, unreadableStoredCaptionCount } = await import("./copiesLane");
+
+const VTT = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\none two three four\n";
+
+test("no zstd in this Node: the problem names the Node it needs; asked to assert, it refuses", () => {
+ assert.equal(zstdSupportProblem(), null, "this Node has it");
+ const old = {};
+ const p = zstdSupportProblem(old, "v22.11.0");
+ assert.match(String(p), /needs node:zlib zstd — Node >= 22\.15 \(this is v22\.11\.0\)/);
+ assert.throws(() => assertZstdSupport("the editor", old, "v22.11.0"), /the editor refuses to start: .*Node >= 22\.15/);
+});
+
+test("a bare-node reader of stored text, and a common/bin CLI, refuse to start on a Node without zstd", async (t) => {
+ // A preload that takes zstd away, as an older Node would not have it (its
+ // own temp dir: made and removed by this test).
+ const own = await mkdtemp(path.join(tmpdir(), "no-zstd-"));
+ t.after(() => rm(own, { recursive: true, force: true }));
+ const NO_ZSTD = path.join(own, "no-zstd.mjs");
+ await writeFile(
+ NO_ZSTD,
+ 'import zlib from "node:zlib";\nfor (const k of ["zstdDecompress", "createZstdCompress", "createZstdDecompress"]) delete zlib[k];\n',
+ );
+ const reader = spawnSync(process.execPath, ["--import", NO_ZSTD, "-e", `await import(${JSON.stringify(path.join(COMMON, "lib", "storedText-read.mjs"))})`], {
+ encoding: "utf8",
+ input: "",
+ });
+ assert.notEqual(reader.status, 0);
+ assert.match(reader.stderr, /refuses to start: stored text .*needs node:zlib zstd — Node >= 22\.15/);
+ // A CLI entry (runIfEntryPoint): a tiny entry point in the temp dir.
+ const entry = path.join(own, "cli-entry.ts");
+ const cli = path.join(COMMON, "bin", "_cli.ts");
+ await writeFile(entry, `import { runIfEntryPoint } from ${JSON.stringify(cli)};\nrunIfEntryPoint(import.meta.url, async () => { console.log("ran"); });\n`);
+ const tsx = path.join(COMMON, "node_modules", ".bin", "tsx");
+ const run = spawnSync(tsx, [entry], { encoding: "utf8", cwd: own, env: { ...process.env, NODE_OPTIONS: `--import=${NO_ZSTD}` } });
+ assert.notEqual(run.status, 0, run.stdout + run.stderr);
+ assert.doesNotMatch(run.stdout, /ran/);
+ assert.match(run.stderr, /cli-entry\.ts refuses to start: .*Node >= 22\.15/);
+ const ok = spawnSync(tsx, [entry], { encoding: "utf8", cwd: own, env: { ...process.env, NODE_OPTIONS: "" } });
+ assert.equal(ok.status, 0, ok.stderr);
+ assert.match(ok.stdout, /ran/);
+});
+
+async function videoWithCorruptStored(id: string): Promise<string> {
+ const dir = path.join(ROOT, "channels", "synth", "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), JSON.stringify({ id }));
+ // A frame header claiming 64 bytes, then garbage: it does not decode.
+ await writeFile(path.join(dir, "transcript.en.vtt.zst"), Buffer.from([0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x40, 1, 2, 3, 4, 5, 6]));
+ return dir;
+}
+
+test("a stored caption that does not decode is THROWN by the caption readers, never skipped as no text", async () => {
+ const dir = await videoWithCorruptStored("bad1");
+ await assert.rejects(readEnglishVttCues(dir), (e: unknown) => isStoredTextReadError(e));
+ await assert.rejects(readVideoTracks(dir), (e: unknown) => isStoredTextReadError(e));
+ // A readable fallback track does not hide it either: the corrupt one is
+ // the preferred one, and its words are unknown.
+ await writeFile(path.join(dir, "transcript.en-US.vtt"), VTT);
+ await assert.rejects(readEnglishVttCues(dir), (e: unknown) => isStoredTextReadError(e));
+ // A MISSING track is still just missing.
+ const none = path.join(ROOT, "channels", "synth", "data", "none1");
+ await mkdir(none, { recursive: true });
+ assert.equal(await readEnglishVttCues(none), null);
+});
+
+test("the copies lane: an unreadable stored caption is not \"not done\" (it would send the lane to transcribe it)", async () => {
+ await videoWithCorruptStored("bad2");
+ const paths = { channelsDir: path.join(ROOT, "channels") } as never;
+ const before = unreadableStoredCaptionCount();
+ const warned: string[] = [];
+ const warn = console.warn;
+ console.warn = (m: string) => void warned.push(m);
+ try {
+ const done = await __computeDoneForTest(
+ "transcription",
+ paths,
+ {} as never,
+ "synth/bad2",
+ { facts: { duration: 10, captionsCountAsDone: true }, replaceAutoSubs: false },
+ ["metadata.info.json", "transcript.en.vtt"],
+ );
+ assert.equal(done, true);
+ } finally {
+ console.warn = warn;
+ }
+ assert.equal(unreadableStoredCaptionCount(), before + 1, "counted");
+ assert.match(warned.join("\n"), /synth\/bad2: a stored caption cannot be read — .*transcript\.en\.vtt\.zst/);
+});
diff --git a/common/lib/captionTracks-server.ts b/common/lib/captionTracks-server.ts
@@ -2,7 +2,9 @@
// says what an alternate is). SERVER-ONLY (node:fs).
import path from "node:path";
-import { readdir, readFile } from "node:fs/promises";
+import { readFile } from "node:fs/promises";
+import { logicalEntries } from "./storedText";
+import { isStoredTextReadError, readStoredText, readdirLogical } from "./storedText-server";
import { parseVtt, type Cue } from "./vtt";
import { parseTranscriptJson } from "./whisper";
import {
@@ -47,13 +49,17 @@ export async function readEnglishVttTracks(
entries: readonly string[],
): Promise<{ filename: string; cues: Cue[] }[]> {
const out: { filename: string; cues: Cue[] }[] = [];
- for (const filename of englishVttsByPreference(entries)) {
+ for (const filename of englishVttsByPreference(logicalEntries(entries))) {
try {
out.push({
filename,
- cues: parseVtt(await readFile(path.join(videoDir, filename), "utf8")),
+ // Either form (lib/storedText.ts): a track stored as `.zst` is read.
+ cues: parseVtt(await readStoredText(videoDir, filename, "utf8")),
});
- } catch {
+ } catch (err) {
+ // A stored track that does not decode is an error (REVIEW-1 F3): the
+ // record must not be written without it.
+ if (isStoredTextReadError(err)) throw err;
// unreadable: not a track
}
}
@@ -72,7 +78,8 @@ export async function readTrackFields(
primaryCues: readonly Cue[] | undefined,
entries?: readonly string[],
): Promise<TrackFields> {
- const listing = entries ?? (await readdir(videoDir).catch(() => [] as string[]));
+ // LOGICAL (lib/storedText.ts): a stored track is listed under its name.
+ const listing = entries ? logicalEntries(entries) : await readdirLogical(videoDir);
if (!mayHaveAltTracks(primaryKind, listing)) return {};
const vtts = await readEnglishVttTracks(videoDir, listing);
let primaryTrack: string;
@@ -105,7 +112,7 @@ export async function readTrackFields(
export async function readVideoTracks(
videoDir: string,
): Promise<{ tracks: AltTrack[] } | null> {
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const entries = await readdirLogical(videoDir);
let primary: AltTrack | null = null;
let kind: "vtt" | "whisper" = "vtt";
if (entries.includes(WHISPER_FILENAME)) {
diff --git a/common/lib/copies/dating.test.ts b/common/lib/copies/dating.test.ts
@@ -0,0 +1,93 @@
+// lib/copies/dating.ts: the date a copies scan pairs a video by. Every title,
+// channel and date here is synthetic.
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { recordedDatePatternProblem } from "../recordedDate";
+import {
+ dateChannel,
+ dateEvidence,
+ datingAdvice,
+ detectTitleDate,
+ noCandidatesAdvice,
+ recordedDatePatchCommand,
+ TITLE_DATE_SHAPES,
+ type DatingRecord,
+} from "./dating";
+
+const upload = (title: string, uploadDate = "20260310"): DatingRecord => ({ title, uploadDate, wasLive: false });
+const live = (title: string, uploadDate: string): DatingRecord => ({ title, uploadDate, wasLive: true });
+
+test("every built-in title shape is a valid recordedDate rule, so the one detected can be proposed verbatim", () => {
+ for (const s of TITLE_DATE_SHAPES) assert.equal(recordedDatePatternProblem(s.pattern), null, s.id);
+});
+
+test("the order: the channel's rule, else a live stream's day, else a title date, else the upload", () => {
+ const re = new RegExp(TITLE_DATE_SHAPES[0].pattern, "i");
+ assert.deepEqual(dateEvidence({ ...upload("2023-01-02 x"), recordedDate: "20230101" }, re), { date: "20230101", from: "rule" });
+ assert.deepEqual(dateEvidence(live("2023-01-02 x", "20230103"), re), { date: "20230103", from: "live" });
+ assert.deepEqual(dateEvidence(upload("2023-01-02 x"), re), { date: "20230102", from: "title" });
+ assert.deepEqual(dateEvidence(upload("2023-01-02 x"), null), { date: "20260310", from: "upload" });
+ // A title date after the upload is a date the title mentions, not the stream's.
+ assert.deepEqual(dateEvidence(upload("2027-01-02 preview"), re), { date: "20260310", from: "upload" });
+ assert.equal(dateEvidence({ title: "x", uploadDate: "", wasLive: false }, re), null);
+});
+
+test("a re-upload channel's leading title dates are detected in their mixed spellings (fails against upload-date dating)", () => {
+ const d = dateChannel(
+ [upload("2023 01 04 a stream"), upload("2023-01-05 the stream"), upload("2023 Jan 06 more"), upload("2012 a stream part 2")],
+ false,
+ );
+ assert.deepEqual(
+ d.dated.map((x) => [x.date, x.from]),
+ [
+ ["20230104", "title"],
+ ["20230105", "title"],
+ ["20230106", "title"],
+ ["20260310", "upload"],
+ ],
+ );
+ assert.equal(d.dating.detectedPattern, TITLE_DATE_SHAPES[0].pattern);
+ assert.deepEqual(d.dating.span, { from: "20230104", to: "20260310" });
+ const advice = datingAdvice("pref-chan", d, null).join("\n");
+ assert.match(advice, /pref-chan: 3 of 4 videos are dated by a date their titles carry/);
+ assert.ok(advice.includes(recordedDatePatchCommand("pref-chan", TITLE_DATE_SHAPES[0].pattern)));
+ assert.match(advice, /pref-chan: 1 of 4 videos have only an upload date/);
+});
+
+test("a mirror's tagged titles are detected; a live channel is dated by its streams whatever its titles say", () => {
+ const tagged = dateChannel([upload("[Copy] 2023-01-04"), upload("[Copy] 2023-01-05 Part 2/2"), upload("[Copy] 2023-01-07")], false);
+ assert.equal(tagged.dating.byFrom.title, 3);
+ const lives = dateChannel([live("[Copy] 2023-01-04", "20230105"), live("A stream", "20230106")], false);
+ assert.deepEqual(lives.dating.byFrom, { rule: 0, live: 2, title: 0, upload: 0, none: 0 });
+ assert.equal(lives.dating.detectedPattern, undefined);
+ assert.deepEqual(datingAdvice("mirror-chan", lives, null), [], "nothing to set on a live channel");
+});
+
+test("a shape that reads only a few titles does not stand for the channel; the advice names it with what it reads", () => {
+ const recs = [upload("Episode 1"), upload("Episode 2"), upload("Recap of 2023-01-04"), upload("Episode 3"), upload("Episode 4")];
+ assert.equal(detectTitleDate(recs), null);
+ const d = dateChannel(recs, false);
+ assert.equal(d.dating.byFrom.upload, 5);
+ const advice = datingAdvice("pref-chan", d, "searched by runtime.").join("\n");
+ assert.match(advice, /closest title shape reads 1 of 5/);
+ assert.match(advice, /searched by runtime\./);
+});
+
+test("with the channel's rule set, no shape is guessed past it", () => {
+ const d = dateChannel([{ ...upload("2023-01-04 x"), recordedDate: "20230104" }, upload("2023 Jan 05 y")], true);
+ assert.deepEqual(d.dating.byFrom, { rule: 1, live: 0, title: 0, upload: 1, none: 0 });
+ assert.doesNotMatch(datingAdvice("pref-chan", d, null).join("\n"), /recordedDateTitlePattern/);
+});
+
+test("the patch command is one valid JSON body, and a scan with no dated pair names each member's span", () => {
+ const cmd = recordedDatePatchCommand("pref-chan", TITLE_DATE_SHAPES[0].pattern);
+ const body = JSON.parse(/--json '(.*)'$/.exec(cmd)![1]);
+ assert.deepEqual(body, { slug: "pref-chan", patch: { recordedDateTitlePattern: TITLE_DATE_SHAPES[0].pattern } });
+ assert.equal(
+ noCandidatesAdvice(1, [
+ { slug: "pref-chan", span: { from: "20260303", to: "20261118" } },
+ { slug: "mirror-chan", span: { from: "20230104", to: "20260225" } },
+ ]),
+ "no two members' videos are dated within 1 day(s) of each other (pref-chan 2026-03-03…2026-11-18; mirror-chan 2023-01-04…2026-02-25): check the dates above before reading 0 as \"no copies\".",
+ );
+});
diff --git a/common/lib/copies/dating.ts b/common/lib/copies/dating.ts
@@ -0,0 +1,212 @@
+// THE DATE A COPIES SCAN PAIRS A VIDEO BY (lane copies-dates). Pure.
+//
+// The copies scan (controller/copiesScan.ts) pairs two members' videos when
+// their dates are at most `dateWindowDays` apart, so the date it reads is the
+// whole of its first stage. A video's `upload_date` is the day THAT COPY went
+// up: right for a live stream (the video is the stream) and for a creator's
+// own upload, wrong for a re-upload channel, whose copies go up weeks or years
+// after the streams. The first real scan answered 0 candidates for exactly
+// that: a re-upload channel dated by its uploads (all of them months after the
+// last stream its live mirror held) against the mirror dated by its streams.
+//
+// THE ORDER, best evidence first; a video is dated by the first that gives one:
+// rule the channel's `recordedDate.titlePattern` (lib/recordedDate.ts):
+// the operator's word, as the index derived it or applied here. With
+// a rule set nothing else is read off a title: a title the rule does
+// not read is not guessed past it.
+// live a finished live stream's own day: its `upload_date`, which yt-dlp
+// sets from the stream (equal to the UTC day of `release_timestamp`
+// on 822 of 832 live videos measured, a day apart on the rest — the
+// date window absorbs it).
+// title with NO rule set, a date the channel's titles carry in one of the
+// shapes below, when that shape reads at least TITLE_DATE_MIN_SHARE
+// of the channel's videos that are not live streams (and at least
+// TITLE_DATE_MIN_VIDEOS of them). The one shape is applied to the
+// whole channel, as a rule would be, and the same guards hold: a real
+// day, no later than the upload. The scan then SAYS the rule is not
+// set and gives the exact patch that sets it, so every other reader
+// (coverage, the index) dates the channel the same way.
+// upload anything else: a not-live video's upload day. On a re-upload
+// channel that is the copy's day, so such a video is also looked for
+// by runtime and words (lib/copies/match.ts, runtimeCandidates).
+//
+// A date only proposes candidates. What a pair IS stays the matcher's: words
+// both ways and agreeing runtimes to confirm; a metadata-only pair (one side
+// without words) is held for a bounded wait, never skipped.
+
+import { deriveRecordedDate, recordedDatePatternProblem } from "../recordedDate";
+
+export type DateFrom = "rule" | "live" | "title" | "upload";
+
+export const DATE_FROM_ORDER: readonly DateFrom[] = ["rule", "live", "title", "upload"];
+
+// The title shapes the scan recognises without a rule. Each is a valid
+// recordedDate.titlePattern (the dating test proves it), so the one detected
+// is proposed to the operator verbatim.
+export const TITLE_DATE_SHAPES: readonly { id: string; pattern: string }[] = [
+ // "2023-01-04 …", "2023 01 04 …", "2023 Jan 04 …", "(2023.01.04) …"
+ { id: "leading", pattern: "^\\W{0,3}(?<year>\\d{4})[-\\s._/](?<month>\\d{1,2}|[a-z]{3,9})[-\\s._/](?<day>\\d{1,2})\\b" },
+ // "[Mirror] 2023-01-04 …", "[VOD] 2023.01.04 …"
+ { id: "tagged", pattern: "^\\s*\\[[^\\]]{1,40}\\]\\s*(?<year>\\d{4})[-._/](?<month>\\d{1,2})[-._/](?<day>\\d{1,2})\\b" },
+ // "… stream 2023-01-04 …"
+ { id: "iso", pattern: "\\b(?<year>\\d{4})-(?<month>\\d{2})-(?<day>\\d{2})\\b" },
+ // "… January 4, 2023 …", "… Jan 4th 2023 …"
+ { id: "month-name", pattern: "\\b(?<month>[a-z]{3,9})\\.? (?<day>\\d{1,2})(?:st|nd|rd|th)?,? (?<year>\\d{4})\\b" },
+];
+
+export const TITLE_DATE_MIN_SHARE = 0.5;
+export const TITLE_DATE_MIN_VIDEOS = 3;
+
+export type DatingRecord = {
+ title: string;
+ // YYYYMMDD, or "" when unknown.
+ uploadDate: string;
+ // The channel rule's date (the index's, or applied by the reader).
+ recordedDate?: string;
+ wasLive: boolean;
+};
+
+export type DetectedTitleDate = {
+ pattern: string;
+ // Not-live videos the shape reads, of how many.
+ reads: number;
+ of: number;
+};
+
+const YMD = /^\d{8}$/;
+
+/**
+ * The title shape that dates most of a channel's not-live videos, when it
+ * reads enough of them to stand for the channel; with `best`, the best shape
+ * whatever it reads (for advice), null when none reads one.
+ */
+export function detectTitleDate(
+ records: readonly DatingRecord[],
+ opts: { best?: boolean } = {},
+): DetectedTitleDate | null {
+ const notLive = records.filter((r) => !r.wasLive);
+ if (notLive.length === 0) return null;
+ let top: DetectedTitleDate | null = null;
+ for (const shape of TITLE_DATE_SHAPES) {
+ if (recordedDatePatternProblem(shape.pattern)) continue;
+ const re = new RegExp(shape.pattern, "i");
+ let reads = 0;
+ for (const r of notLive) if (deriveRecordedDate(re, r.title, r.uploadDate || undefined)) reads++;
+ if (reads > 0 && (!top || reads > top.reads)) top = { pattern: shape.pattern, reads, of: notLive.length };
+ }
+ if (!top || opts.best) return top;
+ return top.reads >= TITLE_DATE_MIN_VIDEOS && top.reads >= TITLE_DATE_MIN_SHARE * top.of ? top : null;
+}
+
+/** A video's date and where it came from, by the order above; null: undated. */
+export function dateEvidence(
+ r: DatingRecord,
+ detected: RegExp | null,
+): { date: string; from: DateFrom } | null {
+ if (r.recordedDate && YMD.test(r.recordedDate)) return { date: r.recordedDate, from: "rule" };
+ const upload = YMD.test(r.uploadDate) ? r.uploadDate : null;
+ if (r.wasLive && upload) return { date: upload, from: "live" };
+ if (!r.wasLive && detected) {
+ const d = deriveRecordedDate(detected, r.title, upload ?? undefined);
+ if (d) return { date: d, from: "title" };
+ }
+ return upload ? { date: upload, from: "upload" } : null;
+}
+
+export type ChannelDating = {
+ videos: number;
+ byFrom: Record<DateFrom | "none", number>;
+ // The span of the dates the scan pairs by (YYYYMMDD), null: none dated.
+ span: { from: string; to: string } | null;
+ // Whether the channel's config sets a recordedDate rule.
+ ruleSet: boolean;
+ // The title shape the scan dated the channel by (no rule set).
+ detectedPattern?: string;
+};
+
+export type DatedChannel<T extends DatingRecord> = {
+ dating: ChannelDating;
+ dated: { record: T; date: string | null; from: DateFrom | null }[];
+ // With no rule set and no shape detected: the best shape and what it reads,
+ // for the advice (null when no shape reads any title).
+ bestShape: DetectedTitleDate | null;
+};
+
+/** One channel's videos, each dated by the order above, with the tally. */
+export function dateChannel<T extends DatingRecord>(records: readonly T[], ruleSet: boolean): DatedChannel<T> {
+ const detected = ruleSet ? null : detectTitleDate(records);
+ const re = detected ? new RegExp(detected.pattern, "i") : null;
+ const byFrom: Record<DateFrom | "none", number> = { rule: 0, live: 0, title: 0, upload: 0, none: 0 };
+ let from: string | null = null;
+ let to: string | null = null;
+ const dated = records.map((record) => {
+ const e = dateEvidence(record, re);
+ byFrom[e?.from ?? "none"]++;
+ if (e) {
+ if (!from || e.date < from) from = e.date;
+ if (!to || e.date > to) to = e.date;
+ }
+ return { record, date: e?.date ?? null, from: e?.from ?? null };
+ });
+ return {
+ dating: {
+ videos: records.length,
+ byFrom,
+ span: from && to ? { from, to } : null,
+ ruleSet,
+ ...(detected ? { detectedPattern: detected.pattern } : {}),
+ },
+ dated,
+ bestShape: ruleSet || detected ? null : detectTitleDate(records, { best: true }),
+ };
+}
+
+/** The ops call that sets a channel's recorded-date rule to `pattern`. */
+export function recordedDatePatchCommand(slug: string, pattern: string): string {
+ return `pnpm ops channel-config --json '${JSON.stringify({ slug, patch: { recordedDateTitlePattern: pattern } })}'`;
+}
+
+const ymdShow = (d: string) => `${d.slice(0, 4)}-${d.slice(4, 6)}-${d.slice(6, 8)}`;
+
+/**
+ * What the scan says about a channel's dates, as sentences: the rule it lacks
+ * (with the exact patch), the videos it could date only by their upload.
+ */
+export function datingAdvice(slug: string, d: DatedChannel<DatingRecord>, runtimeSearch: string | null): string[] {
+ const out: string[] = [];
+ const { dating } = d;
+ if (dating.detectedPattern) {
+ out.push(
+ `${slug}: ${dating.byFrom.title} of ${dating.videos} videos are dated by a date their titles carry; the channel ` +
+ `sets no recordedDate rule, so the scan read the shape itself. Set it, so the index and coverage date them the ` +
+ `same way: ${recordedDatePatchCommand(slug, dating.detectedPattern)}`,
+ );
+ }
+ if (dating.byFrom.upload > 0) {
+ let s =
+ `${slug}: ${dating.byFrom.upload} of ${dating.videos} videos have only an upload date (not a live stream, no ` +
+ `date in the title${dating.ruleSet ? " the channel's rule reads" : ""}); on a channel of re-uploads that is the ` +
+ `day of the copy, not of the stream.`;
+ if (runtimeSearch) s += ` ${runtimeSearch}`;
+ // With a rule set, or one proposed above, that is the channel's shape:
+ // these titles simply carry none, and nothing more is proposed.
+ if (!dating.ruleSet && !dating.detectedPattern) {
+ s += d.bestShape
+ ? ` The closest title shape reads ${d.bestShape.reads} of ${d.bestShape.of}; if the titles carry the ` +
+ `stream's day, set a rule: ${recordedDatePatchCommand(slug, d.bestShape.pattern)}`
+ : ` If the titles carry the stream's day, set a rule: ${recordedDatePatchCommand(slug, "<regex with groups year, month, day>")}`;
+ }
+ out.push(s);
+ }
+ if (dating.byFrom.none > 0) out.push(`${slug}: ${dating.byFrom.none} of ${dating.videos} videos have no date at all.`);
+ return out;
+}
+
+/** The sentence for a scan with no date candidate at all, naming each member's span. */
+export function noCandidatesAdvice(
+ windowDays: number,
+ spans: readonly { slug: string; span: ChannelDating["span"] }[],
+): string {
+ const parts = spans.map((s) => `${s.slug} ${s.span ? `${ymdShow(s.span.from)}…${ymdShow(s.span.to)}` : "undated"}`);
+ return `no two members' videos are dated within ${windowDays} day(s) of each other (${parts.join("; ")}): check the dates above before reading 0 as "no copies".`;
+}
diff --git a/common/lib/copies/file.ts b/common/lib/copies/file.ts
@@ -15,6 +15,7 @@
// the decisions only ever act on pairs the scan lists.
import type { CopyLink, TextEvidence } from "./match";
+import type { ChannelDating, DateFrom } from "./dating";
export const COPIES_DIRNAME = "copies";
export const COPIES_FORMAT = "archilyzer-copies";
@@ -28,6 +29,9 @@ export type CopyMember = {
title: string;
duration: number;
date: string | null;
+ // Where `date` came from: the channel's rule, the live stream's own day, a
+ // date the titles carry, or the upload (lib/copies/dating.ts).
+ dateFrom?: DateFrom | null;
};
export type CopyPairRecord = {
@@ -43,7 +47,11 @@ export type CopyPairRecord = {
evidence: {
// What decided the link: the words, or (no text on one side) metadata.
kind: "text" | "metadata";
- dateDeltaDays: number;
+ // How the pair was proposed: dated within the window, or by runtime (one
+ // side had no date to go by; such a pair is always decided by its words).
+ via?: "date" | "runtime";
+ // null: one side is undated.
+ dateDeltaDays: number | null;
durationOk: boolean;
text?: TextEvidence;
};
@@ -65,6 +73,11 @@ export type CopiesTotals = {
// Candidates the words said were different recordings.
rejected: number;
withinChannel: number;
+ // The runtime search (lib/copies/match.ts runtimeCandidates): videos
+ // searched, the candidates it proposed, those the words rejected, and the
+ // videos left unsearched by its cap. The date stage's figures above do not
+ // include them.
+ runtime?: { searched: number; candidates: number; rejected: number; capped: number };
};
export type CopiesFile = {
@@ -84,6 +97,12 @@ export type CopiesFile = {
};
pairs: CopyPairRecord[];
totals: CopiesTotals;
+ // How each member's videos were dated, by channel.
+ dating?: Record<string, ChannelDating>;
+ // What the scan says about its own inputs: a channel lacking its
+ // recorded-date rule (with the exact patch), videos it could date only by
+ // their upload, a scan whose members' dates never meet.
+ advice?: string[];
};
// Who gave a decision: the caller's word, as judge-trending takes it (the
diff --git a/common/lib/copies/match.test.ts b/common/lib/copies/match.test.ts
@@ -6,6 +6,7 @@ import {
classifyCandidate,
copyCandidates,
cuesToWords,
+ runtimeCandidates,
textEvidence,
COPY_PHRASE_WORDS,
type CopyRecord,
@@ -205,3 +206,48 @@ test("the adjacent day's stream with the closer runtime is not linked over the t
assert.deepEqual(classifyCandidate(nextDay, null), { link: "metadata" });
assert.equal(classifyCandidate(sameDay, null), null);
});
+
+test("the runtime search: only for a video its date cannot pair, both sides with words, nearest runtimes first, bounded", async () => {
+ const up = (channel: string, dir: string, duration: number): CopyRecord => ({ ...rec(channel, dir, "20260310", duration), dateFrom: "upload" });
+ const lv = (dir: string, date: string, duration: number): CopyRecord => ({ ...rec("mirror-chan", dir, date, duration), dateFrom: "live" });
+ const records = [
+ up("pref-chan", "p1", 7200),
+ up("pref-chan", "p2", 7200), // no words
+ up("pref-chan", "p3", 7200), // already paired by date
+ up("pref-chan", "p4", 7205), // same channel: never its own candidate
+ lv("m1", "20230101", 7260),
+ lv("m2", "20230102", 7100),
+ lv("m3", "20230103", 7400), // runtimes apart
+ lv("m4", "20230104", 7210),
+ lv("m5", "20230105", 7190),
+ ];
+ const noWords = new Set(["pref-chan/p2"]);
+ const hasText = (r: CopyRecord) => !noWords.has(`${r.channel}/${r.dir}`);
+ const dated = new Set(["pref-chan/p3"]);
+ const s = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3 });
+ assert.deepEqual(
+ s.candidates.map((c) => [c.a.dir, c.b.dir, c.via, c.durationOk]),
+ [
+ ["p1", "m5", "runtime", true],
+ ["p1", "m4", "runtime", true],
+ ["p1", "m1", "runtime", true],
+ ["p4", "m4", "runtime", true],
+ ["p4", "m5", "runtime", true],
+ ["p4", "m1", "runtime", true],
+ ],
+ "nearest three each; never p2 (no words), p3 (paired by date), m3 (runtimes apart) or p1 with p4",
+ );
+ assert.equal(s.searched, 2, "p1 and p4; a live mirror's own day pairs it, so it is never searched from");
+ // The scan's cap: once reached, the rest are counted, not searched.
+ const capped = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3, maxPairs: 2 });
+ assert.equal(capped.candidates.length, 2);
+ assert.deepEqual([capped.searched, capped.capped], [1, 1]);
+ // A channel with a recordedDate rule is dated by it and never searched from.
+ const ruled = await runtimeCandidates(GROUP, records, { hasText, dated, perVideo: 3, ruled: new Set(["pref-chan"]) });
+ assert.deepEqual([ruled.candidates.length, ruled.searched, ruled.capped], [0, 0, 0]);
+ // A runtime candidate has nothing but its runtime: without words, no pair at all.
+ assert.equal(classifyCandidate(s.candidates[0], null), null);
+ assert.deepEqual(classifyCandidate(s.candidates[0], textEvidence(stream(5, 3000), shift(stream(5, 3000), 30))), {
+ link: "confirmed",
+ });
+});
diff --git a/common/lib/copies/match.ts b/common/lib/copies/match.ts
@@ -37,6 +37,7 @@
// reads a time across copies.
import type { SourceGroup } from "./settings";
+import type { DateFrom } from "./dating";
export const COPY_PHRASE_WORDS = 6;
export const COPY_PROBES = 40;
@@ -66,6 +67,8 @@ export type CopyRecord = {
duration: number;
// YYYYMMDD, or null when undated.
date: string | null;
+ // Where `date` came from (lib/copies/dating.ts); absent: not said.
+ dateFrom?: DateFrom | null;
};
export type Word = { w: string; t: number };
@@ -112,8 +115,13 @@ export type CopyLink = "confirmed" | "metadata" | "part-of" | "overlaps";
export type CopyCandidate = {
a: CopyRecord;
b: CopyRecord;
- dateDeltaDays: number;
+ // Days between the two dates; null when one side is undated (a runtime
+ // candidate).
+ dateDeltaDays: number | null;
durationOk: boolean;
+ // How it was proposed: dated within the window (the default), or — one side
+ // dated only by its upload — by runtime, for the words to decide.
+ via?: "date" | "runtime";
};
export type CopyClassification = { link: CopyLink; part?: "a" | "b" } | null;
@@ -315,6 +323,7 @@ export function copyCandidates(
b,
dateDeltaDays: Math.abs(dd),
durationOk: runtimesAgree(a.duration, b.duration, group),
+ via: "date",
});
}
}
@@ -322,6 +331,119 @@ export function copyCandidates(
return out.sort((x, y) => order(x.a, y.a) || order(x.b, y.b));
}
+// THE RUNTIME SEARCH, for a video of a channel with NO recordedDate rule whose
+// date says nothing about its stream (lib/copies/dating.ts: only an upload
+// date, or none) and which found no candidate by date (a channel with a rule
+// is dated by the operator's word, and is never searched from, as before): the other members' videos whose runtimes agree, nearest
+// first, at most COPY_RUNTIME_PER_VIDEO of them, and at most
+// COPY_RUNTIME_MAX_PAIRS such pairs in one scan. Both sides must have words:
+// a runtime alone is no evidence of anything, so a runtime candidate is
+// decided by its words or dropped (classifyCandidate), never held. The bound:
+// at most min(8 × such videos, 2,000) text comparisons per scan, each about
+// 0.15 s of one core measured on 4-hour streams — five minutes at worst.
+export const COPY_RUNTIME_PER_VIDEO = 8;
+export const COPY_RUNTIME_MAX_PAIRS = 2000;
+
+export type RuntimeSearch = {
+ candidates: CopyCandidate[];
+ // Videos searched (undated or upload-dated, with words and a runtime, no date candidate).
+ searched: number;
+ // Such videos left unsearched once the scan's cap was reached.
+ capped: number;
+};
+
+const needsRuntimeSearch = (r: CopyRecord, ruled: ReadonlySet<string>) =>
+ (!r.date || r.dateFrom === "upload") && !ruled.has(r.channel);
+
+/** Whether any record would be searched by runtime (the scan reads no cue file otherwise). */
+export function wantsRuntimeSearch(records: readonly CopyRecord[], ruled: ReadonlySet<string>): boolean {
+ return records.some((r) => needsRuntimeSearch(r, ruled));
+}
+
+/**
+ * Runtime candidates for the videos whose date cannot pair them (above).
+ * `hasText` says which videos have words; `dated` holds the keys
+ * (`<channel>/<dir>`) of videos that already have a date candidate; `ruled`
+ * the channels with a recordedDate rule (never searched from); `breathe` is
+ * awaited before each searched video (the scan yields to the event loop there).
+ * Deterministic: by the searched video's rank and dir, then runtime distance.
+ */
+export async function runtimeCandidates(
+ group: Pick<SourceGroup, "channels" | "durationToleranceSeconds" | "durationToleranceRatio">,
+ records: readonly CopyRecord[],
+ opts: {
+ hasText: (r: CopyRecord) => boolean;
+ dated: ReadonlySet<string>;
+ ruled?: ReadonlySet<string>;
+ perVideo?: number;
+ maxPairs?: number;
+ breathe?: () => Promise<void>;
+ },
+): Promise<RuntimeSearch> {
+ const ruled = opts.ruled ?? new Set<string>();
+ const perVideo = opts.perVideo ?? COPY_RUNTIME_PER_VIDEO;
+ const maxPairs = opts.maxPairs ?? COPY_RUNTIME_MAX_PAIRS;
+ const rank = new Map(group.channels.map((c, i) => [c, i]));
+ const order = (x: CopyRecord, y: CopyRecord) =>
+ rank.get(x.channel)! - rank.get(y.channel)! || (x.dir < y.dir ? -1 : x.dir > y.dir ? 1 : 0);
+ const keyOf = (r: CopyRecord) => `${r.channel}/${r.dir}`;
+ const pool = records
+ .filter((r) => rank.has(r.channel) && r.duration > 0 && opts.hasText(r))
+ .sort((x, y) => x.duration - y.duration || order(x, y));
+ const wanted = pool.filter((r) => needsRuntimeSearch(r, ruled) && !opts.dated.has(keyOf(r))).sort(order);
+ const seen = new Set<string>();
+ const out: CopyCandidate[] = [];
+ let searched = 0;
+ let capped = 0;
+ for (const r of wanted) {
+ if (out.length >= maxPairs) {
+ capped++;
+ continue;
+ }
+ await opts.breathe?.();
+ searched++;
+ // The pool is sorted by runtime: walk out from r's place both ways.
+ let lo = 0;
+ let hi = pool.length;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (pool[mid].duration < r.duration) lo = mid + 1;
+ else hi = mid;
+ }
+ const near: CopyRecord[] = [];
+ let i = lo - 1;
+ let j = lo;
+ const ok = (o: CopyRecord) => o.channel !== r.channel && runtimesAgree(r.duration, o.duration, group);
+ while (near.length < perVideo && (i >= 0 || j < pool.length)) {
+ const left = i >= 0 ? pool[i] : null;
+ const right = j < pool.length ? pool[j] : null;
+ const inLeft = left !== null && runtimesAgree(r.duration, left.duration, group);
+ const inRight = right !== null && runtimesAgree(r.duration, right.duration, group);
+ if (!inLeft && !inRight) break;
+ const takeLeft = inLeft && (!inRight || r.duration - left!.duration <= right!.duration - r.duration);
+ const o = takeLeft ? left! : right!;
+ if (takeLeft) i--;
+ else j++;
+ if (ok(o)) near.push(o);
+ }
+ for (const o of near) {
+ if (out.length >= maxPairs) break;
+ const [a, b] = order(r, o) <= 0 ? [r, o] : [o, r];
+ const key = `${keyOf(a)}\u0000${keyOf(b)}`;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ out.push({
+ a,
+ b,
+ dateDeltaDays: a.date && b.date ? Math.abs(dayNumber(a.date) - dayNumber(b.date)) : null,
+ durationOk: true,
+ via: "runtime",
+ });
+ }
+ }
+ return { candidates: out, searched, capped };
+}
+
/**
* What a candidate is, given its text evidence (null = one side has no text).
* With words on both sides they decide, and CONFIRMED needs the runtimes to
@@ -346,5 +468,7 @@ export function classifyCandidate(c: CopyCandidate, text: TextEvidence | null):
return null;
}
}
+ // A runtime candidate has nothing but its runtime: no words, no pair.
+ if (c.via === "runtime") return null;
return c.durationOk ? { link: "metadata" } : null;
}
diff --git a/common/lib/operationUnit.test.ts b/common/lib/operationUnit.test.ts
@@ -47,6 +47,7 @@ function files(entries: string[]): VideoFiles {
audioFiles: entries.filter((e) => e.startsWith("audio.")),
partAudioFiles: [],
entries,
+ physicalEntries: entries,
};
}
diff --git a/common/lib/storedText-read.d.mts b/common/lib/storedText-read.d.mts
@@ -0,0 +1,14 @@
+// Types for ./storedText-read.mjs: the stored-text read path in plain JS.
+import type { Stats } from "node:fs";
+export const STORED_TEXT_SUFFIX: ".zst";
+export function isStoredTextName(name: string): boolean;
+export function plainNameOf(name: string): string | null;
+export function logicalEntries(entries: Iterable<string>): string[];
+export function readdirLogical(dir: string): Promise<string[]>;
+export function frameContentSize(head: Uint8Array): number | null;
+export function decodeStoredBytes(bytes: Buffer, label?: string): Promise<Buffer>;
+export function readStoredText(dir: string, name: string): Promise<Buffer>;
+export function readStoredText(dir: string, name: string, encoding: "utf8"): Promise<string>;
+export function readStoredTextHead(dir: string, name: string, bytes: number): Promise<Buffer>;
+export function statStoredText(dir: string, name: string): Promise<{ form: "plain" | "zst"; stats: Stats }>;
+export function storedTextLogicalSize(dir: string, name: string): Promise<number>;
diff --git a/common/lib/storedText-read.mjs b/common/lib/storedText-read.mjs
@@ -0,0 +1,206 @@
+// STORED TEXT, THE READ PATH IN PLAIN JS — for umtool's bare-node scripts
+// (report-to-video's cue source, the clip words, the ingredients rail), which
+// cannot import lib/storedText-server.ts. The same rules (lib/storedText.ts):
+// a declared file — the raw live chat, or a caption track
+// `transcript.<lang>.vtt` — may be on disk as `<name>.zst`, one zstd frame
+// whose header carries the content size; THE PLAIN FILE, WHEN PRESENT, IS THE
+// TRUTH; a matching listing is LOGICAL (the `.zst` reported under its plain
+// name, once). storedText.mjs-twin.test.ts holds this module and the TS one
+// equal (names, decode, head, sizes); change one, change the other.
+// SERVER-ONLY (node:fs, node:zlib). Read only: nothing here writes.
+
+import { open, readdir, readFile, stat } from "node:fs/promises";
+import path from "node:path";
+import zlib from "node:zlib";
+import { assertZstdSupport } from "./zstdSupport.mjs";
+
+// A bare-node script that may read a stored file refuses to start on a Node
+// without zstd (REVIEW-1 F3): asked when this module loads.
+assertZstdSupport("this script (a reader of stored text)");
+
+export const STORED_TEXT_SUFFIX = ".zst";
+const LIVE_CHAT = "transcript.live_chat.json";
+const CAPTION_RE = /^transcript\.(?!tmp-\d+\.vtt$)[^.]+\.vtt$/;
+
+/** @param {string} name */
+export function isStoredTextName(name) {
+ return name === LIVE_CHAT || CAPTION_RE.test(name);
+}
+
+/** @param {string} name */
+export function plainNameOf(name) {
+ if (!name.endsWith(STORED_TEXT_SUFFIX)) return null;
+ const plain = name.slice(0, -STORED_TEXT_SUFFIX.length);
+ return isStoredTextName(plain) ? plain : null;
+}
+
+/** @param {Iterable<string>} entries */
+export function logicalEntries(entries) {
+ const out = [];
+ const seen = new Set();
+ for (const e of entries) {
+ const n = plainNameOf(e) ?? e;
+ if (seen.has(n)) continue;
+ seen.add(n);
+ out.push(n);
+ }
+ return out;
+}
+
+/** @param {string} dir */
+export async function readdirLogical(dir) {
+ return logicalEntries(await readdir(dir).catch(() => []));
+}
+
+const ZSTD_MAGIC = 0xfd2fb528;
+
+/** The content size a zstd frame header declares, or null. @param {Uint8Array} head */
+export function frameContentSize(head) {
+ if (head.length < 5) return null;
+ const dv = new DataView(head.buffer, head.byteOffset, head.byteLength);
+ if (dv.getUint32(0, true) !== ZSTD_MAGIC) return null;
+ const fhd = head[4];
+ const fcsFlag = fhd >> 6;
+ const singleSegment = (fhd >> 5) & 1;
+ const dictFlag = fhd & 3;
+ if (fcsFlag === 0 && !singleSegment) return null;
+ const off = 5 + (singleSegment ? 0 : 1) + [0, 1, 2, 4][dictFlag];
+ const fcsBytes = fcsFlag === 0 ? 1 : [1, 2, 4, 8][fcsFlag];
+ if (head.length < off + fcsBytes) return null;
+ if (fcsBytes === 1) return head[off];
+ if (fcsBytes === 2) return dv.getUint16(off, true) + 256;
+ if (fcsBytes === 4) return dv.getUint32(off, true);
+ const n = dv.getUint32(off + 4, true) * 2 ** 32 + dv.getUint32(off, true);
+ return Number.isSafeInteger(n) ? n : null;
+}
+
+function assertZstd() {
+ if (typeof zlib.zstdDecompress !== "function" || typeof zlib.createZstdDecompress !== "function") {
+ throw new Error(`stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`);
+ }
+}
+
+const isEnoent = (err) => err?.code === "ENOENT" || err?.code === "ENOTDIR";
+const enoent = (dir, name) =>
+ Object.assign(new Error(`ENOENT: no such file, '${path.join(dir, name)}' (nor its stored form)`), { code: "ENOENT" });
+
+/** A stored file's bytes decoded, its checksum and length checked. @param {Buffer} bytes @param {string} label */
+export async function decodeStoredBytes(bytes, label = "stored text") {
+ assertZstd();
+ const want = frameContentSize(bytes.subarray(0, 18));
+ if (want === null) throw new Error(`${label}: not a whole stored-text frame (no content size in the frame header)`);
+ const out = await new Promise((resolve, reject) =>
+ zlib.zstdDecompress(bytes, { maxOutputLength: Math.max(1, want + 1) }, (err, res) => (err ? reject(err) : resolve(res))),
+ ).catch((err) => {
+ throw new Error(`${label}: not a whole stored-text frame (${err.message})`);
+ });
+ if (out.length !== want) throw new Error(`${label}: not a whole stored-text frame (decoded ${out.length} bytes, header says ${want})`);
+ return out;
+}
+
+/**
+ * The plain file's bytes when it opens; else (a declared name) the stored form
+ * decoded; ENOENT when neither opens.
+ * @param {string} dir @param {string} name @param {"utf8"} [encoding]
+ */
+export async function readStoredText(dir, name, encoding) {
+ try {
+ return encoding ? await readFile(path.join(dir, name), encoding) : await readFile(path.join(dir, name));
+ } catch (err) {
+ if (!isEnoent(err) || !isStoredTextName(name)) throw err;
+ }
+ const storedPath = path.join(dir, name + STORED_TEXT_SUFFIX);
+ let bytes;
+ try {
+ bytes = await readFile(storedPath);
+ } catch (err) {
+ if (isEnoent(err)) throw enoent(dir, name);
+ throw err;
+ }
+ const out = await decodeStoredBytes(bytes, storedPath);
+ return encoding ? out.toString(encoding) : out;
+}
+
+/** The first `bytes` bytes as the plain file has them (decoded from a stored form). */
+export async function readStoredTextHead(dir, name, bytes) {
+ try {
+ const fh = await open(path.join(dir, name), "r");
+ try {
+ const buf = Buffer.alloc(bytes);
+ const { bytesRead } = await fh.read(buf, 0, bytes, 0);
+ return buf.subarray(0, bytesRead);
+ } finally {
+ await fh.close();
+ }
+ } catch (err) {
+ if (!isEnoent(err) || !isStoredTextName(name)) throw err;
+ }
+ assertZstd();
+ const storedPath = path.join(dir, name + STORED_TEXT_SUFFIX);
+ let fh;
+ try {
+ fh = await open(storedPath, "r");
+ } catch (err) {
+ if (isEnoent(err)) throw enoent(dir, name);
+ throw err;
+ }
+ const src = fh.createReadStream();
+ const dec = zlib.createZstdDecompress();
+ const out = [];
+ let n = 0;
+ try {
+ await new Promise((resolve, reject) => {
+ dec.on("data", (chunk) => {
+ if (n >= bytes) return;
+ out.push(chunk);
+ n += chunk.length;
+ if (n >= bytes) {
+ src.unpipe(dec);
+ src.destroy();
+ dec.destroy();
+ resolve();
+ }
+ });
+ dec.on("end", resolve);
+ dec.on("error", (err) => reject(new Error(`${storedPath}: not a whole stored-text frame (${err.message})`)));
+ src.on("error", reject);
+ src.pipe(dec);
+ });
+ } finally {
+ src.destroy();
+ await fh.close().catch(() => {});
+ }
+ return Buffer.concat(out).subarray(0, bytes);
+}
+
+/** `stat` of the plain name, else of its stored form (which carries the plain file's times). */
+export async function statStoredText(dir, name) {
+ try {
+ return { form: "plain", stats: await stat(path.join(dir, name)) };
+ } catch (err) {
+ if (!isEnoent(err) || !isStoredTextName(name)) throw err;
+ }
+ try {
+ return { form: "zst", stats: await stat(path.join(dir, name + STORED_TEXT_SUFFIX)) };
+ } catch (err) {
+ if (isEnoent(err)) throw enoent(dir, name);
+ throw err;
+ }
+}
+
+/** The LOGICAL size: the plain file's, or the stored frame header's content size. */
+export async function storedTextLogicalSize(dir, name) {
+ const s = await statStoredText(dir, name);
+ if (s.form === "plain") return s.stats.size;
+ const file = path.join(dir, name + STORED_TEXT_SUFFIX);
+ const fh = await open(file, "r");
+ try {
+ const head = Buffer.alloc(18);
+ const { bytesRead } = await fh.read(head, 0, 18, 0);
+ const n = frameContentSize(head.subarray(0, bytesRead));
+ if (n === null) throw new Error(`${file}: not a whole stored-text frame (no content size in the frame header)`);
+ return n;
+ } finally {
+ await fh.close();
+ }
+}
diff --git a/common/lib/storedText-read.test.ts b/common/lib/storedText-read.test.ts
@@ -0,0 +1,69 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, rm, 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-read.test.ts
+//
+// THE PLAIN-JS TWIN (lib/storedText-read.mjs, for umtool's bare-node scripts)
+// AND THE TS READ PATH (lib/storedText.ts, lib/storedText-server.ts) GIVE THE
+// SAME ANSWERS: which names are declared, the logical listing, the decoded
+// bytes and head, the logical size, and a truncated frame refused. Change one,
+// change the other. Temp dirs, synthetic names.
+
+import * as ts from "./storedText";
+import * as tsServer from "./storedText-server";
+import * as mjs from "./storedText-read.mjs";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-read-twin-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const NAMES = [
+ "transcript.live_chat.json",
+ "transcript.en.vtt",
+ "transcript.en-orig.vtt",
+ "transcript.es.vtt",
+ "transcript.tmp-77.vtt",
+ "transcript.json",
+ "transcript.cues.json",
+ "metadata.info.json",
+ "transcript.en.vtt.part",
+ "transcript.en.srv3",
+];
+
+test("the declared names and the logical listing are the same in both", () => {
+ for (const n of NAMES) {
+ assert.equal(mjs.isStoredTextName(n), ts.isStoredTextName(n), n);
+ assert.equal(mjs.plainNameOf(`${n}.zst`), ts.plainNameOf(`${n}.zst`), n);
+ }
+ const listing = [...NAMES, ...NAMES.map((n) => `${n}.zst`), "x.zst"];
+ assert.deepEqual(mjs.logicalEntries(listing), ts.logicalEntries(listing));
+});
+
+test("the read, the head, the stat and the logical size are the same in both", async () => {
+ const dir = path.join(ROOT, "v1");
+ await mkdir(dir, { recursive: true });
+ const body = "WEBVTT\n\n" + "00:00:00.000 --> 00:00:01.000\nline é\n\n".repeat(400);
+ await writeFile(path.join(dir, "transcript.en.vtt.zst"), await tsServer.encodeStoredBytes(Buffer.from(body)));
+ await writeFile(path.join(dir, "transcript.es.vtt"), body);
+ for (const n of ["transcript.en.vtt", "transcript.es.vtt"]) {
+ assert.equal(await mjs.readStoredText(dir, n, "utf8"), await tsServer.readStoredText(dir, n, "utf8"), n);
+ assert.deepEqual(await mjs.readStoredTextHead(dir, n, 2048), await tsServer.readStoredTextHead(dir, n, 2048), n);
+ assert.equal(await mjs.storedTextLogicalSize(dir, n), await tsServer.storedTextLogicalSize(dir, n), n);
+ assert.equal((await mjs.statStoredText(dir, n)).stats.mtimeMs, (await tsServer.statStoredText(dir, n)).stats.mtimeMs, n);
+ }
+ assert.equal(await mjs.readStoredText(dir, "transcript.en.vtt", "utf8"), body);
+ assert.deepEqual(await mjs.readdirLogical(dir), await tsServer.readdirLogical(dir));
+ await assert.rejects(mjs.readStoredText(dir, "transcript.de.vtt"), { code: "ENOENT" });
+});
+
+test("a truncated stored frame is refused by both, never read short", async () => {
+ const dir = path.join(ROOT, "v2");
+ await mkdir(dir, { recursive: true });
+ const whole = await tsServer.encodeStoredBytes(Buffer.from("WEBVTT\n\n".repeat(5000)));
+ await writeFile(path.join(dir, "transcript.en.vtt.zst"), whole.subarray(0, Math.floor(whole.length / 2)));
+ await assert.rejects(mjs.readStoredText(dir, "transcript.en.vtt"), /not a whole stored-text frame/);
+ await assert.rejects(tsServer.readStoredText(dir, "transcript.en.vtt"), /not a whole stored-text frame/);
+});
diff --git a/common/lib/storedText-server.ts b/common/lib/storedText-server.ts
@@ -59,12 +59,31 @@ export function assertZstdAvailable(): void {
typeof z.createZstdCompress !== "function" ||
typeof z.createZstdDecompress !== "function"
) {
- throw new Error(
+ throw new StoredTextUnsupportedError(
`stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`,
);
}
}
+// This Node cannot read a stored file at all (no zstd). Every process asks at
+// boot (lib/zstdSupport.mjs) and refuses to start; this is the backstop.
+export class StoredTextUnsupportedError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "StoredTextUnsupportedError";
+ }
+}
+
+// A STORED FILE THAT IS THERE AND CANNOT BE READ — a frame that does not
+// decode, or a Node without zstd — is an ERROR, never "no text" (REVIEW-1 F3,
+// captions lane): a reader that skips it as it skips a missing file would let
+// the index write a record with no cues over a readable one, or a lane read
+// the video as needing a transcript. Readers that tolerate a missing or
+// malformed track RETHROW these.
+export function isStoredTextReadError(err: unknown): boolean {
+ return err instanceof StoredTextCorruptError || err instanceof StoredTextUnsupportedError;
+}
+
export const STORED_TEXT_LEVEL = 9;
// The compressor's options for a source of `size` bytes: level 9, checksum on,
@@ -198,6 +217,63 @@ export async function readStoredText(
return encoding ? out.toString(encoding) : out;
}
+// THE HEAD of a declared file: its first `bytes` bytes as the plain file has
+// them — read from the plain file when it opens, else DECODED from the stored
+// form (the first bytes of a zstd frame are not text: a sniff of them would
+// answer wrong, not absent — the caption provenance sniff, the word-timing
+// sniff). Only the head is decoded; the frame's checksum is checked by a whole
+// read, not here. ENOENT when neither form opens.
+export async function readStoredTextHead(dir: string, name: string, bytes: number): Promise<Buffer> {
+ try {
+ const fh = await open(path.join(dir, name), "r");
+ try {
+ const buf = Buffer.alloc(bytes);
+ const { bytesRead } = await fh.read(buf, 0, bytes, 0);
+ return buf.subarray(0, bytesRead);
+ } finally {
+ await fh.close();
+ }
+ } catch (err) {
+ if (!isEnoent(err) || !isStoredTextName(name)) throw err;
+ }
+ const storedPath = path.join(dir, storedNameOf(name));
+ let fh;
+ try {
+ fh = await open(storedPath, "r");
+ } catch (err) {
+ if (isEnoent(err)) throw enoent(dir, name);
+ throw err;
+ }
+ const src = fh.createReadStream();
+ const dec = createStoredTextDecompressor();
+ const out: Buffer[] = [];
+ let n = 0;
+ try {
+ await new Promise<void>((resolve, reject) => {
+ const finish = () => resolve();
+ dec.on("data", (chunk: Buffer) => {
+ if (n >= bytes) return;
+ out.push(chunk);
+ n += chunk.length;
+ if (n >= bytes) {
+ src.unpipe(dec);
+ src.destroy();
+ dec.destroy();
+ finish();
+ }
+ });
+ dec.on("end", finish);
+ dec.on("error", (err) => reject(new StoredTextCorruptError(storedPath, err.message)));
+ src.on("error", reject);
+ src.pipe(dec);
+ });
+ } finally {
+ src.destroy();
+ await fh.close().catch(() => {});
+ }
+ return Buffer.concat(out).subarray(0, bytes);
+}
+
export type StoredTextStat = {
// Which form answered.
form: "plain" | "zst";
diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts
@@ -45,7 +45,9 @@ import {
import { keptChatCaptureName } from "./mediaTier";
import { onDrive, stalledLocationForPath } from "./storageHealth";
import { LIVE_RECORDING_FILENAME } from "./liveCapture";
-import { isStoredTextName, plainNameOf, storedNameOf } from "./storedText";
+import { isStoredCaptionName, isStoredTextName, plainNameOf, storedNameOf } from "./storedText";
+import { parseVtt } from "./vtt";
+import { unpinAfterPickDeleted } from "./transcriptPin-server";
import {
StoredTextCorruptError,
createStoredTextCompressor,
@@ -55,10 +57,50 @@ import {
// Remove `name` in both forms (any name: for one that is not declared, its
// `.zst` sibling is not this module's and is removed only if it is there —
-// nothing else ever writes one). Missing is not an error.
-export async function removeStoredText(videoDir: string, name: string): Promise<void> {
- await removeMediaFile(videoDir, storedNameOf(name));
- await removeMediaFile(videoDir, name);
+// nothing else ever writes one) AND every leftover of a stopped run on it — a
+// temp, and above all a set-aside original (`.<name>.retire-…`), which is a
+// whole copy: left behind, the next compress run would find the name free and
+// could bring the deleted file back (REVIEW-1 F2, captions lane). Under the
+// file's lock, so no run of ours is between its steps while the file goes;
+// a run that holds it is waited for (a few seconds), then this throws and
+// nothing is removed. Missing is not an error.
+//
+// A REFUSAL, NEVER A THROW, when it cannot take the lock (REVIEW-2 N2): a run
+// that holds it past the wait, or a disk so full the lock's few bytes do not
+// fit. Then NOTHING is removed and `{refused}` says why; the caller reports it.
+export type RemoveStoredTextOutcome = { removed: true } | { refused: string };
+
+export async function removeStoredText(videoDir: string, name: string): Promise<RemoveStoredTextOutcome> {
+ for (let attempt = 0; ; attempt++) {
+ let done: boolean;
+ try {
+ done = await withFileLock(videoDir, name, false, async () => {
+ await removeMediaFile(videoDir, storedNameOf(name));
+ await removeMediaFile(videoDir, name);
+ await removeLeftoversOf(videoDir, name);
+ return true;
+ });
+ } catch (err) {
+ if (err instanceof LockUnavailableError) return { refused: `${name} not deleted: ${err.message}` };
+ throw err;
+ }
+ if (done) return { removed: true };
+ if (attempt >= 40) {
+ return { refused: `${name} not deleted: it is being compressed or restored right now — try again in a moment` };
+ }
+ await new Promise((r) => setTimeout(r, 250));
+ }
+}
+
+// Every leftover of a run on `name` in the video dir — temps and set-asides,
+// whoever named them — each through removeMediaFile (a set-aside may be a
+// tier link: its bytes go too). Only for a deleter: the file is being removed
+// on purpose, so a copy of it must not survive to be adopted later.
+async function removeLeftoversOf(videoDir: string, name: string): Promise<void> {
+ const re = leftoverRes(name);
+ for (const e of await readdir(videoDir).catch(() => [] as string[])) {
+ if (re.temp.test(e) || re.retire.test(e)) await removeMediaFile(videoDir, e);
+ }
}
// ── THE COMPRESSOR ──────────────────────────────────────────────────────────
@@ -426,18 +468,30 @@ function lockHolderRunning(owner: Owner): boolean {
}
// The dir lock, or null when a live run holds it. Returns its release.
+// The dir lock could not be made at all — a full disk (ENOSPC), a read-only
+// one. Nothing was done; a deleter answers it as a refusal (REVIEW-2 N2).
+export class LockUnavailableError extends Error {
+ constructor(videoDir: string, cause: Error) {
+ super(`the stored-text lock cannot be made in ${path.basename(videoDir)} (${(cause as NodeJS.ErrnoException).code ?? cause.message})`);
+ this.name = "LockUnavailableError";
+ }
+}
+
async function takeDirLock(videoDir: string): Promise<(() => Promise<void>) | null> {
const lock = path.join(videoDir, STORED_TEXT_DIR_LOCK);
const me = { pid: process.pid, token: selfToken() };
const tmp = path.join(videoDir, `${STORED_TEXT_DIR_LOCK}.${me.pid}-${me.token}-${Math.random().toString(36).slice(2, 8)}`);
try {
- await writeFile(tmp, JSON.stringify(me), { flag: "wx" });
- } catch (err) {
- // No video dir: nothing to lock and nothing to do.
- if (errCode(err) === "ENOENT") return async () => {};
- throw err;
- }
- try {
+ // Inside the try whose `finally` removes it: on a FULL disk `wx` creates
+ // the file and then fails to write it, and the empty temp must not stay
+ // behind, one per file visited (REVIEW-2 N2).
+ try {
+ await writeFile(tmp, JSON.stringify(me), { flag: "wx" });
+ } catch (err) {
+ // No video dir: nothing to lock and nothing to do.
+ if (errCode(err) === "ENOENT") return async () => {};
+ throw new LockUnavailableError(videoDir, err as Error);
+ }
for (let attempt = 0; attempt < 3; attempt++) {
try {
await link(tmp, lock);
@@ -526,6 +580,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;
@@ -582,8 +650,22 @@ async function repairLeftovers(
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 like any plain file.
+ // The original was set aside and not removed. It is ADOPTED — the file
+ // again, verified like any plain file — ONLY when it is plainly an
+ // interrupted run's of this compressor (its name carries the run's pid
+ // AND start token, and that process is gone: checked above) AND no
+ // deletion happened since: the stored form the run made BEFORE it set
+ // the original aside is still here. Every deleter removes both forms and
+ // the set-aside together, so a set-aside with no stored form beside it
+ // means the file was deleted some other way: it is NOT brought back but
+ // kept, listed for a person (REVIEW-1 F2, captions lane).
+ const z = await entryAt(videoDir, storedNameOf(name));
+ if (owner.token === undefined || z.kind === "none") {
+ ctx.log(
+ ` ${e} kept for a person: ${owner.token === undefined ? "a set-aside named before runs carried a start token" : `no ${storedNameOf(name)} beside it — deleted since?`}`,
+ );
+ return skip("retired-kept", `${e}: not adopted (${owner.token === undefined ? "no start token" : "no stored form"})`);
+ }
await rename(path.join(videoDir, e), path.join(videoDir, name));
ctx.log(` restored ${e} as ${name}`);
continue;
@@ -747,6 +829,9 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
}
const sd = await digestOf(bytesPath, { throttle: opts.throttle });
if (zd.sha !== sd.sha || zd.bytes !== sd.bytes) {
+ // Recorded, so the job's survey does not count the pair as work on every
+ // run (REVIEW-1 N2): it waits for a person until either form changes.
+ await recordBothDiffer(videoDir, name).catch(() => {});
return skip("both-differ", `${name} (${sd.bytes} bytes) and ${stored} (${zd.bytes} bytes) differ`);
}
// The same content: given the plain file's times, exactly.
@@ -786,7 +871,19 @@ async function compressOne(videoDir: string, name: string, opts: CompressOptions
if (await lstatOrNull(path.join(channelDir, TIER_RELOCATION_MARKER))) return skip("relocating");
const retired = `.${name}.retire-${pid}-${token}`;
const retiredPath = path.join(videoDir, retired);
- await rename(p.path, retiredPath);
+ try {
+ await rename(p.path, retiredPath);
+ } catch (err) {
+ if (errCode(err) !== "ENOENT") throw err;
+ // The original was removed since its last look. Every in-app deleter
+ // holds this file's lock, so what removed it is OUTSIDE the lock —
+ // yt-dlp's own overwrite in a re-download, which deletes the plain file
+ // and fetches after. The verified stored copy is KEPT (REVIEW-2 N3): if
+ // that fetch fails (a 429, a video gone) it is the caption; a new plain
+ // file landing later is `same` or `both-differ`, both safe.
+ log(` ${name} was removed while it was being compressed: the verified stored copy is kept`);
+ return { status: "changed" };
+ }
crash("retired");
const nowL = await lstatOrNull(retiredPath);
const nowS = await stat(retiredPath).catch(() => null);
@@ -1362,6 +1459,188 @@ export async function keepPlainAsCapture(
});
}
+// ── BOTH FORMS DIFFER: RECORDED ONCE, FOR A PERSON (REVIEW-1 N2) ───────────
+//
+// A pair the compressor refused (`both-differ`) is written to the CHANNEL's
+// `.stored-text-differs.json` (beside its config — the video dir is left
+// exactly as it was) with each form's identity (inode, size, mtime). While both
+// forms are exactly those files, the job's survey counts the pair as WAITING
+// FOR A PERSON — listed by the dry run, never work, never refused again. Any
+// change to either form (a person settles it on the files card, a writer
+// lands a new one) makes the entry stale and the pair is work again. A record,
+// not a lock: nothing is kept from being read or deleted by it. Written only
+// by the compress-text job, one per channel at a time.
+export const STORED_TEXT_DIFFERS_FILENAME = ".stored-text-differs.json";
+
+type FormIdent = { ino: number; size: number; mtimeMs: number };
+type DiffersRecord = Record<string, { plain: FormIdent; stored: FormIdent; at: string }>;
+
+const channelDirOf = (videoDir: string) => path.dirname(path.dirname(videoDir));
+const differsKey = (videoDir: string, name: string) => `${path.basename(videoDir)}/${name}`;
+
+async function formIdents(videoDir: string, name: string): Promise<{ plain: FormIdent; stored: FormIdent } | null> {
+ const [p, z] = await Promise.all([lstatOrNull(path.join(videoDir, name)), lstatOrNull(path.join(videoDir, storedNameOf(name)))]);
+ if (!p || !z) return null;
+ const id = (st: Stats): FormIdent => ({ ino: st.ino, size: st.size, mtimeMs: st.mtimeMs });
+ return { plain: id(p), stored: id(z) };
+}
+
+// The channel's record (one read per survey).
+export async function readStoredTextDiffers(channelDir: string): Promise<DiffersRecord> {
+ try {
+ const v = JSON.parse(await readFile(path.join(channelDir, STORED_TEXT_DIFFERS_FILENAME), "utf8")) as unknown;
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as DiffersRecord) : {};
+ } catch {
+ return {};
+ }
+}
+
+async function recordBothDiffer(videoDir: string, name: string): Promise<void> {
+ const ids = await formIdents(videoDir, name);
+ if (!ids) return;
+ const channelDir = channelDirOf(videoDir);
+ const rec = await readStoredTextDiffers(channelDir);
+ rec[differsKey(videoDir, name)] = { ...ids, at: new Date().toISOString() };
+ const file = path.join(channelDir, STORED_TEXT_DIFFERS_FILENAME);
+ const tmp = `${file}.${process.pid}-${selfToken()}`;
+ await writeFile(tmp, JSON.stringify(rec, null, 1));
+ await rename(tmp, file);
+}
+
+// Is this pair the one recorded as differing — both forms the very files
+// that were compared? (The survey's question; a stat each, no content read.)
+export async function bothDifferRecorded(record: DiffersRecord, videoDir: string, name: string): Promise<boolean> {
+ const rec = record[differsKey(videoDir, name)];
+ if (!rec) return false;
+ const ids = await formIdents(videoDir, name);
+ const same = (a: FormIdent, b: FormIdent) => a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs;
+ return !!ids && same(ids.plain, rec.plain) && same(ids.stored, rec.stored);
+}
+
+// ── A RE-DOWNLOAD OVER A STORED CAPTION (REVIEW-1 F1 of the captions lane) ──
+//
+// A managed re-download of a youtube-handling video fetches its captions
+// again (AGENTS.md: "YouTube's subtitles are fetched again first, as on any
+// re-download"): yt-dlp, run without `--no-overwrites`, replaces a plain
+// caption it finds. Over a track stored compressed it finds none, and lands
+// a new plain file beside the stored one. Main's rule is kept — the new
+// caption becomes the track — with one guarantee the overwrite never had:
+// the stored copy goes only AFTER the new file is whole and is a caption.
+// Per track that was stored-only before the pass:
+//
+// - nothing landed, or a `.part` of it (a fetch that did not finish): the
+// stored track is untouched (a video that is gone returns nothing);
+// - a whole new file with the SAME content: the new plain file goes, the
+// stored form stays — no churn, its mtime unchanged, the index sees
+// nothing;
+// - a whole new file with OTHER content that parses to at least one cue: it
+// is the track (as an overwrite was on main), and only then the stored
+// form is removed;
+// - an empty file, or one with no cue: dropped, the stored track untouched;
+// - a stored form that does not decode: both kept, for a person.
+//
+// Each outcome is a line in the job log.
+
+// A test's seam: called after the new plain file and its dir are fsynced and
+// before the stored copy is removed (the order is what REVIEW-2 N1 asks).
+let syncedForTest: ((videoDir: string, name: string) => Promise<void> | void) | undefined;
+export function setRefetchSyncedHookForTest(fn: typeof syncedForTest): void {
+ syncedForTest = fn;
+}
+
+export type RefetchedCaptionOutcome = {
+ track: string;
+ name: string;
+ status: "nothing-landed" | "partial" | "same" | "replaced" | "dropped-empty" | "kept-both" | "busy" | "no-stored";
+ detail?: string;
+};
+
+export async function settleRefetchedCaptions(
+ videoDir: string,
+ storedTracks: readonly string[],
+ onLog: (line: string) => void = () => {},
+): Promise<RefetchedCaptionOutcome[]> {
+ const out: RefetchedCaptionOutcome[] = [];
+ for (const track of storedTracks) {
+ const name = `transcript.${track}.vtt`;
+ if (!isStoredCaptionName(name)) continue;
+ const r = await withFileLock<RefetchedCaptionOutcome>(
+ videoDir,
+ name,
+ { track, name, status: "busy" },
+ () => settleOne(videoDir, track, name),
+ );
+ out.push(r);
+ const say: Record<RefetchedCaptionOutcome["status"], string> = {
+ "nothing-landed": "nothing was fetched; the stored track is kept",
+ partial: "the fetch did not finish (a .part); the stored track is kept",
+ same: "fetched again with the same content; the stored track is kept (the new copy dropped)",
+ replaced: "fetched again with new content; the new track replaces the stored one",
+ "dropped-empty": "fetched again with no cues; dropped, the stored track is kept",
+ "kept-both": "fetched again; the stored track could not be read, so both are kept for a person",
+ busy: "being compressed or restored right now; left as it is",
+ "no-stored": "no stored form any more; left as it is",
+ };
+ onLog(`Captions ${name}: ${say[r.status]}${r.detail ? ` (${r.detail})` : ""}.\n`);
+ }
+ return out;
+}
+
+async function settleOne(videoDir: string, track: string, name: string): Promise<RefetchedCaptionOutcome> {
+ const base = { track, name };
+ const entries = await readdir(videoDir).catch(() => [] as string[]);
+ if (entries.some((e) => e.startsWith(`${name}.part`))) return { ...base, status: "partial" };
+ const plain = await entryAt(videoDir, name);
+ if (plain.kind === "none") return { ...base, status: "nothing-landed" };
+ const z = await storedPathOf(videoDir, name);
+ if (!z) return { ...base, status: "no-stored" };
+ let fresh: Buffer;
+ try {
+ fresh = await readFile(path.join(videoDir, name));
+ } catch (err) {
+ return { ...base, status: "kept-both", detail: `the new file does not open: ${(err as Error).message}` };
+ }
+ let zd: Digest;
+ try {
+ zd = await digestOf(z, { decode: true });
+ } catch (err) {
+ return { ...base, status: "kept-both", detail: (err as Error).message };
+ }
+ const fd = { sha: createHash("sha256").update(fresh).digest("hex"), bytes: fresh.length };
+ if (fd.sha === zd.sha && fd.bytes === zd.bytes) {
+ await removeMediaFile(videoDir, name);
+ await fsyncDir(videoDir);
+ return { ...base, status: "same" };
+ }
+ let cues = 0;
+ try {
+ cues = fresh.length > 0 ? parseVtt(fresh.toString("utf8")).length : 0;
+ } catch {
+ cues = 0;
+ }
+ if (cues === 0) {
+ await removeMediaFile(videoDir, name);
+ await fsyncDir(videoDir);
+ return { ...base, status: "dropped-empty", detail: `${fresh.length} bytes` };
+ }
+ // The new track is whole (yt-dlp has exited; no `.part`) and a caption: it
+ // is the track, as an overwrite was on main. Its data and its name are made
+ // DURABLE first — yt-dlp never fsyncs, and a power cut after the stored
+ // copy's removal must not leave a zero-length caption (REVIEW-2 N1). Only
+ // then the stored one goes.
+ const fh = await open(path.join(videoDir, name), "r");
+ try {
+ await fh.sync();
+ } finally {
+ await fh.close();
+ }
+ await fsyncDir(videoDir);
+ await syncedForTest?.(videoDir, name);
+ await removeMediaFile(videoDir, storedNameOf(name));
+ await fsyncDir(videoDir);
+ return { ...base, status: "replaced", detail: `${cues} cues, ${fresh.length} bytes` };
+}
+
// ── THE FILES CARD'S DELETE OF ONE NAMED FORM ───────────────────────────────
//
// A person deleting `X` or `X.zst` on the files card asked for ONE file: only
@@ -1373,18 +1652,38 @@ export async function keepPlainAsCapture(
export type RemoveFormOutcome = {
removed: string[];
kept?: { name: string; same: "same" | "differs" | "unreadable" };
+ // The plain transcript.en.vtt (a "Set as transcript" pick) went beside a
+ // stored one of other content: the pin went too (transcriptPin-server.ts).
+ unpinned?: boolean;
};
-export async function removeStoredTextForm(videoDir: string, filename: string): Promise<RemoveFormOutcome | "busy"> {
+export async function removeStoredTextForm(
+ videoDir: string,
+ filename: string,
+): Promise<RemoveFormOutcome | "busy" | { refused: string }> {
const plain = plainNameOf(filename) ?? filename;
if (!isStoredTextName(plain)) {
await removeMediaFile(videoDir, filename);
return { removed: [filename] };
}
+ try {
+ return await removeStoredTextFormLocked(videoDir, filename, plain);
+ } catch (err) {
+ // No lock could be made (a full disk): nothing was removed (REVIEW-2 N2).
+ if (err instanceof LockUnavailableError) return { refused: `${filename} not deleted: ${err.message}` };
+ throw err;
+ }
+}
+
+async function removeStoredTextFormLocked(videoDir: string, filename: string, plain: string): Promise<RemoveFormOutcome | "busy"> {
return withFileLock<RemoveFormOutcome | "busy">(videoDir, plain, "busy", async () => {
const other = filename === plain ? storedNameOf(plain) : plain;
+ // A stopped run's leftovers on the name go with any form deleted: a
+ // set-aside original left behind could be adopted by the next run and
+ // bring the deleted file back (REVIEW-1 F2, captions lane).
if (!(await lstatOrNull(path.join(videoDir, other)))) {
await removeMediaFile(videoDir, filename);
+ await removeLeftoversOf(videoDir, plain);
return { removed: [filename] };
}
const z = await storedPathOf(videoDir, plain);
@@ -1394,7 +1693,12 @@ export async function removeStoredTextForm(videoDir: string, filename: string):
]);
const same = !pd || !zd ? "unreadable" : pd.sha === zd.sha && pd.bytes === zd.bytes ? "same" : "differs";
await removeMediaFile(videoDir, filename);
+ await removeLeftoversOf(videoDir, plain);
await fsyncDir(videoDir);
- return { removed: [filename], kept: { name: other, same } };
+ // The pick deleted, YouTube's own stored `en` beside it: the pin goes too,
+ // or it would rank that very track first (REVIEW-1 N1, captions lane).
+ const unpinned =
+ filename === "transcript.en.vtt" && same === "differs" ? await unpinAfterPickDeleted(videoDir) : false;
+ return { removed: [filename], kept: { name: other, same }, ...(unpinned ? { unpinned: true } : {}) };
});
}
diff --git a/common/lib/storedText.compress.test.ts b/common/lib/storedText.compress.test.ts
@@ -166,7 +166,12 @@ for (const tiered of [false, true]) {
const before = await tree(f.channelDir);
const out = await run(f);
assert.deepEqual(out.status === "skipped" && out.reason, "both-differ", JSON.stringify(out));
- assert.deepEqual(await tree(f.channelDir), before);
+ // Nothing of the video's is touched; the refusal is RECORDED beside the
+ // channel's config (REVIEW-1 N2 of the captions lane: listed once, not
+ // work again until a form changes).
+ const differs = path.join(f.channelDir, ".stored-text-differs.json");
+ assert.deepEqual((await tree(f.channelDir)).filter((l) => !l.includes(".stored-text-differs.json")), before);
+ assert.deepEqual(Object.keys(JSON.parse(await readFile(differs, "utf8"))), [`vid00000001/${CHAT}`]);
assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWER\n", "the plain one is read");
});
@@ -461,7 +466,9 @@ test("an abort mid-write and an appending writer: the original is untouched, no
test("not a declared name: refused", async () => {
const f = await fixture(false);
- const out = await compressStoredText(f.videoDir, "transcript.en.vtt");
+ // (A caption track is declared since lane text-compress-captions; the
+ // metadata is not.)
+ const out = await compressStoredText(f.videoDir, "metadata.info.json");
assert.equal(out.status === "skipped" && out.reason, "not-declared");
});
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)",
@@ -84,6 +89,7 @@ const DEFINITIONS = new Set([
"common/lib/storedText.ts",
"common/lib/storedText-server.ts",
"common/lib/storedText-write-server.ts",
+ "common/lib/storedText-read.mjs",
]);
async function walk(dir: string, out: string[]): Promise<void> {
@@ -184,11 +190,19 @@ test("every app line naming the raw live chat goes through the stored-text helpe
const SUB_FLAGS =
/(["'])--(?:sub-langs?|all-subs|write-subs|write-auto-subs|write-automatic-subs)\1|["'`]--(?:sub-langs?)=|^\s*["'`]live_chat["'`],?\s*$/;
+// CAPTIONS TOO (lane text-compress-captions): a caption track stored as
+// `transcript.<lang>.vtt.zst` is fetched again by any pass that asks for it.
+// The missing-subs pass (`--no-overwrites`, where main skipped a present
+// track) excludes the stored tracks by code; the managed download (no
+// `--no-overwrites`, where main replaced it) fetches them and settles each
+// after the pass. Both take the stored tracks from the PHYSICAL listing.
const CHAT_WRITERS: Record<string, { file: string; guard: string; test: string }> = {
youtubeHandlingArgs: {
file: "common/ytdlp/downloadOneManaged.ts",
- guard: "chatStored (storedFormsIn === \"zst\"): the chat left out of --sub-langs",
- test: "controller/storedText.chat.test.ts (youtubeHandlingArgs)",
+ guard:
+ "chatStored (storedFormsIn === \"zst\"): the chat left out of --sub-langs; a stored caption IS fetched " +
+ "again (main's re-download rule) and its caller settles it after the pass (settleRefetchedCaptions)",
+ test: "controller/storedText.chat.test.ts (youtubeHandlingArgs); ytdlp/captionsRefetch.test.ts",
},
liveChatOnlyArgs: {
file: "common/ytdlp/downloadOneManaged.ts",
@@ -197,8 +211,8 @@ const CHAT_WRITERS: Record<string, { file: string; guard: string; test: string }
},
downloadSubsForUrl: {
file: "common/ytdlp/runYtdlp.ts",
- guard: "subLangsForVideo: the chat left out of --sub-langs for a stored chat",
- test: "controller/storedText.chat.test.ts (subLangsForVideo)",
+ guard: "subLangsForVideo: the chat left out of --sub-langs for a stored chat, each stored caption excluded by code",
+ test: "controller/storedText.chat.test.ts (subLangsForVideo); controller/storedText.captions.test.ts (subLangsForVideo)",
},
};
@@ -258,3 +272,157 @@ test("every yt-dlp argv that can write the raw chat is a pinned builder, and eve
"be tested, and be counted in CALLERS",
);
});
+
+// ── THE THIRD GATE: CAPTIONS (lane text-compress-captions) ─────────────────
+//
+// A caption track may be on disk as `transcript.<lang>.vtt.zst`. A raw read,
+// stat or delete of a caption NAME (its constants, a `transcript.<x>.vtt`
+// literal, a record's `ytVttFile` / `vttFile` / `picked.filename`) outside the
+// stored-text helpers sees a compressed track as ABSENT — and the three
+// misses that cost the most are a re-fetch of the URL (destinationExists), an
+// audio download and a transcription for a video that has captions
+// (hasAnyTranscriptOnDisk), and a purge that leaves the `.zst` (the captions
+// come back). Two tripwires, like the first gate:
+//
+// 1. A LINE THAT CALLS A RAW FS READ, STAT OR DELETE and names a caption in
+// the same statement (the line or the two before it) must also name a
+// sanctioned reader or deleter there, or be ALLOWED_CAPTION with its
+// reason. Writes are not gated: every writer writes the plain name, which
+// is the truth (lib/storedText.ts).
+// 2. A FILE THAT APPLIES A CAPTION RULE to a listing (`englishVttsByPreference`,
+// `resolvePrimaryVtt`, `captionInputs`, `listTranscriptVtts`, …) must take
+// a LOGICAL listing somewhere in it (`readVideoFiles`, `logicalEntries`,
+// `readdirLogical`, `logicalFileNames`, the umtool twin) — a raw readdir
+// fed to the rule loses every stored track — or be a RULE_ONLY file with
+// its reason (it is handed a logical listing by its callers).
+//
+// WHAT THEY CANNOT SEE: a variable holding a caption name read far from where
+// it was named; a listing passed through a parameter from a raw readdir in
+// another file; a shell or Python reader.
+
+const CAPTION_NAMES =
+ /\b(?:VTT_FILENAME|ORIG_VTT_FILENAME|CANONICAL_VTT|EN_ORIG_TRACK)\b|transcript\.[A-Za-z-]*\.vtt(?![.\w])|\.ytVttFile\b|\bvttFile\b|picked\.filename\b/;
+const RAW_FS = /\b(?:readFile|readFileSync|stat|statSync|lstat|lstatSync|open|openSync|createReadStream|rm|rmSync|unlink|unlinkSync|copyFile|rename|access|existsSync|removeMediaFile|renameMediaFile)\s*\(/;
+const CAPTION_SANCTIONED =
+ /\b(?:readStoredText|readStoredTextHead|statStoredText|storedTextMtimeMs|storedTextExists|storedTextForms|storedTextLogicalSize|removeStoredText|removeStoredTextForm|compressStoredText|restoreStoredText|verifyStoredText|decodeStoredBytes|captionBytes|readEnglishVttCues|readEnglishVttTracks|readVttProvenance|resolveVttProvenance)\b/;
+
+const ALLOWED_CAPTION: { file: string; code: RegExp; why: string }[] = [
+ {
+ file: "common/lib/localMediaCommit-server.ts",
+ code: /const current = await lstat\(target\);/,
+ why: "the new record's DIRECTORY, checked before each link of a commit that made it (mkdir, EEXIST refused): no stored form can be in it",
+ },
+];
+
+// The caption rules, and the files that define them.
+const CAPTION_RULES =
+ /\b(?:englishVttsByPreference|resolvePrimaryVtt|captionInputs|listTranscriptVtts|readEnglishVttCues|readEnglishVttTracks|mayHaveAltTracks|resolveCaptionsProvenance)\s*\(/;
+const LOGICAL_LISTING = /\b(?:readVideoFiles|logicalEntries|readdirLogical|logicalFileNames)\b/;
+const RULE_ONLY: Record<string, string> = {
+ "common/lib/videoStatus.ts": "the rules themselves (readEnglishVttCues makes its listing logical)",
+};
+
+test("every app line that reads, stats or deletes a caption track goes through the stored-text helpers", async () => {
+ const offenders: string[] = [];
+ for (const { rel, lines } of await appFiles()) {
+ if (DEFINITIONS.has(rel)) continue;
+ for (let i = 0; i < lines.length; i++) {
+ const code = codeOnly(lines[i]);
+ if (!RAW_FS.test(code)) continue;
+ const statement = [lines[i - 2] ?? "", lines[i - 1] ?? "", code].map(codeOnly).join("\n");
+ if (!CAPTION_NAMES.test(statement)) continue;
+ if (CAPTION_SANCTIONED.test(statement)) continue;
+ if (ALLOWED_CAPTION.some((a) => a.file === rel && a.code.test(code))) continue;
+ offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`);
+ }
+ }
+ assert.deepEqual(
+ offenders,
+ [],
+ "read, stat or delete a caption track through lib/storedText(-server|-write-server).ts — it may be stored as .zst",
+ );
+});
+
+test("every file that applies a caption rule to a listing takes a logical listing", async () => {
+ const offenders: string[] = [];
+ for (const { rel, lines } of await appFiles()) {
+ if (DEFINITIONS.has(rel) || RULE_ONLY[rel]) continue;
+ const code = lines.map(codeOnly);
+ const uses = code.findIndex((l) => CAPTION_RULES.test(l) && !/^\s*(?:export\s+)?(?:async\s+)?function\b/.test(l));
+ if (uses < 0) continue;
+ if (code.some((l) => LOGICAL_LISTING.test(l))) continue;
+ offenders.push(`${rel}:${uses + 1}: ${lines[uses].trim()}`);
+ }
+ assert.deepEqual(
+ offenders,
+ [],
+ "a caption rule fed a raw readdir loses every track stored as .zst: list with readVideoFiles / readdirLogical / logicalEntries",
+ );
+});
+
+// ── THE CAPTIONS GATES, TIGHTER (REVIEW-1 N8 of the captions lane) ─────────
+//
+// 5. In a file that applies a caption rule, EVERY readdir of a video dir is
+// logical (wrapped in logicalEntries / readdirLogical on its line or the
+// next) or listed below with why: a raw listing fed to the rule loses every
+// stored track. A listing of a channel's or the index's own dirs (not a
+// video dir) is not asked.
+// 6. A caption PARSE (`parseVtt`, `hasWordTiming`, `vttWordStarts`,
+// `sniffVttProvenance`) fed by a raw `readFile` in the same statement:
+// the bytes of a stored track are zstd, not text.
+// 7. The managed download's subtitle pass fetches stored captions again
+// (main's rule): the file that calls its argv builder must settle them.
+
+const NOT_A_VIDEO_DIR = /readdir\(\s*(?:channelsDir|dataDir|paths\.|\w*OutDir\b|\w*ChannelDir\b|channelDir\b|summariesOut\b|transcriptsOutDir)/;
+const RAW_VIDEO_READDIR: { file: string; code: RegExp; why: string }[] = [
+ { file: "common/controller/channelSnapshot.ts", code: /entries = await readdir\(dir\);/, why: "dirFileBytes: the clips/ cache's files, never a caption" },
+ { file: "common/controller/copiesLane.ts", code: /readdir: \(p\) => readdir\(p\)/, why: "the io seam; signatureOf makes the listing logical" },
+ { file: "common/controller/findClips.ts", code: /const entries = await readdir\(videoDir\)/, why: "media and sidecar names; the transcript pick wraps it in logicalEntries" },
+ { file: "editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts", code: /const entries = await readdir\(videoDir\)\.catch/, why: "the audio files only (isRealAudioFile)" },
+ { file: "editor/app/channels/[slug]/videos/[id]/videoActions.ts", code: /const (?:firstEntries|entries) = await readdir\((?:videoDir|resolved)\)/, why: "audio and containers; the captions check wraps it in logicalEntries" },
+];
+const PARSE = /\b(?:parseVtt|hasWordTiming|vttWordStarts|sniffVttProvenance)\s*\(/;
+const PARSE_RAW_ALLOWED: { file: string; code: RegExp; why: string }[] = [
+ { file: "common/controller/copiesLane.ts", code: /for \(const cue of parseVtt\(text\)\)/, why: "text from io.readCaption (readStoredText); io.readFile only in a test's seam" },
+];
+
+test("in a file that applies a caption rule, every readdir of a video dir is logical", async () => {
+ const offenders: string[] = [];
+ for (const { rel, lines } of await appFiles()) {
+ if (DEFINITIONS.has(rel) || RULE_ONLY[rel]) continue;
+ const code = lines.map(codeOnly);
+ if (!code.some((l) => CAPTION_RULES.test(l) || /\b(?:isTranscriptVtt|isEnglishVtt|isTranscriptVttName)\s*\(/.test(l))) continue;
+ code.forEach((l, i) => {
+ if (!/\breaddir\s*\(/.test(l) || NOT_A_VIDEO_DIR.test(l)) return;
+ if (/logicalEntries\(|readdirLogical/.test(l + (code[i + 1] ?? ""))) return;
+ if (RAW_VIDEO_READDIR.some((a) => a.file === rel && a.code.test(l))) return;
+ offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`);
+ });
+ }
+ assert.deepEqual(offenders, [], "a raw readdir beside a caption rule: make it logical (readdirLogical / logicalEntries) or list it with why");
+});
+
+test("no caption parse is fed a raw readFile", async () => {
+ const offenders: string[] = [];
+ for (const { rel, lines } of await appFiles()) {
+ if (DEFINITIONS.has(rel) || rel === "common/lib/vtt.ts") continue;
+ const code = lines.map(codeOnly);
+ code.forEach((l, i) => {
+ if (!PARSE.test(l)) return;
+ const st = [code[i - 2] ?? "", code[i - 1] ?? "", l].join("\n");
+ if (!/\breadFile(?:Sync)?\s*\(/.test(st)) return;
+ if (PARSE_RAW_ALLOWED.some((a) => a.file === rel && a.code.test(l))) return;
+ offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`);
+ });
+ }
+ assert.deepEqual(offenders, [], "parse a caption read through readStoredText — its bytes may be zstd");
+});
+
+test("the file that builds the managed download's subtitle argv settles stored captions after the pass", async () => {
+ for (const { rel, lines } of await appFiles()) {
+ const text = lines.map(codeOnly).join("\n");
+ if (!/\byoutubeHandlingArgs\s*\(/.test(text.replace(/export function youtubeHandlingArgs\s*\(/, ""))) continue;
+ assert.match(text, /\bsettleRefetchedCaptions\s*\(/, `${rel}: calls youtubeHandlingArgs without settleRefetchedCaptions`);
+ assert.match(text, /\bstoredOnlyCaptionTracks\s*\(/, `${rel}: settles without the PHYSICAL listing's stored tracks`);
+ }
+});
diff --git a/common/lib/storedText.test.ts b/common/lib/storedText.test.ts
@@ -12,6 +12,7 @@ import path from "node:path";
import {
STORED_TEXT_NAMES,
+ isStoredCaptionName,
isStoredTextName,
listingHas,
logicalEntries,
@@ -33,7 +34,7 @@ import {
StoredTextCorruptError,
} from "./storedText-server";
import { classifyEntry, isScratchEntry, isTierable, LIVE_CHAT_STORED_FILENAME } from "./mediaTier";
-import { LIVE_CHAT_FILENAME } from "./videoStatus";
+import { LIVE_CHAT_FILENAME, isTranscriptVtt } from "./videoStatus";
const ROOT = await mkdtemp(path.join(tmpdir(), "stored-text-"));
test.after(() => rm(ROOT, { recursive: true, force: true }));
@@ -47,25 +48,50 @@ async function dir(name: string): Promise<string> {
return d;
}
-test("the declared names: the live chat only, its stored form `.zst`", () => {
+test("the declared names: the live chat and every caption track, each with its stored form `.zst`", () => {
assert.deepEqual([...STORED_TEXT_NAMES], [CHAT]);
assert.equal(isStoredTextName(CHAT), true);
- assert.equal(isStoredTextName("transcript.en.vtt"), false);
+ // Every caption track (lane text-compress-captions), any language code.
+ for (const c of ["transcript.en.vtt", "transcript.en-orig.vtt", "transcript.en-US.vtt", "transcript.es.vtt", "transcript.en-en-GB.vtt"]) {
+ assert.equal(isStoredTextName(c), true, c);
+ assert.equal(isStoredCaptionName(c), true, c);
+ assert.equal(isTranscriptVtt(c), true, `${c}: the same pattern as videoStatus`);
+ assert.equal(plainNameOf(`${c}.zst`), c);
+ }
+ // Not declared: the metadata, the whisper transcript, the cues, a
+ // transcriber's temp, a `.part`, another track format.
+ for (const n of ["metadata.info.json", "transcript.json", "transcript.cues.json", "transcript.tmp-4242.vtt", "transcript.en.vtt.part", "transcript.en.srv3", "live_chat.cues.json"]) {
+ assert.equal(isStoredTextName(n), false, n);
+ assert.equal(plainNameOf(`${n}.zst`), null, n);
+ }
+ assert.equal(isStoredCaptionName(CHAT), false);
assert.equal(storedNameOf(CHAT), "transcript.live_chat.json.zst");
assert.equal(plainNameOf("transcript.live_chat.json.zst"), CHAT);
- // Not declared: a `.zst` of another name stands for nothing here.
- assert.equal(plainNameOf("transcript.en.vtt.zst"), null);
assert.equal(plainNameOf(CHAT), null);
assert.equal(LIVE_CHAT_STORED_FILENAME, storedNameOf(CHAT));
});
+test("the classifier: a stored caption is TEXT, never tiered; its compressor's temps and set-aside are scratch", () => {
+ assert.equal(classifyEntry("transcript.en.vtt.zst"), "text");
+ assert.equal(isTierable("transcript.en.vtt.zst"), false);
+ assert.equal(isScratchEntry(".transcript.en.vtt.zst.compressing-4242-abc123"), true);
+ assert.equal(isScratchEntry(".transcript.en-orig.vtt.retire-4242-abc123"), true);
+ assert.equal(isScratchEntry(".transcript.es.vtt.restoring-4242-abc123"), true);
+ assert.equal(isTierable(".transcript.en.vtt.zst.compressing-4242"), false);
+});
+
test("a logical listing reports the stored chat under its plain name, once", () => {
assert.deepEqual(
logicalEntries(["metadata.info.json", "transcript.live_chat.json.zst", CHAT, "x.zst"]),
["metadata.info.json", CHAT, "x.zst"],
);
assert.equal(listingHas(["transcript.live_chat.json.zst"], CHAT), true);
- assert.equal(listingHas(["transcript.en.vtt.zst"], "transcript.en.vtt"), false);
+ assert.equal(listingHas(["transcript.en.vtt.zst"], "transcript.en.vtt"), true);
+ assert.equal(listingHas(["metadata.info.json.zst"], "metadata.info.json"), false);
+ assert.deepEqual(
+ logicalEntries(["transcript.en-orig.vtt.zst", "transcript.en.vtt", "transcript.en.vtt.zst", "metadata.info.json"]),
+ ["transcript.en-orig.vtt", "transcript.en.vtt", "metadata.info.json"],
+ );
assert.equal(storedFormsIn([CHAT], CHAT), "plain");
assert.equal(storedFormsIn(["transcript.live_chat.json.zst"], CHAT), "zst");
assert.equal(storedFormsIn([CHAT, "transcript.live_chat.json.zst"], CHAT), "both");
diff --git a/common/lib/storedText.ts b/common/lib/storedText.ts
@@ -4,11 +4,13 @@
// lib/storedText-server.ts, the compressor and the one deleter
// lib/storedText-write-server.ts).
//
-// DECLARED NAMES ONLY. A name is stored compressed only when it is in
-// STORED_TEXT_NAMES; for every other name `<name>.zst` means nothing here. The
-// raw live-chat replay is the one declared name today (lane text-compress,
-// slices 1–2: the media drive's tens of GB of chat). Captions are a later
-// slice; `metadata.info.json` is out of scope.
+// DECLARED NAMES ONLY. A name is stored compressed only when it is declared
+// (`isStoredTextName`); for every other name `<name>.zst` means nothing here.
+// Two kinds are declared: the raw live-chat replay (STORED_TEXT_NAMES — lane
+// text-compress, slices 1–2: the media drive's tens of GB of chat) and EVERY
+// CAPTION TRACK, `transcript.<lang>.vtt` (lane text-compress-captions, slices
+// 4–5: about 77 GB on the corpus disk; `isStoredCaptionName`).
+// `metadata.info.json` is not declared (a design note only).
//
// THE RULE: PLAIN, WHEN PRESENT, IS THE TRUTH. Every writer keeps writing the
// plain name (yt-dlp, the chat fetch); none has to know about the stored form.
@@ -25,14 +27,26 @@ import { LIVE_CHAT_MEDIA_FILENAME } from "./mediaTier";
export const STORED_TEXT_SUFFIX = ".zst";
-// The names stored compressed. One state per name, whatever its size: simpler
-// to test than "compressed when big".
+// The FIXED names stored compressed. One state per name, whatever its size:
+// simpler to test than "compressed when big".
export const STORED_TEXT_NAMES: readonly string[] = Object.freeze([LIVE_CHAT_MEDIA_FILENAME]);
const DECLARED = new Set(STORED_TEXT_NAMES);
+// EVERY CAPTION TRACK: `transcript.<lang>.vtt`, any language code (videoStatus
+// `isTranscriptVtt`'s pattern, less the temp below — storedText.test.ts holds
+// them together; this module cannot import videoStatus, which imports it). The en / en-orig pair,
+// the regional and auto-translated tracks, the foreign-language subtitles.
+// Not a transcriber's temp output (`transcript.tmp-<pid>.vtt`,
+// controller/transcribeOne.ts): somebody's in-flight bytes, never stored.
+const CAPTION_RE = /^transcript\.(?!tmp-\d+\.vtt$)[^.]+\.vtt$/;
+
+export function isStoredCaptionName(name: string): boolean {
+ return CAPTION_RE.test(name);
+}
+
export function isStoredTextName(name: string): boolean {
- return DECLARED.has(name);
+ return DECLARED.has(name) || CAPTION_RE.test(name);
}
export function storedNameOf(name: string): string {
@@ -44,7 +58,7 @@ export function storedNameOf(name: string): string {
export function plainNameOf(name: string): string | null {
if (!name.endsWith(STORED_TEXT_SUFFIX)) return null;
const plain = name.slice(0, -STORED_TEXT_SUFFIX.length);
- return DECLARED.has(plain) ? plain : null;
+ return isStoredTextName(plain) ? plain : null;
}
// The name a listing that MATCHES reports for this entry.
@@ -83,3 +97,30 @@ export function storedFormsIn(entries: readonly string[], name: string): StoredF
if (zst) return "zst";
return null;
}
+
+// THE CAPTION TRACKS ON DISK IN THE STORED FORM ONLY, by their track code
+// (`transcript.en-orig.vtt.zst` with no plain `transcript.en-orig.vtt` →
+// "en-orig"), from a PHYSICAL listing. These are what a yt-dlp subtitle pass
+// must not be asked for: yt-dlp's own "already present" skip looks for the
+// plain name, so it would fetch the track again and land a second copy beside
+// the stored one (a request against the subtitle 429 limit, and two forms).
+export function storedOnlyCaptionTracks(entries: readonly string[]): string[] {
+ const have = new Set(entries);
+ const out: string[] = [];
+ for (const e of entries) {
+ const plain = plainNameOf(e);
+ if (plain === null || !CAPTION_RE.test(plain) || have.has(plain)) continue;
+ out.push(plain.slice("transcript.".length, -".vtt".length));
+ }
+ return out.sort();
+}
+
+// `--sub-langs` with these tracks EXCLUDED: each appended as `-<code>`, its
+// regex characters escaped (yt-dlp matches a code as a regex anchored at both
+// ends, and applies the exclusions after the requests before them, so
+// `en.*,-en` asks every English track but `en`). Unchanged when there are none.
+export function excludeSubTracks(subLangs: string, tracks: readonly string[]): string {
+ if (tracks.length === 0) return subLangs;
+ const esc = (t: string) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ return [subLangs, ...tracks.map((t) => `-${esc(t)}`)].join(",");
+}
diff --git a/common/lib/subtitleProvenance.ts b/common/lib/subtitleProvenance.ts
@@ -1,7 +1,8 @@
import path from "node:path";
-import { createReadStream } from "node:fs";
import { readFile } from "node:fs/promises";
import { englishVttsByPreference, type VideoFiles } from "./videoStatus";
+import { readStoredTextHead } from "./storedText-server";
+import { logicalEntries } from "./storedText";
// Where a VTT transcript came from: YouTube's speech recognition ("asr", what
// yt-dlp downloads under --write-auto-subs) or a human-authored/uploaded track
@@ -59,37 +60,24 @@ export function sniffVttProvenance(head: string): SubtitleProvenance {
return "unknown";
}
-// Read only the head of the VTT (createReadStream start/end), never the whole
-// file: a 3-hour ASR transcript is multiple MB.
+// Read only the head of the VTT, never the whole file: a 3-hour ASR transcript
+// is multiple MB. A track stored compressed (`transcript.en.vtt.zst`,
+// lib/storedText.ts) has its head DECODED: the raw bytes of a zstd frame
+// would sniff as "unknown" — and an ASR track read as manual is one the purge
+// keeps and the replace lane never schedules.
export async function readVttProvenance(
videoDir: string,
vttFile: string,
): Promise<SubtitleProvenance> {
let head: string;
try {
- head = await readHead(path.join(videoDir, vttFile), PROVENANCE_SNIFF_BYTES);
+ head = (await readStoredTextHead(videoDir, vttFile, PROVENANCE_SNIFF_BYTES)).toString("utf8");
} catch {
return "unknown";
}
return sniffVttProvenance(head);
}
-function readHead(file: string, bytes: number): Promise<string> {
- return new Promise((resolve, reject) => {
- const stream = createReadStream(file, {
- encoding: "utf8",
- start: 0,
- end: bytes - 1,
- });
- let out = "";
- stream.on("data", (chunk) => {
- out += chunk;
- });
- stream.on("error", reject);
- stream.on("end", () => resolve(out));
- });
-}
-
// The language/track segment of a transcript sidecar filename:
// "transcript.en-US.vtt" -> "en-US". Null for anything else.
export function vttTrackName(filename: string): string | null {
@@ -150,7 +138,7 @@ export async function resolveCaptionsProvenance(
videoDir: string,
entries: readonly string[],
): Promise<SubtitleProvenance | null> {
- const vtts = englishVttsByPreference(entries);
+ const vtts = englishVttsByPreference(logicalEntries(entries));
if (vtts.length === 0) return null;
let unknown = false;
for (const name of vtts) {
diff --git a/common/lib/transcriptPin-server.ts b/common/lib/transcriptPin-server.ts
@@ -37,3 +37,17 @@ export async function pinTranscript(videoDir: string, from: string): Promise<voi
pinnedAt: new Date().toISOString(),
});
}
+
+// THE PIN GOES WITH THE PICK (REVIEW-1 N1, captions lane): "Set as
+// transcript" writes the chosen track as a PLAIN transcript.en.vtt and pins
+// it. Over a stored `transcript.en.vtt.zst` (YouTube's own `en`, compressed)
+// the pick lands beside it; deleting the plain pick then would leave the pin
+// ranking the stored `en` first — the very track the pin was made to avoid.
+// So a delete of the plain transcript.en.vtt that leaves a stored form of
+// OTHER content beside it removes the pin too: the caption-track rule picks
+// again. Returns whether a pin was removed.
+export async function unpinAfterPickDeleted(videoDir: string): Promise<boolean> {
+ if (!(await transcriptPinSidecar.load(videoDir))) return false;
+ await transcriptPinSidecar.remove(videoDir);
+ return true;
+}
diff --git a/common/lib/videoStatus.ts b/common/lib/videoStatus.ts
@@ -3,6 +3,7 @@ import { readdir, readFile, stat } from "node:fs/promises";
import { isPartAudioFile, isRealAudioFile } from "./mediaFiles";
import { parseVtt, type Cue } from "./vtt";
import { logicalEntries } from "./storedText";
+import { isStoredTextReadError, readStoredText } from "./storedText-server";
export type VideoFiles = {
hasMeta: boolean;
@@ -29,7 +30,12 @@ export type VideoFiles = {
// Surfaced separately so the UI can offer a Resume action; audio-check's
// own internal snapshots (.part.good, .part.testing) are excluded.
partAudioFiles: string[];
- // The raw readdir() listing this whole record was derived from.
+ // The LOGICAL readdir() listing this whole record was derived from
+ // (lib/storedText.ts): a file stored compressed — `transcript.en.vtt.zst`,
+ // `transcript.live_chat.json.zst` — is listed under its plain name, once,
+ // and every reader of its bytes goes through lib/storedText-server.ts. A
+ // caller that OPERATES on each entry as a file (the byte walk, a mover)
+ // takes `physicalEntries`.
//
// Exposed so a caller that needs a question this type does not already answer
// — "is there a source container?", "is there a saved-video pointer?" — can
@@ -39,6 +45,8 @@ export type VideoFiles = {
// that is free and one that doubles the report's I/O. See
// lib/operations.ts, which classifies missing vs missing-input from it.
entries: string[];
+ // The raw readdir(): every entry under its own name (a `.zst` is a file).
+ physicalEntries: string[];
};
export type IndexTranscript =
@@ -187,21 +195,26 @@ export function captionInputs(entries: readonly string[]): string[] {
// preference order, that parses to at least one cue. When every track parses
// to nothing, the most preferred one is returned with its empty list (the
// video has captions, they say nothing). Null when there is no English VTT, or
-// none can be read. `entries` is the caller's readdir of `videoDir`, when it
-// has one.
+// none can be read. `entries` is the caller's LOGICAL listing of `videoDir`
+// (readVideoFiles().entries), when it has one — a physical readdir is made
+// logical here too, so a track stored as `transcript.en.vtt.zst` is read
+// (lib/storedText.ts) and the name answered is always the plain one.
export async function readEnglishVttCues(
videoDir: string,
entries?: readonly string[],
): Promise<{ filename: string; cues: Cue[] } | null> {
const names = englishVttsByPreference(
- entries ?? (await readdir(videoDir).catch(() => [] as string[])),
+ logicalEntries(entries ?? (await readdir(videoDir).catch(() => [] as string[]))),
);
let first: { filename: string; cues: Cue[] } | null = null;
for (const filename of names) {
let cues: Cue[];
try {
- cues = parseVtt(await readFile(path.join(videoDir, filename), "utf8"));
- } catch {
+ cues = parseVtt(await readStoredText(videoDir, filename, "utf8"));
+ } catch (err) {
+ // A stored track that is there and does not decode is an error, never
+ // a track to skip past (lib/storedText-server.ts isStoredTextReadError).
+ if (isStoredTextReadError(err)) throw err;
continue;
}
if (cues.length > 0) return { filename, cues };
@@ -230,7 +243,8 @@ export async function readVideoFiles(
videoDir: string,
opts: { checkUntranscribable?: boolean } = {},
): Promise<VideoFiles> {
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const physicalEntries = await readdir(videoDir).catch(() => [] as string[]);
+ const entries = logicalEntries(physicalEntries);
const hasMeta = entries.includes(META_FILENAME);
const ytVttFile = resolvePrimaryVtt(entries);
const hasYtVtt = ytVttFile !== null;
@@ -270,6 +284,7 @@ export async function readVideoFiles(
audioFiles,
partAudioFiles,
entries,
+ physicalEntries,
};
}
diff --git a/common/lib/zstdSupport.d.mts b/common/lib/zstdSupport.d.mts
@@ -0,0 +1,4 @@
+// Types for ./zstdSupport.mjs: the boot-time zstd assertion.
+export const ZSTD_NODE_NEEDED: ">= 22.15";
+export function zstdSupportProblem(z?: object, version?: string): string | null;
+export function assertZstdSupport(who: string, z?: object, version?: string): void;
diff --git a/common/lib/zstdSupport.mjs b/common/lib/zstdSupport.mjs
@@ -0,0 +1,29 @@
+// STORED TEXT NEEDS node:zlib's zstd (Node >= 22.15; 23.8 on the 23 line) —
+// asked ONCE AT BOOT by every process that may read the corpus (the editor's
+// instrumentation, every common/bin CLI through runIfEntryPoint, umtool's bin
+// and its bare-node readers through lib/storedText-read.mjs). A process on an
+// older Node would read every caption or chat stored as `.zst` as unreadable:
+// the index would drop their text, a lane would schedule work for them. So it
+// REFUSES TO START with this sentence instead of running degraded (REVIEW-1
+// F3, captions lane). Plain JS, no import but node:zlib: safe to load first.
+
+import zlib from "node:zlib";
+
+export const ZSTD_NODE_NEEDED = ">= 22.15";
+
+/** The problem, or null when this Node has zstd. @param {object} [z] node:zlib (a test passes a fake) @param {string} [version] */
+export function zstdSupportProblem(z = zlib, version = process.version) {
+ const ok =
+ typeof z.zstdDecompress === "function" &&
+ typeof z.createZstdCompress === "function" &&
+ typeof z.createZstdDecompress === "function";
+ return ok
+ ? null
+ : `stored text (captions and live chats stored as .zst) needs node:zlib zstd — Node ${ZSTD_NODE_NEEDED} (this is ${version})`;
+}
+
+/** Throws the problem, naming who refuses. @param {string} who @param {object} [z] @param {string} [version] */
+export function assertZstdSupport(who, z = zlib, version = process.version) {
+ const p = zstdSupportProblem(z, version);
+ if (p) throw new Error(`${who} refuses to start: ${p}`);
+}
diff --git a/common/package.json b/common/package.json
@@ -79,6 +79,8 @@
"./lib/sourceStatus.mjs": "./lib/sourceStatus.mjs",
"./lib/sourceStatus-server.mjs": "./lib/sourceStatus-server.mjs",
"./lib/videoDir-server.mjs": "./lib/videoDir-server.mjs",
+ "./lib/storedText-read.mjs": "./lib/storedText-read.mjs",
+ "./lib/zstdSupport.mjs": "./lib/zstdSupport.mjs",
"./lib/videoDirId.mjs": "./lib/videoDirId.mjs",
"./ytdlp/platformArgs.mjs": "./ytdlp/platformArgs.mjs",
"./lib/*": "./lib/*.ts",
diff --git a/common/publish/composeReports.ts b/common/publish/composeReports.ts
@@ -71,11 +71,12 @@
import { isLocalRecord } from "../lib/localMedia";
import { pageCaptureView, pageCopyLinks } from "../lib/waybackPages/view";
-import { copyFile, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises";
+import { copyFile, mkdir, rm, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import { publishFileSizeProblem } from "../lib/builtExport";
import type { Paths } from "../lib/paths";
import { resolveVideoDir } from "../lib/videoDir-server.mjs";
+import { isStoredTextReadError, readStoredText, readdirLogical } from "../lib/storedText-server";
import { type Site } from "../lib/site";
import { storeReportDir } from "../lib/report/store";
import { getSettings } from "../lib/settings";
@@ -295,11 +296,15 @@ export type CitedRecord = {
wayback: WaybackProvenance | null;
};
-async function readCues(file: string, kind: "vtt" | "whisper"): Promise<Cue[]> {
+// Either form (lib/storedText.ts): a caption stored as `.zst` is read.
+async function readCues(dir: string, name: string, kind: "vtt" | "whisper"): Promise<Cue[]> {
try {
- const raw = await readFile(file, "utf8");
+ const raw = await readStoredText(dir, name, "utf8");
return kind === "vtt" ? parseVtt(raw) : parseTranscriptJson(raw);
- } catch {
+ } catch (err) {
+ // A stored track that does not decode is an error, never "no cues": a
+ // quote checked against nothing would read as not said (REVIEW-1 F3).
+ if (isStoredTextReadError(err)) throw err;
return [];
}
}
@@ -315,7 +320,8 @@ export async function readCitedRecord(
// The record's directory: a Twitch record's v<n> is data/<n>/ (release 23
// F1b). The record keeps the id it is cited by.
const dir = await resolveVideoDir(channelsDir, slug, id);
- const entries = await readdir(dir).catch(() => [] as string[]);
+ // LOGICAL (lib/storedText.ts): a stored caption is listed under its name.
+ const entries = await readdirLogical(dir);
if (entries.length === 0) return null;
let summary: CitedRecord["summary"] | null = null;
let cues: Cue[] = [];
@@ -332,7 +338,7 @@ export async function readCitedRecord(
const meta = await loadRawMetadataFromDir(dir);
if (!meta) return null;
summary = summarize(slug, id, meta, channelName);
- if (entries.includes(WHISPER_FILENAME)) cues = await readCues(path.join(dir, WHISPER_FILENAME), "whisper");
+ if (entries.includes(WHISPER_FILENAME)) cues = await readCues(dir, WHISPER_FILENAME, "whisper");
}
// The caption-track rule (videoStatus.ts): the first English VTT, `en-orig`
// first, that has cues.
@@ -343,11 +349,11 @@ export async function readCitedRecord(
if (n?.cues?.length) tracks.push({ name: path.basename(fresh.cuesPath), cues: n.cues });
}
if (entries.includes(WHISPER_FILENAME)) {
- const w = await readCues(path.join(dir, WHISPER_FILENAME), "whisper");
+ const w = await readCues(dir, WHISPER_FILENAME, "whisper");
if (w.length > 0) tracks.push({ name: WHISPER_FILENAME, cues: w });
}
for (const name of englishVttsByPreference(entries)) {
- const v = await readCues(path.join(dir, name), "vtt");
+ const v = await readCues(dir, name, "vtt");
if (v.length > 0) tracks.push({ name, cues: v });
}
if (tracks.length === 0 && cues.length > 0) tracks.push({ name: "cues", cues });
diff --git a/common/ytdlp/captionsRefetch.test.ts b/common/ytdlp/captionsRefetch.test.ts
@@ -0,0 +1,232 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { Paths } from "../lib/paths";
+import type { ChannelConfig } from "../lib/channelConfig";
+import { downloadOneManaged } from "./downloadOneManaged";
+import { storeFixture } from "../testing/storedTextFixture";
+import { readStoredText } from "../lib/storedText-server";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test ytdlp/captionsRefetch.test.ts
+//
+// A MANAGED RE-DOWNLOAD OVER A CAPTION STORED COMPRESSED (REVIEW-1 F1 of the
+// captions lane). Main's rule is kept: a re-download fetches the captions
+// again and the new file replaces the old one. Over a stored track the new
+// file lands beside it, and after the pass each such track is settled: the
+// same content keeps the stored form (the new copy dropped, nothing moves);
+// new content with cues replaces it, only once whole; nothing, a `.part`, an
+// empty or cue-less file leaves the stored track untouched. The job log says
+// which, per track. The yt-dlp is a temp node script; no network.
+
+const ID = "Zz0capRefet";
+const VIDEO = `https://www.youtube.com/watch?v=${ID}`;
+const EN = "transcript.en.vtt";
+
+// The prefetch writes the info json; the subtitle pass copies whatever the
+// scenario put in `landing/` into the video dir (what yt-dlp would write, not
+// seeing a .zst), or exits 1 as for a video that is gone. Any other pass (an
+// audio download) writes audio.mp3.
+const FAKE_YTDLP = `#!/usr/bin/env node
+const fs = require("node:fs");
+const path = require("node:path");
+const argv = process.argv.slice(2);
+const root = process.env.FAKE_ROOT;
+fs.appendFileSync(path.join(root, "argv.log"), JSON.stringify(argv) + "\\n");
+const has = (f) => argv.includes(f);
+const dir = path.join("data", "${ID}");
+fs.mkdirSync(dir, { recursive: true });
+if (has("--skip-download") && has("--write-info-json") && has("--no-write-subs")) {
+ fs.copyFileSync(path.join(root, "meta.json"), path.join(dir, "metadata.info.json"));
+ process.exit(0);
+}
+if (has("--write-subs")) {
+ if (fs.existsSync(path.join(root, "gone"))) { console.error("ERROR: [youtube] ${ID}: Video unavailable. This video has been removed by the uploader"); process.exit(1); }
+ for (const n of fs.readdirSync(path.join(root, "landing"))) fs.copyFileSync(path.join(root, "landing", n), path.join(dir, n));
+ process.exit(0);
+}
+fs.writeFileSync(path.join(dir, "audio.mp3"), "AUDIO");
+process.exit(0);
+`;
+
+const vtt = (words: string) =>
+ `WEBVTT\n\n00:00:00.000 --> 00:00:02.000\n${words}\n\n00:00:02.000 --> 00:00:04.000\n${words} again\n`;
+const OLD = vtt("the stored words");
+const META = {
+ id: ID,
+ title: "A video",
+ duration: 600,
+ upload_date: "20260101",
+ webpage_url: VIDEO,
+ automatic_captions: { en: [{ ext: "vtt" }] },
+};
+
+async function runWith(landing: Record<string, string>, opts: { gone?: boolean; handling?: "youtube" | "transcribe" } = {}) {
+ const root = await mkdtemp(path.join(tmpdir(), "captions-refetch-"));
+ const ytdlp = path.join(root, "fake-ytdlp.cjs");
+ await writeFile(ytdlp, FAKE_YTDLP);
+ await chmod(ytdlp, 0o755);
+ await writeFile(path.join(root, "meta.json"), JSON.stringify(META));
+ await mkdir(path.join(root, "landing"));
+ for (const [n, t] of Object.entries(landing)) await writeFile(path.join(root, "landing", n), t);
+ if (opts.gone) await writeFile(path.join(root, "gone"), "");
+ process.env.FAKE_ROOT = root;
+ const paths = {
+ transcriptsDir: root,
+ channelsDir: path.join(root, "channels"),
+ savedVideosDir: path.join(root, "saved-videos"),
+ ytdlpBin: ytdlp,
+ ffmpegBin: path.join(root, "no-ffmpeg"),
+ ffprobeBin: path.join(root, "no-ffprobe"),
+ } as Paths;
+ const videoDir = path.join(paths.channelsDir, "c", "data", ID);
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify(META));
+ await writeFile(path.join(videoDir, EN), OLD);
+ await storeFixture(videoDir, EN);
+ const storedMtime = (await stat(path.join(videoDir, `${EN}.zst`))).mtimeMs;
+ let log = "";
+ const record = await downloadOneManaged({
+ channelSlug: "c",
+ channelConfig: { handling: opts.handling ?? "youtube", url: "https://www.youtube.com/@c/videos" } as ChannelConfig,
+ paths,
+ videoUrl: VIDEO,
+ onLog: (s) => {
+ log += s;
+ },
+ signal: new AbortController().signal,
+ });
+ const argvs = (await readFile(path.join(root, "argv.log"), "utf8").catch(() => ""))
+ .split("\n")
+ .filter(Boolean)
+ .map((l) => JSON.parse(l) as string[]);
+ return {
+ record,
+ log,
+ videoDir,
+ storedMtime,
+ subPasses: argvs.filter((a) => a.includes("--write-subs")),
+ captions: (await readdir(videoDir)).filter((f) => f.startsWith("transcript.") && !f.endsWith(".json")).sort(),
+ cleanup: () => rm(root, { recursive: true, force: true }),
+ };
+}
+
+test("the caption is asked for again (main's re-download rule): no stored track left out of --sub-langs", async () => {
+ const r = await runWith({ [EN]: OLD });
+ try {
+ assert.equal(r.subPasses.length, 1, r.log);
+ const langs = r.subPasses[0][r.subPasses[0].indexOf("--sub-langs") + 1];
+ assert.ok(!/-en\b/.test(langs), `no exclusion: ${langs}`);
+ } finally {
+ await r.cleanup();
+ }
+});
+
+test("fetched again with the SAME content: the stored form stays, its mtime unchanged; the new copy dropped", async () => {
+ const r = await runWith({ [EN]: OLD });
+ try {
+ assert.deepEqual(r.captions, [`${EN}.zst`]);
+ assert.equal((await stat(path.join(r.videoDir, `${EN}.zst`))).mtimeMs, r.storedMtime, "nothing moved: the index sees nothing");
+ assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with the same content; the stored track is kept/);
+ } finally {
+ await r.cleanup();
+ }
+});
+
+test("fetched again with NEW content that has cues: it is the track, and the stored one is gone", async () => {
+ const NEW = vtt("the corrected manual words");
+ const r = await runWith({ [EN]: NEW });
+ try {
+ assert.deepEqual(r.captions, [EN]);
+ assert.equal(await readFile(path.join(r.videoDir, EN), "utf8"), NEW);
+ assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with new content; the new track replaces the stored one \(2 cues/);
+ } finally {
+ await r.cleanup();
+ }
+});
+
+test("a video that is gone returns nothing: the stored caption stays", async () => {
+ const r = await runWith({}, { gone: true });
+ try {
+ assert.deepEqual(r.captions, [`${EN}.zst`]);
+ assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD);
+ assert.match(r.log, /Captions transcript\.en\.vtt: nothing was fetched; the stored track is kept/);
+ } finally {
+ await r.cleanup();
+ }
+});
+
+test("a fetch that left a .part: the stored track untouched", async () => {
+ const r = await runWith({ [`${EN}.part`]: "WEBVTT\n\n00:00:00.000 --> 00:0" });
+ try {
+ assert.ok(r.captions.includes(`${EN}.zst`));
+ assert.ok(!r.captions.includes(EN));
+ assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD);
+ assert.match(r.log, /Captions transcript\.en\.vtt: the fetch did not finish \(a \.part\); the stored track is kept/);
+ } finally {
+ await r.cleanup();
+ }
+});
+
+for (const [what, body] of [["an empty file", ""], ["a header with no cue", "WEBVTT\n\n"]] as const) {
+ test(`fetched again as ${what}: dropped, the stored track untouched`, async () => {
+ const r = await runWith({ [EN]: body });
+ try {
+ assert.deepEqual(r.captions, [`${EN}.zst`]);
+ assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD);
+ assert.match(r.log, /Captions transcript\.en\.vtt: fetched again with no cues; dropped, the stored track is kept/);
+ } finally {
+ await r.cleanup();
+ }
+ });
+}
+
+test("a track that is NEW (not stored before) is not settled: it lands as yt-dlp wrote it", async () => {
+ const ORIG = vtt("what was said");
+ const r = await runWith({ [EN]: OLD, "transcript.en-orig.vtt": ORIG });
+ try {
+ assert.deepEqual(r.captions, ["transcript.en-orig.vtt", `${EN}.zst`]);
+ assert.doesNotMatch(r.log, /Captions transcript\.en-orig\.vtt/);
+ } finally {
+ await r.cleanup();
+ }
+});
+
+test("replaceAutoSubs's audio download (transcribe handling) asks for no caption and leaves the stored one untouched", async () => {
+ const r = await runWith({ [EN]: vtt("must not land") }, { handling: "transcribe" });
+ try {
+ assert.equal(r.subPasses.length, 0, "no subtitle pass");
+ assert.ok(r.captions.includes(`${EN}.zst`));
+ assert.ok(!r.captions.includes(EN));
+ assert.equal(await readStoredText(r.videoDir, EN, "utf8"), OLD);
+ assert.doesNotMatch(r.log, /Captions transcript\.en\.vtt/);
+ } finally {
+ await r.cleanup();
+ }
+});
+
+// REVIEW-2 N1: the new plain file and its dir are fsynced BEFORE the stored
+// copy goes (yt-dlp never fsyncs; a power cut must not leave a zero-length
+// caption and no stored form). The seam runs between the two.
+test("replaced: the new file is synced while the stored copy is still there; only then the stored copy goes", async () => {
+ const { setRefetchSyncedHookForTest, settleRefetchedCaptions } = await import("../lib/storedText-write-server");
+ const { mkdtemp: mk } = await import("node:fs/promises");
+ const dir = path.join(await mk(path.join(tmpdir(), "settle-order-")), "channels", "c", "data", "v1");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, EN), OLD);
+ await storeFixture(dir, EN);
+ await writeFile(path.join(dir, EN), vtt("new words"));
+ const seen: string[][] = [];
+ setRefetchSyncedHookForTest(async (d) => void seen.push((await readdir(d)).sort()));
+ try {
+ const out = await settleRefetchedCaptions(dir, ["en"]);
+ assert.equal(out[0].status, "replaced");
+ } finally {
+ setRefetchSyncedHookForTest(undefined);
+ }
+ assert.deepEqual(seen, [[".stored-text.lock", EN, `${EN}.zst`]], "synced with both forms on disk (under the file's lock)");
+ assert.deepEqual((await readdir(dir)).sort(), [EN]);
+ await rm(path.dirname(path.dirname(path.dirname(path.dirname(dir)))), { recursive: true, force: true });
+});
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -70,7 +70,13 @@ import { evaluateDownloadFilters } from "../lib/downloadFilters";
import { normalizeLiveChat } from "../controller/normalizeLiveChat";
import { writeCuesAfterDownload } from "../controller/normalizeTranscript";
import { LIVE_CHAT_FILENAME } from "../lib/videoStatus";
-import { listingHas, storedFormsIn } from "../lib/storedText";
+import {
+ listingHas,
+ logicalEntries,
+ storedFormsIn,
+ storedOnlyCaptionTracks,
+} from "../lib/storedText";
+import { settleRefetchedCaptions } from "../lib/storedText-write-server";
import {
upsertMetadataScan,
type MetadataScanEntry,
@@ -293,11 +299,21 @@ export type ManagedDownloadOpts = {
// an ERROR and a non-zero exit. `--sleep-subtitles` is the pace before each
// subtitle request — the request YouTube throttles — never below `-t sleep`'s 5.
//
-// A CHAT ALREADY STORED (`chatStored`, lib/storedText.ts): yt-dlp's own
-// "already present" skip looks for the plain `transcript.live_chat.json`, so
-// over a compressed one it would fetch the whole replay again. The chat is
-// left out of the sub-langs instead, as for a `later` channel. Exported for
-// its test.
+// A CHAT ALREADY STORED (`chatStored`, lib/storedText.ts) is left out of the
+// sub-langs, as for a `later` channel: this pass runs without
+// `--no-overwrites`, and yt-dlp's default REPLACES a subtitle file it finds —
+// over a compressed chat it finds none and fetches the whole replay again,
+// which is often shorter than the live capture (lane text-compress, REVIEW-2
+// R1: no capture is replaced because another arrived).
+//
+// A CAPTION TRACK STORED COMPRESSED IS FETCHED AGAIN, as on main (AGENTS.md:
+// "YouTube's subtitles are fetched again first, as on any re-download"): main
+// replaced a plain caption with the new download. Over a stored one the new
+// file lands beside it, and the caller settles each such track after the pass
+// (settleRefetchedCaptions, lib/storedText-write-server.ts): the same content
+// keeps the stored form, new content with cues replaces it — only once the
+// new file is whole — and nothing, a `.part` or an empty file leaves the
+// stored track untouched. Exported for its test.
export function youtubeHandlingArgs(
config: ChannelConfig,
reuseInfoJson = false,
@@ -671,8 +687,11 @@ async function sourceMediaPartials(videoDir: string): Promise<string[]> {
return out;
}
+// LOGICAL (lib/storedText.ts): a caption stored as `transcript.en.vtt.zst` is
+// a transcript on disk — a miss here downloads the audio and queues a
+// transcription for a video that has captions.
async function hasAnyTranscriptOnDisk(videoDir: string): Promise<boolean> {
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const entries = logicalEntries(await readdir(videoDir).catch(() => [] as string[]));
return entries.some((e) => {
if (e === "transcript.json") return true;
const m = e.match(
@@ -685,6 +704,9 @@ async function hasAnyTranscriptOnDisk(videoDir: string): Promise<boolean> {
});
}
+// Exported for the unit test ONLY (controller/storedText.captions.test.ts).
+export const __hasAnyTranscriptOnDiskForTest = hasAnyTranscriptOnDisk;
+
// Listed, none of them (lib/listedCaptions-server.ts — the one rule): the
// no-subs fallback's reason to fetch audio. No readable metadata says nothing.
async function metadataReportsNoCaptions(
@@ -1323,13 +1345,15 @@ async function runManagedDownload(
// its own args; youtube handling downloads subtitles (the persistence plan only
// applies to the no-subs fallback below). For transcribe handling the plan
// chooses audio-only vs. keep-source-video and yt-dlp vs. app extraction.
- const chatStored =
+ // What is stored compressed in the video's dir (lib/storedText.ts): the
+ // chat (left out of the subtitle request) and the caption tracks (fetched
+ // again, then settled against the stored form after the pass).
+ const storedListing =
opts.channelConfig.handling === "youtube" && canonicalId
- ? storedFormsIn(
- await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[]),
- LIVE_CHAT_FILENAME,
- ) === "zst"
- : false;
+ ? await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[])
+ : [];
+ const chatStored = storedFormsIn(storedListing, LIVE_CHAT_FILENAME) === "zst";
+ const storedCaptionTracks = storedOnlyCaptionTracks(storedListing);
const mediaArgs =
opts.channelConfig.handling === "youtube"
? [
@@ -1632,6 +1656,14 @@ async function runManagedDownload(
}
}
+ // THE CAPTIONS FETCHED AGAIN OVER STORED ONES (REVIEW-1 F1, captions lane):
+ // each track that was stored-only before the pass is settled now — after
+ // every subtitle-fetching attempt, before anything reads the dir — whether
+ // the pass succeeded or not (a whole file it landed is judged on its own).
+ if (storedCaptionTracks.length > 0 && canonicalId) {
+ await settleRefetchedCaptions(path.join(channelDir, "data", canonicalId), storedCaptionTracks, opts.onLog);
+ }
+
// A RATE-LIMITED DOWNLOAD FALLS BACK TO THE STORED URL (release 32 R7): the
// measured case — yt-dlp's own fetch of Odysee's original file answered 429
// while the player's ranged reads of it answered 206.
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -2,7 +2,12 @@
// process's outward doors refuse before any request.
import "../lib/noNetwork.mjs";
import { tierChannelMedia } from "../lib/mediaTier-server";
-import { logicalEntries, storedFormsIn } from "../lib/storedText";
+import {
+ excludeSubTracks,
+ logicalEntries,
+ storedFormsIn,
+ storedOnlyCaptionTracks,
+} from "../lib/storedText";
import path from "node:path";
import { mkdir, readdir, readFile } from "node:fs/promises";
import { writeFileAtomic } from "../lib/jsonFile-server";
@@ -1483,13 +1488,22 @@ function compileSubLangMatcher(spec: string): (track: string) => boolean {
const SUB_EXT_PATTERN = "(?:vtt|json|json3|srv1|srv2|srv3)";
-// One video's `--sub-langs` for the missing-subs fetch. A chat stored
-// compressed (lib/storedText.ts) is on disk, but yt-dlp's own "already
-// present" skip looks for the plain name and would fetch the whole replay
-// again: it is left out, as for a `later` channel. Exported for its test.
+// One video's `--sub-langs` for the missing-subs fetch, from its PHYSICAL
+// listing. This pass runs with `--no-overwrites`, under which yt-dlp skips a
+// track that is "already present" — by the PLAIN name only. A chat or a
+// caption track stored compressed (lib/storedText.ts) is on disk, so it is
+// left out, keeping main's behaviour (fetch only what is missing) instead of
+// landing a second copy beside it: a stored chat as for a `later` channel,
+// each stored caption by its code (`,-en,-en-orig`). (The managed download,
+// which runs WITHOUT `--no-overwrites` and so replaced a caption on main,
+// fetches stored captions again and settles them: downloadOneManaged.ts.)
+// Exported for its test.
export function subLangsForVideo(entries: readonly string[], subLangs: string): string {
- if (storedFormsIn(entries, LIVE_CHAT_FILENAME) !== "zst") return subLangs;
- return effectiveSubLangs({ subLangs, chat: "later" });
+ const chatLeftOut =
+ storedFormsIn(entries, LIVE_CHAT_FILENAME) === "zst"
+ ? effectiveSubLangs({ subLangs, chat: "later" })
+ : subLangs;
+ return excludeSubTracks(chatLeftOut, storedOnlyCaptionTracks(entries));
}
// Over a LOGICAL listing (lib/storedText.ts): a chat stored as
@@ -1807,7 +1821,9 @@ export async function destinationExists(
} = {},
): Promise<boolean> {
const dir = path.join(dataDir, id);
- const entries = await readdir(dir).catch(() => [] as string[]);
+ // LOGICAL (lib/storedText.ts): a caption stored as `transcript.en.vtt.zst`
+ // is the destination on disk — a miss here re-fetches the URL.
+ const entries = logicalEntries(await readdir(dir).catch(() => [] as string[]));
// A retry of a corrupt full source asks the source again whatever is on
// disk — the kept container, or a salvage transcript made from it (release
// 30, lane Q). Only the retry asks; a sweep still counts it as there.
diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md
@@ -13,6 +13,21 @@
live (`liveRecording.autoRestartOnBoot`); ended, what is in staging lands; unreadable, nothing starts.
- Parts that together hold more than the longest are joined `-c copy` when proven (length and sound at each join),
the joins on the row and in `live-joins.json`; a gap is stated and needs a person.
+- **The copies scan dates a re-upload by the stream's day, not the upload's, and says what it could not date.**
+ - Before, it dated every video by its channel's `recordedDate` rule, else its upload day. A re-upload channel with
+ no rule was dated by its uploads, months after the streams its live mirror held, and the scan answered "0
+ candidate pairs" with nothing to say why.
+ - Now each video is dated by the best evidence it has: the channel's rule, else a live stream's own day, else (no
+ rule set) a date the channel's titles carry in a shape the scan recognises (it must read at least half the
+ channel's videos that are not live streams), else the upload day. Each pair's members record where their date came from.
+ - The runtime search: on a channel with NO `recordedDate` rule, a video with only an upload day, or none, that
+ finds no candidate by date is compared, by its words, with the videos of the other channels whose runtimes agree
+ (its 8 nearest, at most 2,000 such pairs a scan). Such a pair is decided by its words only; without words on both
+ sides it is no pair, never a hold. A channel with a rule is never searched from, so a group whose channels all
+ have rules is scanned exactly as before.
+ - The scan's result and log carry `advice`: a channel dated from its titles with no rule set, with the exact
+ `pnpm ops channel-config` patch that sets one; videos dated only by their upload; and, when no two members'
+ videos are dated near each other, each member's dated span. `dating` gives each channel's count by source.
- **A clip window past the end of a saved recording is cut from the saved video, clamped at the end.**
- Before, the last clip of a recording asked for a window that ended past the saved container (its cut plus a
3 s pad). The window was "not-covering" and went to the platform's download queue: a network fetch for footage
@@ -109,6 +124,31 @@
stored chat again on purpose: the stored capture is kept as `chat-capture-kept.<stamp>.json.zst` and never
removed automatically; the log compares both. An empty replay leaves the stored capture the chat.
- Two different captures are never settled by deleting one. A second editor process waits for a video's lock.
+- **Caption tracks may be on disk compressed, and every reader still finds them.**
+ - A caption track (`transcript.en.vtt`, `transcript.en-orig.vtt`, any `transcript.<lang>.vtt`) may be stored as
+ `transcript.<lang>.vtt.zst`. Every reader reads either form with the same times: the index, normalize, the
+ snapshot's buckets, the caption-provenance sniff (it decodes the head), report compose, the remote worker's
+ inputs (sent plain), the clip tools. Nothing is fetched or transcribed again because a track is stored:
+ "already downloaded" and "has a transcript" count it, and a subtitle download leaves a stored track out of
+ `--sub-langs`.
+ - The superseded-auto-caption purge and the clear-transcript fix remove both forms; the purge keeps both when
+ they differ. The tier migration's reclaim takes a platter copy whose twin is stored only when it decodes to the
+ 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.
+ - A re-download still fetches a stored caption again, as before: the same content keeps the stored form, new
+ content with cues replaces it once whole, and nothing, a `.part` or an empty file leaves it; the job log says
+ which, per track. A refused pair is listed once, not on every run. Deleting a caption also removes a stopped
+ run's set-aside, so it cannot come back. Deleting a "Set as transcript" pick beside a stored `en` removes the pin.
+ - The editor, the CLIs and umtool refuse to start on a Node without zstd (>= 22.15 needed). A stored file that
+ does not decode is an error: the index keeps the record it had and says so.
- **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/channels/[slug]/videos/[id]/files/[name]/route.test.ts b/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.test.ts
@@ -66,3 +66,36 @@ test("a path that leaves the video dir is refused; a missing file is a 404", asy
});
assert.equal(missing.status, 404);
});
+
+// A CAPTION STORED COMPRESSED (lane text-compress-captions): the files card
+// previews `transcript.en.vtt.zst` as its decoded text (`?decoded=1`), and the
+// plain name answers the decoded text when only the stored form is on disk.
+// Without `?decoded=1` the stored name is its own file, bytes as they are.
+test("a stored caption: its decoded text by the plain name or ?decoded=1; its own bytes without", async () => {
+ const { encodeStoredBytes } = await import("yt-dlp-transcript-common/lib/storedText-server");
+ const text = "WEBVTT\n\n00:00:00.000 --> 00:00:01.000\nstored words\n";
+ const zst = await encodeStoredBytes(Buffer.from(text));
+ await writeFile(path.join(VIDEO_DIR, "transcript.en.vtt.zst"), zst);
+ const ask = (name: string, q = "") =>
+ GET(new Request(`http://localhost/api/channels/chan/videos/vidA/files/${name}${q}`), {
+ params: Promise.resolve({ slug: "chan", id: "vidA", name }),
+ });
+ const byPlain = await ask("transcript.en.vtt");
+ assert.equal(byPlain.status, 200);
+ assert.match(byPlain.headers.get("content-type") ?? "", /^text\/vtt/);
+ assert.equal(await byPlain.text(), text);
+ const decoded = await ask("transcript.en.vtt.zst", "?decoded=1");
+ assert.equal(decoded.status, 200);
+ assert.equal(await decoded.text(), text);
+ const raw = await ask("transcript.en.vtt.zst");
+ assert.equal(raw.status, 200);
+ assert.equal(raw.headers.get("content-type"), "application/octet-stream");
+ assert.deepEqual(Buffer.from(await raw.arrayBuffer()), zst);
+ // A plain file beside it is the truth: the plain name serves it as it is.
+ await writeFile(path.join(VIDEO_DIR, "transcript.en.vtt"), "WEBVTT\n\nnewer\n");
+ assert.equal(await (await ask("transcript.en.vtt")).text(), "WEBVTT\n\nnewer\n");
+ // …and the stored one, asked by its own name decoded, is still its own.
+ assert.equal(await (await ask("transcript.en.vtt.zst", "?decoded=1")).text(), text);
+ // Neither form: a 404.
+ assert.equal((await ask("transcript.de.vtt")).status, 404);
+});
diff --git a/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.ts b/editor/app/api/channels/[slug]/videos/[id]/files/[name]/route.ts
@@ -1,6 +1,6 @@
import path from "node:path";
import { createReadStream, type ReadStream } from "node:fs";
-import { lstat, stat } from "node:fs/promises";
+import { lstat, readFile, stat } from "node:fs/promises";
import { NextResponse } from "next/server";
import { getPaths } from "yt-dlp-transcript-common/lib/paths";
import { makeSafeController } from "yt-dlp-transcript-common/lib/safeStreamController";
@@ -15,6 +15,8 @@ import {
isDriveNotAnswering,
onDrive,
} from "yt-dlp-transcript-common/lib/storageHealth";
+import { isStoredCaptionName, plainNameOf, storedNameOf } from "yt-dlp-transcript-common/lib/storedText";
+import { decodeStoredBytes, readStoredText } from "yt-dlp-transcript-common/lib/storedText-server";
export const dynamic = "force-dynamic";
@@ -168,6 +170,50 @@ export async function GET(
if (onMediaTier && channelMediaStall(channelConfig)) return notAnswering();
const drive = onMediaTier ? mediaDir || legacyDrive : legacyDrive;
+ // A CAPTION STORED COMPRESSED (lib/storedText.ts) is served as its text,
+ // decoded: asked by its stored name with `?decoded=1` (the files card's
+ // preview of `transcript.en.vtt.zst`), or by its plain name when only the
+ // stored form is on disk (a reader that asks for the track it was listed).
+ // Captions only — small text on the corpus disk; the raw chat is never read
+ // whole to be served. Without `?decoded=1` the stored name is its own file.
+ const decoded = new URL(request.url).searchParams.get("decoded") === "1";
+ const storedPlain = plainNameOf(name);
+ const captionOf =
+ decoded && storedPlain !== null && isStoredCaptionName(storedPlain)
+ ? storedPlain
+ : isStoredCaptionName(name) &&
+ !(await lstat(fullPath).then(() => true, () => false)) &&
+ (await lstat(path.join(path.dirname(fullPath), storedNameOf(name))).then(() => true, () => false))
+ ? name
+ : null;
+ if (captionOf !== null) {
+ const dir = path.dirname(fullPath);
+ let text: string;
+ try {
+ // Asked by the plain name: `readStoredText` (the plain file when it is
+ // there — the truth — else the stored form). Asked by the stored name:
+ // THAT file's bytes, decoded (its frame's checksum and length checked),
+ // whatever stands beside it.
+ const read = async () =>
+ captionOf === name
+ ? readStoredText(dir, captionOf, "utf8")
+ : (await decodeStoredBytes(await readFile(fullPath), name)).toString("utf8");
+ text = await (legacyDrive ? onDrive(legacyDrive, read) : read());
+ } catch (err) {
+ if (isDriveNotAnswering(err)) return notAnswering();
+ return NextResponse.json({ error: `Not read: ${(err as Error).message}` }, { status: 404 });
+ }
+ const body = Buffer.from(text, "utf8");
+ return new Response(body, {
+ status: 200,
+ headers: {
+ "Content-Type": contentTypeFor(captionOf),
+ "Content-Length": String(body.length),
+ "Cache-Control": "no-store",
+ },
+ });
+ }
+
let stats;
try {
stats = await (drive ? onDrive(drive, () => stat(fullPath)) : stat(fullPath));
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/channels/[slug]/incompleteTranscriptActions.ts b/editor/app/channels/[slug]/incompleteTranscriptActions.ts
@@ -198,8 +198,11 @@ export async function clearIncompleteTranscriptsAction(
let succeeded = 0;
for (const id of cleaned) {
try {
- await clearIncompleteTranscriptOne({ slug, videoId: id, paths });
- succeeded++;
+ const r = await clearIncompleteTranscriptOne({ slug, videoId: id, paths });
+ // A caption that could not be locked (a full disk) was refused, not
+ // removed: the video is not cleared, and says why.
+ if (r.refused?.length) failures.push({ videoId: id, error: r.refused.join("; ") });
+ else succeeded++;
} catch (e) {
failures.push({ videoId: id, error: (e as Error).message });
}
diff --git a/editor/app/channels/[slug]/lib/fixIncompleteTranscript.test.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.test.ts
@@ -0,0 +1,35 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm -C editor exec tsx --test "app/channels/*/lib/fixIncompleteTranscript.test.ts"
+//
+// CLEARING A TRUNCATED TRANSCRIPT CLEARS ITS CAPTIONS IN BOTH FORMS (lane
+// text-compress-captions). A track stored as `transcript.<lang>.vtt.zst`
+// (lib/storedText.ts) missed by the clear would bring the cleared transcript
+// back. Temp corpus, synthetic names.
+
+const ROOT = await mkdtemp(path.join(os.tmpdir(), "clear-incomplete-"));
+process.env.TRANSCRIPTS_DIR = ROOT;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+const { clearIncompleteTranscriptOne } = await import("./fixIncompleteTranscript");
+const { getPaths } = await import("yt-dlp-transcript-common/lib/paths");
+const { encodeStoredBytes } = await import("yt-dlp-transcript-common/lib/storedText-server");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+test("every caption track goes, stored or plain, and the metadata stays", async () => {
+ const dir = path.join(ROOT, "channels", "synth", "data", "vid00000001");
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(dir, "metadata.info.json"), "{}");
+ await writeFile(path.join(dir, "audio.mp3"), "A");
+ await writeFile(path.join(dir, "transcript.json"), "{}");
+ await writeFile(path.join(dir, "transcript.en.vtt.zst"), await encodeStoredBytes(Buffer.from("WEBVTT\n\nstored\n")));
+ await writeFile(path.join(dir, "transcript.en-orig.vtt"), "WEBVTT\n\nplain\n");
+ await writeFile(path.join(dir, "transcript.en-orig.vtt.zst"), await encodeStoredBytes(Buffer.from("WEBVTT\n\nolder\n")));
+ const out = await clearIncompleteTranscriptOne({ slug: "synth", videoId: "vid00000001", paths: getPaths() });
+ assert.equal(out.removed, 4, "audio, transcript.json and the two caption tracks (each in every form)");
+ assert.deepEqual(await readdir(dir), ["metadata.info.json"]);
+});
diff --git a/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts
@@ -11,6 +11,7 @@
import { removeMediaFile } from "yt-dlp-transcript-common/lib/mediaTier-server";
import { removeStoredText } from "yt-dlp-transcript-common/lib/storedText-write-server";
+import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText";
import path from "node:path";
import { readdir } from "node:fs/promises";
import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig";
@@ -132,7 +133,7 @@ export async function clearIncompleteTranscriptOne(opts: {
slug: string;
videoId: string;
paths: Paths;
-}): Promise<{ removed: number }> {
+}): Promise<{ removed: number; refused?: string[] }> {
const { slug, videoId, paths } = opts;
const videoDir = videoDirOf(paths, slug, videoId);
const dataDir = path.resolve(paths.channelsDir, slug, "data");
@@ -143,7 +144,9 @@ export async function clearIncompleteTranscriptOne(opts: {
`Refusing to clear: video path resolved outside the data dir (${videoId})`,
);
}
- const entries = await readdir(resolved).catch(() => [] as string[]);
+ // LOGICAL (lib/storedText.ts): a caption track stored as `.zst` is listed
+ // under its plain name, so it is cleared too (in both forms, below).
+ const entries = logicalEntries(await readdir(resolved).catch(() => [] as string[]));
const toRemove = entries.filter(
(name) =>
isRealAudioFile(name) ||
@@ -151,12 +154,16 @@ export async function clearIncompleteTranscriptOne(opts: {
name === "transcript.json" ||
name === "transcript.cues.json",
);
+ const refused: string[] = [];
for (const name of toRemove) {
// Through its link when tiered (release 17): the bytes go too. A caption
// track in both forms (lib/storedText-write-server.ts): a stored copy left
- // behind would bring the cleared transcript back.
- if (isTranscriptVtt(name)) await removeStoredText(resolved, name);
- else await removeMediaFile(resolved, name);
+ // behind would bring the cleared transcript back. One that cannot be
+ // locked (a full disk, a run holding it) is refused, nothing removed.
+ if (isTranscriptVtt(name)) {
+ const out = await removeStoredText(resolved, name);
+ if ("refused" in out) refused.push(out.refused);
+ } else await removeMediaFile(resolved, name);
}
- return { removed: toRemove.length };
+ return { removed: toRemove.length - refused.length, ...(refused.length ? { refused } : {}) };
}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx b/editor/app/channels/[slug]/videos/[id]/components/VideoPanel.tsx
@@ -50,6 +50,7 @@ import {
isAudioFile,
isTranscodeSource,
isTranscriptVttName,
+ logicalFileNames,
type VideoFile,
} from "./cards/videoFiles";
@@ -159,9 +160,10 @@ export function VideoPanel({
!hasTranscriptJson &&
primaryVtt !== null &&
vttProvenance[primaryVtt] === "asr";
- const vttTracks = files
- .filter((f) => isTranscriptVttName(f.name))
- .map((f) => f.name)
+ // LOGICAL (lib/storedText.ts): a track stored as `.zst` is listed under
+ // its plain name — the name every action on it takes.
+ const vttTracks = logicalFileNames(files)
+ .filter((name) => isTranscriptVttName(name))
.sort();
// The transcript the index/viewer will actually use: whisper wins over VTT.
const activeTranscript = hasTranscriptJson ? WHISPER_FILENAME : primaryVtt;
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx b/editor/app/channels/[slug]/videos/[id]/components/cards/FilesList.tsx
@@ -7,7 +7,7 @@ import { TextFilePreview } from "../TextFilePreview";
import {
deleteVideoFileAction,
} from "../../videoActions";
-import { mediaKind, mediaUrl, type VideoFile } from "./videoFiles";
+import { isStoredCaptionFile, mediaKind, mediaUrl, type VideoFile } from "./videoFiles";
export function FilesList({
slug,
@@ -27,7 +27,10 @@ export function FilesList({
className="flex flex-col gap-3"
>
{files.map((f) => {
- const kind = mediaKind(f.name);
+ // A caption stored compressed (`transcript.en.vtt.zst`, lib/storedText.ts)
+ // is listed as the file it is, and previewed as its decoded text.
+ const storedCaption = isStoredCaptionFile(f.name);
+ const kind = storedCaption ? "text" : mediaKind(f.name);
return (
<li
key={f.name}
@@ -53,7 +56,7 @@ export function FilesList({
/>
) : kind === "text" ? (
<TextFilePreview
- src={mediaUrl(slug, videoId, f.name)}
+ src={`${mediaUrl(slug, videoId, f.name)}${storedCaption ? "?decoded=1" : ""}`}
filename={f.name}
/>
) : null}
diff --git a/editor/app/channels/[slug]/videos/[id]/components/cards/videoFiles.ts b/editor/app/channels/[slug]/videos/[id]/components/cards/videoFiles.ts
@@ -2,6 +2,11 @@ import {
AUDIO_EXTS,
VIDEO_CONTAINER_EXTS,
} from "yt-dlp-transcript-common/lib/mediaFiles";
+import {
+ isStoredCaptionName,
+ logicalEntries,
+ plainNameOf,
+} from "yt-dlp-transcript-common/lib/storedText";
export type VideoFile = {
name: string;
@@ -21,6 +26,19 @@ export function isTranscriptVttName(name: string): boolean {
return /^transcript\.[^.]+\.vtt$/.test(name);
}
+// The files card's listing is PHYSICAL: a caption stored compressed is
+// `transcript.en.vtt.zst` there (lib/storedText.ts). Everything that MATCHES
+// names — which tracks there are, which is primary — takes this LOGICAL list
+// of it, where that file is `transcript.en.vtt`, once.
+export function logicalFileNames(files: readonly VideoFile[]): string[] {
+ return logicalEntries(files.map((f) => f.name));
+}
+
+export function isStoredCaptionFile(name: string): boolean {
+ const plain = plainNameOf(name);
+ return plain !== null && isStoredCaptionName(plain);
+}
+
// One list, shared with the detection predicates in lib/mediaFiles.ts — these
// were duplicated here and drifting. isAudioFile deliberately stays on
// AUDIO_EXTS alone: audio.mp4 is a wrong-format cleanup target, not something
diff --git a/editor/app/channels/[slug]/videos/[id]/page.tsx b/editor/app/channels/[slug]/videos/[id]/page.tsx
@@ -1,5 +1,6 @@
import type { Metadata } from "next";
import { LiveRecordingsAttention } from "../../../../components/LiveRecordingsAttention";
+import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText";
import Link from "next/link";
import { notFound } from "next/navigation";
import path from "node:path";
@@ -196,9 +197,11 @@ export default async function VideoDetailPage({
// auto-captions" vs "manual captions" — and offer to replace the former with a
// transcript of our own. One 4 KB head read per VTT (see subtitleProvenance).
const vttProvenance: Record<string, SubtitleProvenance> = {};
- for (const f of dirData.files) {
- if (!isTranscriptVtt(f.name)) continue;
- vttProvenance[f.name] = await resolveVttProvenance(videoDir, f.name);
+ // By LOGICAL name (lib/storedText.ts): a track stored as `.zst` is sniffed
+ // decoded, under its plain name.
+ for (const name of logicalEntries(dirData.files.map((f) => f.name))) {
+ if (!isTranscriptVtt(name)) continue;
+ vttProvenance[name] = await resolveVttProvenance(videoDir, name);
}
const cov = await readTranscriptCoverage(videoDir);
const coverage = cov
@@ -425,7 +428,7 @@ export default async function VideoDetailPage({
// Read HERE, in the server component, never in the client one: an env
// var does not exist in the browser. Unset means no link at all.
umtoolUrl={process.env.UMTOOL_URL?.replace(/\/+$/, "") || null}
- primaryVtt={resolvePrimaryVtt(dirData.files.map((f) => f.name))}
+ primaryVtt={resolvePrimaryVtt(logicalEntries(dirData.files.map((f) => f.name)))}
vttProvenance={vttProvenance}
handling={config.handling}
defaultQueueKey={defaultQueueKey}
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -61,6 +61,8 @@ import {
import { onDrive } from "yt-dlp-transcript-common/lib/storageHealth";
import { isTierable } from "yt-dlp-transcript-common/lib/mediaTier";
import { removeStoredTextForm } from "yt-dlp-transcript-common/lib/storedText-write-server";
+import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText";
+import { readStoredText } from "yt-dlp-transcript-common/lib/storedText-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";
@@ -756,7 +758,8 @@ export async function whisperVideoAction(
: await transcriptionContainer({ paths, slug, videoDir, entries: firstEntries });
if (!audioOnDisk && asr !== true && r.config.handling === "youtube") {
- const onDisk = englishVttsByPreference(firstEntries);
+ // LOGICAL (lib/storedText.ts): a caption stored as `.zst` is on disk.
+ const onDisk = englishVttsByPreference(logicalEntries(firstEntries));
if (onDisk.length > 0) {
return {
ok: false,
@@ -1080,18 +1083,25 @@ export async function deleteVideoFileAction(
if (out === "busy") {
return { ok: false, error: `${filename} not deleted: it is being compressed or restored right now. Try again in a moment.` };
}
+ if ("refused" in out) return { ok: false, error: out.refused };
+ // The pick deleted beside a stored `en` of other content: the pin went with
+ // it (removeStoredTextForm; REVIEW-1 N1, captions lane).
+ const unpinned = out.unpinned === true;
revalidatePath(`/channels/${slug}/videos/${videoId}`);
requestChannelSnapshot(getPaths(), slug);
if (out.kept) {
const k = out.kept;
+ const pinNote = unpinned
+ ? " The transcript pin was removed with it: the caption-track rule picks the transcript again."
+ : "";
return {
ok: true,
note:
- k.same === "same"
- ? `Deleted ${filename} only. ${k.name} is still here with the same content: readers still see the chat.`
+ (k.same === "same"
+ ? `Deleted ${filename} only. ${k.name} is still here with the same content: readers still read it.`
: k.same === "differs"
? `Deleted ${filename} only. ${k.name} is still here with different content, and is the file readers read.`
- : `Deleted ${filename} only. ${k.name} is still here (it could not be read whole to compare).`,
+ : `Deleted ${filename} only. ${k.name} is still here (it could not be read whole to compare).`) + pinNote,
};
}
return { ok: true };
@@ -1122,10 +1132,16 @@ export async function setPrimaryTranscriptAction(
}
let raw: string;
try {
- raw = await readFile(source, "utf8");
+ // Either form (lib/storedText.ts): a track stored as `.zst` is read.
+ raw = await readStoredText(videoDir, path.basename(source), "utf8");
} catch {
return { ok: false, error: `File not found: ${filename}` };
}
+ // The copy is written under the plain name. A STORED `transcript.en.vtt.zst`
+ // beside it (YouTube's own `en` track, compressed) is NOT removed: the new
+ // plain file is what every reader reads (lib/storedText.ts, plain is the
+ // truth), and the earlier track stays beside it — both forms, different
+ // content, which compress-text lists and never settles by deleting one.
if (filename !== VTT_FILENAME) {
await writeFileAtomic(path.join(videoDir, VTT_FILENAME), raw);
}
diff --git a/editor/app/channels/[slug]/videos/page.tsx b/editor/app/channels/[slug]/videos/page.tsx
@@ -1,5 +1,6 @@
import path from "node:path";
import type { Metadata } from "next";
+import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText";
import { notFound } from "next/navigation";
import { isSocialChannel } from "yt-dlp-transcript-common/lib/channelConfig";
import type { ChannelSnapshot } from "yt-dlp-transcript-common/controller/channelSnapshot";
@@ -249,7 +250,7 @@ export default async function ChannelVideosPage({
slug={slug}
videoId={selectedVideoId}
files={dirData.files}
- primaryVtt={resolvePrimaryVtt(dirData.files.map((f) => f.name))}
+ primaryVtt={resolvePrimaryVtt(logicalEntries(dirData.files.map((f) => f.name)))}
handling={config.handling}
defaultQueueKey={platformDefaultQueueKey}
existingQueues={existingQueues}
diff --git a/editor/app/instrumentation.test.ts b/editor/app/instrumentation.test.ts
@@ -0,0 +1,35 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { spawnSync } from "node:child_process";
+import { mkdtemp, rm, writeFile } from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm -C editor exec tsx --test app/instrumentation.test.ts
+//
+// REVIEW-1 F3 (captions lane): on a Node without zstd the editor REFUSES TO
+// START — register() says which Node it needs and exits — instead of running
+// with every stored caption and chat unreadable. The check is the first thing
+// register() does in the Node runtime, before any runner is armed.
+
+const EDITOR = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+
+test("register() on a Node without zstd: the editor refuses to start, naming the Node it needs", async (t) => {
+ const own = await mkdtemp(path.join(os.tmpdir(), "editor-no-zstd-"));
+ t.after(() => rm(own, { recursive: true, force: true }));
+ const preload = path.join(own, "no-zstd.mjs");
+ await writeFile(preload, 'import zlib from "node:zlib";\nfor (const k of ["zstdDecompress", "createZstdCompress", "createZstdDecompress"]) delete zlib[k];\n');
+ const tsx = path.join(EDITOR, "..", "node_modules", ".bin", "tsx");
+ const script = `import(${JSON.stringify(path.join(EDITOR, "instrumentation.ts"))}).then((m) => m.register()).then(() => console.log("BOOTED"));`;
+ const r = spawnSync(tsx, ["-e", script], {
+ cwd: EDITOR,
+ encoding: "utf8",
+ timeout: 60_000,
+ env: { ...process.env, NODE_OPTIONS: `--import=${preload}`, NEXT_RUNTIME: "nodejs", TRANSCRIPTS_DIR: own, SETTINGS_FILE: path.join(own, "s.json") },
+ });
+ assert.equal(r.status, 1, r.stdout + r.stderr);
+ assert.doesNotMatch(r.stdout, /BOOTED/);
+ assert.match(r.stderr, /editor refuses to start: stored text .*needs node:zlib zstd — Node >= 22\.15/);
+});
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/editor/instrumentation.ts b/editor/instrumentation.ts
@@ -19,6 +19,18 @@ export async function register() {
// its transitive imports (runTick -> server actions, lmdb, fs) are Node-only,
// so guard the import — and run nothing on Edge.
if (process.env.NEXT_RUNTIME !== "nodejs") return;
+ // STORED TEXT NEEDS node:zlib zstd (common/lib/zstdSupport.mjs): on an older
+ // Node every caption or chat stored as `.zst` would read as unreadable — the
+ // index would drop its text, a lane would schedule work for it. The editor
+ // refuses to start instead of running degraded (REVIEW-1 F3, captions lane).
+ {
+ const { zstdSupportProblem } = await import("yt-dlp-transcript-common/lib/zstdSupport.mjs");
+ const problem = zstdSupportProblem();
+ if (problem) {
+ console.error(`editor refuses to start: ${problem}`);
+ process.exit(1);
+ }
+ }
// ARCHILYZER_NO_NETWORK (common/lib/noNetwork.mjs) is the test harness's switch. A server booted with it reaches
// no site at all, so it is said first and loudly: set by accident in a service unit, it must not pass for a
// normal boot.
diff --git a/scripts/archilyzer-ops.mjs b/scripts/archilyzer-ops.mjs
@@ -2512,36 +2512,45 @@ 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 once (recorded per channel; not visited again until a form",
+ " changes): 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',
@@ -3331,8 +3340,18 @@ export function usage() {
'copies-scan pairs a source group\'s channels video by video: {"group",',
' "dryRun"?} -> {jobId}. The group is settings.sourceGroups\' (an ordered',
" list of channels holding the same recordings, the preferred source first;",
- " pnpm ops settings sets it). Two videos are candidates when their recorded",
- " dates are at most dateWindowDays apart. Where both have a cue file their",
+ " pnpm ops settings sets it). Two videos are candidates when their dates",
+ " are at most dateWindowDays apart. A video is dated by the best evidence",
+ " it has: its channel's recordedDate rule, else a live stream's own day,",
+ " else (no rule set) a date the channel's titles carry in a shape the scan",
+ " recognises, else its upload day. On a channel with no rule, a video with",
+ " only an upload day (on a re-upload channel, the copy's day) or none, and",
+ " no candidate by date, is looked for by runtime instead: its 8 nearest",
+ " agreeing runtimes on the other channels, at most 2,000 such pairs a",
+ " scan, decided by their words",
+ " only (no words, no pair). The result's advice says what the scan could",
+ " not date well, with the exact channel-config patch that sets a",
+ " channel's rule. Where both have a cue file their",
" words decide, probed both ways (40 phrases each way, each counted once):",
" each copy holding at least 75 % of the other AND runtimes within the",
" group's tolerance is confirmed; one inside the other, or the words the",
@@ -3348,7 +3367,7 @@ export function usage() {
" reported only (get copies says each one's reason). Cancelling the job",
" stops it with nothing written; dryRun writes nothing. The log ends with",
" @@copies-scan {group, dryRun, unchanged, file?, channels, missing?,",
- " totals}.",
+ " totals, dating, advice?}.",
"",
'copies-release releases copies to their lanes: {"group", "video":',
' "<channel>/<dir>" | "videos": [...], "undo"?, "note"?, "by"?} ->',
diff --git a/umtool/bin/umtool.mjs b/umtool/bin/umtool.mjs
@@ -148,6 +148,7 @@
// umtool candidates <project> [ls | import <sweep.md> | add <json>] proposed clips for the Cut tab's Candidates panel
// umtool ingredient <channel>/<video> [--window <from>-<to>] [--used-in] [--json] a recording's life cycle, nine stages (/ingredients)
import process from "node:process";
+import { zstdSupportProblem } from "yt-dlp-transcript-common/lib/zstdSupport.mjs";
import {
PROJECT_KINDS,
REPORTS_ROOT,
@@ -202,6 +203,15 @@ import {
outDirState,
} from "../lib/report/storage.mjs";
+// It reads the corpus, where captions and chats may be stored as `.zst`: on a
+// Node without zstd it refuses to start (common/lib/zstdSupport.mjs).
+{
+ const zstd = zstdSupportProblem();
+ if (zstd) {
+ console.error(`umtool refuses to start: ${zstd}`);
+ process.exit(1);
+ }
+}
const argv = process.argv.slice(2);
const cmd = argv.find((a) => !a.startsWith("-")) ?? "help";
const rest = argv.filter((a) => a !== cmd);
diff --git a/umtool/lib/ingredients/stages.mjs b/umtool/lib/ingredients/stages.mjs
@@ -27,6 +27,7 @@ import { describeClock } from "yt-dlp-transcript-common/lib/recordingClock.mjs";
import { readRecordingClock } from "yt-dlp-transcript-common/lib/recordingClock-read.mjs";
import { audioFilesOf, present, readSavedVideoPointer, WIN_EPS } from "yt-dlp-transcript-common/lib/evidenceClip.mjs";
import { readChannelPlatform, recordIdOfVideoDir, resolveVideoDirId } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { logicalEntries } from "yt-dlp-transcript-common/lib/storedText-read.mjs";
import { archiveMomentUrl } from "umtool-report-to-video/site-links";
import { readLog } from "../research/log.mjs";
import { readQuoteCheck, rowIsCurrent } from "../report/quoteCheck.mjs";
@@ -221,7 +222,8 @@ async function downloadedStage({ idn }) {
const f = await fileState(dir, n);
if (f) media.push(f);
}
- const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n));
+ // LOGICAL (common/lib/storedText-read.mjs): a caption stored as `.zst` is a caption.
+ const vtts = logicalEntries(names).filter((n) => /^transcript\..+\.vtt$/.test(n));
const problems = [];
if (outcome && !outcome.status.startsWith("ok")) problems.push(`the last download ended ${outcome.status}`);
if (availability && !AVAILABLE.has(availability.availability)) problems.push(`the recording reads ${availability.availability} (checked ${availability.checkedAt ?? "?"})`);
@@ -276,7 +278,7 @@ async function transcribedStage({ idn }) {
const outcome = to && typeof to === "object" ? { at: to.transcribedAt ?? null, worker: to.worker?.appId ?? to.worker?.id ?? null, durationMs: fin(to.durationMs) ? to.durationMs : null, salvaged: !!to.salvaged } : null;
const words = await statOf(path.join(dir, "words.json"));
const names = await readdir(dir).catch(() => []);
- const vtts = names.filter((n) => /^transcript\..+\.vtt$/.test(n));
+ const vtts = logicalEntries(names).filter((n) => /^transcript\..+\.vtt$/.test(n));
const line = cues
? `${cues.source ?? "cues"}${cues.engine ?? outcome?.worker ? ` (${cues.engine ?? outcome?.worker})` : ""}${cues.coverage !== null ? `, ${Math.round(cues.coverage * 100)}% of ${hms(cues.duration)}` : ""}${outcome?.salvaged ? ", SALVAGED (gaps)" : ""}${words ? ", timed words" : ""}${pin ? ", pinned" : ""}`
: vtts.length
diff --git a/umtool/report-to-video/clip-words.mjs b/umtool/report-to-video/clip-words.mjs
@@ -21,6 +21,7 @@
import { readFile } from "node:fs/promises";
import path from "node:path";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { readStoredText } from "yt-dlp-transcript-common/lib/storedText-read.mjs";
import { hasLocalMedia } from "./local-media.mjs";
import { whisperWords } from "./montage.mjs";
@@ -105,7 +106,8 @@ export async function clipWords(entry, provenance, from, to, { channelsDir }) {
const cues = await json("transcript.cues.json");
const names = [...new Set([typeof cues?.vttFile === "string" ? path.basename(cues.vttFile) : null, "transcript.en-orig.vtt", "transcript.en.vtt"].filter(Boolean))];
for (const name of names) {
- const text = await readFile(path.join(dir, name), "utf8").catch(() => null);
+ // Either form (common/lib/storedText-read.mjs): a stored caption is read.
+ const text = await readStoredText(dir, name, "utf8").catch(() => null);
if (!text) continue;
const words = vttWordStarts(text).filter(inSpan);
if (words.length) return { words, timed: false, from: "captions" };
diff --git a/umtool/report-to-video/cues.mjs b/umtool/report-to-video/cues.mjs
@@ -64,6 +64,7 @@ import os from "node:os";
import { createHash } from "node:crypto";
import { fileURLToPath } from "node:url";
import { resolveVideoDir } from "yt-dlp-transcript-common/lib/videoDir-server.mjs";
+import { readdirLogical, readStoredTextHead, storedTextLogicalSize } from "yt-dlp-transcript-common/lib/storedText-read.mjs";
import { fetchOnOrigin, readJsonBounded, transcriptsManifestUrl } from "./archive-fetch.mjs";
// For the other readers of an archive that come through this module (linkCheck.mjs).
@@ -165,19 +166,23 @@ async function staleCaptionRecord(videoDir, record) {
if (record?.source !== "vtt" || record.captionTrackRule === CAPTION_TRACK_RULE_VERSION) {
return false;
}
- const entries = await readdir(videoDir).catch(() => []);
+ // LOGICAL (common/lib/storedText-read.mjs): a caption stored as
+ // `transcript.en.vtt.zst` is a track under its plain name; its head is read
+ // DECODED and its size is the LOGICAL one (the frame header's) — the raw
+ // bytes of a stored track would sniff and size as something else.
+ const entries = await readdirLogical(videoDir);
const english = entries.filter((e) => ENGLISH_VTT_RE.test(e));
if (!Array.isArray(record.cues) || record.cues.length === 0) {
if (english.length !== 1) return true;
- const head = (await readFile(path.join(videoDir, english[0]), "utf8").catch(() => "")).slice(0, 2048);
+ const head = (await readStoredTextHead(videoDir, english[0], 2048).catch(() => Buffer.alloc(0))).toString("utf8");
return !/<\d{2}:\d{2}:\d{2}\.\d{3}>/.test(head);
}
if (!entries.includes("transcript.en.vtt") || !entries.includes("transcript.en-orig.vtt")) return false;
const [en, orig] = await Promise.all([
- stat(path.join(videoDir, "transcript.en.vtt")),
- stat(path.join(videoDir, "transcript.en-orig.vtt")),
+ storedTextLogicalSize(videoDir, "transcript.en.vtt"),
+ storedTextLogicalSize(videoDir, "transcript.en-orig.vtt"),
]);
- return en.size !== orig.size;
+ return en !== orig;
}
export class CueLookupError extends Error {
diff --git a/umtool/report-to-video/cues.test.mjs b/umtool/report-to-video/cues.test.mjs
@@ -10,6 +10,7 @@ import test from "node:test";
import { mkdtemp, mkdir, symlink, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
+import { zstdCompressSync } from "node:zlib";
import {
CAPTION_TRACK_RULE_VERSION,
@@ -278,6 +279,46 @@ test("a local caption record from before the caption-track rule is refused where
}
});
+// --- the same, over captions STORED COMPRESSED (lane text-compress-captions) --
+// A track may be `transcript.<lang>.vtt.zst` (common/lib/storedText.ts): one
+// zstd frame with its content size. The rule's listing, head and sizes must be
+// the LOGICAL ones — on the raw listing a stored en reads as absent, and an
+// unversioned record beside an en / en-orig that DIFFER would be cut from.
+
+const stored = (text) => zstdCompressSync(Buffer.from(text, "utf8"));
+
+test("over stored captions: a differing pair is still refused, an identical pair and a lone word-timed track are read", async () => {
+ const dir = await mkdtemp(path.join(tmpdir(), "cues-stored-"));
+ try {
+ const vdir = path.join(dir, "chan", "data", "vid1");
+ await mkdir(vdir, { recursive: true });
+ await writeFile(path.join(vdir, "transcript.en.vtt.zst"), stored("WEBVTT\n\nserved words\n"));
+ await writeFile(path.join(vdir, "transcript.en-orig.vtt"), "WEBVTT\n\nwhat was said\n");
+ await writeFile(path.join(vdir, "transcript.cues.json"), JSON.stringify({ ...RECORD, source: "vtt" }));
+ const src = createCueSource({ channelsDir: dir, siteOrigin: ORIGIN, cacheDir: null, fetchImpl: stubFetch(ROUTES) });
+ await assert.rejects(src.load("chan", "vid1"), /older caption-track rule/);
+
+ // Both stored, byte-identical: equal LOGICAL sizes — read as usual.
+ await rm(path.join(vdir, "transcript.en-orig.vtt"));
+ await writeFile(path.join(vdir, "transcript.en.vtt.zst"), stored("WEBVTT\n\nwhat was said\n"));
+ await writeFile(path.join(vdir, "transcript.en-orig.vtt.zst"), stored("WEBVTT\n\nwhat was said\n"));
+ assert.equal((await src.load("chan", "vid1")).from, "local");
+
+ // A zero-cue record beside ONE stored track with word timing: genuinely
+ // empty, read from the DECODED head.
+ const lone = path.join(dir, "chan", "data", "vid2");
+ await mkdir(lone, { recursive: true });
+ await writeFile(
+ path.join(lone, "transcript.en.vtt.zst"),
+ stored("WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nword<00:00:01.000><c> timed</c>\n"),
+ );
+ await writeFile(path.join(lone, "transcript.cues.json"), JSON.stringify({ ...RECORD, id: "vid2", source: "vtt", cues: [] }));
+ assert.equal((await src.load("chan", "vid2")).from, "local");
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
test("a lone-track caption record with cues needs no rule to be read", async () => {
const dir = await mkdtemp(path.join(tmpdir(), "cues-rule-"));
try {