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
58 changes: 52 additions & 6 deletions Lib/profiling/sampling/collector.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from abc import ABC, abstractmethod
from collections import Counter

from .constants import (
DEFAULT_LOCATION,
THREAD_STATUS_HAS_GIL,
Expand Down Expand Up @@ -89,11 +91,38 @@ def _find_leaf_tasks(all_task_ids, all_parent_ids):
return all_task_ids - all_parent_ids


def _build_linear_stacks(leaf_task_ids, task_map, child_to_parent):
for leaf_id in leaf_task_ids:
def _find_cycle_dependents(task_map, leaf_task_ids):
# count how many tasks each parent is waiting for
remaining_children = Counter(
parent.task_name
for task_info, _ in task_map.values()
for parent in task_info.awaited_by
)

# here, we separate the leaves from the cyclic tasks and the tasks waiting on them.
# cyclic tasks will never be removed from the counter because they have no end
# (no final point where a task has nothing left to wait for)
leaves = list(leaf_task_ids)
while leaves:
task_info, _ = task_map[leaves.pop()]
for parent in task_info.awaited_by:
parent_id = parent.task_name
remaining_children[parent_id] -= 1
if remaining_children[parent_id] == 0:
del remaining_children[parent_id]
if parent_id in task_map:
leaves.append(parent_id)

return remaining_children.keys()


def _build_linear_stacks(
start_task_ids, task_map, child_to_parent, covered, *, skip_covered=False
):
for start_id in start_task_ids:
frames = []
visited = set()
current_id = leaf_id
visited = covered if skip_covered else set()
current_id = start_id
thread_id = None

while current_id is not None:
Expand Down Expand Up @@ -126,14 +155,31 @@ def _build_linear_stacks(leaf_task_ids, task_map, child_to_parent):
frames.append(FrameInfo(("<task>", None, task_name, None)))
current_id = None

if not skip_covered:
covered.update(visited)
if frames and thread_id is not None:
yield frames, thread_id, leaf_id
yield frames, thread_id, start_id


def iter_async_frames(awaited_info_list):
task_map, child_to_parent, all_task_ids, all_parent_ids = _build_task_graph(awaited_info_list)
leaf_task_ids = _find_leaf_tasks(all_task_ids, all_parent_ids)
yield from _build_linear_stacks(leaf_task_ids, task_map, child_to_parent)
covered = set()
yield from _build_linear_stacks(leaf_task_ids, task_map, child_to_parent, covered)
missed = all_task_ids - covered
if not missed:
return
missed &= _find_cycle_dependents(task_map, leaf_task_ids)
parents = {
child_to_parent[task_id][0] for task_id in missed if task_id in child_to_parent
}
# second pass for situations where we have cycle awaiter, e.g: X->(A->B, B->A)
start_task_ids = missed - parents
yield from _build_linear_stacks(start_task_ids, task_map, child_to_parent, covered)
# third pass for situations where we have cycle and independent task, e.g: X(no awaits) (A->B, B->A)
yield from _build_linear_stacks(
missed, task_map, child_to_parent, covered, skip_covered=True,
)


class Collector(ABC):
Expand Down
37 changes: 23 additions & 14 deletions Lib/test/test_profiling/test_sampling_profiler/test_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
try:
import _remote_debugging # noqa: F401
from profiling.sampling.pstats_collector import PstatsCollector
from profiling.sampling.stack_collector import FlamegraphCollector
from profiling.sampling.stack_collector import CollapsedStackCollector, FlamegraphCollector
from profiling.sampling.sample import sample, sample_live, SampleProfiler
except ImportError:
raise unittest.SkipTest(
Expand Down Expand Up @@ -142,15 +142,8 @@ def test_multiple_leaf_tasks(self):
self.assertEqual(leaf_ids, {10, 20})

def test_cycle_detection(self):
"""Test _build_linear_stacks: cycle detection prevents infinite loops.
Task graph (cyclic dependency):
A (id=1) <---> B (id=2)
Neither task is a leaf (both have parents), so no stacks are produced.
"""
collector = PstatsCollector(sample_interval_usec=1000)
"""Collapsed stacks include a cycle alongside an independent task."""
collector = CollapsedStackCollector(sample_interval_usec=1000)
task_a = MockTaskInfo(
task_id=1,
task_name="A",
Expand All @@ -165,11 +158,27 @@ def test_cycle_detection(self):
awaited_by=[MockCoroInfo(task_name=1, call_stack=[MockFrameInfo("a.py", 15, "a")])]
)

awaited_info_list = [MockAwaitedInfo(thread_id=400, awaited_by=[task_a, task_b])]
stacks = list(collector._iter_async_frames(awaited_info_list))
independent = MockTaskInfo(3, "independent", [])
collector.collect([MockAwaitedInfo(400, [task_a, task_b, independent])])

# No leaves (both have parents), should return empty
self.assertEqual(len(stacks), 0)
names_by_stack = [
sorted(name for _, _, name in frames)
for frames, _ in collector.stack_counter
]
self.assertCountEqual(names_by_stack, [["A", "B", "a", "b"], ["independent"]])

def test_cycle_with_external_waiter(self):
x = MockTaskInfo(32, "X", [])
b = MockTaskInfo(96, "B", [], [MockCoroInfo(64, [])])
for waiters in [(32, 96), (96, 32)]:
with self.subTest(waiters=waiters):
a = MockTaskInfo(64, "A", [], [MockCoroInfo(i, []) for i in waiters])
collector = CollapsedStackCollector(sample_interval_usec=1000)
collector.collect([MockAwaitedInfo(400, [x, a, b])])
stacks = [
[name for _, _, name in frames] for frames, _ in collector.stack_counter
]
self.assertEqual(stacks, [["X", "A (2 parents)", "B"]])

def test_orphaned_parent_reference(self):
"""Test _build_linear_stacks: handles parent ID not in task_map."""
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Include tasks in asyncio await cycles in async-aware stack dumps and profiles.
Patch by Timofei Ivankov.
Loading