diff --git a/src/notice-store.ts b/src/notice-store.ts index db62b04e5c..566368e36f 100644 --- a/src/notice-store.ts +++ b/src/notice-store.ts @@ -46,6 +46,10 @@ const DISMISS_FILE = "upgrade-notices.json"; let cache: Map | null = null; let hydrating = false; +// #5761: independent of the lazy cache — cache !== null only means "some +// dismissal touched this process", NOT "hydration completed". Bailing on it +// (the old gate) let one pre-hydration receipt block the migration forever. +let hydrated = false; let warned = false; function warnOnce(tag: string, err: unknown): void { @@ -94,39 +98,49 @@ export function dismissedCache(): ReadonlySet | null { /** Once per process (wired at cli start): load kv rows + import the legacy * file one time. Legacy-only instances keep the pure-file path forever - * (cache intentionally left null). Never throws. */ + * (cache intentionally left null). Never throws. + * #5761 (twin of the #5757 host-plugin fix): UNION into whatever cache a + * pre-hydration dismissal already lazily created instead of bailing — that + * early receipt used to block both the one-time file→kv migration and every + * sibling lane's rows for the whole process lifetime. */ export async function hydrateNoticeReceipts(): Promise { - if (cache !== null || hydrating || !unifiedReceiptsActive()) return; + if (hydrated || hydrating || !unifiedReceiptsActive()) return; hydrating = true; - const merged = new Map(); const now = Date.now(); - let importedFromFile = 0; try { const dbRows = await getStore().listKvAsync(NS); - for (const r of dbRows) merged.set(r.key, r.updatedAt); - for (const k of fileKeysOf(process.env)) { - if (!merged.has(k)) { - merged.set(k, now); - importedFromFile += 1; + const rowKeys = new Set(dbRows.map((r) => r.key)); + // One-time migration: every file key not yet in kv goes into kv + // (best-effort, no format policing — the API path validates, the file + // may not). The view below unions file keys directly, so each is honored + // in-process whether or not its kv write landed. + const fileKeys = fileKeysOf(process.env); + const toImport = [...fileKeys].filter((k) => !rowKeys.has(k)); + for (const k of toImport) { + try { + await getStore().setKvAsync(NS, k, { at: now }); + } catch (err) { + warnOnce("migrate", err); + break; } } - if (importedFromFile > 0) { - for (const [k] of merged) { - if (![...dbRows].some((r) => r.key === k)) { - try { - await getStore().setKvAsync(NS, k, { at: now }); - } catch (err) { - warnOnce("migrate", err); - break; - } - } - } - loggerLog("info", `[notices] imported ${importedFromFile} receipt(s) from the legacy JSON file into unified storage (kv_store namespace "notices")`); + if (toImport.length > 0) { + loggerLog("info", `[notices] imported ${toImport.length} receipt(s) from the legacy JSON file into unified storage (kv_store namespace "notices")`); + } + // Snapshot the LIVE view only now: nothing awaits between here and the + // publish below, so a dismissal landing any time up to this point + // (pre-hydration lazy adoption included) survives the final + // assignment instead of being clobbered until restart. + const merged = new Map(cache ?? []); + for (const r of dbRows) merged.set(r.key, r.updatedAt); + for (const k of fileKeys) { + if (!merged.has(k)) merged.set(k, now); } + cache = merged; + hydrated = true; } catch (err) { warnOnce("hydrate", err); } - cache = merged; hydrating = false; } @@ -171,5 +185,6 @@ export function persistDismissedKey(key: string): void { export function _resetNoticeReceiptsForTest(): void { cache = null; hydrating = false; + hydrated = false; warned = false; } diff --git a/src/storage/mysql.ts b/src/storage/mysql.ts index 2648a74087..9bdf82b33f 100644 --- a/src/storage/mysql.ts +++ b/src/storage/mysql.ts @@ -40,6 +40,7 @@ import { mkdirSync, appendFileSync, readFileSync, existsSync } from "node:fs"; import { join } from "node:path"; import { log as loggerLog } from "../logger.js"; import { sha256Hex, rewriteArchiveLog, validateExtKey, serializeExtValue } from "./store.js"; +import { StorageSchemaFloorError } from "./schema.js"; import { identityOfStoredContent } from "./identity.js"; import type { MessageContentStore } from "acp-kernel"; import type { StorageBackend, StorageReadView } from "./backend.js"; @@ -75,6 +76,15 @@ export type Mysql2Module = typeof import("mysql2/promise"); * DDL. */ const MYSQL_SCHEMA_VERSION = 11; +/** #5788: parity with STORAGE_MIN_READER_VERSION (src/storage/schema.ts) — + * the oldest schema version this build can still read. v8 is the only + * non-additive migration (identity backfill, #4390/#4677); v9/v10/v11 are + * additive and do not raise it. Persisted per library (bili_meta key + * "schema_reader_floor") so an older build opening a library a newer + * build migrated can REFUSE instead of silently writing rows it cannot + * read back (rolling upgrade / rollback). */ +const MYSQL_MIN_READER_VERSION = 8; + /** Parity constants with the sqlite v8 streaming backfill * (src/storage/schema.ts, #4677): same page size, same printable absent * marker. The printable form exists because node:sqlite truncates bound @@ -321,7 +331,28 @@ export class MysqlBackend implements StorageBackend { const rawStamp = (metaRows[0] as Row | undefined)?.meta_value; const parsedStamp = Number(rawStamp); const current = Number.isFinite(parsedStamp) ? parsedStamp : 0; - if (current < MYSQL_SCHEMA_VERSION) { + // #5788: reader floor gate — a library stamped by a NEWER build + // whose non-additive migration floor is above this build's + // schema version cannot be read by this build. Refuse (same + // bucket as CANTOPEN/readonly — the data is not corrupt, it is + // newer; degrading or writing would let the newer build's rows + // lose their semantics). A missing floor row (pre-feature + // library) is UNKNOWN, not "too new" — it passes, so existing + // libraries never false-refuse. Math: floor ≤ the build that + // wrote it stamped schema_version, so floor > runningVersion + // implies the stamp is above runningVersion; the explicit stamp + // check documents the intent. + const [floorRows] = (await conn.query( + "SELECT meta_value FROM bili_meta WHERE meta_key = 'schema_reader_floor'", + )) as unknown as Row[][]; + const rawFloor = (floorRows[0] as Row | undefined)?.meta_value; + const parsedFloor = Number(rawFloor); + const floor = Number.isFinite(parsedFloor) ? parsedFloor : 0; + if (current > MYSQL_SCHEMA_VERSION && floor > MYSQL_SCHEMA_VERSION) { + throw new StorageSchemaFloorError(floor, MYSQL_SCHEMA_VERSION); + } + const migrated = current < MYSQL_SCHEMA_VERSION; + if (migrated) { // #4390 v8: position-independent identity + historian // tombstones. CREATE TABLE IF NOT EXISTS does not upgrade an // existing v7 table — probe information_schema and ALTER @@ -390,13 +421,40 @@ export class MysqlBackend implements StorageBackend { // from the committed sessions on the next boot. await this.migrateV8Identities(); } - // Stamp advances but never downgrades: a future library stamped - // higher than this build keeps its stamp. - await conn.query( - "INSERT INTO bili_meta (meta_key, meta_value) VALUES ('schema_version', ?) " + - "ON DUPLICATE KEY UPDATE meta_value = GREATEST(CAST(meta_value AS UNSIGNED), CAST(? AS UNSIGNED))", - [String(MYSQL_SCHEMA_VERSION), String(MYSQL_SCHEMA_VERSION)], - ); + // #5788: stamp the schema version AND (when a migration just + // ran) the reader floor in ONE transaction — a crash between + // the two statements would leave a torn pair. The gate reads + // the floor only when the stamp is already above this build, + // so a torn pair (floor committed, stamp not yet advanced) + // would under-report the floor and let a too-old build in. + // The floor row is written only when a migration ran (parity + // with sqlite's migrateSchema): a pre-feature library already + // at this build's version keeps "unknown" and passes the gate. + await conn.beginTransaction(); + try { + // Stamp advances but never downgrades: a future library + // stamped higher than this build keeps its stamp. + await conn.query( + "INSERT INTO bili_meta (meta_key, meta_value) VALUES ('schema_version', ?) " + + "ON DUPLICATE KEY UPDATE meta_value = GREATEST(CAST(meta_value AS UNSIGNED), CAST(? AS UNSIGNED))", + [String(MYSQL_SCHEMA_VERSION), String(MYSQL_SCHEMA_VERSION)], + ); + if (migrated) { + await conn.query( + "INSERT INTO bili_meta (meta_key, meta_value) VALUES ('schema_reader_floor', ?) " + + "ON DUPLICATE KEY UPDATE meta_value = GREATEST(CAST(meta_value AS UNSIGNED), CAST(? AS UNSIGNED))", + [String(MYSQL_MIN_READER_VERSION), String(MYSQL_MIN_READER_VERSION)], + ); + } + await conn.commit(); + } catch (err) { + try { + await conn.rollback(); + } catch { + /* connection-level failure — the rethrow below propagates */ + } + throw err; + } } finally { conn.release(); } diff --git a/src/storage/schema.ts b/src/storage/schema.ts index 5efaae598c..f8e837ce9f 100644 --- a/src/storage/schema.ts +++ b/src/storage/schema.ts @@ -85,6 +85,35 @@ // older build opening a v11 file ignores the extra indexes. export const STORAGE_SCHEMA_VERSION = 11; +/** #5788: the oldest schema version this build can still READ. Every + * NON-ADDITIVE migration (one that changes the meaning of existing rows, + * not just adds columns/indexes) MUST raise this constant in the same + * commit — v8 is the only one so far (position-independent identity + * backfill, #4390/#4677: a pre-v8 build writing into a v8 store would + * emit rows with no identity and corrupt the cross-save JOIN key). v9/ + * v10/v11 are additive (indexes / nullable columns) and do NOT raise it. + * Persisted per store (kv_store namespace "storage", key + * "schema_reader_floor") so an older build opening a store a newer build + * migrated can REFUSE instead of silently writing rows it cannot read + * back — the rolling upgrade / rollback case (#5082 shared-index + * topology). A test pins floor ≤ STORAGE_SCHEMA_VERSION. */ +export const STORAGE_MIN_READER_VERSION = 8; + +/** #5788: the store's persisted reader floor is above this build's schema + * version — a NEWER build applied a non-additive migration this build + * cannot read. The file is NOT corrupt (it is simply newer than this + * build), so this is a startup refusal in the CANTOPEN/readonly bucket + * (handled in shadow.ts), not a StorageIntegrityError: degrading to the + * legacy path or writing into the store would let the newer build's rows + * lose their semantics. Remediation: upgrade bili, or restore a + * pre-upgrade index.db{,-wal,-shm} backup. */ +export class StorageSchemaFloorError extends Error { + constructor(public readonly storedFloor: number, public readonly runningVersion: number) { + super(`[storage] schema reader floor ${storedFloor} is above this build's schema version ${runningVersion} — the store was migrated by a newer bili with a non-additive change this build cannot read; upgrade bili, or restore a pre-upgrade index.db{,-wal,-shm} backup, before starting`); + this.name = "StorageSchemaFloorError"; + } +} + /** #3250: cap for `journal_size_limit` (see STORAGE_PRAGMAS). Passive and * auto checkpoints move frames into the main db and reset the write offset * but NEVER shrink the WAL file — without this limit a long-lived process's @@ -311,15 +340,59 @@ CREATE INDEX IF NOT EXISTS idx_message_media_media_hash ON message_media(media_h CREATE INDEX IF NOT EXISTS idx_checkpoints_state_hash ON checkpoints(state_hash); `; -/** Applied inside one transaction whenever user_version < STORAGE_SCHEMA_VERSION. */ -export function migrateSchema(db: { +/** The structural surface migrateSchema needs from a SQLite handle — + * satisfied by both node:sqlite and better-sqlite3 (and test fakes). */ +type SchemaDb = { exec(sql: string): void; prepare(sql: string): { get(...a: unknown[]): unknown; all(...a: unknown[]): unknown[]; run(...a: unknown[]): unknown }; transaction(fn: () => T): T; -}): { from: number; to: number } { +}; + +/** #5788: read the persisted reader floor (kv_store namespace "storage", + * key "schema_reader_floor") and refuse when it is above this build's + * schema version. A MISSING row (pre-feature store) is UNKNOWN, not + * "too new" — it passes, so existing stores never false-refuse. A + * MALFORMED value passes too: a false refusal would make an existing + * store unopenable, while a false pass degrades to today's (ungated) + * behavior. Math: floor ≤ the build that wrote it stamped user_version, + * so floor > runningVersion implies the stamp is above runningVersion — + * one check suffices, and it only ever runs in the from >= + * STORAGE_SCHEMA_VERSION branch (where kv_store is guaranteed to exist). */ +function enforceReaderFloor(db: SchemaDb): void { + let row: { value_json: string } | undefined; + try { + row = db.prepare( + "SELECT value_json FROM kv_store WHERE namespace = 'storage' AND key = 'schema_reader_floor'", + ).get() as { value_json: string } | undefined; + } catch { + // kv_store unreadable (a corrupt store missing the table) — treat as + // unknown and pass: the gate must never introduce a NEW fail-at-open + // path, so a store that opened before this feature still opens (it + // fails later on its first real kv op, as it did before). + return; + } + if (row === undefined) return; + let floor: unknown; + try { + floor = JSON.parse(row.value_json); + } catch { + return; + } + if (typeof floor !== "number" || !Number.isInteger(floor)) return; + if (floor > STORAGE_SCHEMA_VERSION) throw new StorageSchemaFloorError(floor, STORAGE_SCHEMA_VERSION); +} + +/** Applied inside one transaction whenever user_version < STORAGE_SCHEMA_VERSION. */ +export function migrateSchema(db: SchemaDb): { from: number; to: number } { const row = db.prepare("PRAGMA user_version").get() as { user_version: number } | undefined; const from = row?.user_version ?? 0; - if (from >= STORAGE_SCHEMA_VERSION) return { from, to: from }; + if (from >= STORAGE_SCHEMA_VERSION) { + // #5788: the store is at/above this build — before no-op'ing, make + // sure a newer build's non-additive migration didn't raise the + // reader floor past this build (refuse if so). + enforceReaderFloor(db); + return { from, to: from }; + } let needV8Backfill = false; db.transaction(() => { if (from < 1) db.exec(STORAGE_DDL_V1); @@ -444,7 +517,20 @@ export function migrateSchema(db: { } }); if (needV8Backfill) migrateV8Identities(db); - db.exec(`PRAGMA user_version = ${STORAGE_SCHEMA_VERSION}`); + // #5788: stamp the schema version AND the reader floor in ONE small + // transaction — a crash between the two statements would leave a torn + // pair. The gate reads the floor only when the stamp is already at/ + // above this build, so a torn pair (floor row committed, stamp not yet + // bumped) would under-report the floor and let a too-old build in. + // PRAGMA user_version is transactional in SQLite (header write + // participates in the txn), so both land or neither does. + db.transaction(() => { + db.prepare( + "INSERT INTO kv_store (namespace, key, value_json, updated_at) VALUES ('storage', 'schema_reader_floor', ?, ?) " + + "ON CONFLICT(namespace, key) DO UPDATE SET value_json = excluded.value_json, updated_at = excluded.updated_at", + ).run(JSON.stringify(STORAGE_MIN_READER_VERSION), Date.now()); + db.exec(`PRAGMA user_version = ${STORAGE_SCHEMA_VERSION}`); + }); return { from, to: STORAGE_SCHEMA_VERSION }; } diff --git a/src/storage/shadow.ts b/src/storage/shadow.ts index 1a50754e90..0665bc78e3 100644 --- a/src/storage/shadow.ts +++ b/src/storage/shadow.ts @@ -36,6 +36,7 @@ import { splitMediaContent } from "./identity.js"; import type { BlockView } from "../session.js"; import { effectiveJsonWriterOff, resolveStorageMode, resolveStorageWalJournalSizeLimit, unifiedSelectionIsSqlite, type StorageMode } from "../knobs.ts"; import { UnifiedStore, StorageIntegrityError, type CheckpointRow, type SessionSummaryRow, type WebSummaryRow } from "./store.ts"; +import { StorageSchemaFloorError } from "./schema.ts"; import path from "node:path"; import { resolveBackendName, backendSelectionNotice, selectedBackendRaw, openBackend, type StorageBackend } from "./backend.ts"; import { canonicalDigest, canonicalize, sha256 } from "./canonical.ts"; @@ -483,6 +484,24 @@ export class UnifiedShadow { ); return null; } + // #5788: the store's reader floor is above this build — a newer + // build migrated it with a non-additive change this build cannot + // read. Refuse (same bucket as CANTOPEN/readonly — the file is + // NOT corrupt, it is newer). The generic tail below must NOT + // apply here: "move index.db aside to force a fresh rebuild" + // would DESTROY the newer build's data, so the floor error gets + // its own line naming the real remediation (upgrade bili, or + // restore a pre-upgrade backup). The explicit legacy opt-out is + // offered like the other environment-refusals — the JSON + // envelopes keep being written and stay the load path. + if (err instanceof StorageSchemaFloorError) { + loggerLog( + "error", + `[storage] unified sidecar refused to open ${dir}/index.db (${errStr}) — REFUSING TO START (owner policy 2026-10-30: NO degradation in any case — upgrade bili to a build that can read this store, or restore a pre-upgrade index.db{,-wal,-shm} backup, or set BILI_STORAGE_UNIFIED=legacy explicitly to serve JSON-only)`, + ); + recordSidecarOpenFailure(errStr); + throw err; + } // Deleting the index cannot fix a no-engine failure (the engine is // missing from the process, not from the file), so the deletion // hint below must not be offered for those shapes. @@ -567,6 +586,20 @@ export class UnifiedShadow { return shadow; } catch (err) { const errStr = String(err); + // #5788: the library's reader floor is above this build — a + // newer build migrated it with a non-additive change this build + // cannot read. Refuse with the real remediation (upgrade bili / + // restore a pre-upgrade backup) instead of the generic + // "fix the connection" line, which would mislead the operator + // into thinking the DSN is at fault. + if (err instanceof StorageSchemaFloorError) { + loggerLog( + "error", + `[storage] mysql backend refused to open (${errStr}) — REFUSING TO START (no degradation in any case, 2026-10-30 owner policy); upgrade bili to a build that can read this library, or restore a pre-upgrade backup`, + ); + recordSidecarOpenFailure(errStr); + throw err; + } loggerLog("error", `[storage] mysql backend failed to open (${errStr}) — REFUSING TO START (no degradation in any case, 2026-10-30 owner policy); fix the connection or unset storage.backend`); recordSidecarOpenFailure(errStr); throw err; diff --git a/tests/notice-unified-store.test.ts b/tests/notice-unified-store.test.ts index 6a13ce55a0..62166e6249 100644 --- a/tests/notice-unified-store.test.ts +++ b/tests/notice-unified-store.test.ts @@ -90,3 +90,64 @@ test("cap trims oldest non-builtin keys only; built-ins survive", async () => { const small = dismissedCache()!; for (const k of two) assert.ok(small.has(k), "under-cap keys all retained"); }); + +// #5761: a dismissal landing BEFORE the boot hydration lazily created the +// cache, which made the hydrate bail — blocking the one-time file→kv +// migration (and hiding sibling lanes' rows) for the process lifetime. +// Twin of the #5757 host-plugin regression case. +test("a pre-hydration dismissal no longer blocks the migration", async () => { + try { fs.rmSync(path.join(stateBili, "upgrade-notices.json")); } catch { /* fresh volume */ } + _resetNoticeReceiptsForTest(); + + // the admin action lands before cli-start hydration has run — the lazy + // adoption sees an EMPTY file, so nothing below can come from it: + assert.equal(dismissUpgradeNotice(WM_FASTPATH_INTRO_ID), true); + const lateKey = `late-file@${"b".repeat(16)}`; + fs.mkdirSync(stateBili, { recursive: true }); + fs.writeFileSync(path.join(stateBili, "upgrade-notices.json"), JSON.stringify({ dismissed: [WM_FASTPATH_INTRO_ID, lateKey] }, null, 2)); + await new Promise((r) => setTimeout(r, 50)); // let the queued receipt land in kv + await hydrateNoticeReceipts(); + + const seen = dismissedUpgradeNotices(); + assert.ok(seen.has(WM_FASTPATH_INTRO_ID), "the pre-dismissed id stays visible"); + assert.ok(seen.has(lateKey), "hydration ran despite the pre-existing lazy cache"); + const rows = await getStore().listKvAsync("notices"); + assert.ok(rows.some((r) => r.key === WM_FASTPATH_INTRO_ID), "receipt landed in kv_store"); + assert.ok(rows.some((r) => r.key === lateKey), "one-time migration ran despite the pre-existing lazy cache"); +}); + +// #5761 variant: a dismissal landing inside the hydrate's await gap used to +// be clobbered by the final cache assignment until restart. The publish must +// fold in everything added up to it. Both KV directions are gated so the +// dismissal's own durable write cannot land before the list resolves — +// otherwise the old code would re-derive the key from kv and mask the loss. +test("a dismissal landing during hydration survives the final publish", async () => { + try { fs.rmSync(path.join(stateBili, "upgrade-notices.json")); } catch { /* fresh volume */ } + _resetNoticeReceiptsForTest(); + const store = getStore(); + const origList = store.listKvAsync.bind(store); + const origSet = store.setKvAsync.bind(store); + let releaseList: () => void = () => undefined; + let releaseSet: () => void = () => undefined; + const listGate = new Promise((resolve) => { releaseList = resolve; }); + const setGate = new Promise((resolve) => { releaseSet = resolve; }); + store.listKvAsync = async (ns?: string, prefix?: string) => { + await listGate; + return origList(ns, prefix); + }; + store.setKvAsync = async (ns: string, key: string, value: unknown) => { + await setGate; + return origSet(ns, key, value); + }; + const hydr = hydrateNoticeReceipts(); + await new Promise((r) => setTimeout(r, 20)); // park the hydrate inside the gated list + const midKey = `mid-hydrate@${"c".repeat(16)}`; + assert.equal(dismissUpgradeNotice(midKey), true); // memory now, durable write parked on setGate + releaseList(); // list resolves WITHOUT midKey — only the live-cache union can save it + await hydr; + store.listKvAsync = origList; + store.setKvAsync = origSet; + releaseSet(); + const seen = dismissedUpgradeNotices(); + assert.ok(seen.has(midKey), "mid-hydration dismissal survived the final publish"); +}); diff --git a/tests/storage-backup-repair.test.ts b/tests/storage-backup-repair.test.ts index f40c508c22..924bda55f6 100644 --- a/tests/storage-backup-repair.test.ts +++ b/tests/storage-backup-repair.test.ts @@ -247,11 +247,13 @@ test("repair (no --from): salvage extracts what survived into a fresh schema", { const rows = ro.db.prepare("SELECT count(*) AS n FROM sessions").get() as { n: number }; assert.equal(rows.n, 3); // WITHOUT ROWID tables are in the report and self-consistent: - // whatever the salvager claims, the new db must agree. + // whatever the salvager claims, the new db must agree. The fresh + // schema carries a system row (schema_reader_floor, #5788) the + // salvager does not copy — count only user rows. const kv = data.tables.find((t) => t.table === "kv_store"); assert.ok(kv, "kv_store (WITHOUT ROWID) must appear in the per-table report"); - const n = (ro.db.prepare("SELECT count(*) AS n FROM kv_store").get() as { n: number }).n; - assert.equal(kv.salvaged, n, "kv_store salvaged count must match the new db"); + const n = (ro.db.prepare("SELECT count(*) AS n FROM kv_store WHERE NOT (namespace = 'storage' AND key = 'schema_reader_floor')").get() as { n: number }).n; + assert.equal(kv.salvaged, n, "kv_store salvaged count must match the new db's user rows"); if (n < 2) assert.ok(kv.note, "a lost WITHOUT ROWID table must carry a note"); } finally { ro.db.close(); diff --git a/tests/storage-reader-floor.test.ts b/tests/storage-reader-floor.test.ts new file mode 100644 index 0000000000..fec0f61891 --- /dev/null +++ b/tests/storage-reader-floor.test.ts @@ -0,0 +1,303 @@ +/** + * #5788: persist a schema READER FLOOR so an older build refuses a store a + * newer build migrated with a NON-ADDITIVE change. + * + * The schema stamp (user_version / bili_meta schema_version) only says "how + * far a store has been migrated" — it carries no information about whether an + * OLDER build can still read the result. Today an older build opening a + * newer-migrated store either no-ops (sqlite: `from >= version`) or silently + * re-runs additive DDL (mysql), and then WRITES rows it cannot read back — + * a rolling-upgrade / rollback footgun. + * + * The fix persists, per store, the oldest schema version the writing build + * can still read (STORAGE_MIN_READER_VERSION / MYSQL_MIN_READER_VERSION, both + * 8 — v8 is the only non-additive migration, the identity backfill). The + * floor and the stamp move in ONE transaction (a torn pair would under-report + * the floor and let a too-old build in). On open, a build whose own schema + * version is below the stored floor REFUSES TO START (same bucket as + * CANTOPEN/readonly — the data is newer, not corrupt; degrading would + * split-brain, #3923). A missing floor row is UNKNOWN (a pre-feature store), + * not "too new" — it passes, so existing stores never false-refuse. + * + * The mysql hermetic arms stand in for the driver with a typed fake (the same + * discipline as tests/issue4739-storage-read-snapshot.test.ts); the real + * driver path is covered by the CI mysql-contract job. + */ + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import { UnifiedStore } from "../src/storage/store.ts"; +import { MysqlBackend, type Mysql2Module } from "../src/storage/mysql.ts"; +import { + STORAGE_SCHEMA_VERSION, + STORAGE_MIN_READER_VERSION, + StorageSchemaFloorError, +} from "../src/storage/schema.ts"; + +// Hermeticity pins (same as the other storage suites): a developer machine's +// real config must not leak a tier into these tests. +process.env.BILI_PERSIST_ZSTD = "0"; +process.env.BILI_CONFIG_FILE = path.join( + fs.mkdtempSync(path.join(os.tmpdir(), "bili-reader-floor-hermetic-")), + "no-config.json", +); +process.env.BILI_STORAGE_UNIFIED = "legacy"; +for (const k of ["BILI_STORAGE_BACKEND", "BILI_MYSQL_DSN"]) delete process.env[k]; + +function tmpdir(prefix: string): string { + return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); +} + +function rmBestEffort(p: string): void { + try { + fs.rmSync(p, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } catch { + /* leaked temp dir on a Windows runner is harmless */ + } +} + +/** Open a fresh store (migrates v1 → current head, writing the floor row + + * stamp) and close it, leaving a fully-migrated index.db on disk. */ +function freshMigratedDb(dir: string): string { + const dbPath = path.join(dir, "index.db"); + const store = UnifiedStore.open(dbPath); + store.close(); + return dbPath; +} + +// --- sqlite (hermetic, node:sqlite) --------------------------------------- + +test("#5788 invariant: the reader floor never exceeds the current schema version", () => { + assert.ok(Number.isInteger(STORAGE_MIN_READER_VERSION) && STORAGE_MIN_READER_VERSION >= 1, "floor is a positive integer"); + assert.ok(STORAGE_MIN_READER_VERSION <= STORAGE_SCHEMA_VERSION, "floor must be ≤ the current version (a build can always read its own head)"); +}); + +test("#5788 sqlite: the migration writes the floor row and the stamp atomically", async () => { + const dir = tmpdir("bili-floor-migrate-"); + try { + const dbPath = freshMigratedDb(dir); + const { DatabaseSync } = await import("node:sqlite"); + const raw = new DatabaseSync(dbPath); + const ver = raw.prepare("PRAGMA user_version").get() as { user_version: number }; + assert.equal(ver.user_version, STORAGE_SCHEMA_VERSION, "user_version at the schema head after migration"); + const floorRow = raw + .prepare("SELECT value_json FROM kv_store WHERE namespace = 'storage' AND key = 'schema_reader_floor'") + .get() as { value_json: string } | undefined; + assert.ok(floorRow, "the migration wrote the reader floor row"); + assert.equal(JSON.parse(floorRow!.value_json), STORAGE_MIN_READER_VERSION, "the floor row carries the min reader version"); + raw.close(); + } finally { + rmBestEffort(dir); + } +}); + +test("#5788 sqlite: a store whose floor is above this build's version is refused", async () => { + const dir = tmpdir("bili-floor-refuse-"); + try { + const dbPath = freshMigratedDb(dir); + const { DatabaseSync } = await import("node:sqlite"); + const raw = new DatabaseSync(dbPath); + // Simulate a FUTURE build that migrated with a non-additive change: + // it stamped user_version higher AND raised the reader floor above + // this build's schema version. + raw.exec(`PRAGMA user_version = ${STORAGE_SCHEMA_VERSION + 1}`); + raw + .prepare("INSERT INTO kv_store (namespace, key, value_json, updated_at) VALUES ('storage', 'schema_reader_floor', ?, 0) ON CONFLICT(namespace, key) DO UPDATE SET value_json = excluded.value_json") + .run(String(STORAGE_SCHEMA_VERSION + 1)); + raw.close(); + await assert.rejects( + async () => UnifiedStore.open(dbPath), + (err: unknown) => + err instanceof StorageSchemaFloorError && + err.storedFloor === STORAGE_SCHEMA_VERSION + 1 && + err.runningVersion === STORAGE_SCHEMA_VERSION, + ); + } finally { + rmBestEffort(dir); + } +}); + +test("#5788 sqlite: a store at the current version with the known floor opens (no false refuse)", async () => { + const dir = tmpdir("bili-floor-pass-current-"); + try { + const dbPath = freshMigratedDb(dir); + const store = UnifiedStore.open(dbPath); + try { + const { DatabaseSync } = await import("node:sqlite"); + const raw = new DatabaseSync(dbPath); + const ver = raw.prepare("PRAGMA user_version").get() as { user_version: number }; + assert.equal(ver.user_version, STORAGE_SCHEMA_VERSION, "user_version left untouched"); + raw.close(); + } finally { + store.close(); + } + } finally { + rmBestEffort(dir); + } +}); + +test("#5788 sqlite: a pre-feature store (no floor row) opens — unknown passes, never false-refuses", async () => { + const dir = tmpdir("bili-floor-pass-nofloor-"); + try { + const dbPath = freshMigratedDb(dir); + const { DatabaseSync } = await import("node:sqlite"); + const raw = new DatabaseSync(dbPath); + raw.prepare("DELETE FROM kv_store WHERE namespace = 'storage' AND key = 'schema_reader_floor'").run(); + raw.close(); + const store = UnifiedStore.open(dbPath); // must not throw + store.close(); + } finally { + rmBestEffort(dir); + } +}); + +test("#5788 sqlite: an additive future bump (higher user_version, same floor) opens", async () => { + const dir = tmpdir("bili-floor-pass-additive-"); + try { + const dbPath = freshMigratedDb(dir); + const { DatabaseSync } = await import("node:sqlite"); + const raw = new DatabaseSync(dbPath); + // A future ADDITIVE migration raises user_version but NOT the floor. + raw.exec(`PRAGMA user_version = ${STORAGE_SCHEMA_VERSION + 1}`); + raw.close(); + const store = UnifiedStore.open(dbPath); // must not throw (floor 8 ≤ 11) + store.close(); + } finally { + rmBestEffort(dir); + } +}); + +// --- mysql (hermetic, typed driver fake) ----------------------------------- + +interface MysqlFake { + driver: Mysql2Module; + ops: string[]; +} + +/** A typed stand-in for the mysql2/promise driver: answers the meta reads + * with the given stamp/floor (null = the row is absent) and records every + * operation in order so the stamp+floor transaction can be inspected. The + * v8 data step is a no-op (the session list comes back empty) and the + * probe-first DDL sees every column/index as already present, so a + * migration arm exercises the stamp+floor write without the backfill. */ +function makeMysqlFake(stamp: string | null, floor: string | null): MysqlFake { + const ops: string[] = []; + const conn = { + async query(sql: string): Promise { + ops.push(sql); + if (sql.includes("FROM bili_meta") && sql.includes("'schema_version'")) { + return stamp === null ? [[]] : [[{ meta_value: stamp }]]; + } + if (sql.includes("FROM bili_meta") && sql.includes("'schema_reader_floor'")) { + return floor === null ? [[]] : [[{ meta_value: floor }]]; + } + if (sql.includes("GET_LOCK")) return [[{ ok: 1 }]]; + if (sql.includes("SELECT DISTINCT session_id FROM messages")) return [[]]; + if (sql.includes("information_schema.COLUMNS") && sql.includes("TABLE_NAME = 'messages'")) { + return [[{ col: "identity" }, { col: "retired_at" }, { col: "ts" }]]; + } + if (sql.includes("information_schema.COLUMNS") && sql.includes("TABLE_NAME = 'sessions'")) { + return [[{ col: "meta_json", dflt: "{}" }, { col: "stats_json", dflt: "{}" }, { col: "metadata_json", dflt: "{}" }, { col: "kstate_json", dflt: "{}" }, { col: "tail_json", dflt: "{}" }]]; + } + if (sql.includes("information_schema.STATISTICS")) { + return [ + [{ tbl: "content", idx: "idx_content_refcount" }], + [{ tbl: "messages", idx: "idx_messages_content_hash" }], + [{ tbl: "blocks", idx: "idx_blocks_one_hash" }], + [{ tbl: "blocks", idx: "idx_blocks_summary_hash" }], + [{ tbl: "ccr_entries", idx: "idx_ccr_entries_content_hash" }], + [{ tbl: "message_media", idx: "idx_message_media_media_hash" }], + [{ tbl: "checkpoints", idx: "idx_checkpoints_state_hash" }], + ]; + } + return [[]]; + }, + async beginTransaction() { ops.push("__begin__"); }, + async commit() { ops.push("__commit__"); }, + async rollback() { ops.push("__rollback__"); }, + release() { ops.push("__release__"); }, + }; + const driver = { + createPool: () => ({ + getConnection: async () => conn, + query: async () => { throw new Error("query escaped to the pool"); }, + end: async () => {}, + }), + } as unknown as Mysql2Module; + return { driver, ops }; +} + +test("#5788 mysql: a library whose floor is above this build's version is refused", async () => { + const { driver } = makeMysqlFake(String(STORAGE_SCHEMA_VERSION + 1), String(STORAGE_SCHEMA_VERSION + 1)); + const backend = new MysqlBackend("mysql://floor-refuse", driver); + try { + await assert.rejects( + async () => backend.init(), + (err: unknown) => + err instanceof StorageSchemaFloorError && + err.storedFloor === STORAGE_SCHEMA_VERSION + 1 && + err.runningVersion === STORAGE_SCHEMA_VERSION, + ); + } finally { + await backend.close(); + } +}); + +test("#5788 mysql: a library at the current version with the known floor opens", async () => { + const { driver, ops } = makeMysqlFake(String(STORAGE_SCHEMA_VERSION), String(STORAGE_MIN_READER_VERSION)); + const backend = new MysqlBackend("mysql://floor-pass-current", driver); + try { + await backend.init(); // must not throw + // No migration ran (stamp already at the head) → the stamp is + // re-stamped (GREATEST no-op) but the floor is NOT re-written: a + // pre-feature library keeps "unknown" and passes the gate. + const stampInsert = ops.find((o) => o.includes("INSERT INTO bili_meta") && o.includes("'schema_version'")); + assert.ok(stampInsert, "the stamp INSERT is issued"); + const floorInsert = ops.find((o) => o.includes("INSERT INTO bili_meta") && o.includes("'schema_reader_floor'")); + assert.equal(floorInsert, undefined, "the floor is NOT re-written when no migration ran"); + } finally { + await backend.close(); + } +}); + +test("#5788 mysql: a pre-feature library (no floor row) opens — unknown passes", async () => { + const { driver } = makeMysqlFake(String(STORAGE_SCHEMA_VERSION), null); + const backend = new MysqlBackend("mysql://floor-pass-nofloor", driver); + try { + await backend.init(); // must not throw + } finally { + await backend.close(); + } +}); + +test("#5788 mysql: an additive future bump (higher stamp, same floor) opens", async () => { + const { driver } = makeMysqlFake(String(STORAGE_SCHEMA_VERSION + 1), String(STORAGE_MIN_READER_VERSION)); + const backend = new MysqlBackend("mysql://floor-pass-additive", driver); + try { + await backend.init(); // must not throw (floor 8 ≤ 11) + } finally { + await backend.close(); + } +}); + +test("#5788 mysql: a migration writes the stamp and the floor in ONE transaction", async () => { + const { driver, ops } = makeMysqlFake(String(STORAGE_SCHEMA_VERSION - 1), String(STORAGE_MIN_READER_VERSION)); + const backend = new MysqlBackend("mysql://floor-migrate", driver); + try { + await backend.init(); // migrated = true (stamp below the head) + const lastBegin = ops.lastIndexOf("__begin__"); + const lastCommit = ops.lastIndexOf("__commit__"); + assert.ok(lastBegin !== -1 && lastCommit !== -1, "a final stamp+floor transaction ran"); + assert.ok(lastBegin < lastCommit, "begin precedes commit"); + const window = ops.slice(lastBegin, lastCommit); + assert.ok(window.some((o) => o.includes("INSERT INTO bili_meta") && o.includes("'schema_version'")), "the stamp INSERT is inside the final transaction"); + assert.ok(window.some((o) => o.includes("INSERT INTO bili_meta") && o.includes("'schema_reader_floor'")), "the floor INSERT is in the SAME transaction as the stamp"); + assert.equal(window.filter((o) => o === "__begin__").length, 1, "exactly one begin in the window"); + assert.equal(window.filter((o) => o === "__commit__").length, 0, "no commit until the very end (atomicity)"); + } finally { + await backend.close(); + } +});