The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): carry compression_exhausted bit; scope overflow terminal to context_overflow
ca-shrimp3b0e81459b5a
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 3962e2902cc..ab6c0c49a79 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -3279,14 +3279,15 @@ class _StreamingCall(StreamingWaitMonitor):from agent.error_classifier import classify_api_error_cls = classify_api_error(error, provider=str(getattr(self.agent, "provider", "") or ""), model=str(getattr(self.agent, "model", "") or ""))- # #106260: a context-overflow / payload-too-large error after partial delivery must NOT- # seed a continuation stub with the recovered text — the transcript already cannot fit- # (compression failed or protect_last_n covers it), and appending tens of KB only makes- # every later request larger. Return an EMPTY stub marked terminal: the loop ends the- # turn via the recovery contract instead of continuing into the same overflow.- if _cls is not None and _cls.reason in (- FailoverReason.context_overflow, FailoverReason.payload_too_large,- ):+ # #106260: a context-overflow error after partial delivery must NOT seed a+ # continuation stub with the recovered text — the transcript already cannot fit+ # (compression failed or protect_last_n covers it), and appending tens of KB only+ # makes every later request larger. Return an EMPTY stub marked terminal: the loop+ # ends the turn via the recovery contract instead of continuing into the same+ # overflow. Scope is deliberately context_overflow ONLY: payload_too_large (413)+ # has its own byte-scored recovery owner (turn_overflow._recover_payload_too_large,+ # #88960/#47339) that must not be bypassed (review P1, andrexibiza).+ if _cls is not None and _cls.reason == FailoverReason.context_overflow:logger.warning("Partial stream ended on a context-overflow error after %s chars; ""NOT seeding a continuation stub (transcript is already over budget): %s",diff --git a/agent/turn_truncation.py b/agent/turn_truncation.pyindex 8e3ccfc42bf..ca2b3ef03c0 100644--- a/agent/turn_truncation.py+++ b/agent/turn_truncation.py@@ -73,11 +73,12 @@ def normalize_response_for_agent(agent: Any, response: Any) -> Any:def partial_result(messages: List[Dict[str, Any]], api_call_count: int, final_response: str,- error: Optional[str] = None, *, failed: bool = False,+ error: Optional[str] = None, *, failed: bool = False, compression_exhausted: bool = False,) -> Dict[str, Any]:"""Typed incomplete-turn result (``partial`` unless ``failed``); ``error`` defaults to- ``final_response``."""- return {+ ``final_response``. ``compression_exhausted`` carries the #98722 typed bit the gateway+ consumes to reset/move future input to a clean session (see run_turn.py)."""+ result = {"final_response": final_response,"messages": messages,"api_calls": api_call_count,@@ -85,6 +86,9 @@ def partial_result(("failed" if failed else "partial"): True,"error": final_response if error is None else error,}+ if compression_exhausted:+ result["compression_exhausted"] = True+ return result@dataclass@@ -129,16 +133,20 @@ class _Trunc(TruncationVerdict):def end_turn(self, final_response: str, error: Optional[str] = None, *,result_messages: Optional[List[Dict[str, Any]]] = None, cleanup: bool = True,- failed: bool = False,+ failed: bool = False, compression_exhausted: bool = False,) -> TruncationVerdict:- """Persist and end the turn as partial (or ``failed``)."""+ """Persist and end the turn as partial (or ``failed``).++ ``compression_exhausted`` forwards the #98722 typed bit so the gateway can+ move future input off a bloated session (run_turn.py consumes it).+ """agent = self.agentif cleanup:agent._cleanup_task_resources(self.effective_task_id)agent._persist_session(self.messages, self.conversation_history)return self.done("return", partial_result(self.messages if result_messages is None else result_messages, self.api_call_count,- final_response, error, failed=failed,+ final_response, error, failed=failed, compression_exhausted=compression_exhausted,))@property@@ -346,10 +354,14 @@ def recover_from_truncation("budget).",force=True,)+ # Carry the #98722 typed exhaustion bit so the gateway resets/moves future+ # input to a clean session instead of leaving this bloated one authoritative+ # for the next turn (review P1, andrexibiza).return st.end_turn(_CONTEXT_OVERFLOW_PARTIAL_FINAL,error=_CONTEXT_OVERFLOW_PARTIAL_FINAL,failed=True,+ compression_exhausted=True,)_trunc_msg = normalize_response_for_agent(agent, response)diff --git a/tests/run_agent/test_overflow_partial_terminal_106260.py b/tests/run_agent/test_overflow_partial_terminal_106260.pyindex 5c751a5f22c..0b505cc560f 100644--- a/tests/run_agent/test_overflow_partial_terminal_106260.py+++ b/tests/run_agent/test_overflow_partial_terminal_106260.py@@ -86,6 +86,36 @@ class TestOverflowTerminalStub:assert response.choices[0].message.content is None+ @patch("run_agent.AIAgent._create_request_openai_client")+ @patch("run_agent.AIAgent._close_request_openai_client")+ def test_payload_too_large_partial_is_not_made_terminal(+ self, _mock_close, mock_create, monkeypatch,+ ):+ """Review P1 (andrexibiza): payload_too_large (413) has its own byte-scored+ recovery owner and must NOT be collapsed into the context-overflow terminal+ contract — the partial keeps its normal continuation stub."""+ def _overflowing_stream():+ yield _make_stream_chunk(content="some media-heavy partial output ...")+ raise RuntimeError(+ "Request payload too large (413): 5MB exceeds the 4MB limit"+ )++ mock_client = MagicMock()+ mock_client.chat.completions.create.side_effect = lambda *a, **kw: _overflowing_stream()+ mock_create.return_value = mock_client++ agent = _make_agent()+ agent._current_streamed_assistant_text = "some media-heavy partial output ..."++ monkeypatch.setenv("HERMES_STREAM_RETRIES", "0")+ response = agent._interruptible_streaming_api_call({})++ assert response.id == PARTIAL_STREAM_STUB_ID+ assert getattr(response, "_overflow_terminal", False) is False+ # The recovered text is preserved for the normal continuation path.+ assert response.choices[0].message.content == "some media-heavy partial output ..."++class TestRecoverFromTruncationOverflowTerminal:def _mock_agent(self):agent = MagicMock()@@ -127,6 +157,9 @@ class TestRecoverFromTruncationOverflowTerminal:result = verdict.result or {}assert result.get("failed") is Trueassert result.get("final_response") == _CONTEXT_OVERFLOW_PARTIAL_FINAL+ # #98722 typed bit: the gateway consumes this to reset/move future input+ # to a clean session instead of leaving the bloated one authoritative.+ assert result.get("compression_exhausted") is True# No fragment or nudge was appended to the transcript.assert result.get("messages") == []