The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): retry FTS index rebuild after cooldown instead of giving up
Rook-CodeVoltcaba409bb86b
diff --git a/gateway/session.py b/gateway/session.pyindex a957f7f1453..4a65b282877 100644--- a/gateway/session.py+++ b/gateway/session.py@@ -782,7 +782,9 @@ class SessionStore(self._transcript_reroutes: Dict[str, str] = {}self._dirty_transcripts: Dict[str, List[Dict[str, Any]]] = {}self._transcript_append_failures: Dict[str, int] = {}- self._fts_rebuild_attempted = False+ # Monotonic timestamp of the last FTS5 rebuild attempt, or None before any attempt; see+ # SessionTranscriptMixin._rebuild_fts_once for the cooldown this gates.+ self._fts_rebuild_last_attempt_at: Optional[float] = Noneself._has_active_processes_fn = has_active_processes_fnself._write_sessions_json = bool(getattr(config, "write_sessions_json", True))diff --git a/gateway/session_transcript.py b/gateway/session_transcript.pyindex e24fe43a48f..d8f294dca22 100644--- a/gateway/session_transcript.py+++ b/gateway/session_transcript.py@@ -7,6 +7,7 @@ from __future__ import annotationsimport contextlibimport loggingimport threading+import timefrom agent.turn_context import extract_api_content_sidecarfrom typing import TYPE_CHECKING, Any, Dict, List, Optional@@ -47,6 +48,14 @@ class SessionTranscriptMixin:compression-reroute following, FTS corruption recovery, rewrite/rewind/load."""_MAX_PENDING_PER_SESSION = 200 # in-memory pending messages per session (DB broken)+ # Cooldown between FTS5 rebuild attempts (see _rebuild_fts_once); avoids permanently+ # disabling recovery after one failed attempt while still avoiding a rebuild storm against+ # a database that is corrupt on every write.+ _FTS_REBUILD_COOLDOWN_SECONDS = 300+ # Consecutive transcript-append failures for one session before escalating from WARNING to+ # ERROR (see _append_to_transcript_serialized); a session stalled past this many attempts is+ # no longer a transient blip and needs operator attention.+ _TRANSCRIPT_APPEND_FAILURE_ESCALATION_THRESHOLD = 3def _compression_tip_for_session_id(self, session_id: Optional[str]) -> Optional[str]:"""Latest compression continuation for *session_id* (heals a mapping left pointing at a@@ -285,9 +294,15 @@ class SessionTranscriptMixin:with self._transcript_retry_lock:failures = self._transcript_append_failures.get(session_id, 0) + 1self._transcript_append_failures[session_id] = failures- logger.warning(- "Session DB transcript append failed for %s (failure_count=%d, pending=%d); "- "will retry: %s", session_id, failures, len(pending), exc)+ if failures >= self._TRANSCRIPT_APPEND_FAILURE_ESCALATION_THRESHOLD:+ logger.error(+ "Session DB transcript append failed for %s (failure_count=%d, "+ "pending=%d); session is stalled and needs operator attention: %s",+ session_id, failures, len(pending), exc)+ else:+ logger.warning(+ "Session DB transcript append failed for %s (failure_count=%d, pending=%d); "+ "will retry: %s", session_id, failures, len(pending), exc)returnelse:with self._transcript_retry_lock:@@ -365,10 +380,20 @@ class SessionTranscriptMixin:return isinstance(exc, sqlite3.DatabaseError) and SessionDB._is_fts_write_corruption_error(exc)def _rebuild_fts_once(self) -> bool:- """Attempt FTS5 ``rebuild`` once per store lifetime; True if any index was rebuilt."""- if self._fts_rebuild_attempted:+ """Attempt FTS5 ``rebuild``, at most once per ``_FTS_REBUILD_COOLDOWN_SECONDS`` window;+ True if any index was rebuilt.++ A permanent one-shot flag meant a single rebuild failure (e.g. a transient WAL+ split-brain guard hit) permanently disabled recovery for the life of the process, even+ though later corruption on the same store could be fixable. Retrying on a cooldown lets+ the store try again after the underlying condition (e.g. a foreign holder) has likely+ cleared, without hammering a database that is corrupt on every write.+ """+ now = time.monotonic()+ last_attempt = self._fts_rebuild_last_attempt_at+ if last_attempt is not None and (now - last_attempt) < self._FTS_REBUILD_COOLDOWN_SECONDS:return False- self._fts_rebuild_attempted = True+ self._fts_rebuild_last_attempt_at = nowdb = self._dbif db is None or not hasattr(db, "rebuild_fts"):return Falsediff --git a/tests/gateway/test_pending_queue_spool.py b/tests/gateway/test_pending_queue_spool.pyindex cec51cb2780..40a94587e91 100644--- a/tests/gateway/test_pending_queue_spool.py+++ b/tests/gateway/test_pending_queue_spool.py@@ -9,6 +9,7 @@ successful transcript flush — not silently discarded (#78182, #82616).import jsonimport loggingimport threading+import timeimport pytest@@ -22,7 +23,7 @@ def _make_store(db):store._transcript_retry_lock = threading.Lock()store._dirty_transcripts = {}store._transcript_append_failures = {}- store._fts_rebuild_attempted = True+ store._fts_rebuild_last_attempt_at = time.monotonic()return storediff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.pyindex 1b7cc376f42..852145a2ce1 100644--- a/tests/gateway/test_session.py+++ b/tests/gateway/test_session.py@@ -1,5 +1,7 @@"""Tests for gateway session management."""import json+import logging+import timeimport pytestfrom dataclasses import replacefrom datetime import datetime, timedelta@@ -1402,7 +1404,7 @@ class TestGatewaySessionDbRecovery:store._transcript_retry_lock = threading.Lock()store._dirty_transcripts = {}store._transcript_append_failures = {}- store._fts_rebuild_attempted = False+ store._fts_rebuild_last_attempt_at = Nonestore.append_to_transcript("parent", {"role": "assistant", "content": "routed to child"}@@ -1441,7 +1443,7 @@ class TestGatewaySessionDbRecovery:store._transcript_retry_lock = threading.Lock()store._dirty_transcripts = {}store._transcript_append_failures = {}- store._fts_rebuild_attempted = False+ store._fts_rebuild_last_attempt_at = Nonestore.append_to_transcript("root", {"role": "assistant", "content": "routed to tip"}@@ -1477,7 +1479,7 @@ class TestGatewaySessionDbRecovery:store._transcript_retry_lock = threading.Lock()store._dirty_transcripts = {}store._transcript_append_failures = {}- store._fts_rebuild_attempted = False+ store._fts_rebuild_last_attempt_at = Nonestore.append_to_transcript("root", {"role": "assistant", "content": "must not land"}@@ -1514,7 +1516,7 @@ class TestGatewaySessionDbRecovery:]}store._transcript_append_failures = {"parent": 2}- store._fts_rebuild_attempted = True+ store._fts_rebuild_last_attempt_at = time.monotonic()child_attempts = []failed_old_2 = False@@ -1587,6 +1589,70 @@ class TestGatewaySessionDbRecovery:RuntimeError("gifts received"))+ def test_rebuild_fts_once_retries_after_cooldown_and_escalates_log(self, caplog, monkeypatch):+ """_rebuild_fts_once must block retries until the cooldown window elapses, then allow+ one more attempt (#114266: a permanent one-shot flag disabled recovery forever after a+ single failed rebuild). Once the append-failure count crosses the escalation threshold,+ the append-failure logging must escalate from WARNING to ERROR."""+ import threading+ from types import SimpleNamespace++ class FakeDb:+ def __init__(self):+ self.rebuild_calls = 0++ def rebuild_fts(self):+ self.rebuild_calls += 1+ return 1++ fake_db = FakeDb()+ store = object.__new__(SessionStore)+ store._db = fake_db+ store._fts_rebuild_last_attempt_at = None++ # Fake clock so the cooldown boundary is exact and not flaky under real time.+ clock = {"now": 1000.0}+ monkeypatch.setattr(time, "monotonic", lambda: clock["now"])++ assert store._rebuild_fts_once() is True+ assert fake_db.rebuild_calls == 1++ # Still within the cooldown window: blocked, no second rebuild call.+ clock["now"] += store._FTS_REBUILD_COOLDOWN_SECONDS - 1+ assert store._rebuild_fts_once() is False+ assert fake_db.rebuild_calls == 1++ # Cooldown has elapsed: retry is allowed again.+ clock["now"] += 2+ assert store._rebuild_fts_once() is True+ assert fake_db.rebuild_calls == 2++ # --- Escalation logging on _append_to_transcript_serialized ---+ db_fail = SimpleNamespace(+ append_message=lambda **kwargs: (_ for _ in ()).throw(+ RuntimeError("database disk image is malformed")+ )+ )+ log_store = object.__new__(SessionStore)+ log_store._db = db_fail+ log_store._transcript_retry_lock = threading.Lock()+ log_store._dirty_transcripts = {}+ log_store._transcript_append_failures = {}+ log_store._fts_rebuild_last_attempt_at = time.monotonic()++ threshold = log_store._TRANSCRIPT_APPEND_FAILURE_ESCALATION_THRESHOLD+ with caplog.at_level(logging.WARNING, logger="gateway.session_transcript"):+ for i in range(threshold - 1):+ caplog.clear()+ log_store.append_to_transcript("s-esc", {"role": "user", "content": f"m{i}"})+ assert any(r.levelno == logging.WARNING for r in caplog.records)+ assert not any(r.levelno == logging.ERROR for r in caplog.records)++ caplog.clear()+ log_store.append_to_transcript("s-esc", {"role": "user", "content": "trigger"})+ assert any(r.levelno == logging.ERROR for r in caplog.records)+ assert log_store._transcript_append_failures["s-esc"] == threshold+def test_pending_queue_caps_at_max(self):"""Pending queue should drop oldest messages when exceeding the capto prevent unbounded memory growth on persistent DB failure."""@@ -1608,7 +1674,7 @@ class TestGatewaySessionDbRecovery:store._transcript_retry_lock = threading.Lock()store._dirty_transcripts = {}store._transcript_append_failures = {}- store._fts_rebuild_attempted = True+ store._fts_rebuild_last_attempt_at = time.monotonic()# Fill beyond the capfor i in range(store._MAX_PENDING_PER_SESSION + 10):diff --git a/tests/gateway/test_session_db_corrupt_fallback.py b/tests/gateway/test_session_db_corrupt_fallback.pyindex 9a6be9a1141..82526cedc3a 100644--- a/tests/gateway/test_session_db_corrupt_fallback.py+++ b/tests/gateway/test_session_db_corrupt_fallback.py@@ -62,7 +62,7 @@ def test_corrupt_state_db_diverts_pending_without_fts_rebuild(tmp_path, monkeypa# No FTS surgery ran on either layer.assert store._db._fts_enabled is Trueassert store._db._fts_stale is False- assert store._fts_rebuild_attempted is False+ assert store._fts_rebuild_last_attempt_at is Noneassert sid not in store._dirty_transcripts_assert_diverted(tmp_path, sid, "after-corrupt")finally:diff --git a/tests/gateway/test_session_db_replaced_fallback.py b/tests/gateway/test_session_db_replaced_fallback.pyindex 21c97006667..61b68c298f3 100644--- a/tests/gateway/test_session_db_replaced_fallback.py+++ b/tests/gateway/test_session_db_replaced_fallback.py@@ -59,7 +59,7 @@ def test_replaced_state_db_diverts_pending_without_fts_rebuild(tmp_path, monkeyp# detached, and the gateway one-shot rebuild was not consumed.assert store._db._fts_enabled is Trueassert store._db._fts_stale is False- assert store._fts_rebuild_attempted is False+ assert store._fts_rebuild_last_attempt_at is None_assert_diverted(tmp_path, sid, "after-replace")store.close_all_db_handles()@@ -98,6 +98,6 @@ def test_copyfile_replaced_state_db_diverts_pending_without_fts_rebuild(# detached, and the gateway one-shot rebuild was not consumed.assert store._db._fts_enabled is Trueassert store._db._fts_stale is False- assert store._fts_rebuild_attempted is False+ assert store._fts_rebuild_last_attempt_at is None_assert_diverted(tmp_path, sid, "after-cp")store.close_all_db_handles()