Skip to content

fix(profiling): attribute copied-Context worker threads - #21329

Closed
taegyunkim wants to merge 13 commits into
mainfrom
taegyunkim/profiling-copied-context-workers
Closed

taegyunkim wants to merge 13 commits into
mainfrom
taegyunkim/profiling-copied-context-workers

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

This draft carries a stack of commits, so CI runs on all of them together. Review it commit by commit. Each commit is one change and builds on the ones before it. The first three commits are #21297.

Supersedes #19736, #19420 and #19737.

Problem. The stack profiler labels each sample with a span: span id, local root span id and trace endpoint. Today the label comes from the thread: the span that was last activated on that thread. That is wrong for code where one thread runs many units of work, or where a thread runs on behalf of another one:

  • Concurrent asyncio tasks on one thread borrow each other's spans and endpoints (the tests from test(profiling): add asyncio task span attribution tests #21236 show this).
  • gevent greenlets on one thread do the same.
  • Worker threads started by asyncio.to_thread or anyio.to_thread.run_sync run in a copy of the caller's contextvars.Context. Entering that copy activates no span, so their samples have no span, or one that never moves to the parent span when the span finishes.

Approach. The native span link table is keyed by execution unit: a thread, an asyncio task or a greenlet. A unit's entry is its key. The tracer's activation listener and a few creation hooks write keys. The sampler labels a sample with the key of the unit it ran, instead of the thread's.

Commit What it does
refactor(profiling): key native span links by execution unit (+2 follow-ups) Native storage keyed by thread, task or greenlet.
feat(profiling): expose keyed span link bindings Python bindings. The GIL is released only when the table lock is contended.
fix(profiling): publish span links with revalidation and retarget on finish Writes are checked against the profiler lifecycle. When a span finishes, or is discarded by a MicroVM identity refresh (trace.span_discard), keys that point at it move to its unfinished parent.
feat(profiling): snapshot per-unit span attribution in the sampler The sampler can read a task's or greenlet's key, behind a switch per domain that is off by default.
fix(profiling): render tasks of asyncio loops started without set_event_loop Loops run through asyncio.Runner(loop_factory=...) or a bare run_until_complete now render as tasks.
feat(profiling): track asyncio task span links Writes asyncio task keys: on activation, and at task creation from the creator's span.
fix(profiling): isolate asyncio task span attribution Turns the asyncio switch on.
fix(profiling): isolate gevent greenlet span attribution Writes greenlet keys and turns the greenlet switch on.
fix(profiling): attribute copied-Context worker threads Wraps asyncio.to_thread and anyio.to_thread.run_sync, so the worker's thread key gets the caller's span while the function runs.

Testing

  • Native: stack_test (C++ unit tests for the table, the sampler snapshot and the running-loop slots) passes from a fresh build.
  • Python end-to-end tests run the profiler in a subprocess, decode the pprof output and check each sample's labels:
    • asyncio: test_stack_asyncio_task_attribution.py, test_stack_asyncio_task_span_links.py, test_stack_asyncio_endpoint_labels.py (the strict xfails from test(profiling): add asyncio task span attribution tests #21236 are removed), test_asyncio_running_loop.py
    • gevent: test_stack_gevent_span_links.py, plus profiler cases in tests/opentelemetry/test_context.py
    • workers: test_stack_asyncio_to_thread_span_links.py, and test_stack_anyio_to_thread_span_links.py in a new profile-anyio suite
  • The concurrent-unit tests check that every sample of a unit carries that unit's span or no span. With the per-domain switch off, they fail.
  • Locally on Linux aarch64, in-tree build: the full tests/profiling suite on Python 3.9, 3.12 and 3.14, the gevent venv (3.12) and both uvloop venvs (3.9, 3.13), plus profile-anyio on 3.9 and 3.15. Python 3.10, 3.11 and 3.15 ran the changed test files only.

Risks

  • A task or greenlet whose inherited span the profiler cannot determine now shows no span until it activates one, instead of the thread's span. For asyncio this covers:
    • tasks created with asyncio.Task(...) directly
    • tasks from a custom task factory on Python 3.11 and earlier
    • tasks on loops that are neither BaseEventLoop subclasses nor uvloop
    • tasks under a context provider that overrides active()
    • tasks that existed when profiling started or were created while it was stopped
  • Echion, the native stack walker, can render one task's frames under another task in two cases. A sample may overlap the moment a task is created, exits, or starts or stops waiting. Or uvloop may be set up through uvloop.install() or a policy on Python 3.9 or 3.10, before asyncio.run(). Both happen on main too. With this change, those frames carry the other task's span instead of the thread's.
  • Worker stacks for asyncio.to_thread and anyio.to_thread.run_sync gain a run_in_worker frame. Eager asyncio tasks gain a wrapper frame.

Additional Notes

  • The profile-anyio lock files were generated on an aarch64 host, not with the canonical command. Run scripts/test-requirements lock profile-anyio on an x86-64 host before this leaves draft.
  • The two Echion rendering issues in Risks predate this change and are left for separate fixes.

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 83 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=120)
ddtrace.llmobs._integrations.claude_agent_sdk -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.typesafe -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=118)
ddtrace.llmobs._integrations.langchain -×-> 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

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Oct 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/context_meta.py                      @DataDog/profiling-python
ddtrace/internal/datadog/profiling/dd_wrapper/include/sample.hpp        @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/echion/echion/threads.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_running_loop.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/internal/datadog/profiling/stack/test/test_stack_renderer_span_labels.cpp  @DataDog/profiling-python
ddtrace/profiling/_asyncio.py                                           @DataDog/profiling-python
ddtrace/profiling/_copied_context_workers.py                            @DataDog/profiling-python
ddtrace/profiling/_gevent.py                                            @DataDog/profiling-python
ddtrace/profiling/_span_links.py                                        @DataDog/profiling-python
ddtrace/profiling/collector/_task.pyi                                   @DataDog/profiling-python
ddtrace/profiling/collector/_task.pyx                                   @DataDog/profiling-python
ddtrace/profiling/collector/stack.py                                    @DataDog/profiling-python
releasenotes/notes/profiling-asyncio-eager-task-wrapper-frame-8e3c5a1f9d2b4c67.yaml  @DataDog/apm-python
releasenotes/notes/profiling-asyncio-loop-without-set-event-loop-c0638f0647b55497.yaml  @DataDog/apm-python
releasenotes/notes/profiling-asyncio-task-span-isolation-3c52a8b1ab0734db.yaml  @DataDog/apm-python
releasenotes/notes/profiling-copied-context-workers-bd4a91229d5c103c.yaml  @DataDog/apm-python
releasenotes/notes/profiling-gevent-greenlet-span-attribution-91108159694de09a.yaml  @DataDog/apm-python
releasenotes/notes/profiling-span-link-finish-parent-5bdf22c4348d38dd.yaml  @DataDog/apm-python
tests/opentelemetry/test_context.py                                     @DataDog/apm-sdk-capabilities
tests/profiling/collector/test_asyncio_import_order.py                  @DataDog/profiling-python
tests/profiling/collector/test_asyncio_running_loop.py                  @DataDog/profiling-python
tests/profiling/collector/test_stack_anyio_to_thread_span_links.py      @DataDog/profiling-python
tests/profiling/collector/test_stack_asyncio_endpoint_labels.py         @DataDog/profiling-python
tests/profiling/collector/test_stack_asyncio_task_attribution.py        @DataDog/profiling-python
tests/profiling/collector/test_stack_asyncio_task_span_links.py         @DataDog/profiling-python
tests/profiling/collector/test_stack_asyncio_to_thread_span_links.py    @DataDog/profiling-python
tests/profiling/collector/test_stack_endpoint_labels.py                 @DataDog/profiling-python
tests/profiling/collector/test_stack_gevent_span_links.py               @DataDog/profiling-python
tests/profiling/collector/test_stack_keyed_span_links.py                @DataDog/profiling-python
tests/profiling/collector/test_stack_logical_attribution.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
tests/profiling/suitespec.yml                                           @DataDog/profiling-python
tests/profiling/test_context_meta.py                                    @DataDog/profiling-python
tests/requirements_locks/03ce24e62658.txt                               @DataDog/apm-python
tests/requirements_locks/12570ac5c1c0.txt                               @DataDog/apm-python
tests/requirements_locks/1e5df8b341c8.txt                               @DataDog/apm-python
tests/requirements_locks/29bddb792f5b.txt                               @DataDog/apm-python
tests/requirements_locks/3a3ea1a7c3db.txt                               @DataDog/apm-python
tests/requirements_locks/a478c3baab8f.txt                               @DataDog/apm-python
tests/requirements_locks/a8109753c3ae.txt                               @DataDog/apm-python

@pr-commenter

pr-commenter Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-09 20:44:26

Comparing candidate commit d7dc513 in PR branch taegyunkim/profiling-copied-context-workers with baseline commit 7c3de6e in branch main.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 625 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 [-693.292ns; +717.048ns] or [-6.458%; +6.680%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1738.159ns; +1942.611ns] or [-8.649%; +9.666%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1649.445ns; +1901.153ns] or [-8.488%; +9.784%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-352.775ns; +368.205ns] or [-8.155%; +8.511%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-221.373ns; +215.937ns] or [-8.113%; +7.913%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-88.505ns; +89.213ns] or [-5.941%; +5.989%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4473.444ns; +5014.085ns] or [-8.822%; +9.889%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-970.728ns; +974.388ns] or [-9.031%; +9.065%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-55706.510ns; +54423.059ns] or [-9.571%; +9.350%]

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

@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Pipelines  Tests

✨ Unblock PR with BitsAI

❌ Errors

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

🚦 2 Pipeline jobs failed

DDCI - DataDog/dd-trace-py | profiling/profile 23/25 — 🔧 Needs a code fix, caused by this PR

View more details · View in DDCI

DataDog/apm-reliability/dd-trace-py | profiling/profile 23/25 — 🔧 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: d7dc513 | Docs | View more details | Give us feedback!

…ministic

Bind the entry's optional to a local before dereferencing it so
bugprone-unchecked-optional-access can see the has_value() check.

The contention test relied on two threads overlapping on the mutex,
which valgrind's serialized scheduler never produced. Move the
try-lock-then-hook logic into run_locked and test it with a mutex that
another thread holds until the hook runs.
…finish

Move the stack profiler's span link writes to the keyed table, and
remove the native pending-link bookkeeping they replace.

- publish() writes a unit's key with stack.link, then checks whether
  the span finished in the meantime. retarget_finished() moves a key
  whose span finished to the span's unfinished parent under the default
  context provider's rules, or to no span otherwise.
- The span finish listener retargets the keys that hold the finished
  span, whichever thread finishes it.
- On start, the collector opens the links and republishes the span that
  is already active on the current thread. On stop it closes them first.
- context_meta.resolve() and span_info() turn the active item, a span or
  a propagated Context, into a link entry. inheritance_mode() tells
  whether the provider follows the default provider's active() rule.
- Remove link_span, unlink_span, clear_span and unlink_finished_span
  from the extension, with the native code behind them.
The sampler can now label asyncio task and greenlet samples with the span
linked to that task or greenlet, instead of the span of the thread they ran
on. Nothing writes task or greenlet keys yet, and both per-domain switches are
off by default, so rendering is unchanged.

- LogicalSpanReader reads the domain's switch and birth_watermark() once
  before Echion unwinds a thread. Each task or greenlet key is looked up after
  that unit's frames are copied, and a key born after the watermark is
  ignored, so a new object at a reused address never labels an old one.
- StackRenderer pushes span and origin-task labels once it knows whether the
  sample is a task or greenlet sample. An attributed sample gets only its own
  span, or none. Every sample keeps the origin-task labels.
- set_logical_attribution(domain, enabled) turns attribution on or off for
  SPAN_LINK_DOMAIN_ASYNCIO_TASK or SPAN_LINK_DOMAIN_GREENLET.
…nt_loop

The stack profiler only renders the tasks of a thread's configured loop, which
set_event_loop, uvloop.new_event_loop or late attachment record. Loops that run
without being set, such as asyncio.Runner(loop_factory=...) or a bare
loop.run_until_complete(), were sampled as plain threads.

Each native thread record now also has a running-loop slot, holding the plain
asyncio loop (BaseEventLoop) whose run_forever runs on the thread. Echion reads
effective_loop() and effective_uvloop() at every loop read site, including the
choice of the logical attribution domain for a thread: the running loop when
one is set, otherwise the configured loop.

- Python 3.13+: hooks on BaseEventLoop._run_forever_setup and
  _run_forever_cleanup set and clear the slot.
- Before 3.13: a hook on BaseEventLoop.run_forever does the same, guarded so
  that nested, closed or already-running calls do not touch the slot.
- Late attachment on 3.13+ fills the running slot with an unowned entry and
  leaves the configured slot alone. Before 3.13, for uvloop, and for loop
  classes that override run_forever, it keeps the configured slot. It now also
  sets uvloop mode for a uvloop loop when uvloop support is on.
- enter/exit take thread_info_map_lock with run_locked, the try_lock helper
  span links use, and the bindings pass ReleaseGilOnContention, so they
  release the GIL only on contention.
- Two tests in test_asyncio_import_order.py that start the profiler after the
  loop was created or started now pass, so their xfail markers are removed.
Write the span each asyncio task runs to the stack profiler's task keys: from the activation listener, from a creation hook on loop.create_task (BaseEventLoop and uvloop), and from the first step of eager tasks. A weakref erases a task's key when the task dies. Per-task attribution in the sampler stays off.
Turn on per-task attribution for asyncio tasks where the profiler
installs its task key writers. A sample of an asyncio task now carries
the span of that task's own key, or no span, instead of the span that
any task on the thread activated last.

Remove the strict xfails that #21236 added to the asyncio endpoint label
tests. Add end-to-end tests that decode profiles for inherited, eager,
finished, OpenTelemetry, uvloop and asyncio.Runner cases. The
concurrent-task tests check that every sample of each task carries that
task's span or no span, and they fail with per-task attribution off.

Some checks only count a task's own samples. Echion, the native stack
walker, can render one task's frames under another task in two cases
that predate this change: a sample that overlaps the moment a task
starts or stops waiting, and uvloop set up through uvloop.install() or
a policy before Python 3.11, where it does not find the loop boundary.
Each greenlet that the stack profiler tracks now gets its own span link
key, and greenlet samples use only that key, never the span of their
thread.

- The activation listener writes the current greenlet's key, keyed by
  gevent.thread.get_ident(greenlet), which is the id the sampler reads.
  It is the same stack.link call that writes the thread and asyncio
  task keys, so a greenlet that runs an asyncio loop gets the span of
  the task that activates it.
- _natively_tracked records the greenlets that stack.track_greenlet
  accepted. Only these get keys. A weak reference untracks a greenlet
  when it is collected, and untracking always clears its key.
- The greenlet tracer seeds a greenlet once per profiler lifecycle with
  the span it inherited in its own Context. This labels greenlets that
  ran before profiling started, that were suspended across a stop and a
  start, and, in a fork child, the suspended greenlets of the forking
  thread.
- Spawning a greenlet erases any key left at its address.
- The gevent support turns the Greenlet attribution switch on once it
  tracks greenlets. Unpatching gevent turns it off first.
asyncio.to_thread and anyio.to_thread.run_sync run a function on a
worker thread in a copy of the caller's Context. The worker inherits the
caller's active span, but entering that copy activates no span, so the
worker's thread key never got it. AnyIO worker samples had no span.
asyncio.to_thread worker samples had none either, or, with the futures
integration, a label that did not move to the parent when the span
finished.

- run_in_worker writes the inherited span to the worker's thread key
  before the function runs, and clears the key when it returns or
  raises. The function runs exactly once, and profiler errors never
  reach it.
- install() adds import hooks that wrap asyncio.threads.to_thread and
  anyio.to_thread.run_sync. The collector calls it on start, before
  the keyed span links open, and a module whose hook failed is retried
  on the next start.
- A new profile-anyio test suite covers AnyIO on the asyncio and trio
  backends.
@taegyunkim
taegyunkim force-pushed the taegyunkim/profiling-copied-context-workers branch from 0262d4a to a5e73bb Compare October 28, 2026 18:14
…copied-context-workers

# Conflicts:
#	ddtrace/internal/datadog/profiling/stack/test/CMakeLists.txt
#	ddtrace/profiling/collector/stack.py
Main removed opentracing from the default test dependencies, which changes every environment's lock hash. Regenerate the profile-anyio locks under their new hashes. Each lock differs from the old one only by the removed opentracing pin.
@taegyunkim

Copy link
Copy Markdown
Contributor Author

Closing in favor of smaller PRs, starting with #21653. The copied-Context worker change will come back as its own PR.

@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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant