Solution:
Root Cause: Unwritten Page Cache and B-Tree Structure Corruption
When power cuts during active write transactions, SQLite's memory cache page fails to flush to physical storage. This results in missing header pointers or invalid page counts within
home-assistant_v2.db, causing the Python
sqlite3 driver to throw
database disk image is malformed during read operations.
# Diagnostic Verification:
Access the Home Assistant Terminal (SSH or Advanced Web Terminal) and execute a diagnostic integrity check on the database file:
bash organize
cd /config
sqlite3 home-assistant_v2.db "PRAGMA integrity_check;"
If output shows error lines such as
Page N is never used or
malformed, the B-Tree structure is corrupted.
# Step-by-Step Fix:
1. Stop the Home Assistant Core service to release file locks:
bash
ha core stop
2. Navigate to the configuration directory and back up the malformed database files:
bash
cd /config
mv home-assistant_v2.db home-assistant_v2.db.corrupt
mv home-assistant_v2.db-wal home-assistant_v2.db-wal.bak 2>/dev/null || true
3. Dump the uncorrupted schema and records from the corrupted file into a clean database:
bash
sqlite3 home-assistant_v2.db.corrupt ".mode insert" ".dump" | sqlite3 home-assistant_v2.db.recovered
4. Replace the old database with the recovered database file and set correct file permissions:
bash
mv home-assistant_v2.db.recovered home-assistant_v2.db
chmod 664 home-assistant_v2.db
5. Start Home Assistant Core:
bash
ha core start
# Prevention & Long-Term Monitoring:
Connect the Home Assistant host system to an Uninterruptible Power Supply (UPS) integrated with the NUT (Network UPS Tools) integration for automated graceful shutdowns.