Skip to content

Commit 88b5c4a

Browse files
deadlovelllkumaraditya303
authored andcommitted
gh-161083: Fix stale awaited_by nodes on invalid asyncio.gather() arguments (GH-161084)
(cherry picked from commit 9d05428) Co-authored-by: Timofei Ivankov <128279579+deadlovelll@users.noreply.github.com> Co-authored-by: Kumar Aditya <kumaraditya@python.org>
1 parent 8aa5d65 commit 88b5c4a

3 files changed

Lines changed: 19 additions & 2 deletions

File tree

‎Lib/asyncio/tasks.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -924,8 +924,6 @@ def _done_callback(fut, cur_task=cur_task):
924924
if fut.done():
925925
done_futs.append(fut)
926926
else:
927-
if cur_task is not None:
928-
futures.future_add_to_awaited_by(fut, cur_task)
929927
fut.add_done_callback(_done_callback)
930928

931929
else:
@@ -935,6 +933,11 @@ def _done_callback(fut, cur_task=cur_task):
935933
children.append(fut)
936934

937935
outer = _GatheringFuture(children, loop=loop)
936+
# Add the awaited-by edges only after all arguments are validated
937+
if cur_task is not None and len(done_futs) < nfuts:
938+
for fut in arg_to_fut.values():
939+
if not fut.done():
940+
futures.future_add_to_awaited_by(fut, cur_task)
938941
# Run done callbacks after GatheringFuture created so any post-processing
939942
# can be performed at this point
940943
# optimization: in the special case that *all* futures finished eagerly,

‎Lib/test/test_asyncio/test_tasks.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1233,6 +1233,18 @@ async def coro():
12331233

12341234
self.loop.run_until_complete(self.new_task(self.loop, coro()))
12351235

1236+
def test_gather_invalid_arg_does_not_add_awaited_by(self):
1237+
async def coro():
1238+
task = self.new_task(self.loop, asyncio.sleep(0))
1239+
try:
1240+
with self.assertRaises(TypeError):
1241+
asyncio.gather(task, None)
1242+
self.assertFalse(task._asyncio_awaited_by)
1243+
finally:
1244+
await task
1245+
1246+
self.loop.run_until_complete(self.new_task(self.loop, coro()))
1247+
12361248
def test_gather_discards_awaited_by_for_pending(self):
12371249
# gh-157213: a child outliving gather() must lose the awaited-by edge
12381250
async def fail():
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix stale task nodes left by :func:`asyncio.gather` when argument validation
2+
fails. Patch by Timofei Ivankov

0 commit comments

Comments
 (0)