Title: asyncio: cancelling a task awaiting subprocess `stdin.wait_closed()` cancels the shared close future, then `pipe_connection_lost()` raises `InvalidStateError` · Issue #162217 · python/cpython · GitHub
Open Graph Title: asyncio: cancelling a task awaiting subprocess `stdin.wait_closed()` cancels the shared close future, then `pipe_connection_lost()` raises `InvalidStateError` · Issue #162217 · python/cpython
X Title: asyncio: cancelling a task awaiting subprocess `stdin.wait_closed()` cancels the shared close future, then `pipe_connection_lost()` raises `InvalidStateError` · Issue #162217 · python/cpython
Description: Bug report Bug description For a subprocess created with asyncio.create_subprocess_exec(..., stdin=PIPE), proc.stdin.wait_closed() awaits the protocol's shared _stdin_closed future directly. SubprocessStreamProtocol._get_close_waiter() r...
Open Graph Description: Bug report Bug description For a subprocess created with asyncio.create_subprocess_exec(..., stdin=PIPE), proc.stdin.wait_closed() awaits the protocol's shared _stdin_closed future directly. Subpro...
X Description: Bug report Bug description For a subprocess created with asyncio.create_subprocess_exec(..., stdin=PIPE), proc.stdin.wait_closed() awaits the protocol's shared _stdin_closed future directly. Su...
Opengraph URL: https://github.com/python/cpython/issues/162217
X: @github
Domain: github.com
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"asyncio: cancelling a task awaiting subprocess `stdin.wait_closed()` cancels the shared close future, then `pipe_connection_lost()` raises `InvalidStateError`","articleBody":"# Bug report\n\n### Bug description\n\nFor a subprocess created with `asyncio.create_subprocess_exec(..., stdin=PIPE)`, `proc.stdin.wait_closed()` awaits the protocol's shared `_stdin_closed` future directly. `SubprocessStreamProtocol._get_close_waiter()` returns it, and `StreamWriter.wait_closed()` awaits it without `shield()`. If the task awaiting `wait_closed()` is cancelled after `proc.stdin.close()` but before the pipe's `connection_lost` callback runs, the cancellation cancels that shared future.\n\nWhen `SubprocessStreamProtocol.pipe_connection_lost(0, None)` runs later, it calls `self._stdin_closed.set_result(None)` on the already-cancelled future. The event loop then logs:\n\n```\nException in callback SubprocessStreamProtocol.pipe_connection_lost()\n...\nasyncio.exceptions.InvalidStateError: invalid state\n```\n\n`StreamReaderProtocol` guards the equivalent future for sockets (`if not self._closed.done(): ...`); `SubprocessStreamProtocol.pipe_connection_lost()` has no such check.\n\nMinimal, deterministic reproducer:\n\n```python\nimport asyncio\nimport sys\n\n\nasync def main(mode: str) -> int:\n loop = asyncio.get_running_loop()\n errors = []\n loop.set_exception_handler(lambda _loop, ctx: errors.append(ctx))\n proc = await asyncio.create_subprocess_exec(\n \"cat\", stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE,\n stderr=asyncio.subprocess.PIPE,\n )\n proc.stdin.close()\n\n async def closer():\n if mode == \"shield\":\n await asyncio.shield(proc.stdin.wait_closed())\n else:\n await proc.stdin.wait_closed()\n\n task = asyncio.create_task(closer())\n await asyncio.sleep(0) # let closer() reach the await on the close future\n task.cancel() # cancel between close() and pipe_connection_lost()\n try:\n await task\n except asyncio.CancelledError:\n pass\n print(\"stdin close future:\", proc._protocol._stdin_closed)\n await proc.communicate()\n await proc.wait()\n for _ in range(5):\n await asyncio.sleep(0)\n for ctx in errors:\n print(\"loop exception:\", repr(ctx.get(\"exception\")), \"|\", ctx.get(\"message\"))\n return 1 if errors else 0\n\n\nif __name__ == \"__main__\":\n sys.exit(asyncio.run(main(sys.argv[1] if len(sys.argv) > 1 else \"plain\")))\n```\n\nOutput on 3.14.4 (Linux):\n\n```\n$ python3 repro.py\nstdin close future: \u003cFuture cancelled>\nloop exception: InvalidStateError('invalid state') | Exception in callback SubprocessStreamProtocol.pipe_connection_lost()\n\n$ python3 repro.py shield\nstdin close future: \u003cFuture finished result=None>\n```\n\nThe visible impact is an error logged from a loop callback (for example during application shutdown, when a task blocked in `wait_closed()` gets cancelled). Process I/O is otherwise unaffected. In our case it appeared intermittently in a test suite (about 5 in 2,000 runs under load) until we stopped awaiting `wait_closed()` on that path.\n\nPossible fixes, either of which avoids the error:\n- In `SubprocessStreamProtocol.pipe_connection_lost()`, only call `set_result()` / `set_exception()` on `_stdin_closed` when it is not already done, mirroring `StreamReaderProtocol`.\n- Or have `wait_closed()` (or `_get_close_waiter()`) shield the shared future, so cancelling one waiter does not cancel it for everyone.\n\nPossibly related older report: bpo-23140.\n\n### CPython versions tested on\n\n3.14\n\n### Operating systems tested on\n\nLinux\n\n\n\u003c!-- gh-linked-prs -->\n### Linked PRs\n* gh-162284\n* gh-162317\n* gh-162320\n* gh-162321\n\u003c!-- /gh-linked-prs -->\n","author":{"url":"https://github.com/AugustusHsu","@type":"Person","name":"AugustusHsu"},"datePublished":"2026-11-18T15:46:30Z","url":"https://github.com/python/cpython/issues/162217"}
| 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:3ab31b7a-d2d1-7065-505c-609e4b8ae8cd |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | D5CC:1CCECA:1425186:1ACD523:6B02038B |
| html-safe-nonce | 4c33615e1bb8d437887428e0de6abe984236f64b0c49f190bba0e815bcb7396f |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJENUNDOjFDQ0VDQToxNDI1MTg2OjFBQ0Q1MjM6NkIwMjAzOEIiLCJ2aXNpdG9yX2lkIjoiMzY2Mjg4MTY4MTAxMjAzMjM5NiIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | c1a3e8c3415cd24de1a65c104e8b29fa0423f2ce6aa6ac6ec5e085861665d010 |
| hovercard-subject-tag | issue:6470947088 |
| 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/162217/issue_layout |
| twitter:image | https://opengraph.githubassets.com/6de1b71849e5f6bdf960109dc99ef821573082d6508186277ed9999f57f85ae4/python/cpython/issues/162217 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/6de1b71849e5f6bdf960109dc99ef821573082d6508186277ed9999f57f85ae4/python/cpython/issues/162217 |
| og:image:alt | Bug report Bug description For a subprocess created with asyncio.create_subprocess_exec(..., stdin=PIPE), proc.stdin.wait_closed() awaits the protocol's shared _stdin_closed future directly. Subpro... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | AugustusHsu |
| 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 | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
Viewport: width=device-width