From 10a9bc1c892d0fdaa796016cf49674c65e49078c Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 29 Oct 2026 16:06:52 +0800 Subject: [PATCH 1/6] fix: route corruption-shaped SQLite throws into the integrity quarantine decision (#4816/#5108) --- src/storage/integrity-check.ts | 33 ++++++++++++++++++--- src/storage/sqlite-errors.ts | 54 ++++++++++++++++++++++++++++++++++ src/storage/store.ts | 40 +++++++++++++++++++++---- 3 files changed, 118 insertions(+), 9 deletions(-) create mode 100644 src/storage/sqlite-errors.ts diff --git a/src/storage/integrity-check.ts b/src/storage/integrity-check.ts index 7a7f10fc4a..5e7149ee4a 100644 --- a/src/storage/integrity-check.ts +++ b/src/storage/integrity-check.ts @@ -157,7 +157,15 @@ try { const verdict = rows.map((row) => String(row.quick_check ?? "")).join(" ").trim(); parentPort.postMessage({ ok: true, verdict }); } catch (err) { - parentPort.postMessage({ ok: false, error: String(err) }); + // #5108/#4816: a corruption-shaped THROW out of quick_check (truncated file, + // garbage header, broken overflow chain) is a FAIL VERDICT, not "could not + // run" — classify it exactly like src/storage/sqlite-errors.ts does (inlined + // here because this string is bundled verbatim and cannot import modules; + // keep the two in sync, the worker-facet regression test pins both). + const m = String((err && err.message) || err); + const c = String((err && err.code) || "").toUpperCase(); + const corrupt = c === "SQLITE_CORRUPT" || c === "SQLITE_NOTADB" || m.includes("database disk image is malformed") || m.includes("file is not a database"); + parentPort.postMessage(corrupt ? { ok: false, corrupt: true, error: m } : { ok: false, error: m }); } `; @@ -169,7 +177,7 @@ const inflight = new Set(); * (#4609). Records the outcome, caches it (ok or fail — a cached fail makes * the NEXT open throw and quarantine via the #4175 path), and tells the * caller's store instance so a clean close can refresh the cache key. */ -export function scheduleBackgroundIntegrityCheck(dbPath: string, onVerdict?: (ok: boolean) => void): void { +export function scheduleBackgroundIntegrityCheck(dbPath: string, onVerdict?: (ok: boolean, detail?: string) => void): void { const size = statPart(dbPath)?.s ?? 0; loggerLog("info", `[storage] background quick_check started for ${dbPath} (${(size / (1024 * 1024)).toFixed(1)} MiB over the ${Math.round(effectiveSyncThreshold() / (1024 * 1024))} MiB sync threshold) — serving continues; the verdict lands in /__bili/status (#4609)`); inflight.add(dbPath); @@ -190,7 +198,7 @@ export function scheduleBackgroundIntegrityCheck(dbPath: string, onVerdict?: (ok worker.unref(); } }; - worker.on("message", (msg: { ok?: boolean; verdict?: string; error?: string }) => { + worker.on("message", (msg: { ok?: boolean; corrupt?: boolean; verdict?: string; error?: string }) => { finish(() => { if (msg.ok === true) { const verdict = String(msg.verdict ?? ""); @@ -207,8 +215,25 @@ export function scheduleBackgroundIntegrityCheck(dbPath: string, onVerdict?: (ok recordIntegrityOutcome(dbPath, false, 0, verdict.slice(0, 400)); writeIntegrityCache(dbPath, false, verdict.slice(0, 400)); loggerLog("error", `[storage] background quick_check FAILED for ${dbPath}: ${verdict.slice(0, 400)} — verdict cached; the next open quarantines this file set and reopens fresh (JSON envelopes remain the recovery source, #4175/#4609)`); - onVerdict?.(false); + // Detail rides with the verdict so a clean close can + // refresh the FAIL cache onto post-checkpoint stats + // (#5108/#4816) — without it the verdict would go stale + // after the first clean restart and never quarantine. + onVerdict?.(false, verdict.slice(0, 400)); } + } else if (msg.corrupt === true) { + // #5108/#4816: the scan itself threw a corruption-shaped error + // (the throwing shapes of CORRUPT/NOTADB). Same consequences as + // a bad verdict row: record loudly and cache the fail so the + // NEXT open quarantines + reopens fresh (#4175 path). Without + // this branch the throw fell into "could not run" below and the + // fail verdict was never recorded — a large corrupt store stayed + // unverified boot after boot with no quarantine ever running. + const detail = String(msg.error ?? "").slice(0, 400); + recordIntegrityOutcome(dbPath, false, 0, detail); + writeIntegrityCache(dbPath, false, detail); + loggerLog("error", `[storage] background quick_check threw a corruption-shaped error for ${dbPath}: ${detail} — FAIL verdict cached; the next open quarantines this file set and reopens fresh (JSON envelopes remain the recovery source, #5108/#4175)`); + onVerdict?.(false, detail); } else { loggerLog("warn", `[storage] background quick_check could not run for ${dbPath}: ${String(msg.error)} — the store serves unverified; the next boot rechecks`); } diff --git a/src/storage/sqlite-errors.ts b/src/storage/sqlite-errors.ts new file mode 100644 index 0000000000..e031712b39 --- /dev/null +++ b/src/storage/sqlite-errors.ts @@ -0,0 +1,54 @@ +/** + * #5108/#4816: corruption-shaped SQLite error classification. + * + * PRAGMA quick_check has TWO failure shapes: it can RETURN non-ok verdict + * rows (page-level damage), or it can THROW out of the statement itself + * (truncated file, garbage header, broken overflow chain — probe-verified on + * node:sqlite v22: ERR_SQLITE_ERROR with the raw sqlite3_errmsg text). The + * #4175 quarantine decision only saw the verdict-row shape, so every + * throwing corruption escaped as a raw driver error and degraded the store + * to legacy-only forever with no auto-heal. + * + * This classifier maps the throwing shapes onto the same decision. It + * matches ONLY SQLITE_CORRUPT / SQLITE_NOTADB: + * - better-sqlite3 stamps err.code with the symbolic name ("SQLITE_CORRUPT", + * "SQLITE_NOTADB"); + * - node:sqlite throws ERR_SQLITE_ERROR whose message IS the stable English + * errmsg text ("database disk image is malformed" / "file is not a + * database") — matched by substring, which also catches the + * [storage:] wrapper prefix openSqliteDatabase adds. + * + * Transient shapes MUST NOT match: BUSY/LOCKED (a live foreign process — + * the supported shared-directory topology, #3923/#3959), IOERR (Windows + * Defender real-time scan / sync-folder locks, #362 class), CANTOPEN + * (permissions). Quarantining a merely locked-but-healthy index over a + * transient condition would destroy a working index — the exact opposite of + * what recovery is for. + * + * NOTE: the background-check worker (integrity-check.ts WORKER_SOURCE) is + * bundled VERBATIM into dist and cannot import this module — it carries an + * inlined copy of these matchers. Keep the two in sync (the worker-facet + * regression test pins the behavior end to end). + */ + +const CORRUPTION_ERRMSG_MARKERS = [ + "database disk image is malformed", // SQLITE_CORRUPT + "file is not a database", // SQLITE_NOTADB +]; + +/** Returns the error detail when `err` is a corruption-shaped SQLite failure, + * null otherwise. */ +export function sqliteCorruptionDetail(err: unknown): string | null { + const code = (err as { code?: unknown } | null)?.code; + if (typeof code === "string") { + const upper = code.toUpperCase(); + if (upper === "SQLITE_CORRUPT" || upper === "SQLITE_NOTADB") { + return err instanceof Error ? err.message : String(err); + } + } + const msg = err instanceof Error ? err.message : String(err ?? ""); + for (const marker of CORRUPTION_ERRMSG_MARKERS) { + if (msg.includes(marker)) return msg; + } + return null; +} diff --git a/src/storage/store.ts b/src/storage/store.ts index 0cab41538d..818c854af9 100644 --- a/src/storage/store.ts +++ b/src/storage/store.ts @@ -25,6 +25,7 @@ import { migrateSchema, storagePragmas, WAL_JOURNAL_SIZE_LIMIT } from "./schema. import { identityOfStoredContent } from "./identity.js"; import { recordIntegrityOutcome, recordSecondProcessOwner, recordBackupOutcome } from "./runtime-status.js"; import { integrityModeFor, writeIntegrityCache, scheduleBackgroundIntegrityCheck, backgroundIntegrityInflightForTests, noteIntegrityCheckRun } from "./integrity-check.js"; +import { sqliteCorruptionDetail } from "./sqlite-errors.js"; import { listInstances, type RegistryEntry } from "../instance.js"; import type { MessageContentStore } from "acp-kernel"; @@ -350,6 +351,13 @@ export class UnifiedStore { * verdict cache onto the post-checkpoint stats so the next boot skips * the rescan. Never true while a check is still in flight or failed. */ private lastIntegrityOk = false; + /** #5108/#4816: a completed check said the file set is CORRUPT — a clean + * close refreshes the FAIL verdict onto post-checkpoint stats so the + * next boot's cached-fail path quarantines instead of rescan-looping + * (a clean close moves the WAL, which would otherwise invalidate the + * cache key and send a large corrupt store back to unverified forever). + * Outranks lastIntegrityOk at close time. */ + private lastIntegrityFailDetail: string | null = null; private constructor(db: SqliteDatabase, engine: SqliteEngineName, engineSource: SqliteEngineSource, lockPath: string | null, foreignLockHolder: { pid: number } | null, dbPath: string) { this.db = db; @@ -401,8 +409,16 @@ export class UnifiedStore { // before rethrowing — the #2771 fallback tells operators to // DELETE the file, and Windows refuses to delete a file this // process still holds (unlink EBUSY, #4347 probe). + // #5108/#4816: corruption-shaped THROWS (truncated file, garbage + // header, broken overflow chain) must become StorageIntegrityError + // like the verdict-row path does — the raw rethrow escaped the + // shadow's quarantine guard (#4175) and left the corrupt set in + // place forever. Transient shapes (BUSY/IOERR/CANTOPEN) stay raw: + // quarantining a locked-but-healthy index would be the bug. recordIntegrityOutcome(path, false, Date.now() - started, String(err).slice(0, 400)); db.close(); + const detail = sqliteCorruptionDetail(err); + if (detail !== null) throw new StorageIntegrityError(path, detail.slice(0, 400)); throw err; } const durationMs = Date.now() - started; @@ -459,7 +475,12 @@ export class UnifiedStore { // file to reset the index — and Windows refuses to delete a file a // live process still holds open. Close, then rethrow for the // shadow's legacy-only degradation. + // #5108/#4816: large stores (> sync threshold) skip the pre-migration + // scan, so a corruption can surface HERE first — classify it the same + // way so the shadow quarantines instead of degrading forever. db.close(); + const detail = sqliteCorruptionDetail(err); + if (detail !== null) throw new StorageIntegrityError(path, detail.slice(0, 400)); throw err; } // #3250: converge the WAL an unclean exit left behind (SIGKILL / power @@ -480,7 +501,7 @@ export class UnifiedStore { // read-only connection — open() returns immediately; the verdict // lands in runtime-status and the cache (a cached failure makes the // NEXT open quarantine + reopen fresh via the #4175 path). - if (mode.kind === "async") scheduleBackgroundIntegrityCheck(path, (ok) => { if (ok) store.noteIntegrityOk(); }); + if (mode.kind === "async") scheduleBackgroundIntegrityCheck(path, (ok, detail) => { if (ok) store.noteIntegrityOk(); else if (detail !== undefined) store.noteIntegrityFail(detail); }); return store; } @@ -491,6 +512,12 @@ export class UnifiedStore { this.lastIntegrityOk = true; } + /** #5108/#4816: mirror of noteIntegrityOk for a completed FAIL verdict — + * see lastIntegrityFailDetail for why the close-time refresh needs it. */ + noteIntegrityFail(detail: string): void { + this.lastIntegrityFailDetail = detail; + } + close(): void { // #3250: converge the WAL before releasing the handle so a clean exit // leaves nothing for the next boot's recovery to replay. Same isolation @@ -504,10 +531,13 @@ export class UnifiedStore { this.db.close(); // #4609: a clean close of a verified store refreshes the verdict // cache onto the post-checkpoint stats — the normal restart path then - // skips the rescan. Deferred while a background check is still in - // flight (its own completion writes the cache). Best-effort. - if (this.lastIntegrityOk && !backgroundIntegrityInflightForTests(this.dbPath)) { - writeIntegrityCache(this.dbPath, true); + // skips the rescan. #5108/#4816: the same refresh carries a FAIL + // verdict (fail outranks ok — never cache ok for a corrupt file). + // Deferred while a background check is still in flight (its own + // completion writes the cache). Best-effort. + if (!backgroundIntegrityInflightForTests(this.dbPath)) { + if (this.lastIntegrityFailDetail !== null) writeIntegrityCache(this.dbPath, false, this.lastIntegrityFailDetail); + else if (this.lastIntegrityOk) writeIntegrityCache(this.dbPath, true); } // #4175: release the ownership lockfile on a clean close so the next // open in another process is not told a dead pid holds it. When a From 1f230a2e99b13a29e7d06015dd16dbec717c6265 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 29 Oct 2026 16:06:52 +0800 Subject: [PATCH 2/6] =?UTF-8?q?fix:=20make=20index.db=20quarantine=20robus?= =?UTF-8?q?t=20=E2=80=94=20name=20rename=20failures,=20never=20reopen=20ov?= =?UTF-8?q?er=20an=20unquarantined=20corrupt=20file=20(#4816/#5108)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/storage/shadow.ts | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) diff --git a/src/storage/shadow.ts b/src/storage/shadow.ts index aec7da44eb..2521a5c9fa 100644 --- a/src/storage/shadow.ts +++ b/src/storage/shadow.ts @@ -26,7 +26,7 @@ import { planIngest, planIngestDelta, loadLegacyView, completeBlockContents, typ import type { BlockView } from "../session.js"; import { resolveStorageMode, resolveStorageWalJournalSizeLimit, type StorageMode } from "../knobs.ts"; import { UnifiedStore, StorageIntegrityError, type CheckpointRow, type SessionSummaryRow, type WebSummaryRow } from "./store.ts"; -import { renameSync } from "node:fs"; +import { existsSync, renameSync } from "node:fs"; import path from "node:path"; import { resolveBackendName, backendSelectionNotice, selectedBackendRaw, openBackend, type StorageBackend } from "./backend.ts"; import { canonicalize, sha256 } from "./canonical.ts"; @@ -203,14 +203,23 @@ export class UnifiedShadow { if (!(err instanceof StorageIntegrityError)) throw err; const stamp = Date.now(); const quarantined: string[] = []; + let primaryRenameFailure: string | null = null; + const sidecarLeft: string[] = []; for (const suffix of ["", "-wal", "-shm"]) { const from = `${dir}/index.db${suffix}`; + if (!existsSync(from)) continue; // absent sidecar files are fine const to = `${dir}/index.db${suffix}.corrupt-${stamp}`; try { renameSync(from, to); quarantined.push(path.basename(to)); - } catch { - /* absent sidecar files are fine */ + } catch (rerr) { + // #5108/#4347: the old empty catch swallowed EVERY failure + // — including a primary that could not be moved — and the + // code below then claimed success. Capture the errno and + // decide per file what a failed move actually means. + const why = String((rerr as NodeJS.ErrnoException).code ?? rerr); + if (suffix === "") primaryRenameFailure = why; + else sidecarLeft.push(`${path.basename(from)} (${why})`); } } // #4609: the verdict cache belongs to the quarantined file set — @@ -220,8 +229,30 @@ export class UnifiedShadow { const cacheFrom = `${dir}/index.db.chk`; renameSync(cacheFrom, `${cacheFrom}.corrupt-${stamp}`); quarantined.push(path.basename(`${cacheFrom}.corrupt-${stamp}`)); - } catch { - /* absent cache is fine */ + } catch (rerr) { + if (existsSync(`${dir}/index.db.chk`)) { + // Present but unmovable — harmless (the fresh store's stats + // key misses and rescans), but say so instead of staying silent. + loggerLog("warn", `[storage] quarantined index.db but its .chk verdict cache could not be moved (${String((rerr as NodeJS.ErrnoException).code ?? rerr)}) — it will be overwritten by the next check`); + } + } + if (primaryRenameFailure !== null) { + // The corrupt PRIMARY is still in place: a fresh reopen would + // just re-hit the same corrupt file, so do NOT attempt it — + // degrade loudly with the real errno instead of claiming the + // quarantine succeeded. The operator moves the file aside by + // hand (the same manual workaround that always worked). + loggerLog( + "error", + `[storage] index.db failed its integrity quick_check (${err.detail}) but the corrupt file could NOT be quarantined (rename ${primaryRenameFailure}${sidecarLeft.length > 0 ? `; also left behind: ${sidecarLeft.join(", ")}` : ""}) — staying legacy-only; move ${path.join(dir, "index.db")} aside by hand to rebuild the index (#5108/#4347)`, + ); + throw new StorageIntegrityError(`${dir}/index.db`, `${err.detail}; quarantine rename failed: ${primaryRenameFailure}`); + } + if (sidecarLeft.length > 0) { + // Probe-verified (node:sqlite v22): SQLite RESETS a stale -wal + // whose parent db was replaced rather than replaying it onto + // the fresh file, so leftover sidecars are safe to leave. + loggerLog("warn", `[storage] quarantined index.db but ${sidecarLeft.join(", ")} could not be renamed — left in place (a stale -wal is reset, not replayed, on the next open)`); } loggerLog( "error", From 96826db1474d6f197dd0f89a29ec4e57ed8cd5c7 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 29 Oct 2026 16:06:52 +0800 Subject: [PATCH 3/6] fix: report the resolved engine when index.db open fails after resolution; middle-truncate long degrade reasons (#5108) --- src/storage/driver.ts | 8 ++++++++ src/storage/runtime-status.ts | 28 ++++++++++++++++++++++++---- 2 files changed, 32 insertions(+), 4 deletions(-) diff --git a/src/storage/driver.ts b/src/storage/driver.ts index 6bc44be0c7..047fa93449 100644 --- a/src/storage/driver.ts +++ b/src/storage/driver.ts @@ -218,6 +218,14 @@ export function clearSelfDownloadedEngineForTests(): void { let cachedEngine: ResolvedEngine | null = null; +/** #5108: the last successfully resolved engine (null until resolution + * succeeds). Diagnostics surfaces use it to say WHICH engine resolved when a + * store open later failed with a real error — reporting "engine: none" for a + * corrupt-index failure misdirected triage toward an engine problem. */ +export function resolvedSqliteEngineInfo(): ResolvedEngine | null { + return cachedEngine; +} + function detectEngine(): ResolvedEngine { if (cachedEngine) return cachedEngine; if (probeBuiltinSqlite()) cachedEngine = { name: "node:sqlite", source: "builtin" }; diff --git a/src/storage/runtime-status.ts b/src/storage/runtime-status.ts index f2c0aee365..e71d5eca15 100644 --- a/src/storage/runtime-status.ts +++ b/src/storage/runtime-status.ts @@ -27,9 +27,16 @@ import type { BootstrapOutcome, CooldownMarker } from "./engine-bootstrap.js"; import { bootstrapFailureMarkerPath, COOLDOWN_MS, nodeSqliteUpgradeHint, readBootstrapFailureMarker } from "./engine-bootstrap.js"; import { fileStorageAutoDownload, fileStorageJsonWriter, fileStorageUnified, fileStorageWalJournalSizeLimit, resolveStorageMode } from "../knobs.js"; import { log as loggerLog } from "../logger.js"; +import { resolvedSqliteEngineInfo } from "./driver.js"; import { MAX_CONSECUTIVE_FAILURES, sqliteOpenFailureHint, type UnifiedShadow } from "./shadow.js"; import type { StorageMode } from "./shadow.js"; +/** The driver's no-engine error text — one predicate, used wherever the + * "is this actually an engine problem?" distinction matters (#5108). */ +function isNoEngineError(errStr: string): boolean { + return /no SQLite engine available/i.test(errStr); +} + interface RuntimeState { /** Recorded by the SessionStore constructor; null only before first store build. */ requested: StorageMode | null; @@ -160,7 +167,13 @@ function pidAlive(pid: number): boolean { /** Short one-line form of a raw error for interpolation into banner text. */ function shortenError(err: string): string { const oneLine = err.replace(/\s+/g, " ").trim(); - return oneLine.length > 160 ? `${oneLine.slice(0, 157)}...` : oneLine; + if (oneLine.length <= 160) return oneLine; + // #5108/#4816: both ends carry signal — the error class up front, the + // errno/detail at the end (e.g. "quarantine rename failed: EPERM") — so + // cut the MIDDLE (usually a long path) instead of the tail. Head-only + // truncation made the actionable detail invisible on exactly the + // long-path machines (Windows user profiles) this fix targets. + return `${oneLine.slice(0, 78)}…${oneLine.slice(-78)}`; } function degradeReason(): string { @@ -183,7 +196,7 @@ function degradeReason(): string { const e = shortenError(state.sidecarOpenError); // 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 (/no SQLite engine available/i.test(e)) { + if (isNoEngineError(e)) { return `no SQLite engine available (node:sqlite missing, better-sqlite3 not installed)${nodeSqliteUpgradeHint()}`; } return `index database failed to open (${e})${sqliteOpenFailureHint(state.sidecarOpenError)}`; @@ -277,7 +290,14 @@ function getStorageRuntimeStatus(): StorageRuntimeStatus { degraded, intentionalOptOut, reason: degraded ? degradeReason() : null, - engine: sidecar ? sidecar.engineInfo : null, + // #5108: an open failure AFTER the engine resolved (corrupt index.db, + // …) must not report "engine: none" — that misdirected triage toward + // an engine problem when the engine was fine and the file was not. + engine: sidecar + ? sidecar.engineInfo + : state.sidecarOpenError !== null && !isNoEngineError(state.sidecarOpenError) + ? resolvedSqliteEngineInfo() + : null, bootstrap: state.bootstrap?.status ?? null, bootstrapFailure: cd.marker, cooldownRemainingMs: cd.remainingMs, @@ -369,7 +389,7 @@ export function storageDiagnosticsLines(ctx: { sessions: number; storageLogLines `requested mode: ${st.requested}`, `effective mode: ${st.effective}${st.intentionalOptOut ? " (BILI_ENCRYPTION_KEY opt-out — intentional)" : ""}`, ...(st.degraded && st.reason ? [`degrade reason: ${st.reason}`] : []), - `engine: ${st.engine ? `${st.engine.name}/${st.engine.source}` : "none"}`, + `engine: ${st.engine ? `${st.engine.name}/${st.engine.source}${state.sidecarOpenError !== null && !isNoEngineError(state.sidecarOpenError) ? " (resolved, but index.db open failed — see degrade reason)" : ""}` : "none"}`, `engine bootstrap: ${st.bootstrap ?? "not run"}`, ...(st.bootstrapFailure ? [ `bootstrap failure marker: at=${new Date(st.bootstrapFailure.atMs).toISOString()} reason="${st.bootstrapFailure.reason}"${st.cooldownRemainingMs ? ` (cooldown ~${Math.round(st.cooldownRemainingMs / 60_000)}m remaining, until ${new Date(st.bootstrapFailure.atMs + COOLDOWN_MS).toISOString()})` : ""}`, From 238a7e4368697515541a92cf849dda9666b6bf0f Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 29 Oct 2026 16:06:52 +0800 Subject: [PATCH 4/6] fix: sample the tail of dsh child bootstrap output instead of the head when it exceeds the window (#4816) --- src/launcher.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/launcher.ts b/src/launcher.ts index 04ccd7f72d..03bde8e482 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -5069,16 +5069,23 @@ export async function ensureProxyRunning( // means rotation happened under us — everything left is ours. let start = spawnLogOffset; if (size < start) start = Math.max(0, size - 256); - const len = Math.min(256, size - start); - if (len <= 0) return ""; + const span = size - start; + if (span <= 0) return ""; + // #4816: the death cause sits at the END of a child's output — + // when this spawn wrote more than the sample window, take the + // TAIL instead of the head (head-only sampling then showed + // startup noise while the fatal line sat unread further down). + const len = Math.min(256, span); + const off = span > len ? start + (span - len) : start; + const label = span > len ? "tail" : "head"; const fd = fs.openSync(logPath, "r"); try { const buf = Buffer.alloc(len); - const n = fs.readSync(fd, buf, 0, len, start); + const n = fs.readSync(fd, buf, 0, len, off); if (n === 0) return ""; let s = buf.subarray(0, n).toString("utf8").replace(/\s+/g, " ").trim(); if (s.length > 200) s = `${s.slice(0, 200)}…`; - return ` — child output head: "${s}"`; + return ` — child output ${label}: "${s}"`; } finally { fs.closeSync(fd); } From 6faac8faaddf28b76f9519a26472a4ffe584db41 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 29 Oct 2026 16:06:52 +0800 Subject: [PATCH 5/6] test: regression coverage for corruption-throw quarantine, recovery, rename-failure, background-check and diagnostics facets (#4816/#5108) --- tests/corrupt-index-child.ts | 82 ++++-- ...sue4816-integrity-throw-quarantine.test.ts | 253 ++++++++++++++++++ tests/storage-engine-proofs.test.ts | 38 +-- tests/web-storage-banner.test.ts | 28 +- 4 files changed, 345 insertions(+), 56 deletions(-) create mode 100644 tests/issue4816-integrity-throw-quarantine.test.ts diff --git a/tests/corrupt-index-child.ts b/tests/corrupt-index-child.ts index 76eb4d5335..f312938db1 100644 --- a/tests/corrupt-index-child.ts +++ b/tests/corrupt-index-child.ts @@ -1,7 +1,7 @@ /** - * #4338: the corrupt index.db degrade scenarios run in a spawned CHILD - * process, and this file is both the child program and the shared helper - * module the two parent test files import. + * #4338: the corrupt-index and no-engine-banner scenarios run in a spawned + * CHILD process, and this file is both the child program and the shared + * helper module the two parent test files import. * * Why a child: on Windows, node:sqlite's FAILED open of a corrupt index.db * can leave an OS file handle held with no JS-side instance to release @@ -34,7 +34,7 @@ import { spawnSync } from "node:child_process"; import http from "node:http"; import { once } from "node:events"; import assert from "node:assert/strict"; -import { mkdirSync, realpathSync, writeFileSync, writeSync } from "node:fs"; +import { mkdirSync, realpathSync, writeSync } from "node:fs"; import * as fs from "node:fs"; import * as path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; @@ -42,6 +42,7 @@ import { defaultConfig } from "acp-kernel"; import type { ProxyOptions } from "../src/config.ts"; import { startServer } from "../src/server.ts"; import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { setSqliteEnginesUnavailableForTests } from "../src/storage/driver.ts"; import { loadLegacyView, toLegacyLike } from "../src/storage/ingest.ts"; import { canonicalize, sha256, sortObjectKeys } from "./golden-canonical.ts"; @@ -192,24 +193,32 @@ export function makeOpts(upstreamPort: number): ProxyOptions { // sides reference these constants, so the coverage list cannot drift. // --------------------------------------------------------------------------- +// #4816: throwing-shape corruption (header garbage / truncation) is now +// quarantined and the store RECOVERS to full mode on a fresh index.db — +// these checks pin that recovery plus the original #2781/#4357 leak guards. const ENGPROOF_CHECK_NAMES = { - fallbackRead: "legacy fallback returned a session over the corrupt index", - midFlowGuard: "no live handle after the corrupt-index read (#2781 rename guard)", - stateDigest: "corrupt-index fallback state digest matches the clean full-mode read", - writeNow: "writeNow keeps working over the legacy path after the corrupt-index degrade", + quarantine: "corrupt index.db was renamed aside (index.db.corrupt-* kept for forensics)", + freshIndex: "a fresh index.db replaced the quarantined one", + lazyImport: "session reloaded from the legacy envelope into the recovered index", + midFlowGuard: "no live handle on the QUARANTINED file (#2781/#4357 rename guard)", + stateDigest: "recovered-index state digest matches the clean full-mode read", + writeNow: "writeNow keeps working over the recovered full mode", postCloseGuard: "no live handle after the final close (post-close rename guard)", fdGuard: "no open fd into the corrupt index dir after close (/proc/self/fd, Linux)", } as const; export const ENGPROOF_CHECKS: readonly string[] = Object.values(ENGPROOF_CHECK_NAMES); +// #4816: a corrupt index.db no longer degrades — it quarantines and recovers +// (see engproof). The banner wire shape is pinned here through the remaining +// deterministic cross-platform degrade cause: the engine ladder exhausted. const BANNER_CHECK_NAMES = { overviewAnswers: "/__bili/overview answers 200 with JSON", requestedFull: "storage.requested is full", effectiveLegacy: "storage.effective is legacy", - degraded: "storage.degraded is true (corrupt index.db trips the warning)", + degraded: "storage.degraded is true (the no-engine degrade trips the warning)", intentionalOptOut: "storage.intentionalOptOut is false", - reason: "storage.reason matches /index database failed to open/", - engine: "storage.engine is null", + reason: "storage.reason names the missing engine", + engine: "storage.engine is null when no engine resolved", } as const; export const BANNER_CHECKS: readonly string[] = Object.values(BANNER_CHECK_NAMES); @@ -331,28 +340,48 @@ async function engproofScenario(argv: string[], run: CheckRun): Promise { fs.writeSync(fd, Buffer.alloc(512, 0x5a), 0, 512, 0); fs.closeSync(fd); - // THE #2771 regression: construction must survive, reads must fall - // back to the legacy file, and the digest must be exact. + // THE #2771 regression: construction must survive. Since #4816 the + // throwing-shape corruption is quarantined and the store recovers to + // full mode on a fresh index.db — reads lazily import the session back + // from the legacy envelope, and the digest must be exact. const store2 = new SessionStore({ dir, debounceMs: 1, enabled: true }); + await run.run(ENGPROOF_CHECK_NAMES.quarantine, () => { + const names = fs.readdirSync(dir); + const q = names.find((n) => n.startsWith("index.db.corrupt-")); + assert.ok(q, `no quarantined index.db.corrupt-* in ${names.join(", ")}`); + }); + await run.run(ENGPROOF_CHECK_NAMES.freshIndex, () => + assert.ok(fs.existsSync(path.join(dir, "index.db")), "fresh index.db absent after quarantine")); const reloaded = store2.loadSync("corpus-folded", { protocol: "anthropic", upstreamOrigin: "http://127.0.0.1:8199" }); store2.cancelAll(); try { - await run.run(ENGPROOF_CHECK_NAMES.fallbackRead, () => - assert.ok(reloaded, "legacy fallback returned null over a corrupt index")); + await run.run(ENGPROOF_CHECK_NAMES.lazyImport, () => + assert.ok(reloaded, "recovered store returned null for a session whose legacy envelope exists")); if (!reloaded) return; - // Regression (#2781): the failed open must have CLOSED its handle. - await runGuard(run, ENGPROOF_CHECK_NAMES.midFlowGuard, dir, "-moved"); + // Leak guard (#2781/#4357): the DEAD quarantined file must carry no + // live handle. The whole-dir rename used pre-#4816 is wrong now — + // the store legitimately holds the FRESH index.db, and only a + // handle on the dead file is the leak class this guard hunts. + await run.run(ENGPROOF_CHECK_NAMES.midFlowGuard, () => { + const q = fs.readdirSync(dir).find((n) => n.startsWith("index.db.corrupt-")); + assert.ok(q, "quarantined file vanished before the leak guard ran"); + const src = path.join(dir, q!); + const probe = `${src}-moved`; + fs.renameSync(src, probe); + fs.renameSync(probe, src); + }); // #4316 PR3/3: the clean full-mode read carried the one-time ledger - // alignment; the legacy fallback over the corrupt index did not. The - // parent passes its digest already modulo that alignment (single - // definition), so strip it here too before comparing. + // alignment; the recovered load applies it again. The parent passes + // its digest already modulo that alignment (single definition), so + // strip it here too before comparing. await run.run(ENGPROOF_CHECK_NAMES.stateDigest, () => assert.equal(viewStateDigest(stripOneTimeAlignment(toLegacyLike(reloaded))), expectedStateDigest, - "corrupt-index fallback state digest drift vs clean full-mode read")); + "recovered-index state digest drift vs clean full-mode read")); - // Writes must keep working (legacy path) — no throw, file refreshed. + // Writes must keep working (full path into the fresh index) — no + // throw, files refreshed. await run.run(ENGPROOF_CHECK_NAMES.writeNow, () => store2.writeNow(reloaded)); } finally { store2.closeQuietly(); @@ -394,7 +423,10 @@ async function bannerScenario(argv: string[], run: CheckRun): Promise { if (!base) throw new Error("banner mode needs "); const dir = path.join(base, "sessions"); mkdirSync(dir, { recursive: true }); - writeFileSync(path.join(dir, "index.db"), Buffer.from("this is definitely not a sqlite database file".repeat(8))); + // #4816: the former corrupt-index cause here now quarantines and recovers + // instead of degrading — force the engine ladder exhausted (deterministic + // on every platform) as the degrade trigger for the banner wire shape. + setSqliteEnginesUnavailableForTests(true); const store = new SessionStore({ dir, enabled: true }); _setStoreForTest(store); const upstreamPort = await freePort(); @@ -415,9 +447,9 @@ async function bannerScenario(argv: string[], run: CheckRun): Promise { if (!storage) return; await run.run(BANNER_CHECK_NAMES.requestedFull, () => assert.equal(storage.requested, "full")); await run.run(BANNER_CHECK_NAMES.effectiveLegacy, () => assert.equal(storage.effective, "legacy")); - await run.run(BANNER_CHECK_NAMES.degraded, () => assert.equal(storage.degraded, true, "corrupt index.db trips the warning")); + await run.run(BANNER_CHECK_NAMES.degraded, () => assert.equal(storage.degraded, true, "no-engine degrade trips the warning")); await run.run(BANNER_CHECK_NAMES.intentionalOptOut, () => assert.equal(storage.intentionalOptOut, false)); - await run.run(BANNER_CHECK_NAMES.reason, () => assert.match(storage.reason ?? "", /index database failed to open/)); + await run.run(BANNER_CHECK_NAMES.reason, () => assert.match(storage.reason ?? "", /no SQLite engine available/)); await run.run(BANNER_CHECK_NAMES.engine, () => assert.equal(storage.engine, null)); } finally { await close(proxy); diff --git a/tests/issue4816-integrity-throw-quarantine.test.ts b/tests/issue4816-integrity-throw-quarantine.test.ts new file mode 100644 index 0000000000..87fbc352b1 --- /dev/null +++ b/tests/issue4816-integrity-throw-quarantine.test.ts @@ -0,0 +1,253 @@ +/** + * #4816/#5108 regression: corruption-shaped quick_check failures must reach + * the #4175 quarantine decision instead of escaping it as raw driver errors. + * + * The #4175 quarantine guard only catches StorageIntegrityError, but several + * corruption shapes make `PRAGMA quick_check` THROW (truncated file → + * "database disk image is malformed", garbage header → "file is not a + * database") instead of returning non-ok verdict rows. Those raw throws + * escaped the shadow's quarantine and left the corrupt index in place + * forever (permanent legacy-only degrade; the reporter's only exit was a + * manual rename). Facets covered here: + * 1. the classifier itself (corruption shapes match, transient shapes do NOT); + * 2. UnifiedStore.open turns a throwing scan into StorageIntegrityError; + * 3. the shadow quarantines + reopens fresh instead of degrading; + * 4. a failed quarantine rename degrades loudly with the errno (no doomed reopen); + * 5. the background (large-store) check caches its FAIL verdict across a clean close; + * 6. /__bili/status reports the resolved engine when the failure happened AFTER resolution. + */ +import test from "node:test"; +import assert from "node:assert/strict"; +import { chmodSync, closeSync, existsSync, mkdtempSync, openSync, readdirSync, rmSync, statSync, truncateSync, writeFileSync, writeSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { UnifiedStore, StorageIntegrityError } from "../src/storage/store.js"; +import { UnifiedShadow } from "../src/storage/shadow.js"; +import { sqliteCorruptionDetail } from "../src/storage/sqlite-errors.js"; +import { openSqliteDatabase, probeBuiltinSqlite, probeHostBetterSqlite3 } from "../src/storage/driver.js"; +import { + readIntegrityCache, + resetIntegrityCheckStateForTests, + setIntegritySyncThresholdForTests, + backgroundIntegrityInflightForTests, +} from "../src/storage/integrity-check.js"; +import { + _resetStorageRuntimeStatusForTest, + recordSidecarOpenFailure, + storageStatusWire, + storageDiagnosticsLines, +} from "../src/storage/runtime-status.js"; + +const HAS_ENGINE = probeBuiltinSqlite() || probeHostBetterSqlite3(); +const SKIP_NO_ENGINE = HAS_ENGINE ? undefined : "no SQLite engine available on this host"; +const SKIP_RENAME_FAIL = SKIP_NO_ENGINE ?? (process.platform === "win32" ? "chmod has no permission effect on Windows" : undefined); + +function tmpDir(): string { + return mkdtempSync(join(tmpdir(), "bili-issue4816-")); +} + +async function waitFor(pred: () => boolean, ms: number): Promise { + const deadline = Date.now() + ms; + while (!pred()) { + if (Date.now() > deadline) throw new Error("timed out waiting"); + await new Promise((r) => setTimeout(r, 25)); + } +} + +/** A real multi-page db (~62 KB, 200 rows) — enough pages for truncation to break. */ +function seedValidDb(dbPath: string): void { + const { db } = openSqliteDatabase(dbPath); + db.exec("CREATE TABLE IF NOT EXISTS seed (id INTEGER PRIMARY KEY, v TEXT)"); + const ins = db.prepare("INSERT INTO seed (v) VALUES (?)"); + for (let i = 0; i < 200; i++) ins.run(`row-${i}-${"x".repeat(300)}`); + db.close(); +} + +function truncateHalf(dbPath: string): void { + truncateSync(dbPath, Math.floor(statSync(dbPath).size / 2)); +} + +function garbageHeader(dbPath: string): void { + writeFileSync(dbPath, Buffer.from("this is definitely not a sqlite database file, not even close")); +} + +/** Zero page 2 (the first btree data page after sqlite_master on page 1). + * Verified recipe: pragmas/schema-migration survive (they only touch the + * header + page 1) but the full quick_check scan throws CORRUPT — needed to + * exercise the background-check facet, where open() must succeed first. */ +function zeroFirstDataPage(dbPath: string): void { + const fd = openSync(dbPath, "r+"); + try { + writeSync(fd, Buffer.alloc(4096, 0), 0, 4096, 4096); + } finally { + closeSync(fd); + } +} + +test("#4816 classifier: corruption shapes match, transient shapes must NOT", () => { + // better-sqlite3 stamps symbolic err.code values + assert.notEqual(sqliteCorruptionDetail(Object.assign(new Error("database disk image is malformed"), { code: "SQLITE_CORRUPT" })), null); + assert.notEqual(sqliteCorruptionDetail(Object.assign(new Error("file is not a database"), { code: "SQLITE_NOTADB" })), null); + // node:sqlite ERR_SQLITE_ERROR carries the errmsg text only + assert.notEqual(sqliteCorruptionDetail(Object.assign(new Error("database disk image is malformed"), { code: "ERR_SQLITE_ERROR" })), null); + assert.notEqual(sqliteCorruptionDetail(new Error("file is not a database")), null); + // the [storage:] wrapper keeps the message text + assert.notEqual(sqliteCorruptionDetail(new Error("[storage:better-sqlite3] file is not a database")), null); + // Transient shapes MUST stay unclassified: quarantining a locked-but-healthy + // index over an AV lock would destroy a working store (#362/#3823 class). + assert.equal(sqliteCorruptionDetail(Object.assign(new Error("database is locked"), { code: "SQLITE_BUSY" })), null); + assert.equal(sqliteCorruptionDetail(Object.assign(new Error("disk I/O error"), { code: "ERR_SQLITE_ERROR" })), null); + assert.equal(sqliteCorruptionDetail(Object.assign(new Error("unable to open database file"), { code: "SQLITE_CANTOPEN" })), null); + assert.equal(sqliteCorruptionDetail(new Error("some other failure")), null); + assert.equal(sqliteCorruptionDetail(null), null); + assert.equal(sqliteCorruptionDetail(undefined), null); +}); + +test("#4816 store: a throwing quick_check becomes StorageIntegrityError", { skip: SKIP_NO_ENGINE }, () => { + const dir = tmpDir(); + try { + const p = join(dir, "index.db"); + seedValidDb(p); + truncateHalf(p); // proven to make PRAGMA quick_check throw CORRUPT + assert.throws( + () => UnifiedStore.open(p), + (err: unknown) => err instanceof StorageIntegrityError && /malformed/.test(err.detail), + ); + } finally { + rmSync(dir, { recursive: true, force: true }); + } + + const dir2 = tmpDir(); + try { + const p = join(dir2, "index.db"); + seedValidDb(p); + garbageHeader(p); // proven to make PRAGMA quick_check throw NOTADB + assert.throws( + () => UnifiedStore.open(p), + (err: unknown) => err instanceof StorageIntegrityError && /not a database/.test(err.detail), + ); + // control: a healthy file still opens + rmSync(p); + seedValidDb(p); + const s = UnifiedStore.open(p); + s.close(); + } finally { + rmSync(dir2, { recursive: true, force: true }); + } + + const dir3 = tmpDir(); + try { + const p = join(dir3, "index.db"); + seedValidDb(p); + zeroFirstDataPage(p); // page-content corruption throws like truncation does + assert.throws( + () => UnifiedStore.open(p), + (err: unknown) => err instanceof StorageIntegrityError && /malformed/.test(err.detail), + ); + } finally { + rmSync(dir3, { recursive: true, force: true }); + } +}); + +test("#4816 shadow: throwing corruption is quarantined and the store recovers to full mode", { skip: SKIP_NO_ENGINE }, () => { + const dir = tmpDir(); + let shadow: UnifiedShadow | null = null; + try { + seedValidDb(join(dir, "index.db")); + truncateHalf(join(dir, "index.db")); + shadow = UnifiedShadow.maybeOpen(dir, { BILI_STORAGE_UNIFIED: "full" }, () => null); + assert.ok(shadow !== null, "corrupt index must be quarantined + reopened fresh, not degrade legacy-only"); + assert.equal(shadow.readsUnified, true); + const names = readdirSync(dir); + assert.ok(names.some((n) => n.startsWith("index.db.corrupt-")), `quarantined copy kept for forensics, got ${names.join(", ")}`); + assert.ok(existsSync(join(dir, "index.db")), "fresh index.db exists after quarantine"); + } finally { + shadow?.close(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("#4816 shadow: a failed quarantine rename degrades loudly with the errno, no doomed reopen", { skip: SKIP_RENAME_FAIL }, () => { + const dir = tmpDir(); + try { + seedValidDb(join(dir, "index.db")); + truncateHalf(join(dir, "index.db")); + chmodSync(dir, 0o555); + try { + _resetStorageRuntimeStatusForTest(); + const shadow = UnifiedShadow.maybeOpen(dir, { BILI_STORAGE_UNIFIED: "full" }, () => null); + assert.equal(shadow, null, "must degrade when the primary cannot be moved aside"); + assert.ok(existsSync(join(dir, "index.db")), "corrupt primary stays in place when the rename fails"); + assert.ok(!readdirSync(dir).some((n) => n.startsWith("index.db.corrupt-")), "no partial quarantine"); + const wire = storageStatusWire(); + assert.match(wire.reason ?? "", /index database failed to open/); + assert.match(wire.reason ?? "", /quarantine rename failed/); + } finally { + chmodSync(dir, 0o755); + _resetStorageRuntimeStatusForTest(); + } + } finally { + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("#4816 worker facet: a large store's throwing background check caches FAIL across a clean close", { skip: SKIP_NO_ENGINE }, async () => { + const dir = tmpDir(); + try { + resetIntegrityCheckStateForTests(); + setIntegritySyncThresholdForTests(1); // force async mode for any size + const p = join(dir, "index.db"); + seedValidDb(p); + zeroFirstDataPage(p); // open() survives; only the full worker scan throws + const s1 = UnifiedStore.open(p); + try { + await waitFor(() => !backgroundIntegrityInflightForTests(p), 15000); + const cache = readIntegrityCache(p); + assert.ok(cache !== null && cache.ok === false, `FAIL verdict cached by the worker, got ${JSON.stringify(cache)}`); + assert.match(cache?.detail ?? "", /malformed/); + } finally { + s1.close(); // checkpoint moves the WAL — the refresh must carry the FAIL verdict + } + // Next boot: cached-fail → typed error → the shadow would quarantine. + assert.throws( + () => UnifiedStore.open(p), + (err: unknown) => err instanceof StorageIntegrityError && /malformed/.test(err.detail), + ); + } finally { + setIntegritySyncThresholdForTests(null); + resetIntegrityCheckStateForTests(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("#5108 diagnostics: engine reports the resolved engine when the open failed after resolution", { skip: SKIP_NO_ENGINE }, () => { + const dir = tmpDir(); + try { + seedValidDb(join(dir, "index.db")); + const s = UnifiedStore.open(join(dir, "index.db")); + s.close(); // populates the driver's resolved-engine info + _resetStorageRuntimeStatusForTest(); + recordSidecarOpenFailure("[storage] database disk image is malformed"); + const wire = storageStatusWire(); + assert.ok(wire.engine !== null, "resolved engine must be reported even though the sidecar never opened"); + assert.ok(typeof wire.engine?.name === "string" && wire.engine.name.length > 0); + const lines = storageDiagnosticsLines({ sessions: 0, storageLogLines: [] }); + assert.ok(lines.some((l) => l.includes("resolved, but index.db open failed")), `diagnostics line annotated, got ${JSON.stringify(lines)}`); + } finally { + _resetStorageRuntimeStatusForTest(); + rmSync(dir, { recursive: true, force: true }); + } +}); + +test("#5108 diagnostics: no-engine failures keep reporting engine null", () => { + _resetStorageRuntimeStatusForTest(); + recordSidecarOpenFailure("no SQLite engine available"); + try { + const wire = storageStatusWire(); + assert.equal(wire.engine, null); + const lines = storageDiagnosticsLines({ sessions: 0, storageLogLines: [] }); + assert.ok(!lines.some((l) => l.includes("resolved, but index.db open failed"))); + } finally { + _resetStorageRuntimeStatusForTest(); + } +}); diff --git a/tests/storage-engine-proofs.test.ts b/tests/storage-engine-proofs.test.ts index d9eb3334b2..656d37c1d0 100644 --- a/tests/storage-engine-proofs.test.ts +++ b/tests/storage-engine-proofs.test.ts @@ -26,13 +26,15 @@ * loads with the exact digest. * SELF-DISABLE — 3 consecutive sidecar failures disable it; reads flip * back to legacy; the legacy file stays readable. - * CORRUPT INDEX — a corrupt index.db degrades the store to legacy-only - * instead of bricking construction (#2771). + * CORRUPT INDEX — a corrupt index.db is quarantined and the store + * recovers to full mode instead of bricking + * construction (#2771 → #4816). * CAS REFCOUNT — shared content blobs survive deleteSession of one * session and are collected only at refcount 0. * - * The corrupt-index test is the regression for #2771; the rest are contract - * pins (proof-only, no product change). + * The corrupt-index test is the regression for #2771 (re-pinned for the + * #4816 quarantine-and-recover behavior); the rest are contract pins + * (proof-only, no product change). */ import { test } from "node:test"; @@ -361,10 +363,11 @@ test("storage engine: sidecar self-disables after 3 consecutive failures (reads }); // --------------------------------------------------------------------------- -// CORRUPT INDEX (#2771): construction degrades to legacy-only. +// CORRUPT INDEX (#2771 → #4816): construction quarantines the corrupt index +// and recovers to full mode. // --------------------------------------------------------------------------- -test("storage engine: corrupt index.db degrades to legacy-only instead of bricking construction (#2771)", { timeout: 180_000 }, async () => { +test("storage engine: corrupt index.db is quarantined and recovers to full mode instead of bricking construction (#2771/#4816)", { timeout: 180_000 }, async () => { const dir = tmpdir("bili-engproof-corrupt-"); const prev = process.env.BILI_STORAGE_UNIFIED; try { @@ -381,17 +384,18 @@ test("storage engine: corrupt index.db degrades to legacy-only instead of bricki clean.closeQuietly(); assert.ok(viaFull, "full-mode read returned null"); - // #4338: everything past this point (corrupt the header → degrade - // construction → fallback read → rename guards → write → close) runs - // in a spawned child. On Windows the FAILED open of the corrupt index - // can leave an OS handle with no JS reference to release, and the - // resulting persistent EBUSY at rmrf outlives the whole tmp-rm retry - // ladder; the child exiting RELEASES all its handles by OS guarantee, - // so this parent's rmrf below cannot be blocked. The child prints a - // JSON verdict of named checks; every one is re-asserted here, so - // assertion coverage is 1:1 with the in-process era (same asserts, - // executed in the child, verified in the parent). The child also runs - // the #2781 mid-flow rename guard plus a post-close guard, so future + // #4338: everything past this point (corrupt the header → quarantine + // + fresh reopen → lazy-import read → leak guards → write → close) + // runs in a spawned child. On Windows any sqlite file the scenario + // touches can leave an OS handle with no JS reference to release, and + // the resulting persistent EBUSY at rmrf would outlive the whole + // tmp-rm retry ladder; the child exiting RELEASES all its handles by + // OS guarantee, so this parent's rmrf below cannot be blocked. The + // child prints a JSON verdict of named checks; every one is + // re-asserted here, so assertion coverage is 1:1 with the + // in-process era (same asserts, executed in the child, verified in + // the parent). The child also runs the #2781/#4357 mid-flow leak + // guard on the quarantined file plus a post-close guard, so future // handle-leak drift trips there by name instead of at teardown. // #4316 PR3/3: expected digest computed modulo the one-time ledger // alignment — the clean read above already carried it in memory, and diff --git a/tests/web-storage-banner.test.ts b/tests/web-storage-banner.test.ts index fe015f7a33..2b1d7352cb 100644 --- a/tests/web-storage-banner.test.ts +++ b/tests/web-storage-banner.test.ts @@ -1,7 +1,8 @@ // #3040 web surface: SQLite unified storage degrades to legacy-only through // several fail-open paths (#2825 contract): engine ladder exhausted, -// self-download blocked in cooldown, corrupt index.db guard (#2771), 3-strike -// sidecar disable. The proxy keeps running on JSON — correct — but until now +// self-download blocked in cooldown, non-corruption index-open failures, +// 3-strike sidecar disable (a corrupt index.db since #4816 quarantines and +// recovers instead of degrading). The proxy keeps running on JSON — correct — but until now // the condition was only visible as one-time log lines, so environments that // cannot run SQLite were never learned about before the upcoming full-mode // default flip. These tests pin the wire contract the web banner reads: @@ -263,21 +264,20 @@ test("#3040 BILI_ENCRYPTION_KEY opt-out is intentional: reported, never warned", } }); -test("#3040 corrupt index.db (guard #2771): degraded with the open-failure reason", { skip: !(probeBuiltinSqlite() || probeHostBetterSqlite3()) && "no SQLite engine available on this host", timeout: 180_000 }, async () => { +test("#3040 engine-ladder-exhausted degrade: banner wire shape with the open-failure reason", { timeout: 180_000 }, async () => { const base = mkdtempSync(path.join(tmpdir(), "bili-storage-banner-")); try { - // #4338: the whole corrupt-index scenario (write the bad index.db → + // #4338: the whole scenario (force the engine ladder exhausted → // construct the store → serve /__bili/overview → assert the degraded - // wire shape → close) runs in a spawned child. On Windows the FAILED - // open of the corrupt index can leave an OS handle with no JS - // reference to release, and this test's rmrf(base) then died on a - // persistent EBUSY that outlived the whole tmp-rm retry ladder; the - // child exiting RELEASES all its handles by OS guarantee, so the - // rmrf below cannot be blocked. The child prints a JSON verdict of - // named checks; every one is re-asserted here, so assertion coverage - // is 1:1 with the in-process era (same asserts, executed in the - // child, verified in the parent). The spawn env below is the child's - // only isolation — this process's own env and seams stay untouched. + // wire shape → close) runs in a spawned child so any OS handle the + // store opens is released by process exit before this parent's + // rmrf(base) can hit a Windows EBUSY. (#4816 moved the trigger off + // the corrupt-index cause: that one now quarantines and recovers, so + // the banner surface is pinned through the deterministic no-engine + // path instead.) The child prints a JSON verdict of named checks; + // every one is re-asserted here, so assertion coverage stays 1:1 + // with the in-process era. The spawn env below is the child's only + // isolation — this process's own env and seams stay untouched. const childEnv: NodeJS.ProcessEnv = { ...process.env }; delete childEnv.BILI_STORAGE_UNIFIED; delete childEnv.BILI_ENCRYPTION_KEY; From 9dc0577da644e3578aeb67beabe5cc731371c468 Mon Sep 17 00:00:00 2001 From: ci-check Date: Thu, 29 Oct 2026 17:25:16 +0800 Subject: [PATCH 6/6] fix: repair #5124 CI failures (family gate + two non-hermetic storage tests) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - runtime-status shortenError: raw .slice(-78) -> safeSuffix (and head via safePrefix) — the code-unit-safe clamp the #816/#1615 family gate requires - issue4816 rename-fail test: pin BILI_STORAGE_UNIFIED=full around the wire assertion — the CI baseline preload pins legacy for the non-storage corpus (#2815), so requested resolved to legacy and nothing was reportable as degraded (passes locally without the preload, fails on every CI shard) - storage-review-fixes review 3: re-pinned to the NEW intended behavior — the garbage-header corruption shape makes quick_check throw, so the store now quarantines the corrupt file set and recovers a fresh index instead of degrading legacy-only forever (PR behavior change (a)); asserts the forensic copy + fresh index.db exist --- src/storage/runtime-status.ts | 3 ++- tests/issue4816-integrity-throw-quarantine.test.ts | 9 +++++++++ tests/storage-review-fixes.test.ts | 14 ++++++++++---- 3 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/storage/runtime-status.ts b/src/storage/runtime-status.ts index e71d5eca15..94a31789be 100644 --- a/src/storage/runtime-status.ts +++ b/src/storage/runtime-status.ts @@ -27,6 +27,7 @@ import type { BootstrapOutcome, CooldownMarker } from "./engine-bootstrap.js"; import { bootstrapFailureMarkerPath, COOLDOWN_MS, nodeSqliteUpgradeHint, readBootstrapFailureMarker } from "./engine-bootstrap.js"; 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 { MAX_CONSECUTIVE_FAILURES, sqliteOpenFailureHint, type UnifiedShadow } from "./shadow.js"; import type { StorageMode } from "./shadow.js"; @@ -173,7 +174,7 @@ function shortenError(err: string): string { // cut the MIDDLE (usually a long path) instead of the tail. Head-only // truncation made the actionable detail invisible on exactly the // long-path machines (Windows user profiles) this fix targets. - return `${oneLine.slice(0, 78)}…${oneLine.slice(-78)}`; + return `${safePrefix(oneLine, 78)}…${safeSuffix(oneLine, 78)}`; } function degradeReason(): string { diff --git a/tests/issue4816-integrity-throw-quarantine.test.ts b/tests/issue4816-integrity-throw-quarantine.test.ts index 87fbc352b1..d527122645 100644 --- a/tests/issue4816-integrity-throw-quarantine.test.ts +++ b/tests/issue4816-integrity-throw-quarantine.test.ts @@ -169,6 +169,13 @@ test("#4816 shadow: throwing corruption is quarantined and the store recovers to test("#4816 shadow: a failed quarantine rename degrades loudly with the errno, no doomed reopen", { skip: SKIP_RENAME_FAIL }, () => { const dir = tmpDir(); + // The wire reason below resolves `requested` from the REAL process env + // (runtime-status records it only via SessionStore), and the CI baseline + // preload pins BILI_STORAGE_UNIFIED=legacy for the non-storage corpus + // (#2815) — under legacy there is nothing to report degraded. Pin full to + // match the mode maybeOpen is asked for; restore afterwards. + const prevUnified = process.env.BILI_STORAGE_UNIFIED; + process.env.BILI_STORAGE_UNIFIED = "full"; try { seedValidDb(join(dir, "index.db")); truncateHalf(join(dir, "index.db")); @@ -187,6 +194,8 @@ test("#4816 shadow: a failed quarantine rename degrades loudly with the errno, n _resetStorageRuntimeStatusForTest(); } } finally { + if (prevUnified === undefined) delete process.env.BILI_STORAGE_UNIFIED; + else process.env.BILI_STORAGE_UNIFIED = prevUnified; rmSync(dir, { recursive: true, force: true }); } }); diff --git a/tests/storage-review-fixes.test.ts b/tests/storage-review-fixes.test.ts index ea5feb6d54..acff76510d 100644 --- a/tests/storage-review-fixes.test.ts +++ b/tests/storage-review-fixes.test.ts @@ -136,7 +136,7 @@ test("review 2: destroyed-substrate blocks are deleted and cannot resurrect on a }); }); -test("review 3: corrupt index.db degrades to legacy-only instead of bricking the proxy", async () => { +test("review 3: corrupt index.db auto-quarantines and recovers instead of bricking the proxy", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-review-corrupt-")); try { const session = loadCorpusCase(dir, "folded", "corpus-folded", "anthropic"); @@ -151,8 +151,14 @@ test("review 3: corrupt index.db degrades to legacy-only instead of bricking the store = new SessionStore({ dir, debounceMs: 1, enabled: true }); // must NOT throw await store.writeNow(session); const reloaded = store.loadSync(session.id, { protocol: "anthropic", upstreamOrigin: "http://127.0.0.1:8199" }); - assert.ok(reloaded, "legacy fallback load must succeed"); - assert.equal(store.replicasAvailable(), false, "shadow is unavailable while degraded"); + assert.ok(reloaded, "session load must succeed"); + // #5124/#4816 behavior change (a): this corruption shape makes + // quick_check THROW, so the store quarantines the corrupt file set + // and recovers a fresh index — it no longer degrades legacy-only. + assert.equal(store.replicasAvailable(), true, "throwing corruption must be quarantined + recovered, not stay legacy-only"); + const names = fs.readdirSync(dir); + assert.ok(names.some((n) => n.startsWith("index.db.corrupt-")), `quarantined copy kept for forensics, got ${names.join(", ")}`); + assert.ok(fs.existsSync(path.join(dir, "index.db")), "fresh index.db exists after quarantine"); await store.flushAll(); // flush the JSON record to disk (closeQuietly only cancels) } finally { store!.closeQuietly(); @@ -163,7 +169,7 @@ test("review 3: corrupt index.db degrades to legacy-only instead of bricking the process.env.BILI_STORAGE_UNIFIED = "shadow"; try { const again = new SessionStore({ dir, debounceMs: 1, enabled: true }); - assert.ok(again.loadSync(session.id, { protocol: "anthropic", upstreamOrigin: "http://127.0.0.1:8199" }), "second process must load via legacy"); + assert.ok(again.loadSync(session.id, { protocol: "anthropic", upstreamOrigin: "http://127.0.0.1:8199" }), "second process must load the session"); again.closeQuietly(); } finally { delete process.env.BILI_STORAGE_UNIFIED;