The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): defer the unclean-exit state.db integrity scan off the startup path
yoyodine-industriesac90478e0880
diff --git a/gateway/lifecycle_ledger.py b/gateway/lifecycle_ledger.pyindex e39c3c38eba..254dc6ef4b4 100644--- a/gateway/lifecycle_ledger.py+++ b/gateway/lifecycle_ledger.py@@ -186,8 +186,11 @@ def detect_unclean_exit(home: Optional[Path] = None) -> Optional[dict[str, Any]]# clamp at 900s, so a single entry lease cannot cover a multi-thousand-second healthy# check on a huge store — without renewal the watchdog kills the attempt with exit 75# and the restart loop never reaches the cron ticker. The progress handler below renews-# a phase-owned lease for as long as SQLite is making progress, and always returns 0-# so it never aborts the check; the ok/absent/first-complaint verdicts stay fail-closed.+# a phase-owned lease for as long as SQLite is making progress; without a deadline it+# always returns 0 so it never aborts the check, and the ok/absent/first-complaint+# verdicts stay fail-closed. When an explicit ``deadline_at`` is supplied (t_8a73f016)+# the handler returns non-zero once it passes, so SQLite aborts the scan and the caller+# can bound a pathological store instead of pinning the boot path._INTEGRITY_CHECK_LEASE_PHASE = "state_db_unclean_integrity_check"_INTEGRITY_CHECK_LEASE_S = 900.0# VM instructions between progress-handler invocations; each invocation is a@@ -196,12 +199,15 @@ _INTEGRITY_CHECK_PROGRESS_OPS = 100_000_INTEGRITY_CHECK_LEASE_RENEW_S = 60.0-def _install_integrity_check_lease(conn: sqlite3.Connection) -> None:+def _install_integrity_check_lease(conn: sqlite3.Connection, *, deadline_at: Optional[float] = None) -> None:"""Claim the integrity-check lease and renew it from a SQLite progress handler.``report_startup_progress`` is a no-op when no watchdog is armed and never raises.- The handler always returns 0 -- it must never abort the verdict PRAGMA. Synchronous- by design: no checker worker thread can outlive the check.+ Without ``deadline_at`` the handler always returns 0 -- it must never abort the verdict+ PRAGMA. With ``deadline_at`` (a ``time.monotonic`` timestamp) it returns non-zero once+ that instant is reached, so SQLite raises ``OperationalError: interrupted`` and the+ caller can bound the scan. Synchronous by design: no checker worker thread can outlive+ the check."""from hermes_startup_watchdog import report_startup_progress@@ -214,12 +220,14 @@ def _install_integrity_check_lease(conn: sqlite3.Connection) -> None:if now - last_renew >= _INTEGRITY_CHECK_LEASE_RENEW_S:last_renew = nowreport_startup_progress(_INTEGRITY_CHECK_LEASE_S, phase=_INTEGRITY_CHECK_LEASE_PHASE)+ if deadline_at is not None and now >= deadline_at:+ return 1return 0conn.set_progress_handler(_on_progress, _INTEGRITY_CHECK_PROGRESS_OPS)-def check_state_db_integrity(home: Optional[Path] = None) -> str:+def check_state_db_integrity(home: Optional[Path] = None, *, deadline_s: Optional[float] = None) -> str:"""``"ok"``, ``"absent"``, or the first ``quick_check`` complaint. Never raises.Only after an unclean death — SIGKILL mid-WAL-checkpoint can leave half-written@@ -230,29 +238,51 @@ def check_state_db_integrity(home: Optional[Path] = None) -> str:Holds a phase-owned startup-watchdog lease for the check duration(renewed from a SQLite progress handler, #115542) so a long healthy checkon a huge store is not mistaken for a parked deadlock.++ ``deadline_s`` (optional, t_8a73f016): abort the scan once that many seconds elapse and+ return ``"check-incomplete: exceeded <N>s"``. ``deadline_s=None`` (default) is the+ historic unbounded behaviour -- the progress handler never aborts the PRAGMA."""path = _home_path(home, "state.db")if not path.exists():return "absent"+ deadline_at: Optional[float] = None+ if deadline_s is not None:+ try:+ deadline_at = time.monotonic() + max(0.0, float(deadline_s))+ except (TypeError, ValueError):+ deadline_at = Nonetry:with closing(sqlite3.connect(str(path))) as conn:- _install_integrity_check_lease(conn)+ _install_integrity_check_lease(conn, deadline_at=deadline_at)row = conn.execute("PRAGMA quick_check(1)").fetchone()except Exception as exc:+ if (deadline_at is not None and isinstance(exc, sqlite3.OperationalError)+ and "interrupt" in str(exc).lower()):+ limit = max(0.0, float(deadline_s)) if deadline_s is not None else 0.0+ return f"check-incomplete: exceeded {limit:g}s"return f"check-failed: {exc}"return "check-failed: no result" if not row or row[0] is None else str(row[0])-def _report_unclean_exit(evidence: dict[str, Any], home: Optional[Path]) -> None:- """Integrity-check the store, persist the exit-diag record, log at WARNING."""- # The death may have torn the store; this is the only moment we know to look.- verdict = evidence["state_db_integrity"] = check_state_db_integrity(home=home)- if verdict not in ("ok", "absent"):- 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`.",- verdict,- )+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.++ When ``defer_integrity_check`` is set, the forensic store scan is NOT run here (it would+ gate platform startup); the record carries ``state_db_integrity: "deferred"`` and+ :func:`run_deferred_integrity_check` runs the scan post-connect.+ """+ if defer_integrity_check:+ evidence["state_db_integrity"] = "deferred"+ else:+ # The death may have torn the store; this is the only moment we know to look.+ verdict = evidence["state_db_integrity"] = check_state_db_integrity(home=home)+ if verdict not in ("ok", "absent"):+ 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`.",+ verdict,+ )_append_exit_diag({"ts": _now_iso(), "tag": "gateway.previous_unclean_exit", "pid": os.getpid(), **evidence}, home)logger.warning("Previous gateway life (pid=%s, started_at=%s) exited UNCLEANLY (no exit path ran — SIGKILL / OOM / "@@ -263,14 +293,21 @@ def _report_unclean_exit(evidence: dict[str, Any], home: Optional[Path]) -> None)-def record_startup(home: Optional[Path] = None) -> Optional[dict[str, Any]]:+def record_startup(home: Optional[Path] = None, *, defer_integrity_check: bool = True) -> Optional[dict[str, Any]]:"""Boot entry point: report any unclean previous exit (evidence dict, also persisted- to ``gateway-exit-diag.log`` and logged at WARNING) then claim the sentinel. Never raises."""+ to ``gateway-exit-diag.log`` and logged at WARNING) then claim the sentinel. Never raises.++ ``defer_integrity_check`` defaults to True: the state.db integrity scan is forensic and+ must NOT gate platform startup (a large store's ``quick_check`` blocked the ``:8644`` fleet+ peer-DM transport for minutes). In deferred mode the exit-diag record is written+ immediately with ``state_db_integrity: "deferred"`` and the scan runs post-connect via+ :func:`run_deferred_integrity_check`. Pass False for the historic INLINE scan.+ """evidence: Optional[dict[str, Any]] = Nonetry:evidence = detect_unclean_exit(home)if evidence is not None:- _report_unclean_exit(evidence, home)+ _report_unclean_exit(evidence, home, defer_integrity_check=defer_integrity_check)except Exception:logger.debug("Unclean-exit detection failed", exc_info=True)try:@@ -295,6 +332,47 @@ def record_startup(home: Optional[Path] = None) -> Optional[dict[str, Any]]:return evidence+def run_deferred_integrity_check(+ evidence: Optional[dict[str, Any]], *, home: Optional[Path] = None, deadline_s: float = 1800.0+) -> str:+ """Run the deferred post-connect state.db scan and append a second diag record.++ Companion to :func:`record_startup` with ``defer_integrity_check=True``: the forensic scan+ is moved off the startup path (where, on a multi-GB store, it gated every platform adapter+ — including the ``:8644`` fleet peer-DM transport — for minutes) into a daemon thread+ started only after platforms connected. ``deadline_s`` bounds a pathological store so the+ thread cannot be pinned forever.++ Appends ``{"tag": "gateway.state_db_integrity", "deferred": true, "state_db_integrity":+ <verdict>, "prior_pid": ...}`` and logs the existing ERROR text on a bad verdict. NEVER+ raises -- a forensic scan must not disturb a running gateway (the alerting path is the+ bounded per-poll readiness probe ``gateway/readiness.py::_probe_state_db``).+ """+ try:+ verdict = check_state_db_integrity(home=home, deadline_s=deadline_s)+ if verdict not in ("ok", "absent"):+ 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`.",+ verdict,+ )+ record: dict[str, Any] = {+ "ts": _now_iso(),+ "tag": "gateway.state_db_integrity",+ "deferred": True,+ "state_db_integrity": verdict,+ }+ if isinstance(evidence, dict) and evidence.get("prior_pid") is not None:+ record["prior_pid"] = evidence.get("prior_pid")+ _append_exit_diag(record, home)+ if isinstance(evidence, dict):+ evidence["state_db_integrity"] = verdict+ return verdict+ except Exception:+ logger.debug("Deferred state.db integrity check failed", exc_info=True)+ return "check-failed: deferred scan raised"++def mark_exited(exit_code: Optional[int] = None, reason: str = "graceful_shutdown", home: Optional[Path] = None) -> None:"""Mark the current life as cleanly exited. Idempotent, never raises.diff --git a/tests/gateway/test_lifecycle_state_db_check.py b/tests/gateway/test_lifecycle_state_db_check.pyindex 679891cdaf8..45b85c0fe17 100644--- a/tests/gateway/test_lifecycle_state_db_check.py+++ b/tests/gateway/test_lifecycle_state_db_check.py@@ -10,17 +10,26 @@ it on 2026-08-30 17:15 and surfaced as "Session not found".VM death" — it just never looked at the database that death may have torn.The check is gated on the unclean exit precisely because it costs ~2s on a500MB store; a clean boot must not pay it.++Since t_8a73f016 the scan is DEFERRED by default: the boot entry point writes+the exit-diag record and claims the sentinel immediately, and the forensic scan+runs post-connect (``run_deferred_integrity_check``) so a large store can never+gate platform startup (the ``:8644`` fleet peer-DM transport). The tests below+keep the historic INLINE behaviour covered via ``defer_integrity_check=False``."""from __future__ import annotationsimport jsonimport sqlite3+import threading+import timefrom pathlib import Pathfrom gateway.lifecycle_ledger import (check_state_db_integrity,get_lifecycle_sentinel_path,record_startup,+ run_deferred_integrity_check,)_DEAD_PID = 2 ** 22 + 12345 # beyond default pid_max; never alive@@ -57,6 +66,20 @@ def _make_state_db(home: Path, *, corrupt: bool) -> Path:return path+def _make_multi_page_state_db(home: Path, rows: int = 300_000) -> Path:+ """A store large enough that ``quick_check`` takes measured tens of ms, so a+ wall-clock deadline can fire MID-scan. Cheap to build (~1s)."""+ path = home / "state.db"+ conn = sqlite3.connect(path)+ conn.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(rows)]+ )+ conn.commit()+ conn.close()+ return path++def _exit_diag_records(home: Path) -> list:log = home / "logs" / "gateway-exit-diag.log"if not log.exists():@@ -90,7 +113,7 @@ def test_unclean_exit_records_the_corruption_verdict(tmp_path: Path) -> None:_make_state_db(tmp_path, corrupt=True)_write_sentinel(tmp_path)- evidence = record_startup(home=tmp_path)+ evidence = record_startup(home=tmp_path, defer_integrity_check=False)assert evidence is not Noneassert evidence["state_db_integrity"] != "ok"@@ -102,7 +125,7 @@ def test_unclean_exit_on_a_healthy_store_records_ok(tmp_path: Path) -> None:_make_state_db(tmp_path, corrupt=False)_write_sentinel(tmp_path)- evidence = record_startup(home=tmp_path)+ evidence = record_startup(home=tmp_path, defer_integrity_check=False)assert evidence is not Noneassert evidence["state_db_integrity"] == "ok"@@ -124,6 +147,98 @@ def test_clean_exit_does_not_pay_for_the_check(tmp_path: Path, monkeypatch) -> Nassert not called, "integrity check ran on a clean boot"+# ── deferred startup (t_8a73f016): the scan must not gate platform startup ───+++def test_deferred_startup_never_runs_the_check_inline(tmp_path: Path, monkeypatch) -> None:+ """DEFERRAL IS THE DEFAULT: the boot entry point must return WITHOUT the forensic+ scan completing, and the exit-diag record must record that the verdict is pending.+ The blocking stub below never returns unless the deferred path wrongly runs it."""+ import gateway.lifecycle_ledger as ledger++ started = threading.Event()+ released = threading.Event()++ def _blocking_check(**kwargs):+ started.set()+ released.wait(10) # never set by the caller -> proves the boot path did not run it+ return "ok"++ monkeypatch.setattr(ledger, "check_state_db_integrity", _blocking_check)+ _write_sentinel(tmp_path)++ begin = time.monotonic()+ evidence = record_startup(home=tmp_path) # default: defer_integrity_check=True+ elapsed = time.monotonic() - begin++ assert evidence is not None+ assert evidence["state_db_integrity"] == "deferred"+ assert not started.is_set(), "the inline integrity scan ran on the deferred boot path"+ assert elapsed < 5.0+ record = _exit_diag_records(tmp_path)[0]+ assert record["state_db_integrity"] == "deferred"+ assert record["tag"] == "gateway.previous_unclean_exit"+++def test_deferred_scan_appends_a_second_record_and_returns_the_verdict(tmp_path: Path) -> None:+ _make_state_db(tmp_path, corrupt=True)+ _write_sentinel(tmp_path)++ evidence = record_startup(home=tmp_path, defer_integrity_check=True)+ assert evidence is not None and evidence["state_db_integrity"] == "deferred"++ verdict = run_deferred_integrity_check(evidence, home=tmp_path, deadline_s=60.0)++ records = _exit_diag_records(tmp_path)+ assert [r["tag"] for r in records] == [+ "gateway.previous_unclean_exit", "gateway.state_db_integrity"]+ deferred = records[1]+ assert deferred["deferred"] is True+ assert deferred["state_db_integrity"] == verdict+ assert deferred["prior_pid"] == _DEAD_PID+ assert verdict != "ok"+ assert evidence["state_db_integrity"] == verdict+++def test_deferred_scan_never_raises(tmp_path: Path, monkeypatch) -> None:+ import gateway.lifecycle_ledger as ledger++ _write_sentinel(tmp_path)+ evidence = record_startup(home=tmp_path, defer_integrity_check=True)++ def _boom(**kwargs):+ raise RuntimeError("boom")++ monkeypatch.setattr(ledger, "check_state_db_integrity", _boom)++ assert run_deferred_integrity_check(evidence, home=tmp_path).startswith("check-failed")+++# ── bounded scan: a deadline aborts through the progress handler ─────────────+++def test_deadline_bounds_the_scan(tmp_path: Path, monkeypatch) -> None:+ import gateway.lifecycle_ledger as ledger++ _make_multi_page_state_db(tmp_path)+ monkeypatch.setattr(ledger, "_INTEGRITY_CHECK_PROGRESS_OPS", 1_000)++ verdict = check_state_db_integrity(home=tmp_path, deadline_s=0.01)++ assert verdict.startswith("check-incomplete: exceeded"), verdict+++def test_no_deadline_keeps_the_historic_verdict_contract(tmp_path: Path, monkeypatch) -> None:+ """``deadline_s=None`` must be byte-for-byte today's behaviour: the handler never aborts."""+ import gateway.lifecycle_ledger as ledger++ _make_multi_page_state_db(tmp_path)+ monkeypatch.setattr(ledger, "_INTEGRITY_CHECK_PROGRESS_OPS", 1_000)++ assert check_state_db_integrity(home=tmp_path) == "ok"+ assert check_state_db_integrity(home=tmp_path, deadline_s=None) == "ok"++# ── startup-watchdog lease during the check (#115542) ───────────────────────@@ -157,7 +272,7 @@ def test_unclean_exit_check_renews_the_startup_lease_while_sqlite_progresses(_make_state_db(tmp_path, corrupt=False)_write_sentinel(tmp_path)- evidence = record_startup(home=tmp_path)+ evidence = record_startup(home=tmp_path, defer_integrity_check=False)assert evidence is not None and evidence["state_db_integrity"] == "ok"assert handle._lease_phase == "state_db_unclean_integrity_check"