Skip to content

The agent that grows with you

fix(anthropic): simplify recovery and make accounting explicit

JoaoMarcos446403dd325c22
diff --git a/agent/anthropic_thinking_replay.py b/agent/anthropic_thinking_replay.py
index c65ba7e385a..0a0dccc13bc 100644
--- a/agent/anthropic_thinking_replay.py
+++ b/agent/anthropic_thinking_replay.py
@@ -1,140 +1,77 @@
-"""Durable suppression of Anthropic thinking blocks rejected by signature validation.
+"""Durable request-local suppression for Anthropic thinking rejected by signature validation.
-A signature failure is request-specific evidence about opaque replay blocks, not a reason
-to erase canonical reasoning history. Store only hashes of rejected signatures in the
-session model config, filter every replay carrier on retry, and reapply the suppression
-when a later request (or resumed process) rebuilds the wire copy.
+Canonical history stays untouched. We persist only fingerprints of rejected opaque
+signature/data values, then filter those blocks from each rebuilt request copy. This is
+needed beyond the immediate retry because context selection and process resume can rebuild
+from canonical history later.
"""
from __future__ import annotations
import hashlib
-import json
import logging
-from typing import Any, Iterable
+from typing import Any
logger = logging.getLogger(__name__)
_MODEL_CONFIG_KEY = "_anthropic_rejected_thinking"
_THINKING_TYPES = frozenset({"thinking", "redacted_thinking"})
-
-
-def _opaque_value(block: Any) -> Any:
- if not isinstance(block, dict):
- return None
- if block.get("type") == "thinking":
- return block.get("signature")
- if block.get("type") == "redacted_thinking":
- return block.get("data")
- return None
+_CARRIERS = ("reasoning_details", "anthropic_content_blocks", "_anthropic_content_blocks")
+_STRIP_ALL = "*"
def _fingerprint(block: Any) -> str | None:
- value = _opaque_value(block)
+ if not isinstance(block, dict) or block.get("type") not in _THINKING_TYPES:
+ return None
+ kind = block["type"]
+ value = block.get("signature" if kind == "thinking" else "data")
if value in (None, "", b""):
return None
- try:
- payload = json.dumps(value, sort_keys=True, ensure_ascii=True, default=str)
- except (TypeError, ValueError):
- payload = repr(value)
- kind = str(block.get("type") if isinstance(block, dict) else "")
+ payload = value if isinstance(value, str) else repr(value)
return hashlib.sha256(f"{kind}\0{payload}".encode("utf-8", "replace")).hexdigest()
-def _carrier_lists(message: Any) -> Iterable[list]:
- if not isinstance(message, dict):
- return
- for key in ("reasoning_details", "anthropic_content_blocks", "_anthropic_content_blocks"):
- value = message.get(key)
- if isinstance(value, list):
- yield value
-
-
-def _collect_fingerprints(messages: Any) -> set[str]:
- found: set[str] = set()
- if not isinstance(messages, list):
- return found
- for message in messages:
- for blocks in _carrier_lists(message):
- for block in blocks:
- if isinstance(block, dict) and block.get("type") in _THINKING_TYPES:
- if fp := _fingerprint(block):
- found.add(fp)
- return found
-
-
-def _decode_state(raw: Any) -> tuple[set[str], bool]:
- if isinstance(raw, list):
- return ({v for v in raw if isinstance(v, str) and v}, False)
- if not isinstance(raw, dict):
- return set(), False
- values = raw.get("fingerprints")
- fingerprints = {
- value for value in (values if isinstance(values, list) else [])
- if isinstance(value, str) and value
- }
- return fingerprints, bool(raw.get("strip_all"))
-
-
-def _load_state(agent: Any) -> tuple[set[str], bool]:
- if getattr(agent, "_anthropic_rejected_thinking_loaded", False):
- return (
- set(getattr(agent, "_anthropic_rejected_thinking_fingerprints", set()) or set()),
- bool(getattr(agent, "_anthropic_rejected_thinking_strip_all", False)),
- )
+def _rejected(agent: Any) -> set[str]:
+ if hasattr(agent, "_anthropic_rejected_thinking"):
+ return set(getattr(agent, "_anthropic_rejected_thinking") or set())
- fingerprints: set[str] = set()
- strip_all = False
+ rejected: set[str] = set()
getter = getattr(getattr(agent, "_session_db", None), "get_session_model_config_value", None)
session_id = getattr(agent, "session_id", None)
if session_id and callable(getter):
try:
- fingerprints, strip_all = _decode_state(getter(session_id, _MODEL_CONFIG_KEY, None))
+ raw = getter(session_id, _MODEL_CONFIG_KEY, [])
+ if isinstance(raw, list):
+ rejected.update(value for value in raw if isinstance(value, str) and value)
+ elif isinstance(raw, dict):
+ # Compatibility with the earlier review-fix head.
+ values = raw.get("fingerprints")
+ if isinstance(values, list):
+ rejected.update(value for value in values if isinstance(value, str) and value)
+ if raw.get("strip_all"):
+ rejected.add(_STRIP_ALL)
except Exception:
logger.debug("Anthropic thinking suppression restore failed", exc_info=True)
- agent._anthropic_rejected_thinking_fingerprints = fingerprints
- agent._anthropic_rejected_thinking_strip_all = strip_all
- agent._anthropic_rejected_thinking_loaded = True
- return fingerprints, strip_all
+ agent._anthropic_rejected_thinking = rejected
+ return rejected
-def _persist_state(agent: Any, fingerprints: set[str], strip_all: bool) -> None:
+def _persist(agent: Any, rejected: set[str]) -> None:
if getattr(agent, "_persist_disabled", False):
return
patcher = getattr(getattr(agent, "_session_db", None), "patch_session_model_config", None)
session_id = getattr(agent, "session_id", None)
if not session_id or not callable(patcher):
return
- value = {
- "fingerprints": sorted(fingerprints),
- "strip_all": bool(strip_all),
- }
try:
- patcher(session_id, {_MODEL_CONFIG_KEY: value})
+ patcher(session_id, {_MODEL_CONFIG_KEY: sorted(rejected)})
except Exception:
logger.debug("Anthropic thinking suppression persist failed", exc_info=True)
-def _should_remove(block: Any, fingerprints: set[str], strip_all: bool) -> bool:
- if not isinstance(block, dict) or block.get("type") not in _THINKING_TYPES:
- return False
- if strip_all:
- return True
- fp = _fingerprint(block)
- return fp is not None and fp in fingerprints
-
-
def _mirrored_readable_thinking(message: Any) -> str | None:
- """Readable thinking mirrored into canonical reasoning fields, if identifiable.
-
- Anthropic normalization stores each signed thinking block in reasoning_details
- and stores their readable text joined by a blank line in reasoning/reasoning_content.
- Ordered blocks duplicate the same data only for interleaved tool turns. Prefer
- reasoning_details so a rejected signed carrier cannot fall back through the generic
- mirror after suppression.
- """
if not isinstance(message, dict):
return None
for key in ("reasoning_details", "anthropic_content_blocks"):
@@ -156,18 +93,24 @@ def _mirrored_readable_thinking(message: Any) -> str | None:
return None
-def _filter_message(message: Any, fingerprints: set[str], strip_all: bool) -> int:
+def _strip_message(message: Any, rejected: set[str]) -> int:
if not isinstance(message, dict):
return 0
- mirrored = _mirrored_readable_thinking(message)
+
+ mirror = _mirrored_readable_thinking(message)
removed = 0
- for key in ("reasoning_details", "anthropic_content_blocks", "_anthropic_content_blocks"):
+ for key in _CARRIERS:
blocks = message.get(key)
if not isinstance(blocks, list):
continue
kept = []
for block in blocks:
- if _should_remove(block, fingerprints, strip_all):
+ fingerprint = _fingerprint(block)
+ if (
+ isinstance(block, dict)
+ and block.get("type") in _THINKING_TYPES
+ and (_STRIP_ALL in rejected or (fingerprint is not None and fingerprint in rejected))
+ ):
removed += 1
else:
kept.append(block)
@@ -176,55 +119,46 @@ def _filter_message(message: Any, fingerprints: set[str], strip_all: bool) -> in
else:
message.pop(key, None)
- # Canonical Anthropic storage also keeps the same readable thinking in generic
- # reasoning fields. If any signed block from that exact mirror was rejected,
- # remove the mirror from this request copy too; otherwise context selection can
- # resurrect the rejected thinking as an unsigned block after its carrier is gone.
- if removed and mirrored is not None:
+ # Once a signed carrier is rejected, do not let its canonical readable mirror
+ # re-enter native conversion as unsigned reasoning after context replacement.
+ if removed and mirror is not None:
for key in ("reasoning", "reasoning_content"):
- if message.get(key) == mirrored:
+ if message.get(key) == mirror:
message.pop(key, None)
return removed
def apply_rejected_thinking_suppression(agent: Any, messages: Any) -> int:
- """Filter previously rejected thinking from a freshly built request copy."""
+ """Filter rejected thinking from a request copy rebuilt from canonical history."""
if getattr(agent, "api_mode", None) != "anthropic_messages" or not isinstance(messages, list):
return 0
- fingerprints, strip_all = _load_state(agent)
- if not fingerprints and not strip_all:
+ rejected = _rejected(agent)
+ if not rejected:
return 0
- return sum(_filter_message(message, fingerprints, strip_all) for message in messages)
+ return sum(_strip_message(message, rejected) for message in messages)
def remember_rejected_thinking(agent: Any, api_messages: Any) -> int:
- """Remember signed blocks from a rejected request and remove them from every carrier.
-
- The provider error generally does not identify which signed block failed, so all signed
- thinking blocks in that rejected request become suppressed suspects. New blocks produced
- later have different signatures and continue to replay normally.
- """
+ """Fingerprint the rejected request and repair its retry copy without mutating history."""
if not isinstance(api_messages, list):
return 0
- current = _collect_fingerprints(api_messages)
- fingerprints, strip_all = _load_state(agent)
- if current:
- fingerprints.update(current)
- else:
- # Defensive fallback: a signature-classified error without an inspectable signature
- # must still change the retry request instead of burning the one-shot on identical bytes.
- strip_all = True
-
- agent._anthropic_rejected_thinking_fingerprints = fingerprints
- agent._anthropic_rejected_thinking_strip_all = strip_all
- agent._anthropic_rejected_thinking_loaded = True
- _persist_state(agent, fingerprints, strip_all)
-
- # Suppression changes provider-visible history without changing the canonical
- # content/tool fingerprint used by usage anchors. An old provider count would
- # therefore still appear valid and override the smaller repaired request.
+ current = {
+ fingerprint
+ for message in api_messages
+ if isinstance(message, dict)
+ for key in _CARRIERS
+ for block in (message.get(key) if isinstance(message.get(key), list) else ())
+ if (fingerprint := _fingerprint(block)) is not None
+ }
+ rejected = _rejected(agent)
+ rejected.update(current or {_STRIP_ALL})
+ agent._anthropic_rejected_thinking = rejected
+ _persist(agent, rejected)
+
+ # The provider-visible history changed while the canonical content fingerprint did
+ # not, so a previous prompt-token anchor is no longer valid for this request shape.
from agent.usage_anchor import set_usage_anchor
set_usage_anchor(agent, None)
- return sum(_filter_message(message, fingerprints, strip_all) for message in api_messages)
+ return sum(_strip_message(message, rejected) for message in api_messages)
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.py
index 3a39788173f..8ea8eccabb8 100644
--- a/agent/message_sanitization.py
+++ b/agent/message_sanitization.py
@@ -638,20 +638,20 @@ def stale_thinking_reaches_wire(api_mode: Any, provider: Any, model: Any, base_u
return (api_mode or "") != "codex_responses" and needs_reasoning_echo(provider, model, base_url)
-def native_anthropic_accounting_projection(messages: Any) -> Any:
- """Project native Anthropic replay messages into the generic rough estimator.
-
- Canonical history may retain storage-only reasoning alongside the signed replay
- carriers. Native conversion prefers ordered anthropic_content_blocks over
- reasoning_details and never sends reasoning itself, so charging all three
- representations can double-count the same thinking. Keep normal content/tool
- payloads, replace the active replay carrier with readable thinking text exactly
- once, and never price opaque signature/data bytes as plaintext.
+def native_anthropic_accounting_projection(messages: Any) -> tuple[Any, tuple[str, ...]]:
+ """Return the native Anthropic wire shadow plus readable replay thinking out-of-band.
+
+ Canonical history may retain storage-only reasoning alongside signed replay carriers.
+ Native conversion prefers ordered anthropic_content_blocks over reasoning_details and
+ never sends reasoning itself. The generic message estimator therefore receives only
+ ordinary wire-shaped fields, while readable thinking is returned separately for the
+ explicit Anthropic accounting seam. Opaque signature/data bytes are never priced.
"""
if not isinstance(messages, list):
- return messages
+ return messages, ()
projected = []
+ replayed_thinking: list[str] = []
replayable_ordered_types = {"thinking", "redacted_thinking", "text", "tool_use", "image"}
thinking_types = {"thinking", "redacted_thinking"}
for message in messages:
@@ -697,11 +697,9 @@ def native_anthropic_accounting_projection(messages: Any) -> Any:
and block.get("thinking")
):
readable.append(block["thinking"])
- if readable:
- shadow["_anthropic_readable_thinking_estimate"] = "\n".join(readable)
-
+ replayed_thinking.extend(readable)
projected.append(shadow)
- return projected
+ return projected, tuple(replayed_thinking)
def apply_reasoning_content_policy(source_msg: dict, api_msg: dict, needs_thinking_pad: bool) -> None:
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index c95bc58431d..e305e1c93cd 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -2410,6 +2410,29 @@ def estimate_messages_tokens_rough(messages: List[Dict[str, Any]], *, charge_sta
return sum(_estimate_message_tokens_cached(msg, image_cost) for msg in messages)
+def estimate_native_anthropic_messages_tokens_rough(messages: List[Dict[str, Any]]) -> int:
+ """Estimate native Anthropic messages with replayed readable thinking charged exactly once."""
+ from agent.message_sanitization import native_anthropic_accounting_projection
+
+ projected, replayed_thinking = native_anthropic_accounting_projection(messages)
+ return estimate_messages_tokens_rough(projected) + sum(
+ estimate_tokens_rough(text) for text in replayed_thinking
+ )
+
+
+def estimate_native_anthropic_request_tokens_rough(
+ messages: List[Dict[str, Any]], *, system_prompt: str = "",
+ tools: Optional[List[Dict[str, Any]]] = None,
+) -> int:
+ """Request estimate for native Anthropic; opaque replay bytes never enter text accounting."""
+ from agent.message_sanitization import native_anthropic_accounting_projection
+
+ projected, replayed_thinking = native_anthropic_accounting_projection(messages)
+ return estimate_request_tokens_rough(
+ projected, system_prompt=system_prompt, tools=tools
+ ) + sum(estimate_tokens_rough(text) for text in replayed_thinking)
+
+
# Thinking-text keys replayed for at most the newest assistant turn on non-echo routes — must stay
# in lockstep with ``context_compressor._NEWEST_TURN_ONLY_BUDGET_KEYS``.
_STALE_THINKING_ESTIMATE_KEYS = ("reasoning", "reasoning_content")
diff --git a/agent/turn_context.py b/agent/turn_context.py
index db075141bde..cd902474841 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -23,7 +23,11 @@ from agent.memory_manager import build_memory_context_block
from agent.memory_provider import is_trivial_prompt
from agent.message_content import flatten_message_text
from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, append_message, stamp_message_timestamp
-from agent.model_metadata import estimate_messages_tokens_rough, estimate_request_tokens_rough
+from agent.model_metadata import (
+ estimate_messages_tokens_rough,
+ estimate_native_anthropic_request_tokens_rough,
+ estimate_request_tokens_rough,
+)
from agent.image_token_cost import bind_image_token_cost
from agent.usage_anchor import anchored_context_tokens, restore_usage_anchor
from agent.turn_author import parse_turn_author
@@ -69,17 +73,18 @@ def _preflight_request_tokens(
getattr(agent, "base_url", ""), getattr(agent, "model", "")
):
from agent.anthropic_thinking_replay import apply_rejected_thinking_suppression
- from agent.message_sanitization import native_anthropic_accounting_projection
# Preflight runs on canonical history, while the eventual request is a
# filtered copy. Mirror suppression onto shallow message copies before
- # projection so already-rejected blocks cannot trigger phantom compression.
+ # pricing the exact native replay carriers.
estimate_messages = [
dict(message) if isinstance(message, dict) else message
for message in messages
]
apply_rejected_thinking_suppression(agent, estimate_messages)
- estimate_messages = native_anthropic_accounting_projection(estimate_messages)
+ return estimate_native_anthropic_request_tokens_rough(
+ estimate_messages, system_prompt=system_prompt or "", tools=tools
+ )
return estimate_request_tokens_rough(
estimate_messages, system_prompt=system_prompt or "", tools=tools,
charge_stale_thinking=charge_stale_thinking,
diff --git a/agent/turn_request_assembly.py b/agent/turn_request_assembly.py
index c9fdf5ff617..be7436e72fc 100644
--- a/agent/turn_request_assembly.py
+++ b/agent/turn_request_assembly.py
@@ -13,10 +13,7 @@ from dataclasses import dataclass
import logging
from typing import Any
-from agent.message_sanitization import (
- _sanitize_messages_surrogates,
- native_anthropic_accounting_projection,
-)
+from agent.message_sanitization import _sanitize_messages_surrogates
from agent.usage_anchor import anchored_context_tokens
from agent.prompt_caching import build_prompt_cache_plan, effective_cache_ttl
from agent.turn_context import build_api_messages
@@ -118,7 +115,10 @@ def assemble_api_request(
_CODEX_INCOMPLETE_NUDGE, _apply_context_engine_selection, _canonicalize_api_tool_calls,
_clone_message_for_send, _midturn_request_pressure_tokens, _pressure_with_real_floor,
)
- from agent.model_metadata import estimate_messages_tokens_rough
+ from agent.model_metadata import (
+ estimate_messages_tokens_rough,
+ estimate_native_anthropic_messages_tokens_rough,
+ )
api_messages, effective_system = build_api_messages(
agent, messages, current_turn_user_idx=current_turn_user_idx,
@@ -244,15 +244,17 @@ def assemble_api_request(
from agent.turn_context import _agent_stale_thinking_on_wire
if _agent_stale_thinking_on_wire(agent):
- _estimate_messages = api_messages
if getattr(agent, "api_mode", "") == "anthropic_messages":
from agent.anthropic_thinking_policy import native_anthropic_preserves_prior_thinking
if native_anthropic_preserves_prior_thinking(
getattr(agent, "base_url", ""), getattr(agent, "model", "")
):
- _estimate_messages = native_anthropic_accounting_projection(api_messages)
- approx_tokens = estimate_messages_tokens_rough(_estimate_messages)
+ approx_tokens = estimate_native_anthropic_messages_tokens_rough(api_messages)
+ else:
+ approx_tokens = estimate_messages_tokens_rough(api_messages)
+ else:
+ approx_tokens = estimate_messages_tokens_rough(api_messages)
else:
approx_tokens = estimate_messages_tokens_rough(api_messages, charge_stale_thinking=False)
# Route-aware: native Responses compaction prunes the wire payload, so the raw
diff --git a/tests/agent/test_anthropic_preserved_thinking_replay.py b/tests/agent/test_anthropic_preserved_thinking_replay.py
index d5debbcd36b..9995c9e8e4d 100644
--- a/tests/agent/test_anthropic_preserved_thinking_replay.py
+++ b/tests/agent/test_anthropic_preserved_thinking_replay.py
@@ -11,7 +11,11 @@ from agent.message_sanitization import (
native_anthropic_accounting_projection,
stale_thinking_reaches_wire,
)
-from agent.model_metadata import estimate_messages_tokens_rough
+from agent.model_metadata import (
+ estimate_messages_tokens_rough,
+ estimate_native_anthropic_messages_tokens_rough,
+ estimate_native_anthropic_request_tokens_rough,
+)
def _signed_turn(question: str, answer: str, sig: str, *, thinking: str | None = None):
@@ -430,7 +434,6 @@ def test_context_selection_canonical_clone_does_not_double_count_thinking(monkey
def test_canonical_preflight_dedupes_ordered_thinking_carrier():
- from agent.model_metadata import estimate_request_tokens_rough
from agent.turn_context import _preflight_request_tokens
agent = _assembly_agent()
@@ -456,9 +459,7 @@ def test_canonical_preflight_dedupes_ordered_thinking_carrier():
request_copy = copy.deepcopy(canonical)
request_copy[1].pop("reasoning", None)
- expected = estimate_request_tokens_rough(
- native_anthropic_accounting_projection(request_copy)
- )
+ expected = estimate_native_anthropic_request_tokens_rough(request_copy)
assert preflight == expected
@@ -476,16 +477,16 @@ def test_native_accounting_projection_dedupes_ordered_carrier_and_opaque_bytes()
ordered_only = copy.deepcopy(huge_opaque)
ordered_only.pop("reasoning_details")
- projected_huge = native_anthropic_accounting_projection([huge_opaque])
- projected_ordered = native_anthropic_accounting_projection([ordered_only])
- projected_small = native_anthropic_accounting_projection([base])
+ projected_huge, readable = native_anthropic_accounting_projection([huge_opaque])
- assert estimate_messages_tokens_rough(projected_huge) == estimate_messages_tokens_rough(
- projected_ordered
- )
- assert estimate_messages_tokens_rough(projected_huge) == estimate_messages_tokens_rough(
- projected_small
- )
+ assert "_anthropic_readable_thinking_estimate" not in repr(projected_huge)
+ assert readable == ("x" * 8000,)
+ assert estimate_native_anthropic_messages_tokens_rough(
+ [huge_opaque]
+ ) == estimate_native_anthropic_messages_tokens_rough([ordered_only])
+ assert estimate_native_anthropic_messages_tokens_rough(
+ [huge_opaque]
+ ) == estimate_native_anthropic_messages_tokens_rough([base])
def test_context_selection_cannot_restore_rejected_thinking(monkeypatch):