Skip to content

feat(sampling): OTel consistent-probability rv/th derivation (APMAPI-2181) - #2276

Open
MilanGarnier wants to merge 13 commits into
mainfrom
milan.garnier/otel-consistent-sampling
Open

feat(sampling): OTel consistent-probability rv/th derivation (APMAPI-2181)#2276
MilanGarnier wants to merge 13 commits into
mainfrom
milan.garnier/otel-consistent-sampling

Conversation

@MilanGarnier

@MilanGarnier MilanGarnier commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Adds a public API to emit OpenTelemetry consistent-probability-sampling tracestate (ot.th/ot.rv). https://opentelemetry.io/docs/specs/otel/trace/tracestate-probability-sampling/

Part of APMAPI-2170 (OTel consistent probability sampling across dd-trace-*).

Changes

  • SamplingMechanism::is_probability() — classifies rate-driven mechanisms
  • OtelConsistentSampling { rv, th } +
  • TraceRootSamplingInfo::otel_consistent_sampling(trace_id) returns Some(OtelConsistentSampling) for a probability decision

Tests

Tests from system-tests #7372
cargo test -p libdd-sampling

@github-actions

github-actions Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

📚 Documentation Check Results

⚠️ 180 documentation warning(s) found

📦 libdd-sampling - 180 warning(s)


Updated: 2026-08-06 15:20:30 UTC | Commit: fa6af2b | missing-docs job results

@github-actions

github-actions Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

🔒 Cargo Deny Results

⚠️ 2 issue(s) found, showing only errors (advisories, bans, sources)

📦 libdd-sampling - 2 error(s)

Show output
error[vulnerability]: Invalid pointer dereference in `fmt::Pointer` impl for `Atomic` and `Shared` when the underlying pointer is invalid
   ┌─ /home/runner/work/libdatadog/libdatadog/Cargo.lock:30:1
   │
30 │ crossbeam-epoch 0.9.18 registry+https://github.com/rust-lang/crates.io-index
   │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ security vulnerability detected
   │
   ├ ID: RUSTSEC-2026-0204
   ├ Advisory: https://rustsec.org/advisories/RUSTSEC-2026-0204
   ├ Affected versions of `fmt::Display` dereference the underlying pointer. This causes a invalid pointer dereference e.g., when a pointer created with `Atomic::null` or `Shared::null`. `fmt::Debug` impls and pre-0.9 `fmt::Display` impls, which do not dereference pointers, are not affected by this issue.
   ├ Announcement: https://github.com/crossbeam-rs/crossbeam/pull/1276
   ├ Solution: Upgrade to >=0.9.20 (try `cargo update -p crossbeam-epoch`)
   ├ crossbeam-epoch v0.9.18
     └── crossbeam-deque v0.8.5
         └── rayon-core v1.12.1
             └── rayon v1.10.0
                 └── criterion v0.5.1
                     ├── libdd-common v5.1.0
                     │   └── libdd-sampling v5.0.0
                     └── (dev) libdd-sampling v5.0.0 (*)

error[unsound]: Rand is unsound with a custom logger using `rand::rng()`
   ┌─ /home/runner/work/libdatadog/libdatadog/Cargo.lock:97:1
   │
97 │ rand 0.8.5 registry+https://github.com/rust-lang/crates.io-index
   │ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ unsound advisory detected
   │
   ├ ID: RUSTSEC-2026-0097
   ├ Advisory: https://rustsec.org/advisories/RUSTSEC-2026-0097
   ├ It has been reported (by [@lopopolo](https://github.com/lopopolo)) that the `rand` library is [unsound](https://rust-lang.github.io/unsafe-code-guidelines/glossary.html#soundness-of-code--of-a-library) (i.e. that safe code using the public API can cause Undefined Behaviour) when all the following conditions are met:
     
     - The `log` and `thread_rng` features are enabled
     - A [custom logger](https://docs.rs/log/latest/log/#implementing-a-logger) is defined
     - The custom logger accesses `rand::rng()` (previously `rand::thread_rng()`) and calls any `TryRng` (previously `RngCore`) methods on `ThreadRng`
     - The `ThreadRng` (attempts to) reseed while called from the custom logger (this happens every 64 kB of generated data)
     - Trace-level logging is enabled or warn-level logging is enabled and the random source (the `getrandom` crate) is unable to provide a new seed
     
     `TryRng` (previously `RngCore`) methods for `ThreadRng` use `unsafe` code to cast `*mut BlockRng<ReseedingCore>` to `&mut BlockRng<ReseedingCore>`. When all the above conditions are met this results in an aliased mutable reference, violating the Stacked Borrows rules. Miri is able to detect this violation in sample code. Since construction of [aliased mutable references is Undefined Behaviour](https://doc.rust-lang.org/stable/nomicon/references.html), the behaviour of optimized builds is hard to predict.
   ├ Announcement: https://github.com/rust-random/rand/pull/1763
   ├ Solution: Upgrade to >=0.10.1 OR <0.10.0, >=0.9.3 OR <0.9.0, >=0.8.6 (try `cargo update -p rand`)
   ├ rand v0.8.5
     └── (dev) libdd-common v5.1.0
         └── libdd-sampling v5.0.0

advisories FAILED, bans ok, sources ok

Updated: 2026-08-06 15:19:02 UTC | Commit: fa6af2b | dependency-check job results

@datadog-datadog-prod-us1

datadog-datadog-prod-us1 Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Pipelines  Tests

⚠️ Warnings

🚦 2 Pipeline jobs failed

Lint | Valid LICENSE-3rdparty.csv   View in Datadog   GitHub Actions

🔄 Retry job. This looks flaky and may succeed on retry. Failed to resolve action download info. Service Unavailable.

Required checks pass | allchecks   View in Datadog   GitHub Actions

See error Some checks have failed or timed out. View workflow run summary for details.

ℹ️ Info

No other issues found (see more)

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
Patch Coverage: 100.00%
Overall Coverage: 76.22% (+0.67%)

Useful? React with 👍 / 👎

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

@pr-commenter

pr-commenter Bot commented Jul 27, 2026

Copy link
Copy Markdown

Benchmarks

Comparison

Benchmark execution time: 2026-08-06 15:36:41

Comparing candidate commit 532f4fb in PR branch milan.garnier/otel-consistent-sampling with baseline commit f3d3d80 in branch main.

Found 6 performance improvements and 1 performance regressions! Performance is the same for 41 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:datadog_sample_span/tag_rule_matching/wall_time

  • 🟥 execution_time [+17.065ns; +17.321ns] or [+5.239%; +5.318%]

scenario:glob_matcher/ascii_case_insensitive_match/wall_time

  • 🟩 execution_time [-1.308ns; -1.222ns] or [-4.462%; -4.169%]

scenario:glob_matcher/ascii_exact_match/wall_time

  • 🟩 execution_time [-1.958ns; -1.878ns] or [-6.686%; -6.412%]

scenario:glob_matcher/ascii_exact_miss/wall_time

  • 🟩 execution_time [-1.695ns; -1.656ns] or [-11.524%; -11.261%]

scenario:glob_matcher/unicode_exact_match/wall_time

  • 🟩 execution_time [-6.841ns; -6.801ns] or [-8.557%; -8.506%]

scenario:glob_matcher/unicode_pattern_ascii_subject/wall_time

  • 🟩 execution_time [-4.393ns; -4.335ns] or [-4.659%; -4.598%]

scenario:glob_matcher/unicode_pattern_wildcard_match/wall_time

  • 🟩 execution_time [-9.272ns; -9.217ns] or [-6.983%; -6.941%]

Candidate

Omitted due to size.

Baseline

Omitted due to size.

@dd-octo-sts

dd-octo-sts Bot commented Jul 27, 2026

Copy link
Copy Markdown
Contributor

Artifact Size Benchmark Report

aarch64-alpine-linux-musl
Artifact Baseline Commit Change
/aarch64-alpine-linux-musl/lib/libdatadog_profiling.a 87.32 MB 87.32 MB 0% (0 B) 👌
/aarch64-alpine-linux-musl/lib/libdatadog_profiling.so 8.01 MB 8.01 MB 0% (0 B) 👌
aarch64-unknown-linux-gnu
Artifact Baseline Commit Change
/aarch64-unknown-linux-gnu/lib/libdatadog_profiling.a 98.55 MB 98.55 MB 0% (0 B) 👌
/aarch64-unknown-linux-gnu/lib/libdatadog_profiling.so 10.78 MB 10.78 MB 0% (0 B) 👌
libdatadog-x64-windows
Artifact Baseline Commit Change
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.dll 26.05 MB 26.05 MB 0% (0 B) 👌
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.lib 89.60 KB 89.60 KB 0% (0 B) 👌
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.pdb 188.11 MB 188.10 MB -0% (-8.00 KB) 👌
/libdatadog-x64-windows/debug/static/datadog_profiling_ffi.lib 980.77 MB 980.77 MB 0% (0 B) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.dll 8.49 MB 8.49 MB 0% (0 B) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.lib 89.60 KB 89.60 KB 0% (0 B) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.pdb 25.10 MB 25.10 MB 0% (0 B) 👌
/libdatadog-x64-windows/release/static/datadog_profiling_ffi.lib 49.93 MB 49.93 MB 0% (0 B) 👌
libdatadog-x86-windows
Artifact Baseline Commit Change
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.dll 22.69 MB 22.69 MB 0% (0 B) 👌
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.lib 91.00 KB 91.00 KB 0% (0 B) 👌
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.pdb 192.87 MB 192.86 MB -0% (-8.00 KB) 👌
/libdatadog-x86-windows/debug/static/datadog_profiling_ffi.lib 969.41 MB 969.41 MB 0% (0 B) 👌
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.dll 6.56 MB 6.56 MB 0% (0 B) 👌
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.lib 91.00 KB 91.00 KB 0% (0 B) 👌
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.pdb 26.97 MB 26.97 MB 0% (0 B) 👌
/libdatadog-x86-windows/release/static/datadog_profiling_ffi.lib 47.53 MB 47.53 MB 0% (0 B) 👌
x86_64-alpine-linux-musl
Artifact Baseline Commit Change
/x86_64-alpine-linux-musl/lib/libdatadog_profiling.a 77.87 MB 77.87 MB 0% (0 B) 👌
/x86_64-alpine-linux-musl/lib/libdatadog_profiling.so 8.93 MB 8.93 MB 0% (0 B) 👌
x86_64-unknown-linux-gnu
Artifact Baseline Commit Change
/x86_64-unknown-linux-gnu/lib/libdatadog_profiling.a 93.36 MB 93.36 MB 0% (0 B) 👌
/x86_64-unknown-linux-gnu/lib/libdatadog_profiling.so 10.87 MB 10.87 MB 0% (0 B) 👌

MilanGarnier and others added 8 commits July 27, 2026 13:44
Compute th as round(2^56*(1-rate)) via 2^56 - round(2^56*rate) (exact,
avoids the single-shot IEEE-754 rounding the RFC warns against), and
return None from otel_consistent_sampling when a probability keep was
overturned by the trace rate limiter (rl_effective_rate set).
Use exact integer arithmetic over the canonical 6-decimal rate (the
form format_sampling_rate / dd= already use) so th reproduces the RFC
imprecision-appendix's decimal table (0.2 -> cccccccccccccd,
0.99 -> 028f5c28f5c28f), which an f64 pipeline cannot represent.
@MilanGarnier
MilanGarnier marked this pull request as ready for review July 28, 2026 14:57
@MilanGarnier
MilanGarnier requested a review from a team as a code owner July 28, 2026 14:57

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

ℹ️ 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 libdd-sampling/src/datadog_sampler.rs Outdated
Comment thread libdd-sampling/src/datadog_sampler.rs Outdated
@MilanGarnier
MilanGarnier changed the base branch from main to milan.garnier/otel-rate-limiter-effective-rate July 28, 2026 16:35
@MilanGarnier
MilanGarnier marked this pull request as draft July 30, 2026 16:02
Base automatically changed from milan.garnier/otel-rate-limiter-effective-rate to main July 30, 2026 17:22
@MilanGarnier
MilanGarnier marked this pull request as ready for review July 31, 2026 12:51

@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: 99ec5bae75

ℹ️ 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 libdd-sampling/src/datadog_sampler.rs
@MilanGarnier
MilanGarnier force-pushed the milan.garnier/otel-consistent-sampling branch from 99ec5ba to 984c9f7 Compare August 3, 2026 08:52
Comment thread libdd-sampling/src/datadog_sampler.rs
@MilanGarnier
MilanGarnier requested a review from bantonsson August 6, 2026 08:46

@bantonsson bantonsson 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.

The PR description is messy and confusing. It says:

th = round(2^56 * (1 - rate_micros / 1_000_000)) (56-bit), on the rate rounded to 6 decimals so it
matches the RFC appendix's imprecision table rather than a float
(1.0 - rate) * 2^56

But the code does exactly (1.0 - rate) * 2^56, or am I missing something?

Also, the test code in DataDog/system-tests#7372 does truncation, ie int(...) but this code does .round().

Please clean up the description and change the code.

fn derive_th(rate: f64) -> u64 {
const U56_MOD: u64 = 1u64 << 56;
const U56_MAX: u64 = U56_MOD - 1;
(((1.0 - rate) * U56_MOD as f64).round() as u64).clamp(0, U56_MAX)

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.

Are you sure this is a good idea?
f64 have 53 bits of precision, and you are doing 56 bits arithmetic. So when you cast back to u64, if 1.0 - rate is bigger than 1/8th you will collapse the lower bits of your result together

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.

I think that the system tests also suffer from this issue. This is the code that the OTel spec for this points to as an example https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/pkg/sampling/probability.go

@MilanGarnier MilanGarnier Aug 6, 2026

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.

The spec we used as a basis (and also for system tests) is https://opentelemetry.io/docs/specs/otel/trace/tracestate-probability-sampling/
The code you linked also uses round and then the part about adding precision I'm not exactly sure to understand why we would need this.

About system-tests, although the comment says int(), the values are calculated with round() and the go tracer opted for round() as well https://github.com/DataDog/dd-trace-go/pull/5060/changes

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.

About doing 1.0 - rate, I understand it would be better to do the operations in 56 bit arithmetic (converting rate to a 56 bit int before), this is just a different implem from what we went for with the go tracer and system tests already @paullegranddc

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.

An alternative would be to do

fn derive_th(rate: f64) -> u64 {
    const U56_MOD: u64 = 1u64 << 56;
    const U56_MAX: u64 = U56_MOD - 1;
    U56_MAX - ((U56_MOD as f64 * rate) as u64).clamp(0, U56_MAX)
}

This would not pass the current system tests in their current form
WDYT ?

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.

The thing I'm most confused about is why the code and system tests don't do what the spec says:

OpenTelemetry SDKs are recommended to use 4 digits of precision by default.

Why do we compare the full hex representation and not only to 4 digits of precision?

Also, the comments in system tests must be very explicit (and correct) about how the values are computed and what precision is expected of the tracers.

@MilanGarnier
MilanGarnier force-pushed the milan.garnier/otel-consistent-sampling branch from 4a4cfad to 532f4fb Compare August 6, 2026 15:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants