Skip to content

fix(profiling): isolate asyncio task span attribution - #19736

Closed
taegyunkim wants to merge 23 commits into
mainfrom
taegyunkim/profiling-task-span-links
Closed

taegyunkim wants to merge 23 commits into
mainfrom
taegyunkim/profiling-task-span-links

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Description

JIRA: PROF-16348

Fixes incorrect span and endpoint labels in asyncio profiles. Tasks are sampled independently, but their attribution currently comes from the shared event-loop thread, so one task can be labeled with another task's span.

This PR:

  • Centralizes profiler span-link routing and lifecycle management in _span_links.py.
  • Stores span links per task, seeded from inherited context at task creation and updated on span activation. Native map operations and loop-registration lookups release the GIL while finish-order bookkeeping stays GIL-protected.
  • Snapshots each task's attribution alongside its sampled stack. Unattributed tasks never fall back to the thread's span.
  • Cleans up links when tasks or spans finish and invalidates inherited attribution across profiler restarts and forks.

Supports asyncio and uvloop task-creation APIs, including eager tasks, without task-switch hooks. This changes profile attribution, not tracing context propagation.

Testing

#21236 added end-to-end tests that fail on main, marked xfail(strict=True). This PR removes those markers, so its diff shows the cases it fixes:

  • Concurrent tasks on one thread keep their own endpoint and span id.
  • An untraced task does not borrow a traced task's span.
  • A task started with an explicit empty Context gets no span, including eager tasks and custom task factories before Python 3.12.

It also adds regression tests for cases that pass on main only because samples fall back to the thread's span: uvloop gather, loops started without set_event_loop, finished spans in a copied Context, and eager tasks with an inherited Context.

Latest validation

Merged origin/main at 45470538bb (which includes #21236) in e0170beb88. The merge commits are SSH-signed.

  • The profiling suite passed via scripts/run-tests -r on Python 3.14 (4e4a3f7e4205) and 3.11 (331e573a0885). It includes test_stack_asyncio_endpoint_labels.py, test_asyncio_span_links.py and test_stack_span_links.py.
  • The uvloop test passed on Python 3.14 with uvloop installed (e94c45592f17).
  • scripts/lint typing passed for the whole project after typing ProfilerTracer.context_provider as BaseContextProvider.

The existing stack validation is documented in the dependent PRs, including AnyIO, gevent, native sanitizer, Valgrind, and staging coverage.

Risks

This changes attribution bookkeeping in profiler hot paths and adds lifecycle coordination across task creation, span activation/finish, profiler restart, and fork. The implementation bounds that risk by keeping tracing context propagation unchanged, using private profiler-only maps, validating span generation and lifetime before publication, and cleaning mappings on every supported lifecycle boundary. Regression tests cover concurrent tasks, custom task factories, eager tasks, finished spans, restarts, and forks.

Additional Notes

This is the base of the stack. AnyIO worker attribution (#19737) and gevent attribution (#19420) are separate follow-ups stacked on this PR.

Direct asyncio.Task(...) construction bypasses creation hooks. Before Python 3.12, creation-time attribution is omitted when a custom task factory makes the inherited context unverifiable.

Pre-review checklist

Before submitting your PR for review, please make sure the following have
been done/checked.

  • The changes have been tested in real services in staging
  • The PR does not result in new crashes

@taegyunkim

Copy link
Copy Markdown
Contributor Author

This replaces #19346 after reordering the stack. The shared logical execution-context infrastructure and asyncio consumer are now first so this branch can be built and tested directly in staging.

@datadog-datadog-prod-us1-2

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

Copy link
Copy Markdown
Contributor

Pipelines  Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

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

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 17, 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/_types.py                            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/docs/Standalone.md                   @DataDog/profiling-python
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/echion/echion/stacks.h         @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/sampler.hpp            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/span_links.hpp         @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/sampler.cpp                @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/span_links.cpp             @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/internal/datadog/profiling/stack/test/CMakeLists.txt            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_asyncio_loop_registration.cpp  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_span_links.cpp       @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_span_links_alloc.cpp  @DataDog/profiling-python
ddtrace/profiling/_asyncio.py                                           @DataDog/profiling-python
ddtrace/profiling/_span_links.py                                        @DataDog/profiling-python
ddtrace/profiling/collector/stack.py                                    @DataDog/profiling-python
releasenotes/notes/profiling-asyncio-endpoint-isolation-b47f8d86e916cf43.yaml  @DataDog/apm-python
tests/profiling/collector/test_asyncio_span_links.py                    @DataDog/profiling-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

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

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 119 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=121)
ddtrace.llmobs._utils -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=119)
ddtrace.llmobs._evaluators.runner -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=119)
ddtrace.llmobs._integrations.bedrock -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=119)
ddtrace.llmobs._integrations.typesafe -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=119)

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 force-pushed the taegyunkim/profiling-task-span-links branch 4 times, most recently from 1ef4500 to 38cc0d2 Compare August 19, 2026 17:04
@taegyunkim
taegyunkim marked this pull request as ready for review August 19, 2026 17:15
@taegyunkim
taegyunkim requested review from a team as code owners August 19, 2026 17:15

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 38cc0d2f60

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread ddtrace/profiling/collector/stack.py Resolved
Comment thread ddtrace/profiling/_asyncio.py Resolved
Comment thread ddtrace/profiling/_asyncio.py Resolved

@emmettbutler emmettbutler left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

release note looks good

@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-task-span-links branch from 43e6277 to bdd394c Compare September 10, 2026 15:29
@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 changed the base branch from main to taegyunkim/profiling-span-link-lifecycle September 15, 2026 20:44
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-span-link-lifecycle branch from fabbeef to d92c58d Compare September 16, 2026 16:20
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 653909d to 8f8861f Compare September 16, 2026 16:20
@taegyunkim
taegyunkim changed the base branch from taegyunkim/profiling-span-link-lifecycle to main September 16, 2026 19:04
Publish inherited attribution before eager task execution and preserve coroutine names and cancellation semantics. Revalidate publication across span finish and profiler resets, roll back allocation and finalizer failures, and release the GIL while waiting for loop-registration state.

Add Python and native regression tests for eager execution, concurrent finish, lifecycle invalidation, cleanup failures, and lock contention.
Use ELF link-time wrapping around scalar new calls in an isolated test executable compiled from the production SpanLinks implementation. Delegate allocation and deallocation to the runtime so ASan and Valgrind retain their allocator interception and the failure injector remains active.

Keep the allocation regression enabled in the Linux sanitizer and Valgrind matrix, document the linker requirement, and format the asyncio registration test declaration.
Compare custom-factory task names with an unprofiled baseline, since CPython 3.13.13 overwrites the factory name even when the requested name is None. Assert the original coroutine names at the factory boundary and on the task coroutine, covering both implicit and explicit task names.
@taegyunkim taegyunkim changed the title fix(profiling): attribute asyncio task samples to inherited spans fix(profiling): isolate asyncio task span attribution Sep 21, 2026
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 7d55ec9 to c1a0208 Compare September 27, 2026 10:36
…task-span-links

# Conflicts:
#	ddtrace/profiling/collector/stack.py
…ovider

The task span-link changes call context_provider.active(), which mypy
rejects now that ProfilerTracer types context_provider as object.
BaseContextProvider lives in ddtrace.internal.native, so this keeps
profiling free of tracing-product imports.
Add end-to-end tests that run the stack profiler with the tracer and check
the trace endpoint and span id labels on asyncio task samples.

On main, span labels are tracked per thread, not per task, so a task can
pick up another task's endpoint, an untraced task can borrow a traced
task's span, and a task started with an empty Context still gets the
creator's endpoint. Every test here fails on main and is marked
xfail(strict=True), so the fix in #19736 has to remove the markers when
it makes them pass.
- Check span id and local root span id for concurrent traced tasks.
- Eager test: drop the single-value EMPTY_CONTEXT parameter, rename it,
  use asyncio.run, and check the eager first step and the resumed step
  on their own samples.
…ttribution-tests' into taegyunkim/profiling-task-span-links

# Conflicts:
#	tests/profiling/collector/test_stack_asyncio_endpoint_labels.py
@taegyunkim
taegyunkim changed the base branch from main to taegyunkim/profiling-task-span-attribution-tests October 26, 2026 15:48
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Oct 26, 2026
## Description

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

The stack profiler tracks span labels per thread, not per asyncio task. Tasks on the same event loop share a thread, so a task's samples get the span and endpoint of whichever span was activated on the thread last, even if it belongs to another task.

These tests cover:

| Test | What happens on `main` | Python |
|---|---|---|
| `keeps_asyncio_task_endpoints_separate` | Task A's samples get task B's endpoint and span id. | all |
| `does_not_use_thread_endpoint_for_untraced_asyncio_task` | An untraced task gets a traced task's endpoint and span id. | all |
| `respects_explicit_empty_child_task_context` | A task created with an empty `Context` gets its creator's endpoint. | 3.11+ |
| `omits_unverifiable_pre312_custom_factory_context` | Same, for a task made by a custom task factory. | < 3.12 |
| `respects_explicit_empty_context_for_eager_task` | Same, for an eager task, in its first step and after it resumes. | 3.12+ |

They're all `xfail(strict=True)`. #19736 fixes this and removes the markers, so its diff shows which cases it fixes.

## Testing

Ran the file on 3.9 to 3.14. Every test xfails or is skipped for its version. To make sure they fail because of the bug and not something else, I also checked that:

- with `--runxfail`, each test fails at its first label assertion, and
- with the label assertions removed, each test passes (samples exist for every task).

## Risks

None, test-only. Like other wall-time tests these are timing-sensitive, and a strict xfail that passes by chance fails the test.

## Additional Notes

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


Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
Base automatically changed from taegyunkim/profiling-task-span-attribution-tests to main October 26, 2026 18:44
…task-span-links

# Conflicts:
#	tests/profiling/collector/test_stack_asyncio_endpoint_labels.py
@taegyunkim

Copy link
Copy Markdown
Contributor Author

Closing in favor of smaller PRs that land this in steps, starting with #21621 (merged), #21744 and #21653.

@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.

3 participants