Skip to content

fix: solve #5084 — recover from corrupt tanstack-db SQLite & guard startup - #5085

Closed
github-actions[bot] wants to merge 1 commit into
mainfrom
triage/issue-5084-26927869229
Closed

github-actions[bot] wants to merge 1 commit into
mainfrom
triage/issue-5084-26927869229

Conversation

@github-actions

@github-actions github-actions Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

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() threw SqliteError: database disk image is malformed (SQLITE_CORRUPT).

Two problems compounded:

  1. No recovery — persistence.ts opened the cache DB with zero error handling, so a corrupt file made startup throw every launch.
  2. Silent windowless zombie — the startup sequence is an un-caught async IIFE (apps/desktop/src/main/index.ts). The rejection silently aborted everything after the DB init, including MainWindow(). The process stayed alive with no visible window, Window→Move & Resize grayed out, and nothing in main.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 — detects SQLITE_CORRUPT* / SQLITE_NOTADB via better-sqlite3's .code.
  • quarantineCorruptDatabase — renames the file (and -wal/-shm sidecars) aside as .corrupt-<ts> (nothing deleted; recoverable later).
  • openSqliteWithRecovery(dbPath, label, open) — runs open(); on a corruption error it quarantines, logs, reports to Sentry (no-op in dev), and retries open() once. Non-corruption errors rethrow; a second failure propagates (no infinite retry). The open callback is injectable so unit tests never need real better-sqlite3 (which can't load under bun test).

2. persistence.ts routes the DB open through the helper. tanstack-db.sqlite is 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.ts adds 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):

  • Reproduction: corruption on first open → main + -wal/-shm quarantined to .corrupt-*, second open returned.
  • Recovers when sidecars are absent.
  • Non-corruption errors (SQLITE_BUSY) rethrown, files untouched.
  • Second open also throws → propagates (no infinite retry).
  • isSqliteCorruptionError truth table.
17 pass / 0 fail

bun run lint exits 0. Changed files typecheck clean.

Closes #5084


Open in Stage

Summary by cubic

Recovers cleanly from a corrupt tanstack-db.sqlite and prevents a windowless zombie process by guarding startup errors. Fixes #5084.

  • Bug Fixes
    • Add sqlite-recovery helper to detect corruption, quarantine the DB and sidecars, log/report, and retry open once.
    • Open tanstack-db via recovery; it's a cache, so quarantine-and-rebuild is safe. Ensures the DB handle is closed before retry (Windows-friendly).
    • Catch unhandled errors in the startup IIFE to show an error dialog and exit instead of leaving the app running without a window.

Written for commit 14c08ed. Summary will update on new commits.

Review in cubic

@ghost

ghost commented Jun 4, 2026

Copy link
Copy Markdown

Ready to review this PR? Stage has broken it down into 4 individual chapters for you:

Title
1 Implement SQLite corruption detection and recovery logic
2 Verify SQLite recovery with unit tests
3 Apply recovery logic to Tanstack DB persistence
4 Add fatal error guard to startup sequence
Open in Stage

Chapters generated by Stage for commit 14c08ed on Jun 4, 2026 3:15am UTC.

@greptile-apps

greptile-apps Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR addresses a real regression where a truncated tanstack-db.sqlite after an auto-update caused a silent windowless zombie process on every subsequent launch. The fix introduces a new sqlite-recovery.ts helper that quarantines corrupt databases and retries once, routes the tanstack persistence open through it, and adds a .catch() last-resort guard to the startup IIFE so future startup failures surface as an error dialog instead of a zombie.

  • sqlite-recovery.ts: New injectable helper with isSqliteCorruptionError, quarantineCorruptDatabase, and openSqliteWithRecovery<T>; includes a solid bun:test suite covering the happy path, retry limit, non-corruption rethrow, and sidecar handling.
  • persistence.ts: Routes initTanstackDbPersistence through the recovery wrapper; the callback closes its Database handle before rethrowing so Windows can rename the locked file.
  • index.ts: The startup IIFE now has a .catch() that shows an error dialog and calls app.exit(1) instead of leaving a windowless process alive.

Confidence Score: 4/5

Safe 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.

Important Files Changed

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)
Loading
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

Comment on lines +22 to +40
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;
}
},
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
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";

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Suggested change
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!

Comment on lines +121 to +123
const quarantined = require("node:fs")
.readdirSync(dir)
.find((f: string) => f.includes(".corrupt-"));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Companion change: replace the require("node:fs").readdirSync call with the now-imported readdirSync.

Suggested change
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!

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.

[bug] Superset sqlite got corrupted and window never opened

1 participant