Skip to content

fix(core): auto-recover corrupted sqlite database on startup#37822

Open
leecoder wants to merge 1 commit into
anomalyco:devfrom
leecoder:sqlite-auto-recovery
Open

fix(core): auto-recover corrupted sqlite database on startup#37822
leecoder wants to merge 1 commit into
anomalyco:devfrom
leecoder:sqlite-auto-recovery

Conversation

@leecoder

Copy link
Copy Markdown

Issue for this PR

Closes #37821

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

When the SQLite database file is corrupted, opencode crashes on startup with database disk image is malformed or file is not a database. This happened to me after a power loss corrupted the WAL file.

The fix wraps DB initialization with Layer.catchCause. If the init fails with a corruption-related SQLite error, it:

  1. Renames the corrupted .db, -wal, -shm files with a .corrupt-<timestamp> suffix
  2. Retries initialization with a fresh database
  3. Logs a warning so the user knows recovery happened

The detection uses error message matching (file is not a database / database disk image is malformed) rather than header-only inspection, so it catches both header corruption and internal page corruption.

If the backup rename itself fails (permissions, file lock), it logs a distinct warning instead of silently claiming success.

How did you verify your code works?

  • Added a test in database-migration.test.ts that writes a file with valid SQLite header but corrupted internal pages, then verifies recovery creates a working database and the .corrupt-* backup exists
  • Manual smoke test with a fully corrupted file confirmed the warning log and fresh DB creation
  • bun typecheck passes for both packages/core and packages/opencode

Screenshots / recordings

N/A - not a UI change

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

@leecoder
leecoder force-pushed the sqlite-auto-recovery branch from bb3cb06 to d1e3102 Compare July 20, 2026 02:46
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.

opencode crashes on startup when SQLite database is corrupted

1 participant