Skip to content

The agent that grows with you

fix(agent): route oversize rejections that arrive as HTTP 400 to the image-shrink recovery

dacheah270fe15c8b53
diff --git a/agent/error_classifier.py b/agent/error_classifier.py
index 47bed99af58..e4c5d9fed7c 100644
--- a/agent/error_classifier.py
+++ b/agent/error_classifier.py
@@ -176,10 +176,16 @@ _PAYLOAD_TOO_LARGE_PATTERNS = (
# tile-patch budget (ceil(w/32)×ceil(h/32)) exceeds its 30000-patch ceiling
# with wording that names no image-size vocabulary — without this pattern it
# fell to format_error (non-retryable), bypassing the shrink recovery (#106337).
+# Byte caps enforced with a 400 instead of a 413 (#112473): NVIDIA NIM caps the whole
+# payload ("Please make sure your payload is below 26214400 bytes in size"); Alibaba
+# DashScope caps the base64 image string via Jackson ("String value length (N) exceeds the
+# maximum allowed (M, from `StreamReadConstraints.getMaxStringLength()`)"). Only an inline
+# image reaches those sizes, so shrinking is the recovery; the method-scoped Jackson token
+# is used because the bare class name also appears when Jackson caps a *token* length.
_IMAGE_TOO_LARGE_PATTERNS = (
"image exceeds", "image too large", "image_too_large", "image size exceeds", "image dimensions exceed",
"dimensions exceed max allowed size", "max allowed size: 8000", "media exceeds", "media too large",
- "patches after processing",
+ "patches after processing", "make sure your payload is below", "streamreadconstraints.getmaxstringlength",
)
# Undecodable image bytes → strip-and-retry, never shrink. xAI wordings
@@ -809,9 +815,49 @@ def _classify_402(error_msg: str, result_fn: Callable[..., Any]) -> Any:
return result_fn(**(_V_RATE_LIMIT if transient else _V_BILLING))
+def _has_large_inline_image(content: Any) -> bool:
+ """True when a rejected ``content`` list carries a ``data:image/`` part the shrink pass would rewrite
+ (over ``conversation_compression._IMAGE_SHRINK_TARGET_BYTES``; below it a shrink retry is a no-op)."""
+ from agent.conversation_compression import _IMAGE_SHRINK_TARGET_BYTES
+
+ for part in content if isinstance(content, list) else ():
+ image = part.get("image_url") if isinstance(part, dict) else None
+ url = image.get("url") if isinstance(image, dict) else image
+ if isinstance(url, str) and url.startswith("data:image/") and len(url) > _IMAGE_SHRINK_TARGET_BYTES:
+ return True
+ return False
+
+
+def _oversized_message_content_rejection(body: Any) -> bool:
+ """400 rejecting a *message* ``content`` field whose rejected value carries a large inline image.
+
+ Nebius Token Factory caps a single image at 10 MiB and reports the violation through the field that
+ failed to coerce — pydantic ``{"type": "string_type", "loc": ["body","messages",N,"content","str"],
+ "msg": "Input should be a valid string", "input": [...]}`` — naming no size vocabulary, so the
+ keyword multimodal *tool*-content rule (#104731) claimed it and spent its retry stripping tool images
+ that were never there (#112473). The same list-shaped content with a small image succeeds, so the
+ image bytes are the trigger. Tool-scoped locs (``messages.N.tool.content.str``) stay with #104731.
+ """
+ details = body.get("detail") if isinstance(body, dict) else None
+ for detail in details if isinstance(details, list) else ():
+ loc = detail.get("loc") if isinstance(detail, dict) else None
+ if detail.get("type") != "string_type" or not isinstance(loc, list) or len(loc) < 2:
+ continue
+ parts = [str(x).lower() for x in loc]
+ if parts[:2] == ["body", "messages"] and parts[-2:] == ["content", "str"] and not any(
+ x.startswith("tool") for x in parts
+ ) and _has_large_inline_image(detail.get("input")):
+ return True
+ return False
+
+
def _classify_400(c: _Ctx) -> Verdict:
"""400 Bad Request — image/tool shapes, request-shape rejections, overflow, or generic."""
msg, code = c.msg, c.code
+ # A size cap reported *through* a message content field must beat the keyword
+ # multimodal rule, which would otherwise claim "input should be a valid string".
+ if _oversized_message_content_rejection(c.body):
+ return _V_IMAGE_TOO_LARGE
verdict = _first_match(msg, _IMAGE_TOOL_RULES)
if verdict is not None:
return verdict
diff --git a/agent/turn_api_error.py b/agent/turn_api_error.py
index 9905d6774f0..4a0d218423f 100644
--- a/agent/turn_api_error.py
+++ b/agent/turn_api_error.py
@@ -274,8 +274,17 @@ def settle_unrecovered_error(
# eager fallback already gave up, so retrying only burns paid requests on a depleted
# balance. Mirrors 401/403.
is_local_validation_error = _is_local_validation_error(api_error)
+ # ``recover_after_classification`` sets ``image_shrink_retry_attempted`` BEFORE it runs the shrink,
+ # so an image-size rejection reaching this point with the flag set had nothing left to shrink (the
+ # excess is text on a host whose cap is payload-scoped, or an unshrinkable image). Re-sending the
+ # byte-identical body ``max_retries`` times changes nothing: treat it as a client error and try
+ # the fallback chain now, as the format_error verdict these 400s carried before did (#112473).
+ shrink_spent = classified.reason == FailoverReason.image_too_large and bool(
+ getattr(_retry, "image_shrink_retry_attempted", False)
+ )
is_client_error = (
is_local_validation_error
+ or shrink_spent
or (
not classified.retryable
and not classified.should_compress
@@ -311,7 +320,7 @@ def settle_unrecovered_error(
# the cascade. An UNCLASSIFIED local ValueError/TypeError keeps its historical fallback;
# a recognised verdict that opts out wins even when the exception is a ValueError subclass.
_unclassified_local = is_local_validation_error and classified.reason == FailoverReason.unknown
- if classified.should_fallback or _unclassified_local:
+ if classified.should_fallback or _unclassified_local or shrink_spent:
# Announce the fallback only when a chain exists, else "trying fallback..." lies
# before a silent abort.
if agent._has_pending_fallback():