Repository navigation
fix: solve #5084 — recover from corrupt tanstack-db SQLite & guard startup - #5085
github-actions[bot] wants to merge 1 commit into
Conversation
|
Ready to review this PR? Stage has broken it down into 4 individual chapters for you:
Chapters generated by Stage for commit 14c08ed on Jun 4, 2026 3:15am UTC. |
Greptile SummaryThis PR addresses a real regression where a truncated
Confidence Score: 4/5Safe to merge — the recovery logic is well-structured and the startup guard closes a real gap. The only concern is a theoretical Windows handle-leak if better-sqlite3's constructor throws before the try/catch can run opened.close(), which can be tightened with a one-line restructure. The core recovery path is correct for the reported bug (corruption detected inside createNodeSQLitePersistence → handle closed → rename succeeds → retry). The remaining concern is that new Database(dbPath) sits outside the try/catch, so if better-sqlite3 throws SQLITE_CORRUPT from its own constructor (e.g. during internal PRAGMA setup), the explicit close call is skipped and Windows file-lock release depends on the native addon's error path rather than application code. This is fixable with a minor restructure and does not affect the primary bug scenario. apps/desktop/src/main/lib/persistence/persistence.ts — the new Database(dbPath) constructor call outside the try/catch is the one spot worth a second look before merge.
|
| Filename | Overview |
|---|---|
| apps/desktop/src/main/lib/sqlite-recovery.ts | New recovery helper — logic is sound; minor concern that if better-sqlite3's constructor throws SQLITE_CORRUPT, handle cleanup is implicit (relies on native addon cleanup) rather than explicit. |
| apps/desktop/src/main/lib/persistence/persistence.ts | Correctly routes DB open through recovery wrapper; try/catch closes the handle when createNodeSQLitePersistence throws, but new Database(dbPath) lives outside that block, leaving constructor-throw cleanup to better-sqlite3's native error path. |
| apps/desktop/src/main/index.ts | Adds a .catch() last-resort guard to the startup IIFE; correctly shows a dialog only when app.isReady(), swallows dialog errors, and always calls app.exit(1). |
| apps/desktop/src/main/lib/sqlite-recovery.test.ts | Good coverage with real temp files and injected errors; one style nit: readdirSync is fetched via require() instead of being added to the top-level import. |
Sequence Diagram
sequenceDiagram
participant IIFE as Startup IIFE
participant persist as initTanstackDbPersistence
participant recovery as openSqliteWithRecovery
participant fs as Filesystem
participant sqlite as better-sqlite3
IIFE->>persist: initTanstackDbPersistence()
persist->>recovery: openSqliteWithRecovery(dbPath, "tanstack-db", open)
recovery->>sqlite: open() → new Database(dbPath)
sqlite-->>recovery: throws SQLITE_CORRUPT
recovery->>recovery: isSqliteCorruptionError? → true
recovery->>fs: quarantineCorruptDatabase(dbPath)
fs->>fs: renameSync(db → db.corrupt-ts)
fs->>fs: renameSync(-wal, -shm sidecars)
recovery->>sqlite: open() retry → new Database(dbPath)
sqlite-->>recovery: success (fresh DB)
recovery-->>persist: "{ database, persistence }"
persist-->>IIFE: returns
Note over IIFE: If any await in IIFE throws…
IIFE-->>IIFE: .catch(error)
IIFE->>IIFE: dialog.showMessageBox(Quit)
IIFE->>IIFE: app.exit(1)
Prompt To Fix All With AI
Fix the following 3 code review issues. Work through them one at a time, proposing concise fixes.
---
### Issue 1 of 3
apps/desktop/src/main/lib/persistence/persistence.ts:22-40
`new Database(dbPath)` lives outside the `try/catch`, so if better-sqlite3's constructor throws `SQLITE_CORRUPT` (which it can when it runs internal setup PRAGMAs on a corrupt file), handle cleanup is delegated entirely to the native addon's error path rather than being explicit. Moving the constructor inside the `try` block lets the catch always call `opened?.close()` regardless of where the error originates, removing the implicit dependency on better-sqlite3's native cleanup behaviour on Windows.
```suggestion
const { database: db, persistence } = openSqliteWithRecovery(
dbPath,
"tanstack-db",
() => {
let opened: Database.Database | undefined;
try {
opened = new Database(dbPath);
const persistence = createNodeSQLitePersistence({
database: opened,
appliedTxPruneMaxRows: 1_000,
appliedTxPruneMaxAgeSeconds: 24 * 60 * 60,
});
return { database: opened, persistence };
} catch (error) {
// Release the handle so the file can be renamed on Windows.
opened?.close();
throw error;
}
},
);
```
### Issue 2 of 3
apps/desktop/src/main/lib/sqlite-recovery.test.ts:2
`readdirSync` is fetched via `require("node:fs")` rather than the ESM `import` at the top of the file. Adding it to the existing import is consistent with the rest of the file and avoids mixing module systems.
```suggestion
import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
```
### Issue 3 of 3
apps/desktop/src/main/lib/sqlite-recovery.test.ts:121-123
Companion change: replace the `require("node:fs").readdirSync` call with the now-imported `readdirSync`.
```suggestion
const quarantined = readdirSync(dir).find((f: string) =>
f.includes(".corrupt-"),
);
```
Reviews (1): Last reviewed commit: "fix: recover from corrupt tanstack-db SQ..." | Re-trigger Greptile
| const { database: db, persistence } = openSqliteWithRecovery( | ||
| dbPath, | ||
| "tanstack-db", | ||
| () => { | ||
| const opened = new Database(dbPath); | ||
| try { | ||
| const persistence = createNodeSQLitePersistence({ | ||
| database: opened, | ||
| appliedTxPruneMaxRows: 1_000, | ||
| appliedTxPruneMaxAgeSeconds: 24 * 60 * 60, | ||
| }); | ||
| return { database: opened, persistence }; | ||
| } catch (error) { | ||
| // Release the handle so the file can be renamed on Windows. | ||
| opened.close(); | ||
| throw error; | ||
| } | ||
| }, | ||
| ); |
There was a problem hiding this comment.
new Database(dbPath) lives outside the try/catch, so if better-sqlite3's constructor throws SQLITE_CORRUPT (which it can when it runs internal setup PRAGMAs on a corrupt file), handle cleanup is delegated entirely to the native addon's error path rather than being explicit. Moving the constructor inside the try block lets the catch always call opened?.close() regardless of where the error originates, removing the implicit dependency on better-sqlite3's native cleanup behaviour on Windows.
| const { database: db, persistence } = openSqliteWithRecovery( | |
| dbPath, | |
| "tanstack-db", | |
| () => { | |
| const opened = new Database(dbPath); | |
| try { | |
| const persistence = createNodeSQLitePersistence({ | |
| database: opened, | |
| appliedTxPruneMaxRows: 1_000, | |
| appliedTxPruneMaxAgeSeconds: 24 * 60 * 60, | |
| }); | |
| return { database: opened, persistence }; | |
| } catch (error) { | |
| // Release the handle so the file can be renamed on Windows. | |
| opened.close(); | |
| throw error; | |
| } | |
| }, | |
| ); | |
| const { database: db, persistence } = openSqliteWithRecovery( | |
| dbPath, | |
| "tanstack-db", | |
| () => { | |
| let opened: Database.Database | undefined; | |
| try { | |
| opened = new Database(dbPath); | |
| const persistence = createNodeSQLitePersistence({ | |
| database: opened, | |
| appliedTxPruneMaxRows: 1_000, | |
| appliedTxPruneMaxAgeSeconds: 24 * 60 * 60, | |
| }); | |
| return { database: opened, persistence }; | |
| } catch (error) { | |
| // Release the handle so the file can be renamed on Windows. | |
| opened?.close(); | |
| throw error; | |
| } | |
| }, | |
| ); |
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/persistence/persistence.ts
Line: 22-40
Comment:
`new Database(dbPath)` lives outside the `try/catch`, so if better-sqlite3's constructor throws `SQLITE_CORRUPT` (which it can when it runs internal setup PRAGMAs on a corrupt file), handle cleanup is delegated entirely to the native addon's error path rather than being explicit. Moving the constructor inside the `try` block lets the catch always call `opened?.close()` regardless of where the error originates, removing the implicit dependency on better-sqlite3's native cleanup behaviour on Windows.
```suggestion
const { database: db, persistence } = openSqliteWithRecovery(
dbPath,
"tanstack-db",
() => {
let opened: Database.Database | undefined;
try {
opened = new Database(dbPath);
const persistence = createNodeSQLitePersistence({
database: opened,
appliedTxPruneMaxRows: 1_000,
appliedTxPruneMaxAgeSeconds: 24 * 60 * 60,
});
return { database: opened, persistence };
} catch (error) {
// Release the handle so the file can be renamed on Windows.
opened?.close();
throw error;
}
},
);
```
How can I resolve this? If you propose a fix, please make it concise.| @@ -0,0 +1,169 @@ | |||
| import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; | |||
| import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; | |||
There was a problem hiding this comment.
readdirSync is fetched via require("node:fs") rather than the ESM import at the top of the file. Adding it to the existing import is consistent with the rest of the file and avoids mixing module systems.
| import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; | |
| import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs"; |
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/sqlite-recovery.test.ts
Line: 2
Comment:
`readdirSync` is fetched via `require("node:fs")` rather than the ESM `import` at the top of the file. Adding it to the existing import is consistent with the rest of the file and avoids mixing module systems.
```suggestion
import { existsSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";
```
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
| const quarantined = require("node:fs") | ||
| .readdirSync(dir) | ||
| .find((f: string) => f.includes(".corrupt-")); |
There was a problem hiding this comment.
Companion change: replace the
require("node:fs").readdirSync call with the now-imported readdirSync.
| const quarantined = require("node:fs") | |
| .readdirSync(dir) | |
| .find((f: string) => f.includes(".corrupt-")); | |
| const quarantined = readdirSync(dir).find((f: string) => | |
| f.includes(".corrupt-"), | |
| ); |
Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/desktop/src/main/lib/sqlite-recovery.test.ts
Line: 121-123
Comment:
Companion change: replace the `require("node:fs").readdirSync` call with the now-imported `readdirSync`.
```suggestion
const quarantined = readdirSync(dir).find((f: string) =>
f.includes(".corrupt-"),
);
```
How can I resolve this? If you propose a fix, please make it concise.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Root cause
The desktop app auto-updated 1.12.1→1.12.2 and the restart truncated
~/.superset/tanstack-db.sqlite(1.1 GB). On every subsequent launch,initTanstackDbPersistence()threwSqliteError: database disk image is malformed(SQLITE_CORRUPT).Two problems compounded:
persistence.tsopened the cache DB with zero error handling, so a corrupt file made startup throw every launch.apps/desktop/src/main/index.ts). The rejection silently aborted everything after the DB init, includingMainWindow(). The process stayed alive with no visible window, Window→Move & Resize grayed out, and nothing inmain.log(startup died before logger wiring). The only evidence was a Sentry breadcrumb.The fix
1. New
lib/sqlite-recovery.ts— a small, injectable helper:isSqliteCorruptionError— detectsSQLITE_CORRUPT*/SQLITE_NOTADBvia better-sqlite3's.code.quarantineCorruptDatabase— renames the file (and-wal/-shmsidecars) aside as.corrupt-<ts>(nothing deleted; recoverable later).openSqliteWithRecovery(dbPath, label, open)— runsopen(); on a corruption error it quarantines, logs, reports to Sentry (no-op in dev), and retriesopen()once. Non-corruption errors rethrow; a second failure propagates (no infinite retry). Theopencallback is injectable so unit tests never need realbetter-sqlite3(which can't load underbun test).2.
persistence.tsroutes the DB open through the helper.tanstack-db.sqliteis a pure sync cache with no migrations, so quarantine-and-rebuild-from-server is safe and silent. The callback closes its handle before throwing so the quarantine rename works on Windows.3.
index.tsadds a.catch()to the startup IIFE — a last-resort guard so any startup failure surfaces an error dialog and exits instead of leaving a windowless process.Tests
lib/sqlite-recovery.test.ts(bun:test, real temp files, fake errors with.code— no real sqlite):-wal/-shmquarantined to.corrupt-*, second open returned.SQLITE_BUSY) rethrown, files untouched.isSqliteCorruptionErrortruth table.bun run lintexits 0. Changed files typecheck clean.Closes #5084
Summary by cubic
Recovers cleanly from a corrupt
tanstack-db.sqliteand prevents a windowless zombie process by guarding startup errors. Fixes #5084.sqlite-recoveryhelper to detect corruption, quarantine the DB and sidecars, log/report, and retry open once.tanstack-dbvia recovery; it's a cache, so quarantine-and-rebuild is safe. Ensures the DB handle is closed before retry (Windows-friendly).Written for commit 14c08ed. Summary will update on new commits.