-
Notifications
You must be signed in to change notification settings - Fork 772
fix: clear leaked running loop in MCP client background thread #2111
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
mkmeral
wants to merge
1
commit into
strands-agents:main
Choose a base branch
from
mkmeral:fix/otel-threading-mcp-client
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+39
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -88,3 +88,39 @@ def capturing_background_task(self): | |
| ) | ||
| # Verify it was indeed a different thread | ||
| assert background_thread_value["thread_id"] != main_thread_id, "Background task should run in a different thread" | ||
|
|
||
|
|
||
| def test_mcp_client_clears_running_loop_in_background_thread(mock_transport, mock_session): | ||
| """Test that _background_task clears any leaked running event loop state. | ||
|
|
||
| When OpenTelemetry's ThreadingInstrumentor is active, Thread.run() is wrapped to propagate | ||
| trace context, which can leak the parent thread's running event loop reference into child | ||
| threads. This causes "RuntimeError: Cannot run the event loop while another loop is running" | ||
| when the background thread calls run_until_complete(). | ||
|
|
||
| This test simulates that scenario by setting a running loop before _background_task runs | ||
| and verifying it gets cleared. | ||
| """ | ||
| import asyncio | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Issue: Suggestion: Move |
||
|
|
||
| cleared_running_loop = {} | ||
|
|
||
| original_background_task = MCPClient._background_task | ||
|
|
||
| def simulating_otel_leak_background_task(self): | ||
| # Simulate OTEL ThreadingInstrumentor leaking the parent's running loop | ||
| fake_loop = asyncio.new_event_loop() | ||
| asyncio._set_running_loop(fake_loop) # type: ignore[attr-defined] | ||
|
|
||
| # Call the real _background_task — it should clear the leaked loop and succeed | ||
| try: | ||
| return original_background_task(self) | ||
| finally: | ||
| cleared_running_loop["success"] = True | ||
| fake_loop.close() | ||
|
|
||
| with patch.object(MCPClient, "_background_task", simulating_otel_leak_background_task): | ||
| with MCPClient(mock_transport["transport_callable"]) as client: | ||
| assert client._background_thread is not None | ||
|
|
||
| assert cleared_running_loop.get("success"), "_background_task should have run successfully despite leaked loop" | ||
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Important:
asyncio._set_running_loopis a private/internal CPython API (prefixed with_). While it's been stable across Python 3.10–3.13 and is the correct low-level mechanism for this, it's worth noting the risk: this could change in a future CPython release without deprecation notice.Suggestion: Consider adding a defensive wrapper or at minimum a brief inline comment noting the Python version range where this is known to work, so future maintainers know to verify if the minimum supported Python version changes. For example:
This is non-blocking — the existing comment is already good context about why, just suggesting adding a note about the private API nature.