Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 12 additions & 3 deletions Lib/asyncio/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ def _build_graph_for_future(
future: futures.Future,
*,
limit: int | None = None,
seen: set[int] | None = None,
) -> FutureCallGraph:
if not isinstance(future, futures.Future):
raise TypeError(
Expand Down Expand Up @@ -68,9 +69,15 @@ def _build_graph_for_future(
else:
break

if future._asyncio_awaited_by:
if seen is None:
seen = set()

# gh-156860: "awaited by" is a DAG, not a tree. Expand each future once
if future._asyncio_awaited_by and id(future) not in seen:
seen.add(id(future))
for parent in future._asyncio_awaited_by:
awaited_by.append(_build_graph_for_future(parent, limit=limit))
awaited_by.append(
_build_graph_for_future(parent, limit=limit, seen=seen))

if limit is not None:
if limit > 0:
Expand Down Expand Up @@ -170,8 +177,10 @@ def capture_call_graph(

awaited_by = []
if future._asyncio_awaited_by:
seen = {id(future)}
for parent in future._asyncio_awaited_by:
awaited_by.append(_build_graph_for_future(parent, limit=limit))
awaited_by.append(
_build_graph_for_future(parent, limit=limit, seen=seen))

if limit is not None:
limit *= -1
Expand Down
36 changes: 36 additions & 0 deletions Lib/test/test_asyncio/test_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,42 @@ async def main():

self.assertTrue(stack_for_fut[1].startswith('* Future(id='))

async def test_build_graph_for_future_expands_dag_once(self):
# gh-156860: a future reachable by several paths is expanded once.
async def waits_for(*deps):
await asyncio.gather(*deps)

fut = asyncio.Future()
layer = [fut]
for _ in range(3):
layer = [asyncio.ensure_future(waits_for(*layer)) for _ in range(2)]
await asyncio.sleep(0)
captured = asyncio.format_call_graph(fut)

fut.set_result(None)
await asyncio.gather(*layer)

self.assertEqual(captured.count('* Task'), 10)

async def test_capture_call_graph_expands_dag_once(self):
# gh-156860
captured = None

async def waits_for(*deps):
await asyncio.gather(*deps)

async def root():
nonlocal captured
await asyncio.sleep(0)
captured = asyncio.format_call_graph()

layer = [asyncio.ensure_future(root())]
for _ in range(3):
layer = [asyncio.ensure_future(waits_for(*layer)) for _ in range(2)]
await asyncio.gather(*layer)

self.assertEqual(captured.count('* Task'), 13)

async def test_capture_call_graph_positive_limit(self):
captured = None

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix exponential growth of :func:`asyncio.print_call_graph` output when
several tasks await the same future.
Loading