Archilyzer · Source

archilyzer

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

commit bac70970c5ddf868d9b8c7c02524a07d7d31174d
parent ba5ae2347fc02867852ddc27aa079bd6b16db7f5
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date:   Tue, 29 Sep 2026 21:21:33 -0400

Merge r15/index-hold (release 15 slice IG) — the index build holds a channel whose media cannot be read instead of emptying it: not rescanned, its records and shared pages kept, its availability states carried; a full rebuild with one held refuses unless ARCHILYZER_INDEX_ALLOW_HELD=1; heldChannels in the result and the log; the hold's words shared with the stats build; reviewed SHIP

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

Diffstat:
MENVIRONMENT.md | 1+
Acommon/controller/buildIndex.test.ts | 645+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/controller/buildIndex.ts | 235+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mcommon/controller/buildStats.ts | 34+++++++++-------------------------
Acommon/lib/channelMediaHold.ts | 61+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mcommon/lib/envVars.ts | 1+
Meditor/CHANGELOG.md | 1+
Mplans/FACTS.md | 79+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++------
Mplans/STATE.md | 14+++++++-------
Aplans/release-15.md | 219+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Mplans/stats-cache-key.md | 2++
11 files changed, 1238 insertions(+), 54 deletions(-)

diff --git a/ENVIRONMENT.md b/ENVIRONMENT.md @@ -76,6 +76,7 @@ Tokens, credentials and knobs a running process reads. Most configuration is not | `AUDIO_CHECK_RESUME_DURING_PROBE` | the channel's `audioCheck.resumeDuringProbe` | `1` or `true` resumes yt-dlp during the audio check's probe, anything else holds it, for a one-off comparison run; unset = the channel's setting. | common/ytdlp/audioCheckedDownload.ts | | `AUDIO_CHECK_BACKOFF_FACTOR` | the built-in factor | The audio check's interval backoff factor, in (0, 1], for a one-off run. | common/ytdlp/audioCheckedDownload.ts | | `ARCHILYZER_STATS_ALLOW_DOWNGRADE` | off | `1` lets a stats build clear a stats cache that a NEWER build wrote, for a deliberate rollback. Unset, such a build refuses and names both versions. | common/controller/buildStats.ts | +| `ARCHILYZER_INDEX_ALLOW_HELD` | off | `1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel. | common/controller/buildIndex.ts | | `MCP_IO_STATS` | off | `1` turns on per-call I/O accounting, for `mcp/bench`. | common/lib/archive/io-stats.ts | | `ARCHILYZER_EDITOR_URL` | `http://localhost:3001` | Which editor `pnpm ops` and the MCP's `fetch_clip` talk to. | scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, umtool | | `ARCHILYZER_AGENT` | `cli` | Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`. | scripts/archilyzer-ops.mjs | diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts @@ -0,0 +1,645 @@ +// Integration: the index build's HOLD, through the REAL buildIndex, over a temp +// corpus. +// +// A channel's `data/` may be an absolute symlink to another drive (AGENTS.md, +// "A channel's `data/` may live on another drive"). With that drive unmounted +// the link dangles, and the index build used to read the channel as having no +// videos: it removed every record the channel had, and the site built next +// published the channel as gone. These cases pin the hold that replaced it: +// the channel is not rescanned, and its records and shared pages are kept as +// they are; a FULL rebuild with a channel held refuses unless +// ARCHILYZER_INDEX_ALLOW_HELD is set; and all of it undoes itself when the +// drive is back. The stats build's twin is buildStats.test.ts case (i). +// +// Run with: node_modules/.bin/tsx --test common/controller/buildIndex.test.ts + +import { after, test } from "node:test"; +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { createRequire, syncBuiltinESMExports } from "node:module"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + renameSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// EVERY PATH getPaths() CAN RESOLVE TO A PLACE THIS FILE'S CODE MAY WRITE IS +// PINNED UNDER ROOT before anything calls it (the buildStats.test.ts list). The +// last case proves no write this file caused landed outside ROOT. +const ROOT = mkdtempSync(path.join(tmpdir(), "build-index-")); +const PINNED: Record<string, string> = { + TRANSCRIPTS_DIR: path.join(ROOT, "transcripts"), + SAVED_VIDEOS_DIR: path.join(ROOT, "saved-videos"), + SITES_DIR: path.join(ROOT, "transcripts", "sites"), + SETTINGS_FILE: path.join(ROOT, "settings.json"), + EXPORT_PUBLIC_DIR: path.join(ROOT, "public"), + EXPORT_INDEX_DIR: path.join(ROOT, ".export-index"), + EXPORT_BUILDS_DIR: path.join(ROOT, ".export-builds"), + EDITOR_CHANGELOG_FILE: path.join(ROOT, "editor-CHANGELOG.md"), + EXPORT_CHANGELOG_FILE: path.join(ROOT, "export-CHANGELOG.md"), + CHARTS_CONFIG_FILE: path.join(ROOT, "chart-templates.json"), + SEARCH_ALIASES_FILE: path.join(ROOT, "transcripts", "search-aliases.json"), + CURATED_TAGS_FILE: path.join(ROOT, "transcripts", "tags.json"), + ARCHILYZER_CONFIG_DIR: path.join(ROOT, "config"), + ARCHILYZER_SOURCE_SCRATCH: path.join(ROOT, "source-scratch"), +}; +Object.assign(process.env, PINNED); +delete process.env.ARCHILYZER_INDEX_ALLOW_HELD; +after(() => rmSync(ROOT, { recursive: true, force: true })); + +const { getPaths } = await import("../lib/paths"); +const { buildIndex, INDEX_ALLOW_HELD_ENV } = await import("./buildIndex"); +const { writeGlobalTags } = await import("../lib/curatedTagsStore"); +const { META_PAGES_PENDING } = await import("./curatedTagsIndex"); +const { open } = await import("lmdb"); + +const paths = getPaths(); +const CHANNEL = "test-channel"; +const DRIVE_CHANNEL = "drive-channel"; +const SITE = "testsite"; +const MEDIA = path.join(ROOT, "media"); +const AWAY = `${MEDIA}-away`; +const COMMON = fileURLToPath(new URL("..", import.meta.url)); + +// ── a write spy over the whole file ───────────────────────────────────────── +// The buildStats.test.ts spy, writes only: node:fs and node:fs/promises, async, +// sync and callback, synced into the named ESM imports the code under test +// holds. The last case reads it. +const writes: string[] = []; +let afterStat: ((p: string) => void) | null = null; +{ + const req = createRequire(import.meta.url); + const fsCjs = req("node:fs") as Record<string, unknown>; + const fspCjs = req("node:fs/promises") as Record<string, unknown>; + const WRITES = ["writeFile", "appendFile", "rename", "mkdir", "rm", "rmdir", "unlink", "copyFile", "cp", "symlink", "link", "utimes", "truncate", "mkdtemp", "chmod"]; + const TWO_PATHS = new Set(["rename", "copyFile", "cp", "symlink", "link"]); + const opensForWrite = (flags: unknown) => + (typeof flags === "string" && /[wa+]/.test(flags)) || + (typeof flags === "number" && (flags & 3) !== 0); + const asPath = (v: unknown) => + typeof v === "string" ? v : v instanceof URL ? fileURLToPath(v) : Buffer.isBuffer(v) ? v.toString() : null; + const wrap = (mod: Record<string, unknown>, name: string, mode: "write" | "open") => { + const fn = mod[name]; + if (typeof fn !== "function") return; + mod[name] = function (this: unknown, ...args: unknown[]) { + if (mode === "write" || opensForWrite(args[1])) { + const ps = TWO_PATHS.has(name.replace(/Sync$/, "")) ? [args[0], args[1]] : [args[0]]; + for (const a of ps) { + const p = asPath(a); + if (p !== null) writes.push(path.resolve(p)); + } + } + return (fn as (...a: unknown[]) => unknown).apply(this, args); + }; + }; + for (const n of WRITES) { + wrap(fspCjs, n, "write"); + wrap(fsCjs, n, "write"); + wrap(fsCjs, `${n}Sync`, "write"); + } + wrap(fspCjs, "open", "open"); + wrap(fsCjs, "open", "open"); + wrap(fsCjs, "openSync", "open"); + wrap(fsCjs, "createWriteStream", "write"); + // Case (i)'s hook: the drive is lost DURING the scan's walk. node:fs/promises + // `stat` calls `afterStat` with each path it has just answered for. + const stat = fspCjs.stat as (...a: unknown[]) => Promise<unknown>; + fspCjs.stat = async function (this: unknown, ...args: unknown[]) { + const result = await stat.apply(this, args); + const p = asPath(args[0]); + if (p !== null) afterStat?.(path.resolve(p)); + return result; + }; + syncBuiltinESMExports(); +} + +// ── the corpus ────────────────────────────────────────────────────────────── +const writeJson = (file: string, value: unknown) => { + mkdirSync(path.dirname(file), { recursive: true }); + writeFileSync(file, JSON.stringify(value, null, 2)); +}; +const videoDir = (id: string, channel = CHANNEL) => + path.join(paths.channelsDir, channel, "data", id); + +// YouTube's rolling-caption shape: parseVtt keeps only lines carrying inline +// timing tags, so a plain cue would parse to nothing. +const 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"; + +// Metadata and English captions; `subs` adds a German track, which the index +// publishes in the shared subs tree. +function seedVideo( + id: string, + channel = CHANNEL, + opts: { title?: string; subs?: boolean; dir?: string } = {}, +): void { + const dir = opts.dir ?? videoDir(id, channel); + writeJson(path.join(dir, "metadata.info.json"), { + id, + title: opts.title ?? `Video ${id}`, + channel: channel, + upload_date: "20260601", + duration: 120, + description: "fixture", + webpage_url: `https://www.youtube.com/watch?v=${id}`, + extractor_key: "Youtube", + }); + writeFileSync(path.join(dir, "transcript.en.vtt"), VTT); + if (opts.subs) writeFileSync(path.join(dir, "transcript.de.vtt"), VTT); +} + +function writeChannel(slug: string, extra: Record<string, unknown> = {}): void { + writeJson(path.join(paths.channelsDir, slug, "config.json"), { + handling: "youtube", + name: slug, + url: `https://www.youtube.com/@${slug}/videos`, + ...extra, + }); +} + +// A fresh corpus, LMDB and export tree per test, so every count is exact. The +// drive is a storage location, as /storage records it: a held channel is named +// by its label, never by a path. +function resetCorpus(channels: string[] = [CHANNEL, DRIVE_CHANNEL]): void { + for (const p of [paths.transcriptsDir, PINNED.EXPORT_INDEX_DIR, MEDIA, AWAY]) { + rmSync(p, { recursive: true, force: true }); + } + mkdirSync(paths.transcriptsDir, { recursive: true }); + writeFileSync( + paths.settingsFile, + JSON.stringify({ + storage: { locations: [{ id: "usb", label: "USB drive", root: MEDIA, autoRepoint: false }] }, + }), + ); + writeChannel(CHANNEL); + writeJson(path.join(paths.sitesDir, SITE, "site.json"), { + siteId: SITE, + siteTitle: "Test Site", + siteDescription: "fixture", + headerTitle: "Test Site", + homeTagline: "", + socialLinks: [], + groups: [{ id: "default", name: "All channels", selectedByDefault: true }], + defaultGroupId: "default", + channels: channels.map((slug) => ({ slug, groupId: "default" })), + }); +} + +// A channel whose data/ is a relocated symlink, the way the editor's Storage +// panel leaves it: channels/<slug>/data -> <MEDIA>/<slug>/data, with +// config.dataDir recording the target. d1 carries a subtitle track. +function seedDriveChannel(titles: Record<string, string> = {}): void { + const target = path.join(MEDIA, DRIVE_CHANNEL, "data"); + mkdirSync(target, { recursive: true }); + writeChannel(DRIVE_CHANNEL, { dataDir: target }); + symlinkSync(target, path.join(paths.channelsDir, DRIVE_CHANNEL, "data")); + seedVideo("d1", DRIVE_CHANNEL, { subs: true, title: titles.d1 }); + seedVideo("d2", DRIVE_CHANNEL, { title: titles.d2 }); +} + +// Unmount: the link now dangles, exactly as an absent USB drive leaves it. +const unmount = () => renameSync(MEDIA, AWAY); +const remount = () => renameSync(AWAY, MEDIA); + +async function runIndex(log: string[] = []) { + const res = await buildIndex({ paths, onLog: (s) => log.push(s) }); + return { res, log }; +} + +// ── reading what the build left ───────────────────────────────────────────── +// The index LMDB, opened the way buildIndex opens it, and closed again. +function withIndex<T>(fn: (db: (name: string) => ReturnType<ReturnType<typeof open>["openDB"]>) => T): T { + const root = open({ path: paths.lmdbPath, maxDbs: 18, compression: true }); + try { + return fn((name) => root.openDB({ name, encoding: "msgpack" })); + } finally { + root.close(); + } +} +// Every indexed video, as "<channel>/<dir>". +const indexed = () => + withIndex((db) => + [...db("mtimes").getKeys()].map((k) => (k as unknown as string[]).join("/")).sort(), + ); +const summaryCount = () => withIndex((db) => [...db("sums").getKeys()].length); +const storedSchema = () => withIndex((db) => db("meta").get("schema") as number); +const setStoredSchema = (v: number) => withIndex((db) => db("meta").putSync("schema", v)); +const pagesPending = () => withIndex((db) => db("meta").get(META_PAGES_PENDING)); + +// A directory tree as {relative path: contents}, or null when it is not there. +function tree(dir: string): Record<string, string> | null { + if (!existsSync(dir)) return null; + const out: Record<string, string> = {}; + const walk = (d: string) => { + for (const e of readdirSync(d, { withFileTypes: true })) { + const p = path.join(d, e.name); + if (e.isDirectory()) walk(p); + else out[path.relative(dir, p)] = readFileSync(p, "utf8"); + } + }; + walk(dir); + return out; +} +const sharedTranscripts = (slug = DRIVE_CHANNEL) => + tree(path.join(paths.exportSharedTranscriptsDir, slug)); +const sharedSubs = (slug = DRIVE_CHANNEL) => tree(path.join(paths.exportSharedSubsDir, slug)); + +type Published = { id: string; channelSlug?: string; state?: string; curatedTags?: string[] }; +const siteDir = () => path.join(paths.exportSitesIndexDir, SITE); +const summaries = (): Published[] => + JSON.parse(readFileSync(path.join(siteDir(), "summaries", "page-0000.json"), "utf8")); +const siteManifest = () => + JSON.parse(readFileSync(path.join(siteDir(), "summaries", "manifest.json"), "utf8")) as { + channels: { slug: string; count: number }[]; + }; +const siteSubsManifest = () => + JSON.parse(readFileSync(path.join(siteDir(), "subs", "manifest.json"), "utf8")) as { + channels: { slug: string; videoCount: number }[]; + }; +const stateOf = (id: string) => { + const r = summaries().find((s) => s.id === id); + assert.ok(r, `${id} is published`); + return r.state ?? "available"; +}; +const transcriptRecord = (id: string, slug = DRIVE_CHANNEL): Published => { + const page = JSON.parse( + readFileSync(path.join(paths.exportSharedTranscriptsDir, slug, "page-0000.json"), "utf8"), + ) as Published[]; + const r = page.find((s) => s.id === id); + assert.ok(r, `${id} is on its channel's transcript page`); + return r; +}; + +const DRIVE_VIDEOS = [`${DRIVE_CHANNEL}/d1`, `${DRIVE_CHANNEL}/d2`]; + +// ── the cases ─────────────────────────────────────────────────────────────── + +test("(a) an unmounted drive: the channel's records, transcript pages and subs survive an incremental build", async () => { + resetCorpus(); + seedVideo("local"); + seedDriveChannel(); + const mounted = await runIndex(); + assert.deepEqual(mounted.res.heldChannels, []); + assert.deepEqual(indexed(), [...DRIVE_VIDEOS, `${CHANNEL}/local`]); + const pagesBefore = sharedTranscripts(); + const subsBefore = sharedSubs(); + assert.ok(pagesBefore?.["manifest.json"] && pagesBefore["page-0000.json"], "the drive's transcript pages"); + assert.ok(subsBefore?.["manifest.json"], "the drive's subs pages"); + + unmount(); + // Something else changed too, so the build rewrites the shared trees and + // the site: the hold has to survive a real build, not a no-op one. + seedVideo("local2"); + const { res, log } = await runIndex(); + + assert.deepEqual(res.heldChannels, [DRIVE_CHANNEL]); + assert.equal(res.added, 1); + assert.equal(res.removed, 0, "not read as a channel with no videos"); + assert.deepEqual(indexed(), [...DRIVE_VIDEOS, `${CHANNEL}/local`, `${CHANNEL}/local2`]); + assert.equal(summaryCount(), 4); + // Byte-identical, manifest included: its generatedAt shows no rewrite. + assert.deepEqual(sharedTranscripts(), pagesBefore); + assert.deepEqual(sharedSubs(), subsBefore); + // The site built from this index still publishes the channel. + for (const id of ["d1", "d2", "local", "local2"]) { + assert.ok(summaries().some((s) => s.id === id), `${id} still published`); + } + assert.equal(siteManifest().channels.find((c) => c.slug === DRIVE_CHANNEL)?.count, 2); + assert.equal(siteSubsManifest().channels.find((c) => c.slug === DRIVE_CHANNEL)?.videoCount, 1); + + // Said, with the location's label and no path. + const line = log.find((l) => l.startsWith(`Channel ${DRIVE_CHANNEL}:`)); + assert.ok(line, log.join("\n")); + assert.match( + line, + /its media is not reachable \(drive not mounted\?\), on location "USB drive"; its 2 indexed video\(s\) are kept as they are, not rescanned/, + ); + assert.ok(!line.includes(ROOT), line); + assert.ok( + log.some((l) => l.startsWith("Diff: +1 added, ~0 changed, -0 removed, 2 total. Held: 1 channel(s), 2 video(s) kept.")), + log.join("\n"), + ); + assert.ok( + log.some((l) => l.startsWith("Done in") && l.endsWith(`Held, their media not readable: ${DRIVE_CHANNEL}.`)), + log.join("\n"), + ); +}); + +test("(b) a held channel's availability states are carried over, not re-read from the missing drive", async () => { + resetCorpus(); + seedVideo("local"); + seedDriveChannel(); + // Both drive videos fell out of the channel's listing. d2 was confirmed + // public after that scan (available); d1 never was (maybe missing). + writeJson(path.join(paths.channelsDir, DRIVE_CHANNEL, "maybe-missing.json"), { + checkedAt: "2026-08-01T12:00:00.000Z", + freshPlaylistCount: 0, + ids: ["d1", "d2"], + }); + writeJson(path.join(videoDir("d2", DRIVE_CHANNEL), "availability.json"), { + checkedAt: "2026-08-02T00:00:00.000Z", + availability: "public", + }); + await runIndex(); + assert.deepEqual([stateOf("d1"), stateOf("d2")], ["maybe_missing", "available"]); + + unmount(); + seedVideo("local2"); // so the site is rebuilt + const { res } = await runIndex(); + assert.deepEqual(res.heldChannels, [DRIVE_CHANNEL]); + // Re-read from the missing drive, d2's confirmation would be gone and both + // would say "maybe missing"; skipped without the carry, d1's would vanish. + assert.deepEqual([stateOf("d1"), stateOf("d2")], ["maybe_missing", "available"]); + const videoState = withIndex((db) => + Object.fromEntries([...db("videoState").getRange()].map(({ key, value }) => [String(key).replace("\x00", "/"), value])), + ); + assert.deepEqual(videoState, { [`${DRIVE_CHANNEL}/d1`]: "maybe_missing" }); +}); + +test("(c) a full rebuild with a channel held refuses without the override, and holds with it", async () => { + resetCorpus(); + seedVideo("local"); + seedDriveChannel(); + await runIndex(); + const current = storedSchema(); + const pagesBefore = sharedTranscripts(); + const subsBefore = sharedSubs(); + + unmount(); + setStoredSchema(current - 1); + await assert.rejects(runIndex(), (err: Error) => { + assert.match( + err.message, + new RegExp( + `must be rebuilt in full \\(index schema ${current - 1} -> ${current}\\), but 1 channel\\(s\\) cannot be read: ` + + `drive-channel \\(its media is not reachable \\(drive not mounted\\?\\), on location "USB drive"\\)`, + ), + ); + // Why, the ways out (mounting first), and the override by name; no path. + assert.match(err.message, /the next site build would publish them as gone/); + assert.match( + err.message, + /For each: mount its media and run this again; or repair or re-point its location on \/storage; or finish or clear its move .*; or, if it is gone for good, delete the channel or set excludeFromBuild/, + ); + // The override by name, and where it is set for each way a build runs. + assert.match( + err.message, + new RegExp( + `set ${INDEX_ALLOW_HELD_ENV}=1 in the environment of the process that runs the build: ` + + `for the command line, the command's own \\(\`${INDEX_ALLOW_HELD_ENV}=1 pnpm archilyzer index\`\\); ` + + `for the editor's Build index job, or a site build started from the editor, the editor's own environment, which takes a restart of the editor\\.$`, + ), + ); + assert.ok(!err.message.includes(ROOT), err.message); + return true; + }); + // Refused before the clear: nothing touched. + assert.equal(storedSchema(), current - 1); + assert.deepEqual(indexed(), [...DRIVE_VIDEOS, `${CHANNEL}/local`]); + assert.deepEqual(sharedTranscripts(), pagesBefore); + + // The CLI (the export's build:index, a site build's data phase) exits + // non-zero on it, and leaves the index as it was. + const cli = spawnSync( + path.join(COMMON, "node_modules", ".bin", "tsx"), + ["bin/archilyzer.ts", "index"], + { cwd: COMMON, env: { ...process.env }, encoding: "utf8" }, + ); + assert.notEqual(cli.status, 0, cli.stdout + cli.stderr); + assert.match(cli.stderr, /must be rebuilt in full/); + assert.equal(storedSchema(), current - 1); + assert.deepEqual(indexed(), [...DRIVE_VIDEOS, `${CHANNEL}/local`]); + + // Overridden: the rebuild runs, the held channel's records go with the + // clear (they cannot be re-read), and its pages are left as they are. + process.env[INDEX_ALLOW_HELD_ENV] = "1"; + try { + const { res, log } = await runIndex(); + assert.deepEqual(res.heldChannels, [DRIVE_CHANNEL]); + assert.equal(storedSchema(), current); + assert.deepEqual(indexed(), [`${CHANNEL}/local`]); + assert.deepEqual(sharedTranscripts(), pagesBefore); + assert.deepEqual(sharedSubs(), subsBefore); + assert.ok( + log.some( + (l) => + l.startsWith(`Channel ${DRIVE_CHANNEL}: its media is not reachable`) && + l.includes(`held under ${INDEX_ALLOW_HELD_ENV}: this full rebuild cleared its index records`), + ), + log.join("\n"), + ); + } finally { + delete process.env[INDEX_ALLOW_HELD_ENV]; + } + + // The drive back: an ordinary build takes the channel in again. + remount(); + const back = await runIndex(); + assert.deepEqual(back.res.heldChannels, []); + assert.equal(back.res.added, 2); + assert.deepEqual(indexed(), [...DRIVE_VIDEOS, `${CHANNEL}/local`]); + assert.equal(siteManifest().channels.find((c) => c.slug === DRIVE_CHANNEL)?.count, 2); +}); + +test("(d) a first build, with no index yet, is a full rebuild: it refuses with a channel held too", async () => { + resetCorpus(); + seedVideo("local"); + seedDriveChannel(); + unmount(); + await assert.rejects(runIndex(), /index schema <none> -> \d+\), but 1 channel\(s\) cannot be read: drive-channel/); + remount(); + const { res } = await runIndex(); + assert.deepEqual(res.heldChannels, []); + assert.deepEqual(indexed(), [...DRIVE_VIDEOS, `${CHANNEL}/local`]); +}); + +test("(e) the drive back: the held set is empty and what arrived meanwhile is indexed", async () => { + resetCorpus(); + seedVideo("local"); + seedDriveChannel(); + await runIndex(); + unmount(); + const away = await runIndex(); + assert.deepEqual(away.res.heldChannels, [DRIVE_CHANNEL]); + assert.equal(away.res.removed, 0); + + // Downloaded onto the drive while it was elsewhere. + seedVideo("d3", DRIVE_CHANNEL, { dir: path.join(AWAY, DRIVE_CHANNEL, "data", "d3") }); + remount(); + const { res, log } = await runIndex(); + assert.deepEqual(res.heldChannels, []); + assert.equal(res.added, 1); + assert.equal(res.changed, 0, "the kept records match the disk"); + assert.equal(res.removed, 0); + assert.deepEqual(indexed(), [...DRIVE_VIDEOS, `${DRIVE_CHANNEL}/d3`, `${CHANNEL}/local`]); + assert.deepEqual(Object.keys(JSON.parse(sharedTranscripts()!["manifest.json"]).slugToPage).sort(), ["d1", "d2", "d3"]); + assert.ok(!log.some((l) => l.includes("Held")), log.join("\n")); +}); + +test("(f) a channel that is really empty is still emptied, not held", async () => { + resetCorpus(["emptied", "gone", CHANNEL]); + for (const slug of ["emptied", "gone"]) { + writeChannel(slug); + seedVideo("x1", slug); + seedVideo("x2", slug); + } + seedVideo("local"); + await runIndex(); + assert.equal(indexed().length, 5); + + // Its media deleted: an empty data/ in place, and no data/ at all. Neither + // was relocated, so there is no drive to be missing. + for (const id of ["x1", "x2"]) rmSync(videoDir(id, "emptied"), { recursive: true }); + rmSync(path.join(paths.channelsDir, "gone", "data"), { recursive: true }); + const { res, log } = await runIndex(); + assert.deepEqual(res.heldChannels, []); + assert.equal(res.removed, 4); + assert.deepEqual(indexed(), [`${CHANNEL}/local`]); + assert.deepEqual(JSON.parse(sharedTranscripts("emptied")!["manifest.json"]).slugToPage, {}); + // The missing directory is said, not swallowed. + assert.ok( + log.includes("Channel gone: no data/ directory; indexed as a channel with no videos."), + log.join("\n"), + ); +}); + +test("(g) a data directory that cannot be read holds its channel, and says why", async () => { + if (process.getuid?.() === 0) return; // root reads through a mode of 000 + resetCorpus(["locked", "flaky", CHANNEL]); + for (const slug of ["locked", "flaky"]) { + writeChannel(slug); + seedVideo("x1", slug); + seedVideo("x2", slug); + } + await runIndex(); + assert.equal(indexed().length, 4); + + // The whole data/ unreadable; and one video dir unreadable mid-walk. + const locked = path.join(paths.channelsDir, "locked", "data"); + const flaky = videoDir("x2", "flaky"); + chmodSync(locked, 0o000); + chmodSync(flaky, 0o000); + try { + const { res, log } = await runIndex(); + assert.deepEqual([...res.heldChannels].sort(), ["flaky", "locked"]); + assert.equal(res.removed, 0); + assert.equal(indexed().length, 4); + assert.ok( + log.some((l) => l.startsWith("Channel locked: its data directory could not be read (EACCES)")), + log.join("\n"), + ); + assert.ok( + // One video's directory, said apart from the whole data/ above. + log.some((l) => l.startsWith("Channel flaky: a video in its data directory could not be read (EACCES)")), + log.join("\n"), + ); + } finally { + chmodSync(locked, 0o755); + chmodSync(flaky, 0o755); + } + const { res } = await runIndex(); + assert.deepEqual(res.heldChannels, []); + assert.equal(indexed().length, 4); +}); + +test("(h) a curated-tag change while a channel is held reaches its pages when the drive is back", async () => { + resetCorpus(); + seedVideo("local"); + seedDriveChannel({ d1: "Stream with Elfpire Eva" }); + await runIndex(); + assert.equal("curatedTags" in transcriptRecord("d1"), false); + + unmount(); + // A rule edit moves no mtime. It re-derives d1 in the index (no disk read), + // but d1's page is not rewritten while its channel is held. + writeGlobalTags(paths, { + version: 1, + tags: [ + { + id: "eva-collab", + label: "Collab", + group: "eva", + groupLabel: "Eva", + order: 1, + rules: [{ id: "meta", kind: "metadata" as const, pattern: "elfpire", enabled: true }], + }, + ], + assignments: {}, + }); + const pagesBefore = sharedTranscripts(); + const { log } = await runIndex(); + assert.deepEqual(sharedTranscripts(), pagesBefore); + assert.equal(pagesPending(), true, "the page debt is kept"); + assert.ok(log.some((l) => l.startsWith("curated tags: the pages of 1 held channel(s) are not rewritten while held")), log.join("\n")); + + remount(); + const back = await runIndex(); + assert.equal(back.res.added + back.res.changed + back.res.removed, 0, "no mtime moved"); + assert.deepEqual(transcriptRecord("d1").curatedTags, ["eva-collab"]); + assert.equal(pagesPending(), false); +}); + +test("(i) the drive lost MID-WALK: the second look holds the channel instead of dropping the rest of it", async () => { + resetCorpus(); + seedVideo("local"); + seedDriveChannel(); + for (const id of ["d3", "d4"]) seedVideo(id, DRIVE_CHANNEL); + const drive = [...DRIVE_VIDEOS, `${DRIVE_CHANNEL}/d3`, `${DRIVE_CHANNEL}/d4`]; + await runIndex(); + assert.deepEqual(indexed(), [...drive, `${CHANNEL}/local`]); + const pagesBefore = sharedTranscripts(); + const subsBefore = sharedSubs(); + + // The first look before the walk finds the drive, and readdir lists all four + // videos. Then the drive goes, right after the walk's first metadata stat: + // every later stat in the channel is ENOENT, which on its own reads as "no + // metadata yet" and would drop the rest of the channel as gone. + let lost = false; + afterStat = (p) => { + if (lost || !p.endsWith(`${path.sep}metadata.info.json`)) return; + if (!p.includes(`${path.sep}${DRIVE_CHANNEL}${path.sep}data${path.sep}`)) return; + lost = true; + unmount(); + }; + seedVideo("local2"); // so the build is not a no-op + const { res, log } = await runIndex().finally(() => { + afterStat = null; + }); + assert.ok(lost, "the drive went away inside the walk"); + assert.deepEqual(res.heldChannels, [DRIVE_CHANNEL]); + assert.equal(res.removed, 0, log.join("\n")); + assert.equal(res.added, 1); + assert.deepEqual(indexed(), [...drive, `${CHANNEL}/local`, `${CHANNEL}/local2`]); + assert.deepEqual(sharedTranscripts(), pagesBefore); + assert.deepEqual(sharedSubs(), subsBefore); + assert.ok( + log.some((l) => + l.startsWith(`Channel ${DRIVE_CHANNEL}: its media is not reachable (drive not mounted?), on location "USB drive"; its 4 indexed video(s) are kept`), + ), + log.join("\n"), + ); +}); + +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); + assert.ok(statSync(ROOT).isDirectory()); + const outside = writes.filter((p) => p !== ROOT && !p.startsWith(ROOT + path.sep)); + assert.deepEqual(outside, []); + assert.ok(writes.length > 0, "the spy saw the writes"); +}); diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts @@ -8,6 +8,22 @@ // // Per-channel config.json selects the transcript parser ("youtube" → VTT, // "transcribe" → whisper.cpp JSON). Short-circuits when mtimes already match. +// +// A CHANNEL WHOSE MEDIA IS NOT REACHABLE is HELD, not emptied: a relocated +// `data/` on an unmounted drive, one mid-relocation, a link and a config that +// disagree (inspectChannelMedia), or a data dir that fails to read. It is not +// rescanned; its index records are kept as they are and its shared page trees +// (transcripts, subs, digests) are left as they are, so the next site build +// still publishes it. Until this hold the scan read such a channel as having +// no videos, removed every record it had, and the site built next published +// the channel as gone. The stats build has the same hold (buildStats.ts); the +// words are shared (lib/channelMediaHold.ts). +// +// A FULL REBUILD (a schema change, or no index yet) with a channel held +// REFUSES: it clears every channel's records, and a held channel cannot be +// re-read, so it would come out empty. ARCHILYZER_INDEX_ALLOW_HELD=1 lets it +// proceed; the held channel is then out of the index until its media is back +// and the index is built again. import path from "node:path"; import { createHash } from "node:crypto"; @@ -78,6 +94,13 @@ import { type ChannelHandling, } from "../lib/channelConfig"; import { readChannelConfigFile } from "./channels"; +import { inspectChannelMedia } from "../lib/channelMedia"; +import { + HELD_WAYS_OUT, + describeHeld, + heldReason, + isMediaHeld, +} from "../lib/channelMediaHold"; import { resolveChannelGroupId } from "../lib/channelGroups"; import type { Paths } from "../lib/paths"; import { @@ -275,21 +298,32 @@ async function exists(p: string): Promise<boolean> { } } +function errCode(err: unknown): string { + const code = (err as NodeJS.ErrnoException | null)?.code; + return typeof code === "string" ? code : String(err); +} + +// `held` maps each channel whose media could not be read to why, in words with +// no path in them. A held channel contributes no live entries; the caller keeps +// its records and pages (see the file header). async function scanSource( channelsDir: string, log: (msg: string) => void, ): Promise<{ live: LiveEntry[]; channels: Map<string, ChannelConfig>; + held: Map<string, string>; }> { + const locations = getSettings().storage.locations; const channels = new Map<string, ChannelConfig>(); const live: LiveEntry[] = []; + const held = new Map<string, string>(); let channelEntries: Dirent[]; try { channelEntries = await readdir(channelsDir, { withFileTypes: true }); } catch { // Fresh transcripts dir with no channels yet. - return { live, channels }; + return { live, channels, held }; } for (const ch of channelEntries) { if (!ch.isDirectory()) continue; @@ -308,13 +342,33 @@ async function scanSource( // and routing it through the video scan would only ever produce noise. Its // posts tree is built from the JSONL shards further down. if (isSocialChannel(cfg)) continue; + // An unmounted drive is not an empty channel (lib/channelMedia.ts): the + // readdir below would fail, and every record the channel has would be + // removed as gone. + const media = await inspectChannelMedia({ channelsDir }, ch.name, cfg); + if (isMediaHeld(media.status)) { + held.set(ch.name, heldReason(media, cfg.dataDir, locations)); + continue; + } const dataDir = path.join(channelDir, "data"); let videoEntries: Dirent[]; try { videoEntries = await readdir(dataDir, { withFileTypes: true }); - } catch { + } catch (err) { + const code = errCode(err); + // No data/ at all on a channel whose media was never moved: it has + // downloaded nothing yet (or its media was deleted), and it IS empty. + if (code === "ENOENT" && media.status === "in-place") { + log(`Channel ${ch.name}: no data/ directory; indexed as a channel with no videos.`); + continue; + } + // Anything else — a relocated drive gone between the check and the + // read, a permission or I/O error — is a channel that could not be read. + held.set(ch.name, `its data directory could not be read (${code})`); continue; } + const channelLive: LiveEntry[] = []; + let readFailure: string | null = null; for (const v of videoEntries) { if (!v.isDirectory()) continue; const videoDir = v.name; @@ -323,7 +377,16 @@ async function scanSource( let metaMs: number; try { metaMs = (await stat(metaPath)).mtimeMs; - } catch { + } catch (err) { + // ENOENT is a video dir with no metadata yet (a download in flight, a + // partial one): skipped, as always. Any other error is the channel's + // media failing mid-scan; the channel is held below rather than read + // as missing this video and every one after it. + const code = errCode(err); + if (code !== "ENOENT" && code !== "ENOTDIR") { + readFailure = code; + break; + } continue; } // Hybrid: a single channel may contain both YouTube auto-subs (.vtt) @@ -373,7 +436,7 @@ async function scanSource( // Sidecar absent — the common case (102 of ~76,000 videos have one). } } - live.push({ + channelLive.push({ channelSlug: ch.name, handling: cfg.handling, configName: cfg.name, @@ -389,8 +452,24 @@ async function scanSource( digestMs, }); } + if (readFailure !== null) { + // One video, not the directory: said apart from the readdir failure + // above, so the log points at the right place. The whole channel is + // held all the same. + held.set(ch.name, `a video in its data directory could not be read (${readFailure})`); + continue; + } + // Asked again after the walk: a drive that went away DURING it leaves the + // videos after that point missing from this scan, which would remove them. + // Three syscalls a channel. + const after = await inspectChannelMedia({ channelsDir }, ch.name, cfg); + if (isMediaHeld(after.status)) { + held.set(ch.name, heldReason(after, cfg.dataDir, locations)); + continue; + } + for (const e of channelLive) live.push(e); } - return { live, channels }; + return { live, channels, held }; } function pathKeyId(k: PathKey): string { @@ -418,6 +497,9 @@ export type BuildIndexResult = { changed: number; removed: number; shortCircuited: boolean; + // Channels whose media could not be read, so they were not rescanned: their + // index records and shared pages were kept as they were (see the header). + heldChannels: string[]; }; export type BuildIndexOptions = { @@ -425,6 +507,17 @@ export type BuildIndexOptions = { onLog?: (msg: string) => void; }; +// Set to 1 (or true/yes/on) to let a FULL rebuild proceed with a channel held. +// Declared in lib/envVars.ts. +export const INDEX_ALLOW_HELD_ENV = "ARCHILYZER_INDEX_ALLOW_HELD"; +const TRUTHY = new Set(["1", "true", "yes", "on"]); +function allowsHeldFullRebuild( + env: Record<string, string | undefined> = process.env, +): boolean { + const raw = env.ARCHILYZER_INDEX_ALLOW_HELD; + return typeof raw === "string" && TRUTHY.has(raw.trim().toLowerCase()); +} + export async function buildIndex({ paths, onLog, @@ -535,6 +628,39 @@ export async function buildIndex({ const storedSchema = meta.get("schema") as number | undefined; const schemaBumped = storedSchema !== SCHEMA_VERSION; + + // Recorded as INDEX_SCANNED_AT_KEY only when this build completes, so + // buildStats can tell apart a video with no `mtimes` record: metadata newer + // than this is "not indexed yet"; older, and this build saw it and skipped it + // (no upload_date, or processing failed) or its channel was held. + // + // The scan reads only the source tree, so it runs BEFORE a schema clear: a + // full rebuild must know which channels it cannot read before it drops them. + const scanStartedAt = Date.now(); + const { + live, + channels: channelConfigs, + held, + } = await scanSource(channelsDir, log); + + // A full rebuild clears every channel's records, and a held channel cannot be + // re-read: it would come out of this build empty, and the site built next + // would publish it as gone. Refuse, unless told to go on without it. + const heldThroughClear = schemaBumped && held.size > 0; + if (heldThroughClear && !allowsHeldFullRebuild()) { + await root.close(); + throw new Error( + `The index must be rebuilt in full (index schema ${storedSchema ?? "<none>"} -> ${SCHEMA_VERSION}), ` + + `but ${held.size} channel(s) cannot be read: ${describeHeld(held)}. ` + + `A full rebuild clears every channel's index records, so these would come out empty and the next site build would publish them as gone. ` + + `${HELD_WAYS_OUT} ` + + `To rebuild without them anyway (each stays out of the index until its media is back and the index is built again), set ${INDEX_ALLOW_HELD_ENV}=1 ` + + `in the environment of the process that runs the build: for the command line, the command's own ` + + `(\`${INDEX_ALLOW_HELD_ENV}=1 pnpm archilyzer index\`); for the editor's Build index job, or a site build started from the editor, ` + + `the editor's own environment, which takes a restart of the editor.`, + ); + } + if (schemaBumped) { log( `Schema change (${storedSchema ?? "<none>"} -> ${SCHEMA_VERSION}); invalidating LMDB cache.`, @@ -557,12 +683,6 @@ export async function buildIndex({ await meta.put("schema", SCHEMA_VERSION); } - // Recorded as INDEX_SCANNED_AT_KEY only when this build completes, so - // buildStats can tell apart a video with no `mtimes` record: metadata newer - // than this is "not indexed yet"; older, and this build saw it and skipped it - // (no upload_date, or processing failed). - const scanStartedAt = Date.now(); - const { live, channels: channelConfigs } = await scanSource(channelsDir, log); const livePathIds = new Set<string>(); const liveByPathId = new Map<string, LiveEntry>(); for (const s of live) { @@ -590,12 +710,29 @@ export async function buildIndex({ changed.push(s); } } + // A held channel has no live entries, and its records are not "gone": they + // are kept, and counted for the log. + const keptHeld = new Map<string, number>(); for (const { key, value } of mtimes.getRange()) { const k = key as PathKey; + if (held.has(k[0])) { + keptHeld.set(k[0], (keptHeld.get(k[0]) ?? 0) + 1); + continue; + } if (!livePathIds.has(pathKeyId(k))) { removed.push({ pathKey: k, indexKey: (value as MtimeRecord).indexKey }); } } + let keptHeldTotal = 0; + for (const [slug, why] of held) { + const kept = keptHeld.get(slug) ?? 0; + keptHeldTotal += kept; + log( + heldThroughClear + ? `Channel ${slug}: ${why}; held under ${INDEX_ALLOW_HELD_ENV}: this full rebuild cleared its index records, so it is out of the index until its media is back and the index is built again. Its transcript, subtitle and digest pages are left as they are.` + : `Channel ${slug}: ${why}; its ${kept} indexed video(s) are kept as they are, not rescanned, and its transcript, subtitle and digest pages are left as they are.`, + ); + } const anyMutations = added.length > 0 || changed.length > 0 || removed.length > 0; @@ -608,6 +745,8 @@ export async function buildIndex({ // from LMDB further below so they reflect current site config. const sharedManifestsPresent = async (): Promise<boolean> => { for (const channelSlug of channelConfigs.keys()) { + // A held channel's pages are not written this build either way. + if (held.has(channelSlug)) continue; const mPath = path.join(transcriptsOutDir, channelSlug, "manifest.json"); const raw = await readFile(mPath, "utf8").catch(() => null); if (!raw) return false; @@ -638,7 +777,10 @@ export async function buildIndex({ const curatedFresh = new Set<string>(); log( - `Diff: +${added.length} added, ~${changed.length} changed, -${removed.length} removed, ${live.length} total.`, + `Diff: +${added.length} added, ~${changed.length} changed, -${removed.length} removed, ${live.length} total.` + + (held.size > 0 + ? ` Held: ${held.size} channel(s), ${keptHeldTotal} video(s) kept.` + : ""), ); for (const channelSlug of channelConfigs.keys()) { @@ -1056,6 +1198,10 @@ export async function buildIndex({ if (sharedNeedsBuild) { for (const channelSlug of Array.from(channelConfigs.keys()).sort()) { + // A held channel's pages are left exactly as the last build wrote them: + // not rewritten, not pruned, and (below) not removed. After a full rebuild + // its records are gone, and a rewrite would publish it empty. + if (held.has(channelSlug)) continue; const channelDir = path.join(transcriptsOutDir, channelSlug); await mkdir(channelDir, { recursive: true }); @@ -1172,6 +1318,10 @@ export async function buildIndex({ // availability.json for just those ids is cheap and exact. let maybeMissingCount = 0; for (const slug of channelConfigs.keys()) { + // A held channel's availability.json files are on the media that cannot be + // read, and a missing one reads as "maybe missing": its states are carried + // over from the last build instead (below). + if (held.has(slug)) continue; const record = await loadMaybeMissing(paths, slug); if (!record?.ids.length) continue; const scannedAtMs = Date.parse(record.checkedAt); @@ -1199,6 +1349,25 @@ export async function buildIndex({ ); } + // A held channel keeps the states the last build published for it (the + // confirmed ones above come from its kept records; this adds the overlay's), + // read back before the wholesale rewrite below. Nothing to carry after a full + // rebuild: the clear took them, with the records they described. + if (held.size > 0) { + for (const { key, value } of videoState.getRange()) { + const id = key as string; + const cut = id.indexOf("\x00"); + if (cut < 0) continue; + const slug = id.slice(0, cut); + if (!held.has(slug)) continue; + const rec = mtimes.get([slug, id.slice(cut + 1)]); + if (!rec) continue; + const st = value as VideoState; + stateByIndexKey.set(indexKeyId(rec.indexKey), st); + stateByPath.set(id, st); + } + } + // Publish the sparse map for buildStats, which runs after us against the same // LMDB file and would otherwise have to re-read ~76k availability.json files // to build the status chart. Rewritten wholesale each build: the map is small @@ -1219,6 +1388,16 @@ export async function buildIndex({ if (sharedNeedsBuild) { for (const channelSlug of Array.from(channelConfigs.keys()).sort()) { + // Held: its subs dir is left as it is, and its stats carried over so the + // site manifests still list it (none to carry after a full rebuild). + if (held.has(channelSlug)) { + const prev = channelStatsDb.get(channelSlug); + if (prev) { + channelStats.set(channelSlug, prev); + subsTotalCount += prev.videoCount; + } + continue; + } const cfg = channelConfigs.get(channelSlug)!; const subsChannelDir = path.join(subsOutDir, channelSlug); const tracksInChannel = new Set<string>(); @@ -1331,7 +1510,7 @@ export async function buildIndex({ const subsChannelSlugSet = new Set(channelStats.keys()); for (const e of topSubsEntries) { if (e.isDirectory()) { - if (!subsChannelSlugSet.has(e.name)) { + if (!subsChannelSlugSet.has(e.name) && !held.has(e.name)) { await rm(path.join(subsOutDir, e.name), { recursive: true, force: true, @@ -1365,7 +1544,17 @@ export async function buildIndex({ // curated-tag page debt is settled. Deliberately AFTER the page build and not // beside the hashes: an interrupt anywhere above must leave the flag standing // so the next build rewrites the shards. - clearCuratedPagesPending(meta); + // + // Except for a held channel's pages, which were not written: the re-apply + // pass re-derives its records in LMDB like any other, and its pages owe them. + // The flag stays, so the first build with its media back rewrites them. + if (held.size > 0 && curatedReapply.pagesPending) { + log( + `curated tags: the pages of ${held.size} held channel(s) are not rewritten while held; the re-derived tags reach them on the first build with their media back.`, + ); + } else { + clearCuratedPagesPending(meta); + } await meta.flushed; // --------------------------------------------------------------------------- @@ -1578,6 +1767,16 @@ export async function buildIndex({ if (sharedNeedsBuild) { for (const channelSlug of Array.from(channelConfigs.keys()).sort()) { + // Held: as with subs, its digest dir is left as it is and its stats + // carried over. + if (held.has(channelSlug)) { + const prev = channelDigestStatsDb.get(channelSlug); + if (prev) { + channelDigestStats.set(channelSlug, prev); + digestTotalCount += prev.digestCount; + } + continue; + } const cfg = channelConfigs.get(channelSlug)!; const digestChannelDir = path.join(digestsOutDir, channelSlug); let digestCount = 0; @@ -1677,7 +1876,7 @@ export async function buildIndex({ }).catch(() => [] as Dirent[]); for (const e of topDigestEntries) { if (e.isDirectory()) { - if (!channelDigestStats.has(e.name)) { + if (!channelDigestStats.has(e.name) && !held.has(e.name)) { await rm(path.join(digestsOutDir, e.name), { recursive: true, force: true, @@ -2010,7 +2209,10 @@ export async function buildIndex({ const durationMs = Date.now() - t0; log( - `Done in ${(durationMs / 1000).toFixed(2)}s. ${sites.length} site(s): ${sitesBuilt} built, ${sitesSkipped} up to date; ${live.length} transcripts in pool.`, + `Done in ${(durationMs / 1000).toFixed(2)}s. ${sites.length} site(s): ${sitesBuilt} built, ${sitesSkipped} up to date; ${live.length} transcripts in pool.` + + (held.size > 0 + ? ` Held, their media not readable: ${[...held.keys()].join(", ")}.` + : ""), ); return { totalCount: aggregateSummaries, @@ -2024,5 +2226,6 @@ export async function buildIndex({ changed: changed.length, removed: removed.length, shortCircuited: !sharedNeedsBuild && sitesBuilt === 0, + heldChannels: [...held.keys()], }; } diff --git a/common/controller/buildStats.ts b/common/controller/buildStats.ts @@ -63,12 +63,14 @@ import { import type { VideoStatus } from "../lib/stats"; import type { ChannelConfig } from "../lib/channelConfig"; import { readChannelConfigFile } from "./channels"; +import { inspectChannelMedia } from "../lib/channelMedia"; import { - inspectChannelMedia, - type ChannelMediaStatus, -} from "../lib/channelMedia"; + HELD_WAYS_OUT, + describeHeld, + heldReason, + isMediaHeld, +} from "../lib/channelMediaHold"; import { getSettings } from "../lib/settings"; -import { locationLabelOfDataDir } from "../lib/storageLocations"; import type { Paths } from "../lib/paths"; import { listSites, siteStatsDir } from "../lib/site"; import { @@ -248,16 +250,6 @@ async function resolveAcquisitionDates( return { downloadedDate, transcribedDate }; } -// Why a channel is held, without the paths inspectChannelMedia's `detail` -// carries (/storage shows those). -const HELD_REASON: Record<ChannelMediaStatus, string> = { - unreachable: "its media is not reachable (drive not mounted?)", - "in-transition": "a move of its media is in progress or was interrupted", - inconsistent: "its data link and its config disagree", - ok: "reachable", - "in-place": "reachable", -}; - // `held` maps each channel whose media is not reachable to why, in words with // no path in them: it is not scanned, and the caller keeps its cached stats // (see the file header). @@ -292,12 +284,8 @@ async function scanSource( // An unmounted drive is not an empty channel (lib/channelMedia.ts): the // readdir below would fail and every one of its stats would be removed. const media = await inspectChannelMedia({ channelsDir }, ch.name, cfg); - if (media.status !== "ok" && media.status !== "in-place") { - const label = locationLabelOfDataDir(cfg.dataDir ?? media.target, locations); - held.set( - ch.name, - `${HELD_REASON[media.status]}${label ? `, on location "${label}"` : ""}`, - ); + if (isMediaHeld(media.status)) { + held.set(ch.name, heldReason(media, cfg.dataDir, locations)); continue; } const dataDir = path.join(channelDir, "data"); @@ -444,11 +432,7 @@ export async function buildStats({ await root.close(); throw new Error( `The stats cache must be rebuilt (stats schema ${storedSchema ?? "<none>"} -> ${STATS_SCHEMA_VERSION}), ` + - `but ${held.size} channel(s) cannot be read: ` + - [...held].map(([slug, why]) => `${slug} (${why})`).join("; ") + - `. For each: mount its media and run this again; or repair or re-point its location on /storage; ` + - `or finish or clear its move (the channel's Storage panel); or, if it is gone for good, ` + - `delete the channel or set excludeFromBuild in its config.`, + `but ${held.size} channel(s) cannot be read: ${describeHeld(held)}. ${HELD_WAYS_OUT}`, ); } log( diff --git a/common/lib/channelMediaHold.ts b/common/lib/channelMediaHold.ts @@ -0,0 +1,61 @@ +import type { + ChannelMediaLocation, + ChannelMediaStatus, +} from "./channelMedia"; +import { + locationLabelOfDataDir, + type StorageLocation, +} from "./storageLocations"; + +// THE HOLD, in the words both pool-wide builds use. +// +// The index build (controller/buildIndex.ts) and the stats build +// (controller/buildStats.ts) each walk every channel's `data/`. A channel whose +// media cannot be read — a relocated `data/` on an unmounted drive, a move in +// progress, a link and a config that disagree — is HELD by both: not rescanned, +// and what the last build knew of it kept, rather than read as a channel with +// no videos and removed (lib/channelMedia.ts says why that reading is the +// dangerous one). This module is only the shared vocabulary: which statuses +// hold, why, in words with no path in them (/storage shows the paths), and the +// ways out a refusal names. Each build decides for itself what "kept" means. +// +// Pure: no I/O. The caller asks inspectChannelMedia and passes the answer in. + +// "ok" and "in-place" are read; every other status holds, including any a later +// inspectChannelMedia adds. +export function isMediaHeld(status: ChannelMediaStatus): boolean { + return status !== "ok" && status !== "in-place"; +} + +// Why a channel is held, without the paths inspectChannelMedia's `detail` +// carries. +export const HELD_REASON: Record<ChannelMediaStatus, string> = { + unreachable: "its media is not reachable (drive not mounted?)", + "in-transition": "a move of its media is in progress or was interrupted", + inconsistent: "its data link and its config disagree", + ok: "reachable", + "in-place": "reachable", +}; + +// The reason, and the storage location's label when the channel's media is on +// one. `dataDir` is the channel config's; the inspector's target stands in when +// the config names none (a move in flight). +export function heldReason( + media: Pick<ChannelMediaLocation, "status" | "target">, + dataDir: string | undefined, + locations: StorageLocation[], +): string { + const label = locationLabelOfDataDir(dataDir ?? media.target, locations); + return `${HELD_REASON[media.status]}${label ? `, on location "${label}"` : ""}`; +} + +// A held channel named in a refusal, as `slug (why)`, joined. +export function describeHeld(held: Map<string, string>): string { + return [...held].map(([slug, why]) => `${slug} (${why})`).join("; "); +} + +// What a refusal tells the operator to do, mounting first. +export const HELD_WAYS_OUT = + `For each: mount its media and run this again; or repair or re-point its location on /storage; ` + + `or finish or clear its move (the channel's Storage panel); or, if it is gone for good, ` + + `delete the channel or set excludeFromBuild in its config.`; diff --git a/common/lib/envVars.ts b/common/lib/envVars.ts @@ -112,6 +112,7 @@ const DECLARED: EnvVarDecl[] = [ { name: "AUDIO_CHECK_RESUME_DURING_PROBE", audience: "runtime", default: "the channel's `audioCheck.resumeDuringProbe`", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "`1` or `true` resumes yt-dlp during the audio check's probe, anything else holds it, for a one-off comparison run; unset = the channel's setting." }, { name: "AUDIO_CHECK_BACKOFF_FACTOR", audience: "runtime", default: "the built-in factor", readBy: "common/ytdlp/audioCheckedDownload.ts", doc: "The audio check's interval backoff factor, in (0, 1], for a one-off run." }, { name: "ARCHILYZER_STATS_ALLOW_DOWNGRADE", audience: "runtime", default: "off", readBy: "common/controller/buildStats.ts", doc: "`1` lets a stats build clear a stats cache that a NEWER build wrote, for a deliberate rollback. Unset, such a build refuses and names both versions." }, + { name: "ARCHILYZER_INDEX_ALLOW_HELD", audience: "runtime", default: "off", readBy: "common/controller/buildIndex.ts", doc: "`1` lets a FULL index rebuild (a schema change, or no index yet) proceed while a channel's media cannot be read; that channel stays out of the index until its media is back and the index is built again. Unset, such a build refuses and names each channel." }, { name: "MCP_IO_STATS", audience: "runtime", default: "off", readBy: "common/lib/archive/io-stats.ts", doc: "`1` turns on per-call I/O accounting, for `mcp/bench`." }, { name: "ARCHILYZER_EDITOR_URL", audience: "runtime", default: "`http://localhost:3001`", readBy: "scripts/archilyzer-ops.mjs, mcp/src/fetchClip.ts, umtool", doc: "Which editor `pnpm ops` and the MCP's `fetch_clip` talk to." }, { name: "ARCHILYZER_AGENT", audience: "runtime", default: "`cli`", readBy: "scripts/archilyzer-ops.mjs", doc: "Who is asking, recorded as the provenance of a curated-tag write through `pnpm ops`." }, diff --git a/editor/CHANGELOG.md b/editor/CHANGELOG.md @@ -3,6 +3,7 @@ ## [Unreleased] - **Transcripts that arrived after a video was first seen are counted.** The stats behind the homepage, the hub and every site's charts were cached per video and refreshed only when the video's metadata changed, so a transcript that came later — a Whisper run days after the download, or a video downloaded after the last index build — never reached them, and a video with YouTube captions alone had no transcription date. Counts and charts were low; the homepage could show a site with 0 transcripts, 0 channels and 0 hours while it served its videos. A stat is now also redone whenever the index re-reads the video, every transcript has a date, and a captioned video is dated by when its captions arrived rather than by a later Normalize run, so its place on "Transcribed over time" can move. **After updating, rebuild and restart the editor before anything else:** until then, **Build stats dataset** runs the old code and would undo the new stats, while a site, hub or homepage build already runs the new code — and the first stats build of any kind re-reads every video once (about 10–30 minutes on a large archive; it can be stopped and picks up where it stopped). Then build the index, the stats, the homepage, the hub, and the sites. - **A stats build keeps the stats of a channel whose drive is not mounted, and will not undo a newer version's stats.** A channel whose media is on a drive that is not mounted (or is being moved) is left as it was instead of being read as a channel with no videos; a stats rebuild that has to start over refuses until the drive is back. A stats build refuses to clear stats written by a newer version of the editor; set `ARCHILYZER_STATS_ALLOW_DOWNGRADE=1` to roll back on purpose. Its log also says apart how many videos were downloaded since the last index build (they catch up after the next one) and how many the index skipped (no upload date, or it failed on them). +- **An index build keeps a channel whose drive is not mounted, instead of dropping it from the sites.** **Build index**, a site build's data phase and `archilyzer index` read a channel whose media is on a drive that is not mounted (or is being moved, or whose link and config disagree) as a channel with no videos: they removed its videos from the index, and the next site build published the channel as gone. Such a channel is now left as the last build had it — its videos stay in the index, its pages stay as they were, and the sites built next still list it — and the log names it, with its storage location: one line per channel, ` Held: N channel(s), K video(s) kept.` at the end of the `Diff:` line, and the channels again on the last line. A data folder that fails to read is held the same way, and a channel with no data folder at all is said in the log instead of passed over. An index rebuild that has to start over (after an update that changes the index's format, or with no index yet) refuses while any channel is held and says which; mount the drive first, or set `ARCHILYZER_INDEX_ALLOW_HELD=1` to rebuild without that channel until its drive is back and the index is built again — on the command for a command-line build (`ARCHILYZER_INDEX_ALLOW_HELD=1 pnpm archilyzer index`), or in the editor's own environment, with a restart, for **Build index** and the site builds started from the editor. - **Building the homepage now publishes the source: a read-only git mirror, its raw tree and a fresh tarball, behind a gate.** `archilyzer build homepage`, the `/sites` Homepage jobs and `pnpm ops build-homepage` run `archilyzer source publish` between compose and `next build`. It makes a fresh clone of the private `main` (the repository itself is never rewritten), rewrites that copy with git-filter-repo using your scrub rules (file contents and commit messages; your home directory becomes `/home/user` without a rule), and publishes it under `homepage/public` for `git clone https://archilyzer.pages.dev/source/archilyzer.git`, beside `/source/tree/` and the Downloads tarball. Before anything is written, every object of the rewritten history and every file about to be published is searched for every string you have denied; **one hit refuses the build**, and its log names the string only by where you wrote it (`denylist line 3 (len 5)`) and each hit by its object, field and byte offset — never a byte of the object. **A refusal withdraws the source**: the last publish is removed from `homepage/public` and the last build's copy from `homepage/out`, and **Deploy homepage refuses** a build whose source was not audited under today's rules and today's `main` ("run `archilyzer build homepage`, then deploy"). The rules live outside the repo, in `~/.config/archilyzer/source-scrub.txt` and `source-denylist.txt` (`ARCHILYZER_CONFIG_DIR`, `SOURCE_SCRUB_FILE`, `SOURCE_DENYLIST_FILE`); **without them the build refuses**, naming the missing file. **Put everything private in the denylist before any deploy, a preview included**: previews are public, and every deployment stays reachable at its own address until you delete it. Install git-filter-repo once (`pipx install git-filter-repo`; the editor's process needs `~/.local/bin` on its `PATH` to find it) — without it the build fetches it through `pipx run`, which needs the network — and gitleaks if you want its secret scan too. An unchanged `main` with unchanged rules is skipped, so a rebuild costs about 20 seconds only when something moved. A checkout with no git repository (the docker image, a tarball install) builds with the /source page's empty state. `archilyzer source publish --check` audits without writing, `archilyzer source audit <clone>/.git` checks any clone, `archilyzer build homepage --no-source` removes the published source instead, and `archilyzer doctor` reports the tools, the two files (rule counts and permissions, never their contents) and the last publish. `create-archives.sh` is gone. See PUBLISH.md, "The source mirror (homepage)". - **umtool reads the corpus from its checkout (or `TRANSCRIPTS_DIR`), and the song project's data defaults to `~/.local/share/archilyzer/song`.** If yours is elsewhere, link it there before restarting umtool: `mkdir -p ~/.local/share/archilyzer && ln -s <where the data is> ~/.local/share/archilyzer/song` (the data stays where it is). With no `CHANNELS_DIR`, umtool reads the corpus at `$TRANSCRIPTS_DIR/channels`, else the checkout's own `transcripts/channels`; it used to fall back to an absolute path that existed on one machine only. The song project's videos default to `~/reports/quartering-uh-song/videos`; `SONG_DIR` and `VIDEO_ROOT` still win. The song project's tracked manifests record their paths relative to the song folders, and the twenty one-off `umtool/song/*.sh` run logs, which only ever ran on the machine that wrote them, are gone. - **umtool's production build no longer reads the corpus folder.** Since umtool began finding the corpus from its checkout (the bullet above), `next build` treated the checkout's whole `transcripts/channels` as files to bundle. On a real archive it ran out of memory and was killed, so umtool could not be rebuilt. The build now ignores that folder and finishes in about 25 s at under 1 GB, the same as a checkout with no corpus. Nothing changes when umtool runs. diff --git a/plans/FACTS.md b/plans/FACTS.md @@ -7413,8 +7413,12 @@ on anchors elsewhere in this file: index it: - no `upload_date` (`buildIndex.ts:701`); - a processing failure; - - or the channel's media was unreachable during that build, since buildIndex has no drive - guard. + - or its channel was held during that build (its media unreachable). Since release 15 (slice + IG) an incremental build keeps a held channel's records, so this is a video that reached the + drive after the last index build that could read it. Once the drive is back, a stats-only run + (Build stats dataset, or a pool composer) before the next index build counts it here, and + that index build heals it. Under `ARCHILYZER_INDEX_ALLOW_HELD`, a full rebuild drops all of + the held channel's records the same way (see "The index build's hold"). It stays until fixed, and is logged as such rather than as pending (`:500`). - **A transcript always has a date, and a caption video takes its captions' arrival.** @@ -7446,10 +7450,9 @@ on anchors elsewhere in this file: - This is the build's own guard. The job registry's `needsMedia` check (`streamCommand.ts refuseForUnreachableMedia`) is per channel and needs a `channelSlug`, so it never covered this pool-wide build, from the editor or from the CLI. - - **buildIndex has no such guard.** An index build with a drive unmounted drops those channels' - index records, and the site pages built from it lose them. - - Its `Diff: … -R removed` line (`buildIndex.ts:641`) shows it. - - A proper hold there is a follow-up slice (`stats-cache-key.md`, "Left"). + - **buildIndex had no such guard until release 15.** An index build with a drive unmounted + dropped those channels' index records, and the site pages built from it lost them. It holds + them now: see "The index build's hold" below. - **One stats build at a time: an operator rule, not a lock.** - Two concurrent runs are harmless unless one clears the cache (a schema change) after the other has scanned. The other then collects a partly refilled `statsByPath` and publishes truncated @@ -7484,3 +7487,67 @@ on anchors elsewhere in this file: finishes the rest. - Run in the editor, it stalls the editor's event loop for the length of the pass. Prefer the CLI with the editor idle. + +## The index build's hold (verified 2026-09-29, branch `r15/index-hold`) + +The record is [`release-15.md`](release-15.md), "Slice IG, as shipped". Anchors are at the branch +tip. The branch added lines to `buildIndex.ts` from `:10` on, so every `buildIndex.ts` anchor above +this section is stale, by +16 near the top and +203 at the end; they are not rewritten in place. + +- **An unmounted drive is not an empty channel, for the index either.** + - `scanSource` (`common/controller/buildIndex.ts:309`) calls `inspectChannelMedia({ channelsDir }, + slug, cfg)` for every channel that is not excluded and not social (`:348`), before it reads + `data/`. A status other than `ok` or `in-place` (`isMediaHeld`, + `common/lib/channelMediaHold.ts:26`) puts the channel in `held` with a reason and no path, and + it is not scanned. + - It calls it again after the walk (`:465`), so a drive that goes away mid-walk holds the + channel instead of dropping the videos after that point (without it, `buildIndex.test.ts` + case (i) removes 3 of 4). + - A failed `readdir(data/)` holds too (`its data directory could not be read (<code>)`), except + ENOENT on an `in-place` channel, which is a channel with no downloads and is logged as such + (`:362`). A per-video metadata `stat` failing with anything but ENOENT or ENOTDIR holds the + channel too, logged as `a video in its data directory could not be read (<code>)` (`:387`). +- **What a held channel keeps, on an incremental build:** + - its `mtimes` records: the removal pass skips its keys and counts them (`:715`), so `sums`, + `cues`, `subs`, `digests` and `byChannel` keep them too; + - its shared transcript, subs and digest trees: not rewritten, not pruned, not removed + (`:1204`, `:1393`, `:1772`, and the top-level cleanups `:1513`, `:1879`); + - its subs and digest stats, carried from `channelStatsDb` / `channelDigestStatsDb`, so the + per-site subs and digest manifests still list it; + - its availability states: the maybe-missing overlay skips it (`:1324`), and the last build's + `videoState` entries for it are carried over (`:1356`). Its `availability.json` files are on + the missing drive, and a missing one reads as `maybe_missing`. + - The per-site summaries come from LMDB, so the site built next still lists its videos. +- **A curated-tag change while a channel is held:** the re-apply pass re-derives its records in + LMDB (no disk read), but its pages are not written, so `curatedPagesPending` is NOT cleared while + a channel is held and the pass had pages pending (`:1551`). The first build with the drive back + rewrites them. +- **A full rebuild with a channel held refuses** (`:649`). A full rebuild is a schema change or a + first build (no `meta.schema`); it clears every sub-DB, and a held channel cannot be re-read. + - The scan now runs BEFORE the clear (`:639`), so the refusal leaves the index untouched. + `scanStartedAt` is still taken at the scan's start. + - The message names each channel with its location's label, the ways out (`HELD_WAYS_OUT`, + shared with the stats build's refusal), and `ARCHILYZER_INDEX_ALLOW_HELD` (`:512`, declared in + `envVars.ts`) with where it is set: the command's own environment for a CLI run; the editor's + own environment, and so a restart, for the editor's Build index job or a site build started + from the editor (their children inherit `process.env`). The CLI exits 1 on it, so a site + build's data phase fails with it. + - With the variable set, the build proceeds: the held channel's records go with the clear, its + shared trees are left on disk, and it is out of the index (the site lists it with 0 videos) + until its media is back and an index build runs. +- **Who sees it:** `BuildIndexResult.heldChannels` (`:502`); the log's per-channel line, the + `Diff:` line's ` Held: N channel(s), K video(s) kept.` suffix (`:780`), and the `Done in` line's + ` Held, their media not readable: <slugs>.` suffix. The CLI (`archilyzer index`, the export's + and homepage's `build:index`, so every site build's data phase) prints the log; the editor's + **Build index** job (`buildIndexAction`) streams it into the job log, which `pnpm ops build-index + --wait` follows. Nothing reads the result's field outside the tests. +- **The words are shared with the stats build** (`lib/channelMediaHold.ts`): `HELD_REASON` is a + `Record<ChannelMediaStatus, string>`, so a new status added to `inspectChannelMedia` fails tsc + until it has a reason; `isMediaHeld` treats any status but `ok` and `in-place` as held. +- **Not covered:** a drive that drops during the PROCESSING phase (after the scan), for a changed + video whose metadata was read before the drop. A transcript read that fails after it is caught + as "no cues" (`cueList = undefined`, `:838`); a sub-track read that fails is skipped, and with + none left the video's subs are removed (`subs.remove`, `:895`); a digest load that fails leaves + no digest, which is removed (`digests.remove`, `:962`/`:965`). `mtimes` is then written with the + video's current mtimes, so the loss lasts until any of its tracked mtimes (metadata, transcript, + subs, availability, digest) moves. diff --git a/plans/STATE.md b/plans/STATE.md @@ -20,13 +20,13 @@ holds the record, the review and the rollout. FACTS has "The stats cache key". step 0: it runs the source publish. - **Merge note:** `homepage/social-visible` merged `main` (`10cefd15`) at `4d11542c`; the one conflict, `homepage/CHANGELOG.md`'s `[Unreleased]`, kept both sides. -- **FOLLOW-UP, its own slice: the index build still treats an unmounted drive as an empty - channel.** It drops that channel's index records, and the next site build publishes the channel - as gone. - - The fix: give `buildIndex` the stats build's hold, or at least a refusal with an override. - - Schedule it before routine builds resume after this rollout. - - Until then, the rollout's step 3 `Diff:` check is the safeguard: thousands removed means a - drive was missing. +- **CLOSED by release 15 slice IG (branch `r15/index-hold`, [`release-15.md`](release-15.md)): + the index build no longer treats an unmounted drive as an empty channel.** It holds the channel: + not rescanned, its index records and shared pages kept, and the `Diff:` line says + ` Held: N channel(s), K video(s) kept.` A full rebuild with a channel held refuses unless + `ARCHILYZER_INDEX_ALLOW_HELD=1`. FACTS has "The index build's hold". Until that branch is merged + and rolled out, the rollout's step 3 `Diff:` check stays the safeguard: thousands removed means + a drive was missing. **Now (2026-09-28, evening): release 12 — the source mirror — is merged to `main` and NOT rolled out.** [`release-12.md`](release-12.md) holds Q's and R's records, their reviews, "Merged" and diff --git a/plans/release-15.md b/plans/release-15.md @@ -0,0 +1,219 @@ +# Release 15 — storage and build hardening + +`main` at `99d4d76a` (release 14's T1, H1 and H2 merged). No plan file of its own: each slice's +prompt carries its ruling, and this record carries what was built. Rules: +`plans/tools/implementer-rules.md`, with the commit trailer this release's prompts give. + +**The standing choices** (not re-opened): +- **An unmounted drive is not an empty channel,** for any build that walks the pool. The stats + build already holds such a channel ([`stats-cache-key.md`](stats-cache-key.md)); the index + build gets the same hold here. +- **A slice that needs another slice's file stops and says so**; it does not edit it. +- **Nothing is edited in the primary checkout**; each slice has its own worktree, and the parent + merges with `git merge --no-ff` only on a clean tree. + +## The slices + +| Slice | Branch | What | Owns | +|---|---|---|---| +| IG | `r15/index-hold` | The index build holds an unreachable channel instead of emptying it | `common/controller/buildIndex.ts` + new `buildIndex.test.ts`, `common/controller/buildStats.ts` (the hold's words move to a shared module), new `common/lib/channelMediaHold.ts`, `common/lib/envVars.ts`, `ENVIRONMENT.md`; records: `plans/{STATE,FACTS,stats-cache-key}.md` | +| DS | `r15/drive-stall` | A stalled drive does not stop the editor answering | per its prompt | +| UT | `r15/umtool-trace` | umtool's build stops tracing the whole `umtool/` folder | per its prompt | + +**Order:** IG → DS. DS adds a health gate inside `inspectChannelMedia`, which IG's hold calls +through its public signature. UT is independent. The shared files are `editor/CHANGELOG.md`'s +`[Unreleased]` and this record. + +## Record + +### Slice IG, as shipped — the index build holds an unreachable channel (2026-09-29) + +Branch `r15/index-hold` off `main` `99d4d76a`, worktree `~/Projects/r12-paths-fix` (block #12: +editor 4201, test 4211, export 4210), one Opus implementer. Scratch files `ig-*` in the job's +`tmp`. The ruling: an index build meets a channel it cannot read the way the stats build already +does. It holds the channel instead of reading it as empty, and a full rebuild with one held refuses +unless `ARCHILYZER_INDEX_ALLOW_HELD=1`. + +**What was wrong.** `scanSource` read `data/` with a bare `catch { continue }`. A relocated +channel whose drive was unmounted (a dangling `data/` link) therefore contributed no videos. The +removal pass then dropped every record the channel had, the page writers rewrote its shared +transcript tree empty and removed its subs tree, and the next site build published the channel as +gone. Only the `Diff: … -R removed` line showed it. + +- **The hold** (`common/controller/buildIndex.ts`): + - `scanSource` asks `inspectChannelMedia({ channelsDir }, slug, cfg)` for every channel that is + not excluded and not social, before it reads `data/`. + - Any status but `ok` or `in-place` holds the channel, with a reason and its storage + location's label, and no path. + - It asks again after the walk, so a drive that goes away mid-walk holds the channel instead of + dropping the videos after that point. + - A `readdir(data/)` that fails holds the channel too: `its data directory could not be read + (<code>)`. + - The exception is ENOENT on an `in-place` channel: a channel with nothing downloaded (or its + media deleted), which is emptied as before. The log now says it: `Channel <slug>: no data/ + directory; indexed as a channel with no videos.` + - A per-video metadata `stat` failing with anything but ENOENT or ENOTDIR holds the channel, + logged as `a video in its data directory could not be read (<code>)`. + - **A held channel keeps everything:** + - its `mtimes` records, since the removal pass skips its keys, and so its `sums`, `cues`, + `subs`, `digests` and `byChannel` entries; + - its shared transcript, subs and digest trees: not rewritten, not pruned, and not removed by + the top-level cleanups; + - its subs and digest stats, carried from their sub-DBs, so the per-site manifests still list + it; + - its availability states. The maybe-missing overlay skips it, since its `availability.json` + files are on the missing drive and a missing one reads as "maybe missing". The last build's + `videoState` entries for it are carried over. + - The per-site summaries are built from LMDB, so the sites built next still list its videos. + - **A curated-tag change while held:** the re-apply pass re-derives the held channel's records + in LMDB as usual, but its pages are not written. The pages-pending flag is therefore kept (and + logged) while any channel is held, and the first build with the drive back writes them. +- **A full rebuild refuses** (a schema change, or a first build with no index). + - The scan now runs BEFORE the clear, so a refusal leaves the index untouched. `scanStartedAt` + is still taken at the scan's start. + - The message names each channel with its location's label and says why a clear would publish + it as gone. It gives the ways out, mounting first (the same words as the stats build's + refusal), then the override by name and where it is set: the command's own environment for a + CLI run, and the editor's own environment (which takes a restart) for its Build index job or a + site build started from it. Their children inherit the editor's `process.env`. + - With `ARCHILYZER_INDEX_ALLOW_HELD=1` (1/true/yes/on, declared in `envVars.ts`, `ENVIRONMENT.md` + regenerated), the build proceeds. The held channel's records go with the clear; they cannot be + carried across a format change. Its shared trees are left on disk, and it is out of the index + until its media is back and an index build runs. +- **The words are shared:** new `common/lib/channelMediaHold.ts` (`isMediaHeld`, `HELD_REASON`, + `heldReason`, `describeHeld`, `HELD_WAYS_OUT`). `buildStats.ts` uses it, and its messages are + byte-identical (its case (i) passes unchanged). +- **The result and the log:** `BuildIndexResult.heldChannels`. The log carries one line per held + channel (`Channel <slug>: <why>; its N indexed video(s) are kept as they are, not rescanned, and + its transcript, subtitle and digest pages are left as they are.`). The `Diff:` line ends in + ` Held: N channel(s), K video(s) kept.` and the `Done in` line in ` Held, their media not + readable: <slugs>.` Both prefixes are unchanged: the e2e helper waits for `Done`. + +**Who reports it** (every caller of `buildIndex`): + +| Caller | What it shows | +|---|---| +| `pnpm archilyzer index` (also the root, export and homepage `build:index` scripts) | The log on stdout, with the three lines above. It exits 0 on a hold. On the refusal it exits 1 with the message on stderr (`runIfEntryPoint`). `common/bin/build-index.ts` is unchanged: it prints the log and discards the result. | +| A site build's data phase (`build:data`, from `buildSite`'s steps and `buildAll`'s Phase A in `common/publish/build.ts`) | The same lines, in the site build's job log. A refusal stops the steps at the data phase (`Build failed (exit 1)` / `Data phase failed (exit 1)`), so nothing is composed or deployed from an emptied index. The hub build does not run the index. | +| The editor's **Build index** job (`buildIndexAction`, `editor/app/sites/lib/buildAction.ts`) | The lines in the job's log on `/sites` and `/jobs`. A refusal fails the job with the message. The action discards the result, and it was left unchanged: the log already carries every held channel, and `editor/app/sites/**` belongs to another slice this release. | +| `pnpm ops build-index --wait` | Follows the job's log, so it prints the same lines. | +| The tests | `heldChannels`. | + +**Commits** + +| Commit | What | +|---|---| +| `c6ae51b0` | `plans:` this record: the header, the slices, and empty Record and Rollout sections. | +| `51328098` | `common:` the hold's words move to `lib/channelMediaHold.ts`; the stats build uses them, with its messages unchanged. | +| `ffb01d8e` | `common:` the index build's hold, the refusal and its override, `heldChannels`, the log lines; `envVars.ts` + `ENVIRONMENT.md`; new `buildIndex.test.ts` (9 cases). | +| `702cd0da` | `plans:` this section; FACTS "The index build's hold" (and the two stale statements in "The stats cache key" corrected); the STATE follow-up closed; `stats-cache-key.md` "Left" marked closed; the editor changelog. | +| `9ec48351` | `common:` review L3 + L5: one unreadable video directory is logged apart from an unreadable `data/`; the refusal says where the override is set. | +| `5af516b7` | `common(test):` review M1: case (i), the drive lost mid-walk. | +| this commit | `plans:` the review's findings to their commits; FACTS L1, L2 and the anchors; the changelog's override sentence (L5). | + +**Tests** (`common/controller/buildIndex.test.ts`, the real `buildIndex` over a temp corpus). The +drive channel is seeded with `buildStats.test.ts`'s `seedDriveChannel` shape and unmounted by +renaming its media root away. Every path is pinned under a temp root, and case (z) spies on +node:fs writes. + +| Case | What it pins | On the pre-change `buildIndex.ts` | +|---|---|---| +| (a) | Unmounted, incremental build with another change: records kept, the drive's transcript and subs trees byte-identical (manifest included), the site still lists both videos and its subs count; the log lines, with the label and no path | removed 2, not 0 | +| (b) | Availability carried: `maybe_missing` stays and a post-scan confirmation stays `available`; `videoState` unchanged | d1 no longer published | +| (c) | A full rebuild refuses (message, ways out, the variable, no path); the index and pages untouched; the CLI exits non-zero; with the override it holds (records cleared, pages kept); the drive back re-adds both | no refusal | +| (d) | A first build (no index) with a channel held refuses too | no refusal | +| (e) | The drive back: held set empty, a video added to the drive meanwhile indexed, 0 changed | removed 2 while away | +| (f) | A really empty in-place channel (an empty `data/`, and no `data/`) is emptied, not held; the missing `data/` is logged | the new log line only (the emptying matched, as it should) | +| (g) | An unreadable `data/`, and an unreadable video dir mid-walk (mode 000), hold their channels with `EACCES` | removed 3 | +| (h) | A tag rule added while held: the held pages untouched, the flag kept; the drive back writes the tag to them and clears the flag | the drive's pages emptied | +| (i) | The drive lost MID-WALK: `node:fs/promises` `stat` unmounts it right after the walk's first drive metadata stat, so every later stat in the channel is ENOENT. The second look holds the channel: 0 removed, records and pages unchanged, the log line | removed 3 of 4; the same with only the second look deleted from the new code | +| (z) | No write outside the temp root | passes on both | + +The pre-change column was run with the old `buildIndex.ts` swapped in once, with the +`heldChannels` assertions removed so each case reached its first substantive assertion. + +#### Gates (at `ffb01d8e`, and after the review at `5af516b7`; logs `$T/ig-*.log`) + +- **tsc** was clean before every commit: 78 s at the branch point, 48 s at `ffb01d8e`, 50 s at + `5af516b7`. +- **Unit:** + + | Suite | Result | + |---|---| + | common | 2,219/2,219 at `ffb01d8e` (the branch point's 2,210 plus the 9 new cases), 77 s; **2,220/2,220** at `5af516b7` (case (i) added), 78 s | + | editor unit | 87/87 | + | `test:scripts` | 191 passed, 1 skipped (192) | + | mcp | 271/271 | + +- **Docs:** `docs env --check`, `docs files --check` and `settings example --check` all exit **0**, + at both points. +- **Build:** the editor's `next build`, with the primary's `transcripts/` linked in and capped at + 5 GB with no swap: 64 s, max RSS 1,642 MB. The link was removed after the build, and nothing + ran through it. +- **e2e** (editor, detached and queued; the spec list is every spec that runs Build index: + `availability`, `build`, `channel-build-toggle`, `chat-only`, `duplicate-shorts`, `jobs`, + `regional-vtt-fallback`, `tags`, passed as `e2e/<name>.spec.ts` so `availability` does not also + match `pre-clean-availability`): **35 passed, 0 failed, 3.6 min**, after 1 min 45 s in the + queue. No e2e fixture has an unreachable channel, so these confirm the hold changes nothing for a + readable corpus. Not rerun after the review: its two log-wording changes touch no spec (`git grep + "could not be read" editor/e2e` finds only the curated-tag preview and the title filter). +- **Numbers tool:** none. + +#### Found and left + +- **A drive that drops during the processing phase** (after the scan) is not covered, for a changed + video whose metadata was read before the drop. Its transcript read is caught as "no cues", so its + cues are removed. A failed sub-track read is skipped, and with none left its subs are removed. A + failed digest load leaves no digest, which is removed. `mtimes` is then written with the video's + current mtimes, so the loss lasts until any of its tracked mtimes (metadata, transcript, subs, + availability, digest) moves. These are per-video reads inside the worker, left to the slice that + handles drive stalls. +- **A drive that drops and comes back inside one walk** is not covered either: the second look + finds it, and the videos skipped in between are removed. +- **`inspectChannelMedia` is asked twice per channel** (before and after the walk), three syscalls + each today. Slice DS puts a health gate inside it, and that gate runs twice per channel per + index build. +- **Under the override,** a held channel is listed on its sites with 0 videos, and its subs and + digest counts are left out of the site manifests. Its old shared page trees stay on disk, and a + compose copies them. +- **While a channel is held after a tag change,** the pages-pending flag stays set. Every build + until the drive is back is then a full page walk; it skips unchanged pages by hash, so it rewrites + none. +- **The digest tree's retention has no test.** The code path mirrors the subs tree's, and no + fixture carries a digest sidecar. +- **The editor shows a hold only in the job log.** A `/sites` badge would be in `editor/app/sites/**`. + +#### Decisions the operator could overturn + +| What I assumed | The alternative | +|---|---| +| A held channel's shared pages are not written at all. **Ruled at review: keep the skip.** | Rewrite them from the kept records: byte-identical on an incremental build, and a tag change would reach them at once. After an override rebuild the records are gone, and a rewrite would publish the channel empty. | +| Under the override, the held channel's records go with the clear. | Carry them across the clear. A schema change means the stored format moved, so the old records cannot be trusted. | +| An unreadable `data/`, or a per-video `stat` failing with anything but ENOENT, holds the channel. | Hold only for the statuses `inspectChannelMedia` reports, and keep treating other read errors as "no videos", as the old code did. | +| A channel with no `data/` is logged, one line per build. | Stay silent, as before; the ruling asked for a log. | +| The CLI exits 0 on a hold, since the hold is the safe outcome; the refusal exits 1. **Ruled at review: both stay.** | Exit non-zero so scripts notice; a site build's data phase would then fail whenever a drive is out. | +| The words live in a new `lib/channelMediaHold.ts` shared with the stats build. | Duplicate them in `buildIndex.ts` and leave `buildStats.ts` untouched. | + +#### Review + +**Verdict: SHIP AFTER FIXES** (`ig-review.md` in the job's scratch). No High. Every write path a +held channel could reach was traced, and the refusal fires before anything is deleted. + +| Finding | Where | +|---|---| +| M1: the second look after the walk had no test | `5af516b7`: case (i). It fails with 3 of 4 removed when that look is deleted. | +| L1: FACTS said an unreachable drive reaches `notIndexable` only through the override | this commit: a video that reached the drive after the last index build that could read it is counted there by a stats-only run between the drive's return and the next index build, which heals it. | +| L2: the processing-phase gap also loses subs and digests, until any tracked mtime moves | this commit, in "Found and left" and FACTS. | +| L3: one unreadable video dir was logged as the whole data directory | `9ec48351`: `a video in its data directory could not be read (<code>)`; case (g) expects it. | +| L4 (optional): a narrower `HELD_REASON` type | **Left**, as the review allowed. The current contract already fails tsc on a new status. | +| L5: the refusal did not say where the override is set | `9ec48351` (message, case (c)) and this commit (changelog). | +| L6: check the held set before routine builds resume | A rollout note; the parent records it. | +| L7: stale trees under the override | Already in "Found and left". | +| Q2: the commit trailer | Ruled correct. | + +**What runs which code, for the rollout.** Every CLI command and every spawned data phase runs the +checkout's code, so they hold from the moment `main` has this branch. The editor's in-process +**Build index** button runs its built bundle, so it holds only after the editor is rebuilt and +restarted. + +## Rollout diff --git a/plans/stats-cache-key.md b/plans/stats-cache-key.md @@ -273,6 +273,8 @@ PATH, so it is `pnpm archilyzer …`. `mtimes`, cues and pages), or at least a refusal with an override. - When: schedule it before routine builds resume after this rollout. - Until then, the rollout's step 3 `Diff:` check is the safeguard. + - **Closed by release 15 slice IG** ([`release-15.md`](release-15.md), "Slice IG, as shipped"): + the hold, and a refusal with an override for a full rebuild. - **A cross-process lock for builds** (see "Concurrent stats builds" above). The rule stands in for it. - **O5:** a manual English caption (no inline timing tags) indexes as 0 cues (FACTS).