Skip to content

fix(profiling): attribute asyncio task samples to the task's own span - #21653

Closed
taegyunkim wants to merge 1 commit into
mainfrom
taegyunkim/profiling-asyncio-task-span-key
Closed

taegyunkim wants to merge 1 commit into
mainfrom
taegyunkim/profiling-asyncio-task-span-key

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Description

JIRA: PROF-16348

The stack profiler labels each sample with the active span, tracked per thread. Tasks on one event loop share a thread, so when tasks each start a span, a task's samples get whichever span was activated on the thread last. For example, task A starts span A and awaits, task B starts span B, then A resumes: A's samples are labeled with span B.

This PR also links each activated span to the running asyncio task, using the AsyncioTask key from #21621:

  • _link_span passes id() of the running task to link_span and clear_span.
  • Task samples use the task's span. A task with no span of its own still gets the thread's span, as before. Removing that fallback first needs tasks to get their creator's span at creation, which comes in a follow-up.
  • Span labels are now added once the renderer knows whether a sample belongs to a task, a greenlet or the thread. The first task on a thread reuses the thread's sample, so adding the thread's labels up front would label that task twice.
  • Greenlet samples pass the Greenlet domain. Nothing links greenlet keys yet, so they keep the thread's span.

Testing

  • test_stack_keeps_asyncio_task_endpoints_separate no longer xfails. The other four tests in the file still strict-xfail; they need the follow-ups.
  • New: a child task with no span of its own keeps its creator's span.
  • New: a task that activates no context while its span is still open gets no span label. It fails if clear_span does not clear the task's link.
  • Updated three unit tests that check the exact link_span and clear_span arguments.
  • Ran locally on Linux aarch64 with scripts/run-tests: all of tests/profiling on Python 3.12; the asyncio, span link and threadpool tests on 3.9 and 3.14; the gevent tests on 3.12. Also the native tests and clang-tidy on the changed files.

Added cost per span activation, on Linux aarch64:

Python 3.12 / 3.14
Finding the running task, outside asyncio 81 / 66 ns
Finding the running task, inside a task 154 / 146 ns
Extra native link and unlink, inside a task ~140 ns

For scale, one tracer.trace() span inside a task costs about 51 µs on the same host with the profiler on, so this adds about 0.6% inside tasks and 0.15% outside asyncio.

Risks

A task's span link is removed when the span finishes or the task activates no context, not when the task ends. If a task ends with its span still open, a new task at the same address can show that span until it finishes.

Additional Notes

None.

Span labels were tracked per thread only, so when tasks on one event loop each started a span, a task's samples got whichever span was activated on the thread last. Also link each activated span to the running asyncio task, and label task samples with the task's span. A task with no span of its own still gets the thread's span, as before.

Span labels are now added once the renderer knows whether a sample belongs to a task, a greenlet or the thread, because the first task on a thread reuses the thread's sample.
@cit-pr-commenter-54b7da

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/__init__.pyi                   @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/_stack.pyi                     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/stack_renderer.hpp     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/threads.cc          @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/stack.cpp                  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp         @DataDog/profiling-python
ddtrace/profiling/_asyncio.py                                           @DataDog/profiling-python
ddtrace/profiling/collector/stack.py                                    @DataDog/profiling-python
releasenotes/notes/profiling-asyncio-task-span-710e0aaf58a1d371.yaml    @DataDog/apm-python
tests/profiling/collector/test_stack_asyncio_endpoint_labels.py         @DataDog/profiling-python
tests/profiling/collector/test_stack_span_links.py                      @DataDog/profiling-python
tests/profiling/collector/test_stack_threadpool.py                      @DataDog/profiling-python

@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

There are 77 dependency direction violations that already exist on the base branch and have not been changed by this PR.

Show existing violations (showing 5 of 77 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=120)
ddtrace.llmobs._integrations.langgraph -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.mcp -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.pydantic_ai -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)

To see all violations, download the layers-base.json and layers-pr.json artifacts from this CI job and run:

uv run --script scripts/import-analysis/layers.py compare layers-base.json layers-pr.json

@pr-commenter

pr-commenter Bot commented Nov 10, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-10 17:23:24

Comparing candidate commit 0a56e24 in PR branch taegyunkim/profiling-asyncio-task-span-key with baseline commit f34f97a in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 572 metrics, 9 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 [-730.939ns; +644.518ns] or [-6.753%; +5.955%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1865.368ns; +1759.569ns] or [-9.227%; +8.703%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1751.118ns; +1770.400ns] or [-9.007%; +9.106%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-396.162ns; +319.320ns] or [-9.015%; +7.267%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-202.600ns; +229.091ns] or [-7.455%; +8.430%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-82.736ns; +88.696ns] or [-5.495%; +5.891%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4392.449ns; +4936.860ns] or [-8.644%; +9.715%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-1110.343ns; +798.125ns] or [-10.212%; +7.341%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-58.137µs; +52.963µs] or [-9.947%; +9.062%]

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 16, 2026
…21743)

## Description

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

Adds a test for an eager task (Python 3.12+) that starts its own trace while its creator's span is still open. Every sample of the child's work must carry the child's span id, local root span id and endpoint, and none may carry the parent's. The test first checks that the child really starts its own trace, so a change in span parenting fails at that check instead of looking like a profiler bug.

This passes on main, where task samples get the thread's latest span. It guards #21653. During an eager step, the sampler also emits the parent task, with the child's frames on top. Once task samples use their own task's span, that copy gets the parent's span.

## Testing

The new test passes on main on Python 3.12, 3.13 and 3.14 (Linux aarch64, `scripts/run-tests`). With #21653 applied, it fails on 3.12.

## Risks

None. Test only.

## Additional Notes

None.


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

Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
@taegyunkim taegyunkim closed this Nov 23, 2026
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