commit 2a0ea61b63bbd18be61066b835fdf84ea634756a
parent b08a6ca150b3d78710efa3bbef483b83bf9e1c66
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Sat, 21 Nov 2026 01:35:11 -0500
stored text, slice 1: one read path for the raw live chat in either form
The raw live-chat replay may now be on disk as `transcript.live_chat.json.zst`
(one zstd frame, content size and checksum in the frame). Nothing writes that
form yet; this slice makes every reader, lister and deleter accept it, so the
compressor (slice 2) can never make a chat look absent.
- lib/storedText.ts (names, logical listings), lib/storedText-server.ts (the
read path: plain first, else the stored form, decoded and length-checked —
node's zstd does not throw on a truncated frame), and
lib/storedText-write-server.ts (removeStoredText: both forms, each through
removeMediaFile, the stored one first).
- The classifier: the stored chat is media and tierable; the compressor's
`.compressing-<pid>` and `.retire-<pid>` temps are scratch.
- Chat readers routed: normalizeLiveChat (freshness, read, tier both forms),
liveChatPlan / the after-run check / renormalizeChatRefusal, the snapshot's
chatOnly and chatOnlyPending, hasLiveChatOnDisk, trackOnDisk, the archive
build's left-out count, the index's sub-track key, tier test and reads,
readSubTracks (logical).
- yt-dlp's own "already present" skip sees only the plain name: over a stored
chat, the download's and the missing-subs fetch's sub-langs leave the chat
out (no re-fetch of the replay).
- reconcileVideoDirs collides by the logical name and stashes the loser.
- Deleters: the auto-caption purge, the clear-transcript fix and the files
card's delete of a declared name remove both forms (no resurrection).
- The sidecar guard refuses a stored-form name; the tier hook sets times in
numeric seconds (a Date truncated sub-ms mtimes and re-ingested a record).
- A grep gate fails any new app line naming the raw chat outside the helpers.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
28 files changed, 1271 insertions(+), 53 deletions(-)
diff --git a/common/controller/archiveLiveChat.ts b/common/controller/archiveLiveChat.ts
@@ -18,7 +18,6 @@ import path from "node:path";
import {
access,
link,
- lstat,
mkdir,
readdir,
rm,
@@ -30,6 +29,7 @@ import { listChannelStatsFromDisk, type ChannelStat } from "./channels";
import { isLiveChatCuesFresh, normalizeLiveChat } from "./normalizeLiveChat";
import { inspectChannelMedia } from "../lib/channelMedia";
import { LIVE_CHAT_MEDIA_FILENAME } from "../lib/mediaTier";
+import { storedTextExists } from "../lib/storedText-server";
import {
archiveExtension,
archiveSidecarPath,
@@ -192,10 +192,8 @@ async function stageChannel(
() => false,
);
if (!have) {
- const hasRaw = await lstat(path.join(videoDir, LIVE_CHAT_MEDIA_FILENAME)).then(
- () => true,
- () => false,
- );
+ // Either form (lib/storedText.ts), by `lstat`.
+ const hasRaw = await storedTextExists(videoDir, LIVE_CHAT_MEDIA_FILENAME);
if (hasRaw) leftOut++;
return;
}
diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts
@@ -895,6 +895,54 @@ test("(n) lane missing-source: an undated state with a channel held is re-read o
assert.ok(third.log.some((l) => l.startsWith("Shared transcript pages up to date")), third.log.join("\n"));
});
+test("(s) lane text-compress: a raw chat compressed in place changes NOTHING the index holds, and is still read", async () => {
+ resetCorpus();
+ seedVideo("c1");
+ seedDriveChannel();
+ const chat =
+ JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text: "zst" }] }, authorName: { simpleText: "a" }, timestampUsec: "1000000" } } } }], videoOffsetTimeMsec: "1000" } }) + "\n";
+ // c1: a real raw replay on the corpus disk; d2: a tier link onto the drive.
+ // Both with sub-millisecond times — a `Date` would lose them.
+ const { utimesSync, lutimesSync } = await import("node:fs");
+ writeFileSync(path.join(videoDir("c1"), "transcript.live_chat.json"), chat);
+ utimesSync(path.join(videoDir("c1"), "transcript.live_chat.json"), 1763700000.123457, 1763700000.987653);
+ mkdirSync(path.join(DRIVE_MEDIA(), "d2"), { recursive: true });
+ writeFileSync(path.join(DRIVE_MEDIA(), "d2", "transcript.live_chat.json"), chat);
+ symlinkSync("../../media/d2/transcript.live_chat.json", path.join(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json"));
+ lutimesSync(path.join(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json"), 1763700001.5, 1763700001.000003);
+ const tracksOf = (id: string) =>
+ withIndex((db) =>
+ [...db("subs").getRange()]
+ .filter(({ key }) => (key as unknown as string[])[2] === id)
+ .flatMap(({ value }) => (value as { track: string }[]).map((t) => t.track)),
+ );
+ const mtimesOf = () => withIndex((db) => [...db("mtimes").getRange()].map(({ key, value }) => [key, value]));
+ await runIndex();
+ assert.ok(tracksOf("c1").includes("live_chat"));
+ assert.ok(tracksOf("d2").includes("live_chat"));
+ const before = mtimesOf();
+
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(videoDir("c1"), "transcript.live_chat.json");
+ await storeFixture(videoDir("d2", DRIVE_CHANNEL), "transcript.live_chat.json");
+ assert.equal(existsSync(path.join(videoDir("c1"), "transcript.live_chat.json")), false);
+
+ const after = await runIndex();
+ assert.equal(after.res.changed, 0, after.log.join("\n"));
+ assert.equal(after.res.added, 0);
+ assert.equal(after.res.removed, 0);
+ assert.deepEqual(mtimesOf(), before, "the stored mtimes are the same numbers");
+ assert.ok(tracksOf("c1").includes("live_chat"));
+
+ // A change elsewhere re-reads both records: the chat comes from the stored form.
+ seedVideo("c1", CHANNEL, { title: "Retitled" });
+ seedVideo("d2", DRIVE_CHANNEL, { title: "Retitled" });
+ const reread = await runIndex();
+ assert.equal(reread.res.changed, 2, reread.log.join("\n"));
+ assert.ok(tracksOf("c1").includes("live_chat"), "read from the real stored file");
+ assert.ok(tracksOf("d2").includes("live_chat"), "read through the stored form's tier link");
+});
+
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
@@ -28,7 +28,6 @@
import path from "node:path";
import { createHash } from "node:crypto";
import {
- lstat,
mkdir,
readdir,
readFile,
@@ -101,6 +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 { onDrive } from "../lib/storageHealth";
import {
HELD_WAYS_OUT,
@@ -591,8 +591,14 @@ async function scanSource(
// channels/<slug>/media, possibly on another drive. The link carries
// the file's times (the tier hook's `lutimes`), so this answers from
// the corpus disk and never reaches the media drive.
- const p = path.join(fullVideoDir, t.filename);
- const ms = (await (isTierable(t.filename) ? lstat(p) : stat(p))).mtimeMs;
+ //
+ // EITHER FORM (lib/storedText.ts): a chat stored compressed is asked
+ // under its stored name, whose times the compressor set to the plain
+ // file's exactly — the same `subsMs`, so a compression re-ingests
+ // nothing.
+ const ms = (
+ await statStoredText(fullVideoDir, t.filename, { link: isTierable(t.filename) })
+ ).stats.mtimeMs;
if (subsMs === null || ms > subsMs) subsMs = ms;
} catch {
// ignore
@@ -1290,16 +1296,24 @@ export async function buildIndex({
// Not read (unreachable, not answering, unreadable): the cues
// the last build held are kept; with none to keep, the record
// is written with no sub-track time, so the next build retries.
+ // Asked of the form present (lib/storedText.ts): a chat stored
+ // compressed is a link as `transcript.live_chat.json.zst`.
+ const rawDir = path.dirname(rawPath);
const tiered =
t.track === "live_chat" &&
- (await lstat(rawPath).then((l) => l.isSymbolicLink(), () => false));
+ (await statStoredText(rawDir, t.filename, { link: true }).then(
+ (l) => l.stats.isSymbolicLink(),
+ () => false,
+ ));
if (tiered) {
const access = mediaAccess.get(s.channelSlug);
let raw: string | null = null;
if (access?.readable) {
try {
- if (access.drive) await onDrive(access.drive, () => stat(rawPath));
- raw = await readFile(rawPath, "utf8");
+ if (access.drive) {
+ await onDrive(access.drive, () => statStoredText(rawDir, t.filename));
+ }
+ raw = await readStoredText(rawDir, t.filename, "utf8");
} catch {
raw = null;
}
@@ -1312,7 +1326,7 @@ export async function buildIndex({
}
trackCues = (await parseLiveChatOnRecordingClock(videoFullDir, raw)).cues;
} else {
- const raw = await readFile(rawPath, "utf8");
+ const raw = await readStoredText(rawDir, t.filename, "utf8");
// A stale chat's raw is parsed onto the recording's clock,
// as the normalizer does (lane chat-clock).
trackCues =
diff --git a/common/controller/channelSnapshot.test.ts b/common/controller/channelSnapshot.test.ts
@@ -628,6 +628,36 @@ test("a chat-only livestream is a corpus member, not a settled stub", async () =
}
});
+test("a chat-only livestream whose chat is STORED compressed is still a corpus member (lane text-compress)", async () => {
+ // Missed, the video would fall back to chatOnlyPending — download-lane work
+ // that fetches the whole chat again.
+ const { dir, paths, channelDir } = await filteredChannel({
+ filter: { include: "keep", rejectedLivestreams: "chat-only" },
+ listed: ["aaaa0000001", "cccc0000003"],
+ scanned: {
+ aaaa0000001: { title: "keep this one" },
+ cccc0000003: { title: "a long stream", liveStatus: "was_live" },
+ },
+ });
+ try {
+ const videoDir = path.join(channelDir, "data", "cccc0000003");
+ await mkdir(videoDir, { recursive: true });
+ await writeFile(
+ path.join(videoDir, "metadata.info.json"),
+ JSON.stringify({ id: "cccc0000003", title: "a long stream" }),
+ );
+ await writeFile(path.join(videoDir, "transcript.live_chat.json"), '{"action":{}}\n');
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(videoDir, "transcript.live_chat.json");
+ const snap = await generateChannelSnapshot(paths, "alpha");
+ assert.deepEqual(snap.buckets.chatOnly, ["cccc0000003"]);
+ assert.deepEqual(snap.buckets.chatOnlyPending, []);
+ assert.ok(!snap.undownloadedIds.includes("cccc0000003"));
+ } finally {
+ await rm(dir, { recursive: true, force: true });
+ }
+});
+
test("before the chat lands it is chatOnlyPending — the download lane's bucket", async () => {
const { dir, paths } = await filteredChannel({
filter: { include: "keep", rejectedLivestreams: "chat-only" },
diff --git a/common/controller/channelSnapshot.ts b/common/controller/channelSnapshot.ts
@@ -25,6 +25,7 @@ import {
import { resolveCookiePolicy } from "../lib/cookiePolicy";
import { assertChannelTextReadable } from "../lib/channelMedia";
import { isTierable } from "../lib/mediaTier";
+import { listingHas } from "../lib/storedText";
import { isDriveNotAnswering, onDrive } from "../lib/storageHealth";
import { CLIPS_DIR_NAME } from "../lib/clipWindow";
import { getSettings } from "../lib/settings";
@@ -1547,7 +1548,8 @@ export async function generateChannelSnapshot(
// under this line classifies a video by what is MISSING, and nothing is
// missing from a chat-only video.
if (settledIds.has(id) && !videoHasAnyArtifact(files)) {
- if (files.entries.includes(LIVE_CHAT_FILENAME)) {
+ // Either form (lib/storedText.ts): a compressed chat is still on disk.
+ if (listingHas(files.entries, LIVE_CHAT_FILENAME)) {
chatOnly.push(id);
} else {
settledOnDisk.push(id);
@@ -1817,7 +1819,7 @@ export async function generateChannelSnapshot(
// store's `noLiveChat` flag is the other way out of this list: a stream
// we asked and got nothing from is not in `chatOnlyIds` at all, so it
// settles as an ordinary rejection instead of sitting here forever.
- if (!f?.entries.includes(LIVE_CHAT_FILENAME)) chatOnlyPending.push(dirId);
+ if (!f || !listingHas(f.entries, LIVE_CHAT_FILENAME)) chatOnlyPending.push(dirId);
continue;
}
// A settled video has no artifact and never will while the filter stands.
diff --git a/common/controller/fetchLiveChat.ts b/common/controller/fetchLiveChat.ts
@@ -56,6 +56,8 @@ import { detectPlatform } from "../lib/platform";
import type { Paths } from "../lib/paths";
import { downloadQueueKey, resolveQueueKey } from "../lib/queueKeys";
import { LIVE_CHAT_CUES_FILENAME, LIVE_CHAT_FILENAME, META_FILENAME } from "../lib/videoStatus";
+import { listingHas } from "../lib/storedText";
+import { storedTextExists } from "../lib/storedText-server";
import {
heldPlatformRefusal,
platformCooldownRemainingMs,
@@ -128,7 +130,9 @@ export async function liveChatPlan(
const fresh = await isLiveChatCuesFresh(videoDir);
if (fresh.fresh) return { kind: "fresh", cuesPath: fresh.cuesPath };
const entries = await readdir(videoDir).catch(() => [] as string[]);
- if (entries.includes(LIVE_CHAT_FILENAME) && entries.includes(META_FILENAME)) return { kind: "normalize" };
+ // Either form of the raw (lib/storedText.ts): a compressed chat is ON DISK —
+ // missing it here is a fetch of the whole replay again.
+ if (listingHas(entries, LIVE_CHAT_FILENAME) && entries.includes(META_FILENAME)) return { kind: "normalize" };
const url = await findVideoSourceUrl(paths, slug, videoId, config);
if (!url) {
return {
@@ -243,7 +247,7 @@ export async function fetchLiveChat(opts: FetchLiveChatOpts): Promise<FetchLiveC
/* shared-state write is best-effort */
}
const entries = await readdir(videoDir).catch(() => [] as string[]);
- if (!entries.includes(LIVE_CHAT_FILENAME)) {
+ if (!listingHas(entries, LIVE_CHAT_FILENAME)) {
opts.onLog(`No chat replay for ${opts.videoId}: the source has none (chat replay off, or never live). Nothing written.\n`);
return { status: "none" };
}
@@ -311,7 +315,7 @@ export async function renormalizeChatRefusal(
const videoDir = path.join(paths.channelsDir, slug, "data", videoId);
if (!(await isDirectory(videoDir))) return notFetchedRefusal(videoId, slug);
const here = (name: string) => lstat(path.join(videoDir, name)).then(() => true, () => false);
- if (!(await here(LIVE_CHAT_FILENAME))) {
+ if (!(await storedTextExists(videoDir, LIVE_CHAT_FILENAME))) {
return (
`${videoId} has no raw chat on disk (${LIVE_CHAT_FILENAME}): "renormalize" reads only the file ` +
`already here and never fetches — fetch-chat without it fetches the chat`
diff --git a/common/controller/normalizeLiveChat.ts b/common/controller/normalizeLiveChat.ts
@@ -11,9 +11,11 @@
// `clock`. A chat fetched as a replay is already on that clock and is not moved.
import path from "node:path";
-import { lstat, readFile, stat } from "node:fs/promises";
+import { readFile, stat } from "node:fs/promises";
import { writeJsonAtomic } from "../lib/jsonFile-server";
import { tierMediaFile } from "../lib/mediaTier-server";
+import { LIVE_CHAT_STORED_FILENAME } from "../lib/mediaTier";
+import { readStoredText, storedTextMtimeMs } from "../lib/storedText-server";
import {
hasLiveCapturedLines,
liveChatClockOf,
@@ -73,12 +75,13 @@ async function mtimeMs(p: string): Promise<number | null> {
// the file's mtime onto the link (`lutimes`), so the link answers the same
// freshness question from the corpus disk — the index build asks it per video
// and must never reach the media drive to do so.
-async function rawMtimeMs(p: string): Promise<number | null> {
- try {
- return (await lstat(p)).mtimeMs;
- } catch {
- return null;
- }
+//
+// EITHER FORM (lib/storedText.ts): the plain name when present, else the
+// stored `transcript.live_chat.json.zst`, which the compressor gives the plain
+// file's times exactly — the same answer, so a compression re-normalizes
+// nothing.
+async function rawMtimeMs(videoDir: string): Promise<number | null> {
+ return storedTextMtimeMs(videoDir, LIVE_CHAT_FILENAME, { link: true });
}
/**
@@ -136,12 +139,11 @@ export async function normalizeLiveChat(
opts: NormalizeLiveChatOptions,
): Promise<NormalizeLiveChatOutcome> {
const metaPath = path.join(opts.videoDir, META_FILENAME);
- const rawPath = path.join(opts.videoDir, LIVE_CHAT_FILENAME);
const cuesPath = path.join(opts.videoDir, LIVE_CHAT_CUES_FILENAME);
const [metaStatMs, rawStatMs, cuesMs] = await Promise.all([
mtimeMs(metaPath),
- rawMtimeMs(rawPath),
+ rawMtimeMs(opts.videoDir),
mtimeMs(cuesPath),
]);
@@ -166,7 +168,7 @@ export async function normalizeLiveChat(
opts.configName,
);
- const rawLiveChat = await readFile(rawPath, "utf8");
+ const rawLiveChat = await readStoredText(opts.videoDir, LIVE_CHAT_FILENAME, "utf8");
let cues: Cue[];
let clock: LiveChatClock;
try {
@@ -198,9 +200,12 @@ export async function normalizeLiveChat(
// THE MEDIA TIER'S HOOK (release 17): the raw replay is read once, here, and
// every other reader uses the cues just written — so it moves into
// channels/<slug>/media now (a relative link stays). Never throws.
- if (opts.tier !== false) await tierMediaFile(opts.videoDir, LIVE_CHAT_FILENAME, {
- onLog: opts.log ? (line) => opts.log?.(line.trimEnd()) : undefined,
- });
+ // The stored form too, when that is what is here as a real file.
+ if (opts.tier !== false) {
+ const onLog = opts.log ? (line: string) => opts.log?.(line.trimEnd()) : undefined;
+ await tierMediaFile(opts.videoDir, LIVE_CHAT_FILENAME, { onLog });
+ await tierMediaFile(opts.videoDir, LIVE_CHAT_STORED_FILENAME, { onLog });
+ }
return { status: "wrote", cuesPath };
}
@@ -233,7 +238,7 @@ export async function readNormalizedLiveChat(
}
// Sidecar is fresh iff it exists and its mtime is >= both metadata.info.json
-// and transcript.live_chat.json. Used by buildIndex to decide whether to
+// and transcript.live_chat.json (either form). Used by buildIndex to decide whether to
// trust the cached cues without re-parsing the raw payload. Its version is
// not asked (LIVE_CHAT_FILE_VERSION above).
export async function isLiveChatCuesFresh(
@@ -241,11 +246,10 @@ export async function isLiveChatCuesFresh(
): Promise<{ fresh: boolean; cuesPath: string }> {
const cuesPath = path.join(videoDir, LIVE_CHAT_CUES_FILENAME);
const metaPath = path.join(videoDir, META_FILENAME);
- const rawPath = path.join(videoDir, LIVE_CHAT_FILENAME);
const [cuesMs, metaMs, rawMs] = await Promise.all([
mtimeMs(cuesPath),
mtimeMs(metaPath),
- rawMtimeMs(rawPath),
+ rawMtimeMs(videoDir),
]);
if (cuesMs === null || metaMs === null || rawMs === null) {
return { fresh: false, cuesPath };
diff --git a/common/controller/purgeSupersededAutoSubs.ts b/common/controller/purgeSupersededAutoSubs.ts
@@ -1,4 +1,4 @@
-import { removeMediaFile } from "../lib/mediaTier-server";
+import { removeStoredText } from "../lib/storedText-write-server";
import path from "node:path";
import fs from "fs-extra";
import type { Paths } from "../lib/paths";
@@ -89,7 +89,9 @@ export async function purgeSupersededAutoSubs({
skipped++;
continue;
}
- await removeMediaFile(videoDir, name); // the one rm of a video-dir entry (release 17)
+ // Both forms (lib/storedText-write-server.ts): a stored copy left behind
+ // would bring the captions back. Each through removeMediaFile.
+ await removeStoredText(videoDir, name);
log(`Removed ${id}/${name}`);
removedFiles++;
removedHere++;
diff --git a/common/controller/reconcileVideoDirs.test.ts b/common/controller/reconcileVideoDirs.test.ts
@@ -164,3 +164,52 @@ test("a dry run reports the same merge and moves nothing", async (t) => {
["20.00-30.00.mp4"],
);
});
+
+// ONE FILE, TWO NAMES (lane text-compress): a stored chat on one side and a
+// plain one on the other are the same file. Merged by name both would land,
+// the plain one would read as the truth, and the other side's copy would be
+// superseded with no trace. The loser's forms are stashed as `.dup-<src>`.
+test("a stored chat and a plain chat collide by their LOGICAL name; the loser is stashed, not superseded", async (t) => {
+ const channelDir = await makeChannel();
+ t.after(() => rm(channelDir, { recursive: true, force: true }));
+ await writeStrayDir(channelDir, "canonical01", {
+ "transcript.live_chat.json.zst": "destination stored chat",
+ });
+ await writeStrayDir(channelDir, "v-canonical01", {
+ "transcript.live_chat.json": "source plain chat",
+ });
+ await reconcileVideoDirs({ channelDir });
+ const dst = path.join(channelDir, "data", "canonical01");
+ const names = (await readdir(dst)).filter((n) => n.startsWith("transcript.")).sort();
+ assert.deepEqual(names, [
+ "transcript.live_chat.json",
+ "transcript.live_chat.json.zst.dup-v-canonical01",
+ ]);
+ // The source wins (yt-dlp's bytes, as for any transcript.*); the other is kept.
+ assert.equal(await readFile(path.join(dst, "transcript.live_chat.json"), "utf8"), "source plain chat");
+ assert.equal(
+ await readFile(path.join(dst, "transcript.live_chat.json.zst.dup-v-canonical01"), "utf8"),
+ "destination stored chat",
+ );
+});
+
+test("both forms on the source side move in together over a destination's stored chat", async (t) => {
+ const channelDir = await makeChannel();
+ t.after(() => rm(channelDir, { recursive: true, force: true }));
+ await writeStrayDir(channelDir, "canonical01", {
+ "transcript.live_chat.json.zst": "old stored",
+ });
+ await writeStrayDir(channelDir, "v-canonical01", {
+ "transcript.live_chat.json": "src plain",
+ "transcript.live_chat.json.zst": "src stored",
+ });
+ await reconcileVideoDirs({ channelDir });
+ const dst = path.join(channelDir, "data", "canonical01");
+ assert.deepEqual((await readdir(dst)).filter((n) => n.startsWith("transcript.")).sort(), [
+ "transcript.live_chat.json",
+ "transcript.live_chat.json.zst",
+ "transcript.live_chat.json.zst.dup-v-canonical01",
+ ]);
+ assert.equal(await readFile(path.join(dst, "transcript.live_chat.json.zst"), "utf8"), "src stored");
+ assert.equal(await readFile(path.join(dst, "transcript.live_chat.json.zst.dup-v-canonical01"), "utf8"), "old stored");
+});
diff --git a/common/controller/reconcileVideoDirs.ts b/common/controller/reconcileVideoDirs.ts
@@ -2,6 +2,7 @@ import path from "node:path";
import { readdir, readFile, rename, rmdir, stat } from "node:fs/promises";
import { extractVideoId } from "../ytdlp/runYtdlp";
import { CLIPS_DIR_NAME } from "../lib/clipWindow";
+import { isStoredTextName, logicalNameOf } from "../lib/storedText";
// The app keys every video by its canonical, URL-derived id
// (`extractVideoId(webpage_url)`) and expects its data under
@@ -83,6 +84,20 @@ async function mergeDir(
readdir(dstDir).catch(() => [] as string[]),
]);
const dstSet = new Set(dstEntries);
+ // ONE FILE, TWO NAMES (lib/storedText.ts): `transcript.live_chat.json` and
+ // its stored `transcript.live_chat.json.zst` collide although their names
+ // differ — merged by name, both would land and the plain one (the truth)
+ // would silently supersede the other side's copy. So a collision is by the
+ // LOGICAL name, and the loser's every form is stashed aside.
+ const dstForms = new Map<string, string[]>();
+ for (const d of dstEntries) {
+ const l = logicalNameOf(d);
+ if (!isStoredTextName(l)) continue;
+ dstForms.set(l, [...(dstForms.get(l) ?? []), d]);
+ }
+ // Logical names whose collision is settled: the destination's forms are
+ // stashed (the source won), so the source's other forms move in as they are.
+ const settled = new Set<string>();
for (const f of srcEntries) {
const src = path.join(srcDir, f);
// `clips/` IS A DIRECTORY, and the collision rule below is written for
@@ -103,6 +118,28 @@ async function mergeDir(
if (!dryRun) await rmdir(src).catch(() => {});
continue;
}
+ const logical = logicalNameOf(f);
+ const forms = dstForms.get(logical);
+ if (forms && !settled.has(logical)) {
+ settled.add(logical);
+ if (sourceWins(logical)) {
+ // Keep the source's; stash every destination form aside.
+ for (const d of forms) {
+ if (!dryRun) await rename(path.join(dstDir, d), path.join(dstDir, `${d}.dup-${srcName}`));
+ dstSet.delete(d);
+ }
+ } else {
+ // Keep the destination's; stash this and any other source form aside.
+ for (const g of srcEntries) {
+ if (logicalNameOf(g) !== logical) continue;
+ if (!dryRun) await rename(path.join(srcDir, g), path.join(dstDir, `${g}.dup-${srcName}`));
+ moved.push(`${g}.dup-${srcName}`);
+ }
+ continue;
+ }
+ } else if (forms && !sourceWins(logical)) {
+ continue; // stashed with its first form above
+ }
if (!dstSet.has(f)) {
if (!dryRun) await rename(src, path.join(dstDir, f));
moved.push(f);
diff --git a/common/controller/storedText.chat.test.ts b/common/controller/storedText.chat.test.ts
@@ -0,0 +1,142 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+import type { ChannelConfig } from "../lib/channelConfig";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/storedText.chat.test.ts
+//
+// THE CHAT IS STILL FOUND BY EVERY READER AFTER IT IS COMPRESSED (lane
+// text-compress, slice 1). Each case builds a video dir whose raw replay is
+// `transcript.live_chat.json.zst` only — a real file, and a tier link into
+// the channel's `media/` — and asks every reader of the raw chat what it
+// sees. Before this slice the track vanished and the plan FETCHED the whole
+// replay again. Temp corpus, no network, no yt-dlp.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-chat-"));
+const CORPUS = path.join(ROOT, "transcripts");
+process.env.TRANSCRIPTS_DIR = CORPUS;
+process.env.SETTINGS_FILE = path.join(ROOT, "settings.json");
+await mkdir(CORPUS, { recursive: true });
+await writeFile(process.env.SETTINGS_FILE, "{}");
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { getPaths } = await import("../lib/paths");
+const { liveChatPlan, renormalizeChatRefusal } = await import("./fetchLiveChat");
+const { normalizeLiveChat, isLiveChatCuesFresh } = await import("./normalizeLiveChat");
+const { readSubTracks } = await import("../lib/videoStatus");
+const { trackOnDisk, subLangsForVideo } = await import("../ytdlp/runYtdlp");
+const { youtubeHandlingArgs } = await import("../ytdlp/downloadOneManaged");
+const { storeFixture } = await import("../testing/storedTextFixture");
+
+const paths = getPaths();
+const SLUG = "synth-chat";
+const CONFIG = { handling: "youtube", url: "https://www.youtube.com/@synth/streams", name: "Synth" } as ChannelConfig;
+const CHAT = "transcript.live_chat.json";
+
+function chatLine(sec: number, author: string, text: string): string {
+ return JSON.stringify({
+ replayChatItemAction: {
+ actions: [
+ {
+ addChatItemAction: {
+ item: { liveChatTextMessageRenderer: { message: { runs: [{ text }] }, authorName: { simpleText: author } } },
+ },
+ },
+ ],
+ videoOffsetTimeMsec: String(sec * 1000),
+ },
+ });
+}
+const REPLAY = [chatLine(12, "viewer1", "lol"), chatLine(14, "viewer2", "LMAO"), chatLine(30, "viewer3", "W")].join("\n") + "\n";
+
+const channelDir = path.join(CORPUS, "channels", SLUG);
+
+async function video(id: string, opts: { tiered?: boolean } = {}): Promise<string> {
+ const dir = path.join(channelDir, "data", id);
+ await mkdir(dir, { recursive: true });
+ await writeFile(path.join(channelDir, "config.json"), JSON.stringify(CONFIG));
+ await writeFile(
+ path.join(dir, "metadata.info.json"),
+ JSON.stringify({ id, title: "Synth stream", webpage_url: `https://www.youtube.com/watch?v=${id}`, was_live: true }),
+ );
+ if (opts.tiered) {
+ const media = path.join(channelDir, "media", id);
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, CHAT), REPLAY);
+ await symlink(path.join("..", "..", "media", id, CHAT), path.join(dir, CHAT));
+ } else {
+ await writeFile(path.join(dir, CHAT), REPLAY);
+ }
+ return dir;
+}
+
+const cuesOf = async (dir: string) =>
+ JSON.parse(await readFile(path.join(dir, "live_chat.cues.json"), "utf8")).cues;
+
+for (const tiered of [false, true]) {
+ const how = tiered ? "a tier link" : "a real file";
+
+ test(`compressed as ${how}: the live_chat track is listed under its plain name`, async () => {
+ const dir = await video(`list${tiered ? "t" : "r"}`, { tiered });
+ await storeFixture(dir, CHAT);
+ assert.deepEqual(
+ (await readSubTracks(dir)).map((t) => [t.track, t.filename]),
+ [["live_chat", CHAT]],
+ );
+ });
+
+ test(`compressed as ${how}: normalize reads it and writes the same cues`, async () => {
+ const id = `norm${tiered ? "t" : "r"}`;
+ const dir = await video(id, { tiered });
+ assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, force: true, tier: false })).status, "wrote");
+ const fromPlain = await cuesOf(dir);
+ await storeFixture(dir, CHAT);
+ // Fresh: the stored form carries the plain file's times exactly.
+ assert.equal((await isLiveChatCuesFresh(dir)).fresh, true);
+ assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, tier: false })).status, "fresh");
+ assert.equal((await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, force: true, tier: false })).status, "wrote");
+ assert.deepEqual(await cuesOf(dir), fromPlain);
+ assert.equal(fromPlain.length, 3);
+ });
+
+ test(`compressed as ${how}: the plan normalizes or says fresh — it NEVER fetches`, async () => {
+ const id = `plan${tiered ? "t" : "r"}`;
+ const dir = await video(id, { tiered });
+ await storeFixture(dir, CHAT);
+ // No cues yet: the raw on disk is normalized, not fetched again.
+ assert.deepEqual(await liveChatPlan(paths, SLUG, id, CONFIG), { kind: "normalize" });
+ await normalizeLiveChat({ videoDir: dir, channelSlug: SLUG, tier: false });
+ assert.equal((await liveChatPlan(paths, SLUG, id, CONFIG)).kind, "fresh");
+ // A re-normalize finds the raw chat on disk.
+ assert.equal(await renormalizeChatRefusal(paths, SLUG, id), null);
+ });
+
+ test(`compressed as ${how}: the missing-subs prefilter sees the chat on disk`, async () => {
+ const dir = await video(`subs${tiered ? "t" : "r"}`, { tiered });
+ await storeFixture(dir, CHAT);
+ const { readdir } = await import("node:fs/promises");
+ const entries = await readdir(dir);
+ assert.equal(trackOnDisk(entries, "live_chat"), true);
+ // And a fetch for another missing track leaves the chat out: yt-dlp's own
+ // skip would not see the stored form and would fetch the replay again.
+ assert.equal(subLangsForVideo(entries, "en.*,live_chat"), "en.*");
+ assert.equal(subLangsForVideo(["transcript.live_chat.json"], "en.*,live_chat"), "en.*,live_chat");
+ });
+}
+
+test("a download over a stored chat leaves the chat out of its sub-langs", () => {
+ const langs = (args: string[]) => args[args.indexOf("--sub-langs") + 1];
+ assert.equal(langs(youtubeHandlingArgs(CONFIG, false, false)), "en.*,live_chat");
+ assert.equal(langs(youtubeHandlingArgs(CONFIG, false, true)), "en.*");
+});
+
+test("with no chat in either form the plan still fetches (the control)", async () => {
+ const id = "nochat";
+ const dir = await video(id);
+ await rm(path.join(dir, CHAT));
+ assert.equal((await liveChatPlan(paths, SLUG, id, CONFIG)).kind, "fetch");
+ assert.notEqual(await renormalizeChatRefusal(paths, SLUG, id), null);
+});
diff --git a/common/controller/storedText.delete.test.ts b/common/controller/storedText.delete.test.ts
@@ -0,0 +1,80 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { lstat, mkdir, mkdtemp, readdir, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test controller/storedText.delete.test.ts
+//
+// NO RESURRECTION (lane text-compress, slice 1). A plain file written again
+// beside an older stored copy, then deleted by a deleter that knows only the
+// plain name, would bring the older copy back as the file — silently and
+// wrongly. Every deleter of a declared name removes both forms
+// (`removeStoredText`), each through `removeMediaFile`. Temp dirs only.
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-delete-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const { removeStoredText } = await import("../lib/storedText-write-server");
+const { purgeSupersededAutoSubs } = await import("./purgeSupersededAutoSubs");
+const { readStoredText } = await import("../lib/storedText-server");
+const { storeFixture } = await import("../testing/storedTextFixture");
+
+const CHAT = "transcript.live_chat.json";
+
+async function videoDir(slug: string, id: string): Promise<string> {
+ const d = path.join(ROOT, "channels", slug, "data", id);
+ await mkdir(d, { recursive: true });
+ return d;
+}
+
+const exists = (p: string) => lstat(p).then(() => true, () => false);
+
+test("removeStoredText: a plain chat re-written beside an older stored one — both go", async () => {
+ const d = await videoDir("c", "v1");
+ await writeFile(path.join(d, CHAT), "OLD\n");
+ await storeFixture(d, CHAT);
+ await writeFile(path.join(d, CHAT), "NEW\n");
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "NEW\n");
+ await removeStoredText(d, CHAT);
+ await assert.rejects(readStoredText(d, CHAT, "utf8"), { code: "ENOENT" });
+ assert.deepEqual(await readdir(d), []);
+});
+
+test("removeStoredText through tier links: the bytes in media/<id>/ go too, never orphaned", async () => {
+ const d = await videoDir("t", "v2");
+ const media = path.join(ROOT, "channels", "t", "media", "v2");
+ await mkdir(media, { recursive: true });
+ await writeFile(path.join(media, CHAT), "CHAT\n");
+ await symlink(path.join("..", "..", "media", "v2", CHAT), path.join(d, CHAT));
+ await storeFixture(d, CHAT, { keepPlain: true });
+ assert.ok(await exists(path.join(media, `${CHAT}.zst`)));
+ await removeStoredText(d, CHAT);
+ assert.deepEqual(await readdir(d), []);
+ assert.equal(await exists(path.join(media, CHAT)), false);
+ assert.equal(await exists(path.join(media, `${CHAT}.zst`)), false);
+});
+
+// YouTube's rolling-caption shape: an ASR track (inline word timing).
+const ASR_VTT =
+ "WEBVTT\nKind: captions\nLanguage: en\n\n" +
+ "00:00:00.000 --> 00:00:05.000 align:start position:0%\n" +
+ "First<00:00:01.000><c> caption</c><00:00:02.000><c> line.</c>\n\n" +
+ "00:01:00.000 --> 00:01:50.000 align:start position:0%\n" +
+ "Second<00:01:10.000><c> caption</c><00:01:20.000><c> line.</c>\n";
+
+test("the superseded-auto-caption purge removes a caption's stored sibling too", async () => {
+ const d = await videoDir("p", "v3");
+ await writeFile(path.join(d, "transcript.json"), JSON.stringify({ transcription: [{ text: "x" }] }));
+ await writeFile(path.join(d, "transcript.en.vtt"), ASR_VTT);
+ // What a later stored-captions slice would leave: an older stored copy.
+ await writeFile(path.join(d, "transcript.en.vtt.zst"), "older stored copy");
+ const r = await purgeSupersededAutoSubs({
+ channelSlug: "p",
+ paths: { channelsDir: path.join(ROOT, "channels") } as never,
+ onLog: () => {},
+ });
+ assert.equal(r.removedFiles, 1);
+ assert.deepEqual((await readdir(d)).sort(), ["transcript.json"]);
+});
diff --git a/common/lib/mediaTier-server.test.ts b/common/lib/mediaTier-server.test.ts
@@ -277,6 +277,32 @@ test("the link carries the file's mtime, so an lstat answers freshness without t
await rm(f.root, { recursive: true, force: true });
});
+test("the link keeps a SUB-MILLISECOND mtime exactly (lane text-compress: numeric seconds, not Dates)", async () => {
+ // The index compares these with `!==`: a `Date` keeps whole milliseconds,
+ // so tiering a file with nanosecond times moved its key and re-ingested it.
+ const f = await fixture();
+ await mkdir(channelMediaLink(f.paths, f.slug));
+ const file = path.join(f.videoDir, "transcript.live_chat.json");
+ await utimes(file, 1763700000.123457, 1763700000.987653);
+ const before = (await stat(file)).mtimeMs;
+ assert.notEqual(before, Math.trunc(before), "the fixture has a sub-ms time");
+ assert.equal(await tierMediaFile(f.videoDir, "transcript.live_chat.json"), "tiered");
+ assert.equal((await lstat(file)).mtimeMs, before, "the link");
+ assert.equal((await stat(file)).mtimeMs, before, "the bytes");
+ await rm(f.root, { recursive: true, force: true });
+});
+
+test("the STORED chat (`.zst`) is tiered like the plain one", async () => {
+ const f = await fixture();
+ await mkdir(channelMediaLink(f.paths, f.slug));
+ await writeFile(path.join(f.videoDir, "transcript.live_chat.json.zst"), "ZST");
+ assert.equal(await tierMediaFile(f.videoDir, "transcript.live_chat.json.zst"), "tiered");
+ const link = path.join(f.videoDir, "transcript.live_chat.json.zst");
+ assert.ok((await lstat(link)).isSymbolicLink());
+ assert.equal(await readlink(link), tierLinkTarget("vid1", "transcript.live_chat.json.zst"));
+ await rm(f.root, { recursive: true, force: true });
+});
+
test("a move marker on the channel: the hook writes nothing into media/", async () => {
assert.equal(TIER_RELOCATION_MARKER, RELOCATION_MARKER_FILENAME);
const f = await fixture();
diff --git a/common/lib/mediaTier-server.ts b/common/lib/mediaTier-server.ts
@@ -220,7 +220,11 @@ export async function tierMediaFile(
// `stat` of the file did before it was tiered — the live-chat freshness
// check and the index's sub-track key read it there, on the corpus disk,
// instead of reaching the media drive.
- await lutimes(tmpLink, st.atime, st.mtime).catch(() => {});
+ //
+ // NUMERIC SECONDS, never the `Date`s: a `Date` holds whole milliseconds,
+ // so a file with sub-ms times came out with a different `mtimeMs` and the
+ // index — which compares it with `!==` — re-ingested the record once.
+ await lutimes(tmpLink, st.atimeMs / 1000, st.mtimeMs / 1000).catch(() => {});
await rm(destTmp, { force: true });
try {
await fsx.link(file, destTmp);
@@ -229,7 +233,7 @@ export async function tierMediaFile(
await rm(destTmp, { force: true }).catch(() => {});
if (!NO_HARD_LINK.has(errCode(err) ?? "")) throw err;
await fsx.copyFileAtomic(file, dest);
- await utimes(dest, st.atime, st.mtime).catch(() => {});
+ await utimes(dest, st.atimeMs / 1000, st.mtimeMs / 1000).catch(() => {});
}
placed = true;
if (await markerStands(mediaRoot)) {
@@ -427,7 +431,7 @@ export async function renameMediaFile(
const tmpLink = path.join(videoDir, `.${to}.tierlink-${process.pid}`);
await rm(tmpLink, { force: true });
await symlink(path.relative(videoDir, newTarget), tmpLink);
- await lutimes(tmpLink, st.atime, st.mtime).catch(() => {});
+ await lutimes(tmpLink, st.atimeMs / 1000, st.mtimeMs / 1000).catch(() => {});
await rename(tmpLink, path.join(videoDir, to));
await rm(file, { force: true });
return;
diff --git a/common/lib/mediaTier.ts b/common/lib/mediaTier.ts
@@ -33,6 +33,12 @@ import {
// pins that the two agree.
export const LIVE_CHAT_MEDIA_FILENAME = "transcript.live_chat.json";
+// The raw replay's STORED form (lib/storedText.ts): the same bytes, one zstd
+// frame. Media and tierable exactly like the plain name — without this the
+// tier hook would never move a compressed chat and the reclaim's "a tierable
+// file stays" rule would not cover it.
+export const LIVE_CHAT_STORED_FILENAME = `${LIVE_CHAT_MEDIA_FILENAME}.zst`;
+
// The clip-window cache dir (`clipWindow.ts`'s `CLIPS_DIR_NAME`, pinned by the
// test for the same reason). Never tiered, never classified as media.
export const CLIPS_DIR = "clips";
@@ -81,6 +87,15 @@ const SCRATCH_PATTERNS: ReadonlyArray<RegExp> = [
// The salvage transcription's decoded WAV (`audio.salvage.wav`,
// lib/salvageAudio-server.ts): removed when the transcription ends.
/^audio\.salvage\.wav$/,
+ // The stored-text compressor's temp (`.transcript.live_chat.json.zst.compressing-<pid>`,
+ // lib/storedText-write-server.ts): never a copy anyone reads — the stored
+ // form appears only by a rename of a verified temp — and a dead pid's is
+ // discarded by the next run.
+ /\.compressing-\d+$/,
+ // The original the compressor set aside, between the stored form landing
+ // and the original's removal (`.transcript.live_chat.json.retire-<pid>`):
+ // the next run removes it, or renames it back when it is the only copy.
+ /\.retire-\d+$/,
];
export function isScratchEntry(name: string): boolean {
@@ -98,7 +113,8 @@ export function classifyEntry(name: string): MediaTierKind {
if (
isRealAudioFile(name) ||
isSourceMediaFile(name) ||
- name === LIVE_CHAT_MEDIA_FILENAME
+ name === LIVE_CHAT_MEDIA_FILENAME ||
+ name === LIVE_CHAT_STORED_FILENAME
) {
return "media";
}
@@ -114,7 +130,11 @@ export function classifyEntry(name: string): MediaTierKind {
// - `audio.*.part` stays real: it is yt-dlp's resumable partial, which yt-dlp
// appends to and renames.
export function isTierable(name: string): boolean {
- return isRealAudioFile(name) || name === LIVE_CHAT_MEDIA_FILENAME;
+ return (
+ isRealAudioFile(name) ||
+ name === LIVE_CHAT_MEDIA_FILENAME ||
+ name === LIVE_CHAT_STORED_FILENAME
+ );
}
export type ClassifiedVideoDir = {
diff --git a/common/lib/sidecar-server.test.ts b/common/lib/sidecar-server.test.ts
@@ -87,6 +87,13 @@ test("sidecar() refuses a transcript.<x>.<y> name at declaration", () => {
assert.throws(() => sidecar("a/b.json", sidecarField((v) => v)), /bare filename/);
});
+test("sidecar() refuses a declared stored-text name's stored form (it would be read as the chat)", () => {
+ assert.throws(
+ () => sidecar("transcript.live_chat.json.zst", sidecarField((v) => v)),
+ /stored form of transcript\.live_chat\.json/,
+ );
+});
+
test("absent, unparseable and coercion-rejected all load as null", async () => {
const dir = await scratch();
assert.equal(await loadAvailability(dir), null);
diff --git a/common/lib/sidecar-server.ts b/common/lib/sidecar-server.ts
@@ -32,6 +32,7 @@ import path from "node:path";
import { rm } from "node:fs/promises";
import { z } from "zod";
import { SUB_FILE_RE } from "./videoStatus";
+import { plainNameOf } from "./storedText";
import {
readJsonFile,
writeJsonAtomic,
@@ -74,6 +75,13 @@ export function sidecar<T>(
`Sidecar "${filename}" matches SUB_FILE_RE (transcript.<x>.<y>) and would be read as a subtitle track — rename it`,
);
}
+ // A declared stored-text name's stored form (lib/storedText.ts) is read as
+ // that file: a sidecar so named would be read as the live chat.
+ if (plainNameOf(filename) !== null) {
+ throw new Error(
+ `Sidecar "${filename}" is the stored form of ${plainNameOf(filename)} and would be read as it — rename it`,
+ );
+ }
if (filename.includes("/") || filename.includes(path.sep)) {
throw new Error(`Sidecar "${filename}" must be a bare filename`);
}
diff --git a/common/lib/storedText-server.ts b/common/lib/storedText-server.ts
@@ -0,0 +1,292 @@
+// STORED TEXT ON DISK — THE READ PATH (lib/storedText.ts has the names and
+// the rules). Every reader of a declared name goes through here and accepts
+// either form: the plain file when it is present (the truth), else the stored
+// `<name>.zst`, decompressed. A reader that opens the plain name directly sees
+// a compressed file as ABSENT — which, for the live chat, makes the app fetch
+// it again — and storedText.grep.test.ts fails any such read added outside
+// this module.
+//
+// THE FORMAT: one zstd frame, the content size in its header (the logical size
+// is a few header bytes away) and the content checksum on (a corrupt file
+// throws instead of returning wrong text). Node's zstd does NOT throw on a
+// TRUNCATED frame — it returns what it decoded — so every read here also
+// requires the decoded length to equal the header's content size.
+//
+// SERVER-ONLY.
+
+import path from "node:path";
+import { lstat, open, readdir, readFile, stat } from "node:fs/promises";
+import type { Stats } from "node:fs";
+import zlib from "node:zlib";
+import type { Transform } from "node:stream";
+import {
+ isStoredTextName,
+ logicalEntries,
+ storedNameOf,
+ type StoredForms,
+} from "./storedText";
+
+// Node's zstd, typed here: the workspace's @types/node predates it.
+export type ZstdOptions = {
+ pledgedSrcSize?: number;
+ maxOutputLength?: number;
+ params?: Record<number, number>;
+};
+type ZstdZlib = {
+ zstdDecompress?: (buf: Buffer, opts: ZstdOptions, cb: (err: Error | null, out: Buffer) => void) => void;
+ createZstdCompress?: (opts: ZstdOptions) => Transform;
+ createZstdDecompress?: (opts?: ZstdOptions) => Transform;
+ constants: Record<string, number>;
+};
+const z = zlib as unknown as ZstdZlib;
+
+export function createStoredTextCompressor(size: number): Transform {
+ assertZstdAvailable();
+ return z.createZstdCompress!(storedTextCompressOptions(size));
+}
+
+export function createStoredTextDecompressor(): Transform {
+ assertZstdAvailable();
+ return z.createZstdDecompress!();
+}
+
+// Node's zstd: `zlib.zstdCompress` and friends from Node 22.15.0 (23.8.0).
+// Asked at first use, not at import: a process on an older Node that never
+// meets a stored file keeps working, and one that does gets this sentence.
+export function assertZstdAvailable(): void {
+ if (
+ typeof z.zstdDecompress !== "function" ||
+ typeof z.createZstdCompress !== "function" ||
+ typeof z.createZstdDecompress !== "function"
+ ) {
+ throw new Error(
+ `stored text needs node:zlib zstd — Node >= 22.15 (this is ${process.version})`,
+ );
+ }
+}
+
+export const STORED_TEXT_LEVEL = 9;
+
+// The compressor's options for a source of `size` bytes: level 9, checksum on,
+// the size pledged so it lands in the frame header.
+export function storedTextCompressOptions(size: number): ZstdOptions {
+ assertZstdAvailable();
+ const c = z.constants;
+ return {
+ pledgedSrcSize: size,
+ params: {
+ [c.ZSTD_c_compressionLevel]: STORED_TEXT_LEVEL,
+ [c.ZSTD_c_checksumFlag]: 1,
+ [c.ZSTD_c_contentSizeFlag]: 1,
+ },
+ };
+}
+
+const ZSTD_MAGIC = 0xfd2fb528;
+
+// The content size a zstd frame header declares, or null when the bytes are
+// not a frame header that carries one. `head` needs at most 18 bytes.
+export function frameContentSize(head: Uint8Array): number | null {
+ if (head.length < 5) return null;
+ const dv = new DataView(head.buffer, head.byteOffset, head.byteLength);
+ if (dv.getUint32(0, true) !== ZSTD_MAGIC) return null;
+ const fhd = head[4];
+ const fcsFlag = fhd >> 6;
+ const singleSegment = (fhd >> 5) & 1;
+ const dictFlag = fhd & 3;
+ if (fcsFlag === 0 && !singleSegment) return null; // size not recorded
+ let off = 5 + (singleSegment ? 0 : 1) + [0, 1, 2, 4][dictFlag];
+ const fcsBytes = fcsFlag === 0 ? 1 : [1, 2, 4, 8][fcsFlag];
+ if (head.length < off + fcsBytes) return null;
+ switch (fcsBytes) {
+ case 1:
+ return head[off];
+ case 2:
+ return dv.getUint16(off, true) + 256;
+ case 4:
+ return dv.getUint32(off, true);
+ default: {
+ const lo = dv.getUint32(off, true);
+ const hi = dv.getUint32(off + 4, true);
+ const n = hi * 2 ** 32 + lo;
+ return Number.isSafeInteger(n) ? n : null;
+ }
+ }
+}
+
+// One whole buffer as a stored frame (the compressor streams; this is for a
+// small file and for tests' fixtures).
+export async function encodeStoredBytes(bytes: Buffer): Promise<Buffer> {
+ const c = createStoredTextCompressor(bytes.length);
+ const out: Buffer[] = [];
+ c.on("data", (d: Buffer) => out.push(d));
+ const done = new Promise<void>((resolve, reject) => {
+ c.on("end", () => resolve());
+ c.on("error", reject);
+ });
+ c.end(bytes);
+ await done;
+ return Buffer.concat(out);
+}
+
+export class StoredTextCorruptError extends Error {
+ constructor(file: string, why: string) {
+ super(`${file}: not a whole stored-text frame (${why})`);
+ this.name = "StoredTextCorruptError";
+ }
+}
+
+// A stored file's bytes, decoded and checked: the frame's checksum (zstd
+// throws), and the decoded length against the header's content size (a
+// truncated frame decodes short without an error).
+export async function decodeStoredBytes(bytes: Buffer, label = "stored text"): Promise<Buffer> {
+ assertZstdAvailable();
+ const want = frameContentSize(bytes.subarray(0, 18));
+ if (want === null) throw new StoredTextCorruptError(label, "no content size in the frame header");
+ let out: Buffer;
+ try {
+ out = await new Promise<Buffer>((resolve, reject) =>
+ z.zstdDecompress!(bytes, { maxOutputLength: Math.max(1, want + 1) }, (err, res) =>
+ err ? reject(err) : resolve(res),
+ ),
+ );
+ } catch (err) {
+ throw new StoredTextCorruptError(label, (err as Error).message);
+ }
+ if (out.length !== want) {
+ throw new StoredTextCorruptError(label, `decoded ${out.length} bytes, header says ${want}`);
+ }
+ return out;
+}
+
+function isEnoent(err: unknown): boolean {
+ const code = (err as NodeJS.ErrnoException | null)?.code;
+ return code === "ENOENT" || code === "ENOTDIR";
+}
+
+function enoent(dir: string, name: string): NodeJS.ErrnoException {
+ const err = new Error(`ENOENT: no such file, '${path.join(dir, name)}' (nor its stored form)`) as NodeJS.ErrnoException;
+ err.code = "ENOENT";
+ return err;
+}
+
+// THE READ: the plain file's bytes when it opens; else (a declared name) the
+// stored form, decoded. A plain name that is a dangling link (an interrupted
+// removal, a drive not mounted) does not open, so the stored form is read;
+// when neither opens, ENOENT.
+export async function readStoredText(dir: string, name: string): Promise<Buffer>;
+export async function readStoredText(dir: string, name: string, encoding: "utf8"): Promise<string>;
+export async function readStoredText(
+ dir: string,
+ name: string,
+ encoding?: "utf8",
+): Promise<Buffer | string> {
+ try {
+ return encoding ? await readFile(path.join(dir, name), encoding) : await readFile(path.join(dir, name));
+ } catch (err) {
+ if (!isEnoent(err) || !isStoredTextName(name)) throw err;
+ }
+ const storedPath = path.join(dir, storedNameOf(name));
+ let bytes: Buffer;
+ try {
+ bytes = await readFile(storedPath);
+ } catch (err) {
+ if (isEnoent(err)) throw enoent(dir, name);
+ throw err;
+ }
+ const out = await decodeStoredBytes(bytes, storedPath);
+ return encoding ? out.toString(encoding) : out;
+}
+
+export type StoredTextStat = {
+ // Which form answered.
+ form: "plain" | "zst";
+ // The path that was stat'ed.
+ file: string;
+ stats: Stats;
+};
+
+// THE STAT a freshness or change check asks: of the plain name when it is
+// there, else of the stored form — which carries the plain file's times
+// exactly (the compressor sets them, numeric seconds), so the answer's
+// `mtimeMs` is the SAME number either way. `link: true` is `lstat` (a tiered
+// name is asked on the corpus disk, never on the media drive); otherwise
+// `stat`, where a dangling plain link falls through to the stored form.
+export async function statStoredText(
+ dir: string,
+ name: string,
+ opts: { link?: boolean } = {},
+): Promise<StoredTextStat> {
+ const ask = opts.link ? lstat : stat;
+ const plain = path.join(dir, name);
+ try {
+ return { form: "plain", file: plain, stats: await ask(plain) };
+ } catch (err) {
+ if (!isEnoent(err) || !isStoredTextName(name)) throw err;
+ }
+ const stored = path.join(dir, storedNameOf(name));
+ try {
+ return { form: "zst", file: stored, stats: await ask(stored) };
+ } catch (err) {
+ if (isEnoent(err)) throw enoent(dir, name);
+ throw err;
+ }
+}
+
+// The `mtimeMs` of `statStoredText`, or null when neither form answers.
+export async function storedTextMtimeMs(
+ dir: string,
+ name: string,
+ opts: { link?: boolean } = {},
+): Promise<number | null> {
+ try {
+ return (await statStoredText(dir, name, opts)).stats.mtimeMs;
+ } catch {
+ return null;
+ }
+}
+
+// Is `name` here in either form? An `lstat` — what a listing would say: a
+// dangling link is an entry (a drive that is not mounted is not an empty dir).
+export async function storedTextExists(dir: string, name: string): Promise<boolean> {
+ try {
+ await statStoredText(dir, name, { link: true });
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+// Which forms are present, by `lstat` of each.
+export async function storedTextForms(dir: string, name: string): Promise<StoredForms | null> {
+ const here = (n: string) => lstat(path.join(dir, n)).then(() => true, () => false);
+ const plain = await here(name);
+ const zst = isStoredTextName(name) ? await here(storedNameOf(name)) : false;
+ if (plain && zst) return "both";
+ if (plain) return "plain";
+ if (zst) return "zst";
+ return null;
+}
+
+// The LOGICAL size: the plain file's, or the content size the stored frame's
+// header declares (18 bytes read, nothing decompressed). Follows links.
+export async function storedTextLogicalSize(dir: string, name: string): Promise<number> {
+ const s = await statStoredText(dir, name);
+ if (s.form === "plain") return s.stats.size;
+ const fh = await open(s.file, "r");
+ try {
+ const head = Buffer.alloc(18);
+ const { bytesRead } = await fh.read(head, 0, 18, 0);
+ const n = frameContentSize(head.subarray(0, bytesRead));
+ if (n === null) throw new StoredTextCorruptError(s.file, "no content size in the frame header");
+ return n;
+ } finally {
+ await fh.close();
+ }
+}
+
+// A MATCHING listing of a dir: readdir, each declared `X.zst` reported as `X`.
+// A missing dir lists nothing.
+export async function readdirLogical(dir: string): Promise<string[]> {
+ return logicalEntries(await readdir(dir).catch(() => [] as string[]));
+}
diff --git a/common/lib/storedText-write-server.ts b/common/lib/storedText-write-server.ts
@@ -0,0 +1,26 @@
+// STORED TEXT ON DISK — THE WRITE HALF: the one way to delete a declared name
+// (`removeStoredText`), and the compressor (`compressStoredText`, below). The
+// names and the rules are lib/storedText.ts; the read path is
+// lib/storedText-server.ts.
+//
+// THE ONE WAY TO DELETE A DECLARED NAME. A deleter that removed only the plain
+// `transcript.live_chat.json` would RESURRECT an older stored
+// `transcript.live_chat.json.zst` beside it — the one failure here that is
+// silent and wrong. So every deleter of a declared name calls
+// `removeStoredText`, which removes both forms, each through
+// `removeMediaFile` (a tier link's bytes go too). The stored form goes FIRST:
+// a process killed between the two leaves the plain file — the truth — never
+// the older stored copy alone.
+//
+// lib/, so no controller import (architecture.test.ts). SERVER-ONLY.
+
+import { removeMediaFile } from "./mediaTier-server";
+import { storedNameOf } from "./storedText";
+
+// Remove `name` in both forms (any name: for one that is not declared, its
+// `.zst` sibling is not this module's and is removed only if it is there —
+// nothing else ever writes one). Missing is not an error.
+export async function removeStoredText(videoDir: string, name: string): Promise<void> {
+ await removeMediaFile(videoDir, storedNameOf(name));
+ await removeMediaFile(videoDir, name);
+}
diff --git a/common/lib/storedText.grep.test.ts b/common/lib/storedText.grep.test.ts
@@ -0,0 +1,96 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { readdir, readFile } from "node:fs/promises";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.grep.test.ts
+//
+// THE STORED-TEXT GATE (lane text-compress). The raw live chat may be on disk
+// as `transcript.live_chat.json.zst` (lib/storedText.ts). A reader that opens,
+// stats, lists or deletes the plain name directly sees that file as ABSENT —
+// for the chat that is a fetch of the whole replay again, or (a deleter) an
+// older stored copy brought back as the file. So every line of app code that
+// names the raw chat must go through the stored-text helpers. A context-blind
+// grep, like architecture.test.ts: each line naming it (by its constant or the
+// literal) must also name a sanctioned helper within the same statement (the
+// line or the two before it), or interpolate the name into a message, or be
+// an import, or be one of the definitions below.
+
+const COMMON = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
+const REPO = path.dirname(COMMON);
+
+const ROOTS = ["common", "editor/app", "mcp/src", "umtool", "export/scripts", "export/lib", "export/app"];
+const SKIP_DIRS = new Set(["node_modules", ".next", "out", "public", "e2e", "dist", ".turbo"]);
+
+// The names of the raw chat in code: the two constants, the stored one, the
+// literal (but not its `.part`, its `.zst` spelled out in a comment, or the
+// derived `live_chat.cues.json`).
+const NAMES = /\bLIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\b|transcript\.live_chat\.json(?![.\w])/;
+
+// The read path, the existence checks, the one deleter, and the tier hook
+// (which moves whichever form it is given and never reads it).
+const SANCTIONED =
+ /\b(?:listingHas|storedFormsIn|logicalEntries|readdirLogical|storedTextExists|storedTextForms|storedTextMtimeMs|statStoredText|readStoredText|storedTextLogicalSize|removeStoredText|compressStoredText|tierMediaFile|isStoredTextName)\b/;
+
+// Where the names are DEFINED or are the rules themselves.
+const DEFINITIONS = new Set([
+ "common/lib/videoStatus.ts",
+ "common/lib/mediaTier.ts",
+ "common/lib/storedText.ts",
+ "common/lib/storedText-server.ts",
+ "common/lib/storedText-write-server.ts",
+]);
+
+async function walk(dir: string, out: string[]): Promise<void> {
+ let entries;
+ try {
+ entries = await readdir(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ if (SKIP_DIRS.has(e.name)) continue;
+ const p = path.join(dir, e.name);
+ if (e.isDirectory()) await walk(p, out);
+ else if (/\.(?:ts|tsx|mjs|js)$/.test(e.name) && !/\.(?:test|spec|unit)\.|\.d\.m?ts$/.test(e.name)) out.push(p);
+ }
+}
+
+function codeOnly(line: string): string {
+ const t = line.trim();
+ if (t.startsWith("//") || t.startsWith("*") || t.startsWith("/*")) return "";
+ // A trailing comment is not code.
+ return line.replace(/\s\/\/.*$/, "");
+}
+
+test("every app line naming the raw live chat goes through the stored-text helpers", async () => {
+ const files: string[] = [];
+ for (const r of ROOTS) await walk(path.join(REPO, r), files);
+ assert.ok(files.length > 200, `walked ${files.length} files`);
+ const offenders: string[] = [];
+ for (const file of files) {
+ const rel = path.relative(REPO, file);
+ if (DEFINITIONS.has(rel)) continue;
+ const lines = (await readFile(file, "utf8")).split("\n");
+ for (let i = 0; i < lines.length; i++) {
+ const code = codeOnly(lines[i]);
+ if (!NAMES.test(code)) continue;
+ // An import or an import/export list member.
+ if (/^\s*(?:import\b|export\s*\{)/.test(code) || /^\s*[A-Z_]+,?\s*$/.test(code)) continue;
+ // Interpolated into a message (a log line, an error).
+ if (/\$\{LIVE_CHAT_(?:MEDIA_|STORED_)?FILENAME\}/.test(code)) continue;
+ // UI copy naming the file.
+ if (/<code>transcript\.live_chat\.json<\/code>/.test(code)) continue;
+ const statement = [lines[i - 2] ?? "", lines[i - 1] ?? "", code].map(codeOnly).join("\n");
+ if (SANCTIONED.test(statement)) continue;
+ offenders.push(`${rel}:${i + 1}: ${lines[i].trim()}`);
+ }
+ }
+ assert.deepEqual(
+ offenders,
+ [],
+ "read, list, stat or delete the raw live chat through lib/storedText(-server|-write-server).ts — it may be stored as .zst",
+ );
+});
diff --git a/common/lib/storedText.test.ts b/common/lib/storedText.test.ts
@@ -0,0 +1,157 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { lstat, mkdir, mkdtemp, readFile, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import path from "node:path";
+
+// Run with:
+// pnpm --filter yt-dlp-transcript-common exec tsx --test lib/storedText.test.ts
+//
+// STORED TEXT (lane text-compress): the names, the classifier, and the one
+// read path that accepts either form. Temp dirs, synthetic names.
+
+import {
+ STORED_TEXT_NAMES,
+ isStoredTextName,
+ listingHas,
+ logicalEntries,
+ plainNameOf,
+ storedFormsIn,
+ storedNameOf,
+} from "./storedText";
+import {
+ decodeStoredBytes,
+ encodeStoredBytes,
+ frameContentSize,
+ readStoredText,
+ readdirLogical,
+ statStoredText,
+ storedTextExists,
+ storedTextForms,
+ storedTextLogicalSize,
+ storedTextMtimeMs,
+ StoredTextCorruptError,
+} from "./storedText-server";
+import { classifyEntry, isScratchEntry, isTierable, LIVE_CHAT_STORED_FILENAME } from "./mediaTier";
+import { LIVE_CHAT_FILENAME } from "./videoStatus";
+
+const ROOT = await mkdtemp(path.join(tmpdir(), "stored-text-"));
+test.after(() => rm(ROOT, { recursive: true, force: true }));
+
+const CHAT = LIVE_CHAT_FILENAME;
+const BODY = '{"replayChatItemAction":{"actions":[]}}\n'.repeat(500);
+
+async function dir(name: string): Promise<string> {
+ const d = path.join(ROOT, name);
+ await mkdir(d, { recursive: true });
+ return d;
+}
+
+test("the declared names: the live chat only, its stored form `.zst`", () => {
+ assert.deepEqual([...STORED_TEXT_NAMES], [CHAT]);
+ assert.equal(isStoredTextName(CHAT), true);
+ assert.equal(isStoredTextName("transcript.en.vtt"), false);
+ assert.equal(storedNameOf(CHAT), "transcript.live_chat.json.zst");
+ assert.equal(plainNameOf("transcript.live_chat.json.zst"), CHAT);
+ // Not declared: a `.zst` of another name stands for nothing here.
+ assert.equal(plainNameOf("transcript.en.vtt.zst"), null);
+ assert.equal(plainNameOf(CHAT), null);
+ assert.equal(LIVE_CHAT_STORED_FILENAME, storedNameOf(CHAT));
+});
+
+test("a logical listing reports the stored chat under its plain name, once", () => {
+ assert.deepEqual(
+ logicalEntries(["metadata.info.json", "transcript.live_chat.json.zst", CHAT, "x.zst"]),
+ ["metadata.info.json", CHAT, "x.zst"],
+ );
+ assert.equal(listingHas(["transcript.live_chat.json.zst"], CHAT), true);
+ assert.equal(listingHas(["transcript.en.vtt.zst"], "transcript.en.vtt"), false);
+ assert.equal(storedFormsIn([CHAT], CHAT), "plain");
+ assert.equal(storedFormsIn(["transcript.live_chat.json.zst"], CHAT), "zst");
+ assert.equal(storedFormsIn([CHAT, "transcript.live_chat.json.zst"], CHAT), "both");
+ assert.equal(storedFormsIn([], CHAT), null);
+});
+
+test("the classifier: the stored chat is media and tierable; the compressor's temps are scratch", () => {
+ assert.equal(classifyEntry("transcript.live_chat.json.zst"), "media");
+ assert.equal(isTierable("transcript.live_chat.json.zst"), true);
+ assert.equal(classifyEntry(".transcript.live_chat.json.zst.compressing-4242"), "scratch");
+ assert.equal(isScratchEntry(".transcript.live_chat.json.retire-4242"), true);
+ assert.equal(isTierable(".transcript.live_chat.json.zst.compressing-4242"), false);
+ // Not a declared stored form: text, as before.
+ assert.equal(classifyEntry("transcript.en.vtt.zst"), "text");
+});
+
+test("a frame carries its content size; the reader decodes and checks it", async () => {
+ const bytes = await encodeStoredBytes(Buffer.from(BODY));
+ assert.equal(frameContentSize(bytes.subarray(0, 18)), Buffer.byteLength(BODY));
+ assert.equal((await decodeStoredBytes(bytes)).toString(), BODY);
+ assert.equal(frameContentSize(Buffer.from("not a frame at all")), null);
+});
+
+test("a TRUNCATED or corrupt stored file throws — it never reads as shorter text", async () => {
+ const bytes = await encodeStoredBytes(Buffer.from(BODY));
+ await assert.rejects(decodeStoredBytes(bytes.subarray(0, bytes.length - 12)), StoredTextCorruptError);
+ for (const off of [10, Math.floor(bytes.length / 2), bytes.length - 2]) {
+ const bad = Buffer.from(bytes);
+ bad[off] ^= 0xff;
+ await assert.rejects(decodeStoredBytes(bad), StoredTextCorruptError, `flipped byte ${off}`);
+ }
+ await assert.rejects(decodeStoredBytes(Buffer.from("plain text")), StoredTextCorruptError);
+});
+
+test("readStoredText: plain first, else the stored form, else ENOENT", async () => {
+ const d = await dir("read");
+ await assert.rejects(readStoredText(d, CHAT, "utf8"), { code: "ENOENT" });
+ await writeFile(path.join(d, storedNameOf(CHAT)), await encodeStoredBytes(Buffer.from(BODY)));
+ assert.equal(await readStoredText(d, CHAT, "utf8"), BODY);
+ assert.ok((await readStoredText(d, CHAT)).equals(Buffer.from(BODY)));
+ // Both: the plain one is the truth.
+ await writeFile(path.join(d, CHAT), "NEWER\n");
+ assert.equal(await readStoredText(d, CHAT, "utf8"), "NEWER\n");
+ // A name that is not declared never reads a `.zst`.
+ await writeFile(path.join(d, "other.json.zst"), await encodeStoredBytes(Buffer.from("x")));
+ await assert.rejects(readStoredText(d, "other.json", "utf8"), { code: "ENOENT" });
+});
+
+test("a dangling plain link (an interrupted removal) reads the stored form", async () => {
+ const d = await dir("dangling");
+ await symlink("../nowhere/transcript.live_chat.json", path.join(d, CHAT));
+ await writeFile(path.join(d, storedNameOf(CHAT)), await encodeStoredBytes(Buffer.from(BODY)));
+ assert.equal(await readStoredText(d, CHAT, "utf8"), BODY);
+ // A listing (lstat) still has the plain name; a stat falls through.
+ assert.equal((await statStoredText(d, CHAT, { link: true })).form, "plain");
+ assert.equal((await statStoredText(d, CHAT)).form, "zst");
+});
+
+test("statStoredText answers the plain file's mtimeMs from the stored form, exactly", async () => {
+ const d = await dir("mtime");
+ const plain = path.join(d, CHAT);
+ await writeFile(plain, BODY);
+ // A nanosecond-precision time, as ext4 keeps them.
+ await utimes(plain, 1763700000.123456, 1763700000.987654);
+ const before = (await lstat(plain)).mtimeMs;
+ const { storeFixture } = await import("../testing/storedTextFixture");
+ await storeFixture(d, CHAT);
+ assert.equal(await storedTextMtimeMs(d, CHAT, { link: true }), before);
+ assert.equal(await storedTextMtimeMs(d, CHAT), before);
+ assert.equal(await storedTextMtimeMs(d, "transcript.de.vtt"), null);
+});
+
+test("existence, forms, logical size and the logical readdir", async () => {
+ const d = await dir("exists");
+ assert.equal(await storedTextExists(d, CHAT), false);
+ assert.equal(await storedTextForms(d, CHAT), null);
+ await writeFile(path.join(d, storedNameOf(CHAT)), await encodeStoredBytes(Buffer.from(BODY)));
+ await writeFile(path.join(d, "metadata.info.json"), "{}");
+ assert.equal(await storedTextExists(d, CHAT), true);
+ assert.equal(await storedTextForms(d, CHAT), "zst");
+ assert.equal(await storedTextLogicalSize(d, CHAT), Buffer.byteLength(BODY));
+ assert.ok((await stat(path.join(d, storedNameOf(CHAT)))).size < Buffer.byteLength(BODY) / 5);
+ assert.deepEqual((await readdirLogical(d)).sort(), ["metadata.info.json", CHAT]);
+ await writeFile(path.join(d, CHAT), BODY);
+ assert.equal(await storedTextForms(d, CHAT), "both");
+ assert.equal(await storedTextLogicalSize(d, CHAT), Buffer.byteLength(BODY));
+ assert.deepEqual(await readdirLogical(path.join(d, "missing")), []);
+ assert.equal((await readFile(path.join(d, CHAT), "utf8")).length, BODY.length);
+});
diff --git a/common/lib/storedText.ts b/common/lib/storedText.ts
@@ -0,0 +1,85 @@
+// STORED TEXT — a big, rarely read text file kept on disk as one zstd frame,
+// under its own name plus `.zst` (`transcript.live_chat.json.zst`), and read
+// back as if it were the plain file. Pure: names only, no fs (the read path is
+// lib/storedText-server.ts, the compressor and the one deleter
+// lib/storedText-write-server.ts).
+//
+// DECLARED NAMES ONLY. A name is stored compressed only when it is in
+// STORED_TEXT_NAMES; for every other name `<name>.zst` means nothing here. The
+// raw live-chat replay is the one declared name today (lane text-compress,
+// slices 1–2: the media drive's tens of GB of chat). Captions are a later
+// slice; `metadata.info.json` is out of scope.
+//
+// THE RULE: PLAIN, WHEN PRESENT, IS THE TRUTH. Every writer keeps writing the
+// plain name (yt-dlp, the chat fetch); none has to know about the stored form.
+// When both are present the plain one is either the latest write or a
+// compression that has not finished — reading it is right in both cases.
+//
+// TWO KINDS OF LISTING. One used to MATCH names (is the chat on disk, which
+// tracks are there, what to fetch) is LOGICAL: `logicalEntries` reports each
+// declared `X.zst` as `X`. One used to OPERATE on every entry as a file (the
+// files card, the movers, the byte walk) stays PHYSICAL: there the `.zst` is a
+// file with its own name and size.
+
+import { LIVE_CHAT_MEDIA_FILENAME } from "./mediaTier";
+
+export const STORED_TEXT_SUFFIX = ".zst";
+
+// The names stored compressed. One state per name, whatever its size: simpler
+// to test than "compressed when big".
+export const STORED_TEXT_NAMES: readonly string[] = Object.freeze([LIVE_CHAT_MEDIA_FILENAME]);
+
+const DECLARED = new Set(STORED_TEXT_NAMES);
+
+export function isStoredTextName(name: string): boolean {
+ return DECLARED.has(name);
+}
+
+export function storedNameOf(name: string): string {
+ return `${name}${STORED_TEXT_SUFFIX}`;
+}
+
+// The plain name a stored file stands for, or null when `name` is not the
+// stored form of a declared name.
+export function plainNameOf(name: string): string | null {
+ if (!name.endsWith(STORED_TEXT_SUFFIX)) return null;
+ const plain = name.slice(0, -STORED_TEXT_SUFFIX.length);
+ return DECLARED.has(plain) ? plain : null;
+}
+
+// The name a listing that MATCHES reports for this entry.
+export function logicalNameOf(name: string): string {
+ return plainNameOf(name) ?? name;
+}
+
+// A readdir's names as a matching listing: each declared `X.zst` reported as
+// `X`, deduped (both forms present are one file), first-seen order kept.
+export function logicalEntries(entries: Iterable<string>): string[] {
+ const out: string[] = [];
+ const seen = new Set<string>();
+ for (const e of entries) {
+ const n = logicalNameOf(e);
+ if (seen.has(n)) continue;
+ seen.add(n);
+ out.push(n);
+ }
+ return out;
+}
+
+// Does this PHYSICAL listing hold `name` in either form?
+export function listingHas(entries: readonly string[], name: string): boolean {
+ if (entries.includes(name)) return true;
+ return isStoredTextName(name) && entries.includes(storedNameOf(name));
+}
+
+export type StoredForms = "plain" | "zst" | "both";
+
+// Which forms of a declared `name` a physical listing holds, or null for none.
+export function storedFormsIn(entries: readonly string[], name: string): StoredForms | null {
+ const plain = entries.includes(name);
+ const zst = isStoredTextName(name) && entries.includes(storedNameOf(name));
+ if (plain && zst) return "both";
+ if (plain) return "plain";
+ if (zst) return "zst";
+ return null;
+}
diff --git a/common/lib/videoStatus.ts b/common/lib/videoStatus.ts
@@ -2,6 +2,7 @@ import path from "node:path";
import { readdir, readFile, stat } from "node:fs/promises";
import { isPartAudioFile, isRealAudioFile } from "./mediaFiles";
import { parseVtt, type Cue } from "./vtt";
+import { logicalEntries } from "./storedText";
export type VideoFiles = {
hasMeta: boolean;
@@ -272,8 +273,12 @@ export async function readVideoFiles(
};
}
+// A LOGICAL listing (lib/storedText.ts): a chat stored as
+// `transcript.live_chat.json.zst` is the `live_chat` track under its plain
+// name — the name every reader of the track's bytes opens through
+// lib/storedText-server.ts.
export async function readSubTracks(videoDir: string): Promise<SubTrack[]> {
- const entries = await readdir(videoDir).catch(() => [] as string[]);
+ const entries = logicalEntries(await readdir(videoDir).catch(() => [] as string[]));
const tracks: SubTrack[] = [];
for (const entry of entries) {
if (entry === WHISPER_FILENAME) continue;
diff --git a/common/testing/storedTextFixture.ts b/common/testing/storedTextFixture.ts
@@ -0,0 +1,40 @@
+// Tests' twin of the stored-text compressor (lib/storedText-write-server.ts):
+// a fixture file put into its stored form the way the compressor leaves it —
+// `<name>.zst` beside it with the plain file's times (numeric seconds), a
+// tier link's stored bytes beside its target in `media/<id>/` with a link of
+// the plain link's times — and the plain form removed (or kept, `keepPlain`).
+// Temp dirs only.
+
+import path from "node:path";
+import { lstat, lutimes, readFile, readlink, rm, stat, symlink, utimes, writeFile } from "node:fs/promises";
+import { encodeStoredBytes } from "../lib/storedText-server";
+import { storedNameOf } from "../lib/storedText";
+
+export async function storeFixture(
+ videoDir: string,
+ name: string,
+ opts: { keepPlain?: boolean } = {},
+): Promise<void> {
+ const plain = path.join(videoDir, name);
+ const l = await lstat(plain);
+ if (l.isSymbolicLink()) {
+ const rel = await readlink(plain);
+ const target = path.resolve(videoDir, rel);
+ const st = await stat(target);
+ const storedBytes = path.join(path.dirname(target), storedNameOf(name));
+ await writeFile(storedBytes, await encodeStoredBytes(await readFile(target)));
+ await utimes(storedBytes, st.atimeMs / 1000, st.mtimeMs / 1000);
+ const link = path.join(videoDir, storedNameOf(name));
+ await symlink(path.join(path.dirname(rel), storedNameOf(name)), link);
+ await lutimes(link, l.atimeMs / 1000, l.mtimeMs / 1000);
+ if (!opts.keepPlain) {
+ await rm(target);
+ await rm(plain);
+ }
+ return;
+ }
+ const stored = path.join(videoDir, storedNameOf(name));
+ await writeFile(stored, await encodeStoredBytes(await readFile(plain)));
+ await utimes(stored, l.atimeMs / 1000, l.mtimeMs / 1000);
+ if (!opts.keepPlain) await rm(plain);
+}
diff --git a/common/ytdlp/downloadOneManaged.ts b/common/ytdlp/downloadOneManaged.ts
@@ -70,6 +70,7 @@ import { evaluateDownloadFilters } from "../lib/downloadFilters";
import { normalizeLiveChat } from "../controller/normalizeLiveChat";
import { writeCuesAfterDownload } from "../controller/normalizeTranscript";
import { LIVE_CHAT_FILENAME } from "../lib/videoStatus";
+import { listingHas, storedFormsIn } from "../lib/storedText";
import {
upsertMetadataScan,
type MetadataScanEntry,
@@ -291,9 +292,16 @@ export type ManagedDownloadOpts = {
// "no transcript" and fetches the media (attempt 3). Any other error is still
// 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.
-function youtubeHandlingArgs(
+//
+// A CHAT ALREADY STORED (`chatStored`, lib/storedText.ts): yt-dlp's own
+// "already present" skip looks for the plain `transcript.live_chat.json`, so
+// over a compressed one it would fetch the whole replay again. The chat is
+// left out of the sub-langs instead, as for a `later` channel. Exported for
+// its test.
+export function youtubeHandlingArgs(
config: ChannelConfig,
reuseInfoJson = false,
+ chatStored = false,
): string[] {
const args = [
"--write-auto-subs",
@@ -301,7 +309,7 @@ function youtubeHandlingArgs(
"--sub-langs",
// Without the live chat unless the channel fetches it with the download
// (ChannelConfig.chat).
- effectiveSubLangs(config),
+ effectiveSubLangs(chatStored ? { ...config, chat: "later" } : config),
];
if (!reuseInfoJson) args.push("--write-info-json");
args.push(
@@ -614,7 +622,8 @@ export function liveChatOnlyArgs(
// a metadata.info.json is the leftover this slice exists to stop creating.
async function hasLiveChatOnDisk(videoDir: string): Promise<boolean> {
const entries = await readdir(videoDir).catch(() => [] as string[]);
- return entries.includes(LIVE_CHAT_FILENAME);
+ // Either form (lib/storedText.ts).
+ return listingHas(entries, LIVE_CHAT_FILENAME);
}
function attemptSucceeded(exitCode: number | null): boolean {
@@ -1292,11 +1301,18 @@ async function runManagedDownload(
// its own args; youtube handling downloads subtitles (the persistence plan only
// applies to the no-subs fallback below). For transcribe handling the plan
// chooses audio-only vs. keep-source-video and yt-dlp vs. app extraction.
+ const chatStored =
+ opts.channelConfig.handling === "youtube" && canonicalId
+ ? storedFormsIn(
+ await readdir(path.join(channelDir, "data", canonicalId)).catch(() => [] as string[]),
+ LIVE_CHAT_FILENAME,
+ ) === "zst"
+ : false;
const mediaArgs =
opts.channelConfig.handling === "youtube"
? [
...outputArgsForUrl(opts.videoUrl),
- ...youtubeHandlingArgs(opts.channelConfig, reuseInfoJson),
+ ...youtubeHandlingArgs(opts.channelConfig, reuseInfoJson, chatStored),
]
: transcribeMediaArgs(
opts.videoUrl,
diff --git a/common/ytdlp/runYtdlp.ts b/common/ytdlp/runYtdlp.ts
@@ -2,6 +2,7 @@
// process's outward doors refuse before any request.
import "../lib/noNetwork.mjs";
import { tierChannelMedia } from "../lib/mediaTier-server";
+import { logicalEntries, storedFormsIn } from "../lib/storedText";
import path from "node:path";
import { mkdir, readdir, readFile } from "node:fs/promises";
import { writeFileAtomic } from "../lib/jsonFile-server";
@@ -26,7 +27,7 @@ import {
platformMinGapSeconds,
staticSleepRequestsSeconds,
} from "./channelArgs";
-import { isRealAudioFile } from "../lib/videoStatus";
+import { isRealAudioFile, LIVE_CHAT_FILENAME } from "../lib/videoStatus";
import { readVttProvenance } from "../lib/subtitleProvenance";
import { extractVideoId } from "../lib/videoId";
import type { Paths } from "../lib/paths";
@@ -1482,10 +1483,21 @@ function compileSubLangMatcher(spec: string): (track: string) => boolean {
const SUB_EXT_PATTERN = "(?:vtt|json|json3|srv1|srv2|srv3)";
-function trackOnDisk(entries: string[], track: string): boolean {
+// One video's `--sub-langs` for the missing-subs fetch. A chat stored
+// compressed (lib/storedText.ts) is on disk, but yt-dlp's own "already
+// present" skip looks for the plain name and would fetch the whole replay
+// again: it is left out, as for a `later` channel. Exported for its test.
+export function subLangsForVideo(entries: readonly string[], subLangs: string): string {
+ if (storedFormsIn(entries, LIVE_CHAT_FILENAME) !== "zst") return subLangs;
+ return effectiveSubLangs({ subLangs, chat: "later" });
+}
+
+// Over a LOGICAL listing (lib/storedText.ts): a chat stored as
+// `transcript.live_chat.json.zst` is on disk. Exported for its test.
+export function trackOnDisk(entries: string[], track: string): boolean {
const escaped = track.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
const re = new RegExp(`^transcript\\.${escaped}\\.${SUB_EXT_PATTERN}$`);
- return entries.some((e) => re.test(e));
+ return logicalEntries(entries).some((e) => re.test(e));
}
// Fetch only the missing subtitle tracks for one already-downloaded video.
@@ -1545,6 +1557,7 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> {
const matchesSubLang = compileSubLangMatcher(subLangs);
const tofetch: string[] = [];
+ const subLangsFor = new Map<string, string>();
let upToDate = 0;
let unidentifiable = 0;
let noMetadata = 0;
@@ -1609,6 +1622,8 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> {
continue;
}
tofetch.push(url);
+ const own = subLangsForVideo(entries, subLangs);
+ if (own !== subLangs) subLangsFor.set(url, own);
}
opts.onLog(
@@ -1678,7 +1693,7 @@ async function downloadMissingSubs(opts: RunYtdlpOpts): Promise<void> {
task ? { ...opts, onLog: task.onLog } : opts,
root,
url,
- subLangs,
+ subLangsFor.get(url) ?? subLangs,
);
// yt-dlp exited clean. A subtitle 429 it reported anyway (a WARNING)
// is still a deferral; otherwise the subtitles came down and the
diff --git a/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts b/editor/app/channels/[slug]/lib/fixIncompleteTranscript.ts
@@ -10,6 +10,7 @@
// short transcript. The fix MUST re-fetch the audio first.
import { removeMediaFile } from "yt-dlp-transcript-common/lib/mediaTier-server";
+import { removeStoredText } from "yt-dlp-transcript-common/lib/storedText-write-server";
import path from "node:path";
import { readdir } from "node:fs/promises";
import type { ChannelConfig } from "yt-dlp-transcript-common/lib/channelConfig";
@@ -151,8 +152,11 @@ export async function clearIncompleteTranscriptOne(opts: {
name === "transcript.cues.json",
);
for (const name of toRemove) {
- // Through its link when tiered (release 17): the bytes go too.
- await removeMediaFile(resolved, name);
+ // Through its link when tiered (release 17): the bytes go too. A caption
+ // track in both forms (lib/storedText-write-server.ts): a stored copy left
+ // behind would bring the cleared transcript back.
+ if (isTranscriptVtt(name)) await removeStoredText(resolved, name);
+ else await removeMediaFile(resolved, name);
}
return { removed: toRemove.length };
}
diff --git a/editor/app/channels/[slug]/videos/[id]/videoActions.ts b/editor/app/channels/[slug]/videos/[id]/videoActions.ts
@@ -60,6 +60,8 @@ import {
} from "yt-dlp-transcript-common/lib/channelMedia";
import { onDrive } from "yt-dlp-transcript-common/lib/storageHealth";
import { isTierable } from "yt-dlp-transcript-common/lib/mediaTier";
+import { isStoredTextName } from "yt-dlp-transcript-common/lib/storedText";
+import { removeStoredText } from "yt-dlp-transcript-common/lib/storedText-write-server";
import { setExcludedFromTruncatedCheck } from "yt-dlp-transcript-common/lib/excludeTruncatedCheck-server";
import { pinTranscript } from "yt-dlp-transcript-common/lib/transcriptPin-server";
import { readVideoTracks } from "yt-dlp-transcript-common/lib/captionTracks-server";
@@ -1072,8 +1074,13 @@ export async function deleteVideoFileAction(
return { ok: false, error: `Not a regular file: ${filename}` };
}
// Through its link when the file is tiered (release 17): the bytes on the
- // media tier go too, never orphaned behind a removed link.
- await removeMediaFile(videoDir, path.basename(target));
+ // media tier go too, never orphaned behind a removed link. A declared stored
+ // name (lib/storedText.ts) is one file in two forms: the plain one deleted
+ // takes its stored copy with it, which would otherwise come back as the
+ // file. The stored form clicked by its own name goes alone.
+ const name = path.basename(target);
+ if (isStoredTextName(name)) await removeStoredText(videoDir, name);
+ else await removeMediaFile(videoDir, name);
revalidatePath(`/channels/${slug}/videos/${videoId}`);
requestChannelSnapshot(getPaths(), slug);
return { ok: true };