feat: per-instance random source for deterministic behaviour#8
Merged
Conversation
Add WithRandomSource(src rand.Source) to allow per-instance control of the random sampling used to make shed/pass decisions. The source must be safe for concurrent use if the throttle is used concurrently. Follows the same pattern as WithNow and WithRejectedErrorFunc. Switch the package from math/rand to math/rand/v2. Update tests to use two fixed sources — alwaysShed (Uint64 returns 0) and neverShed (Uint64 returns MaxUint64) — replacing probabilistic assertions with exact ones throughout.
6db2104 to
cc7ce14
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
WithRandomSource(src rand.Source)— new per-instance option that controls the random draw used to decide whether a request is shed. Follows the same pattern asWithNowandWithRejectedErrorFunc. Falls back to the globalrand.Float64()when not set. The source must be safe for concurrent use if the throttle is used concurrently (same contract as the rest of the API — no implicit wrapping).math/rand→math/rand/v2— the package now uses the v2 API, available since Go 1.22 (our minimum version).Deterministic tests — two fixed sources (
alwaysShed,neverShed) replace every probabilistic assertion in the test suite. Tests that previously relied on "shed rate should be > 30%" or "P(all forwarded) < 0.01%" now assert exact outcomes. Also replaces the two real-time integration tests (TestAdaptiveThrottleRecovery,TestAdaptiveThrottleMinimumRate) with clock- and formula-based equivalents, and addsTestRejectionProbabilityFormulaandTestRejectionProbabilityPriorityCrossContaminationto verify the formulas directly.