PYTHON-5867 - Close sockets on interruption or cancellation during async connection creation#2858
PYTHON-5867 - Close sockets on interruption or cancellation during async connection creation#2858NoahStapp wants to merge 8 commits into
Conversation
…ync connection creation
There was a problem hiding this comment.
Pull request overview
This PR addresses a resource-leak scenario in PyMongo’s async connection setup by ensuring sockets/transports are closed when connection creation is interrupted (e.g., task cancellation), which is especially important for event-loop reliability and preventing leaked file descriptors.
Changes:
- Add cancellation/interruption-safe cleanup (
except BaseException: close(); raise) in async socket creation and TLS configuration paths. - Ensure transports are aborted / sockets are closed when failures occur during async protocol interface setup.
- Add a destructor (
__del__) toAsyncNetworkingInterfaceto synchronously close the underlying raw socket if the connection is orphaned (e.g., loop already closed).
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
pymongo/pool_shared.py |
Adds broad-exception cleanup to prevent socket leaks during async connection creation/configuration and protocol setup. |
pymongo/network_layer.py |
Adds AsyncNetworkingInterface.__del__ to defensively close raw sockets when async connections are orphaned. |
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
| import asyncio | ||
| import functools | ||
| import socket as _socket | ||
| import ssl as _ssl |
There was a problem hiding this comment.
Do _socket and _ssl need to be private here ?
There was a problem hiding this comment.
Good catch, vestigial import naming from an earlier version that overrode them.
PYTHON-5867
Changes in this PR
Close sockets opened as part of async connection creation when an interruption or cancellation occurs.
Test Plan
Fix existing PyPy test failure.
Checklist
Checklist for Author
Checklist for Reviewer