Skip to content

Commit ee23046

Browse files
authored
gh-155433: Fix TaskGroup losing outside cancellation after cancel() (#155439)
1 parent 5442687 commit ee23046

3 files changed

Lines changed: 28 additions & 0 deletions

File tree

Lib/asyncio/taskgroups.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,13 +116,15 @@ async def _aexit(self, et, exc):
116116
# can be cancelled multiple times if our parent task
117117
# is being cancelled repeatedly (or even once, when
118118
# our own cancellation is already in progress)
119+
pending_cancellation_error = None
119120
while self._tasks:
120121
if self._on_completed_fut is None:
121122
self._on_completed_fut = self._loop.create_future()
122123

123124
try:
124125
await self._on_completed_fut
125126
except exceptions.CancelledError as ex:
127+
pending_cancellation_error = ex
126128
if not self._aborting:
127129
# Our parent task is being cancelled:
128130
#
@@ -163,6 +165,9 @@ async def _aexit(self, et, exc):
163165
# If there are no pending cancellations left,
164166
# don't propagate CancelledError.
165167
propagate_cancellation_error = None
168+
elif propagate_cancellation_error is None:
169+
# gh-155433: the remaining cancellation is not ours, don't drop it
170+
propagate_cancellation_error = pending_cancellation_error
166171

167172
# Propagate CancelledError if there is one, except if there
168173
# are other errors -- those have priority.

Lib/test/test_asyncio/test_taskgroups.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1187,6 +1187,27 @@ async def test_taskgroup_cancel_before_create_task(self):
11871187
with self.assertRaises(RuntimeError):
11881188
tg.create_task(asyncio.sleep(1))
11891189

1190+
async def test_taskgroup_cancel_keeps_outer_cancellation(self):
1191+
# gh-155433: any cancellation from outside the group must propagate.
1192+
async def child():
1193+
try:
1194+
await asyncio.sleep(10)
1195+
finally:
1196+
await asyncio.sleep(0.1)
1197+
1198+
async def body():
1199+
async with asyncio.TaskGroup() as tg:
1200+
tg.create_task(child())
1201+
await asyncio.sleep(0)
1202+
tg.cancel()
1203+
1204+
task = asyncio.create_task(body())
1205+
await asyncio.sleep(0.01)
1206+
task.cancel('message')
1207+
with self.assertRaises(asyncio.CancelledError) as cm:
1208+
await task
1209+
self.assertEqual('message', cm.exception.args[0])
1210+
11901211
async def test_taskgroup_cancel_before_exception(self):
11911212
async def raise_exc(parent_tg: asyncio.TaskGroup):
11921213
parent_tg.cancel()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :class:`asyncio.TaskGroup` losing outside cancellation after
2+
``cancel()``.

0 commit comments

Comments
 (0)