The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): scan state.db in the background only in WAL mode
unsupportedpastelsf500e6f2f957
diff --git a/gateway/lifecycle_ledger.py b/gateway/lifecycle_ledger.pyindex 254dc6ef4b4..6f4c4a45174 100644--- a/gateway/lifecycle_ledger.py+++ b/gateway/lifecycle_ledger.py@@ -265,6 +265,19 @@ def check_state_db_integrity(home: Optional[Path] = None, *, deadline_s: Optionareturn "check-failed: no result" if not row or row[0] is None else str(row[0])+def _state_db_journal_mode(path: Path) -> Optional[str]:+ """On-disk journal mode of ``path`` via one ``PRAGMA journal_mode`` read on a short-lived+ connection (no lock outlives it); ``None`` when undeterminable. Never raises."""+ try:+ from hermes_state_wal import _on_disk_journal_mode++ with closing(sqlite3.connect(str(path), timeout=1.0)) as conn:+ return _on_disk_journal_mode(conn) or None+ except Exception:+ logger.debug("Could not read state.db journal mode", exc_info=True)+ return None++def _report_unclean_exit(evidence: dict[str, Any], home: Optional[Path], *, defer_integrity_check: bool = False) -> None:"""Persist the exit-diag record and log at WARNING.@@ -347,10 +360,27 @@ def run_deferred_integrity_check(<verdict>, "prior_pid": ...}`` and logs the existing ERROR text on a bad verdict. NEVERraises -- a forensic scan must not disturb a running gateway (the alerting path is thebounded per-poll readiness probe ``gateway/readiness.py::_probe_state_db``).++ Only a WAL store is scanned: in rollback-journal mode (``database.journal_mode: delete``,+ or a silent WAL fallback) the scan's SHARED lock would block every live commit for its+ whole run, so the scan is skipped with a ``skipped: ...`` verdict and one WARNING. The+ on-disk mode decides, not config; an undeterminable mode is skipped too."""try:- verdict = check_state_db_integrity(home=home, deadline_s=deadline_s)- if verdict not in ("ok", "absent"):+ path = _home_path(home, "state.db")+ mode = _state_db_journal_mode(path) if path.exists() else "wal"+ if mode != "wal":+ verdict = (f"skipped: rollback-journal store (journal_mode={mode or 'unknown'}), "+ "scan would block live writes")+ logger.warning(+ "Previous gateway exit was unclean, but the state.db integrity check was skipped: %s is a "+ "rollback-journal store (journal_mode=%s) and a background scan would block live writes. "+ "To check it, stop the gateway and run: sqlite3 %s 'PRAGMA quick_check'",+ path, mode or "unknown", path,+ )+ else:+ verdict = check_state_db_integrity(home=home, deadline_s=deadline_s)+ if verdict not in ("ok", "absent") and not verdict.startswith("skipped:"):logger.error("state.db FAILED integrity check after an unclean gateway exit: %s — sessions may read as ""missing until it is repaired. Run `hermes doctor`.",diff --git a/tests/gateway/test_lifecycle_state_db_check.py b/tests/gateway/test_lifecycle_state_db_check.pyindex 45b85c0fe17..1efd5445965 100644--- a/tests/gateway/test_lifecycle_state_db_check.py+++ b/tests/gateway/test_lifecycle_state_db_check.py@@ -20,6 +20,7 @@ keep the historic INLINE behaviour covered via ``defer_integrity_check=False``.from __future__ import annotationsimport json+import loggingimport sqlite3import threadingimport time@@ -49,10 +50,12 @@ def _write_sentinel(home: Path, phase: str = "running") -> None:)-def _make_state_db(home: Path, *, corrupt: bool) -> Path:+def _make_state_db(home: Path, *, corrupt: bool, journal_mode: str = "delete") -> Path:"""Build a real SQLite file, optionally with a genuinely torn b-tree page."""path = home / "state.db"conn = sqlite3.connect(path)+ if journal_mode != "delete":+ assert conn.execute(f"PRAGMA journal_mode={journal_mode}").fetchone()[0] == journal_modeconn.execute("CREATE TABLE sessions (id INTEGER PRIMARY KEY, v TEXT)")conn.executemany("INSERT INTO sessions (v) VALUES (?)", [(f"row-{i}" * 40,) for i in range(4000)]@@ -181,7 +184,7 @@ def test_deferred_startup_never_runs_the_check_inline(tmp_path: Path, monkeypatcdef test_deferred_scan_appends_a_second_record_and_returns_the_verdict(tmp_path: Path) -> None:- _make_state_db(tmp_path, corrupt=True)+ _make_state_db(tmp_path, corrupt=True, journal_mode="wal")_write_sentinel(tmp_path)evidence = record_startup(home=tmp_path, defer_integrity_check=True)@@ -214,6 +217,94 @@ def test_deferred_scan_never_raises(tmp_path: Path, monkeypatch) -> None:assert run_deferred_integrity_check(evidence, home=tmp_path).startswith("check-failed")+# ── rollback-journal stores: a background scan would block live writers ──────+# In journal_mode=delete a quick_check holds a SHARED lock for its whole run, so every+# live gateway commit waits on it; WAL readers never block writers.+++def _spy_on_scan(monkeypatch) -> list:+ """Record every scan while still running the real one."""+ import gateway.lifecycle_ledger as ledger++ calls: list = []+ real = ledger.check_state_db_integrity++ def _spy(**kwargs):+ calls.append(kwargs)+ return real(**kwargs)++ monkeypatch.setattr(ledger, "check_state_db_integrity", _spy)+ return calls+++def test_deferred_scan_still_runs_on_a_wal_store(tmp_path: Path, monkeypatch) -> None:+ _make_state_db(tmp_path, corrupt=False, journal_mode="wal")+ calls = _spy_on_scan(monkeypatch)++ verdict = run_deferred_integrity_check({"prior_pid": _DEAD_PID}, home=tmp_path, deadline_s=60.0)++ assert verdict == "ok"+ assert len(calls) == 1+ assert _exit_diag_records(tmp_path)[-1]["state_db_integrity"] == "ok"+++def test_deferred_scan_skips_a_rollback_journal_store(tmp_path: Path, monkeypatch, caplog) -> None:+ path = _make_state_db(tmp_path, corrupt=False)+ calls = _spy_on_scan(monkeypatch)+ evidence = {"prior_pid": _DEAD_PID}++ with caplog.at_level(logging.WARNING, logger="gateway.lifecycle_ledger"):+ verdict = run_deferred_integrity_check(evidence, home=tmp_path, deadline_s=60.0)++ assert not calls, "quick_check ran beside live traffic on a rollback-journal store"+ assert verdict == ("skipped: rollback-journal store (journal_mode=delete), "+ "scan would block live writes")+ assert evidence["state_db_integrity"] == verdict+ record = _exit_diag_records(tmp_path)[-1]+ assert record["tag"] == "gateway.state_db_integrity"+ assert record["state_db_integrity"] == verdict+ assert record["prior_pid"] == _DEAD_PID+ warnings = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]+ assert len(warnings) == 1+ assert "unclean" in warnings[0].lower() and "skipped" in warnings[0].lower()+ assert str(path) in warnings[0] and "PRAGMA quick_check" in warnings[0]+ # The journal-mode probe left no lock behind: a live writer commits without waiting.+ writer = sqlite3.connect(path, timeout=0)+ try:+ writer.execute("BEGIN EXCLUSIVE")+ writer.execute("INSERT INTO sessions (v) VALUES ('live')")+ writer.commit()+ finally:+ writer.close()+++def test_deferred_scan_skips_when_the_journal_mode_is_undeterminable(tmp_path: Path, monkeypatch) -> None:+ import hermes_state_wal++ _make_state_db(tmp_path, corrupt=False, journal_mode="wal")+ calls = _spy_on_scan(monkeypatch)++ def _unreadable(conn):+ raise sqlite3.DatabaseError("file is not a database")++ monkeypatch.setattr(hermes_state_wal, "_on_disk_journal_mode", _unreadable)++ verdict = run_deferred_integrity_check({"prior_pid": _DEAD_PID}, home=tmp_path, deadline_s=60.0)++ assert not calls+ assert verdict == ("skipped: rollback-journal store (journal_mode=unknown), "+ "scan would block live writes")+ assert _exit_diag_records(tmp_path)[-1]["state_db_integrity"] == verdict+++def test_deferred_scan_of_an_absent_store_is_unchanged(tmp_path: Path) -> None:+ verdict = run_deferred_integrity_check({"prior_pid": _DEAD_PID}, home=tmp_path, deadline_s=60.0)++ assert verdict == "absent"+ assert _exit_diag_records(tmp_path)[-1]["state_db_integrity"] == "absent"+ assert not (tmp_path / "state.db").exists()++# ── bounded scan: a deadline aborts through the progress handler ─────────────