Skip to content

feat(sampling): Support for OpenTelemetry consistent tracestate sampling - #12397

Draft
MilanGarnier wants to merge 15 commits into
milan.garnier/otel-tracestate-refactorfrom
milan.garnier/ot.th
Draft

feat(sampling): Support for OpenTelemetry consistent tracestate sampling#12397
MilanGarnier wants to merge 15 commits into
milan.garnier/otel-tracestate-refactorfrom
milan.garnier/ot.th

Conversation

@MilanGarnier

@MilanGarnier MilanGarnier commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

What Does This Do

Adds OpenTelemetry consistent probability-sampling behavior on top of the
ot tracestate parsing introduced by #12405.

  • Validates and normalizes rv and th.
  • Generates probability state for loaded agent rates and sampling rules.
  • Preserves inherited randomness and unknown fields across overrides.
  • Keeps limiter outcomes distinct from raw probability decisions.
  • Adds focused parsing, propagation, continuation, and sampling tests.

Motivation

Make Java tracer sampling decisions interoperable with OpenTelemetry
consistent probability sampling and provide the state needed for downstream
tracestate propagation.

Additional Notes

Contributor Checklist

  • Format the title according to the contribution guidelines.
  • Assign the required type: and comp: labels.

Jira ticket: APMAPI-2171

@MilanGarnier MilanGarnier added type: feature Enhancements and improvements comp: context propagation Trace context propagation tag: ai generated Largely based on code generated by an AI or LLM labels Sep 3, 2026
@MilanGarnier MilanGarnier changed the title Support OpenTelemetry tracestate sampling feat(sampling): Support for OpenTelemetry consistent tracestate sampling Sep 3, 2026
@datadog-datadog-prod-us1-2

This comment has been minimized.

@dd-octo-sts

dd-octo-sts Bot commented Sep 3, 2026

Copy link
Copy Markdown
Contributor

🟢 Java Benchmark SLOs — All performance SLOs passed

Suite Status
Startup 🟢 pass

SLO thresholds are defined here based on automatically generated metrics. A warning is raised when results are within 5% of the threshold.

PR vs. master results
Scenario Candidate master Δ (95% CI of mean)
startup:insecure-bank:iast:Agent 14.84 s 14.68 s [+0.3%; +1.9%] (maybe worse)
startup:insecure-bank:tracing:Agent 13.65 s 13.67 s [-1.2%; +0.9%] (no difference)
startup:petclinic:appsec:Agent 17.48 s 17.38 s [-0.4%; +1.5%] (no difference)
startup:petclinic:iast:Agent 17.30 s 16.91 s [-1.9%; +6.6%] (no difference)
startup:petclinic:profiling:Agent 17.37 s 16.59 s [+0.4%; +9.0%] (maybe worse)
startup:petclinic:sca:Agent 17.35 s 17.42 s [-1.4%; +0.6%] (no difference)
startup:petclinic:tracing:Agent 16.57 s 16.69 s [-1.7%; +0.3%] (no difference)

Commit: 7772c8c7 · CI Pipeline · Benchmarking Platform UI


Load and DaCapo benchmarks can be triggered manually in the GitLab pipeline. Results will appear in the Benchmarking Platform UI after completion.

@MilanGarnier
MilanGarnier changed the base branch from master to milan.garnier/preserve-deterministic-sampler-rate September 3, 2026 13:59
Base automatically changed from milan.garnier/preserve-deterministic-sampler-rate to master September 3, 2026 18:45
@MilanGarnier
MilanGarnier changed the base branch from master to milan.garnier/otel-tracestate-refactor September 4, 2026 09:30
@MilanGarnier
MilanGarnier force-pushed the milan.garnier/ot.th branch 5 times, most recently from 7a1ddea to a0176c9 Compare September 8, 2026 14:26
@MilanGarnier

Copy link
Copy Markdown
Contributor Author

@codex review

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

ℹ️ 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 thread dd-trace-core/src/main/java/datadog/trace/core/DDSpanContext.java
@MilanGarnier
MilanGarnier marked this pull request as ready for review September 10, 2026 09:02
@MilanGarnier
MilanGarnier requested review from a team as code owners September 10, 2026 09:02
@MilanGarnier
MilanGarnier requested review from mhlidd and removed request for a team September 10, 2026 09:02

@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: 629892d492

ℹ️ 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 thread dd-trace-core/src/main/java/datadog/trace/core/propagation/HttpCodec.java Outdated
Comment on lines +654 to +658
if (setSamplingPriorityWithRate(samplingPriority, rate, sampleRate, samplingMechanism)
&& probabilitySamplingResult != null) {
context
.getPropagationTags()
.updateOtelTraceState(

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 Publish probability state before exposing the decision

When sibling spans inject concurrently on a trace whose priority is initially unset, setSamplingPriorityWithRate publishes the non-UNSET priority before this separate OTel-state update. Another injector can therefore skip sampling and serialize a W3C header without rv/th; if it finishes caching that header after this thread clears the cache, the stale header can remain cached for every later injection on the trace. Update the priority and probability state coherently, or prevent header construction from observing and caching this intermediate state.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm unsure whether this is a real issue or not, and if it is real, what is the best way to mitigate it

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Confirmed this is real, not just theoretical — walking through the exact sequence:

  1. DDSpan.setSamplingPriority(...) calls context.setSamplingPriority(...) first, publishing the new non-UNSET priority. Only afterward does it call updateOtelTraceState(...) to update otelTraceState/otelSamplingDecision.
  2. In the window between those two steps, a sibling span's injector can observe the now-published priority and take the headerCache miss path in PTagsFactory.PTags.headerValue(HeaderType) (PTagsFactory.java ~445-464). It computes a header via resolveOtelTraceState(headerType, samplingPriority) using the new priority but the still-stale otelTraceState/otelSamplingDecision — producing a header without rv/th — and caches it via setCachedHeader (plain field write, no version check).
  3. If that cache write lands after step 1's later call to clearCachedHeader(W3C) (triggered by setOtelTraceState/setOtelSamplingDecision once the real update happens), the incomplete header is now permanently cached — nothing clears it again — and every subsequent injection on the trace serializes a W3C header missing the OTel probability-sampling fields.

So this needs to be fixed, not just accepted as a known edge case. The cleanest mitigation is probably to make the priority publish and the OTel-state update atomic from the perspective of headerValue() — e.g. compute/set both under the same guard that setSamplingPriority uses, so no reader can observe the new priority before the OTel state that goes with it.

@datadog-datadog-prod-us1-2 datadog-datadog-prod-us1-2 Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Datadog Autotest: FAIL

Compound extraction can emit a W3C sampled flag that conflicts with the propagated OTel probability threshold when propagation styles have different sampling decisions.

Open Bits AI session

🤖 Datadog Autotest · Commit 3c81345 · What is Autotest? · @DataDog review to ask questions · Any feedback? Reach out in #autotest

boolean sampled = sampler.sample(span);
int samplingPriority = sampled ? PrioritySampling.SAMPLER_KEEP : PrioritySampling.SAMPLER_DROP;

Boolean probabilitySamplingResult = rates.hasAgentRates() ? sampled : null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

probabilitySamplingResult is gated on rates.hasAgentRates() — a flag for the whole RateSamplersByEnvAndService snapshot — rather than whether this span's sampling decision actually came from an agent-provided rate.

hasAgentRates is set true as soon as any entry in the agent's rate update is non-null (line ~121), for the entire snapshot across all env/service combinations. But rates.getSampler(env, serviceName) can still fall through to fallbackSampler (the hardcoded DEFAULT_SAMPLER, not agent-derived) for any env/service combination the agent didn't send a rate for. In that case sampled comes from the default sampler, yet probabilitySamplingResult is still computed as non-null (since hasAgentRates is true snapshot-wide) — so DDSpan.setSamplingPriority(..., probabilitySamplingResult) injects an OTel consistent-sampling probability decision (rv/th) into the span's tracestate that misrepresents an unrelated default-sampler decision as agent-rate-based probability sampling.

Compare with RuleBasedTraceSampler elsewhere in this PR, which correctly ties probabilitySamplingResult to the matched rule for that specific span rather than a class-wide flag. This one should probably check whether sampler (the one actually used for this span) came from an agent rate vs. the fallback, not whether the snapshot contains any agent rate at all.

original.startsWith(DATADOG_MEMBER_KEY, memberStart)
|| original.startsWith(OTEL_MEMBER_KEY, memberStart);
if (!managedMember) {
boolean datadogMember = original.startsWith(DATADOG_MEMBER_KEY, memberStart);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

appendOtelAndVendorMembers, when called with preserveDatadogMember=true (the new OTLP-export path via getW3CTracestate(int)), copies every member matching original.startsWith(DATADOG_MEMBER_KEY, memberStart) verbatim into the output. Contrast with fromHeaderValue's extraction parser (line 73), which guards the same check with ddMemberIndex == -1 so only the first dd= member is ever recognized/kept.

If an inbound W3C tracestate somehow contains more than one dd= member (malformed, but stored verbatim as tracestate at extraction since nothing here validates uniqueness on the way in), this loop will re-emit all of them into the OTLP-exported traceState, producing a tracestate with duplicate list-member keys — invalid per the W3C tracestate spec (https://www.w3.org/TR/trace-context/#tracestate-header-field-values, "duplicated with the same key MUST be discarded"). Worth applying the same first-occurrence guard here that extraction already uses.


String tracestate = propagationTags.getW3CTracestate();
int samplingPriority = span.samplingPriority();
// TODO Cache the effective tracestate once per trace.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

getW3CTracestate(samplingPriority) bypasses headerCache entirely and unconditionally calls W3CPTagsCodec.updateOtelTraceState(this, resolved), which fully re-parses the original tracestate and rebuilds it with a fresh StringBuilder — even though OtelSamplingDecision.resolve() already caches the resolved decision per trace. For an N-span trace exported via OTLP (this call runs once per span, same TODO duplicated in OtlpTraceProto.java:95), that's O(N) redundant identical string rebuilds instead of O(1).

Given this is on the OTLP export hot path and scales with span count, this is worth fixing rather than leaving as a TODO — every tracer feature that adds a per-span cost here compounds for every other product exporting via OTLP. A per-trace cache keyed on the resolved OtelTraceState/OtelSamplingDecision (mirroring how headerCache already works for headerValue()) would turn this back into O(1) per trace.

} else if (hasKey(raw, start, end, separator, 't', 'h')) {
boolean validThresholdLength = fieldValueStart < end && end - fieldValueStart <= HEX_DIGITS;
long parsedThreshold =
validThresholdLength ? parseLowercaseHex(raw, fieldValueStart, end) : NO_VALUE;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

th omits trailing zeros, so this needs to be right-padded to 14 digits before conversion. For example, th:8 represents 0x80000000000000, but this currently parses it as numeric 8.

}

@Override
public String getW3CTracestate(int samplingPriority) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

OtelTraceState.parse() may normalize the ot member while tracestate remains raw. Is returning the raw value here intentional? It preserves the previous OTLP behavior, but means invalid nested rv/th fields are still exported whenever resolution leaves the state unchanged.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I was not intending to put the OTLP trace export in this PR but rather later in the stack

@MilanGarnier
MilanGarnier marked this pull request as draft September 11, 2026 15:59
@MilanGarnier

Copy link
Copy Markdown
Contributor Author

I got more ideas today on how to have a cleaner design so I'll refactor this before re-asking for review

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

Labels

comp: context propagation Trace context propagation tag: ai generated Largely based on code generated by an AI or LLM type: feature Enhancements and improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants