Merge pull request #2082 from Gordonynh/fix/anthropic-stale-thinking-replay

fix: omit completed Anthropic thinking at durable history replay
This commit is contained in:
Bingxi Zhao
2026-10-27 23:46:25 +08:00
committed by GitHub
2 changed files with 95 additions and 3 deletions

View File

@@ -130,6 +130,34 @@ def history_groups(rows: list[dict[str, Any]]) -> list[list[dict[str, Any]]]:
return groups
def _without_completed_thinking(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""Drop prefix-bound Anthropic thoughts only at the durable turn boundary.
Current-turn tool rounds never pass through history replay. Keep their
signed state intact, and leave the stored transcript and other providers'
replay state untouched.
"""
result = deepcopy(messages)
for message in result:
if message.get("role") != "assistant":
continue
message.pop("thinking_blocks", None)
state = message.get("_provider_response_state")
if isinstance(state, dict):
state.pop("thinking_blocks", None)
if not state:
message.pop("_provider_response_state", None)
content = message.get("content")
if isinstance(content, list):
message["content"] = [
block
for block in content
if not isinstance(block, dict)
or block.get("type") not in {"thinking", "redacted_thinking"}
]
return result
def replay_group(
rows: list[dict[str, Any]], route: dict[str, str] | None = None
) -> list[dict[str, Any]]:
@@ -165,7 +193,7 @@ def replay_group(
message.pop(key, None)
for call in message.get("tool_calls") or []:
call.pop("extra_content", None)
return messages
return _without_completed_thinking(messages)
messages = []
for row in rows:
expanded = expand_message_context(row)
@@ -177,7 +205,7 @@ def replay_group(
if state:
expanded[-1]["_provider_response_state"] = state
messages.extend(expanded)
return messages
return _without_completed_thinking(messages)
#: Snapshot name the rolling summary rides under when it is replayed.

View File

@@ -296,7 +296,7 @@ async def test_budget_uses_the_replayed_route_and_preserves_stored_signed_state(
session_id="s",
llm_config=SimpleNamespace(binding="openai", model="gpt-test", context_window=16000),
)
builder._summarize.assert_awaited_once()
builder._summarize.assert_not_awaited()
assert records == before
@@ -371,3 +371,67 @@ async def test_recompaction_retains_prior_summary_when_history_replay_has_no_sum
assert request["messages"][-1]["content"] == "[Conversation summary]\nEarlier stable preference"
assert all("_context_snapshot" not in message for message in request["messages"])
assert "already condensed" not in str(request["messages"])
@pytest.mark.parametrize("representation", ["direct", "private", "content"])
def test_completed_turn_replay_drops_thinking_before_a_new_question(representation):
from deeptutor.services.llm.provider_core.anthropic_provider import AnthropicProvider
record = turn_record()
# A completed stored turn may end with a tool result. The following user
# question must not be confused with another tool-loop continuation.
record["messages"].pop()
thought = {"type": "thinking", "thinking": "old thought", "signature": "old-signature"}
assistant = record["messages"][1]
encrypted = {"type": "reasoning", "id": "r", "encrypted_content": "opaque"}
assistant["_provider_response_state"] = {"responses_output_items": [encrypted]}
if representation == "direct":
assistant["thinking_blocks"] = [thought]
elif representation == "private":
assistant["_provider_response_state"]["thinking_blocks"] = [thought]
else:
assistant["content"] = [thought, {"type": "redacted_thinking", "data": "opaque"}]
source = rows(record)
before = deepcopy(source)
history = replay_history(source)
assert history[1]["_provider_response_state"] == {"responses_output_items": [encrypted]}
provider = object.__new__(AnthropicProvider)
_, converted = provider._convert_messages([*history, {"role": "user", "content": "next"}])
assert all(
block.get("type") not in {"thinking", "redacted_thinking"}
for message in converted
for block in message["content"]
if isinstance(block, dict)
)
assert history[2]["content"] == "tool evidence"
assert source == before
# A live tool round bypasses durable replay, including internal user nudges.
_, current = provider._convert_messages(
[
{"role": "user", "content": "current question"},
{"role": "assistant", "content": "working", "thinking_blocks": [thought]},
{"role": "user", "content": "finish the current turn"},
]
)
assert current[1]["content"][0] == thought
def test_legacy_display_history_drops_only_completed_thinking():
thought = {"type": "thinking", "thinking": "old", "signature": "signature"}
source = [
{
"role": "assistant",
"content": "answer",
"metadata": {
"provider_response_state": {
"thinking_blocks": [thought],
"reasoning_content": "portable",
}
},
}
]
before = deepcopy(source)
replayed = replay_history(source)
assert replayed[0]["_provider_response_state"] == {"reasoning_content": "portable"}
assert source == before