From 57f2d554a6633dab71ecfaa43d22b2fed89670a8 Mon Sep 17 00:00:00 2001 From: chidea Date: Sun, 1 Nov 2026 11:05:49 +0900 Subject: [PATCH 1/3] feat(storage): run the store on bun's builtin bun:sqlite bun has no node:sqlite, and a better-sqlite3 N-API prebuild cannot be loaded there at all ("Could not load the default exports from better-sqlite3", measured on bun 1.3.14), so the #2833 ladder resolved to no engine and every bun-run proxy degraded to legacy-only storage. - driver.ts: ladder step 0 = bun:sqlite, required only when process.versions.bun exists. bun's builtin is synchronous and already shaped like better-sqlite3, so the adapter covers the three measured divergences: named params bind by the sigil written in the SQL (the store's SQL is better-sqlite3 style and passes bare { a: 1 } bags, so bare keys are duplicated into the sigil forms each statement really uses, string literals blanked first); BLOB columns come back as a bare Uint8Array and are normalized to Buffer; run() reports BigInt changes/lastInsertRowid (now Number) and there is no .open flag. Writes take .immediate(), reads .deferred() (#2690: a deferred transaction that upgrades mid-flight hits SQLITE_BUSY_SNAPSHOT, which busy_timeout cannot resolve); close() is idempotent. - probe seam: a bag pinning only { builtin, host } now simulates a NODE host (bun off unless the test opts in with bun: true), so the ladder suites keep passing on a machine whose runtime happens to be bun. - engine-bootstrap.ts: bun never downloads a prebuild (not-needed); nodeSqliteUpgradeHint and the degrade banner name bun:sqlite instead of the Node lever; the self-contained integrity worker picks its engine by the runtime it runs on ({ readonly: true } on bun). - tests: new tests/storage-bun-sqlite.test.ts (9 tests: fake-Database contract pins that also run on Node CI, plus real-bun lock/rollback and a real UnifiedStore round-trip through open, ingest, reads, close and reopen). Seven raw test handles stop pinning node:sqlite so those suites run on any runtime; the three node:sqlite-only legs in storage-unified skip by probe instead of failing to load. Measured under bun against the pre-change baseline on this machine: 24 more storage tests pass, zero regressions (storage-unified 4/13 -> 14 pass + 4 skip + 0 fail; ingest-watermark 1/15 -> 15/1; bounded-load 1/4 -> 4/1; engine-proofs 1/11 -> 7/5; plugin-fork 35/21 -> 51/5; engine-bootstrap unchanged at 43/1). Remaining bun failures are the node:test shim's missing t.mock (oven-sh/bun#5090), Node-only suites that statically import node:sqlite, and ERR_SERVER_NOT_RUNNING in the child-process harness. --- CHANGELOG.md | 8 + src/storage/driver.ts | 190 ++++++++++- src/storage/engine-bootstrap.ts | 25 +- src/storage/integrity-check.ts | 16 +- src/storage/runtime-status.ts | 17 +- tests/block-bounds-live-only.test.ts | 4 +- tests/fork-clone-media-refcount.test.ts | 4 +- tests/issue4982-fork-lineage-conflict.test.ts | 6 +- tests/plugin-fork.test.ts | 6 +- tests/storage-bun-sqlite.test.ts | 321 ++++++++++++++++++ tests/storage-unified.test.ts | 15 +- tests/unified-remap-collision.test.ts | 4 +- 12 files changed, 586 insertions(+), 30 deletions(-) create mode 100644 tests/storage-bun-sqlite.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 9488c0885b..86d652b14b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,14 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Added - **消息时间戳渲染默认开启(#4313 后续)**:此前 `compress.messageTimestamps` 为可选特性(默认关,线上字节与特性前逐字节一致)。生产会话的缓存审计(同会话开关前后命中率均 95.0%、无一条时间戳导致的前缀重写 miss、全部异常可归因上游 TTL 驱逐)证实存戳渲染跨轮逐字节稳定,故默认翻转为**开**:`time=` 压缩标签属性、回执指纹行 `[起 – 止]` 覆盖跨度、摘要 Occurred 行对所有人默认可见(每条消息首次出现时铸一次不可变墙钟戳,渲染只读存戳不读墙钟)。关闭方式不变:文件 `compress.messageTimestamps: false` 或 `BILI_MESSAGE_TIMESTAMPS=0`,关闭后每个出站字节与 pre-#4313 master 一致。升级用户的一次性代价:标志首次解析为开的那个重启后,每个活跃会话付一次冻结前缀缓存重写(旧消息补上 time= 属性 + 提示词变体切换),之后稳定。测试基线:tests/preload-test-env.mjs 整套件 pin 显示门控关,字节对比型金标保持特性前形态;issue4313 toggle 套件按新契约翻转并新增 message-timestamps-default-on.test.ts 钉住生产默认路径。 + +### Storage — bun 运行时原生支持(`bun:sqlite`) + +- **在 bun 上跑 bili 不再退回 legacy**:引擎阶梯加了第 0 步 `bun:sqlite`(src/storage/driver.ts,只有 `process.versions.bun` 存在时才 require —— bun 里 `node:sqlite` 根本不存在,而 better-sqlite3 的 N-API 预编译在 bun 下必定 "Could not load the default exports from better-sqlite3",阶梯三步全落空只会得到 legacy-only)。bun 内置引擎与 better-sqlite3 同形(`Database`、同步 `run/get/all`、`.transaction()`),适配层只补三处实测差异:命名参数按 SQL 里书写的记号绑定(`:a`/`@b`/`$c`,而库内 SQL 是 better-sqlite3 风格、传裸键 `{ a: 1 }`)——按语句把裸键复制成该语句真正用到的记号形态(字面量先抹平,故字符串里的 `:name` 不会被误认);BLOB 列回裸 `Uint8Array` → 归一成 Buffer(媒体/载荷读取端按 Buffer 契约写);`run()` 的 `changes`/`lastInsertRowid` 是 BigInt → 收成 number,并补 bun 没有的 `.open` 旗标。写事务走 `.immediate()`、只读走 `.deferred()`(#2690 的写锁拓扑:延迟事务中途升级为写锁会撞 busy_timeout 救不回的 SQLITE_BUSY_SNAPSHOT),`close()` 幂等。 +- **自举与状态文案不再指错运行时**:bun 上自举直接 `not-needed`(给 bun 下载 N-API 预编译纯属浪费带宽且必加载失败);`nodeSqliteUpgradeHint` 与降级横幅在 bun 上讲 `bun:sqlite`,不再让运维去升 Node;整史后台完整性 worker 是自包含源串、不复用阶梯,也按 `process.versions.bun` 选引擎(bun 的只读选项名是 `readonly`,不是 Node 的 `readOnly`)。 +- **测试钉住契约**:tests/storage-bun-sqlite.test.ts —— 假 Database 那几组经测试缝 `setBunDatabaseFactoryForTests` 在 Node CI 上同样可跑(记号双写、字面量外只重写一次、BigInt/Uint8Array/null 归一、事务必须 `.immediate()`、阶梯第 0 步优先、被钉的 `{builtin, host}` 探针袋视为 Node 主机);真内置那几组仅在 bun 下跑(真 BEGIN 与回滚、嵌套事务不提前提交、写完锁立刻交还,以及真 UnifiedStore 端到端:开库跑 PRAGMA 阶梯 + quick_check + 迁移、命名参数插入、读回、close 触发 WAL checkpoint 后重开仍在)。 +- **既有存储套件在 bun 下实测**:7 处写死 `openSqliteDatabase(path, "node:sqlite")` 的裸句柄改为随动自动探测后,block-bounds 1/0、fork-clone-media 3/0、issue4982 18/0、unified-remap 3/0 全绿;storage-unified 从 4 通过/13 失败变成 14 通过/4 跳过/0 失败(三条只驱动 `node:sqlite` 的 leg 现按驱动探针跳过);storage-ingest-watermark 15/1、bounded-load 4/1、engine-proofs 7/5、plugin-fork 51/5、engine-bootstrap 维持 43/1。与改动前同机基线相比:多通过 24 条,零回归。剩余失败与存储引擎无关:bun 的 node:test 垫片没有 `t.mock`(oven-sh/bun#5090)、Node 专用套件顶层静态 `import("node:sqlite")`、以及子进程 harness 在 bun 下的 ERR_SERVER_NOT_RUNNING。 + ### #5079 — `prompt_cache_key` 自注入默认关闭,`promptCache.routing` 一个开关管住两条 wire - **行为变更(旧→新)**:此前 bili 在插件车道对一切目的地默认给请求体盖 `prompt_cache_key=<会话 id>`(#2218/#2649 定案,Responses wire 仅对 `api.openai.com` 注入)。由于大量服务见到该字段会直接拒绝、且这类服务无法枚举,**默认反转为关闭**:`promptCache.routing` 缺省值从 `"auto"` 变为 `"disabled"`(无法识别的值同样落到 `"disabled"`)。客户端自带的 key 不受影响:任何模式下都原样转发(A/B 探测记忆对已证实拒收的 origin+model 组合照常撤键)。 diff --git a/src/storage/driver.ts b/src/storage/driver.ts index 95b4231a4a..58a4d085b8 100644 --- a/src/storage/driver.ts +++ b/src/storage/driver.ts @@ -2,6 +2,14 @@ * Minimal SQLite driver seam for the unified storage layer (#2671). * * Engine resolution order (#2833, owner-approved 2026-10-12): + * 0. bun builtin — bun:sqlite (bun's own built-in synchronous SQLite). Only + * ever available when the host runtime IS bun, where + * node:sqlite does NOT exist; without this step a bun-run + * bili falls through to the N-API better-sqlite3 path, whose + * prebuilt binding cannot be loaded by bun ("Could not load + * the default exports from better-sqlite3"), so the unified + * store cannot open at all. Same zero-native-dependency + * invariant as step 1. * 1. builtin — node:sqlite (DatabaseSync; unflagged on recent Node 22.x, * stable lineage since Node 23.4). Zero native dependency, * zero build scripts — preferred wherever it exists. @@ -74,7 +82,22 @@ import { createRequire } from "node:module"; const require = createRequire(import.meta.url); -export type SqliteEngineName = "better-sqlite3" | "node:sqlite"; +// Specifier through a constant: `bun:sqlite` is bun's own builtin and is NOT in +// module.builtinModules, so a quoted-literal require reads as an external npm +// package to scripts/check-dist-external.mjs (the same indirection that +// SQLITE_SPEC in src/storage/integrity-check.ts uses for node:sqlite). It is +// required lazily, and only when isBunRuntime() says this process IS bun, so a +// thin Node install never evaluates it. +const BUN_SQLITE_SPEC = "bun:sqlite"; + +export type SqliteEngineName = "better-sqlite3" | "node:sqlite" | "bun:sqlite"; + +/** True when the host runtime is bun (aliased `node` installs included). bun + * implements `bun:sqlite` and NOT `node:sqlite`, so the ladder must tell them + * apart; on real Node this is false and the ladder below is unchanged. */ +export function isBunRuntime(): boolean { + return typeof process !== "undefined" && process.versions?.bun !== undefined; +} interface OpenedDatabase { readonly db: SqliteDatabase; @@ -210,6 +233,134 @@ function adaptNodeSqliteStatement(stmt: NodeSqliteStatement): SqliteStatement { }; } +interface BunSqliteStatement { + run(...args: unknown[]): { changes?: number | bigint; lastInsertRowid?: number | bigint } | undefined; + get(...args: unknown[]): unknown; + all(...args: unknown[]): unknown[]; +} + +export interface BunSqliteDatabase { + exec(sql: string): unknown; + prepare(sql: string): BunSqliteStatement; + /** bun mirrors better-sqlite3's shape: wraps fn and returns the callable + * wrapper with immediate/deferred/exclusive lock-mode variants attached. */ + transaction(fn: () => T): (() => T) & { immediate(): T; deferred(): T; exclusive(): T }; + close(): void; +} + +export type BunSqliteCtor = new (path: string) => BunSqliteDatabase; + +let bunDatabaseFactoryForTests: ((path: string) => BunSqliteDatabase) | null = null; + +/** Test seam: substitute how the bun:sqlite emulation obtains its database + * handle, so the bun adapter can be pinned on a Node CI runner where + * `bun:sqlite` cannot load. Null = the real builtin bun:sqlite module. */ +export function setBunDatabaseFactoryForTests(factory: ((path: string) => BunSqliteDatabase) | null): void { + bunDatabaseFactoryForTests = factory; +} + +/** bun binds named parameters by the exact sigil written in the SQL (`:a`, `@a`, + * `$a`), while the store's SQL is better-sqlite3 style and passes plain + * `{ name: value }` objects. Collect the sigil forms a statement actually uses + * (literals blanked first) so the adapter can offer bun both spellings. */ +type BunNamedParamForms = Map; + +function bunNamedParamForms(sql: string): BunNamedParamForms | undefined { + const forms: BunNamedParamForms = new Map(); + for (const m of sql.replace(/'[^']*'/g, "''").matchAll(/(?:^|[^:@$])([:@$])([A-Za-z_][A-Za-z0-9_]*)/g)) { + const bare = m[2]; + const full = m[1] + bare; + const list = forms.get(bare) ?? []; + if (!list.includes(full)) list.push(full); + forms.set(bare, list); + } + return forms.size > 0 ? forms : undefined; +} + +/** Duplicate each named key into the sigil form(s) the statement uses, keeping + * the bare key too (bun accepts it). A positional / array / binary / Date first + * argument is not a named-parameter bag and passes through untouched. */ +function bunParamArgs(args: unknown[], forms: BunNamedParamForms | undefined): unknown[] { + if (forms === undefined || args.length === 0) return args; + const first = args[0]; + if (first === null || typeof first !== "object" || Array.isArray(first) || ArrayBuffer.isView(first) || first instanceof Date) return args; + const src = first as Record; + const out = Object.assign({}, src) as Record; + for (const key of Object.keys(src)) { + for (const form of forms.get(key) ?? []) out[form] = src[key]; + } + return [out, ...args.slice(1)]; +} + +/** bun hands back a bare `Uint8Array` for BLOB columns where better-sqlite3 and + * node:sqlite hand back a Buffer; the store's media/payload readers expect a + * Buffer, so normalize on the way out. `null` rows collapse to `undefined`, + * matching the node:sqlite adapter's no-row contract. */ +function bunRow(row: unknown): unknown { + if (row === null) return undefined; + if (row === undefined || typeof row !== "object") return row; + const src = row as Record; + let mapped: Record | undefined; + for (const key of Object.keys(src)) { + const v = src[key]; + if (v instanceof Uint8Array && !Buffer.isBuffer(v)) { + if (mapped === undefined) mapped = Object.assign({}, src); + mapped[key] = Buffer.from(v); + } + } + return mapped ?? row; +} + +function adaptBunSqliteStatement(stmt: BunSqliteStatement, forms: BunNamedParamForms | undefined): SqliteStatement { + return { + run: (...args: unknown[]) => { + const res = stmt.run(...bunParamArgs(args, forms)); + return { + changes: Number(res?.changes ?? 0), + lastInsertRowid: Number(res?.lastInsertRowid ?? 0), + }; + }, + get: (...args: unknown[]) => bunRow(stmt.get(...bunParamArgs(args, forms))), + all: (...args: unknown[]) => stmt.all(...bunParamArgs(args, forms)).map((row) => bunRow(row)), + }; +} + +function openBunSqlite(path: string): SqliteDatabase { + // bun:sqlite is synchronous like better-sqlite3, and already carries a + // .transaction() helper — only the parameter spelling, the BLOB type and + // the missing `.open` flag differ from what the store expects. + const db = bunDatabaseFactoryForTests + ? bunDatabaseFactoryForTests(path) + : (() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { Database } = require(BUN_SQLITE_SPEC) as { Database: BunSqliteCtor }; + return new Database(path); + })(); + let closed = false; + const mode = (fn: () => T, variant: "immediate" | "deferred"): T => { + const t = db.transaction(fn); + // BEGIN IMMEDIATE for writes, deferred for reads — the same #2690 + // reasoning as wrapBetterSqlite3: a deferred read-then-write + // transaction upgrades mid-flight to a write lock (SQLITE_BUSY_SNAPSHOT, + // which busy_timeout cannot resolve), so writers take the lock up front. + return t[variant] ? t[variant]() : t(); + }; + return { + exec: (sql) => void db.exec(sql), + prepare: (sql) => adaptBunSqliteStatement(db.prepare(sql), bunNamedParamForms(sql)), + transaction: (fn) => mode(fn, "immediate"), + readTransaction: (fn) => mode(fn, "deferred"), + close: () => { + if (closed) return; + closed = true; + db.close(); + }, + get open() { + return !closed; + }, + }; +} + export type SqliteEngineSource = "builtin" | "host" | "self-downloaded"; interface ResolvedEngine { @@ -217,14 +368,31 @@ interface ResolvedEngine { readonly source: SqliteEngineSource; } -let probeOverridesForTests: { builtin?: boolean; host?: boolean } | null = null; +let probeOverridesForTests: { bun?: boolean; builtin?: boolean; host?: boolean } | null = null; /** Test seam: override engine availability probes (null = real probes). Lets - * resolution-order tests run deterministically on any CI Node version. */ -export function setSqliteProbeOverridesForTests(o: { builtin?: boolean; host?: boolean } | null): void { + * resolution-order tests run deterministically on any CI Node version. A bag + * that names only `builtin`/`host` simulates a NODE host: bun stays off unless + * the caller opts in with `bun: true`, so the #2833 ladder remains testable on + * a machine whose runtime happens to be bun (where `node` is aliased to bun). */ +export function setSqliteProbeOverridesForTests(o: { bun?: boolean; builtin?: boolean; host?: boolean } | null): void { probeOverridesForTests = o; } +/** bun:sqlite presence probe: bun's builtin synchronous SQLite. False on real + * Node (there is no `bun:sqlite` module to require) and false whenever a test + * pins a Node-host bag, so the #2833 ladder below stays authoritative there. */ +export function probeBunSqlite(): boolean { + if (probeOverridesForTests?.bun !== undefined) return probeOverridesForTests.bun; + if (probeOverridesForTests) return false; // a pinned bag = simulated Node host + if (!isBunRuntime()) return false; + try { + return (require(BUN_SQLITE_SPEC) as { Database?: unknown }).Database !== undefined; + } catch { + return false; + } +} + /** node:sqlite presence probe (#2833 step 1). Absent on Node <= 21 and early * 22.x minors that still gate it behind --experimental-sqlite. */ export function probeBuiltinSqlite(): boolean { @@ -275,7 +443,8 @@ export function resolvedSqliteEngineInfo(): ResolvedEngine | null { function detectEngine(): ResolvedEngine { if (cachedEngine) return cachedEngine; - if (probeBuiltinSqlite()) cachedEngine = { name: "node:sqlite", source: "builtin" }; + if (probeBunSqlite()) cachedEngine = { name: "bun:sqlite", source: "builtin" }; + else if (probeBuiltinSqlite()) cachedEngine = { name: "node:sqlite", source: "builtin" }; else if (probeHostBetterSqlite3()) cachedEngine = { name: "better-sqlite3", source: "host" }; else if (selfDownloadedLoader) cachedEngine = { name: "better-sqlite3", source: "self-downloaded" }; else throw new SqliteDriverError("no SQLite engine available", "node:sqlite"); @@ -284,7 +453,7 @@ function detectEngine(): ResolvedEngine { /** Test seam: forces the engine for the next open (does not affect open handles). */ export function setPreferredSqliteEngineForTests(engine: SqliteEngineName | null): void { - cachedEngine = engine ? { name: engine, source: engine === "node:sqlite" ? "builtin" : "host" } : null; + cachedEngine = engine ? { name: engine, source: engine === "node:sqlite" || engine === "bun:sqlite" ? "builtin" : "host" } : null; } let enginesUnavailableForTests = false; @@ -305,7 +474,14 @@ export function openSqliteDatabase(path: string, engine?: SqliteEngineName): Ope if (enginesUnavailableForTests) { throw new SqliteDriverError("no SQLite engine available", "node:sqlite"); } - const resolved = engine ? { name: engine, source: (engine === "node:sqlite" ? "builtin" : "host") as SqliteEngineSource } : detectEngine(); + const resolved = engine ? { name: engine, source: (engine === "node:sqlite" || engine === "bun:sqlite" ? "builtin" : "host") as SqliteEngineSource } : detectEngine(); + if (resolved.name === "bun:sqlite") { + try { + return { db: openBunSqlite(path), engine: resolved.name, source: resolved.source }; + } catch (err) { + throw new SqliteDriverError(String(err), resolved.name); + } + } if (resolved.name === "better-sqlite3") { try { const ctor = resolved.source === "self-downloaded" ? selfDownloadedLoader!() : loadHostBetterSqlite3(); diff --git a/src/storage/engine-bootstrap.ts b/src/storage/engine-bootstrap.ts index 1a04a34b02..c4a44858b7 100644 --- a/src/storage/engine-bootstrap.ts +++ b/src/storage/engine-bootstrap.ts @@ -6,10 +6,11 @@ * build-script approval (pnpm >=10 strictDepBuilds hard-fails unlisted native * deps; dsh profile bundles run pnpm non-interactively against a fixed list). * - * Resolution order (owner-approved): builtin node:sqlite -> host-provided - * better-sqlite3 -> cached self-downloaded prebuilt -> (this module downloads - * the prebuilt when none of the above exists) -> none = legacy-only (#2825 - * contract). This module owns ONLY the download/cache step; driver.ts owns + * Resolution order (owner-approved): builtin bun:sqlite (available ONLY when the + * runtime IS bun, where node:sqlite does not exist) -> builtin node:sqlite -> + * host-provided better-sqlite3 -> cached self-downloaded prebuilt -> (this module + * downloads the prebuilt when none of the above exists) -> none = legacy-only + * (#2825 contract). This module owns ONLY the download/cache step; driver.ts owns * resolution order and opening. * * Artifacts are pinned PER NODE MAJOR, because the binding is not portable @@ -54,7 +55,7 @@ import { gunzipSync } from "node:zlib"; import { log as loggerLog } from "../logger.js"; import { cacheDir } from "../paths.js"; -import { probeBuiltinSqlite, probeHostBetterSqlite3, registerSelfDownloadedBetterSqlite3, type BetterSqlite3Ctor } from "./driver.js"; +import { isBunRuntime, probeBuiltinSqlite, probeBunSqlite, probeHostBetterSqlite3, registerSelfDownloadedBetterSqlite3, type BetterSqlite3Ctor } from "./driver.js"; import { fileStorageAutoDownload, fileStorageUnified, resolveStorageMode, resolveSqliteAutoDownload, updateRegistryBase } from "../knobs.js"; import { normalizeRegistryBase } from "../update.js"; import { proxyDispatcher } from "../upstream-proxy.js"; @@ -346,6 +347,14 @@ async function runBootstrap(opts: EnsureSqliteEngineOptions): Promise= 22.5 for the builtin node:sqlite"; const parts = nodeVersion.split(".").map((p) => Number.parseInt(p, 10)); const major = parts[0]; const minor = parts[1]; diff --git a/src/storage/integrity-check.ts b/src/storage/integrity-check.ts index 075e79e730..df7883d429 100644 --- a/src/storage/integrity-check.ts +++ b/src/storage/integrity-check.ts @@ -149,12 +149,20 @@ const { parentPort, workerData } = require("node:worker_threads"); // (node:sqlite is NOT in module.builtinModules, so it is not skipped as a // builtin); variable indirection is that gate's sanctioned invisible path. // Do NOT inline the specifier back into the call — it re-trips the gate -// (same class as #3511/#3516/#4008; see 8b70e913 for the same fix in -// src/storage/quick-check-worker.ts). +// (same class as #3511/#3516/#4008; driver.ts uses the same indirection for +// bun:sqlite). +// bun is not Node: it has no node:sqlite, and its own builtin speaks the +// better-sqlite3-shaped API (Database, the "readonly" option instead of node's +// "readOnly"), so the worker picks the engine by the runtime it actually runs +// on — the same process.versions.bun test driver.ts uses. const SQLITE_SPEC = "node:sqlite"; +const BUN_SQLITE_SPEC = "bun:sqlite"; +const isBunRuntime = typeof process !== "undefined" && process.versions != null && process.versions.bun != null; +const openReadOnly = isBunRuntime + ? (p) => new (require(BUN_SQLITE_SPEC).Database)(p, { readonly: true }) + : (p) => new (require(SQLITE_SPEC).DatabaseSync)(p, { readOnly: true }); try { - const { DatabaseSync } = require(SQLITE_SPEC); - const db = new DatabaseSync(workerData.path, { readOnly: true }); + const db = openReadOnly(workerData.path); const rows = db.prepare("PRAGMA quick_check").all(); db.close(); const verdict = rows.map((row) => String(row.quick_check ?? "")).join(" ").trim(); diff --git a/src/storage/runtime-status.ts b/src/storage/runtime-status.ts index 28d555ba11..2ef3b10a2b 100644 --- a/src/storage/runtime-status.ts +++ b/src/storage/runtime-status.ts @@ -28,7 +28,7 @@ import { bootstrapFailureMarkerPath, COOLDOWN_MS, nodeSqliteUpgradeHint, readBoo import { fileStorageAutoDownload, fileStorageJsonWriter, fileStorageUnified, fileStorageWalJournalSizeLimit, resolveStorageMode } from "../knobs.js"; import { log as loggerLog } from "../logger.js"; import { safePrefix, safeSuffix } from "../text-safe.js"; -import { resolvedSqliteEngineInfo } from "./driver.js"; +import { isBunRuntime, resolvedSqliteEngineInfo } from "./driver.js"; import { sqliteOpenFailureHint, type UnifiedShadow } from "./shadow.js"; import type { StorageMode } from "./shadow.js"; @@ -195,6 +195,17 @@ function shortenError(err: string): string { return `${safePrefix(oneLine, 78)}…${safeSuffix(oneLine, 78)}`; } +/** The generic no-engine reason, phrased for the runtime that is actually short + * an engine: under bun there is no node:sqlite, and a better-sqlite3 N-API + * prebuild cannot be loaded by bun at all — naming the Node lever there sends + * operators to fix the wrong runtime. Node keeps the historical wording. */ +function noEngineReason(): string { + const missing = isBunRuntime() + ? "bun:sqlite missing, better-sqlite3 not loadable under bun" + : "node:sqlite missing, better-sqlite3 not installed"; + return `no SQLite engine available (${missing})${nodeSqliteUpgradeHint()}`; +} + function degradeReason(): string { // No pinned artifact serves this runtime (below every Node floor, or a Node // ABI no prebuild targets), so the engine is refused BEFORE any load and the @@ -211,7 +222,7 @@ function degradeReason(): string { // The driver's no-engine error surfaces through the same open path — // say what it actually is instead of "index database failed to open". if (isNoEngineError(e)) { - return `no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)${nodeSqliteUpgradeHint()}`; + return noEngineReason(); } // #4626-era owner chain (final, 2026-10-30): a provably-corrupt index // stays EXACTLY in place (no move, no copy, no rebuild) and bili @@ -237,7 +248,7 @@ function degradeReason(): string { break; } } - return `no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)${nodeSqliteUpgradeHint()}`; + return noEngineReason(); } const COOLDOWN_CACHE_MS = 30_000; diff --git a/tests/block-bounds-live-only.test.ts b/tests/block-bounds-live-only.test.ts index 8537119998..47abb1b1b3 100644 --- a/tests/block-bounds-live-only.test.ts +++ b/tests/block-bounds-live-only.test.ts @@ -75,7 +75,9 @@ function open(label: string): Handle { const dir = mkdtempSync(path.join(tmpdir(), `bili-block-bounds-${label}-`)); const dbPath = path.join(dir, "index.db"); const store = UnifiedStore.open(dbPath); - const raw = openSqliteDatabase(dbPath, "node:sqlite"); + // Engine unpinned on purpose: the store above opened this file through + // auto-detect, and bun has no node:sqlite to pin. + const raw = openSqliteDatabase(dbPath); const q = raw.db as unknown as { prepare(sql: string): { get(...a: unknown[]): unknown; run(...a: unknown[]): unknown }; close?(): void }; return { dir, diff --git a/tests/fork-clone-media-refcount.test.ts b/tests/fork-clone-media-refcount.test.ts index 5f6702cc61..0cd9b297c9 100644 --- a/tests/fork-clone-media-refcount.test.ts +++ b/tests/fork-clone-media-refcount.test.ts @@ -72,7 +72,9 @@ function open(label: string): Handle { const dir = mkdtempSync(path.join(tmpdir(), `bili-clone-ref-${label}-`)); const dbPath = path.join(dir, "index.db"); const store = UnifiedStore.open(dbPath); - const raw = openSqliteDatabase(dbPath, "node:sqlite"); + // Engine unpinned on purpose: the store above opened this file through + // auto-detect, and bun has no node:sqlite to pin. + const raw = openSqliteDatabase(dbPath); const q = raw.db as unknown as { prepare(sql: string): { get(...a: unknown[]): unknown; run(...a: unknown[]): unknown }; close?(): void }; return { dir, diff --git a/tests/issue4982-fork-lineage-conflict.test.ts b/tests/issue4982-fork-lineage-conflict.test.ts index 9d32258193..8d4e05a7f8 100644 --- a/tests/issue4982-fork-lineage-conflict.test.ts +++ b/tests/issue4982-fork-lineage-conflict.test.ts @@ -46,7 +46,9 @@ for (const populated of [false, true]) { const dir = mkdtempSync(join(tmpdir(), "bili-4982-lineage-")); const filename = join(dir, "index.db"); let store = UnifiedStore.open(filename); - const raw = openSqliteDatabase(filename, "node:sqlite").db; + // Engine unpinned on purpose: the store above used auto-detect, and bun + // has no node:sqlite to pin. + const raw = openSqliteDatabase(filename).db; try { for (const id of ["parent", "other", "placeholder"]) raw.prepare("INSERT INTO sessions (session_id, created_at, updated_at) VALUES (?, 1, 1)").run(id); @@ -131,7 +133,7 @@ for (const fail of [false, true]) { const dir = mkdtempSync(join(tmpdir(), "bili-4982-atomic-")); const filename = join(dir, "index.db"); const store = UnifiedStore.open(filename); - const raw = openSqliteDatabase(filename, "node:sqlite").db; + const raw = openSqliteDatabase(filename).db; try { raw.prepare("INSERT INTO sessions (session_id, created_at, updated_at) VALUES ('parent', 1, 1)").run(); const bytes = Buffer.from("body"); diff --git a/tests/plugin-fork.test.ts b/tests/plugin-fork.test.ts index 88720715af..e1db2ff6a6 100644 --- a/tests/plugin-fork.test.ts +++ b/tests/plugin-fork.test.ts @@ -140,7 +140,9 @@ test("HTTP fork preserves sparse parent ledger before the child's first save", { assert.equal(parent.state.blocks.length, 1); parent.metadata.publicSnapshotRetained = true; assert(h.store.flushSync(parent)); - const raw = openSqliteDatabase(join(h.dir, "sessions", "index.db"), "node:sqlite"); + // Engine unpinned on purpose: the harness store used auto-detect, and bun + // has no node:sqlite to pin. + const raw = openSqliteDatabase(join(h.dir, "sessions", "index.db")); // Model a ledger with retired historical positions: live messages are // at 0, 3, 4, never the snapshot's dense array positions 0, 1, 2. const positions = raw.db.prepare("SELECT seq FROM messages WHERE session_id = ? AND seq > 0 ORDER BY seq DESC").all(parent.id) as { seq: number }[]; @@ -165,7 +167,7 @@ test("HTTP fork preserves sparse parent ledger before the child's first save", { assert(h.store.flushSync(child)); assert.deepEqual(h.store.loadSync(child.id)!.state.messageRefs, parent.state.messageRefs); assert.deepEqual(JSON.parse(JSON.stringify(h.store.loadSync(child.id)!.state.blocks)), JSON.parse(JSON.stringify(child.state.blocks))); - const verify = openSqliteDatabase(join(h.dir, "sessions", "index.db"), "node:sqlite"); + const verify = openSqliteDatabase(join(h.dir, "sessions", "index.db")); try { const bounds = verify.db.prepare("SELECT start_seq, end_seq FROM blocks WHERE session_id = ?").get(child.id) as { start_seq: number; end_seq: number }; assert.equal(bounds.start_seq, 0); diff --git a/tests/storage-bun-sqlite.test.ts b/tests/storage-bun-sqlite.test.ts new file mode 100644 index 0000000000..2feb29d12e --- /dev/null +++ b/tests/storage-bun-sqlite.test.ts @@ -0,0 +1,321 @@ +/** + * bun:sqlite as bili's unified-store engine (this fork's bun support). + * + * Upstream bili only knows better-sqlite3 and node:sqlite. Under bun neither + * exists: there is no `node:sqlite` module, and a better-sqlite3 N-API + * prebuild cannot be loaded by bun at all. The only engine bun has is its + * builtin `bun:sqlite`, which is synchronous like better-sqlite3 but differs + * in three ways src/storage/driver.ts's adapter has to absorb: + * + * 1. NAMED PARAMETERS bind by the exact sigil written in the SQL (`:a`, `@b`, + * `$c`); the store's SQL is better-sqlite3 style and passes plain + * `{ a: 1 }` bags. + * 2. BLOB columns come back as a bare `Uint8Array`, not a Buffer. + * 3. `run()` reports `changes` / `lastInsertRowid` as BigInt, and the + * database has no `.open` flag. + * + * Tests 1-6 pin that contract against a fake bun Database so they run on the + * Node CI runner too (the seam `setBunDatabaseFactoryForTests` bypasses the + * unloadable module). The last group runs only under bun and drives the real + * builtin, including the write-lock mode the #2690 multi-process topology + * depends on. + */ + +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 { + isBunRuntime, + openSqliteDatabase, + resolvedSqliteEngineInfo, + setBunDatabaseFactoryForTests, + setPreferredSqliteEngineForTests, + setSqliteProbeOverridesForTests, + type BunSqliteDatabase, +} from "../src/storage/driver.ts"; +import { UnifiedStore } from "../src/storage/store.ts"; +import { planIngest, type LegacySessionLike } from "../src/storage/ingest.ts"; +import type { CoreMessage } from "acp-kernel"; + +process.env.BILI_PERSIST_ZSTD = "0"; + +type Call = { kind: "exec" | "run" | "get" | "all"; sql: string; args: unknown[] }; + +/** Minimal stand-in for bun's Database: records every call, returns the shapes + * bun really returns (BigInt counters, Uint8Array BLOB, null for no row). */ +class FakeBun implements BunSqliteDatabase { + readonly calls: Call[] = []; + readonly txModes: string[] = []; + closeCount = 0; + /** What get() hands back; bun returns null where better-sqlite3 says undefined. */ + row: unknown = { n: 5, blob: new Uint8Array([1, 2, 3]) }; + exec(sql: string): unknown { + this.calls.push({ kind: "exec", sql, args: [] }); + return undefined; + } + prepare(sql: string) { + const rec = (kind: Call["kind"], args: unknown[]) => this.calls.push({ kind, sql, args }); + return { + run: (...args: unknown[]) => (rec("run", args), { changes: 2n, lastInsertRowid: 7n }), + get: (...args: unknown[]) => (rec("get", args), this.row), + all: (...args: unknown[]) => (rec("all", args), []), + }; + } + transaction(fn: () => T): (() => T) & { immediate(): T; deferred(): T; exclusive(): T } { + const wrap = (mode: string) => () => { + this.txModes.push(mode); + return fn(); + }; + return Object.assign(wrap("default"), { immediate: wrap("immediate"), deferred: wrap("deferred"), exclusive: wrap("exclusive") }); + } + close(): void { + this.closeCount++; + } +} + +function openFake(): { db: ReturnType["db"]; fake: FakeBun } { + const fake = new FakeBun(); + setBunDatabaseFactoryForTests(() => fake); + const { db } = openSqliteDatabase("/unused/index.db", "bun:sqlite"); + return { db, fake }; +} + +function reset(): void { + setBunDatabaseFactoryForTests(null); + setPreferredSqliteEngineForTests(null); + setSqliteProbeOverridesForTests(null); +} + +test("bun named params: every sigil the SQL writes is offered to bun", () => { + try { + const { db, fake } = openFake(); + db.prepare("INSERT INTO t (a, b, c) VALUES (:a, @b, $c)").run({ a: 1, b: "x", c: true }); + const bag = fake.calls[0].args[0] as Record; + assert.deepEqual(bag, { a: 1, ":a": 1, b: "x", "@b": "x", c: true, "$c": true }); + // A literal that merely LOOKS like a sigil must not invent a binding. + db.prepare("SELECT ':nope' AS s, x::int AS i FROM t WHERE y = :y").run({ y: 2 }); + const second = fake.calls[1].args[0] as Record; + assert.deepEqual(Object.keys(second).sort(), [":y", "y"]); + } finally { + reset(); + } +}); + +test("bun args that are not a named bag pass through untouched", () => { + try { + const { db, fake } = openFake(); + const blob = new Uint8Array([9, 9]); + const when = new Date(0); + db.prepare("INSERT INTO media VALUES (?, ?, ?)").run(blob, when, 3); + assert.deepEqual(fake.calls[0].args, [blob, when, 3]); + assert.equal(fake.calls[0].args[0], blob, "the caller's own binary argument must reach bun as-is"); + // Named SQL driven positionally: no rewriting, no crash. + db.prepare("SELECT * FROM t WHERE a = :a").run(4); + assert.deepEqual(fake.calls[1].args, [4]); + } finally { + reset(); + } +}); + +test("bun rows: BLOB becomes Buffer, no row becomes undefined", () => { + try { + const { db, fake } = openFake(); + const row = db.prepare("SELECT n, blob FROM t WHERE a = :a").get({ a: 1 }) as { n: number; blob: unknown }; + assert.equal(row.n, 5); + assert.ok(Buffer.isBuffer(row.blob), "the store's media readers expect a Buffer, not a bare Uint8Array"); + assert.deepEqual([...(row.blob as Buffer)], [1, 2, 3]); + fake.row = null; + assert.equal(db.prepare("SELECT n FROM t WHERE a = :a").get({ a: 404 }), undefined, "bun hands back null where better-sqlite3 hands back undefined"); + } finally { + reset(); + } +}); + +test("bun run() reports numeric changes/lastInsertRowid", () => { + try { + const { db } = openFake(); + const res = db.prepare("UPDATE t SET a = :a WHERE b = :b").run({ a: 1, b: 2 }); + assert.equal(typeof res.changes, "number"); + assert.deepEqual(res, { changes: 2, lastInsertRowid: 7 }); + } finally { + reset(); + } +}); + +test("bun transactions: writes take the write lock up front, reads defer", () => { + try { + const { db, fake } = openFake(); + assert.equal(db.transaction(() => "written"), "written"); + assert.equal(db.readTransaction(() => "read"), "read"); + assert.deepEqual(fake.txModes, ["immediate", "deferred"]); + assert.equal(db.open, true); + db.close(); + assert.equal(db.open, false); + db.close(); + assert.equal(fake.closeCount, 1, "close() must be idempotent — the store closes on both the happy and the failing path"); + } finally { + reset(); + } +}); + +test("bun probe is false on real Node, so the #2833 ladder stays authoritative there", () => { + try { + setSqliteProbeOverridesForTests(null); + if (isBunRuntime()) { + assert.equal(resolvedSqliteEngineInfo() === null || resolvedSqliteEngineInfo()?.name === "bun:sqlite", true); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-bun-engine-")); + const { db, engine, source } = openSqliteDatabase(path.join(dir, "index.db")); + assert.equal(engine, "bun:sqlite"); + assert.equal(source, "builtin"); + assert.deepEqual(resolvedSqliteEngineInfo(), { name: "bun:sqlite", source: "builtin" }); + db.close(); + } else { + // On Node there is no bun:sqlite to load: an engine chosen there could + // never open, so step 0 of the ladder must decline. + assert.throws(() => require("bun:sqlite"), () => true); + assert.equal(openSqliteDatabase("/unused/index.db").engine === "bun:sqlite", false); + } + } finally { + reset(); + } +}); + +// --- the real builtin, bun only ---------------------------------------------- + +const notBun = !isBunRuntime() && "bun:sqlite exists only under bun"; + +test("real bun:sqlite round-trips the store's SQL shapes", { skip: notBun }, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-bun-real-")); + const { db, engine } = openSqliteDatabase(path.join(dir, "index.db"), "bun:sqlite"); + assert.equal(engine, "bun:sqlite"); + try { + // The PRAGMAs the store issues at open, including the ones whose result + // row bun must still hand back (journal_mode). + db.exec("PRAGMA journal_mode = WAL; PRAGMA busy_timeout = 5000;"); + assert.equal((db.prepare("PRAGMA journal_mode").get() as { journal_mode: string }).journal_mode, "wal"); + db.exec("CREATE TABLE t (a INTEGER PRIMARY KEY, b TEXT, c BLOB)"); + db.transaction(() => { + db.prepare("INSERT INTO t (a, b, c) VALUES (:a, :b, :c)").run({ a: 1, b: "hello", c: new Uint8Array([1, 2, 3]) }); + db.prepare("INSERT INTO t (a, b, c) VALUES (:a, :b, :c)").run({ a: 2, b: "world", c: new Uint8Array([4]) }); + }); + const row = db.prepare("SELECT a, b, c FROM t WHERE a = :a").get({ a: 1 }) as { a: number; b: string; c: unknown }; + assert.deepEqual({ a: row.a, b: row.b }, { a: 1, b: "hello" }); + assert.ok(Buffer.isBuffer(row.c)); + assert.deepEqual([...(row.c as Buffer)], [1, 2, 3]); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM t").get() as { n: number }).n, 2); + } finally { + db.close(); + } +}); + +test("real bun:sqlite: BEGIN really opens, rollback reverts nested writes, lock releases", { skip: notBun }, async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-bun-tx-")); + const file = path.join(dir, "index.db"); + // bun ships no ambient types here (tsc runs on Node), and the dist external + // gate only tolerates the specifier as an opaque variable — same shape the + // driver itself loads it through. + const spec = "bun:" + "sqlite"; + const { Database } = (await import(spec)) as { Database: new (p: string) => BunSqliteDatabase & { inTransaction: boolean } }; + const raws: (BunSqliteDatabase & { inTransaction: boolean })[] = []; + setBunDatabaseFactoryForTests((p) => { + const d = new Database(p); + raws.push(d); + return d; + }); + const db = openSqliteDatabase(file, "bun:sqlite").db; + const other = openSqliteDatabase(file, "bun:sqlite").db; + try { + db.exec("PRAGMA busy_timeout = 5000; CREATE TABLE t (a INTEGER PRIMARY KEY)"); + other.exec("PRAGMA busy_timeout = 5000"); + let lockHeld: boolean | null = null; + let nestedRan = false; + assert.throws( + () => + db.transaction(() => { + lockHeld = raws[0]!.inTransaction; + db.prepare("INSERT INTO t VALUES (?)").run(1); + // Nested through the adapter: bun ignores the inner BEGIN — + // the same contract better-sqlite3 gives the store, so this + // must neither throw nor commit early. + nestedRan = db.transaction(() => (db.prepare("INSERT INTO t VALUES (?)").run(2), true)) === true; + throw new Error("boom"); + }), + /boom/, + ); + assert.equal(lockHeld, true, "the engine must be inside BEGIN while the callback runs"); + assert.equal(nestedRan, true); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM t").get() as { n: number }).n, 0, "the outer rollback must revert the nested write as well"); + // An aborted IMMEDIATE transaction must hand the write lock back: a second + // connection writes immediately instead of queueing on busy_timeout (#2690). + other.transaction(() => void other.prepare("INSERT INTO t VALUES (?)").run(3)); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM t").get() as { n: number }).n, 1); + assert.equal(db.readTransaction(() => (db.prepare("SELECT COUNT(*) AS n FROM t").get() as { n: number }).n), 1); + } finally { + db.close(); + other.close(); + reset(); + } +}); + +// ── 5. the real store on bun:sqlite ───────────────────────────────────────── +// The fakes above pin the adapter; this drives the actual UnifiedStore the proxy +// runs on: open (PRAGMA ladder, foreign_keys, verbatim migrations, PRAGMA +// quick_check), ingest (named-param inserts inside BEGIN IMMEDIATE), reads, +// close (WAL checkpoint) and a reopen through a fresh driver instance. +function storeMsg(id: string): CoreMessage { + return { id, role: "user", contentType: "text", text: `body ${id}` } as unknown as CoreMessage; +} + +/** The minimal legacy session the storage suites feed the store. */ +function storeSession(id: string, tail: CoreMessage[]): LegacySessionLike { + const byRaw: Record = {}; + const byRef: Record = {}; + tail.forEach((m, i) => { + const ref = `m${String(i + 1).padStart(5, "0")}`; + byRaw[m.id] = ref; + byRef[ref] = m.id; + }); + const blk = { + blockId: "blk1", runId: 1, createdAt: 1_000, tier: 1, active: true, + summary: "summary body", kind: "fold", reason: "test", + effectiveMessageIds: tail.map((m) => m.id), directMessageIds: [] as string[], + }; + return { + id, createdAt: 1_000, lastSeen: 2_000, + meta: { protocol: "openai" }, stats: {}, metadata: {}, + state: { blocks: [blk as never], nextBlockId: 2, nextRunId: 2, messageRefs: { byRaw, byRef } }, + blockContents: new Map(), lastMessages: tail, lastMessagesFolded: false, + pluginSnapshot: undefined, contentStore: undefined, + }; +} + +test("the real UnifiedStore round-trips a session on bun:sqlite", { skip: notBun }, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-bun-store-")); + const dbPath = path.join(dir, "index.db"); + const tail = ["a", "b", "c"].map(storeMsg); + let store: UnifiedStore | undefined; + try { + store = UnifiedStore.open(dbPath); + assert.equal(store.engine, "bun:sqlite", "auto-detect must resolve the builtin engine under bun"); + assert.equal(store.engineSource, "builtin"); + store.ingestSession(planIngest(storeSession("sess-bun", tail))); + assert.ok(store.sessionCounters("sess-bun"), "the counter row landed"); + const rows = store.messagesForIds("sess-bun", ["a", "b", "c"], false); + assert.deepEqual(rows.map((r) => r.msgId), ["a", "b", "c"]); + assert.ok(rows.every((r) => r.content.length > 0), "content rows were written and read back"); + store.close(); + store = undefined; + const again = UnifiedStore.open(dbPath); + try { + assert.deepEqual(again.messagesForIds("sess-bun", ["b", "c"], false).map((r) => r.msgId), ["b", "c"], + "the data survives close (WAL checkpoint) and a reopen through a fresh driver instance"); + } finally { + again.close(); + } + } finally { + try { store?.close(); } catch { /* already closed */ } + fs.rmSync(dir, { recursive: true, force: true }); + } +}); diff --git a/tests/storage-unified.test.ts b/tests/storage-unified.test.ts index 3c5908f29a..73f841cc8c 100644 --- a/tests/storage-unified.test.ts +++ b/tests/storage-unified.test.ts @@ -13,7 +13,7 @@ import { restampRefsToLedger } from "acp-kernel"; import { UnifiedStore } from "../src/storage/store.ts"; import { resolveStorageMode } from "../src/storage/shadow.ts"; import { resolveStorageWalJournalSizeLimit } from "../src/knobs.ts"; -import { setPreferredSqliteEngineForTests, type SqliteEngineName } from "../src/storage/driver.ts"; +import { probeBuiltinSqlite, setPreferredSqliteEngineForTests, type SqliteEngineName } from "../src/storage/driver.ts"; /** * Unified-storage acceptance (Phase 1, #2671). @@ -200,11 +200,18 @@ function betterSqliteAvailable(): boolean { } } +/** node:sqlite is a NODE builtin; bun ships `bun:sqlite` instead and cannot load + * it, so the legs that drive that engine explicitly skip on a bun runtime (the + * driver probe is the same test the production ladder runs). */ +function nodeSqliteAvailable(): boolean { + return probeBuiltinSqlite(); +} + test("storage unified: corpus round-trip digests equal the legacy manifest (better-sqlite3)", { skip: !betterSqliteAvailable() && "better-sqlite3 not installed (optional native dependency)" }, () => { for (const name of Object.keys(CASE_META)) runCase("better-sqlite3", name); }); -test("storage unified: corpus round-trip digests equal the legacy manifest (node:sqlite)", () => { +test("storage unified: corpus round-trip digests equal the legacy manifest (node:sqlite)", { skip: !nodeSqliteAvailable() && "node:sqlite not available on this runtime (bun ships bun:sqlite)" }, () => { for (const name of Object.keys(CASE_META)) runCase("node:sqlite", name); }); @@ -772,7 +779,7 @@ test("storage: BLOCKED ref replays via byRaw only, never into byRef", () => { // binding per sessions row — and a dev build that already carried the // columns in its V1 DDL must migrate without a duplicate-column error. // --------------------------------------------------------------------------- -test("schema v2: dev-window v1 database upgrades in place (identity columns added, rows survive)", async () => { +test("schema v2: dev-window v1 database upgrades in place (identity columns added, rows survive)", { skip: !nodeSqliteAvailable() && "node:sqlite not available on this runtime (bun ships bun:sqlite)" }, async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-schema-v2-")); try { const dbPath = path.join(dir, "index.db"); @@ -833,7 +840,7 @@ test("schema v2: dev-window v1 database upgrades in place (identity columns adde // #4313: v10 immutable first-seen time column (messages.ts) // --------------------------------------------------------------------------- -test("schema v10: v9→v10 migration adds messages.ts without backfill; idempotent", async () => { +test("schema v10: v9→v10 migration adds messages.ts without backfill; idempotent", { skip: !nodeSqliteAvailable() && "node:sqlite not available on this runtime (bun ships bun:sqlite)" }, async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-unified-v10-")); const dbPath = path.join(dir, "index.db"); try { diff --git a/tests/unified-remap-collision.test.ts b/tests/unified-remap-collision.test.ts index 702c44e8a3..c218541d5f 100644 --- a/tests/unified-remap-collision.test.ts +++ b/tests/unified-remap-collision.test.ts @@ -99,7 +99,9 @@ function openFixture(sessionId: string): Fixture { seed.close(); const handles: { close?: () => void }[] = []; - const openedRaw = openSqliteDatabase(dbPath, "node:sqlite"); + // Engine unpinned on purpose: the seeded store used auto-detect, and bun has + // no node:sqlite to pin. + const openedRaw = openSqliteDatabase(dbPath); const raw = openedRaw.db as unknown as { prepare(sql: string): { run(...args: unknown[]): unknown; get(...args: unknown[]): unknown }; close?(): void }; handles.push(raw); return { From 0a46006d3ac49e1a98863689858185e4a6a89876 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 1 Nov 2026 18:27:39 +0800 Subject: [PATCH 2/3] fix(test): pin the Node probe without opening a real DB path MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review finding on #5435 (ai-aligned fix, no production code touched): the 'bun probe is false on real Node' test called openSqliteDatabase("/unused/index.db") to assert the picked engine is not bun:sqlite. On every Node runtime the ladder resolves a real engine (node:sqlite builtin or better-sqlite3) and then genuinely tries to open the nonexistent path, throwing 'unable to open database file' before it can report anything — the assertion could never pass under Node. Pin probeBunSqlite() === false instead: that IS step 0 of the ladder, and it needs no database at all. Verified locally: Node 22 (6 pass / 3 bun-only skips) and bun 1.4.0 (9/9 pass). --- tests/storage-bun-sqlite.test.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/storage-bun-sqlite.test.ts b/tests/storage-bun-sqlite.test.ts index 2feb29d12e..9e8c53b6c5 100644 --- a/tests/storage-bun-sqlite.test.ts +++ b/tests/storage-bun-sqlite.test.ts @@ -29,6 +29,7 @@ import * as path from "node:path"; import { isBunRuntime, openSqliteDatabase, + probeBunSqlite, resolvedSqliteEngineInfo, setBunDatabaseFactoryForTests, setPreferredSqliteEngineForTests, @@ -172,10 +173,11 @@ test("bun probe is false on real Node, so the #2833 ladder stays authoritative t assert.deepEqual(resolvedSqliteEngineInfo(), { name: "bun:sqlite", source: "builtin" }); db.close(); } else { - // On Node there is no bun:sqlite to load: an engine chosen there could - // never open, so step 0 of the ladder must decline. + // On Node there is no bun:sqlite to load, so step 0 of the ladder must + // decline. Pin the probe itself — openSqliteDatabase() on a fake path + // throws CANTOPEN before it could report its engine (review finding). assert.throws(() => require("bun:sqlite"), () => true); - assert.equal(openSqliteDatabase("/unused/index.db").engine === "bun:sqlite", false); + assert.equal(probeBunSqlite(), false); } } finally { reset(); From 1d11fd4e5a88bbb0dee6f05837381d3f855f5de6 Mon Sep 17 00:00:00 2001 From: ci-check Date: Sun, 1 Nov 2026 18:27:39 +0800 Subject: [PATCH 3/3] refactor(storage): drop the unused export on BunSqliteCtor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The check-unused-exports CI gate fails on this head: BunSqliteCtor is exported but only used inside driver.ts itself (the require() cast at openBunSqlite). Drop the leading export per the gate's INTERNAL_ONLY suggestion — no importers exist. --- src/storage/driver.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/storage/driver.ts b/src/storage/driver.ts index 58a4d085b8..c2f63486ad 100644 --- a/src/storage/driver.ts +++ b/src/storage/driver.ts @@ -248,7 +248,7 @@ export interface BunSqliteDatabase { close(): void; } -export type BunSqliteCtor = new (path: string) => BunSqliteDatabase; +type BunSqliteCtor = new (path: string) => BunSqliteDatabase; let bunDatabaseFactoryForTests: ((path: string) => BunSqliteDatabase) | null = null;