Skip to content

Commit 679c306

Browse files
asvetlovdeadlovelllclaude
authored
[3.14] gh-162061: Fix awaited-by links for asyncio.gather() (GH-162394) (#162454)
(cherry picked from commit 0890d65) Co-authored-by: Timofei Ivankov <128279579+deadlovelll@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 42df427 commit 679c306

4 files changed

Lines changed: 51 additions & 16 deletions

File tree

‎Lib/asyncio/tasks.py‎

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -836,17 +836,12 @@ def gather(*coros_or_futures, return_exceptions=False):
836836
return outer
837837

838838
loop = events._get_running_loop()
839-
if loop is not None:
840-
cur_task = current_task(loop)
841-
else:
842-
cur_task = None
843839

844-
def _done_callback(fut, cur_task=cur_task):
840+
def _done_callback(fut):
845841
nonlocal nfinished
846842
nfinished += 1
847843

848-
if cur_task is not None:
849-
futures.future_discard_from_awaited_by(fut, cur_task)
844+
futures.future_discard_from_awaited_by(fut, outer)
850845

851846
if outer is None or outer.done():
852847
if not fut.cancelled():
@@ -861,13 +856,13 @@ def _done_callback(fut, cur_task=cur_task):
861856
# instead of returning it.
862857
exc = fut._make_cancelled_error()
863858
# gh-157213: children outliving gather() must lose the edge
864-
_discard_awaited_by(children, cur_task)
859+
_discard_awaited_by(children, outer)
865860
outer.set_exception(exc)
866861
return
867862
else:
868863
exc = fut.exception()
869864
if exc is not None:
870-
_discard_awaited_by(children, cur_task)
865+
_discard_awaited_by(children, outer)
871866
outer.set_exception(exc)
872867
return
873868

@@ -934,10 +929,9 @@ def _done_callback(fut, cur_task=cur_task):
934929

935930
outer = _GatheringFuture(children, loop=loop)
936931
# 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)
932+
for fut in arg_to_fut.values():
933+
if not fut.done():
934+
futures.future_add_to_awaited_by(fut, outer)
941935
# Run done callbacks after GatheringFuture created so any post-processing
942936
# can be performed at this point
943937
# optimization: in the special case that *all* futures finished eagerly,

‎Lib/test/test_asyncio/test_graph.py‎

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import asyncio
22
import io
33
import unittest
4+
from unittest import mock
45

56

67
# To prevent a warning "test altered the execution environment"
@@ -198,10 +199,32 @@ async def main():
198199
'T<anon>',
199200
['s capture_test_stack', 'a deep', 'a c1'],
200201
[
201-
['T<anon>', ['a main', 'a test_stack_gather'], []]
202+
['F', [], [
203+
['T<anon>', ['a main', 'a test_stack_gather'], []],
204+
]],
202205
]
203206
])
204207

208+
async def test_gather_awaited_by_different_task(self):
209+
# gh-162061
210+
async def consume(fut):
211+
await fut
212+
213+
release = asyncio.Event()
214+
child = asyncio.create_task(release.wait())
215+
gathered = asyncio.gather(child)
216+
consumer = asyncio.create_task(consume(gathered), eager_start=True)
217+
graph = asyncio.capture_call_graph(child, limit=0)
218+
release.set()
219+
await consumer
220+
self.assertFalse(asyncio.capture_call_graph(child, limit=0).awaited_by)
221+
222+
waiter, = graph.awaited_by
223+
self.assertIs(waiter.future, gathered)
224+
parent, = waiter.awaited_by
225+
self.assertIs(parent.future, consumer)
226+
self.assertFalse(parent.awaited_by)
227+
205228
async def test_stack_gather_survivor(self):
206229
# gh-157213: a child that outlives gather() must not be shown as awaited
207230

@@ -562,6 +585,17 @@ def setUp(self):
562585
self._Future = asyncio.Future
563586
asyncio.Future = futures.Future = futures._PyFuture
564587

588+
# The real _GatheringFuture subclasses the C Future, which the
589+
# pure-Python awaited-by helpers ignore.
590+
class _PyGatheringFuture(futures._PyFuture):
591+
def __init__(self, children, *, loop):
592+
super().__init__(loop=loop)
593+
self._children = children
594+
self._cancel_requested = False
595+
cancel = tasks._GatheringFuture.cancel
596+
self.enterContext(mock.patch.object(tasks, '_GatheringFuture',
597+
_PyGatheringFuture))
598+
565599
self._Task = asyncio.Task
566600
asyncio.Task = tasks.Task = tasks._PyTask
567601

‎Lib/test/test_external_inspection.py‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -793,6 +793,8 @@ async def main():
793793
]
794794
for task_name in ["Task-1", "Task-2"]:
795795
self.assertIn(task_name, tasks_names)
796+
future_name, = (node.task_name for node in stack_trace[0].awaited_by
797+
if node.is_future)
796798

797799
# Now ensure that the awaited_by_relationships are correct
798800
id_to_task = {
@@ -809,7 +811,8 @@ async def main():
809811
task_name_to_awaited_by,
810812
{
811813
"Task-1": set(),
812-
"Task-2": {"Task-1"},
814+
"Task-2": {future_name},
815+
future_name: {"Task-1"},
813816
},
814817
)
815818

@@ -825,6 +828,7 @@ async def main():
825828
coroutine_stacks,
826829
{
827830
"Task-1": [(tuple([script_name, 21, "main"]),)],
831+
future_name: [()],
828832
"Task-2": [
829833
(
830834
tuple([script_name, 11, "deep"]),
@@ -849,7 +853,8 @@ async def main():
849853
awaited_by_coroutine_stacks,
850854
{
851855
"Task-1": [],
852-
"Task-2": [
856+
"Task-2": [(future_name, ())],
857+
future_name: [
853858
("Task-1", (tuple([script_name, 21, "main"]),))
854859
],
855860
},
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix the asyncio call graph to show which task awaits :func:`asyncio.gather`.
2+
Patch by Timofei Ivankov.

0 commit comments

Comments
 (0)