diff --git a/Lib/asyncio/base_events.py b/Lib/asyncio/base_events.py index 5d295bc3fb9b5cc..8b25dc5490c9be9 100644 --- a/Lib/asyncio/base_events.py +++ b/Lib/asyncio/base_events.py @@ -1020,8 +1020,12 @@ def _check_sendfile_params(self, sock, file, offset, count): "offset must be a non-negative integer (got {!r})".format( offset)) - async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): - """Create, bind and connect one socket.""" + async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None, + connected_sockets=None): + """Create, bind and connect one socket. + + If *connected_sockets* is a list, the connected socket is appended to it. + """ my_exceptions = [] exceptions.append(my_exceptions) family, type_, proto, _, address = addr_info @@ -1051,6 +1055,8 @@ async def _connect_sock(self, exceptions, addr_info, local_addr_infos=None): else: raise OSError(f"no matching local address with {family=} found") await self.sock_connect(sock, address) + if connected_sockets is not None: + connected_sockets.append(sock) return sock except OSError as exc: my_exceptions.append(exc) @@ -1157,18 +1163,28 @@ async def create_connection( except OSError: continue else: # using happy eyeballs - sock = (await staggered.staggered_race( - ( - # can't use functools.partial as it keeps a reference - # to exceptions - lambda addrinfo=addrinfo: self._connect_sock( - exceptions, addrinfo, laddr_infos - ) - for addrinfo in infos - ), - happy_eyeballs_delay, - loop=self, - ))[0] # can't use sock, _, _ as it keeks a reference to exceptions + # Sockets connected by the attempts, so that the winner is + # closed if the race is cancelled before it returns. + connected = [] + try: + sock = (await staggered.staggered_race( + ( + # can't use functools.partial as it keeps a + # reference to exceptions + lambda addrinfo=addrinfo: self._connect_sock( + exceptions, addrinfo, laddr_infos, connected + ) + for addrinfo in infos + ), + happy_eyeballs_delay, + loop=self, + ))[0] # can't use sock, _, _ as it keeks a reference to exceptions + except BaseException: + for connected_sock in connected: + connected_sock.close() + raise + finally: + connected = None if sock is None: exceptions = [exc for sub in exceptions for exc in sub] diff --git a/Lib/test/test_asyncio/test_base_events.py b/Lib/test/test_asyncio/test_base_events.py index 0c54b64efad7e28..addf084115ffb8d 100644 --- a/Lib/test/test_asyncio/test_base_events.py +++ b/Lib/test/test_asyncio/test_base_events.py @@ -1412,6 +1412,35 @@ async def mock_race(coro_fns, delay, loop): with self.assertRaisesRegex(TimeoutError, "create_connection failed"): self.loop.run_until_complete(coro) + def test_create_connection_happy_eyeballs_cancelled_closes_winner(self): + # A socket that wins the race must not leak if create_connection() + # is cancelled before the race returns it. + sock = mock.Mock() + connected = False + + async def getaddrinfo(*args, **kw): + return [(socket.AF_INET, socket.SOCK_STREAM, 0, '', ('192.0.2.1', 80))] + + async def connect_sock(exceptions, addr_info, local_addr_infos=None, + connected_sockets=None): + nonlocal connected + connected = True + connected_sockets.append(sock) + return sock + + self.loop.getaddrinfo = getaddrinfo + self.loop._connect_sock = connect_sock + + task = self.loop.create_task(self.loop.create_connection( + MyProto, 'example.com', 80, happy_eyeballs_delay=0.1)) + while not connected: + test_utils.run_once(self.loop) + task.cancel() + with self.assertRaises(asyncio.CancelledError): + self.loop.run_until_complete(task) + + sock.close.assert_called_once_with() + def test_create_connection_host_port_sock(self): coro = self.loop.create_connection( MyProto, 'example.com', 80, sock=object()) diff --git a/Misc/NEWS.d/next/Library/2026-11-15-18-49-07.gh-issue-162059.cUkuR1.rst b/Misc/NEWS.d/next/Library/2026-11-15-18-49-07.gh-issue-162059.cUkuR1.rst new file mode 100644 index 000000000000000..d1bcced9c0ff51d --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-15-18-49-07.gh-issue-162059.cUkuR1.rst @@ -0,0 +1,3 @@ +Fix a socket leak in :meth:`asyncio.loop.create_connection` with +*happy_eyeballs_delay*: if the call is cancelled after an attempt connects but +before the race returns, the connected socket is now closed.