Skip to content

The agent that grows with you

fix(state): guard vacuum() and optimize_fts() against quarantined SessionDB handles

nftpoetrist9e0dc4319ae2
diff --git a/hermes_state_maintenance.py b/hermes_state_maintenance.py
index de2dd1fa273..c501102fb58 100644
--- a/hermes_state_maintenance.py
+++ b/hermes_state_maintenance.py
@@ -337,13 +337,11 @@ class SessionMaintenanceMixin:
Takes an exclusive lock — callers must ensure no other writers are active. FTS5
segments are merged first (:meth:`optimize_fts`) so their pages are reclaimed too;
returns the number of FTS indexes optimized (0 on merge failure / no FTS). A quarantined
- handle (corrupt image, replaced file, lost WAL generation) never checkpoints or rewrites
- pages: the halt raised by ``optimize_fts`` would otherwise be swallowed below and the
- VACUUM would proceed on the split-brain handle (#105670)."""
- quarantine_reason = self._quarantine_reason()
- if quarantine_reason is not None:
- logger.warning("Skipping VACUUM for %s: this handle observed %s.", self.db_path, quarantine_reason)
- return 0
+ handle (corrupt image, replaced file, lost WAL generation) raises before any rewrite: a
+ VACUUM reads every page and commits the result back, turning contained damage into an
+ amplified one (#105670). Same guard ``_execute_write`` applies to every write."""
+ self._raise_if_db_corrupt()
+ self._raise_if_db_replaced()
optimized = 0
try:
optimized = self.optimize_fts() # manages its own lock
diff --git a/hermes_state_search.py b/hermes_state_search.py
index 3e23b08744b..4f7744fb4cf 100644
--- a/hermes_state_search.py
+++ b/hermes_state_search.py
@@ -1184,7 +1184,11 @@ class SessionSearchMixin:
def optimize_fts(self) -> int:
"""Merge fragmented FTS5 segments into one per index (``'optimize'``). Pure
maintenance: changes neither results nor ``snippet()`` output, only layout and
- speed; VACUUM then returns the freed pages. Returns the number optimized."""
+ speed; VACUUM then returns the freed pages. Returns the number optimized. A quarantined
+ handle never issues ``'optimize'``: it rewrites index segments in place and would compound
+ structural damage (or a split WAL generation) instead of leaving it diagnosable."""
+ self._raise_if_db_corrupt()
+ self._raise_if_db_replaced()
optimized = 0
with self._lock:
for tbl in self._present_fts_tables():
diff --git a/tests/hermes_state/test_deleted_wal_checkpoint_guard.py b/tests/hermes_state/test_deleted_wal_checkpoint_guard.py
index be93c2b8352..2976003e8b6 100644
--- a/tests/hermes_state/test_deleted_wal_checkpoint_guard.py
+++ b/tests/hermes_state/test_deleted_wal_checkpoint_guard.py
@@ -77,7 +77,8 @@ def test_close_after_halt_runs_no_checkpoint(tmp_path, force_wal):
db._try_wal_checkpoint()
db._fts_stale = True
assert db.retry_deferred_fts_recovery() is False
- assert db.vacuum() == 0
+ with pytest.raises(DeletedWalGenerationError):
+ db.vacuum()
assert not [c for c in mock_execute.call_args_list if "vacuum" in str(c).lower()], "VACUUM ran on a quarantined handle"
db.close()
# No checkpoint call should have been made.
diff --git a/tests/hermes_state/test_state_db_corrupt_quarantine.py b/tests/hermes_state/test_state_db_corrupt_quarantine.py
index 2acac229391..05475ba3aac 100644
--- a/tests/hermes_state/test_state_db_corrupt_quarantine.py
+++ b/tests/hermes_state/test_state_db_corrupt_quarantine.py
@@ -13,7 +13,12 @@ import sqlite3
import pytest
-from hermes_state import SessionDB, StateDbCorruptError
+from hermes_state import (
+ DeletedWalGenerationError,
+ SessionDB,
+ StateDbCorruptError,
+ StateDbReplacedError,
+)
class _MalformedConn:
@@ -234,3 +239,71 @@ class TestSharedRegistry:
registry.close_all()
assert not any("wal_checkpoint" in sql for sql in recorder.recorded)
assert holder_a._conn is None
+
+
+_QUARANTINE_FLAGS = [
+ ("_db_corrupt", StateDbCorruptError),
+ ("_db_replaced", StateDbReplacedError),
+ ("_db_wal_generation_lost", DeletedWalGenerationError),
+]
+
+
+def _force_flag(db, flag_name):
+ setattr(db, flag_name, True)
+ if flag_name == "_db_corrupt":
+ db._db_corrupt_reason = "forced for test"
+
+
+def _clear_flag(db, flag_name):
+ setattr(db, flag_name, False)
+ if flag_name == "_db_corrupt":
+ db._db_corrupt_reason = ""
+
+
+class TestVacuumAndMaintenanceRespectQuarantine:
+ """vacuum()/optimize_fts() must check the same
+ quarantine flags _execute_write does before touching the connection.
+
+ Without this, `hermes sessions vacuum`/`optimize` and the default-on
+ ``maybe_auto_prune_and_vacuum`` auto-maintenance could run VACUUM /
+ FTS5 'optimize' / an explicit WAL checkpoint directly over a
+ structurally damaged, replaced, or split-WAL-generation file — turning
+ a contained, diagnosable corruption into an amplified, unrecoverable
+ one (the exact class of damage the quarantine exists to prevent).
+ """
+
+ @pytest.mark.parametrize("flag_name,expected_exc", _QUARANTINE_FLAGS)
+ def test_vacuum_refuses_when_quarantined(self, tmp_path, flag_name, expected_exc):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ real_conn = db._conn
+ try:
+ db.create_session(session_id="s1", source="cli", model="test")
+ db.append_message("s1", role="user", content="hello world")
+ recorder = _RecordingConn(real_conn)
+ db._conn = recorder
+ _force_flag(db, flag_name)
+ with pytest.raises(expected_exc):
+ db.vacuum()
+ assert recorder.recorded == []
+ finally:
+ _clear_flag(db, flag_name)
+ db._conn = real_conn
+ db.close()
+
+ @pytest.mark.parametrize("flag_name,expected_exc", _QUARANTINE_FLAGS)
+ def test_optimize_fts_refuses_when_quarantined(self, tmp_path, flag_name, expected_exc):
+ db = SessionDB(db_path=tmp_path / "state.db")
+ real_conn = db._conn
+ try:
+ db.create_session(session_id="s1", source="cli", model="test")
+ db.append_message("s1", role="user", content="hello world")
+ recorder = _RecordingConn(real_conn)
+ db._conn = recorder
+ _force_flag(db, flag_name)
+ with pytest.raises(expected_exc):
+ db.optimize_fts()
+ assert recorder.recorded == []
+ finally:
+ _clear_flag(db, flag_name)
+ db._conn = real_conn
+ db.close()