diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h
index e34cdd6a51f..6dac7458938 100644
--- a/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h
+++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h
@@ -87,7 +87,7 @@ class EchionSampler
bool asyncio_loop_tracked_ = false;
size_t asyncio_task_count_ = 0;
- // Maximum number of frames to collect for plain thread stacks.
+ // Maximum number of frames to collect for thread and task stacks.
size_t stack_max_frames_ = g_default_max_nframes;
// Maximum number of leaf tasks / greenlets to unwind and emit per cycle.
diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h
index d9be0acd6ce..c658f9a722c 100644
--- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h
+++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h
@@ -47,9 +47,15 @@ class FrameStack : public std::vector
public:
using Key = Frame::Key;
- void render(EchionSampler& echion, TruncationStatus truncation);
+ // truncation_index is the index into this FrameStack before which to render the truncation marker.
+ // An index of size() puts the marker after all frames; SIZE_MAX disables it.
+ // truncated_frames is the number of truncated thread frames represented by the marker; zero emits nothing.
+ void render(EchionSampler& echion, TruncationStatus truncation, size_t truncation_index, size_t truncated_frames);
};
+[[nodiscard]] size_t
+rendered_location_count(const Frame& frame);
+
// Forward declaration
class EchionSampler;
@@ -95,6 +101,8 @@ class StackInfo
uint64_t task_id;
bool on_cpu;
FrameStack stack;
+ size_t truncation_index = SIZE_MAX;
+ size_t truncated_frames = 0;
// Per-task override wall-time to use in reservoir sampling.
// nullopt means "use the thread-level wall time"
diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h
index f80201d66c8..f0892515120 100644
--- a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h
+++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h
@@ -145,7 +145,10 @@ class TaskInfo
{
}
- size_t unwind(EchionSampler& echion, FrameStack&, bool using_uvloop);
+ // Append up to max_depth coroutine frames to stack, starting with the innermost coroutine.
+ // Return the discovered coroutine-frame count, including frames not appended because of the limit.
+ // Stitching uses this count to distinguish coroutine frames from synchronous frames in the physical stack.
+ size_t unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop, size_t max_depth);
};
// Checks whether a Frame is the uvloop.run coroutine wrapper.
diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h
index 87053ca6fb3..5c50308c357 100644
--- a/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h
+++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h
@@ -16,6 +16,7 @@
#include
#include
#include
+#include
#include
#if defined PL_LINUX
@@ -59,17 +60,15 @@ class ThreadInfo
uintptr_t asyncio_loop = 0;
uintptr_t tstate_addr = 0; // Remote address of PyThreadState for accessing asyncio_tasks_head
bool using_uvloop = false; // Whether this thread is using uvloop instead of asyncio
+ // Index into python_stack of the event-loop boundary frame.
+ // Empty if no boundary was found in the collected physical frames.
+ std::optional asyncio_boundary_index;
[[nodiscard]] Result update_cpu_time();
[[nodiscard]] Result sample(EchionSampler&, PyThreadState*, microsecond_t);
[[nodiscard]] Result unwind(EchionSampler&, PyThreadState*, microsecond_t wall_time_us);
- // Number of frames in python_stack from the asyncio boundary frame (inclusive) up to the root,
- // that is to say the asyncio machinery plus the synchronous entry point. Returns the size of the
- // whole stack when the boundary frame is not there.
- [[nodiscard]] size_t find_upper_python_stack_size(EchionSampler&) const;
-
// ------------------------------------------------------------------------
#if defined PL_LINUX
ThreadInfo(uintptr_t thread_id, unsigned long native_id, const char* name, clockid_t cpu_clock_id)
@@ -127,6 +126,7 @@ class ThreadInfo
void reset_cycle_state() noexcept;
void render_unwound_stacks(EchionSampler&);
+ bool is_asyncio_boundary_frame(EchionSampler&, const Frame&);
[[nodiscard]] Result unwind_tasks(EchionSampler&, PyThreadState*, microsecond_t wall_time_us);
void unwind_greenlets(EchionSampler&, PyThreadState*, unsigned long, microsecond_t wall_time_us);
[[nodiscard]] Result> get_all_tasks(EchionSampler&, PyThreadState* tstate);
diff --git a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_task_unwind.cpp b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_task_unwind.cpp
index 1f4f817b771..bb57264ce74 100644
--- a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_task_unwind.cpp
+++ b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_task_unwind.cpp
@@ -37,7 +37,7 @@ LLVMFuzzerTestOneInput(const uint8_t* data, size_t size)
// Point gc_frame at the outermost coroutine frame so the GC-marker path is exercised.
PyObject* gc_frame = (*maybe_task)->coro ? (*maybe_task)->coro->frame : nullptr;
auto gc_frame_scope = echion_sampler.use_gc_frame(gc_frame);
- (void)(*maybe_task)->unwind(echion_sampler, stack, using_uvloop);
+ (void)(*maybe_task)->unwind(echion_sampler, stack, using_uvloop, MAX_STACK_UNWIND_SAFETY_LIMIT);
}
g_data = nullptr;
diff --git a/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp b/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp
index 45e3a652aaa..624102ffbcd 100644
--- a/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp
+++ b/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp
@@ -100,6 +100,7 @@ class StackRenderer
std::optional walltime_ns_override = std::nullopt);
void render_frame(Frame& frame);
void mark_truncated();
+ void render_truncated_frames(size_t count);
void render_gc_frame();
void render_cpu_time(microsecond_t cpu_time_us);
void render_native_frame(const std::string& name, const std::string& module);
diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc
index 3901b5cf278..3ffc65afcc7 100644
--- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc
+++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc
@@ -5,14 +5,31 @@
#include "dd_wrapper/include/profiler_state.hpp"
+size_t
+rendered_location_count(const Frame& frame)
+{
+ size_t count = frame.is_in_gc ? 2 : 1;
+ if (frame.code_object == 0 || frame.lasti < 0) {
+ return count;
+ }
+
+ auto& registry = Datadog::ProfilerState::get().native_call_registry;
+ const int offset_bytes = frame.lasti * static_cast(sizeof(_Py_CODEUNIT));
+ return registry.lookup(frame.code_object, offset_bytes, frame.first_lineno) ? count + 1 : count;
+}
+
void
-FrameStack::render(EchionSampler& echion, TruncationStatus truncation)
+FrameStack::render(EchionSampler& echion, TruncationStatus truncation, size_t truncation_index, size_t truncated_frames)
{
auto& renderer = echion.renderer();
auto& registry = Datadog::ProfilerState::get().native_call_registry;
- for (auto it = this->begin(); it != this->end(); ++it) {
- auto& frame = *it;
+ for (size_t i = 0; i < size(); ++i) {
+ if (i == truncation_index) {
+ renderer.render_truncated_frames(truncated_frames);
+ }
+
+ auto& frame = (*this)[i];
// The collection runs underneath everything the frame is doing, including a native call
// such as gc.collect that is still in progress. Locations are leaf-to-root, so the GC
@@ -36,6 +53,9 @@ FrameStack::render(EchionSampler& echion, TruncationStatus truncation)
renderer.render_frame(frame);
}
+ if (truncation_index == size()) {
+ renderer.render_truncated_frames(truncated_frames);
+ }
if (truncation == TruncationStatus::Truncated) {
renderer.mark_truncated();
}
diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc
index fed774a24c3..d666cdf0730 100644
--- a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc
+++ b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc
@@ -229,7 +229,7 @@ is_uvloop_wrapper_frame(EchionSampler& echion, bool using_uvloop, const Frame& f
}
size_t
-TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop)
+TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop, size_t max_depth)
{
// TODO: Check for running task.
(void)echion;
@@ -250,11 +250,11 @@ TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop)
}
}
- // Total number of frames added to the Stack
- size_t count = 0;
+ size_t depth = coro_frames.size();
+ size_t retained = 0;
- // Unwind the coro frames
- while (!coro_frames.empty()) {
+ // Unwind only the frames that can contribute to this task's output.
+ while (!coro_frames.empty() && retained < max_depth) {
PyObject* frame = coro_frames.top();
coro_frames.pop();
@@ -279,11 +279,12 @@ TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop)
// Skip the uvloop wrapper frame if present (only at the outermost level of the top-level Task)
if (!stack.empty() && is_uvloop_wrapper_frame(echion, using_uvloop, stack.back())) {
stack.pop_back();
+ depth--;
continue;
}
- count += 1;
+ retained++;
}
- return count;
+ return depth;
}
diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc
index 25fb6b4b039..50bbd48c5ed 100644
--- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc
+++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc
@@ -12,6 +12,34 @@
#include
#include
+namespace {
+size_t
+select_frame_prefix(const FrameStack& frames, size_t start, size_t count, size_t budget, size_t& locations)
+{
+ size_t selected = 0;
+ while (selected < count) {
+ const size_t frame_locations = rendered_location_count(frames[start + selected]);
+ if (frame_locations > budget - locations) {
+ break;
+ }
+ locations += frame_locations;
+ selected++;
+ }
+ return selected;
+}
+
+// Keep the Python frame when it and its injected locations cannot all fit.
+void
+drop_injected_locations_to_fit(Frame& frame, size_t budget)
+{
+ // Disable native lookup on this sample's copy before dropping the GC marker.
+ frame.code_object = 0;
+ if (budget == 1) {
+ frame.is_in_gc = false;
+ }
+}
+} // namespace
+
void
ThreadInfo::reset_cycle_state() noexcept
{
@@ -25,10 +53,7 @@ ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate, microsecond_t w
// This entry reset is a precondition for a new snapshot: never append to logical state from an earlier cycle.
reset_cycle_state();
- // Asyncio stitching needs the root-side event-loop boundary and overlap
- // metadata, so preserve Echion's existing discovery depth for task-aware
- // stacks. Non-task thread stacks can stop at the configured reporting limit.
- const size_t max_frames = asyncio_loop ? MAX_STACK_UNWIND_SAFETY_LIMIT : echion.stack_max_frames();
+ const size_t max_frames = echion.stack_max_frames();
python_stack_unwind_result = UnwindResult::Unknown();
// Mark before unwinding so a failed stack copy is not reported as a missing tracked loop.
if (asyncio_loop) {
@@ -39,8 +64,17 @@ ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate, microsecond_t w
return frame_unwind_result.error();
}
python_stack_unwind_result = *frame_unwind_result;
+ asyncio_boundary_index.reset();
if (asyncio_loop) {
+ // Look for the boundary only in the bounded physical stack.
+ for (size_t i = 0; i < python_stack.size(); i++) {
+ if (is_asyncio_boundary_frame(echion, python_stack[i])) {
+ asyncio_boundary_index = i;
+ break;
+ }
+ }
+
// unwind_tasks returns a [[nodiscard]] Result.
// We cast it to void to ignore failures.
(void)unwind_tasks(echion, tstate, wall_time_us);
@@ -53,13 +87,9 @@ ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate, microsecond_t w
return Result::ok();
}
-// ----------------------------------------------------------------------------
-size_t
-ThreadInfo::find_upper_python_stack_size(EchionSampler& echion) const
+bool
+ThreadInfo::is_asyncio_boundary_frame(EchionSampler& echion, const Frame& frame)
{
- // Defaults to the full Python stack size (and updated if we find the boundary frame)
- size_t upper_python_stack_size = python_stack.size();
-
// Check if the Python stack contains the asyncio boundary frame.
// For regular asyncio, this is "Handle._run" from asyncio/events.py.
// For uvloop, this is "Runner.run" from asyncio/runners.py (uvloop uses asyncio.Runner internally).
@@ -72,83 +102,62 @@ ThreadInfo::find_upper_python_stack_size(EchionSampler& echion) const
auto& boundary_frame = using_uvloop ? uvloop_boundary_frame : asyncio_boundary_frame;
- for (size_t i = 0; i < python_stack.size(); i++) {
- const auto& frame = python_stack[i];
-
- bool is_boundary_frame = false;
+ if (boundary_frame) {
+ return frame.name == boundary_frame->name && frame.filename == boundary_frame->filename;
+ }
- if (boundary_frame) {
- is_boundary_frame = frame.name == boundary_frame->name && frame.filename == boundary_frame->filename;
- } else {
- auto maybe_frame_name = echion.string_table().lookup(frame.name);
- if (!maybe_frame_name) {
- continue;
- }
- const auto& frame_name = maybe_frame_name->get();
+ auto maybe_frame_name = echion.string_table().lookup(frame.name);
+ if (!maybe_frame_name) {
+ return false;
+ }
+ const auto& frame_name = maybe_frame_name->get();
- if (using_uvloop) {
- // For uvloop, the boundary frame depends on the Python version:
- // - Python 3.11+: Runner.run from asyncio/runners.py (uvloop uses asyncio.Runner)
- // - Python < 3.11: run from uvloop/__init__.py (uvloop has its own implementation)
+ bool is_boundary_frame = false;
+ if (using_uvloop) {
#if PY_VERSION_HEX >= 0x030b0000
- constexpr std::string_view runner_run = "Runner.run";
- is_boundary_frame = frame_name == runner_run;
+ constexpr std::string_view runner_run = "Runner.run";
+ is_boundary_frame = frame_name == runner_run;
#else
- constexpr std::string_view uvloop_init_py = "uvloop/__init__.py";
- constexpr std::string_view run = "run";
- auto maybe_filename = echion.string_table().lookup(frame.filename);
- if (!maybe_filename) {
- continue;
- }
- const auto& filename = maybe_filename->get();
- auto is_uvloop = filename.rfind(uvloop_init_py) == filename.size() - uvloop_init_py.size();
- is_boundary_frame = is_uvloop && (frame_name == run);
+ constexpr std::string_view uvloop_init_py = "uvloop/__init__.py";
+ constexpr std::string_view run = "run";
+ auto maybe_filename = echion.string_table().lookup(frame.filename);
+ if (!maybe_filename) {
+ return false;
+ }
+ const auto& filename = maybe_filename->get();
+ auto is_uvloop = filename.size() >= uvloop_init_py.size() &&
+ filename.rfind(uvloop_init_py) == filename.size() - uvloop_init_py.size();
+ is_boundary_frame = is_uvloop && frame_name == run;
#endif
- } else {
- // For regular asyncio, the boundary frame is Handle._run from asyncio/events.py
+ } else {
#if PY_VERSION_HEX >= 0x030b0000
- // After Python 3.11, function names in Frames are qualified with e.g. the class name, so we
- // can use the qualified name to identify the "_run" Frame.
- constexpr std::string_view _run = "Handle._run";
- is_boundary_frame = frame_name == _run;
+ constexpr std::string_view handle_run = "Handle._run";
+ is_boundary_frame = frame_name == handle_run;
#else
- // Before Python 3.11, function names in Frames are not qualified, so we
- // can use the filename to identify the "_run" Frame.
- constexpr std::string_view asyncio_events_py = "asyncio/events.py";
- constexpr std::string_view _run = "_run";
- auto maybe_filename = echion.string_table().lookup(frame.filename);
- if (!maybe_filename) {
- continue;
- }
- const auto& filename = maybe_filename->get();
- auto is_asyncio = filename.size() >= asyncio_events_py.size() &&
- filename.rfind(asyncio_events_py) == filename.size() - asyncio_events_py.size();
- is_boundary_frame = is_asyncio && (frame_name.size() >= _run.size() &&
- frame_name.rfind(_run) == frame_name.size() - _run.size());
-#endif
- }
-
- if (is_boundary_frame) {
- boundary_frame = BoundaryFrame{ frame.name, frame.filename };
- }
- }
-
- if (is_boundary_frame) {
- upper_python_stack_size = python_stack.size() - i;
- break;
+ constexpr std::string_view asyncio_events_py = "asyncio/events.py";
+ constexpr std::string_view run = "_run";
+ auto maybe_filename = echion.string_table().lookup(frame.filename);
+ if (!maybe_filename) {
+ return false;
}
+ const auto& filename = maybe_filename->get();
+ auto is_asyncio = filename.size() >= asyncio_events_py.size() &&
+ filename.rfind(asyncio_events_py) == filename.size() - asyncio_events_py.size();
+ is_boundary_frame =
+ is_asyncio && frame_name.size() >= run.size() && frame_name.rfind(run) == frame_name.size() - run.size();
+#endif
}
- return upper_python_stack_size;
+ if (is_boundary_frame) {
+ boundary_frame = BoundaryFrame{ frame.name, frame.filename };
+ }
+ return is_boundary_frame;
}
// ----------------------------------------------------------------------------
Result
ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microsecond_t wall_time_us)
{
- // The size of the "pure Python" stack (before asyncio Frames).
- const size_t upper_python_stack_size = find_upper_python_stack_size(echion);
-
std::vector leaf_tasks;
std::unordered_set parent_tasks;
std::unordered_map waitee_map; // Indexed by task origin
@@ -214,15 +223,22 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco
}
}
- // Pre-compute per-task coroutine stacks so that each task's coroutine chain is walked exactly once.
- // Without this, a parent task's coroutine chain would be walked once for each child task that
- // references it in its task chain (e.g. 10 children from asyncio.gather = 10 redundant unwinds
- // of the parent's coroutine chain).
- std::unordered_map task_coro_stacks;
+ // Pre-compute at most max_frames coroutine frames per task. Task linkage and
+ // coroutine depth remain available as metadata, but frames that cannot be
+ // reported are not materialized.
+ struct CachedTaskStack
+ {
+ FrameStack frames;
+ size_t depth = 0;
+ };
+ const size_t max_frames = echion.stack_max_frames();
+ const bool physical_context_unknown =
+ !asyncio_boundary_index && python_stack_unwind_result.truncation == TruncationStatus::Truncated;
+ std::unordered_map task_coro_stacks;
for (auto& task : all_tasks) {
- FrameStack task_stack;
- task->unwind(echion, task_stack, using_uvloop);
- task_coro_stacks.emplace(task->origin, std::move(task_stack));
+ CachedTaskStack cached;
+ cached.depth = task->unwind(echion, cached.frames, using_uvloop, max_frames);
+ task_coro_stacks.emplace(task->origin, std::move(cached));
}
// Swap the on-CPU task to slot 0 so it is always retained by reservoir sampling.
@@ -279,90 +295,56 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco
// Must match _task.task_object_address() so lock and stack samples correlate.
auto task_id = reinterpret_cast(leaf_task.get().origin);
auto stack_info = std::make_unique(leaf_task.get().name, leaf_task.get().is_on_cpu, task_id);
- auto& stack = stack_info->stack;
if (leaf_task_idx > 0) {
stack_info->walltime_ns = scaled_walltime_ns;
}
++leaf_task_idx;
- // Safety: prevent infinite loops from cycles in task chain maps
+ FrameStack task_frames;
+ size_t on_cpu_task_depth = 0;
+ std::optional on_cpu_task_start;
+
+ // Safety: prevent infinite loops from cycles in task chain maps.
size_t task_chain_depth = 0;
- for (auto current_task = leaf_task;;) {
+ for (auto current_task = leaf_task; task_frames.size() < max_frames;) {
if (++task_chain_depth > MAX_RECURSION_DEPTH) {
break;
}
auto& task = current_task.get();
-
// Only the emitted leaf task can own the GC marker. Every other task in the chain is
- // context for that leaf, and must not make a suspended leaf look like the collection
- // ran in it.
+ // context for that leaf, and must not make a suspended leaf look like the collection ran in it.
const bool leaf_owns_gc_marker = task_chain_depth == 1 && stack_info->on_cpu;
- // Look up the pre-computed coroutine stack for this task.
- // FrameStack order is leaf-to-root. For on-CPU tasks, synchronous frames from
- // python_stack must be appended before coroutine frames.
- // Decide how many coroutine frames to keep before appending the on-CPU sync frames below.
- // This preserves the previous task-stack truncation behavior while avoiding front insertion.
- const FrameStack* task_stack = nullptr;
- size_t task_stack_size = 0;
- size_t task_frames_to_push = 0;
if (auto it = task_coro_stacks.find(task.origin); it != task_coro_stacks.end()) {
- task_stack = &it->second;
- task_stack_size = task_stack->size();
- if (stack.size() < MAX_STACK_UNWIND_SAFETY_LIMIT) {
- task_frames_to_push = std::min(task_stack_size, MAX_STACK_UNWIND_SAFETY_LIMIT - stack.size());
- }
- }
- if (task.is_on_cpu) {
- // Get the "bottom" part of the Python synchronous Stack, that is to say the
- // synchronous functions and coroutines called by the Task's outermost coroutine
- // The number of Frames to push is the total number of Frames in the Python stack, from which we
- // subtract the number of Frames in the "upper Python stack" (asyncio machinery + sync entrypoint)
- // This gives us [outermost coroutine, ... , innermost coroutine, outermost sync function, ... ,
- // innermost sync function]
- // TODO: This may be incorrect if the Task that we know is on CPU does not match the Task that
- // actually was on CPU when the Python Thread Stack was captured. One way to work around this
- // may be to look at every Task Stack and match it against the Thread Stack. This would be
- // somewhat costly though, and so far I have not seen a single instance of this race condition.
- size_t frames_to_push = (python_stack.size() > upper_python_stack_size + task_stack_size)
- ? python_stack.size() - upper_python_stack_size - task_stack_size
- : 0;
- // These frames should render before the coroutine frames. Append them first in leaf-to-root order.
- for (size_t i = 0; i < frames_to_push; i++) {
- auto python_frame = python_stack[i];
-
- // Skip the uvloop wrapper frame if present in the Python stack
- if (is_uvloop_wrapper_frame(echion, using_uvloop, python_frame)) {
- continue;
+ const auto& cached = it->second;
+ const size_t first_added = task_frames.size();
+ const size_t frames_to_push = std::min(cached.frames.size(), max_frames - first_added);
+ task_frames.insert(task_frames.end(),
+ cached.frames.begin(),
+ cached.frames.begin() + static_cast(frames_to_push));
+ if (!leaf_owns_gc_marker) {
+ for (size_t i = first_added; i < task_frames.size(); ++i) {
+ task_frames[i].is_in_gc = false;
}
- if (!leaf_owns_gc_marker) {
- python_frame.is_in_gc = false;
- }
- stack.push_back(python_frame);
}
- }
- if (task_stack != nullptr) {
- for (size_t i = 0; i < task_frames_to_push; i++) {
- auto task_frame = (*task_stack)[i];
- if (!leaf_owns_gc_marker) {
- task_frame.is_in_gc = false;
- }
- stack.push_back(task_frame);
+ if (task.is_on_cpu) {
+ on_cpu_task_start = first_added;
+ on_cpu_task_depth = cached.depth;
}
}
- // Task labels are rendered separately from frames; do not add a synthetic
- // frame for the task name here.
+ if (task_frames.size() >= max_frames) {
+ break;
+ }
- // Get the next task in the chain
PyObject* task_origin = task.origin;
if (auto maybe_waitee = waitee_map.find(task_origin); maybe_waitee != waitee_map.end()) {
current_task = maybe_waitee->second;
continue;
}
+ bool found_parent = false;
{
- // Check for, e.g., gather links
std::lock_guard lock(echion.task_link_map_lock());
auto& task_link_map = echion.task_link_map();
auto& weak_task_link_map = echion.weak_task_link_map();
@@ -370,41 +352,167 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco
if (auto maybe_parent = task_link_map.find(task_origin); maybe_parent != task_link_map.end()) {
if (auto maybe_origin = origin_map.find(maybe_parent->second); maybe_origin != origin_map.end()) {
current_task = maybe_origin->second;
- continue;
+ found_parent = true;
}
}
- // Check for weak links
- if (weak_task_link_map.find(task_origin) != weak_task_link_map.end() &&
- origin_map.find(weak_task_link_map[task_origin]) != origin_map.end()) {
- current_task = origin_map.find(weak_task_link_map[task_origin])->second;
- continue;
+ if (!found_parent) {
+ auto weak_parent = weak_task_link_map.find(task_origin);
+ if (weak_parent != weak_task_link_map.end()) {
+ if (auto maybe_origin = origin_map.find(weak_parent->second);
+ maybe_origin != origin_map.end()) {
+ current_task = maybe_origin->second;
+ found_parent = true;
+ }
+ }
}
}
- break;
+ if (!found_parent) {
+ break;
+ }
}
- // Finish off with the remaining thread stack
- // If we have seen an on-CPU Task, then upper_python_stack_size will be set and will include the sync entry
- // point and the asyncio machinery Frames. Otherwise, we are in `select` (idle) and we should push all the
- // Frames.
-
- // There could be a race condition where relevant partial Python Thread Stack ends up being different from the
- // one we saw in TaskInfo::unwind. This is extremely unlikely, I believe, but failing to account for it would
- // cause an underflow, so let's be conservative.
- size_t start_index = 0;
- if (python_stack.size() >= upper_python_stack_size) {
- start_index = python_stack.size() - upper_python_stack_size;
+ // NOTE: Task candidates are selected before physical candidates,
+ // but rendered in logical leaf-to-root order below. Keep budgeting and
+ // output ordering separate when changing this stitching policy.
+ // Apply the configured limit to rendered locations, including injected native and GC locations.
+ const bool task_collection_full = task_frames.size() >= max_frames;
+ size_t task_locations = 0;
+ size_t task_to_keep = select_frame_prefix(task_frames, 0, task_frames.size(), max_frames, task_locations);
+ if (task_to_keep == 0 && !task_frames.empty()) {
+ drop_injected_locations_to_fit(task_frames.front(), max_frames);
+ task_to_keep = 1;
+ task_locations = rendered_location_count(task_frames.front());
}
- for (size_t i = start_index; i < python_stack.size(); i++) {
- auto python_frame = python_stack[i];
- if (!stack_info->on_cpu) {
- python_frame.is_in_gc = false;
+ const bool task_truncated = task_collection_full || task_to_keep < task_frames.size();
+ task_frames.erase(task_frames.begin() + static_cast(task_to_keep),
+ task_frames.end());
+
+ // Task frames receive the reporting budget first. If capacity remains,
+ // fill it with physical context. Synchronous leaf frames go just before
+ // the running task's frames, after any suspended descendants. They have
+ // priority over event-loop roots.
+ auto& stack = stack_info->stack;
+ if (task_truncated || task_locations == max_frames || physical_context_unknown ||
+ (on_cpu_task_start && !asyncio_boundary_index)) {
+ stack = std::move(task_frames);
+ if (physical_context_unknown && using_uvloop && stack_info->on_cpu && stack.empty()) {
+ // The uvloop wrapper can leave a running task with no coroutine frames.
+ // Use only its own physical leaf frames rather than emit an empty task stack.
+ size_t locations = 0;
+ for (const auto& frame : python_stack) {
+ if (is_uvloop_wrapper_frame(echion, using_uvloop, frame)) {
+ continue;
+ }
+ const size_t frame_locations = rendered_location_count(frame);
+ if (frame_locations > max_frames - locations) {
+ if (stack.empty()) {
+ stack.push_back(frame);
+ drop_injected_locations_to_fit(stack.back(), max_frames);
+ }
+ break;
+ }
+ stack.push_back(frame);
+ locations += frame_locations;
+ if (locations == max_frames) {
+ break;
+ }
+ }
+ if (stack.empty()) {
+ continue; // The bounded prefix contained only the wrapper.
+ }
+ }
+ } else {
+ size_t locations = task_locations;
+
+ if (on_cpu_task_start && asyncio_boundary_index) {
+ const size_t leaf_depth =
+ *asyncio_boundary_index > on_cpu_task_depth ? *asyncio_boundary_index - on_cpu_task_depth : 0;
+ const size_t runtime_start = *asyncio_boundary_index;
+ const size_t runtime_available = python_stack.size() - runtime_start;
+
+ const auto on_cpu_begin =
+ task_frames.begin() + static_cast(*on_cpu_task_start);
+ stack.insert(stack.end(), task_frames.begin(), on_cpu_begin);
+ const size_t leaf_start = stack.size();
+ size_t leaf_dropped = 0;
+ for (size_t i = 0; i < leaf_depth; ++i) {
+ const auto& frame = python_stack[i];
+ if (using_uvloop && is_uvloop_wrapper_frame(echion, using_uvloop, frame)) {
+ continue;
+ }
+ if (leaf_dropped == 0) {
+ const size_t frame_locations = rendered_location_count(frame);
+ if (frame_locations <= max_frames - locations) {
+ locations += frame_locations;
+ stack.push_back(frame);
+ continue;
+ }
+ if (!using_uvloop) {
+ leaf_dropped = leaf_depth - i;
+ break;
+ }
+ }
+ ++leaf_dropped;
+ }
+ size_t runtime_to_keep =
+ select_frame_prefix(python_stack, runtime_start, runtime_available, max_frames, locations);
+
+ // A truncation marker consumes one location. Remove the
+ // lowest-priority selected physical frame if the real locations
+ // have already filled the budget.
+ if ((leaf_dropped > 0 || runtime_available > runtime_to_keep) && locations >= max_frames) {
+ if (runtime_to_keep > 0) {
+ runtime_to_keep--;
+ } else if (stack.size() > leaf_start) {
+ stack.pop_back();
+ ++leaf_dropped;
+ }
+ }
+
+ if (leaf_dropped > 0) {
+ stack_info->truncation_index = stack.size();
+ stack_info->truncated_frames = leaf_dropped;
+ }
+ stack.insert(stack.end(), on_cpu_begin, task_frames.end());
+ const auto runtime_begin =
+ python_stack.begin() + static_cast(runtime_start);
+ stack.insert(stack.end(),
+ runtime_begin,
+ runtime_begin + static_cast(runtime_to_keep));
+ if (leaf_dropped == 0 && runtime_available > runtime_to_keep) {
+ stack_info->truncation_index = stack.size();
+ stack_info->truncated_frames = runtime_available - runtime_to_keep;
+ }
+ } else {
+ // Skip frames from any running task that is not part of this task's chain.
+ const size_t runtime_start = asyncio_boundary_index.value_or(0);
+ const size_t runtime_available = python_stack.size() - runtime_start;
+ size_t sync_to_keep =
+ select_frame_prefix(python_stack, runtime_start, runtime_available, max_frames, locations);
+ const bool sync_truncated = runtime_available > sync_to_keep;
+ if (sync_truncated && locations >= max_frames && sync_to_keep > 0) {
+ sync_to_keep--;
+ }
+
+ stack = std::move(task_frames);
+ const auto runtime_begin =
+ python_stack.begin() + static_cast(runtime_start);
+ stack.insert(
+ stack.end(), runtime_begin, runtime_begin + static_cast(sync_to_keep));
+ if (sync_truncated) {
+ stack_info->truncation_index = stack.size();
+ stack_info->truncated_frames = runtime_available - sync_to_keep;
+ }
}
- stack.push_back(python_frame);
}
+ if (!stack_info->on_cpu) {
+ for (auto& frame : stack_info->stack) {
+ frame.is_in_gc = false;
+ }
+ }
current_tasks.push_back(std::move(stack_info));
}
@@ -869,7 +977,8 @@ ThreadInfo::render_unwound_stacks(EchionSampler& echion)
task_name, task_stack_info->on_cpu, task_stack_info->task_id, task_stack_info->walltime_ns);
});
- task_stack_info->stack.render(echion, TruncationStatus::Unknown);
+ task_stack_info->stack.render(
+ echion, TruncationStatus::Unknown, task_stack_info->truncation_index, task_stack_info->truncated_frames);
renderer.render_stack_end();
}
@@ -881,12 +990,12 @@ ThreadInfo::render_unwound_stacks(EchionSampler& echion)
});
auto& stack = greenlet_stack->stack;
- stack.render(echion, TruncationStatus::Unknown);
+ stack.render(echion, TruncationStatus::Unknown, SIZE_MAX, 0);
renderer.render_stack_end();
}
} else {
- python_stack.render(echion, python_stack_unwind_result.truncation);
+ python_stack.render(echion, python_stack_unwind_result.truncation, SIZE_MAX, 0);
renderer.render_stack_end();
}
}
diff --git a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp
index 06bf8fa49dc..280fb80925b 100644
--- a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp
+++ b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp
@@ -220,6 +220,17 @@ StackRenderer::mark_truncated()
}
}
+void
+StackRenderer::render_truncated_frames(size_t count)
+{
+ if (sample == nullptr || count == 0) {
+ return;
+ }
+
+ const std::string name = "<" + std::to_string(count) + " frame" + (count == 1 ? "" : "s") + " truncated>";
+ sample->push_frame(name, "", 0, 0);
+}
+
void
StackRenderer::render_gc_frame()
{
diff --git a/releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml b/releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml
new file mode 100644
index 00000000000..6cad21f3011
--- /dev/null
+++ b/releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml
@@ -0,0 +1,4 @@
+---
+fixes:
+ - |
+ profiling: Applies ``DD_PROFILING_MAX_FRAMES`` to asyncio task stacks, reducing profiler CPU and memory overhead.
diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py
new file mode 100644
index 00000000000..0bfd3c8d2a1
--- /dev/null
+++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py
@@ -0,0 +1,407 @@
+from importlib.util import find_spec
+import sys
+
+import pytest
+
+
+@pytest.mark.subprocess(
+ env={
+ "DD_PROFILING_MAX_FRAMES": "4",
+ "DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_task_frame_budget",
+ },
+ err=None,
+)
+def test_task_frames_take_priority_when_the_budget_is_full() -> None:
+ import asyncio
+ import os
+ import time
+
+ from ddtrace.internal.datadog.profiling import stack
+ from ddtrace.profiling import profiler
+ from tests.profiling.collector import pprof_utils
+ from tests.profiling.collector.test_utils import async_run
+
+ assert stack.is_available, stack.failure_msg
+
+ def sync_code() -> None:
+ deadline = time.time() + 1
+ while time.time() < deadline:
+ pass
+
+ async def inner3() -> None:
+ sync_code()
+
+ async def inner2() -> None:
+ await inner3()
+
+ async def inner1() -> None:
+ await asyncio.create_task(inner2())
+
+ async def outer() -> None:
+ await inner1()
+
+ async def async_main() -> None:
+ await outer()
+
+ p = profiler.Profiler()
+ p.start()
+ async_run(async_main())
+ p.stop()
+
+ output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
+ profile = pprof_utils.parse_newest_profile(output_filename)
+
+ actual = []
+ for sample in pprof_utils.get_samples_with_label_key(profile, "task name"):
+ label = pprof_utils.get_label_with_key(profile.string_table, sample, "task name")
+ if label is not None and profile.string_table[label.str] == "Task-2":
+ actual.append(
+ [
+ pprof_utils.get_location_from_id(profile, location_id).function_name
+ for location_id in sample.location_id
+ ]
+ )
+
+ expected = ["inner2", "inner1", "outer", "async_main"]
+ assert expected in actual, actual
+
+
+@pytest.mark.subprocess(
+ env={
+ "DD_PROFILING_MAX_FRAMES": "4",
+ "DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_deep_sync_frame_budget",
+ },
+ err=None,
+)
+def test_deep_sync_stack_does_not_hide_task_context() -> None:
+ import asyncio
+ import os
+ import time
+
+ from ddtrace.internal.datadog.profiling import stack
+ from ddtrace.profiling import profiler
+ from tests.profiling.collector import pprof_utils
+ from tests.profiling.collector.test_utils import async_run
+
+ assert stack.is_available, stack.failure_msg
+
+ def deep_sync(depth: int) -> None:
+ if depth > 0:
+ deep_sync(depth - 1)
+ return
+
+ deadline = time.time() + 1
+ while time.time() < deadline:
+ pass
+
+ async def deep_task() -> None:
+ deep_sync(20)
+
+ async def async_main() -> None:
+ await asyncio.create_task(deep_task())
+
+ p = profiler.Profiler()
+ p.start()
+ async_run(async_main())
+ p.stop()
+
+ output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
+ profile = pprof_utils.parse_newest_profile(output_filename)
+
+ actual = [
+ [pprof_utils.get_location_from_id(profile, location_id).function_name for location_id in sample.location_id]
+ for sample in pprof_utils.get_samples_with_label_key(profile, "task name")
+ ]
+
+ assert any("deep_task" in names for names in actual), actual
+
+
+@pytest.mark.subprocess(
+ env={
+ "DD_PROFILING_MAX_FRAMES": "8",
+ "DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_mixed_frame_budget",
+ },
+ err=None,
+)
+def test_task_stack_uses_remaining_budget_for_sync_context() -> None:
+ import asyncio
+ import os
+ import re
+ import time
+
+ from ddtrace.internal.datadog.profiling import stack
+ from ddtrace.profiling import profiler
+ from tests.profiling.collector import pprof_utils
+ from tests.profiling.collector.test_utils import async_run
+
+ assert stack.is_available, stack.failure_msg
+
+ def sync_code() -> None:
+ deadline = time.time() + 1
+ while time.time() < deadline:
+ pass
+
+ async def inner3() -> None:
+ sync_code()
+
+ async def inner2() -> None:
+ await inner3()
+
+ async def inner1() -> None:
+ await asyncio.create_task(inner2())
+
+ async def outer() -> None:
+ await inner1()
+
+ async def async_main() -> None:
+ await outer()
+
+ p = profiler.Profiler()
+ p.start()
+ async_run(async_main())
+ p.stop()
+
+ output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
+ profile = pprof_utils.parse_newest_profile(output_filename)
+
+ actual = []
+ for sample in pprof_utils.get_samples_with_label_key(profile, "task name"):
+ label = pprof_utils.get_label_with_key(profile.string_table, sample, "task name")
+ if label is not None and profile.string_table[label.str] == "Task-2":
+ actual.append(
+ [
+ pprof_utils.get_location_from_id(profile, location_id).function_name
+ for location_id in sample.location_id
+ ]
+ )
+
+ assert any(
+ len(names) <= 8 and "sync_code" in names and re.fullmatch(r"<[1-9][0-9]* frames? truncated>", names[-1])
+ for names in actual
+ ), actual
+
+
+@pytest.mark.subprocess(
+ env={"DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_collection_frame_limit"},
+ err=None,
+)
+def test_asyncio_collection_honors_frame_limit() -> None:
+ import asyncio
+ import os
+ import time
+
+ from ddtrace.internal.datadog.profiling import ddup
+ from ddtrace.internal.datadog.profiling.stack import _stack
+ from ddtrace.profiling.collector import stack
+ from tests.profiling.collector import pprof_utils
+
+ pprof_prefix = os.environ["DD_PROFILING_OUTPUT_PPROF"]
+ ddup.config(env="test", service="test", version="0.0.0", max_nframes=64, output_filename=pprof_prefix)
+ ddup.start()
+ ddup.upload()
+
+ def sync_leaf() -> None:
+ time.sleep(0.5)
+
+ async def inner() -> None:
+ sync_leaf()
+
+ async def outer() -> None:
+ await inner()
+
+ with stack.StackCollector(nframes=1):
+ assert _stack._get_frame_limits() == (1, 1024)
+ asyncio.run(outer())
+
+ ddup.upload()
+ profile = pprof_utils.parse_newest_profile(pprof_prefix + "." + str(os.getpid()))
+ samples = pprof_utils.get_samples_with_label_key(profile, "task name")
+ pprof_utils.assert_profile_has_sample(
+ profile,
+ samples,
+ expected_sample=pprof_utils.StackEvent(
+ thread_name="MainThread",
+ locations=[pprof_utils.StackLocation(function_name="outer", filename="", line_no=-1)],
+ ),
+ print_samples_on_failure=True,
+ )
+
+
+@pytest.mark.subprocess(
+ env={"DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_running_parent"},
+ err=None,
+)
+def test_running_parent_sync_frames_follow_suspended_child_frames() -> None:
+ import asyncio
+ import os
+ import sys
+ import time
+
+ from tests.profiling.collector import pprof_utils
+ from tests.profiling.collector.test_utils import ProfilerContextManager
+
+ def parent_sync() -> None:
+ time.sleep(1)
+
+ async def child(ready: asyncio.Event, done: asyncio.Event) -> None:
+ ready.set()
+ await done.wait()
+
+ async def parent() -> None:
+ ready = asyncio.Event()
+ done = asyncio.Event()
+ task = asyncio.create_task(child(ready, done), name="suspended_child")
+ await ready.wait()
+ parent_sync()
+ done.set()
+ await task
+
+ with ProfilerContextManager():
+ asyncio.run(parent())
+
+ output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
+ profile = pprof_utils.parse_newest_profile(output_filename)
+ samples = pprof_utils.get_samples_with_label_key(profile, "task name")
+ child_stacks = []
+ for sample in pprof_utils.get_samples_with_function(profile, samples, "parent_sync"):
+ label = pprof_utils.get_label_with_key(profile.string_table, sample, "task name")
+ if label is not None and profile.string_table[label.str] == "suspended_child":
+ locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id]
+ child_stacks.append([loc.function_name for loc in locations if loc.filename != ""])
+
+ assert child_stacks
+ wait_name = "Event.wait" if sys.version_info >= (3, 11) else "wait"
+ assert all(names[:4] == [wait_name, "child", "parent_sync", "parent"] for names in child_stacks), child_stacks
+
+
+@pytest.mark.skipif(find_spec("uvloop") is None, reason="uvloop is not installed in this environment")
+@pytest.mark.subprocess(
+ env={"DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_uvloop_missing_boundary"},
+ parametrize={"DD_PROFILING_MAX_FRAMES": ["1", "3"], "DD_PROFILING_STACK_NATIVE_FRAMES": ["true", "false"]},
+ err=None,
+)
+def test_uvloop_keeps_physical_leaf_when_boundary_is_missing() -> None:
+ import asyncio
+ import os
+ import time
+
+ import uvloop
+
+ from tests.profiling.collector import pprof_utils
+ from tests.profiling.collector.test_utils import ProfilerContextManager
+
+ def sync_leaf() -> None:
+ time.sleep(1)
+
+ async def main() -> None:
+ task = asyncio.current_task()
+ assert task is not None
+ task.set_name("uvloop_main")
+ sync_leaf()
+
+ with ProfilerContextManager():
+ uvloop.run(main())
+
+ output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
+ profile = pprof_utils.parse_newest_profile(output_filename)
+ max_frames = int(os.environ["DD_PROFILING_MAX_FRAMES"])
+ stacks = set()
+ for sample in pprof_utils.get_samples_with_label_key(profile, "task name"):
+ label = pprof_utils.get_label_with_key(profile.string_table, sample, "task name")
+ if label is not None and profile.string_table[label.str] == "uvloop_main":
+ stacks.add(
+ tuple(
+ pprof_utils.get_location_from_id(profile, location_id).function_name
+ for location_id in sample.location_id
+ )
+ )
+
+ assert stacks
+ assert all(0 < len(names) <= max_frames for names in stacks), stacks
+ assert not any({"wrapper", "run..wrapper"}.intersection(names) for names in stacks), stacks
+ assert any("sync_leaf" in names for names in stacks), stacks
+
+
+@pytest.mark.skipif(sys.version_info < (3, 12), reason="Native C frame tracking requires Python 3.12+")
+@pytest.mark.subprocess(
+ env={
+ "DD_PROFILING_MAX_FRAMES": "1",
+ "DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_native_call_frame_budget",
+ "DD_PROFILING_STACK_NATIVE_FRAMES": "true",
+ },
+ err=None,
+)
+def test_one_frame_budget_keeps_coroutine_calling_native_code() -> None:
+ import asyncio
+ import os
+ import time
+
+ from tests.profiling.collector import pprof_utils
+ from tests.profiling.collector.test_utils import ProfilerContextManager
+
+ async def native_call() -> None:
+ time.sleep(1)
+
+ async def main() -> None:
+ await asyncio.create_task(native_call(), name="native_call")
+
+ with ProfilerContextManager():
+ asyncio.run(main())
+
+ output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
+ profile = pprof_utils.parse_newest_profile(output_filename)
+ stacks = set()
+ for sample in pprof_utils.get_samples_with_label_key(profile, "task name"):
+ label = pprof_utils.get_label_with_key(profile.string_table, sample, "task name")
+ if label is not None and profile.string_table[label.str] == "native_call":
+ stacks.add(
+ tuple(
+ pprof_utils.get_location_from_id(profile, location_id).function_name
+ for location_id in sample.location_id
+ )
+ )
+
+ assert stacks == {("native_call",)}, stacks
+
+
+@pytest.mark.skipif(sys.version_info < (3, 12), reason="Native C frame tracking requires Python 3.12+")
+@pytest.mark.subprocess(
+ env={
+ "DD_PROFILING_MAX_FRAMES": "2",
+ "DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_gc_frame_budget",
+ "DD_PROFILING_STACK_GC_ENABLED": "true",
+ "DD_PROFILING_STACK_NATIVE_FRAMES": "true",
+ },
+ err=None,
+)
+def test_two_frame_budget_keeps_collecting_coroutine_and_gc_marker() -> None:
+ import asyncio
+ import gc
+ import os
+
+ from tests.profiling.collector import pprof_utils
+ from tests.profiling.collector.gc_utils import slow_cyclic_collection_coroutine
+ from tests.profiling.collector.test_utils import ProfilerContextManager
+
+ gc.disable()
+
+ with ProfilerContextManager():
+ asyncio.run(slow_cyclic_collection_coroutine())
+
+ output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid())
+ profile = pprof_utils.parse_newest_profile(output_filename)
+ stacks = set()
+ for sample in pprof_utils.get_samples_with_label_key(profile, "task name"):
+ label = pprof_utils.get_label_with_key(profile.string_table, sample, "task name")
+ if label is not None and profile.string_table[label.str] == "Task-1":
+ stacks.add(
+ tuple(
+ pprof_utils.get_location_from_id(profile, location_id).function_name
+ for location_id in sample.location_id
+ )
+ )
+
+ assert () not in stacks, stacks
+ assert all(len(names) <= 2 for names in stacks), stacks
+ gc_stacks = {names for names in stacks if "Garbage collection" in names}
+ assert gc_stacks == {("Garbage collection", "slow_cyclic_collection_coroutine")}, stacks
diff --git a/tests/profiling/collector/test_asyncio_task_stacks.py b/tests/profiling/collector/test_asyncio_task_stacks.py
index ca8f0ad40da..8dc15629513 100644
--- a/tests/profiling/collector/test_asyncio_task_stacks.py
+++ b/tests/profiling/collector/test_asyncio_task_stacks.py
@@ -5,6 +5,7 @@
@pytest.mark.subprocess(
env={"DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_off_cpu_sibling"},
+ parametrize={"DD_PROFILING_MAX_FRAMES": ["64", "6"]},
err=None,
)
def test_suspended_task_does_not_inherit_running_sibling_frames() -> None:
@@ -15,13 +16,15 @@ def test_suspended_task_does_not_inherit_running_sibling_frames() -> None:
from ddtrace.profiling import profiler
from tests.profiling.collector import pprof_utils
- def busy_sync() -> None:
- deadline = time.monotonic() + 1
- while time.monotonic() < deadline:
- pass
+ def busy_sync(depth: int) -> None:
+ if depth:
+ busy_sync(depth - 1)
+ else:
+ time.sleep(1)
async def busy(done: asyncio.Event) -> None:
- busy_sync()
+ # The smaller budget can't reach the event-loop boundary through this stack.
+ busy_sync(20)
done.set()
async def sleeper(done: asyncio.Event) -> None:
@@ -49,7 +52,7 @@ async def main() -> None:
]
)
- assert sleeper_stacks
+ assert any("sleeper" in names for names in sleeper_stacks), sleeper_stacks
leaked = [names for names in sleeper_stacks if {"busy_sync", "busy"}.intersection(names)]
assert not leaked, leaked
diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py
index dbd11b07af1..95bc09efbf8 100644
--- a/tests/profiling/collector/test_stack.py
+++ b/tests/profiling/collector/test_stack.py
@@ -258,9 +258,10 @@ def test_set_max_frames_after_fork_restart() -> None:
env=dict(
DD_PROFILING_OUTPUT_PPROF="/tmp/test_asyncio_native_frame_limit",
),
+ parametrize={"DD_TEST_STACK_MODE": ["plain", "asyncio"]},
err=None,
)
-def test_asyncio_discovery_ignores_plain_stack_limit() -> None:
+def test_stack_collection_preserves_sync_context() -> None:
import asyncio
import os
import time
@@ -270,6 +271,8 @@ def test_asyncio_discovery_ignores_plain_stack_limit() -> None:
from ddtrace.profiling.collector import stack
from tests.profiling.collector import pprof_utils
+ use_asyncio = os.environ["DD_TEST_STACK_MODE"] == "asyncio"
+ nframes = 64 if use_asyncio else 1
pprof_prefix = os.environ["DD_PROFILING_OUTPUT_PPROF"]
ddup.config(
env="test",
@@ -293,50 +296,53 @@ async def inner() -> None:
async def outer() -> None:
await inner()
- with stack.StackCollector(nframes=1):
- assert _stack._get_frame_limits() == (1, 1024)
- sync_outer()
- asyncio.run(outer())
+ with stack.StackCollector(nframes=nframes):
+ assert _stack._get_frame_limits() == (nframes, 1024)
+ if use_asyncio:
+ asyncio.run(outer())
+ else:
+ sync_outer()
ddup.upload()
profile = pprof_utils.parse_newest_profile(pprof_prefix + "." + str(os.getpid()))
- plain_samples = [
- sample
- for sample in pprof_utils.get_samples_with_value_type(profile, "wall-time")
- if pprof_utils.get_label_with_key(profile.string_table, sample, "task name") is None
- ]
- plain_stack_was_bounded = False
- for sample in plain_samples:
- locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id]
- if not any(location.function_name == "sync_leaf" for location in locations):
- continue
- python_locations = [
- location
- for location in locations
- if location.filename != "" and not location.function_name.startswith("<")
+ if not use_asyncio:
+ plain_samples = [
+ sample
+ for sample in pprof_utils.get_samples_with_value_type(profile, "wall-time")
+ if pprof_utils.get_label_with_key(profile.string_table, sample, "task name") is None
]
- plain_stack_was_bounded = len(python_locations) <= 1 and "omitted>" in locations[-1].function_name
- if plain_stack_was_bounded:
- break
-
- assert plain_stack_was_bounded
+ plain_stack_was_bounded = False
+ for sample in plain_samples:
+ locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id]
+ if not any(location.function_name == "sync_leaf" for location in locations):
+ continue
+ python_locations = [
+ location
+ for location in locations
+ if location.filename != "" and not location.function_name.startswith("<")
+ ]
+ plain_stack_was_bounded = len(python_locations) <= 1 and "omitted>" in locations[-1].function_name
+ if plain_stack_was_bounded:
+ break
- samples = pprof_utils.get_samples_with_label_key(profile, "task name")
- pprof_utils.assert_profile_has_sample(
- profile,
- samples,
- expected_sample=pprof_utils.StackEvent(
- thread_name="MainThread",
- locations=[
- pprof_utils.StackLocation(function_name="sync_leaf", filename="", line_no=-1),
- pprof_utils.StackLocation(function_name="sync_outer", filename="", line_no=-1),
- pprof_utils.StackLocation(function_name="inner", filename="", line_no=-1),
- pprof_utils.StackLocation(function_name="outer", filename="", line_no=-1),
- ],
- ),
- print_samples_on_failure=True,
- )
+ assert plain_stack_was_bounded
+ else:
+ samples = pprof_utils.get_samples_with_label_key(profile, "task name")
+ pprof_utils.assert_profile_has_sample(
+ profile,
+ samples,
+ expected_sample=pprof_utils.StackEvent(
+ thread_name="MainThread",
+ locations=[
+ pprof_utils.StackLocation(function_name="sync_leaf", filename="", line_no=-1),
+ pprof_utils.StackLocation(function_name="sync_outer", filename="", line_no=-1),
+ pprof_utils.StackLocation(function_name="inner", filename="", line_no=-1),
+ pprof_utils.StackLocation(function_name="outer", filename="", line_no=-1),
+ ],
+ ),
+ print_samples_on_failure=True,
+ )
def test_stack_locations(tmp_path: Path) -> None: