fix(session): remove orphaned toolResult blocks in middle of conversation #1612
+322
−15
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
This PR fixes issue #1610 where Browser Tool + Memory causes
ValidationExceptionafter the first message in a session.Problem
When using tools (especially Browser Tool) with session memory, context truncation or summarization may remove
toolUseblocks while keeping their correspondingtoolResultblocks. This creates "orphaned"toolResultblocks that cause:Error Scenario
toolUseblockstoolUseblocks removed,toolResultkeptThis is a widespread issue affecting:
Root Cause
The existing
_fix_broken_tool_usemethod only handled:toolResultat the START of conversation (first message)toolUse(missingtoolResult)toolResultin the MIDDLE of conversationSolution
Added
_remove_orphaned_tool_resultsmethod that:toolUseIdvalues fromtoolUseblocks in all messagestoolResultblockstoolResultwhosetoolUseIdhas no matchingtoolUsetoolResultblocksCode Change
Testing
Added 5 new tests covering:
test_fix_broken_tool_use_removes_orphaned_tool_result_in_middletest_fix_broken_tool_use_removes_multiple_orphaned_tool_resultstest_fix_broken_tool_use_keeps_valid_tool_results_removes_orphanedtest_fix_broken_tool_use_removes_orphaned_from_mixed_content_messagetest_fix_broken_tool_use_browser_tool_memory_scenarioAll 29 tests pass:
Files Changed
src/strands/session/repository_session_manager.py- Added_remove_orphaned_tool_resultsmethodtests/strands/session/test_repository_session_manager.py- Added 5 new testsRelated Issues
Note: This fix is backward compatible and won't affect existing valid conversations. It only removes
toolResultblocks that have no matchingtoolUseblock anywhere in the conversation history.