Repository navigation
Description
Bug report
Bug description:
When loop.create_connection() runs with happy_eyeballs_delay and is cancelled after an attempt has connected but before staggered_race() returns, the connected socket is never closed. It is only released by the garbage collector, with a ResourceWarning: unclosed <socket.socket ...>.
staggered_race() re-raises the CancelledError once its tasks finish, even when one of them has already won, so the winner's result (the socket) is dropped. create_connection() never sees it, so nothing closes it. Without happy_eyeballs_delay, _connect_sock() closes the socket on cancellation and nothing leaks.
Reproducer (a local server; cancel after 0–7 loop iterations):
import asyncio, gc, warnings
leaks = []
warnings.simplefilter("always")
warnings.showwarning = lambda message, category, *a, **k: leaks.append(message) if category is ResourceWarning else None
async def trial(port, spins, eyeballs):
loop = asyncio.get_running_loop()
options = {"happy_eyeballs_delay": 0.25} if eyeballs else {}
task = loop.create_task(loop.create_connection(asyncio.Protocol, "127.0.0.1", port, **options))
for _ in range(spins):
await asyncio.sleep(0)
task.cancel()
try:
transport, _ = await task
transport.close()
except asyncio.CancelledError:
pass
await asyncio.sleep(0)
async def main(eyeballs):
loop = asyncio.get_running_loop()
server = await loop.create_server(asyncio.Protocol, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
for i in range(400):
await trial(port, i % 8, eyeballs)
server.close()
for eyeballs in (False, True):
leaks.clear()
asyncio.run(main(eyeballs))
gc.collect()
print(f"happy_eyeballs={eyeballs}: {len(leaks)} leaked sockets")Output on 3.13.12 (macOS); 3.11.15 and 3.14.3 behave the same, and the code on main is unchanged:
happy_eyeballs=False: 0 leaked sockets
happy_eyeballs=True: 199 leaked sockets
A cancellation here is routine: asyncio.timeout() / wait_for() around open_connection(..., happy_eyeballs_delay=...), or a client closed while it connects.
Proposed fix: create_connection() remembers the sockets the attempts connect and closes them if the race raises. staggered_race() keeps propagating the cancellation as it does now.
CPython versions tested on:
3.11, 3.13, 3.14
Operating systems tested on:
macOS
Linked PRs
Metadata
Metadata
Assignees
Labels
Projects
- StatusShow more project fieldsTodo
Activity
kumaraditya303 commentedon Nov 17, 2026
This is not a real leak, the socket would be closed later anyways by the garbage collector. asyncio apps create a lot of cyclic garbage and it is not worth manually clearing cycles unless it holds on to large amount of memory.