Skip to content

Commit 6d8a063

Browse files
committed
refactor(storage): extract HedgeLimiter from HedgingThreadPool
1 parent 4a2bfb0 commit 6d8a063

7 files changed

Lines changed: 370 additions & 233 deletions

‎google/cloud/storage/google_cloud_cpp_storage.bzl‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ google_cloud_cpp_storage_hdrs = [
7474
"internal/hash_validator.h",
7575
"internal/hash_validator_impl.h",
7676
"internal/hash_values.h",
77+
"internal/hedge_limiter.h",
7778
"internal/hedged_object_read_source.h",
7879
"internal/hedged_read_metrics.h",
7980
"internal/hedging_thread_pool.h",

‎google/cloud/storage/google_cloud_cpp_storage.cmake‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,6 +117,7 @@ add_library(
117117
internal/hash_validator_impl.h
118118
internal/hash_values.cc
119119
internal/hash_values.h
120+
internal/hedge_limiter.h
120121
internal/hedged_object_read_source.cc
121122
internal/hedged_object_read_source.h
122123
internal/hedged_read_metrics.cc
@@ -462,6 +463,7 @@ if (BUILD_TESTING)
462463
internal/hash_function_impl_test.cc
463464
internal/hash_validator_test.cc
464465
internal/hash_values_test.cc
466+
internal/hedge_limiter_test.cc
465467
internal/hedged_object_read_source_test.cc
466468
internal/hedged_read_metrics_test.cc
467469
internal/hedging_thread_pool_test.cc
Lines changed: 174 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,174 @@
1+
// Copyright 2026 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H
16+
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H
17+
18+
#include "google/cloud/storage/version.h"
19+
#include "google/cloud/internal/clock.h"
20+
#include <algorithm>
21+
#include <atomic>
22+
#include <chrono>
23+
#include <cstdint>
24+
#include <memory>
25+
#include <mutex>
26+
#include <utility>
27+
28+
namespace google {
29+
namespace cloud {
30+
namespace storage {
31+
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
32+
namespace internal {
33+
34+
/**
35+
* Enforces connection-wide rate, concurrency, and lifetime limits on
36+
* speculative hedged requests.
37+
*
38+
* Values `<= 0` disable the corresponding limit; `capacity` is clamped to at
39+
* least `1.0` so fractional rate limits (`0.0 < rate_limit < 1.0`) can still
40+
* issue hedges once refilled.
41+
*/
42+
class HedgeLimiter {
43+
public:
44+
using Clock = google::cloud::internal::SteadyClock;
45+
46+
HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent,
47+
std::int64_t max_total)
48+
: HedgeLimiter(rate_limit, capacity, max_concurrent, max_total,
49+
std::make_shared<Clock>()) {}
50+
51+
/// @p clock must not be null. Tests inject `testing_util::FakeSteadyClock`.
52+
HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent,
53+
std::int64_t max_total, std::shared_ptr<Clock const> clock)
54+
: clock_(std::move(clock)),
55+
rate_limit_(rate_limit),
56+
tokens_capacity_((std::max)(1.0, capacity)),
57+
tokens_((std::max)(1.0, capacity)),
58+
last_refill_(clock_->Now()),
59+
max_concurrent_hedges_(max_concurrent),
60+
max_total_hedges_(max_total) {}
61+
62+
~HedgeLimiter() = default;
63+
64+
HedgeLimiter(HedgeLimiter const&) = delete;
65+
HedgeLimiter& operator=(HedgeLimiter const&) = delete;
66+
HedgeLimiter(HedgeLimiter&&) = delete;
67+
HedgeLimiter& operator=(HedgeLimiter&&) = delete;
68+
69+
/**
70+
* Reserves capacity for one hedged request.
71+
*
72+
* On success the caller *must* eventually call `ReleaseHedgeSlot()`.
73+
*/
74+
bool TryAcquireHedgeToken() {
75+
// Once the lifetime budget is spent, deny with a single atomic load.
76+
if (IsTotalBudgetSpent()) return false;
77+
78+
// Gate 1: the ceiling on concurrently active hedges. When
79+
// max_concurrent_hedges_ <= 0, concurrency limiting is disabled.
80+
if (max_concurrent_hedges_ > 0) {
81+
std::int64_t current =
82+
active_concurrent_hedges_.load(std::memory_order_relaxed);
83+
do {
84+
if (current >= max_concurrent_hedges_) return false;
85+
} while (!active_concurrent_hedges_.compare_exchange_weak(
86+
current, current + 1, std::memory_order_relaxed));
87+
}
88+
89+
// Gate 2: the rate limit on new hedges (token bucket). When
90+
// rate_limit_ <= 0.0, rate limiting is disabled.
91+
if (rate_limit_ > 0.0) {
92+
std::lock_guard<std::mutex> lock(limiter_mutex_);
93+
Refill();
94+
if (tokens_ < 1.0) {
95+
ReleaseHedgeSlot();
96+
return false;
97+
}
98+
tokens_ -= 1.0;
99+
}
100+
101+
// Gate 3: the lifetime budget. Checked last so the counter only moves for
102+
// a hedge that is granted, which keeps `IsTotalBudgetSpent()` exact. If
103+
// another thread took the last unit since the check above, return what the
104+
// earlier gates reserved. When max_total_hedges_ <= 0, the lifetime limit
105+
// is disabled.
106+
if (max_total_hedges_ > 0) {
107+
std::int64_t granted =
108+
total_hedges_granted_.load(std::memory_order_relaxed);
109+
do {
110+
if (granted >= max_total_hedges_) {
111+
ReleaseHedgeSlot();
112+
ReturnRateToken();
113+
return false;
114+
}
115+
} while (!total_hedges_granted_.compare_exchange_weak(
116+
granted, granted + 1, std::memory_order_relaxed));
117+
}
118+
119+
return true;
120+
}
121+
122+
/// Releases the concurrency slot. The lifetime budget is never returned.
123+
void ReleaseHedgeSlot() {
124+
if (max_concurrent_hedges_ > 0) {
125+
active_concurrent_hedges_.fetch_sub(1, std::memory_order_relaxed);
126+
}
127+
}
128+
129+
/// Returns true once the lifetime budget is spent. No hedge is granted after
130+
/// that, so callers can skip racing altogether.
131+
bool IsTotalBudgetSpent() const {
132+
return max_total_hedges_ > 0 &&
133+
total_hedges_granted_.load(std::memory_order_relaxed) >=
134+
max_total_hedges_;
135+
}
136+
137+
private:
138+
void ReturnRateToken() {
139+
if (rate_limit_ <= 0.0) return;
140+
std::lock_guard<std::mutex> lock(limiter_mutex_);
141+
tokens_ = (std::min)(tokens_capacity_, tokens_ + 1.0);
142+
}
143+
144+
void Refill() {
145+
Clock::time_point const now = clock_->Now();
146+
double const elapsed =
147+
std::chrono::duration_cast<std::chrono::duration<double>>(now -
148+
last_refill_)
149+
.count();
150+
last_refill_ = now;
151+
tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_);
152+
}
153+
154+
std::shared_ptr<Clock const> const clock_;
155+
double const rate_limit_;
156+
double const tokens_capacity_;
157+
double tokens_;
158+
Clock::time_point last_refill_;
159+
std::mutex limiter_mutex_;
160+
161+
std::int64_t const max_concurrent_hedges_;
162+
std::atomic<std::int64_t> active_concurrent_hedges_{0};
163+
164+
std::int64_t const max_total_hedges_;
165+
std::atomic<std::int64_t> total_hedges_granted_{0};
166+
};
167+
168+
} // namespace internal
169+
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
170+
} // namespace storage
171+
} // namespace cloud
172+
} // namespace google
173+
174+
#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H
Lines changed: 180 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,180 @@
1+
// Copyright 2026 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// https://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
#include "google/cloud/storage/internal/hedge_limiter.h"
16+
#include "google/cloud/testing_util/fake_clock.h"
17+
#include <gmock/gmock.h>
18+
#include <gtest/gtest.h>
19+
#include <atomic>
20+
#include <chrono>
21+
#include <cstdint>
22+
#include <memory>
23+
#include <thread>
24+
#include <vector>
25+
26+
namespace google {
27+
namespace cloud {
28+
namespace storage {
29+
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN
30+
namespace internal {
31+
namespace {
32+
33+
using ::google::cloud::testing_util::FakeSteadyClock;
34+
using ::testing::Eq;
35+
36+
TEST(HedgeLimiterTest, MaxConcurrentHedgesLimit) {
37+
HedgeLimiter limiter(0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/0);
38+
39+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
40+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
41+
42+
limiter.ReleaseHedgeSlot();
43+
44+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
45+
}
46+
47+
TEST(HedgeLimiterTest, RateLimiter) {
48+
// 5 tokens/second (one token per 200ms), burst capacity of 2 tokens.
49+
auto clock = std::make_shared<FakeSteadyClock>();
50+
HedgeLimiter limiter(5.0, 2.0, 0, 0, clock);
51+
52+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
53+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
54+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
55+
56+
// Half-token step margins avoid IEEE-754 boundary rounding sensitivity.
57+
clock->AdvanceTime(std::chrono::milliseconds(100)); // +0.5 token
58+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
59+
clock->AdvanceTime(std::chrono::milliseconds(200)); // +1.0 token => 1.5
60+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
61+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
62+
63+
// Refill is clamped at burst capacity (2 tokens).
64+
clock->AdvanceTime(std::chrono::seconds(10));
65+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
66+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
67+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
68+
}
69+
70+
TEST(HedgeLimiterTest, FractionalRateLimiter) {
71+
// 0.5 tokens/second (one token per 2s); capacity 0.5 clamps to floor 1.0.
72+
auto clock = std::make_shared<FakeSteadyClock>();
73+
HedgeLimiter limiter(0.5, 0.5, 0, 0, clock);
74+
75+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
76+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
77+
78+
clock->AdvanceTime(std::chrono::seconds(1)); // +0.5 token
79+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
80+
clock->AdvanceTime(std::chrono::seconds(2)); // +1.0 token => clamped to 1.0
81+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
82+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
83+
}
84+
85+
TEST(HedgeLimiterTest, ZeroRateLimitDisablesRateLimiting) {
86+
HedgeLimiter limiter(0.0, 0.0, 0, 0);
87+
88+
for (int i = 0; i < 100; ++i) {
89+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
90+
}
91+
}
92+
93+
TEST(HedgeLimiterTest, MaxTotalHedgesLimit) {
94+
HedgeLimiter limiter(0.0, 0.0, 0, /*max_total=*/3);
95+
96+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
97+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
98+
EXPECT_FALSE(limiter.IsTotalBudgetSpent());
99+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
100+
EXPECT_TRUE(limiter.IsTotalBudgetSpent());
101+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
102+
103+
// Releasing a hedge frees its concurrency slot, never its lifetime budget.
104+
limiter.ReleaseHedgeSlot();
105+
limiter.ReleaseHedgeSlot();
106+
limiter.ReleaseHedgeSlot();
107+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
108+
}
109+
110+
TEST(HedgeLimiterTest, ConcurrencyDenialDoesNotSpendTotalBudget) {
111+
HedgeLimiter limiter(0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/2);
112+
113+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
114+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
115+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
116+
EXPECT_FALSE(limiter.IsTotalBudgetSpent());
117+
limiter.ReleaseHedgeSlot();
118+
119+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
120+
limiter.ReleaseHedgeSlot();
121+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
122+
}
123+
124+
TEST(HedgeLimiterTest, RateLimitDenialDoesNotSpendTotalBudget) {
125+
auto clock = std::make_shared<FakeSteadyClock>();
126+
HedgeLimiter limiter(0.001, 1.0, 0, /*max_total=*/2, clock);
127+
128+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
129+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
130+
EXPECT_FALSE(limiter.TryAcquireHedgeToken());
131+
EXPECT_FALSE(limiter.IsTotalBudgetSpent());
132+
133+
clock->AdvanceTime(std::chrono::seconds(1500));
134+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
135+
EXPECT_TRUE(limiter.IsTotalBudgetSpent());
136+
}
137+
138+
TEST(HedgeLimiterTest, ZeroMaxTotalDisablesLifetimeLimit) {
139+
HedgeLimiter limiter(0.0, 0.0, 0, /*max_total=*/0);
140+
141+
for (int i = 0; i < 100; ++i) {
142+
EXPECT_TRUE(limiter.TryAcquireHedgeToken());
143+
}
144+
EXPECT_FALSE(limiter.IsTotalBudgetSpent());
145+
}
146+
147+
TEST(HedgeLimiterTest, MaxTotalHedgesUnderContention) {
148+
std::int64_t const max_total = 100;
149+
// A rate limit that never runs out, so threads racing for the last unit of
150+
// budget also exercise returning the rate token.
151+
HedgeLimiter limiter(1e9, 1e9, /*max_concurrent=*/4, max_total);
152+
153+
std::atomic<std::int64_t> granted{0};
154+
std::vector<std::thread> threads;
155+
threads.reserve(8);
156+
for (int t = 0; t != 8; ++t) {
157+
threads.emplace_back([&limiter, &granted] {
158+
for (int i = 0; i != 1000; ++i) {
159+
if (!limiter.TryAcquireHedgeToken()) continue;
160+
++granted;
161+
limiter.ReleaseHedgeSlot();
162+
}
163+
});
164+
}
165+
for (std::thread& t : threads) t.join();
166+
167+
while (limiter.TryAcquireHedgeToken()) {
168+
++granted;
169+
limiter.ReleaseHedgeSlot();
170+
}
171+
EXPECT_THAT(granted.load(), Eq(max_total));
172+
EXPECT_TRUE(limiter.IsTotalBudgetSpent());
173+
}
174+
175+
} // namespace
176+
} // namespace internal
177+
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
178+
} // namespace storage
179+
} // namespace cloud
180+
} // namespace google

0 commit comments

Comments
 (0)