From 7b6f2f4390c58c18b49420380669c0a19858cb75 Mon Sep 17 00:00:00 2001 From: Timofey Ivankov Date: Fri, 28 Aug 2026 17:21:28 +0300 Subject: [PATCH] gh-156321: Fix asyncio.shield() reporting a retrieved exception --- Lib/asyncio/tasks.py | 11 ++++++++++- Lib/test/test_asyncio/test_tasks.py | 15 +++++++++++++++ ...2026-08-28-17-15-00.gh-issue-156321.mNOuMG.rst | 2 ++ 3 files changed, 27 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Library/2026-08-28-17-15-00.gh-issue-156321.mNOuMG.rst diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 498eec3f31b292b..b9157212fadef04 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -909,10 +909,19 @@ def _done_callback(fut, cur_task=cur_task): return outer -def _log_on_exception(fut): +def _log_on_exception(fut, deferred=False): if fut.cancelled(): return + if not deferred: + # gh-156321: an exception retrieved by an awaiter must not be reported + fut._loop.call_soon(_log_on_exception, fut, True) + return + + if not fut._log_traceback: + # The exception was retrieved, nothing to report. + return + exc = fut.exception() if exc is None: return diff --git a/Lib/test/test_asyncio/test_tasks.py b/Lib/test/test_asyncio/test_tasks.py index 9c111da8c27f162..fe3245a78339e40 100644 --- a/Lib/test/test_asyncio/test_tasks.py +++ b/Lib/test/test_asyncio/test_tasks.py @@ -2136,6 +2136,21 @@ def test_shield_cancel_outer_exception(self): test_utils.run_briefly(self.loop) mock_handler.assert_called_once() + def test_shield_cancel_outer_exception_retrieved(self): + # gh-156321: an exception retrieved by an awaiter must not be reported + mock_handler = mock.Mock() + self.loop.set_exception_handler(mock_handler) + inner = self.new_future(self.loop) + outer = asyncio.shield(inner) + test_utils.run_briefly(self.loop) + outer.cancel() + test_utils.run_briefly(self.loop) + inner.set_exception(Exception('foo')) + self.assertIsNotNone(inner.exception()) + test_utils.run_briefly(self.loop) + test_utils.run_briefly(self.loop) + mock_handler.assert_not_called() + def test_shield_cancel_outer_in_task(self): inner = self.new_future(self.loop) diff --git a/Misc/NEWS.d/next/Library/2026-08-28-17-15-00.gh-issue-156321.mNOuMG.rst b/Misc/NEWS.d/next/Library/2026-08-28-17-15-00.gh-issue-156321.mNOuMG.rst new file mode 100644 index 000000000000000..05f3fa5d6732d59 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-08-28-17-15-00.gh-issue-156321.mNOuMG.rst @@ -0,0 +1,2 @@ +Fix :func:`asyncio.shield` reporting an exception that was already +retrieved.