Fixed Race Condition in RunResultStreaming.stream_events() Method #1745
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.
Problem Description
There was a critical race condition in the
RunResultStreaming.stream_events()method insrc/agents/result.pythat caused premature cancellation of session operations during streaming.Issues: Closes #1658 - Resolves race condition causing incomplete session state during streaming operations.
Root Cause
_cleanup_tasks()method was being called immediately after the streaming loop finished_run_impl_task) completedsession.add_items()calls were being cancelled prematurelyImpact
Solution
Added proper task synchronization in the
stream_events()method around line 219:Technical Details
_cleanup_tasks()ran immediately after streaming loop completion_cleanup_tasks()waits for_run_impl_taskto complete first_await_task_safely()method for proper error handlingTesting Results
Comprehensive testing confirms the fix resolves the race condition:
Test Coverage
Specific Validation
session.add_items()Checklist
await self._await_task_safely(self._run_impl_task)Files Changed
src/agents/result.py- Added task synchronization instream_events()methodImpact
Environment Tested: