Skip to content

Commit 9fce599

Browse files
committed
gh-128588: gh-128550: remove eager tasks optimization that missed and introduced incorrect cancellations
1 parent 59fcae7 commit 9fce599

File tree

2 files changed

+49
-7
lines changed

2 files changed

+49
-7
lines changed

Lib/asyncio/taskgroups.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -197,14 +197,12 @@ def create_task(self, coro, *, name=None, context=None):
197197
else:
198198
task = self._loop.create_task(coro, name=name, context=context)
199199

200-
# optimization: Immediately call the done callback if the task is
200+
# Always schedule the done callback even if the task is
201201
# already done (e.g. if the coro was able to complete eagerly),
202-
# and skip scheduling a done callback
203-
if task.done():
204-
self._on_task_done(task)
205-
else:
206-
self._tasks.add(task)
207-
task.add_done_callback(self._on_task_done)
202+
# otherwise if the task completes with an exception then it will cancel
203+
# the current task too early. gh-128550, gh-128588
204+
self._tasks.add(task)
205+
task.add_done_callback(self._on_task_done)
208206
try:
209207
return task
210208
finally:

Lib/test/test_asyncio/test_taskgroups.py

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1041,6 +1041,50 @@ class MyKeyboardInterrupt(KeyboardInterrupt):
10411041
self.assertListEqual(gc.get_referrers(exc), no_other_refs())
10421042

10431043

1044+
async def test_cancels_task_if_created_during_creation(self):
1045+
# regression test for gh-128550
1046+
ran = False
1047+
class MyError(Exception):
1048+
pass
1049+
1050+
exc = None
1051+
try:
1052+
async with asyncio.TaskGroup() as tg:
1053+
async def third_task():
1054+
raise MyError("third task failed")
1055+
1056+
async def second_task():
1057+
nonlocal ran
1058+
tg.create_task(third_task())
1059+
with self.assertRaises(asyncio.CancelledError):
1060+
await asyncio.sleep(0) # eager tasks cancel here
1061+
await asyncio.sleep(0) # lazy tasks cancel here
1062+
ran = True
1063+
1064+
tg.create_task(second_task())
1065+
except* MyError as excs:
1066+
exc = excs.exceptions[0]
1067+
1068+
self.assertTrue(ran)
1069+
self.assertIsInstance(exc, MyError)
1070+
1071+
1072+
async def test_cancellation_does_not_leak_out_of_tg(self):
1073+
class MyError(Exception):
1074+
pass
1075+
1076+
async def throw_error():
1077+
raise MyError
1078+
1079+
try:
1080+
async with asyncio.TaskGroup() as tg:
1081+
tg.create_task(throw_error())
1082+
except* MyError:
1083+
pass
1084+
1085+
await asyncio.sleep(0)
1086+
1087+
10441088
class TestTaskGroup(BaseTestTaskGroup, unittest.IsolatedAsyncioTestCase):
10451089
loop_factory = asyncio.EventLoop
10461090

0 commit comments

Comments
 (0)