[BUG] _fix_broken_tool_use does not repair orphaned toolUse in the last message, causing session corruption on process termination
Checks
- [x] I have updated to the lastest minor and patch version of Strands
- [x] I have checked the documentation and this is not expected behavior
- [x] I have searched ./issues and there are no duplicates of my issue
Strands Version
1.34.0
Python Version
3.13
Operating System
macOS 26.3.1
Installation Method
git clone
Steps to Reproduce
- Set up two agents: a supervisor (B) and a worker (C), running on separate runtimes
- Configure B with a RepositorySessionManager (e.g., S3-backed)
- Have C execute a tool that takes longer than B's runtime timeout (e.g., 6 minutes with a 5-minute timeout)
- B's process is terminated while waiting for C's response
- Send a new message to B using the same session ID
Expected Behavior
The session is restored with the orphaned toolUse repaired (a toolResult with status: "error" is inserted), and the agent processes the new user message normally.
Actual Behavior
The model provider returns a ValidationException:
botocore.errorfactory.ValidationException: An error occurred (ValidationException) when calling the
ConverseStream operation: The model returned the following errors: messages.N: tool_use ids were
found without tool_result blocks immediately after: tooluse_XXXX. Each tool_use
block must have a corresponding tool_result block in the next message.
Additional Context
When an agent process is terminated while waiting for a tool response (e.g., runtime timeout), the session stored in S3 ends with an assistant message containing toolUse but no corresponding toolResult. On the next invocation, the session is restored and a new user message is appended, resulting in a ValidationException from the model provider.
RepositorySessionManager._fix_broken_tool_use already handles orphaned toolUse messages in the middle of the conversation, but explicitly skips the last message:
python
# Check all but the latest message in the messages array
# The latest message being orphaned is handled in the agent class
if index + 1 < len(messages):
The "agent class" handling refers to _has_tool_use_in_latest_message in event_loop_cycle, which skips model invocation and re- executes the tool when the last message is a toolUse. However, this only works when the same agent instance continues execution within the same process. It does not work when a new process restores the session and a new user message is appended before entering the event loop.
Possible Solution
Remove the if index + 1 < len(messages) guard in _fix_broken_tool_use so that the last message is also repaired. When the last message is an orphaned toolUse, append a toolResult with status: "error" using the existing generate_missing_tool_result_content utility.
This is safe because _fix_broken_tool_use is only called during session restoration (initialize), not during the event loop. At restoration time, the original tool execution context is already lost, so re-executing the tool is not viable — reporting the error to the model and letting it decide how to proceed is the correct behavior.
Related Issues
No response
The latest message being orphaned is handled in the agent class ... The "agent class" handling refers to _has_tool_use_in_latest_message in event_loop_cycle, which skips model invocation and re-executes the tool when the last message is a toolUse. However, this only works when the same agent instance continues execution within the same process. It does not work when a new process restores the session and a new user message is appended before entering the event loop.
This might be intentional behavior - I think we wanted the ability to suspend and resume later on back to that use case. In the fix for this issue, we should be careful that we're not breaking another use case.
Traced the issue. The if index + 1 < len(messages) guard in _fix_broken_tool_use explicitly skips the last message, but the agent-class fallback (via _has_tool_use_in_latest_message) only works within the same process. On a fresh process restore with a new user message appended, the orphaned toolUse reaches the model unrepaired. The fix is to remove the guard and append a synthetic toolResult when the last message is an orphaned toolUse. Happy to open a PR if that looks right.
The latest message being orphaned is handled in the agent class ... The "agent class" handling refers to _has_tool_use_in_latest_message in event_loop_cycle, which skips model invocation and re-executes the tool when the last message is a toolUse. However, this only works when the same agent instance continues execution within the same process. It does not work when a new process restores the session and a new user message is appended before entering the event loop.
This might be intentional behavior - I think we wanted the ability to suspend and resume later on back to that use case. In the fix for this issue, we should be careful that we're not breaking another use case.
@zastrowm
This fix is safe — _fix_broken_tool_use only runs during initialize() (session restoration), not during the event loop. The suspend/resume path uses _has_tool_use_in_latest_message and is completely unaffected. Our customers are hitting this bug, so it would be great if you could review #2026 when you get a chance.
To zastrowm's concern: the suspend/resume path uses _has_tool_use_in_latest_message in the event loop and is unaffected — _fix_broken_tool_use only runs during initialize(). Happy to close #2073 in favor of #2026 — seems like it's been waiting on a review. The cross-process restore scenario is described in more detail there if any of it's useful.
I'm still a bit confused how this issue happens in the first place. We intentionally don't repair the latest message in the session manager, and instead rely on the agent invocation to fix this: https://github.com/strands-agents/sdk-python/blob/main/src/strands/agent/agent.py#L986-L1001
Basically, during agent invocation, we check to see if the latest message is a tool use, and if so, then we put a toolResult message after it so that the conversation is valid. Then we append the use message so we have a fully valid conversation.
The reason we do this is because if you resume a session that had interrupted its tool use, you can pass None into your agent and that tool will automatically execute, saving an llm invoke.
By automatically adding a toolResult after an orphaned tool use in the session manager, you break this behavior. But ideally you shouldnt be getting this error in the first place. Can you help me understand how you get this error? Maybe a small reproducible example?
You can find more context about this fix in the following pull request: https://github.com/strands-agents/sdk-python/pull/1123
My earlier comment was wrong on two points. Correcting them.
_has_tool_use_in_latest_message is not the function that handles the new-prompt case. It's in event_loop.py and handles the None-resume path (when prompt=None), where it re-executes the orphaned tool rather than injecting a synthetic result. @Unshure is right that the correct function is _convert_prompt_to_messages at agent.py:988.
What that actually does: when prompt is not None, it inserts a synthetic toolResult as a separate user message, then the new prompt gets appended after. So Bedrock receives:
[..., {role: assistant, content: [toolUse]}, {role: user, content: [toolResult]}, {role: user, content: [text]}]
Two consecutive user messages at the end. Bedrock Converse rejects that with:
ValidationException: A conversation must alternate between user and assistant roles.
(confirmed by langchain-aws #130, #192)
That's a different error from "tool_use ids found without tool_result." The reporter's error means the toolResult is absent, not just misplaced. That points to the prompt=None path, where _convert_prompt_to_messages skips the check entirely and _has_tool_use_in_latest_message fires, trying to re-execute the orphaned tool. After cross-process restore, that re-execution is probably not what you want.
Two gaps:
- With a prompt: the fix inserts the synthetic
toolResult, but creates consecutive user messages. Bedrock rejects that. - Without a prompt (
prompt=None): the check is skipped, the orphaned tool gets re-executed instead.
The fix for gap 1 is merging the synthetic toolResult content into the new user message. Bedrock accepts mixed content types in a single user turn.
Thanks for the prompt response :)
Just wrote a quick test script to try this out:
from strands import Agent
agent = Agent(messages=[
{
"role": "user",
"content" : [{"text": "Hello!"}]
}, {
"role": "user",
"content" : [{"text": "Hello!"}]
}
])
agent("Hello!")
print(agent.messages)
With the following output:
➜ ~ python test.py
Hello! Hello! Hello!
Great to meet you! How are you doing today? Is there anything I can help you with?
[{'role': 'user', 'content': [{'text': 'Hello!'}]}, {'role': 'user', 'content': [{'text': 'Hello!'}]}, {'role': 'user', 'content': [{'text': 'Hello!'}]}, {'role': 'assistant', 'content': [{'text': 'Hello! Hello! Hello! \n\nGreat to meet you! How are you doing today? Is there anything I can help you with?'}]}]
Basically, in this case, bedrock did accept multiple consecutive user messages. This was a limitation in the past, but bedrock has not had this limitation for quite a while now.
If possible, do you mind sharing a reproducible code example of this error being present in the latest version of strands? I do believe there is a bug somewhere here, but its just hard to pin down.
Ran a repro with MockedSessionRepository seeded with orphaned toolUse and a model that captures what it receives before raising. No real Bedrock call needed.
Standard non-stateful paths: no bug
| Scenario | What model receives |
|---|---|
agent("Follow-up") |
[user, assistant(toolUse), user(toolResult), user("Follow-up")] — valid |
agent(None) |
Tool re-executed; model receives [user, assistant(toolUse), user(toolResult)] — valid |
agent(None) then agent("Follow-up") |
Both calls send valid payloads |
_convert_prompt_to_messages handles all three correctly.
Stateful model path: confirmed bug
When model.stateful = True, initialize() skips message restore (agent.messages = []). The guard in _convert_prompt_to_messages:
if len(self.messages) > 0 and any("toolUse" in content ...):
is False, so no synthetic toolResult gets inserted. Only the new user message goes to Bedrock. The server-side session still has [user(Run), assistant(toolUse)], so Bedrock appends user("Follow-up") and rejects with tool_use ids found without tool_result.
The fix can't be in _fix_broken_tool_use — initialize() skips message restore entirely for stateful models, so that branch never runs. The guard in _convert_prompt_to_messages needs to handle the empty-messages case, or fall back to the session repository to check the last persisted message.
@nmiyat — are you using model.stateful = True (OpenAI Responses API)? That's the only path I can reproduce this on. If you're on standard Bedrock, sharing your invocation code would help.
(Also correcting my earlier comment: Bedrock accepts consecutive user messages now, as @Unshure showed, so that analysis was wrong.)
Thanks everyone for the thorough investigation here.
Based on the analysis in this thread (particularly the repro work in this comment):
For non-stateful model providers (standard Bedrock, Anthropic, etc.), _convert_prompt_to_messages already handles orphaned toolUse in the last message correctly — both the prompt=None and prompt="something" paths produce valid conversations. This was confirmed independently by multiple people in this thread.
For stateful models (model.stateful = True), the SDK intentionally skips message restore during initialize() because the conversation history is managed server-side by the model provider. The SDK doesn't have local access to those messages, so detecting or repairing an orphaned toolUse isn't something the SDK can or should do — that's the model provider's responsibility.
Given this, I'm closing this issue. If there's a specific reproducible scenario on a non-stateful model provider where this actually breaks, please reopen with a minimal repro and we'll take another look.