From bb6e5de11bee9cfc04e89ecc8ed22baac88de2ba Mon Sep 17 00:00:00 2001 From: Ajay Yadav Date: Wed, 25 Nov 2026 08:22:12 +0000 Subject: [PATCH 1/4] fix(storage): make OpenStream and OpenObject cancellation-safe --- .../storage/internal/async/open_object.cc | 21 ++- .../storage/internal/async/open_object.h | 7 +- .../internal/async/open_object_test.cc | 176 ++++++++++++++++++ .../storage/internal/async/open_stream.cc | 110 +++++++---- .../storage/internal/async/open_stream.h | 31 +-- .../internal/async/open_stream_test.cc | 85 ++++++++- 6 files changed, 375 insertions(+), 55 deletions(-) diff --git a/google/cloud/storage/internal/async/open_object.cc b/google/cloud/storage/internal/async/open_object.cc index 148bdfb1cd593..659750d9faad3 100644 --- a/google/cloud/storage/internal/async/open_object.cc +++ b/google/cloud/storage/internal/async/open_object.cc @@ -44,7 +44,10 @@ OpenObject::OpenObject(storage_internal::StorageStub& stub, CompletionQueue& cq, initial_request_(std::move(request)) {} future> OpenObject::Call() { - auto future = promise_.get_future(); + promise_ = promise>([w = WeakFromThis()] { + if (std::shared_ptr self = w.lock()) self->OnCancel(); + }); + future> future = promise_.get_future(); rpc_->Start().then([w = WeakFromThis()](auto f) { if (auto self = w.lock()) self->OnStart(f.get()); }); @@ -92,9 +95,20 @@ void OpenObject::OnWrite(bool ok) { void OpenObject::OnRead( std::optional response) { if (!response) return DoFinish(); + State expected = State::kOpening; + if (!state_.compare_exchange_strong(expected, State::kCommitted)) { + rpc_->Cancel(); + return DoFinish(); + } promise_.set_value(OpenStreamResult{std::move(rpc_), std::move(*response)}); } +void OpenObject::OnCancel() { + State expected = State::kOpening; + if (!state_.compare_exchange_strong(expected, State::kCancelled)) return; + rpc_->Cancel(); +} + void OpenObject::DoFinish() { rpc_->Finish().then([w = WeakFromThis()](auto f) { if (auto self = w.lock()) self->OnFinish(f.get()); @@ -102,6 +116,11 @@ void OpenObject::DoFinish() { } void OpenObject::OnFinish(Status status) { + if (state_.load() == State::kCancelled) { + promise_.set_value(google::cloud::internal::CancelledError( + "Stream cancelled while opening", GCP_ERROR_INFO())); + return; + } if (!status.ok()) return promise_.set_value(std::move(status)); // This should not happen, it indicates an EOF on the stream, but we // did not ask to close it. diff --git a/google/cloud/storage/internal/async/open_object.h b/google/cloud/storage/internal/async/open_object.h index 65f01dba4024c..c600e3e3540d8 100644 --- a/google/cloud/storage/internal/async/open_object.h +++ b/google/cloud/storage/internal/async/open_object.h @@ -25,6 +25,7 @@ #include "google/cloud/version.h" #include "google/storage/v2/storage.pb.h" #include +#include #include #include @@ -89,6 +90,8 @@ class OpenObject : public std::enable_shared_from_this { future> Call(); private: + enum class State { kOpening, kCommitted, kCancelled }; + std::weak_ptr WeakFromThis(); static std::unique_ptr CreateRpc( @@ -101,12 +104,14 @@ class OpenObject : public std::enable_shared_from_this { void OnWrite(bool ok); void OnRead( std::optional response); + void OnCancel(); void DoFinish(); void OnFinish(Status status); std::shared_ptr rpc_; - promise> promise_; + promise> promise_{null_promise_t{}}; google::storage::v2::BidiReadObjectRequest initial_request_; + std::atomic state_{State::kOpening}; }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END diff --git a/google/cloud/storage/internal/async/open_object_test.cc b/google/cloud/storage/internal/async/open_object_test.cc index c1fa3a4dcde02..0ccf2e714276b 100644 --- a/google/cloud/storage/internal/async/open_object_test.cc +++ b/google/cloud/storage/internal/async/open_object_test.cc @@ -24,8 +24,12 @@ #include "google/cloud/testing_util/validate_metadata.h" #include #include +#include #include +#include #include +#include +#include namespace google { namespace cloud { @@ -472,6 +476,178 @@ TEST(OpenImpl, TimeoutCancellation) { EXPECT_THAT(response, StatusIs(StatusCode::kCancelled)); } +enum class CancelPhase { kStart, kWrite, kRead, kFinish }; + +class OpenObjectCancelPhaseTest : public ::testing::TestWithParam { +}; + +TEST_P(OpenObjectCancelPhaseTest, CancelsCleanlyAtHandshakePhase) { + CancelPhase const phase = GetParam(); + AsyncSequencer sequencer; + MockStorageStub mock; + EXPECT_CALL(mock, AsyncBidiReadObject).WillOnce([&sequencer, phase] { + auto stream = std::make_unique(); + EXPECT_CALL(*stream, Start).WillOnce([&sequencer] { + return sequencer.PushBack("Start").then( + [](future f) { return f.get(); }); + }); + if (phase == CancelPhase::kWrite || phase == CancelPhase::kRead) { + EXPECT_CALL(*stream, Write).WillOnce([&sequencer] { + return sequencer.PushBack("Write").then( + [](future f) { return f.get(); }); + }); + } + if (phase == CancelPhase::kRead) { + EXPECT_CALL(*stream, Read).WillOnce([&sequencer] { + return sequencer.PushBack("Read").then([](future) { + return std::make_optional( + google::storage::v2::BidiReadObjectResponse{}); + }); + }); + } + if (phase != CancelPhase::kFinish) { + ::testing::InSequence seq; + EXPECT_CALL(*stream, Cancel).Times(1); + EXPECT_CALL(*stream, Finish).WillOnce([&sequencer, phase] { + return sequencer.PushBack("Finish").then([phase](future) { + return phase == CancelPhase::kRead + ? internal::UnavailableError("reset", GCP_ERROR_INFO()) + : Status{}; + }); + }); + } else { + ::testing::InSequence seq; + EXPECT_CALL(*stream, Finish).WillOnce([&sequencer] { + return sequencer.PushBack("Finish").then( + [](future) { return Status{}; }); + }); + EXPECT_CALL(*stream, Cancel).Times(1); + } + return std::unique_ptr(std::move(stream)); + }); + + CompletionQueue cq; + auto coro = std::make_shared( + mock, cq, std::make_shared(), + internal::MakeImmutableOptions({}), + google::storage::v2::BidiReadObjectRequest{}); + future> pending = coro->Call(); + + auto const pop = [&sequencer](char const* expected) { + auto [p, name] = sequencer.PopFrontWithName(); + EXPECT_EQ(name, expected); + return std::move(p); + }; + + promise start = pop("Start"); + if (phase == CancelPhase::kStart) pending.cancel(); + start.set_value(phase != CancelPhase::kFinish); + + if (phase == CancelPhase::kWrite || phase == CancelPhase::kRead) { + promise write = pop("Write"); + if (phase == CancelPhase::kWrite) pending.cancel(); + write.set_value(true); + } + if (phase == CancelPhase::kRead) { + promise read = pop("Read"); + pending.cancel(); + read.set_value(true); + } + + promise finish = pop("Finish"); + if (phase == CancelPhase::kFinish) pending.cancel(); + EXPECT_FALSE(pending.is_ready()); + finish.set_value(true); + + EXPECT_THAT(pending.get(), StatusIs(StatusCode::kCancelled)); +} + +INSTANTIATE_TEST_SUITE_P(CancelPhases, OpenObjectCancelPhaseTest, + ::testing::Values(CancelPhase::kStart, + CancelPhase::kWrite, + CancelPhase::kRead, + CancelPhase::kFinish)); + +TEST(OpenImpl, ConcurrentCancelAndReadCompletion) { + for (int iter = 0; iter != 25; ++iter) { + std::mutex gate_mu; + std::condition_variable gate_cv; + int ready = 0; + bool release = false; + std::atomic cancel_calls{0}; + auto read_promise = std::make_shared< + promise>>(); + future read_future = read_promise->get_future(); + + MockStorageStub mock; + EXPECT_CALL(mock, AsyncBidiReadObject).WillOnce([&] { + auto stream = std::make_unique<::testing::NiceMock>(); + ON_CALL(*stream, Start).WillByDefault([] { + return make_ready_future(true); + }); + ON_CALL(*stream, Write) + .WillByDefault( + [](google::storage::v2::BidiReadObjectRequest const&, + grpc::WriteOptions) { return make_ready_future(true); }); + EXPECT_CALL(*stream, Read) + .WillOnce( + [f = std::move(read_future)]() mutable { return std::move(f); }) + .WillRepeatedly([] { + return make_ready_future(std::make_optional( + google::storage::v2::BidiReadObjectResponse{})); + }); + ON_CALL(*stream, Cancel).WillByDefault([&cancel_calls] { + ++cancel_calls; + }); + ON_CALL(*stream, Finish).WillByDefault([] { + return make_ready_future(Status{}); + }); + return std::unique_ptr(std::move(stream)); + }); + + CompletionQueue cq; + auto coro = std::make_shared( + mock, cq, std::make_shared(), + internal::MakeImmutableOptions({}), + google::storage::v2::BidiReadObjectRequest{}); + future> pending = coro->Call(); + + auto const wait_at_gate = [&] { + std::unique_lock lock(gate_mu); + ++ready; + gate_cv.notify_all(); + gate_cv.wait(lock, [&] { return release; }); + }; + std::thread reader([&] { + wait_at_gate(); + read_promise->set_value( + std::make_optional(google::storage::v2::BidiReadObjectResponse{})); + }); + std::thread canceller([&] { + wait_at_gate(); + pending.cancel(); + }); + + { + std::unique_lock lock(gate_mu); + gate_cv.wait(lock, [&] { return ready == 2; }); + release = true; + } + gate_cv.notify_all(); + reader.join(); + canceller.join(); + + StatusOr result = pending.get(); + if (result.ok()) { + EXPECT_EQ(cancel_calls.load(), 0); + EXPECT_TRUE(result->stream->Read().get().has_value()); + } else { + EXPECT_THAT(result, StatusIs(StatusCode::kCancelled)); + EXPECT_EQ(cancel_calls.load(), 1); + } + } +} + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal diff --git a/google/cloud/storage/internal/async/open_stream.cc b/google/cloud/storage/internal/async/open_stream.cc index ca41fba9c6557..c5ff2660a0991 100644 --- a/google/cloud/storage/internal/async/open_stream.cc +++ b/google/cloud/storage/internal/async/open_stream.cc @@ -24,62 +24,100 @@ OpenStream::OpenStream(std::unique_ptr rpc) : rpc_(std::move(rpc)) {} void OpenStream::Cancel() { - cancel_.store(true); + { + std::lock_guard lk(mu_); + if (cancel_) return; + cancel_ = true; + ++pending_ops_; + if (!finish_issued_) { + finish_issued_ = true; + finish_deferred_ = true; + finish_promise_ = promise{}; + finish_ = finish_promise_.get_future(); + } + } rpc_->Cancel(); - MaybeFinish(); + EndOp(); } future OpenStream::Start() { - if (cancel_) return make_ready_future(false); - return rpc_->Start(); + if (!BeginOp()) return make_ready_future(false); + return rpc_->Start().then([s = shared_from_this()](future f) mutable { + std::shared_ptr self = std::move(s); + bool const cancelled = self->EndOp(); + bool const ok = f.get(); + return !cancelled && ok; + }); } future OpenStream::Write( google::storage::v2::BidiReadObjectRequest const& request) { - if (cancel_) return make_ready_future(false); - pending_write_.store(true); + if (!BeginOp()) return make_ready_future(false); return rpc_->Write(request, grpc::WriteOptions{}) - .then([s = shared_from_this()](auto f) mutable { - auto self = std::move(s); - self->OnWrite(); - return f.get(); + .then([s = shared_from_this()](future f) mutable { + std::shared_ptr self = std::move(s); + bool const cancelled = self->EndOp(); + bool const ok = f.get(); + return !cancelled && ok; }); } future OpenStream::Read() { - if (cancel_) return make_ready_future(ReadType(std::nullopt)); - pending_read_.store(true); - return rpc_->Read().then([s = shared_from_this()](auto f) mutable { - auto self = std::move(s); - self->OnRead(); - return f.get(); - }); + if (!BeginOp()) return make_ready_future(ReadType(std::nullopt)); + return rpc_->Read().then( + [s = shared_from_this()](future f) mutable { + std::shared_ptr self = std::move(s); + bool const cancelled = self->EndOp(); + ReadType result = f.get(); + if (cancelled) return ReadType(std::nullopt); + return result; + }); } future OpenStream::Finish() { - if (finish_issued_.exchange(true)) return {}; - return rpc_->Finish().then([s = shared_from_this()](auto f) mutable { - auto result = f.get(); - s.reset(); - return result; - }); -} - -void OpenStream::OnWrite() { - pending_write_.store(false); - return MaybeFinish(); + { + std::lock_guard lk(mu_); + if (finish_issued_) return std::move(finish_); + finish_issued_ = true; + } + return rpc_->Finish().then( + [s = shared_from_this()](future f) mutable { + s.reset(); + return f.get(); + }); } -void OpenStream::OnRead() { - pending_read_.store(false); - return MaybeFinish(); +bool OpenStream::BeginOp() { + std::lock_guard lk(mu_); + if (cancel_ || finish_issued_) return false; + ++pending_ops_; + return true; } -void OpenStream::MaybeFinish() { - if (!cancel_) return; - // Once `cancel_` is true these can only become false. - if (pending_read_ || pending_write_) return; - Finish(); +bool OpenStream::EndOp() { + promise deferred_finish{null_promise_t{}}; + bool issue_finish = false; + bool cancelled = false; + { + std::lock_guard lk(mu_); + --pending_ops_; + cancelled = cancel_; + if (finish_deferred_ && pending_ops_ == 0) { + finish_deferred_ = false; + deferred_finish = std::move(finish_promise_); + issue_finish = true; + } + } + if (issue_finish) { + rpc_->Finish().then( + [s = shared_from_this(), + p = std::move(deferred_finish)](future f) mutable { + promise out = std::move(p); + s.reset(); + out.set_value(f.get()); + }); + } + return cancelled; } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END diff --git a/google/cloud/storage/internal/async/open_stream.h b/google/cloud/storage/internal/async/open_stream.h index b339d6949bd02..7574994514d38 100644 --- a/google/cloud/storage/internal/async/open_stream.h +++ b/google/cloud/storage/internal/async/open_stream.h @@ -21,9 +21,9 @@ #include "google/cloud/status_or.h" #include "google/cloud/version.h" #include "google/storage/v2/storage.pb.h" -#include #include #include +#include #include namespace google { @@ -36,12 +36,13 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN * * gRPC imposes a number of restrictions on how to close bidi streaming RPCs. * This class automates most of these restrictions. In particular, it waits - * (using background threads) until all pending `Read()` and `Write()` calls - * complete before trying to `Finish()` and then delete the stream. + * (using background threads) until all pending `Start()`, `Read()`, and + * `Write()` calls complete before trying to `Finish()` and then delete the + * stream. * * gRPC will assert if one deletes a streaming read-write RPC before waiting for * the result of `Finish()` calls. It will also assert if one calls `Finish()` - * while there are pending `Read()` or `Write()` calls. + * while there are pending `Start()`, `Read()`, or `Write()` calls. * * This class tracks what operations, if any, are pending. On cancel, it waits * until all pending operations complete, then calls `Finish()` and then deletes @@ -62,21 +63,29 @@ class OpenStream : public std::enable_shared_from_this { explicit OpenStream(std::unique_ptr rpc); + /// Cancels the stream and calls `Finish()` once pending operations drain. void Cancel(); future Start(); future Write(google::storage::v2::BidiReadObjectRequest const& request); future Read(); + /// Returns the stream's `Finish()` future; subsequent calls return `{}`. future Finish(); private: - void OnWrite(); - void OnRead(); - void MaybeFinish(); + bool BeginOp(); + /// Decrements `pending_ops_`, starts any cancel-deferred `Finish()` at 0, + /// and returns whether `Cancel()` has been called. + bool EndOp(); - std::atomic cancel_{false}; - std::atomic pending_read_{false}; - std::atomic pending_write_{false}; - std::atomic finish_issued_{false}; + std::mutex mu_; + /// Active `Start()`, `Write()`, `Read()`, and `Cancel()` calls blocking + /// cancel-deferred `rpc_->Finish()`. + int pending_ops_ = 0; + bool cancel_ = false; + bool finish_issued_ = false; + bool finish_deferred_ = false; + promise finish_promise_{null_promise_t{}}; + future finish_; std::unique_ptr rpc_; }; diff --git a/google/cloud/storage/internal/async/open_stream_test.cc b/google/cloud/storage/internal/async/open_stream_test.cc index 7a8183e36ebe9..0de36586e7f30 100644 --- a/google/cloud/storage/internal/async/open_stream_test.cc +++ b/google/cloud/storage/internal/async/open_stream_test.cc @@ -40,12 +40,15 @@ TEST(OpenStream, CancelBlocksAllRequest) { EXPECT_CALL(*mock, Start).Times(0); EXPECT_CALL(*mock, Write).Times(0); EXPECT_CALL(*mock, Read).Times(0); - EXPECT_CALL(*mock, Cancel).Times(1); - EXPECT_CALL(*mock, Finish).WillOnce([&sequencer] { - return sequencer.PushBack("Finish").then([](auto) { - return internal::CancelledError("test-only", GCP_ERROR_INFO()); + { + ::testing::InSequence seq; + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Finish).WillOnce([&sequencer] { + return sequencer.PushBack("Finish").then([](auto) { + return internal::CancelledError("test-only", GCP_ERROR_INFO()); + }); }); - }); + } auto actual = std::make_shared(std::move(mock)); actual->Cancel(); @@ -73,7 +76,8 @@ TEST(OpenStream, DuplicateFinish) { auto actual = std::make_shared(std::move(mock)); - auto f1 = actual->Finish(); + future f1 = actual->Finish(); + EXPECT_FALSE(actual->Finish().valid()); auto next = sequencer.PopFrontWithName(); EXPECT_EQ(next.second, "Finish"); next.first.set_value(true); @@ -119,6 +123,75 @@ TEST(OpenStream, CleanShutdown) { next.first.set_value(true); } +TEST(OpenStream, CancelDuringStartDefersFinishAndHandsOffFutureOnce) { + AsyncSequencer sequencer; + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Start).WillOnce([&sequencer] { + return sequencer.PushBack("Start").then( + [](future f) { return f.get(); }); + }); + { + ::testing::InSequence seq; + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Finish).WillOnce([&sequencer] { + return sequencer.PushBack("Finish").then([](future) { + return internal::CancelledError("test-only", GCP_ERROR_INFO()); + }); + }); + } + + auto actual = std::make_shared(std::move(mock)); + future start = actual->Start(); + auto [pending_start, start_name] = sequencer.PopFrontWithName(); + EXPECT_EQ(start_name, "Start"); + + actual->Cancel(); + actual->Cancel(); + future claimed = actual->Finish(); + ASSERT_TRUE(claimed.valid()); + EXPECT_FALSE(claimed.is_ready()); + EXPECT_FALSE(actual->Finish().valid()); + actual.reset(); + + // `Finish` must not be invoked on `mock` until `Start` completes. + EXPECT_TRUE(sequencer.empty()); + pending_start.set_value(true); + EXPECT_FALSE(start.get()); + + auto [pending_finish, finish_name] = sequencer.PopFrontWithName(); + EXPECT_EQ(finish_name, "Finish"); + pending_finish.set_value(true); + EXPECT_THAT(claimed.get(), StatusIs(StatusCode::kCancelled)); +} + +TEST(OpenStream, CancelDuringReadDropsResponseAndReleasesRetainedPromise) { + auto retained_read = std::make_shared>(); + auto mock = std::make_unique(); + EXPECT_CALL(*mock, Read).WillOnce([retained_read] { + return retained_read->get_future(); + }); + { + ::testing::InSequence seq; + EXPECT_CALL(*mock, Cancel).Times(1); + EXPECT_CALL(*mock, Finish).WillOnce([] { + return make_ready_future(Status{}); + }); + } + + auto actual = std::make_shared(std::move(mock)); + std::weak_ptr weak = actual; + future read = actual->Read(); + + actual->Cancel(); + actual.reset(); + EXPECT_FALSE(weak.expired()); + + retained_read->set_value( + ReadType(google::storage::v2::BidiReadObjectResponse{})); + EXPECT_FALSE(read.get().has_value()); + EXPECT_TRUE(weak.expired()); +} + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal From f7b776578e4ee7a9d3ab801949076d4b700f2037 Mon Sep 17 00:00:00 2001 From: Ajay Yadav Date: Mon, 2 Nov 2026 16:56:02 +0000 Subject: [PATCH 2/4] refactor(storage): extract HedgeLimiter from HedgingThreadPool Extract the connection-wide rate, concurrency, and lifetime hedge limiter out of HedgingThreadPool into internal/hedge_limiter.h so AsyncConnectionImpl can share the same rate/concurrency/total limiter state machine without instantiating a thread pool. --- .../storage/google_cloud_cpp_storage.bzl | 1 + .../storage/google_cloud_cpp_storage.cmake | 1 + google/cloud/storage/internal/hedge_limiter.h | 144 ++++++++++++++++++ .../storage/internal/hedging_thread_pool.h | 113 ++------------ 4 files changed, 156 insertions(+), 103 deletions(-) create mode 100644 google/cloud/storage/internal/hedge_limiter.h diff --git a/google/cloud/storage/google_cloud_cpp_storage.bzl b/google/cloud/storage/google_cloud_cpp_storage.bzl index a30997d7b3a15..854e388db6b27 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 6801cbc9674fe..a7c8f577bd136 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 diff --git a/google/cloud/storage/internal/hedge_limiter.h b/google/cloud/storage/internal/hedge_limiter.h new file mode 100644 index 0000000000000..83ac5c49bd25d --- /dev/null +++ b/google/cloud/storage/internal/hedge_limiter.h @@ -0,0 +1,144 @@ +// 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 +#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`. + */ +class HedgeLimiter { + public: + HedgeLimiter(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) {} + + ~HedgeLimiter() = default; + + HedgeLimiter(HedgeLimiter const&) = delete; + HedgeLimiter& operator=(HedgeLimiter const&) = delete; + HedgeLimiter(HedgeLimiter&&) = delete; + HedgeLimiter& operator=(HedgeLimiter&&) = delete; + + /// Reserves capacity for one hedge; callers *must* call `ReleaseHedgeSlot()`. + bool TryAcquireHedgeToken() { + if (IsTotalBudgetSpent()) return false; + + 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)); + } + + if (rate_limit_ > 0.0) { + std::lock_guard lock(limiter_mutex_); + Refill(); + if (tokens_ < 1.0) { + ReleaseHedgeSlot(); + return false; + } + tokens_ -= 1.0; + } + + // Checked last so `total_hedges_granted_` moves only for granted hedges. + 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 permanently exhausted. + 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() { + auto 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_); + } + + double rate_limit_; + double tokens_capacity_; + double tokens_; + std::chrono::steady_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/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. From 29f8f8e3608261a4cf2cac913957d52ca306b792 Mon Sep 17 00:00:00 2001 From: Ajay Yadav Date: Mon, 2 Nov 2026 17:09:26 +0000 Subject: [PATCH 3/4] feat(storage): add speculative open hedging to AsyncClient::Open Extends storage_experimental::EnableReadHedgingOption to storage::AsyncClient::Open() (BidiReadObject) so slow initial stream-open handshakes race against up to MaxReadHedgesOption delayed speculative attempts scheduled via CompletionQueue::MakeRelativeTimer without spawning dedicated read or hedging thread pools. --- google/cloud/storage/async/client.h | 3 + .../storage/internal/async/connection_impl.cc | 359 ++++++++- .../storage/internal/async/connection_impl.h | 4 + .../async/connection_impl_open_test.cc | 730 ++++++++++++++++++ google/cloud/storage/options.h | 54 +- 5 files changed, 1119 insertions(+), 31 deletions(-) diff --git a/google/cloud/storage/async/client.h b/google/cloud/storage/async/client.h index edbfc0f25a28e..db756092ba1f8 100644 --- a/google/cloud/storage/async/client.h +++ b/google/cloud/storage/async/client.h @@ -285,6 +285,9 @@ class AsyncClient { * will resume any incomplete ranged reads if the connection(s) are * interrupted. Use `ResumePolicyOption` and `ResumePolicy` to control this. * + * @see `storage_experimental::EnableReadHedgingOption` for speculative + * stream-open hedging. + * * @param bucket_name the name of the bucket that contains the object. * @param object_name the name of the object to be read. * @param opts options controlling the behavior of this RPC, for example diff --git a/google/cloud/storage/internal/async/connection_impl.cc b/google/cloud/storage/internal/async/connection_impl.cc index 40b536c920906..e017265738524 100644 --- a/google/cloud/storage/internal/async/connection_impl.cc +++ b/google/cloud/storage/internal/async/connection_impl.cc @@ -60,12 +60,18 @@ #include "google/cloud/internal/async_retry_loop.h" #include "google/cloud/internal/async_streaming_read_rpc_timeout.h" #include "google/cloud/internal/async_streaming_write_rpc_timeout.h" +#include "google/cloud/internal/call_context.h" #include "google/cloud/internal/make_status.h" #include +#include +#include +#include #include #include +#include #include #include +#include namespace google { namespace cloud { @@ -231,6 +237,300 @@ OpenStreamFactory MakeOpenStreamFactory( }); } +// Races the primary stream-open attempt against up to `max_hedges` delayed +// speculative attempts for a single `AsyncConnectionImpl::Open()` call. +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, + std::chrono::milliseconds hedge_delay, int max_hedges, + 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(), hedge_delay)), + max_hedges_(max_hedges), + limiter_(std::move(limiter)), + metrics_(std::move(metrics)), + call_context_(std::move(options)) { + attempts_.reserve(static_cast(max_hedges_) + 1); + } + + future> Start() { + std::weak_ptr weak = shared_from_this(); + result_promise_ = promise>([weak] { + if (auto self = weak.lock()) { + google::cloud::internal::ScopedCallContext scope(self->call_context_); + self->OnCallerCancel(); + } + }); + auto result_future = result_promise_.get_future(); + + std::uint64_t attempt_id = 0; + std::uint64_t timer_gen = 0; + { + std::lock_guard lock(mu_); + active_attempts_ = 1; + attempt_id = ++next_attempt_id_; + timer_gen = ++timer_generation_; + } + + AttachAttempt(attempt_id, StartAttempt(attempt_id, /*is_primary=*/true)); + ArmTimer(timer_gen, hedge_delay_); + return result_future; + } + + private: + struct AttemptEntry { + std::uint64_t id; + future pending; + }; + + struct Outstanding { + future timer; + std::vector attempts; + }; + + static void CancelIfValid(future& f) { + if (f.valid()) f.cancel(); + } + + static void CancelOutstanding(Outstanding& outstanding) { + CancelIfValid(outstanding.timer); + for (AttemptEntry& entry : outstanding.attempts) { + CancelIfValid(entry.pending); + } + } + + static Status CancelledOpenError() { + return google::cloud::internal::CancelledError("Open operation cancelled", + GCP_ERROR_INFO()); + } + + Outstanding DrainOutstandingLocked() { + ++timer_generation_; + return Outstanding{std::move(timer_future_), std::move(attempts_)}; + } + + void Resolve(Outstanding& outstanding, StatusOr result) { + CancelOutstanding(outstanding); + result_promise_.set_value(std::move(result)); + } + + future StartAttempt(std::uint64_t attempt_id, bool is_primary) { + std::shared_ptr slot_guard; + if (!is_primary) { + slot_guard = std::shared_ptr( + limiter_.get(), [l = limiter_](void*) { l->ReleaseHedgeSlot(); }); + } + google::cloud::internal::ScopedCallContext scope(call_context_); + auto self = shared_from_this(); + return factory_(initial_request_) + .then([self = std::move(self), slot_guard = std::move(slot_guard), + attempt_id, + is_primary](future> f) mutable { + slot_guard.reset(); + self->OnAttemptDone(attempt_id, is_primary, f.get()); + }); + } + + void AttachAttempt(std::uint64_t attempt_id, future attempt) { + bool cancel_now = false; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) { + cancel_now = true; + } else { + attempts_.push_back(AttemptEntry{attempt_id, std::move(attempt)}); + } + } + if (cancel_now) CancelIfValid(attempt); + } + + void RemoveAttemptLocked(std::uint64_t attempt_id) { + auto it = std::find_if( + attempts_.begin(), attempts_.end(), + [attempt_id](AttemptEntry const& e) { return e.id == attempt_id; }); + if (it != attempts_.end()) attempts_.erase(it); + } + + void ArmTimer(std::uint64_t timer_gen, std::chrono::milliseconds delay) { + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_ || timer_gen != timer_generation_) { + return; + } + } + std::weak_ptr weak = shared_from_this(); + future timer = cq_.MakeRelativeTimer(delay).then( + [weak, + timer_gen](future> f) { + if (auto self = weak.lock()) { + self->OnTimer(timer_gen, f.get().ok()); + } + }); + bool cancel_now = false; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) { + cancel_now = true; + } else if (timer_gen == timer_generation_) { + timer_future_ = std::move(timer); + } + } + if (cancel_now) CancelIfValid(timer); + } + + void OnTimer(std::uint64_t timer_gen, bool expired) { + if (!expired) return; + google::cloud::internal::ScopedCallContext scope(call_context_); + + bool dispatch_hedge = false; + std::uint64_t attempt_id = 0; + bool arm_next_timer = false; + std::uint64_t next_timer_gen = 0; + std::chrono::milliseconds next_delay = hedge_delay_; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_ || timer_gen != timer_generation_ || + hedges_dispatched_ >= max_hedges_) { + return; + } + bool const acquired = limiter_->TryAcquireHedgeToken(); + if (acquired) { + dispatch_hedge = true; + ++active_attempts_; + ++hedges_dispatched_; + attempt_id = ++next_attempt_id_; + } + if (hedges_dispatched_ < max_hedges_ && !limiter_->IsTotalBudgetSpent()) { + arm_next_timer = true; + next_timer_gen = ++timer_generation_; + next_delay = + acquired ? hedge_delay_ + : (std::max)(hedge_delay_, std::chrono::milliseconds(10)); + } + } + + if (dispatch_hedge) { + metrics_->OnHedgeDispatched(); + AttachAttempt(attempt_id, StartAttempt(attempt_id, /*is_primary=*/false)); + } + if (arm_next_timer) ArmTimer(next_timer_gen, next_delay); + } + + void OnAttemptDone(std::uint64_t attempt_id, bool is_primary, + StatusOr result) { + google::cloud::internal::ScopedCallContext scope(call_context_); + if (result.ok()) { + OnAttemptSuccess(attempt_id, is_primary, *std::move(result)); + return; + } + OnAttemptError(attempt_id, is_primary, std::move(result).status()); + } + + void OnAttemptSuccess(std::uint64_t attempt_id, bool is_primary, + OpenStreamResult result) { + Outstanding outstanding; + bool won = false; + { + std::lock_guard lock(mu_); + if (!resolved_ && !caller_cancelled_) { + won = true; + --active_attempts_; + RemoveAttemptLocked(attempt_id); + resolved_ = true; + outstanding = DrainOutstandingLocked(); + } + } + if (!won) { + if (result.stream) result.stream->Cancel(); + OnAttemptError(attempt_id, is_primary, CancelledOpenError()); + return; + } + if (!is_primary) metrics_->OnHedgeWon(); + Resolve(outstanding, std::move(result)); + } + + bool ShouldResolveErrorLocked(bool permanent_primary_error) const { + if (caller_cancelled_) return active_attempts_ == 0; + return permanent_primary_error || active_attempts_ == 0; + } + + Status SelectFinalErrorLocked() const { + if (caller_cancelled_ && primary_error_.code() != StatusCode::kCancelled) { + return CancelledOpenError(); + } + return primary_error_; + } + + void OnAttemptError(std::uint64_t attempt_id, bool is_primary, + Status status) { + // Per-stream stall timeouts cancel the underlying RPC and surface as + // `kCancelled` on that attempt even when the caller did not cancel `Open`. + bool const permanent_primary_error = + is_primary && retry_policy_->IsPermanentFailure(status) && + status.code() != StatusCode::kCancelled; + Outstanding outstanding; + Status final_error; + bool resolve_now = false; + { + std::lock_guard lock(mu_); + --active_attempts_; + RemoveAttemptLocked(attempt_id); + if (resolved_) return; + if (is_primary) primary_error_ = std::move(status); + if (ShouldResolveErrorLocked(permanent_primary_error)) { + 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(); + } + CancelOutstanding(outstanding); + } + + 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_; + + std::mutex mu_; + bool resolved_ = false; + bool caller_cancelled_ = false; + int active_attempts_ = 0; + int hedges_dispatched_ = 0; + std::uint64_t next_attempt_id_ = 0; + std::uint64_t timer_generation_ = 0; + Status primary_error_; + future timer_future_; + std::vector attempts_; +}; + } // namespace AsyncConnectionImpl::AsyncConnectionImpl( @@ -239,7 +539,22 @@ AsyncConnectionImpl::AsyncConnectionImpl( : cq_(std::move(cq)), refresh_(std::move(refresh)), stub_(std::move(stub)), - options_(std::move(options)) {} + options_(std::move(options)) { + if (options_.get()) { + double const rate_limit = + options_.get(); + std::int64_t const max_concurrent = + options_.get(); + std::int64_t const max_total = + options_.get(); + // Allow bursts of up to one second worth of hedges. + hedge_limiter_ = std::make_shared( + rate_limit, rate_limit, max_concurrent, max_total); + hedged_read_metrics_ = + std::make_shared( + opentelemetry::metrics::Provider::GetMeterProvider()); + } +} future> AsyncConnectionImpl::GetBucket( GetBucketParams p) { @@ -327,22 +642,40 @@ AsyncConnectionImpl::Open(OpenParams p) { // Get the policy factory and immediately create a policy. auto resume_policy = current->get()(); - auto retry = - std::shared_ptr(retry_policy(*current)); - auto backoff = - std::shared_ptr(backoff_policy(*current)); - auto const* function_name = __func__; + bool const enable_hedging = + current->get(); + std::chrono::milliseconds const hedge_delay = + current->has() + ? current->get() + : std::chrono::milliseconds(500); + int const max_hedges = + current->has() + ? current->get() + : 2; + + std::shared_ptr retry = retry_policy(*current); + std::shared_ptr backoff = backoff_policy(*current); + char const* function_name = __func__; // The application is waiting on this open, so its retries are reported. So // are the descriptor's, with one exception below. - auto factory = MakeOpenStreamFactory(stub_, cq_, retry, backoff, current, - function_name, OpenLogging::kEnabled); + OpenStreamFactory factory = + MakeOpenStreamFactory(stub_, cq_, retry, backoff, current, function_name, + OpenLogging::kEnabled); // Used only when the descriptor re-opens a stream that ended cleanly: see // `MakeOpenStreamFactory()` and `ObjectDescriptorImpl`. - auto clean_resume_factory = MakeOpenStreamFactory( - stub_, cq_, std::move(retry), std::move(backoff), std::move(current), - function_name, OpenLogging::kDisabled); - - auto pending = factory(std::move(initial_request)); + OpenStreamFactory clean_resume_factory = + MakeOpenStreamFactory(stub_, cq_, retry, std::move(backoff), current, + function_name, OpenLogging::kDisabled); + + future> pending = + enable_hedging && max_hedges > 0 && hedge_limiter_ && + !hedge_limiter_->IsTotalBudgetSpent() + ? std::make_shared( + cq_, factory, std::move(initial_request), std::move(retry), + hedge_delay, max_hedges, hedge_limiter_, hedged_read_metrics_, + std::move(current)) + ->Start() + : factory(std::move(initial_request)); using ReturnType = std::shared_ptr; return pending.then([rp = std::move(resume_policy), fa = std::move(factory), qfa = std::move(clean_resume_factory), diff --git a/google/cloud/storage/internal/async/connection_impl.h b/google/cloud/storage/internal/async/connection_impl.h index 8f89c72a2f19d..5c3acb0c67d33 100644 --- a/google/cloud/storage/internal/async/connection_impl.h +++ b/google/cloud/storage/internal/async/connection_impl.h @@ -22,6 +22,8 @@ #include "google/cloud/storage/idempotency_policy.h" #include "google/cloud/storage/internal/async/reader_connection_factory.h" #include "google/cloud/storage/internal/hash_function.h" +#include "google/cloud/storage/internal/hedge_limiter.h" +#include "google/cloud/storage/internal/hedged_read_metrics.h" #include "google/cloud/storage/options.h" #include "google/cloud/storage/retry_policy.h" #include "google/cloud/async_streaming_read_write_rpc.h" @@ -148,6 +150,8 @@ class AsyncConnectionImpl std::shared_ptr refresh_; std::shared_ptr stub_; Options options_; + std::shared_ptr hedge_limiter_; + std::shared_ptr hedged_read_metrics_; google::cloud::internal::InvocationIdGenerator invocation_id_generator_; }; diff --git a/google/cloud/storage/internal/async/connection_impl_open_test.cc b/google/cloud/storage/internal/async/connection_impl_open_test.cc index dc536ec06962c..0026f6db86cdf 100644 --- a/google/cloud/storage/internal/async/connection_impl_open_test.cc +++ b/google/cloud/storage/internal/async/connection_impl_open_test.cc @@ -29,15 +29,26 @@ #include "google/cloud/testing_util/async_sequencer.h" #include "google/cloud/testing_util/is_proto_equal.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/scoped_log.h" #include "google/cloud/testing_util/status_matchers.h" #include "google/cloud/testing_util/validate_metadata.h" #include "absl/strings/match.h" #include #include +#include +#include +#include +#include +#include +#include #include +#include +#include +#include #include #include +#include #include #include @@ -908,6 +919,725 @@ TEST(AsyncConnectionImplTest, OpenWithReadRanges) { next.first.set_value(true); } +class ScopedMeterProvider { + public: + explicit ScopedMeterProvider( + opentelemetry::nostd::shared_ptr< + opentelemetry::metrics::MeterProvider> const& provider) + : previous_(opentelemetry::metrics::Provider::GetMeterProvider()) { + opentelemetry::metrics::Provider::SetMeterProvider(provider); + } + ~ScopedMeterProvider() { + opentelemetry::metrics::Provider::SetMeterProvider(previous_); + } + + private: + opentelemetry::nostd::shared_ptr + previous_; +}; + +std::unique_ptr InstallMockHedgeMetrics( + int expected_dispatched, int expected_won) { + using ::google::cloud::testing_util::MockCounter; + using ::google::cloud::testing_util::MockMeter; + using ::google::cloud::testing_util::MockMeterProvider; + using ::testing::_; + using ::testing::ByMove; + using ::testing::Eq; + using ::testing::Return; + + auto dispatched = std::make_unique>(); + auto won = std::make_unique>(); + EXPECT_CALL(*dispatched, Add(std::uint64_t{1})).Times(expected_dispatched); + EXPECT_CALL(*won, Add(std::uint64_t{1})).Times(expected_won); + + opentelemetry::nostd::shared_ptr meter = + std::make_shared(); + EXPECT_CALL(*meter, CreateUInt64Counter( + Eq("storage.read_hedging.hedges_dispatched"), _, _)) + .WillOnce(Return(ByMove(opentelemetry::nostd::unique_ptr< + opentelemetry::metrics::Counter>( + dispatched.release())))); + EXPECT_CALL(*meter, + CreateUInt64Counter(Eq("storage.read_hedging.hedge_won"), _, _)) + .WillOnce(Return(ByMove( + opentelemetry::nostd::unique_ptr< + opentelemetry::metrics::Counter>(won.release())))); + + auto provider = std::make_shared(); + EXPECT_CALL(*provider, GetMeter).WillOnce(Return(meter)); + opentelemetry::nostd::shared_ptr + global_provider{ + std::shared_ptr(provider)}; + return std::make_unique(global_provider); +} + +future> MakeSequencedTimer( + AsyncSequencer& sequencer, std::string const& name, + std::atomic& cancelled_timers) { + auto step = sequencer.PushBack(name); + auto timer_promise = std::make_shared< + promise>>( + [&cancelled_timers] { ++cancelled_timers; }); + auto timer_future = timer_promise->get_future(); + step.then([timer_promise](future f) mutable { + if (!f.get()) { + timer_promise->set_value( + internal::CancelledError("timer cancelled", GCP_ERROR_INFO())); + return; + } + timer_promise->set_value(std::chrono::system_clock::now()); + }); + return timer_future; +} + +struct ParkedReadState { + using Response = google::storage::v2::BidiReadObjectResponse; + std::mutex mu; + bool cancelled = false; + bool waiting = false; + promise> pending; + + future> Park() { + std::lock_guard lock(mu); + if (cancelled || waiting) { + return make_ready_future(std::optional()); + } + waiting = true; + return pending.get_future(); + } + + void Release() { + bool wake = false; + { + std::lock_guard lock(mu); + if (!cancelled) { + cancelled = true; + wake = waiting; + } + } + if (wake) pending.set_value(std::nullopt); + } +}; + +std::unique_ptr MakeParkedStreamWithStart( + std::function()> on_start, std::int64_t generation, + std::atomic* cancel_count = nullptr) { + using Response = google::storage::v2::BidiReadObjectResponse; + auto stream = std::make_unique>(); + auto parked = std::make_shared(); + EXPECT_CALL(*stream, Start).WillOnce(std::move(on_start)); + ON_CALL(*stream, Write) + .WillByDefault( + [](google::storage::v2::BidiReadObjectRequest const&, + grpc::WriteOptions) { return make_ready_future(true); }); + ON_CALL(*stream, Read) + .WillByDefault(InvokeWithoutArgs([generation, parked, n = 0]() mutable { + if (n++ == 0) { + Response response; + response.mutable_metadata()->set_bucket( + "projects/_/buckets/test-bucket"); + response.mutable_metadata()->set_name("test-object"); + response.mutable_metadata()->set_generation(generation); + response.mutable_read_handle()->set_handle("handle-123"); + return make_ready_future( + std::optional(std::move(response))); + } + return parked->Park(); + })); + ON_CALL(*stream, Cancel).WillByDefault([parked, cancel_count] { + if (cancel_count != nullptr) ++(*cancel_count); + parked->Release(); + }); + ON_CALL(*stream, Finish).WillByDefault(InvokeWithoutArgs([] { + return make_ready_future(Status{}); + })); + return std::unique_ptr(std::move(stream)); +} + +google::storage::v2::BidiReadObjectSpec MakeTestReadSpec() { + google::storage::v2::BidiReadObjectSpec spec; + spec.set_bucket("projects/_/buckets/test-bucket"); + spec.set_object("test-object"); + spec.set_generation(42); + return spec; +} + +class OpenHedgingTest : public ::testing::Test { + protected: + void ExpectMetrics(int dispatched, int won) { + metrics_ = InstallMockHedgeMetrics(dispatched, won); + } + + void ExpectHedgeTimers(std::vector names) { + if (names.empty()) { + EXPECT_CALL(*mock_cq_, MakeRelativeTimer).Times(0); + return; + } + auto const count = static_cast(names.size()); + EXPECT_CALL(*mock_cq_, MakeRelativeTimer) + .Times(count) + .WillRepeatedly( + [this, names = std::move(names)](std::chrono::nanoseconds d) { + auto const idx = timer_delays_.size(); + timer_delays_.push_back( + std::chrono::duration_cast(d)); + auto const name = + idx < names.size() ? names[idx] : std::string("ExtraTimer"); + return MakeSequencedTimer(sequencer_, name, cancelled_timers_); + }); + } + + promise PopStep(char const* expected) { + auto [p, name] = sequencer_.PopFrontWithName(); + EXPECT_EQ(name, expected); + return std::move(p); + } + + std::unique_ptr MakeImmediateStream( + std::int64_t generation, std::atomic* cancel_count = nullptr) { + return MakeParkedStreamWithStart([] { return make_ready_future(true); }, + generation, cancel_count); + } + + std::unique_ptr MakeSequencedStream( + std::string step, std::int64_t generation, + std::atomic* cancel_count = nullptr) { + return MakeParkedStreamWithStart( + [this, s = std::move(step)] { return sequencer_.PushBack(s); }, + generation, cancel_count); + } + + std::unique_ptr MakeStalledStream( + std::string start_step, std::string finish_step = "", + std::atomic* cancel_count = nullptr) { + auto stream = std::make_unique>(); + EXPECT_CALL(*stream, Start).WillOnce([this, s = std::move(start_step)] { + return sequencer_.PushBack(s); + }); + ON_CALL(*stream, Cancel).WillByDefault([cancel_count] { + if (cancel_count != nullptr) ++(*cancel_count); + }); + if (!finish_step.empty()) { + EXPECT_CALL(*stream, Finish).WillOnce([this, f = std::move(finish_step)] { + return sequencer_.PushBack(f).then( + [](future) { return Status{}; }); + }); + } else { + ON_CALL(*stream, Finish).WillByDefault(InvokeWithoutArgs([] { + return make_ready_future(Status{}); + })); + } + return std::unique_ptr(std::move(stream)); + } + + std::unique_ptr MakeFailingStream(std::string start_step, + Status status) { + auto stream = std::make_unique>(); + EXPECT_CALL(*stream, Start).WillOnce([this, s = std::move(start_step)] { + return sequencer_.PushBack(s).then([](future) { return false; }); + }); + EXPECT_CALL(*stream, Finish).WillOnce([st = std::move(status)] { + return make_ready_future(st); + }); + return std::unique_ptr(std::move(stream)); + } + + std::shared_ptr MakeConnection(Options opts, + bool disable_mso = true) { + if (disable_mso) { + opts = internal::MergeOptions( + std::move(opts), + Options{}.set(false)); + } + return std::make_shared( + CompletionQueue(mock_cq_), std::shared_ptr(), + mock_stub_, TestOptions(std::move(opts))); + } + + static auto Open(std::shared_ptr const& conn, + Options opts) { + return conn->Open({MakeTestReadSpec(), std::move(opts)}); + } + + static auto Open(std::shared_ptr const& conn) { + return Open(conn, conn->options()); + } + + AsyncSequencer sequencer_; + std::atomic cancelled_timers_{0}; + std::vector timer_delays_; + std::shared_ptr mock_stub_ = + std::make_shared(); + std::shared_ptr mock_cq_ = + std::make_shared(); + std::unique_ptr metrics_; +}; + +TEST_F(OpenHedgingTest, GatingAndPerCallOverrides) { + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject).Times(4).WillRepeatedly([this] { + return MakeImmediateStream(42); + }); + ExpectHedgeTimers({}); + + // 1. Disabled by default. + auto disabled_conn = MakeConnection(Options{}); + auto res1 = Open(disabled_conn).get(); + ASSERT_THAT(res1, IsOkAndHolds(NotNull())); + res1->reset(); + + // 2. Per-call `EnableReadHedgingOption(true)` without client-level opt-in is + // a no-op because `hedge_limiter_` is only allocated at client creation. + auto per_call_enable = disabled_conn->options(); + per_call_enable.set(true); + auto res2 = Open(disabled_conn, std::move(per_call_enable)).get(); + ASSERT_THAT(res2, IsOkAndHolds(NotNull())); + res2->reset(); + + // 3 & 4. Client enabled, suppressed per-call via `EnableReadHedgingOption` + // or `MaxReadHedgesOption(0)`. + auto enabled_conn = MakeConnection( + Options{}.set(true)); + auto disable_flag = enabled_conn->options(); + disable_flag.set(false); + auto res3 = Open(enabled_conn, std::move(disable_flag)).get(); + ASSERT_THAT(res3, IsOkAndHolds(NotNull())); + res3->reset(); + + auto disable_zero = enabled_conn->options(); + disable_zero.set(0); + auto res4 = Open(enabled_conn, std::move(disable_zero)).get(); + ASSERT_THAT(res4, IsOkAndHolds(NotNull())); + res4->reset(); +} + +TEST_F(OpenHedgingTest, FastPrimaryCancelsTimer) { + ExpectMetrics(0, 0); + // MSO opens one standby stream after `Open()` succeeds; verify that standby + // stream does NOT arm a second hedge timer. + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce([this] { return MakeSequencedStream("PrimaryStart", 101); }) + .WillOnce([this] { return MakeImmediateStream(101); }); + ExpectHedgeTimers({"HedgeTimer1"}); + + auto conn = MakeConnection( + Options{} + .set(true) + .set(true) + .set( + std::chrono::milliseconds(250)) + .set(2), + /*disable_mso=*/false); + + auto pending = Open(conn); + auto primary_start = PopStep("PrimaryStart"); + auto timer1 = PopStep("HedgeTimer1"); + EXPECT_THAT(timer_delays_, ElementsAre(std::chrono::milliseconds(250))); + + primary_start.set_value(true); + auto result = pending.get(); + ASSERT_THAT(result, IsOkAndHolds(NotNull())); + EXPECT_EQ((*result)->metadata()->generation(), 101); + EXPECT_EQ(cancelled_timers_.load(), 1); + + timer1.set_value(false); + result->reset(); +} + +TEST_F(OpenHedgingTest, SlowPrimaryHedgeWinsAndResumeIsUnhedged) { + ScopedLog log; + ExpectMetrics(1, 1); + std::atomic primary_cancel_count{0}; + + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce([this, &primary_cancel_count] { + return MakeStalledStream("PrimaryStart", "PrimaryFinish", + &primary_cancel_count); + }) + .WillOnce([this] { + // Opens with generation 202, then ends cleanly on `HedgeStreamEnd` to + // trigger a descriptor background resume. + using Response = google::storage::v2::BidiReadObjectResponse; + auto stream = std::make_unique>(); + EXPECT_CALL(*stream, Start).WillOnce([this] { + return sequencer_.PushBack("HedgeStart"); + }); + ON_CALL(*stream, Write) + .WillByDefault([](auto const&, grpc::WriteOptions) { + return make_ready_future(true); + }); + ON_CALL(*stream, Read) + .WillByDefault(InvokeWithoutArgs([this, n = 0]() mutable { + if (n++ == 0) { + Response response; + response.mutable_metadata()->set_bucket( + "projects/_/buckets/test-bucket"); + response.mutable_metadata()->set_name("test-object"); + response.mutable_metadata()->set_generation(202); + response.mutable_read_handle()->set_handle("hedge-handle"); + return make_ready_future( + std::optional(std::move(response))); + } + return sequencer_.PushBack("HedgeStreamEnd") + .then([](future) { return std::optional(); }); + })); + ON_CALL(*stream, Finish).WillByDefault(InvokeWithoutArgs([] { + return make_ready_future(Status{}); + })); + return std::unique_ptr(std::move(stream)); + }) + .WillOnce([this] { return MakeSequencedStream("ResumeStart", 202); }); + // Only 2 timers for `max_hedges = 2`; background resume must not arm any. + ExpectHedgeTimers({"HedgeTimer1", "HedgeTimer2"}); + + auto conn = MakeConnection( + Options{} + .set( + storage::LimitedErrorCountResumePolicy(1)) + .set(true) + .set( + std::chrono::milliseconds(100)) + .set(2)); + + auto pending = Open(conn); + auto primary_start = PopStep("PrimaryStart"); + auto timer1 = PopStep("HedgeTimer1"); + + timer1.set_value(true); + auto hedge_start = PopStep("HedgeStart"); + auto timer2 = PopStep("HedgeTimer2"); + + hedge_start.set_value(true); + auto hedge_stream_end = PopStep("HedgeStreamEnd"); + + auto result = pending.get(); + ASSERT_THAT(result, IsOkAndHolds(NotNull())); + EXPECT_EQ((*result)->metadata()->generation(), 202); + EXPECT_EQ(primary_cancel_count.load(), 1); + EXPECT_EQ(cancelled_timers_.load(), 1); + timer2.set_value(false); + + // Cancelled losing primary winds down silently without `[gcs-retry]` logs. + primary_start.set_value(true); + PopStep("PrimaryFinish").set_value(true); + + hedge_stream_end.set_value(true); + PopStep("ResumeStart").set_value(true); + + result->reset(); + EXPECT_THAT(RetryRecords(log), IsEmpty()); +} + +TEST_F(OpenHedgingTest, PrimaryWinsAfterHedgeDispatched) { + ExpectMetrics(1, 0); + std::atomic hedge_cancel_count{0}; + + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce([this] { return MakeSequencedStream("PrimaryStart", 1); }) + .WillOnce([this, &hedge_cancel_count] { + return MakeStalledStream("HedgeStart", "HedgeFinish", + &hedge_cancel_count); + }); + ExpectHedgeTimers({"HedgeTimer1"}); + + auto conn = MakeConnection( + Options{} + .set(true) + .set(1)); + + auto pending = Open(conn); + auto primary_start = PopStep("PrimaryStart"); + PopStep("HedgeTimer1").set_value(true); + auto hedge_start = PopStep("HedgeStart"); + + primary_start.set_value(true); + auto result = pending.get(); + ASSERT_THAT(result, IsOkAndHolds(NotNull())); + EXPECT_EQ((*result)->metadata()->generation(), 1); + EXPECT_EQ(hedge_cancel_count.load(), 1); + + hedge_start.set_value(true); + PopStep("HedgeFinish").set_value(true); + result->reset(); +} + +class OpenHedgingRescueTest : public OpenHedgingTest, + public ::testing::WithParamInterface {}; + +TEST_P(OpenHedgingRescueTest, PrimaryTransientOrStallErrorRescuedByHedge) { + ExpectMetrics(1, 1); + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce( + [this] { return MakeFailingStream("PrimaryStart", GetParam()); }) + .WillOnce([this] { return MakeSequencedStream("HedgeStart", 303); }); + ExpectHedgeTimers({"HedgeTimer1"}); + + auto conn = MakeConnection( + Options{} + .set( + storage::LimitedErrorCountAsyncRetryPolicy(0).clone()) + .set(true) + .set(1)); + + auto pending = Open(conn); + auto primary_start = PopStep("PrimaryStart"); + PopStep("HedgeTimer1").set_value(true); + auto hedge_start = PopStep("HedgeStart"); + + primary_start.set_value(false); + hedge_start.set_value(true); + + auto result = pending.get(); + ASSERT_THAT(result, IsOkAndHolds(NotNull())); + EXPECT_EQ((*result)->metadata()->generation(), 303); + result->reset(); +} + +INSTANTIATE_TEST_SUITE_P(PrimaryErrors, OpenHedgingRescueTest, + ::testing::Values(RedirectError("h1", "tok1"), + Status(StatusCode::kCancelled, + "Stream stall timeout"))); + +TEST_F(OpenHedgingTest, PrimaryPermanentFailureAbortsInFlightHedge) { + ExpectMetrics(1, 0); + std::atomic hedge_cancel_count{0}; + + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce([this] { + return MakeFailingStream("PrimaryStart", PermanentError()); + }) + .WillOnce([this, &hedge_cancel_count] { + return MakeStalledStream("HedgeStart", "HedgeFinish", + &hedge_cancel_count); + }); + ExpectHedgeTimers({"HedgeTimer1", "HedgeTimer2"}); + + auto conn = MakeConnection( + Options{} + .set(true) + .set(2)); + + auto pending = Open(conn); + auto primary_start = PopStep("PrimaryStart"); + PopStep("HedgeTimer1").set_value(true); + auto hedge_start = PopStep("HedgeStart"); + auto timer2 = PopStep("HedgeTimer2"); + + primary_start.set_value(false); + EXPECT_THAT(pending.get(), StatusIs(PermanentError().code())); + EXPECT_EQ(hedge_cancel_count.load(), 1); + EXPECT_EQ(cancelled_timers_.load(), 1); + + timer2.set_value(false); + hedge_start.set_value(true); + PopStep("HedgeFinish").set_value(true); +} + +TEST_F(OpenHedgingTest, AllAttemptsFailReturnsPrimaryError) { + ExpectMetrics(1, 0); + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce([this] { + return MakeFailingStream( + "PrimaryStart", + Status(StatusCode::kUnavailable, "primary unavailable")); + }) + .WillOnce([this] { + return MakeFailingStream( + "HedgeStart", + Status(StatusCode::kDeadlineExceeded, "hedge deadline")); + }); + ExpectHedgeTimers({"HedgeTimer1"}); + + auto conn = MakeConnection( + Options{} + .set( + storage::LimitedErrorCountAsyncRetryPolicy(0).clone()) + .set(true) + .set(1)); + + auto pending = Open(conn); + auto primary_start = PopStep("PrimaryStart"); + PopStep("HedgeTimer1").set_value(true); + auto hedge_start = PopStep("HedgeStart"); + + primary_start.set_value(false); + hedge_start.set_value(false); + EXPECT_THAT(pending.get(), + StatusIs(StatusCode::kUnavailable, HasSubstr("primary"))); +} + +TEST_F(OpenHedgingTest, CallerCancelCancelsAllAttemptsAndTimer) { + std::atomic cancelled_streams{0}; + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce([this, &cancelled_streams] { + return MakeStalledStream("PrimaryStart", "PrimaryFinish", + &cancelled_streams); + }) + .WillOnce([this, &cancelled_streams] { + return MakeStalledStream("HedgeStart", "HedgeFinish", + &cancelled_streams); + }); + ExpectHedgeTimers({"HedgeTimer1", "HedgeTimer2"}); + + auto conn = MakeConnection( + Options{} + .set(true) + .set(2)); + + auto pending = Open(conn); + auto primary_start = PopStep("PrimaryStart"); + PopStep("HedgeTimer1").set_value(true); + auto hedge_start = PopStep("HedgeStart"); + auto timer2 = PopStep("HedgeTimer2"); + + pending.cancel(); + EXPECT_EQ(cancelled_timers_.load(), 1); + EXPECT_EQ(cancelled_streams.load(), 2); + + timer2.set_value(false); + primary_start.set_value(true); + hedge_start.set_value(true); + sequencer_.PopFrontWithName().first.set_value(true); + sequencer_.PopFrontWithName().first.set_value(true); + + EXPECT_THAT(pending.get(), StatusIs(StatusCode::kCancelled)); +} + +TEST_F(OpenHedgingTest, RespectsConcurrencyAndLifetimeLimits) { + using ms = std::chrono::milliseconds; + ExpectMetrics(2, 2); + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce([this] { return MakeStalledStream("Call1Primary"); }) + .WillOnce([this] { return MakeStalledStream("Call2Primary"); }) + .WillOnce([this] { return MakeSequencedStream("Call1Hedge", 601); }) + .WillOnce([this] { return MakeImmediateStream(602); }) + .WillOnce([this] { return MakeImmediateStream(603); }); + // Call 1 arms Timer 1 and (once Hedge 1 starts) Timer 2; Call 2 arms Timer 1, + // hits `MaxConcurrentHedgesOption(1)` -> re-arms at >= 10ms, then spends the + // 2nd & final lifetime token so neither Call 2 nor Call 3 arms more timers. + ExpectHedgeTimers( + {"Call1Timer1", "Call2Timer1", "Call1Timer2", "Call2RetryTimer"}); + + auto conn = MakeConnection( + Options{} + .set(true) + .set(ms(1)) + .set(2) + .set(1) + .set(2)); + + auto call1 = Open(conn); + auto call2 = Open(conn); + auto c1_primary = PopStep("Call1Primary"); + auto c1_timer1 = PopStep("Call1Timer1"); + auto c2_primary = PopStep("Call2Primary"); + auto c2_timer1 = PopStep("Call2Timer1"); + + // Call 1 acquires the single concurrency slot (total 1/2) and arms Timer 2. + c1_timer1.set_value(true); + auto c1_hedge = PopStep("Call1Hedge"); + auto c1_timer2 = PopStep("Call1Timer2"); + + // Call 2 is denied by `MaxConcurrentHedgesOption(1)` and re-arms at 10ms. + c2_timer1.set_value(true); + auto c2_retry = PopStep("Call2RetryTimer"); + EXPECT_THAT(timer_delays_, ElementsAre(ms(1), ms(1), ms(1), ms(10))); + + // Finishing Call 1's hedge releases the concurrency slot before + // `call1.get()`. + c1_hedge.set_value(true); + auto res1 = call1.get(); + ASSERT_THAT(res1, IsOkAndHolds(NotNull())); + EXPECT_EQ((*res1)->metadata()->generation(), 601); + c1_timer2.set_value(false); + + // 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 subsequent Call 3. + c2_retry.set_value(true); + auto res2 = call2.get(); + ASSERT_THAT(res2, IsOkAndHolds(NotNull())); + EXPECT_EQ((*res2)->metadata()->generation(), 602); + + auto res3 = Open(conn).get(); + ASSERT_THAT(res3, IsOkAndHolds(NotNull())); + EXPECT_EQ((*res3)->metadata()->generation(), 603); + + c1_primary.set_value(true); + c2_primary.set_value(true); + res1->reset(); + res2->reset(); + res3->reset(); +} + +TEST(AsyncConnectionImplTest, OpenHedgingConcurrentCompletionRace) { + 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::vector workers; + workers.reserve(2); + + auto make_racing_stream = [&](std::int64_t generation) { + auto start_promise = std::make_shared>(); + auto start_future = + std::make_shared>(start_promise->get_future()); + workers.emplace_back([&, start_promise]() mutable { + { + std::unique_lock lock(gate_mu); + ++ready_workers; + gate_cv.notify_all(); + gate_cv.wait(lock, [&] { return release_workers; }); + } + start_promise->set_value(true); + }); + return MakeParkedStreamWithStart( + [start_future]() mutable { return std::move(*start_future); }, + generation, &cancelled_streams); + }; + + auto mock_stub = std::make_shared(); + EXPECT_CALL(*mock_stub, AsyncBidiReadObject) + .WillOnce([&] { return make_racing_stream(1); }) + .WillOnce([&] { return make_racing_stream(2); }); + + 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())); + }); + + auto conn = std::make_shared( + CompletionQueue(mock_cq), std::shared_ptr(), + mock_stub, + TestOptions( + Options{} + .set(false) + .set(true) + .set(1))); + + auto pending = conn->Open({MakeTestReadSpec(), conn->options()}); + { + std::unique_lock lock(gate_mu); + gate_cv.wait(lock, [&] { return ready_workers == 2; }); + release_workers = true; + } + gate_cv.notify_all(); + for (auto& w : workers) w.join(); + + auto result = pending.get(); + ASSERT_THAT(result, IsOkAndHolds(NotNull())); + EXPECT_THAT((*result)->metadata()->generation(), + ::testing::AnyOf(::testing::Eq(1), ::testing::Eq(2))); + EXPECT_EQ(cancelled_streams.load(), 1); + result->reset(); + EXPECT_EQ(cancelled_streams.load(), 2); + } +} + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal diff --git a/google/cloud/storage/options.h b/google/cloud/storage/options.h index ff179dc79eccc..af5557bc0027e 100644 --- a/google/cloud/storage/options.h +++ b/google/cloud/storage/options.h @@ -35,21 +35,31 @@ namespace storage_experimental { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN /** - * Enable experimental request hedging for `ReadObject()` streams. - * - * When enabled, opening a download races the initial request against one or - * more delayed, duplicate ("hedged") requests, and the first to respond wins. - * A read that stalls mid-stream, that is, one that takes longer than - * `ReadHedgeDelayOption`, is raced the same way against duplicate requests - * resuming from the stream's current offset. This reduces tail latency at the - * cost of additional requests. + * Enable experimental request hedging for object downloads. + * + * For `storage::Client::ReadObject()`, opening a download races the initial + * request against one or more delayed, duplicate ("hedged") requests, and the + * first to respond wins. A read that stalls mid-stream, that is, one that takes + * longer than `ReadHedgeDelayOption`, is raced the same way against duplicate + * requests resuming from the stream's current offset. + * + * For `storage::AsyncClient::Open()`, enabling this option at client creation + * time races the initial `BidiReadObject` stream-open handshake against up to + * `MaxReadHedgesOption` delayed attempts spaced by `ReadHedgeDelayOption` + * (bounded by `ReadHedgeRateLimitOption`, `MaxConcurrentHedgesOption`, and + * `MaxTotalHedgesOption`). Individual calls may opt out via + * `EnableReadHedgingOption(false)` or `MaxReadHedgesOption(0)`, or override + * `ReadHedgeDelayOption` and `MaxReadHedgesOption`; subsequent ranged reads and + * stream resumes are not hedged. This reduces tail latency at the cost of + * additional requests. * * The client records two OpenTelemetry counters through the global meter * provider in effect when the client is created: * `storage.read_hedging.hedges_dispatched`, the number of hedged requests - * issued, and `storage.read_hedging.hedge_won`, the number of reads completed - * by a hedged request instead of the original one. Nothing is recorded unless - * the application installs a meter provider before creating the client. + * issued, and `storage.read_hedging.hedge_won`, the number of reads or stream + * opens completed by a hedged request instead of the original one. Nothing is + * recorded unless the application installs a meter provider before creating the + * client. * * @ingroup storage-options */ @@ -84,9 +94,10 @@ struct MaxConcurrentHedgesOption { * The maximum total number of hedged requests over the life of the connection. * * Once this many hedges have been sent, the connection stops hedging and serves - * every later read with the primary request only. This bounds the extra load - * hedging can add when a VM or the service is degraded, where most reads are - * slow and hedging them only adds requests without making them faster. + * every later read or stream open with the primary request only. This bounds + * the extra load hedging can add when a VM or the service is degraded, where + * most requests are slow and hedging them only adds load without making them + * faster. * * The default is 0, meaning no limit. * @@ -110,6 +121,8 @@ struct MaxTotalHedgesOption { * stalled read that is raced later, so a stream can hold up to * `MaxReadHedgesOption` + 1 buffers of this size at once. * + * @note Ignored by `storage::AsyncClient::Open()`. + * * The default is 64 MiB (64 * 1024 * 1024). * * @ingroup storage-options @@ -121,8 +134,9 @@ struct MaximumHedgeBufferOption { /** * The delay before starting a hedged request. * - * This is also the mid-stream stall threshold: a read that takes longer than - * this marks the stream as stalled, and the next read is raced. + * For `storage::Client::ReadObject()`, this is also the mid-stream stall + * threshold: a read that takes longer than this marks the stream as stalled, + * and the next read is raced. * * The default is 500 milliseconds. * @@ -133,14 +147,14 @@ struct ReadHedgeDelayOption { }; /** - * The maximum number of hedged requests per raced read. + * The maximum number of hedged requests per raced read or stream open. * * A read is raced when the stream is opened, and again whenever a read stalls * mid-stream, so this bounds a single race rather than the whole stream. The * total number of hedges a stream may issue is bounded at a small multiple of * this value, so a uniformly slow stream cannot keep racing indefinitely. * - * The default is 2. Set to 0 to disable hedging for reads even when + * The default is 2. Set to 0 to disable hedging even when * `EnableReadHedgingOption` is set. * * @ingroup storage-options @@ -156,6 +170,8 @@ struct MaxReadHedgesOption { * Set to 0 for automatic sizing (defaults to at least 64 threads or 4x hardware * concurrency). * + * @note Ignored by `storage::AsyncClient::Open()`. + * * @ingroup storage-options */ struct ReadThreadPoolSizeOption { @@ -169,6 +185,8 @@ struct ReadThreadPoolSizeOption { * Set to 0 for automatic sizing (defaults to `MaxConcurrentHedgesOption` if * set, or at least 16 threads or 2x hardware concurrency). * + * @note Ignored by `storage::AsyncClient::Open()`. + * * @ingroup storage-options */ struct HedgingThreadPoolSizeOption { From c2f8dbb896c3f9c50a4f13f8ce3089b25b8ac0fd Mon Sep 17 00:00:00 2001 From: Ajay Yadav Date: Mon, 2 Nov 2026 18:11:18 +0000 Subject: [PATCH 4/4] fix(storage): abort on any permanent open error and set kReadHedging feature bit --- .../storage/internal/async/connection_impl.cc | 151 ++++--- .../storage/internal/async/connection_impl.h | 11 +- .../async/connection_impl_open_test.cc | 393 ++++++++++++------ google/cloud/storage/internal/hedge_limiter.h | 7 +- google/cloud/storage/options.h | 7 +- 5 files changed, 376 insertions(+), 193 deletions(-) diff --git a/google/cloud/storage/internal/async/connection_impl.cc b/google/cloud/storage/internal/async/connection_impl.cc index e017265738524..3236ba0d383d2 100644 --- a/google/cloud/storage/internal/async/connection_impl.cc +++ b/google/cloud/storage/internal/async/connection_impl.cc @@ -51,6 +51,8 @@ #include "google/cloud/storage/internal/hash_function_impl.h" #include "google/cloud/storage/internal/hash_validator.h" #include "google/cloud/storage/internal/hash_validator_impl.h" +#include "google/cloud/storage/internal/hedge_limiter.h" +#include "google/cloud/storage/internal/hedged_read_metrics.h" #include "google/cloud/storage/internal/retry_logging.h" #include "google/cloud/storage/internal/storage_stub.h" #include "google/cloud/storage/internal/storage_stub_factory.h" @@ -66,6 +68,7 @@ #include #include #include +#include #include #include #include @@ -156,6 +159,11 @@ std::unique_ptr CreateHashValidator( /// Whether the retry loop opening a bidi read stream reports its retries. enum class OpenLogging { kEnabled, kDisabled }; +/// Whether the stream-open attempt is part of a hedged `Open()` race. +enum class OpenHedging { kDisabled, kEnabled }; + +std::chrono::milliseconds constexpr kHedgeRetryMinDelay{10}; + /** * Creates the factory that opens a bidi read stream. * @@ -181,12 +189,12 @@ OpenStreamFactory MakeOpenStreamFactory( std::shared_ptr retry, std::shared_ptr backoff, google::cloud::internal::ImmutableOptions current, - char const* function_name, OpenLogging logging) { + char const* function_name, OpenLogging logging, OpenHedging hedging) { return OpenStreamFactory( [stub = std::move(stub), cq = std::move(cq), retry = std::move(retry), backoff = std::move(backoff), current = std::move(current), - function_name, - logging](google::storage::v2::BidiReadObjectRequest request) { + function_name, logging, + hedging](google::storage::v2::BidiReadObjectRequest request) { struct DummyRequest {}; std::string resource = @@ -194,7 +202,7 @@ OpenStreamFactory MakeOpenStreamFactory( ? RetryLogResource(request.read_object_spec().bucket(), request.read_object_spec().object()) : std::string{}; - auto call = [stub, request = std::move(request)]( + auto call = [stub, request = std::move(request), hedging]( CompletionQueue& cq, std::shared_ptr context, google::cloud::internal::ImmutableOptions options, @@ -202,11 +210,16 @@ OpenStreamFactory MakeOpenStreamFactory( // Every stream the descriptor opens (the first one, resumes, and // the extra streams of the multi-stream optimization) goes through // this factory, so this is where the service learns which client - // features are in play for the read. + // features are in play for the read. `kReadHedging` is set only on + // the initial hedged `Open()` attempts, not on unhedged descriptor + // secondary or resume streams. std::uint32_t features = 0; if (options->get()) { features |= FeatureBit(TrackedFeature::kMultistreamInMrd); } + if (hedging == OpenHedging::kEnabled) { + features |= FeatureBit(TrackedFeature::kReadHedging); + } AddFeaturesHeader(*context, features); auto open = std::make_shared( *stub, cq, std::move(context), std::move(options), request); @@ -256,7 +269,7 @@ class HedgedOpenOperation retry_policy_(std::move(retry_policy)), hedge_delay_( (std::max)(std::chrono::milliseconds::zero(), hedge_delay)), - max_hedges_(max_hedges), + max_hedges_((std::max)(0, max_hedges)), limiter_(std::move(limiter)), metrics_(std::move(metrics)), call_context_(std::move(options)) { @@ -266,12 +279,13 @@ class HedgedOpenOperation future> Start() { std::weak_ptr weak = shared_from_this(); result_promise_ = promise>([weak] { - if (auto self = weak.lock()) { + if (std::shared_ptr self = weak.lock()) { google::cloud::internal::ScopedCallContext scope(self->call_context_); self->OnCallerCancel(); } }); - auto result_future = result_promise_.get_future(); + future> result_future = + result_promise_.get_future(); std::uint64_t attempt_id = 0; std::uint64_t timer_gen = 0; @@ -288,6 +302,35 @@ class HedgedOpenOperation } private: + class HedgeSlot { + public: + HedgeSlot() = default; + explicit HedgeSlot(std::shared_ptr limiter) + : limiter_(std::move(limiter)) {} + ~HedgeSlot() { Release(); } + + HedgeSlot(HedgeSlot&&) noexcept = default; + HedgeSlot& operator=(HedgeSlot&& other) noexcept { + if (this != &other) { + Release(); + limiter_ = std::move(other.limiter_); + } + return *this; + } + HedgeSlot(HedgeSlot const&) = delete; + HedgeSlot& operator=(HedgeSlot const&) = delete; + + void Release() { + if (limiter_) { + limiter_->ReleaseHedgeSlot(); + limiter_.reset(); + } + } + + private: + std::shared_ptr limiter_; + }; + struct AttemptEntry { std::uint64_t id; future pending; @@ -325,18 +368,13 @@ class HedgedOpenOperation } future StartAttempt(std::uint64_t attempt_id, bool is_primary) { - std::shared_ptr slot_guard; - if (!is_primary) { - slot_guard = std::shared_ptr( - limiter_.get(), [l = limiter_](void*) { l->ReleaseHedgeSlot(); }); - } + HedgeSlot slot = is_primary ? HedgeSlot{} : HedgeSlot{limiter_}; google::cloud::internal::ScopedCallContext scope(call_context_); - auto self = shared_from_this(); + std::shared_ptr self = shared_from_this(); return factory_(initial_request_) - .then([self = std::move(self), slot_guard = std::move(slot_guard), - attempt_id, + .then([self = std::move(self), slot = std::move(slot), attempt_id, is_primary](future> f) mutable { - slot_guard.reset(); + slot.Release(); self->OnAttemptDone(attempt_id, is_primary, f.get()); }); } @@ -355,10 +393,11 @@ class HedgedOpenOperation } void RemoveAttemptLocked(std::uint64_t attempt_id) { - auto it = std::find_if( - attempts_.begin(), attempts_.end(), - [attempt_id](AttemptEntry const& e) { return e.id == attempt_id; }); - if (it != attempts_.end()) attempts_.erase(it); + attempts_.erase(std::remove_if(attempts_.begin(), attempts_.end(), + [attempt_id](AttemptEntry const& e) { + return e.id == attempt_id; + }), + attempts_.end()); } void ArmTimer(std::uint64_t timer_gen, std::chrono::milliseconds delay) { @@ -372,7 +411,7 @@ class HedgedOpenOperation future timer = cq_.MakeRelativeTimer(delay).then( [weak, timer_gen](future> f) { - if (auto self = weak.lock()) { + if (std::shared_ptr self = weak.lock()) { self->OnTimer(timer_gen, f.get().ok()); } }); @@ -413,9 +452,8 @@ class HedgedOpenOperation if (hedges_dispatched_ < max_hedges_ && !limiter_->IsTotalBudgetSpent()) { arm_next_timer = true; next_timer_gen = ++timer_generation_; - next_delay = - acquired ? hedge_delay_ - : (std::max)(hedge_delay_, std::chrono::milliseconds(10)); + next_delay = acquired ? hedge_delay_ + : (std::max)(hedge_delay_, kHedgeRetryMinDelay); } } @@ -459,25 +497,35 @@ class HedgedOpenOperation Resolve(outstanding, std::move(result)); } - bool ShouldResolveErrorLocked(bool permanent_primary_error) const { + // 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. + bool ShouldResolveErrorLocked() const { if (caller_cancelled_) return active_attempts_ == 0; - return permanent_primary_error || active_attempts_ == 0; + return !permanent_error_.ok() || active_attempts_ == 0; } Status SelectFinalErrorLocked() const { - if (caller_cancelled_ && primary_error_.code() != StatusCode::kCancelled) { - return CancelledOpenError(); + // `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::uint64_t attempt_id, bool is_primary, Status status) { - // Per-stream stall timeouts cancel the underlying RPC and surface as - // `kCancelled` on that attempt even when the caller did not cancel `Open`. - bool const permanent_primary_error = - is_primary && retry_policy_->IsPermanentFailure(status) && - status.code() != StatusCode::kCancelled; + // 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 = retry_policy_->IsPermanentFailure(status) && + status.code() != StatusCode::kCancelled; Outstanding outstanding; Status final_error; bool resolve_now = false; @@ -486,8 +534,9 @@ class HedgedOpenOperation --active_attempts_; RemoveAttemptLocked(attempt_id); if (resolved_) return; + if (permanent_error && permanent_error_.ok()) permanent_error_ = status; if (is_primary) primary_error_ = std::move(status); - if (ShouldResolveErrorLocked(permanent_primary_error)) { + if (ShouldResolveErrorLocked()) { resolve_now = true; resolved_ = true; final_error = SelectFinalErrorLocked(); @@ -517,7 +566,7 @@ class HedgedOpenOperation std::shared_ptr limiter_; std::shared_ptr metrics_; google::cloud::internal::CallContext call_context_; - promise> result_promise_; + promise> result_promise_{null_promise_t{}}; std::mutex mu_; bool resolved_ = false; @@ -526,6 +575,7 @@ class HedgedOpenOperation int hedges_dispatched_ = 0; std::uint64_t next_attempt_id_ = 0; std::uint64_t timer_generation_ = 0; + Status permanent_error_; Status primary_error_; future timer_future_; std::vector attempts_; @@ -653,6 +703,10 @@ AsyncConnectionImpl::Open(OpenParams p) { ? current->get() : 2; + bool const hedging_active = enable_hedging && max_hedges > 0 && + hedge_limiter_ && + !hedge_limiter_->IsTotalBudgetSpent(); + std::shared_ptr retry = retry_policy(*current); std::shared_ptr backoff = backoff_policy(*current); char const* function_name = __func__; @@ -660,22 +714,25 @@ AsyncConnectionImpl::Open(OpenParams p) { // are the descriptor's, with one exception below. OpenStreamFactory factory = MakeOpenStreamFactory(stub_, cq_, retry, backoff, current, function_name, - OpenLogging::kEnabled); + OpenLogging::kEnabled, OpenHedging::kDisabled); // Used only when the descriptor re-opens a stream that ended cleanly: see // `MakeOpenStreamFactory()` and `ObjectDescriptorImpl`. OpenStreamFactory clean_resume_factory = - MakeOpenStreamFactory(stub_, cq_, retry, std::move(backoff), current, - function_name, OpenLogging::kDisabled); + MakeOpenStreamFactory(stub_, cq_, retry, backoff, current, function_name, + OpenLogging::kDisabled, OpenHedging::kDisabled); future> pending = - enable_hedging && max_hedges > 0 && hedge_limiter_ && - !hedge_limiter_->IsTotalBudgetSpent() - ? std::make_shared( - cq_, factory, std::move(initial_request), std::move(retry), - hedge_delay, max_hedges, hedge_limiter_, hedged_read_metrics_, - std::move(current)) - ->Start() - : factory(std::move(initial_request)); + hedging_active ? std::make_shared( + cq_, + MakeOpenStreamFactory( + stub_, cq_, retry, std::move(backoff), current, + function_name, OpenLogging::kEnabled, + OpenHedging::kEnabled), + std::move(initial_request), std::move(retry), + hedge_delay, max_hedges, hedge_limiter_, + hedged_read_metrics_, std::move(current)) + ->Start() + : factory(std::move(initial_request)); using ReturnType = std::shared_ptr; return pending.then([rp = std::move(resume_policy), fa = std::move(factory), qfa = std::move(clean_resume_factory), diff --git a/google/cloud/storage/internal/async/connection_impl.h b/google/cloud/storage/internal/async/connection_impl.h index 5c3acb0c67d33..e0af0635b9ebb 100644 --- a/google/cloud/storage/internal/async/connection_impl.h +++ b/google/cloud/storage/internal/async/connection_impl.h @@ -22,8 +22,6 @@ #include "google/cloud/storage/idempotency_policy.h" #include "google/cloud/storage/internal/async/reader_connection_factory.h" #include "google/cloud/storage/internal/hash_function.h" -#include "google/cloud/storage/internal/hedge_limiter.h" -#include "google/cloud/storage/internal/hedged_read_metrics.h" #include "google/cloud/storage/options.h" #include "google/cloud/storage/retry_policy.h" #include "google/cloud/async_streaming_read_write_rpc.h" @@ -41,6 +39,15 @@ namespace google { namespace cloud { +namespace storage { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace internal { +class HedgeLimiter; +class HedgedReadMetrics; +} // namespace internal +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage + namespace storage_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN class GrpcChannelRefresh; diff --git a/google/cloud/storage/internal/async/connection_impl_open_test.cc b/google/cloud/storage/internal/async/connection_impl_open_test.cc index 0026f6db86cdf..af34cd5c4d344 100644 --- a/google/cloud/storage/internal/async/connection_impl_open_test.cc +++ b/google/cloud/storage/internal/async/connection_impl_open_test.cc @@ -40,6 +40,7 @@ #include #include #include +#include #include #include #include @@ -975,11 +976,12 @@ std::unique_ptr InstallMockHedgeMetrics( future> MakeSequencedTimer( AsyncSequencer& sequencer, std::string const& name, std::atomic& cancelled_timers) { - auto step = sequencer.PushBack(name); + future step = sequencer.PushBack(name); auto timer_promise = std::make_shared< promise>>( [&cancelled_timers] { ++cancelled_timers; }); - auto timer_future = timer_promise->get_future(); + future> timer_future = + timer_promise->get_future(); step.then([timer_promise](future f) mutable { if (!f.get()) { timer_promise->set_value( @@ -1022,7 +1024,7 @@ struct ParkedReadState { std::unique_ptr MakeParkedStreamWithStart( std::function()> on_start, std::int64_t generation, - std::atomic* cancel_count = nullptr) { + std::atomic* cancel_count) { using Response = google::storage::v2::BidiReadObjectResponse; auto stream = std::make_unique>(); auto parked = std::make_shared(); @@ -1031,30 +1033,32 @@ std::unique_ptr MakeParkedStreamWithStart( .WillByDefault( [](google::storage::v2::BidiReadObjectRequest const&, grpc::WriteOptions) { return make_ready_future(true); }); - ON_CALL(*stream, Read) - .WillByDefault(InvokeWithoutArgs([generation, parked, n = 0]() mutable { - if (n++ == 0) { - Response response; - response.mutable_metadata()->set_bucket( - "projects/_/buckets/test-bucket"); - response.mutable_metadata()->set_name("test-object"); - response.mutable_metadata()->set_generation(generation); - response.mutable_read_handle()->set_handle("handle-123"); - return make_ready_future( - std::optional(std::move(response))); - } - return parked->Park(); - })); + ON_CALL(*stream, Read).WillByDefault([generation, parked, n = 0]() mutable { + if (n++ == 0) { + Response response; + response.mutable_metadata()->set_bucket("projects/_/buckets/test-bucket"); + response.mutable_metadata()->set_name("test-object"); + response.mutable_metadata()->set_generation(generation); + response.mutable_read_handle()->set_handle("handle-123"); + return make_ready_future(std::optional(std::move(response))); + } + return parked->Park(); + }); ON_CALL(*stream, Cancel).WillByDefault([parked, cancel_count] { if (cancel_count != nullptr) ++(*cancel_count); parked->Release(); }); - ON_CALL(*stream, Finish).WillByDefault(InvokeWithoutArgs([] { + ON_CALL(*stream, Finish).WillByDefault([] { return make_ready_future(Status{}); - })); + }); return std::unique_ptr(std::move(stream)); } +std::unique_ptr MakeImmediateStream(std::int64_t generation) { + return MakeParkedStreamWithStart([] { return make_ready_future(true); }, + generation, nullptr); +} + google::storage::v2::BidiReadObjectSpec MakeTestReadSpec() { google::storage::v2::BidiReadObjectSpec spec; spec.set_bucket("projects/_/buckets/test-bucket"); @@ -1065,6 +1069,10 @@ google::storage::v2::BidiReadObjectSpec MakeTestReadSpec() { class OpenHedgingTest : public ::testing::Test { protected: + using OpenResult = + StatusOr>; + using OpenFuture = future; + void ExpectMetrics(int dispatched, int won) { metrics_ = InstallMockHedgeMetrics(dispatched, won); } @@ -1074,15 +1082,15 @@ class OpenHedgingTest : public ::testing::Test { EXPECT_CALL(*mock_cq_, MakeRelativeTimer).Times(0); return; } - auto const count = static_cast(names.size()); + std::size_t const count = names.size(); EXPECT_CALL(*mock_cq_, MakeRelativeTimer) - .Times(count) + .Times(static_cast(count)) .WillRepeatedly( [this, names = std::move(names)](std::chrono::nanoseconds d) { - auto const idx = timer_delays_.size(); + std::size_t const idx = timer_delays_.size(); timer_delays_.push_back( std::chrono::duration_cast(d)); - auto const name = + std::string const name = idx < names.size() ? names[idx] : std::string("ExtraTimer"); return MakeSequencedTimer(sequencer_, name, cancelled_timers_); }); @@ -1094,23 +1102,20 @@ class OpenHedgingTest : public ::testing::Test { return std::move(p); } - std::unique_ptr MakeImmediateStream( - std::int64_t generation, std::atomic* cancel_count = nullptr) { - return MakeParkedStreamWithStart([] { return make_ready_future(true); }, - generation, cancel_count); - } - - std::unique_ptr MakeSequencedStream( - std::string step, std::int64_t generation, - std::atomic* cancel_count = nullptr) { + std::unique_ptr MakeSequencedStream(std::string step, + std::int64_t generation) { return MakeParkedStreamWithStart( [this, s = std::move(step)] { return sequencer_.PushBack(s); }, - generation, cancel_count); + generation, nullptr); + } + + std::unique_ptr MakeStalledStream(std::string start_step) { + return MakeStalledStream(std::move(start_step), "", nullptr); } std::unique_ptr MakeStalledStream( - std::string start_step, std::string finish_step = "", - std::atomic* cancel_count = nullptr) { + std::string start_step, std::string finish_step, + std::atomic* cancel_count) { auto stream = std::make_unique>(); EXPECT_CALL(*stream, Start).WillOnce([this, s = std::move(start_step)] { return sequencer_.PushBack(s); @@ -1124,9 +1129,9 @@ class OpenHedgingTest : public ::testing::Test { [](future) { return Status{}; }); }); } else { - ON_CALL(*stream, Finish).WillByDefault(InvokeWithoutArgs([] { + ON_CALL(*stream, Finish).WillByDefault([] { return make_ready_future(Status{}); - })); + }); } return std::unique_ptr(std::move(stream)); } @@ -1143,27 +1148,26 @@ class OpenHedgingTest : public ::testing::Test { return std::unique_ptr(std::move(stream)); } - std::shared_ptr MakeConnection(Options opts, - bool disable_mso = true) { - if (disable_mso) { - opts = internal::MergeOptions( - std::move(opts), - Options{}.set(false)); - } + std::shared_ptr MakeConnection(Options opts) { + opts = internal::MergeOptions( + std::move(opts), + Options{}.set(false)); return std::make_shared( CompletionQueue(mock_cq_), std::shared_ptr(), mock_stub_, TestOptions(std::move(opts))); } - static auto Open(std::shared_ptr const& conn, - Options opts) { + static OpenFuture Open(std::shared_ptr const& conn, + Options opts) { return conn->Open({MakeTestReadSpec(), std::move(opts)}); } - static auto Open(std::shared_ptr const& conn) { + static OpenFuture Open(std::shared_ptr const& conn) { return Open(conn, conn->options()); } + // Every step pushed onto `sequencer_` must be popped and resolved before + // teardown (un-drained futures terminate in `-fno-exceptions` builds). AsyncSequencer sequencer_; std::atomic cancelled_timers_{0}; std::vector timer_delays_; @@ -1175,38 +1179,39 @@ class OpenHedgingTest : public ::testing::Test { }; TEST_F(OpenHedgingTest, GatingAndPerCallOverrides) { - EXPECT_CALL(*mock_stub_, AsyncBidiReadObject).Times(4).WillRepeatedly([this] { + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject).Times(4).WillRepeatedly([] { return MakeImmediateStream(42); }); ExpectHedgeTimers({}); // 1. Disabled by default. - auto disabled_conn = MakeConnection(Options{}); - auto res1 = Open(disabled_conn).get(); + std::shared_ptr disabled_conn = + MakeConnection(Options{}); + OpenResult res1 = Open(disabled_conn).get(); ASSERT_THAT(res1, IsOkAndHolds(NotNull())); res1->reset(); // 2. Per-call `EnableReadHedgingOption(true)` without client-level opt-in is // a no-op because `hedge_limiter_` is only allocated at client creation. - auto per_call_enable = disabled_conn->options(); + Options per_call_enable = disabled_conn->options(); per_call_enable.set(true); - auto res2 = Open(disabled_conn, std::move(per_call_enable)).get(); + OpenResult res2 = Open(disabled_conn, std::move(per_call_enable)).get(); ASSERT_THAT(res2, IsOkAndHolds(NotNull())); res2->reset(); // 3 & 4. Client enabled, suppressed per-call via `EnableReadHedgingOption` // or `MaxReadHedgesOption(0)`. - auto enabled_conn = MakeConnection( + std::shared_ptr enabled_conn = MakeConnection( Options{}.set(true)); - auto disable_flag = enabled_conn->options(); + Options disable_flag = enabled_conn->options(); disable_flag.set(false); - auto res3 = Open(enabled_conn, std::move(disable_flag)).get(); + OpenResult res3 = Open(enabled_conn, std::move(disable_flag)).get(); ASSERT_THAT(res3, IsOkAndHolds(NotNull())); res3->reset(); - auto disable_zero = enabled_conn->options(); + Options disable_zero = enabled_conn->options(); disable_zero.set(0); - auto res4 = Open(enabled_conn, std::move(disable_zero)).get(); + OpenResult res4 = Open(enabled_conn, std::move(disable_zero)).get(); ASSERT_THAT(res4, IsOkAndHolds(NotNull())); res4->reset(); } @@ -1217,25 +1222,24 @@ TEST_F(OpenHedgingTest, FastPrimaryCancelsTimer) { // stream does NOT arm a second hedge timer. EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) .WillOnce([this] { return MakeSequencedStream("PrimaryStart", 101); }) - .WillOnce([this] { return MakeImmediateStream(101); }); + .WillOnce([] { return MakeImmediateStream(101); }); ExpectHedgeTimers({"HedgeTimer1"}); - auto conn = MakeConnection( + std::shared_ptr conn = MakeConnection( Options{} .set(true) .set(true) .set( std::chrono::milliseconds(250)) - .set(2), - /*disable_mso=*/false); + .set(2)); - auto pending = Open(conn); - auto primary_start = PopStep("PrimaryStart"); - auto timer1 = PopStep("HedgeTimer1"); + OpenFuture pending = Open(conn); + promise primary_start = PopStep("PrimaryStart"); + promise timer1 = PopStep("HedgeTimer1"); EXPECT_THAT(timer_delays_, ElementsAre(std::chrono::milliseconds(250))); primary_start.set_value(true); - auto result = pending.get(); + OpenResult result = pending.get(); ASSERT_THAT(result, IsOkAndHolds(NotNull())); EXPECT_EQ((*result)->metadata()->generation(), 101); EXPECT_EQ(cancelled_timers_.load(), 1); @@ -1263,34 +1267,34 @@ TEST_F(OpenHedgingTest, SlowPrimaryHedgeWinsAndResumeIsUnhedged) { return sequencer_.PushBack("HedgeStart"); }); ON_CALL(*stream, Write) - .WillByDefault([](auto const&, grpc::WriteOptions) { - return make_ready_future(true); - }); - ON_CALL(*stream, Read) - .WillByDefault(InvokeWithoutArgs([this, n = 0]() mutable { - if (n++ == 0) { - Response response; - response.mutable_metadata()->set_bucket( - "projects/_/buckets/test-bucket"); - response.mutable_metadata()->set_name("test-object"); - response.mutable_metadata()->set_generation(202); - response.mutable_read_handle()->set_handle("hedge-handle"); - return make_ready_future( - std::optional(std::move(response))); - } - return sequencer_.PushBack("HedgeStreamEnd") - .then([](future) { return std::optional(); }); - })); - ON_CALL(*stream, Finish).WillByDefault(InvokeWithoutArgs([] { + .WillByDefault( + [](google::storage::v2::BidiReadObjectRequest const&, + grpc::WriteOptions) { return make_ready_future(true); }); + ON_CALL(*stream, Read).WillByDefault([this, n = 0]() mutable { + if (n++ == 0) { + Response response; + response.mutable_metadata()->set_bucket( + "projects/_/buckets/test-bucket"); + response.mutable_metadata()->set_name("test-object"); + response.mutable_metadata()->set_generation(202); + response.mutable_read_handle()->set_handle("hedge-handle"); + return make_ready_future( + std::optional(std::move(response))); + } + return sequencer_.PushBack("HedgeStreamEnd").then([](future) { + return std::optional(); + }); + }); + ON_CALL(*stream, Finish).WillByDefault([] { return make_ready_future(Status{}); - })); + }); return std::unique_ptr(std::move(stream)); }) .WillOnce([this] { return MakeSequencedStream("ResumeStart", 202); }); // Only 2 timers for `max_hedges = 2`; background resume must not arm any. ExpectHedgeTimers({"HedgeTimer1", "HedgeTimer2"}); - auto conn = MakeConnection( + std::shared_ptr conn = MakeConnection( Options{} .set( storage::LimitedErrorCountResumePolicy(1)) @@ -1299,18 +1303,18 @@ TEST_F(OpenHedgingTest, SlowPrimaryHedgeWinsAndResumeIsUnhedged) { std::chrono::milliseconds(100)) .set(2)); - auto pending = Open(conn); - auto primary_start = PopStep("PrimaryStart"); - auto timer1 = PopStep("HedgeTimer1"); + OpenFuture pending = Open(conn); + promise primary_start = PopStep("PrimaryStart"); + promise timer1 = PopStep("HedgeTimer1"); timer1.set_value(true); - auto hedge_start = PopStep("HedgeStart"); - auto timer2 = PopStep("HedgeTimer2"); + promise hedge_start = PopStep("HedgeStart"); + promise timer2 = PopStep("HedgeTimer2"); hedge_start.set_value(true); - auto hedge_stream_end = PopStep("HedgeStreamEnd"); + promise hedge_stream_end = PopStep("HedgeStreamEnd"); - auto result = pending.get(); + OpenResult result = pending.get(); ASSERT_THAT(result, IsOkAndHolds(NotNull())); EXPECT_EQ((*result)->metadata()->generation(), 202); EXPECT_EQ(primary_cancel_count.load(), 1); @@ -1340,18 +1344,18 @@ TEST_F(OpenHedgingTest, PrimaryWinsAfterHedgeDispatched) { }); ExpectHedgeTimers({"HedgeTimer1"}); - auto conn = MakeConnection( + std::shared_ptr conn = MakeConnection( Options{} .set(true) .set(1)); - auto pending = Open(conn); - auto primary_start = PopStep("PrimaryStart"); + OpenFuture pending = Open(conn); + promise primary_start = PopStep("PrimaryStart"); PopStep("HedgeTimer1").set_value(true); - auto hedge_start = PopStep("HedgeStart"); + promise hedge_start = PopStep("HedgeStart"); primary_start.set_value(true); - auto result = pending.get(); + OpenResult result = pending.get(); ASSERT_THAT(result, IsOkAndHolds(NotNull())); EXPECT_EQ((*result)->metadata()->generation(), 1); EXPECT_EQ(hedge_cancel_count.load(), 1); @@ -1372,22 +1376,22 @@ TEST_P(OpenHedgingRescueTest, PrimaryTransientOrStallErrorRescuedByHedge) { .WillOnce([this] { return MakeSequencedStream("HedgeStart", 303); }); ExpectHedgeTimers({"HedgeTimer1"}); - auto conn = MakeConnection( + std::shared_ptr conn = MakeConnection( Options{} .set( storage::LimitedErrorCountAsyncRetryPolicy(0).clone()) .set(true) .set(1)); - auto pending = Open(conn); - auto primary_start = PopStep("PrimaryStart"); + OpenFuture pending = Open(conn); + promise primary_start = PopStep("PrimaryStart"); PopStep("HedgeTimer1").set_value(true); - auto hedge_start = PopStep("HedgeStart"); + promise hedge_start = PopStep("HedgeStart"); primary_start.set_value(false); hedge_start.set_value(true); - auto result = pending.get(); + OpenResult result = pending.get(); ASSERT_THAT(result, IsOkAndHolds(NotNull())); EXPECT_EQ((*result)->metadata()->generation(), 303); result->reset(); @@ -1412,16 +1416,16 @@ TEST_F(OpenHedgingTest, PrimaryPermanentFailureAbortsInFlightHedge) { }); ExpectHedgeTimers({"HedgeTimer1", "HedgeTimer2"}); - auto conn = MakeConnection( + std::shared_ptr conn = MakeConnection( Options{} .set(true) .set(2)); - auto pending = Open(conn); - auto primary_start = PopStep("PrimaryStart"); + OpenFuture pending = Open(conn); + promise primary_start = PopStep("PrimaryStart"); PopStep("HedgeTimer1").set_value(true); - auto hedge_start = PopStep("HedgeStart"); - auto timer2 = PopStep("HedgeTimer2"); + promise hedge_start = PopStep("HedgeStart"); + promise timer2 = PopStep("HedgeTimer2"); primary_start.set_value(false); EXPECT_THAT(pending.get(), StatusIs(PermanentError().code())); @@ -1433,6 +1437,116 @@ TEST_F(OpenHedgingTest, PrimaryPermanentFailureAbortsInFlightHedge) { PopStep("HedgeFinish").set_value(true); } +TEST_F(OpenHedgingTest, HedgePermanentFailureAbortsStalledPrimary) { + ExpectMetrics(1, 0); + std::atomic primary_cancel_count{0}; + + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce([this, &primary_cancel_count] { + return MakeStalledStream("PrimaryStart", "PrimaryFinish", + &primary_cancel_count); + }) + .WillOnce( + [this] { return MakeFailingStream("HedgeStart", PermanentError()); }); + ExpectHedgeTimers({"HedgeTimer1", "HedgeTimer2"}); + + std::shared_ptr conn = MakeConnection( + Options{} + .set(true) + .set(2)); + + OpenFuture pending = Open(conn); + promise primary_start = PopStep("PrimaryStart"); + PopStep("HedgeTimer1").set_value(true); + promise hedge_start = PopStep("HedgeStart"); + promise timer2 = PopStep("HedgeTimer2"); + + hedge_start.set_value(false); + EXPECT_THAT(pending.get(), StatusIs(PermanentError().code())); + EXPECT_EQ(primary_cancel_count.load(), 1); + EXPECT_EQ(cancelled_timers_.load(), 1); + + timer2.set_value(false); + primary_start.set_value(true); + PopStep("PrimaryFinish").set_value(true); +} + +TEST_F(OpenHedgingTest, FeatureHeaderSetOnlyOnHedgedOpenAttempts) { + std::string const both_features = + EncodeFeatureMask(FeatureBit(TrackedFeature::kMultistreamInMrd) | + FeatureBit(TrackedFeature::kReadHedging)); + std::string const mso_only = + EncodeFeatureMask(FeatureBit(TrackedFeature::kMultistreamInMrd)); + + ValidateMetadataFixture fixture; + std::vector> metadata; + std::atomic primary_cancel_count{0}; + + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + // 1. Call 1 Primary (hedged open + MSO). + .WillOnce([&, this](CompletionQueue const&, + std::shared_ptr const& context, + google::cloud::internal::ImmutableOptions const&) { + metadata.push_back(fixture.GetMetadata(*context)); + return MakeStalledStream("PrimaryStart", "PrimaryFinish", + &primary_cancel_count); + }) + // 2. Call 1 Hedge 1 (hedged open + MSO) — spends + // `MaxTotalHedgesOption(1)`. + .WillOnce([&, this](CompletionQueue const&, + std::shared_ptr const& context, + google::cloud::internal::ImmutableOptions const&) { + metadata.push_back(fixture.GetMetadata(*context)); + return MakeSequencedStream("HedgeStart", 701); + }) + // 3. Call 1 MSO standby stream — unhedged descriptor stream (MSO only). + .WillOnce([&](CompletionQueue const&, + std::shared_ptr const& context, + google::cloud::internal::ImmutableOptions const&) { + metadata.push_back(fixture.GetMetadata(*context)); + return MakeImmediateStream(701); + }) + // 4. Call 2 after `MaxTotalHedgesOption(1)` is exhausted (MSO false) — + // hedging is no longer in effect, so `kFeaturesHeader` is omitted. + .WillOnce([&](CompletionQueue const&, + std::shared_ptr const& context, + google::cloud::internal::ImmutableOptions const&) { + metadata.push_back(fixture.GetMetadata(*context)); + return MakeImmediateStream(702); + }); + ExpectHedgeTimers({"HedgeTimer1"}); + + std::shared_ptr conn = MakeConnection( + Options{} + .set(true) + .set(true) + .set(2) + .set(1)); + + OpenFuture call1 = Open(conn); + promise primary_start = PopStep("PrimaryStart"); + PopStep("HedgeTimer1").set_value(true); + PopStep("HedgeStart").set_value(true); + + OpenResult res1 = call1.get(); + ASSERT_THAT(res1, IsOkAndHolds(NotNull())); + primary_start.set_value(true); + PopStep("PrimaryFinish").set_value(true); + res1->reset(); + + Options no_mso = conn->options(); + no_mso.set(false); + OpenResult res2 = Open(conn, std::move(no_mso)).get(); + ASSERT_THAT(res2, IsOkAndHolds(NotNull())); + res2->reset(); + + ASSERT_THAT(metadata, SizeIs(4)); + EXPECT_THAT(metadata[0], Contains(Pair(kFeaturesHeader, both_features))); + EXPECT_THAT(metadata[1], Contains(Pair(kFeaturesHeader, both_features))); + EXPECT_THAT(metadata[2], Contains(Pair(kFeaturesHeader, mso_only))); + EXPECT_THAT(metadata[3], Not(Contains(Key(kFeaturesHeader)))); +} + TEST_F(OpenHedgingTest, AllAttemptsFailReturnsPrimaryError) { ExpectMetrics(1, 0); EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) @@ -1448,17 +1562,17 @@ TEST_F(OpenHedgingTest, AllAttemptsFailReturnsPrimaryError) { }); ExpectHedgeTimers({"HedgeTimer1"}); - auto conn = MakeConnection( + std::shared_ptr conn = MakeConnection( Options{} .set( storage::LimitedErrorCountAsyncRetryPolicy(0).clone()) .set(true) .set(1)); - auto pending = Open(conn); - auto primary_start = PopStep("PrimaryStart"); + OpenFuture pending = Open(conn); + promise primary_start = PopStep("PrimaryStart"); PopStep("HedgeTimer1").set_value(true); - auto hedge_start = PopStep("HedgeStart"); + promise hedge_start = PopStep("HedgeStart"); primary_start.set_value(false); hedge_start.set_value(false); @@ -1479,16 +1593,16 @@ TEST_F(OpenHedgingTest, CallerCancelCancelsAllAttemptsAndTimer) { }); ExpectHedgeTimers({"HedgeTimer1", "HedgeTimer2"}); - auto conn = MakeConnection( + std::shared_ptr conn = MakeConnection( Options{} .set(true) .set(2)); - auto pending = Open(conn); - auto primary_start = PopStep("PrimaryStart"); + OpenFuture pending = Open(conn); + promise primary_start = PopStep("PrimaryStart"); PopStep("HedgeTimer1").set_value(true); - auto hedge_start = PopStep("HedgeStart"); - auto timer2 = PopStep("HedgeTimer2"); + promise hedge_start = PopStep("HedgeStart"); + promise timer2 = PopStep("HedgeTimer2"); pending.cancel(); EXPECT_EQ(cancelled_timers_.load(), 1); @@ -1497,8 +1611,8 @@ TEST_F(OpenHedgingTest, CallerCancelCancelsAllAttemptsAndTimer) { timer2.set_value(false); primary_start.set_value(true); hedge_start.set_value(true); - sequencer_.PopFrontWithName().first.set_value(true); - sequencer_.PopFrontWithName().first.set_value(true); + PopStep("PrimaryFinish").set_value(true); + PopStep("HedgeFinish").set_value(true); EXPECT_THAT(pending.get(), StatusIs(StatusCode::kCancelled)); } @@ -1510,15 +1624,15 @@ TEST_F(OpenHedgingTest, RespectsConcurrencyAndLifetimeLimits) { .WillOnce([this] { return MakeStalledStream("Call1Primary"); }) .WillOnce([this] { return MakeStalledStream("Call2Primary"); }) .WillOnce([this] { return MakeSequencedStream("Call1Hedge", 601); }) - .WillOnce([this] { return MakeImmediateStream(602); }) - .WillOnce([this] { return MakeImmediateStream(603); }); + .WillOnce([] { return MakeImmediateStream(602); }) + .WillOnce([] { return MakeImmediateStream(603); }); // Call 1 arms Timer 1 and (once Hedge 1 starts) Timer 2; Call 2 arms Timer 1, // hits `MaxConcurrentHedgesOption(1)` -> re-arms at >= 10ms, then spends the // 2nd & final lifetime token so neither Call 2 nor Call 3 arms more timers. ExpectHedgeTimers( {"Call1Timer1", "Call2Timer1", "Call1Timer2", "Call2RetryTimer"}); - auto conn = MakeConnection( + std::shared_ptr conn = MakeConnection( Options{} .set(true) .set(ms(1)) @@ -1526,27 +1640,27 @@ TEST_F(OpenHedgingTest, RespectsConcurrencyAndLifetimeLimits) { .set(1) .set(2)); - auto call1 = Open(conn); - auto call2 = Open(conn); - auto c1_primary = PopStep("Call1Primary"); - auto c1_timer1 = PopStep("Call1Timer1"); - auto c2_primary = PopStep("Call2Primary"); - auto c2_timer1 = PopStep("Call2Timer1"); + OpenFuture call1 = Open(conn); + OpenFuture call2 = Open(conn); + promise c1_primary = PopStep("Call1Primary"); + promise c1_timer1 = PopStep("Call1Timer1"); + promise c2_primary = PopStep("Call2Primary"); + promise c2_timer1 = PopStep("Call2Timer1"); // Call 1 acquires the single concurrency slot (total 1/2) and arms Timer 2. c1_timer1.set_value(true); - auto c1_hedge = PopStep("Call1Hedge"); - auto c1_timer2 = PopStep("Call1Timer2"); + promise c1_hedge = PopStep("Call1Hedge"); + promise c1_timer2 = PopStep("Call1Timer2"); // Call 2 is denied by `MaxConcurrentHedgesOption(1)` and re-arms at 10ms. c2_timer1.set_value(true); - auto c2_retry = PopStep("Call2RetryTimer"); + promise c2_retry = PopStep("Call2RetryTimer"); EXPECT_THAT(timer_delays_, ElementsAre(ms(1), ms(1), ms(1), ms(10))); // Finishing Call 1's hedge releases the concurrency slot before // `call1.get()`. c1_hedge.set_value(true); - auto res1 = call1.get(); + OpenResult res1 = call1.get(); ASSERT_THAT(res1, IsOkAndHolds(NotNull())); EXPECT_EQ((*res1)->metadata()->generation(), 601); c1_timer2.set_value(false); @@ -1554,11 +1668,11 @@ TEST_F(OpenHedgingTest, RespectsConcurrencyAndLifetimeLimits) { // 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 subsequent Call 3. c2_retry.set_value(true); - auto res2 = call2.get(); + OpenResult res2 = call2.get(); ASSERT_THAT(res2, IsOkAndHolds(NotNull())); EXPECT_EQ((*res2)->metadata()->generation(), 602); - auto res3 = Open(conn).get(); + OpenResult res3 = Open(conn).get(); ASSERT_THAT(res3, IsOkAndHolds(NotNull())); EXPECT_EQ((*res3)->metadata()->generation(), 603); @@ -1570,6 +1684,8 @@ TEST_F(OpenHedgingTest, RespectsConcurrencyAndLifetimeLimits) { } TEST(AsyncConnectionImplTest, OpenHedgingConcurrentCompletionRace) { + using OpenResult = + StatusOr>; for (int iter = 0; iter != 25; ++iter) { std::mutex gate_mu; std::condition_variable gate_cv; @@ -1579,7 +1695,7 @@ TEST(AsyncConnectionImplTest, OpenHedgingConcurrentCompletionRace) { std::vector workers; workers.reserve(2); - auto make_racing_stream = [&](std::int64_t generation) { + auto const make_racing_stream = [&](std::int64_t generation) { auto start_promise = std::make_shared>(); auto start_future = std::make_shared>(start_promise->get_future()); @@ -1619,16 +1735,17 @@ TEST(AsyncConnectionImplTest, OpenHedgingConcurrentCompletionRace) { .set(true) .set(1))); - auto pending = conn->Open({MakeTestReadSpec(), conn->options()}); + future pending = + conn->Open({MakeTestReadSpec(), conn->options()}); { std::unique_lock lock(gate_mu); gate_cv.wait(lock, [&] { return ready_workers == 2; }); release_workers = true; } gate_cv.notify_all(); - for (auto& w : workers) w.join(); + for (std::thread& w : workers) w.join(); - auto result = pending.get(); + OpenResult result = pending.get(); ASSERT_THAT(result, IsOkAndHolds(NotNull())); EXPECT_THAT((*result)->metadata()->generation(), ::testing::AnyOf(::testing::Eq(1), ::testing::Eq(2))); diff --git a/google/cloud/storage/internal/hedge_limiter.h b/google/cloud/storage/internal/hedge_limiter.h index 83ac5c49bd25d..2a5d960cb9f01 100644 --- a/google/cloud/storage/internal/hedge_limiter.h +++ b/google/cloud/storage/internal/hedge_limiter.h @@ -113,7 +113,8 @@ class HedgeLimiter { } void Refill() { - auto const now = std::chrono::steady_clock::now(); + std::chrono::steady_clock::time_point const now = + std::chrono::steady_clock::now(); double const elapsed = std::chrono::duration_cast>(now - last_refill_) @@ -122,8 +123,8 @@ class HedgeLimiter { tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_); } - double rate_limit_; - double tokens_capacity_; + double const rate_limit_; + double const tokens_capacity_; double tokens_; std::chrono::steady_clock::time_point last_refill_; std::mutex limiter_mutex_; diff --git a/google/cloud/storage/options.h b/google/cloud/storage/options.h index af5557bc0027e..b112c9b9afd16 100644 --- a/google/cloud/storage/options.h +++ b/google/cloud/storage/options.h @@ -49,9 +49,10 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN * (bounded by `ReadHedgeRateLimitOption`, `MaxConcurrentHedgesOption`, and * `MaxTotalHedgesOption`). Individual calls may opt out via * `EnableReadHedgingOption(false)` or `MaxReadHedgesOption(0)`, or override - * `ReadHedgeDelayOption` and `MaxReadHedgesOption`; subsequent ranged reads and - * stream resumes are not hedged. This reduces tail latency at the cost of - * additional requests. + * `ReadHedgeDelayOption` and `MaxReadHedgesOption`. Any initial ranges passed + * via `ReadRangesOption` are sent with each hedged open attempt; subsequent + * `ObjectDescriptor::Read()` ranged reads and stream resumes are not hedged. + * This reduces tail latency at the cost of additional requests. * * The client records two OpenTelemetry counters through the global meter * provider in effect when the client is created: