Skip to content

refactor: move sampling interfaces to SpanData and Context - #19811

Draft
emmettbutler wants to merge 4 commits into
emmett.butler/native-context-2from
emmett.butler/native-context-3
Draft

refactor: move sampling interfaces to SpanData and Context#19811
emmettbutler wants to merge 4 commits into
emmett.butler/native-context-2from
emmett.butler/native-context-3

Conversation

@emmettbutler

Copy link
Copy Markdown
Collaborator

This change removes a layering violation between Span and sampling.py by moving the relevant functionality to SpanData and Context.

@emmettbutler
emmettbutler requested review from a team as code owners August 21, 2026 17:59
@emmettbutler
emmettbutler requested review from juanjux and rachelyangdog and removed request for a team August 21, 2026 17:59
@emmettbutler
emmettbutler marked this pull request as draft August 21, 2026 18:00
@emmettbutler emmettbutler added the changelog/no-changelog A changelog entry is not required for this PR. label Aug 21, 2026

@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: c88b419d1e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +610 to +612
let copied = parent
.bind(py)
.call_method1("copy", (trace_id_obj, span_id_obj))?;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Release the SpanData borrow before dispatching Context.copy

When a public Context subclass overrides copy() and that method reads the current span (for example via a context provider), call_method1 executes the override while this getter's &mut self still holds the span's mutable PyO3 borrow. The reentrant span read then fails with an Already mutably borrowed/PanicException, whereas the previous Python getter invoked parent.copy() without holding such a borrow. Split this into immutable-read, Python-call, and mutable-write phases so valid custom contexts cannot crash when a child first reads .context.

AGENTS.md reference: AGENTS.md:L11-L11

Useful? React with 👍 / 👎.

Comment thread ddtrace/_trace/span.py
Comment on lines +132 to +133
# `context`/`_context` (lazy build of this span's trace Context, cached on
# first read) are implemented natively on `SpanData` and inherited here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve context in the rendered Span API docs

docs/api.rst renders ddtrace.trace.Span with :members: but without :inherited-members:. Replacing the Python property with an inherited SpanData descriptor therefore removes context—including the detailed customer-facing documentation deleted here—from the generated Span API reference. Keep a documented forwarding property on Span or explicitly include and document this inherited member.

AGENTS.md reference: AGENTS.md:L24-L29

Useful? React with 👍 / 👎.

@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Aug 21, 2026

Copy link
Copy Markdown
Contributor

Pipelines  Tests

⚠️ Warnings

🚦 9 Pipeline jobs failed

DataDog/apm-reliability/dd-trace-py | build linux serverless: [amd64, cp315-cp315, v113741238-d2b8243-manylinux2014_x86_64, 1] — 🔧 Needs a code fix, caused by this PR

View in Datadog · View in GitLab

DataDog/apm-reliability/dd-trace-py | build linux serverless: [amd64, cp315-cp315, v126532274-233089d-musllinux_1_2_x86_64, 1] — 🔧 Needs a code fix, caused by this PR

View in Datadog · View in GitLab

DataDog/apm-reliability/dd-trace-py | build linux: [amd64, cp315-cp315, v113741238-d2b8243-manylinux2014_x86_64] — 🔧 Needs a code fix, caused by this PR

View in Datadog · View in GitLab

View all 9 failed jobs.

ℹ️ 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: bb2ee36 | Docs | View more details | Give us feedback!

Comment thread src/native/context/context_data.rs Outdated
@pr-commenter

pr-commenter Bot commented Aug 21, 2026

Copy link
Copy Markdown

Benchmarks

Benchmark execution time: 2026-08-21 20:31:27

Comparing candidate commit bb2ee36 in PR branch emmett.butler/native-context-3 with baseline commit 79d06af in branch emmett.butler/native-context-2.

📊 Benchmarking dashboard

Found 0 performance improvements and 11 performance regressions! Performance is the same for 601 metrics, 10 unstable metrics.

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-empty_headers

  • 🟥 execution_time [+42.190ns; +49.887ns] or [+7.478%; +8.842%]

scenario:httppropagationextract-tracecontext_headers

  • 🟥 execution_time [+2.290µs; +2.477µs] or [+7.207%; +7.797%]

scenario:httppropagationextract-wsgi_empty_headers

  • 🟥 execution_time [+44.545ns; +52.958ns] or [+7.881%; +9.370%]

scenario:httppropagationinject-ids_only

  • 🟥 execution_time [+1.972µs; +2.106µs] or [+11.972%; +12.786%]

scenario:iastaspects-casefold_noaspect

  • 🟥 execution_time [+28.911µs; +34.758µs] or [+11.526%; +13.857%]

scenario:iastaspects-join_aspect

  • 🟥 execution_time [+60.277µs; +64.782µs] or [+29.308%; +31.499%]

scenario:iastaspects-title_aspect

  • 🟥 execution_time [+41.724µs; +47.615µs] or [+15.565%; +17.763%]

scenario:iastaspectsospath-ospathbasename_aspect

  • 🟥 execution_time [+104.093µs; +111.523µs] or [+24.973%; +26.755%]

scenario:span-start

  • 🟥 execution_time [+1.133ms; +1.293ms] or [+8.028%; +9.159%]

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

  • 🟥 execution_time [+297.730ns; +345.438ns] or [+11.118%; +12.899%]

scenario:tracer-small

  • 🟥 execution_time [+26.460µs; +27.995µs] or [+8.007%; +8.471%]

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 [-627.050ns; +860.070ns] or [-5.704%; +7.824%]

scenario:coreapiscenario-core_dispatch_1_listener

  • unstable execution_time [-30.737ns; +35.608ns] or [-4.984%; +5.774%]

scenario:coreapiscenario-core_dispatch_50_listeners

  • unstable execution_time [-1555.080ns; +1771.821ns] or [-9.067%; +10.331%]

scenario:coreapiscenario-core_dispatch_exception_listeners

  • unstable execution_time [-1069.270ns; +1396.103ns] or [-8.332%; +10.879%]

scenario:coreapiscenario-core_dispatch_listeners

  • unstable execution_time [-333.478ns; +324.980ns] or [-9.023%; +8.793%]

scenario:coreapiscenario-core_dispatch_no_args_listeners

  • unstable execution_time [-238.565ns; +280.380ns] or [-8.099%; +9.519%]

scenario:coreapiscenario-core_dispatch_with_results_1_listener

  • unstable execution_time [-74.559ns; +73.819ns] or [-6.214%; +6.152%]

scenario:coreapiscenario-core_dispatch_with_results_50_listeners

  • unstable execution_time [-3912.761ns; +4047.462ns] or [-9.591%; +9.921%]

scenario:coreapiscenario-core_dispatch_with_results_listeners

  • unstable execution_time [-768.717ns; +804.835ns] or [-9.416%; +9.859%]

scenario:packagesupdateimporteddependencies-import_many_stdlib_cached

  • unstable execution_time [-64.012µs; +57.707µs] or [-9.943%; +8.964%]

Co-authored-by: Brett Langdon <brett.langdon@datadoghq.com>
@cit-pr-commenter-54b7da

Copy link
Copy Markdown

Codeowners resolved as

Resolved from the full PR diff against emmett.butler/native-context-2 using the target branch CODEOWNERS file.
CODEOWNERS team requests not listed below are not required by the current file set.

ddtrace/_trace/sampling_rule.py                                         @DataDog/apm-sdk-capabilities-python
ddtrace/_trace/span.py                                                  @DataDog/apm-sdk-capabilities-python @DataDog/apm-core-python
ddtrace/internal/native/_native.pyi                                     @DataDog/apm-core-python
ddtrace/internal/sampling.py                                            @DataDog/apm-sdk-capabilities-python
src/native/context/context_data.rs                                      @DataDog/apm-core-python
src/native/span/span_data.rs                                            @DataDog/apm-core-python

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 21, 2026

Copy link
Copy Markdown

Circular import analysis

⚠️ Existing circular imports

There are 3 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
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

@cit-pr-commenter-54b7da

cit-pr-commenter-54b7da Bot commented Aug 21, 2026

Copy link
Copy Markdown

Dependency direction analysis

⚠️ Existing dependency direction violations

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

Show existing violations (showing 5 of 242 highest severity)
ddtrace.internal.tracemethods -×-> ddtrace.trace  (internal-core -> product:tracing, score=134)
ddtrace.llmobs._integrations.llama_index -×-> ddtrace.trace  (product:llmobs -> product:tracing, score=132)
ddtrace.internal.opentelemetry.trace -×-> ddtrace.trace  (product:opentelemetry -> product:tracing, score=132)
ddtrace.profiling.collector.stack -×-> ddtrace.trace  (product:profiling -> product:tracing, score=132)
ddtrace.debugging._debugger -×-> ddtrace.trace  (product:debugging -> 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

✅ Dependency direction violations removed

1 violation(s) have been removed by this PR.

ddtrace.internal.sampling -×-> ddtrace._trace.span  (internal-core -> product:tracing, score=58)

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.

2 participants