The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): round the eviction overshoot up to whole batches so the image limit actually holds
teknium1c37753c424bd
diff --git a/agent/anthropic_message_convert.py b/agent/anthropic_message_convert.pyindex 482508ce521..6479285755a 100644--- a/agent/anthropic_message_convert.py+++ b/agent/anthropic_message_convert.py@@ -618,7 +618,12 @@ def _evict_old_screenshots(result: List[Dict[str, Any]]) -> None:]if len(blocks) <= _OUTBOUND_IMAGE_LIMIT:return- retire = min(_SCREENSHOT_EVICTION_BATCH, max(len(blocks) - _MAX_KEEP_SCREENSHOTS, 0))+ # 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+ # "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:]:placeholder = _text_block("[screenshot removed to save context]")block["content"] = [diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 1e8ea16f757..063037979b7 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -1274,6 +1274,32 @@ def _retire_stale_tool_result_images(return pruned+def _batched_retire_count(+ count: int,+ sizes_newest_first: List[int],+ *,+ limit: int,+ budget: int,+ batch: int,+ keep_newest: int,+) -> int:+ """How many of the OLDEST image-bearing 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.+ """+ if count <= 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)))++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")@@ -1311,12 +1337,17 @@ def evict_stale_outbound_tool_images(and api_messages[i].get("role") == "tool"and (size := _image_payload_bytes(api_messages[i])) > 0]- over = len(images) > _OUTBOUND_IMAGE_LIMIT or sum(s for _, s in images) > _OUTBOUND_IMAGE_BUDGET_BYTES- if not over:+ retire = _batched_retire_count(+ len(images),+ [s for _, s in images],+ limit=_OUTBOUND_IMAGE_LIMIT,+ budget=_OUTBOUND_IMAGE_BUDGET_BYTES,+ batch=_IMAGE_EVICTION_BATCH,+ keep_newest=keep_newest,+ )+ if retire <= 0:return 0- # Retire a whole batch so the next several turns stay under the limit and append cleanly.- retire = min(_IMAGE_EVICTION_BATCH, max(len(images) - keep_newest, 0))pruned = 0for i, _ in images[-retire:]:new_msg = _strip_images_from_tool_msg(api_messages[i])diff --git a/tests/agent/test_outbound_stale_vision.py b/tests/agent/test_outbound_stale_vision.pyindex df4ea642a3a..23426ee6938 100644--- a/tests/agent/test_outbound_stale_vision.py+++ b/tests/agent/test_outbound_stale_vision.py@@ -109,17 +109,21 @@ class TestOutboundStaleVisionEviction:"""from agent.conversation_loop import _clone_message_for_send- def first_surviving(n: int) -> str:+ def surviving(n: int) -> list:msgs = [_clone_message_for_send(m) for m in _history_with_screenshots(n)]evict_stale_outbound_tool_images(msgs)- return _image_bearing_tool_ids(msgs)[0]-- span = range(_MAX_KEEP_TOOL_IMAGES + 1, _OUTBOUND_IMAGE_LIMIT + _IMAGE_EVICTION_BATCH)- frontier = [first_surviving(n) for n in span]- held = sum(a == b for a, b in zip(frontier, frontier[1:]))- assert held >= len(frontier) - 3, (- f"eviction advanced on nearly every image (frontier={frontier}); "- "each advance rewrites a cached row and restarts the prefix"+ return _image_bearing_tool_ids(msgs)++ # 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)+ kept = [surviving(n) for n in span]+ 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, (+ f"frontier moved {moves} times over {len(span)} images (frontier={frontier}); "+ "each move rewrites a cached row and restarts the prefix")def test_does_not_rewrite_persisted_history(self):diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.pyindex 9613371d5ed..d61732740d9 100644--- a/tests/tools/test_computer_use.py+++ b/tests/tools/test_computer_use.py@@ -571,17 +571,17 @@ class TestAnthropicAdapterMultimodal:))- # The frontier must hold across at least one new screenshot. Asserted as an- # absolute invariant rather than against the batch constant, so shrinking the- # batch back to a one-step frontier fails this test.- counts = [placeholder_count(n) for n in range(_OUTBOUND_IMAGE_LIMIT - 2,- _OUTBOUND_IMAGE_LIMIT + _SCREENSHOT_EVICTION_BATCH)]- held = [a == b for a, b in zip(counts, counts[1:])]- assert any(held), (- f"eviction rewrote a new block on every screenshot (counts={counts}); "+ # 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)+ counts = [placeholder_count(n) for n in span]+ 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}); ""each step invalidates the cached prefix")- assert counts[-1] >= counts[0], "eviction must still make progress"# ---------------------------------------------------------------------------# Context compressor: screenshot-aware pruning