diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 498eec3f31b292b..1c63472aae25a6e 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -268,7 +268,11 @@ def __step(self, exc=None): raise exceptions.InvalidStateError( f'__step(): already done: {self!r}, {exc!r}') if self._must_cancel: - if not isinstance(exc, exceptions.CancelledError): + if not isinstance(exc, (exceptions.CancelledError, + # gh-108549: do not swallow these + # 2 exceptions + SystemExit, KeyboardInterrupt) + ): exc = self._make_cancelled_error() self._must_cancel = False self._fut_waiter = None diff --git a/Lib/test/test_asyncio/test_tasks.py b/Lib/test/test_asyncio/test_tasks.py index 9c111da8c27f162..8d11238fbd4449a 100644 --- a/Lib/test/test_asyncio/test_tasks.py +++ b/Lib/test/test_asyncio/test_tasks.py @@ -1891,6 +1891,25 @@ async def notmuch(): self.loop.run_until_complete(task), 'ko') + def test_step_dont_swallow_systemexit(self): + # gh-108549: do not swallow + # KeybordInterrupt too. + async def sub_task(): + raise SystemExit + + async def gather(): + try: + await asyncio.gather(sub_task(),) + except SystemExit: + pass + + t = self.new_task(self.loop, gather()) + with self.assertRaises(SystemExit): + self.loop.run_until_complete(t) + t.cancel() + self.loop.run_until_complete(t) + self.assertTrue(t.done()) + def test_step_result_future(self): # If coroutine returns future, task waits on this future. diff --git a/Misc/NEWS.d/next/Library/2026-08-24-14-28-47.gh-issue-108549.XZ34WD.rst b/Misc/NEWS.d/next/Library/2026-08-24-14-28-47.gh-issue-108549.XZ34WD.rst new file mode 100644 index 000000000000000..c97425a91921f54 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-08-24-14-28-47.gh-issue-108549.XZ34WD.rst @@ -0,0 +1 @@ +In ``asyncio.Task.__step``, do not cancel the current task when a ``SystemExit`` (or a ``KeyboardInterrupt``) exception was just raised. diff --git a/Modules/_asynciomodule.c b/Modules/_asynciomodule.c index a380f8ac72b32f4..6d808eb71f3c361 100644 --- a/Modules/_asynciomodule.c +++ b/Modules/_asynciomodule.c @@ -3051,8 +3051,13 @@ task_step_impl(asyncio_state *state, TaskObj *task, PyObject *exc) if (task->task_must_cancel) { assert(exc != Py_None); - if (!exc || !PyErr_GivenExceptionMatches(exc, state->asyncio_CancelledError)) { - /* exc was not a CancelledError */ + if (!exc || + (!PyErr_GivenExceptionMatches(exc, state->asyncio_CancelledError) && + !PyErr_GivenExceptionMatches(exc, PyExc_KeyboardInterrupt) && + !PyErr_GivenExceptionMatches(exc, PyExc_SystemExit)) + ) { + /* exc was not a CancelledError, + neither SystemExit or KeyboardInterrupt (see gh-108549 )*/ exc = create_cancelled_error(state, (FutureObj*)task); if (!exc) {