The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(state): recover FTS after orphan holder deferrals
fangliquanflq8f3a82f96a65
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.pyindex 524ab04f119..34336079622 100644--- a/hermes_cli/doctor.py+++ b/hermes_cli/doctor.py@@ -461,6 +461,18 @@ def _render_state_db_stats(stats: dict, holders=None) -> list:"",))+ deferral = stats.get("fts_rebuild_deferral")+ if isinstance(deferral, dict):+ attempts = deferral.get("attempts")+ pids = deferral.get("holder_pids") or []+ lines.append((+ "warn",+ f"state.db FTS repair is blocked after {attempts or '?'} "+ f"deferral(s) by PID(s) {pids or 'unknown'}",+ "(stop the listed processes, then run 'hermes sessions "+ "optimize-storage' with the gateway stopped)",+ ))+# Advisory: oversized database. Suggest auto_prune, and — when the v23# FTS rebuild is pending OR the DB still carries the legacy inline# trigram layout (fts_storage_version marker absent) — the offlinediff --git a/hermes_state.py b/hermes_state.pyindex 46fb1e4f61f..f4d6351aa92 100644--- a/hermes_state.py+++ b/hermes_state.py@@ -77,6 +77,7 @@ from hermes_state_common import ( # noqa: F401 (re-exported for back-compat)escape_like as _escape_like,DEFERRED_INDEX_SQL,FTS_CJK_STALE_KEY,+ FTS_REBUILD_DEFERRAL_KEY,FTS_SQL,FTS_STALE_KEY,FTS_STORAGE_VERSION,@@ -3767,6 +3768,7 @@ def collect_state_db_stats(db_path: Path) -> Dict[str, Any]:- ``fts_rebuild_pending`` — True when the deferred v23 backfill has notfinished (high_water present and progress < high_water)- ``fts_rebuild_high_water`` / ``fts_rebuild_progress`` — raw ints+ - ``fts_rebuild_deferral`` — durable blocked-repair diagnostic, when present"""stats: Dict[str, Any] = {"page_count": None,@@ -3782,6 +3784,7 @@ def collect_state_db_stats(db_path: Path) -> Dict[str, Any]:"fts_rebuild_pending": None,"fts_rebuild_high_water": None,"fts_rebuild_progress": None,+ "fts_rebuild_deferral": None,}# WAL sidecar size needs no connection at all.@@ -3872,6 +3875,17 @@ def collect_state_db_stats(db_path: Path) -> Dict[str, Any]:stats["fts_rebuild_pending"] = Falseelse:stats["fts_rebuild_pending"] = (progress or 0) < high_water+ try:+ row = conn.execute(+ "SELECT value FROM state_meta WHERE key = ? LIMIT 1",+ (FTS_REBUILD_DEFERRAL_KEY,),+ ).fetchone()+ if row:+ parsed = json.loads(row[0])+ if isinstance(parsed, dict):+ stats["fts_rebuild_deferral"] = parsed+ except Exception:+ passfinally:try:conn.close()@@ -3915,6 +3929,23 @@ def count_db_holders(db_path: Path) -> Optional[int]:return None+def _is_inactive_orphan_desktop_holder(+ *,+ ppid: int,+ age_seconds: float,+ min_age_seconds: float,+ ephemeral_backend: bool,+ connection_statuses: List[str],+) -> bool:+ """Pure safety predicate for the narrow Desktop holder reap."""+ return (+ ppid in (0, 1)+ and age_seconds >= min_age_seconds+ and ephemeral_backend+ and "ESTABLISHED" not in connection_statuses+ )++def _read_proc_cmdline(pid: int) -> Optional[str]:"""Read /proc/<pid>/cmdline, world-readable even when fd table is not.@@ -5136,6 +5167,69 @@ class SessionDB(SessionSearchMixin, SessionSchemaMixin, SessionPortabilityMixin)return holders or [(-1, f"open-file scan failed: {exc}")]return holders+ def _reap_inactive_orphan_desktop_holders(+ self, holders: List[Tuple[int, str]], *, min_age_seconds: float+ ) -> List[int]:+ """Terminate old PPID-1 Desktop ephemeral backends with no client.++ Inspection fails closed: anything whose parent, age, argv, or network+ connections cannot be proved safe remains a repair-blocking holder.+ """+ if not sys.platform.startswith("linux") or psutil is None:+ return []+ try:+ from hermes_cli.dashboard_procs import _is_ephemeral_port_zero_backend+ except Exception:+ return []++ now = time.time()+ candidates = []+ for pid, _path in holders:+ if pid <= 0:+ continue+ try:+ process = psutil.Process(pid)+ statuses = [+ conn.status for conn in process.net_connections(kind="inet")+ ]+ if not _is_inactive_orphan_desktop_holder(+ ppid=process.ppid(),+ age_seconds=now - process.create_time(),+ min_age_seconds=min_age_seconds,+ ephemeral_backend=_is_ephemeral_port_zero_backend(process.cmdline()),+ connection_statuses=statuses,+ ):+ continue+ except Exception:+ continue+ candidates.append(process)++ signalled: List[int] = []+ for process in candidates:+ try:+ process.terminate()+ signalled.append(process.pid)+ except (psutil.Error, OSError):+ continue+ if not signalled:+ return []++ try:+ _gone, alive = psutil.wait_procs(candidates, timeout=1.5)+ except Exception:+ alive = []+ for process in alive:+ try:+ process.kill()+ except (psutil.Error, OSError):+ continue+ if alive:+ try:+ psutil.wait_procs(alive, timeout=1.5)+ except Exception:+ pass+ return signalled+def _try_runtime_fts_rebuild(self, exc: sqlite3.DatabaseError) -> bool:"""One-shot in-place FTS rebuild after a corrupt-index write failure.diff --git a/hermes_state_common.py b/hermes_state_common.pyindex 1b0daa290e6..ff1da505f09 100644--- a/hermes_state_common.py+++ b/hermes_state_common.py@@ -733,6 +733,9 @@ FTS_CJK_STALE_KEY = "fts_cjk_stale"# them would preserve an unknown index gap.FTS_STALE_KEY = "fts_stale"+# Durable diagnostic for stale FTS recovery blocked across process restarts.+FTS_REBUILD_DEFERRAL_KEY = "fts_rebuild_deferral"+# ── Legacy (v22 / inline-content) FTS DDL ──────────────────────────────# Used ONLY to keep an existing pre-v23 install's search working and itsdiff --git a/hermes_state_schema.py b/hermes_state_schema.pyindex d234364f77c..ce87cfe6737 100644--- a/hermes_state_schema.py+++ b/hermes_state_schema.py@@ -11,12 +11,14 @@ module-level constants live in hermes_state_common.import loggingimport jsonimport sqlite3+import timefrom typing import Dict, Optional, Sequencefrom hermes_constants import get_hermes_homefrom hermes_state_common import (DEFERRED_INDEX_SQL,FTS_CJK_STALE_KEY,+ FTS_REBUILD_DEFERRAL_KEY,FTS_STALE_KEY,FTS_SQL,FTS_STORAGE_VERSION,@@ -35,6 +37,9 @@ from hermes_state_common import (# keep that logger identity so log filtering/capture behavior is unchanged.logger = logging.getLogger("hermes_state")+_FTS_HOLDER_ESCALATE_ATTEMPTS = 3+_FTS_HOLDER_ESCALATE_SECONDS = 60.0+# Cache for schema_read_probe_statements() — parsing SCHEMA_SQL spins up an# in-memory SQLite database, so derive the statements once per process._READ_PROBE_STATEMENTS: Optional[tuple] = None@@ -397,13 +402,78 @@ class SessionSchemaMixin:"""Atomically rebuild stale base/trigram indexes and resume syncing."""foreign_holders = self._foreign_state_db_holders()if foreign_holders:- 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.",- foreign_holders,+ now = time.time()+ record = None+ try:+ row = cursor.execute(+ "SELECT value FROM state_meta WHERE key = ? LIMIT 1",+ (FTS_REBUILD_DEFERRAL_KEY,),+ ).fetchone()+ if row:+ raw = row["value"] if isinstance(row, sqlite3.Row) else row[0]+ parsed = json.loads(raw)+ if isinstance(parsed, dict):+ record = parsed+ except (sqlite3.Error, TypeError, ValueError, json.JSONDecodeError):+ record = None++ try:+ first_seen = float((record or {}).get("first_seen", now))+ attempts = int((record or {}).get("attempts", 0)) + 1+ except (TypeError, ValueError):+ first_seen = now+ attempts = 1+ if first_seen > now or first_seen < 0:+ first_seen = now+ holder_pids = sorted({pid for pid, _path in foreign_holders if pid > 0})+ diagnostic = {+ "first_seen": first_seen,+ "last_seen": now,+ "attempts": attempts,+ "holder_pids": holder_pids,+ }+ 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)),)- return False++ escalated = (+ attempts >= _FTS_HOLDER_ESCALATE_ATTEMPTS+ and now - first_seen >= _FTS_HOLDER_ESCALATE_SECONDS+ )+ if escalated:+ reaped = self._reap_inactive_orphan_desktop_holders(+ foreign_holders,+ min_age_seconds=_FTS_HOLDER_ESCALATE_SECONDS,+ )+ if reaped:+ logger.error(+ "Reaped inactive orphan Desktop backend(s) %s after %d "+ "state.db FTS rebuild deferrals; checking holders again.",+ reaped,+ attempts,+ )+ foreign_holders = self._foreign_state_db_holders()+ 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 foreign_holders:+ 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 False# Full structural rebuild: admit through the single cross-process# authority (fail closed). Losing the race means another process is# already performing this exact recovery; the stale breadcrumb stays@@ -483,7 +553,8 @@ class SessionSchemaMixin:"BEGIN IMMEDIATE;"+ drop_sql+ rebuild_sql- + f"DELETE FROM state_meta WHERE key = '{FTS_STALE_KEY}';"+ + "DELETE FROM state_meta WHERE key IN "+ + f"('{FTS_STALE_KEY}', '{FTS_REBUILD_DEFERRAL_KEY}');"+ "COMMIT;")try:diff --git a/tests/state/test_fts_runtime_rebuild.py b/tests/state/test_fts_runtime_rebuild.pyindex b511acf7b7d..a969d2bea8b 100644--- a/tests/state/test_fts_runtime_rebuild.py+++ b/tests/state/test_fts_runtime_rebuild.py@@ -13,6 +13,7 @@ sync triggers, and retries the canonical write. Search degrades to ``LIKE``until a later open atomically rebuilds the index and restores the triggers."""+import jsonimport osimport sqlite3from types import SimpleNamespace@@ -20,13 +21,16 @@ from types import SimpleNamespaceimport pytestimport hermes_state+import hermes_state_schemafrom hermes_state import (+ FTS_REBUILD_DEFERRAL_KEY,FTS_STALE_KEY,LEGACY_FTS_SQL,LEGACY_FTS_TRIGRAM_SQL,SCHEMA_SQL,SessionDB,_FTS_TRIGGERS,+ _is_inactive_orphan_desktop_holder,)@@ -87,6 +91,29 @@ def _base_fts_triggers(db_path):class TestRuntimeFtsRebuild:+ def test_inactive_orphan_reap_predicate_preserves_live_or_ambiguous_holders(self):+ common = {+ "ppid": 1,+ "age_seconds": 120.0,+ "min_age_seconds": 60.0,+ "ephemeral_backend": True,+ "connection_statuses": [],+ }+ assert _is_inactive_orphan_desktop_holder(**common)+ assert not _is_inactive_orphan_desktop_holder(**{**common, "ppid": 42})+ assert not _is_inactive_orphan_desktop_holder(+ **{**common, "age_seconds": 10.0}+ )+ assert not _is_inactive_orphan_desktop_holder(+ **{**common, "ephemeral_backend": False}+ )+ assert not _is_inactive_orphan_desktop_holder(+ **{+ **common,+ "connection_statuses": ["ESTABLISHED"],+ }+ )+def test_foreign_holder_detection_includes_deleted_wal(self, db, tmp_path, monkeypatch):@@ -519,6 +546,59 @@ class TestRuntimeFtsRebuild:finally:reopened.close()+ def test_repeated_deferrals_reap_inactive_orphan_then_rebuild(+ 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}),+ ),+ )+ 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")]+ assert reopened._fts_stale is False+ assert _meta_value(db_path, FTS_STALE_KEY) is None+ assert _meta_value(db_path, FTS_REBUILD_DEFERRAL_KEY) is None+ assert reopened.search_messages("before restart")+ 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.pyindex e89f1452c0d..f64ce4821ef 100644--- a/tests/test_state_db_stats.py+++ b/tests/test_state_db_stats.py@@ -10,6 +10,7 @@ Covers:the doctor state.db section prints from."""+import jsonimport osimport sqlite3import sys@@ -78,6 +79,33 @@ def test_collect_stats_is_read_only(populated_db):db.close()+def test_collect_and_render_stale_fts_holder_deferral(populated_db):+ conn = sqlite3.connect(str(populated_db))+ conn.execute(+ "INSERT INTO state_meta (key, value) VALUES (?, ?)",+ (+ "fts_rebuild_deferral",+ json.dumps({"attempts": 4, "holder_pids": [4242], "first_seen": 1.0}),+ ),+ )+ conn.commit()+ conn.close()++ stats = collect_state_db_stats(populated_db)+ assert stats["fts_rebuild_deferral"]["attempts"] == 4+ assert stats["fts_rebuild_deferral"]["holder_pids"] == [4242]++ from hermes_cli.doctor import _render_state_db_stats++ rendered = _render_state_db_stats(stats)+ warnings = [+ " ".join((text, detail))+ for kind, text, detail in rendered+ if kind == "warn"+ ]+ assert any("4242" in warning and "optimize-storage" in warning for warning in warnings)++def test_collect_stats_missing_file_never_raises(tmp_path):stats = collect_state_db_stats(tmp_path / "nope" / "state.db")assert isinstance(stats, dict)