Skip to content

perf(profiling): bound asyncio task stack collection - #19085

Draft
taegyunkim wants to merge 49 commits into
mainfrom
taegyunkim/prof-14213-task-stack-frame-budget
Draft

taegyunkim wants to merge 49 commits into
mainfrom
taegyunkim/prof-14213-task-stack-frame-budget

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Description

Bounds asyncio stack collection with DD_PROFILING_MAX_FRAMES. Before this change the limit applied only to plain thread stacks, and each task's coroutine chain was unwound in full on every sample. We noticed this while working on the Linux CPU timer profiler (#18724).

When stitching task and synchronous stacks, task frames get the budget first, then synchronous leaf frames, then event-loop roots. Injected native and GC locations count against the budget, and a <N frames truncated> marker shows where physical context was cut. The leaf coroutine frame is always kept, even at a one-frame limit.

Because the physical stack is also bounded, a deep running task can hide the event-loop boundary frame. In that case suspended tasks report only their task frames, and a running uvloop task with no coroutine frames keeps its bounded synchronous leaf.

JIRA: PROF-14213

Testing

test_asyncio_task_frame_budget.py covers task-frame priority, deep synchronous stacks, the remaining budget, the collector versus exporter limit, suspended siblings of a running task, a running parent with a suspended child, the uvloop wrapper, native and GC frames at one- and two-frame limits, and a hidden boundary.

Ran locally on CPython 3.12.15 (with uvloop 0.22.1) and 3.10.22 before the latest main merge.

Risks

Low frame limits prefer task frames over synchronous frames. When the boundary frame lies beyond the limit, suspended task samples lose their event-loop roots.

Additional Notes

Frame-cache sizing is unchanged; #20351 follows up. Gevent keeps its existing behavior.

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against main using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/stacks.h         @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/tasks.h          @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/threads.h        @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/fuzz/fuzz_echion_task_unwind.cpp  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/stacks.cc           @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/tasks.cc            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc          @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp         @DataDog/profiling-python
releasenotes/notes/profiling-bound-task-stack-frames-5c8460b0d7e2118f.yaml  @DataDog/apm-python
tests/profiling/collector/test_asyncio_task_frame_budget.py             @DataDog/profiling-python
tests/profiling/collector/test_asyncio_task_stacks.py                   @DataDog/profiling-python
tests/profiling/collector/test_stack.py                                 @DataDog/profiling-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

There are 1 circular imports that already exist on the base branch and have not been changed by this PR.

ddtrace.errortracking._handled_exceptions.bytecode_injector -> ddtrace.errortracking._handled_exceptions.callbacks -> ddtrace.errortracking._handled_exceptions.collector -> ddtrace.errortracking._handled_exceptions.bytecode_reporting -> ddtrace.errortracking._handled_exceptions.bytecode_injector

@datadog-datadog-us1-prod

datadog-datadog-us1-prod Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: 841084c | Docs | View more details | Give us feedback!

@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from 32b532a to ecdbdab Compare July 15, 2026 20:02
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-task-stack-frame-budget branch 2 times, most recently from 3b50116 to e3d2e8a Compare July 16, 2026 01:00
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Jul 16, 2026
## Description

Aligns profiling frame-limit configuration with the backend's [600-location limit](https://datadoghq.atlassian.net/wiki/spaces/PROF/pages/5307007274/Profiling+Libraries+Frame+Truncation+Behaviors).

- raises the native exporter cap from 512 to 599 captured frames
- reserves the 600th backend location for the synthetic `<N frames omitted>` indicator on truncated stacks
- clamps `DD_PROFILING_MAX_FRAMES` to 599 in `ddtrace.internal.settings.profiling`
- preserves configured values from 513 through 599 instead of reducing them to 512 in the native exporter
- ensures collectors receive the same effective configured limit

JIRA: [PROF-14213](https://datadoghq.atlassian.net/browse/PROF-14213?atlOrigin=eyJpIjoiNWFmMTNkMDg2MmJjNDVlZTlkN2JlNGZkMjg3ZWZiYzEiLCJwIjoiaiJ9)

## Testing

- Added configuration tests covering the default, values below the maximum captured-frame limit, the exact 599-frame limit, and values at or above the 600-location backend limit.
- Ran `TestMaxFramesConfig` on Python 3.9, all 6 tests passed. The editable install also rebuilt the native extension successfully.
- Completed a clean Python 3.14 native build for the initial change.
- Ran `scripts/lint checks`, targeted formatting, spelling, and `git diff --check`. Broad lint checks reported only existing repository warnings.

## Risks

Configurations between 513 and 599 can now retain more frames than before. This matches the backend contract but can slightly increase per-sample work for users who explicitly configure values in that range.

Values of 600 and above are now clamped to 599 at configuration load instead of reaching individual collectors unchanged. This leaves one location for the omitted-frame indicator so truncated samples remain within the backend's 600-location cap.

## Additional Notes

This PR is the base of stacked #19073 and #19085, which propagate the limit into Echion and bound task-aware stack collection.

[PROF-14213]: https://datadoghq.atlassian.net/browse/PROF-14213?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiaiJ9


Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from 67ae55e to c0a7c8f Compare July 16, 2026 21:17
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-task-stack-frame-budget branch from b2e94b5 to 29fa643 Compare July 16, 2026 21:17
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-propagate-max-frames branch from c0a7c8f to dd6bece Compare July 16, 2026 21:45
@taegyunkim
taegyunkim force-pushed the taegyunkim/prof-14213-task-stack-frame-budget branch from 29fa643 to 679beb6 Compare July 16, 2026 21:45
…-propagate-max-frames

# Conflicts:
#	ddtrace/internal/datadog/profiling/stack/__init__.pyi
#	ddtrace/internal/datadog/profiling/stack/_stack.pyi
#	ddtrace/internal/datadog/profiling/stack/echion/echion/echion_sampler.h
#	ddtrace/internal/datadog/profiling/stack/src/stack.cpp
#	ddtrace/profiling/collector/stack.py
…max-frames' into taegyunkim/prof-14213-propagate-max-frames
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Sep 21, 2026
## Description

[PROF-14213](https://datadoghq.atlassian.net/browse/PROF-14213)

Clarifies the existing native stack safety ceiling by renaming `MAX_TASK_FRAMES` to `MAX_STACK_UNWIND_SAFETY_LIMIT` everywhere it is used, while retaining the value 2048 and the current behavior.

The ceiling applies to thread, task, and greenlet stack unwinding, truncation probing, and task-aware stitching, not just task stacks. The name and comment distinguish this internal safety ceiling from the configured per-sample frame limit.

Keeps asyncio boundary detection inline in `find_upper_python_stack_size` to minimize the diff. The full-stack scan, return semantics, and existing asyncio/uvloop boundary-frame caches are unchanged.

This deliberately does not introduce the bounded task frame budget from #19085.

## Testing

Latest follow-up (`4fcfbd6830`):

- `scripts/lint cformat --fix` and `scripts/lint cformat`: passed.
- `scripts/lint checks`: passed (existing repository-wide AST-grep warnings were reported).
- `git diff --check`: passed. No `MAX_STACK_DISCOVERY_DEPTH` references remain.
- Targeted `scripts/run-tests` in the Python 3.13 profiling environment could not start: environment setup reported an inaccessible worktree Git path and a permission error reading the generated requirements cache. The latest follow-ups have not been runtime-tested.

Previously recorded validation, before these review follow-ups:

- Python 3.13 profiling environment: 408 passed, 35 skipped, 2 xfailed.
- Python 3.13 uvloop profiling environment: 411 passed, 32 skipped, 2 xfailed.
- Native stack standalone test build on Python 3.13: all 23 C++ tests passed, including `StackUnwind.ProbeBudgetExhaustionRemainsUnknown`.
- `scripts/run-benchmarks --list <changed files>`: no matching benchmark suites.

## Risks

Low. This is an internal naming and comment change. The safety-limit value, all call sites, full-stack boundary scan, boundary caching, and stitching behavior are unchanged.

## Additional Notes

This is prerequisite 1 for #19085.

No release note is needed because the change is internal and behavior-preserving; the PR uses the `changelog/no-changelog` label.


[PROF-14213]: https://datadoghq.atlassian.net/browse/PROF-14213?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
Adopt MAX_STACK_UNWIND_SAFETY_LIMIT from #20352 while retaining asyncio task frame budgeting and upstream task-address discovery changes.
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.
@taegyunkim taegyunkim changed the title perf(profiling): bound task stack collection perf(profiling): bound asyncio task stack collection Sep 21, 2026
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.
brettlangdon pushed a commit that referenced this pull request Sep 23, 2026
## Description

[PROF-14213](https://datadoghq.atlassian.net/browse/PROF-14213)

Clarifies the existing native stack safety ceiling by renaming `MAX_TASK_FRAMES` to `MAX_STACK_UNWIND_SAFETY_LIMIT` everywhere it is used, while retaining the value 2048 and the current behavior.

The ceiling applies to thread, task, and greenlet stack unwinding, truncation probing, and task-aware stitching, not just task stacks. The name and comment distinguish this internal safety ceiling from the configured per-sample frame limit.

Keeps asyncio boundary detection inline in `find_upper_python_stack_size` to minimize the diff. The full-stack scan, return semantics, and existing asyncio/uvloop boundary-frame caches are unchanged.

This deliberately does not introduce the bounded task frame budget from #19085.

## Testing

Latest follow-up (`4fcfbd6830`):

- `scripts/lint cformat --fix` and `scripts/lint cformat`: passed.
- `scripts/lint checks`: passed (existing repository-wide AST-grep warnings were reported).
- `git diff --check`: passed. No `MAX_STACK_DISCOVERY_DEPTH` references remain.
- Targeted `scripts/run-tests` in the Python 3.13 profiling environment could not start: environment setup reported an inaccessible worktree Git path and a permission error reading the generated requirements cache. The latest follow-ups have not been runtime-tested.

Previously recorded validation, before these review follow-ups:

- Python 3.13 profiling environment: 408 passed, 35 skipped, 2 xfailed.
- Python 3.13 uvloop profiling environment: 411 passed, 32 skipped, 2 xfailed.
- Native stack standalone test build on Python 3.13: all 23 C++ tests passed, including `StackUnwind.ProbeBudgetExhaustionRemainsUnknown`.
- `scripts/run-benchmarks --list <changed files>`: no matching benchmark suites.

## Risks

Low. This is an internal naming and comment change. The safety-limit value, all call sites, full-stack boundary scan, boundary caching, and stitching behavior are unchanged.

## Additional Notes

This is prerequisite 1 for #19085.

No release note is needed because the change is internal and behavior-preserving; the PR uses the `changelog/no-changelog` label.


[PROF-14213]: https://datadoghq.atlassian.net/browse/PROF-14213?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ

Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
@pr-commenter

pr-commenter Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-23 20:36:47

Comparing candidate commit 841084c in PR branch taegyunkim/prof-14213-task-stack-frame-budget with baseline commit cbf6506 in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 605 metrics, 10 unstable metrics, 1 flaky benchmarks without significant changes.

Explanation

This is an A/B test comparing a candidate commit's performance against that of a baseline commit. Performance changes are noted in the tables below as:

  • 🟩 = significantly better candidate vs. baseline
  • 🟥 = significantly worse candidate vs. baseline

We compute a confidence interval (CI) over the relative difference of means between metrics from the candidate and baseline commits, considering the baseline as the reference.

If the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD), the change is considered significant.

Feel free to reach out to #apm-benchmarking-platform on Slack if you have any questions.

More details about the CI and significant changes

You can imagine this CI as a range of values that is likely to contain the true difference of means between the candidate and baseline commits.

CIs of the difference of means are often centered around 0%, because often changes are not that big:

---------------------------------(------|---^--------)-------------------------------->
                              -0.6%    0%  0.3%     +1.2%
                                 |          |        |
         lower bound of the CI --'          |        |
sample mean (center of the CI) -------------'        |
         upper bound of the CI ----------------------'

As described above, a change is considered significant if the CI is entirely outside the configured SIGNIFICANT_IMPACT_THRESHOLD (or the deprecated UNCONFIDENCE_THRESHOLD).

For instance, for an execution time metric, this confidence interval indicates a significantly worse performance:

----------------------------------------|---------|---(---------^---------)---------->
                                       0%        1%  1.3%      2.2%      3.1%
                                                  |   |         |         |
       significant impact threshold --------------'   |         |         |
                      lower bound of CI --------------'         |         |
       sample mean (center of the CI) --------------------------'         |
                      upper bound of CI ----------------------------------'

Unstable benchmarks

These benchmarks have a confidence interval too wide to call a change; treat them as noise rather than signal.

scenario:coreapiscenario-context_with_data_listeners

  • unstable execution_time [-708.964ns; +703.407ns] or [-6.560%; +6.509%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-38.324ns; +36.142ns] or [-5.932%; +5.594%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1872.663ns; +1826.304ns] or [-9.277%; +9.047%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1820.151ns; +1693.784ns] or [-9.331%; +8.683%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-356.728ns; +373.776ns] or [-8.171%; +8.562%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-220.803ns; +224.825ns] or [-7.981%; +8.126%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-80.395ns; +96.124ns] or [-5.827%; +6.967%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4633.761ns; +4377.335ns] or [-9.519%; +8.992%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-1073.585ns; +740.571ns] or [-10.291%; +7.099%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-72.347µs; +39.720µs] or [-12.252%; +6.727%]

Known flaky benchmarks

These benchmarks are marked as flaky and will not trigger a failure. Modify FLAKY_BENCHMARKS_REGEX to control which benchmarks are marked as flaky.

Known flaky benchmarks without significant changes:

  • scenario:packagespackageforrootmodulemapping-cache_off

gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Nov 20, 2026
## Description

Adds regression tests for two task stack properties the profiler already handles on `main`:

- A suspended task doesn't pick up frames from a sibling task running on the same thread.
- Running task stacks under `uvloop.run` don't include its `wrapper` frame.

These guard upcoming changes to task stack collection in #19085, where earlier revisions broke both.

## Testing

The new tests in `tests/profiling/collector/test_asyncio_task_stacks.py` pass on `main` with CPython 3.12 and uvloop. The uvloop test skips when uvloop isn't installed.

## Risks

None. Test-only.

## Additional Notes

No release note because this only adds tests. JIRA: PROF-14213.


Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
…acks

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant