Skip to content

The agent that grows with you

fix(state): diagnose futile FTS deferral from a permanent holder

KoNit-Ke7ca9b47acf2
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index 940a5453277..aba3d59b5a3 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -80,9 +80,21 @@ def _render_state_db_stats(stats: dict, holders=None) -> list:
lines.append(("info", "FTS tables: " + (", ".join(present) if present else "none"), ""))
deferral = stats.get("fts_rebuild_deferral")
if isinstance(deferral, dict):
- lines.append(("warn", f"state.db FTS repair is blocked after {deferral.get('attempts') or '?'} deferral(s) "
- f"by PID(s) {deferral.get('holder_pids') or [] or 'unknown'}",
- "(stop the listed processes, then run 'hermes sessions optimize-storage' with the gateway stopped)"))
+ pids = deferral.get("holder_pids") or []
+ attempts = deferral.get("attempts") or "?"
+ futile = deferral.get("futile") is True or deferral.get("kind") == "permanent_holder"
+ if futile:
+ lines.append((
+ "warn",
+ f"state.db FTS repair is blocked by a permanent holder "
+ f"(another Hermes service, PID(s) {pids}) after {attempts} futile deferral(s)",
+ "(stop the other Hermes service; leave this gateway running — "
+ "retry_deferred_fts_recovery admits once this process is the sole holder)",
+ ))
+ else:
+ lines.append(("warn", f"state.db FTS repair is blocked after {attempts} deferral(s) "
+ f"by PID(s) {pids or 'unknown'}",
+ "(stop the listed processes, then run 'hermes sessions optimize-storage' with the gateway stopped)"))
# Oversized DB: suggest auto_prune, plus the offline optimize-storage pass when the FTS rebuild is
# pending OR the DB predates the current trigram layout (fts_storage_version < FTS_STORAGE_VERSION).
if logical is not None and logical > STATE_DB_SIZE_WARN_BYTES:
diff --git a/hermes_state_schema.py b/hermes_state_schema.py
index e9052ccae62..87414606e5b 100644
--- a/hermes_state_schema.py
+++ b/hermes_state_schema.py
@@ -37,6 +37,21 @@ _FTS_HOLDER_ESCALATE_SECONDS = 60.0
_FTS_STALE_RETRY_SECONDS = 60.0
_FTS_STALE_RETRY_MAX_SECONDS = 3600.0
+
+def _fts_holder_pid_set(value):
+ """Sorted unique positive PIDs, or None when the stored set is missing/unusable."""
+ if not isinstance(value, (list, tuple)):
+ return None
+ pids = set()
+ for item in value:
+ try:
+ pid = int(item)
+ except (TypeError, ValueError):
+ return None
+ if pid > 0:
+ pids.add(pid)
+ return sorted(pids)
+
# schema_read_probe_statements() cache (parses SCHEMA_SQL in an in-memory DB; once per process).
_READ_PROBE_STATEMENTS: Optional[tuple] = None
@@ -422,7 +437,8 @@ class SessionSchemaMixin:
"""Record a deferral diagnostic for the foreign processes holding the DB; True = defer
(holders remain). After ``_FTS_HOLDER_ESCALATE_ATTEMPTS`` deferrals spanning
``_FTS_HOLDER_ESCALATE_SECONDS``, provably inactive orphan Desktop backends are
- reaped and the holders re-checked."""
+ reaped and the holders re-checked. A stable PID set that survives that reap is
+ recorded as a futile/permanent-holder diagnostic; the orphan predicate is unchanged."""
now = time.time()
try:
row = cursor.execute(
@@ -439,14 +455,9 @@ class SessionSchemaMixin:
first_seen, attempts = now, 1
if first_seen > now or first_seen < 0:
first_seen = now
- diagnostic = {
- "first_seen": first_seen, "last_seen": now, "attempts": attempts,
- "holder_pids": sorted({pid for pid, _path in foreign_holders if pid > 0}),
- }
- cursor.execute(
- "INSERT INTO state_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
- (FTS_REBUILD_DEFERRAL_KEY, json.dumps(diagnostic, sort_keys=True)),
- )
+ previous_pids = _fts_holder_pid_set(record.get("holder_pids"))
+ holder_pids = sorted({pid for pid, _path in foreign_holders if pid > 0})
+ futile = False
if attempts >= _FTS_HOLDER_ESCALATE_ATTEMPTS and now - first_seen >= _FTS_HOLDER_ESCALATE_SECONDS:
reaped = self._reap_inactive_orphan_desktop_holders(
foreign_holders, min_age_seconds=_FTS_HOLDER_ESCALATE_SECONDS,
@@ -457,20 +468,59 @@ class SessionSchemaMixin:
"state.db FTS rebuild deferrals; checking holders again.", reaped, attempts,
)
foreign_holders = self._foreign_state_db_holders()
+ holder_pids = sorted({pid for pid, _path in foreign_holders if pid > 0})
if foreign_holders:
- logger.error(
- "state.db FTS repair remains blocked after %d deferrals "
- "by holder(s) %s. Stop the listed processes, then run "
- "`hermes sessions optimize-storage` with the gateway stopped. "
- "`hermes doctor` reports this degraded state.", attempts, foreign_holders,
- )
+ if previous_pids is not None and holder_pids and holder_pids == previous_pids:
+ futile = True
+ logger.error(
+ "state.db FTS repair is futile after %d deferrals: the same "
+ "holder PID set %s is a permanent holder (another Hermes "
+ "service), not a transient peer. Stop the other Hermes "
+ "service; leave this gateway running. "
+ "retry_deferred_fts_recovery admits once this process is "
+ "the sole holder. `hermes doctor` reports this degraded state.",
+ attempts, holder_pids,
+ )
+ else:
+ logger.error(
+ "state.db FTS repair remains blocked after %d deferrals "
+ "by holder(s) %s. Stop the listed processes, then run "
+ "`hermes sessions optimize-storage` with the gateway stopped. "
+ "`hermes doctor` reports this degraded state.", attempts, foreign_holders,
+ )
+ else:
+ self._fts_stale_retry_after = 0.0
+ self._fts_stale_retry_interval = 0.0
+ self._fts_permanent_holder_deferral = False
+ diagnostic = {
+ "first_seen": first_seen, "last_seen": now, "attempts": attempts,
+ "holder_pids": holder_pids,
+ }
+ if futile:
+ diagnostic["futile"] = True
+ diagnostic["kind"] = "permanent_holder"
+ self._fts_permanent_holder_deferral = True
+ else:
+ self._fts_permanent_holder_deferral = False
+ cursor.execute(
+ "INSERT INTO state_meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ (FTS_REBUILD_DEFERRAL_KEY, json.dumps(diagnostic, sort_keys=True)),
+ )
if not foreign_holders:
return False
- logger.warning(
- "Deferred stale state.db FTS rebuild while foreign processes "
- "hold the database or WAL sidecars (%s); canonical writes and LIKE search remain available (deferral %d).",
- foreign_holders, attempts,
- )
+ if futile:
+ logger.warning(
+ "Deferred stale state.db FTS rebuild while a permanent foreign holder "
+ "blocks repair (%s); stop the other Hermes service and leave this "
+ "gateway running (deferral %d).",
+ foreign_holders, attempts,
+ )
+ else:
+ logger.warning(
+ "Deferred stale state.db FTS rebuild while foreign processes "
+ "hold the database or WAL sidecars (%s); canonical writes and LIKE search remain available (deferral %d).",
+ foreign_holders, attempts,
+ )
return True
def _recover_stale_fts(self, cursor: sqlite3.Cursor, *, legacy: bool, timeout_seconds=None) -> bool:
@@ -513,6 +563,11 @@ class SessionSchemaMixin:
if self.read_only or self._conn is None:
return False
now = time.monotonic()
+ if getattr(self, "_fts_permanent_holder_deferral", False) and not self._foreign_state_db_holders():
+ # Permanent holder gone: do not wait out a doubled-to-cap backoff (#106393).
+ self._fts_stale_retry_after = 0.0
+ self._fts_stale_retry_interval = 0.0
+ self._fts_permanent_holder_deferral = False
if now < getattr(self, "_fts_stale_retry_after", 0.0):
return False
interval = float(getattr(self, "_fts_stale_retry_interval", 0.0))
diff --git a/tests/state/test_fts_runtime_rebuild.py b/tests/state/test_fts_runtime_rebuild.py
index c4e4e5a8e10..38108f59a76 100644
--- a/tests/state/test_fts_runtime_rebuild.py
+++ b/tests/state/test_fts_runtime_rebuild.py
@@ -16,6 +16,7 @@ rebuild later, outside the failed live write/search operation.
import json
import os
import sqlite3
+import time
import pytest
@@ -27,6 +28,24 @@ from hermes_state_common import FTS_REBUILD_DEFERRAL_KEY, FTS_STALE_KEY, LEGACY_
from hermes_state_dbfile import _concrete_state_db_holder_pids, _is_inactive_orphan_desktop_holder
+def _deferral_is_futile(record):
+ if not isinstance(record, dict):
+ return False
+ if record.get("futile") is True:
+ return True
+ kind = str(record.get("kind") or record.get("status") or "").lower()
+ return "futile" in kind or "permanent_holder" in kind
+
+
+def _doctor_deferral_blob(stats):
+ from hermes_cli.doctor_state import _render_state_db_stats
+
+ return " ".join(
+ " ".join(str(part) for part in row)
+ for row in _render_state_db_stats(stats)
+ ).lower()
+
+
@pytest.fixture
def db(tmp_path):
d = SessionDB(db_path=tmp_path / "state.db")
@@ -785,6 +804,243 @@ class TestRuntimeFtsRebuild:
finally:
reopened.close()
+ def test_stable_permanent_holder_marks_futile_deferral(
+ self, db, tmp_path, monkeypatch, caplog
+ ):
+ """Same supervised holder across the escalate window is futile, not a transient peer."""
+ if not db._fts_enabled:
+ pytest.skip("FTS5 unavailable in this build")
+ db_path = tmp_path / "state.db"
+ db.create_session("s1", source="test")
+ db.append_message("s1", "user", "seed")
+ _corrupt_fts(db_path)
+ monkeypatch.setattr(
+ db,
+ "rebuild_fts",
+ lambda: (_ for _ in ()).throw(sqlite3.DatabaseError("still corrupt")),
+ )
+ db.append_message("s1", "user", "before restart")
+ db.close()
+
+ raw = sqlite3.connect(str(db_path))
+ raw.execute(
+ "INSERT INTO state_meta (key, value) VALUES (?, ?) "
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ (
+ FTS_REBUILD_DEFERRAL_KEY,
+ json.dumps({
+ "first_seen": 1.0,
+ "last_seen": 30.0,
+ "attempts": 2,
+ "holder_pids": [4242],
+ }),
+ ),
+ )
+ raw.commit()
+ raw.close()
+
+ monkeypatch.setattr(
+ SessionDB,
+ "_foreign_state_db_holders",
+ lambda self: [(4242, str(db_path) + "-wal")],
+ )
+ monkeypatch.setattr(
+ SessionDB,
+ "_reap_inactive_orphan_desktop_holders",
+ lambda self, holders, *, min_age_seconds: [],
+ )
+ monkeypatch.setattr(hermes_state_schema.time, "time", lambda: 120.0)
+
+ reopened = SessionDB(db_path=db_path)
+ try:
+ record = json.loads(_meta_value(db_path, FTS_REBUILD_DEFERRAL_KEY))
+ assert _deferral_is_futile(record), record
+ assert record.get("holder_pids") == [4242]
+ assert reopened._fts_stale is True
+ from hermes_cli.doctor_state import _render_state_db_stats
+ from hermes_state_dbfile import collect_state_db_stats
+
+ blob = _doctor_deferral_blob(collect_state_db_stats(db_path))
+ assert "stop the other hermes service" in blob
+ assert "gateway" in blob
+ assert "canonical writes and like search remain available" not in caplog.text.lower()
+ finally:
+ reopened.close()
+
+ def test_changing_holder_pids_do_not_mark_futile(
+ self, db, tmp_path, monkeypatch
+ ):
+ if not db._fts_enabled:
+ pytest.skip("FTS5 unavailable in this build")
+ db_path = tmp_path / "state.db"
+ db.create_session("s1", source="test")
+ db.append_message("s1", "user", "seed")
+ _corrupt_fts(db_path)
+ monkeypatch.setattr(
+ db,
+ "rebuild_fts",
+ lambda: (_ for _ in ()).throw(sqlite3.DatabaseError("still corrupt")),
+ )
+ db.append_message("s1", "user", "before restart")
+ db.close()
+
+ raw = sqlite3.connect(str(db_path))
+ raw.execute(
+ "INSERT INTO state_meta (key, value) VALUES (?, ?) "
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ (
+ FTS_REBUILD_DEFERRAL_KEY,
+ json.dumps({
+ "first_seen": 1.0,
+ "last_seen": 30.0,
+ "attempts": 2,
+ "holder_pids": [4242],
+ }),
+ ),
+ )
+ raw.commit()
+ raw.close()
+
+ monkeypatch.setattr(
+ SessionDB,
+ "_foreign_state_db_holders",
+ lambda self: [(9999, str(db_path) + "-wal")],
+ )
+ monkeypatch.setattr(
+ SessionDB,
+ "_reap_inactive_orphan_desktop_holders",
+ lambda self, holders, *, min_age_seconds: [],
+ )
+ monkeypatch.setattr(hermes_state_schema.time, "time", lambda: 120.0)
+
+ reopened = SessionDB(db_path=db_path)
+ try:
+ record = json.loads(_meta_value(db_path, FTS_REBUILD_DEFERRAL_KEY))
+ assert not _deferral_is_futile(record), record
+ assert record.get("holder_pids") == [9999]
+ assert reopened._fts_stale is True
+ finally:
+ reopened.close()
+
+ def test_orphan_reap_clearing_holders_does_not_mark_futile(
+ self, db, tmp_path, monkeypatch
+ ):
+ """CONTROL: escalate + successful orphan reap stays on the existing rebuild path."""
+ if not db._fts_enabled:
+ pytest.skip("FTS5 unavailable in this build")
+ db_path = tmp_path / "state.db"
+ db.create_session("s1", source="test")
+ db.append_message("s1", "user", "seed")
+ _corrupt_fts(db_path)
+ monkeypatch.setattr(
+ db,
+ "rebuild_fts",
+ lambda: (_ for _ in ()).throw(sqlite3.DatabaseError("still corrupt")),
+ )
+ db.append_message("s1", "user", "before restart")
+ db.close()
+
+ raw = sqlite3.connect(str(db_path))
+ raw.execute(
+ "INSERT INTO state_meta (key, value) VALUES (?, ?) "
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ (
+ FTS_REBUILD_DEFERRAL_KEY,
+ json.dumps({
+ "first_seen": 1.0,
+ "last_seen": 30.0,
+ "attempts": 2,
+ "holder_pids": [4242],
+ }),
+ ),
+ )
+ raw.commit()
+ raw.close()
+
+ holder_scans = iter(([(4242, str(db_path) + "-wal")], []))
+ reaped = []
+ monkeypatch.setattr(
+ SessionDB,
+ "_foreign_state_db_holders",
+ lambda self: next(holder_scans),
+ )
+ monkeypatch.setattr(
+ SessionDB,
+ "_reap_inactive_orphan_desktop_holders",
+ lambda self, holders, *, min_age_seconds: reaped.extend(holders) or [4242],
+ )
+ monkeypatch.setattr(hermes_state_schema.time, "time", lambda: 120.0)
+
+ reopened = SessionDB(db_path=db_path)
+ try:
+ assert reaped == [(4242, str(db_path) + "-wal")]
+ leftover = _meta_value(db_path, FTS_REBUILD_DEFERRAL_KEY)
+ if leftover is not None:
+ assert not _deferral_is_futile(json.loads(leftover)), leftover
+ assert reopened._fts_stale is False
+ assert _meta_value(db_path, FTS_STALE_KEY) is None
+ finally:
+ reopened.close()
+
+ def test_permanent_holder_clear_resets_stale_retry_backoff(
+ self, db, tmp_path, monkeypatch
+ ):
+ if not db._fts_enabled:
+ pytest.skip("FTS5 unavailable in this build")
+ db_path = tmp_path / "state.db"
+ db.create_session("s1", source="test")
+ db.append_message("s1", "user", "seed")
+ _corrupt_fts(db_path)
+ monkeypatch.setattr(
+ db,
+ "rebuild_fts",
+ lambda: (_ for _ in ()).throw(sqlite3.DatabaseError("still corrupt")),
+ )
+ db.append_message("s1", "user", "before restart")
+ db.close()
+
+ raw = sqlite3.connect(str(db_path))
+ raw.execute(
+ "INSERT INTO state_meta (key, value) VALUES (?, ?) "
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
+ (
+ FTS_REBUILD_DEFERRAL_KEY,
+ json.dumps({
+ "first_seen": 1.0,
+ "last_seen": 30.0,
+ "attempts": 2,
+ "holder_pids": [4242],
+ }),
+ ),
+ )
+ raw.commit()
+ raw.close()
+
+ current_holders = [(4242, str(db_path) + "-wal")]
+ monkeypatch.setattr(
+ SessionDB,
+ "_foreign_state_db_holders",
+ lambda self: list(current_holders),
+ )
+ monkeypatch.setattr(
+ SessionDB,
+ "_reap_inactive_orphan_desktop_holders",
+ lambda self, holders, *, min_age_seconds: [],
+ )
+ monkeypatch.setattr(hermes_state_schema.time, "time", lambda: 120.0)
+
+ reopened = SessionDB(db_path=db_path)
+ try:
+ record = json.loads(_meta_value(db_path, FTS_REBUILD_DEFERRAL_KEY))
+ assert _deferral_is_futile(record), record
+ current_holders = []
+ reopened._fts_stale_retry_after = time.monotonic() + 3600.0
+ reopened._fts_stale_retry_interval = 3600.0
+ assert reopened.retry_deferred_fts_recovery() is True
+ assert reopened._fts_stale is False
+ finally:
+ reopened.close()
+
def test_legacy_inline_fts_fails_open_and_recovers(self, tmp_path, monkeypatch):
db_path = tmp_path / "legacy-state.db"
raw = sqlite3.connect(str(db_path))
diff --git a/tests/test_state_db_stats.py b/tests/test_state_db_stats.py
index 75f7b61ae41..27f05f310ff 100644
--- a/tests/test_state_db_stats.py
+++ b/tests/test_state_db_stats.py
@@ -109,6 +109,32 @@ def test_collect_and_render_stale_fts_holder_deferral(populated_db):
assert any("4242" in warning and "optimize-storage" in warning for warning in warnings)
+def test_render_permanent_holder_deferral_is_actionable():
+ from hermes_cli.doctor_state import _render_state_db_stats
+
+ lines = _render_state_db_stats(
+ _base_stats(
+ fts_rebuild_deferral={
+ "attempts": 12,
+ "holder_pids": [4242],
+ "first_seen": 1.0,
+ "futile": True,
+ "kind": "permanent_holder",
+ }
+ )
+ )
+ warnings = [
+ " ".join((text, detail)).lower()
+ for kind, text, detail in lines
+ if kind == "warn"
+ ]
+ blob = " ".join(warnings)
+ assert "4242" in blob
+ assert "stop the other hermes service" in blob
+ assert "gateway" in blob
+ assert "optimize-storage" not in blob or "leave this gateway" in blob
+
+
def test_collect_stats_missing_file_never_raises(tmp_path):
stats = collect_state_db_stats(tmp_path / "nope" / "state.db")
assert isinstance(stats, dict)