The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): count no-DB transcript appends and spool a stalled session's backlog to disk
teknium1d0d004bce1a3
diff --git a/gateway/session_transcript.py b/gateway/session_transcript.pyindex 3dd6836b0ec..d666b16ee59 100644--- a/gateway/session_transcript.py+++ b/gateway/session_transcript.py@@ -108,8 +108,11 @@ class SessionTranscriptMixin:return self._lazy("_transcript_drain_lock", threading.RLock)def append_to_transcript(self, session_id: str, message: Dict[str, Any], skip_db: bool = False) -> None:- """Serialize transcript draining across queue migration boundaries."""- if not self._db_for_session_id(session_id) or skip_db:+ """Serialize transcript draining across queue migration boundaries. A session with no usable+ store is NOT skipped: the write is queued and counted like any other failed append, so a+ dead/unopenable state.db escalates and spools instead of dropping turns silently+ (#114266)."""+ if skip_db:returnwith self._get_transcript_drain_lock():self._append_to_transcript_serialized(self._follow_reroutes(session_id), message)@@ -241,6 +244,9 @@ class SessionTranscriptMixin:# DB write outside the retry lock so other sessions can append.while True:+ # Spooled backlog (cap eviction or a stalled session) is older than ``msg``: replay it+ # first so recovery keeps transcript order; a still-dead DB just fails both.+ self._drain_spooled_drops(session_id)try:self._append_transcript_message(session_id, msg)except Exception as exc:@@ -295,10 +301,11 @@ class SessionTranscriptMixin:failures = self._transcript_append_failures.get(session_id, 0) + 1self._transcript_append_failures[session_id] = failuresif failures >= self._TRANSCRIPT_APPEND_FAILURE_ESCALATION_THRESHOLD:+ spooled = self._spool_stalled_backlog(session_id, queue_session_id)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)+ "pending=%d, spooled_to_disk=%d); session is stalled and needs operator "+ "attention: %s", session_id, failures, len(pending), spooled, exc)else:logger.warning("Session DB transcript append failed for %s (failure_count=%d, pending=%d); "@@ -310,12 +317,30 @@ class SessionTranscriptMixin:if not queue_empty:msg = pending[0]if queue_empty:- # Backlog clear: replay cap-dropped messages spooled to disk.- # See #78182.- self._drain_spooled_drops(session_id)returncontinue+ def _spool_stalled_backlog(self, session_id: str, queue_session_id: str) -> int:+ """Move a stalled session's in-memory backlog (oldest first) to the on-disk pending spool so+ a crash/restart during the outage no longer loses it (#114266): ``recover_pending_to_db``+ replays it at boot, ``_drain_spooled_drops`` before the next live write. Stops at the first+ spool failure so order holds; whatever stays in memory remains under the cap."""+ with self._transcript_retry_lock:+ pending = self._dirty_transcripts.get(queue_session_id, [])+ backlog = list(pending)+ spooled = 0+ for message in backlog:+ if _spool_dropped(session_id, message) is None:+ break+ spooled += 1+ if spooled:+ self._lazy("_spooled_drop_sessions", set).add(session_id)+ with self._transcript_retry_lock:+ del pending[:spooled]+ if not pending:+ self._dirty_transcripts.pop(queue_session_id, None)+ return spooled+def _drain_spooled_drops(self, session_id: str) -> None:"""Replay cap-dropped spooled transcript messages after DB recovery. Best-effort: replayfailures keep the spool files for the next successful flush; nothing here may raise."""diff --git a/tests/gateway/test_pending_queue_spool.py b/tests/gateway/test_pending_queue_spool.pyindex 40a94587e91..0c1645981c4 100644--- a/tests/gateway/test_pending_queue_spool.py+++ b/tests/gateway/test_pending_queue_spool.py@@ -24,6 +24,9 @@ def _make_store(db):store._dirty_transcripts = {}store._transcript_append_failures = {}store._fts_rebuild_last_attempt_at = time.monotonic()+ # These tests exercise the cap-eviction spool path; keep the stalled-session spool (which+ # normally fires first, at the escalation threshold) out of the way.+ store._TRANSCRIPT_APPEND_FAILURE_ESCALATION_THRESHOLD = 10 ** 6return storediff --git a/tests/gateway/test_session.py b/tests/gateway/test_session.pyindex 62ab9c7a308..f8c787ed726 100644--- a/tests/gateway/test_session.py+++ b/tests/gateway/test_session.py@@ -1515,7 +1515,9 @@ class TestGatewaySessionDbRecovery:{"role": "assistant", "content": "old-2"},]}- store._transcript_append_failures = {"parent": 2}+ # One short of the escalation threshold: the migrated backlog must stay in memory here+ # (at the threshold the stalled-session path spools it to disk instead).+ store._transcript_append_failures = {"parent": 1}store._fts_rebuild_last_attempt_at = time.monotonic()child_attempts = []failed_old_2 = False@@ -1636,6 +1638,42 @@ class TestGatewaySessionDbRecovery:assert levels == [logging.WARNING] * (threshold - 1) + [logging.ERROR]assert store._transcript_append_failures["s-esc"] == threshold+ def test_no_usable_db_counts_failures_and_spools_backlog_before_cap(+ self, caplog, tmp_path, monkeypatch+ ):+ """The reporter's outage shape (#114266): ``SessionStore._db is None`` used to early-return+ silently — no counter, no log, turns held in memory until a crash. Now each append counts+ toward the same ERROR escalation and, once the session is stalled, the backlog is spooled+ to disk (long before the 200-message cap) and replayed in order on recovery."""+ import threading+ from types import SimpleNamespace+ import hermes_constants++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)+ store = object.__new__(SessionStore)+ store._db = None+ store._transcript_retry_lock = threading.Lock()+ store._dirty_transcripts = {}+ store._transcript_append_failures = {}+ store._fts_rebuild_last_attempt_at = time.monotonic()+ threshold = store._TRANSCRIPT_APPEND_FAILURE_ESCALATION_THRESHOLD+ with caplog.at_level(logging.WARNING, logger="gateway.session_transcript"):+ for i in range(threshold):+ store.append_to_transcript("s-dead", {"role": "user", "content": f"m{i}"})+ assert store._transcript_append_failures["s-dead"] == threshold+ assert [r.levelno for r in caplog.records if "transcript append failed" in r.getMessage()][-1] == logging.ERROR+ spooled = sorted(json.loads(p.read_text())["data"]["message"]["content"]+ for p in (tmp_path / "pending_messages").glob("pending-*.json"))+ assert spooled == [f"m{i}" for i in range(threshold)] # durable before the cap+ assert "s-dead" not in store._dirty_transcripts++ rows = []+ store._db = SimpleNamespace(append_message=lambda **kw: rows.append(kw["content"]))+ store.append_to_transcript("s-dead", {"role": "assistant", "content": "recovered"})+ assert rows == [f"m{i}" for i in range(threshold)] + ["recovered"] # replayed in order+ assert list((tmp_path / "pending_messages").glob("pending-*.json")) == []+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."""