The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(conversation_loop): prune dead vision-strip fallback; harden output-cap retry tests
BobClawblaw04098e2b5f98
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 942dc3c62dd..72d9289a323 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,9 +12,13 @@`compression_exhausted=True`.The fix adds `_compress_context()` to the output-cap retry path so the compressor- drops the middle window, freeing ~50% of tokens in one pass. If compression makes- ≥5% savings, the session continues; otherwise vision payloads are stripped, and- if that fails too, the session ends with a clear "cannot compress further" message.+ drops the middle window, freeing a large fraction of tokens in one pass. If+ compression makes ≥5% token savings (or drops the message count), the session+ continues under the ceiling. If compression cannot reduce the request, the loop+ retries with the reduced `max_tokens` and, if the error keeps recurring,+ terminates through the existing max-attempts guard with a clear "cannot compress+ further" message — it no longer spins on `max_tokens` alone. Compression failures+ stay non-fatal and fall back to retrying on `max_tokens` alone.Affected providers: vLLM, DashScope (Qwen), OpenRouter, LM Studio, Anthropic.diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex e5f6c20e0db..4f4e57f8bf1 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -4788,19 +4788,10 @@ def run_conversation(agent, messages, conversation_history)new_tokens = estimate_messages_tokens_rough(messages)- approx_tokens = new_tokensif len(messages) < original_len:agent._buffer_status(COMPRESSION_RETRY_MESSAGES_STATUS_TEMPLATE.format(before=original_len, after=len(messages)))elif new_tokens > 0 and new_tokens < original_tokens * 0.95:agent._buffer_status(COMPRESSION_RETRY_TOKENS_STATUS_TEMPLATE.format(before=original_tokens, after=new_tokens))- elif agent._try_strip_image_parts_from_tool_messages(- api_messages,- remember_model=False,- ):- agent._buffer_status(- "📐 Compression could not reduce the request further — "- "removed retained vision payloads and retrying..."- )except Exception:# Compression must never turn an output-cap error# fatal — fall through and retry on max_tokens alone.diff --git a/docs/reports/output_cap_compression_fix.md b/docs/reports/output_cap_compression_fix.mdindex 8ecdd68e283..8a5b7218c97 100644--- a/docs/reports/output_cap_compression_fix.md+++ b/docs/reports/output_cap_compression_fix.md@@ -79,9 +79,11 @@ is actually compressed before retrying:1. The compressor drops the middle window, freeing a large fraction of tokensin a single pass.-2. If compression made real progress, the session continues under the ceiling.-3. If compression could not reduce further, vision payloads are stripped and it- retries again.+2. If compression made real progress (message count dropped, or ≥5% token+ savings), the session continues under the ceiling.+3. If compression could not reduce the request, the loop retries with the already+ reduced `max_tokens` and, if the error keeps recurring, terminates through the+ existing max-attempts guard with a clear "cannot compress further" message.4. Compression failures are non-fatal: if anything goes wrong duringcompression, the code falls back to retrying on `max_tokens` alone. Theexisting max-attempts guard still bounds the retry loop, so it cannot spin@@ -90,12 +92,19 @@ is actually compressed before retrying:## Verification- Both output-cap retry regression tests pass:- `test_output_cap_retry_uses_provider_available_out` and+ `test_output_cap_retry_uses_provider_available_out`, and`test_output_cap_retry_with_large_api_only_content`.-- Full `tests/run_agent/test_run_agent.py`: 232 passed, 1 failed — and the 1- failure (`test_interruptible_anthropic_interrupt_never_closes_shared_client`)- is a pre-existing environment issue (missing `anthropic` package), failing- identically on a clean base without this change.+- New `test_output_cap_retry_triggers_compression_and_recovers` locks in the+ fix and asserts that the retry sends the compressed history on the wire (not+ the original oversized request) and that `context_length` is untouched.+- New `test_output_cap_retry_compression_no_progress_terminates_bounded` locks+ in that a zero-progress compression terminates via the max-attempts guard+ rather than spinning forever.+- Full `tests/run_agent/test_run_agent.py`: 235 passed with the optional+ `anthropic` package installed. (Without it, the single+ `test_interruptible_anthropic_interrupt_never_closes_shared_client` fails on+ an ``ImportError: The 'anthropic' package is required`` — an environment+ issue, unrelated to this change.)- `ruff check` passes on both modified files.## Impactdiff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex b77ee236aed..473e869faf7 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -4212,9 +4212,70 @@ class TestRunConversation:# The retry honored the reduced max_tokens (available_out - 64).second_call = agent.client.chat.completions.create.call_args_list[1].kwargsassert second_call["max_tokens"] <= 936+ # LOCK IN THE FIX: the retry must actually SEND the compressed history+ # (the 1-message payload from _compress_context + its new system+ # prompt), not the original multi-message window. Without this, the+ # output-cap retry would call the compressor but re-transmit the same+ # oversized request forever.+ second_messages = second_call.get("messages", [])+ assert second_messages[-1].get("content") == "hello"+ assert len(second_messages) == 2+ assert second_messages[0]["role"] == "system"# context_length was NOT mutated by an output-cap error.assert agent.context_compressor.context_length == 200_000+ def test_output_cap_retry_compression_no_progress_terminates_bounded(self, agent):+ """Regression: when the compressor cannot reduce the request (zero+ progress AND no images to strip), the output-cap retry must terminate+ via the max-attempts guard instead of spinning forever.++ The compressor is injected to return the input unchanged (same list+ object, no lock-defer — just zero progress), and the provider keeps+ rejecting, so the only correct outcome is a bounded+ ``compression_exhausted`` failure, not an unbounded loop.+ """+ self._setup_agent(agent)+ agent.api_mode = "chat_completions"+ agent.provider = "openrouter"+ agent.model = "some/model"+ agent.max_tokens = 65_536+ agent.compression_enabled = True+ agent.context_compressor.context_length = 200_000+ agent.context_compressor.should_compress = MagicMock(return_value=True)++ error_msg = (+ "max_tokens: 65536 > context_window: 200000 "+ "- input_tokens: 199000 = available_tokens: 1000"+ )++ def _rejecting(*args, **kwargs):+ exc = Exception(error_msg)+ exc.status_code = 400+ exc.code = 400+ raise exc++ # The provider never recovers (side effect raises on every call).+ agent.client.chat.completions.create.side_effect = _rejecting++ def _no_progress(messages, system_message, **kwargs):+ # Compressor runs but cannot shrink the request: no-op, same list.+ return messages, system_message++ with (+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ patch.object(agent.context_compressor, "update_model"),+ patch.object(agent, "_compress_context", side_effect=_no_progress),+ ):+ result = agent.run_conversation("hello")++ assert result["completed"] is False+ assert result.get("compression_exhausted") is True+ # Terminated in a bounded number of API calls (default max attempts=3+ # => ~4 create calls), NOT an unbounded retry loop.+ assert agent.client.chat.completions.create.call_count <= 6+