Skip to content
15 changes: 11 additions & 4 deletions src/launcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5269,16 +5269,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);
}
Expand Down
8 changes: 8 additions & 0 deletions src/storage/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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" };
Expand Down
33 changes: 29 additions & 4 deletions src/storage/integrity-check.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
}
`;

Expand All @@ -169,7 +177,7 @@ const inflight = new Set<string>();
* (#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);
Expand All @@ -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 ?? "");
Expand All @@ -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`);
}
Expand Down
29 changes: 25 additions & 4 deletions src/storage/runtime-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,17 @@ 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";

/** 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;
Expand Down Expand Up @@ -162,7 +170,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 `${safePrefix(oneLine, 78)}…${safeSuffix(oneLine, 78)}`;
}

function degradeReason(): string {
Expand All @@ -185,7 +199,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)}`;
Expand Down Expand Up @@ -279,7 +293,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,
Expand Down Expand Up @@ -371,7 +392,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()})` : ""}`,
Expand Down
41 changes: 36 additions & 5 deletions src/storage/shadow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -240,14 +240,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 —
Expand All @@ -257,8 +266,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",
Expand Down
54 changes: 54 additions & 0 deletions src/storage/sqlite-errors.ts
Original file line number Diff line number Diff line change
@@ -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:<engine>] 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;
}
Loading
Loading