Title: asyncio: socket leak and silent error when transport creation fails for an accepted connection · Issue #155934 · python/cpython · GitHub
Open Graph Title: asyncio: socket leak and silent error when transport creation fails for an accepted connection · Issue #155934 · python/cpython
X Title: asyncio: socket leak and silent error when transport creation fails for an accepted connection · Issue #155934 · python/cpython
Description: Bug report Bug description When an incoming connection has been accepted and protocol_factory() (or transport creation) then raises inside BaseSelectorEventLoop._accept_connection2() (Lib/asyncio/selector_events.py), two things go wrong....
Open Graph Description: Bug report Bug description When an incoming connection has been accepted and protocol_factory() (or transport creation) then raises inside BaseSelectorEventLoop._accept_connection2() (Lib/asyncio/s...
X Description: Bug report Bug description When an incoming connection has been accepted and protocol_factory() (or transport creation) then raises inside BaseSelectorEventLoop._accept_connection2() (Lib/asyncio/s...
Opengraph URL: https://github.com/python/cpython/issues/155934
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"asyncio: socket leak and silent error when transport creation fails for an accepted connection","articleBody":"# Bug report\n\n## Bug description\n\nWhen an incoming connection has been accepted and `protocol_factory()` (or transport creation) then raises inside `BaseSelectorEventLoop._accept_connection2()` (`Lib/asyncio/selector_events.py`), two things go wrong.\n\nFirst, **The accepted socket is never closed.** Ownership of `conn` only passes to the transport once it is created; if creation fails, nothing closes the socket, so the `fd` leaks until garbage collection\n(Log: `ResourceWarning: unclosed \u003csocket.socket ...>` with the server's address as `laddr`).\n\nSecond, **The error is reported only in debug mode.** The `except BaseException` block calls `call_exception_handler()` behind `if self._debug:`, so with the default `debug=False` the failure is not reported anywhere. The client sees an established connection that never answers (the TCP handshake and ACKs come from the kernel), while the server keeps no record that the connection ever existed.\n\nThis is the server-side counterpart of gh-153133, which fixed the same socket leak in `create_connection()` (gh-153134).\nIt is also inconsistent with `_accept_connection()` itself, which reports accept-stage errors (e.g. `EMFILE`, `ENFILE`, ...) via `call_exception_handler()` unconditionally.\n\n## Reproducer\n\n```python\nimport asyncio\nimport sys\n\nasync def main(debug):\n loop = asyncio.get_running_loop()\n loop.set_debug(debug)\n handler_calls = []\n loop.set_exception_handler(lambda l, ctx: handler_calls.append(ctx.get(\"message\")))\n\n def bad_factory():\n raise RuntimeError(\"boom in protocol_factory\")\n\n server = await loop.create_server(bad_factory, \"127.0.0.1\", 0)\n port = server.sockets[0].getsockname()[1]\n\n reader, writer = await asyncio.open_connection(\"127.0.0.1\", port)\n await asyncio.sleep(0.2)\n\n writer.close()\n server.close()\n await server.wait_closed()\n print(f\"debug={debug} exception_handler calls={len(handler_calls)} {handler_calls}\")\n\nasyncio.run(main(debug=(sys.argv[1:] == [\"1\"])))\n```\n\nOutput on current main:\n\n```\n$ ./python repro.py\ndebug=False exception_handler calls=\nResourceWarning: unclosed \u003csocket.socket fd=8, ..., laddr=('127.0.0.1', \u003cserver port>), ...>\n\n$ ./python repro.py 1\ndebug=True exception_handler calls=1ation for incoming connection']\n```\n\nThe leaked socket's `laddr` is the server port, it is the accepted server-side socket.\n\n## Suggested fix\n\nMirror gh-153134 on the server side. When the transport was never created, close `conn` and report the exception unconditionally. Reporting should stay limited to that case because the same `except` block also sees `await waiter` failures such as SSL handshake errors from port scanners, and reporting those unconditionally would be noisy.\n\nI'd like to work on this as part of the PyCon KR sprint. @hugovk @corona10 \n\nFound while verifying entries from [devdanzin's stdlib audit catalog] n.22 (https://gist.github.com/devdanzin/3198710e3c0128fda5e0a7b4e0768e5f).\n\n### CPython versions tested on:\n\nCPython main branch\n\n### Operating systems tested on:\n\nmacOS\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-155936\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/danielKim614","@type":"Person","name":"danielKim614"},"datePublished":"2026-08-17T06:01:53Z","url":"https://github.com/python/cpython/issues/155934"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:25be892a-6da0-5092-925e-97bac25a7206 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D2B2:A99C2:4824528:5B75545:6B022F64 |
| html-safe-nonce | 92773515a313399fd6b1e8b57be7ce37ad0285353e378f08e645cda372bd2bb3 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJEMkIyOkE5OUMyOjQ4MjQ1Mjg6NUI3NTU0NTo2QjAyMkY2NCIsInZpc2l0b3JfaWQiOiI4OTM2ODk2NDMxNTE2NjkyMzI0IiwicmVnaW9uX2VkZ2UiOiJpYWQiLCJyZWdpb25fcmVuZGVyIjoiaWFkIn0= |
| visitor-hmac | e4cd2de92d0f4edd8ac63aa6d6a49b2316117055356f04315cdc7ea81c02d82e |
| hovercard-subject-tag | issue:5168791868 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/python/cpython/155934/issue_layout |
| twitter:image | https://opengraph.githubassets.com/4e12a281180f8cf0b747b59f6936a89ad8f6c03b03d4aa5dce1cdbb85085aa73/python/cpython/issues/155934 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/4e12a281180f8cf0b747b59f6936a89ad8f6c03b03d4aa5dce1cdbb85085aa73/python/cpython/issues/155934 |
| og:image:alt | Bug report Bug description When an incoming connection has been accepted and protocol_factory() (or transport creation) then raises inside BaseSelectorEventLoop._accept_connection2() (Lib/asyncio/s... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | danielKim614 |
| hostname | github.com |
| expected-hostname | github.com |
| None | 87e774ee7c6b3bee0490394e4d3e57ec9dbc956f74b87ea685dc8996c1676456 |
| turbo-cache-control | no-preview |
| go-import | github.com/python/cpython git https://github.com/python/cpython.git |
| octolytics-dimension-user_id | 1525981 |
| octolytics-dimension-user_login | python |
| octolytics-dimension-repository_id | 81598961 |
| octolytics-dimension-repository_nwo | python/cpython |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 81598961 |
| octolytics-dimension-repository_network_root_nwo | python/cpython |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 423dbb54c5e7bfecc838eb387c1435eb3d0e760d |
| ui-target | canary-1 |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width