diff --git a/hermes_state.py b/hermes_state.py index 08576cacf6..3cdffe3744 100644 --- a/hermes_state.py +++ b/hermes_state.py @@ -3257,9 +3257,22 @@ def repair_state_db_schema(db_path: Path, *, backup: bool = True) -> Dict[str, A ) logger.error("state.db repair skipped: %s", report["error"]) else: + # Probe the mode BEFORE surgery (#89674): every repair + # strategy rewrites the file, and a rebuilt SQLite file comes + # back in the default journal mode (delete) — silently moving + # a WAL store out of WAL with nothing in the logs recording + # the flip. The open-time WAL-reset gate never sees this flip + # because it happens inside the repair path (distinct from + # the open-time flip #89393 warns about). A probe of the + # damaged file may fail, in which case the canonical + # database.journal_mode setting is the restore target. + before_mode = _probe_journal_mode_for_repair(db_path) result = _repair_state_db_schema_locked( db_path, backup=backup, report=report ) + if result.get("repaired"): + result["journal_mode_before"] = before_mode + _restore_journal_mode_after_repair(db_path, before_mode) # Environmental aborts happen before a strategy gets to mutate the # isolated snapshot. They are retriable operating conditions, not # proof that the damaged database exhausted a repair strategy. @@ -3277,6 +3290,71 @@ def repair_state_db_schema(db_path: Path, *, backup: bool = True) -> Dict[str, A return result +def _probe_journal_mode_for_repair(db_path: Path) -> Optional[str]: + """Best-effort journal-mode probe for a (possibly malformed) DB file. + + Returns the on-disk mode (``wal``/``delete``), or ``None`` when the file + cannot be opened or probed — a malformed header or a concurrent opener's + locks are both expected on the repair path. Callers fall back to the + configured ``database.journal_mode`` for ``None``. + """ + try: + conn = sqlite3.connect(str(db_path)) + try: + return _on_disk_journal_mode(conn) + finally: + conn.close() + except (sqlite3.Error, OSError): + return None + + +def _restore_journal_mode_after_repair(db_path: Path, before_mode: Optional[str]) -> None: + """Re-apply the journal mode after schema surgery (#89674). + + A repaired/rebuilt SQLite file comes back in the default journal mode + (delete). Without this restore, a corruption event deterministically + moves a WAL store out of WAL and nothing records the change — the + WAL-reset gate at open time never sees the flip because it happened + inside the repair path, not at open (the open-time flip #89393 warns + about is a different door). + + The restore runs through :func:`apply_wal_with_fallback` — the canonical + journal-mode path — rather than issuing a switch pragma directly, so it + inherits the vulnerable-SQLite WAL-reset gate (a rebuilt file IS a new + database: on a vulnerable runtime the gate deliberately keeps it in + DELETE, and "restore could not reach WAL" there is the expected outcome, + not a failure), the macOS-NFS silent-refusal handling, and the WAL + companions (size limit, checkpoint barrier, synchronous=FULL) that the + front door applies. ``before_mode`` is the pre-surgery probe (None when + the damaged file could not be probed) and is only used for the log + comparison — the restore target itself is whatever the canonical path + resolves from ``database.journal_mode``. + + Best-effort by design: the repair itself already succeeded, so failures + to re-apply are logged at WARNING, never raised. + """ + try: + conn = sqlite3.connect(str(db_path)) + try: + after = apply_wal_with_fallback(conn, db_label=db_path.name) + finally: + conn.close() + if before_mode and after != before_mode: + logger.warning( + "state.db repair changed journal_mode %r -> %r " + "(pre-surgery probe %r; restore resolved through " + "apply_wal_with_fallback per database.journal_mode and the " + "WAL-reset gate)", + before_mode, after, before_mode, + ) + except (sqlite3.Error, OSError) as exc: + logger.warning( + "state.db repair at %s: post-surgery journal-mode restore " + "failed (%s); verify with PRAGMA journal_mode on the next open", + db_path, exc, + ) + + def _repair_state_db_schema_locked( db_path: Path, *, backup: bool, report: Dict[str, Any] ) -> Dict[str, Any]: diff --git a/tests/test_state_db_malformed_repair.py b/tests/test_state_db_malformed_repair.py index 2d634e3f16..c55b2dfc92 100644 --- a/tests/test_state_db_malformed_repair.py +++ b/tests/test_state_db_malformed_repair.py @@ -643,3 +643,140 @@ def test_backup_false_still_skips_backup_and_repairs(tmp_path): assert report["repaired"] is True assert report["backup_path"] is None assert not list(tmp_path.glob("state.db.malformed-backup-*")) + + +# --------------------------------------------------------------------------- +# Journal-mode restore after surgery (#89674): corruption drops the WAL bit +# from the header, the repair strategies rebuild the file in the default +# (delete) mode, and nothing used to record the flip. The configured +# database.journal_mode must be re-applied, with a WARNING naming it. +# --------------------------------------------------------------------------- + + +def _mode_of(db_path) -> str: + conn = sqlite3.connect(str(db_path)) + try: + return str(conn.execute("PRAGMA journal_mode").fetchone()[0]).lower() + finally: + conn.close() + + +def _configure_journal_mode(monkeypatch, tmp_path, mode) -> None: + import yaml + + home = tmp_path / "hermes-home" + home.mkdir(exist_ok=True) + monkeypatch.setenv("HERMES_HOME", str(home)) + (home / "config.yaml").write_text( + yaml.safe_dump({"database": {"journal_mode": mode}}), encoding="utf-8", + ) + monkeypatch.setattr( + hermes_state, "is_sqlite_wal_reset_vulnerable", lambda **kwargs: False, + ) + + +def test_repair_restores_configured_wal_after_surgery( + tmp_path, caplog, monkeypatch +): + """A repaired file left in delete mode must return to the configured WAL. + + Simulates the reported sequence: corruption drops the WAL bit (the file + reads back as delete), surgery heals the schema, and the store must end + up in the canonical database.journal_mode again — with a WARNING so the + operator sees the mode moved.""" + import logging + + db_path = tmp_path / "state.db" + _configure_journal_mode(monkeypatch, tmp_path, "wal") + _build_healthy_db(db_path) + assert _mode_of(db_path) == "wal" + # Downgrade while the file is still healthy (the damaged file rejects + # every statement — see test_duplicate_fts_makes_every_statement_fail), + # simulating the header state the reporter's corruption storm left: the + # WAL bit is gone and the file reads back as delete. + conn = sqlite3.connect(str(db_path)) + conn.execute("PRAGMA journal_mode=DELETE") + conn.close() + assert _mode_of(db_path) == "delete" + _corrupt_duplicate_fts(db_path) + + with caplog.at_level(logging.WARNING, logger="hermes_state"): + report = repair_state_db_schema(db_path) + + assert report["repaired"] is True + assert _mode_of(db_path) == "wal" + assert any( + "changed journal_mode" in r.getMessage() for r in caplog.records + ), f"expected the mode flip to be logged; got: {[r.getMessage() for r in caplog.records]}" + + +def test_repair_logs_nothing_when_mode_already_matches( + tmp_path, caplog, monkeypatch +): + """FTS-only corruption keeps the WAL bit; the restore is then a no-op and + must not emit a mode-flip WARNING.""" + import logging + + db_path = tmp_path / "state.db" + _configure_journal_mode(monkeypatch, tmp_path, "wal") + _build_healthy_db(db_path) + _corrupt_duplicate_fts(db_path) + + with caplog.at_level(logging.WARNING, logger="hermes_state"): + report = repair_state_db_schema(db_path) + + assert report["repaired"] is True + assert _mode_of(db_path) == "wal" + assert not any( + "changed journal_mode" in r.getMessage() for r in caplog.records + ) + + +def test_repair_restore_failure_is_nonfatal_and_logged( + tmp_path, caplog, monkeypatch +): + """When the post-surgery WAL switch is refused (locked/unsupported fs), + the repair result stands and a WARNING names the modes and the config + key — never an exception out of the repair path.""" + import logging + from unittest.mock import patch + + db_path = tmp_path / "state.db" + _configure_journal_mode(monkeypatch, tmp_path, "wal") + _build_healthy_db(db_path) + conn = sqlite3.connect(str(db_path)) + conn.execute("PRAGMA journal_mode=DELETE") + conn.close() + _corrupt_duplicate_fts(db_path) + + def _refused(conn, mode): + raise sqlite3.OperationalError("database is locked") + + with ( + patch.object(hermes_state, "_set_journal_mode_no_wait", _refused), + caplog.at_level(logging.WARNING, logger="hermes_state"), + ): + report = repair_state_db_schema(db_path) + + assert report["repaired"] is True + assert _mode_of(db_path) == "delete" + assert any( + "could not" in r.getMessage() and "restored" in r.getMessage() + for r in caplog.records + ) + + +def test_repair_honors_configured_delete_mode(tmp_path, monkeypatch): + """An explicit database.journal_mode=delete store stays delete after + repair — the restore applies the operator's setting, not a hard-coded + WAL.""" + db_path = tmp_path / "state.db" + _configure_journal_mode(monkeypatch, tmp_path, "delete") + _build_healthy_db(db_path) + assert _mode_of(db_path) == "delete" + _corrupt_duplicate_fts(db_path) + + report = repair_state_db_schema(db_path) + + assert report["repaired"] is True + assert _mode_of(db_path) == "delete"