Skip to content

fix(state): heal a damaged or missing history.db instead of exiting - #1900

Merged
frahlg merged 2 commits into
masterfrom
f1-damaged-history-heals
Oct 27, 2026
Merged

frahlg merged 2 commits into
masterfrom
f1-damaged-history-heals

Conversation

@frahlg

@frahlg frahlg commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Item F1 of the stable plan.

Problem

history.db has no heal path. When it is damaged, openHistory returns an error, main.go exits, and systemd restarts Core every 5 s. No driver runs until someone restores a backup by hand. Two cases on master 83c2b24:

  • Zero the 100-byte SQLite header of history.db: Open fails with file is not a database (26).
  • Remove history.db and its -wal/-shm: Open fails with primary 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

  • openHistory now wraps the old body (renamed openHistoryOnce). It heals when history.db is missing, when it is empty (no history_migrations rows 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 failed quick_check after the error. The checked steps are the schema count, schema, generation read, sqlite-v1 count, 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 failed quick_check of history.db counts. On heal it:
    • moves history.db and its -wal/-shm to .corrupt-<ms> with the existing quarantine;
    • clears the active and pending generation keys, so the fresh file binds a new generation;
    • on a site that converted beta history, also clears 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;
    • records a HealEvent{Tier: "history", Action: "rebuilt"}.
  • requireConvertedBeta lets a missing, empty or SQLITE_CORRUPT/NOTADB history.db through to the heal on a converted site. Unconverted beta archives are still refused.
  • Busy, full or read-only errors are not damage and still fail as before.
  • Still refused: a readable history.db bound to another generation (a wrong file from a restore), the restore-generation path, unbound or incomplete history, and beta data that needs conversion.
  • Not covered: damage in a table no startup query reads (for example a ts_samples page) does not stop Core at boot, so nothing heals it then. That is the same as on master.
  • /api/health storage gains "history": "ok", and the storage banner in web/app.js also 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.md states 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. TestHistoryMissingOrUnboundPrimaryFails drops its missing case (now TestHistoryUnboundPrimaryFails), and TestSnapshotToSkipsTimeSeriesTables now expects a compact snapshot opened alone to report the history heal rather than fail.

Tests

  • New go/internal/state/history_heal_test.go, from the audit repro (caa-131):
    • TestCorruptHistoryHealsOnOpen and TestMissingHistoryHealsOnOpen: Open succeeds, reports one history heal event, accepts writes, binds a generation, keeps the damaged file, and a second Open reports no event.
    • TestForeignHistoryGenerationStillRefused.
    • Added after review: TestCorruptHistoryDataPageHealsOnOpen (history_source_cursor and energy_ledger_meta root pages), TestTruncatedHistoryHealsOnOpen, TestZeroLengthHistoryHealsOnOpen, TestConvertedBetaHistoryHealsOnOpen (missing, header, data page, zero length; beta key cleared) and TestRestoreGenerationCorruptStillRefused. On 63e5892 the data-page, zero-length and converted-beta tests fail.
  • The original repro tests fail on master (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 -race together with the new tests.
  • go test ./internal/backup/... ./cmd/ftw/...: ok.
  • go vet ./... and go build ./...: ok.
  • After review fixes (cbe1f74): go test -race on internal/state passes apart from TestLiveBackupPastItsLimitNamesTheLimitAndTable, a 1 s backup deadline that missed under load with other packages running. It passes 3 of 3 alone under -race. internal/api, internal/backup and cmd/ftw pass under -race. go vet on 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_check runs only after an open or schema error, so a healthy boot does no extra work.

🤖 Generated with Claude Code

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]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T13:38:55.024310Z 63e5892 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +55 to +56
func (s *Store) openHistory() error {
err := s.openHistoryOnce()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Comment on lines +60 to +63
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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]>
@frahlg
frahlg merged commit fd928c6 into master Oct 27, 2026
22 checks passed
@frahlg
frahlg deleted the f1-damaged-history-heals branch November 11, 2026 09:16
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.

1 participant