Skip to content

chore(profiling): read span labels from a contextvars.Context without the GIL - #22109

Draft
taegyunkim wants to merge 1 commit into
taegyunkim/profiling-span-layout-descriptorfrom
taegyunkim/profiling-context-reader
Draft

taegyunkim wants to merge 1 commit into
taegyunkim/profiling-span-layout-descriptorfrom
taegyunkim/profiling-context-reader

Conversation

@taegyunkim

@taegyunkim taegyunkim commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor

Description

A step toward attributing asyncio task samples to the task's own span (PROF-16348). Stacked on #22069.

This adds an Echion reader that finds DD_CONTEXTVAR in a contextvars.Context by walking CPython's HAMT from raw memory. It resolves the active span the way DefaultContextProvider.active() does, and computes the labels StackCollector._link_span attaches. It uses Echion's fault-safe copy and does no allocation, locking or Python calls, so the CPU timer's signal handler can later reuse it with a different copy function. Every walk is bounded.

CPython doesn't export its HAMT node types, so stack.start() finds them from live Contexts, which also checks the struct mirrors. On any mismatch the reader stays disabled.

The sampler doesn't use the reader yet. Test-only bindings expose it so Python tests can compare it with the tracer.

Customer impact

None. The reader isn't used for samples yet.

Testing

  • Native gtests cover bitmap, array and collision nodes, depth and copy limits, unreadable memory, span subclasses and each label rule on a fake heap, plus lookups in live Contexts. I ran them on CPython 3.9, 3.12, 3.13, 3.14 and 3.15 (Linux aarch64).
  • test_stack_context_reader.py compares the reader with active() and _link_span across fixed scenarios and 300 random span trees, on 3.9 to 3.15.
  • Reader init takes about 36 µs once per process (3.13, median of 30).

Risks

None for samples. At stack.start(), the startup check creates a few dozen ContextVars in private Contexts.

Additional Notes

A span id of 0 gives no labels, unlike _link_span.

… the GIL

Add an Echion reader that finds the tracer's context variable in a
contextvars.Context by walking CPython's HAMT from raw memory, resolves the
active span the way DefaultContextProvider.active() does, and computes the
labels StackCollector._link_span attaches. It uses Echion's fault-safe copy,
does no allocation, locking or Python calls, and bounds every walk. The HAMT
node types are found at startup from live objects, and the reader stays
disabled if the layout does not check out.

The reader is not used by the sampler yet. Test-only bindings expose it so
Python tests can compare it with the tracer.
@taegyunkim taegyunkim added the changelog/no-changelog A changelog entry is not required for this PR. label Nov 25, 2026
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 22 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=103)
ddtrace.llmobs._integrations.base -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.llmobs._integrations.bedrock_agents -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=101)
ddtrace.internal.span_bus -×-> ddtrace._trace.span  (internal-core -> product:tracing, score=35)
ddtrace.llmobs._llmobs -×-> ddtrace._trace.span  (product:llmobs -> product:tracing, score=33)

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

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against taegyunkim/profiling-span-layout-descriptor 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/CMakeLists.txt                 @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/_stack.pyi                     @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/context_labels.h  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/echion/echion/cpython/context.h  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/echion/context_labels.cc   @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/src/stack.cpp                  @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/CMakeLists.txt            @DataDog/profiling-python
ddtrace/internal/datadog/profiling/stack/test/test_context_labels.cpp   @DataDog/profiling-python
tests/profiling/collector/test_stack_context_reader.py                  @DataDog/profiling-python

@pr-commenter

pr-commenter Bot commented Nov 26, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-11-26 00:22:44

Comparing candidate commit 74fa5f1 in PR branch taegyunkim/profiling-context-reader with baseline commit dd77e88 in branch taegyunkim/profiling-span-layout-descriptor.

📊 Benchmarking dashboard

Found 0 performance improvements and 0 performance regressions! Performance is the same for 593 metrics, 10 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 [-681.151ns; +703.880ns] or [-6.376%; +6.589%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-37.733ns; +37.666ns] or [-5.874%; +5.864%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1815.991ns; +1816.805ns] or [-9.064%; +9.068%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1722.739ns; +1774.948ns] or [-8.975%; +9.247%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-366.966ns; +349.104ns] or [-8.543%; +8.127%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-221.879ns; +215.917ns] or [-8.245%; +8.024%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-81.225ns; +89.969ns] or [-5.961%; +6.602%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-4545.244ns; +4429.088ns] or [-9.386%; +9.146%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-963.175ns; +861.104ns] or [-9.465%; +8.462%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-52.530µs; +61.505µs] or [-8.927%; +10.452%]

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

changelog/no-changelog A changelog entry is not required for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant