Fix streaming deadlock with async tools by using send_nowait #8936
+66
−13
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
When using DSPy's streaming feature (
dspy.streamify()) with async tools (like MCP tools or ReAct tool calls), the stream would freeze indefinitely after a tool completed execution. The stream never continued past the "Tool calling finished!" status message, causing the application to hang.Root Cause
The
sync_send_to_streamfunction was usingThreadPoolExecutorto send messages when running in an event loop:The issue occurred because:
@with_callbacksdecorator)sync_send_to_streamto send status messagesfuture.result()blocked the current thread, causing the event loop to deadlockSolution
Replaced the ThreadPoolExecutor approach with anyio's
send_nowait()method, which is a synchronous, non-blocking method available onMemoryObjectSendStream:This allows callbacks to send status messages without blocking the event loop, fixing the deadlock while maintaining backward compatibility.
Changes
sync_send_to_streamindspy/streaming/messages.pyto usestream.send_nowait()concurrent.futuresimporttest_async_tool_streaming_no_deadlockto prevent future regressionsTesting
Impact
This fix enables:
The change also improves performance by eliminating thread creation overhead.
Original prompt
Fixes #8934
✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.