Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 37 additions & 22 deletions src/notice-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ const DISMISS_FILE = "upgrade-notices.json";

let cache: Map<string, number> | 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 {
Expand Down Expand Up @@ -94,39 +98,49 @@ export function dismissedCache(): ReadonlySet<string> | 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<void> {
if (cache !== null || hydrating || !unifiedReceiptsActive()) return;
if (hydrated || hydrating || !unifiedReceiptsActive()) return;
hydrating = true;
const merged = new Map<string, number>();
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<string, number>(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;
}

Expand Down Expand Up @@ -171,5 +185,6 @@ export function persistDismissedKey(key: string): void {
export function _resetNoticeReceiptsForTest(): void {
cache = null;
hydrating = false;
hydrated = false;
warned = false;
}
74 changes: 66 additions & 8 deletions src/storage/mysql.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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();
}
Expand Down
96 changes: 91 additions & 5 deletions src/storage/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<T>(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);
Expand Down Expand Up @@ -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 };
}

Expand Down
Loading
Loading