Skip to content

gh-130141: clean up asyncio._SelectorTransport during __del__ #130142

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
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions Lib/asyncio/selector_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -864,16 +864,37 @@ def close(self):
self._closing = True
self._loop._remove_reader(self._sock_fd)
if not self._buffer:
self._conn_lost += 1
self._loop._remove_writer(self._sock_fd)
self._conn_lost += 1
self._loop.call_soon(self._call_connection_lost, None)

def __del__(self, _warn=warnings.warn):
if self._sock is not None:
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)
if self._protocol_connected:
self._protocol_connected = False
_warn(f"unclosed transport {self!r}", ResourceWarning, source=self)

if self._buffer:
self._buffer.clear()
self._loop._remove_writer(self._sock_fd)

if not self._closing:
self._closing = True
self._loop._remove_reader(self._sock_fd)

self._conn_lost += 1

self._sock_fd = -1
self._sock.close()
if self._server is not None:
self._server._detach(self)
self._sock = None

self._protocol = None
self._loop = None

server = self._server
if server is not None:
self._server = None
server._detach(self)

def _fatal_error(self, exc, message='Fatal error on transport'):
# Should be called from exception handler only.
Expand Down Expand Up @@ -904,8 +925,10 @@ def _force_close(self, exc):
def _call_connection_lost(self, exc):
try:
if self._protocol_connected:
self._protocol_connected = False
self._protocol.connection_lost(exc)
finally:
self._sock_fd = -1
self._sock.close()
self._sock = None
self._protocol = None
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix asyncio selector stall if :class:`!asyncio._SelectorTransport` is
resurrected from GC for .close() after the fd has been reused.
Loading