Fix integer-range bugs in absl::log_uniform_int_distribution. Previously, floating-point `log`/`pow` bucket math and signed `result_type` casts caused misbehavior on large or signed ranges: * For `base > 2`, `double` rounding could drop exact-power endpoints (e.g. `10^15` in base 10), create spurious singleton top buckets (e.g. `5^26 - 1` in base 5), or trigger `[conv.fpint]` float-to-int overflow UB at `UINT64_MAX`. * Casting unsigned bucket offsets `[lo, hi]` to signed `result_type` before sampling inverted `lo > hi` whenever `min < 0` and `max - min > INT_MAX`. Output sequences change for affected `base > 2` and wide signed ranges; `absl::log_uniform_int_distribution` does not guarantee cross-release stability. PiperOrigin-RevId: 1022527247
diff --git a/absl/random/log_uniform_int_distribution.h b/absl/random/log_uniform_int_distribution.h index 99abe05..3f5b6a1 100644 --- a/absl/random/log_uniform_int_distribution.h +++ b/absl/random/log_uniform_int_distribution.h
@@ -16,7 +16,6 @@ #define ABSL_RANDOM_LOG_UNIFORM_INT_DISTRIBUTION_H_ #include <algorithm> -#include <cmath> #include <ios> #include <istream> #include <limits> @@ -33,10 +32,16 @@ // log_uniform_int_distribution: // -// Returns a random variate R in range [min, max] such that -// floor(log(R-min, base)) is uniformly distributed. -// We ensure uniformity by discretization using the -// boundary sets [0, 1, base, base * base, ... min(base*n, max)] +// Returns a random variate R in range [a, b] (where a = min(), b = max()) such +// that floor(log(R - a, base)) is uniformly distributed. +// Uniformity is ensured by discretizing R - a into buckets: +// +// e = 0: {a} +// e = k: [a + base^(k-1), std::min(a + base^k - 1, b)] (1 <= k <= L) +// +// where L = 0 if a == b, and L = floor(log_base(b - a)) + 1 otherwise. +// A bucket e is chosen uniformly from {0, ..., L}, and then a value is chosen +// uniformly from that bucket. // template <typename IntType = int> class log_uniform_int_distribution { @@ -69,22 +74,18 @@ // value which can be used to construct bounds. log_range_ = (std::min)(random_internal::BitWidth(range()), std::numeric_limits<unsigned_type>::digits); - } else if (base_ > 2) { + } else if (base_ > 2 && range() > 0) { // An out-of-contract base_ (<= 1) skips this branch entirely so that - // no floating-point undefined behavior is reached. - // - // NOTE: Computing the logN(x) introduces error from 2 sources: - // 1. Conversion of int to double loses precision for values >= - // 2^53, which may cause some log() computations to operate on - // different values. - // 2. The error introduced by the division will cause the result - // to differ from the expected value. - // - // Thus a result which should equal K may equal K +/- epsilon, - // which can eliminate some values depending on where the bounds fall. - const double inv_log_base = 1.0 / std::log(static_cast<double>(base_)); - const double log_range = std::log(static_cast<double>(range()) + 0.5); - log_range_ = static_cast<int>(std::ceil(inv_log_base * log_range)); + // division by 0 or non-termination is never reached. + const unsigned_type ubase = static_cast<unsigned_type>(base_); + const unsigned_type limit = range() / ubase; + unsigned_type pow = 1; + int log_range = 1; + while (pow <= limit) { + pow *= ubase; + ++log_range; + } + log_range_ = log_range; } } @@ -110,7 +111,7 @@ result_type max_; result_type base_; unsigned_type range_; // max - min - int log_range_; // ceil(logN(range_)) + int log_range_; // floor(log_base(range_)) + 1 (0 if range_ == 0) static_assert(random_internal::IsIntegral<IntType>::value, "Class-template absl::log_uniform_int_distribution<> must be " @@ -138,7 +139,8 @@ template <typename URBG> result_type operator()(URBG& g, // NOLINT(runtime/references) const param_type& p) { - return static_cast<result_type>((p.min)() + Generate(g, p)); + return static_cast<result_type>(static_cast<unsigned_type>((p.min)()) + + Generate(g, p)); } result_type(min)() const { return (param_.min)(); } @@ -184,34 +186,31 @@ } const int d = e - 1; - unsigned_type base_e, top_e; - if (p.base() == 2) { - base_e = static_cast<unsigned_type>(1) << d; - - top_e = (e >= std::numeric_limits<unsigned_type>::digits) - ? (std::numeric_limits<unsigned_type>::max)() - : (static_cast<unsigned_type>(1) << e) - 1; + // param_type establishes b^(log_range - 1) <= range < b^log_range whenever + // log_range > 0. Thus b^d <= range for every e in [1, log_range], and + // b^e <= range (so b^e fits in unsigned_type) iff e < log_range. + const unsigned_type ubase = static_cast<unsigned_type>(p.base()); + unsigned_type lo; + if (ubase == 2) { + lo = static_cast<unsigned_type>(unsigned_type{1} << d); } else { - const double r = std::pow(static_cast<double>(p.base()), d); - const double s = (r * static_cast<double>(p.base())) - 1.0; - - base_e = - (r > static_cast<double>((std::numeric_limits<unsigned_type>::max)())) - ? (std::numeric_limits<unsigned_type>::max)() - : static_cast<unsigned_type>(r); - - top_e = - (s > static_cast<double>((std::numeric_limits<unsigned_type>::max)())) - ? (std::numeric_limits<unsigned_type>::max)() - : static_cast<unsigned_type>(s); + lo = 1; + unsigned_type factor = ubase; + for (int exp = d; exp > 0; exp >>= 1) { + if ((exp & 1) != 0) { + lo *= factor; + } + if (exp > 1) { + factor *= factor; + } + } } - - const unsigned_type lo = (base_e >= p.range()) ? p.range() : base_e; - const unsigned_type hi = (top_e >= p.range()) ? p.range() : top_e; + const unsigned_type hi = (e == p.log_range()) + ? p.range() + : static_cast<unsigned_type>((lo * ubase) - 1); // choose uniformly over [lo, hi] - return absl::uniform_int_distribution<result_type>( - static_cast<result_type>(lo), static_cast<result_type>(hi))(g); + return absl::uniform_int_distribution<unsigned_type>(lo, hi)(g); } template <typename CharT, typename Traits, typename IntType>
diff --git a/absl/random/log_uniform_int_distribution_test.cc b/absl/random/log_uniform_int_distribution_test.cc index 4404111..1c81dbe 100644 --- a/absl/random/log_uniform_int_distribution_test.cc +++ b/absl/random/log_uniform_int_distribution_test.cc
@@ -20,9 +20,11 @@ #include <cstdint> #include <iterator> #include <limits> +#include <ostream> #include <random> #include <sstream> #include <string> +#include <type_traits> #include <vector> #include "gmock/gmock.h" @@ -41,6 +43,16 @@ namespace { +using ::testing::AllOf; +using ::testing::Each; +using ::testing::ElementsAre; +using ::testing::Field; +using ::testing::Ge; +using ::testing::Gt; +using ::testing::IsTrue; +using ::testing::Le; +using ::testing::SizeIs; + template <typename IntType> class LogUniformIntDistributionTypeTest : public ::testing::Test {}; @@ -272,9 +284,9 @@ // NOTE: absl::log_uniform_int_distribution is not guaranteed to be stable. TEST(LogUniformIntDistributionTest, StabilityTest) { - using testing::ElementsAre; - // absl::uniform_int_distribution stability relies on - // absl::random_internal::LeadingSetBit, std::log, std::pow. + // absl::log_uniform_int_distribution stability relies on + // absl::uniform_int_distribution, absl::random_internal::BitWidth, and + // integer exponentiation. absl::random_internal::sequence_urbg urbg( {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull, 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull, @@ -298,4 +310,190 @@ } } +template <typename IntType> +struct SampleSummary { + bool all_in_bounds = true; + IntType min_sample = (std::numeric_limits<IntType>::max)(); + IntType max_sample = (std::numeric_limits<IntType>::min)(); + int max_hits = 0; + std::vector<int> bucket_counts; +}; + +template <typename IntType> +void PrintTo(const SampleSummary<IntType>& summary, std::ostream* os) { + *os << "{all_in_bounds: " << (summary.all_in_bounds ? "true" : "false") + << ", min_sample: " << summary.min_sample + << ", max_sample: " << summary.max_sample + << ", max_hits: " << summary.max_hits + << ", bucket_counts: " << ::testing::PrintToString(summary.bucket_counts) + << "}"; +} + +MATCHER(AllInBounds, "") { + return ::testing::ExplainMatchResult( + Field("all_in_bounds", &std::decay_t<arg_type>::all_in_bounds, IsTrue()), + arg, result_listener); +} + +MATCHER_P(MinSampleIs, matcher, "") { + return ::testing::ExplainMatchResult( + Field("min_sample", &std::decay_t<arg_type>::min_sample, matcher), arg, + result_listener); +} + +MATCHER_P(MaxSampleIs, matcher, "") { + return ::testing::ExplainMatchResult( + Field("max_sample", &std::decay_t<arg_type>::max_sample, matcher), arg, + result_listener); +} + +MATCHER_P(MaxHitsIs, matcher, "") { + return ::testing::ExplainMatchResult( + Field("max_hits", &std::decay_t<arg_type>::max_hits, matcher), arg, + result_listener); +} + +MATCHER_P(BucketCountsAre, matcher, "") { + return ::testing::ExplainMatchResult( + Field("bucket_counts", &std::decay_t<arg_type>::bucket_counts, matcher), + arg, result_listener); +} + +MATCHER_P(HasNonEmptyBuckets, count, "") { + return ::testing::ExplainMatchResult( + Field("bucket_counts", &std::decay_t<arg_type>::bucket_counts, + AllOf(SizeIs(count), Each(Gt(0)))), + arg, result_listener); +} + +// Fixed seed for deterministic sampling tests (fractional hex digits of Euler's +// number e, matching LogUniformIntChiSquaredTest above). +constexpr uint64_t kTestSeed = 0x2B7E151628AED2A6ULL; + +template <typename IntType> +SampleSummary<IntType> SampleLogUniform(IntType min, IntType max, IntType base, + int trials) { + using Unsigned = std::make_unsigned_t<IntType>; + const Unsigned umin = static_cast<Unsigned>(min); + const Unsigned umax = static_cast<Unsigned>(max); + const Unsigned ubase = static_cast<Unsigned>(base); + const auto exact_bucket = [ubase](Unsigned offset) -> size_t { + if (offset == 0) return 0; + size_t bucket = 1; + const Unsigned limit = offset / ubase; + Unsigned pow = 1; + while (pow <= limit) { + pow *= ubase; + ++bucket; + } + return bucket; + }; + + SampleSummary<IntType> summary; + summary.bucket_counts.assign(exact_bucket(umax - umin) + 1, 0); + absl::random_internal::pcg64_2018_engine rng(kTestSeed); + absl::log_uniform_int_distribution<IntType> dist(min, max, base); + for (int i = 0; i < trials; ++i) { + const IntType v = dist(rng); + if (v < min || v > max) { + summary.all_in_bounds = false; + } else { + ++summary.bucket_counts[exact_bucket(static_cast<Unsigned>(v) - umin)]; + } + summary.min_sample = (std::min)(summary.min_sample, v); + summary.max_sample = (std::max)(summary.max_sample, v); + if (v == max) { + ++summary.max_hits; + } + } + return summary; +} + +TEST(LogUniformIntDistributionTest, NegativeToMaxInt32RangeCoversAllBuckets) { + constexpr int32_t kMaxI32 = (std::numeric_limits<int32_t>::max)(); + // [-10, INT32_MAX] spans > INT32_MAX across 11 base-10 buckets (e in 0..10), + // with the top bucket covering [10^9 - 10, INT32_MAX]. + EXPECT_THAT(SampleLogUniform<int32_t>(-10, kMaxI32, 10, /*trials=*/5000), + AllOf(AllInBounds(), MinSampleIs(-10), + MaxSampleIs(Gt(kMaxI32 / 2)), HasNonEmptyBuckets(11))); +} + +TEST(LogUniformIntDistributionTest, FullInt64RangeCoversAllBuckets) { + constexpr int64_t kMinI64 = (std::numeric_limits<int64_t>::min)(); + constexpr int64_t kMaxI64 = (std::numeric_limits<int64_t>::max)(); + // [INT64_MIN, INT64_MAX] spans 2^64 - 1 across 21 base-10 buckets (e in + // 0..20), with the top bucket covering [INT64_MIN + 10^19, INT64_MAX]. + EXPECT_THAT(SampleLogUniform<int64_t>(kMinI64, kMaxI64, 10, /*trials=*/5000), + AllOf(AllInBounds(), MinSampleIs(kMinI64), + MaxSampleIs(Gt(kMaxI64 / 2)), HasNonEmptyBuckets(21))); +} + +TEST(LogUniformIntDistributionTest, FullUint64RangeBase2Covers65FullBuckets) { + constexpr uint64_t kMaxU64 = (std::numeric_limits<uint64_t>::max)(); + // UINT64_MAX == 2^64 - 1 forms 65 full base-2 buckets (e in 0..64) with top + // bucket [2^63, UINT64_MAX] and no singleton spike at UINT64_MAX. + EXPECT_THAT( + SampleLogUniform<uint64_t>(0, kMaxU64, 2, /*trials=*/10000), + AllOf(AllInBounds(), MinSampleIs(0u), MaxSampleIs(Ge(uint64_t{1} << 63)), + MaxHitsIs(0), HasNonEmptyBuckets(65))); +} + +TEST(LogUniformIntDistributionTest, FullUint64RangeBase4Covers33FullBuckets) { + constexpr uint64_t kMaxU64 = (std::numeric_limits<uint64_t>::max)(); + // UINT64_MAX == 4^32 - 1 forms 33 full base-4 buckets (e in 0..32) with no + // singleton spike at UINT64_MAX. + EXPECT_THAT( + SampleLogUniform<uint64_t>(0, kMaxU64, 4, /*trials=*/5000), + AllOf(AllInBounds(), MinSampleIs(0u), MaxSampleIs(Ge(uint64_t{1} << 62)), + MaxHitsIs(0), HasNonEmptyBuckets(33))); +} + +TEST(LogUniformIntDistributionTest, FullUint64RangeBase3ReachesTopOfRange) { + constexpr uint64_t kMaxU64 = (std::numeric_limits<uint64_t>::max)(); + // Base 3 on [0, UINT64_MAX] has 42 buckets (3^40 < UINT64_MAX < 3^41), with + // the top bucket [3^40, UINT64_MAX] extending all the way to UINT64_MAX. + EXPECT_THAT( + SampleLogUniform<uint64_t>(0, kMaxU64, 3, /*trials=*/10000), + AllOf(AllInBounds(), MinSampleIs(0u), + MaxSampleIs(Gt(kMaxU64 - (kMaxU64 >> 6))), HasNonEmptyBuckets(42))); +} + +TEST(LogUniformIntDistributionTest, MaxBaseFormsThreeEqualBuckets) { + constexpr uint64_t kMaxU64 = (std::numeric_limits<uint64_t>::max)(); + // Base == UINT64_MAX on [0, UINT64_MAX] forms 3 buckets ({0}, + // [1, UINT64_MAX - 1], and {UINT64_MAX}), each drawn with probability 1/3. + const auto approx_one_third = AllOf(Ge(850), Le(1150)); + EXPECT_THAT( + SampleLogUniform<uint64_t>(0, kMaxU64, kMaxU64, /*trials=*/3000), + AllOf(AllInBounds(), MinSampleIs(0u), MaxSampleIs(kMaxU64), + MaxHitsIs(approx_one_third), + BucketCountsAre(ElementsAre(approx_one_third, approx_one_third, + approx_one_third)))); +} + +TEST(LogUniformIntDistributionTest, SingleValueRangeReturnsMin) { + // Empty range (min == max) with base > 2 always returns min. + EXPECT_THAT(SampleLogUniform<uint64_t>(5, 5, 3, /*trials=*/100), + AllOf(AllInBounds(), MinSampleIs(5u), MaxSampleIs(5u), + BucketCountsAre(ElementsAre(100)))); +} + +TEST(LogUniformIntDistributionTest, ExactPowerMaxFormsSingletonTopBucket) { + // On [0, 10^15] in base 10, 10^15 starts bucket e = 16 as a singleton + // {10^15}, receiving 1/17 of draws (~1000 of 17000). + constexpr int64_t kPow10_15 = 1'000'000'000'000'000LL; + EXPECT_THAT(SampleLogUniform<int64_t>(0, kPow10_15, 10, /*trials=*/17000), + AllOf(AllInBounds(), MaxHitsIs(AllOf(Ge(850), Le(1150))), + HasNonEmptyBuckets(17))); +} + +TEST(LogUniformIntDistributionTest, PowerMinusOneMaxHasNoSingletonTopBucket) { + // On [0, 5^26 - 1] in base 5 (> 2^53), bucket e = 26 spans [5^25, 5^26 - 1] + // in full, with no singleton bucket at max. + constexpr uint64_t kPow5_26Minus1 = 1'490'116'119'384'765'625ULL - 1; + EXPECT_THAT( + SampleLogUniform<uint64_t>(0, kPow5_26Minus1, 5, /*trials=*/10000), + AllOf(AllInBounds(), MaxHitsIs(0), HasNonEmptyBuckets(27))); +} + } // namespace