Skip to content

The agent that grows with you

fix(state): catch the corruption-class DatabaseError inside rebuild_fts()

liuhao1024e9a981bb6c4e
diff --git a/hermes_state_search.py b/hermes_state_search.py
index 58a84f127ac..594b6551b65 100644
--- a/hermes_state_search.py
+++ b/hermes_state_search.py
@@ -1329,6 +1329,15 @@ class SessionSearchMixin:
except sqlite3.OperationalError as exc:
self._conn.rollback()
logger.warning("FTS rebuild failed for %s: %s", tbl, exc)
+ except sqlite3.DatabaseError as exc:
+ # SQLITE_CORRUPT ("database disk image is malformed") is a DatabaseError,
+ # not an OperationalError — the corruption class this recovery exists for.
+ # Without this arm the error escaped the loop un-rolled-back and callers
+ # lost the 0-means-no-progress signal they route on (#133375).
+ self._conn.rollback()
+ logger.error(
+ "FTS rebuild failed with a corruption-class error for %s: %s; "
+ "the index needs the offline repair path (repair_state_db_schema)", tbl, exc)
return rebuilt
def _merge_fts_incrementally(self, *, max_pages: int, max_commands: Optional[int] = None) -> int:
diff --git a/tests/hermes_state/test_fts_rebuild_corruption_class.py b/tests/hermes_state/test_fts_rebuild_corruption_class.py
new file mode 100644
index 00000000000..aa2e20a0a8c
--- /dev/null
+++ b/tests/hermes_state/test_fts_rebuild_corruption_class.py
@@ -0,0 +1,76 @@
+"""``rebuild_fts()`` must catch the corruption class it exists to recover from (#133375).
+
+SQLITE_CORRUPT — ``sqlite3.DatabaseError("database disk image is malformed")`` — is not an
+``OperationalError`` (its subclass); it is a sibling. The in-place FTS rebuild is the recovery
+path for a corrupt index, so a failing ``'rebuild'`` command raises precisely the class the
+except arm must cover. Catching only ``OperationalError`` let the error escape the per-index
+loop un-rolled-back, and callers could not distinguish "rebuild attempted and hit structural
+corruption" from deferral. These tests pin the caught-and-rolled-back behavior.
+"""
+
+import sqlite3
+
+import pytest
+
+from hermes_state import SessionDB
+
+
+def db(tmp_path):
+ d = SessionDB(db_path=tmp_path / "state.db")
+ if not d._fts_enabled:
+ d.close()
+ pytest.skip("FTS5 unavailable in this build")
+ d.create_session("s1", source="test")
+ d.append_message("s1", "user", "hello world")
+ yield d
+ try:
+ d.close()
+ except Exception:
+ pass
+
+
+def _corrupting_execute(match):
+ """Wrap ``execute`` so ``'rebuild'`` commands whose SQL satisfies *match* raise the
+ corruption-class error; every other statement passes through."""
+
+ def wrap(real_execute):
+ def execute(sql, *args, **kwargs):
+ if "VALUES('rebuild')" in sql and match(sql):
+ raise sqlite3.DatabaseError("database disk image is malformed")
+ return real_execute(sql, *args, **kwargs)
+
+ return execute
+
+ return wrap
+
+
+def test_corruption_class_error_is_caused_rolled_back_and_reported(
+ db, monkeypatch, caplog
+):
+ """The exact production failure (#133375): every index rebuild raises DatabaseError.
+ The call must return 0 (no progress), roll the connection back, and say the offline
+ repair path is needed — not propagate the error out of the loop."""
+ monkeypatch.setattr(
+ db._conn, "execute", _corrupting_execute(lambda sql: True)(db._conn.execute)
+ )
+ with caplog.at_level("ERROR"):
+ assert db.rebuild_fts() == 0
+ assert (
+ db._conn.in_transaction is False
+ ) # the except arm rolled the failed statement back
+ assert any("offline repair" in rec.message for rec in caplog.records)
+
+
+def test_one_corrupt_index_does_not_stop_the_remaining_indexes(db, monkeypatch):
+ """Only messages_fts is corrupt; trigram/cjk must still be rebuilt — the loop survives
+ a corruption-class failure on one index. The trailing ``(`` keeps the match off
+ ``messages_fts_trigram``/``_cjk``."""
+ monkeypatch.setattr(
+ db._conn,
+ "execute",
+ _corrupting_execute(lambda sql: sql.startswith("INSERT INTO messages_fts("))(
+ db._conn.execute
+ ),
+ )
+ assert db.rebuild_fts() >= 1