Skip to content

feat: SQLite engine self-bootstrap — builtin -> host -> cached -> self-download (#2833) - #2845

Merged
ranxianglei merged 6 commits into
masterfrom
2026-10-12_sqlite-engine-bootstrap
Oct 13, 2026
Merged

ranxianglei merged 6 commits into
masterfrom
2026-10-12_sqlite-engine-bootstrap

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

Closes #2833 (thorough fix for the #2823 build-blocked failure domain; #2825 was the stopgap).

Mechanism

#2823: under pnpm >=10 strictDepBuilds, any native dependency needing install-time build scripts that is not on the host's allowlist hard-fails the whole install (ERR_PNPM_IGNORED_BUILDS -> dsh reports build-blocked). #2825 removed better-sqlite3 from optionalDependencies and pinned the no-engine legacy-only degrade contract. This PR lands the owner-approved thorough fix: engine acquisition never depends on host install-time build-script approval, via runtime self-bootstrapping.

Resolution order (per request, sticky per process)

  1. builtin — node:sqlite when the runtime provides it (Node >= 22.5); zero native deps, never touches the gate;
  2. host — opportunistic require("better-sqlite3") probe (hosts that already ship it keep using it);
  3. cached self-download — previously bootstrapped copy in <cache>/billion-context/sqlite/better-sqlite3-13.0.3/;
  4. self-download — one-time download of the pinned better-sqlite3 13.0.3 npm tarball (in-tarball N-API prebuilds for all 8 platform-arch targets, zero lifecycle scripts), sha512-pinned in-repo, extracted by a dependency-free gunzip+ustar reader, atomic publish, proxy-aware via the existing network.proxy chain;
  5. none — legacy JSON only (the fix(storage): drop better-sqlite3 optional dep (#2823) #2825 contract, unchanged).

Failure is fail-safe at every step: download error arms a 6h cooldown marker, then legacy-only; corrupt cache dir is logged and skipped (no re-download loop); unsupported platform never downloads. Bounded startup block: wired into bili start before the first store open, single 10s fetch timeout, once per machine lifetime.

Config surface

New key storage.sqliteAutoDownload (boolean, default true) + env override BILI_SQLITE_AUTO_DOWNLOAD — documented in CONFIGURATION.md en/zh.

  • What it does: gates the network fetch in step 4 only. A previously-cached copy is used even when false; disabling only prevents new downloads. All other resolution steps are unaffected by the switch.
  • Why the existing surface cannot express it: no existing knob controls engine acquisition (the pre-existing knobs control storage mode/format, not where the engine comes from).
  • Alternatives considered: (a) vendor the full package in-repo (~27MB unpacked across all targets) — rejected against the repo's lean-dist philosophy and the fact that Node >= 22.5 users never need it; (b) per-engine policy objects — YAGNI, one boolean covers the real decision.
  • Migration: none. Absent config behaves as true; existing installs are unaffected (they either have a builtin/host engine or were already legacy-only).

Behavior changes (old -> new)

  1. Engine preference flip on Node >= 22.5: old = better-sqlite3 preferred when present, node:sqlite fallback; new = node:sqlite preferred when present, better-sqlite3 fallback. Both are spec-compliant drivers behind the same seam; the unified store records which engine wrote what and reads are engine-agnostic. Reason: the builtin has zero native-dep footprint and can never trip a host gate.
  2. New capability, default-on: machines without a builtin or host engine (e.g. Node 20/21) now perform a one-time ~11MB registry download of a pinned, sha512-verified prebuilt tarball instead of silently running legacy-only. This is the point of the issue (0.1.189更新失败,插件市场更新报错 #2823 impact: those hosts got nothing). Opt-out: storage.sqliteAutoDownload: false.
  3. Bounded startup delay: bili start may block up to ~10s once on first-ever bootstrap (only on machines that reach step 4); subsequent starts are a local cache hit. After a failed attempt, a 6h cooldown applies and startup proceeds immediately in legacy-only mode.
  4. Enablement log now records engine/source (e.g. [engine:better-sqlite3/self-downloaded]) for field diagnosis — additive log detail only.

No change to: wire protocol, persistence format/version (index.db schema untouched; #2771 corrupt-index degrade, CAS refcounting, dual-domain affinity all preserved), nudge cadence, kernel, updater.

Tests & pre-flight

  • New hermetic suite tests/storage-engine-bootstrap.test.ts (21 tests): loopback mock registry, isolated XDG cache, fake pinned tarball fixtures — resolution order x5, bootstrap flows (happy path/cache-hit/sha-mismatch-quarantine/cooldown-expiry/offline/disabled-knob/legacy-short-circuit/builtin/host/unsupported-platform/concurrent-dedup) x10, extractor security (non-gzip, missing-prebuilt, path traversal, symlink rejection) x4, knob matrix, platform key sanity.
  • The hermetic suite caught a REAL extractor bug before shipping: the ustar parser advanced past header+padding but not the payload, desynchronizing every header after any non-empty entry. Fixed at source (off += size + pad512(size)).
  • Sibling suites green on this head: storage-engine-proofs 8/8, storage-unified 13/13. typecheck clean, build clean.
  • Real-download lane tests/e2e/e2e-sqlite-bootstrap.test.ts (gated ACP_TEST_SQLITE_BOOTSTRAP=1, outside the default glob): verified locally end-to-end against the live registry on linux-x64 — download, sha verify, load, DDL/DML/rollback proof, full UnifiedStore schema migration over the self-downloaded binding.

Ref: #2823 (bug), #2825 (stopgap + contract), #2833 (this design).

ework-agent added 2 commits October 12, 2026 03:23
…f-download (#2833)

Engine acquisition no longer depends on host install-time build-script
approval (the strictDepBuilds gate behind #2823/#2825):

- detectEngine order: built-in node:sqlite (Node >= 22.5) -> host
  better-sqlite3 require probe -> registered self-downloaded loader ->
  none (legacy-only per the #2825 contract)
- new src/storage/engine-bootstrap.ts: one-time download of the pinned
  better-sqlite3 13.0.3 npm tarball (in-tarball N-API prebuilds for all
  8 platform-arch targets, no build scripts), sha512-pinned in-repo,
  extracted via a dependency-free gunzip+ustar reader into
  <cache>/sqlite/better-sqlite3-<version>, atomic publish, 6h cooldown
  after failure, proxy-aware via the existing network.proxy chain
- storage.sqliteAutoDownload (default true) / BILI_SQLITE_AUTO_DOWNLOAD
  gate the network fetch only; a cached copy is used even when false
- wired into bili start before the first store open (bounded ~10s);
  enablement log now records engine/source for field diagnosis
@github-actions

github-actions Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-12_sqlite-engine-bootstrap (10c28aa)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.3150-pr.2845.cf24a59

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr2845.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,开始 review PR #2845(branch 2026-10-12_sqlite-engine-bootstrap @ 62eb23e7)。这是 [PR] 镜像 issue,按规范走审查流程:拉分支核对代码 + CI 状态 + 回归清点,结论用结构化八问回复。稍等。

ework-agent added 4 commits October 12, 2026 03:41
…unpassable

assert.equal from node:assert/strict is strictEqual: comparing the fake
driver's get() result against a fresh { ok: true } literal always fails on
reference equality, so the test could never pass. Use deepEqual to assert
the actual value (the point: the registered self-downloaded loader drives a
real open through the driver).

Review fix for PR #2845 (found by local run of the suite: 20/21 with this
line failing).
downloadAndInstall published via fsp.rename(tmpDir, finalDir) only. When a
stale/partial final dir already exists (killed run, local tampering), the
rename fails ENOTEMPTY over the non-empty dir, so every retry re-downloads
and fails at publish, re-arming the 6h cooldown indefinitely — contradicting
the documented 'corrupt cache dir is skipped' contract. Before publishing:
a usable existing dir means a concurrent process already published the same
pinned artifact (treat as success); an unusable one is removed and replaced.
Adds the hermetic regression test (stale dir -> downloaded, complete cache,
no cooldown marker).

Review fix for PR #2845.
…xports gate

OpenedDatabase (driver.ts) and EngineBootstrapSpec/DEFAULT_ENGINE_SPEC/
BootstrapStatus/EnsureSqliteEngineOptions (engine-bootstrap.ts) have no
references outside their declaring files and tsup emits no d.ts, so the
exports are pure surface bloat. Unexport them; behavior unchanged.

Review fix for PR #2845 (CI unused-exports job).
…blocks

The PR hand-edited the generated param-ref/env-map blocks instead of adding
a seed entry, which broke docs-sync/docs-coverage/config-surface-guard. Add
the seed to website/config-reference/process.yaml and regenerate (also fixes
the env-map row ordering the generator sorts by name). Sync the static zh
long-form BILI_STORAGE_UNIFIED entry to the new engine-resolution wording.

Review fix for PR #2845.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review complete — 4 review-fix commits pushed to the branch (62eb23e70..10c28aaf9), CI re-running. Direction is sound; the mechanism is implemented exactly as designed in #2833. Details below.

What I verified (not just the diff)

  • Entry-point coverage: startServer has exactly one production call site (src/cli.ts:603), and every native plugin lane (opencode/pi/dsh/omp) spawns its proxy via dist/index.js start → all proxy processes funnel through the single ensureSqliteEngine chokepoint. No lane escapes the bootstrap.
  • Resolution order & fail-safety read through end-to-end (engine-bootstrap.ts + driver.ts): builtin → host → cached → self-download → none, sticky per process, every failure path lands in legacy-only. Cache-hit check correctly precedes the auto-download gate (cached copies used even when the knob is off). Extractor rejects symlinks/hardlinks/devices/traversal, include-filter limits materialization to ~1.5 MB, atomic tmp→rename publish, sha512 stream-verified, cooldown marker corrupt-fails-open.
  • Local runs (targeted, per test discipline): typecheck clean, build clean, storage suites 55 tests green (bootstrap 22 + proofs + unified + review-fixes + replicas), knobs/config/cli suites 24 green. node:sqlite confirmed unflagged on Node 22.23.x here, consistent with the "Node >= 22.5" wording.
  • Regression sweep of touched paths: index.db schema untouched; [Bug][storage] corrupt index.db bricks SessionStore construction in shadow/full mode (violates the sidecar never-breaks-legacy policy) #2771 corrupt-index degrade, CAS refcounting, dual-domain affinity intact; wire protocol/nudge/kernel/updater untouched; shadow enablement log change is additive ([engine:<name>/<source>]). Disclosed behavior changes (engine preference flip on modern Node, default-on one-time download, bounded ~10s first-boot delay) match the code.

What I fixed (labeled commits on the branch)

  1. fix(test) — the hermetic suite had an unpassable assertion: assert.equal under node:assert/strict is reference-equality, so assert.equal(o.db.prepare("SELECT 1").get(), { ok: true }) could never pass (verified: 20/21 locally, exactly this line). Changed to deepEqual. Note: the PR body claimed sibling suites green but never claimed the new suite itself green — this explains why.
  2. fix(storage) — stale-cache-dir loop: if an unusable final dir already existed (killed run / local tampering), fsp.rename over the non-empty dir fails ENOTEMPTY, so every retry re-downloaded and failed at publish, re-arming the 6h cooldown forever — contradicting the documented "corrupt cache dir is skipped" contract. Now: usable existing dir = concurrent winner (treated as success); unusable = removed and replaced. Added the hermetic regression test.
  3. refactor(storage) — dropped 5 internal-only exports flagged by the unused-exports gate (no external references; tsup emits no d.ts). Behavior-neutral.
  4. docs(config) — the original commits hand-edited the generated param-ref/env-map blocks instead of adding a seed entry, which broke docs-sync, docs-coverage, and config-surface-guard. Added the seed to website/config-reference/process.yaml and regenerated (the generator also corrected the env-map row ordering). Synced the static zh long-form BILI_STORAGE_UNIFIED entry, which the original docs commit left stale (still described the pre-彻底解决 dsh/pnpm 构建脚本门导致 build-blocked:SQLite 引擎自举(内置优先 → 运行时自下载 → 复用宿主) #2833 engine behavior). All four gates now pass locally.

Residuals (assessed, not blocking)

  • Cross-process race: dedup is per-process only; two cold starts in the same window both download once — the rename loser now degrades gracefully (see fix fix: address all code review findings (condense, routing, session-id, dead code) #2 above) and the next boot is a cache hit. Fail-safe, rare.
  • .wip-*/.dl-* tmp entries leak if a process is SIGKILLed mid-extract (prune only matches better-sqlite3-*). Bounded few-MB disk hygiene; not worth expanding this PR's scope.
  • Pinned sha512 (13.0.3): I cannot independently fetch registry.npmjs.org from this environment; the digest rests on your local e2e attestation (ACP_TEST_SQLITE_BOOTSTRAP=1). The hermetic lane covers everything except the live artifact itself, which is exactly what the gated e2e exists for.

结构化八问

  1. 是什么问题:pnpm ≥10 strictDepBuilds 下原生依赖安装期构建脚本未获批会硬失败整个安装(0.1.189更新失败,插件市场更新报错 #2823),导致无内置 SQLite 的宿主拿不到统一存储引擎;fix(storage): drop better-sqlite3 optional dep (#2823) #2825 只做了降级止血。本 PR 落地 owner 批准的彻底修法:引擎获取完全不依赖宿主安装期审批,运行时自举(builtin → host → cached → self-download → none)。
  2. 什么原因导致的:根因是"引擎获取"与"宿主安装期构建脚本审批"耦合——引擎作为包依赖声明时,其 install-time build script 成为宿主管控面的一部分。修法把获取移到运行时(自下载钉死版本+sha512 的 N-API 预编译 tarball),从机制上解除耦合,不是堵症状。
  3. 影响范围与严重程度:修复前——Node < 22.5(或宿主未提供 node:sqlite)且启用 unified 存储的机器静默退化为 legacy-only(功能降级而非故障);修复后这些机器获得完整引擎。默认开启的自下载是新增能力,opt-out 为 storage.sqliteAutoDownload: false。
  4. 怎么修复的:五级解析顺序(进程内粘性),下载走既有 proxy 链与 registry mirror,流式 sha512 校验,零依赖 gunzip+ustar 提取器(白名单条目、拒绝符号链接/穿越),tmp→rename 原子发布,失败武装 6h cooldown 后 legacy-only,启动阻塞有界(单次 10s)。
  5. 是否有回归问题:审过的既有行为——index.db schema/CAS/双域亲和/[Bug][storage] corrupt index.db bricks SessionStore construction in shadow/full mode (violates the sidecar never-breaks-legacy policy) #2771 损坏降级均保持;wire 协议、nudge、kernel、updater 未触碰;唯一语义变更是 Node ≥ 22.5 上引擎偏好翻转(node:sqlite 优先于 better-sqlite3),已在 PR 正文披露旧值→新值+原因,两引擎同 seam 下规格兼容且 store 记录写入方。review 中发现并修掉两处真实缺陷(不可通过的测试断言、stale 缓存目录冷却循环)+ 文档生成流程违规(手改生成块)+ zh 文档失同步,均已以标注 commit 推回分支。
  6. 是否破坏缓存:不涉及模型前缀缓存;新增的是本机磁盘缓存(~/.cache/billion-context/sqlite/),失效策略为版本目录名+平台键,cooldown marker 损坏时 fail-open 向重试方向,无去重键漂移。
  7. 是否改了设计方向:无转向——按 彻底解决 dsh/pnpm 构建脚本门导致 build-blocked:SQLite 引擎自举(内置优先 → 运行时自下载 → 复用宿主) #2833 既定设计实现;驱动 seam 从"双引擎探测"扩展为"三来源解析",边界不变(driver 管解析与打开,bootstrap 只管下载/缓存步)。
  8. 是否引入了新的配置:是——storage.sqliteAutoDownload(boolean,默认 true)+ env BILI_SQLITE_AUTO_DOWNLOAD,已按 config surface 规则补种子并再生成 en/zh 文档;只闸门第 4 级网络下载,缓存副本不受开关影响;缺省行为等同 true,存量安装无需迁移。

判定:CI 在新 head(10c28aaf9)全绿后即可合并。 机制正确、测试有牙(断言全部对网络请求数/落盘布局/cooldown marker/错误形状钉死)、四个此前失败的守卫本地已全部转绿。合并请人工执行:#2845

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 全绿确认 — head 10c28aaf9 上 27/27 checks 通过(含此前失败的 unused-exports / docs-sync / docs-coverage / config-surface-guard,以及全部 test/e2e/real-client lanes),PR 状态 mergeable: clean。

四个 review-fix commit(断言修复、stale-cache-dir 自愈、internal-only 导出收敛、文档种子+再生成+zh 同步)均已随 CI 验证。可以合并了:#2845 (合并请人工执行)

ranxianglei added a commit that referenced this pull request Oct 13, 2026
…tter-sqlite3

The #2845 suite assumed better-sqlite3 is absent from node_modules (true
on fresh CI npm ci since #2825, false on dev machines that installed it
earlier): when present, the host branch opens with source "host" —
equally valid proof the branch was taken. Accept either outcome.
@ranxianglei
ranxianglei merged commit 79b7063 into master Oct 13, 2026
27 checks passed
@ranxianglei
ranxianglei deleted the 2026-10-12_sqlite-engine-bootstrap branch October 15, 2026 05:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

彻底解决 dsh/pnpm 构建脚本门导致 build-blocked:SQLite 引擎自举(内置优先 → 运行时自下载 → 复用宿主)

1 participant