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
2 changes: 1 addition & 1 deletion Lib/asyncio/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def _build_graph_for_future(
coro = coro.cr_await
elif hasattr(coro, 'ag_await'):
# A native async generator or duck-type compatible iterator
st.append(FrameCallGraphEntry(coro.cr_frame))
st.append(FrameCallGraphEntry(coro.ag_frame))
coro = coro.ag_await
else:
break
Expand Down
26 changes: 26 additions & 0 deletions Lib/test/test_asyncio/test_graph.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import asyncio
import io
import sys
import unittest


Expand Down Expand Up @@ -146,6 +147,31 @@ async def main():
'async generator CallStackTestBase.test_stack_async_gen.<locals>.gen()',
stack_for_gen_nested_call[1])

def test_ag_frame_used_for_async_generator(self):
# Regression test for gh-148736: the ag_await branch of
# _build_graph_for_future must read ag_frame, not cr_frame.
from asyncio.graph import _build_graph_for_future

sentinel_frame = sys._getframe()

class FakeAsyncGen:
ag_await = None
ag_frame = sentinel_frame

class FakeCoro:
cr_frame = sentinel_frame
cr_await = FakeAsyncGen()

loop = asyncio.new_event_loop()
try:
fut = loop.create_future()
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you should use a task and a real agen

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair point on the sentinels. Worth flagging: the ag_await branch on line 65 is effectively dead code. async_generator.__anext__() returns an async_generator_asend, which exposes neither cr_await nor ag_await, so the walker hits else: break and never reaches it. A real-async-gen test would pass before and after the patch.

Duck-typed stubs are the only way to drive that branch. Open to closing this if dead-code cleanup isn't worth the churn.

fut.get_coro = lambda: FakeCoro()
result = _build_graph_for_future(fut)
finally:
loop.close()

self.assertEqual(len(result.call_stack), 2)

async def test_stack_gather(self):

stack_for_deep = None
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Fix a latent :exc:`AttributeError` in :mod:`asyncio` call-graph capture when
walking an async generator's ``ag_await`` chain: the walker referenced
``cr_frame`` instead of ``ag_frame``.
Loading