Skip to content

The agent that grows with you

fix(agent): mirror substitute_api_content's guard in the estimator shadow

Israel Lot5c45d9c20886
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index ea8dc220b31..0645c35a6c0 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -2992,19 +2992,35 @@ def _wire_message_shadow(msg: Dict[str, Any]) -> Dict[str, Any]:
``content`` at every API-bound build site, so exactly one of the two is
ever sent. Counting both double-counts any message whose sidecar differs
from its clean stored content (2.00x on a 40KB sidecar).
+
+ The substitution mirrors that helper's guard exactly: only a non-empty
+ STRING sidecar on a ``user``/``assistant`` row displaces ``content``.
+ Any other sidecar shape is popped and discarded on the wire without
+ touching ``content``, so a shadow that substituted unconditionally
+ would UNDERcount those rows — the dangerous direction, since it makes
+ compaction fire too late and the turn dies on a hard context error.
* Base64 image payloads are replaced with a placeholder; they are charged
separately at a flat rate by ``_count_image_tokens``, and counting their
raw chars here would massively overestimate usage.
"""
+ sidecar = msg.get("api_content")
+ sidecar_wins = (
+ isinstance(sidecar, str)
+ and bool(sidecar)
+ and msg.get("role") in ("user", "assistant")
+ )
shadow: Dict[str, Any] = {}
for k, v in msg.items():
if k == "_anthropic_content_blocks":
continue
if k == "api_content":
- shadow["content"] = v
+ # Always popped before the request is built; only counted when it
+ # actually replaces ``content``.
+ if sidecar_wins:
+ shadow["content"] = v
continue
if k == "content":
- if "api_content" in msg:
+ if sidecar_wins:
# The sidecar wins on the wire; skip the clean copy so the
# same logical content is not counted twice.
continue
diff --git a/tests/agent/test_model_metadata.py b/tests/agent/test_model_metadata.py
index febcd24106f..5a3440f0401 100644
--- a/tests/agent/test_model_metadata.py
+++ b/tests/agent/test_model_metadata.py
@@ -104,8 +104,36 @@ class TestEstimateMessagesTokensRough:
# substituted (which would undercount the real request).
assert result >= (len(big_sidecar) // 4) * 0.9
- def test_api_content_does_not_defeat_image_stripping(self):
- """A sidecar must not smuggle raw base64 past the flat image rate."""
+ def test_non_string_api_content_does_not_displace_content(self):
+ """Only a sidecar shape the wire actually substitutes may displace content.
+
+ ``substitute_api_content()`` overwrites ``content`` only for a
+ non-empty STRING sidecar on a user/assistant row; every other shape
+ is popped and discarded, leaving the clean ``content`` on the wire.
+ The shadow must mirror that guard — substituting unconditionally
+ would drop the real content from the estimate and UNDERcount, which
+ is the dangerous direction (compaction fires too late and the turn
+ dies on a hard context error).
+ """
+ body = "clean stored content " * 2000
+ baseline = estimate_messages_tokens_rough([{"role": "user", "content": body}])
+
+ for bad_sidecar in (None, "", 42, ["not", "a", "string"]):
+ msg = {"role": "user", "content": body, "api_content": bad_sidecar}
+ assert estimate_messages_tokens_rough([msg]) >= baseline, bad_sidecar
+
+ # Same for a role the substitution never applies to.
+ tool_row = {"role": "tool", "content": body, "api_content": "ignored"}
+ assert estimate_messages_tokens_rough([tool_row]) >= baseline
+
+ def test_image_stripping_survives_shadow_extraction(self):
+ """Non-regression for the ``_wire_message_shadow()`` extraction.
+
+ Both estimator helpers now share one shadow builder; this pins the
+ flat per-image accounting that the extraction moved, independent of
+ the ``api_content`` fix (a valid sidecar is a string, so it cannot
+ carry an image list).
+ """
import base64
import os