import { test } from "node:test"; import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { lstat, mkdir, mkdtemp, readdir, readFile, readlink, rename, 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.compress.test.ts // // THE COMPRESSOR (lane text-compress, slice 2) — a DATA-LOSS-SENSITIVE path: // it removes originals. Every case is a temp channel tree. The kill points are // the compressor's `crashAt` seam: it throws there and nothing after it runs, // cleanup included — what a SIGKILL leaves — and the temps carry a pid that is // not alive. After each: a reader still gets ONE WHOLE COPY, a leftover // partial stored file never counts as the file, and the next run finishes. const ROOT = await mkdtemp(path.join(tmpdir(), "stored-compress-")); test.after(() => rm(ROOT, { recursive: true, force: true })); const { compressStoredText, CompressKill, verifyStoredText, } = await import("./storedText-write-server"); const { readStoredText, statStoredText, readdirLogical, encodeStoredBytes } = await import("./storedText-server"); const CHAT = "transcript.live_chat.json"; const ZST = `${CHAT}.zst`; const DEAD = 999_999_999; // never a live pid const KILL_POINTS = ["compressing", "written", "verified", "placed", "linked", "retired"] as const; // ~1.6 MB of chat lines, varied enough that the stored frame is written in // several chunks (so a kill at "compressing" leaves a PARTIAL temp). const ORIGINAL = Array.from({ length: 12_000 }, (_, i) => JSON.stringify({ replayChatItemAction: { actions: [{ addChatItemAction: { item: { liveChatTextMessageRenderer: { message: { runs: [{ text: `msg ${i} ${createHash("md5").update(String(i)).digest("hex")}` }] }, authorName: { simpleText: `viewer${i % 97}` } } } } }], videoOffsetTimeMsec: String(i * 1000), }, }), ).join("\n") + "\n"; let n = 0; type Fixture = { channelDir: string; videoDir: string; mediaDir: string; tiered: boolean; plainMs: number; bytesMs: number }; // A video with its raw chat — a real file, or a tier link into media// — // with sub-millisecond times (as ext4 keeps them). async function fixture(tiered: boolean, opts: { mediaAway?: boolean } = {}): Promise { const slug = `ch${++n}`; const channelDir = path.join(ROOT, "channels", slug); const id = "vid00000001"; const videoDir = path.join(channelDir, "data", id); const mediaRoot = path.join(ROOT, "drive", slug, "media"); const mediaDir = path.join(mediaRoot, id); await mkdir(videoDir, { recursive: true }); await writeFile(path.join(channelDir, "config.json"), JSON.stringify({ handling: "youtube" })); await writeFile(path.join(videoDir, "metadata.info.json"), JSON.stringify({ id })); if (tiered) { await mkdir(mediaDir, { recursive: true }); await symlink(mediaRoot, path.join(channelDir, "media")); await writeFile(path.join(mediaDir, CHAT), ORIGINAL); await utimes(path.join(mediaDir, CHAT), 1763700000.111111, 1763700000.222223); await symlink(path.join("..", "..", "media", id, CHAT), path.join(videoDir, CHAT)); const { lutimes } = await import("node:fs/promises"); await lutimes(path.join(videoDir, CHAT), 1763700005.5, 1763700005.123457); } else { await writeFile(path.join(videoDir, CHAT), ORIGINAL); await utimes(path.join(videoDir, CHAT), 1763700000.111111, 1763700000.987653); } const plainMs = (await lstat(path.join(videoDir, CHAT))).mtimeMs; const bytesMs = (await stat(path.join(videoDir, CHAT))).mtimeMs; return { channelDir, videoDir, mediaDir, tiered, plainMs, bytesMs }; } const killAt = (point: string) => (p: string) => { if (p === point) throw new CompressKill(p as never); }; // A READER GETS ONE WHOLE COPY: the read path answers the original, the // logical listing has the chat, and a stored form that is there decodes whole. async function assertWhole(f: Fixture, why: string): Promise { assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: the read path`); assert.ok((await readdirLogical(f.videoDir)).includes(CHAT), `${why}: listed`); const z = await lstat(path.join(f.videoDir, ZST)).catch(() => null); if (z) { const v = await verifyStoredText(f.videoDir, CHAT); assert.equal(v.status, "ok", `${why}: a stored form present is whole (${JSON.stringify(v)})`); } } // THE END STATE: the stored form only, the same content, the same times, no // temp anywhere. async function assertFinal(f: Fixture, why: string): Promise { const data = (await readdir(f.videoDir)).sort(); assert.deepEqual(data, ["metadata.info.json", ZST], `${why}: data/`); if (f.tiered) { assert.ok((await lstat(path.join(f.videoDir, ZST))).isSymbolicLink(), `${why}: a tier link`); assert.equal(await readlink(path.join(f.videoDir, ZST)), path.join("..", "..", "media", "vid00000001", ZST)); assert.deepEqual((await readdir(f.mediaDir)).sort(), [ZST], `${why}: media/`); } assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `${why}: content`); assert.equal((await statStoredText(f.videoDir, CHAT, { link: true })).stats.mtimeMs, f.plainMs, `${why}: the lstat key`); assert.equal((await statStoredText(f.videoDir, CHAT)).stats.mtimeMs, f.bytesMs, `${why}: the stat`); assert.ok((await stat(path.join(f.videoDir, ZST))).size < ORIGINAL.length / 4, `${why}: compressed`); } const run = (f: Fixture, extra: Parameters[2] = {}) => compressStoredText(f.videoDir, CHAT, { reserveBytes: 0, ...extra }); for (const tiered of [false, true]) { const how = tiered ? "tiered" : "real"; test(`${how}: compressed, then idempotent`, async () => { const f = await fixture(tiered); const out = await run(f); assert.equal(out.status, "compressed", JSON.stringify(out)); assert.ok(out.status === "compressed" && out.before === ORIGINAL.length && out.tiered === tiered); await assertFinal(f, "first run"); assert.equal((await run(f)).status, "already"); await assertFinal(f, "second run"); }); // A real file has no tier link to place. for (const point of KILL_POINTS.filter((p) => tiered || p !== "linked")) { test(`${how}: killed at "${point}" — one whole copy remains, a partial never counts, the next run finishes`, async () => { const f = await fixture(tiered); let partial = 0; await assert.rejects(run(f, { pid: DEAD, crashAt: killAt(point) }), CompressKill); await assertWhole(f, `after the kill at ${point}`); if (point === "compressing" || point === "written" || point === "verified") { // The temp is the only stored bytes, and no reader sees it. const work = tiered ? f.mediaDir : f.videoDir; const temps = (await readdir(work)).filter((e) => e.includes(".compressing-")); assert.equal(temps.length, 1, `${point}: the temp is there`); assert.equal(await lstat(path.join(work, ZST)).catch(() => null), null, `${point}: no stored file`); partial = (await stat(path.join(work, temps[0]))).size; } const out = await run(f); assert.equal(out.status, "compressed", `${point}: ${JSON.stringify(out)}`); await assertFinal(f, `the run after ${point}`); if (point === "compressing") { assert.ok(partial < (await stat(path.join(f.videoDir, ZST))).size, "the temp the kill left was partial"); } }); } test(`${how}: both forms with DIFFERENT content are refused, and nothing is touched`, async () => { const f = await fixture(tiered); await run(f); // A newer plain file beside the stored one (a re-fetch). await writeFile(path.join(f.videoDir, CHAT), "NEWER\n"); const before = await tree(f.channelDir); const out = await run(f); assert.deepEqual(out.status === "skipped" && out.reason, "both-differ", JSON.stringify(out)); // 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"); }); test(`${how}: a writer that replaces the file mid-run wins — "changed", the new file read, the earlier content's stored copy KEPT`, async () => { // The seam is synchronous: the new file lands by rename, as yt-dlp's do, // between the stored form landing and the original being set aside. const g = await fixture(tiered); const { writeFileSync, renameSync } = await import("node:fs"); const r = await run(g, { crashAt: (p) => { if (p !== "placed") return; writeFileSync(path.join(g.videoDir, ".new-chat"), "REWRITTEN\n"); renameSync(path.join(g.videoDir, ".new-chat"), path.join(g.videoDir, CHAT)); }, }); assert.equal(r.status, "changed", JSON.stringify(r)); assert.equal(await readFile(path.join(g.videoDir, CHAT), "utf8"), "REWRITTEN\n"); assert.equal(await readStoredText(g.videoDir, CHAT, "utf8"), "REWRITTEN\n"); assert.deepEqual((await readdir(g.videoDir)).filter((e) => e.includes(".retire-")), []); // REVIEW-2 R1: two captures with different content are never settled by // deleting one — the stored copy of the earlier content stays, whole. assert.deepEqual((await readdir(g.videoDir)).sort(), ["metadata.info.json", CHAT, ZST]); const zBytes = tiered ? path.join(g.mediaDir, ZST) : path.join(g.videoDir, ZST); const { decodeStoredBytes } = await import("./storedText-server"); assert.equal((await decodeStoredBytes(await readFile(zBytes))).toString("utf8"), ORIGINAL, "the earlier capture, byte-identical"); // And the next run refuses the pair, for a person. const again = await run(g); assert.equal(again.status === "skipped" && again.reason, "both-differ", JSON.stringify(again)); }); test(`${how}: skipped, touching nothing — a .part, a recording, a move, a job, a recent write, a full disk`, async () => { const cases: [string, (f: Fixture) => Promise[2]>][] = [ ["partial", async (f) => (await writeFile(path.join(f.videoDir, `${CHAT}.part`), "x"), {})], ["recording", async (f) => (await writeFile(path.join(f.videoDir, "live-recording.json"), JSON.stringify({ status: "recording" })), {})], ["relocating", async (f) => (await writeFile(path.join(f.channelDir, ".relocating.json"), "{}"), {})], ["busy", async () => ({ isBusy: () => true })], ["recent", async (f) => ({ quietMs: 600_000, now: () => f.bytesMs + 1000 })], ["low-space", async () => ({ reserveBytes: Number.MAX_SAFE_INTEGER })], ]; for (const [reason, arrange] of cases) { const f = await fixture(tiered); const extra = await arrange(f); const before = await tree(path.dirname(path.dirname(f.channelDir))); const out = await run(f, extra); assert.equal(out.status === "skipped" && out.reason, reason, `${reason}: ${JSON.stringify(out)}`); assert.deepEqual(await tree(path.dirname(path.dirname(f.channelDir))), before, `${reason}: nothing touched`); } }); } for (const tiered of [false, true]) { const how = tiered ? "tiered" : "real"; test(`${how}: a move of the channel's media that begins mid-run keeps the original (the tier hook's rule)`, async () => { const f = await fixture(tiered); const { writeFileSync } = await import("node:fs"); const out = await run(f, { crashAt: (p) => { if (p === "placed") writeFileSync(path.join(f.channelDir, ".relocating.json"), "{}"); }, }); assert.equal(out.status === "skipped" && out.reason, "relocating", JSON.stringify(out)); assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, "the original is untouched"); await assertWhole(f, "mid-move"); await rm(path.join(f.channelDir, ".relocating.json")); assert.equal((await run(f)).status, "compressed"); await assertFinal(f, "after the move"); }); test(`${how}: a newer file written just after the original was set aside is kept, and read`, async () => { const f = await fixture(tiered); const { writeFileSync } = await import("node:fs"); const out = await run(f, { crashAt: (p) => { if (p === "retired") writeFileSync(path.join(f.videoDir, CHAT), "NEWEST\n"); }, }); assert.equal(out.status, "changed", JSON.stringify(out)); assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), "NEWEST\n", "the newer file is the truth"); assert.deepEqual((await readdir(f.videoDir)).filter((e) => e.includes(".retire-")), []); // Both captures kept (REVIEW-2 R1): the newer file, and the earlier // content's stored copy, whole. assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT, ZST]); assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "differs"); const again = await run(f); assert.equal(again.status === "skipped" && again.reason, "both-differ", "refused, both kept"); }); test(`${how}: the stored form replaced by another process before the original goes — the original stays (REVIEW-2 R3)`, async () => { const f = await fixture(tiered); const { writeFileSync, renameSync } = await import("node:fs"); const zBytes = tiered ? path.join(f.mediaDir, ZST) : path.join(f.videoDir, ZST); const out = await run(f, { crashAt: (p) => { // After the stored form is verified and in place: someone else's run // swaps a different file in under its name. if (p !== (tiered ? "linked" : "placed")) return; writeFileSync(zBytes + ".other", "not the verified frame"); renameSync(zBytes + ".other", zBytes); }, }); assert.equal(out.status, "changed", JSON.stringify(out)); assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL, "the original is untouched"); }); test(`${how}: the tier hook's own temp link is not taken for a dead run's leftover (REVIEW-2 N2)`, async () => { const f = await fixture(tiered); const hookTemp = path.join(f.videoDir, `.${CHAT}.tierlink-${process.pid}`); await writeFile(hookTemp, "the hook's"); assert.equal((await run(f)).status, "compressed"); assert.equal(await readFile(hookTemp, "utf8"), "the hook's"); await rm(hookTemp); }); } test("an unmounted media drive: skipped as unreachable, and nothing is created on the root filesystem", async () => { const f = await fixture(true); const drive = path.join(ROOT, "drive", path.basename(f.channelDir)); await rename(drive, `${drive}-unmounted`); try { const out = await run(f); assert.equal(out.status === "skipped" && out.reason, "unreachable", JSON.stringify(out)); assert.equal(await lstat(drive).catch(() => null), null, "the mountpoint is not rebuilt"); assert.deepEqual((await readdir(f.videoDir)).sort(), ["metadata.info.json", CHAT]); } finally { await rename(`${drive}-unmounted`, drive); } assert.equal((await run(f)).status, "compressed"); }); test("killed INSIDE the original's removal (its bytes gone, its link not): readers get the stored form; the next run removes the link", async () => { const f = await fixture(true); await run(f); // What `removeMediaFile` leaves when killed between its two steps. await symlink(path.join("..", "..", "media", "vid00000001", CHAT), path.join(f.videoDir, CHAT)); assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL); const out = await run(f); assert.equal(out.status, "already", JSON.stringify(out)); await assertFinal(f, "after the dangling link"); }); test("a dangling plain link with NO stored form is left alone (the bytes may be on a drive)", async () => { const f = await fixture(true); await rm(path.join(f.mediaDir, CHAT)); const out = await run(f); assert.equal(out.status === "skipped" && out.reason, "dangling"); assert.ok((await lstat(path.join(f.videoDir, CHAT))).isSymbolicLink()); }); test("a corrupt stored form beside the plain file is refused; a truncated one never reads as the file", async () => { const f = await fixture(false); const good = await encodeStoredBytes(Buffer.from(ORIGINAL)); await writeFile(path.join(f.videoDir, ZST), good.subarray(0, Math.floor(good.length / 2))); // The plain file is the truth while it is there. assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL); const out = await run(f); assert.equal(out.status === "skipped" && out.reason, "stored-corrupt", JSON.stringify(out)); assert.ok((await lstat(path.join(f.videoDir, CHAT))).isFile(), "the original stays"); assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "corrupt"); }); test("a set-aside original of a dead run that is NOT the stored content is kept for a person", async () => { const f = await fixture(false); await run(f); await writeFile(path.join(f.videoDir, CHAT), "NEWER\n"); await writeFile(path.join(f.videoDir, `.${CHAT}.retire-${DEAD}`), "SOMETHING ELSE\n"); const out = await run(f); assert.equal(out.status === "skipped" && out.reason, "retired-kept", JSON.stringify(out)); assert.equal(await readFile(path.join(f.videoDir, `.${CHAT}.retire-${DEAD}`), "utf8"), "SOMETHING ELSE\n"); }); // REVIEW-1 F4(b): a leftover is dead unless the process that named it runs NOW // — the pid AND its start token. An editor that comes back with the same pid // (a container) finds its own earlier run's set-aside: dead, finished. A live // process of another pid with the same start: alive, nothing touched. A pid // reused by a later process (another start token): dead. for (const tiered of [false, true]) { const how = tiered ? "tiered" : "real"; const { processStartToken } = await import("./storedText-write-server"); const killRetired = (p: string) => { if (p === "retired") throw new CompressKill(p as never); }; test(`${how}: this pid's leftover from an EARLIER process start is dead — the next run finishes`, async () => { for (const token of ["oldstart1", undefined]) { const f = await fixture(tiered); await assert.rejects(run(f, { pid: process.pid, ...(token ? { token } : {}), crashAt: killRetired }), CompressKill); const left = (await readdir(f.videoDir)).filter((e) => e.includes(".retire-")); assert.equal(left.length, 1); assert.match(left[0], new RegExp(`retire-${process.pid}-`)); await assertWhole(f, "after the kill"); const out = await run(f); assert.equal(out.status, "compressed", JSON.stringify(out)); await assertFinal(f, `own pid, ${token ?? "this start"}`); } }); test(`${how}: a leftover of ANOTHER live process (same pid, same start) is left alone; a reused pid's is dead`, async () => { const other = process.ppid; const live = processStartToken(other); assert.ok(live, "the parent's start token is readable"); const f = await fixture(tiered); await assert.rejects(run(f, { pid: other, token: live!, crashAt: killRetired }), CompressKill); const before = await tree(f.channelDir); const out = await run(f); assert.equal(out.status === "skipped" && out.reason, "busy", JSON.stringify(out)); assert.deepEqual(await tree(f.channelDir), before, "nothing touched"); const g = await fixture(tiered); await assert.rejects(run(g, { pid: other, token: "reused0", crashAt: killRetired }), CompressKill); const again = await run(g); assert.equal(again.status, "compressed", JSON.stringify(again)); await assertFinal(g, "a reused pid"); }); } test("the quiet period asks the later of mtime and ctime: a backdated mtime is still recent (REVIEW-1 N4)", async () => { const f = await fixture(false); // The fixture's mtime is days old; its ctime is now (the utimes itself). const out = await run(f, { quietMs: 600_000 }); assert.equal(out.status === "skipped" && out.reason, "recent", JSON.stringify(out)); const later = await run(f, { quietMs: 600_000, now: () => Date.now() + 3_600_000 }); assert.equal(later.status, "compressed"); }); // A KERNEL-WRITTEN mtime has nanoseconds; `utimes` takes a double of seconds. // Measured (Node 22.23.5, ext4): `mtimeMs` round-trips EXACTLY — the number // the index compares (buildIndex: `mtimeMs !==`) — while `mtimeNs` may move by // a few hundred ns. Pinned both ways: the index sees no change; the // nanoseconds are not promised. test("a nanosecond kernel mtime: the stored form's mtimeMs equals the original's exactly (the index key)", async () => { for (const tiered of [false, true]) { const f = await fixture(tiered); const bytes = tiered ? path.join(f.mediaDir, CHAT) : path.join(f.videoDir, CHAT); // Rewrite in place so the kernel stamps the time (no utimes). await writeFile(bytes, ORIGINAL); const name = path.join(f.videoDir, CHAT); const lBefore = await lstat(name, { bigint: true }); const sBefore = await stat(name, { bigint: true }); const msL = (await lstat(name)).mtimeMs; const msS = (await stat(name)).mtimeMs; assert.notEqual(sBefore.mtimeNs % 1_000_000n, 0n, "a sub-millisecond kernel time"); assert.equal((await run(f)).status, "compressed"); assert.equal((await statStoredText(f.videoDir, CHAT, { link: true })).stats.mtimeMs, msL, "lstat mtimeMs"); assert.equal((await statStoredText(f.videoDir, CHAT)).stats.mtimeMs, msS, "stat mtimeMs"); const zs = await stat(path.join(f.videoDir, ZST), { bigint: true }); const drift = zs.mtimeNs - sBefore.mtimeNs; assert.ok(drift > -1000n && drift < 1000n, `mtimeNs within a microsecond (drift ${drift} ns)`); void lBefore; } }); test("a stored file missing its last 1-4 bytes (the checksum) still decodes whole and right: pinned (REVIEW-1 N7)", async () => { const f = await fixture(false); assert.equal((await run(f)).status, "compressed"); const z = path.join(f.videoDir, ZST); const whole = await readFile(z); for (const cut of [1, 4]) { await writeFile(z, whole.subarray(0, whole.length - cut)); // Without its checksum the frame is not checked, but every byte of the // content is there, and the length matches the header: the text is right. assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ORIGINAL, `cut ${cut}`); assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "ok", `cut ${cut}`); } // One byte more and content is missing: never read as the file. await writeFile(z, whole.subarray(0, whole.length - 5 - 100)); await assert.rejects(readStoredText(f.videoDir, CHAT, "utf8")); }); test("a 0-byte chat compresses and reads back as 0 bytes", async () => { const f = await fixture(false); await writeFile(path.join(f.videoDir, CHAT), ""); assert.equal((await run(f)).status, "compressed"); assert.equal(await readStoredText(f.videoDir, CHAT, "utf8"), ""); assert.equal((await verifyStoredText(f.videoDir, CHAT)).status, "ok"); }); test("an abort mid-write and an appending writer: the original is untouched, no temp is left", async () => { const f = await fixture(false); const ac = new AbortController(); await assert.rejects(run(f, { signal: ac.signal, crashAt: (p) => { if (p === "compressing") ac.abort(); } })); assert.equal(await readFile(path.join(f.videoDir, CHAT), "utf8"), ORIGINAL); assert.deepEqual((await readdir(f.videoDir)).sort(), [CHAT, "metadata.info.json"].sort()); const g = await fixture(false); const { appendFileSync } = await import("node:fs"); const out = await run(g, { crashAt: (p) => { if (p === "compressing") appendFileSync(path.join(g.videoDir, CHAT), "MORE\n"); } }); assert.equal(out.status, "changed", JSON.stringify(out)); assert.equal(await readFile(path.join(g.videoDir, CHAT), "utf8"), ORIGINAL + "MORE\n", "the writer's file is kept"); assert.deepEqual((await readdir(g.videoDir)).sort(), [CHAT, "metadata.info.json"].sort(), "no temp, no stored form"); }); test("not a declared name: refused", async () => { const f = await fixture(false); // (A caption track is declared since lane text-compress-captions; the // metadata is not.) const out = await compressStoredText(f.videoDir, "metadata.info.json"); assert.equal(out.status === "skipped" && out.reason, "not-declared"); }); // Every entry under `dir`: its kind, size, times and content hash (a link: // its target and its own times) — what "nothing was touched" compares. async function tree(dir: string): Promise { const out: string[] = []; async function walk(d: string): Promise { for (const e of (await readdir(d).catch(() => [] as string[])).sort()) { const p = path.join(d, e); const l = await lstat(p); const rel = path.relative(ROOT, p); if (l.isSymbolicLink()) out.push(`${rel} -> ${await readlink(p)} ${l.mtimeMs}`); else if (l.isDirectory()) { out.push(`${rel}/`); await walk(p); } else { const h = createHash("sha256").update(await readFile(p)).digest("hex"); out.push(`${rel} ${l.size} ${l.mtimeMs} ${h}`); } } } await walk(dir); return out; }