Skip to content

The agent that grows with you

refactor(agent): one image-eviction policy for both send-path passes

kshitijk4poor5dcfae44b4a9
diff --git a/agent/anthropic_message_convert.py b/agent/anthropic_message_convert.py
index 7e3ac0b8419..b5931676f54 100644
--- a/agent/anthropic_message_convert.py
+++ b/agent/anthropic_message_convert.py
@@ -10,6 +10,7 @@ import logging
import re
from typing import Any, Dict, List, Optional, Tuple
+from agent.image_eviction_policy import outbound_image_retire_count
from agent.anthropic_endpoints import (
_is_deepseek_anthropic_endpoint, _is_kimi_family_endpoint, _is_nous_portal_endpoint,
_is_third_party_anthropic_endpoint, _model_name_is_deepseek_thinking,
@@ -21,14 +22,6 @@ _THINKING_TYPES = frozenset(("thinking", "redacted_thinking"))
_CACHEABLE_TYPES = frozenset(("text", "tool_use"))
_EMPTY_TEXT_PLACEHOLDER = "(empty)"
_EMPTY_SCHEMA = {"type": "object", "properties": {}}
-# Screenshot eviction mirrors the API's own per-request image limit rather than a keep-newest
-# count: 20 is the documented threshold above which Anthropic imposes a stricter per-image
-# dimension cap on every image in the request, including ones nested in tool_result content.
-# Below it nothing is rewritten, so the prompt-cache prefix survives; at it, a whole batch goes
-# at once, costing one slower turn per batch instead of one per screenshot.
-_MAX_KEEP_SCREENSHOTS = 3
-_OUTBOUND_IMAGE_LIMIT = 20
-_SCREENSHOT_EVICTION_BATCH = 8
_BEDROCK_REGION_PREFIXES = ("global.", "us.", "eu.", "apac.", "ap.", "au.", "jp.", "ca.", "sa.", "me.", "af.")
@@ -600,18 +593,12 @@ def _manage_thinking_signatures(result: List[Dict[str, Any]], base_url: str | No
def _evict_old_screenshots(result: List[Dict[str, Any]]) -> None:
- """Retire screenshot payloads once the request nears the API's per-request image limit.
-
- Mutates ``result`` in place. Eviction is triggered by the LIMIT, not by a keep-newest
- count: retiring an image edits a block the provider has already cached, and Anthropic
- 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 satisfiability
- floor: only when reserved uploads alone fill the ceiling do the newest frames stay.
+ """Retire screenshot payloads once the request would cross the API's per-request image limit.
+
+ Mutates ``result`` in place. This wire pass has no byte sizes, so it enforces the block
+ ceiling only; the auxiliary Anthropic client (``agent.auxiliary_client`` via
+ ``anthropic_adapter.build_anthropic_kwargs``) reaches it without the compressor's
+ send-path pass, so it must hold the invariant alone. Policy: :mod:`agent.image_eviction_policy`.
"""
reserved = sum(
1
@@ -623,42 +610,18 @@ def _evict_old_screenshots(result: List[Dict[str, Any]]) -> None:
# (oldest first), so the inner walk must also run newest -> oldest or a batch that
# ends mid-message retires the newest frames instead of the oldest (#103217).
carriers = [
- (block, sum(1 for b in block["content"] if b.get("type") == "image"))
+ (block, sum(1 for b in block["content"] if _block_type(b) == "image"))
for msg in reversed(result)
for block in reversed(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"})
]
- total_blocks = reserved + sum(n for _, n in carriers)
- if total_blocks <= _OUTBOUND_IMAGE_LIMIT:
- return
- # 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.
- # The keep floor only shelters a breach that retiring every screenshot cannot fix
- # (reserved uploads alone over the ceiling); one tool_result carrying 25 frames is
- # fixable and must not hide behind a floor counted in carriers.
- floor = min(_MAX_KEEP_SCREENSHOTS, len(carriers))
-
- def _fits(kept: int) -> bool:
- return reserved + sum(n for _, n in carriers[:kept]) <= _OUTBOUND_IMAGE_LIMIT
-
- max_retire = len(carriers) - floor if not _fits(0) else len(carriers)
- retire = 0
- while retire < max_retire:
- step = min(retire + _SCREENSHOT_EVICTION_BATCH, max_retire)
- if step > len(carriers) - floor and _fits(floor):
- # A whole batch would retire the frames the model was just asked about while
- # keeping the floor already clears the ceiling; take the smaller edit instead.
- step = len(carriers) - floor
- retire = step
- if _fits(len(carriers) - retire):
- break
- for block, _ in carriers[-retire:] if retire else []:
+ retire = outbound_image_retire_count([n for _, n in carriers], reserved)
+ for block, _ in carriers[len(carriers) - retire:]:
placeholder = _text_block("[screenshot removed to save context]")
block["content"] = [
- placeholder if b.get("type") == "image" else b for b in block["content"]
+ placeholder if _block_type(b) == "image" else b for b in block["content"]
]
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 6c096105cca..d2a37bf2f57 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -14,6 +14,7 @@ import uuid
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Tuple
+from agent.image_eviction_policy import outbound_image_retire_count
from agent.auxiliary_client import (
AuxiliaryExplicitCancellation,
_is_connection_error,
@@ -982,21 +983,8 @@ _PRESSURE_KEEP_RECENT_MESSAGES = 3
# Native vision_analyze / computer_use screenshots that sit inside the protected tail cannot be demoted by
# pass 2, so they ride every later request until anti-thrash disables compression (#92699).
_MAX_KEEP_TOOL_IMAGES = 3
-
-# Send-path eviction thresholds. The count above is the COMPACTION keep-window; the send path
-# must not use it, because evicting at 3 images retires one more message on every new image and
-# each retirement edits a row inside the Anthropic cached prefix, re-writing the whole history.
-# Mirror the provider's own constraint instead: hold images until the request would cross a real
-# API limit, then retire a BATCH, so the cost is one slower turn per batch and zero below it.
-#
-# 20 is the documented threshold at which Anthropic applies a stricter per-image dimension cap
-# (2000 px) to EVERY image in the request, counting images nested in tool_result content. Staying
-# at or below it keeps large screenshots legal. The hard ceilings are higher (100 images per
-# request on 200K-context models, 600 otherwise) but the 32 MB request-size limit usually binds
-# first, which the byte budget below guards with headroom for the text portion of the request.
-_OUTBOUND_IMAGE_LIMIT = 20
-_OUTBOUND_IMAGE_BUDGET_BYTES = 24_000_000
-_IMAGE_EVICTION_BATCH = 8
+# Compaction window only. The send path's same-valued OUTBOUND_IMAGE_FLOOR (agent/image_eviction_policy.py)
+# is a satisfiability floor with different semantics; do not merge the two.
# Below this window the threshold is floored (raise-only): at 50% the incompressible
# floor eats the reclaimed headroom and compaction re-fires every 1-2 turns.
@@ -1219,10 +1207,14 @@ def _replace_image_parts(parts: Any, placeholder: str) -> Optional[List[Any]]:
return [{"type": "text", "text": placeholder} if _is_image_part(p) else p for p in parts]
+def _tool_result_parts(content: Any) -> Any:
+ """Part list of a tool-result body, unwrapping the ``_multimodal`` envelope."""
+ return content.get("content") if isinstance(content, dict) and content.get("_multimodal") else content
+
+
def _tool_content_has_images(content: Any) -> bool:
"""True when a tool-result body (part list or ``_multimodal`` envelope) carries images."""
- inner = content.get("content") if isinstance(content, dict) and content.get("_multimodal") else content
- return _content_has_images(inner)
+ return _content_has_images(_tool_result_parts(content))
def _strip_images_from_tool_msg(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]:
@@ -1242,147 +1234,47 @@ def _rewritten(msg: Dict[str, Any], content: Any) -> Dict[str, Any]:
return new_msg
-def _retire_stale_tool_result_images(
- result: List[Dict[str, Any]],
- keep_newest: int = _MAX_KEEP_TOOL_IMAGES,
-) -> int:
+def _retire_stale_tool_result_images(result: List[Dict[str, Any]], keep_newest: int = _MAX_KEEP_TOOL_IMAGES) -> int:
"""Replace image payloads on older tool results with text placeholders.
-
- Keeps the newest ``keep_newest`` image-bearing tool messages; user uploads untouched.
- Compaction's pass: it commits the rewrite into the canonical transcript once, so it
- reclaims every eligible byte. The SEND path must not call this — see
- :func:`evict_stale_outbound_tool_images` for why a per-turn count-based window is
- ruinous for the prompt cache. Mutates ``result`` in place; returns messages rewritten.
- """
- indexes = [
- i
- for i in range(len(result) - 1, -1, -1)
- if isinstance(result[i], dict)
- and result[i].get("role") == "tool"
- and _tool_content_has_images(result[i].get("content"))
- ]
- retire = len(indexes) - max(keep_newest, 0)
- if retire <= 0:
- return 0
-
- pruned = 0
- for i in indexes[-retire:]:
- new_msg = _strip_images_from_tool_msg(result[i])
+ Keeps the newest ``keep_newest`` image-bearing tool messages; user uploads untouched. Mutates
+ ``result`` in place; returns the number of messages rewritten. Compaction only: it commits the
+ rewrite into the canonical transcript once. The send path uses
+ :func:`evict_stale_outbound_tool_images` (a per-request keep-newest window rewrites the cached
+ prefix on every new image, #113517)."""
+ seen = pruned = 0
+ for i in range(len(result) - 1, -1, -1):
+ msg = result[i]
+ if not isinstance(msg, dict) or msg.get("role") != "tool" or not _tool_content_has_images(msg.get("content")):
+ continue
+ seen += 1
+ if seen <= max(keep_newest, 0):
+ continue
+ new_msg = _strip_images_from_tool_msg(msg)
if new_msg is not None:
result[i] = new_msg
pruned += 1
return pruned
-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]]) -> Tuple[int, int]:
- """``(blocks, bytes)`` of image payload the send path counts but must never rewrite.
+def _image_payload(msg: Dict[str, Any]) -> Tuple[int, int]:
+ """``(blocks, bytes)`` of image payload in a message.
- User uploads occupy the provider's per-request block and size budgets exactly like
- tool screenshots, so ignoring them lets a mixed session breach either ceiling;
- rewriting them would silently discard something the user attached by hand.
+ The provider counts BLOCKS: one ``tool_result`` carrying three screenshots is three against
+ the per-request limit.
"""
+ parts = _tool_result_parts(msg.get("content"))
+ if not isinstance(parts, list):
+ return 0, 0
blocks = payload = 0
- for m in api_messages:
- if isinstance(m, dict) and m.get("role") != "tool":
- blocks += _image_block_count(m)
- payload += _image_payload_bytes(m)
+ for p in parts:
+ if not _is_image_part(p):
+ continue
+ blocks += 1
+ payload += len(json.dumps(p, ensure_ascii=False))
return blocks, payload
-def _outbound_image_retire_count(
- block_counts_newest_first: List[int],
- sizes_newest_first: List[int],
- *,
- reserved_blocks: int,
- reserved_bytes: int,
- limit: int,
- budget: int,
- batch: int,
- keep_newest: int,
-) -> int:
- """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, ...)``
- 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.
-
- Reserved user uploads count toward BOTH ceilings; they are never rewritten, but
- ignoring their bytes lets a handful of large uploads carry the request past the
- provider's hard request-size limit unnoticed.
-
- ``keep_newest`` is a SATISFIABILITY floor, not an unconditional one. It exists for the
- case where reserved uploads alone breach the ceiling: retiring every tool screenshot
- then cannot fix the request and would only blind the model on the frames it was just
- asked about, which is worse than the stricter dimension cap the block limit avoids.
- Whenever retiring tool content CAN bring the request inside the ceiling, it does so,
- past the floor only when keeping the floor does not fit — a batch step that would blind
- the model while the floor alone clears the ceiling is cut back to the floor. Byte
- pressure never yields to the floor, because the request-size limit is hard and the
- provider answers 413.
- """
- total = len(block_counts_newest_first)
-
- def _blocks_fit(kept: int) -> bool:
- return reserved_blocks + sum(block_counts_newest_first[:kept]) <= limit
-
- def _bytes_fit(kept: int) -> bool:
- return reserved_bytes + sum(sizes_newest_first[:kept]) <= budget
-
- def _fits(kept: int) -> bool:
- return _blocks_fit(kept) and _bytes_fit(kept)
-
- if _fits(total):
- return 0
-
- floor = min(max(keep_newest, 0), total)
- if not _fits(0) and _bytes_fit(floor):
- # Reserved uploads alone breach the block ceiling: no retirement can fix it, so the
- # newest frames stay rather than blinding the model for nothing.
- max_retire = total - floor
- else:
- max_retire = total
-
- retire = 0
- while retire < max_retire:
- step = min(retire + batch, max_retire)
- if step > total - floor and _fits(floor):
- # A whole batch would retire the frames the model was just asked about while
- # keeping the floor already clears the ceiling; take the smaller edit instead.
- step = total - floor
- retire = step
- if _fits(total - retire):
- break
- return retire
-
-
-def _image_payload_bytes(msg: Dict[str, Any]) -> int:
- """Serialized size of the image parts in a tool message (0 when it carries none)."""
- content = msg.get("content")
- inner = content.get("content") if isinstance(content, dict) and content.get("_multimodal") else content
- if not isinstance(inner, list):
- return 0
- return sum(len(json.dumps(p, ensure_ascii=False)) for p in inner if _is_image_part(p))
-
-
-def evict_stale_outbound_tool_images(
- api_messages: List[Dict[str, Any]],
- keep_newest: int = _MAX_KEEP_TOOL_IMAGES,
-) -> int:
+def evict_stale_outbound_tool_images(api_messages: List[Dict[str, Any]]) -> int:
"""Drop stale screenshot/vision payloads from the per-call API copy.
Compression's keep-newest pass only runs when prune/compress fires, and the Anthropic
@@ -1391,39 +1283,32 @@ def evict_stale_outbound_tool_images(
the reactive strip (#89286). Call this on the cloned ``api_messages`` list after
sanitization (#89296). Do not pass persisted history — the rewrite is send-path only.
- Eviction is driven by the PROVIDER LIMIT, not by a keep-newest count. Retiring an image
- edits a message the provider has already cached, and Anthropic matches its prompt cache
- 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.
-
- 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.
+ Eviction is driven by the provider limit, counted in image BLOCKS, with user uploads
+ reserved against the ceiling but never rewritten — policy and rationale in
+ :mod:`agent.image_eviction_policy`. Returns the number of messages rewritten.
"""
- images = [
- (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
- ]
- reserved_blocks, reserved_bytes = _reserved_image_blocks(api_messages)
- retire = _outbound_image_retire_count(
- [blocks for _, blocks, _ in images],
- [s for _, _, s in images],
- reserved_blocks=reserved_blocks,
+ carriers: List[Tuple[int, Tuple[int, int]]] = []
+ reserved_blocks = reserved_bytes = 0
+ for i in range(len(api_messages) - 1, -1, -1):
+ msg = api_messages[i]
+ if not isinstance(msg, dict):
+ continue
+ blocks, size = _image_payload(msg)
+ if not blocks:
+ continue
+ if msg.get("role") == "tool":
+ carriers.append((i, (blocks, size)))
+ else:
+ reserved_blocks += blocks
+ reserved_bytes += size
+ retire = outbound_image_retire_count(
+ [blocks for _, (blocks, _) in carriers],
+ reserved_blocks,
+ carrier_bytes_newest_first=[size for _, (_, size) in carriers],
reserved_bytes=reserved_bytes,
- limit=_OUTBOUND_IMAGE_LIMIT,
- budget=_OUTBOUND_IMAGE_BUDGET_BYTES,
- batch=_IMAGE_EVICTION_BATCH,
- keep_newest=keep_newest,
)
- if retire <= 0:
- return 0
-
pruned = 0
- for i, _, _ in images[-retire:]:
+ for i, _ in carriers[len(carriers) - 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/agent/image_eviction_policy.py b/agent/image_eviction_policy.py
new file mode 100644
index 00000000000..0a1ff1cb9f5
--- /dev/null
+++ b/agent/image_eviction_policy.py
@@ -0,0 +1,91 @@
+"""Send-path image eviction policy shared by both stateless outbound passes.
+
+Two passes retire old tool-result images from the per-request copy of the conversation:
+``agent.context_compressor.evict_stale_outbound_tool_images`` on the OpenAI-shaped list and
+``agent.anthropic_message_convert._evict_old_screenshots`` on the Anthropic wire list. Both run
+from scratch on a fresh clone every request, so they must agree on one policy or the second
+pass re-evicts on a different frontier than the first (#113517). This module is stdlib-only so
+the wire converter, a leaf, can import it without dragging in the compaction stack.
+
+Why the trigger is a provider limit, not a keep-newest count: retiring an image edits a message
+the provider has already cached, and Anthropic matches its prompt cache on an exact byte prefix.
+A keep-newest-N window retires one more message on every new image, so every turn is a
+full-prefix miss. Holding images until the request would cross a real API limit and then
+retiring a batch costs one slower turn per batch and nothing below the limit.
+
+20 is the documented threshold at which Anthropic applies a stricter per-image dimension cap
+(2000 px) to EVERY image in the request, counting images nested in tool_result content. The hard
+ceilings are higher (100 images per request on 200K-context models, 600 otherwise) but the 32 MB
+request-size limit usually binds first, which the byte budget guards with headroom for text.
+"""
+
+from __future__ import annotations
+
+from typing import Optional, Sequence
+
+OUTBOUND_IMAGE_LIMIT = 20
+OUTBOUND_IMAGE_BUDGET_BYTES = 24_000_000
+IMAGE_EVICTION_BATCH = 8
+# Satisfiability floor — see outbound_image_retire_count.
+OUTBOUND_IMAGE_FLOOR = 3
+
+
+def outbound_image_retire_count(
+ carrier_blocks_newest_first: Sequence[int],
+ reserved_blocks: int,
+ *,
+ carrier_bytes_newest_first: Optional[Sequence[int]] = None,
+ reserved_bytes: int = 0,
+ limit: int = OUTBOUND_IMAGE_LIMIT,
+ budget: int = OUTBOUND_IMAGE_BUDGET_BYTES,
+ batch: int = IMAGE_EVICTION_BATCH,
+ floor: int = OUTBOUND_IMAGE_FLOOR,
+) -> int:
+ """How many of the OLDEST image-bearing tool results to retire.
+
+ ``carrier_blocks_newest_first`` is the image-block count per image-bearing tool result,
+ newest first; ``reserved_blocks`` counts images the pass must never rewrite (user
+ uploads). The byte dimension is active only when ``carrier_bytes_newest_first`` is
+ given (the wire pass has no sizes).
+
+ The retire count must be a STEP FUNCTION of the overshoot, because the pass is recomputed
+ on every request: an exact ``count - limit`` target moves the frontier on every new image,
+ and a fixed one-batch retire stops enforcing the limit after the first batch. So the count
+ advances in quanta until the request fits.
+
+ The floor is a SATISFIABILITY floor: it shelters the newest frames only when reserved
+ uploads alone breach the block ceiling (no retirement can fix that), and never under byte
+ pressure — the request-size limit is hard and the provider answers 413.
+ """
+ total = len(carrier_blocks_newest_first)
+ sizes = carrier_bytes_newest_first
+ blocks_kept = [0] * (total + 1)
+ bytes_kept = [0] * (total + 1)
+ for i in range(total):
+ blocks_kept[i + 1] = blocks_kept[i] + carrier_blocks_newest_first[i]
+ bytes_kept[i + 1] = bytes_kept[i] + (sizes[i] if sizes is not None else 0)
+
+ def _bytes_fit(kept: int) -> bool:
+ return sizes is None or reserved_bytes + bytes_kept[kept] <= budget
+
+ def _fits(kept: int) -> bool:
+ return reserved_blocks + blocks_kept[kept] <= limit and _bytes_fit(kept)
+
+ if _fits(total):
+ return 0
+
+ floor = min(max(floor, 0), total)
+ max_retire = total - floor if not _fits(0) and _bytes_fit(floor) else total
+ if max_retire <= 0:
+ return 0
+ retire = 0
+ while retire < max_retire:
+ step = min(retire + batch, max_retire)
+ if step > total - floor and _fits(floor):
+ # A whole batch would retire the frames the model was just asked about while
+ # keeping the floor already clears the ceiling; take the smaller edit instead.
+ step = total - floor
+ retire = step
+ if _fits(total - retire):
+ break
+ return retire
diff --git a/tests/agent/test_outbound_stale_vision.py b/tests/agent/test_outbound_stale_vision.py
index e3cb6406cca..b940703fe16 100644
--- a/tests/agent/test_outbound_stale_vision.py
+++ b/tests/agent/test_outbound_stale_vision.py
@@ -12,12 +12,14 @@ import json
from agent.agent_runtime_helpers import sanitize_api_messages
from agent.context_compressor import (
- _IMAGE_EVICTION_BATCH,
- _MAX_KEEP_TOOL_IMAGES,
- _OUTBOUND_IMAGE_LIMIT,
_tool_content_has_images,
evict_stale_outbound_tool_images,
)
+from agent.image_eviction_policy import (
+ IMAGE_EVICTION_BATCH,
+ OUTBOUND_IMAGE_FLOOR,
+ OUTBOUND_IMAGE_LIMIT,
+)
def _image_tool(i: int, *, blob: str = "A" * 80) -> list[dict]:
@@ -95,21 +97,21 @@ class TestOutboundStaleVisionEviction:
def test_nothing_is_evicted_below_the_provider_limit(self):
"""The common case must be append-only: no rewrite, so the cached prefix survives."""
- history = _history_with_screenshots(_OUTBOUND_IMAGE_LIMIT)
+ history = _history_with_screenshots(OUTBOUND_IMAGE_LIMIT)
outbound = sanitize_api_messages(history)
assert evict_stale_outbound_tool_images(outbound) == 0
assert _image_bearing_tool_ids(outbound) == [
- f"call_{i}" for i in range(_OUTBOUND_IMAGE_LIMIT)
+ f"call_{i}" for i in range(OUTBOUND_IMAGE_LIMIT)
]
def test_eviction_retires_a_batch_once_over_the_limit(self):
- n = _OUTBOUND_IMAGE_LIMIT + 1
+ n = OUTBOUND_IMAGE_LIMIT + 1
history = _history_with_screenshots(n)
outbound = sanitize_api_messages(history)
pruned = evict_stale_outbound_tool_images(outbound)
- assert pruned == _IMAGE_EVICTION_BATCH
+ assert pruned == IMAGE_EVICTION_BATCH
kept = _image_bearing_tool_ids(outbound)
- assert kept == [f"call_{i}" for i in range(_IMAGE_EVICTION_BATCH, n)]
+ assert kept == [f"call_{i}" for i in range(IMAGE_EVICTION_BATCH, n)]
oldest = next(m for m in outbound if m.get("tool_call_id") == "call_0")
assert isinstance(oldest["content"], list)
@@ -138,9 +140,9 @@ class TestOutboundStaleVisionEviction:
# Span three batch windows: a fixed one-batch retire holds the frontier but stops
# enforcing the limit after the first window, which the count assertion catches.
- span = range(_MAX_KEEP_TOOL_IMAGES + 1, _OUTBOUND_IMAGE_LIMIT + 3 * _IMAGE_EVICTION_BATCH)
+ span = range(OUTBOUND_IMAGE_FLOOR + 1, OUTBOUND_IMAGE_LIMIT + 3 * IMAGE_EVICTION_BATCH)
kept = [surviving(n) for n in span]
- assert all(len(k) <= _OUTBOUND_IMAGE_LIMIT for k in kept), [len(k) for k in kept]
+ assert all(len(k) <= OUTBOUND_IMAGE_LIMIT for k in kept), [len(k) for k in kept]
frontier = [k[0] for k in kept]
moves = sum(a != b for a, b in zip(frontier, frontier[1:]))
assert moves == 3, (
@@ -192,7 +194,7 @@ class TestOutboundStaleVisionEviction:
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
+ 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.
@@ -229,7 +231,7 @@ class TestOutboundStaleVisionEviction:
for n_uploads in (8, 12):
outbound = outbound_for(n_uploads)
- assert _outbound_image_blocks(outbound) <= _OUTBOUND_IMAGE_LIMIT, (
+ 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")
@@ -255,7 +257,7 @@ class TestOutboundStaleVisionEviction:
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,U{k}"},
}
- for k in range(_OUTBOUND_IMAGE_LIMIT + 1)
+ for k in range(OUTBOUND_IMAGE_LIMIT + 1)
],
],
}
@@ -264,7 +266,7 @@ class TestOutboundStaleVisionEviction:
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
+ assert len(_image_bearing_tool_ids(outbound)) == OUTBOUND_IMAGE_FLOOR
def test_a_batch_that_would_blind_the_model_stops_at_the_floor(self):
"""A whole-batch retire must not take the newest frames when the floor already fits.
@@ -273,7 +275,7 @@ class TestOutboundStaleVisionEviction:
one eight-wide batch would retire all six tool frames -- including the one the model
was just asked about -- although keeping the newest three already clears the limit.
"""
- uploads = _OUTBOUND_IMAGE_LIMIT - 5
+ uploads = OUTBOUND_IMAGE_LIMIT - 5
history: list[dict] = [
{
"role": "user",
@@ -290,8 +292,9 @@ class TestOutboundStaleVisionEviction:
history.extend(_image_tool(i))
outbound = sanitize_api_messages(history)
evict_stale_outbound_tool_images(outbound)
- assert _outbound_image_blocks(outbound) <= _OUTBOUND_IMAGE_LIMIT
- assert _image_bearing_tool_ids(outbound) == [f"call_{i}" for i in range(3, 6)]
+ assert _outbound_image_blocks(outbound) <= OUTBOUND_IMAGE_LIMIT
+ kept = _image_bearing_tool_ids(outbound)
+ assert kept[-OUTBOUND_IMAGE_FLOOR:] == [f"call_{i}" for i in range(6 - OUTBOUND_IMAGE_FLOOR, 6)]
def test_byte_pressure_overrides_the_keep_newest_floor(self):
"""A hard request-size breach must not be preserved by the floor.
@@ -394,28 +397,28 @@ class TestOutboundStaleVisionEviction:
"type": "image_url",
"image_url": {"url": f"data:image/png;base64,A{k}"},
}
- for k in range(_OUTBOUND_IMAGE_LIMIT + 5)
+ for k in range(OUTBOUND_IMAGE_LIMIT + 5)
],
],
}
)
outbound = sanitize_api_messages(history)
- assert _outbound_image_blocks(outbound) > _OUTBOUND_IMAGE_LIMIT
+ assert _outbound_image_blocks(outbound) > OUTBOUND_IMAGE_LIMIT
evict_stale_outbound_tool_images(outbound)
- assert _outbound_image_blocks(outbound) <= _OUTBOUND_IMAGE_LIMIT, (
+ assert _outbound_image_blocks(outbound) <= OUTBOUND_IMAGE_LIMIT, (
"the floor sheltered a breach that retiring tool content could fix"
)
def test_does_not_rewrite_persisted_history(self):
from agent.conversation_loop import _clone_message_for_send
- n = _OUTBOUND_IMAGE_LIMIT + 1
+ n = OUTBOUND_IMAGE_LIMIT + 1
history = _history_with_screenshots(n)
outbound = [_clone_message_for_send(m) for m in history]
evict_stale_outbound_tool_images(outbound)
assert _image_bearing_tool_ids(history) == [f"call_{i}" for i in range(n)]
assert _image_bearing_tool_ids(outbound) == [
- f"call_{i}" for i in range(_IMAGE_EVICTION_BATCH, n)
+ f"call_{i}" for i in range(IMAGE_EVICTION_BATCH, n)
]
def test_user_uploads_are_not_evicted(self):
@@ -431,9 +434,9 @@ class TestOutboundStaleVisionEviction:
],
}
]
- for i in range(_MAX_KEEP_TOOL_IMAGES + 2):
+ for i in range(OUTBOUND_IMAGE_LIMIT):
history.extend(_image_tool(i))
outbound = sanitize_api_messages(history)
- evict_stale_outbound_tool_images(outbound)
+ assert evict_stale_outbound_tool_images(outbound) > 0
user = next(m for m in outbound if m.get("role") == "user")
assert user["content"][1]["image_url"]["url"].endswith("USERUPLOAD")
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index 273f04105b6..645d69f5069 100644
--- a/tests/tools/test_computer_use.py
+++ b/tests/tools/test_computer_use.py
@@ -469,12 +469,9 @@ class TestAnthropicAdapterMultimodal:
# Build screenshots interleaved with assistant messages. The eviction frontier
# advances in whole batches, so use a count that lands exactly on one advance.
- from agent.anthropic_message_convert import (
- _OUTBOUND_IMAGE_LIMIT,
- _SCREENSHOT_EVICTION_BATCH,
- )
+ from agent.image_eviction_policy import IMAGE_EVICTION_BATCH, OUTBOUND_IMAGE_LIMIT
- total = _OUTBOUND_IMAGE_LIMIT + 1
+ total = OUTBOUND_IMAGE_LIMIT + 1
messages: List[Dict[str, Any]] = [{"role": "user", "content": "start"}]
for i in range(total):
messages.append({
@@ -514,20 +511,17 @@ class TestAnthropicAdapterMultimodal:
for x in b["content"]
)
]
- assert len(placeholders) == _SCREENSHOT_EVICTION_BATCH
- assert len(with_images) == total - _SCREENSHOT_EVICTION_BATCH
+ assert len(placeholders) == IMAGE_EVICTION_BATCH
+ assert len(with_images) == total - IMAGE_EVICTION_BATCH
def test_parallel_batch_retires_the_oldest_siblings_first(self):
"""Sibling tool_results in one user message are oldest-first; eviction must not
retire the newest of them (#103217)."""
- from agent.anthropic_message_convert import (
- _OUTBOUND_IMAGE_LIMIT,
- _SCREENSHOT_EVICTION_BATCH,
- _evict_old_screenshots,
- )
+ from agent.anthropic_message_convert import _evict_old_screenshots
+ from agent.image_eviction_policy import IMAGE_EVICTION_BATCH, OUTBOUND_IMAGE_LIMIT
img = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "A"}}
- n = _OUTBOUND_IMAGE_LIMIT + 1
+ n = OUTBOUND_IMAGE_LIMIT + 1
result = [{
"role": "user",
"content": [
@@ -540,7 +534,7 @@ class TestAnthropicAdapterMultimodal:
b["tool_use_id"] for b in result[0]["content"]
if any(x.get("type") == "image" for x in b["content"])
]
- assert survivors == [f"t{i}" for i in range(_SCREENSHOT_EVICTION_BATCH, n)]
+ assert survivors == [f"t{i}" for i in range(IMAGE_EVICTION_BATCH, n)]
def test_floor_yields_when_one_carrier_breaches_the_block_limit(self):
"""The keep floor shelters only breaches eviction cannot fix.
@@ -549,14 +543,15 @@ class TestAnthropicAdapterMultimodal:
a floor of three counted in carriers would retire nothing and ship a request the
API rejects. With no reserved uploads the breach is fixable, so it must be fixed.
"""
- from agent.anthropic_message_convert import _OUTBOUND_IMAGE_LIMIT, _evict_old_screenshots
+ from agent.anthropic_message_convert import _evict_old_screenshots
+ from agent.image_eviction_policy import OUTBOUND_IMAGE_LIMIT
img = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "A"}}
result = [{
"role": "user",
"content": [{
"type": "tool_result", "tool_use_id": "t0",
- "content": [dict(img) for _ in range(_OUTBOUND_IMAGE_LIMIT + 5)],
+ "content": [dict(img) for _ in range(OUTBOUND_IMAGE_LIMIT + 5)],
}],
}]
_evict_old_screenshots(result)
@@ -565,10 +560,11 @@ class TestAnthropicAdapterMultimodal:
def test_a_batch_that_would_blind_the_model_stops_at_the_floor(self):
"""Fifteen reserved uploads plus six one-frame tool_results: one eight-wide batch would
retire every frame although keeping the newest three already clears the ceiling."""
- from agent.anthropic_message_convert import _OUTBOUND_IMAGE_LIMIT, _evict_old_screenshots
+ from agent.anthropic_message_convert import _evict_old_screenshots
+ from agent.image_eviction_policy import OUTBOUND_IMAGE_LIMIT
img = {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": "A"}}
- result = [{"role": "user", "content": [dict(img) for _ in range(_OUTBOUND_IMAGE_LIMIT - 5)]}]
+ result = [{"role": "user", "content": [dict(img) for _ in range(OUTBOUND_IMAGE_LIMIT - 5)]}]
for i in range(6):
result.append({"role": "assistant", "content": [{"type": "tool_use", "id": f"t{i}", "name": "s", "input": {}}]})
result.append({"role": "user", "content": [{"type": "tool_result", "tool_use_id": f"t{i}", "content": [dict(img)]}]})
@@ -577,7 +573,8 @@ class TestAnthropicAdapterMultimodal:
b["tool_use_id"] for m in result for b in m["content"]
if b.get("type") == "tool_result" and any(x.get("type") == "image" for x in b["content"])
]
- assert kept == ["t3", "t4", "t5"]
+ assert kept[-3:] == ["t3", "t4", "t5"]
+ assert OUTBOUND_IMAGE_LIMIT - 5 + len(kept) <= OUTBOUND_IMAGE_LIMIT
def test_eviction_frontier_holds_between_batch_advances(self):
"""Screenshot eviction must not rewrite a new block on every capture.
@@ -587,11 +584,8 @@ class TestAnthropicAdapterMultimodal:
forcing a full-prefix re-write that costs far more than the image tokens it
reclaims.
"""
- from agent.anthropic_message_convert import (
- _OUTBOUND_IMAGE_LIMIT,
- _SCREENSHOT_EVICTION_BATCH,
- convert_messages_to_anthropic,
- )
+ from agent.anthropic_message_convert import convert_messages_to_anthropic
+ from agent.image_eviction_policy import IMAGE_EVICTION_BATCH, OUTBOUND_IMAGE_LIMIT
fake_png = "iVBORw0KGgo="
@@ -636,9 +630,9 @@ class TestAnthropicAdapterMultimodal:
# Span three batch windows. The placeholder count must step once per batch (a
# one-step frontier fails the plateau check) AND the surviving image count must
# never exceed the limit (a fixed one-batch retire fails that after window one).
- span = range(_OUTBOUND_IMAGE_LIMIT - 2, _OUTBOUND_IMAGE_LIMIT + 3 * _SCREENSHOT_EVICTION_BATCH)
+ span = range(OUTBOUND_IMAGE_LIMIT - 2, OUTBOUND_IMAGE_LIMIT + 3 * IMAGE_EVICTION_BATCH)
counts = [placeholder_count(n) for n in span]
- assert all(n - c <= _OUTBOUND_IMAGE_LIMIT for n, c in zip(span, counts)), counts
+ assert all(n - c <= OUTBOUND_IMAGE_LIMIT for n, c in zip(span, counts)), counts
steps = sum(a != b for a, b in zip(counts, counts[1:]))
assert steps == 3, (
f"eviction frontier moved {steps} times over {len(span)} screenshots (counts={counts}); "