Skip to content

The agent that grows with you

fix(state): make a refused pre-repair backup a hard stop (#69603)

Tekniumd724bd037626
diff --git a/hermes_state.py b/hermes_state.py
index b68f7992f4f..eb36c4d1249 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -1581,12 +1581,16 @@ def _bump_schema_cookie(conn: sqlite3.Connection) -> None:
logger.warning("Could not bump state.db schema cookie: %s", exc)
-def _backup_db_file(db_path: Path) -> Optional[Path]:
+def _backup_db_file(db_path: Path) -> "Tuple[Optional[Path], Optional[str]]":
"""Copy a (possibly malformed) DB file to a timestamped backup beside it.
Raw file copy on purpose: the DB won't open cleanly, so we preserve the
bytes exactly for forensics / manual restore. WAL and SHM sidecars are
- copied too when present. Returns the backup path, or None on failure.
+ copied too when present. Returns ``(backup_path, None)`` on success or
+ ``(None, reason)`` on failure — callers on the repair path treat a
+ refused backup as a HARD STOP (see #69603: proceeding without the
+ pre-repair backup leaves the writable_schema surgery, FTS deletion and
+ VACUUM strategies mutating the only remaining copy of the damaged DB).
Refuses when a connection to this database is still live in the process:
reading the file would ``close()`` a descriptor for it and cancel that
@@ -1603,13 +1607,13 @@ def _backup_db_file(db_path: Path) -> Optional[Path]:
has_live_connection = None # type: ignore[assignment]
if has_live_connection is not None and has_live_connection(db_path):
- logger.error(
- "Refusing to raw-copy %s for backup: a connection to it is still "
- "open in this process and the copy would cancel that connection's "
- "POSIX locks. Close all SessionDB handles first.",
- db_path,
+ reason = (
+ f"a connection to {db_path} is still open in this process; "
+ "raw-copying it would cancel that connection's POSIX advisory "
+ "locks. Close all SessionDB handles first."
)
- return None
+ logger.error("Refusing to raw-copy %s for backup: %s", db_path, reason)
+ return None, reason
stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
backup_path = db_path.with_name(f"{db_path.name}.malformed-backup-{stamp}")
@@ -1619,10 +1623,10 @@ def _backup_db_file(db_path: Path) -> Optional[Path]:
sidecar = db_path.with_name(db_path.name + suffix)
if sidecar.exists():
shutil.copy2(sidecar, backup_path.with_name(backup_path.name + suffix))
- return backup_path
+ return backup_path, None
except Exception as exc: # pragma: no cover - best effort
logger.warning("Could not back up malformed DB %s: %s", db_path, exc)
- return None
+ return None, f"backup copy failed: {exc}"
def preflight_db_writability(
@@ -1920,8 +1924,21 @@ def _repair_state_db_schema_locked(
return report
if backup:
- bpath = _backup_db_file(db_path)
+ bpath, backup_error = _backup_db_file(db_path)
report["backup_path"] = str(bpath) if bpath else None
+ if bpath is None:
+ # HARD STOP (#69603): every strategy below mutates the damaged
+ # file in place (FTS rebuild, REINDEX, writable_schema surgery,
+ # VACUUM). Without the pre-repair backup, the damaged DB is the
+ # only copy of the user's data — a failed or interrupted repair
+ # would then be unrecoverable. Abort and surface the reason
+ # instead of proceeding fail-open.
+ report["error"] = (
+ "pre-repair backup refused; aborting schema repair to avoid "
+ f"mutating the only copy of the damaged DB: {backup_error}"
+ )
+ logger.error("state.db repair aborted: %s", report["error"])
+ return report
# ── Strategy 0: rebuild FTS indexes in place (FTS write-corruption) ──
# The FTS5 'rebuild' command rewrites the internal index from the canonical
diff --git a/tests/test_state_db_malformed_repair.py b/tests/test_state_db_malformed_repair.py
index 10027947105..177abd71094 100644
--- a/tests/test_state_db_malformed_repair.py
+++ b/tests/test_state_db_malformed_repair.py
@@ -557,3 +557,68 @@ def test_schema_surgery_bumps_the_schema_cookie(tmp_path):
finally:
probe.close()
assert after != before
+
+
+# ---------------------------------------------------------------------------
+# Backup refusal is a hard stop (#69603)
+# ---------------------------------------------------------------------------
+# The Aug 2026 incident on #69603: the pre-repair backup was refused because
+# another same-process handle was open, and the repair proceeded anyway —
+# every later strategy (writable_schema surgery, FTS deletion, VACUUM) was
+# then reachable against the only remaining copy of the damaged DB.
+
+
+def test_backup_refusal_hard_stops_the_repair(tmp_path, monkeypatch):
+ """A refused pre-repair backup must abort the repair, not fail open."""
+ db_path = tmp_path / "state.db"
+ _build_healthy_db(db_path)
+ _corrupt_duplicate_fts(db_path)
+ original_bytes = db_path.read_bytes()
+
+ monkeypatch.setattr(
+ hermes_state,
+ "_backup_db_file",
+ lambda p: (None, "a connection to it is still open in this process"),
+ )
+
+ report = repair_state_db_schema(db_path)
+
+ assert report["repaired"] is False
+ assert report["backup_path"] is None
+ assert "backup refused" in (report["error"] or "")
+ assert "still open" in report["error"]
+ # No mutating strategy ran: the damaged source bytes are untouched.
+ assert db_path.read_bytes() == original_bytes
+ assert hermes_state._db_opens_cleanly(db_path) is not None
+
+
+def test_backup_copy_failure_hard_stops_the_repair(tmp_path, monkeypatch):
+ """An OS-level backup copy failure aborts the repair with the reason."""
+ db_path = tmp_path / "state.db"
+ _build_healthy_db(db_path)
+ _corrupt_duplicate_fts(db_path)
+
+ monkeypatch.setattr(
+ hermes_state,
+ "_backup_db_file",
+ lambda p: (None, "backup copy failed: [Errno 28] No space left on device"),
+ )
+
+ report = repair_state_db_schema(db_path)
+
+ assert report["repaired"] is False
+ assert "No space left on device" in (report["error"] or "")
+ assert not list(tmp_path.glob("state.db.malformed-backup-*"))
+
+
+def test_backup_false_still_skips_backup_and_repairs(tmp_path):
+ """Explicit backup=False (CLI --no-backup) keeps working."""
+ db_path = tmp_path / "state.db"
+ _build_healthy_db(db_path)
+ _corrupt_duplicate_fts(db_path)
+
+ report = repair_state_db_schema(db_path, backup=False)
+
+ assert report["repaired"] is True
+ assert report["backup_path"] is None
+ assert not list(tmp_path.glob("state.db.malformed-backup-*"))