Skip to content

test(sampling): make rate_limiter thread-safety test deterministic - #2354

Merged
gh-worker-dd-mergequeue-cf854d[bot] merged 2 commits into
mainfrom
ban/fix-flaky-rate-limiter-test
Aug 17, 2026
Merged

test(sampling): make rate_limiter thread-safety test deterministic#2354
gh-worker-dd-mergequeue-cf854d[bot] merged 2 commits into
mainfrom
ban/fix-flaky-rate-limiter-test

Conversation

@bantonsson

Copy link
Copy Markdown
Contributor

What does this PR do?

Replace the flaky test_rate_limiter_thread_safety test with three deterministic ones:

  • test_rate_limiter_thread_safety_no_panic: shared limiter under contention must not panic (smoke check, no count assertion).
  • test_rate_limiter_budget_invariant_concurrent: four threads race on a frozen clock; total allowed must be exactly 100 and the next request must be denied (no slack).
  • test_rate_limiter_window_reset_under_contention: drain a window, advance the mock clock past the boundary, race on the fresh window; the second budget must be exactly 10.

Motivation

The previous test_rate_limiter_thread_safety relied on wall-clock timing and asserted a loose 95..=105 range. On a loaded CI runner the 1s window could roll over or replenish could add tokens mid-test, letting the total drift outside the intended 100 while still passing. The ±5 slack also hid real bugs (lost updates, double-spend, token leak).

Additional Notes

Introduce a Clock abstraction (pub(crate) enum with System and test-only Mock variants) so RateLimiter reads time through an injectable source. new keeps using the real wall-clock; a new new_with_clock constructor lets tests drive a frozen, manually advanced clock. The Mock variant, MockClockInner, mock(), and advance() are #[cfg(test)]-gated so production builds carry no mock machinery or dead code.

No test in rate_limiter depends on wall-clock timing anymore.`p

How to test the change?

Run the tests.

@bantonsson
bantonsson requested a review from a team as a code owner August 17, 2026 09:01
@bantonsson bantonsson added the AI Generated PR largely written by AI tools label Aug 17, 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: c1b780c02a

ℹ️ About Codex in GitHub

Your team has set up Codex to 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 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread libdd-sampling/src/rate_limiter.rs
Comment thread libdd-sampling/src/rate_limiter.rs
@datadog-datadog-prod-us1-2

datadog-datadog-prod-us1-2 Bot commented Aug 17, 2026

Copy link
Copy Markdown

Tests

🎉 All green!

🧪 All tests passed
❄️ No new flaky tests detected

🎯 Code Coverage (details)
Patch Coverage: 99.03%
Overall Coverage: 76.53% (+0.06%)

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

@pr-commenter

pr-commenter Bot commented Aug 17, 2026

Copy link
Copy Markdown

Benchmarks

Comparison

Benchmark execution time: 2026-08-17 11:34:21

Comparing candidate commit 64ddac1 in PR branch ban/fix-flaky-rate-limiter-test with baseline commit 3cd2b36 in branch main.

Found 0 performance improvements and 7 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/multiple_rules_first_match/wall_time

  • 🟥 execution_time [+10.720ns; +10.873ns] or [+6.740%; +6.836%]

scenario:datadog_sample_span/resource_pattern_rule_matching/wall_time

  • 🟥 execution_time [+12.829ns; +13.286ns] or [+5.039%; +5.218%]

scenario:datadog_sample_span/service_rule_not_matching/wall_time

  • 🟥 execution_time [+7.865ns; +7.941ns] or [+5.869%; +5.925%]

scenario:datadog_sample_span/tag_rule_matching/wall_time

  • 🟥 execution_time [+23.281ns; +23.520ns] or [+7.227%; +7.301%]

scenario:datadog_sample_span/tag_rule_not_matching/wall_time

  • 🟥 execution_time [+11.017ns; +11.138ns] or [+7.836%; +7.922%]

scenario:glob_matcher/ascii_wildcard_backtrack_match/wall_time

  • 🟥 execution_time [+11.585ns; +11.606ns] or [+31.043%; +31.098%]

scenario:glob_matcher/ascii_wildcard_heavy_backtrack/wall_time

  • 🟥 execution_time [+10.562ns; +10.588ns] or [+25.695%; +25.757%]

Candidate

Omitted due to size.

Baseline

Omitted due to size.

@dd-octo-sts

dd-octo-sts Bot commented Aug 17, 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.so 8.20 MB 8.20 MB 0% (0 B) 👌
/aarch64-alpine-linux-musl/lib/libdatadog_profiling.a 89.46 MB 89.46 MB 0% (0 B) 👌
aarch64-unknown-linux-gnu
Artifact Baseline Commit Change
/aarch64-unknown-linux-gnu/lib/libdatadog_profiling.a 100.64 MB 100.64 MB 0% (0 B) 👌
/aarch64-unknown-linux-gnu/lib/libdatadog_profiling.so 11.06 MB 11.06 MB 0% (0 B) 👌
libdatadog-x64-windows
Artifact Baseline Commit Change
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.dll 26.62 MB 26.62 MB 0% (0 B) 👌
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.lib 94.56 KB 94.56 KB 0% (0 B) 👌
/libdatadog-x64-windows/debug/dynamic/datadog_profiling_ffi.pdb 180.62 MB 180.62 MB 0% (0 B) 👌
/libdatadog-x64-windows/debug/static/datadog_profiling_ffi.lib 771.67 MB 771.67 MB 0% (0 B) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.dll 8.72 MB 8.72 MB 0% (0 B) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.lib 94.56 KB 94.56 KB 0% (0 B) 👌
/libdatadog-x64-windows/release/dynamic/datadog_profiling_ffi.pdb 25.64 MB 25.64 MB 0% (0 B) 👌
/libdatadog-x64-windows/release/static/datadog_profiling_ffi.lib 51.06 MB 51.06 MB 0% (0 B) 👌
libdatadog-x86-windows
Artifact Baseline Commit Change
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.dll 23.20 MB 23.20 MB 0% (0 B) 👌
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.lib 96.04 KB 96.04 KB 0% (0 B) 👌
/libdatadog-x86-windows/debug/dynamic/datadog_profiling_ffi.pdb 185.60 MB 185.63 MB +.01% (+32.00 KB) 🔍
/libdatadog-x86-windows/debug/static/datadog_profiling_ffi.lib 759.92 MB 759.92 MB 0% (0 B) 👌
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.dll 6.74 MB 6.74 MB 0% (0 B) 👌
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.lib 96.04 KB 96.04 KB 0% (0 B) 👌
/libdatadog-x86-windows/release/dynamic/datadog_profiling_ffi.pdb 27.58 MB 27.58 MB 0% (0 B) 👌
/libdatadog-x86-windows/release/static/datadog_profiling_ffi.lib 48.61 MB 48.61 MB 0% (0 B) 👌
x86_64-alpine-linux-musl
Artifact Baseline Commit Change
/x86_64-alpine-linux-musl/lib/libdatadog_profiling.a 79.72 MB 79.72 MB 0% (0 B) 👌
/x86_64-alpine-linux-musl/lib/libdatadog_profiling.so 9.15 MB 9.15 MB 0% (0 B) 👌
x86_64-unknown-linux-gnu
Artifact Baseline Commit Change
/x86_64-unknown-linux-gnu/lib/libdatadog_profiling.a 95.38 MB 95.38 MB 0% (0 B) 👌
/x86_64-unknown-linux-gnu/lib/libdatadog_profiling.so 11.16 MB 11.16 MB 0% (0 B) 👌

The previous `test_rate_limiter_thread_safety` relied on wall-clock
timing and asserted a loose `95..=105` range. On a loaded CI runner the
1s window could roll over or `replenish` could add tokens mid-test,
letting the total drift outside the intended 100 while still passing.
The ±5 slack also hid real bugs (lost updates, double-spend, token leak).

Introduce a `Clock` abstraction (`pub(crate)` enum with `System` and
test-only `Mock` variants) so `RateLimiter` reads time through an
injectable source. `new` keeps using the real wall-clock; a new
`new_with_clock` constructor lets tests drive a frozen, manually
advanced clock. The `Mock` variant, `MockClockInner`, `mock()`, and
`advance()` are `#[cfg(test)]`-gated so production builds carry no mock
machinery or dead code.

Replace the flaky test with three deterministic ones:
- `test_rate_limiter_thread_safety_no_panic`: shared limiter under
  contention must not panic (smoke check, no count assertion).
- `test_rate_limiter_budget_invariant_concurrent`: four threads race on
  a frozen clock; total allowed must be exactly 100 and the next
  request must be denied (no slack).
- `test_rate_limiter_window_reset_under_contention`: drain a window,
  advance the mock clock past the boundary, race on the fresh window;
  the second budget must be exactly 10.

No test in `rate_limiter` depends on wall-clock timing anymore.
Two P2 comments from Codex:

1. Workers were not synchronized, so a scheduler could run each spawned
   thread to completion before the next starts, reducing the "concurrent"
   tests to sequential access. Add a `std::sync::Barrier` start gate to
   `test_rate_limiter_thread_safety_no_panic`,
   `test_rate_limiter_budget_invariant_concurrent`, and the race portion
   of `test_rate_limiter_window_reset_under_contention` so all workers
   reach the start line before any begins issuing requests, maximizing
   `is_allowed` overlap.

2. `test_rate_limiter_window_reset_under_contention` only verified token
   replenishment, not the `current_window_start` rollover in
   `update_rate_counts_locked`. Breaking the rollover logic would still
   pass because `replenish` alone restores the bucket. Restructure the
   test to use an asymmetric per-window allow/deny ratio (first window
   10/100 = 0.1, second window 10/10 = 1.0) and assert `effective_rate`
   after the reset: the expected (1.0 + 0.1)/2 = 0.55 can only occur if
   `prev_window_rate` was set and the counts were reset by the rollover.
   A mutation test (disabling the rollover branch) confirms the new
   assertion fails when the rollover is broken.
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.

2 participants