diff --git a/Lib/asyncio/taskgroups.py b/Lib/asyncio/taskgroups.py index a431b45a19489d..1fdffcc81a8865 100644 --- a/Lib/asyncio/taskgroups.py +++ b/Lib/asyncio/taskgroups.py @@ -222,6 +222,9 @@ def create_task(self, coro, **kwargs): # the current task too early. gh-128550, gh-128588 self._tasks.add(task) task.add_done_callback(self._on_task_done) + # gh-155418: an eager task can cancel the group before joining _tasks + if self._aborting and not task.done(): + task.cancel() try: return task finally: diff --git a/Lib/test/test_asyncio/test_taskgroups.py b/Lib/test/test_asyncio/test_taskgroups.py index bc246400b83e9b..d32d661d8dce11 100644 --- a/Lib/test/test_asyncio/test_taskgroups.py +++ b/Lib/test/test_asyncio/test_taskgroups.py @@ -1154,6 +1154,20 @@ async def test_taskgroup_cancel_before_create_task(self): with self.assertRaises(RuntimeError): tg.create_task(asyncio.sleep(1)) + async def test_taskgroup_cancel_from_child_before_first_suspension(self): + # gh-155418: an eager task can cancel the group before joining _tasks + done = [] + + async def child(tg): + tg.cancel() + await asyncio.sleep(10) + done.append(True) + + async with asyncio.TaskGroup() as tg: + task = tg.create_task(child(tg)) + self.assertTrue(task.cancelled()) + self.assertEqual(done, []) + async def test_taskgroup_cancel_before_exception(self): async def raise_exc(parent_tg: asyncio.TaskGroup): parent_tg.cancel() diff --git a/Misc/NEWS.d/next/Library/2026-08-09-14-27-23.gh-issue-155418.kCXUIG.rst b/Misc/NEWS.d/next/Library/2026-08-09-14-27-23.gh-issue-155418.kCXUIG.rst new file mode 100644 index 00000000000000..680ebf05bf5887 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-08-09-14-27-23.gh-issue-155418.kCXUIG.rst @@ -0,0 +1,2 @@ +Fix :class:`asyncio.TaskGroup` hang when a task cancels it before +suspending.