Skip to content

The agent that grows with you

fix(agent): count image BLOCKS and reserve user uploads against the limit

Meowrasaki5768f78e4fe3
diff --git a/agent/anthropic_message_convert.py b/agent/anthropic_message_convert.py
index 6479285755a..c6928330d76 100644
--- a/agent/anthropic_message_convert.py
+++ b/agent/anthropic_message_convert.py
@@ -607,24 +607,39 @@ def _evict_old_screenshots(result: List[Dict[str, Any]]) -> None:
matches its prompt cache on an exact byte prefix, so a count-based window that retires
one more block per new screenshot makes every turn a full-prefix miss. Holding images
until the limit and then dropping a batch costs one slower turn per batch instead.
+
+ The ceiling is counted in image blocks, so a ``tool_result`` holding several
+ screenshots weighs several blocks, and user-uploaded images are reserved against the
+ limit without ever being rewritten. ``_MAX_KEEP_SCREENSHOTS`` is a floor: when reserved
+ uploads alone fill the ceiling the newest frames still reach the model.
"""
- blocks = [
- block
+ reserved = sum(
+ 1
+ for msg in result
+ for block in (msg.get("content") if isinstance(msg.get("content"), list) else [])
+ if _block_type(block) == "image"
+ )
+ carriers = [
+ (block, sum(1 for b in block["content"] if b.get("type") == "image"))
for msg in reversed(result)
for block in (msg.get("content") if isinstance(msg.get("content"), list) else [])
if _block_type(block) == "tool_result"
and isinstance(block.get("content"), list)
and _has_block_type(block["content"], {"image"})
]
- if len(blocks) <= _OUTBOUND_IMAGE_LIMIT:
+ total_blocks = reserved + sum(n for _, n in carriers)
+ if total_blocks <= _OUTBOUND_IMAGE_LIMIT:
return
- # Overshoot rounded UP to a whole batch: this runs statelessly on every request, so a fixed
- # one-batch retire would stop enforcing the limit after the first batch, and an exact
+ # Extend by whole batches: this runs statelessly on every request, so a fixed one-batch
+ # retire would stop enforcing the limit after the first batch, and an exact
# "limit minus batch" target would move the frontier on every new screenshot.
- overshoot = len(blocks) - _OUTBOUND_IMAGE_LIMIT
- retire = -(-overshoot // _SCREENSHOT_EVICTION_BATCH) * _SCREENSHOT_EVICTION_BATCH
- retire = min(retire, max(len(blocks) - _MAX_KEEP_SCREENSHOTS, 0))
- for block in blocks[-retire:]:
+ max_retire = max(len(carriers) - _MAX_KEEP_SCREENSHOTS, 0)
+ retire = 0
+ while retire < max_retire:
+ retire = min(retire + _SCREENSHOT_EVICTION_BATCH, max_retire)
+ if reserved + sum(n for _, n in carriers[: len(carriers) - retire]) <= _OUTBOUND_IMAGE_LIMIT:
+ break
+ for block, _ in carriers[-retire:] if retire else []:
placeholder = _text_block("[screenshot removed to save context]")
block["content"] = [
placeholder if b.get("type") == "image" else b for b in block["content"]
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 063037979b7..ea0670b30e7 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -1274,30 +1274,69 @@ def _retire_stale_tool_result_images(
return pruned
-def _batched_retire_count(
- count: int,
+def _image_block_count(msg: Dict[str, Any]) -> int:
+ """Number of API image BLOCKS in a message.
+
+ The provider counts blocks, not messages: one ``tool_result`` carrying three
+ screenshots is three blocks against the per-request limit.
+ """
+ content = msg.get("content")
+ inner = content.get("content") if isinstance(content, dict) and content.get("_multimodal") else content
+ return sum(1 for p in inner if _is_image_part(p)) if isinstance(inner, list) else 0
+
+
+def _reserved_image_blocks(api_messages: List[Dict[str, Any]]) -> int:
+ """Image blocks the send path must count but must never rewrite (user uploads).
+
+ They occupy the provider's per-request budget exactly like tool screenshots, so
+ ignoring them lets a mixed session sail past the limit; rewriting them would
+ silently discard something the user attached by hand.
+ """
+ return sum(
+ _image_block_count(m)
+ for m in api_messages
+ if isinstance(m, dict) and m.get("role") != "tool"
+ )
+
+
+def _outbound_image_retire_count(
+ block_counts_newest_first: List[int],
sizes_newest_first: List[int],
*,
+ reserved_blocks: int,
limit: int,
budget: int,
batch: int,
keep_newest: int,
) -> int:
- """How many of the OLDEST image-bearing messages to retire, in whole batches.
+ """How many of the OLDEST image-bearing tool messages to retire, in whole batches.
The send path recomputes eviction from scratch on a fresh clone every turn, so the
retire count must be a step function of the overshoot: a fixed ``min(batch, ...)``
- would cap total eviction at one batch forever and let the outbound count grow past
- the provider limit unbounded, while ``count - limit + batch`` would advance the
- frontier on every new image again. Rounding the overshoot up to a batch multiple
- keeps the request within ``limit``/``budget`` and moves the frontier once per batch.
+ caps total eviction at one batch forever and lets the outbound request grow past the
+ provider limit unbounded, while an exact ``count - limit`` target moves the frontier
+ on every new image and re-invalidates the cached prefix each turn. Extending by whole
+ batches keeps the request within ``limit``/``budget`` and moves the frontier once per
+ batch.
+
+ ``keep_newest`` is a FLOOR, not a trigger. When reserved user uploads alone fill the
+ ceiling, retiring every tool screenshot would leave the model blind on the very frames
+ it was asked about, which is worse than the stricter dimension cap the limit avoids.
"""
- if count <= limit and sum(sizes_newest_first) <= budget:
+ total = len(block_counts_newest_first)
+ if (reserved_blocks + sum(block_counts_newest_first) <= limit
+ and sum(sizes_newest_first) <= budget):
return 0
- retire = -(-max(count - limit, 0) // batch) * batch
- while retire < count and sum(sizes_newest_first[: count - retire]) > budget:
- retire += batch
- return max(0, min(retire, count - max(keep_newest, 0)))
+
+ max_retire = max(total - max(keep_newest, 0), 0)
+ retire = 0
+ while retire < max_retire:
+ retire = min(retire + batch, max_retire)
+ kept = total - retire
+ if (reserved_blocks + sum(block_counts_newest_first[:kept]) <= limit
+ and sum(sizes_newest_first[:kept]) <= budget):
+ break
+ return retire
def _image_payload_bytes(msg: Dict[str, Any]) -> int:
@@ -1326,20 +1365,22 @@ def evict_stale_outbound_tool_images(
on an exact byte prefix, so every retirement re-writes the whole conversation. A count
of N retires one more message on each new image, making every turn a full-prefix miss.
- Keeping images until the request nears the API's own per-request image and byte limits,
- then retiring a batch, costs one slower turn per batch instead of one per image, and
- costs nothing at all while the request is under the limits.
+ The limit is counted in API image BLOCKS, so a ``tool_result`` carrying several
+ screenshots weighs several blocks, and user uploads are counted against the ceiling
+ without ever being rewritten. ``keep_newest`` is a floor that keeps the newest tool
+ frames reachable when reserved uploads alone fill the ceiling.
"""
images = [
- (i, size)
+ (i, _image_block_count(api_messages[i]), size)
for i in range(len(api_messages) - 1, -1, -1)
if isinstance(api_messages[i], dict)
and api_messages[i].get("role") == "tool"
and (size := _image_payload_bytes(api_messages[i])) > 0
]
- retire = _batched_retire_count(
- len(images),
- [s for _, s in images],
+ retire = _outbound_image_retire_count(
+ [blocks for _, blocks, _ in images],
+ [s for _, _, s in images],
+ reserved_blocks=_reserved_image_blocks(api_messages),
limit=_OUTBOUND_IMAGE_LIMIT,
budget=_OUTBOUND_IMAGE_BUDGET_BYTES,
batch=_IMAGE_EVICTION_BATCH,
@@ -1349,7 +1390,7 @@ def evict_stale_outbound_tool_images(
return 0
pruned = 0
- for i, _ in images[-retire:]:
+ for i, _, _ in images[-retire:]:
new_msg = _strip_images_from_tool_msg(api_messages[i])
if new_msg is not None:
api_messages[i] = new_msg
diff --git a/tests/agent/test_outbound_stale_vision.py b/tests/agent/test_outbound_stale_vision.py
index 23426ee6938..8534d2664cf 100644
--- a/tests/agent/test_outbound_stale_vision.py
+++ b/tests/agent/test_outbound_stale_vision.py
@@ -64,6 +64,26 @@ def _image_bearing_tool_ids(messages: list[dict]) -> list[str]:
]
+def _outbound_image_blocks(messages: list[dict]) -> int:
+ """Total API image blocks in the request, the way the provider counts them."""
+ total = 0
+ for m in messages:
+ content = m.get("content")
+ inner = (
+ content.get("content")
+ if isinstance(content, dict) and content.get("_multimodal")
+ else content
+ )
+ if isinstance(inner, list):
+ total += sum(
+ 1
+ for p in inner
+ if isinstance(p, dict)
+ and p.get("type") in ("image_url", "input_image", "image")
+ )
+ return total
+
+
class TestOutboundStaleVisionEviction:
def test_sanitize_alone_keeps_every_screenshot(self):
"""The previous send chokepoint does not close #89296 by itself."""
@@ -126,6 +146,124 @@ class TestOutboundStaleVisionEviction:
"each move rewrites a cached row and restarts the prefix"
)
+ def test_multi_image_tool_results_count_as_blocks(self):
+ """The provider limit counts image BLOCKS, not tool messages.
+
+ Eight tool results carrying three screenshots each are 24 API blocks against a
+ 20-block ceiling. Counting one unit per message sees only 8 and evicts nothing.
+ """
+ history: list[dict] = [{"role": "user", "content": "start"}]
+ for i in range(8):
+ history.append(
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {
+ "id": f"call_{i}",
+ "type": "function",
+ "function": {
+ "name": "vision_analyze",
+ "arguments": "{}",
+ },
+ }
+ ],
+ }
+ )
+ history.append(
+ {
+ "role": "tool",
+ "tool_call_id": f"call_{i}",
+ "content": [
+ {"type": "text", "text": f"shot {i}"},
+ *[
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,AAA{i}{k}"},
+ }
+ for k in range(3)
+ ],
+ ],
+ }
+ )
+ outbound = sanitize_api_messages(history)
+ assert evict_stale_outbound_tool_images(outbound) > 0, (
+ "24 image blocks across 8 messages must trip the 20-block ceiling"
+ )
+ assert _outbound_image_blocks(outbound) <= _OUTBOUND_IMAGE_LIMIT
+
+ def test_user_uploads_count_against_the_ceiling(self):
+ """Uploads occupy the provider's budget, so they must force tool eviction.
+
+ Holding the tool-screenshot count fixed and adding uploads must increase the
+ number of retired screenshots; ignoring uploads leaves the request over the limit.
+ """
+ def outbound_for(n_uploads: int) -> list[dict]:
+ history: list[dict] = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look"},
+ *[
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,U{k}"},
+ }
+ for k in range(n_uploads)
+ ],
+ ],
+ }
+ ]
+ for i in range(16):
+ history.extend(_image_tool(i))
+ outbound = sanitize_api_messages(history)
+ evict_stale_outbound_tool_images(outbound)
+ return outbound
+
+ assert evict_stale_outbound_tool_images(sanitize_api_messages(
+ [{"role": "user", "content": "start"}]
+ + [m for i in range(16) for m in _image_tool(i)]
+ )) == 0, "16 screenshots alone are under the ceiling"
+
+ for n_uploads in (8, 12):
+ outbound = outbound_for(n_uploads)
+ assert _outbound_image_blocks(outbound) <= _OUTBOUND_IMAGE_LIMIT, (
+ f"{n_uploads} uploads + 16 screenshots left the request over the ceiling"
+ )
+ user = next(m for m in outbound if m.get("role") == "user")
+ intact = sum(
+ 1 for p in user["content"]
+ if isinstance(p, dict) and p.get("type") == "image_url"
+ )
+ assert intact == n_uploads, "user uploads must never be rewritten"
+
+ def test_keep_newest_is_a_floor_when_uploads_fill_the_ceiling(self):
+ """Reserved uploads alone over the limit must not blind the model.
+
+ Retiring every screenshot cannot bring the request under the ceiling here, so
+ the newest frames have to survive rather than be stripped for no benefit.
+ """
+ history: list[dict] = [
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "look"},
+ *[
+ {
+ "type": "image_url",
+ "image_url": {"url": f"data:image/png;base64,U{k}"},
+ }
+ for k in range(_OUTBOUND_IMAGE_LIMIT + 1)
+ ],
+ ],
+ }
+ ]
+ for i in range(5):
+ history.extend(_image_tool(i))
+ outbound = sanitize_api_messages(history)
+ evict_stale_outbound_tool_images(outbound)
+ assert len(_image_bearing_tool_ids(outbound)) == _MAX_KEEP_TOOL_IMAGES
+
def test_does_not_rewrite_persisted_history(self):
from agent.conversation_loop import _clone_message_for_send