Archilyzer · Source

archilyzer

Archilyzer
git clone https://archilyzer.pages.dev/source/archilyzer.git
Log | Files | Refs | README | LICENSE

commit 71465bd8b6a50ccddff76550d66e0998eb955fcc
parent 7f3c9c2b205733cda3fad0d8fd17132dd16ddc8f
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Sat, 21 Nov 2026 12:27:27 -0500

stored text, captions review-1 fixes: a re-download refreshes a stored caption, a deleted one never comes back, an unreadable one is an error

F1. The managed download fetches a stored caption again, as main's
re-download did (AGENTS.md: "YouTube's subtitles are fetched again first, as
on any re-download"); youtubeHandlingArgs no longer excludes stored tracks,
and its wrong comment is corrected. After the pass each track that was
stored-only is settled (settleRefetchedCaptions): the same content keeps the
stored form and drops the new copy (no mtime moves, the index sees nothing);
new content with cues replaces it, the stored form removed only once the new
file is whole and parses; nothing (a video that is gone), a .part, an empty
or cue-less file leaves the stored track untouched. One job-log line per
track. Download missing subs (--no-overwrites, where main skipped a present
track) keeps its exclusion. Tests: ytdlp/captionsRefetch.test.ts, every
branch with a fake yt-dlp, and replaceAutoSubs's audio download.

F2. Every deleter of a caption (removeStoredText: the purge and the
clear-transcript fix; removeStoredTextForm: the files card and ops
delete-file; a video delete removes the dir) also removes the track's
stopped-run leftovers, under the file's lock. The compressor adopts a
set-aside only when it carries a start token, its process is gone, AND the
stored form it made first is still there; otherwise it is kept and listed
(retired-kept). A set-aside rename that finds the original gone removes the
stored copy that run made. Tests: compressText.captions.test.ts (killed at
retired, deleted by each deleter, next run: still deleted; a set-aside with
no stored form: not adopted).

F3. zstd is asserted at boot (lib/zstdSupport.mjs): editor instrumentation,
every common/bin CLI (runIfEntryPoint), umtool's bin, and umtool's bare-node
readers (storedText-read.mjs at load) refuse to start, naming Node >= 22.15.
A stored file that does not decode (isStoredTextReadError) is rethrown by the
caption readers, compose and report refresh; the index leaves the record as
the last build held it (alternates read before any write), logs each path and
an UNREADABLE STORED TEXT count, and retries next build; an unreadable stored
sub track keeps its previous cues. The copies lane counts it done, logs and
counts it. Tests: controller/storedText.unreadable.test.ts,
app/instrumentation.test.ts, buildIndex (w).

Nits: N1 deleting a "Set as transcript" pick beside a stored en of other
content removes the pin (storedText.delete.test.ts); N2 a refused pair is
recorded in the channel's .stored-text-differs.json and listed once as
waiting for a person, not work, until a form changes; N4 captions are
surveyed outside the media drive's watchdog; N8 three more grep gates (every
video-dir readdir beside a caption rule is logical, no caption parse of a raw
readFile, the argv builder's caller settles). OPERATING.md, ops help,
COMMANDS.md, editor CHANGELOG.

Co-Authored-By: Claude <noreply@anthropic.com>

Diffstat:
MCOMMANDS.md | 2+-
MOPERATING.md | 21++++++++++++++++++---
Mcommon/bin/_cli.ts | 9+++++++++
Mcommon/controller/buildIndex.test.ts | 35+++++++++++++++++++++++++++++++++++
Mcommon/controller/buildIndex.ts | 57+++++++++++++++++++++++++++++++++++++++++++++++----------
Mcommon/controller/compressText.captions.test.ts | 80+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/compressText.ts | 41+++++++++++++++++++++++++++++++++--------
Mcommon/controller/copiesLane.ts | 26+++++++++++++++++++++++---
Mcommon/controller/reportRefresh.ts | 11+++++++++--
Mcommon/controller/storedText.captions.test.ts | 10++++++----
Mcommon/controller/storedText.delete.test.ts | 23+++++++++++++++++++++++
Acommon/controller/storedText.unreadable.test.ts | 114+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/captionTracks-server.ts | 7+++++--
Mcommon/lib/storedText-read.mjs | 5+++++
Mcommon/lib/storedText-server.ts | 21++++++++++++++++++++-
Mcommon/lib/storedText-write-server.ts | 249++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---
Mcommon/lib/storedText.compress.test.ts | 7++++++-
Mcommon/lib/storedText.grep.test.ts | 81+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/lib/transcriptPin-server.ts | 14++++++++++++++
Mcommon/lib/videoStatus.ts | 7+++++--
Acommon/lib/zstdSupport.d.mts | 4++++
Acommon/lib/zstdSupport.mjs | 29+++++++++++++++++++++++++++++
Mcommon/package.json | 1+
Mcommon/publish/composeReports.ts | 7+++++--
Acommon/ytdlp/captionsRefetch.test.ts | 208+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/ytdlp/downloadOneManaged.ts | 44++++++++++++++++++++++++++++----------------
Mcommon/ytdlp/runYtdlp.ts | 14+++++++++-----
Meditor/CHANGELOG.md | 6++++++
Meditor/app/channels/[slug]/videos/[id]/videoActions.ts | 10++++++++--
Aeditor/app/instrumentation.test.ts | 35+++++++++++++++++++++++++++++++++++
Meditor/instrumentation.ts | 12++++++++++++
Mscripts/archilyzer-ops.mjs | 3++-
Mumtool/bin/umtool.mjs | 10++++++++++
33 files changed, 1126 insertions(+), 77 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": "&lt;file&gt;" 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 big text files compressed (zstd, level 9): the raw live-chat replays (transcript.live\_chat.json -&gt; .zst, kind live-chat, the default) and the caption tracks (every transcript.&lt;lang&gt;.vtt -&gt; .zst, on the corpus disk: "kinds": \["captions"\], only when named). Read back by every reader as the same file, with the same times (the index sees no change): {"slugs"?: \[...\], "kinds"?: \["live-chat", "captions"\], "dryRun"?, "limit"?, "verify"?, "restore"?}. A caption's dry run also counts the en / en-orig pairs of equal size (compressed each as it is, never deduped). One file at a time: written beside the original, fsynced, read back and hashed against it, and only then the original removed; a crash at any step leaves a whole copy, and the next run finishes it (it visits every dir a stopped run left). Left alone and counted: a file written (mtime or ctime) in the last 10 minutes, one with a .part beside it, a video recording or with a job running, a drive that does not answer, a channel whose media is moving. Both forms present with different content are refused, both kept and listed: nothing removes a stored copy because a different one arrived. A file a writer replaces during the run is kept and read; the earlier content's stored copy is kept beside it. The dry run lists earlier chat captures a re-fetch kept (chat-capture-kept.\*.json.zst), which nothing removes automatically. "dryRun": true answers per channel and kind the files, their bytes, the stored ones, the estimate after (about 5 % for a chat, 20 % for a caption: estimates) and the free space, and writes nothing; "verify": true decodes every stored file in full and writes nothing; "limit" counts files compressed and takes exactly one channel in "slugs". One job per channel with work, on the machine-wide compress-text queue (one file at a time), waiting while render mode holds the machine and slower while a live recording runs. Started by a person only: a restart closes a queued one and resumes no interrupted one (it removes originals) -- a re-run continues. "restore": true is the rollback: every stored file of the kinds put back into its plain form, verified the same way in reverse (decoded beside, fsynced, read back against a fresh decode, the same times, then the .zst removed); with "dryRun" it answers the stored files, their plain bytes and the free space. Run it BEFORE reverting or running an older checkout, which cannot read a stored chat or caption (OPERATING.md). | | +| `compress-text` | compress-text stores big text files compressed (zstd, level 9): the raw live-chat replays (transcript.live\_chat.json -&gt; .zst, kind live-chat, the default) and the caption tracks (every transcript.&lt;lang&gt;.vtt -&gt; .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}'` | diff --git a/OPERATING.md b/OPERATING.md @@ -1770,14 +1770,29 @@ pnpm ops compress-text --json '{"kinds":["captions"],"restore":true}' --wait to the live chat alone; `["live-chat","captions"]` does both, the chat first. - **Every reader reads either form** with the same times: the index (it sees no change), normalize, the snapshot's buckets, the provenance sniff (it decodes the head), compose, the remote worker's inputs (sent plain), umtool's cue - source. A stored track is "on disk" to every skip: no download fetches it again (it is left out of `--sub-langs`), - and no audio is downloaded or transcribed because of it. + 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. + 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 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/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts @@ -1055,6 +1055,41 @@ test("(v) lane text-compress-captions: THE MIGRATION (compress-text, kinds capti 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("(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, @@ -1123,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); @@ -1171,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; } } @@ -1224,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 @@ -1248,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++; @@ -1341,7 +1351,17 @@ 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); + else retrySubs = true; + } // Skip unreadable / malformed sub tracks; the rest of the // video's data is still useful. } @@ -1456,6 +1476,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)}`); } }), @@ -1466,6 +1494,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/compressText.captions.test.ts b/common/controller/compressText.captions.test.ts @@ -258,3 +258,83 @@ test("a caption that is a link into media/ (none on this corpus: the classifier 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)); +}); diff --git a/common/controller/compressText.ts b/common/controller/compressText.ts @@ -63,6 +63,8 @@ import { frameContentSize } from "../lib/storedText-server"; import { compressStoredText, hasStoredTextLeftover, + bothDifferRecorded, + readStoredTextDiffers, restoreStoredText, storedTextLeftoverNames, verifyStoredText, @@ -131,6 +133,9 @@ export type KindLine = { // 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 @@ -274,6 +279,9 @@ type KindSurvey = { work: Candidate[]; // Every file a restore visits: the stored form, or a leftover. restoreWork: Candidate[]; + // Both forms present and recorded as differing, unchanged since: waiting + // for a person — never work (REVIEW-1 N2). + differs: Candidate[]; pairsEqualSize: number; pairsEqualSizeBytes: number; }; @@ -290,12 +298,13 @@ async function surveyChannel( const ids = (await readdir(dataDir).catch(() => [] as string[])).sort(); const byKind: Partial<Record<CompressTextKind, KindSurvey>> = {}; for (const k of kinds) { - byKind[k] = { plain: [], stored: [], work: [], restoreWork: [], pairsEqualSize: 0, pairsEqualSizeBytes: 0 }; + 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 logicalOf = (p: string) => (drive ? onDrive(drive, () => storedLogicalSize(p)) : storedLogicalSize(p)).catch(() => 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); @@ -303,11 +312,15 @@ async function surveyChannel( if (kinds.includes("live-chat")) { for (const k of entries.filter(isKeptChatCapture)) { kept.files += 1; - kept.bytes += (await sizeOf(path.join(videoDir, k))) ?? 0; + kept.bytes += (await sizeOfMedia(path.join(videoDir, k))) ?? 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); @@ -318,7 +331,9 @@ async function surveyChannel( if (size !== null) s.plain.push({ id, videoDir, name, size }); logicalSize[name] = size; } - if (forms === "plain" || forms === "both" || leftover) s.work.push({ id, videoDir, name, size: size ?? 0 }); + 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)); @@ -351,6 +366,7 @@ async function surveyChannel( 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, @@ -447,6 +463,13 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT 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 @@ -477,12 +500,12 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT for (const k of kinds) { const c = kl[k]!; c.estimateAfterBytes = Math.round(c.plainBytes * RATIO[k]); - if (c.plainFiles + c.storedFiles + (k === "live-chat" ? kept.files : 0) > 0) { + 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)}${k === "live-chat" ? keptText : ""}`, + `${pairsText(k)}${differsText(k)}${k === "live-chat" ? keptText : ""}`, ); } } @@ -656,9 +679,11 @@ export async function compressText(opts: CompressTextOptions): Promise<CompressT const b = channels.reduce((a, l) => a + (l.bytesBefore ?? 0), 0); const f = channels.reduce((a, l) => a + (l.bytesAfter ?? 0), 0); 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)` : ""}` + + `${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` : ""}.`, ); } diff --git a/common/controller/copiesLane.ts b/common/controller/copiesLane.ts @@ -31,7 +31,7 @@ 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 { readStoredText } from "../lib/storedText-server"; +import { isStoredTextReadError, readStoredText } from "../lib/storedText-server"; import { resolveCaptionsProvenance } from "../lib/subtitleProvenance"; import { operationsForLane } from "../lib/operations"; import { DIARIZATION_FILENAME } from "../lib/videoStatus"; @@ -87,6 +87,11 @@ const realIo: CopiesLaneIo = { 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. @@ -284,7 +289,10 @@ async function transcriptDone(videoDir: string, entries: readonly string[], rule 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; } } @@ -321,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/reportRefresh.ts b/common/controller/reportRefresh.ts @@ -40,7 +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 { readStoredText, readdirLogical } from "../lib/storedText-server"; +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"; @@ -516,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 readStoredText(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 @@ -189,7 +189,7 @@ test("hasAnyTranscriptOnDisk: a stored caption is a transcript — no audio down assert.equal(await __hasAnyTranscriptOnDiskForTest(chat), false); }); -test("the subtitle passes leave every stored track out of --sub-langs (yt-dlp's skip sees only the plain name)", async () => { +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"); @@ -201,9 +201,11 @@ test("the subtitle passes leave every stored track out of --sub-langs (yt-dlp's // 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]; - assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false, ["en", "en-orig"])), "en.*,live_chat,-en,-en-orig"); - assert.equal(langs(youtubeHandlingArgs(CONFIG, false, true, ["en"])), "en.*,-en"); - assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false)), "en.*,live_chat", "nothing stored: unchanged"); + // 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 () => { diff --git a/common/controller/storedText.delete.test.ts b/common/controller/storedText.delete.test.ts @@ -200,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 @@ -4,7 +4,7 @@ import path from "node:path"; import { readFile } from "node:fs/promises"; import { logicalEntries } from "./storedText"; -import { readStoredText, readdirLogical } from "./storedText-server"; +import { isStoredTextReadError, readStoredText, readdirLogical } from "./storedText-server"; import { parseVtt, type Cue } from "./vtt"; import { parseTranscriptJson } from "./whisper"; import { @@ -56,7 +56,10 @@ export async function readEnglishVttTracks( // 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 } } diff --git a/common/lib/storedText-read.mjs b/common/lib/storedText-read.mjs @@ -12,6 +12,11 @@ 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"; 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, 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,38 @@ 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. +// 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. export async function removeStoredText(videoDir: string, name: string): Promise<void> { - await removeMediaFile(videoDir, storedNameOf(name)); - await removeMediaFile(videoDir, name); + for (let attempt = 0; ; attempt++) { + const done = await withFileLock(videoDir, name, false, async () => { + await removeMediaFile(videoDir, storedNameOf(name)); + await removeMediaFile(videoDir, name); + await removeLeftoversOf(videoDir, name); + return true; + }); + if (done) return; + if (attempt >= 40) { + throw new Error(`${name} is being compressed or restored right now: not deleted — 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 ────────────────────────────────────────────────────────── @@ -596,8 +626,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; @@ -761,6 +805,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. @@ -800,7 +847,17 @@ 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 — a deleter outside the + // lock, or a writer replacing it. A stored form THIS run made would + // outlive a deletion (REVIEW-1 F2): it goes; an older one is not ours. + if (zKind === "none") await removeMediaFile(videoDir, stored); + log(` ${name} was removed while it was being compressed: ${zKind === "none" ? "the stored copy this run made is removed too" : "left as it is"}`); + return { status: "changed" }; + } crash("retired"); const nowL = await lstatOrNull(retiredPath); const nowS = await stat(retiredPath).catch(() => null); @@ -1376,6 +1433,170 @@ 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. + +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. Only now the stored one goes. + 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 @@ -1387,6 +1608,9 @@ 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"> { @@ -1397,8 +1621,12 @@ export async function removeStoredTextForm(videoDir: string, filename: string): } 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); @@ -1408,7 +1636,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"); }); diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts @@ -191,16 +191,18 @@ 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 — -// each builder excludes the stored tracks by code (`storedOnlyCaptionTracks`, -// `excludeSubTracks`), and its caller computes them from the PHYSICAL listing. +// `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; storedCaptionTracks " + - "(storedOnlyCaptionTracks): each stored caption excluded by code", - test: "controller/storedText.chat.test.ts (youtubeHandlingArgs); controller/storedText.captions.test.ts (youtubeHandlingArgs)", + "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", @@ -357,3 +359,70 @@ test("every file that applies a caption rule to a listing takes a logical listin "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/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,7 +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 { readStoredText } from "./storedText-server"; +import { isStoredTextReadError, readStoredText } from "./storedText-server"; export type VideoFiles = { hasMeta: boolean; @@ -211,7 +211,10 @@ export async function readEnglishVttCues( let cues: Cue[]; try { cues = parseVtt(await readStoredText(videoDir, filename, "utf8")); - } catch { + } 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 }; 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,7 @@ "./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 @@ -76,7 +76,7 @@ import path from "node:path"; import { publishFileSizeProblem } from "../lib/builtExport"; import type { Paths } from "../lib/paths"; import { resolveVideoDir } from "../lib/videoDir-server.mjs"; -import { readStoredText, readdirLogical } from "../lib/storedText-server"; +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"; @@ -301,7 +301,10 @@ async function readCues(dir: string, name: string, kind: "vtt" | "whisper"): Pro try { 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 []; } } diff --git a/common/ytdlp/captionsRefetch.test.ts b/common/ytdlp/captionsRefetch.test.ts @@ -0,0 +1,208 @@ +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(); + } +}); diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts @@ -71,12 +71,12 @@ import { normalizeLiveChat } from "../controller/normalizeLiveChat"; import { writeCuesAfterDownload } from "../controller/normalizeTranscript"; import { LIVE_CHAT_FILENAME } from "../lib/videoStatus"; import { - excludeSubTracks, listingHas, logicalEntries, storedFormsIn, storedOnlyCaptionTracks, } from "../lib/storedText"; +import { settleRefetchedCaptions } from "../lib/storedText-write-server"; import { upsertMetadataScan, type MetadataScanEntry, @@ -299,19 +299,25 @@ 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. The same for -// a CAPTION TRACK stored compressed (`storedCaptionTracks`, its codes from -// lib/storedText.ts `storedOnlyCaptionTracks`): each is excluded by its code -// (`,-en,-en-orig`), so a re-download never fetches it again beside the -// stored copy. 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, chatStored = false, - storedCaptionTracks: readonly string[] = [], ): string[] { const args = [ "--write-auto-subs", @@ -319,10 +325,7 @@ export function youtubeHandlingArgs( "--sub-langs", // Without the live chat unless the channel fetches it with the download // (ChannelConfig.chat). - excludeSubTracks( - effectiveSubLangs(chatStored ? { ...config, chat: "later" } : config), - storedCaptionTracks, - ), + effectiveSubLangs(chatStored ? { ...config, chat: "later" } : config), ]; if (!reuseInfoJson) args.push("--write-info-json"); args.push( @@ -1343,7 +1346,8 @@ async function runManagedDownload( // 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. // What is stored compressed in the video's dir (lib/storedText.ts): the - // chat, and the caption tracks — each left out of the subtitle request. + // 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 ? await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[]) @@ -1354,7 +1358,7 @@ async function runManagedDownload( opts.channelConfig.handling === "youtube" ? [ ...outputArgsForUrl(opts.videoUrl), - ...youtubeHandlingArgs(opts.channelConfig, reuseInfoJson, chatStored, storedCaptionTracks), + ...youtubeHandlingArgs(opts.channelConfig, reuseInfoJson, chatStored), ] : transcribeMediaArgs( opts.videoUrl, @@ -1652,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 @@ -1489,11 +1489,15 @@ 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, from its PHYSICAL -// listing. A chat or a caption track stored compressed (lib/storedText.ts) is -// on disk, but yt-dlp's own "already present" skip looks for the plain name -// and would fetch it again, landing a second copy beside the stored one: a -// stored chat is left out as for a `later` channel, and each stored caption -// track is excluded by its code (`,-en,-en-orig`). Exported for its test. +// 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 { const chatLeftOut = storedFormsIn(entries, LIVE_CHAT_FILENAME) === "zst" diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -98,6 +98,12 @@ 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/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts @@ -1083,18 +1083,24 @@ 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.` }; } + // 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" + (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 }; 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/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 @@ -2528,7 +2528,8 @@ export function usage() { " minutes, one with a .part beside it, a video recording or with a job", " running, a drive that does not answer, a channel whose media is moving.", " Both forms present with different content are refused, both kept and", - " listed: nothing removes a stored copy because a different one arrived.", + " 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", 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);