The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): narrow #69078 image-corrupt recovery to the classifier route
Sora-blueskyd61411d131a0
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex d6832ae4897..344f23f976d 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -4892,11 +4892,7 @@ def run_conversation(# history). Shrinking corrupt bytes doesn't help, so strip the# image parts and retry once instead of routing through the# shrink path above. See issue #69078.- if (- classified.reason == FailoverReason.image_corrupt- and not _retry.stripped_images_this_turn- ):- _retry.stripped_images_this_turn = True+ if classified.reason == FailoverReason.image_corrupt:_imgs_removed = _strip_images_from_messages(messages)if isinstance(api_messages, list):_imgs_removed = _strip_images_from_messages(api_messages) or _imgs_removed@@ -4913,34 +4909,6 @@ def run_conversation("strip; surfacing original error.")- # Generic strip-and-retry fallback: any other non-retryable- # 400 whose outgoing request still contains image parts.- # Providers invent new image-rejection wordings faster than- # we can catalogue them (this is exactly what bit us in- # issue #69078 — an xAI corruption message that matched- # none of the patterns above and permanently bricked the- # session). Rather than chase every wording, treat "400 +- # non-retryable + image parts present" as reason enough to- # try once without the images before giving up. One-shot per- # attempt via the same guard as the image-corrupt branch- # above so this never loops.- if (- status_code == 400- and not classified.retryable- and not _retry.stripped_images_this_turn- ):- _retry.stripped_images_this_turn = True- _imgs_removed = _strip_images_from_messages(messages)- if isinstance(api_messages, list):- _imgs_removed = _strip_images_from_messages(api_messages) or _imgs_removed- if _imgs_removed:- agent._vprint(- f"{agent.log_prefix}⚠️ Non-retryable 400 with image content in "- f"the request — stripped images from history and retrying...",- force=True,- )- continue-# Anthropic OAuth subscription rejected the 1M-context beta# header ("long context beta is not yet available for this# subscription"). Disable the beta for the rest of thisdiff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex 09c176a448d..7dd31e41c58 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -296,10 +296,16 @@ _IMAGE_TOO_LARGE_PATTERNS = [# (FailoverReason.image_corrupt), never to the shrink path.## xAI wording: {"code":"invalid-argument","error":"...Invalid PNG image."}+# xAI has a second wording for the same failure class depending on where+# the truncation lands: "Invalid PNG image." for aligned truncation,+# "base64 string of provided image cannot be decoded" for unaligned+# truncation (confirmed by the issue reporter — same root cause, two wire+# messages).# See: https://github.com/NousResearch/hermes-agent/issues/69078_IMAGE_CORRUPT_PATTERNS = ["invalid png image","invalid jpeg image",+ "base64 string of provided image cannot be decoded",]# Providers that follow the OpenAI spec strictly require tool messagediff --git a/agent/turn_retry_state.py b/agent/turn_retry_state.pyindex 4111eecced0..49790c6528c 100644--- a/agent/turn_retry_state.py+++ b/agent/turn_retry_state.py@@ -61,7 +61,6 @@ class TurnRetryState:native_compaction_reject_retry_attempted: bool = Falseimage_shrink_retry_attempted: bool = Falsemultimodal_tool_content_retry_attempted: bool = False- stripped_images_this_turn: bool = Falseoauth_1m_beta_retry_attempted: bool = Falsellama_cpp_grammar_retry_attempted: bool = Falsediff --git a/tests/agent/test_turn_retry_state.py b/tests/agent/test_turn_retry_state.pyindex ab117b619a8..a182f177957 100644--- a/tests/agent/test_turn_retry_state.py+++ b/tests/agent/test_turn_retry_state.py@@ -26,7 +26,6 @@ EXPECTED_FIELDS = {"native_compaction_reject_retry_attempted","image_shrink_retry_attempted","multimodal_tool_content_retry_attempted",- "stripped_images_this_turn","oauth_1m_beta_retry_attempted","llama_cpp_grammar_retry_attempted","primary_recovery_attempted",diff --git a/tests/run_agent/test_69078_image_corrupt_recovery.py b/tests/run_agent/test_69078_image_corrupt_recovery.pyindex 5c11bb11ee4..07080f076b2 100644--- a/tests/run_agent/test_69078_image_corrupt_recovery.py+++ b/tests/run_agent/test_69078_image_corrupt_recovery.py@@ -6,28 +6,45 @@ the existing image-error pattern lists matched that wording, so the turnaborted as non-retryable and the session was permanently bricked (nofurther image-bearing turn could ever succeed).-Two independent pieces are locked in here:+The fix is deliberately narrow (see review history below): only a+recognized corruption wording routes to strip-and-retry.1. agent/error_classifier.py: xAI's "Invalid PNG image." wordingclassifies as FailoverReason.image_corrupt — a new reason distinctfrom image_too_large, because shrinking corrupt bytes can't fix them.- It must NOT be routed to the shrink path.- 2. The generic strip-and-retry fallback: ANY non-retryable 400 whose- outgoing request still contains image parts gets one strip-and-retry- attempt, even for a wording nobody has catalogued yet. This is the- un-brick-generically half of the fix — it doesn't require enumerating- every provider's phrasing.--Both recovery paths share a single one-shot-per-attempt guard-(TurnRetryState.stripped_images_this_turn) so at most one strip happens-per attempt regardless of which branch fires.+ It must NOT be routed to the shrink path, and it takes precedence+ over image_too_large when a message trips both pattern lists.+ 2. agent/conversation_loop.py: the image_corrupt branch strips image+ parts via the existing _strip_images_from_messages helper and+ retries once.++An earlier revision of this fix also shipped a generic fallback — "any+non-retryable 400 with image parts present strips and retries" — without+requiring a recognized wording. Review (Sol xhigh) correctly flagged this+as too destructive: unrelated non-retryable 400s (bad tool schema,+unsupported parameter, billing, content policy) that merely happen to+carry image parts would also get their vision history silently erased and+retried, degrading sessions that were never bricked in the first place.+That branch was reverted; only the classifier-routed image_corrupt path+remains. Future provider wordings get added to _IMAGE_CORRUPT_PATTERNS+(a known-string addition) rather than reintroducing a blanket net.++No TurnRetryState guard is needed for the surviving branch: retrying only+happens when _strip_images_from_messages actually removed something, and+it removes every image_url/image/input_image part from the request in one+pass. A second image_corrupt hit on the retried (now text-only) request+finds nothing left to strip, so the branch reports no progress and falls+through to the normal error path — no separate one-shot flag required."""from __future__ import annotations+import copy+from types import SimpleNamespace+from unittest.mock import MagicMock, patch+from agent.error_classifier import FailoverReason, classify_api_errorfrom agent.message_sanitization import _strip_images_from_messages-from agent.turn_retry_state import TurnRetryStateclass _FakeApiError(Exception):@@ -59,6 +76,19 @@ class TestImageCorruptClassification:result = classify_api_error(err, provider="xai", model="grok-5")assert result.reason == FailoverReason.image_corrupt+ def test_xai_unaligned_truncation_wording_classifies_as_image_corrupt(self):+ """xAI's second wire wording for the same corruption class — fires+ on unaligned base64 truncation instead of aligned (which returns+ "Invalid PNG image." instead). Same root cause, same recovery."""+ err = _FakeApiError(+ status_code=400,+ message='{"code":"invalid-argument","error":"The base64 string '+ 'of provided image cannot be decoded."}',+ )+ result = classify_api_error(err, provider="xai", model="grok-5")+ assert result.reason == FailoverReason.image_corrupt+ assert result.retryable is True+def test_does_not_route_to_shrink_path(self):"""image_corrupt must be a distinct reason from image_too_large —the retry loop only enters the shrink branch on an exact match, so@@ -73,58 +103,39 @@ class TestImageCorruptClassification:assert result.reason == FailoverReason.image_corruptdef test_unrelated_400_still_falls_through_to_format_error(self):+ """A non-retryable 400 with NO image-shaped wording at all must+ remain format_error — this is exactly the class of error the+ (reverted) generic fallback would have wrongly treated as+ image-related as long as the request happened to carry an image."""err = _FakeApiError(status_code=400, message="unsupported parameter: foo")result = classify_api_error(err, provider="xai", model="grok-5")assert result.reason == FailoverReason.format_errorassert result.retryable is False+ def test_compound_message_prefers_corrupt_over_too_large(self):+ """P3 (Sol xhigh): a body matching BOTH corruption and too-large+ wording must classify as image_corrupt, not image_too_large — the+ classifier checks _IMAGE_CORRUPT_PATTERNS first specifically so a+ provider that mentions size alongside corruption still routes to+ strip (shrink cannot repair corrupt bytes) rather than shrink."""+ err = _FakeApiError(+ status_code=400,+ message="Invalid PNG image. Note: image exceeds 8000 pixels.",+ )+ result = classify_api_error(err, provider="xai", model="grok-5")+ assert result.reason == FailoverReason.image_corrupt+ assert result.reason != FailoverReason.image_too_large-# ─── Generic strip-and-retry fallback trigger condition ──────────────────────+# ─── Strip helper (reused, not reimplemented) ────────────────────────────────-class TestGenericStripFallbackTriggerCondition:- """Mirrors the condition added at agent/conversation_loop.py: a- non-retryable 400 whose request still contains image parts gets one- strip-and-retry, regardless of the exact wording.- """- def test_novel_wording_falls_through_to_format_error_non_retryable(self):- """A wording nobody catalogued yet — the generic fallback's whole- point is that classification does NOT need to recognize it; only- (400, non-retryable, image parts present) matters."""- err = _FakeApiError(status_code=400, message="unrecognized image format")- result = classify_api_error(err, provider="some-new-provider", model="x")- assert result.reason == FailoverReason.format_error- assert result.retryable is False- # The trigger condition in conversation_loop.py is:- # status_code == 400 and not classified.retryable- # — both hold here, so the generic fallback fires as long as the- # outgoing request has image parts (checked separately, at retry- # time, via _strip_images_from_messages's return value).---# ─── TurnRetryState guard shape ───────────────────────────────────────────────---class TestStrippedImagesGuard:- def test_guard_defaults_false(self):- state = TurnRetryState()- assert state.stripped_images_this_turn is False-- def test_guard_is_shared_by_both_branches(self):- """Both the image_corrupt branch and the generic fallback branch key- off the same flag, so setting it once from either blocks the other —- proving at most one strip happens per attempt."""- state = TurnRetryState()- state.stripped_images_this_turn = True- assert state.stripped_images_this_turn is True-- def test_one_shot_semantics_mirror_the_loop(self):- """Simulates the loop's guard-and-strip sequence directly against- the real strip helper: first pass strips and would retry, a second- pass on the same attempt is blocked by the guard so it never loops- forever on a request that keeps failing after stripping."""- state = TurnRetryState()+class TestStripHelperBehaviorBackingTheBranch:+ """The image_corrupt branch in conversation_loop.py only retries when+ _strip_images_from_messages actually removed something — this is the+ mechanism that makes a separate one-shot guard unnecessary."""++ def test_strips_and_reports_progress(self):msgs = [{"role": "user","content": [@@ -132,23 +143,136 @@ class TestStrippedImagesGuard:{"type": "image_url", "image_url": {"url": "data:image/png;base64,corrupt"}},],}]-- def attempt_strip_and_retry() -> bool:- if state.stripped_images_this_turn:- return False # guard blocks a second attempt- state.stripped_images_this_turn = True- return _strip_images_from_messages(msgs)-- assert attempt_strip_and_retry() is True+ assert _strip_images_from_messages(msgs) is Trueassert msgs[0]["content"] == [{"type": "text", "text": "look"}]- # Second call on the same attempt: guard blocks it even though the- # (now text-only) messages have nothing left to strip anyway.- assert attempt_strip_and_retry() is False++ def test_second_pass_on_already_stripped_messages_reports_no_progress(self):+ """After a successful strip, a hypothetical repeat call (mirroring+ what a second image_corrupt hit on the retried request would see)+ finds nothing left to remove — this is what stops the branch from+ looping without needing a dedicated retry-state flag."""+ msgs = [{"role": "user", "content": [{"type": "text", "text": "look"}]}]+ assert _strip_images_from_messages(msgs) is Falsedef test_no_image_parts_present_nothing_to_strip(self):- """If the request has no image parts, the generic fallback's own- indicator (the strip helper's return value) is False, so the loop- must not treat this as a recovered attempt and must fall through to- the normal (non-retryable) error path."""msgs = [{"role": "user", "content": "just text, no images"}]assert _strip_images_from_messages(msgs) is False+++# ─── Integration: run_conversation recovers from a corrupt-image 400 ─────────+++def _mock_response(content: str):+ msg = SimpleNamespace(content=content, tool_calls=None)+ choice = SimpleNamespace(message=msg, finish_reason="stop")+ return SimpleNamespace(choices=[choice], model="grok-5", usage=None)+++def _make_agent():+ """Build a minimal AIAgent, mirroring the idiom in+ tests/run_agent/test_32646_fallback_429_after_timeout.py."""+ from run_agent import AIAgent++ with (+ patch("run_agent.get_tool_definitions", return_value=[]),+ patch("run_agent.check_toolset_requirements", return_value={}),+ patch("run_agent.OpenAI", return_value=MagicMock()),+ ):+ agent = AIAgent(+ api_key="fx", # unused — the OpenAI client is mocked below+ base_url="https://openrouter.ai/api/v1",+ provider="openrouter",+ model="x-ai/grok-5",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ )+ agent.client = MagicMock()+ return agent+++class TestRunConversationRecoversFromCorruptImage400:+ def test_strip_and_retry_succeeds_at_the_sequenced_provider_layer(self):+ """A prior turn's image part has gone corrupt on replay. The first+ attempt gets xAI's "Invalid PNG image." 400; the loop must strip+ the image and retry once, succeeding on the second attempt with the+ image no longer in the outgoing request.+ """+ history = [+ {+ "role": "user",+ "content": [+ {"type": "text", "text": "what's in this screenshot?"},+ {+ "type": "image_url",+ "image_url": {+ "url": (+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEA"+ "AAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGBgAAAABQABpfZFQA"+ "AAAABJRU5ErkJggg=="+ )+ },+ },+ ],+ },+ {"role": "assistant", "content": "I see a browser window."},+ ]++ calls = []++ def fake_api_call(api_kwargs):+ # Snapshot — api_kwargs["messages"] is mutated in place by the+ # strip-and-retry recovery, so a bare reference would silently+ # reflect the post-strip state for every prior call too.+ calls.append(copy.deepcopy(api_kwargs.get("messages")))+ attempt = len(calls)+ if attempt == 1:+ raise _FakeApiError(+ status_code=400,+ message='{"code":"invalid-argument","error":"Invalid PNG image."}',+ )+ return _mock_response("The image was unreadable, but here's what I recall.")++ agent = _make_agent()+ agent._api_max_retries = 3++ with (+ patch.object(agent, "_interruptible_api_call", side_effect=fake_api_call),+ # The model is vision-capable in this scenario (that's *why* the+ # image reached the provider as a native image_url part in the+ # first place — the bug is corruption on replay, not routing).+ # Without this, an unrecognized model id defaults to text-mode+ # and the image never reaches the API as image_url at all.+ patch.object(agent, "_model_supports_vision", return_value=True),+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ patch("run_agent.OpenAI", return_value=MagicMock()),+ patch("agent.agent_runtime_helpers.time.sleep"),+ patch("agent.model_metadata.get_model_context_length", return_value=200000),+ ):+ result = agent.run_conversation(+ "did that look right?", conversation_history=history+ )++ assert result["completed"] is True+ assert result["final_response"] == (+ "The image was unreadable, but here's what I recall."+ )+ assert len(calls) == 2++ # First attempt still carried the (corrupted) image part.+ first_msgs = calls[0]+ assert any(+ isinstance(m.get("content"), list)+ and any(p.get("type") == "image_url" for p in m["content"])+ for m in first_msgs+ ), f"expected image_url part in first attempt, got: {first_msgs!r}"++ # Retry stripped it — no image_url parts anywhere in the request.+ second_msgs = calls[1]+ assert not any(+ isinstance(m.get("content"), list)+ and any(p.get("type") == "image_url" for p in m["content"])+ for m in second_msgs+ )