diff --git a/Lib/asyncio/subprocess.py b/Lib/asyncio/subprocess.py index 26d7b755105c9d5..f83d00af5b5d450 100644 --- a/Lib/asyncio/subprocess.py +++ b/Lib/asyncio/subprocess.py @@ -77,13 +77,14 @@ def pipe_connection_lost(self, fd, exc): if pipe is not None: pipe.close() self.connection_lost(exc) - if exc is None: - self._stdin_closed.set_result(None) - else: - self._stdin_closed.set_exception(exc) - # Since calling `wait_closed()` is not mandatory, - # we shouldn't log the traceback if this is not awaited. - self._stdin_closed._log_traceback = False + if not self._stdin_closed.done(): + if exc is None: + self._stdin_closed.set_result(None) + else: + self._stdin_closed.set_exception(exc) + # Since calling `wait_closed()` is not mandatory, + # we shouldn't log the traceback if this is not awaited. + self._stdin_closed._log_traceback = False return if fd == 1: reader = self.stdout diff --git a/Lib/test/test_asyncio/test_subprocess.py b/Lib/test/test_asyncio/test_subprocess.py index 6e85bdd57c9085b..38c236c9441ee07 100644 --- a/Lib/test/test_asyncio/test_subprocess.py +++ b/Lib/test/test_asyncio/test_subprocess.py @@ -435,6 +435,31 @@ async def write_stdin(proc, data): self.loop.run_until_complete, coro) self.loop.run_until_complete(proc.wait()) + def test_stdin_wait_closed_cancelled(self): + # gh-162217: cancelling a task waiting in stdin.wait_closed() must + # not make pipe_connection_lost() fail with InvalidStateError. + async def main(): + proc = await asyncio.create_subprocess_exec( + *PROGRAM_CAT, + stdin=subprocess.PIPE, + stdout=subprocess.DEVNULL, + ) + try: + task = asyncio.create_task(proc.stdin.wait_closed()) + await asyncio.sleep(0) + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + finally: + proc.stdin.close() + await proc.wait() + + messages = [] + self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx)) + + self.loop.run_until_complete(main()) + self.assertEqual(messages, []) + def test_communicate_ignore_broken_pipe(self): # buffer large enough to feed the whole pipe buffer large_data = b'x' * support.PIPE_MAX_SIZE diff --git a/Misc/NEWS.d/next/Library/2026-11-20-09-30-00.gh-issue-162217.wC7sHd.rst b/Misc/NEWS.d/next/Library/2026-11-20-09-30-00.gh-issue-162217.wC7sHd.rst new file mode 100644 index 000000000000000..be12568cb8f7fec --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-11-20-09-30-00.gh-issue-162217.wC7sHd.rst @@ -0,0 +1,4 @@ +Fix :exc:`asyncio.InvalidStateError` being logged when the standard input of +an :mod:`asyncio` subprocess is closed after a task waiting in +:meth:`proc.stdin.wait_closed() ` was +cancelled.