Repository navigation
refactor(storage): extract HedgeLimiter from HedgingThreadPool #16715
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ajayky-os
wants to merge
1
commit into
googleapis:main
Choose a base branch
from
ajayky-os:refactor/storage-extract-hedge-limiter
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 <algorithm> | ||
| #include <atomic> | ||
| #include <chrono> | ||
| #include <cstdint> | ||
| #include <memory> | ||
| #include <mutex> | ||
| #include <utility> | ||
|
|
||
| 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<Clock>()) {} | ||
|
|
||
| /// @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 const> 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<std::mutex> 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<std::mutex> 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<std::chrono::duration<double>>(now - | ||
| last_refill_) | ||
| .count(); | ||
| last_refill_ = now; | ||
| tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_); | ||
| } | ||
|
ajayky-os marked this conversation as resolved.
Resolved
|
||
|
|
||
| std::shared_ptr<Clock const> 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<std::int64_t> active_concurrent_hedges_{0}; | ||
|
|
||
| std::int64_t const max_total_hedges_; | ||
| std::atomic<std::int64_t> 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 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -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 <gmock/gmock.h> | ||
| #include <gtest/gtest.h> | ||
| #include <atomic> | ||
| #include <chrono> | ||
| #include <cstdint> | ||
| #include <memory> | ||
| #include <thread> | ||
| #include <vector> | ||
|
|
||
| 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<FakeSteadyClock>(); | ||
| 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<FakeSteadyClock>(); | ||
| 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<FakeSteadyClock>(); | ||
| 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<std::int64_t> granted{0}; | ||
| std::vector<std::thread> 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 |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.