You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Config.create_sockets() leaves the socket unclosed when bind() fails #94
Config._create_sockets (inherited from Hypercorn) creates a socket, configures it, then calls sock.bind(binding). If bind() raises (e.g. EADDRINUSE), the socket that was just created is never closed, and neither are the sockets already created for earlier entries in binds. They are only reclaimed by the garbage collector, with ResourceWarning: unclosed <socket.socket ... laddr=('0.0.0.0', 0)>.
bind failed as expected: [Errno 98] Address already in use
repro.py:17: ResourceWarning: unclosed <socket.socket fd=4, family=2, type=1, proto=0, laddr=('0.0.0.0', 0)>
collecting...
Here the socket is released by reference counting as soon as the exception is dropped. When the exception travels through task groups / exception groups, the traceback (holding the _create_sockets frame and its local sock) tends to end up in a reference cycle, so the socket stays open until the cyclic GC runs at some arbitrary later point. We hit it in a test suite that fails on ResourceWarning: a test that deliberately binds an occupied port made unrelated tests fail intermittently.
Closing what was created when anything in the loop raises would fix it, e.g. a try/except BaseException around each socket's setup that closes sock and re-raises, and an outer one that closes the already-collected sockets. (For fd:// the socket wraps a caller-owned descriptor, so that path may want detach() rather than close(); it only raises SocketTypeError before any bind.)
The same code is in Hypercorn, reported there as pgjones/hypercorn#392. Happy to send a PR here if you'd like.
Thanks again for the quick fix in #96! Is a release that includes it planned soon?
We currently bind the listening sockets ourselves to avoid the leaked socket on a failed bind(), and we'd like to drop that workaround and hand binding back to Config.create_sockets() once the fix is on PyPI (0.20.1 doesn't include it yet).
Activity
davidbrochart commentedon Nov 2, 2026
Thanks for reporting @MichengLiang, I opened #96.
MichengLiang commentedon Nov 13, 2026
Thanks again for the quick fix in #96! Is a release that includes it planned soon?
We currently bind the listening sockets ourselves to avoid the leaked socket on a failed
bind(), and we'd like to drop that workaround and hand binding back toConfig.create_sockets()once the fix is on PyPI (0.20.1 doesn't include it yet).