Skip to content

fix(profiling): attribute asyncio task samples to inherited spans - #19346

Merged
taegyunkim merged 0 commit into
taegyunkim/profiling-logical-span-linksfrom
taegyunkim/profiling-task-span-links
Aug 17, 2026
Merged

taegyunkim merged 0 commit into
taegyunkim/profiling-logical-span-linksfrom
taegyunkim/profiling-task-span-links

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

This is the second PR in the logical execution-context attribution stack. It reuses #19420's gevent-backed mechanism to attribute each native-rendered asyncio task to the span context that task inherited, instead of applying one event-loop thread link to every task stack.

Routing and rendering

  • Adds the (AsyncioTask, task_id) logical target domain.
  • Gives asyncio higher provider priority than gevent when both schedulers share a thread.
  • Returns a task target only while the current thread has an authoritative native running-loop registration.
  • Snapshots task-keyed attribution beside each unwound task stack.
  • Leaves known tasks unattributed when metadata is missing, instead of falling back to another task's physical-thread span.
  • Tracks loops run without set_event_loop, including Runner(loop_factory=...) and direct run_until_complete() usage.

Inherited task context

  • Python 3.12 and newer read the task's actual context through Task.get_context().
  • Earlier versions use the requested or current context for standard task creation.
  • Custom task factories before Python 3.12 remain conservatively unattributed because their actual context cannot be inspected.
  • Explicit empty contexts, stale profiler generations, and contexts whose source span finished are rejected.
  • Task creation paths share one publication helper, while nested wrappers reuse the installed cleanup finalizer to avoid duplicate publication.

Creation and cleanup

  • Covers BaseEventLoop.create_task, the lowest available ensure_future helper, asyncio.create_task, TaskGroup.create_task, gather-created tasks, and uvloop paths.
  • Wraps the Cython uvloop.Loop.create_task method so uvloop.run() and asyncio.Runner root tasks publish their inherited spans.
  • Uses task done callbacks for prompt cleanup, even when completed tasks remain strongly referenced.
  • Keeps weakref.finalize as the address-reuse and abnormal-lifecycle fallback.
  • Detaches finalizers after fork.

Unsupported third-party native task creation remains best effort. If no safe creation or activation event is observed, the task stays unattributed rather than borrowing the event-loop thread's span.

Review stack

Please review this stack in order:

Order PR Purpose
1 #19420 Shared logical execution-context links and the gevent fix
2 This PR Reuse the mechanism for asyncio tasks
3 #19556 Propagate asyncio attribution into AnyIO worker threads

Testing

Coverage includes:

  • concurrent tasks under different endpoints
  • untraced tasks sharing an event-loop thread with traced tasks
  • explicit empty and finished copied contexts
  • custom factories before Python 3.12
  • nested creation-wrapper deduplication
  • prompt task cleanup and fork reset
  • uvloop gather-created tasks and alternate creation helpers

Validation completed:

  • Python 3.12 profiling suite after integrating task-reservoir changes, normal and fast-copy modes: 387 passed, 40 skipped, 2 xpassed per mode
  • Latest Python 3.12 focused asyncio span-link, endpoint-label, and executor suites passed after restacking on fix(profiling): isolate gevent span attribution across lifecycles #19420
  • Python 3.13 focused asyncio and inherited-context tests: 10 passed, 2 skipped per mode
  • Python 3.13 uvloop profiling suite: 377 passed, 34 skipped, 2 xpassed
  • scripts/lint checks
  • scripts/lint typing -- ddtrace/profiling/_asyncio.py
  • scripts/lint cformat
  • scripts/lint profiling-native-check
  • native stack compilation with warnings treated as errors
  • git diff --check

Risks

  • Task creation gains best-effort wrappers that cannot prevent application task creation if publication fails.
  • Done callbacks and weak finalizers do not retain tasks. Bookkeeping is proportional to live attributed tasks.
  • Activation and lookup operations are expected O(1) and use existing native mutexes.
  • The conservative failure mode is missing attribution, not cross-attribution.

Additional Notes

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Jul 28, 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/__init__.py                    @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/stack_renderer.hpp     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/include/thread_span_links.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/stack.cpp                  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/stack_renderer.cpp         @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/thread_span_links.cpp      @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_thread_span_links.cpp  @DataDog/profiling-python
ddtrace/profiling/_asyncio.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 Jul 28, 2026 •

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

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

ddtrace.contrib.internal.pytorch._distributed -> ddtrace.contrib.internal.pytorch._rank_root -> ddtrace.contrib.internal.pytorch._distributed
ddtrace.contrib.internal.django.patch -> ddtrace.contrib.internal.django.response -> ddtrace.contrib.internal.django.patch
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
ddtrace.llmobs -> ddtrace.llmobs._evaluators -> ddtrace.llmobs._evaluators.format -> ddtrace.llmobs._experiment -> ddtrace.llmobs
ddtrace.appsec._asm_request_context -> ddtrace.appsec._iast._iast_request_context_base -> ddtrace.appsec._iast._iast_env -> ddtrace.appsec._iast.reporter -> ddtrace.appsec._exploit_prevention.stack_traces -> ddtrace.appsec._asm_request_context

@datadog-prod-us1-3

datadog-prod-us1-3 Bot commented Jul 28, 2026 •

Copy link
Copy Markdown

Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

This comment will be updated automatically if new data arrives.
🔗 Commit SHA: ed14a06 | Docs | Datadog PR Page | Give us feedback!

@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch 9 times, most recently from e50665e to e47c953 Compare July 29, 2026 16:51
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from 7629ec0 to e9d510e Compare July 29, 2026 17:30
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch 2 times, most recently from 2268321 to 758e590 Compare July 29, 2026 17:38
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch from e9d510e to c5a8f30 Compare July 29, 2026 17:38
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 758e590 to 07ca94f Compare July 29, 2026 18:23
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch 2 times, most recently from 34fee9c to 4015c0e Compare July 30, 2026 15:47
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch 3 times, most recently from 591493e to 6164ef6 Compare July 30, 2026 18:24
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-clear-finished-endpoint branch 3 times, most recently from 6b72027 to 658892c Compare July 30, 2026 21:31
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 6164ef6 to fe1d37d Compare July 30, 2026 21:38
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 53c4e94 to 7f285d6 Compare August 6, 2026 19:42
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 53bded1 to 6bf922c Compare August 7, 2026 03:47
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 7f285d6 to 8eae04c Compare August 7, 2026 03:48
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 6bf922c to 2ea638f Compare August 11, 2026 18:53
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 8eae04c to d4cf68d Compare August 11, 2026 18:53
@cit-pr-commenter-54b7da

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

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 255 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=134)
ddtrace.appsec._contrib.django -×-> ddtrace.trace  (product:appsec -> product:tracing, score=132)
ddtrace.llmobs._integrations.llama_index -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=132)
ddtrace.llmobs._integrations.pydantic_ai -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=132)
ddtrace.llmobs._integrations.mcp -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=132)

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-logical-span-links branch from 2ea638f to e1bdc05 Compare August 12, 2026 15:04
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from d4cf68d to 6a57deb Compare August 12, 2026 15:04
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from e1bdc05 to fee5719 Compare August 12, 2026 15:18
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 6a57deb to 1550a86 Compare August 12, 2026 15:18
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Aug 13, 2026
## Description

This is the first PR in the span-attribution stack. It fixes stale endpoint and span attribution for physical thread stacks before the later PRs introduce logical asyncio and gevent targets.

### Problem

The stack profiler samples threads independently of application execution, so it keeps a native per-thread copy of the span metadata needed to label profile samples. That copy must follow the lifetime of the tracing context. Otherwise, work that runs after a span finishes can still be labeled with the finished span ID, local-root span ID, and endpoint.

Context activation events are necessary, but they are not sufficient to keep these copies accurate. Consider this sequence:

1. A worker thread activates a span and publishes a native span link.
2. Another thread finishes that span.
3. The worker continues running without performing another context activation.

Finishing the span does not produce an activation event on the worker. Without a separate finish-time cleanup path, its copied link remains stale and subsequent samples are incorrectly attributed to the finished trace.

A local root can also finish before one of its children. In that case the child is still valid and can continue producing profile samples, so cleanup for the root must not remove mappings whose current span is that unfinished child.

### Solution

This PR makes the native `ThreadSpanLinks` store own both directions of each physical association under one mutex:

- thread ID to copied span metadata;
- current span ID to every thread carrying a copy of that exact span.

It then uses two complementary lifecycle signals:

- `ddtrace.context_provider.activate` handles immediate state replacement on the current thread. Activating a span or propagated `Context` publishes its mapping, restoring a parent replaces it, and activating `None` or a `Context` without a span ID clears it.
- `trace.span_finish` performs global reverse invalidation for the exact span that finished. It removes every copied physical-thread mapping for that span, including mappings published on another thread that may never receive another activation. It deliberately preserves mappings for unfinished children when their local root finishes first.

Updating the forward and reverse indexes atomically prevents the two views from diverging. Re-linking a thread removes its previous reverse-index entries first, so a later finish event for an older span cannot erase the thread's newer attribution.

Listener registration occurs only after the collector completes fallible initialization, and both listeners are removed during shutdown. Fork handling reconstructs the native mutex and inherited indexes without traversing potentially inconsistent parent state.

### Review follow-up

Native lifecycle bookkeeping now records in-flight physical span publications before releasing the GIL. If a span finishes while publication is waiting on the native mutex, cleanup is deferred until the final publication completes. This preserves the GIL release introduced in #14852 to avoid thread-pool deadlocks.

## Testing

Added coverage for:

- immediate physical-link clearing on context deactivation;
- finished child-span cleanup across physical threads;
- cross-thread finish cleanup before the linked worker performs another activation;
- preservation of active child links when the local root finishes first;
- reverse-index replacement when a thread advances to a new span;
- nested child-to-parent restoration;
- cleanup on reused thread-pool workers.

Validation completed on the reordered physical-only PR:

- Python 3.13 profiling suite in normal and fast-copy modes: `359 passed, 35 skipped, 2 xfailed` per mode
- Python 3.13 focused cross-thread finish regression: `1 passed` in each mode
- Python 3.11 profiling suite after hardening the reused-worker assertion: `309 passed, 85 skipped, 2 xfailed` in both normal and fast-copy modes
- Reused-worker regression repeated 11 times in both modes: `22 passed`
- Control experiment with the span-finish listener disabled: the cross-thread regression failed in both modes because post-finish samples retained the endpoint, confirming activation alone is insufficient
- `scripts/lint checks`
- targeted style and typing checks
- `scripts/lint cformat`
- `scripts/lint profiling-native-check`
- rebased onto current `main` at `3efdcbe3af`
- `git diff --check`

## Risks

- Physical activation updates perform expected O(1) forward and reverse-index mutations under the existing span-link mutex.
- Finished-span cleanup visits only threads indexed by the exact span that finished.
- The reverse index adds bounded memory proportional to currently linked physical threads.
- The rollback is to disable stack profiling or revert this PR.

## Additional Notes

- Next, common logical stack helpers: #19420
- Gevent integration: #19379
- Asyncio integration: #19346
- Includes a customer-facing profiling fix release note.

Before

<img width="1732" height="905" alt="Screenshot 2026-08-06 at 10 15 34 AM" src="https://github.com/user-attachments/assets/d6a69ad3-1324-4328-b241-c3dc2fdf7cd5" />

After

<img width="1749" height="908" alt="Screenshot 2026-08-06 at 10 15 24 AM" src="https://github.com/user-attachments/assets/cef79a9e-ddc9-4299-b3ff-492126e13ad2" />








Co-authored-by: taegyun.kim <taegyun.kim@datadoghq.com>
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 1550a86 to 3750446 Compare August 13, 2026 15:08
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from fee5719 to 4ec3922 Compare August 13, 2026 15:08
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 3750446 to 94e436d Compare August 13, 2026 15:10
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 4ec3922 to c37ab94 Compare August 13, 2026 15:10
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 94e436d to 61588e2 Compare August 13, 2026 18:17
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch 2 times, most recently from 20bb68d to 9011aa1 Compare August 13, 2026 19:44
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch 2 times, most recently from 08220b6 to f0490a5 Compare August 14, 2026 16:00
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 9011aa1 to 9fe9005 Compare August 14, 2026 16:00
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from f0490a5 to 5c53913 Compare August 17, 2026 18:33
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 9fe9005 to 005391f Compare August 17, 2026 18:33
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-task-span-links branch from 5c53913 to ed14a06 Compare August 17, 2026 19:03
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-logical-span-links branch from 005391f to e515c24 Compare August 17, 2026 19:03
@taegyunkim
taegyunkim merged commit 5ecd359 into taegyunkim/profiling-logical-span-links Aug 17, 2026
@taegyunkim

Copy link
Copy Markdown
Contributor Author

Superseded by #19736 after reordering the stack so the shared infrastructure and asyncio fix land first. GitHub marked this PR merged when its old base branch was restacked above its head; no code was merged to main.

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.

1 participant