The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test(agent): trim #119001 retry-exhaustion tests to two invariants
kshitijk4poor44af0c9faf10
diff --git a/tests/agent/test_retry_exhaustion_partial_retention.py b/tests/agent/test_retry_exhaustion_partial_retention.pyindex c30ec8e9935..be6529bcc28 100644--- a/tests/agent/test_retry_exhaustion_partial_retention.py+++ b/tests/agent/test_retry_exhaustion_partial_retention.py@@ -1,21 +1,23 @@-"""#119001: a 429 / network error that exhausts retries AFTER partial output was-delivered must retain that output instead of ending the turn error-only.+"""#119001: an API error that ends the turn AFTER partial output was delivered must+retain that output instead of ending the turn error-only, and must not persist the+dangling continuation trail.Repro: attempt 1 streams text then dies mid-stream (partial-stub path appends a``_length_continuation_fragment`` + nudge to ``messages``); the continuation-attempt 429s before the stream starts and every retry re-hits the limit.-``build_api_request`` resets ``_current_streamed_assistant_text`` per attempt,-so the only record of the delivered text is the fragment rows — the terminal-builders below must recover it, flag ``partial``, and keep ``final_response``-distinct from ``error`` (the gateway/desktop retention contract).+attempt then fails before the stream starts. ``build_api_request`` resets+``_current_streamed_assistant_text`` per attempt, so the only record of the+delivered text is the fragment rows. Both terminal builders are driven through+``settle_unrecovered_error`` so the ``current_turn_user_idx`` threading is real."""from __future__ import annotations+from types import SimpleNamespace+from unittest.mock import patch++import pytest+from agent.error_classifier import classify_api_error-from agent.turn_recovery import (- max_retries_exhausted_result,- nonretryable_client_error_result,-)+from agent.turn_api_error import settle_unrecovered_errorclass _Agent:@@ -26,6 +28,11 @@ class _Agent:model = "m"base_url = "https://openrouter.ai/api/v1"_current_streamed_assistant_text = ""+ _fallback_index = 0++ @staticmethod+ def _strip_think_blocks(text):+ return textdef _summarize_api_error(self, error):return str(error)@@ -36,6 +43,9 @@ class _Agent:def _try_activate_fallback(self, **_kw):return False+ def _try_recover_primary_transport(self, *_a, **_kw):+ return False+def __getattr__(self, name):return lambda *args, **kwargs: None@@ -51,90 +61,41 @@ PARTIAL = "Here is the first half of the report, already shown to the user."def _messages_with_fragment():return [+ {"role": "user", "content": "earlier turn"},+ {"role": "assistant", "content": "stale", "_length_continuation_fragment": True},{"role": "user", "content": "write a long report"},- {- "role": "assistant",- "content": PARTIAL,- "_length_continuation_fragment": True,- },- {- "role": "user",- "content": "continue where you left off",- "_length_continuation_nudge": True,- },+ {"role": "assistant", "content": PARTIAL, "_length_continuation_fragment": True},+ {"role": "user", "content": "continue where you left off", "_length_continuation_nudge": True},]-def _exhausted(messages, agent=None):- error = _Http(429, "HTTP 429: RequestBurstTooFast — slow down traffic growth")- classified = classify_api_error(error, provider="openrouter", model="m")- assert classified.reason.value == "rate_limit"- return max_retries_exhausted_result(- agent or _Agent(), error, classified, max_retries=3, is_rate_limited=True,- error_msg=str(error).lower(), api_kwargs=None, api_messages=[], messages=messages,- conversation_history=None, api_call_count=3, approx_tokens=10, provider="openrouter",- base_url="https://openrouter.ai/api/v1", model="m",- )---def test_exhausted_429_keeps_delivered_partial():- result = _exhausted(_messages_with_fragment())- assert result.get("partial") is True- assert PARTIAL in result["final_response"]- # Gateway retention contract: final must differ from the error string.- assert result["final_response"].strip() != str(result["error"]).strip()- assert result["failure_reason"] == "rate_limit"- assert result["failed"] is True---def test_exhausted_429_without_partial_is_unchanged():- result = _exhausted([])- assert "partial" not in result- assert "/retry" in result["final_response"]- assert result["failure_reason"] == "rate_limit"---def test_exhausted_429_live_accumulator_counts_as_delivered():- agent = _Agent()- agent._current_streamed_assistant_text = "fresh streamed text"- result = _exhausted([], agent=agent)- assert result.get("partial") is True- assert "fresh streamed text" in result["final_response"]---def test_whitespace_only_fragment_is_not_partial():[email protected]("status, message", [+ (429, "HTTP 429: RequestBurstTooFast — slow down traffic growth"), # max_retries_exhausted_result+ (401, "HTTP 401: invalid api key"), # nonretryable_client_error_result+])+def test_terminal_error_keeps_partial_and_collapses_this_turns_trail(status, message):messages = _messages_with_fragment()- messages[1] = dict(messages[1], content=" ")- result = _exhausted(messages)- assert "partial" not in result---def test_nonretryable_terminal_keeps_delivered_partial():- error = _Http(400, "HTTP 400: Bad request")+ error = _Http(status, message)classified = classify_api_error(error, provider="openrouter", model="m")- result = nonretryable_client_error_result(- _Agent(), error, classified, status_code=400, api_kwargs=None, api_messages=[],- messages=_messages_with_fragment(), conversation_history=None, api_call_count=1,- approx_tokens=10, provider="openrouter",- base_url="https://openrouter.ai/api/v1", model="m",- )- assert result.get("partial") is True- assert PARTIAL in result["final_response"]+ retry = SimpleNamespace(copilot_stale_cred_retry_attempted=False, primary_recovery_attempted=True)+ with patch("agent.conversation_loop._is_copilot_provider", lambda a: False), \+ patch("agent.turn_recovery_autorecover.auto_recover_after_exhaustion", lambda *a, **k: None):+ verdict = settle_unrecovered_error(+ _Agent(), api_error=error, classified=classified, _retry=retry, status_code=status,+ error_msg=message.lower(), is_context_length_error=False, is_rate_limited=status == 429,+ _is_zai_coding_overload=False, _provider="openrouter", _base="https://openrouter.ai/api/v1",+ _model="m", messages=messages, api_messages=[], api_kwargs=None, active_system_prompt="",+ conversation_history=None, approx_tokens=10, retry_count=3, max_retries=3,+ compression_attempts=0, api_call_count=3, current_turn_user_idx=2,+ )+ assert verdict.action == "return"+ result = verdict.result+ assert result.get("partial") is True and result["failed"] is True+ assert PARTIAL in result["final_response"] and "stale" not in result["final_response"]+ # Gateway retention contract: final must differ from the error string.assert result["final_response"].strip() != str(result["error"]).strip()---def test_exhausted_429_collapses_continuation_trail_into_one_assistant_row():- messages = _messages_with_fragment()- error = _Http(429, "HTTP 429: RequestBurstTooFast — slow down traffic growth")- classified = classify_api_error(error, provider="openrouter", model="m")- result = max_retries_exhausted_result(- _Agent(), error, classified, max_retries=3, is_rate_limited=True,- error_msg=str(error).lower(), api_kwargs=None, api_messages=[], messages=messages,- conversation_history=None, api_call_count=3, approx_tokens=10, provider="openrouter",- base_url="https://openrouter.ai/api/v1", model="m", current_turn_user_idx=0,- )- # No dangling synthetic nudge: the turn persists as user -> one assistant row.- assert [m["role"] for m in messages] == ["user", "assistant"]- assert messages[1]["content"] == PARTIAL- assert not any(m.get("_length_continuation_nudge") for m in messages)- assert result.get("partial") is True and PARTIAL in result["final_response"]+ # No dangling synthetic nudge: this turn persists as user -> one assistant row;+ # the earlier turn (before current_turn_user_idx) is left untouched.+ assert [m["role"] for m in messages] == ["user", "assistant", "user", "assistant"]+ assert messages[1]["content"] == "stale"+ assert (messages[3]["content"], messages[3]["finish_reason"]) == (PARTIAL, "error")