MessageWindowChatMemory truncation breaks tool_use/tool_result pairs (Anthropic 400)
Summary
MessageWindowChatMemory performs naïve count-based head truncation when the message count exceeds maxMessages. The cut point is not aware of AssistantMessage (with tool_use blocks) ↔ ToolResponseMessage (with tool_result blocks) pairs. When the cut falls between such a pair, the assistant message is dropped but the tool result survives — and the next request to the provider fails because the conversation now starts with an orphan tool_result.
Reproducer
Anthropic's API enforces this strictly:
400 invalid_request_error messages.0.content.0: unexpected
tool_use_idfound intool_resultblocks: toolu_bdrk_…. Eachtool_resultblock must have a correspondingtool_useblock in the previous message.
In our environment (Spring AI 2.0.0-M5, Anthropic Claude Sonnet, MessageWindowChatMemory with maxMessages=100, tool-heavy ReAct conversations) we hit this every few hours on long-lived threads. A single user turn often produces 4–10 tool calls, so 100 messages is reached after only ~15–20 user turns. Once the window starts sliding, any cut that lands inside a tool_use→tool_result pair corrupts the conversation.
A self-contained reproducer with MessageWindowChatMemory.builder().maxMessages(4).build():
// Pretend the LLM made a tool call in turn 1 and we kept appending.
chatMemory.add(conversationId, List.of(
new UserMessage("u1"),
AssistantMessage.builder().content("").toolCalls(List.of(toolCall("t1"))).build(),
new ToolResponseMessage(List.of(new ToolResponse("t1", "tool_a", "result_a"))),
AssistantMessage.builder().content("done").build(),
new UserMessage("u2"))); // window slides; messages[0] is now ToolResponseMessage(tool_use_id=t1)
// but the AssistantMessage that contained t1 was dropped.
chatMemory.get(conversationId) returns a list whose head is a ToolResponseMessage referencing a tool_use that no longer exists in the history.
Why the bot's recovery isn't enough
Anthropic returns the 400 every request until the corrupt state is cleared. Our app catches BadRequestException and resets the entire conversation — which is annoying and loses context the user expects to be there. We can write our own pair-aware wrapper, but a fix at the framework layer would benefit every user.
Suggested fix
MessageWindowChatMemory (or a pair-aware sibling) should, after computing the window cut, advance the cut forward while messages[0] instanceof ToolResponseMessage (or while messages[0] is a tool_result-bearing message whose matching tool_use is no longer in the kept window). Equivalent forms:
- Keep cutting from the head while the first kept message is a
ToolResponseMessage. - Or: track tool_use_id → tool_use position and never cut between a
tool_useand its matchingtool_result.
Either approach prevents the orphan-tool_result corruption without changing the public API. The same idea applies to OpenAI's tool messages — same constraint, same wire-format requirement.
Related but distinct issues
- #2101 — tool calls not persisted at all (different bug)
- #2529 — tool calls duplicated in memory (different bug)
- #3366 — streaming mode loses
toolCallsonAssistantMessage(different bug) - #4315 — tool messages not stored when using
.stream.chatClientResponse()(different bug)
This issue is specifically about truncation in the persisted store breaking pairs.
Environment
- Spring AI 2.0.0-M5
MessageWindowChatMemory+RedisChatMemoryRepository(Redis JSON)- Anthropic Claude Sonnet 4.6
- Java 25, Spring Boot 4.0
I've submitted a fix for this in PR #6029.
should ToolResponseMessage and tool call message be written to chatmemory?
Yes, they should — and that's exactly the source of the bug this issue describes.
How the tool execution loop works in Spring AI:
When MessageChatMemoryAdvisor is used with internal tool execution, the flow is:
MessageChatMemoryAdvisor.before()hydrates the prompt with stored memory and saves the new user message.- The model returns an
AssistantMessagewithtoolCalls. - The model internally calls
DefaultToolCallingManager.executeToolCalls(), which appends both theAssistantMessage(with tool_use) and the resultingToolResponseMessage(with tool_result) toconversationHistoryand re-calls the model — this loops until no more tool calls. - Only the final assistant response (after all tool rounds are done) is returned to
MessageChatMemoryAdvisor.after(), which then saves it to memory.
The problem is at step 4: after() only saves the final AssistantMessage. The intermediate AssistantMessage(tool_use) + ToolResponseMessage(tool_result) pairs that happened inside the tool loop are never persisted to ChatMemory. They live only in the transient conversationHistory list within that single call.
So on the next user turn, memory only has: [user, ..., final_assistant_reply] — the tool interaction pairs are gone. That part is by design (the internal tool loop is opaque to memory).
Where the bug actually is is in MessageWindowChatMemory.process(): when a previous tool interaction was saved (e.g., via explicit chatMemory.add()), the naïve head-truncation can evict the AssistantMessage(tool_use) while keeping the subsequent ToolResponseMessage(tool_result) — leaving an orphan that causes a 400 from Anthropic.
PR #6029 fixes that by scanning after truncation and dropping any orphaned ToolResponseMessage entries whose paired tool call was evicted.
@suryateja-g13 https://github.com/spring-ai-community/spring-ai-session/issues/11
why Next Turn chat require the tool_call history used by last turn chat?
Good question — the answer is rooted in how ToolCallAdvisor and MessageChatMemoryAdvisor interact.
Why tool pairs end up in memory
ToolCallAdvisor has order HIGHEST_PRECEDENCE + 300, MessageChatMemoryAdvisor has order HIGHEST_PRECEDENCE + 1000. That puts ToolCallAdvisor outside the memory advisor in the chain. Inside its tool loop, it calls callAdvisorChain.copy(this).nextCall() on every iteration — so MessageChatMemoryAdvisor participates in every tool-call round. The Javadoc confirms this is intentional: "Placed early in the chain so that all downstream advisors participate in every tool-call iteration."
The result: after Turn 1 with two tool calls, memory contains:
[UserMessage1, AssistantMsg(tool_call1), ToolResponseMsg1, AssistantMsg(tool_call2), ToolResponseMsg2, AssistantMsg_final]
Why the next turn needs the full history
AssistantMsg(tool_call) entries have tool_call_ids baked into them. Anthropic and OpenAI APIs hard-require every tool_use block to be immediately followed by its matching tool_result. Once those pairs are in memory, you cannot send Turn 2 without them — the API returns a 400.
What PR #6029 fixes
When MessageWindowChatMemory slides the window and the eviction cut falls between AssistantMsg(tool_call) and its ToolResponseMsg, the response becomes an orphan. The fix scans after truncation and drops any ToolResponseMessage whose paired AssistantMessage(tool_call) was evicted.
Note: disableInternalConversationHistory() does not prevent tool pairs from entering memory — see the follow-up below for the full explanation.
@suryateja-g13 What is option B? when opening this ticket I had: advisors.add(ToolCallAdvisor.builder().disableInternalConversationHistory().build()) and it still fails
@davidkarlsen You are correct — disableInternalConversationHistory() does not fix this, and I was wrong to imply it would.
Here is the accurate explanation, traced through the actual source code.
Why disableInternalConversationHistory() does not prevent tool pairs from entering memory
ToolCallAdvisor (order HIGHEST_PRECEDENCE + 300) calls callAdvisorChain.copy(this).nextCall() on every tool iteration. copy(this) creates a sub-chain of all advisors with order > 300 — which includes MessageChatMemoryAdvisor at its default order of HIGHEST_PRECEDENCE + 1000. So memory advisor participates in every iteration regardless of the flag.
disableInternalConversationHistory() only controls what ToolCallAdvisor passes as instructions between iterations. Without it, ToolCallAdvisor passes the full conversationHistory (including messages memory already added), which causes duplication when memory prepends its stored messages again on the next iteration. The flag avoids duplication — it does not stop tool pairs from being saved to memory.
This is confirmed by Spring AI's own integration tests in AbstractToolCallAdvisorIT, which use exactly the pattern you described (disableInternalConversationHistory() + MessageChatMemoryAdvisor at default order) as the recommended multi-turn memory pattern.
After a full turn with two tool calls, memory contains:
[UserMessage1, AssistantMsg(tool_call1), ToolResponseMsg1, AssistantMsg(tool_call2), ToolResponseMsg2, AssistantMsg_final]
Why the next turn needs the tool pairs
The pairs are complete and valid. The LLM API requires every tool_use/tool_call to be paired with its tool_result — and since they are in memory they will be sent on the next turn.
Where the bug actually is
When MessageWindowChatMemory slides the window and the eviction cut falls between AssistantMsg(tool_call) and its ToolResponseMsg, the response becomes an orphan. The API returns a 400 because a tool_result block has no preceding tool_use.
What PR #6029 does
After head-truncation, it scans the retained list and drops any ToolResponseMessage whose paired AssistantMessage(tool_call) was evicted, keeping the conversation valid before sending to the LLM.
True Option B — no tool pairs in memory at all
If you want only [UserMessage, AssistantMsg_final] in memory (no tool pairs), place MessageChatMemoryAdvisor at an order lower than 300 (e.g. HIGHEST_PRECEDENCE + 100). Then it sits outside ToolCallAdvisor's loop, its before() runs once with the user message, and after() only sees the final response. ToolCallAdvisor manages the full tool context internally. No orphan issue possible. But this deviates from the recommended pattern and you lose full tool history in memory.
Why [UserMessage1, AssistantMsg_final]+ UserMessage2 not ok?
Good question — the answer is rooted in how
ToolCallAdvisorandMessageChatMemoryAdvisorinteract.Why tool pairs end up in memory
ToolCallAdvisorhas orderHIGHEST_PRECEDENCE + 300,MessageChatMemoryAdvisorhas orderHIGHEST_PRECEDENCE + 1000. That putsToolCallAdvisoroutside the memory advisor in the chain. Inside its tool loop, it callscallAdvisorChain.copy(this).nextCall()on every iteration — soMessageChatMemoryAdvisorparticipates in every tool-call round. The Javadoc confirms this is intentional: "Placed early in the chain so that all downstream advisors participate in every tool-call iteration."The result: after Turn 1 with two tool calls, memory contains:
[UserMessage1, AssistantMsg(tool_call1), ToolResponseMsg1, AssistantMsg(tool_call2), ToolResponseMsg2, AssistantMsg_final]Why the next turn needs the full history
AssistantMsg(tool_call)entries havetool_call_ids baked into them. Anthropic and OpenAI APIs hard-require everytool_useblock to be immediately followed by its matchingtool_result. Once those pairs are in memory, you cannot send Turn 2 without them — the API returns a 400.What PR #6029 fixes
When
MessageWindowChatMemoryslides the window and the eviction cut falls betweenAssistantMsg(tool_call)and itsToolResponseMsg, the response becomes an orphan. The fix scans after truncation and drops anyToolResponseMessagewhose pairedAssistantMessage(tool_call)was evicted.Note:
disableInternalConversationHistory()does not prevent tool pairs from entering memory — see the follow-up below for the full explanation.