Skip to content

The agent that grows with you

test(anthropic): fold preserved-thinking replay tests into two invariants

kshitijk4poor4ba9073cc45a
diff --git a/tests/agent/test_anthropic_preserved_thinking_replay.py b/tests/agent/test_anthropic_preserved_thinking_replay.py
index 8873bc37a24..adc5d46b04f 100644
--- a/tests/agent/test_anthropic_preserved_thinking_replay.py
+++ b/tests/agent/test_anthropic_preserved_thinking_replay.py
@@ -7,657 +7,308 @@ from types import SimpleNamespace
import pytest
from agent.anthropic_message_convert import convert_messages_to_anthropic
-from agent.message_sanitization import (
- native_anthropic_accounting_projection,
- stale_thinking_reaches_wire,
-)
-from agent.model_metadata import (
- estimate_messages_tokens_rough,
- estimate_native_anthropic_messages_tokens_rough,
- estimate_native_anthropic_request_tokens_rough,
-)
+from agent.message_sanitization import stale_thinking_reaches_wire
+from agent.model_metadata import estimate_tokens_rough
+ANTHROPIC = ("anthropic", "https://api.anthropic.com")
+NOUS = ("nous", "https://inference-api.nousresearch.com/v1/messages")
+OPENROUTER = ("openrouter", "https://openrouter.ai/api/v1")
+KIMI = ("anthropic", "https://api.kimi.com/coding")
-def _signed_turn(question: str, answer: str, sig: str, *, thinking: str | None = None):
+
+def _signed_turn(question, answer, sig, *, thinking=None):
+ thinking = thinking or f"thought-{sig}"
return [
{"role": "user", "content": question},
{
"role": "assistant",
"content": answer,
- "reasoning": thinking or f"thought-{sig}",
- "reasoning_details": [
- {"type": "thinking", "thinking": thinking or f"thought-{sig}", "signature": sig}
- ],
+ "reasoning": thinking,
+ "reasoning_details": [{"type": "thinking", "thinking": thinking, "signature": sig}],
},
]
-def _assistant(messages, index: int):
- return [m for m in messages if m["role"] == "assistant"][index]
-
-
- ("model", "expected"),
- [
- ("claude-opus-4-4", False),
- ("claude-opus-4-5", True),
- ("claude-opus-4-6", True),
- ("claude-sonnet-4-5", False),
- ("claude-sonnet-4-6", True),
- ("claude-opus-4-20250514", False),
- ("claude-sonnet-4-20250514", False),
- ("claude-opus-4-5-20251101", True),
- ("claude-opus-4-6-20250414", True),
- ("claude-sonnet-4-5-20250929", False),
- ("claude-opus-5", True),
- ("claude-sonnet-5-5", True),
- ("claude-fable-5-1", True),
- ("claude-mythos-5", True),
- ("claude-mythos-preview", True),
- ("claude-haiku-4-5", False),
- ],
-)
-def test_native_anthropic_wire_truth_tracks_preserved_thinking_models(model, expected):
- assert stale_thinking_reaches_wire(
- "anthropic_messages", "anthropic", model, "https://api.anthropic.com"
- ) is expected
-
-
-def test_formerly_latest_turn_stays_byte_stable_on_preserved_thinking_model():
- prefix = _signed_turn("Q1", "A1", "sig_1") + _signed_turn("Q2", "A2", "sig_2")
- _, short = convert_messages_to_anthropic(prefix, model="claude-opus-4-6")
- _, long = convert_messages_to_anthropic(
- prefix + _signed_turn("Q3", "A3", "sig_3"), model="claude-opus-4-6"
- )
-
- assert _assistant(short, 1) == _assistant(long, 1)
- assert _assistant(long, 1)["content"][0]["signature"] == "sig_2"
-
-
-def test_older_claude_keeps_latest_only_policy():
- messages = _signed_turn("Q1", "A1", "sig_1") + _signed_turn("Q2", "A2", "sig_2")
- _, converted = convert_messages_to_anthropic(messages, model="claude-sonnet-4-5")
-
- first, second = (_assistant(converted, 0), _assistant(converted, 1))
- assert not any(
- isinstance(block, dict) and block.get("type") in {"thinking", "redacted_thinking"}
- for block in first["content"]
- )
- assert any(
- isinstance(block, dict) and block.get("type") == "thinking"
- for block in second["content"]
- )
-
-
-def test_preserved_thinking_accounting_charges_historical_turns():
- thinking = "x" * 8000
- messages = (
- _signed_turn("Q1", "A1", "sig_1", thinking=thinking)
- + _signed_turn("Q2", "A2", "sig_2", thinking=thinking)
- + _signed_turn("Q3", "A3", "sig_3", thinking=thinking)
- )
- keep_all = estimate_messages_tokens_rough(messages, charge_stale_thinking=True)
- latest_only = estimate_messages_tokens_rough(messages, charge_stale_thinking=False)
-
- assert keep_all - latest_only >= 3500
-
-
-class _ConfigDB:
- def __init__(self):
- self.config = {}
-
- def patch_session_model_config(self, session_id, patch):
- self.config.update(patch)
-
- def get_session_model_config_value(self, session_id, key, default=None):
- return self.config.get(key, default)
-
-
-def _agent(db):
- return SimpleNamespace(
- api_mode="anthropic_messages",
- provider="anthropic",
- model="claude-opus-4-6",
- base_url="https://api.anthropic.com",
- session_id="session-1",
- _session_db=db,
- _persist_disabled=False,
- )
-
-
-def _carrier_message():
- return {
- "role": "assistant",
- "content": "answer",
- "reasoning": "secret chain",
- "reasoning_content": "secret chain",
- "reasoning_details": [
- {"type": "thinking", "thinking": "secret chain", "signature": "sig_bad"},
- {"type": "redacted_thinking", "data": "red_bad"},
- ],
- "anthropic_content_blocks": [
- {"type": "thinking", "thinking": "secret chain", "signature": "sig_bad"},
- {"type": "text", "text": "answer"},
- {"type": "tool_use", "id": "tool_1", "name": "search", "input": {"q": "x"}},
- {"type": "redacted_thinking", "data": "red_bad"},
- ],
- "tool_calls": [
- {
- "id": "tool_1",
- "type": "function",
- "function": {"name": "search", "arguments": "{\"q\":\"x\"}"},
- }
- ],
- }
-
-
-def _non_tool_carrier_message():
- message = _carrier_message()
- message["anthropic_content_blocks"] = [
- block
- for block in message["anthropic_content_blocks"]
- if block.get("type") != "tool_use"
- ]
- message.pop("tool_calls", None)
- return message
-
-
-def test_rejected_signature_is_removed_from_every_carrier_and_persists_across_resume():
- from agent.anthropic_thinking_replay import (
- apply_rejected_thinking_suppression,
- remember_rejected_thinking,
- )
-
- db = _ConfigDB()
- db.config["_usage_anchor"] = {"prompt_tokens": 999}
- first_agent = _agent(db)
- first_agent._usage_anchor = {"prompt_tokens": 999}
- request = [_carrier_message()]
-
- removed = remember_rejected_thinking(first_agent, request)
- assert removed >= 4
- assert "reasoning_details" not in request[0]
- assert "reasoning" not in request[0]
- assert "reasoning_content" not in request[0]
- assert first_agent._usage_anchor is None
- assert db.config["_usage_anchor"] is None
- assert [b["type"] for b in request[0]["anthropic_content_blocks"]] == ["text", "tool_use"]
-
- resumed_agent = _agent(db)
- rebuilt = [_carrier_message()]
- apply_rejected_thinking_suppression(resumed_agent, rebuilt)
- assert "reasoning_details" not in rebuilt[0]
- assert "reasoning" not in rebuilt[0]
- assert "reasoning_content" not in rebuilt[0]
- assert [b["type"] for b in rebuilt[0]["anthropic_content_blocks"]] == ["text", "tool_use"]
-
-
-def test_build_api_messages_applies_persisted_rejection_suppression():
- from agent.anthropic_thinking_replay import remember_rejected_thinking
- from agent.turn_context import build_api_messages
-
- db = _ConfigDB()
- first_agent = _agent(db)
- rejected = [_carrier_message()]
- remember_rejected_thinking(first_agent, rejected)
-
- resumed = _agent(db)
- resumed._current_turn_timestamp = 1.0
- resumed.ephemeral_system_prompt = ""
- resumed._copy_reasoning_content_for_api = lambda source, target: None
- resumed._should_sanitize_tool_calls = lambda: False
-
- history = [
+def _carrier(thinking="secret chain", opaque=""):
+ """Assistant row carrying the same thinking in every field the stores write."""
+ signed = {"type": "thinking", "thinking": thinking, "signature": "sig_bad" + "s" * len(opaque)}
+ redacted = {"type": "redacted_thinking", "data": "red_bad" + opaque}
+ return [
{"role": "user", "content": "Q"},
- _carrier_message(),
- {"role": "user", "content": "continue"},
+ {
+ "role": "assistant",
+ "content": "answer",
+ "reasoning": thinking,
+ "reasoning_content": thinking,
+ "timestamp": 1234567890.0,
+ "finish_reason": "tool_calls",
+ "reasoning_details": [dict(signed), dict(redacted)],
+ "anthropic_content_blocks": [
+ dict(signed),
+ {"type": "text", "text": "answer"},
+ {"type": "tool_use", "id": "tool_1", "name": "search", "input": {"q": "x"}},
+ dict(redacted),
+ ],
+ "tool_calls": [
+ {"id": "tool_1", "type": "function",
+ "function": {"name": "search", "arguments": "{\"q\":\"x\"}"}}
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tool_1", "content": "result"},
]
- api_messages, _ = build_api_messages(
- resumed,
- copy.deepcopy(history),
- current_turn_user_idx=2,
- ext_prefetch_cache="",
- plugin_user_context="",
- moa_config=None,
- active_system_prompt="",
- )
-
- assistant = next(m for m in api_messages if m.get("role") == "assistant")
- assert "reasoning_details" not in assistant
- assert [b["type"] for b in assistant["anthropic_content_blocks"]] == ["text", "tool_use"]
-
-
-def test_nous_portal_uses_same_preserved_thinking_capability_boundary():
- assert stale_thinking_reaches_wire(
- "anthropic_messages",
- "nous",
- "claude-opus-4-6",
- "https://inference-api.nousresearch.com/v1/messages",
- )
- assert not stale_thinking_reaches_wire(
- "anthropic_messages",
- "openrouter",
- "claude-opus-4-6",
- "https://openrouter.ai/api/v1",
- )
-
-
-def test_turn_recovery_repairs_recognized_anthropic_signature_rejection():
- from agent.error_classifier import FailoverReason
- from agent.turn_recovery import _recover_format_errors
- from agent.turn_retry_state import TurnRetryState
-
- db = _ConfigDB()
- agent = _agent(db)
- agent.log_prefix = ""
- agent._vprint = lambda *args, **kwargs: None
-
- canonical = [_carrier_message()]
- canonical_before = copy.deepcopy(canonical)
- request = copy.deepcopy(canonical)
- retry = TurnRetryState()
- classified = SimpleNamespace(reason=FailoverReason.thinking_signature)
+def _native_turn(agent, question, size, sig):
+ """A turn stored by the real producer: Anthropic response -> transport -> assistant row."""
+ from agent.chat_completion_helpers import build_assistant_message
+ from agent.transports.anthropic import AnthropicTransport
- assert _recover_format_errors(
- agent,
- RuntimeError("Invalid signature in thinking block"),
- classified,
- retry,
- canonical,
- request,
+ response = SimpleNamespace(
+ content=[
+ SimpleNamespace(type="thinking", thinking="x" * size, signature=sig),
+ SimpleNamespace(type="text", text="A"),
+ ],
+ stop_reason="end_turn",
+ stop_details=None,
)
- assert retry.thinking_sig_retry_attempted
- assert canonical == canonical_before
- assert "reasoning_details" not in request[0]
- assert [block["type"] for block in request[0]["anthropic_content_blocks"]] == [
- "text",
- "tool_use",
- ]
+ normalized = AnthropicTransport().normalize_response(response)
+ return [{"role": "user", "content": question},
+ build_assistant_message(agent, normalized, normalized.finish_reason)]
- rebuilt = copy.deepcopy(canonical)
- from agent.anthropic_thinking_replay import apply_rejected_thinking_suppression
- apply_rejected_thinking_suppression(_agent(db), rebuilt)
- assert "reasoning_details" not in rebuilt[0]
- assert [block["type"] for block in rebuilt[0]["anthropic_content_blocks"]] == [
- "text",
- "tool_use",
- ]
+def _session_db(tmp_path, *session_ids):
+ from hermes_state import SessionDB
-def test_dated_claude_4_snapshots_keep_latest_only_policy():
- for model in ("claude-opus-4-20250514", "claude-sonnet-4-20250514"):
- messages = _signed_turn("Q1", "A1", "sig_1") + _signed_turn("Q2", "A2", "sig_2")
- _, converted = convert_messages_to_anthropic(messages, model=model)
- first, second = (_assistant(converted, 0), _assistant(converted, 1))
- assert not any(
- isinstance(block, dict) and block.get("type") in {"thinking", "redacted_thinking"}
- for block in first["content"]
- )
- assert any(
- isinstance(block, dict) and block.get("type") == "thinking"
- for block in second["content"]
- )
+ db = SessionDB(db_path=tmp_path / "state.db")
+ for session_id in session_ids:
+ db.create_session(session_id, source="cli", model="claude-opus-4-6")
+ return db
-def _assembly_agent(db=None):
- agent = _agent(db or _ConfigDB())
- agent._current_turn_timestamp = 1.0
- agent.ephemeral_system_prompt = ""
- agent.prefill_messages = []
+def _agent(db, session_id="s1", model="claude-opus-4-6", route=ANTHROPIC):
from agent.agent_runtime_helpers import copy_reasoning_content_for_api
+ from agent.context_compressor import ContextCompressor
+ agent = SimpleNamespace(
+ api_mode="anthropic_messages", provider=route[0], model=model, base_url=route[1],
+ session_id=session_id, _session_db=db, _persist_disabled=False,
+ _current_turn_timestamp=1.0, ephemeral_system_prompt="", prefill_messages=[],
+ tools=[], _use_prompt_caching=False, _usage_anchor=None, verbose_logging=False,
+ reasoning_callback=None, stream_delta_callback=None, _stream_callback=None, log_prefix="",
+ )
agent._needs_thinking_reasoning_pad = lambda: False
agent._copy_reasoning_content_for_api = (
lambda source, target: copy_reasoning_content_for_api(agent, source, target)
)
agent._should_sanitize_tool_calls = lambda: False
agent._sanitize_api_messages = lambda value: value
- agent._emit_warning = lambda *args, **kwargs: None
+ agent._emit_warning = agent._vprint = lambda *args, **kwargs: None
agent._drop_thinking_only_and_merge_users = lambda value, **kwargs: value
- agent.tools = []
- agent._use_prompt_caching = False
- agent._usage_anchor = None
- agent.context_compressor = SimpleNamespace()
agent._extract_reasoning = lambda message: getattr(message, "reasoning", None)
agent._strip_think_blocks = lambda text: text
- agent.verbose_logging = False
- agent.reasoning_callback = None
- agent.stream_delta_callback = None
- agent._stream_callback = None
- return agent
-
-
-def _native_stored_assistant(agent, size, signature):
- from agent.chat_completion_helpers import build_assistant_message
- from agent.transports.anthropic import AnthropicTransport
-
- transport = AnthropicTransport()
- response = SimpleNamespace(
- content=[
- SimpleNamespace(type="thinking", thinking="x" * size, signature=signature),
- SimpleNamespace(type="text", text="A"),
- ],
- stop_reason="end_turn",
- stop_details=None,
+ agent.context_compressor = ContextCompressor(
+ model, provider=route[0], base_url=route[1], api_mode=agent.api_mode,
+ quiet_mode=True, config_context_length=200_000,
)
- normalized = transport.normalize_response(response)
- return build_assistant_message(agent, normalized, normalized.finish_reason)
-
-
-def _native_history(agent, size):
- return [
- {"role": "user", "content": "Q1"},
- _native_stored_assistant(agent, size, "sig_1"),
- {"role": "user", "content": "Q2"},
- _native_stored_assistant(agent, size, "sig_2"),
- {"role": "user", "content": "continue"},
- ]
+ agent.context_compressor.bind_session_state(db, session_id)
+ return agent
def _patch_assembly_loop(monkeypatch, selector=None):
import agent.conversation_loop as loop
monkeypatch.setattr(
- loop,
- "_apply_context_engine_selection",
+ loop, "_apply_context_engine_selection",
selector or (lambda agent, api, history, incoming, logger=None: api),
)
monkeypatch.setattr(loop, "_canonicalize_api_tool_calls", lambda messages: None)
monkeypatch.setattr(
- loop,
- "_midturn_request_pressure_tokens",
- lambda agent, messages, system, approx: approx,
+ loop, "_midturn_request_pressure_tokens", lambda agent, messages, system, approx: approx
)
monkeypatch.setattr(loop, "_pressure_with_real_floor", lambda compressor, value: value)
-def _assemble(agent, history):
+def _select_canonical_clone(agent, api, canonical, incoming, logger=None):
+ return copy.deepcopy(canonical)
+
+
+def _assemble_and_wire(agent, history):
+ """Production request assembly, then the native converter: (assembled, wire messages)."""
from agent.turn_request_assembly import assemble_api_request
- return assemble_api_request(
- agent,
- messages=history,
- current_turn_user_idx=len(history) - 1,
- _ext_prefetch_cache="",
- _plugin_user_context="",
- moa_config=None,
- active_system_prompt="",
- original_user_message=history[-1]["content"],
+ assembled = assemble_api_request(
+ agent, messages=copy.deepcopy(history), current_turn_user_idx=len(history) - 1,
+ _ext_prefetch_cache="", _plugin_user_context="", moa_config=None,
+ active_system_prompt="", original_user_message=history[-1]["content"],
pending_moa_prepared_request=None,
request_logger=logging.getLogger("anthropic-preserved-thinking-test"),
)
-
-
-def test_full_producer_to_wire_prices_surviving_non_tool_thinking(monkeypatch):
- from agent.transports.anthropic import AnthropicTransport
-
- _patch_assembly_loop(monkeypatch)
- agent = _assembly_agent()
-
- small_request = _assemble(agent, _native_history(agent, 1))
- large_request = _assemble(agent, _native_history(agent, 8000))
- assert large_request.approx_tokens - small_request.approx_tokens >= 3500
- assert large_request.request_pressure_tokens == large_request.approx_tokens
-
- kwargs = AnthropicTransport().build_kwargs(
- agent.model,
- large_request.api_messages,
- tools=[],
- base_url=agent.base_url,
- )
- emitted = sum(
- len(block.get("thinking", ""))
- for message in kwargs["messages"]
- for block in (message.get("content") if isinstance(message.get("content"), list) else [])
- if isinstance(block, dict) and block.get("type") == "thinking"
- )
- assert emitted == 16000
-
-
-def test_context_selection_canonical_clone_does_not_double_count_thinking(monkeypatch):
- from agent.transports.anthropic import AnthropicTransport
-
- agent = _assembly_agent()
- history = _native_history(agent, 8000)
-
- _patch_assembly_loop(monkeypatch)
- normal = _assemble(agent, copy.deepcopy(history))
-
- def select_canonical(agent, api, canonical, incoming, logger=None):
- return copy.deepcopy(canonical)
-
- _patch_assembly_loop(monkeypatch, selector=select_canonical)
- selected = _assemble(agent, copy.deepcopy(history))
-
- assert selected.approx_tokens == normal.approx_tokens
- assert selected.request_pressure_tokens == normal.request_pressure_tokens
-
- transport = AnthropicTransport()
- normal_kwargs = transport.build_kwargs(
- agent.model, normal.api_messages, tools=[], base_url=agent.base_url
- )
- selected_kwargs = transport.build_kwargs(
- agent.model, selected.api_messages, tools=[], base_url=agent.base_url
+ _, wire = convert_messages_to_anthropic(
+ copy.deepcopy(assembled.api_messages), base_url=agent.base_url, model=agent.model
)
- assert selected_kwargs["messages"] == normal_kwargs["messages"]
-
-
-def test_canonical_preflight_dedupes_ordered_thinking_carrier():
- from agent.turn_context import _preflight_request_tokens
-
- agent = _assembly_agent()
- thinking = "x" * 8000
- assistant = _carrier_message()
- assistant["reasoning"] = thinking
- assistant["reasoning_details"][0]["thinking"] = thinking
- assistant["anthropic_content_blocks"][0]["thinking"] = thinking
- assistant["tool_calls"] = [
- {
- "id": "tool_1",
- "type": "function",
- "function": {"name": "search", "arguments": "{\"q\":\"x\"}"},
- }
- ]
- canonical = [
- {"role": "user", "content": "Q"},
- assistant,
- {"role": "user", "content": "continue"},
- ]
-
- preflight = _preflight_request_tokens(agent, copy.deepcopy(canonical), "")
-
- request_copy = copy.deepcopy(canonical)
- request_copy[1].pop("reasoning", None)
- expected = estimate_native_anthropic_request_tokens_rough(request_copy)
- assert preflight == expected
-
-
-def test_native_accounting_projection_dedupes_ordered_carrier_and_opaque_bytes():
- base = _carrier_message()
- base["reasoning_details"][0]["thinking"] = "x" * 8000
- base["anthropic_content_blocks"][0]["thinking"] = "x" * 8000
-
- huge_opaque = copy.deepcopy(base)
- huge_opaque["reasoning_details"][0]["signature"] = "s" * 20000
- huge_opaque["reasoning_details"][1]["data"] = "r" * 20000
- huge_opaque["anthropic_content_blocks"][0]["signature"] = "s" * 20000
- huge_opaque["anthropic_content_blocks"][-1]["data"] = "r" * 20000
-
- ordered_only = copy.deepcopy(huge_opaque)
- ordered_only.pop("reasoning_details")
-
- projected_huge, readable = native_anthropic_accounting_projection([huge_opaque])
-
- metadata_copy = copy.deepcopy(huge_opaque)
- metadata_copy["timestamp"] = 1234567890.0
- metadata_copy["finish_reason"] = "tool_calls"
- metadata_copy["api_content"] = "storage-only replay sidecar"
-
- assert "_anthropic_readable_thinking_estimate" not in repr(projected_huge)
- projected_metadata, _ = native_anthropic_accounting_projection([metadata_copy])
- assert projected_metadata == 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])
-
+ return assembled, wire
-def test_context_selection_cannot_restore_rejected_thinking(monkeypatch):
- from agent.anthropic_thinking_replay import remember_rejected_thinking
- db = _ConfigDB()
- first = _assembly_agent(db)
- remember_rejected_thinking(first, [_carrier_message()])
-
- def select_canonical(agent, api, history, incoming, logger=None):
- return copy.deepcopy(history)
-
- _patch_assembly_loop(monkeypatch, selector=select_canonical)
- resumed = _assembly_agent(db)
- history = [
- {"role": "user", "content": "Q"},
- _carrier_message(),
- {"role": "user", "content": "continue"},
- ]
- assembled = _assemble(resumed, history)
- assistant = next(m for m in assembled.api_messages if m.get("role") == "assistant")
-
- assert "reasoning_details" not in assistant
- assert "reasoning" not in assistant
- assert "reasoning_content" not in assistant
- assert [b["type"] for b in assistant["anthropic_content_blocks"]] == ["text", "tool_use"]
- _, native = convert_messages_to_anthropic(assembled.api_messages, model=resumed.model)
- assert "sig_bad" not in repr(native)
- assert "secret chain" not in repr(native)
-
-
-def test_preflight_ignores_persisted_rejected_thinking(monkeypatch):
- from agent.anthropic_thinking_replay import remember_rejected_thinking
- from agent.turn_context import _preflight_request_tokens
-
- db = _ConfigDB()
- first = _assembly_agent(db)
- carrier = _non_tool_carrier_message()
- remember_rejected_thinking(first, [copy.deepcopy(carrier)])
-
- resumed = _assembly_agent(db)
- history = [
- {"role": "user", "content": "Q"},
- copy.deepcopy(carrier),
- {"role": "user", "content": "continue"},
+def _thinking_blocks(wire):
+ return [
+ block
+ for message in wire
+ if message["role"] == "assistant" and isinstance(message["content"], list)
+ for block in message["content"]
+ if isinstance(block, dict) and block.get("type") in {"thinking", "redacted_thinking"}
]
- preflight = _preflight_request_tokens(resumed, copy.deepcopy(history), "")
-
- _patch_assembly_loop(monkeypatch)
- assembled = _assemble(resumed, copy.deepcopy(history))
- assert preflight == assembled.approx_tokens
-
-def test_usage_anchor_still_overrides_projected_rough_pressure(monkeypatch):
- import agent.turn_request_assembly as assembly
-
- _patch_assembly_loop(monkeypatch)
- monkeypatch.setattr(assembly, "anchored_context_tokens", lambda messages, anchor: 1234)
- agent = _assembly_agent()
- agent._usage_anchor = object()
- history = (
- _signed_turn("Q1", "A1", "sig_1", thinking="x" * 8000)
- + [{"role": "user", "content": "continue"}]
- )
-
- assembled = _assemble(agent, history)
- assert assembled.approx_tokens > 1000
- assert assembled.request_pressure_tokens == 1234
- assert agent._request_pressure_anchored is True
-
-
-def _session_db(tmp_path, *session_ids):
- from hermes_state import SessionDB
-
- db = SessionDB(db_path=tmp_path / "state.db")
- for session_id in session_ids:
- db.create_session(session_id, source="cli", model="claude-opus-4-6")
- return db
-
-
-def _session_agent(db, session_id):
- agent = _assembly_agent(db)
- agent.session_id = session_id
- agent.log_prefix = ""
- agent._vprint = lambda *args, **kwargs: None
- return agent
def _reject_signatures(agent, history):
- """Drive the production signature-rejection recovery on a request copy of ``history``."""
+ """Drive production signature-rejection recovery; the canonical history is never mutated."""
from agent.error_classifier import FailoverReason
from agent.turn_recovery import _recover_format_errors
from agent.turn_retry_state import TurnRetryState
+ before, request, retry = copy.deepcopy(history), copy.deepcopy(history), TurnRetryState()
assert _recover_format_errors(
- agent,
- RuntimeError("Invalid signature in thinking block"),
- SimpleNamespace(reason=FailoverReason.thinking_signature),
- TurnRetryState(),
- history,
- copy.deepcopy(history),
+ agent, RuntimeError("Invalid signature in thinking block"),
+ SimpleNamespace(reason=FailoverReason.thinking_signature), retry, history, request,
)
+ assert retry.thinking_sig_retry_attempted and history == before
+ assert not _thinking_blocks(convert_messages_to_anthropic(request, model=agent.model)[1])
+
+
+_PRESERVED = [
+ ("claude-opus-4-4", False), ("claude-opus-4-5", True), ("claude-opus-4-6", True),
+ ("claude-sonnet-4-5", False), ("claude-sonnet-4-6", True), ("claude-haiku-4-5", False),
+ ("claude-opus-4-20250514", False), ("claude-sonnet-4-20250514", False),
+ ("claude-opus-4-5-20251101", True), ("claude-opus-4-6-20250414", True),
+ ("claude-sonnet-4-5-20250929", False), ("claude-opus-5", True), ("claude-sonnet-5-5", True),
+ ("claude-fable-5-1", True), ("claude-mythos-5", True), ("claude-mythos-preview", True),
+]
+# case -> (model, route, number of growing thinking blocks that must reach the wire)
+_ACCOUNTING_CASES = {
+ **{f"route:{m}": (m, ANTHROPIC, int(p)) for m, p in _PRESERVED},
+ "route:nous": ("claude-opus-4-6", NOUS, 1),
+ "route:openrouter": ("claude-opus-4-6", OPENROUTER, 0),
+ "producer": ("claude-opus-4-6", ANTHROPIC, 2),
+ "context_selection_clone": ("claude-opus-4-6", ANTHROPIC, 1),
+ "usage_anchor": ("claude-opus-4-6", ANTHROPIC, 1),
+ "carrier_dedupe": ("claude-opus-4-6", ANTHROPIC, 1),
+ "opaque_bytes": ("claude-opus-4-6", ANTHROPIC, 0),
+ "rejected": ("claude-opus-4-6", ANTHROPIC, 0),
+ "rejected_unpersisted": ("claude-opus-4-6", ANTHROPIC, 0),
+ "reasoning_only": ("claude-opus-4-6", ANTHROPIC, 0),
+ "invalid_ordered_then_details": ("claude-opus-4-6", ANTHROPIC, 1),
+}
+
+
[email protected]("case", list(_ACCOUNTING_CASES))
+def test_estimates_charge_exactly_the_thinking_the_wire_replays(tmp_path, monkeypatch, case):
+ """Invariant: growing thinking text moves the wire, the preflight estimate, the compressor
+ tail walk, and assembled request pressure by the same amount — the full block for every
+ signed historical turn the route replays, nothing for latest-only routes, rejected,
+ storage-only, or opaque (signature/redacted) bytes. A usage anchor still wins pressure."""
+ import agent.turn_request_assembly as assembly
+ from agent.turn_context import _preflight_request_tokens
+ model, route, replayed_blocks = _ACCOUNTING_CASES[case]
+ agent = _agent(_session_db(tmp_path, "s1"), model=model, route=route)
+ agent._persist_disabled = case == "rejected_unpersisted"
+ _patch_assembly_loop(
+ monkeypatch, _select_canonical_clone if case == "context_selection_clone" else None
+ )
+ if case == "usage_anchor":
+ monkeypatch.setattr(assembly, "anchored_context_tokens", lambda messages, anchor: 1234)
+ agent._usage_anchor = object()
-def _request_and_wire(agent, history):
- from agent.turn_context import build_api_messages
+ def history(size):
+ if case == "producer":
+ body = _native_turn(agent, "Q1", size, "sig_1") + _native_turn(agent, "Q2", size, "sig_2")
+ elif case == "carrier_dedupe":
+ body = _carrier(thinking="x" * size)
+ elif case == "opaque_bytes":
+ body = _carrier(thinking="x" * 8000, opaque="r" * size)
+ else:
+ body = _signed_turn("Q1", "A1", "sig_1", thinking="x" * size)
+ if case == "reasoning_only": # rows written by another provider before a switch
+ body[1] = {"role": "assistant", "content": "A1", "reasoning": "x" * size}
+ elif case == "invalid_ordered_then_details":
+ # Dataless redacted_thinking sanitizes away; the converter falls back to details.
+ body[1]["anthropic_content_blocks"] = [{"type": "redacted_thinking"}]
+ body += _signed_turn("Q2", "A2", "sig_2")
+ return body + [{"role": "user", "content": "continue"}]
+
+ if case.startswith("rejected"):
+ _reject_signatures(agent, history(1))
- api_messages, _ = build_api_messages(
- agent,
- copy.deepcopy(history),
- current_turn_user_idx=len(history) - 1,
- ext_prefetch_cache="",
- plugin_user_context="",
- moa_config=None,
- active_system_prompt="",
- )
- _, wire = convert_messages_to_anthropic(
- copy.deepcopy(api_messages), base_url=agent.base_url, model=agent.model
- )
- blocks = [
- block
- for message in wire
- if message["role"] == "assistant" and isinstance(message["content"], list)
- for block in message["content"]
- if isinstance(block, dict) and block.get("type") in {"thinking", "redacted_thinking"}
- ]
- return api_messages, blocks
+ def measure(size):
+ canonical = history(size)
+ preflight = _preflight_request_tokens(agent, copy.deepcopy(canonical), "")
+ assembled, wire = _assemble_and_wire(agent, canonical) # assembly sets the anchor flag
+ return {
+ "wire": sum(estimate_tokens_rough(b.get("thinking", "")) for b in _thinking_blocks(wire)),
+ "preflight": preflight,
+ "tail_walk": agent.context_compressor._walk_tail_budget(
+ canonical, 0, 10**9, 0, cut_at_break=False
+ )[1],
+ "assembled": assembled.approx_tokens,
+ "pressure": assembled.request_pressure_tokens,
+ }
+
+ small, large = measure(1), measure(8000)
+ delta = {key: large[key] - small[key] for key in small}
+ expected = replayed_blocks * (estimate_tokens_rough("x" * 8000) - estimate_tokens_rough("x"))
+ if case == "usage_anchor":
+ assert small["pressure"] == large["pressure"] == 1234
+ assert agent._request_pressure_anchored is True
+ delta["pressure"] = delta["assembled"]
+ assert delta == dict.fromkeys(delta, expected)
+ if case.startswith("route:"):
+ assert stale_thinking_reaches_wire(agent.api_mode, route[0], model, route[1]) is bool(
+ replayed_blocks
+ )
+ # A formerly-latest turn stays byte-stable when history keeps thinking, else loses it.
+ prefix = history(1)[:-1]
+ short = convert_messages_to_anthropic(prefix, base_url=route[1], model=model)[1]
+ longer = convert_messages_to_anthropic(
+ prefix + _signed_turn("Q3", "A3", "sig_3"), base_url=route[1], model=model
+ )[1]
+ assert longer[3] == short[3] if replayed_blocks else not _thinking_blocks([longer[3]])
@pytest.mark.parametrize(
- "boundary", ["rebuild", "session_switch", "compression_child", "unfingerprintable", "kimi_route"]
+ "boundary",
+ ["same_agent", "rebuild", "session_switch", "compression_child", "context_selection",
+ "carrier", "unfingerprintable", "kimi_route"],
)
-def test_rejected_thinking_never_returns_and_nothing_else_is_suppressed(tmp_path, boundary):
+def test_rejected_thinking_never_returns_and_nothing_else_is_suppressed(
+ tmp_path, monkeypatch, boundary
+):
"""Invariant: once Anthropic rejects a signature, every later request in that conversation
- replays exactly the never-rejected signed thinking, whatever lifetime boundary it crosses.
- Routes Anthropic does not sign for keep their own replay contract."""
+ replays exactly the never-rejected signed thinking, whatever lifetime boundary it crosses;
+ the rejection drops the stale usage anchor. Routes Anthropic does not sign for keep their
+ own replay contract."""
from agent.conversation_compression import _carry_session_state_to_child
db = _session_db(tmp_path, "s1", "s2")
- agent = _session_agent(db, "s1")
- if boundary == "kimi_route":
- agent.base_url, agent.model = "https://api.kimi.com/coding", "kimi-k2.5"
+ agent = _agent(db, route=KIMI, model="kimi-k2.5") if boundary == "kimi_route" else _agent(db)
+ agent._usage_anchor = {"prompt_tokens": 999}
+ _patch_assembly_loop(
+ monkeypatch, _select_canonical_clone if boundary == "context_selection" else None
+ )
rejected = _signed_turn("Q1", "A1", "sig_rejected_1") + _signed_turn("Q2", "A2", "sig_rejected_2")
if boundary == "unfingerprintable":
rejected = [{"role": "user", "content": "Q1"}, {"role": "assistant", "content": "A1"}]
+ elif boundary == "carrier":
+ rejected = _carrier()
_reject_signatures(agent, rejected)
+ if boundary != "kimi_route":
+ assert agent._usage_anchor is None
reader = agent
- if boundary == "rebuild":
- reader = _session_agent(db, "s1") # fresh process on the same session
+ if boundary in {"rebuild", "context_selection", "carrier"}:
+ reader = _agent(db) # fresh process on the same session
elif boundary == "session_switch":
# s2 was rejected by an earlier process; the live agent then resumes s2.
rejected = _signed_turn("Q1", "A1", "sig_rejected_s2")
- _reject_signatures(_session_agent(db, "s2"), rejected)
+ _reject_signatures(_agent(db, "s2"), rejected)
agent.session_id = "s2"
later = (
rejected
@@ -674,78 +325,14 @@ def test_rejected_thinking_never_returns_and_nothing_else_is_suppressed(tmp_path
)
agent.session_id = "s1-child"
_carry_session_state_to_child(agent, "s1", None)
- reader = _session_agent(db, "s1-child") # resume the child in a fresh process
+ reader = _agent(db, "s1-child") # resume the child in a fresh process
later = later[2:]
- _, wire_blocks = _request_and_wire(reader, later)
+ _, wire = _assemble_and_wire(reader, later)
replayed = ["sig_kept", "sig_new"]
if boundary == "kimi_route": # one-request repair only; Kimi replays its history as-is
replayed = ["sig_rejected_1", "sig_rejected_2"] + replayed
- assert [block.get("signature") for block in wire_blocks] == replayed
-
-
-def _readable_tokens(blocks):
- from agent.model_metadata import estimate_tokens_rough
-
- return sum(estimate_tokens_rough(block.get("thinking", "")) for block in blocks)
-
-
- "shape", ["rejected", "rejected_unpersisted", "reasoning_only", "invalid_ordered_then_details"]
-)
-def test_native_preflight_and_tail_walk_charge_exactly_the_replayed_thinking(tmp_path, shape):
- """Invariant: on a preserved-thinking native route, growing thinking text moves the
- preflight estimate and the compressor tail walk by exactly what reaches the wire: nothing for
- rejected or storage-only reasoning, the full valid historical block otherwise."""
- from agent.context_compressor import ContextCompressor
- from agent.model_metadata import estimate_tokens_rough
- from agent.turn_context import _preflight_request_tokens
-
- db = _session_db(tmp_path, "s1")
- agent = _session_agent(db, "s1")
- compressor = ContextCompressor(
- agent.model, provider=agent.provider, base_url=agent.base_url,
- api_mode=agent.api_mode, quiet_mode=True, config_context_length=200_000,
- )
- compressor.bind_session_state(db, "s1")
- agent.context_compressor = compressor
- agent._persist_disabled = shape == "rejected_unpersisted"
-
- def history(size):
- thinking = "x" * size
- if shape == "reasoning_only": # e.g. rows written by another provider before a switch
- assistant = {"role": "assistant", "content": "A1", "reasoning": thinking}
- else:
- assistant = _signed_turn("Q1", "A1", "sig_1", thinking=thinking)[1]
- if shape == "invalid_ordered_then_details":
- # Dataless redacted_thinking sanitizes to nothing, so the converter falls back
- # to reasoning_details.
- assistant["anthropic_content_blocks"] = [{"type": "redacted_thinking"}]
- return [
- {"role": "user", "content": "Q1"},
- assistant,
- {"role": "user", "content": "Q2"},
- {"role": "assistant", "content": "A2"},
- {"role": "user", "content": "continue"},
- ]
-
- if shape.startswith("rejected"):
- _reject_signatures(agent, history(1))
-
- def measure(size):
- canonical = history(size)
- _, wire_blocks = _request_and_wire(agent, canonical)
- walked = compressor._walk_tail_budget(
- canonical, 0, 10**9, 0, cut_at_break=False
- )[1]
- return (
- _preflight_request_tokens(agent, copy.deepcopy(canonical), ""),
- walked,
- _readable_tokens(wire_blocks),
- )
-
- small, large = measure(1), measure(8000)
- preflight_delta, walk_delta, wire_delta = (b - a for a, b in zip(small, large))
- replayed = estimate_tokens_rough("x" * 8000) - estimate_tokens_rough("x")
- expected = replayed if shape == "invalid_ordered_then_details" else 0
- assert preflight_delta == walk_delta == wire_delta == expected
+ assert [block.get("signature") for block in _thinking_blocks(wire)] == replayed
+ # The rejected carrier's visible answer and tool call still replay; only thinking goes.
+ assert ("tool_use" in repr(wire)) is (boundary == "carrier")
+ assert "secret chain" not in repr(wire)