The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): consolidate uncompressed-overflow guard to one warn site + re-arm
kshitijk4poorcef999c5cffb
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 44f78ac5e6b..951b8747010 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -2766,24 +2766,27 @@ def run_conversation(int(getattr(_compressor, "threshold_tokens", 0) or 0),)elif not agent.compression_enabled and len(messages) > 1:- # Uncompressed session guard (#89297) - Defense in Depth:- # If mid-turn tool results expand the context beyond model limits- # while compression is disabled, warn the operator in-loop.+ # Uncompressed session guard (#89297): compression is disabled, so+ # nothing shrinks a growing session. Reuse the unconditionally+ # computed request estimate (zero marginal cost — this site runs+ # before every provider request, covering turn-start AND mid-turn+ # tool-result growth) and surface a deduped, actionable warning+ # when the request exceeds the model context window. The dedup is+ # re-armed by the turn-context preflight once the session is back+ # under the window (manual /compress works with compression+ # disabled), so the guard warns again on a later re-overflow.+ # context_compressor always exists (agent_init constructs it even+ # when compression is disabled) and its context_length property+ # hard-floors at a positive default — no metadata re-resolution+ # needed here._ctx_len = getattr(getattr(agent, "context_compressor", None), "context_length", None)- if not isinstance(_ctx_len, int) or _ctx_len <= 0:- try:- from agent.model_metadata import get_model_context_length-- _ctx_len = get_model_context_length(- agent.model,- getattr(agent, "base_url", "") or "",- provider=getattr(agent, "provider", "") or "",- )- except Exception:- _ctx_len = None- if _ctx_len and request_pressure_tokens > _ctx_len:+ if (+ isinstance(_ctx_len, int)+ and _ctx_len > 0+ and request_pressure_tokens > _ctx_len+ ):_warn_fn = getattr(agent, "_warn_uncompressed_context_overflow", None)diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 9128c75e5f8..df8969a6663 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -1166,46 +1166,54 @@ def build_turn_context(elif not agent.compression_enabled:# Uncompressed session guard (#89297): when compression is explicitly# disabled, sessions can grow past the model's context window across- # hundreds of messages without compression to shrink them.- # Run a cheap character pre-check before computing rough tokens.- _raw_chars = sum(- len(m.get("content") or "") for m in messages if isinstance(m, dict)+ # hundreds of messages with nothing to shrink them. The warning itself+ # fires from the conversation loop's pre-API site, which reuses the+ # unconditionally computed request estimate at zero marginal cost and+ # covers both turn-start and mid-turn growth (every provider request+ # passes through it). Here we only RE-ARM the dedup once the session+ # is back under the window, so the guard can warn again after the+ # user compacts (/compress with force=True works with compression+ # disabled) and the context later regrows past the limit.+ _ctx_len = getattr(+ getattr(agent, "context_compressor", None), "context_length", None)- if _raw_chars > 20_000:- _uncompressed_tokens = estimate_request_tokens_rough(- messages,- system_prompt=active_system_prompt or "",- tools=agent.tools or None,- )- _ctx_len = getattr(- getattr(agent, "context_compressor", None), "context_length", None- )- if not isinstance(_ctx_len, int) or _ctx_len <= 0:- try:- from agent.model_metadata import get_model_context_length-- _ctx_len = get_model_context_length(- agent.model,- getattr(agent, "base_url", "") or "",- provider=getattr(agent, "provider", "") or "",- )- except Exception:- _ctx_len = None- if _ctx_len and _uncompressed_tokens > _ctx_len:- _warn_fn = getattr(- agent, "_warn_uncompressed_context_overflow", None+ if isinstance(_ctx_len, int) and _ctx_len > 0:+ _raw_chars = 0+ for _m in messages:+ if not isinstance(_m, dict):+ continue+ _c = _m.get("content")+ if isinstance(_c, str):+ _raw_chars += len(_c)+ elif _c:+ # Non-string, non-empty content (multimodal part lists,+ # dict payloads) defeats a char count — force the real+ # estimate by treating it as over-gate. None/"" (routine+ # assistant tool-call rows) contribute nothing.+ _raw_chars = _ctx_len + 1+ break+ # Cheap gate: a session whose raw text is under ~1/4 of the+ # window (4 chars/token upper bound) cannot be over it — skip+ # the estimator. Non-string (multimodal) content defeats a char+ # count, so any such message forces the real estimate.+ if _raw_chars <= _ctx_len:+ _clear_warn = getattr(+ agent, "_clear_context_overflow_warn", None)- if callable(_warn_fn):- _warn_fn(_uncompressed_tokens, _ctx_len)- else:- _emit_w = getattr(agent, "_emit_warning", None)- if callable(_emit_w):- _emit_w(- f"⚠️ Session context (~{_uncompressed_tokens:,} tokens) exceeds the "- f"model context window (~{_ctx_len:,} tokens) with compression disabled "- f"(compression.enabled: false). Use /compact to compress history or "- f"enable compression in config.yaml."- )+ if callable(_clear_warn):+ _clear_warn()+ else:+ _uncompressed_tokens = estimate_request_tokens_rough(+ messages,+ system_prompt=active_system_prompt or "",+ tools=agent.tools or None,+ )+ if _uncompressed_tokens <= _ctx_len:+ _clear_warn = getattr(+ agent, "_clear_context_overflow_warn", None+ )+ if callable(_clear_warn):+ _clear_warn()if _preflight_compressed:# Compression rebuilt the list (tail messages are fresh compactiondiff --git a/tests/agent/test_uncompressed_context_guardrail.py b/tests/agent/test_uncompressed_context_guardrail.pyindex c509c13460c..04a912d0bb5 100644--- a/tests/agent/test_uncompressed_context_guardrail.py+++ b/tests/agent/test_uncompressed_context_guardrail.py@@ -1,18 +1,35 @@-"""Unit tests for uncompressed context overflow guardrail (Issue #89297)."""+"""Uncompressed context overflow guardrail (#89297).++When compression is explicitly disabled (``compression.enabled: false``),+sessions can grow past the model context window with nothing to shrink them.+The conversation loop's pre-API site warns (deduped, actionable); the+turn-context preflight re-arms the dedup once the session is back under the+window so a later re-overflow warns again.++The fake binds the PRODUCTION ``_warn_uncompressed_context_overflow`` /+``_clear_context_overflow_warn`` methods so their dedup logic is actually+under test (not a reimplementation).+"""from __future__ import annotationsimport types-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock-import pytest--from agent.turn_context import TurnContext, build_turn_context+from agent.turn_context import TurnContext, build_turn_context # noqa: F401+from run_agent import AIAgentfrom tests.agent.test_turn_context import _FakeAgent, _buildclass _FakeUncompressedAgent(_FakeAgent):- """Agent stub with compression disabled (compression.enabled: False)."""+ """Agent stub with compression disabled, bound to the REAL warn methods."""++ # Production methods under test — bound from AIAgent so the dedup key+ # handling and message text cannot silently drift from what ships.+ _warn_uncompressed_context_overflow = (+ AIAgent._warn_uncompressed_context_overflow+ )+ _clear_context_overflow_warn = AIAgent._clear_context_overflow_warndef __init__(self, model="deepseek-v4-flash", context_length=10_000):super().__init__()@@ -27,21 +44,47 @@ class _FakeUncompressedAgent(_FakeAgent):last_prompt_tokens=-1,)- def _warn_uncompressed_context_overflow(self, preflight_tokens: int, context_length: int) -> None:- _warn_key = ("uncompressed_ctx_overflow", context_length)- if getattr(self, "_last_ctx_overflow_warn", None) != _warn_key:- self._last_ctx_overflow_warn = _warn_key- msg = (- f"⚠️ Session context (~{preflight_tokens:,} tokens) exceeds the model "- f"context window (~{context_length:,} tokens) with compression disabled "- f"(compression.enabled: false). Use /compact to compress history or "- f"enable compression in config.yaml."- )- self._emit_warning(msg)++def _oversized_history(n_turns: int = 10) -> list:+ large_turn = "Large context content " * 500 # ~2,500 tokens each+ history = []+ for i in range(n_turns):+ history.append({"role": "user", "content": f"Turn {i}: {large_turn}"})+ history.append({"role": "assistant", "content": f"Reply {i}: {large_turn}"})+ return history+++def test_production_warn_emits_once_and_dedups():+ """The real method warns once, then dedups identical overflows."""+ agent = _FakeUncompressedAgent(context_length=10_000)+ agent._emit_warning = MagicMock()++ agent._warn_uncompressed_context_overflow(15_000, 10_000)+ agent._warn_uncompressed_context_overflow(16_000, 10_000)++ agent._emit_warning.assert_called_once()+ msg = agent._emit_warning.call_args[0][0]+ assert "exceeds the model context window" in msg+ assert "compression.enabled: false" in msg+ assert "10,000 tokens" in msg+++def test_clear_rearms_the_warning():+ """After _clear_context_overflow_warn (session back under the window),+ a later re-overflow warns again."""+ agent = _FakeUncompressedAgent(context_length=10_000)+ agent._emit_warning = MagicMock()++ agent._warn_uncompressed_context_overflow(15_000, 10_000)+ agent._clear_context_overflow_warn()+ agent._warn_uncompressed_context_overflow(15_500, 10_000)++ assert agent._emit_warning.call_count == 2def test_uncompressed_session_within_limits_emits_no_warning():agent = _FakeUncompressedAgent(context_length=128_000)+ agent._emit_warning = MagicMock()history = [{"role": "user", "content": "hello"},{"role": "assistant", "content": "hi there"},@@ -51,21 +94,90 @@ def test_uncompressed_session_within_limits_emits_no_warning():agent._emit_warning.assert_not_called()-def test_uncompressed_session_exceeding_context_limit_warns():- # Model context length is 10,000 tokens (~40,000 chars)- agent = _FakeUncompressedAgent(context_length=10_000)-- # Construct an oversized uncompressed history of ~15,000 tokens (>60,000 chars)- large_turn = "Large context content " * 500 # ~2,500 tokens- history = []- for i in range(10):- history.append({"role": "user", "content": f"Turn {i}: {large_turn}"})- history.append({"role": "assistant", "content": f"Reply {i}: {large_turn}"})+def test_preflight_rearm_clears_dedup_when_back_under_window():+ """The turn-context preflight re-arms the dedup once the session fits+ again (e.g. after a manual /compress), so growth past the window later+ warns a second time."""+ agent = _FakeUncompressedAgent(context_length=128_000)+ agent._emit_warning = MagicMock()+ # Simulate a previously fired warning.+ agent._last_ctx_overflow_warn = ("uncompressed_ctx_overflow", 128_000)+ history = [+ {"role": "user", "content": "hello"},+ {"role": "assistant", "content": "hi there"},+ ]tctx = _build(agent, conversation_history=history)assert isinstance(tctx, TurnContext)++ # Preflight cleared the dedup — the next overflow warns again.+ assert agent._last_ctx_overflow_warn is None+ agent._warn_uncompressed_context_overflow(200_000, 128_000)agent._emit_warning.assert_called_once()- warning_msg = agent._emit_warning.call_args[0][0]- assert "exceeds the model context window" in warning_msg- assert "compression.enabled: false" in warning_msg- assert "10,000 tokens" in warning_msg+++def test_preflight_does_not_rearm_while_still_over_window():+ """While the session is still over the window, the dedup must survive+ the preflight (no per-turn warn spam)."""+ agent = _FakeUncompressedAgent(context_length=10_000)+ agent._emit_warning = MagicMock()+ agent._last_ctx_overflow_warn = ("uncompressed_ctx_overflow", 10_000)++ tctx = _build(agent, conversation_history=_oversized_history())+ assert isinstance(tctx, TurnContext)++ assert agent._last_ctx_overflow_warn == ("uncompressed_ctx_overflow", 10_000)+ agent._emit_warning.assert_not_called()+++def test_multimodal_content_forces_real_estimate_in_rearm_gate():+ """List (multimodal) content defeats a char count; the pre-check must+ treat it as over-gate so the real estimator decides. A tiny multimodal+ session is still under the window, so the dedup is re-armed."""+ agent = _FakeUncompressedAgent(context_length=128_000)+ agent._emit_warning = MagicMock()+ agent._last_ctx_overflow_warn = ("uncompressed_ctx_overflow", 128_000)++ history = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "look at this"},+ {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}},+ ],+ },+ {"role": "assistant", "content": "looking"},+ ]+ tctx = _build(agent, conversation_history=history)+ assert isinstance(tctx, TurnContext)+ assert agent._last_ctx_overflow_warn is None+++def test_none_content_tool_call_rows_do_not_defeat_cheap_gate():+ """Assistant tool-call rows routinely carry content=None; they must+ count as zero chars (NOT force the estimator) so the cheap gate keeps+ its value in ordinary tool-using sessions. Regression for the salvage+ follow-up's first draft, where `None` hit the over-gate branch."""+ from unittest.mock import patch as _patch++ agent = _FakeUncompressedAgent(context_length=128_000)+ agent._emit_warning = MagicMock()+ agent._last_ctx_overflow_warn = ("uncompressed_ctx_overflow", 128_000)++ history = [+ {"role": "user", "content": "run the tool"},+ {"role": "assistant", "content": None,+ "tool_calls": [{"id": "c1", "function": {"name": "t", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "c1", "content": "small result"},+ {"role": "assistant", "content": "done"},+ ]+ with _patch(+ "agent.turn_context.estimate_request_tokens_rough"+ ) as mock_est:+ tctx = _build(agent, conversation_history=history)++ assert isinstance(tctx, TurnContext)+ # Cheap gate decided (tiny session, under window): estimator never ran,+ # and the dedup was still re-armed via the raw-chars branch.+ mock_est.assert_not_called()+ assert agent._last_ctx_overflow_warn is None