From dd6bece2552b2d502c71a84b074f4a2fad6639dd Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Wed, 15 Jul 2026 16:23:58 +0000 Subject: [PATCH 01/28] perf(profiling): honor configured maximum frame count --- .../datadog/profiling/stack/__init__.pyi | 1 + .../datadog/profiling/stack/_stack.pyi | 2 ++ .../profiling/stack/echion/echion/config.h | 4 +-- .../stack/echion/echion/echion_sampler.h | 10 ++++++- .../profiling/stack/echion/echion/stacks.h | 6 ++-- .../profiling/stack/echion/echion/tasks.h | 1 - .../stack/fuzz/fuzz_echion_stacks.cpp | 2 +- .../profiling/stack/include/sampler.hpp | 4 +++ .../profiling/stack/src/echion/stacks.cc | 8 ++--- .../profiling/stack/src/echion/threads.cc | 12 +++++--- .../datadog/profiling/stack/src/sampler.cpp | 30 +++++++++++++++++++ .../datadog/profiling/stack/src/stack.cpp | 28 +++++++++++++++++ ddtrace/profiling/collector/stack.py | 1 + ...propagate-max-frames-f7a718abdfb99c4c.yaml | 4 +++ tests/profiling/collector/test_stack.py | 19 ++++++++++++ 15 files changed, 116 insertions(+), 16 deletions(-) create mode 100644 releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml diff --git a/ddtrace/internal/datadog/profiling/stack/__init__.pyi b/ddtrace/internal/datadog/profiling/stack/__init__.pyi index 3d14af72c8a..f090d7c8448 100644 --- a/ddtrace/internal/datadog/profiling/stack/__init__.pyi +++ b/ddtrace/internal/datadog/profiling/stack/__init__.pyi @@ -20,6 +20,7 @@ def set_adaptive_sampling_baseline(baseline_core_pct: float) -> None: ... def set_p_stable_window_s(p_stable_window_s: int) -> None: ... def set_p_stable_percentile(p_stable_percentile: float) -> None: ... def set_max_threads(max_threads: int) -> None: ... +def set_max_frames(max_frames: int) -> None: ... def set_uvloop_mode(thread_id: int, uvloop_mode: bool) -> None: """Enable uvloop-specific stack unwinding in the native profiler for a specific thread. diff --git a/ddtrace/internal/datadog/profiling/stack/_stack.pyi b/ddtrace/internal/datadog/profiling/stack/_stack.pyi index 921df7f47f8..d613797434d 100644 --- a/ddtrace/internal/datadog/profiling/stack/_stack.pyi +++ b/ddtrace/internal/datadog/profiling/stack/_stack.pyi @@ -16,6 +16,8 @@ def set_adaptive_sampling(do_adaptive_sampling: bool = False) -> None: ... def set_target_overhead(target_overhead: float) -> None: ... def set_max_sampling_period(max_interval_us: int) -> None: ... def set_max_threads(max_threads: int) -> None: ... +def set_max_frames(max_frames: int) -> None: ... +def _get_frame_limits() -> tuple[int, int]: ... def set_uvloop_mode(thread_id: int, uvloop_mode: bool) -> None: ... def set_interval(new_interval: float) -> None: ... diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/config.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/config.h index 6d4811f4510..94b25aa8bd4 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/config.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/config.h @@ -4,5 +4,5 @@ #pragma once -// Maximum number of frames to unwind -inline unsigned int max_frames = 2048; +// Safety limit for Python frames collected while discovering and stitching task-aware stacks. +inline constexpr unsigned int MAX_TASK_FRAMES = 2048; 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 7fd41cfde3e..5938da9bb7b 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h @@ -1,11 +1,14 @@ #pragma once +#include +#include #include #include #include #include #include +#include #include #include #include @@ -53,7 +56,8 @@ class EchionSampler // Only accessed from the sampling thread, so no lock/atomic is needed. size_t asyncio_task_count_ = 0; - // Caches + // Stack depth and caches + size_t stack_max_frames_ = MAX_TASK_FRAMES; StringTable string_table_; LRUCache frame_cache_; @@ -100,6 +104,10 @@ class EchionSampler void add_asyncio_task_count(size_t count) { asyncio_task_count_ += count; } size_t asyncio_task_count() const { return asyncio_task_count_; } + void configure_max_frames(size_t max_frames) { stack_max_frames_ = std::max(max_frames, 1); } + + [[nodiscard]] size_t stack_max_frames() const { return stack_max_frames_; } + // Accessor for StringTable operations StringTable& string_table() { return string_table_; } const StringTable& string_table() const { return string_table_; } diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index 72f180fa57a..0e3e227284a 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -46,17 +46,17 @@ unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, std::unordered_set& seen_frames, - size_t max_depth = max_frames); + size_t max_depth = MAX_TASK_FRAMES); // Convenience variant that owns a local scratch set, for callers that have no // reusable scratch to share (fuzz harnesses and other callers outside the // sampling thread). Prefer the primary overload above on the sampling thread. size_t -unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, size_t max_depth = max_frames); +unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, size_t max_depth = MAX_TASK_FRAMES); // ---------------------------------------------------------------------------- void -unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack); +unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_depth); // ---------------------------------------------------------------------------- class StackInfo diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h index 75a46dd4100..f80201d66c8 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h @@ -31,7 +31,6 @@ #include #include -#include #include #include #include diff --git a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp index 43d31fcb658..4813162029c 100644 --- a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp +++ b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp @@ -50,7 +50,7 @@ LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) tstate.datastack_chunk = reinterpret_cast<_PyStackChunk*>(p2); #endif FrameStack fuzz_stack; - unwind_python_stack(echion_sampler, &tstate, fuzz_stack); + unwind_python_stack(echion_sampler, &tstate, fuzz_stack, MAX_TASK_FRAMES); } g_data = nullptr; diff --git a/ddtrace/internal/datadog/profiling/stack/include/sampler.hpp b/ddtrace/internal/datadog/profiling/stack/include/sampler.hpp index 80e393c185a..3dc30740991 100644 --- a/ddtrace/internal/datadog/profiling/stack/include/sampler.hpp +++ b/ddtrace/internal/datadog/profiling/stack/include/sampler.hpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -129,6 +130,9 @@ class Sampler // update the next rate with the latest interval. This is not perfect because the adjustment is based on // self-time, and we're not currently accounting for the echion self-time. void set_interval(double new_interval); + bool set_max_frames(uint64_t value); + [[nodiscard]] size_t max_frames() const; + [[nodiscard]] size_t frame_cache_capacity() const; bool is_running() const { return thread_running.load(); } void set_adaptive_sampling(bool value) { do_adaptive_sampling = value; } void set_target_overhead(double value) { target_overhead = value; } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index e9a5e340590..e27fb2bb850 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -33,7 +33,7 @@ FrameStack::render(EchionSampler& echion) // Unwind Python frames starting from frame_addr and push them onto stack. // @param seen_frames: Cycle-detection set. Cleared on entry; capacity is reused // by callers (typically EchionSampler::seen_frames_scratch). -// @param max_depth: Maximum number of frames to unwind. Defaults to max_frames. +// @param max_depth: Maximum number of frames to add during this walk. // @return: Number of frames added to the stack. size_t unwind_frame(EchionSampler& echion, @@ -46,7 +46,7 @@ unwind_frame(EchionSampler& echion, size_t count = 0; PyObject* current_frame_addr = frame_addr; - while (current_frame_addr != NULL && stack.size() < max_frames) { + while (current_frame_addr != NULL && stack.size() < MAX_TASK_FRAMES) { if (seen_frames.contains(current_frame_addr)) break; @@ -88,7 +88,7 @@ unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, siz } void -unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack) +unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_depth) { stack.clear(); #if PY_VERSION_HEX >= 0x030b0000 @@ -114,5 +114,5 @@ unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& st #else // Python < 3.11 PyObject* frame_addr = reinterpret_cast(tstate->frame); #endif - unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch()); + unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), max_depth); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 192ccfaea6f..69698808717 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -11,7 +11,11 @@ void ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate) { - unwind_python_stack(echion, tstate, python_stack); + // 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_depth = asyncio_loop ? MAX_TASK_FRAMES : echion.stack_max_frames(); + unwind_python_stack(echion, tstate, python_stack, max_depth); if (asyncio_loop) { // unwind_tasks returns a [[nodiscard]] Result. @@ -252,15 +256,15 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate) // 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 max_frames truncation behavior while avoiding front insertion. + // 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_frames) { - task_frames_to_push = std::min(task_stack_size, max_frames - stack.size()); + if (stack.size() < MAX_TASK_FRAMES) { + task_frames_to_push = std::min(task_stack_size, MAX_TASK_FRAMES - stack.size()); } } if (task.is_on_cpu) { diff --git a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp index a81b99cf8de..499705d9135 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp @@ -450,9 +450,39 @@ Sampler::set_interval(double new_interval_s) Sample::profile_borrow().stats().set_sampling_interval_us(new_interval_us); } +bool +Sampler::set_max_frames(uint64_t value) +{ + // StackCollector configures this before start(). Updating the limit while + // the sampler thread is walking stacks would race with collection. + if ((thread_seq_num.load(std::memory_order_acquire) & 1U) != 0U || thread_running.load(std::memory_order_acquire)) { + return false; + } + + // The configured value is already clamped to the backend limit in + // ddtrace/internal/settings/profiling.py; pass it through as-is. EchionSampler + // enforces a floor of 1 frame. + const size_t requested = static_cast(value); + echion->configure_max_frames(requested); + return true; +} + +size_t +Sampler::max_frames() const +{ + return echion->stack_max_frames(); +} + +size_t +Sampler::frame_cache_capacity() const +{ + return g_default_echion_frame_cache_size; +} + Sampler::Sampler() : echion{ std::make_unique(g_default_echion_frame_cache_size) } { + echion->configure_max_frames(g_default_max_nframes); } Sampler& diff --git a/ddtrace/internal/datadog/profiling/stack/src/stack.cpp b/ddtrace/internal/datadog/profiling/stack/src/stack.cpp index 838787e1f12..6ff46903316 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/stack.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/stack.cpp @@ -316,6 +316,32 @@ stack_set_max_threads(PyObject* Py_UNUSED(self), PyObject* args) Py_RETURN_NONE; } +static PyObject* +stack_set_max_frames(PyObject* Py_UNUSED(self), PyObject* args) +{ + unsigned long long max_frames; + + if (!PyArg_ParseTuple(args, "K", &max_frames)) { + return NULL; + } + + if (!Sampler::get().set_max_frames(max_frames)) { + PyErr_SetString(PyExc_RuntimeError, "cannot change max frames while the stack sampler is running"); + return NULL; + } + + Py_RETURN_NONE; +} + +static PyObject* +stack_get_frame_limits(PyObject* Py_UNUSED(self), PyObject* Py_UNUSED(args)) +{ + const auto& sampler = Sampler::get(); + return Py_BuildValue("KK", + static_cast(sampler.max_frames()), + static_cast(sampler.frame_cache_capacity())); +} + static PyObject* stack_set_uvloop_mode(PyObject* Py_UNUSED(self), PyObject* args) { @@ -860,6 +886,8 @@ static PyMethodDef stack_methods[] = { METH_VARARGS, "Set the percentile (0-100) used to compute p_stable from the rolling window" }, { "set_max_threads", stack_set_max_threads, METH_VARARGS, "Set max threads to sample per cycle (0 = unlimited)" }, + { "set_max_frames", stack_set_max_frames, METH_VARARGS, "Set the plain-stack reporting depth" }, + { "_get_frame_limits", stack_get_frame_limits, METH_NOARGS, "Get plain-stack and frame-cache limits" }, { "set_uvloop_mode", stack_set_uvloop_mode, METH_VARARGS, "Enable uvloop-specific stack unwinding for a thread" }, // Memory copy strategy { "set_fast_copy", stack_set_fast_copy, METH_VARARGS, "Enable or disable fast memory copying (safe_memcpy)" }, diff --git a/ddtrace/profiling/collector/stack.py b/ddtrace/profiling/collector/stack.py index e58d93056c0..77e327bb440 100644 --- a/ddtrace/profiling/collector/stack.py +++ b/ddtrace/profiling/collector/stack.py @@ -63,6 +63,7 @@ def _init(self) -> None: stack.set_p_stable_window_s(config.stack.adaptive_sampling_p_stable_window_s) stack.set_p_stable_percentile(config.stack.adaptive_sampling_p_stable_percentile) stack.set_max_threads(config.stack.max_threads) + stack.set_max_frames(self.nframes) stack.set_fast_copy(config.stack.fast_copy) if stack.is_safe_copy_failed(): LOG.error("No safe memory copy method available (safe_memcpy and process_vm_readv both failed).") diff --git a/releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml b/releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml new file mode 100644 index 00000000000..7af36d9db7b --- /dev/null +++ b/releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + profiling: This fix reduces profiler memory and CPU overhead by limiting plain thread stack collection to ``DD_PROFILING_MAX_FRAMES`` while retaining the deeper internal discovery needed to reconstruct asyncio task stacks. diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index 065af199827..c81abc60a1b 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -70,6 +70,7 @@ def func5() -> None: def test_collect_truncate() -> None: import os + from ddtrace.internal.datadog.profiling.stack import _stack from ddtrace.profiling import profiler from tests.profiling.collector import pprof_utils from tests.profiling.collector.test_stack import func1 @@ -82,6 +83,8 @@ def test_collect_truncate() -> None: p = profiler.Profiler() p.start() + assert _stack._get_frame_limits() == (max_nframes, 1024) + func1() p.stop() @@ -94,6 +97,22 @@ def test_collect_truncate() -> None: assert len(sample.location_id) <= max_nframes + 1, len(sample.location_id) +@pytest.mark.subprocess +def test_native_frame_limit() -> None: + # Clamping to the backend limit happens at the config layer. The native + # sampler passes configured values through and only enforces a floor of one. + from ddtrace.internal.datadog.profiling.stack import _stack + + _stack.set_max_frames(0) + assert _stack._get_frame_limits() == (1, 1024) + + _stack.set_max_frames(65) + assert _stack._get_frame_limits() == (65, 1024) + + _stack.set_max_frames(10_000) + assert _stack._get_frame_limits() == (10_000, 1024) + + def test_stack_locations(tmp_path: Path) -> None: test_name = "test_stack_locations" pprof_prefix = str(tmp_path / test_name) From a4800c7c42878b6dac380e279eb9082d26b528d1 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Fri, 17 Jul 2026 20:36:29 +0000 Subject: [PATCH 02/28] refactor(profiling): use frame config directly --- ddtrace/profiling/collector/stack.py | 6 ++---- tests/profiling/collector/test_stack.py | 2 +- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/ddtrace/profiling/collector/stack.py b/ddtrace/profiling/collector/stack.py index 77e327bb440..38ce24f2edd 100644 --- a/ddtrace/profiling/collector/stack.py +++ b/ddtrace/profiling/collector/stack.py @@ -21,15 +21,13 @@ class StackCollector(collector.Collector): """Execution stacks collector.""" __slots__ = ( - "nframes", "tracer", "_native_call_monitor", ) - def __init__(self, nframes: typing.Optional[int] = None, tracer: typing.Optional[Tracer] = None): + def __init__(self, tracer: typing.Optional[Tracer] = None): super().__init__() - self.nframes = nframes if nframes is not None else config.max_frames self.tracer = tracer self._native_call_monitor: typing.Optional[ModuleType] = None @@ -63,7 +61,7 @@ def _init(self) -> None: stack.set_p_stable_window_s(config.stack.adaptive_sampling_p_stable_window_s) stack.set_p_stable_percentile(config.stack.adaptive_sampling_p_stable_percentile) stack.set_max_threads(config.stack.max_threads) - stack.set_max_frames(self.nframes) + stack.set_max_frames(config.max_frames) stack.set_fast_copy(config.stack.fast_copy) if stack.is_safe_copy_failed(): LOG.error("No safe memory copy method available (safe_memcpy and process_vm_readv both failed).") diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index c81abc60a1b..ef45b1c57dd 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -849,7 +849,7 @@ def worker() -> None: def test_repr() -> None: test_collector._test_repr( stack.StackCollector, - "StackCollector(status=, nframes=64, tracer=None)", + "StackCollector(status=, tracer=None)", ) From ac6a45ddeb2b6e1859dc07b3523ca38907c2eeed Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Fri, 17 Jul 2026 20:45:17 +0000 Subject: [PATCH 03/28] refactor(profiling): clarify stack frame limit naming --- .../datadog/profiling/stack/echion/echion/stacks.h | 9 ++++++--- .../datadog/profiling/stack/src/echion/stacks.cc | 14 +++++++------- .../datadog/profiling/stack/src/echion/threads.cc | 4 ++-- 3 files changed, 15 insertions(+), 12 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index 0e3e227284a..e84f382368a 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -46,17 +46,20 @@ unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, std::unordered_set& seen_frames, - size_t max_depth = MAX_TASK_FRAMES); + size_t max_frames_to_add = MAX_TASK_FRAMES); // Convenience variant that owns a local scratch set, for callers that have no // reusable scratch to share (fuzz harnesses and other callers outside the // sampling thread). Prefer the primary overload above on the sampling thread. size_t -unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, size_t max_depth = MAX_TASK_FRAMES); +unwind_frame(EchionSampler& echion, + PyObject* frame_addr, + FrameStack& stack, + size_t max_frames_to_add = MAX_TASK_FRAMES); // ---------------------------------------------------------------------------- void -unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_depth); +unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_frames); // ---------------------------------------------------------------------------- class StackInfo diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index e27fb2bb850..7362ae86e77 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -33,14 +33,14 @@ FrameStack::render(EchionSampler& echion) // Unwind Python frames starting from frame_addr and push them onto stack. // @param seen_frames: Cycle-detection set. Cleared on entry; capacity is reused // by callers (typically EchionSampler::seen_frames_scratch). -// @param max_depth: Maximum number of frames to add during this walk. +// @param max_frames_to_add: Maximum number of frames to add during this walk. // @return: Number of frames added to the stack. size_t unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, std::unordered_set& seen_frames, - size_t max_depth) + size_t max_frames_to_add) { seen_frames.clear(); size_t count = 0; @@ -70,7 +70,7 @@ unwind_frame(EchionSampler& echion, stack.push_back(maybe_frame->get()); count++; - if (count >= max_depth) { + if (count >= max_frames_to_add) { break; } } @@ -81,14 +81,14 @@ unwind_frame(EchionSampler& echion, // Convenience variant that owns its own scratch set and delegates to the // primary overload above. For callers without a reusable scratch set to share. size_t -unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, size_t max_depth) +unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, size_t max_frames_to_add) { std::unordered_set local_seen_frames; - return unwind_frame(echion, frame_addr, stack, local_seen_frames, max_depth); + return unwind_frame(echion, frame_addr, stack, local_seen_frames, max_frames_to_add); } void -unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_depth) +unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_frames) { stack.clear(); #if PY_VERSION_HEX >= 0x030b0000 @@ -114,5 +114,5 @@ unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& st #else // Python < 3.11 PyObject* frame_addr = reinterpret_cast(tstate->frame); #endif - unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), max_depth); + unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), max_frames); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 69698808717..2c3bcda3f75 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -14,8 +14,8 @@ ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate) // 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_depth = asyncio_loop ? MAX_TASK_FRAMES : echion.stack_max_frames(); - unwind_python_stack(echion, tstate, python_stack, max_depth); + const size_t max_frames = asyncio_loop ? MAX_TASK_FRAMES : echion.stack_max_frames(); + unwind_python_stack(echion, tstate, python_stack, max_frames); if (asyncio_loop) { // unwind_tasks returns a [[nodiscard]] Result. From 3ee80d510952b1df8024294b020742200b366179 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Wed, 12 Aug 2026 23:56:05 +0000 Subject: [PATCH 04/28] fix(profiling): preserve native frame limit semantics --- .../profiling/stack/echion/echion/stacks.h | 5 +- .../stack/include/stack_renderer.hpp | 1 + .../profiling/stack/src/echion/stacks.cc | 28 +++- .../datadog/profiling/stack/src/sampler.cpp | 8 +- .../profiling/stack/src/stack_renderer.cpp | 8 ++ ddtrace/profiling/collector/stack.py | 6 +- tests/profiling/collector/test_stack.py | 129 +++++++++++++++++- 7 files changed, 170 insertions(+), 15 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index e84f382368a..ec8e5e1e0f6 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -30,6 +30,8 @@ class FrameStack : public std::vector public: using Key = Frame::Key; + bool truncated = false; + void render(EchionSampler& echion); }; @@ -46,7 +48,8 @@ unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, std::unordered_set& seen_frames, - size_t max_frames_to_add = MAX_TASK_FRAMES); + size_t max_frames_to_add = MAX_TASK_FRAMES, + bool* truncated = nullptr); // Convenience variant that owns a local scratch set, for callers that have no // reusable scratch to share (fuzz harnesses and other callers outside the diff --git a/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp b/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp index cac64cc4812..061d2a4c115 100644 --- a/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp +++ b/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp @@ -89,6 +89,7 @@ class StackRenderer unsigned long native_id); void render_task_begin(std::string_view task_name, bool on_cpu, uint64_t task_id); void render_frame(Frame& frame); + void render_truncated(); void render_cpu_time(microsecond_t cpu_time_us); void render_native_frame(const std::string& name, const std::string& module); void render_stack_end(); diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index 7362ae86e77..335b21e60dd 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -28,23 +28,38 @@ FrameStack::render(EchionSampler& echion) renderer.render_frame(frame); } + + if (truncated) { + renderer.render_truncated(); + } } // Unwind Python frames starting from frame_addr and push them onto stack. // @param seen_frames: Cycle-detection set. Cleared on entry; capacity is reused // by callers (typically EchionSampler::seen_frames_scratch). // @param max_frames_to_add: Maximum number of frames to add during this walk. +// @param truncated: Set when the walk stops at a frame limit with more frames remaining. // @return: Number of frames added to the stack. size_t unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, std::unordered_set& seen_frames, - size_t max_frames_to_add) + size_t max_frames_to_add, + bool* truncated) { seen_frames.clear(); - size_t count = 0; + if (truncated != nullptr) { + *truncated = false; + } + if (max_frames_to_add == 0) { + if (truncated != nullptr && frame_addr != nullptr) { + *truncated = true; + } + return 0; + } + size_t count = 0; PyObject* current_frame_addr = frame_addr; while (current_frame_addr != NULL && stack.size() < MAX_TASK_FRAMES) { if (seen_frames.contains(current_frame_addr)) @@ -71,10 +86,16 @@ unwind_frame(EchionSampler& echion, count++; if (count >= max_frames_to_add) { + if (truncated != nullptr && current_frame_addr != nullptr) { + *truncated = true; + } break; } } + if (truncated != nullptr && current_frame_addr != nullptr && stack.size() >= MAX_TASK_FRAMES) { + *truncated = true; + } return count; } @@ -91,6 +112,7 @@ void unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_frames) { stack.clear(); + stack.truncated = false; #if PY_VERSION_HEX >= 0x030b0000 if (stack_chunk == nullptr) { stack_chunk = std::make_unique(); @@ -114,5 +136,5 @@ unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& st #else // Python < 3.11 PyObject* frame_addr = reinterpret_cast(tstate->frame); #endif - unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), max_frames); + unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), max_frames, &stack.truncated); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp index 2d1577978e4..f73de1d6aca 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp @@ -567,14 +567,12 @@ Sampler::set_max_frames(uint64_t value) { // StackCollector configures this before start(). Updating the limit while // the sampler thread is walking stacks would race with collection. - if ((thread_seq_num.load(std::memory_order_acquire) & 1U) != 0U || thread_running.load(std::memory_order_acquire)) { + if (sampler_active_.load(std::memory_order_acquire) || thread_running.load(std::memory_order_acquire)) { return false; } - // The configured value is already clamped to the backend limit in - // ddtrace/internal/settings/profiling.py; pass it through as-is. EchionSampler - // enforces a floor of 1 frame. - const size_t requested = static_cast(value); + // Zero preserves the existing exporter behavior: retain the default limit. + const size_t requested = value == 0 ? g_default_max_nframes : static_cast(value); echion->configure_max_frames(requested); return true; } diff --git a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp index 7a6fdec1bf3..d06513967ba 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp @@ -206,6 +206,14 @@ StackRenderer::render_frame(Frame& frame) sample->push_frame(function_id, 0, line); } +void +StackRenderer::render_truncated() +{ + if (sample != nullptr) { + sample->incr_dropped_frames(); + } +} + void StackRenderer::render_native_frame(const std::string& name, const std::string& module) { diff --git a/ddtrace/profiling/collector/stack.py b/ddtrace/profiling/collector/stack.py index 09a7676f60a..420d59c726d 100644 --- a/ddtrace/profiling/collector/stack.py +++ b/ddtrace/profiling/collector/stack.py @@ -31,13 +31,15 @@ class StackCollector(collector.Collector): """Execution stacks collector.""" __slots__ = ( + "nframes", "tracer", "_native_call_monitor", ) - def __init__(self, tracer: typing.Optional[Tracer] = None): + def __init__(self, nframes: typing.Optional[int] = None, tracer: typing.Optional[Tracer] = None): super().__init__() + self.nframes = nframes if nframes is not None else config.max_frames self.tracer = tracer self._native_call_monitor: typing.Optional[ModuleType] = None @@ -71,7 +73,7 @@ def _init(self) -> None: stack.set_p_stable_window_s(config.stack.adaptive_sampling_p_stable_window_s) stack.set_p_stable_percentile(config.stack.adaptive_sampling_p_stable_percentile) stack.set_max_threads(config.stack.max_threads) - stack.set_max_frames(config.max_frames) + stack.set_max_frames(self.nframes) stack.set_fast_copy(config.stack.fast_copy) if stack.is_safe_copy_failed(): LOG.error("No safe memory copy method available (safe_memcpy and process_vm_readv both failed).") diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index ef45b1c57dd..cb4e9f51036 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -92,19 +92,23 @@ def test_collect_truncate() -> None: profile = pprof_utils.parse_newest_profile(output_filename) samples = pprof_utils.get_samples_with_value_type(profile, "wall-time") assert len(samples) > 0 + truncated_samples = 0 for sample in samples: # stack adds one extra frame for "%d frames omitted" message assert len(sample.location_id) <= max_nframes + 1, len(sample.location_id) + if sample.location_id: + root = pprof_utils.get_location_from_id(profile, sample.location_id[-1]) + truncated_samples += root.function_name.startswith("<") and "omitted>" in root.function_name + + assert truncated_samples > 0 @pytest.mark.subprocess def test_native_frame_limit() -> None: - # Clamping to the backend limit happens at the config layer. The native - # sampler passes configured values through and only enforces a floor of one. from ddtrace.internal.datadog.profiling.stack import _stack _stack.set_max_frames(0) - assert _stack._get_frame_limits() == (1, 1024) + assert _stack._get_frame_limits() == (64, 1024) _stack.set_max_frames(65) assert _stack._get_frame_limits() == (65, 1024) @@ -113,6 +117,123 @@ def test_native_frame_limit() -> None: assert _stack._get_frame_limits() == (10_000, 1024) +@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="fork test only on linux") +@pytest.mark.subprocess(err=None) +def test_set_max_frames_after_fork_restart() -> None: + import os + import traceback + + from ddtrace.internal.datadog.profiling import ddup + from ddtrace.internal.datadog.profiling import stack + + ddup.config(env="test", service="test", version="0.0.0") + ddup.start() + stack.set_adaptive_sampling(False) + assert stack.start() + try: + pid = os.fork() + if pid == 0: + try: + stack.stop() + stack.set_max_frames(32) + assert stack.start() + stack.stop() + except BaseException: + traceback.print_exc() + os._exit(1) + os._exit(0) + + _, status = os.waitpid(pid, 0) + assert os.waitstatus_to_exitcode(status) == 0 + finally: + stack.stop() + + +@pytest.mark.subprocess( + env=dict( + DD_PROFILING_OUTPUT_PPROF="/tmp/test_asyncio_native_frame_limit", + ), + err=None, +) +def test_asyncio_discovery_ignores_plain_stack_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) + + def sync_outer() -> None: + sync_leaf() + + async def inner() -> None: + sync_outer() + + async def outer() -> None: + await inner() + + with stack.StackCollector(nframes=1): + assert _stack._get_frame_limits() == (1, 1024) + sync_outer() + asyncio.run(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("<") + ] + 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 + + 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: test_name = "test_stack_locations" pprof_prefix = str(tmp_path / test_name) @@ -849,7 +970,7 @@ def worker() -> None: def test_repr() -> None: test_collector._test_repr( stack.StackCollector, - "StackCollector(status=, tracer=None)", + "StackCollector(status=, nframes=64, tracer=None)", ) From 56be92f538612bf75a9e53149146a7d259383972 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Mon, 17 Aug 2026 21:44:05 +0000 Subject: [PATCH 05/28] test(profiling): strengthen frame limit regressions --- tests/profiling/collector/test_stack.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index 5c26e56cf9a..eab0ad4dc16 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -65,6 +65,7 @@ def func5() -> None: env=dict( DD_PROFILING_MAX_FRAMES="5", DD_PROFILING_OUTPUT_PPROF="/tmp/test_collect_truncate", + DD_PROFILING_STACK_NATIVE_FRAMES="0", ) ) def test_collect_truncate() -> None: @@ -92,15 +93,16 @@ def test_collect_truncate() -> None: profile = pprof_utils.parse_newest_profile(output_filename) samples = pprof_utils.get_samples_with_value_type(profile, "wall-time") assert len(samples) > 0 - truncated_samples = 0 + found_func1_stack = False for sample in samples: # stack adds one extra frame for "%d frames omitted" message assert len(sample.location_id) <= max_nframes + 1, len(sample.location_id) - if sample.location_id: - root = pprof_utils.get_location_from_id(profile, sample.location_id[-1]) - truncated_samples += root.function_name.startswith("<") and "omitted>" in root.function_name + locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id] + if any(location.function_name == "func5" for location in locations): + found_func1_stack = True + assert locations[-1].function_name == "<1 frame omitted>" - assert truncated_samples > 0 + assert found_func1_stack @pytest.mark.subprocess @@ -123,6 +125,8 @@ def test_set_max_frames_after_fork_restart() -> None: import os import traceback + import pytest + from ddtrace.internal.datadog.profiling import ddup from ddtrace.internal.datadog.profiling import stack @@ -131,6 +135,9 @@ def test_set_max_frames_after_fork_restart() -> None: stack.set_adaptive_sampling(False) assert stack.start() try: + with pytest.raises(RuntimeError, match="cannot change max frames while the stack sampler is running"): + stack.set_max_frames(32) + pid = os.fork() if pid == 0: try: From bc3e3ea09293f15382d3c89a4f4cba339a2e79bd Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Mon, 17 Aug 2026 22:16:40 +0000 Subject: [PATCH 06/28] fix(profiling): avoid false truncation markers --- .../profiling/stack/src/echion/stacks.cc | 30 ++++++----- tests/profiling/collector/test_stack.py | 50 +++++++++++++++++++ 2 files changed, 67 insertions(+), 13 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index 335b21e60dd..66fad88ee2b 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -51,17 +51,18 @@ unwind_frame(EchionSampler& echion, seen_frames.clear(); if (truncated != nullptr) { *truncated = false; - } - if (max_frames_to_add == 0) { - if (truncated != nullptr && frame_addr != nullptr) { - *truncated = true; - } + } else if (max_frames_to_add == 0 || stack.size() >= MAX_TASK_FRAMES) { return 0; } size_t count = 0; + size_t frames_probed_after_limit = 0; PyObject* current_frame_addr = frame_addr; - while (current_frame_addr != NULL && stack.size() < MAX_TASK_FRAMES) { + while (current_frame_addr != NULL) { + const bool at_limit = count >= max_frames_to_add || stack.size() >= MAX_TASK_FRAMES; + if (at_limit && frames_probed_after_limit++ >= MAX_TASK_FRAMES) { + break; + } if (seen_frames.contains(current_frame_addr)) break; @@ -82,20 +83,23 @@ unwind_frame(EchionSampler& echion, continue; } + // When reporting truncation, confirm that the bounded lookahead found a + // reportable frame so terminal C/interpreter frames do not produce a false marker. + if (at_limit) { + if (truncated != nullptr) { + *truncated = true; + } + break; + } + stack.push_back(maybe_frame->get()); count++; - if (count >= max_frames_to_add) { - if (truncated != nullptr && current_frame_addr != nullptr) { - *truncated = true; - } + if (truncated == nullptr && (count >= max_frames_to_add || stack.size() >= MAX_TASK_FRAMES)) { break; } } - if (truncated != nullptr && current_frame_addr != nullptr && stack.size() >= MAX_TASK_FRAMES) { - *truncated = true; - } return count; } diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index eab0ad4dc16..017f239b4bd 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -119,6 +119,56 @@ def test_native_frame_limit() -> None: assert _stack._get_frame_limits() == (10_000, 1024) +@pytest.mark.subprocess( + env=dict( + DD_PROFILING_OUTPUT_PPROF="/tmp/test_exact_native_frame_limit", + DD_PROFILING_STACK_NATIVE_FRAMES="0", + ), + err=None, +) +def test_exact_native_frame_limit_is_not_truncated() -> None: + import os + import sys + import time + + from ddtrace.internal.datadog.profiling import ddup + from ddtrace.profiling.collector import stack + from tests.profiling.collector import pprof_utils + + pprof_prefix = os.environ["DD_PROFILING_OUTPUT_PPROF"] + + def sample_full_stack() -> None: + frame_count = 0 + frame = sys._getframe() + while frame is not None: + frame_count += 1 + frame = frame.f_back + + ddup.config( + env="test", + service="test", + version="0.0.0", + max_nframes=frame_count, + output_filename=pprof_prefix, + ) + ddup.start() + + with stack.StackCollector(nframes=frame_count): + time.sleep(0.5) + + sample_full_stack() + ddup.upload() + profile = pprof_utils.parse_newest_profile(pprof_prefix + "." + str(os.getpid())) + found_test_stack = False + for sample in pprof_utils.get_samples_with_value_type(profile, "wall-time"): + locations = [pprof_utils.get_location_from_id(profile, location_id) for location_id in sample.location_id] + if locations and locations[0].function_name == "sample_full_stack": + found_test_stack = True + assert "omitted>" not in locations[-1].function_name + + assert found_test_stack + + @pytest.mark.skipif(not sys.platform.startswith("linux"), reason="fork test only on linux") @pytest.mark.subprocess(err=None) def test_set_max_frames_after_fork_restart() -> None: From 7c5caf1e7c16c75ef1e9e9df9ba7259a4b01d516 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Tue, 18 Aug 2026 15:09:53 +0000 Subject: [PATCH 07/28] refactor(profiling): return stack unwind metadata --- .../profiling/stack/echion/echion/stacks.h | 21 +++++--- .../profiling/stack/echion/echion/threads.h | 1 + .../profiling/stack/src/echion/stacks.cc | 51 +++++++++---------- .../profiling/stack/src/echion/tasks.cc | 6 +-- .../profiling/stack/src/echion/threads.cc | 4 +- 5 files changed, 42 insertions(+), 41 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index a67b6bf8232..e4df556679a 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -22,6 +22,12 @@ class EchionSampler; +struct UnwindResult +{ + size_t frames_added = 0; + bool truncated = false; +}; + // ---------------------------------------------------------------------------- // FrameStack owns the Frames so that they stay valid across cache evictions // (asyncio unwind_tasks precomputes per-task stacks via Frame::get, which can @@ -31,9 +37,7 @@ class FrameStack : public std::vector public: using Key = Frame::Key; - bool truncated = false; - - void render(EchionSampler& echion); + void render(EchionSampler& echion, bool truncated = false); }; // Forward declaration @@ -44,25 +48,26 @@ class EchionSampler; // the sampling thread should pass EchionSampler::seen_frames_scratch() so the // hash table's capacity is reused across calls instead of reallocated per call. // `seen_frames` is cleared on entry. -size_t +UnwindResult unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, std::unordered_set& seen_frames, size_t max_frames_to_add = MAX_TASK_FRAMES, - bool* truncated = nullptr); + bool detect_truncation = false); // Convenience variant that owns a local scratch set, for callers that have no // reusable scratch to share (fuzz harnesses and other callers outside the // sampling thread). Prefer the primary overload above on the sampling thread. -size_t +UnwindResult unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, - size_t max_frames_to_add = MAX_TASK_FRAMES); + size_t max_frames_to_add = MAX_TASK_FRAMES, + bool detect_truncation = false); // ---------------------------------------------------------------------------- -void +UnwindResult unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_frames); // ---------------------------------------------------------------------------- diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h index cc53cfb61f3..4130e3865dc 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h @@ -42,6 +42,7 @@ class ThreadInfo uintptr_t thread_id; unsigned long native_id; FrameStack python_stack; + UnwindResult python_stack_unwind_result; std::vector> current_tasks; std::vector> current_greenlets; diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index 66fad88ee2b..2df43e26e6d 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -6,7 +6,7 @@ #include "dd_wrapper/include/profiler_state.hpp" void -FrameStack::render(EchionSampler& echion) +FrameStack::render(EchionSampler& echion, bool truncated) { auto& renderer = echion.renderer(); auto& registry = Datadog::ProfilerState::get().native_call_registry; @@ -38,29 +38,27 @@ FrameStack::render(EchionSampler& echion) // @param seen_frames: Cycle-detection set. Cleared on entry; capacity is reused // by callers (typically EchionSampler::seen_frames_scratch). // @param max_frames_to_add: Maximum number of frames to add during this walk. -// @param truncated: Set when the walk stops at a frame limit with more frames remaining. -// @return: Number of frames added to the stack. -size_t +// @param detect_truncation: Whether to probe for another reportable frame after reaching the limit. +// @return: Number of frames added and whether another reportable frame was found. +UnwindResult unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, std::unordered_set& seen_frames, size_t max_frames_to_add, - bool* truncated) + bool detect_truncation) { seen_frames.clear(); - if (truncated != nullptr) { - *truncated = false; - } else if (max_frames_to_add == 0 || stack.size() >= MAX_TASK_FRAMES) { - return 0; + UnwindResult result; + if (!detect_truncation && (max_frames_to_add == 0 || stack.size() >= MAX_TASK_FRAMES)) { + return result; } - size_t count = 0; size_t frames_probed_after_limit = 0; PyObject* current_frame_addr = frame_addr; while (current_frame_addr != NULL) { - const bool at_limit = count >= max_frames_to_add || stack.size() >= MAX_TASK_FRAMES; - if (at_limit && frames_probed_after_limit++ >= MAX_TASK_FRAMES) { + const bool at_limit = result.frames_added >= max_frames_to_add || stack.size() >= MAX_TASK_FRAMES; + if (at_limit && (!detect_truncation || frames_probed_after_limit++ >= MAX_TASK_FRAMES)) { break; } if (seen_frames.contains(current_frame_addr)) @@ -86,37 +84,34 @@ unwind_frame(EchionSampler& echion, // When reporting truncation, confirm that the bounded lookahead found a // reportable frame so terminal C/interpreter frames do not produce a false marker. if (at_limit) { - if (truncated != nullptr) { - *truncated = true; - } + result.truncated = true; break; } stack.push_back(maybe_frame->get()); - count++; - - if (truncated == nullptr && (count >= max_frames_to_add || stack.size() >= MAX_TASK_FRAMES)) { - break; - } + result.frames_added++; } - return count; + return result; } // Convenience variant that owns its own scratch set and delegates to the // primary overload above. For callers without a reusable scratch set to share. -size_t -unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, size_t max_frames_to_add) +UnwindResult +unwind_frame(EchionSampler& echion, + PyObject* frame_addr, + FrameStack& stack, + size_t max_frames_to_add, + bool detect_truncation) { std::unordered_set local_seen_frames; - return unwind_frame(echion, frame_addr, stack, local_seen_frames, max_frames_to_add); + return unwind_frame(echion, frame_addr, stack, local_seen_frames, max_frames_to_add, detect_truncation); } -void +UnwindResult unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& stack, size_t max_frames) { stack.clear(); - stack.truncated = false; #if PY_VERSION_HEX >= 0x030b0000 if (stack_chunk == nullptr) { stack_chunk = std::make_unique(); @@ -134,11 +129,11 @@ unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& st _PyCFrame* cframe_addr = tstate->cframe; if (copy_type(cframe_addr, cframe)) // TODO: Invalid frame - return; + return {}; PyObject* frame_addr = reinterpret_cast(cframe.current_frame); #else // Python < 3.11 PyObject* frame_addr = reinterpret_cast(tstate->frame); #endif - unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), max_frames, &stack.truncated); + return unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), max_frames, true); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc index bc49c5e7e50..db908513021 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc @@ -263,12 +263,12 @@ TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop) // For a running Task, unwind_frame would also yield the asyncio runtime frames "on top" // of the Task frame, but we would discard those anyway. Limiting to 1 frame avoids walking // the Frame chain unnecessarily. - auto new_frames = unwind_frame(echion, frame, stack, echion.seen_frames_scratch(), 1); - assert(new_frames <= 1 && "expected exactly 1 frame to be unwound (or 0 in case of an error)"); + auto unwind_result = unwind_frame(echion, frame, stack, echion.seen_frames_scratch(), 1); + assert(unwind_result.frames_added <= 1 && "expected exactly 1 frame to be unwound (or 0 in case of an error)"); // If we failed to unwind the Frame, stop unwinding the coroutine chain; otherwise we could // end up with Stacks with missing Frames between two coroutines Frames. - if (new_frames == 0) { + if (unwind_result.frames_added == 0) { break; } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 55853f0e64a..704a411bca6 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -28,7 +28,7 @@ ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate, microsecond_t w // 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_TASK_FRAMES : echion.stack_max_frames(); - unwind_python_stack(echion, tstate, python_stack, max_frames); + python_stack_unwind_result = unwind_python_stack(echion, tstate, python_stack, max_frames); if (asyncio_loop) { // unwind_tasks returns a [[nodiscard]] Result. @@ -849,7 +849,7 @@ ThreadInfo::render_unwound_stacks(EchionSampler& echion) renderer.render_stack_end(); } } else { - python_stack.render(echion); + python_stack.render(echion, python_stack_unwind_result.truncated); renderer.render_stack_end(); } } From ec937332ab6a2f553a2017748d460c88e6503ddf Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Wed, 19 Aug 2026 15:25:06 +0000 Subject: [PATCH 08/28] refactor(profiling): clarify stack unwind controls --- .../profiling/stack/echion/echion/echion_sampler.h | 2 +- .../datadog/profiling/stack/echion/echion/stacks.h | 10 +++++----- .../profiling/stack/fuzz/fuzz_echion_stacks.cpp | 2 +- .../datadog/profiling/stack/src/echion/greenlets.cc | 2 +- .../datadog/profiling/stack/src/echion/stacks.cc | 13 ++++++++----- .../datadog/profiling/stack/src/echion/tasks.cc | 7 ++++--- .../datadog/profiling/stack/src/echion/threads.cc | 4 ++-- .../datadog/profiling/stack/src/sampler.cpp | 4 ++-- 8 files changed, 24 insertions(+), 20 deletions(-) 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 de43336a611..f8d553dd23b 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h @@ -115,7 +115,7 @@ class EchionSampler void add_asyncio_task_count(size_t count) { asyncio_task_count_ += count; } size_t asyncio_task_count() const { return asyncio_task_count_; } - void configure_max_frames(size_t max_frames) { stack_max_frames_ = std::max(max_frames, 1); } + void set_max_frames(size_t max_frames) { stack_max_frames_ = std::max(max_frames, 1); } [[nodiscard]] size_t stack_max_frames() const { return stack_max_frames_; } unsigned int max_tasks_per_sample() const { return max_tasks_per_sample_; } diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index e4df556679a..dfcc4023bb4 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -37,7 +37,7 @@ class FrameStack : public std::vector public: using Key = Frame::Key; - void render(EchionSampler& echion, bool truncated = false); + void render(EchionSampler& echion, bool truncated); }; // Forward declaration @@ -53,8 +53,8 @@ unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, std::unordered_set& seen_frames, - size_t max_frames_to_add = MAX_TASK_FRAMES, - bool detect_truncation = false); + size_t max_frames_to_add, + bool detect_truncation); // Convenience variant that owns a local scratch set, for callers that have no // reusable scratch to share (fuzz harnesses and other callers outside the @@ -63,8 +63,8 @@ UnwindResult unwind_frame(EchionSampler& echion, PyObject* frame_addr, FrameStack& stack, - size_t max_frames_to_add = MAX_TASK_FRAMES, - bool detect_truncation = false); + size_t max_frames_to_add, + bool detect_truncation); // ---------------------------------------------------------------------------- UnwindResult diff --git a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp index 4813162029c..e6917b6d4ee 100644 --- a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp +++ b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp @@ -30,7 +30,7 @@ LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) // varint line table decoding. { FrameStack fuzz_stack; - (void)unwind_frame(echion_sampler, reinterpret_cast(p0), fuzz_stack, 16); + (void)unwind_frame(echion_sampler, reinterpret_cast(p0), fuzz_stack, 16, false); } // unwind_python_stack — full stack unwind pipeline from a locally-constructed diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/greenlets.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/greenlets.cc index 6c5a2ea2f36..4581f737207 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/greenlets.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/greenlets.cc @@ -40,5 +40,5 @@ GreenletInfo::unwind(EchionSampler& echion, PyObject* cur_frame, PyThreadState* #else // Python < 3.11 frame_addr = cur_frame == Py_None ? reinterpret_cast(tstate->frame) : cur_frame; #endif - unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch()); + unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), MAX_TASK_FRAMES, false); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index 2df43e26e6d..9babaa24ce6 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -49,17 +49,20 @@ unwind_frame(EchionSampler& echion, bool detect_truncation) { seen_frames.clear(); - UnwindResult result; if (!detect_truncation && (max_frames_to_add == 0 || stack.size() >= MAX_TASK_FRAMES)) { - return result; + return UnwindResult{}; } + UnwindResult result; size_t frames_probed_after_limit = 0; PyObject* current_frame_addr = frame_addr; while (current_frame_addr != NULL) { const bool at_limit = result.frames_added >= max_frames_to_add || stack.size() >= MAX_TASK_FRAMES; - if (at_limit && (!detect_truncation || frames_probed_after_limit++ >= MAX_TASK_FRAMES)) { - break; + if (at_limit) { + if (!detect_truncation || frames_probed_after_limit >= MAX_TASK_FRAMES) { + break; + } + frames_probed_after_limit++; } if (seen_frames.contains(current_frame_addr)) break; @@ -129,7 +132,7 @@ unwind_python_stack(EchionSampler& echion, PyThreadState* tstate, FrameStack& st _PyCFrame* cframe_addr = tstate->cframe; if (copy_type(cframe_addr, cframe)) // TODO: Invalid frame - return {}; + return UnwindResult{}; PyObject* frame_addr = reinterpret_cast(cframe.current_frame); #else // Python < 3.11 diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc index db908513021..250953f3e65 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc @@ -263,12 +263,13 @@ TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop) // For a running Task, unwind_frame would also yield the asyncio runtime frames "on top" // of the Task frame, but we would discard those anyway. Limiting to 1 frame avoids walking // the Frame chain unnecessarily. - auto unwind_result = unwind_frame(echion, frame, stack, echion.seen_frames_scratch(), 1); - assert(unwind_result.frames_added <= 1 && "expected exactly 1 frame to be unwound (or 0 in case of an error)"); + auto frame_unwind_result = unwind_frame(echion, frame, stack, echion.seen_frames_scratch(), 1, false); + assert(frame_unwind_result.frames_added <= 1 && + "expected exactly 1 frame to be unwound (or 0 in case of an error)"); // If we failed to unwind the Frame, stop unwinding the coroutine chain; otherwise we could // end up with Stacks with missing Frames between two coroutines Frames. - if (unwind_result.frames_added == 0) { + if (frame_unwind_result.frames_added == 0) { break; } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 704a411bca6..be335957b1d 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -832,7 +832,7 @@ 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); + task_stack_info->stack.render(echion, false); renderer.render_stack_end(); } @@ -844,7 +844,7 @@ ThreadInfo::render_unwound_stacks(EchionSampler& echion) }); auto& stack = greenlet_stack->stack; - stack.render(echion); + stack.render(echion, false); renderer.render_stack_end(); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp index c23a0776b3c..3d9b2069560 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp @@ -573,7 +573,7 @@ Sampler::set_max_frames(uint64_t value) // Zero preserves the existing exporter behavior: retain the default limit. const size_t requested = value == 0 ? g_default_max_nframes : static_cast(value); - echion->configure_max_frames(requested); + echion->set_max_frames(requested); return true; } @@ -592,7 +592,7 @@ Sampler::frame_cache_capacity() const Sampler::Sampler() : echion{ std::make_unique(g_default_echion_frame_cache_size) } { - echion->configure_max_frames(g_default_max_nframes); + echion->set_max_frames(g_default_max_nframes); } Sampler& From 0b6cd5eaec1ddd13b9d547077824366e3ed351f2 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Wed, 19 Aug 2026 15:44:32 +0000 Subject: [PATCH 09/28] refactor(profiling): make truncation status explicit --- .../profiling/stack/echion/echion/stacks.h | 11 ++++++++-- .../profiling/stack/src/echion/stacks.cc | 22 +++++++++++-------- .../profiling/stack/src/echion/threads.cc | 6 ++--- 3 files changed, 25 insertions(+), 14 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index dfcc4023bb4..92a2d2be1f2 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -22,10 +22,17 @@ class EchionSampler; +enum class TruncationStatus +{ + Unchecked, + NotTruncated, + Truncated, +}; + struct UnwindResult { size_t frames_added = 0; - bool truncated = false; + TruncationStatus truncation = TruncationStatus::Unchecked; }; // ---------------------------------------------------------------------------- @@ -37,7 +44,7 @@ class FrameStack : public std::vector public: using Key = Frame::Key; - void render(EchionSampler& echion, bool truncated); + void render(EchionSampler& echion, TruncationStatus truncation); }; // Forward declaration diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index 9babaa24ce6..e4c2aba2224 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -6,7 +6,7 @@ #include "dd_wrapper/include/profiler_state.hpp" void -FrameStack::render(EchionSampler& echion, bool truncated) +FrameStack::render(EchionSampler& echion, TruncationStatus truncation) { auto& renderer = echion.renderer(); auto& registry = Datadog::ProfilerState::get().native_call_registry; @@ -29,7 +29,7 @@ FrameStack::render(EchionSampler& echion, bool truncated) renderer.render_frame(frame); } - if (truncated) { + if (truncation == TruncationStatus::Truncated) { renderer.render_truncated(); } } @@ -39,7 +39,7 @@ FrameStack::render(EchionSampler& echion, bool truncated) // by callers (typically EchionSampler::seen_frames_scratch). // @param max_frames_to_add: Maximum number of frames to add during this walk. // @param detect_truncation: Whether to probe for another reportable frame after reaching the limit. -// @return: Number of frames added and whether another reportable frame was found. +// @return: Number of frames added and the truncation detection status. UnwindResult unwind_frame(EchionSampler& echion, PyObject* frame_addr, @@ -60,12 +60,13 @@ unwind_frame(EchionSampler& echion, const bool at_limit = result.frames_added >= max_frames_to_add || stack.size() >= MAX_TASK_FRAMES; if (at_limit) { if (!detect_truncation || frames_probed_after_limit >= MAX_TASK_FRAMES) { - break; + return result; } frames_probed_after_limit++; } - if (seen_frames.contains(current_frame_addr)) - break; + if (seen_frames.contains(current_frame_addr)) { + return result; + } seen_frames.insert(current_frame_addr); @@ -77,7 +78,7 @@ unwind_frame(EchionSampler& echion, auto maybe_frame = Frame::read(echion, current_frame_addr, ¤t_frame_addr); #endif if (!maybe_frame) { - break; + return result; } if (maybe_frame->get().name == StringTable::C_FRAME) { @@ -87,14 +88,17 @@ unwind_frame(EchionSampler& echion, // When reporting truncation, confirm that the bounded lookahead found a // reportable frame so terminal C/interpreter frames do not produce a false marker. if (at_limit) { - result.truncated = true; - break; + result.truncation = TruncationStatus::Truncated; + return result; } stack.push_back(maybe_frame->get()); result.frames_added++; } + if (detect_truncation) { + result.truncation = TruncationStatus::NotTruncated; + } return result; } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index be335957b1d..77edd8f6912 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -832,7 +832,7 @@ 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, false); + task_stack_info->stack.render(echion, TruncationStatus::Unchecked); renderer.render_stack_end(); } @@ -844,12 +844,12 @@ ThreadInfo::render_unwound_stacks(EchionSampler& echion) }); auto& stack = greenlet_stack->stack; - stack.render(echion, false); + stack.render(echion, TruncationStatus::Unchecked); renderer.render_stack_end(); } } else { - python_stack.render(echion, python_stack_unwind_result.truncated); + python_stack.render(echion, python_stack_unwind_result.truncation); renderer.render_stack_end(); } } From fb910b6c9f5ea5123cccabb26a80a73f7d4d31b3 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Wed, 19 Aug 2026 17:59:30 +0000 Subject: [PATCH 10/28] refactor(profiling): align plain stack default --- .../datadog/profiling/stack/echion/echion/echion_sampler.h | 2 +- ddtrace/internal/datadog/profiling/stack/src/sampler.cpp | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) 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 f8d553dd23b..5d7ac4136ed 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h @@ -59,7 +59,7 @@ class EchionSampler size_t asyncio_task_count_ = 0; // Maximum number of frames to collect for plain thread stacks. - size_t stack_max_frames_ = MAX_TASK_FRAMES; + size_t stack_max_frames_ = g_default_max_nframes; // Maximum number of leaf tasks / greenlets to unwind and emit per cycle. // 0 means unlimited. diff --git a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp index 3d9b2069560..69c85520bc1 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp @@ -592,7 +592,6 @@ Sampler::frame_cache_capacity() const Sampler::Sampler() : echion{ std::make_unique(g_default_echion_frame_cache_size) } { - echion->set_max_frames(g_default_max_nframes); } Sampler& From 28ec6bd4a61488c071e50579eabe0e4d40930c8d Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Wed, 15 Jul 2026 18:42:05 +0000 Subject: [PATCH 11/28] perf(profiling): bound task stack collection --- .../profiling/stack/echion/echion/cache.h | 20 +- .../profiling/stack/echion/echion/config.h | 5 +- .../stack/echion/echion/echion_sampler.h | 10 +- .../profiling/stack/echion/echion/stacks.h | 10 +- .../profiling/stack/echion/echion/tasks.h | 8 +- .../profiling/stack/echion/echion/threads.h | 3 + .../profiling/stack/include/constants.hpp | 7 +- .../stack/include/stack_renderer.hpp | 1 + .../profiling/stack/src/echion/stacks.cc | 28 +- .../profiling/stack/src/echion/tasks.cc | 16 +- .../profiling/stack/src/echion/threads.cc | 356 ++++++++++-------- .../datadog/profiling/stack/src/sampler.cpp | 17 +- .../profiling/stack/src/stack_renderer.cpp | 11 + ...nd-task-stack-frames-5c8460b0d7e2118f.yaml | 4 + .../test_asyncio_task_frame_budget.py | 179 +++++++++ tests/profiling/collector/test_stack.py | 11 +- 16 files changed, 503 insertions(+), 183 deletions(-) create mode 100644 releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml create mode 100644 tests/profiling/collector/test_asyncio_task_frame_budget.py diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/cache.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/cache.h index 695159f431e..a0a3b06066f 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/cache.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/cache.h @@ -4,6 +4,7 @@ #pragma once +#include #include #include #include @@ -11,14 +12,12 @@ #include -#define CACHE_MAX_ENTRIES 2048 - template class LRUCache { public: LRUCache(size_t capacity) - : capacity(capacity) + : capacity_(std::max(capacity, 1)) { } @@ -26,6 +25,17 @@ class LRUCache void store(const K& k, std::unique_ptr v); + void set_capacity(size_t capacity) + { + capacity_ = std::max(capacity, 1); + while (items.size() > capacity_) { + index.erase(items.back().first); + items.pop_back(); + } + } + + [[nodiscard]] size_t capacity() const { return capacity_; } + void clear() { items.clear(); @@ -44,7 +54,7 @@ class LRUCache } private: - size_t capacity; + size_t capacity_; std::list>> items; std::unordered_map>>::iterator> index; }; @@ -54,7 +64,7 @@ void LRUCache::store(const K& k, std::unique_ptr v) { // Check if cache is full - if (items.size() >= capacity) { + if (items.size() >= capacity_) { index.erase(items.back().first); items.pop_back(); } diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/config.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/config.h index 94b25aa8bd4..a86e0623f14 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/config.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/config.h @@ -4,5 +4,6 @@ #pragma once -// Safety limit for Python frames collected while discovering and stitching task-aware stacks. -inline constexpr unsigned int MAX_TASK_FRAMES = 2048; +// Hard safety bound for physical stack discovery. Reportable sync and task +// frame materialization is separately bounded by DD_PROFILING_MAX_FRAMES. +inline constexpr unsigned int MAX_STACK_DISCOVERY_DEPTH = 2048; 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 5d7ac4136ed..766caca67d1 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h @@ -58,7 +58,7 @@ class EchionSampler // Only accessed from the sampling thread, so no lock/atomic is needed. 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. @@ -115,7 +115,12 @@ class EchionSampler void add_asyncio_task_count(size_t count) { asyncio_task_count_ += count; } size_t asyncio_task_count() const { return asyncio_task_count_; } - void set_max_frames(size_t max_frames) { stack_max_frames_ = std::max(max_frames, 1); } + void configure_frame_limits(size_t max_frames, size_t frame_cache_capacity) + { + stack_max_frames_ = std::max(max_frames, 1); + frame_cache_.set_capacity(frame_cache_capacity); + } + [[nodiscard]] size_t stack_max_frames() const { return stack_max_frames_; } unsigned int max_tasks_per_sample() const { return max_tasks_per_sample_; } @@ -129,6 +134,7 @@ class EchionSampler // Accessor for frame cache operations LRUCache& frame_cache() { return frame_cache_; } + [[nodiscard]] size_t frame_cache_capacity() const { return frame_cache_.capacity(); } void postfork_child() { diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index 92a2d2be1f2..59eb0046ff2 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -44,9 +44,15 @@ class FrameStack : public std::vector public: using Key = Frame::Key; - void render(EchionSampler& echion, TruncationStatus truncation); + void render(EchionSampler& echion, + TruncationStatus truncation, + size_t omission_index = SIZE_MAX, + size_t omitted_frames = 0); }; +[[nodiscard]] size_t +rendered_location_count(const Frame& frame); + // Forward declaration class EchionSampler; @@ -88,6 +94,8 @@ class StackInfo uint64_t task_id; bool on_cpu; FrameStack stack; + size_t omission_index = SIZE_MAX; + size_t omitted_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..3b719dc721b 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h @@ -102,6 +102,12 @@ class GenInfo // ---------------------------------------------------------------------------- +struct TaskUnwindResult +{ + size_t retained = 0; + size_t depth = 0; +}; + class TaskInfo { public: @@ -145,7 +151,7 @@ class TaskInfo { } - size_t unwind(EchionSampler& echion, FrameStack&, bool using_uvloop); + TaskUnwindResult unwind(EchionSampler& echion, FrameStack&, 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 4130e3865dc..98451673b85 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 @@ -58,6 +59,7 @@ 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 + std::optional asyncio_boundary_index; [[nodiscard]] Result update_cpu_time(); @@ -117,6 +119,7 @@ class ThreadInfo private: 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/include/constants.hpp b/ddtrace/internal/datadog/profiling/stack/include/constants.hpp index 4cf3ab125b9..c3d311ee211 100644 --- a/ddtrace/internal/datadog/profiling/stack/include/constants.hpp +++ b/ddtrace/internal/datadog/profiling/stack/include/constants.hpp @@ -19,5 +19,8 @@ constexpr unsigned int g_default_max_threads_per_sample = 25; // leaf tasks exceeds this, reservoir sampling is used. 0 means sample all tasks. constexpr unsigned int g_default_max_tasks_per_sample = 50; -// Echion maintains a cache of frames--the size of this cache is specified up-front. -constexpr unsigned int g_default_echion_frame_cache_size = 1024; +// Echion retains recently rendered frames across stack walks. Scale the cache with +// the configured stack depth while bounding both churn and retained memory. +constexpr unsigned int g_min_echion_frame_cache_size = 256; +constexpr unsigned int g_max_echion_frame_cache_size = 1024; +constexpr unsigned int g_echion_frame_cache_size_multiplier = 4; diff --git a/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp b/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp index 143588dc243..6eac811cf11 100644 --- a/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp +++ b/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp @@ -94,6 +94,7 @@ class StackRenderer std::optional walltime_ns_override = std::nullopt); void render_frame(Frame& frame); void render_truncated(); + void render_omitted_frames(size_t count); void render_cpu_time(microsecond_t cpu_time_us); void render_native_frame(const std::string& name, const std::string& module); void render_stack_end(); diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index e4c2aba2224..323f967937f 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -5,14 +5,33 @@ #include "dd_wrapper/include/profiler_state.hpp" +size_t +rendered_location_count(const Frame& frame) +{ + if (frame.code_object == 0 || frame.lasti < 0) { + return 1; + } + + 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) ? 2 : 1; +} + void -FrameStack::render(EchionSampler& echion, TruncationStatus truncation) +FrameStack::render(EchionSampler& echion, + TruncationStatus truncation, + size_t omission_index, + size_t omitted_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 == omission_index) { + renderer.render_omitted_frames(omitted_frames); + } + + auto& frame = (*this)[i]; // Inject native frame BEFORE its Python caller. // sys.monitoring reports instruction offsets in bytes, while the sampler computes @@ -29,6 +48,9 @@ FrameStack::render(EchionSampler& echion, TruncationStatus truncation) renderer.render_frame(frame); } + if (omission_index == size()) { + renderer.render_omitted_frames(omitted_frames); + } if (truncation == TruncationStatus::Truncated) { renderer.render_truncated(); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc index 250953f3e65..909687015a5 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc @@ -228,8 +228,8 @@ is_uvloop_wrapper_frame(EchionSampler& echion, bool using_uvloop, const Frame& f #endif } -size_t -TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop) +TaskUnwindResult +TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop, size_t max_depth) { // TODO: Check for running task. (void)echion; @@ -250,11 +250,10 @@ TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop) } } - // Total number of frames added to the Stack - size_t count = 0; + TaskUnwindResult result{ 0, coro_frames.size() }; - // Unwind the coro frames - while (!coro_frames.empty()) { + // Unwind only the frames that can contribute to this task's output. + while (!coro_frames.empty() && result.retained < max_depth) { PyObject* frame = coro_frames.top(); coro_frames.pop(); @@ -276,11 +275,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(); + result.depth--; continue; } - count += 1; + result.retained++; } - return count; + return result; } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 77edd8f6912..57962b054e6 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -11,6 +11,23 @@ #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; +} +} // namespace + void ThreadInfo::reset_cycle_state() noexcept { @@ -24,13 +41,21 @@ 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_TASK_FRAMES : echion.stack_max_frames(); + const size_t max_frames = echion.stack_max_frames(); python_stack_unwind_result = unwind_python_stack(echion, tstate, python_stack, max_frames); + asyncio_boundary_index.reset(); if (asyncio_loop) { + // Boundary discovery is limited to the physical frames that can be + // reported. If an on-CPU boundary lies beyond the budget, unwind_tasks + // reports task context alone rather than stitching unknown overlap. + 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); @@ -42,14 +67,9 @@ ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate, microsecond_t w } } -// ---------------------------------------------------------------------------- -Result -ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microsecond_t wall_time_us) +bool +ThreadInfo::is_asyncio_boundary_frame(EchionSampler& echion, const Frame& frame) { - // The size of the "pure Python" stack (before asyncio Frames). - // 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). @@ -63,79 +83,62 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco auto& frame_cache_key = using_uvloop ? uvloop_frame_cache_key : asyncio_frame_cache_key; - if (!frame_cache_key) { - for (size_t i = 0; i < python_stack.size(); i++) { - const auto& frame = python_stack[i]; - auto maybe_frame_name = echion.string_table().lookup(frame.name); - if (!maybe_frame_name) { - continue; - } - const auto& frame_name = maybe_frame_name->get(); + if (frame_cache_key) { + return frame.cache_key == *frame_cache_key; + } - bool is_boundary_frame = false; + 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()); + 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 - } + } - if (is_boundary_frame) { - // Although Frames are stored in an LRUCache, the cache key is ALWAYS the same - // even if the Frame gets evicted from the cache. - // This means we can keep the cache key and reuse it to determine - // whether we see the boundary Frame in the Python stack. - frame_cache_key = frame.cache_key; - upper_python_stack_size = python_stack.size() - i; - break; - } - } - } else { - for (size_t i = 0; i < python_stack.size(); i++) { - const auto& frame = python_stack[i]; - if (frame.cache_key == *frame_cache_key) { - upper_python_stack_size = python_stack.size() - i; - break; - } - } + if (is_boundary_frame) { + frame_cache_key = frame.cache_key; } + return is_boundary_frame; +} +// ---------------------------------------------------------------------------- +Result +ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microsecond_t wall_time_us) +{ std::vector leaf_tasks; std::unordered_set parent_tasks; std::unordered_map waitee_map; // Indexed by task origin @@ -230,15 +233,21 @@ 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(); + 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; + auto result = task->unwind(echion, cached.frames, using_uvloop, max_frames); + cached.depth = result.depth; + 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. @@ -295,78 +304,45 @@ 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; + bool has_on_cpu_task = false; + + // 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(); - // 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_TASK_FRAMES) { - task_frames_to_push = std::min(task_stack_size, MAX_TASK_FRAMES - 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++) { - const 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; - } - stack.push_back(python_frame); - } - } - if (task_stack != nullptr) { - for (size_t i = 0; i < task_frames_to_push; i++) { - stack.push_back((*task_stack)[i]); + const auto& cached = it->second; + const size_t frames_to_push = std::min(cached.frames.size(), max_frames - task_frames.size()); + task_frames.insert(task_frames.end(), cached.frames.begin(), cached.frames.begin() + frames_to_push); + if (task.is_on_cpu) { + has_on_cpu_task = true; + 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(); @@ -374,36 +350,109 @@ 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. + // AIDEV-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. A Python frame can + // inject one native location, so counting Frame objects alone can let a + // lower-priority physical segment displace task context in the exporter. + const bool task_collection_full = task_frames.size() >= max_frames; + size_t task_locations = 0; + const size_t task_to_keep = select_frame_prefix(task_frames, 0, task_frames.size(), max_frames, task_locations); + const bool task_truncated = task_collection_full || task_to_keep < task_frames.size(); + task_frames.erase(task_frames.begin() + task_to_keep, task_frames.end()); + + // Task frames receive the reporting budget first. If capacity remains, + // fill it with physical context. For an on-CPU task, split that context + // around the coroutine frames replaced by task_frames: + // + // synchronous leaf frames, logical task frames, event-loop roots + // + // Synchronous leaf frames have priority over event-loop roots. + if (task_truncated || (has_on_cpu_task && !asyncio_boundary_index)) { + stack_info->stack = std::move(task_frames); + } else { + auto& stack = stack_info->stack; + size_t locations = task_locations; + + if (has_on_cpu_task && 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 leaf_available = std::min(leaf_depth, python_stack.size()); + const size_t runtime_start = std::min(*asyncio_boundary_index, python_stack.size()); + const size_t runtime_available = python_stack.size() - runtime_start; + + size_t leaf_to_keep = select_frame_prefix(python_stack, 0, leaf_available, max_frames, locations); + size_t runtime_to_keep = + select_frame_prefix(python_stack, runtime_start, runtime_available, max_frames, locations); + bool leaf_truncated = leaf_depth > leaf_to_keep; + bool runtime_truncated = runtime_available > runtime_to_keep; + + // An omission marker consumes one location. Remove the + // lowest-priority selected physical frame if the real locations + // have already filled the budget. + if ((leaf_truncated || runtime_truncated) && locations >= max_frames) { + if (runtime_to_keep > 0) { + runtime_to_keep--; + locations -= rendered_location_count(python_stack[runtime_start + runtime_to_keep]); + } else if (leaf_to_keep > 0) { + leaf_to_keep--; + locations -= rendered_location_count(python_stack[leaf_to_keep]); + } + leaf_truncated = leaf_depth > leaf_to_keep; + runtime_truncated = runtime_available > runtime_to_keep; + } + + stack.insert(stack.end(), python_stack.begin(), python_stack.begin() + leaf_to_keep); + if (leaf_truncated) { + stack_info->omission_index = stack.size(); + stack_info->omitted_frames = leaf_depth - leaf_to_keep; + } + stack.insert(stack.end(), task_frames.begin(), task_frames.end()); + stack.insert(stack.end(), + python_stack.begin() + runtime_start, + python_stack.begin() + runtime_start + runtime_to_keep); + if (!leaf_truncated && runtime_truncated) { + stack_info->omission_index = stack.size(); + stack_info->omitted_frames = runtime_available - runtime_to_keep; + } + } else { + // An off-CPU task is followed by the event-loop thread stack. + size_t sync_to_keep = select_frame_prefix(python_stack, 0, python_stack.size(), max_frames, locations); + bool sync_truncated = python_stack.size() > sync_to_keep; + if (sync_truncated && locations >= max_frames && sync_to_keep > 0) { + sync_to_keep--; + locations -= rendered_location_count(python_stack[sync_to_keep]); + } - // 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; - } - for (size_t i = start_index; i < python_stack.size(); i++) { - const auto& python_frame = python_stack[i]; - stack.push_back(python_frame); + stack = std::move(task_frames); + stack.insert(stack.end(), python_stack.begin(), python_stack.begin() + sync_to_keep); + if (sync_truncated) { + stack_info->omission_index = stack.size(); + stack_info->omitted_frames = python_stack.size() - sync_to_keep; + } + } } current_tasks.push_back(std::move(stack_info)); @@ -832,7 +881,10 @@ 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::Unchecked); + task_stack_info->stack.render(echion, + TruncationStatus::Unchecked, + task_stack_info->omission_index, + task_stack_info->omitted_frames); renderer.render_stack_end(); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp index 69c85520bc1..b8f0fc7b6a7 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp @@ -96,6 +96,17 @@ create_thread_with_stack(size_t stack_size, Sampler* sampler, uint64_t seq_num) namespace { +size_t +calculate_frame_cache_capacity(size_t max_frames) +{ + if (max_frames >= g_max_echion_frame_cache_size / g_echion_frame_cache_size_multiplier) { + return g_max_echion_frame_cache_size; + } + + const size_t scaled = max_frames * g_echion_frame_cache_size_multiplier; + return std::max(scaled, static_cast(g_min_echion_frame_cache_size)); +} + // Returns the CPU time of the calling thread in microseconds, or 0 on error. uint64_t get_thread_cpu_time_us() @@ -573,7 +584,7 @@ Sampler::set_max_frames(uint64_t value) // Zero preserves the existing exporter behavior: retain the default limit. const size_t requested = value == 0 ? g_default_max_nframes : static_cast(value); - echion->set_max_frames(requested); + echion->configure_frame_limits(requested, calculate_frame_cache_capacity(requested)); return true; } @@ -586,11 +597,11 @@ Sampler::max_frames() const size_t Sampler::frame_cache_capacity() const { - return g_default_echion_frame_cache_size; + return echion->frame_cache_capacity(); } Sampler::Sampler() - : echion{ std::make_unique(g_default_echion_frame_cache_size) } + : echion{ std::make_unique(calculate_frame_cache_capacity(g_default_max_nframes)) } { } diff --git a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp index e29302d0476..d6f165169c7 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp @@ -218,6 +218,17 @@ StackRenderer::render_truncated() } } +void +StackRenderer::render_omitted_frames(size_t count) +{ + if (sample == nullptr || count == 0) { + return; + } + + const std::string name = "<" + std::to_string(count) + " synchronous frame" + (count == 1 ? "" : "s") + " omitted>"; + sample->push_frame(name, "", 0, 0); +} + void StackRenderer::render_native_frame(const std::string& name, const std::string& module) { 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..1261cb30229 --- /dev/null +++ b/releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml @@ -0,0 +1,4 @@ +--- +fixes: + - | + profiling: This fix reduces profiler CPU and memory overhead for asyncio applications by limiting collected task and synchronous stack frames to ``DD_PROFILING_MAX_FRAMES``. When both are present, logical task frames are prioritized and remaining capacity retains synchronous execution context. 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..3ee17a27c98 --- /dev/null +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -0,0 +1,179 @@ +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 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 async_main() -> None: + deep_sync(20) + + 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-1": + actual.append( + [ + pprof_utils.get_location_from_id(profile, location_id).function_name + for location_id in sample.location_id + ] + ) + + assert ["async_main"] 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 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 names[-1].startswith("<") and "synchronous frame" in names[-1] + for names in actual + ), actual diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index 017f239b4bd..e8f0a374223 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -84,7 +84,7 @@ def test_collect_truncate() -> None: p = profiler.Profiler() p.start() - assert _stack._get_frame_limits() == (max_nframes, 1024) + assert _stack._get_frame_limits() == (max_nframes, 256) func1() @@ -106,14 +106,17 @@ def test_collect_truncate() -> None: @pytest.mark.subprocess -def test_native_frame_limit() -> None: +def test_native_frame_limit_scales_cache() -> None: from ddtrace.internal.datadog.profiling.stack import _stack _stack.set_max_frames(0) - assert _stack._get_frame_limits() == (64, 1024) + assert _stack._get_frame_limits() == (64, 256) _stack.set_max_frames(65) - assert _stack._get_frame_limits() == (65, 1024) + assert _stack._get_frame_limits() == (65, 260) + + _stack.set_max_frames(512) + assert _stack._get_frame_limits() == (512, 1024) _stack.set_max_frames(10_000) assert _stack._get_frame_limits() == (10_000, 1024) From aaadf06a4197c9553fb8f74ad76eca412dcba691 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Wed, 15 Jul 2026 20:26:24 +0000 Subject: [PATCH 12/28] fix(profiling): resolve clang-tidy issues --- .../stack/fuzz/fuzz_echion_stacks.cpp | 2 +- .../stack/fuzz/fuzz_echion_task_unwind.cpp | 2 +- .../profiling/stack/src/echion/greenlets.cc | 2 +- .../profiling/stack/src/echion/stacks.cc | 11 ++-- .../profiling/stack/src/echion/threads.cc | 30 ++++++----- .../test_asyncio_task_frame_budget.py | 22 ++++---- tests/profiling/collector/test_stack.py | 51 +++---------------- 7 files changed, 40 insertions(+), 80 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp index e6917b6d4ee..66a395238af 100644 --- a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp +++ b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_stacks.cpp @@ -50,7 +50,7 @@ LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) tstate.datastack_chunk = reinterpret_cast<_PyStackChunk*>(p2); #endif FrameStack fuzz_stack; - unwind_python_stack(echion_sampler, &tstate, fuzz_stack, MAX_TASK_FRAMES); + unwind_python_stack(echion_sampler, &tstate, fuzz_stack, MAX_STACK_DISCOVERY_DEPTH); } g_data = nullptr; 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 426c2e6f8e4..8a43545ca5e 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 @@ -34,7 +34,7 @@ LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) auto maybe_task = TaskInfo::create(echion_sampler, reinterpret_cast(p0)); if (maybe_task) { FrameStack stack; - (void)(*maybe_task)->unwind(echion_sampler, stack, using_uvloop); + (void)(*maybe_task)->unwind(echion_sampler, stack, using_uvloop, MAX_STACK_DISCOVERY_DEPTH); } g_data = nullptr; diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/greenlets.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/greenlets.cc index 4581f737207..809282b6b0d 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/greenlets.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/greenlets.cc @@ -40,5 +40,5 @@ GreenletInfo::unwind(EchionSampler& echion, PyObject* cur_frame, PyThreadState* #else // Python < 3.11 frame_addr = cur_frame == Py_None ? reinterpret_cast(tstate->frame) : cur_frame; #endif - unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), MAX_TASK_FRAMES, false); + unwind_frame(echion, frame_addr, stack, echion.seen_frames_scratch(), MAX_STACK_DISCOVERY_DEPTH, false); } diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index 323f967937f..66cbcc1a3a8 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -18,10 +18,7 @@ rendered_location_count(const Frame& frame) } void -FrameStack::render(EchionSampler& echion, - TruncationStatus truncation, - size_t omission_index, - size_t omitted_frames) +FrameStack::render(EchionSampler& echion, TruncationStatus truncation, size_t omission_index, size_t omitted_frames) { auto& renderer = echion.renderer(); auto& registry = Datadog::ProfilerState::get().native_call_registry; @@ -71,7 +68,7 @@ unwind_frame(EchionSampler& echion, bool detect_truncation) { seen_frames.clear(); - if (!detect_truncation && (max_frames_to_add == 0 || stack.size() >= MAX_TASK_FRAMES)) { + if (!detect_truncation && (max_frames_to_add == 0 || stack.size() >= MAX_STACK_DISCOVERY_DEPTH)) { return UnwindResult{}; } @@ -79,9 +76,9 @@ unwind_frame(EchionSampler& echion, size_t frames_probed_after_limit = 0; PyObject* current_frame_addr = frame_addr; while (current_frame_addr != NULL) { - const bool at_limit = result.frames_added >= max_frames_to_add || stack.size() >= MAX_TASK_FRAMES; + const bool at_limit = result.frames_added >= max_frames_to_add || stack.size() >= MAX_STACK_DISCOVERY_DEPTH; if (at_limit) { - if (!detect_truncation || frames_probed_after_limit >= MAX_TASK_FRAMES) { + if (!detect_truncation || frames_probed_after_limit >= MAX_STACK_DISCOVERY_DEPTH) { return result; } frames_probed_after_limit++; diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 57962b054e6..986cbf622ff 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -324,7 +324,9 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco if (auto it = task_coro_stacks.find(task.origin); it != task_coro_stacks.end()) { const auto& cached = it->second; const size_t frames_to_push = std::min(cached.frames.size(), max_frames - task_frames.size()); - task_frames.insert(task_frames.end(), cached.frames.begin(), cached.frames.begin() + frames_to_push); + task_frames.insert(task_frames.end(), + cached.frames.begin(), + cached.frames.begin() + static_cast(frames_to_push)); if (task.is_on_cpu) { has_on_cpu_task = true; on_cpu_task_depth = cached.depth; @@ -381,7 +383,8 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco size_t task_locations = 0; const size_t task_to_keep = select_frame_prefix(task_frames, 0, task_frames.size(), max_frames, task_locations); const bool task_truncated = task_collection_full || task_to_keep < task_frames.size(); - task_frames.erase(task_frames.begin() + task_to_keep, task_frames.end()); + 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. For an on-CPU task, split that context @@ -415,24 +418,26 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco if ((leaf_truncated || runtime_truncated) && locations >= max_frames) { if (runtime_to_keep > 0) { runtime_to_keep--; - locations -= rendered_location_count(python_stack[runtime_start + runtime_to_keep]); } else if (leaf_to_keep > 0) { leaf_to_keep--; - locations -= rendered_location_count(python_stack[leaf_to_keep]); } leaf_truncated = leaf_depth > leaf_to_keep; runtime_truncated = runtime_available > runtime_to_keep; } - stack.insert(stack.end(), python_stack.begin(), python_stack.begin() + leaf_to_keep); + stack.insert(stack.end(), + python_stack.begin(), + python_stack.begin() + static_cast(leaf_to_keep)); if (leaf_truncated) { stack_info->omission_index = stack.size(); stack_info->omitted_frames = leaf_depth - leaf_to_keep; } stack.insert(stack.end(), task_frames.begin(), task_frames.end()); + const auto runtime_begin = + python_stack.begin() + static_cast(runtime_start); stack.insert(stack.end(), - python_stack.begin() + runtime_start, - python_stack.begin() + runtime_start + runtime_to_keep); + runtime_begin, + runtime_begin + static_cast(runtime_to_keep)); if (!leaf_truncated && runtime_truncated) { stack_info->omission_index = stack.size(); stack_info->omitted_frames = runtime_available - runtime_to_keep; @@ -443,11 +448,12 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco bool sync_truncated = python_stack.size() > sync_to_keep; if (sync_truncated && locations >= max_frames && sync_to_keep > 0) { sync_to_keep--; - locations -= rendered_location_count(python_stack[sync_to_keep]); } stack = std::move(task_frames); - stack.insert(stack.end(), python_stack.begin(), python_stack.begin() + sync_to_keep); + stack.insert(stack.end(), + python_stack.begin(), + python_stack.begin() + static_cast(sync_to_keep)); if (sync_truncated) { stack_info->omission_index = stack.size(); stack_info->omitted_frames = python_stack.size() - sync_to_keep; @@ -881,10 +887,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::Unchecked, - task_stack_info->omission_index, - task_stack_info->omitted_frames); + task_stack_info->stack.render( + echion, TruncationStatus::Unchecked, task_stack_info->omission_index, task_stack_info->omitted_frames); renderer.render_stack_end(); } diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index 3ee17a27c98..ec5759e397a 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -71,6 +71,7 @@ async def async_main() -> None: err=None, ) def test_deep_sync_stack_does_not_hide_task_context() -> None: + import asyncio import os import time @@ -90,9 +91,12 @@ def deep_sync(depth: int) -> None: while time.time() < deadline: pass - async def async_main() -> None: + 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()) @@ -101,18 +105,12 @@ async def async_main() -> None: 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-1": - actual.append( - [ - pprof_utils.get_location_from_id(profile, location_id).function_name - for location_id in sample.location_id - ] - ) + 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 ["async_main"] in actual, actual + assert any("deep_task" in names for names in actual), actual @pytest.mark.subprocess( diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index e8f0a374223..176080b9aee 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -210,12 +210,10 @@ def test_set_max_frames_after_fork_restart() -> None: @pytest.mark.subprocess( - env=dict( - DD_PROFILING_OUTPUT_PPROF="/tmp/test_asyncio_native_frame_limit", - ), + env={"DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_native_frame_limit"}, err=None, ) -def test_asyncio_discovery_ignores_plain_stack_limit() -> None: +def test_asyncio_collection_honors_frame_limit() -> None: import asyncio import os import time @@ -226,69 +224,32 @@ def test_asyncio_discovery_ignores_plain_stack_limit() -> None: 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.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) - def sync_outer() -> None: - sync_leaf() - async def inner() -> None: - sync_outer() + sync_leaf() async def outer() -> None: await inner() with stack.StackCollector(nframes=1): - assert _stack._get_frame_limits() == (1, 1024) - sync_outer() + assert _stack._get_frame_limits() == (1, 256) asyncio.run(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("<") - ] - 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 - 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), - ], + locations=[pprof_utils.StackLocation(function_name="outer", filename="", line_no=-1)], ), print_samples_on_failure=True, ) From b8284b13b37fa420b9a6590dc8a2d2186ad1356f Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Wed, 9 Sep 2026 19:09:53 +0000 Subject: [PATCH 13/28] fix(profiling): handle fuzz unwind result and separate release-note update --- .../datadog/profiling/stack/fuzz/fuzz_echion_thread_unwind.cpp | 2 +- .../notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_thread_unwind.cpp b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_thread_unwind.cpp index d6fe6e8d9b5..c263bb72f3c 100644 --- a/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_thread_unwind.cpp +++ b/ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_thread_unwind.cpp @@ -37,7 +37,7 @@ LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) // Only flexes the "unwind thread stack" path, greenlets // and asyncio aren't used here - thread.unwind(echion_sampler, &tstate, 0); + (void)thread.unwind(echion_sampler, &tstate, 0); g_data = nullptr; g_size = 0; diff --git a/releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml b/releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml index 7af36d9db7b..1bd4ed0c590 100644 --- a/releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml +++ b/releasenotes/notes/profiling-propagate-max-frames-f7a718abdfb99c4c.yaml @@ -1,4 +1,4 @@ --- fixes: - | - profiling: This fix reduces profiler memory and CPU overhead by limiting plain thread stack collection to ``DD_PROFILING_MAX_FRAMES`` while retaining the deeper internal discovery needed to reconstruct asyncio task stacks. + profiling: This fix reduces profiler memory and CPU overhead by truncating stacks at the configured limits. From eb7cc2a415487fd0b3756d15fafdb81a3275d75b Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Thu, 10 Sep 2026 16:10:44 +0000 Subject: [PATCH 14/28] refactor(profiling): rename unknown truncation state --- .../datadog/profiling/stack/echion/echion/stacks.h | 10 +++++----- .../datadog/profiling/stack/echion/echion/threads.h | 2 +- .../datadog/profiling/stack/src/echion/stacks.cc | 4 ++-- .../datadog/profiling/stack/src/echion/threads.cc | 6 +++--- .../profiling/stack/test/test_sampling_cycle_state.cpp | 10 +++++----- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index dacc40ef613..d9be0acd6ce 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -25,7 +25,7 @@ class EchionSampler; enum class TruncationStatus { // Detection was disabled or could not finish safely. - Unchecked, + Unknown, NotTruncated, Truncated, }; @@ -33,9 +33,9 @@ enum class TruncationStatus struct UnwindResult { size_t frames_added = 0; - TruncationStatus truncation = TruncationStatus::Unchecked; + TruncationStatus truncation = TruncationStatus::Unknown; - static UnwindResult Unchecked() { return UnwindResult{ 0, TruncationStatus::Unchecked }; } + static UnwindResult Unknown() { return UnwindResult{ 0, TruncationStatus::Unknown }; } }; // ---------------------------------------------------------------------------- @@ -58,9 +58,9 @@ class EchionSampler; // the sampling thread should pass EchionSampler::seen_frames_scratch() so the // hash table's capacity is reused across calls instead of reallocated per call. // seen_frames is cleared on entry. -// Disabling detection always returns Unchecked. With detection enabled, only a +// Disabling detection always returns Unknown. With detection enabled, only a // reportable frame beyond the limit proves Truncated; reaching the end proves -// NotTruncated. An incomplete probe (read failure, cycle, or safety limit) stays Unchecked. +// NotTruncated. An incomplete probe (read failure, cycle, or safety limit) stays Unknown. UnwindResult unwind_frame(EchionSampler& echion, PyObject* frame_addr, diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h index 1a23b388ace..b23308eb94f 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h @@ -43,7 +43,7 @@ class ThreadInfo uintptr_t thread_id; unsigned long native_id; FrameStack python_stack; - UnwindResult python_stack_unwind_result = UnwindResult::Unchecked(); + UnwindResult python_stack_unwind_result = UnwindResult::Unknown(); std::vector> current_tasks; std::vector> current_greenlets; diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc index 3872812b853..8ba85c328cb 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -57,10 +57,10 @@ unwind_frame(EchionSampler& echion, { seen_frames.clear(); if (!detect_truncation && (max_frames_to_add == 0 || stack.size() >= MAX_TASK_FRAMES)) { - return UnwindResult::Unchecked(); + return UnwindResult::Unknown(); } - auto result = UnwindResult::Unchecked(); + auto result = UnwindResult::Unknown(); size_t frames_probed_after_limit = 0; PyObject* current_frame_addr = frame_addr; while (current_frame_addr != NULL) { diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 2e1a0fbdc48..1f7344aec80 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -28,7 +28,7 @@ ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate, microsecond_t w // 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_TASK_FRAMES : echion.stack_max_frames(); - python_stack_unwind_result = UnwindResult::Unchecked(); + python_stack_unwind_result = UnwindResult::Unknown(); auto frame_unwind_result = unwind_python_stack(echion, tstate, python_stack, max_frames); if (!frame_unwind_result) { return frame_unwind_result.error(); @@ -864,7 +864,7 @@ 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::Unchecked); + task_stack_info->stack.render(echion, TruncationStatus::Unknown); renderer.render_stack_end(); } @@ -876,7 +876,7 @@ ThreadInfo::render_unwound_stacks(EchionSampler& echion) }); auto& stack = greenlet_stack->stack; - stack.render(echion, TruncationStatus::Unchecked); + stack.render(echion, TruncationStatus::Unknown); renderer.render_stack_end(); } diff --git a/ddtrace/internal/datadog/profiling/stack/test/test_sampling_cycle_state.cpp b/ddtrace/internal/datadog/profiling/stack/test/test_sampling_cycle_state.cpp index 5d6964217d4..a7f8db28151 100644 --- a/ddtrace/internal/datadog/profiling/stack/test/test_sampling_cycle_state.cpp +++ b/ddtrace/internal/datadog/profiling/stack/test/test_sampling_cycle_state.cpp @@ -65,20 +65,20 @@ TEST(SamplingCycleState, UnwindReplacesTaskAndGreenletStacksFromPriorCycle) EXPECT_TRUE(thread.current_greenlets.empty()); } -TEST(StackUnwind, DisabledDetectionRemainsUnchecked) +TEST(StackUnwind, DisabledDetectionRemainsUnknown) { EchionSampler echion; FrameStack stack; auto result = unwind_frame(echion, nullptr, stack, 1, false); EXPECT_EQ(result.frames_added, 0); - EXPECT_EQ(result.truncation, TruncationStatus::Unchecked); + EXPECT_EQ(result.truncation, TruncationStatus::Unknown); result = unwind_frame(echion, nullptr, stack, 1, true); EXPECT_EQ(result.truncation, TruncationStatus::NotTruncated); } #if PY_VERSION_HEX >= 0x030c0000 -TEST(StackUnwind, ProbeBudgetExhaustionRemainsUnchecked) +TEST(StackUnwind, ProbeBudgetExhaustionRemainsUnknown) { _set_pid(getpid()); EchionSampler echion; @@ -98,7 +98,7 @@ TEST(StackUnwind, ProbeBudgetExhaustionRemainsUnchecked) auto result = unwind_frame(echion, reinterpret_cast(frames.data()), stack, seen_frames, 0, true); EXPECT_EQ(seen_frames.size(), MAX_TASK_FRAMES); EXPECT_EQ(result.frames_added, 0); - EXPECT_EQ(result.truncation, TruncationStatus::Unchecked); + EXPECT_EQ(result.truncation, TruncationStatus::Unknown); // Within the probe budget, the same ignored chain can prove the stack is complete. frames[MAX_TASK_FRAMES - 1].previous = nullptr; @@ -107,7 +107,7 @@ TEST(StackUnwind, ProbeBudgetExhaustionRemainsUnchecked) result = unwind_frame(echion, reinterpret_cast(frames.data()), stack, seen_frames, 0, false); EXPECT_TRUE(seen_frames.empty()); - EXPECT_EQ(result.truncation, TruncationStatus::Unchecked); + EXPECT_EQ(result.truncation, TruncationStatus::Unknown); } #endif From d175ccdfe2cfc1b68ff8ef4d79b46dc3442cac00 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Thu, 10 Sep 2026 18:23:30 +0000 Subject: [PATCH 15/28] test(profiling): update stack discovery limit coverage --- .../profiling/stack/test/test_sampling_cycle_state.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/test/test_sampling_cycle_state.cpp b/ddtrace/internal/datadog/profiling/stack/test/test_sampling_cycle_state.cpp index a7f8db28151..0841630514a 100644 --- a/ddtrace/internal/datadog/profiling/stack/test/test_sampling_cycle_state.cpp +++ b/ddtrace/internal/datadog/profiling/stack/test/test_sampling_cycle_state.cpp @@ -83,7 +83,7 @@ TEST(StackUnwind, ProbeBudgetExhaustionRemainsUnknown) _set_pid(getpid()); EchionSampler echion; FrameStack stack; - std::vector<_PyInterpreterFrame> frames(MAX_TASK_FRAMES + 1); + std::vector<_PyInterpreterFrame> frames(MAX_STACK_DISCOVERY_DEPTH + 1); for (size_t i = 0; i < frames.size(); i++) { #if PY_VERSION_HEX >= 0x030e0000 frames[i].owner = FRAME_OWNED_BY_INTERPRETER; @@ -96,12 +96,12 @@ TEST(StackUnwind, ProbeBudgetExhaustionRemainsUnknown) // Ignored frames do not prove truncation, even when lookahead reaches its safety ceiling. std::unordered_set seen_frames; auto result = unwind_frame(echion, reinterpret_cast(frames.data()), stack, seen_frames, 0, true); - EXPECT_EQ(seen_frames.size(), MAX_TASK_FRAMES); + EXPECT_EQ(seen_frames.size(), MAX_STACK_DISCOVERY_DEPTH); EXPECT_EQ(result.frames_added, 0); EXPECT_EQ(result.truncation, TruncationStatus::Unknown); // Within the probe budget, the same ignored chain can prove the stack is complete. - frames[MAX_TASK_FRAMES - 1].previous = nullptr; + frames[MAX_STACK_DISCOVERY_DEPTH - 1].previous = nullptr; result = unwind_frame(echion, reinterpret_cast(frames.data()), stack, seen_frames, 0, true); EXPECT_EQ(result.truncation, TruncationStatus::NotTruncated); From 7f050d01c4ad140ae220e807d1687a1816f0566d Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Tue, 15 Sep 2026 20:22:54 +0000 Subject: [PATCH 16/28] docs(profiling): simplify task stack release note --- .../profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml b/releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml index 1261cb30229..6cad21f3011 100644 --- a/releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml +++ b/releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml @@ -1,4 +1,4 @@ --- fixes: - | - profiling: This fix reduces profiler CPU and memory overhead for asyncio applications by limiting collected task and synchronous stack frames to ``DD_PROFILING_MAX_FRAMES``. When both are present, logical task frames are prioritized and remaining capacity retains synchronous execution context. + profiling: Applies ``DD_PROFILING_MAX_FRAMES`` to asyncio task stacks, reducing profiler CPU and memory overhead. From 1001c2ebcb79f7de7335af3988b0c9fb7834bd10 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Mon, 21 Sep 2026 18:02:39 +0000 Subject: [PATCH 17/28] refactor(profiling): defer frame cache scaling to follow-up Keep the existing fixed 1024-entry cache throughout the task-frame-budget work. Dynamic capacity management and its test expectations remain isolated in #20351 for after the rest of the stack lands. --- .../profiling/stack/echion/echion/cache.h | 20 +++++-------------- .../stack/echion/echion/echion_sampler.h | 7 +------ .../profiling/stack/include/constants.hpp | 7 ++----- .../datadog/profiling/stack/src/sampler.cpp | 17 +++------------- tests/profiling/collector/test_stack.py | 17 +++++++--------- 5 files changed, 18 insertions(+), 50 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/cache.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/cache.h index a0a3b06066f..695159f431e 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/cache.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/cache.h @@ -4,7 +4,6 @@ #pragma once -#include #include #include #include @@ -12,12 +11,14 @@ #include +#define CACHE_MAX_ENTRIES 2048 + template class LRUCache { public: LRUCache(size_t capacity) - : capacity_(std::max(capacity, 1)) + : capacity(capacity) { } @@ -25,17 +26,6 @@ class LRUCache void store(const K& k, std::unique_ptr v); - void set_capacity(size_t capacity) - { - capacity_ = std::max(capacity, 1); - while (items.size() > capacity_) { - index.erase(items.back().first); - items.pop_back(); - } - } - - [[nodiscard]] size_t capacity() const { return capacity_; } - void clear() { items.clear(); @@ -54,7 +44,7 @@ class LRUCache } private: - size_t capacity_; + size_t capacity; std::list>> items; std::unordered_map>>::iterator> index; }; @@ -64,7 +54,7 @@ void LRUCache::store(const K& k, std::unique_ptr v) { // Check if cache is full - if (items.size() >= capacity_) { + if (items.size() >= capacity) { index.erase(items.back().first); items.pop_back(); } 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 a248a625453..f9265c80d99 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h @@ -156,11 +156,7 @@ class EchionSampler void add_asyncio_task_count(size_t count) { asyncio_task_count_ += count; } size_t asyncio_task_count() const { return asyncio_task_count_; } - void configure_frame_limits(size_t max_frames, size_t frame_cache_capacity) - { - stack_max_frames_ = std::max(max_frames, 1); - frame_cache_.set_capacity(frame_cache_capacity); - } + void set_max_frames(size_t max_frames) { stack_max_frames_ = std::max(max_frames, 1); } [[nodiscard]] size_t stack_max_frames() const { return stack_max_frames_; } @@ -175,7 +171,6 @@ class EchionSampler // Accessor for frame cache operations LRUCache& frame_cache() { return frame_cache_; } - [[nodiscard]] size_t frame_cache_capacity() const { return frame_cache_.capacity(); } void postfork_child() { diff --git a/ddtrace/internal/datadog/profiling/stack/include/constants.hpp b/ddtrace/internal/datadog/profiling/stack/include/constants.hpp index c3d311ee211..4cf3ab125b9 100644 --- a/ddtrace/internal/datadog/profiling/stack/include/constants.hpp +++ b/ddtrace/internal/datadog/profiling/stack/include/constants.hpp @@ -19,8 +19,5 @@ constexpr unsigned int g_default_max_threads_per_sample = 25; // leaf tasks exceeds this, reservoir sampling is used. 0 means sample all tasks. constexpr unsigned int g_default_max_tasks_per_sample = 50; -// Echion retains recently rendered frames across stack walks. Scale the cache with -// the configured stack depth while bounding both churn and retained memory. -constexpr unsigned int g_min_echion_frame_cache_size = 256; -constexpr unsigned int g_max_echion_frame_cache_size = 1024; -constexpr unsigned int g_echion_frame_cache_size_multiplier = 4; +// Echion maintains a cache of frames--the size of this cache is specified up-front. +constexpr unsigned int g_default_echion_frame_cache_size = 1024; diff --git a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp index 62fb28cf7ca..387bc305ae5 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/sampler.cpp @@ -98,17 +98,6 @@ create_thread_with_stack(size_t stack_size, Sampler* sampler, uint64_t seq_num) namespace { -size_t -calculate_frame_cache_capacity(size_t max_frames) -{ - if (max_frames >= g_max_echion_frame_cache_size / g_echion_frame_cache_size_multiplier) { - return g_max_echion_frame_cache_size; - } - - const size_t scaled = max_frames * g_echion_frame_cache_size_multiplier; - return std::max(scaled, static_cast(g_min_echion_frame_cache_size)); -} - // Returns the CPU time of the calling thread in microseconds, or 0 on error. uint64_t get_thread_cpu_time_us() @@ -605,7 +594,7 @@ Sampler::set_max_frames(uint64_t value) // Setting to 0 uses the default limit. const size_t requested = value == 0 ? g_default_max_nframes : static_cast(value); - echion->configure_frame_limits(requested, calculate_frame_cache_capacity(requested)); + echion->set_max_frames(requested); return true; } @@ -618,11 +607,11 @@ Sampler::max_frames() const size_t Sampler::frame_cache_capacity() const { - return echion->frame_cache_capacity(); + return g_default_echion_frame_cache_size; } Sampler::Sampler() - : echion{ std::make_unique(calculate_frame_cache_capacity(g_default_max_nframes)) } + : echion{ std::make_unique(g_default_echion_frame_cache_size) } { } diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index c1c641193ca..cafb30601e7 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -85,7 +85,7 @@ def test_collect_truncate() -> None: ddup.config(env="test", service="test", version="0.0.0", max_nframes=64, output_filename=pprof_prefix) ddup.start() with stack.StackCollector(): - assert _stack._get_frame_limits() == (max_nframes, 256) + assert _stack._get_frame_limits() == (max_nframes, 1024) func1() ddup.upload() @@ -111,17 +111,14 @@ def test_collect_truncate() -> None: @pytest.mark.subprocess -def test_native_frame_limit_scales_cache() -> None: +def test_native_frame_limit() -> None: from ddtrace.internal.datadog.profiling.stack import _stack _stack.set_max_frames(0) - assert _stack._get_frame_limits() == (64, 256) + assert _stack._get_frame_limits() == (64, 1024) _stack.set_max_frames(65) - assert _stack._get_frame_limits() == (65, 260) - - _stack.set_max_frames(512) - assert _stack._get_frame_limits() == (512, 1024) + assert _stack._get_frame_limits() == (65, 1024) _stack.set_max_frames(10_000) assert _stack._get_frame_limits() == (10_000, 1024) @@ -206,7 +203,7 @@ def test_set_max_frames_after_fork_restart() -> None: try: stack.stop() stack.set_max_frames(1) - assert _stack._get_frame_limits() == (1, 256) + assert _stack._get_frame_limits() == (1, 1024) assert stack.start() func1() stack.stop() @@ -265,7 +262,7 @@ async def outer() -> None: await inner() with stack.StackCollector(nframes=1): - assert _stack._get_frame_limits() == (1, 256) + assert _stack._get_frame_limits() == (1, 1024) asyncio.run(outer()) ddup.upload() @@ -712,7 +709,7 @@ def _do_fib() -> None: threads = [] with stack.StackCollector(nframes=1): - assert _stack._get_frame_limits() == (1, 256) + assert _stack._get_frame_limits() == (1, 1024) for i in range(5): t = threading.Thread(target=_do_fib, name=f"TestThread {i}") t.start() From 375e522a2cb0a70c24d418987a02cfd5c816ddd7 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Mon, 21 Sep 2026 18:16:04 +0000 Subject: [PATCH 18/28] docs(profiling): explain omission marker placement --- .../internal/datadog/profiling/stack/echion/echion/stacks.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index 79660c58ad2..1ae57834aee 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -47,6 +47,10 @@ class FrameStack : public std::vector public: using Key = Frame::Key; + // Mark a gap left by omitted synchronous frames in the stitched leaf-to-root stack. + // omission_index is a zero-based index into retained Frames, not rendered locations: + // insert the marker before that Frame, or append it when the index equals size(). + // SIZE_MAX disables the marker; omitted_frames supplies its count (zero emits nothing). void render(EchionSampler& echion, TruncationStatus truncation, size_t omission_index = SIZE_MAX, From 827dacc2de73109f7bd6b67cee305f42e9c3eff4 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Mon, 21 Sep 2026 18:36:54 +0000 Subject: [PATCH 19/28] refactor(profiling): simplify task unwind metadata Make omission marker arguments explicit and clarify their documentation.\nReturn coroutine depth directly instead of a task-specific result type.\nRestore stitched-stack regression coverage and separate the one-frame test. --- .../profiling/stack/echion/echion/stacks.h | 13 ++--- .../profiling/stack/echion/echion/tasks.h | 10 ++-- .../profiling/stack/src/echion/tasks.cc | 13 ++--- .../profiling/stack/src/echion/threads.cc | 7 ++- .../test_asyncio_task_frame_budget.py | 46 +++++++++++++++++ tests/profiling/collector/test_stack.py | 51 +++++++++++++++++-- 6 files changed, 110 insertions(+), 30 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index 1ae57834aee..09a29b98170 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -47,14 +47,11 @@ class FrameStack : public std::vector public: using Key = Frame::Key; - // Mark a gap left by omitted synchronous frames in the stitched leaf-to-root stack. - // omission_index is a zero-based index into retained Frames, not rendered locations: - // insert the marker before that Frame, or append it when the index equals size(). - // SIZE_MAX disables the marker; omitted_frames supplies its count (zero emits nothing). - void render(EchionSampler& echion, - TruncationStatus truncation, - size_t omission_index = SIZE_MAX, - size_t omitted_frames = 0); + // omission_index locates a gap left by omitted synchronous frames in the leaf-to-root stack. + // It indexes retained Frames, not rendered locations: insert the marker before that Frame, + // or append it when the index equals size(). SIZE_MAX disables the marker. + // omitted_frames supplies the marker's count; zero emits nothing. + void render(EchionSampler& echion, TruncationStatus truncation, size_t omission_index, size_t omitted_frames); }; [[nodiscard]] size_t diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h index 3b719dc721b..02a483edd84 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h @@ -102,12 +102,6 @@ class GenInfo // ---------------------------------------------------------------------------- -struct TaskUnwindResult -{ - size_t retained = 0; - size_t depth = 0; -}; - class TaskInfo { public: @@ -151,7 +145,9 @@ class TaskInfo { } - TaskUnwindResult unwind(EchionSampler& echion, FrameStack&, bool using_uvloop, size_t max_depth); + // Append at most max_depth frames and return the discovered coroutine depth, not the number added. + // Stitching needs that depth to identify overlapping physical frames even when only a prefix is retained. + size_t unwind(EchionSampler& echion, FrameStack&, 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/src/echion/tasks.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc index d07b464ea1d..d666cdf0730 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc @@ -228,7 +228,7 @@ is_uvloop_wrapper_frame(EchionSampler& echion, bool using_uvloop, const Frame& f #endif } -TaskUnwindResult +size_t TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop, size_t max_depth) { // TODO: Check for running task. @@ -250,10 +250,11 @@ TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop, si } } - TaskUnwindResult result{ 0, coro_frames.size() }; + size_t depth = coro_frames.size(); + size_t retained = 0; // Unwind only the frames that can contribute to this task's output. - while (!coro_frames.empty() && result.retained < max_depth) { + while (!coro_frames.empty() && retained < max_depth) { PyObject* frame = coro_frames.top(); coro_frames.pop(); @@ -278,12 +279,12 @@ TaskInfo::unwind(EchionSampler& echion, FrameStack& stack, bool using_uvloop, si // 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(); - result.depth--; + depth--; continue; } - result.retained++; + retained++; } - return result; + 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 b7d98f67dee..1fcf7ff7a95 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -250,8 +250,7 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco std::unordered_map task_coro_stacks; for (auto& task : all_tasks) { CachedTaskStack cached; - auto result = task->unwind(echion, cached.frames, using_uvloop, max_frames); - cached.depth = result.depth; + cached.depth = task->unwind(echion, cached.frames, using_uvloop, max_frames); task_coro_stacks.emplace(task->origin, std::move(cached)); } @@ -954,12 +953,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/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index ec5759e397a..75a2cffe51f 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -175,3 +175,49 @@ async def async_main() -> None: len(names) <= 8 and "sync_code" in names and names[-1].startswith("<") and "synchronous frame" in 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, + ) diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index cafb30601e7..a9557468915 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -234,10 +234,12 @@ def test_set_max_frames_after_fork_restart() -> None: @pytest.mark.subprocess( - env={"DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_native_frame_limit"}, + env=dict( + DD_PROFILING_OUTPUT_PPROF="/tmp/test_asyncio_native_frame_limit", + ), err=None, ) -def test_asyncio_collection_honors_frame_limit() -> None: +def test_asyncio_discovery_preserves_sync_context() -> None: import asyncio import os import time @@ -248,32 +250,71 @@ def test_asyncio_collection_honors_frame_limit() -> None: 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.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: + def sync_outer() -> None: sync_leaf() + async def inner() -> None: + sync_outer() + async def outer() -> None: await inner() with stack.StackCollector(nframes=1): assert _stack._get_frame_limits() == (1, 1024) + sync_outer() + # Asyncio collection now shares the frame limit, so leave room for the stitched stack. + with stack.StackCollector(nframes=64): asyncio.run(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("<") + ] + 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 + 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)], + 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, ) From 468ee51c943ec91c41f6bfe8a918c5b1839227df Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Tue, 22 Sep 2026 00:43:20 +0000 Subject: [PATCH 20/28] docs(profiling): clarify task unwind and omission arguments --- .../datadog/profiling/stack/echion/echion/stacks.h | 7 +++---- .../internal/datadog/profiling/stack/echion/echion/tasks.h | 7 ++++--- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index 09a29b98170..54f45a66c85 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -47,10 +47,9 @@ class FrameStack : public std::vector public: using Key = Frame::Key; - // omission_index locates a gap left by omitted synchronous frames in the leaf-to-root stack. - // It indexes retained Frames, not rendered locations: insert the marker before that Frame, - // or append it when the index equals size(). SIZE_MAX disables the marker. - // omitted_frames supplies the marker's count; zero emits nothing. + // omission_index is the index into this FrameStack before which to render the omission marker. + // An index of size() puts the marker after all frames; SIZE_MAX disables it. + // omitted_frames is the number of synchronous frames represented by the marker; zero emits nothing. void render(EchionSampler& echion, TruncationStatus truncation, size_t omission_index, size_t omitted_frames); }; diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h index 02a483edd84..f0892515120 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h @@ -145,9 +145,10 @@ class TaskInfo { } - // Append at most max_depth frames and return the discovered coroutine depth, not the number added. - // Stitching needs that depth to identify overlapping physical frames even when only a prefix is retained. - size_t unwind(EchionSampler& echion, FrameStack&, bool using_uvloop, size_t max_depth); + // 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. From 0c757a468e85c45a6c1834b52f8500fc7cf6990d Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Tue, 22 Sep 2026 01:11:57 +0000 Subject: [PATCH 21/28] refactor(profiling): clarify stack context and isolate collector tests --- .../stack/echion/echion/echion_sampler.h | 1 - .../profiling/stack/echion/echion/stacks.h | 2 +- .../profiling/stack/echion/echion/threads.h | 2 + .../profiling/stack/src/stack_renderer.cpp | 2 +- .../test_asyncio_task_frame_budget.py | 3 +- tests/profiling/collector/test_stack.py | 86 ++++++++++--------- 6 files changed, 51 insertions(+), 45 deletions(-) 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 f9265c80d99..3cde85038d5 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h @@ -157,7 +157,6 @@ class EchionSampler size_t asyncio_task_count() const { return asyncio_task_count_; } void set_max_frames(size_t max_frames) { stack_max_frames_ = std::max(max_frames, 1); } - [[nodiscard]] size_t stack_max_frames() const { return stack_max_frames_; } unsigned int max_tasks_per_sample() const { return max_tasks_per_sample_; } diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index 54f45a66c85..fa4be21a752 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -49,7 +49,7 @@ class FrameStack : public std::vector // omission_index is the index into this FrameStack before which to render the omission marker. // An index of size() puts the marker after all frames; SIZE_MAX disables it. - // omitted_frames is the number of synchronous frames represented by the marker; zero emits nothing. + // omitted_frames is the number of omitted thread frames represented by the marker; zero emits nothing. void render(EchionSampler& echion, TruncationStatus truncation, size_t omission_index, size_t omitted_frames); }; diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h index 7aca4be7789..14ea3442d1a 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h @@ -60,6 +60,8 @@ 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(); diff --git a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp index ac62cc57110..3799b375bf4 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp @@ -224,7 +224,7 @@ StackRenderer::render_omitted_frames(size_t count) return; } - const std::string name = "<" + std::to_string(count) + " synchronous frame" + (count == 1 ? "" : "s") + " omitted>"; + const std::string name = "<" + std::to_string(count) + " frame" + (count == 1 ? "" : "s") + " omitted>"; sample->push_frame(name, "", 0, 0); } diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index 75a2cffe51f..49e0d8673e5 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -123,6 +123,7 @@ async def async_main() -> 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 @@ -172,7 +173,7 @@ async def async_main() -> None: ) assert any( - len(names) <= 8 and "sync_code" in names and names[-1].startswith("<") and "synchronous frame" in names[-1] + len(names) <= 8 and "sync_code" in names and re.fullmatch(r"<[1-9][0-9]* frames? omitted>", names[-1]) for names in actual ), actual diff --git a/tests/profiling/collector/test_stack.py b/tests/profiling/collector/test_stack.py index a9557468915..f83fd0d0d0a 100644 --- a/tests/profiling/collector/test_stack.py +++ b/tests/profiling/collector/test_stack.py @@ -237,9 +237,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_preserves_sync_context() -> None: +def test_stack_collection_preserves_sync_context() -> None: import asyncio import os import time @@ -249,6 +250,8 @@ def test_asyncio_discovery_preserves_sync_context() -> 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", @@ -272,52 +275,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 collection now shares the frame limit, so leave room for the stitched stack. - with stack.StackCollector(nframes=64): - 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: From 5b43c9bcd34c66af7f4b6d54e4caa8763440fb0c Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Tue, 22 Sep 2026 13:48:04 +0000 Subject: [PATCH 22/28] refactor(profiling): use truncation terminology for stack markers --- .../profiling/stack/echion/echion/stacks.h | 10 +++++----- .../profiling/stack/include/stack_renderer.hpp | 2 +- .../datadog/profiling/stack/src/echion/stacks.cc | 10 +++++----- .../profiling/stack/src/echion/threads.cc | 16 ++++++++-------- .../profiling/stack/src/stack_renderer.cpp | 4 ++-- .../collector/test_asyncio_task_frame_budget.py | 2 +- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h index fa4be21a752..c658f9a722c 100644 --- a/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h +++ b/ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h @@ -47,10 +47,10 @@ class FrameStack : public std::vector public: using Key = Frame::Key; - // omission_index is the index into this FrameStack before which to render the omission marker. + // 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. - // omitted_frames is the number of omitted thread frames represented by the marker; zero emits nothing. - void render(EchionSampler& echion, TruncationStatus truncation, size_t omission_index, size_t omitted_frames); + // 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 @@ -101,8 +101,8 @@ class StackInfo uint64_t task_id; bool on_cpu; FrameStack stack; - size_t omission_index = SIZE_MAX; - size_t omitted_frames = 0; + 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/include/stack_renderer.hpp b/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp index ea782aa717d..89548872898 100644 --- a/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp +++ b/ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp @@ -100,7 +100,7 @@ class StackRenderer std::optional walltime_ns_override = std::nullopt); void render_frame(Frame& frame); void mark_truncated(); - void render_omitted_frames(size_t count); + 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 a4c4f502ac4..1385f3bea51 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc @@ -19,14 +19,14 @@ rendered_location_count(const Frame& frame) } void -FrameStack::render(EchionSampler& echion, TruncationStatus truncation, size_t omission_index, size_t omitted_frames) +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 (size_t i = 0; i < size(); ++i) { - if (i == omission_index) { - renderer.render_omitted_frames(omitted_frames); + if (i == truncation_index) { + renderer.render_truncated_frames(truncated_frames); } auto& frame = (*this)[i]; @@ -53,8 +53,8 @@ FrameStack::render(EchionSampler& echion, TruncationStatus truncation, size_t om renderer.render_frame(frame); } - if (omission_index == size()) { - renderer.render_omitted_frames(omitted_frames); + 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/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 1fcf7ff7a95..70da5896a12 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -425,7 +425,7 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco bool leaf_truncated = leaf_depth > leaf_to_keep; bool runtime_truncated = runtime_available > runtime_to_keep; - // An omission marker consumes one location. Remove the + // A truncation marker consumes one location. Remove the // lowest-priority selected physical frame if the real locations // have already filled the budget. if ((leaf_truncated || runtime_truncated) && locations >= max_frames) { @@ -442,8 +442,8 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco python_stack.begin(), python_stack.begin() + static_cast(leaf_to_keep)); if (leaf_truncated) { - stack_info->omission_index = stack.size(); - stack_info->omitted_frames = leaf_depth - leaf_to_keep; + stack_info->truncation_index = stack.size(); + stack_info->truncated_frames = leaf_depth - leaf_to_keep; } stack.insert(stack.end(), task_frames.begin(), task_frames.end()); const auto runtime_begin = @@ -452,8 +452,8 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco runtime_begin, runtime_begin + static_cast(runtime_to_keep)); if (!leaf_truncated && runtime_truncated) { - stack_info->omission_index = stack.size(); - stack_info->omitted_frames = runtime_available - runtime_to_keep; + stack_info->truncation_index = stack.size(); + stack_info->truncated_frames = runtime_available - runtime_to_keep; } } else { // An off-CPU task is followed by the event-loop thread stack. @@ -468,8 +468,8 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco python_stack.begin(), python_stack.begin() + static_cast(sync_to_keep)); if (sync_truncated) { - stack_info->omission_index = stack.size(); - stack_info->omitted_frames = python_stack.size() - sync_to_keep; + stack_info->truncation_index = stack.size(); + stack_info->truncated_frames = python_stack.size() - sync_to_keep; } } } @@ -941,7 +941,7 @@ ThreadInfo::render_unwound_stacks(EchionSampler& echion) }); task_stack_info->stack.render( - echion, TruncationStatus::Unknown, task_stack_info->omission_index, task_stack_info->omitted_frames); + echion, TruncationStatus::Unknown, task_stack_info->truncation_index, task_stack_info->truncated_frames); 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 3799b375bf4..3287a4a179e 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp +++ b/ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp @@ -218,13 +218,13 @@ StackRenderer::mark_truncated() } void -StackRenderer::render_omitted_frames(size_t count) +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") + " omitted>"; + const std::string name = "<" + std::to_string(count) + " frame" + (count == 1 ? "" : "s") + " truncated>"; sample->push_frame(name, "", 0, 0); } diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index 49e0d8673e5..7054f686079 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -173,7 +173,7 @@ async def async_main() -> None: ) assert any( - len(names) <= 8 and "sync_code" in names and re.fullmatch(r"<[1-9][0-9]* frames? omitted>", names[-1]) + 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 From b060c30b3c39c9c839b5419ba74dff811bea3fe2 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Thu, 19 Nov 2026 17:35:25 +0000 Subject: [PATCH 23/28] fix(profiling): exclude running sibling frames from suspended tasks --- .../profiling/stack/src/echion/threads.cc | 18 ++++--- .../test_asyncio_task_frame_budget.py | 51 +++++++++++++++++++ 2 files changed, 62 insertions(+), 7 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 0b02b4d5f60..9c5ed2a740c 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -428,20 +428,24 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco stack_info->truncated_frames = runtime_available - runtime_to_keep; } } else { - // An off-CPU task is followed by the event-loop thread stack. - size_t sync_to_keep = select_frame_prefix(python_stack, 0, python_stack.size(), max_frames, locations); - bool sync_truncated = python_stack.size() > sync_to_keep; + // 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); - stack.insert(stack.end(), - python_stack.begin(), - python_stack.begin() + static_cast(sync_to_keep)); + 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 = python_stack.size() - sync_to_keep; + stack_info->truncated_frames = runtime_available - sync_to_keep; } } } diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index 7054f686079..8bbaac14696 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -222,3 +222,54 @@ async def outer() -> None: ), print_samples_on_failure=True, ) + + +@pytest.mark.subprocess( + env={"DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_off_cpu_sibling"}, + err=None, +) +def test_suspended_task_does_not_inherit_running_sibling_frames() -> None: + import asyncio + import os + import time + + 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 + + async def busy(done: asyncio.Event) -> None: + busy_sync() + done.set() + + async def sleeper(done: asyncio.Event) -> None: + await done.wait() + + async def main() -> None: + done = asyncio.Event() + await asyncio.gather(asyncio.create_task(sleeper(done), name="sleeper"), asyncio.create_task(busy(done))) + + p = profiler.Profiler() + p.start() + asyncio.run(main()) + p.stop() + + output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid()) + profile = pprof_utils.parse_newest_profile(output_filename) + sleeper_stacks = [] + 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] == "sleeper": + sleeper_stacks.append( + [ + pprof_utils.get_location_from_id(profile, location_id).function_name + for location_id in sample.location_id + ] + ) + + assert sleeper_stacks + leaked = [names for names in sleeper_stacks if {"busy_sync", "busy"}.intersection(names)] + assert not leaked, leaked From 36ef98993b972a0e6c4c8e8d10fa00cf5fafd07a Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Thu, 19 Nov 2026 17:36:55 +0000 Subject: [PATCH 24/28] fix(profiling): stitch running parent frames after suspended children --- .../profiling/stack/src/echion/threads.cc | 22 ++++----- .../test_asyncio_task_frame_budget.py | 47 +++++++++++++++++++ 2 files changed, 58 insertions(+), 11 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 9c5ed2a740c..ae69fa9f11f 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -287,7 +287,7 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco FrameStack task_frames; size_t on_cpu_task_depth = 0; - bool has_on_cpu_task = false; + std::optional on_cpu_task_start; // Safety: prevent infinite loops from cycles in task chain maps. size_t task_chain_depth = 0; @@ -313,7 +313,7 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco } } if (task.is_on_cpu) { - has_on_cpu_task = true; + on_cpu_task_start = first_added; on_cpu_task_depth = cached.depth; } } @@ -372,19 +372,16 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco task_frames.end()); // Task frames receive the reporting budget first. If capacity remains, - // fill it with physical context. For an on-CPU task, split that context - // around the coroutine frames replaced by task_frames: - // - // synchronous leaf frames, logical task frames, event-loop roots - // - // Synchronous leaf frames have priority over event-loop roots. - if (task_truncated || (has_on_cpu_task && !asyncio_boundary_index)) { + // 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. + if (task_truncated || (on_cpu_task_start && !asyncio_boundary_index)) { stack_info->stack = std::move(task_frames); } else { auto& stack = stack_info->stack; size_t locations = task_locations; - if (has_on_cpu_task && asyncio_boundary_index) { + 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 leaf_available = std::min(leaf_depth, python_stack.size()); @@ -410,6 +407,9 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco runtime_truncated = runtime_available > runtime_to_keep; } + const auto on_cpu_begin = + task_frames.begin() + static_cast(*on_cpu_task_start); + stack.insert(stack.end(), task_frames.begin(), on_cpu_begin); stack.insert(stack.end(), python_stack.begin(), python_stack.begin() + static_cast(leaf_to_keep)); @@ -417,7 +417,7 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco stack_info->truncation_index = stack.size(); stack_info->truncated_frames = leaf_depth - leaf_to_keep; } - stack.insert(stack.end(), task_frames.begin(), task_frames.end()); + 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(), diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index 8bbaac14696..cefb2e271c9 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -273,3 +273,50 @@ async def main() -> None: assert sleeper_stacks leaked = [names for names in sleeper_stacks if {"busy_sync", "busy"}.intersection(names)] assert not leaked, leaked + + +@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 From 76a2b0e48697ca313c7e977df44dc723cf7094f9 Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Thu, 19 Nov 2026 17:39:06 +0000 Subject: [PATCH 25/28] fix(profiling): omit the uvloop wrapper from running task stacks --- .../profiling/stack/src/echion/threads.cc | 51 ++++++++++++------- .../test_asyncio_task_frame_budget.py | 37 ++++++++++++++ 2 files changed, 69 insertions(+), 19 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index ae69fa9f11f..27bf92bd2e2 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -384,38 +384,51 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco 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 leaf_available = std::min(leaf_depth, python_stack.size()); - const size_t runtime_start = std::min(*asyncio_boundary_index, python_stack.size()); + const size_t runtime_start = *asyncio_boundary_index; const size_t runtime_available = python_stack.size() - runtime_start; - size_t leaf_to_keep = select_frame_prefix(python_stack, 0, leaf_available, max_frames, locations); + 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); - bool leaf_truncated = leaf_depth > leaf_to_keep; - bool runtime_truncated = runtime_available > runtime_to_keep; // A truncation marker consumes one location. Remove the // lowest-priority selected physical frame if the real locations // have already filled the budget. - if ((leaf_truncated || runtime_truncated) && locations >= max_frames) { + if ((leaf_dropped > 0 || runtime_available > runtime_to_keep) && locations >= max_frames) { if (runtime_to_keep > 0) { runtime_to_keep--; - } else if (leaf_to_keep > 0) { - leaf_to_keep--; + } else if (stack.size() > leaf_start) { + stack.pop_back(); + ++leaf_dropped; } - leaf_truncated = leaf_depth > leaf_to_keep; - runtime_truncated = runtime_available > runtime_to_keep; } - const auto on_cpu_begin = - task_frames.begin() + static_cast(*on_cpu_task_start); - stack.insert(stack.end(), task_frames.begin(), on_cpu_begin); - stack.insert(stack.end(), - python_stack.begin(), - python_stack.begin() + static_cast(leaf_to_keep)); - if (leaf_truncated) { + if (leaf_dropped > 0) { stack_info->truncation_index = stack.size(); - stack_info->truncated_frames = leaf_depth - leaf_to_keep; + stack_info->truncated_frames = leaf_dropped; } stack.insert(stack.end(), on_cpu_begin, task_frames.end()); const auto runtime_begin = @@ -423,7 +436,7 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco stack.insert(stack.end(), runtime_begin, runtime_begin + static_cast(runtime_to_keep)); - if (!leaf_truncated && runtime_truncated) { + if (leaf_dropped == 0 && runtime_available > runtime_to_keep) { stack_info->truncation_index = stack.size(); stack_info->truncated_frames = runtime_available - runtime_to_keep; } diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index cefb2e271c9..78dddd2d75e 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -1,3 +1,5 @@ +from importlib.util import find_spec + import pytest @@ -320,3 +322,38 @@ async def parent() -> None: 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_wrapper"}, + err=None, +) +def test_uvloop_running_task_stack_omits_wrapper() -> None: + 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: + 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) + samples = pprof_utils.get_samples_with_label_key(profile, "task name") + stacks = [ + [pprof_utils.get_location_from_id(profile, location_id).function_name for location_id in sample.location_id] + for sample in samples + ] + assert any("sync_leaf" in names and "main" in names for names in stacks), stacks + wrappers = {"wrapper", "run..wrapper"} + assert not any(wrappers.intersection(names) for names in stacks), stacks From 8260d94a5f9910e32ed0cf3b160848268562a86f Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Thu, 19 Nov 2026 19:30:04 +0000 Subject: [PATCH 26/28] fix(profiling): retain the coroutine leaf under tiny frame budgets --- .../profiling/stack/src/echion/threads.cc | 19 ++-- .../test_asyncio_task_frame_budget.py | 86 +++++++++++++++++++ 2 files changed, 100 insertions(+), 5 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 27bf92bd2e2..1f7e71132f3 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -361,12 +361,21 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco // 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. A Python frame can - // inject one native location, so counting Frame objects alone can let a - // lower-priority physical segment displace task context in the exporter. + // 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; - const size_t task_to_keep = select_frame_prefix(task_frames, 0, task_frames.size(), max_frames, task_locations); + 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()) { + // Keep the Python leaf even when its injected locations do not fit. + // Disable native lookup on this sample's copy before dropping the GC marker. + auto& leaf = task_frames.front(); + leaf.code_object = 0; + if (max_frames == 1) { + leaf.is_in_gc = false; + } + task_to_keep = 1; + task_locations = rendered_location_count(leaf); + } 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()); @@ -375,7 +384,7 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco // 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. - if (task_truncated || (on_cpu_task_start && !asyncio_boundary_index)) { + if (task_truncated || task_locations == max_frames || (on_cpu_task_start && !asyncio_boundary_index)) { stack_info->stack = std::move(task_frames); } else { auto& stack = stack_info->stack; diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index 78dddd2d75e..b3707f9af5e 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -1,4 +1,5 @@ from importlib.util import find_spec +import sys import pytest @@ -357,3 +358,88 @@ async def main() -> None: assert any("sync_leaf" in names and "main" in names for names in stacks), stacks wrappers = {"wrapper", "run..wrapper"} assert not any(wrappers.intersection(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 From 34adcb184fee7da9ef11e790e1b61b9b01601a7e Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Thu, 19 Nov 2026 19:54:35 +0000 Subject: [PATCH 27/28] fix(profiling): handle asyncio boundaries hidden by the frame limit --- .../profiling/stack/src/echion/threads.cc | 60 +++++++++++++----- .../test_asyncio_task_frame_budget.py | 63 +++++++++++++++++-- 2 files changed, 103 insertions(+), 20 deletions(-) diff --git a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc index 5f076708809..50bbd48c5ed 100644 --- a/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc +++ b/ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc @@ -27,6 +27,17 @@ select_frame_prefix(const FrameStack& frames, size_t start, size_t count, size_t } 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 @@ -56,9 +67,7 @@ ThreadInfo::unwind(EchionSampler& echion, PyThreadState* tstate, microsecond_t w asyncio_boundary_index.reset(); if (asyncio_loop) { - // Boundary discovery is limited to the physical frames that can be - // reported. If an on-CPU boundary lies beyond the budget, unwind_tasks - // reports task context alone rather than stitching unknown overlap. + // 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; @@ -223,6 +232,8 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco 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) { CachedTaskStack cached; @@ -370,15 +381,9 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco 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()) { - // Keep the Python leaf even when its injected locations do not fit. - // Disable native lookup on this sample's copy before dropping the GC marker. - auto& leaf = task_frames.front(); - leaf.code_object = 0; - if (max_frames == 1) { - leaf.is_in_gc = false; - } + drop_injected_locations_to_fit(task_frames.front(), max_frames); task_to_keep = 1; - task_locations = rendered_location_count(leaf); + task_locations = rendered_location_count(task_frames.front()); } const bool task_truncated = task_collection_full || task_to_keep < task_frames.size(); task_frames.erase(task_frames.begin() + static_cast(task_to_keep), @@ -388,10 +393,37 @@ ThreadInfo::unwind_tasks(EchionSampler& echion, PyThreadState* tstate, microseco // 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. - if (task_truncated || task_locations == max_frames || (on_cpu_task_start && !asyncio_boundary_index)) { - stack_info->stack = std::move(task_frames); + 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 { - auto& stack = stack_info->stack; size_t locations = task_locations; if (on_cpu_task_start && asyncio_boundary_index) { diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index b3707f9af5e..75c37bbab20 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -229,6 +229,7 @@ async def outer() -> None: @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: @@ -239,13 +240,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: @@ -273,7 +276,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 @@ -360,6 +363,54 @@ async def main() -> None: assert not any(wrappers.intersection(names) for names in stacks), 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={ From d8870d65e7fec26c5f4d19f2baffc853b8f40e7b Mon Sep 17 00:00:00 2001 From: Taegyun Kim Date: Fri, 20 Nov 2026 15:26:46 +0000 Subject: [PATCH 28/28] test(profiling): move shared task stack tests to test_asyncio_task_stacks The sibling and uvloop wrapper tests landed on main in test_asyncio_task_stacks.py. Drop the duplicates here and keep the frame-limit variants of the sibling test in the shared file. --- .../test_asyncio_task_frame_budget.py | 89 ------------------- .../collector/test_asyncio_task_stacks.py | 15 ++-- 2 files changed, 9 insertions(+), 95 deletions(-) diff --git a/tests/profiling/collector/test_asyncio_task_frame_budget.py b/tests/profiling/collector/test_asyncio_task_frame_budget.py index 75c37bbab20..0bfd3c8d2a1 100644 --- a/tests/profiling/collector/test_asyncio_task_frame_budget.py +++ b/tests/profiling/collector/test_asyncio_task_frame_budget.py @@ -227,60 +227,6 @@ async def outer() -> None: ) -@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: - import asyncio - import os - import time - - from ddtrace.profiling import profiler - from tests.profiling.collector import pprof_utils - - def busy_sync(depth: int) -> None: - if depth: - busy_sync(depth - 1) - else: - time.sleep(1) - - async def busy(done: asyncio.Event) -> None: - # 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: - await done.wait() - - async def main() -> None: - done = asyncio.Event() - await asyncio.gather(asyncio.create_task(sleeper(done), name="sleeper"), asyncio.create_task(busy(done))) - - p = profiler.Profiler() - p.start() - asyncio.run(main()) - p.stop() - - output_filename = os.environ["DD_PROFILING_OUTPUT_PPROF"] + "." + str(os.getpid()) - profile = pprof_utils.parse_newest_profile(output_filename) - sleeper_stacks = [] - 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] == "sleeper": - sleeper_stacks.append( - [ - pprof_utils.get_location_from_id(profile, location_id).function_name - for location_id in sample.location_id - ] - ) - - 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 - - @pytest.mark.subprocess( env={"DD_PROFILING_OUTPUT_PPROF": "/tmp/test_asyncio_running_parent"}, err=None, @@ -328,41 +274,6 @@ async def parent() -> None: 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_wrapper"}, - err=None, -) -def test_uvloop_running_task_stack_omits_wrapper() -> None: - 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: - 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) - samples = pprof_utils.get_samples_with_label_key(profile, "task name") - stacks = [ - [pprof_utils.get_location_from_id(profile, location_id).function_name for location_id in sample.location_id] - for sample in samples - ] - assert any("sync_leaf" in names and "main" in names for names in stacks), stacks - wrappers = {"wrapper", "run..wrapper"} - assert not any(wrappers.intersection(names) for names in stacks), 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"}, 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