Repository navigation
fix(state): heal a damaged or missing history.db instead of exiting - #1900
Conversation
A damaged history.db made Core exit at boot, and systemd restarted it every 5 s with no driver running. Core now moves the file and its -wal/-shm aside as .corrupt-<ms>, starts an empty history bound to a new generation and reports a history heal event on /api/health and in the storage banner. A readable history.db from another generation is still refused. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 63e589255f
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| func (s *Store) openHistory() error { | ||
| err := s.openHistoryOnce() |
There was a problem hiding this comment.
Allow already-converted beta sites to reach history recovery
For a site that previously ran ConvertBetaHistory, a missing or header-corrupted history.db still prevents Core from starting: bindConvertedHistory retains history_duckdb_generation, and openStore calls requireConvertedBeta before reaching this recovery wrapper. That preflight returns an error when the converted file is missing or its migration marker cannot be read. These are already-converted sites, not beta archives awaiting conversion, so the new recovery behavior excludes an existing upgrade path. Let missing/damaged converted history reach recovery while preserving the refusal for genuinely unconverted archives; also account for the retained beta key when rebinding the fresh file.
Useful? React with 👍 / 👎.
| case errors.As(err, &damage): | ||
| detail = "history.db was damaged — moved aside and started an empty history (charts and energy totals lost)" | ||
| case !errors.Is(err, errHistoryMissing): | ||
| return err |
There was a problem hiding this comment.
Classify corruption from the remaining startup queries
If corruption affects a data-table page rather than the schema or generation marker, startup can pass all three calls to damaged and then return an unclassified SQLite corruption error. For example, a malformed history_source_cursor page is accessed by the final startup INSERT, whose error is returned directly; refreshSourceDayCache likewise returns errors without classification. This wrapper consequently propagates the error and Core remains in the restart loop instead of rebuilding history. Apply damage classification to the remaining history operations during startup, while continuing to exclude state.db errors and restore-generation failures.
Useful? React with 👍 / 👎.
Review of #1900 found three cases where a damaged history.db still stopped Core: - Converted beta sites. The heal kept history_duckdb_generation, so the retry failed with "beta history needs conversion", and the preflight refused a missing or unreadable history.db before the heal could run. The heal now clears the beta key too (both heal paths need a bound SQLite generation, so conversion is done) and logs its value. The preflight lets a missing, empty or SQLITE_CORRUPT/NOTADB file through. - Damage first read by a later startup query (sqlite-v1 count, ledger version, source cursor batch, source day cache) went up unclassified. Those history-only steps now go through the same check. Steps that also read state.db or other files (chart recovery, raw retirement) count as damage only when quick_check of history.db fails. - A 0-byte history.db opened as an empty database and was refused as a foreign generation. A file with no history_migrations rows now heals like a missing one; a file with another generation is still refused. The failure cleanup also closes a handle that RetireRawHistory swapped in. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Item F1 of the stable plan.
Problem
history.db has no heal path. When it is damaged,
openHistoryreturns an error,main.goexits, and systemd restarts Core every 5 s. No driver runs until someone restores a backup by hand. Two cases on master 83c2b24:Openfails withfile is not a database (26).Openfails withprimary SQLite history is missing; restore a full backup.history.db holds charts and the energy ledger, not control state, so losing it should not stop control.
Change
openHistorynow wraps the old body (renamedopenHistoryOnce). It heals when history.db is missing, when it is empty (nohistory_migrationsrows at all, such as a 0-byte file), or when any startup step on history.db fails with damage. Damage means SQLITE_CORRUPT, SQLITE_NOTADB, or a failedquick_checkafter the error. The checked steps are the schema count, schema, generation read,sqlite-v1count, ledger version, source cursor batch and source day cache. Chart recovery and raw retirement also read state.db or other files, so for them only a failedquick_checkof history.db counts. On heal it:.corrupt-<ms>with the existingquarantine;history_duckdb_generation(logged), since conversion is done and the key would otherwise make the retry ask for conversion. The beta originals stay on disk;HealEvent{Tier: "history", Action: "rebuilt"}.requireConvertedBetalets a missing, empty or SQLITE_CORRUPT/NOTADB history.db through to the heal on a converted site. Unconverted beta archives are still refused.ts_samplespage) does not stop Core at boot, so nothing heals it then. That is the same as on master./api/healthstoragegains"history": "ok", and the storage banner inweb/app.jsalso shows a history heal. This changes one condition; the banner itself is unchanged. A person should still look at it in a browser.docs/architecture.mdstates the new behaviour.Behaviour change: a missing history.db used to be refused on purpose. It now starts empty, logs an error and shows the loss.
TestHistoryMissingOrUnboundPrimaryFailsdrops itsmissingcase (nowTestHistoryUnboundPrimaryFails), andTestSnapshotToSkipsTimeSeriesTablesnow expects a compact snapshot opened alone to report the history heal rather than fail.Tests
go/internal/state/history_heal_test.go, from the audit repro (caa-131):TestCorruptHistoryHealsOnOpenandTestMissingHistoryHealsOnOpen: Open succeeds, reports one history heal event, accepts writes, binds a generation, keeps the damaged file, and a second Open reports no event.TestForeignHistoryGenerationStillRefused.TestCorruptHistoryDataPageHealsOnOpen(history_source_cursorandenergy_ledger_metaroot pages),TestTruncatedHistoryHealsOnOpen,TestZeroLengthHistoryHealsOnOpen,TestConvertedBetaHistoryHealsOnOpen(missing, header, data page, zero length; beta key cleared) andTestRestoreGenerationCorruptStillRefused. On 63e5892 the data-page, zero-length and converted-beta tests fail.file is not a database (26),primary SQLite history is missing) and pass on this branch.go test -race -count=1 ./internal/state/... ./internal/api/...: api ok. state had one failure,TestSnapshotToSkipsTimeSeriesTables, which expected the old refusal. After I updated it, it passes under-racetogether with the new tests.go test ./internal/backup/... ./cmd/ftw/...: ok.go vet ./...andgo build ./...: ok.go test -raceoninternal/statepasses apart fromTestLiveBackupPastItsLimitNamesTheLimitAndTable, a 1 s backup deadline that missed under load with other packages running. It passes 3 of 3 alone under-race.internal/api,internal/backupandcmd/ftwpass under-race.go veton state and api: ok.Risk
Medium. If history.db goes missing because of a mount fault, Core binds a new generation. The old file then fails the generation check when it comes back. That is logged and can be recovered by hand.
quick_checkruns only after an open or schema error, so a healthy boot does no extra work.🤖 Generated with Claude Code