sdk-python icon indicating copy to clipboard operation
sdk-python copied to clipboard

[BUG] Concurrent invocations on the same session interleave toolUse/toolResult messages in the persisted history

Open surecloud-jleite opened this issue 3 months ago • 2 comments

Update (2026-10-12): the trigger turned out to be concurrent invocations on the same session, not an interrupted turn. Two requests running at the same time append their messages interleaved, which produces the warnings below. Since 1.55.0 the restore repair keeps the session usable, but the repair is not persisted and it replaces the real tool results with synthetic errors. Details and redacted histories: https://github.com/strands-agents/harness-sdk/issues/3651#issuecomment-6123070020 (AI-assisted). The original report is below, unchanged.

Strands Version

1.50.2

Python Version

3.13

Operating System

Linux (container)

Model

Claude Sonnet 4.6 via Amazon Bedrock

Session persistence

Custom SessionRepository backed by an append-only external event store

What happens

A turn is interrupted while tools are executing (in our case a model read timeout, and separately a container recycle mid-stream). The session survives and accepts the next turn, but from that point on every turn fails with the same error, indefinitely. No retry, reset, or configuration change recovers it. A new session with the same agent configuration is unaffected.

On each subsequent turn, restore logs this warning:

tool_use_ids=<['toolu_A']>, result_ids=<['toolu_B']> | session history has mismatched toolUse/toolResult pairing, rebuilding

The two id sets have no ids in common. The turn then fails:

ValidationException: The number of toolResult blocks at messages.11.content
exceeds the number of toolUse blocks of previous turn.

Both the warning and the error repeat verbatim on every retry and every later turn, including the same message index each time.

We also see a variant where the warning reports two ids against an empty result set, on a turn where two tools had been called in parallel:

tool_use_ids=<['toolu_C', 'toolu_D']>, result_ids=<[]> | session history has mismatched toolUse/toolResult pairing, rebuilding

followed by the same ValidationException.

In some affected sessions we see this info-level line logged on an earlier turn, before the failures begin:

Agents latest message is toolUse, appending a toolResult message to have valid conversation.

Workaround attempted

The session-manager integration we use (the AgentCore Memory integration for Strands, from the bedrock-agentcore package) exposes a config option, filter_restored_tool_context, which strips historical tool context from restored messages. We tried enabling it to sidestep this failure.

With it enabled, every request fails as soon as there is history to restore:

ValidationException: messages.1.content.6: `thinking` or `redacted_thinking` blocks in
the latest assistant message cannot be modified. These blocks must remain as they were
in the original response.

Our agents run with extended thinking enabled, so that option is not available to us.

Filed separately against that project: https://github.com/aws/bedrock-agentcore-sdk-python/issues/621

Expected

An interrupted turn should leave the session able to continue, possibly with some loss of context. Failing that, the failure should be transient rather than terminal, so that a retry or the next turn can succeed.

Notes

This looks like the same scenario as #859, which is closed as fixed. We are on the latest release.

I don't have a minimal reproducer. This came out of production traffic, and the trigger is a turn dying mid-tool-execution against an append-only session store. Happy to help narrow it down or test a candidate fix against our workload.

surecloud-jleite avatar Aug 05 '26 10:08 surecloud-jleite

I tried to reproduce this and couldn't get to the "permanently unusable" state, but I did find a likely way the bad history gets written in the first place.

What I checked on current main:

  • I ran RepositorySessionManager._fix_broken_tool_use over every short history (up to 5 messages) built from a small set of shapes: assistant toolUse with one or two ids, user toolResult with matching, mismatched, partial, or extra ids, toolResult plus text, plain text turns. The repair always produced a valid pairing and gave the same output when run a second time. The one exception is an empty assistant message after a toolUse, which is #4409 (#4413 is open for it).
  • So on its own the restore-time repair looks sound for the [A] vs [B] and [C, D] vs [] shapes in this report. If the failure survives it in your setup, the history is probably shaped differently from what I generated, and I'd like to see it.

What does produce a corrupt history: when a tool dies mid-run under the default ConcurrentToolExecutor, the turn still finishes normally and the broken history is saved. With a scripted model and FileSessionManager:

  • one tool that raises a BaseException: the toolUse message is followed by a user message with no toolResult
  • two parallel tools, one of which dies: toolUses [C, D] followed by results for D only

That matches #4713, where ConcurrentToolExecutor silently drops a BaseException from a tool. I haven't shown it's the cause of what you saw, since that depends on what killed your turn. A model read timeout is an ordinary Exception, which I didn't see produce this.

@jusabiaga (or whoever filed this): if you can share the persisted message list around the failing index, with the content blocks redacted, plus which tool executor and conversation manager you use, that would help pin it down.

ashishpatel26 avatar Oct 02 '26 04:10 ashishpatel26

Thanks for digging into this. I filed it, and your comment sent me back to our traces. The trigger was not an interrupted turn. In the cases I traced, two invocations ran at the same time on the same session, and their messages were appended to the session interleaved.

How often

Going back to the July and August sessions behind this report: 26 agent sessions hit the ValidationException. In 25 of them, two or more requests on the same session overlapped before the first mismatch warning. Some were a parent agent calling the same sub-agent in parallel with a shared session id. Others were a new message arriving while the previous request was still running. The remaining one had an overlap four days earlier with a clean request in between, so I can't explain that one.

Setup

  • An agent served over HTTP. Each request builds a new Agent and a new AgentCoreMemorySessionManager (bedrock-agentcore) with the same session_id and the default agent_id, and restores the history from it.
  • Tool executor: the default ConcurrentToolExecutor.
  • Conversation manager: SummarizingConversationManager(summary_ratio=0.5, preserve_recent_messages=3, proactive_compression={"compression_threshold": 0.7}) with a separate summarization agent.
  • Plugins: AgentSkills and ContextOffloader.

The histories below are reconstructed from traces and the restore warnings. Ids are replaced and content is dropped.

Case 1: strands 1.54.0, bedrock-agentcore 1.22.0

A second request for the same session arrived 12 minutes later, while request 1 was still running. Request 2 restored the session and started its own tool calls. At one point both picked tools within 250 ms of each other:

[n]   assistant  toolUse X1, X2, X3         (request 2)
[n+1] assistant  toolUse Y1, Y2, Y3, Y4     (request 1)
[n+2] user       toolResult X1, X2, X3      (request 2)
[n+3] user       toolResult Y1, Y2, Y3, Y4  (request 1)

Restore warnings on the next request:

tool_use_ids=<[Y1, Y2, Y3, Y4]>, result_ids=<[X1, X2, X3]> | session history has mismatched toolUse/toolResult pairing, rebuilding
tool_use_ids=<[X1, X2, X3]>, result_ids=<[]> | session history has mismatched toolUse/toolResult pairing, rebuilding

Every request after that failed with ValidationException: The number of toolResult blocks at messages.58.content exceeds the number of toolUse blocks of previous turn, because 1.54.0 did not remove the orphaned result at n+3. That was the "permanently unusable" state. Both requests hit a Bedrock read timeout afterwards, which is the kind of failure I originally blamed.

Case 2: strands 1.59.0, bedrock-agentcore 1.24.1

Two requests for the same session arrived 0.5 s apart and ran fully in parallel. One called a single tool, the other called two:

[8]  assistant  toolUse P           (request 1)
[9]  assistant  toolUse Q1, Q2      (request 2)
[10] user       toolResult P        (request 1)
[11] user       toolResult Q1, Q2   (request 2)

Restore warnings, logged on every request in that session since then:

message_index=<11> | orphaned toolResult with no preceding toolUse. ...
tool_use_ids=<[Q1, Q2]>, result_ids=<[P]> | session history has mismatched toolUse/toolResult pairing, rebuilding
tool_use_ids=<[P]>, result_ids=<[]> | session history has mismatched toolUse/toolResult pairing, rebuilding

Here the repair works and the session stays usable, which matches what you found on main. Two things remain:

  • The repair only runs in memory. The persisted history stays broken, so the same warnings are logged on every restore for the life of the session.
  • The rebuilt history loses the real results of both requests. P and Q1, Q2 all get the synthetic "Tool was interrupted." error result, and the real Q1, Q2 results are removed as orphans. The model then sees three failed tool calls that actually succeeded.

About #4713

Every tool call in both cases finished with success status and nothing raised a BaseException, so I don't think #4713 is what we hit. From what I can see, nothing guards against two Agent instances writing to the same session at the same time. ConcurrencyException only covers concurrent calls on one instance, and the session manager appends messages in arrival order without knowing which invocation they belong to.

I traced our production logs and drafted this with an AI assistant.

surecloud-jleite avatar Oct 12 '26 11:10 surecloud-jleite