commit 8a899cb0e912dbbf5b03b01d728e69875b5c4ce8
parent d67b0260342bfda425cda30fe61ee3f88ed8bfe4
Author: I Mean I'm Just Saying <imeanimjustsaying@kiwifarms.st>
Date: Thu, 19 Nov 2026 13:42:39 -0500
index: a record no longer public carries its state and the day it was first seen
A transcript shard record whose source is members-only, private, deleted or
unlisted at its platform now carries `state` and `stateSince` (YYYYMMDD, the
day the archive first saw that state: the start of the trailing run of
availability history that agrees with it). Summaries and subs carry
`stateSince` beside their `state`. Every other record's bytes are unchanged;
"maybe missing" stays a summaries-only suspicion. The MtimeRecord caches the
day, and the first build after this re-reads only the records with a cached
non-available state and no day (STATE_SINCE_VERSION 1). corpus.json's shard
scheme documents both keys; per-record and additive, so no spec bump.
Co-Authored-By: Claude <noreply@anthropic.com>
Diffstat:
5 files changed, 174 insertions(+), 24 deletions(-)
diff --git a/common/controller/buildIndex.test.ts b/common/controller/buildIndex.test.ts
@@ -801,6 +801,61 @@ test("(l) release 17: a tiered raw live chat that cannot be read, with no cues t
assert.equal((await runIndex()).res.changed, 0);
});
+test("(m) lane missing-source: a record no longer public carries its state and the day it was first seen", async () => {
+ resetCorpus([CHANNEL]);
+ seedVideo("m1");
+ seedVideo("p1");
+ seedVideo("u1");
+ writeJson(path.join(videoDir("m1"), "availability.json"), {
+ checkedAt: "2026-01-09T08:00:00.000Z",
+ checkedBy: "fetch",
+ availability: "members_only",
+ history: [
+ { availability: "public", observedAt: "2026-01-01T08:00:00.000Z", source: "backfill" },
+ { availability: "members_only", observedAt: "2026-01-05T23:30:00.000Z", source: "fetch" },
+ ],
+ });
+ // u1 fell out of the listing and was never confirmed: a suspicion, summaries only.
+ writeJson(path.join(paths.channelsDir, CHANNEL, "maybe-missing.json"), {
+ checkedAt: "2026-01-08T12:00:00.000Z",
+ freshPlaylistCount: 0,
+ ids: ["u1"],
+ });
+ await runIndex();
+ const m1 = transcriptRecord("m1", CHANNEL) as Published & { stateSince?: string };
+ assert.equal(m1.state, "members_only");
+ assert.equal(m1.stateSince, "20260105");
+ for (const id of ["p1", "u1"]) {
+ const r = transcriptRecord(id, CHANNEL) as Record<string, unknown>;
+ assert.ok(!("state" in r) && !("stateSince" in r), `${id}'s shard record has no state keys`);
+ }
+ const sm = summaries().find((s) => s.id === "m1") as Published & { stateSince?: string };
+ assert.equal(sm.state, "members_only");
+ assert.equal(sm.stateSince, "20260105");
+ const su = summaries().find((s) => s.id === "u1") as Record<string, unknown>;
+ assert.equal(su.state, "maybe_missing");
+ assert.ok(!("stateSince" in su));
+
+ // An index built before the day was cached: the record re-read once, and its
+ // shard gains the day; the version recorded, so the next build re-reads none.
+ withIndex((db) => {
+ const mt = db("mtimes");
+ for (const { key, value } of [...mt.getRange()]) {
+ const rec = value as Record<string, unknown>;
+ if (!rec.availabilityDay) continue;
+ delete rec.availabilityDay;
+ mt.putSync(key, rec);
+ }
+ db("meta").removeSync("stateSince");
+ });
+ rmSync(path.join(paths.exportSharedTranscriptsDir, CHANNEL), { recursive: true, force: true });
+ const { log } = await runIndex();
+ assert.ok(log.some((l) => /State since v1: 1 record\(s\) re-read\./.test(l)), log.join("\n"));
+ assert.equal((transcriptRecord("m1", CHANNEL) as Published & { stateSince?: string }).stateSince, "20260105");
+ const again = await runIndex();
+ assert.ok(!again.log.some((l) => /State since v1/.test(l)));
+});
+
test("(z) no write this file caused landed outside its temp root", () => {
// LMDB writes natively, past the spy: its file must be under the root too.
assert.ok(paths.lmdbPath.startsWith(ROOT + path.sep), paths.lmdbPath);
diff --git a/common/controller/buildIndex.ts b/common/controller/buildIndex.ts
@@ -121,7 +121,7 @@ import {
type SubTrack,
} from "../lib/videoStatus";
import {
- resolveEffectiveAvailability,
+ resolveEffectiveAvailabilityObserved,
resolveMaybeMissingState,
} from "../lib/availability-server";
import {
@@ -261,6 +261,23 @@ function storedCuesEmpty(db: { getBinaryFast(key: IndexKey): Buffer | undefined
const ALT_TRACKS_VERSION = 1;
const ALT_TRACKS_KEY = "altTracks";
+// THE DAY A STATE WAS FIRST SEEN (lane missing-source): an MtimeRecord now
+// carries `availabilityDay` beside a non-available `availability`, and the
+// transcript pages carry `state` + `stateSince` on such a record. The first
+// build that sees a new STATE_SINCE_VERSION re-derives every record whose
+// cached state is not "available" and that has no day yet — sparse by
+// construction — then records the version, only when no channel is held.
+const STATE_SINCE_VERSION = 1;
+const STATE_SINCE_KEY = "stateSince";
+
+// An ISO instant as the YYYYMMDD day of uploadDate's shape (UTC), or undefined.
+function isoDay(iso: string | null | undefined): string | undefined {
+ if (!iso) return undefined;
+ const ms = Date.parse(iso);
+ if (!Number.isFinite(ms)) return undefined;
+ return new Date(ms).toISOString().slice(0, 10).replace(/-/g, "");
+}
+
// Whether a scanned record can hold an alternate track at all — no file read.
function canHoldAltTracks(s: {
transcriptKind: IndexTranscript["kind"] | null;
@@ -336,6 +353,9 @@ type MtimeRecord = {
// availabilityMs already participates in change detection, so any video whose
// availability.json is rewritten from here on picks up the exact string.
availability?: Availability;
+ // The day (YYYYMMDD) the archive first saw `availability`, written only when
+ // it is not an "available" state (lane missing-source; STATE_SINCE_VERSION).
+ availabilityDay?: string;
isDeleted: boolean;
isUnlisted: boolean;
indexKey: IndexKey;
@@ -974,6 +994,24 @@ export async function buildIndex({
}
log(`Alternate tracks v${ALT_TRACKS_VERSION}: ${reread} record(s) re-read.`);
}
+
+ // Records whose cached state is not "available" and carries no day yet
+ // (STATE_SINCE_KEY). A schema bump re-reads everything anyway.
+ const stateSinceDue = meta.get(STATE_SINCE_KEY) !== STATE_SINCE_VERSION;
+ if (stateSinceDue && !schemaBumped) {
+ const queued = new Set(
+ [...added, ...changed].map((s) => pathKeyId([s.channelSlug, s.videoDir])),
+ );
+ let reread = 0;
+ for (const s of live) {
+ const pk: PathKey = [s.channelSlug, s.videoDir];
+ const prev = mtimes.get(pk);
+ if (!prev || prev.availabilityDay || stateFromRecord(prev) === "available") continue;
+ reread++;
+ if (!queued.has(pathKeyId(pk))) changed.push(s);
+ }
+ log(`State since v${STATE_SINCE_VERSION}: ${reread} record(s) re-read.`);
+ }
let altTrackRecords = 0;
// RECORDED DATES (release 20 D1, lib/recordedDate.ts): each channel's rule,
@@ -1360,9 +1398,13 @@ export async function buildIndex({
// to notice. Same source buildStats' status chart used to read
// directly, so the two can't disagree.
let availability: Availability | undefined;
+ let availabilityDay: string | undefined;
if (s.availabilityMs !== null) {
- availability =
- (await resolveEffectiveAvailability(videoFullDir)) ?? undefined;
+ const observed = await resolveEffectiveAvailabilityObserved(videoFullDir);
+ availability = observed?.availability;
+ if (availability && stateFromAvailability(availability) !== "available") {
+ availabilityDay = isoDay(observed?.observedAt);
+ }
}
byChannel.put(indexToChannelKey(indexKey), 1);
@@ -1373,6 +1415,7 @@ export async function buildIndex({
availabilityMs: s.availabilityMs,
digestMs: s.digestMs,
...(availability ? { availability } : {}),
+ ...(availabilityDay ? { availabilityDay } : {}),
isDeleted: availability === "deleted",
isUnlisted: availability === "unlisted",
indexKey,
@@ -1596,6 +1639,38 @@ export async function buildIndex({
return { push, finish };
};
+ // The CONFIRMED states, out of MtimeRecord — which caches the availability
+ // check done at mutation-processing time — read before the transcript pages
+ // so a record whose source is no longer as it was carries its `state` and
+ // `stateSince` on its shard (lane missing-source). Previously this loop read
+ // availability.json for every video on every build (~28k sequential disk
+ // reads), which stalled GC right before the heaviest phase.
+ //
+ // All three maps are SPARSE: only non-`available` videos get an entry, so the
+ // common case costs nothing. stateByPath is the same data keyed the way
+ // buildStats needs it (see the videoState sub-DB written below); the
+ // maybe-missing overlay further down adds to the first two, never to the shards.
+ const stateByIndexKey = new Map<string, VideoState>();
+ const stateByPath = new Map<string, VideoState>();
+ const stateSinceByIndexKey = new Map<string, string>();
+ for (const { key, value } of mtimes.getRange()) {
+ const rec = value as MtimeRecord;
+ const st = stateFromRecord(rec);
+ if (st === "available") continue;
+ const ikId = indexKeyId(rec.indexKey);
+ stateByIndexKey.set(ikId, st);
+ stateByPath.set(pathKeyId(key as PathKey), st);
+ if (rec.availabilityDay) stateSinceByIndexKey.set(ikId, rec.availabilityDay);
+ }
+ // What a transcript record carries: a confirmed state and its day, or nothing.
+ const shardStateOf = (indexKey: IndexKey): Pick<TranscriptDetail, "state" | "stateSince"> => {
+ const ikId = indexKeyId(indexKey);
+ const st = stateByIndexKey.get(ikId);
+ if (!st || st === "available" || st === "maybe_missing") return {};
+ const since = stateSinceByIndexKey.get(ikId);
+ return { state: st, ...(since ? { stateSince: since } : {}) };
+ };
+
if (sharedNeedsBuild) {
// One channel's transcript tree into `channelDir`. The SHARED tree (what every
// site copies) leaves local recordings out; a channel that holds one also
@@ -1643,6 +1718,9 @@ export async function buildIndex({
const detail: TranscriptDetail = {
...summary,
cues: cueList,
+ // Only on a record whose source is no longer as it was (lane
+ // missing-source); every other record's bytes are what they were.
+ ...shardStateOf(indexKey),
...(trackFields?.altTracks?.length
? { track: trackFields.track, altTracks: trackFields.altTracks }
: {}),
@@ -1742,23 +1820,8 @@ export async function buildIndex({
log(`Shared transcript pages up to date; skipping rewrite.`);
}
- // Build lookups from indexKey → VideoState out of MtimeRecord, which caches
- // the availability check done at mutation-processing time. Previously this
- // loop read availability.json for every video on every build (~28k sequential
- // disk reads), which stalled GC right before the heaviest phase.
- //
- // Both maps are SPARSE: only non-`available` videos get an entry, so the
- // common case costs nothing. stateByPath is the same data keyed the way
- // buildStats needs it (see the videoState sub-DB written below).
- const stateByIndexKey = new Map<string, VideoState>();
- const stateByPath = new Map<string, VideoState>();
- for (const { key, value } of mtimes.getRange()) {
- const rec = value as MtimeRecord;
- const st = stateFromRecord(rec);
- if (st === "available") continue;
- stateByIndexKey.set(indexKeyId(rec.indexKey), st);
- stateByPath.set(pathKeyId(key as PathKey), st);
- }
+ // The confirmed states were read out of MtimeRecord above, before the
+ // transcript pages (`stateByIndexKey`, `stateByPath`, `stateSinceByIndexKey`).
// Overlay the channel-level quick availability check. Computed here rather
// than in the per-video loop above on purpose: maybe-missing.json is a
@@ -1884,6 +1947,7 @@ export async function buildIndex({
if (isLocalRecord(summary)) continue;
const display = toDisplaySummary(summary, {
state: stateByIndexKey.get(indexKeyId(indexKey)),
+ stateSince: stateSinceByIndexKey.get(indexKeyId(indexKey)),
});
const tracks: Record<string, Cue[]> = {};
let hasLiveChat = false;
@@ -2534,7 +2598,10 @@ export async function buildIndex({
if (acc) acc.count++;
tagCounter.add(ik[1], s.curatedTags);
buffer.push(
- toDisplaySummary(s, { state: stateByIndexKey.get(indexKeyId(ik)) }),
+ toDisplaySummary(s, {
+ state: stateByIndexKey.get(indexKeyId(ik)),
+ stateSince: stateSinceByIndexKey.get(indexKeyId(ik)),
+ }),
);
total++;
if (buffer.length >= pageSize) await flushPage();
@@ -2711,6 +2778,9 @@ export async function buildIndex({
if (altTracksDue && held.size === 0) {
await meta.put(ALT_TRACKS_KEY, ALT_TRACKS_VERSION);
}
+ if (stateSinceDue && held.size === 0) {
+ await meta.put(STATE_SINCE_KEY, STATE_SINCE_VERSION);
+ }
for (const slug of recordedDateRuleChanged) {
const rule = channelConfigs.get(slug)?.recordedDate;
const key = `${RECORDED_DATE_RULE_KEY_PREFIX}${slug}`;
diff --git a/common/lib/corpus.ts b/common/lib/corpus.ts
@@ -52,6 +52,11 @@ import {
// older archive falls back to a shard record's `webpageUrl` / `platform`
// (common/lib/remoteArchives-server.ts channelFactsOf).
//
+// NOT a v7: `state` / `stateSince` on a transcript shard record and
+// `stateSince` on a summary (lane missing-source) are per-record keys, additive,
+// documented in SHARD_SCHEME below — an older reader ignores them, as it always
+// has, and no new document can be fetched.
+//
// NOT a v4: the `generator` field added below is deliberately unversioned. Every
// prior bump announced a new FETCHABLE LAYER — a reader that ignored it would
// miss data it could otherwise have retrieved. `generator` is an informational
@@ -93,11 +98,16 @@ const SHARD_SCHEME = {
"duration, channel, description, tags, webpageUrl, platform, cues: [{ start, end, text }] }; " +
"a record with other English caption tracks whose words differ from its transcript " +
"also carries `track` (the transcript's track id, e.g. \"en-orig\") and " +
- "`altTracks: [{ track, cues }]` (e.g. \"en\", the uploaded captions) — absent otherwise",
+ "`altTracks: [{ track, cues }]` (e.g. \"en\", the uploaded captions) — absent otherwise; " +
+ "a record whose source is no longer as it was at its platform carries `state` " +
+ "(\"members_only\", \"private\", \"deleted\" or \"unlisted\") and `stateSince` " +
+ "(YYYYMMDD, the day the archive first saw it) — absent for a video still public there",
subsManifest:
"<channel.manifests.subs> -> lighter list-view records under the same slugToPage scheme",
summariesIndex:
- "/summaries/manifest.json + /summaries/page-<NNNN>.json -> cross-channel browse index",
+ "/summaries/manifest.json + /summaries/page-<NNNN>.json -> cross-channel browse index; " +
+ "a record carries `state` (also \"maybe_missing\": gone from its channel's listing, " +
+ "unconfirmed) and, for a confirmed state, `stateSince` — both absent when available",
pageNumberFormat: "zero-padded to 4 digits, e.g. page 0 -> page-0000.json",
} as const;
diff --git a/common/lib/transcripts-server.ts b/common/lib/transcripts-server.ts
@@ -279,7 +279,7 @@ export function summarizeStats(
export function toDisplaySummary(
t: TranscriptSummary,
- extras: { state?: VideoState } = {},
+ extras: { state?: VideoState; stateSince?: string } = {},
): DisplaySummary {
const state = extras.state ?? "available";
return {
@@ -303,6 +303,8 @@ export function toDisplaySummary(
// (writeJsonAtomic), so the beneficiaries are the subs page hashes in
// createPageWriter and the compose-site dirSignature reconcile.
...(state === "available" ? {} : { state }),
+ // The day it was first seen, only beside a state (lane missing-source).
+ ...(state !== "available" && extras.stateSince ? { stateSince: extras.stateSince } : {}),
platform: t.platform,
webpageUrl: t.webpageUrl,
// Curated tags ride through to the browse index, so a list can be narrowed
diff --git a/common/lib/transcripts.ts b/common/lib/transcripts.ts
@@ -73,6 +73,11 @@ export type DisplaySummary = {
// available), so a page with no missing videos stays byte-identical to the
// one already on disk and the build's downstream hashing still short-circuits.
state?: VideoState;
+ // THE DAY THE ARCHIVE FIRST SAW `state` (YYYYMMDD, the shape of uploadDate) —
+ // lane missing-source. Present only beside a confirmed state the archive can
+ // date; absent for "available" and for an unconfirmed "maybe missing". A day,
+ // never who saw it or how.
+ stateSince?: string;
platform: Platform;
webpageUrl: string;
// Curated tag ids (common/lib/curatedTags.ts) — the operator's cross-channel
@@ -85,8 +90,16 @@ export type DisplaySummary = {
// `track` / `altTracks` (lib/captionTracks.ts): the primary's track id and the
// other English tracks whose words differ from it — present only on a record
// that has such a track.
+//
+// `state` / `stateSince` (lane missing-source): the record's source is no
+// longer as it was at its platform — members-only, private, deleted or
+// unlisted — and the day the archive first saw it. Present ONLY on such a
+// record (a confirmed state; "maybe missing" stays a summaries-only suspicion),
+// so every other record's page bytes are what they were.
export type TranscriptDetail = TranscriptSummary & {
cues: Cue[] | undefined;
+ state?: Exclude<VideoState, "available" | "maybe_missing">;
+ stateSince?: string;
} & TrackFields;
export type TranscriptPage = TranscriptDetail[];