Skip to content

fix(profiling): correlate AnyIO worker profiles - #19737

Closed
taegyunkim wants to merge 2 commits into
taegyunkim/profiling-task-span-linksfrom
taegyunkim/profiling-anyio-span-links
Closed

taegyunkim wants to merge 2 commits into
taegyunkim/profiling-task-span-linksfrom
taegyunkim/profiling-anyio-span-links

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

JIRA: PROF-16348

Stack restack

This branch has been merged with the latest #19736 head at c1a0208ae2 and pushed at dbd926e119. The merge carries the latest origin/main changes while preserving the AnyIO worker-attribution behavior and its inherited finish/reset race protection.

Stacked on #19736.

AnyIO copies the active tracing context when anyio.to_thread.run_sync offloads synchronous work, but entering that copied context does not emit a tracing activation event. The profiler therefore associates the request span with the asyncio task while worker-thread samples remain unattributed.

This PR wraps the callable submitted through AnyIO's public thread-offload API. On worker entry, it publishes inherited profiler span metadata to the physical thread after validating the lifecycle generation and source-span lifetime. It clears the physical mapping unconditionally when the callable exits so pooled workers cannot retain attribution across requests.

This reuses the lifecycle coordinator from #19736 and the existing native physical-thread mapping. It does not change tracing semantics or add native code.

Testing

Latest main merge validation

The stack merge commit is SSH-signed.

  • Dedicated Python 3.12 profile-anyio environment via scripts/run-tests: 1 passed.
  • scripts/lint fmt passed for the affected profiler and regression-test files.
  • Targeted profiler typing and scripts/lint suitespec-check passed.

Asyncio naming follow-up validation

Focused asyncio, endpoint-attribution, and span-link lifecycle tests via scripts/run-tests:

  • Python 3.12.13 with uvloop: 41 passed, 2 skipped.
  • Python 3.13.13: 40 passed, 3 skipped.
  • Python 3.14.5: 40 passed, 3 skipped.
  • Both naming cases also passed with --ddtrace on Python 3.13.13.
  • Removing coroutine-name preservation temporarily made both new naming cases fail, confirming the regression check remains effective.
  • The asyncio span-link test file passed on the restacked gevent tip: 13 passed.
  • scripts/lint checks: passed.

These are local validation results. New remote CI results are pending after the stack push.

Native CI follow-up validation

The allocation-failure test was rebuilt and run through CTest on Linux with Clang 19.1.7 in three configurations: ASan/LSan/UBSan, Valgrind 3.24.0, and ordinary RelWithDebInfo. All three passed on both #19736 and the restacked gevent tip. Valgrind reported zero errors and no leaks. scripts/lint checks passed on both branches. This validates the failing test locally, not the entire new remote CI pipeline; CI is rerunning after the push.

Restacked validation

On Python 3.12.13, with a freshly rebuilt native extension:

  • Focused profiling suite via scripts/run-tests: 88 passed, 4 skipped.
  • AnyIO regression on the top of the stack: 1 passed.
  • Native build_standalone.sh -- RelWithDebInfo stack_test: 32 stack tests and 23 wrapper tests passed.
  • scripts/lint checks: passed.
  • The new regression selection produced 14 failures with the pre-fix Python code restored; the final focused run passed.
  • scripts/run-benchmarks --list found no matching suites, so no benchmark results are claimed.

The existing testing and staging results below predate this follow-up.

  • scripts/lint checks on the complete rewritten stack
  • scripts/run-tests --venv bbf818a -- tests/profiling/collector/test_anyio_span_links.py
    • Dedicated Python 3.12 profile-anyio environment: 1 passed

The focused regression covers endpoint and span attribution, then verifies cleanup when the same AnyIO worker is reused outside the trace.

A dedicated Python 3.12 environment installs AnyIO only for this regression. This replaces the previous broad dependency change, reducing generated profiling requirement changes from 38 files to one.

Rapid Python smoke test

The cumulative asyncio and AnyIO stack was previously deployed to rapid_python_http_smoke_test as rapid-td-anyio-span-links.

  • Tested wheel commit: 9c149ad273dc90a40860d96f3351383f12cfae73
  • dd-source commit
  • Mosaic change request
  • 24-hour Python profile
  • The base and RSS endpoints returned HTTP 200, and 10/10 CPU-workload requests succeeded.
  • Profiles showed AnyIO workers executing _run_with_anyio_span, with no error-level application logs after the deployment became ready.

Risks

The wrapper runs only for AnyIO thread offloads while stack profiling is enabled. Cleanup is unconditional in a finally block. Weak source-span validation prevents copied contexts from republishing finished or collected spans. Failures are contained to missing profile attribution and do not alter AnyIO or tracing behavior.

Additional Notes

Review this stack in order:

Order PR Purpose
1 #19736 Centralize span-link lifecycle handling and attribute asyncio task samples
2 #19737 Propagate attribution into AnyIO worker threads
3 #19420 Attribute gevent samples and protect greenlet span-link lifecycle

Customer-facing release note: releasenotes/notes/fix-anyio-worker-profile-attribution-abbf595ce67e6ad1.yaml.

@taegyunkim

Copy link
Copy Markdown
Contributor Author

This replaces #19556 after reordering the stack. It now follows the asyncio-first PR #19736 directly and can be staged before the gevent consumer.

@datadog-prod-us1-3

datadog-prod-us1-3 Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Pipelines  Tests

✨ Unblock PR with BitsAI

❌ Errors

Your PR has failed checks. Please review the issues below and take necessary action before merging.

🚦 1 Pipeline job failed

DataDog/apm-reliability/dd-trace-py | contrib/molten 2/2 — 🔧 Needs a code fix, caused by this PR

View more details · View in GitLab

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

Useful? React with 👍 / 👎

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

@pr-commenter

pr-commenter Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-09-27 11:15:55

Comparing candidate commit dbd926e in PR branch taegyunkim/profiling-anyio-span-links with baseline commit c1a0208 in branch taegyunkim/profiling-task-span-links.

📊 Benchmarking dashboard

Found 0 performance improvements and 10 performance regressions! Performance is the same for 612 metrics, 10 unstable metrics, 7 known flaky benchmarks, 17 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 ----------------------------------'

scenario:httppropagationextract-b3_headers

  • 🟥 execution_time [+1.028µs; +1.111µs] or [+13.723%; +14.842%]

scenario:httppropagationextract-empty_headers

  • 🟥 execution_time [+89.545ns; +107.596ns] or [+12.162%; +14.614%]

scenario:iastaspects-add_aspect

  • 🟥 execution_time [+8.262µs; +10.325µs] or [+9.753%; +12.190%]

scenario:iastaspects-format_map_noaspect

  • 🟥 execution_time [+105.227µs; +110.163µs] or [+29.927%; +31.331%]

scenario:iastaspectsremodule-re_expand_aspect

  • 🟥 execution_time [+91.869µs; +103.588µs] or [+14.687%; +16.560%]

scenario:msgpackencoderscenario-simple_one_span

  • 🟥 execution_time [+436.777ns; +501.096ns] or [+10.506%; +12.053%]

scenario:openfeatureflagevaluation-hook-enqueue-typical

  • 🟥 execution_time [+1.515µs; +1.660µs] or [+7.024%; +7.701%]

scenario:otelspan-start

  • 🟥 execution_time [+1.992ms; +2.877ms] or [+8.269%; +11.947%]

scenario:recursivecomputation-shallow

  • 🟥 execution_time [+56.754µs; +60.537µs] or [+8.095%; +8.634%]

scenario:span-start-finish-telemetry

  • 🟥 execution_time [+4.526ms; +4.705ms] or [+11.381%; +11.834%]

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 [-695.181ns; +786.320ns] or [-6.692%; +7.570%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-35.136ns; +43.781ns] or [-5.301%; +6.606%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1986.008ns; +1844.074ns] or [-9.985%; +9.271%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-2172.918ns; +1901.076ns] or [-11.074%; +9.689%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-396.453ns; +366.751ns] or [-9.322%; +8.624%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-236.265ns; +223.520ns] or [-8.840%; +8.364%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-84.410ns; +103.177ns] or [-6.198%; +7.575%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4376.176ns; +4922.140ns] or [-9.111%; +10.248%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-818.560ns; +1082.126ns] or [-8.066%; +10.663%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-52997.934ns; +54589.809ns] or [-9.409%; +9.692%]

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.

scenario:httppropagationinject-ids_only

  • 🟥 execution_time [+2.682µs; +2.819µs] or [+18.671%; +19.623%]

scenario:iastaspects-translate_aspect

  • 🟥 execution_time [+93.718µs; +99.536µs] or [+13.606%; +14.451%]

scenario:iastaspectsospath-ospathbasename_aspect

  • 🟥 execution_time [+141.681µs; +147.192µs] or [+37.174%; +38.620%]

scenario:iastaspectssplit-rsplit_aspect

  • 🟥 execution_time [+31.016µs; +35.653µs] or [+20.083%; +23.086%]

scenario:span-start

  • 🟥 execution_time [+1.349ms; +1.792ms] or [+10.915%; +14.495%]

scenario:telemetryaddmetric-1-count-metric-1-times

  • 🟥 execution_time [+265.177ns; +306.894ns] or [+13.886%; +16.071%]

scenario:tracer-small

  • 🟥 execution_time [+44.672µs; +45.715µs] or [+18.643%; +19.078%]

Known flaky benchmarks without significant changes:

  • scenario:errortrackingflasksqli-baseline
  • scenario:flasksimple-iast-get
  • scenario:iastaspects-casefold_aspect
  • scenario:iastaspects-casefold_noaspect
  • scenario:iastaspects-index_aspect
  • scenario:iastaspects-ljust_noaspect
  • scenario:iastaspects-lower_aspect
  • scenario:iastaspects-replace_aspect
  • scenario:iastaspects-rstrip_aspect
  • scenario:iastaspects-swapcase_aspect
  • scenario:iastaspects-title_noaspect
  • scenario:iastaspects-translate_noaspect
  • scenario:iastaspects-upper_noaspect
  • scenario:packagespackageforrootmodulemapping-cache_off
  • scenario:packagespackageforrootmodulemapping-cache_on
  • scenario:sethttpmeta-all-enabled
  • scenario:telemetryaddmetric-record-100-metrics

@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch 3 times, most recently from 1ef4500 to 38cc0d2 Compare August 19, 2026 17:04
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from fed4ca0 to 9c149ad Compare August 19, 2026 18:00
@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against taegyunkim/profiling-task-span-links using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

.riot/requirements/ff48777.txt                                          @DataDog/apm-python
ddtrace/profiling/_asyncio.py                                           @DataDog/profiling-python
releasenotes/notes/fix-anyio-worker-profile-attribution-abbf595ce67e6ad1.yaml  @DataDog/apm-python
tests/profiling/collector/test_anyio_span_links.py                      @DataDog/profiling-python
tests/profiling/suitespec.yml                                           @DataDog/profiling-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 19, 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

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 201 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=132)
ddtrace.debugging._signal.tracing -×-> ddtrace.trace  (product:debugging -> product:tracing, score=130)
ddtrace.llmobs._integrations.openai_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=130)
ddtrace.internal.ci_visibility.filters -×-> ddtrace.trace  (product:ci_visibility -> product:tracing, score=130)
ddtrace.internal.opentelemetry.context -×-> ddtrace.trace  (product:opentelemetry -> product:tracing, score=130)

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

@taegyunkim
taegyunkim marked this pull request as ready for review August 19, 2026 18:59
@taegyunkim
taegyunkim requested review from a team as code owners August 19, 2026 18:59
@taegyunkim
taegyunkim marked this pull request as draft August 19, 2026 19:49
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from 9c149ad to ab8acda Compare August 20, 2026 03:40
@taegyunkim
taegyunkim marked this pull request as ready for review August 20, 2026 03:41
Comment thread .riot/requirements/19760b6.txt Resolved
Comment thread ddtrace/profiling/_asyncio.py Resolved
Comment thread ddtrace/profiling/_asyncio.py Resolved
Comment thread ddtrace/profiling/_span_links.py Resolved
Comment thread riotfile.py Resolved
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch 2 times, most recently from 52802b4 to c4281a1 Compare August 20, 2026 15:59
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from d3a462e to 415103d Compare August 20, 2026 16:01
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from c4281a1 to 08c344b Compare August 20, 2026 16:01
@taegyunkim
taegyunkim marked this pull request as draft September 15, 2026 19:12
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 01cc2a8 to 0b57e33 Compare September 15, 2026 20:44
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from 722b0a4 to 2126ad0 Compare September 21, 2026 18:51
…rofiling-anyio-span-links

# Conflicts:
#	riotfile.py
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-anyio-span-links branch from 3a38758 to dbd926e Compare September 27, 2026 10:36
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 7d55ec9 to c1a0208 Compare September 27, 2026 10:36
@taegyunkim

Copy link
Copy Markdown
Contributor Author

Closing along with #19736, which this was stacked on. The work is being redone in smaller PRs.

@taegyunkim taegyunkim closed this Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Profiling Continous Profling

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants