https://github.com/python/cpython/commit/51c32a140aacb4567ce3e235e8cf577fa4decb34
commit: 51c32a140aacb4567ce3e235e8cf577fa4decb34
branch: 3.15
author: Miss Islington (bot) <[email protected]>
committer: asvetlov <[email protected]>
date: 2026-11-22T19:36:24Z
summary:

[3.15] gh-162061: Fix awaited-by links for asyncio.gather() (GH-162394) 
(#162453)

gh-162061: Fix awaited-by links for asyncio.gather() (GH-162394)

* gh-162061: Fix awaited-by links for asyncio.gather()

* Apply suggestions from code review

* Apply suggestions from code review

---------
(cherry picked from commit 0890d65356f87a521dd2bbc26d04efb0fd3e6353)

Co-authored-by: Timofei Ivankov <[email protected]>
Co-authored-by: Andrew Svetlov <[email protected]>

files:
A Misc/NEWS.d/next/Library/2026-11-21-13-50-09.gh-issue-162061.UbvZxJ.rst
M Lib/asyncio/tasks.py
M Lib/test/test_asyncio/test_graph.py
M Lib/test/test_external_inspection.py

diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py
index 12d92032b5c92b..78e39854427c07 100644
--- a/Lib/asyncio/tasks.py
+++ b/Lib/asyncio/tasks.py
@@ -836,17 +836,12 @@ def gather(*coros_or_futures, return_exceptions=False):
         return outer
 
     loop = events._get_running_loop()
-    if loop is not None:
-        cur_task = current_task(loop)
-    else:
-        cur_task = None
 
-    def _done_callback(fut, cur_task=cur_task):
+    def _done_callback(fut):
         nonlocal nfinished
         nfinished += 1
 
-        if cur_task is not None:
-            futures.future_discard_from_awaited_by(fut, cur_task)
+        futures.future_discard_from_awaited_by(fut, outer)
 
         if outer is None or outer.done():
             if not fut.cancelled():
@@ -861,13 +856,13 @@ def _done_callback(fut, cur_task=cur_task):
                 # instead of returning it.
                 exc = fut._make_cancelled_error()
                 # gh-157213: children outliving gather() must lose the edge
-                _discard_awaited_by(children, cur_task)
+                _discard_awaited_by(children, outer)
                 outer.set_exception(exc)
                 return
             else:
                 exc = fut.exception()
                 if exc is not None:
-                    _discard_awaited_by(children, cur_task)
+                    _discard_awaited_by(children, outer)
                     outer.set_exception(exc)
                     return
 
@@ -934,10 +929,9 @@ def _done_callback(fut, cur_task=cur_task):
 
     outer = _GatheringFuture(children, loop=loop)
     # Add the awaited-by edges only after all arguments are validated
-    if cur_task is not None and len(done_futs) < nfuts:
-        for fut in arg_to_fut.values():
-            if not fut.done():
-                futures.future_add_to_awaited_by(fut, cur_task)
+    for fut in arg_to_fut.values():
+        if not fut.done():
+            futures.future_add_to_awaited_by(fut, outer)
     # Run done callbacks after GatheringFuture created so any post-processing
     # can be performed at this point
     # optimization: in the special case that *all* futures finished eagerly,
diff --git a/Lib/test/test_asyncio/test_graph.py 
b/Lib/test/test_asyncio/test_graph.py
index 9a2bca3bf04a7c..404df3f9fbafd6 100644
--- a/Lib/test/test_asyncio/test_graph.py
+++ b/Lib/test/test_asyncio/test_graph.py
@@ -1,6 +1,7 @@
 import asyncio
 import io
 import unittest
+from unittest import mock
 
 
 # To prevent a warning "test altered the execution environment"
@@ -198,10 +199,32 @@ async def main():
             'T<anon>',
             ['s capture_test_stack', 'a deep', 'a c1'],
             [
-                ['T<anon>', ['a main', 'a test_stack_gather'], []]
+                ['F', [], [
+                    ['T<anon>', ['a main', 'a test_stack_gather'], []],
+                ]],
             ]
         ])
 
+    async def test_gather_awaited_by_different_task(self):
+        # gh-162061
+        async def consume(fut):
+            await fut
+
+        release = asyncio.Event()
+        child = asyncio.create_task(release.wait())
+        gathered = asyncio.gather(child)
+        consumer = asyncio.create_task(consume(gathered), eager_start=True)
+        graph = asyncio.capture_call_graph(child, limit=0)
+        release.set()
+        await consumer
+        self.assertFalse(asyncio.capture_call_graph(child, limit=0).awaited_by)
+
+        waiter, = graph.awaited_by
+        self.assertIs(waiter.future, gathered)
+        parent, = waiter.awaited_by
+        self.assertIs(parent.future, consumer)
+        self.assertFalse(parent.awaited_by)
+
     async def test_stack_gather_survivor(self):
         # gh-157213: a child that outlives gather() must not be shown as 
awaited
 
@@ -562,6 +585,17 @@ def setUp(self):
         self._Future = asyncio.Future
         asyncio.Future = futures.Future = futures._PyFuture
 
+        # The real _GatheringFuture subclasses the C Future, which the
+        # pure-Python awaited-by helpers ignore.
+        class _PyGatheringFuture(futures._PyFuture):
+            def __init__(self, children, *, loop):
+                super().__init__(loop=loop)
+                self._children = children
+                self._cancel_requested = False
+            cancel = tasks._GatheringFuture.cancel
+        self.enterContext(mock.patch.object(tasks, '_GatheringFuture',
+                                            _PyGatheringFuture))
+
         self._Task = asyncio.Task
         asyncio.Task = tasks.Task = tasks._PyTask
 
diff --git a/Lib/test/test_external_inspection.py 
b/Lib/test/test_external_inspection.py
index 0739c1d331751b..0295623d2f0af2 100644
--- a/Lib/test/test_external_inspection.py
+++ b/Lib/test/test_external_inspection.py
@@ -1342,11 +1342,14 @@ async def main():
                     relationships = self._get_awaited_by_relationships(
                         stack_trace
                     )
+                    future_name, = (node.task_name for node in 
stack_trace[0].awaited_by
+                                    if node.is_future)
                     self.assertEqual(
                         relationships,
                         {
                             "Task-1": set(),
-                            "Task-2": {"Task-1"},
+                            "Task-2": {future_name},
+                            future_name: {"Task-1"},
                         },
                     )
 
@@ -1360,6 +1363,7 @@ async def main():
                         coroutine_stacks,
                         {
                             "Task-1": [((script_name, 21, "main", None),)],
+                            future_name: [()],
                             "Task-2": [
                                 (
                                     (script_name, 11, "deep", None),
@@ -1387,7 +1391,8 @@ async def main():
                         awaited_by_coroutine_stacks,
                         {
                             "Task-1": [],
-                            "Task-2": [
+                            "Task-2": [(future_name, ())],
+                            future_name: [
                                 ("Task-1", ((script_name, 21, "main", None),))
                             ],
                         },
diff --git 
a/Misc/NEWS.d/next/Library/2026-11-21-13-50-09.gh-issue-162061.UbvZxJ.rst 
b/Misc/NEWS.d/next/Library/2026-11-21-13-50-09.gh-issue-162061.UbvZxJ.rst
new file mode 100644
index 00000000000000..db5b2e79b5b2db
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-11-21-13-50-09.gh-issue-162061.UbvZxJ.rst
@@ -0,0 +1,2 @@
+Fix the asyncio call graph to show which task awaits :func:`asyncio.gather`.
+Patch by Timofei Ivankov.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to