From 6d8a063ec79584f911c61ff0fa486b3e4464d2c4 Mon Sep 17 00:00:00 2001 From: Ajay Yadav Date: Thu, 26 Nov 2026 12:06:58 +0000 Subject: [PATCH 1/2] 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", From 957c80c69ed91458dd5e663bb8c634db893791cd Mon Sep 17 00:00:00 2001 From: Ajay Yadav Date: Thu, 26 Nov 2026 12:11:21 +0000 Subject: [PATCH 2/2] impl(storage): add HedgedOpenStream coordinator for async Open --- .../storage/google_cloud_cpp_storage_grpc.bzl | 2 + .../google_cloud_cpp_storage_grpc.cmake | 3 + .../internal/async/hedged_open_stream.cc | 355 ++++++++++++ .../internal/async/hedged_open_stream.h | 73 +++ .../internal/async/hedged_open_stream_test.cc | 526 ++++++++++++++++++ .../storage_client_grpc_unit_tests.bzl | 1 + 6 files changed, 960 insertions(+) create mode 100644 google/cloud/storage/internal/async/hedged_open_stream.cc create mode 100644 google/cloud/storage/internal/async/hedged_open_stream.h create mode 100644 google/cloud/storage/internal/async/hedged_open_stream_test.cc diff --git a/google/cloud/storage/google_cloud_cpp_storage_grpc.bzl b/google/cloud/storage/google_cloud_cpp_storage_grpc.bzl index 34d8ffe483dd8..790f2e0ca33d0 100644 --- a/google/cloud/storage/google_cloud_cpp_storage_grpc.bzl +++ b/google/cloud/storage/google_cloud_cpp_storage_grpc.bzl @@ -43,6 +43,7 @@ google_cloud_cpp_storage_grpc_hdrs = [ "internal/async/connection_tracing.h", "internal/async/default_options.h", "internal/async/handle_redirect_error.h", + "internal/async/hedged_open_stream.h", "internal/async/insert_object.h", "internal/async/multi_stream_manager.h", "internal/async/object_descriptor_connection_tracing.h", @@ -124,6 +125,7 @@ google_cloud_cpp_storage_grpc_srcs = [ "internal/async/connection_tracing.cc", "internal/async/default_options.cc", "internal/async/handle_redirect_error.cc", + "internal/async/hedged_open_stream.cc", "internal/async/insert_object.cc", "internal/async/multi_stream_manager.cc", "internal/async/object_descriptor_connection_tracing.cc", diff --git a/google/cloud/storage/google_cloud_cpp_storage_grpc.cmake b/google/cloud/storage/google_cloud_cpp_storage_grpc.cmake index 33474bfc66ecf..b24be6ced6352 100644 --- a/google/cloud/storage/google_cloud_cpp_storage_grpc.cmake +++ b/google/cloud/storage/google_cloud_cpp_storage_grpc.cmake @@ -109,6 +109,8 @@ add_library( internal/async/default_options.h internal/async/handle_redirect_error.cc internal/async/handle_redirect_error.h + internal/async/hedged_open_stream.cc + internal/async/hedged_open_stream.h internal/async/insert_object.cc internal/async/insert_object.h internal/async/multi_stream_manager.cc @@ -426,6 +428,7 @@ set(storage_client_grpc_unit_tests internal/async/connection_tracing_test.cc internal/async/default_options_test.cc internal/async/handle_redirect_error_test.cc + internal/async/hedged_open_stream_test.cc internal/async/insert_object_test.cc internal/async/multi_stream_manager_test.cc internal/async/object_descriptor_connection_tracing_test.cc diff --git a/google/cloud/storage/internal/async/hedged_open_stream.cc b/google/cloud/storage/internal/async/hedged_open_stream.cc new file mode 100644 index 0000000000000..afc78a63bb47e --- /dev/null +++ b/google/cloud/storage/internal/async/hedged_open_stream.cc @@ -0,0 +1,355 @@ +// 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/async/hedged_open_stream.h" +#include "google/cloud/internal/call_context.h" +#include "google/cloud/internal/make_status.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace { + +std::chrono::milliseconds constexpr kHedgeRetryMinDelay{10}; + +class HedgedOpenOperation + : public std::enable_shared_from_this { + public: + HedgedOpenOperation( + CompletionQueue cq, OpenStreamFactory factory, + google::storage::v2::BidiReadObjectRequest initial_request, + std::shared_ptr retry_policy, + HedgedOpenParams params, + std::shared_ptr limiter, + std::shared_ptr metrics, + google::cloud::internal::ImmutableOptions options) + : cq_(std::move(cq)), + factory_(std::move(factory)), + initial_request_(std::move(initial_request)), + retry_policy_(std::move(retry_policy)), + hedge_delay_( + (std::max)(std::chrono::milliseconds::zero(), params.delay)), + max_hedges_((std::max)(0, params.max_hedges)), + limiter_(std::move(limiter)), + metrics_(std::move(metrics)), + call_context_(std::move(options)) {} + + future> Start() { + std::weak_ptr weak = shared_from_this(); + result_promise_ = promise>([weak] { + if (std::shared_ptr self = weak.lock()) { + google::cloud::internal::ScopedCallContext scope(self->call_context_); + self->OnCallerCancel(); + } + }); + future> result_future = + result_promise_.get_future(); + + active_attempts_ = 1; + attempts_.emplace_back(future{}); + bool const arm_timer = CanHedge(); + + AttachAttempt(0, StartAttempt(0)); + if (arm_timer) ArmTimer(hedge_delay_); + return result_future; + } + + private: + struct HedgeSlot { + std::shared_ptr limiter; + + HedgeSlot() = default; + explicit HedgeSlot(std::shared_ptr l) + : limiter(std::move(l)) {} + ~HedgeSlot() { Release(); } + HedgeSlot(HedgeSlot&&) noexcept = default; + HedgeSlot& operator=(HedgeSlot&&) = delete; + HedgeSlot(HedgeSlot const&) = delete; + HedgeSlot& operator=(HedgeSlot const&) = delete; + + void Release() { + if (limiter) std::exchange(limiter, nullptr)->ReleaseHedgeSlot(); + } + }; + + struct Outstanding { + future timer; + std::vector>> attempts; + + void Cancel() { + CancelIfValid(timer); + for (std::optional>& pending : attempts) { + if (pending) CancelIfValid(*pending); + } + } + }; + + static void CancelIfValid(future& f) { + if (f.valid()) f.cancel(); + } + + static Status CancelledOpenError() { + return google::cloud::internal::CancelledError("Open operation cancelled", + GCP_ERROR_INFO()); + } + + bool CanHedge() const { + return hedges_dispatched_ < max_hedges_ && + (!limiter_ || !limiter_->IsTotalBudgetSpent()); + } + + future FinishAttemptLocked(std::size_t idx) { + --active_attempts_; + if (idx < attempts_.size() && attempts_[idx].has_value()) { + return *std::exchange(attempts_[idx], std::nullopt); + } + return future{}; + } + + Outstanding DrainOutstandingLocked() { + ++timer_generation_; + return Outstanding{std::move(timer_future_), std::exchange(attempts_, {})}; + } + + void Resolve(Outstanding& outstanding, StatusOr result) { + outstanding.Cancel(); + result_promise_.set_value(std::move(result)); + } + + future StartAttempt(std::size_t idx) { + HedgeSlot slot = idx == 0 ? HedgeSlot{} : HedgeSlot{limiter_}; + google::cloud::internal::ScopedCallContext scope(call_context_); + std::shared_ptr self = shared_from_this(); + return factory_(initial_request_) + .then([self = std::move(self), slot = std::move(slot), + idx](future> f) mutable { + slot.Release(); + self->OnAttemptDone(idx, f.get()); + }); + } + + void AttachAttempt(std::size_t idx, future attempt) { + if (!attempt.valid() || attempt.is_ready()) return; + bool cancel_now = false; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) { + cancel_now = true; + } else if (idx < attempts_.size() && attempts_[idx].has_value()) { + attempts_[idx] = std::move(attempt); + } + } + if (cancel_now) CancelIfValid(attempt); + } + + void ArmTimer(std::chrono::milliseconds delay) { + std::uint64_t gen = 0; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) return; + gen = ++timer_generation_; + } + std::weak_ptr weak = shared_from_this(); + future timer = cq_.MakeRelativeTimer(delay).then( + [weak, gen](future> f) { + if (std::shared_ptr self = weak.lock()) { + self->OnTimer(gen, f.get().ok()); + } + }); + if (!timer.valid() || timer.is_ready()) return; + bool cancel_now = false; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) { + cancel_now = true; + } else if (gen == timer_generation_) { + timer_future_ = std::move(timer); + } + } + if (cancel_now) CancelIfValid(timer); + } + + void OnTimer(std::uint64_t gen, bool expired) { + if (!expired) return; + google::cloud::internal::ScopedCallContext scope(call_context_); + + bool dispatch_hedge = false; + std::size_t idx = 0; + bool arm_next_timer = false; + std::chrono::milliseconds next_delay = hedge_delay_; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_ || gen != timer_generation_ || + hedges_dispatched_ >= max_hedges_) { + return; + } + ++timer_generation_; + timer_future_ = future{}; + bool const acquired = !limiter_ || limiter_->TryAcquireHedgeToken(); + if (acquired) { + dispatch_hedge = true; + ++active_attempts_; + ++hedges_dispatched_; + idx = attempts_.size(); + attempts_.emplace_back(future{}); + } + if (CanHedge()) { + arm_next_timer = true; + next_delay = acquired ? hedge_delay_ + : (std::max)(hedge_delay_, kHedgeRetryMinDelay); + } + } + + // If a sibling won after unlocking `mu_`, `AttachAttempt` cancels it. + if (dispatch_hedge) { + if (metrics_) metrics_->OnHedgeDispatched(); + AttachAttempt(idx, StartAttempt(idx)); + } + if (arm_next_timer) ArmTimer(next_delay); + } + + void OnAttemptDone(std::size_t idx, StatusOr result) { + google::cloud::internal::ScopedCallContext scope(call_context_); + if (!result) return OnAttemptError(idx, std::move(result).status()); + future self_attempt; + Outstanding outstanding; + bool won = false; + { + std::lock_guard lock(mu_); + if (!resolved_ && !caller_cancelled_) { + won = true; + self_attempt = FinishAttemptLocked(idx); + resolved_ = true; + outstanding = DrainOutstandingLocked(); + } + } + if (!won) { + if (result->stream) result->stream->Cancel(); + OnAttemptError(idx, CancelledOpenError()); + return; + } + if (idx > 0 && metrics_) metrics_->OnHedgeWon(); + Resolve(outstanding, *std::move(result)); + } + + Status SelectFinalErrorLocked() const { + // `RetryLoopCancelled` preserves the last transient status code when + // cancelled during backoff, so map caller-cancelled races to `kCancelled`. + if (caller_cancelled_) { + return primary_error_.code() == StatusCode::kCancelled + ? primary_error_ + : CancelledOpenError(); + } + if (!permanent_error_.ok()) return permanent_error_; + return primary_error_; + } + + void OnAttemptError(std::size_t idx, Status status) { + // Unlike mid-stream sync `HedgedObjectReadSource`, every `Open()` attempt + // sends the identical initial request, so an authoritative permanent + // rejection (`kNotFound`, `kPermissionDenied`, ...) from *any* attempt + // aborts stalled siblings immediately. `kCancelled` is excluded because + // per-stream stall timeouts surface as `kCancelled` on that attempt alone. + bool const permanent_error = status.code() != StatusCode::kCancelled && + retry_policy_ && + retry_policy_->IsPermanentFailure(status); + future self_attempt; + Outstanding outstanding; + Status final_error; + bool resolve_now = false; + { + std::lock_guard lock(mu_); + self_attempt = FinishAttemptLocked(idx); + if (resolved_) return; + if (permanent_error && permanent_error_.ok()) permanent_error_ = status; + if (idx == 0) primary_error_ = std::move(status); + // Each attempt runs its own `AsyncRetryLoop`, so `active_attempts_ == 0` + // means every launched attempt already exhausted its retry policy; do + // not wait for un-fired hedge timers to double the retry budget. + if (active_attempts_ == 0 || + (!caller_cancelled_ && !permanent_error_.ok())) { + resolve_now = true; + resolved_ = true; + final_error = SelectFinalErrorLocked(); + outstanding = DrainOutstandingLocked(); + } + } + if (resolve_now) Resolve(outstanding, std::move(final_error)); + } + + void OnCallerCancel() { + Outstanding outstanding; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) return; + caller_cancelled_ = true; + outstanding = DrainOutstandingLocked(); + } + outstanding.Cancel(); + } + + CompletionQueue cq_; + OpenStreamFactory factory_; + google::storage::v2::BidiReadObjectRequest initial_request_; + std::shared_ptr retry_policy_; + std::chrono::milliseconds const hedge_delay_; + int const max_hedges_; + std::shared_ptr limiter_; + std::shared_ptr metrics_; + google::cloud::internal::CallContext call_context_; + promise> result_promise_{null_promise_t{}}; + + std::mutex mu_; + bool resolved_ = false; + bool caller_cancelled_ = false; + int active_attempts_ = 0; + int hedges_dispatched_ = 0; + std::uint64_t timer_generation_ = 0; + Status permanent_error_; + Status primary_error_; + future timer_future_; + std::vector>> attempts_; +}; + +} // namespace + +future> HedgedOpenStream( + CompletionQueue cq, OpenStreamFactory factory, + google::storage::v2::BidiReadObjectRequest initial_request, + std::shared_ptr retry_policy, + HedgedOpenParams params, + std::shared_ptr limiter, + std::shared_ptr metrics, + google::cloud::internal::ImmutableOptions options) { + return std::make_shared( + std::move(cq), std::move(factory), std::move(initial_request), + std::move(retry_policy), params, std::move(limiter), + std::move(metrics), std::move(options)) + ->Start(); +} + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/internal/async/hedged_open_stream.h b/google/cloud/storage/internal/async/hedged_open_stream.h new file mode 100644 index 0000000000000..00671b1d19b54 --- /dev/null +++ b/google/cloud/storage/internal/async/hedged_open_stream.h @@ -0,0 +1,73 @@ +// 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_ASYNC_HEDGED_OPEN_STREAM_H +#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_ASYNC_HEDGED_OPEN_STREAM_H + +#include "google/cloud/storage/async/retry_policy.h" +#include "google/cloud/storage/internal/async/open_stream.h" +#include "google/cloud/storage/internal/hedge_limiter.h" +#include "google/cloud/storage/internal/hedged_read_metrics.h" +#include "google/cloud/completion_queue.h" +#include "google/cloud/future.h" +#include "google/cloud/options.h" +#include "google/cloud/status_or.h" +#include "google/cloud/version.h" +#include "google/storage/v2/storage.pb.h" +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN + +struct HedgedOpenParams { + std::chrono::milliseconds delay; + int max_hedges; +}; + +/** + * Races a primary `OpenStreamFactory` attempt against up to `params.max_hedges` + * delayed speculative attempts spaced by `params.delay`. + * + * The first attempt to succeed wins; remaining in-flight attempts and timers + * are cancelled, and any late-completing loser's `OpenStream` is cancelled via + * `OpenStream::Cancel()`. A permanent non-`kCancelled` error from *any* attempt + * resolves the race immediately; otherwise if all launched attempts fail, the + * primary attempt's error is returned. Cancelling the returned future cancels + * all in-flight attempts and timers. Negative `params.delay` and + * `params.max_hedges` values are clamped to zero. + * + * @p retry_policy classifies permanent failures; if null, no attempt error + * aborts siblings early. + * @p limiter gates speculative hedge dispatches across the connection; if null, + * per-connection rate/concurrency/lifetime limits are not enforced. + * @p metrics may be null, in which case no OpenTelemetry counters are recorded. + */ +future> HedgedOpenStream( + CompletionQueue cq, OpenStreamFactory factory, + google::storage::v2::BidiReadObjectRequest initial_request, + std::shared_ptr retry_policy, + HedgedOpenParams params, + std::shared_ptr limiter, + std::shared_ptr metrics, + google::cloud::internal::ImmutableOptions options); + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google + +#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_ASYNC_HEDGED_OPEN_STREAM_H diff --git a/google/cloud/storage/internal/async/hedged_open_stream_test.cc b/google/cloud/storage/internal/async/hedged_open_stream_test.cc new file mode 100644 index 0000000000000..261b36a032a18 --- /dev/null +++ b/google/cloud/storage/internal/async/hedged_open_stream_test.cc @@ -0,0 +1,526 @@ +// 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/async/hedged_open_stream.h" +#include "google/cloud/mocks/mock_async_streaming_read_write_rpc.h" +#include "google/cloud/storage/testing/canonical_errors.h" +#include "google/cloud/internal/make_status.h" +#include "google/cloud/testing_util/async_sequencer.h" +#include "google/cloud/testing_util/mock_completion_queue_impl.h" +#include "google/cloud/testing_util/mock_opentelemetry_metrics.h" +#include "google/cloud/testing_util/status_matchers.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace { + +using ::google::cloud::storage::testing::canonical_errors::PermanentError; +using ::google::cloud::storage::testing::canonical_errors::TransientError; +using ::google::cloud::testing_util::AsyncSequencer; +using ::google::cloud::testing_util::MockCompletionQueueImpl; +using ::google::cloud::testing_util::MockCounter; +using ::google::cloud::testing_util::MockMeter; +using ::google::cloud::testing_util::MockMeterProvider; +using ::google::cloud::testing_util::StatusIs; +using ::testing::_; +using ::testing::AnyOf; +using ::testing::ByMove; +using ::testing::ElementsAre; +using ::testing::Eq; +using ::testing::HasSubstr; +using ::testing::NiceMock; +using ::testing::Return; + +using MetricsPtr = std::shared_ptr; +using TimerFuture = future>; +using MockRpc = google::cloud::mocks::MockAsyncStreamingReadWriteRpc< + google::storage::v2::BidiReadObjectRequest, + google::storage::v2::BidiReadObjectResponse>; + +MetricsPtr MakeMockHedgeMetrics(int expected_dispatched, int expected_won) { + opentelemetry::nostd::shared_ptr meter = + std::make_shared(); + auto const expect_counter = [&](char const* name, int expected) { + auto counter = std::make_unique>(); + EXPECT_CALL(*counter, Add(std::uint64_t{1})).Times(expected); + EXPECT_CALL(*meter, CreateUInt64Counter(Eq(name), _, _)) + .WillOnce(Return(ByMove(opentelemetry::nostd::unique_ptr< + opentelemetry::metrics::Counter>( + counter.release())))); + }; + expect_counter("storage.read_hedging.hedges_dispatched", expected_dispatched); + expect_counter("storage.read_hedging.hedge_won", expected_won); + + auto provider = std::make_shared(); + EXPECT_CALL(*provider, GetMeter).WillOnce(Return(meter)); + opentelemetry::nostd::shared_ptr + otel_provider{ + std::shared_ptr(provider)}; + return std::make_shared(otel_provider); +} + +OpenStreamResult MakeOpenResult(std::int64_t generation, + std::atomic* stream_cancels) { + auto rpc = std::make_unique>(); + ON_CALL(*rpc, Cancel).WillByDefault([stream_cancels] { + if (stream_cancels != nullptr) ++(*stream_cancels); + }); + ON_CALL(*rpc, Finish).WillByDefault([] { + return make_ready_future(Status{}); + }); + google::storage::v2::BidiReadObjectResponse response; + response.mutable_metadata()->set_generation(generation); + return OpenStreamResult{std::make_shared(std::move(rpc)), + std::move(response)}; +} + +google::storage::v2::BidiReadObjectRequest MakeInitialRequest() { + google::storage::v2::BidiReadObjectRequest req; + req.mutable_read_object_spec()->set_bucket("projects/_/buckets/test-bucket"); + req.mutable_read_object_spec()->set_object("test-object"); + return req; +} + +Status CancelledError() { + return internal::CancelledError("cancelled", GCP_ERROR_INFO()); +} + +class HedgedOpenStreamTest : public ::testing::Test { + protected: + using StepValue = StatusOr; + using ResultFuture = future>; + + void ExpectTimers(std::vector names) { + if (names.empty()) { + EXPECT_CALL(*mock_cq_, MakeRelativeTimer).Times(0); + return; + } + int const count = static_cast(names.size()); + EXPECT_CALL(*mock_cq_, MakeRelativeTimer) + .Times(count) + .WillRepeatedly( + [this, names = std::move(names)](std::chrono::nanoseconds d) { + std::size_t const idx = timer_delays_.size(); + timer_delays_.push_back( + std::chrono::duration_cast(d)); + std::string const name = + idx < names.size() ? names[idx] : std::string("ExtraTimer"); + future step = sequencer_.PushBack(name); + auto timer_promise = std::make_shared< + promise>>( + [this] { ++cancelled_timers_; }); + TimerFuture timer_future = timer_promise->get_future(); + step.then([timer_promise](future f) mutable { + if (!f.get().ok()) { + return timer_promise->set_value(CancelledError()); + } + timer_promise->set_value(std::chrono::system_clock::now()); + }); + return timer_future; + }); + } + + OpenStreamFactory SequencedFactory() { + return [this, n = std::make_shared>(0)]( + google::storage::v2::BidiReadObjectRequest const& req) { + EXPECT_EQ(req.read_object_spec().object(), "test-object"); + int const id = (*n)++; + std::string const label = + id == 0 ? "Primary" : "Hedge" + std::to_string(id); + future step = sequencer_.PushBack(label); + auto attempt_promise = + std::make_shared>>( + [this] { ++cancelled_attempts_; }); + ResultFuture out = attempt_promise->get_future(); + step.then([this, attempt_promise](future f) mutable { + StepValue val = f.get(); + if (!val) return attempt_promise->set_value(std::move(val).status()); + attempt_promise->set_value(MakeOpenResult(*val, &cancelled_streams_)); + }); + return out; + }; + } + + promise PopStep(char const* expected) { + auto [p, name] = sequencer_.PopFrontWithName(); + EXPECT_EQ(name, expected); + return std::move(p); + } + + ResultFuture RunHedgedOpen( + HedgedOpenParams params, + std::shared_ptr limiter, + MetricsPtr metrics) { + return HedgedOpenStream( + CompletionQueue(mock_cq_), SequencedFactory(), MakeInitialRequest(), + storage::LimitedErrorCountAsyncRetryPolicy(0).clone(), params, + std::move(limiter), std::move(metrics), + google::cloud::internal::MakeImmutableOptions(Options{})); + } + + static std::shared_ptr UnlimitedLimiter() { + return std::make_shared(0.0, 0.0, 0, 0); + } + + AsyncSequencer sequencer_; + std::atomic cancelled_timers_{0}; + std::atomic cancelled_attempts_{0}; + std::atomic cancelled_streams_{0}; + std::vector timer_delays_; + std::shared_ptr mock_cq_ = + std::make_shared(); +}; + +TEST_F(HedgedOpenStreamTest, FastPrimaryCancelsTimer) { + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/0, + /*expected_won=*/0); + ExpectTimers({"Timer1"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(250), 2}, + UnlimitedLimiter(), metrics); + promise primary = PopStep("Primary"); + promise timer1 = PopStep("Timer1"); + EXPECT_THAT(timer_delays_, ElementsAre(std::chrono::milliseconds(250))); + + primary.set_value(101); + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result->first_response.metadata().generation(), 101); + EXPECT_EQ(cancelled_timers_.load(), 1); + EXPECT_EQ(cancelled_attempts_.load(), 0); + + timer1.set_value(CancelledError()); +} + +TEST_F(HedgedOpenStreamTest, SlowPrimaryHedgeWinsAndCancelsPrimary) { + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/1, + /*expected_won=*/1); + ExpectTimers({"Timer1", "Timer2"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 2}, + UnlimitedLimiter(), metrics); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + promise timer2 = PopStep("Timer2"); + + hedge1.set_value(202); + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result->first_response.metadata().generation(), 202); + EXPECT_EQ(cancelled_attempts_.load(), 1); + EXPECT_EQ(cancelled_timers_.load(), 1); + + timer2.set_value(CancelledError()); + // Late-completing losing streams are immediately cancelled rather than + // leaked. + primary.set_value(999); + EXPECT_EQ(cancelled_streams_.load(), 1); +} + +TEST_F(HedgedOpenStreamTest, PrimaryWinsAfterHedgeDispatched) { + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/1, + /*expected_won=*/0); + ExpectTimers({"Timer1"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 1}, + UnlimitedLimiter(), metrics); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + + primary.set_value(1); + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result->first_response.metadata().generation(), 1); + EXPECT_EQ(cancelled_attempts_.load(), 1); + + hedge1.set_value(CancelledError()); +} + +class HedgedOpenRescueTest : public HedgedOpenStreamTest, + public ::testing::WithParamInterface {}; + +TEST_P(HedgedOpenRescueTest, PrimaryTransientOrStallErrorRescuedByHedge) { + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/1, + /*expected_won=*/1); + ExpectTimers({"Timer1"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 1}, + UnlimitedLimiter(), metrics); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + + primary.set_value(GetParam()); + hedge1.set_value(303); + + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result->first_response.metadata().generation(), 303); +} + +INSTANTIATE_TEST_SUITE_P(PrimaryErrors, HedgedOpenRescueTest, + ::testing::Values(TransientError(), + Status(StatusCode::kCancelled, + "Stream stall timeout"))); + +class HedgedOpenPermanentAbortTest + : public HedgedOpenStreamTest, + public ::testing::WithParamInterface {}; + +TEST_P(HedgedOpenPermanentAbortTest, PermanentFailureAbortsSiblingImmediately) { + bool const primary_fails = GetParam(); + ExpectTimers({"Timer1", "Timer2"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 2}, + UnlimitedLimiter(), nullptr); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + promise timer2 = PopStep("Timer2"); + + if (primary_fails) { + primary.set_value(PermanentError()); + } else { + hedge1.set_value(PermanentError()); + } + EXPECT_THAT(pending.get(), StatusIs(PermanentError().code())); + EXPECT_EQ(cancelled_attempts_.load(), 1); + EXPECT_EQ(cancelled_timers_.load(), 1); + + timer2.set_value(CancelledError()); + if (primary_fails) { + hedge1.set_value(CancelledError()); + } else { + primary.set_value(CancelledError()); + } +} + +INSTANTIATE_TEST_SUITE_P(FailureOrigin, HedgedOpenPermanentAbortTest, + ::testing::Bool()); + +TEST_F(HedgedOpenStreamTest, AllAttemptsFailReturnsPrimaryError) { + ExpectTimers({"Timer1"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 1}, + UnlimitedLimiter(), nullptr); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + + primary.set_value(Status(StatusCode::kUnavailable, "primary unavailable")); + hedge1.set_value(Status(StatusCode::kDeadlineExceeded, "hedge deadline")); + + EXPECT_THAT(pending.get(), + StatusIs(StatusCode::kUnavailable, HasSubstr("primary"))); +} + +TEST_F(HedgedOpenStreamTest, CallerCancelCancelsAllAttemptsAndTimer) { + ExpectTimers({"Timer1", "Timer2"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 2}, + UnlimitedLimiter(), nullptr); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + promise timer2 = PopStep("Timer2"); + + pending.cancel(); + EXPECT_EQ(cancelled_timers_.load(), 1); + EXPECT_EQ(cancelled_attempts_.load(), 2); + + timer2.set_value(CancelledError()); + primary.set_value(TransientError()); + hedge1.set_value(TransientError()); + + EXPECT_THAT(pending.get(), StatusIs(StatusCode::kCancelled)); +} + +TEST_F(HedgedOpenStreamTest, CallerCancelWithInlineAttemptCompletion) { + ExpectTimers({"Timer1"}); + promise> attempt_promise{null_promise_t{}}; + attempt_promise = promise>( + [&attempt_promise] { attempt_promise.set_value(CancelledError()); }); + OpenStreamFactory inline_cancel_factory = + [&attempt_promise](google::storage::v2::BidiReadObjectRequest const&) { + return attempt_promise.get_future(); + }; + + ResultFuture pending = HedgedOpenStream( + CompletionQueue(mock_cq_), std::move(inline_cancel_factory), + MakeInitialRequest(), + storage::LimitedErrorCountAsyncRetryPolicy(0).clone(), + {std::chrono::milliseconds(100), 1}, UnlimitedLimiter(), nullptr, + google::cloud::internal::MakeImmutableOptions(Options{})); + promise timer1 = PopStep("Timer1"); + + pending.cancel(); + EXPECT_THAT(pending.get(), StatusIs(StatusCode::kCancelled)); + timer1.set_value(CancelledError()); +} + +TEST_F(HedgedOpenStreamTest, + LimiterDenialRetriesAtMinDelayAndRespectsLifetimeBudget) { + using ms = std::chrono::milliseconds; + auto limiter = std::make_shared( + 0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/2); + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/2, + /*expected_won=*/2); + ExpectTimers( + {"Call1Timer1", "Call2Timer1", "Call1Timer2", "Call2RetryTimer"}); + + ResultFuture call1 = RunHedgedOpen({ms(1), 2}, limiter, metrics); + ResultFuture call2 = RunHedgedOpen({ms(1), 2}, limiter, metrics); + promise c1_primary = PopStep("Primary"); + promise c1_timer1 = PopStep("Call1Timer1"); + promise c2_primary = PopStep("Primary"); + promise c2_timer1 = PopStep("Call2Timer1"); + + // Call 1 acquires the single concurrency slot (total 1/2) and arms Timer 2. + c1_timer1.set_value(0); + promise c1_hedge = PopStep("Hedge1"); + promise c1_timer2 = PopStep("Call1Timer2"); + + // Call 2 is denied by `max_concurrent = 1` and re-arms at the 10ms floor. + c2_timer1.set_value(0); + promise c2_retry = PopStep("Call2RetryTimer"); + EXPECT_THAT(timer_delays_, ElementsAre(ms(1), ms(1), ms(1), ms(10))); + + // Finishing Call 1's hedge releases its concurrency slot. + c1_hedge.set_value(601); + ASSERT_TRUE(call1.get().ok()); + c1_timer2.set_value(CancelledError()); + + // Call 2's retry timer acquires the freed slot and spends total budget (2/2), + // so no further timer is armed on Call 2 or on a subsequent Call 3. + c2_retry.set_value(0); + PopStep("Hedge1").set_value(602); + ASSERT_TRUE(call2.get().ok()); + + ResultFuture call3 = RunHedgedOpen({ms(1), 2}, limiter, metrics); + PopStep("Primary").set_value(603); + ASSERT_TRUE(call3.get().ok()); + + c1_primary.set_value(CancelledError()); + c2_primary.set_value(CancelledError()); +} + +TEST_F(HedgedOpenStreamTest, ClampsNegativeParamsToZero) { + // Negative `max_hedges` clamps to 0 (no timers armed). + ExpectTimers({}); + ResultFuture zero_hedges = RunHedgedOpen({std::chrono::milliseconds(-50), -3}, + UnlimitedLimiter(), nullptr); + PopStep("Primary").set_value(42); + ASSERT_TRUE(zero_hedges.get().ok()); + + // Negative `delay` clamps to 0ms. + timer_delays_.clear(); + ExpectTimers({"Timer1"}); + ResultFuture zero_delay = RunHedgedOpen({std::chrono::milliseconds(-25), 1}, + UnlimitedLimiter(), nullptr); + promise primary = PopStep("Primary"); + promise timer1 = PopStep("Timer1"); + EXPECT_THAT(timer_delays_, ElementsAre(std::chrono::milliseconds(0))); + primary.set_value(43); + ASSERT_TRUE(zero_delay.get().ok()); + timer1.set_value(CancelledError()); +} + +TEST(HedgedOpenStreamConcurrencyTest, ConcurrentCompletionRace) { + for (int iter = 0; iter != 25; ++iter) { + std::mutex gate_mu; + std::condition_variable gate_cv; + int ready_workers = 0; + bool release_workers = false; + std::atomic cancelled_streams{0}; + std::atomic attempt_seq{0}; + std::vector workers; + workers.reserve(2); + + OpenStreamFactory factory = + [&](google::storage::v2::BidiReadObjectRequest const&) { + std::int64_t const gen = ++attempt_seq; + OpenStreamResult open_result = + MakeOpenResult(gen, &cancelled_streams); + auto p = std::make_shared>>(); + future> out = p->get_future(); + { + std::lock_guard lock(gate_mu); + workers.emplace_back( + [&, p = std::move(p), res = std::move(open_result)]() mutable { + { + std::unique_lock wlock(gate_mu); + ++ready_workers; + gate_cv.notify_all(); + gate_cv.wait(wlock, [&] { return release_workers; }); + } + p->set_value(std::move(res)); + }); + } + return out; + }; + + auto mock_cq = std::make_shared(); + EXPECT_CALL(*mock_cq, MakeRelativeTimer) + .WillOnce([](std::chrono::nanoseconds) { + return make_ready_future( + StatusOr( + std::chrono::system_clock::now())); + }); + + future> pending = HedgedOpenStream( + CompletionQueue(mock_cq), std::move(factory), MakeInitialRequest(), + storage::LimitedErrorCountAsyncRetryPolicy(0).clone(), + {std::chrono::milliseconds(0), 1}, + std::make_shared(0.0, 0.0, 0, 0), + nullptr, google::cloud::internal::MakeImmutableOptions(Options{})); + + { + std::unique_lock lock(gate_mu); + gate_cv.wait(lock, [&] { return ready_workers == 2; }); + release_workers = true; + } + gate_cv.notify_all(); + for (std::thread& w : workers) w.join(); + + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_THAT(result->first_response.metadata().generation(), + AnyOf(Eq(1), Eq(2))); + // Exactly the losing attempt's `OpenStream` is cancelled, never the winner. + EXPECT_EQ(cancelled_streams.load(), 1); + } +} + +} // namespace +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/storage_client_grpc_unit_tests.bzl b/google/cloud/storage/storage_client_grpc_unit_tests.bzl index d3fbed0e8e840..207da05c56197 100644 --- a/google/cloud/storage/storage_client_grpc_unit_tests.bzl +++ b/google/cloud/storage/storage_client_grpc_unit_tests.bzl @@ -40,6 +40,7 @@ storage_client_grpc_unit_tests = [ "internal/async/connection_tracing_test.cc", "internal/async/default_options_test.cc", "internal/async/handle_redirect_error_test.cc", + "internal/async/hedged_open_stream_test.cc", "internal/async/insert_object_test.cc", "internal/async/multi_stream_manager_test.cc", "internal/async/object_descriptor_connection_tracing_test.cc",