Skip to content

Commit 922413e

Browse files
authored
gh-159645: Fix --async-aware profiles showing event loop frames under tasks (#159679)
1 parent 37b3e08 commit 922413e

3 files changed

Lines changed: 95 additions & 8 deletions

File tree

‎Lib/test/test_external_inspection.py‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import asyncio
2+
import collections.abc
23
import unittest
34
import os
45
import textwrap
@@ -14,6 +15,7 @@
1415
from unittest.mock import ANY
1516
from test.support import (
1617
os_helper,
18+
threading_helper,
1719
SHORT_TIMEOUT,
1820
busy_retry,
1921
requires_gil_enabled,
@@ -763,6 +765,84 @@ async def main():
763765
stacks = self._extract_coroutine_funcnames(asyncio.run(main()))
764766
self.assertEqual(stacks["consumer"], ["consumer"])
765767

768+
@skip_if_not_supported
769+
def test_running_task_stack_between_steps(self):
770+
# gh-159645
771+
traces = []
772+
773+
class Loop(asyncio.SelectorEventLoop):
774+
def call_soon(self, *args, **kwargs):
775+
if asyncio.current_task(self) is not None:
776+
unwinder = RemoteUnwinder(os.getpid())
777+
traces.append(unwinder.get_async_stack_trace())
778+
return super().call_soon(*args, **kwargs)
779+
780+
async def child():
781+
await asyncio.sleep(0)
782+
783+
async def main():
784+
await asyncio.create_task(child(), name="child")
785+
786+
asyncio.run(main(), loop_factory=Loop)
787+
stacks = [list(self._extract_coroutine_funcnames(trace).values())
788+
for trace in traces]
789+
self.assertIn([["__sleep0", "sleep", "child"], ["main"]], stacks)
790+
self.assertIn([[], ["main"]], stacks)
791+
792+
@skip_if_not_supported
793+
def test_running_task_frame_not_in_thread_stack(self):
794+
# gh-159645
795+
ready = threading.Event()
796+
release = threading.Event()
797+
798+
async def child():
799+
ready.set()
800+
release.wait()
801+
await asyncio.sleep(0)
802+
803+
async def main():
804+
loop = asyncio.get_running_loop()
805+
coro = child()
806+
task = asyncio.create_task(coro, name="child")
807+
thread = threading.Thread(target=coro.send, args=(None,))
808+
with threading_helper.start_threads([thread], unlock=release.set):
809+
self.assertTrue(ready.wait(SHORT_TIMEOUT))
810+
self.assertTrue(coro.cr_running)
811+
previous = tasks._swap_current_task(loop, task)
812+
try:
813+
trace = RemoteUnwinder(os.getpid()).get_async_stack_trace()
814+
finally:
815+
tasks._swap_current_task(loop, previous)
816+
await task
817+
return trace
818+
819+
stacks = self._extract_coroutine_funcnames(asyncio.run(main()))
820+
self.assertEqual(stacks["child"], ["child"])
821+
822+
@skip_if_not_supported
823+
def test_running_task_with_non_native_coroutine(self):
824+
# gh-159645
825+
class Wrapper(collections.abc.Coroutine):
826+
def __init__(self, coro):
827+
self._coro = coro
828+
def send(self, value):
829+
return self._coro.send(value)
830+
def throw(self, *args):
831+
return self._coro.throw(*args)
832+
def close(self):
833+
return self._coro.close()
834+
def __await__(self):
835+
return self._coro.__await__()
836+
837+
async def inner():
838+
return RemoteUnwinder(os.getpid()).get_async_stack_trace()
839+
840+
async def main():
841+
return await asyncio.create_task(Wrapper(inner()), name="wrapper")
842+
843+
stacks = self._extract_coroutine_funcnames(asyncio.run(main()))
844+
self.assertEqual(stacks["wrapper"], [])
845+
766846
@skip_if_not_supported
767847
def test_self_trace_with_empty_linetable(self):
768848
def sample():
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix :mod:`profiling.sampling` ``--async-aware`` profiles showing event loop
2+
frames under tasks. Patch by Timofei Ivankov.

‎Modules/_remote_debugging/asyncio.c‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -787,6 +787,10 @@ get_task_frame(RemoteUnwinderObject *unwinder, uintptr_t task_addr, uintptr_t *f
787787
if (get_coro_like_address(unwinder, running_coro_addr, &running_coro_addr) < 0) {
788788
return -1;
789789
}
790+
if (running_coro_addr == 0) {
791+
*frame_addr = 0;
792+
return 0;
793+
}
790794

791795
*frame_addr = running_coro_addr + (uintptr_t)unwinder->debug_offsets.gen_object.gi_iframe;
792796
return 0;
@@ -803,6 +807,7 @@ parse_async_frame_chain(
803807
uintptr_t address_of_thread,
804808
uintptr_t running_task_frame
805809
) {
810+
Py_ssize_t coro_chain_size = PyList_GET_SIZE(calls);
806811
uintptr_t address_of_current_frame;
807812
if (find_running_frame(unwinder, address_of_thread, &address_of_current_frame) < 0) {
808813
set_exception_cause(unwinder, PyExc_RuntimeError, "Running frame search failed in async chain");
@@ -846,11 +851,12 @@ parse_async_frame_chain(
846851
// Stop at the task's own frame. Code objects are shared by
847852
// recursive calls, so they cannot identify it.
848853
if (this_frame == running_task_frame) {
849-
break;
854+
return PyList_SetSlice(calls, 0, coro_chain_size, NULL);
850855
}
851856
}
852857

853-
return 0;
858+
// gh-159645: keep the coroutine chain if the task's frame was not found.
859+
return PyList_SetSlice(calls, coro_chain_size, PY_SSIZE_T_MAX, NULL);
854860
}
855861

856862
/* ============================================================================
@@ -1006,6 +1012,11 @@ process_running_task_chain(
10061012
return -1;
10071013
}
10081014

1015+
// gh-159645: non-native coroutines have no frame to look for.
1016+
if (running_task_frame == 0) {
1017+
return process_task_waiters(unwinder, result, false);
1018+
}
1019+
10091020
// Get the chain from the current frame to this task
10101021
PyObject *coro_chain = PyStructSequence_GET_ITEM(task_info, 2);
10111022
assert(coro_chain != NULL);
@@ -1021,12 +1032,6 @@ process_running_task_chain(
10211032
PyObject *frame_chain = PyStructSequence_GET_ITEM(coro_info, 0);
10221033
assert(frame_chain != NULL);
10231034

1024-
// Clear the coro_chain
1025-
if (PyList_Clear(frame_chain) < 0) {
1026-
set_exception_cause(unwinder, PyExc_RuntimeError, "Failed to clear coroutine chain");
1027-
return -1;
1028-
}
1029-
10301035
// Add the chain from the current frame to this task
10311036
if (parse_async_frame_chain(unwinder, frame_chain, thread_state_addr, running_task_frame) < 0) {
10321037
return -1;

0 commit comments

Comments
 (0)