From 6d8a063ec79584f911c61ff0fa486b3e4464d2c4 Mon Sep 17 00:00:00 2001 From: Ajay Yadav Date: Thu, 26 Nov 2026 12:06:58 +0000 Subject: [PATCH] refactor(storage): extract HedgeLimiter from HedgingThreadPool --- .../storage/google_cloud_cpp_storage.bzl | 1 + .../storage/google_cloud_cpp_storage.cmake | 2 + google/cloud/storage/internal/hedge_limiter.h | 174 +++++++++++++++++ .../storage/internal/hedge_limiter_test.cc | 180 ++++++++++++++++++ .../storage/internal/hedging_thread_pool.h | 113 +---------- .../internal/hedging_thread_pool_test.cc | 132 +------------ .../storage/storage_client_unit_tests.bzl | 1 + 7 files changed, 370 insertions(+), 233 deletions(-) create mode 100644 google/cloud/storage/internal/hedge_limiter.h create mode 100644 google/cloud/storage/internal/hedge_limiter_test.cc diff --git a/google/cloud/storage/google_cloud_cpp_storage.bzl b/google/cloud/storage/google_cloud_cpp_storage.bzl index 9593553fdcdfb..d42f4182ac8cc 100644 --- a/google/cloud/storage/google_cloud_cpp_storage.bzl +++ b/google/cloud/storage/google_cloud_cpp_storage.bzl @@ -74,6 +74,7 @@ google_cloud_cpp_storage_hdrs = [ "internal/hash_validator.h", "internal/hash_validator_impl.h", "internal/hash_values.h", + "internal/hedge_limiter.h", "internal/hedged_object_read_source.h", "internal/hedged_read_metrics.h", "internal/hedging_thread_pool.h", diff --git a/google/cloud/storage/google_cloud_cpp_storage.cmake b/google/cloud/storage/google_cloud_cpp_storage.cmake index 0ba84aa1c303d..76af9dbda548b 100644 --- a/google/cloud/storage/google_cloud_cpp_storage.cmake +++ b/google/cloud/storage/google_cloud_cpp_storage.cmake @@ -117,6 +117,7 @@ add_library( internal/hash_validator_impl.h internal/hash_values.cc internal/hash_values.h + internal/hedge_limiter.h internal/hedged_object_read_source.cc internal/hedged_object_read_source.h internal/hedged_read_metrics.cc @@ -462,6 +463,7 @@ if (BUILD_TESTING) internal/hash_function_impl_test.cc internal/hash_validator_test.cc internal/hash_values_test.cc + internal/hedge_limiter_test.cc internal/hedged_object_read_source_test.cc internal/hedged_read_metrics_test.cc internal/hedging_thread_pool_test.cc diff --git a/google/cloud/storage/internal/hedge_limiter.h b/google/cloud/storage/internal/hedge_limiter.h new file mode 100644 index 0000000000000..78827ec3dcb06 --- /dev/null +++ b/google/cloud/storage/internal/hedge_limiter.h @@ -0,0 +1,174 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H +#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H + +#include "google/cloud/storage/version.h" +#include "google/cloud/internal/clock.h" +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace internal { + +/** + * Enforces connection-wide rate, concurrency, and lifetime limits on + * speculative hedged requests. + * + * Values `<= 0` disable the corresponding limit; `capacity` is clamped to at + * least `1.0` so fractional rate limits (`0.0 < rate_limit < 1.0`) can still + * issue hedges once refilled. + */ +class HedgeLimiter { + public: + using Clock = google::cloud::internal::SteadyClock; + + HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent, + std::int64_t max_total) + : HedgeLimiter(rate_limit, capacity, max_concurrent, max_total, + std::make_shared()) {} + + /// @p clock must not be null. Tests inject `testing_util::FakeSteadyClock`. + HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent, + std::int64_t max_total, std::shared_ptr clock) + : clock_(std::move(clock)), + rate_limit_(rate_limit), + tokens_capacity_((std::max)(1.0, capacity)), + tokens_((std::max)(1.0, capacity)), + last_refill_(clock_->Now()), + max_concurrent_hedges_(max_concurrent), + max_total_hedges_(max_total) {} + + ~HedgeLimiter() = default; + + HedgeLimiter(HedgeLimiter const&) = delete; + HedgeLimiter& operator=(HedgeLimiter const&) = delete; + HedgeLimiter(HedgeLimiter&&) = delete; + HedgeLimiter& operator=(HedgeLimiter&&) = delete; + + /** + * Reserves capacity for one hedged request. + * + * On success the caller *must* eventually call `ReleaseHedgeSlot()`. + */ + bool TryAcquireHedgeToken() { + // Once the lifetime budget is spent, deny with a single atomic load. + if (IsTotalBudgetSpent()) return false; + + // Gate 1: the ceiling on concurrently active hedges. When + // max_concurrent_hedges_ <= 0, concurrency limiting is disabled. + if (max_concurrent_hedges_ > 0) { + std::int64_t current = + active_concurrent_hedges_.load(std::memory_order_relaxed); + do { + if (current >= max_concurrent_hedges_) return false; + } while (!active_concurrent_hedges_.compare_exchange_weak( + current, current + 1, std::memory_order_relaxed)); + } + + // Gate 2: the rate limit on new hedges (token bucket). When + // rate_limit_ <= 0.0, rate limiting is disabled. + if (rate_limit_ > 0.0) { + std::lock_guard lock(limiter_mutex_); + Refill(); + if (tokens_ < 1.0) { + ReleaseHedgeSlot(); + return false; + } + tokens_ -= 1.0; + } + + // Gate 3: the lifetime budget. Checked last so the counter only moves for + // a hedge that is granted, which keeps `IsTotalBudgetSpent()` exact. If + // another thread took the last unit since the check above, return what the + // earlier gates reserved. When max_total_hedges_ <= 0, the lifetime limit + // is disabled. + if (max_total_hedges_ > 0) { + std::int64_t granted = + total_hedges_granted_.load(std::memory_order_relaxed); + do { + if (granted >= max_total_hedges_) { + ReleaseHedgeSlot(); + ReturnRateToken(); + return false; + } + } while (!total_hedges_granted_.compare_exchange_weak( + granted, granted + 1, std::memory_order_relaxed)); + } + + return true; + } + + /// Releases the concurrency slot. The lifetime budget is never returned. + void ReleaseHedgeSlot() { + if (max_concurrent_hedges_ > 0) { + active_concurrent_hedges_.fetch_sub(1, std::memory_order_relaxed); + } + } + + /// Returns true once the lifetime budget is spent. No hedge is granted after + /// that, so callers can skip racing altogether. + bool IsTotalBudgetSpent() const { + return max_total_hedges_ > 0 && + total_hedges_granted_.load(std::memory_order_relaxed) >= + max_total_hedges_; + } + + private: + void ReturnRateToken() { + if (rate_limit_ <= 0.0) return; + std::lock_guard lock(limiter_mutex_); + tokens_ = (std::min)(tokens_capacity_, tokens_ + 1.0); + } + + void Refill() { + Clock::time_point const now = clock_->Now(); + double const elapsed = + std::chrono::duration_cast>(now - + last_refill_) + .count(); + last_refill_ = now; + tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_); + } + + std::shared_ptr const clock_; + double const rate_limit_; + double const tokens_capacity_; + double tokens_; + Clock::time_point last_refill_; + std::mutex limiter_mutex_; + + std::int64_t const max_concurrent_hedges_; + std::atomic active_concurrent_hedges_{0}; + + std::int64_t const max_total_hedges_; + std::atomic total_hedges_granted_{0}; +}; + +} // namespace internal +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage +} // namespace cloud +} // namespace google + +#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H diff --git a/google/cloud/storage/internal/hedge_limiter_test.cc b/google/cloud/storage/internal/hedge_limiter_test.cc new file mode 100644 index 0000000000000..f987efcbfdaea --- /dev/null +++ b/google/cloud/storage/internal/hedge_limiter_test.cc @@ -0,0 +1,180 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "google/cloud/storage/internal/hedge_limiter.h" +#include "google/cloud/testing_util/fake_clock.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace internal { +namespace { + +using ::google::cloud::testing_util::FakeSteadyClock; +using ::testing::Eq; + +TEST(HedgeLimiterTest, MaxConcurrentHedgesLimit) { + HedgeLimiter limiter(0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/0); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + limiter.ReleaseHedgeSlot(); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, RateLimiter) { + // 5 tokens/second (one token per 200ms), burst capacity of 2 tokens. + auto clock = std::make_shared(); + HedgeLimiter limiter(5.0, 2.0, 0, 0, clock); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + // Half-token step margins avoid IEEE-754 boundary rounding sensitivity. + clock->AdvanceTime(std::chrono::milliseconds(100)); // +0.5 token + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + clock->AdvanceTime(std::chrono::milliseconds(200)); // +1.0 token => 1.5 + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + // Refill is clamped at burst capacity (2 tokens). + clock->AdvanceTime(std::chrono::seconds(10)); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, FractionalRateLimiter) { + // 0.5 tokens/second (one token per 2s); capacity 0.5 clamps to floor 1.0. + auto clock = std::make_shared(); + HedgeLimiter limiter(0.5, 0.5, 0, 0, clock); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + clock->AdvanceTime(std::chrono::seconds(1)); // +0.5 token + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + clock->AdvanceTime(std::chrono::seconds(2)); // +1.0 token => clamped to 1.0 + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, ZeroRateLimitDisablesRateLimiting) { + HedgeLimiter limiter(0.0, 0.0, 0, 0); + + for (int i = 0; i < 100; ++i) { + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + } +} + +TEST(HedgeLimiterTest, MaxTotalHedgesLimit) { + HedgeLimiter limiter(0.0, 0.0, 0, /*max_total=*/3); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.IsTotalBudgetSpent()); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.IsTotalBudgetSpent()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + // Releasing a hedge frees its concurrency slot, never its lifetime budget. + limiter.ReleaseHedgeSlot(); + limiter.ReleaseHedgeSlot(); + limiter.ReleaseHedgeSlot(); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, ConcurrencyDenialDoesNotSpendTotalBudget) { + HedgeLimiter limiter(0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/2); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.IsTotalBudgetSpent()); + limiter.ReleaseHedgeSlot(); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + limiter.ReleaseHedgeSlot(); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, RateLimitDenialDoesNotSpendTotalBudget) { + auto clock = std::make_shared(); + HedgeLimiter limiter(0.001, 1.0, 0, /*max_total=*/2, clock); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.IsTotalBudgetSpent()); + + clock->AdvanceTime(std::chrono::seconds(1500)); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.IsTotalBudgetSpent()); +} + +TEST(HedgeLimiterTest, ZeroMaxTotalDisablesLifetimeLimit) { + HedgeLimiter limiter(0.0, 0.0, 0, /*max_total=*/0); + + for (int i = 0; i < 100; ++i) { + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + } + EXPECT_FALSE(limiter.IsTotalBudgetSpent()); +} + +TEST(HedgeLimiterTest, MaxTotalHedgesUnderContention) { + std::int64_t const max_total = 100; + // A rate limit that never runs out, so threads racing for the last unit of + // budget also exercise returning the rate token. + HedgeLimiter limiter(1e9, 1e9, /*max_concurrent=*/4, max_total); + + std::atomic granted{0}; + std::vector threads; + threads.reserve(8); + for (int t = 0; t != 8; ++t) { + threads.emplace_back([&limiter, &granted] { + for (int i = 0; i != 1000; ++i) { + if (!limiter.TryAcquireHedgeToken()) continue; + ++granted; + limiter.ReleaseHedgeSlot(); + } + }); + } + for (std::thread& t : threads) t.join(); + + while (limiter.TryAcquireHedgeToken()) { + ++granted; + limiter.ReleaseHedgeSlot(); + } + EXPECT_THAT(granted.load(), Eq(max_total)); + EXPECT_TRUE(limiter.IsTotalBudgetSpent()); +} + +} // namespace +} // namespace internal +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/internal/hedging_thread_pool.h b/google/cloud/storage/internal/hedging_thread_pool.h index dffceb8eca0b7..f421611ab000b 100644 --- a/google/cloud/storage/internal/hedging_thread_pool.h +++ b/google/cloud/storage/internal/hedging_thread_pool.h @@ -15,11 +15,11 @@ #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGING_THREAD_POOL_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGING_THREAD_POOL_H +#include "google/cloud/storage/internal/hedge_limiter.h" #include "google/cloud/storage/version.h" #include -#include -#include #include +#include #include #include #include @@ -137,13 +137,9 @@ class ThreadPool { /** * Coordinates and bounds speculative hedged requests across a storage client. * - * Hedged requests are gated by `TryAcquireHedgeToken()`, which enforces three - * limits: a maximum number of hedges over the life of the pool (when - * `max_total > 0`), a maximum number of concurrently active hedges (when - * `max_concurrent > 0`), and a maximum rate of new hedges per second via a - * token bucket (when `rate_limit > 0.0`). Setting `rate_limit <= 0.0` disables - * rate limiting (unlimited hedges per second). Task execution is dispatched - * onto a dedicated internal `ThreadPool`. + * Hedged requests are gated by `TryAcquireHedgeToken()` (delegated to + * `HedgeLimiter`), and task execution is dispatched onto a dedicated internal + * `ThreadPool`. */ class HedgingThreadPool { public: @@ -162,12 +158,7 @@ class HedgingThreadPool { */ HedgingThreadPool(std::size_t max_threads, double rate_limit, double capacity, std::int64_t max_concurrent, std::int64_t max_total) - : rate_limit_(rate_limit), - tokens_capacity_((std::max)(1.0, capacity)), - tokens_((std::max)(1.0, capacity)), - last_refill_(std::chrono::steady_clock::now()), - max_concurrent_hedges_(max_concurrent), - max_total_hedges_(max_total), + : limiter_(rate_limit, capacity, max_concurrent, max_total), pool_(max_threads) {} ~HedgingThreadPool() = default; @@ -191,103 +182,19 @@ class HedgingThreadPool { * * On success the caller *must* eventually call `ReleaseHedgeSlot()`. */ - bool TryAcquireHedgeToken() { - // Once the lifetime budget is spent, deny with a single atomic load. - if (IsTotalBudgetSpent()) return false; - - // Gate 1: the ceiling on concurrently active hedges. When - // max_concurrent_hedges_ <= 0, concurrency limiting is disabled. - if (max_concurrent_hedges_ > 0) { - std::int64_t current = - active_concurrent_hedges_.load(std::memory_order_relaxed); - do { - if (current >= max_concurrent_hedges_) return false; - } while (!active_concurrent_hedges_.compare_exchange_weak( - current, current + 1, std::memory_order_relaxed)); - } - - // Gate 2: the rate limit on new hedges (token bucket). When - // rate_limit_ <= 0.0, rate limiting is disabled. - if (rate_limit_ > 0.0) { - std::lock_guard lock(limiter_mutex_); - Refill(); - if (tokens_ < 1.0) { - ReleaseHedgeSlot(); - return false; - } - tokens_ -= 1.0; - } - - // Gate 3: the lifetime budget. Checked last so the counter only moves for - // a hedge that is granted, which keeps `IsTotalBudgetSpent()` exact. If - // another thread took the last unit since the check above, return what - // the earlier gates reserved. When max_total_hedges_ <= 0, the lifetime - // limit is disabled. - if (max_total_hedges_ > 0) { - std::int64_t granted = - total_hedges_granted_.load(std::memory_order_relaxed); - do { - if (granted >= max_total_hedges_) { - ReleaseHedgeSlot(); - ReturnRateToken(); - return false; - } - } while (!total_hedges_granted_.compare_exchange_weak( - granted, granted + 1, std::memory_order_relaxed)); - } - - return true; - } + bool TryAcquireHedgeToken() { return limiter_.TryAcquireHedgeToken(); } /// Releases the concurrency slot. The lifetime budget is never returned. - void ReleaseHedgeSlot() { - if (max_concurrent_hedges_ > 0) { - active_concurrent_hedges_.fetch_sub(1, std::memory_order_relaxed); - } - } + void ReleaseHedgeSlot() { limiter_.ReleaseHedgeSlot(); } /// Returns true once the lifetime budget is spent. No hedge is granted after /// that, so callers can skip racing altogether. - bool IsTotalBudgetSpent() const { - return max_total_hedges_ > 0 && - total_hedges_granted_.load(std::memory_order_relaxed) >= - max_total_hedges_; - } + bool IsTotalBudgetSpent() const { return limiter_.IsTotalBudgetSpent(); } std::size_t max_threads() const { return pool_.max_threads(); } private: - void ReturnRateToken() { - if (rate_limit_ <= 0.0) return; - std::lock_guard lock(limiter_mutex_); - tokens_ = (std::min)(tokens_capacity_, tokens_ + 1.0); - } - - void Refill() { - std::chrono::steady_clock::time_point const now = - std::chrono::steady_clock::now(); - double const elapsed = - std::chrono::duration_cast>(now - - last_refill_) - .count(); - last_refill_ = now; - tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_); - } - - // Token bucket rate limiter. A rate_limit_ <= 0.0 disables rate limiting. - double rate_limit_; - double tokens_capacity_; - double tokens_; - std::chrono::steady_clock::time_point last_refill_; - std::mutex limiter_mutex_; - - // Concurrency limiter. A max_concurrent_hedges_ <= 0 disables limit. - std::int64_t const max_concurrent_hedges_; - std::atomic active_concurrent_hedges_{0}; - - // Lifetime limiter. A max_total_hedges_ <= 0 disables limit. - std::int64_t const max_total_hedges_; - std::atomic total_hedges_granted_{0}; + HedgeLimiter limiter_; // Declared last so the pool (and its worker threads) is destroyed and joined // first, before any other member variables are torn down. diff --git a/google/cloud/storage/internal/hedging_thread_pool_test.cc b/google/cloud/storage/internal/hedging_thread_pool_test.cc index 716183f4d06c5..f49ab725928d4 100644 --- a/google/cloud/storage/internal/hedging_thread_pool_test.cc +++ b/google/cloud/storage/internal/hedging_thread_pool_test.cc @@ -16,12 +16,9 @@ #include #include #include -#include #include -#include #include #include -#include #include namespace google { @@ -139,143 +136,18 @@ TEST(HedgingThreadPoolTest, EnqueueAndExecute) { f2.get(); } -TEST(HedgingThreadPoolTest, MaxConcurrentHedgesLimit) { - // Only one concurrent hedge allowed. - HedgingThreadPool pool(5, 0.0, 0.0, 1, 0); +TEST(HedgingThreadPoolTest, DelegatesToHedgeLimiter) { + HedgingThreadPool pool(2, 0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/1); - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - // Fails because one hedge is active. - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - - pool.ReleaseHedgeSlot(); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); -} - -TEST(HedgingThreadPoolTest, RateLimiter) { - // A rate limit of 5.0 tokens per second (one token per 200ms), and a burst - // capacity of 2 tokens. - HedgingThreadPool pool(5, 5.0, 2.0, 0, 0); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - // The burst capacity is exhausted. - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - - // The refill is time-based, there is no way to inject a fake clock. Wait - // longer than one token's refill period, with margin for slow machines. - std::this_thread::sleep_for(std::chrono::milliseconds(250)); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); -} - -TEST(HedgingThreadPoolTest, FractionalRateLimiter) { - // A rate limit of 0.5 tokens per second (one token per 2 seconds). - // The capacity is set to 0.5, which the pool must clamp to a floor of 1.0. - HedgingThreadPool pool(5, 0.5, 0.5, 0, 0); - - // Since capacity is clamped to 1.0, we must be able to acquire at least one - // token. - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - EXPECT_FALSE(pool.TryAcquireHedgeToken()); -} - -TEST(HedgingThreadPoolTest, ZeroRateLimitDisablesRateLimiting) { - // A rate limit of 0.0 disables rate limiting, allowing unlimited - // acquisitions. - HedgingThreadPool pool(5, 0.0, 0.0, 0, 0); - - for (int i = 0; i < 100; ++i) { - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - } -} - -TEST(HedgingThreadPoolTest, MaxTotalHedgesLimit) { - HedgingThreadPool pool(5, 0.0, 0.0, 0, /*max_total=*/3); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - EXPECT_TRUE(pool.TryAcquireHedgeToken()); EXPECT_FALSE(pool.IsTotalBudgetSpent()); EXPECT_TRUE(pool.TryAcquireHedgeToken()); EXPECT_TRUE(pool.IsTotalBudgetSpent()); EXPECT_FALSE(pool.TryAcquireHedgeToken()); - // Releasing a hedge frees its concurrency slot, but never returns the - // lifetime budget. - pool.ReleaseHedgeSlot(); - pool.ReleaseHedgeSlot(); - pool.ReleaseHedgeSlot(); - EXPECT_FALSE(pool.TryAcquireHedgeToken()); -} - -TEST(HedgingThreadPoolTest, ConcurrencyDenialDoesNotSpendTotalBudget) { - HedgingThreadPool pool(5, 0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/2); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - // Denied by the concurrency limit, so this hedge is never sent. - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - EXPECT_FALSE(pool.IsTotalBudgetSpent()); - pool.ReleaseHedgeSlot(); - - // The denials above did not spend the budget, so one hedge is left. - EXPECT_TRUE(pool.TryAcquireHedgeToken()); pool.ReleaseHedgeSlot(); EXPECT_FALSE(pool.TryAcquireHedgeToken()); } -TEST(HedgingThreadPoolTest, RateLimitDenialDoesNotSpendTotalBudget) { - // A burst capacity of one token, and a refill (one token per 1000 seconds) - // too slow to add a token while the test runs. - HedgingThreadPool pool(5, 0.001, 1.0, 0, /*max_total=*/2); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - // Denied by the rate limit, so this hedge is never sent. - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - // Only the first hedge spent the budget. - EXPECT_FALSE(pool.IsTotalBudgetSpent()); -} - -TEST(HedgingThreadPoolTest, ZeroMaxTotalDisablesLifetimeLimit) { - HedgingThreadPool pool(5, 0.0, 0.0, 0, /*max_total=*/0); - - for (int i = 0; i < 100; ++i) { - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - } - EXPECT_FALSE(pool.IsTotalBudgetSpent()); -} - -TEST(HedgingThreadPoolTest, MaxTotalHedgesUnderContention) { - std::int64_t const max_total = 100; - // A rate limit that never runs out, so threads racing for the last unit of - // budget also exercise returning the rate token. - HedgingThreadPool pool(1, 1e9, 1e9, /*max_concurrent=*/4, max_total); - - std::atomic granted{0}; - std::vector threads; - for (int t = 0; t != 8; ++t) { - threads.emplace_back([&pool, &granted] { - for (int i = 0; i != 1000; ++i) { - if (!pool.TryAcquireHedgeToken()) continue; - ++granted; - pool.ReleaseHedgeSlot(); - } - }); - } - for (auto& t : threads) t.join(); - - // Spend whatever budget the threads left, so the count below does not depend - // on how the threads were scheduled. If contention ever over-granted, or a - // hedge denied by an earlier gate spent budget, the total is off. - while (pool.TryAcquireHedgeToken()) { - ++granted; - pool.ReleaseHedgeSlot(); - } - EXPECT_THAT(granted.load(), Eq(max_total)); - EXPECT_TRUE(pool.IsTotalBudgetSpent()); -} - TEST(HedgingThreadPoolTest, SafeDestructionOnWorkerThread) { TestSafeDestructionOnWorkerThread( std::make_shared(1, 0.0, 0.0, 0, 0)); diff --git a/google/cloud/storage/storage_client_unit_tests.bzl b/google/cloud/storage/storage_client_unit_tests.bzl index e646a81293431..1ca32e963b028 100644 --- a/google/cloud/storage/storage_client_unit_tests.bzl +++ b/google/cloud/storage/storage_client_unit_tests.bzl @@ -67,6 +67,7 @@ storage_client_unit_tests = [ "internal/hash_function_impl_test.cc", "internal/hash_validator_test.cc", "internal/hash_values_test.cc", + "internal/hedge_limiter_test.cc", "internal/hedged_object_read_source_test.cc", "internal/hedged_read_metrics_test.cc", "internal/hedging_thread_pool_test.cc",