The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): escalate a persistent transcript-lag streak to ERROR
teknium13a8b82362fc0
diff --git a/gateway/run.py b/gateway/run.pyindex 27401a7a7e6..8db59e9ec29 100644--- a/gateway/run.py+++ b/gateway/run.py@@ -2188,6 +2188,8 @@ _CONVERSATION_SCOPED_STATE: tuple = (# Stall-watchdog "already notified" latch; cleared on /new so a fresh conversation can warn again.# See #72016."_session_stall_notified",+ # Transcript-lag streak counter (#114266); a fresh conversation starts with no lag history.+ "_transcript_lag_streaks",# Sidecar notes staged but never consumed (turn aborted before run_sync) must not leak into a# future conversation's first user message — session keys are source-derived and REUSED."_pending_turn_sidecar_notes")@@ -3507,6 +3509,9 @@ class GatewayRunner(# paths, busy-ack debounce timestamps and the monotonic run-generation counter (#28686, NEVER reset)# live on SessionState too. See gateway.session_stall.self._session_stall_notified: Dict[str, bool] = {}+ # Consecutive "persisted transcript lagged live cached history" turns per session key; see+ # run_turn_runner._load_turn_history (#114266). Cleared on /new.+ self._transcript_lag_streaks: Dict[str, int] = {}# Startup restore gate: while restart-interrupted sessions auto-resume, real inbound messages# queue instead of competing with the synthetic resume turns; drained after all resume tasks end.self._startup_restore_in_progress = Falsediff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.pyindex 8e14df26ec6..795db094679 100644--- a/gateway/run_turn_runner.py+++ b/gateway/run_turn_runner.py@@ -34,6 +34,10 @@ if TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)# Log-record parity with the origin module.logger = logging.getLogger("gateway.run")+# Consecutive turns a session's persisted transcript may lag its live cached history before+# _load_turn_history escalates the lag line from WARNING to ERROR (#114266: 11 days of WARNING).+_TRANSCRIPT_LAG_ESCALATION_TURNS = 3+# Exact refusals retained for older adapters/connectors without destination preflight.# Substring matching would also silence transient thread-resolution errors._CARD_DESTINATION_REFUSALS = {@@ -1557,16 +1561,27 @@ class TurnRunner:# #50502.if reused_cached_agent and getattr(agent, "session_id", None) == ctx.session_id:selected = _select_cached_agent_history(agent_history, getattr(agent, "_session_messages", None))+ # Consecutive lagging turns per session (cleared on /new): one lag is a blip, a streak+ # is the #114266 write outage and must escalate past a repeating WARNING.+ streaks = getattr(self._runner, "_transcript_lag_streaks", None)+ if streaks is None: # tests may build bare runners+ streaks = self._runner._transcript_lag_streaks = {}if selected is not agent_history:- logger.warning(+ streak = streaks[ctx.session_key] = streaks.get(ctx.session_key, 0) + 1+ log = logger.error if streak >= _TRANSCRIPT_LAG_ESCALATION_TURNS else logger.warning+ log("Persisted transcript lagged live cached history for "- "session %s (disk=%d, memory=%d); preserving live "- "conversation context (possible FTS write corruption)",- ctx.session_key, len(agent_history), len(selected),+ "session %s (disk=%d, memory=%d, consecutive_turns=%d); preserving live "+ "conversation context (possible FTS write corruption)%s",+ ctx.session_key, len(agent_history), len(selected), streak,+ "; state.db is not receiving this session's writes and needs operator attention"+ if streak >= _TRANSCRIPT_LAG_ESCALATION_TURNS else "",)# The live history bypassed _build_gateway_agent_history's cleanup — re-apply# the full canonicalization so no replay transform can slip through.agent_history = canonicalize_replay_history(selected)+ else:+ streaks.pop(ctx.session_key, None)# MEDIA paths already in history are excluded from this turn's extraction (compression-safe).return agent_history, observed_group_context, _collect_history_media_paths(agent_history)diff --git a/tests/gateway/test_cached_agent_history_guard.py b/tests/gateway/test_cached_agent_history_guard.pyindex 2ee152a6b65..5378f0f2629 100644--- a/tests/gateway/test_cached_agent_history_guard.py+++ b/tests/gateway/test_cached_agent_history_guard.py@@ -65,3 +65,35 @@ def test_select_cached_history_ignores_unmarked_ephemeral_scaffolding():]assert _select_cached_agent_history(persisted, live) is persisted+++def test_persistent_transcript_lag_escalates_to_error(caplog):+ """The 'Persisted transcript lagged live cached history' line repeated at WARNING for 11 days in+ #114266. A per-session streak of lagging turns escalates it to ERROR; a turn whose disk copy+ caught up resets the streak."""+ import logging+ from types import SimpleNamespace++ from gateway.run_turn_runner import _TRANSCRIPT_LAG_ESCALATION_TURNS, TurnRunner++ persisted = [{"role": "user", "content": "hello"}]+ live = [{"role": "user", "content": "hello", "_db_persisted": True},+ {"role": "assistant", "content": "not written"}]+ runner = SimpleNamespace()+ ctx = SimpleNamespace(history=persisted, channel_prompt=None, user_config=None,+ session_id="sid-1", session_key="agent:main:telegram:dm:1")+ turn = TurnRunner(runner, ctx)+ agent = SimpleNamespace(session_id="sid-1", _session_messages=live)++ with caplog.at_level(logging.WARNING, logger="gateway.run"):+ for _ in range(_TRANSCRIPT_LAG_ESCALATION_TURNS):+ history, _observed, _media = turn._load_turn_history(agent, reused_cached_agent=True)+ assert len(history) == len(live) # live context still preserved+ levels = [r.levelno for r in caplog.records if "lagged live cached history" in r.getMessage()]+ assert levels == [logging.WARNING] * (_TRANSCRIPT_LAG_ESCALATION_TURNS - 1) + [logging.ERROR]+ assert "consecutive_turns=%d" % _TRANSCRIPT_LAG_ESCALATION_TURNS in caplog.records[-1].getMessage()++ # Disk caught up: the streak resets, so the next lag starts again at WARNING.+ agent._session_messages = [dict(persisted[0], _db_persisted=True)]+ turn._load_turn_history(agent, reused_cached_agent=True)+ assert ctx.session_key not in runner._transcript_lag_streaks