diff --git a/google/cloud/storage/async/client.h b/google/cloud/storage/async/client.h index edbfc0f25a28e..8b99aad5c8a1b 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 @@ -307,6 +310,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 config initial byte ranges to request during connection setup. @@ -326,6 +332,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 spec the BidiReadObjectSpec to use when retrieving the * ObjectDescriptor. * @param opts options controlling the behavior of this RPC, for example diff --git a/google/cloud/storage/google_cloud_cpp_storage.bzl b/google/cloud/storage/google_cloud_cpp_storage.bzl index 9593553fdcdfb..d42f4182ac8cc 100644 --- a/google/cloud/storage/google_cloud_cpp_storage.bzl +++ b/google/cloud/storage/google_cloud_cpp_storage.bzl @@ -74,6 +74,7 @@ google_cloud_cpp_storage_hdrs = [ "internal/hash_validator.h", "internal/hash_validator_impl.h", "internal/hash_values.h", + "internal/hedge_limiter.h", "internal/hedged_object_read_source.h", "internal/hedged_read_metrics.h", "internal/hedging_thread_pool.h", diff --git a/google/cloud/storage/google_cloud_cpp_storage.cmake b/google/cloud/storage/google_cloud_cpp_storage.cmake index 0ba84aa1c303d..76af9dbda548b 100644 --- a/google/cloud/storage/google_cloud_cpp_storage.cmake +++ b/google/cloud/storage/google_cloud_cpp_storage.cmake @@ -117,6 +117,7 @@ add_library( internal/hash_validator_impl.h internal/hash_values.cc internal/hash_values.h + internal/hedge_limiter.h internal/hedged_object_read_source.cc internal/hedged_object_read_source.h internal/hedged_read_metrics.cc @@ -462,6 +463,7 @@ if (BUILD_TESTING) internal/hash_function_impl_test.cc internal/hash_validator_test.cc internal/hash_values_test.cc + internal/hedge_limiter_test.cc internal/hedged_object_read_source_test.cc internal/hedged_read_metrics_test.cc internal/hedging_thread_pool_test.cc diff --git a/google/cloud/storage/google_cloud_cpp_storage_grpc.bzl b/google/cloud/storage/google_cloud_cpp_storage_grpc.bzl index 34d8ffe483dd8..790f2e0ca33d0 100644 --- a/google/cloud/storage/google_cloud_cpp_storage_grpc.bzl +++ b/google/cloud/storage/google_cloud_cpp_storage_grpc.bzl @@ -43,6 +43,7 @@ google_cloud_cpp_storage_grpc_hdrs = [ "internal/async/connection_tracing.h", "internal/async/default_options.h", "internal/async/handle_redirect_error.h", + "internal/async/hedged_open_stream.h", "internal/async/insert_object.h", "internal/async/multi_stream_manager.h", "internal/async/object_descriptor_connection_tracing.h", @@ -124,6 +125,7 @@ google_cloud_cpp_storage_grpc_srcs = [ "internal/async/connection_tracing.cc", "internal/async/default_options.cc", "internal/async/handle_redirect_error.cc", + "internal/async/hedged_open_stream.cc", "internal/async/insert_object.cc", "internal/async/multi_stream_manager.cc", "internal/async/object_descriptor_connection_tracing.cc", diff --git a/google/cloud/storage/google_cloud_cpp_storage_grpc.cmake b/google/cloud/storage/google_cloud_cpp_storage_grpc.cmake index 33474bfc66ecf..b24be6ced6352 100644 --- a/google/cloud/storage/google_cloud_cpp_storage_grpc.cmake +++ b/google/cloud/storage/google_cloud_cpp_storage_grpc.cmake @@ -109,6 +109,8 @@ add_library( internal/async/default_options.h internal/async/handle_redirect_error.cc internal/async/handle_redirect_error.h + internal/async/hedged_open_stream.cc + internal/async/hedged_open_stream.h internal/async/insert_object.cc internal/async/insert_object.h internal/async/multi_stream_manager.cc @@ -426,6 +428,7 @@ set(storage_client_grpc_unit_tests internal/async/connection_tracing_test.cc internal/async/default_options_test.cc internal/async/handle_redirect_error_test.cc + internal/async/hedged_open_stream_test.cc internal/async/insert_object_test.cc internal/async/multi_stream_manager_test.cc internal/async/object_descriptor_connection_tracing_test.cc diff --git a/google/cloud/storage/internal/async/connection_impl.cc b/google/cloud/storage/internal/async/connection_impl.cc index 40b536c920906..3c386f9312e51 100644 --- a/google/cloud/storage/internal/async/connection_impl.cc +++ b/google/cloud/storage/internal/async/connection_impl.cc @@ -23,6 +23,7 @@ #include "google/cloud/storage/internal/async/checksum_helpers.h" #include "google/cloud/storage/internal/async/default_options.h" #include "google/cloud/storage/internal/async/handle_redirect_error.h" +#include "google/cloud/storage/internal/async/hedged_open_stream.h" #include "google/cloud/storage/internal/async/insert_object.h" #include "google/cloud/storage/internal/async/object_descriptor_impl.h" #include "google/cloud/storage/internal/async/open_object.h" @@ -51,6 +52,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" @@ -62,6 +65,8 @@ #include "google/cloud/internal/async_streaming_write_rpc_timeout.h" #include "google/cloud/internal/make_status.h" #include +#include +#include #include #include #include @@ -150,6 +155,9 @@ 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 }; + /** * Creates the factory that opens a bidi read stream. * @@ -175,12 +183,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 = @@ -188,7 +196,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, @@ -196,11 +204,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); @@ -239,7 +252,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 +355,39 @@ 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__; + 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, OpenHedging::kDisabled); + + int const max_hedges = + hedge_limiter_ && !hedge_limiter_->IsTotalBudgetSpent() && + current->get() + ? current->get() + : 0; + future> pending; + if (max_hedges > 0) { + HedgedOpenParams const params{ + current->get(), max_hedges}; + OpenStreamFactory hedged_factory = MakeOpenStreamFactory( + stub_, cq_, retry, backoff, current, function_name, + OpenLogging::kEnabled, OpenHedging::kEnabled); + pending = HedgedOpenStream(cq_, std::move(hedged_factory), + std::move(initial_request), retry, params, + hedge_limiter_, hedged_read_metrics_, current); + } else { + pending = factory(std::move(initial_request)); + } + // Used only when the descriptor re-opens a stream that ended cleanly: see // `MakeOpenStreamFactory()` and `ObjectDescriptorImpl`. - auto clean_resume_factory = MakeOpenStreamFactory( + OpenStreamFactory 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)); + function_name, OpenLogging::kDisabled, OpenHedging::kDisabled); 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..e0af0635b9ebb 100644 --- a/google/cloud/storage/internal/async/connection_impl.h +++ b/google/cloud/storage/internal/async/connection_impl.h @@ -39,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; @@ -148,6 +157,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..e35320f2579ae 100644 --- a/google/cloud/storage/internal/async/connection_impl_open_test.cc +++ b/google/cloud/storage/internal/async/connection_impl_open_test.cc @@ -35,7 +35,15 @@ #include "absl/strings/match.h" #include #include +#include +#include +#include +#include +#include #include +#include +#include +#include #include #include #include @@ -908,6 +916,348 @@ TEST(AsyncConnectionImplTest, OpenWithReadRanges) { next.first.set_value(true); } +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 (std::exchange(cancelled, true)) return; + wake = waiting; + } + if (wake) pending.set_value(std::nullopt); + } +}; + +std::unique_ptr MakeOpenStream( + std::function()> on_start, + std::function< + future>()> + after_first_read, + std::function on_cancel, std::int64_t generation) { + using Response = google::storage::v2::BidiReadObjectResponse; + auto stream = std::make_unique>(); + 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( + [generation, after = std::move(after_first_read), 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 after(); + }); + ON_CALL(*stream, Cancel).WillByDefault(std::move(on_cancel)); + ON_CALL(*stream, Finish).WillByDefault([] { + return make_ready_future(Status{}); + }); + return std::unique_ptr(std::move(stream)); +} + +std::unique_ptr MakeParkedStreamWithStart( + std::function()> on_start, std::int64_t generation) { + auto parked = std::make_shared(); + return MakeOpenStream( + std::move(on_start), [parked] { return parked->Park(); }, + [parked] { parked->Release(); }, generation); +} + +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 OpenHedgingWiringTest : public ::testing::Test { + protected: + using OpenResult = + StatusOr>; + using OpenFuture = future; + using TimerFuture = future>; + + void ExpectHedgeTimers(std::vector names) { + if (names.empty()) { + EXPECT_CALL(*mock_cq_, MakeRelativeTimer).Times(0); + return; + } + int const count = static_cast(names.size()); + EXPECT_CALL(*mock_cq_, MakeRelativeTimer) + .Times(count) + .WillRepeatedly( + [this, names = std::move(names)](std::chrono::nanoseconds) { + std::size_t const idx = timer_count_++; + std::string const name = + idx < names.size() ? names[idx] : std::string("ExtraTimer"); + future step = sequencer_.PushBack(name); + auto timer_promise = std::make_shared< + promise>>( + [this] { ++cancelled_timers_; }); + TimerFuture timer_future = timer_promise->get_future(); + step.then([timer_promise](future f) mutable { + if (!f.get()) { + return timer_promise->set_value(internal::CancelledError( + "timer cancelled", GCP_ERROR_INFO())); + } + timer_promise->set_value(std::chrono::system_clock::now()); + }); + return timer_future; + }); + } + + promise PopStep(char const* expected) { + auto [p, name] = sequencer_.PopFrontWithName(); + EXPECT_EQ(name, expected); + return std::move(p); + } + + static std::unique_ptr MakeImmediateStream( + std::int64_t generation) { + return MakeParkedStreamWithStart([] { return make_ready_future(true); }, + generation); + } + + std::unique_ptr MakeSequencedStream(std::string step, + std::int64_t generation) { + return MakeParkedStreamWithStart( + [this, s = std::move(step)] { return sequencer_.PushBack(s); }, + generation); + } + + std::unique_ptr MakeClosingStream(std::string start_step, + std::string end_step, + std::int64_t generation) { + using Response = google::storage::v2::BidiReadObjectResponse; + return MakeOpenStream( + [this, s = std::move(start_step)] { return sequencer_.PushBack(s); }, + [this, e = std::move(end_step)] { + return sequencer_.PushBack(e).then( + [](future) { return std::optional(); }); + }, + [] {}, generation); + } + + std::unique_ptr MakeStalledStream( + 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); + }); + ON_CALL(*stream, Cancel).WillByDefault([cancel_count] { + if (cancel_count != nullptr) ++(*cancel_count); + }); + EXPECT_CALL(*stream, Finish).WillOnce([this, f = std::move(finish_step)] { + return sequencer_.PushBack(f).then([](future) { return Status{}; }); + }); + return std::unique_ptr(std::move(stream)); + } + + 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 OpenFuture Open(std::shared_ptr const& conn, + Options opts) { + return conn->Open({MakeTestReadSpec(), std::move(opts)}); + } + + static OpenFuture Open(std::shared_ptr const& conn) { + return Open(conn, conn->options()); + } + + AsyncSequencer sequencer_; + std::size_t timer_count_ = 0; + std::atomic cancelled_timers_{0}; + std::shared_ptr mock_stub_ = + std::make_shared(); + std::shared_ptr mock_cq_ = + std::make_shared(); +}; + +TEST_F(OpenHedgingWiringTest, GatingAndPerCallOverrides) { + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject).Times(4).WillRepeatedly([] { + return MakeImmediateStream(42); + }); + ExpectHedgeTimers({}); + + // 1. Disabled by default; 2. Per-call opt-in without client-level opt-in is a + // no-op because `hedge_limiter_` is allocated only at connection creation. + std::shared_ptr disabled_conn = + MakeConnection(Options{}); + OpenResult res1 = Open(disabled_conn).get(); + ASSERT_THAT(res1, IsOkAndHolds(NotNull())); + res1->reset(); + + Options per_call_enable = disabled_conn->options(); + per_call_enable.set(true); + 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)`. + std::shared_ptr enabled_conn = MakeConnection( + Options{}.set(true)); + Options disable_flag = enabled_conn->options(); + disable_flag.set(false); + OpenResult res3 = Open(enabled_conn, std::move(disable_flag)).get(); + ASSERT_THAT(res3, IsOkAndHolds(NotNull())); + res3->reset(); + + Options disable_zero = enabled_conn->options(); + disable_zero.set(0); + OpenResult res4 = Open(enabled_conn, std::move(disable_zero)).get(); + ASSERT_THAT(res4, IsOkAndHolds(NotNull())); + res4->reset(); +} + +TEST_F(OpenHedgingWiringTest, 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}; + auto const capture_and = [&](auto make_stream) { + return [&, make = std::move(make_stream)]( + CompletionQueue const&, + std::shared_ptr const& context, + google::cloud::internal::ImmutableOptions const&) mutable { + metadata.push_back(fixture.GetMetadata(*context)); + return make(); + }; + }; + + EXPECT_CALL(*mock_stub_, AsyncBidiReadObject) + .WillOnce(capture_and([this, &primary_cancel_count] { + return MakeStalledStream("PrimaryStart", "PrimaryFinish", + &primary_cancel_count); + })) + .WillOnce(capture_and( + [this] { return MakeSequencedStream("HedgeStart", 701); })) + // MSO standby stream — unhedged descriptor stream (MSO bit only). + .WillOnce(capture_and([] { return MakeImmediateStream(701); })) + // Call 2 after `MaxTotalHedgesOption(1)` is exhausted (MSO false). + .WillOnce(capture_and([] { 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(OpenHedgingWiringTest, SlowPrimaryHedgeWinsAndResumeIsUnhedged) { + ScopedLog log; + 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 MakeClosingStream("HedgeStart", "HedgeStreamEnd", 202); + }) + .WillOnce([this] { return MakeSequencedStream("ResumeStart", 202); }); + // Only 2 timers for `max_hedges = 2`; background resume must not arm any. + ExpectHedgeTimers({"HedgeTimer1", "HedgeTimer2"}); + + std::shared_ptr conn = MakeConnection( + Options{} + .set( + storage::LimitedErrorCountResumePolicy(1)) + .set(true) + .set( + std::chrono::milliseconds(100)) + .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(true); + promise hedge_stream_end = PopStep("HedgeStreamEnd"); + + OpenResult 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()); +} + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal diff --git a/google/cloud/storage/internal/async/hedged_open_stream.cc b/google/cloud/storage/internal/async/hedged_open_stream.cc new file mode 100644 index 0000000000000..afc78a63bb47e --- /dev/null +++ b/google/cloud/storage/internal/async/hedged_open_stream.cc @@ -0,0 +1,355 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "google/cloud/storage/internal/async/hedged_open_stream.h" +#include "google/cloud/internal/call_context.h" +#include "google/cloud/internal/make_status.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace { + +std::chrono::milliseconds constexpr kHedgeRetryMinDelay{10}; + +class HedgedOpenOperation + : public std::enable_shared_from_this { + public: + HedgedOpenOperation( + CompletionQueue cq, OpenStreamFactory factory, + google::storage::v2::BidiReadObjectRequest initial_request, + std::shared_ptr retry_policy, + HedgedOpenParams params, + std::shared_ptr limiter, + std::shared_ptr metrics, + google::cloud::internal::ImmutableOptions options) + : cq_(std::move(cq)), + factory_(std::move(factory)), + initial_request_(std::move(initial_request)), + retry_policy_(std::move(retry_policy)), + hedge_delay_( + (std::max)(std::chrono::milliseconds::zero(), params.delay)), + max_hedges_((std::max)(0, params.max_hedges)), + limiter_(std::move(limiter)), + metrics_(std::move(metrics)), + call_context_(std::move(options)) {} + + future> Start() { + std::weak_ptr weak = shared_from_this(); + result_promise_ = promise>([weak] { + if (std::shared_ptr self = weak.lock()) { + google::cloud::internal::ScopedCallContext scope(self->call_context_); + self->OnCallerCancel(); + } + }); + future> result_future = + result_promise_.get_future(); + + active_attempts_ = 1; + attempts_.emplace_back(future{}); + bool const arm_timer = CanHedge(); + + AttachAttempt(0, StartAttempt(0)); + if (arm_timer) ArmTimer(hedge_delay_); + return result_future; + } + + private: + struct HedgeSlot { + std::shared_ptr limiter; + + HedgeSlot() = default; + explicit HedgeSlot(std::shared_ptr l) + : limiter(std::move(l)) {} + ~HedgeSlot() { Release(); } + HedgeSlot(HedgeSlot&&) noexcept = default; + HedgeSlot& operator=(HedgeSlot&&) = delete; + HedgeSlot(HedgeSlot const&) = delete; + HedgeSlot& operator=(HedgeSlot const&) = delete; + + void Release() { + if (limiter) std::exchange(limiter, nullptr)->ReleaseHedgeSlot(); + } + }; + + struct Outstanding { + future timer; + std::vector>> attempts; + + void Cancel() { + CancelIfValid(timer); + for (std::optional>& pending : attempts) { + if (pending) CancelIfValid(*pending); + } + } + }; + + static void CancelIfValid(future& f) { + if (f.valid()) f.cancel(); + } + + static Status CancelledOpenError() { + return google::cloud::internal::CancelledError("Open operation cancelled", + GCP_ERROR_INFO()); + } + + bool CanHedge() const { + return hedges_dispatched_ < max_hedges_ && + (!limiter_ || !limiter_->IsTotalBudgetSpent()); + } + + future FinishAttemptLocked(std::size_t idx) { + --active_attempts_; + if (idx < attempts_.size() && attempts_[idx].has_value()) { + return *std::exchange(attempts_[idx], std::nullopt); + } + return future{}; + } + + Outstanding DrainOutstandingLocked() { + ++timer_generation_; + return Outstanding{std::move(timer_future_), std::exchange(attempts_, {})}; + } + + void Resolve(Outstanding& outstanding, StatusOr result) { + outstanding.Cancel(); + result_promise_.set_value(std::move(result)); + } + + future StartAttempt(std::size_t idx) { + HedgeSlot slot = idx == 0 ? HedgeSlot{} : HedgeSlot{limiter_}; + google::cloud::internal::ScopedCallContext scope(call_context_); + std::shared_ptr self = shared_from_this(); + return factory_(initial_request_) + .then([self = std::move(self), slot = std::move(slot), + idx](future> f) mutable { + slot.Release(); + self->OnAttemptDone(idx, f.get()); + }); + } + + void AttachAttempt(std::size_t idx, future attempt) { + if (!attempt.valid() || attempt.is_ready()) return; + bool cancel_now = false; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) { + cancel_now = true; + } else if (idx < attempts_.size() && attempts_[idx].has_value()) { + attempts_[idx] = std::move(attempt); + } + } + if (cancel_now) CancelIfValid(attempt); + } + + void ArmTimer(std::chrono::milliseconds delay) { + std::uint64_t gen = 0; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) return; + gen = ++timer_generation_; + } + std::weak_ptr weak = shared_from_this(); + future timer = cq_.MakeRelativeTimer(delay).then( + [weak, gen](future> f) { + if (std::shared_ptr self = weak.lock()) { + self->OnTimer(gen, f.get().ok()); + } + }); + if (!timer.valid() || timer.is_ready()) return; + bool cancel_now = false; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) { + cancel_now = true; + } else if (gen == timer_generation_) { + timer_future_ = std::move(timer); + } + } + if (cancel_now) CancelIfValid(timer); + } + + void OnTimer(std::uint64_t gen, bool expired) { + if (!expired) return; + google::cloud::internal::ScopedCallContext scope(call_context_); + + bool dispatch_hedge = false; + std::size_t idx = 0; + bool arm_next_timer = false; + std::chrono::milliseconds next_delay = hedge_delay_; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_ || gen != timer_generation_ || + hedges_dispatched_ >= max_hedges_) { + return; + } + ++timer_generation_; + timer_future_ = future{}; + bool const acquired = !limiter_ || limiter_->TryAcquireHedgeToken(); + if (acquired) { + dispatch_hedge = true; + ++active_attempts_; + ++hedges_dispatched_; + idx = attempts_.size(); + attempts_.emplace_back(future{}); + } + if (CanHedge()) { + arm_next_timer = true; + next_delay = acquired ? hedge_delay_ + : (std::max)(hedge_delay_, kHedgeRetryMinDelay); + } + } + + // If a sibling won after unlocking `mu_`, `AttachAttempt` cancels it. + if (dispatch_hedge) { + if (metrics_) metrics_->OnHedgeDispatched(); + AttachAttempt(idx, StartAttempt(idx)); + } + if (arm_next_timer) ArmTimer(next_delay); + } + + void OnAttemptDone(std::size_t idx, StatusOr result) { + google::cloud::internal::ScopedCallContext scope(call_context_); + if (!result) return OnAttemptError(idx, std::move(result).status()); + future self_attempt; + Outstanding outstanding; + bool won = false; + { + std::lock_guard lock(mu_); + if (!resolved_ && !caller_cancelled_) { + won = true; + self_attempt = FinishAttemptLocked(idx); + resolved_ = true; + outstanding = DrainOutstandingLocked(); + } + } + if (!won) { + if (result->stream) result->stream->Cancel(); + OnAttemptError(idx, CancelledOpenError()); + return; + } + if (idx > 0 && metrics_) metrics_->OnHedgeWon(); + Resolve(outstanding, *std::move(result)); + } + + Status SelectFinalErrorLocked() const { + // `RetryLoopCancelled` preserves the last transient status code when + // cancelled during backoff, so map caller-cancelled races to `kCancelled`. + if (caller_cancelled_) { + return primary_error_.code() == StatusCode::kCancelled + ? primary_error_ + : CancelledOpenError(); + } + if (!permanent_error_.ok()) return permanent_error_; + return primary_error_; + } + + void OnAttemptError(std::size_t idx, Status status) { + // Unlike mid-stream sync `HedgedObjectReadSource`, every `Open()` attempt + // sends the identical initial request, so an authoritative permanent + // rejection (`kNotFound`, `kPermissionDenied`, ...) from *any* attempt + // aborts stalled siblings immediately. `kCancelled` is excluded because + // per-stream stall timeouts surface as `kCancelled` on that attempt alone. + bool const permanent_error = status.code() != StatusCode::kCancelled && + retry_policy_ && + retry_policy_->IsPermanentFailure(status); + future self_attempt; + Outstanding outstanding; + Status final_error; + bool resolve_now = false; + { + std::lock_guard lock(mu_); + self_attempt = FinishAttemptLocked(idx); + if (resolved_) return; + if (permanent_error && permanent_error_.ok()) permanent_error_ = status; + if (idx == 0) primary_error_ = std::move(status); + // Each attempt runs its own `AsyncRetryLoop`, so `active_attempts_ == 0` + // means every launched attempt already exhausted its retry policy; do + // not wait for un-fired hedge timers to double the retry budget. + if (active_attempts_ == 0 || + (!caller_cancelled_ && !permanent_error_.ok())) { + resolve_now = true; + resolved_ = true; + final_error = SelectFinalErrorLocked(); + outstanding = DrainOutstandingLocked(); + } + } + if (resolve_now) Resolve(outstanding, std::move(final_error)); + } + + void OnCallerCancel() { + Outstanding outstanding; + { + std::lock_guard lock(mu_); + if (resolved_ || caller_cancelled_) return; + caller_cancelled_ = true; + outstanding = DrainOutstandingLocked(); + } + outstanding.Cancel(); + } + + CompletionQueue cq_; + OpenStreamFactory factory_; + google::storage::v2::BidiReadObjectRequest initial_request_; + std::shared_ptr retry_policy_; + std::chrono::milliseconds const hedge_delay_; + int const max_hedges_; + std::shared_ptr limiter_; + std::shared_ptr metrics_; + google::cloud::internal::CallContext call_context_; + promise> result_promise_{null_promise_t{}}; + + std::mutex mu_; + bool resolved_ = false; + bool caller_cancelled_ = false; + int active_attempts_ = 0; + int hedges_dispatched_ = 0; + std::uint64_t timer_generation_ = 0; + Status permanent_error_; + Status primary_error_; + future timer_future_; + std::vector>> attempts_; +}; + +} // namespace + +future> HedgedOpenStream( + CompletionQueue cq, OpenStreamFactory factory, + google::storage::v2::BidiReadObjectRequest initial_request, + std::shared_ptr retry_policy, + HedgedOpenParams params, + std::shared_ptr limiter, + std::shared_ptr metrics, + google::cloud::internal::ImmutableOptions options) { + return std::make_shared( + std::move(cq), std::move(factory), std::move(initial_request), + std::move(retry_policy), params, std::move(limiter), + std::move(metrics), std::move(options)) + ->Start(); +} + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/internal/async/hedged_open_stream.h b/google/cloud/storage/internal/async/hedged_open_stream.h new file mode 100644 index 0000000000000..00671b1d19b54 --- /dev/null +++ b/google/cloud/storage/internal/async/hedged_open_stream.h @@ -0,0 +1,73 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_ASYNC_HEDGED_OPEN_STREAM_H +#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_ASYNC_HEDGED_OPEN_STREAM_H + +#include "google/cloud/storage/async/retry_policy.h" +#include "google/cloud/storage/internal/async/open_stream.h" +#include "google/cloud/storage/internal/hedge_limiter.h" +#include "google/cloud/storage/internal/hedged_read_metrics.h" +#include "google/cloud/completion_queue.h" +#include "google/cloud/future.h" +#include "google/cloud/options.h" +#include "google/cloud/status_or.h" +#include "google/cloud/version.h" +#include "google/storage/v2/storage.pb.h" +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN + +struct HedgedOpenParams { + std::chrono::milliseconds delay; + int max_hedges; +}; + +/** + * Races a primary `OpenStreamFactory` attempt against up to `params.max_hedges` + * delayed speculative attempts spaced by `params.delay`. + * + * The first attempt to succeed wins; remaining in-flight attempts and timers + * are cancelled, and any late-completing loser's `OpenStream` is cancelled via + * `OpenStream::Cancel()`. A permanent non-`kCancelled` error from *any* attempt + * resolves the race immediately; otherwise if all launched attempts fail, the + * primary attempt's error is returned. Cancelling the returned future cancels + * all in-flight attempts and timers. Negative `params.delay` and + * `params.max_hedges` values are clamped to zero. + * + * @p retry_policy classifies permanent failures; if null, no attempt error + * aborts siblings early. + * @p limiter gates speculative hedge dispatches across the connection; if null, + * per-connection rate/concurrency/lifetime limits are not enforced. + * @p metrics may be null, in which case no OpenTelemetry counters are recorded. + */ +future> HedgedOpenStream( + CompletionQueue cq, OpenStreamFactory factory, + google::storage::v2::BidiReadObjectRequest initial_request, + std::shared_ptr retry_policy, + HedgedOpenParams params, + std::shared_ptr limiter, + std::shared_ptr metrics, + google::cloud::internal::ImmutableOptions options); + +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google + +#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_ASYNC_HEDGED_OPEN_STREAM_H diff --git a/google/cloud/storage/internal/async/hedged_open_stream_test.cc b/google/cloud/storage/internal/async/hedged_open_stream_test.cc new file mode 100644 index 0000000000000..261b36a032a18 --- /dev/null +++ b/google/cloud/storage/internal/async/hedged_open_stream_test.cc @@ -0,0 +1,526 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "google/cloud/storage/internal/async/hedged_open_stream.h" +#include "google/cloud/mocks/mock_async_streaming_read_write_rpc.h" +#include "google/cloud/storage/testing/canonical_errors.h" +#include "google/cloud/internal/make_status.h" +#include "google/cloud/testing_util/async_sequencer.h" +#include "google/cloud/testing_util/mock_completion_queue_impl.h" +#include "google/cloud/testing_util/mock_opentelemetry_metrics.h" +#include "google/cloud/testing_util/status_matchers.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage_internal { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace { + +using ::google::cloud::storage::testing::canonical_errors::PermanentError; +using ::google::cloud::storage::testing::canonical_errors::TransientError; +using ::google::cloud::testing_util::AsyncSequencer; +using ::google::cloud::testing_util::MockCompletionQueueImpl; +using ::google::cloud::testing_util::MockCounter; +using ::google::cloud::testing_util::MockMeter; +using ::google::cloud::testing_util::MockMeterProvider; +using ::google::cloud::testing_util::StatusIs; +using ::testing::_; +using ::testing::AnyOf; +using ::testing::ByMove; +using ::testing::ElementsAre; +using ::testing::Eq; +using ::testing::HasSubstr; +using ::testing::NiceMock; +using ::testing::Return; + +using MetricsPtr = std::shared_ptr; +using TimerFuture = future>; +using MockRpc = google::cloud::mocks::MockAsyncStreamingReadWriteRpc< + google::storage::v2::BidiReadObjectRequest, + google::storage::v2::BidiReadObjectResponse>; + +MetricsPtr MakeMockHedgeMetrics(int expected_dispatched, int expected_won) { + opentelemetry::nostd::shared_ptr meter = + std::make_shared(); + auto const expect_counter = [&](char const* name, int expected) { + auto counter = std::make_unique>(); + EXPECT_CALL(*counter, Add(std::uint64_t{1})).Times(expected); + EXPECT_CALL(*meter, CreateUInt64Counter(Eq(name), _, _)) + .WillOnce(Return(ByMove(opentelemetry::nostd::unique_ptr< + opentelemetry::metrics::Counter>( + counter.release())))); + }; + expect_counter("storage.read_hedging.hedges_dispatched", expected_dispatched); + expect_counter("storage.read_hedging.hedge_won", expected_won); + + auto provider = std::make_shared(); + EXPECT_CALL(*provider, GetMeter).WillOnce(Return(meter)); + opentelemetry::nostd::shared_ptr + otel_provider{ + std::shared_ptr(provider)}; + return std::make_shared(otel_provider); +} + +OpenStreamResult MakeOpenResult(std::int64_t generation, + std::atomic* stream_cancels) { + auto rpc = std::make_unique>(); + ON_CALL(*rpc, Cancel).WillByDefault([stream_cancels] { + if (stream_cancels != nullptr) ++(*stream_cancels); + }); + ON_CALL(*rpc, Finish).WillByDefault([] { + return make_ready_future(Status{}); + }); + google::storage::v2::BidiReadObjectResponse response; + response.mutable_metadata()->set_generation(generation); + return OpenStreamResult{std::make_shared(std::move(rpc)), + std::move(response)}; +} + +google::storage::v2::BidiReadObjectRequest MakeInitialRequest() { + google::storage::v2::BidiReadObjectRequest req; + req.mutable_read_object_spec()->set_bucket("projects/_/buckets/test-bucket"); + req.mutable_read_object_spec()->set_object("test-object"); + return req; +} + +Status CancelledError() { + return internal::CancelledError("cancelled", GCP_ERROR_INFO()); +} + +class HedgedOpenStreamTest : public ::testing::Test { + protected: + using StepValue = StatusOr; + using ResultFuture = future>; + + void ExpectTimers(std::vector names) { + if (names.empty()) { + EXPECT_CALL(*mock_cq_, MakeRelativeTimer).Times(0); + return; + } + int const count = static_cast(names.size()); + EXPECT_CALL(*mock_cq_, MakeRelativeTimer) + .Times(count) + .WillRepeatedly( + [this, names = std::move(names)](std::chrono::nanoseconds d) { + std::size_t const idx = timer_delays_.size(); + timer_delays_.push_back( + std::chrono::duration_cast(d)); + std::string const name = + idx < names.size() ? names[idx] : std::string("ExtraTimer"); + future step = sequencer_.PushBack(name); + auto timer_promise = std::make_shared< + promise>>( + [this] { ++cancelled_timers_; }); + TimerFuture timer_future = timer_promise->get_future(); + step.then([timer_promise](future f) mutable { + if (!f.get().ok()) { + return timer_promise->set_value(CancelledError()); + } + timer_promise->set_value(std::chrono::system_clock::now()); + }); + return timer_future; + }); + } + + OpenStreamFactory SequencedFactory() { + return [this, n = std::make_shared>(0)]( + google::storage::v2::BidiReadObjectRequest const& req) { + EXPECT_EQ(req.read_object_spec().object(), "test-object"); + int const id = (*n)++; + std::string const label = + id == 0 ? "Primary" : "Hedge" + std::to_string(id); + future step = sequencer_.PushBack(label); + auto attempt_promise = + std::make_shared>>( + [this] { ++cancelled_attempts_; }); + ResultFuture out = attempt_promise->get_future(); + step.then([this, attempt_promise](future f) mutable { + StepValue val = f.get(); + if (!val) return attempt_promise->set_value(std::move(val).status()); + attempt_promise->set_value(MakeOpenResult(*val, &cancelled_streams_)); + }); + return out; + }; + } + + promise PopStep(char const* expected) { + auto [p, name] = sequencer_.PopFrontWithName(); + EXPECT_EQ(name, expected); + return std::move(p); + } + + ResultFuture RunHedgedOpen( + HedgedOpenParams params, + std::shared_ptr limiter, + MetricsPtr metrics) { + return HedgedOpenStream( + CompletionQueue(mock_cq_), SequencedFactory(), MakeInitialRequest(), + storage::LimitedErrorCountAsyncRetryPolicy(0).clone(), params, + std::move(limiter), std::move(metrics), + google::cloud::internal::MakeImmutableOptions(Options{})); + } + + static std::shared_ptr UnlimitedLimiter() { + return std::make_shared(0.0, 0.0, 0, 0); + } + + AsyncSequencer sequencer_; + std::atomic cancelled_timers_{0}; + std::atomic cancelled_attempts_{0}; + std::atomic cancelled_streams_{0}; + std::vector timer_delays_; + std::shared_ptr mock_cq_ = + std::make_shared(); +}; + +TEST_F(HedgedOpenStreamTest, FastPrimaryCancelsTimer) { + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/0, + /*expected_won=*/0); + ExpectTimers({"Timer1"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(250), 2}, + UnlimitedLimiter(), metrics); + promise primary = PopStep("Primary"); + promise timer1 = PopStep("Timer1"); + EXPECT_THAT(timer_delays_, ElementsAre(std::chrono::milliseconds(250))); + + primary.set_value(101); + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result->first_response.metadata().generation(), 101); + EXPECT_EQ(cancelled_timers_.load(), 1); + EXPECT_EQ(cancelled_attempts_.load(), 0); + + timer1.set_value(CancelledError()); +} + +TEST_F(HedgedOpenStreamTest, SlowPrimaryHedgeWinsAndCancelsPrimary) { + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/1, + /*expected_won=*/1); + ExpectTimers({"Timer1", "Timer2"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 2}, + UnlimitedLimiter(), metrics); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + promise timer2 = PopStep("Timer2"); + + hedge1.set_value(202); + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result->first_response.metadata().generation(), 202); + EXPECT_EQ(cancelled_attempts_.load(), 1); + EXPECT_EQ(cancelled_timers_.load(), 1); + + timer2.set_value(CancelledError()); + // Late-completing losing streams are immediately cancelled rather than + // leaked. + primary.set_value(999); + EXPECT_EQ(cancelled_streams_.load(), 1); +} + +TEST_F(HedgedOpenStreamTest, PrimaryWinsAfterHedgeDispatched) { + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/1, + /*expected_won=*/0); + ExpectTimers({"Timer1"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 1}, + UnlimitedLimiter(), metrics); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + + primary.set_value(1); + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result->first_response.metadata().generation(), 1); + EXPECT_EQ(cancelled_attempts_.load(), 1); + + hedge1.set_value(CancelledError()); +} + +class HedgedOpenRescueTest : public HedgedOpenStreamTest, + public ::testing::WithParamInterface {}; + +TEST_P(HedgedOpenRescueTest, PrimaryTransientOrStallErrorRescuedByHedge) { + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/1, + /*expected_won=*/1); + ExpectTimers({"Timer1"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 1}, + UnlimitedLimiter(), metrics); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + + primary.set_value(GetParam()); + hedge1.set_value(303); + + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_EQ(result->first_response.metadata().generation(), 303); +} + +INSTANTIATE_TEST_SUITE_P(PrimaryErrors, HedgedOpenRescueTest, + ::testing::Values(TransientError(), + Status(StatusCode::kCancelled, + "Stream stall timeout"))); + +class HedgedOpenPermanentAbortTest + : public HedgedOpenStreamTest, + public ::testing::WithParamInterface {}; + +TEST_P(HedgedOpenPermanentAbortTest, PermanentFailureAbortsSiblingImmediately) { + bool const primary_fails = GetParam(); + ExpectTimers({"Timer1", "Timer2"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 2}, + UnlimitedLimiter(), nullptr); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + promise timer2 = PopStep("Timer2"); + + if (primary_fails) { + primary.set_value(PermanentError()); + } else { + hedge1.set_value(PermanentError()); + } + EXPECT_THAT(pending.get(), StatusIs(PermanentError().code())); + EXPECT_EQ(cancelled_attempts_.load(), 1); + EXPECT_EQ(cancelled_timers_.load(), 1); + + timer2.set_value(CancelledError()); + if (primary_fails) { + hedge1.set_value(CancelledError()); + } else { + primary.set_value(CancelledError()); + } +} + +INSTANTIATE_TEST_SUITE_P(FailureOrigin, HedgedOpenPermanentAbortTest, + ::testing::Bool()); + +TEST_F(HedgedOpenStreamTest, AllAttemptsFailReturnsPrimaryError) { + ExpectTimers({"Timer1"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 1}, + UnlimitedLimiter(), nullptr); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + + primary.set_value(Status(StatusCode::kUnavailable, "primary unavailable")); + hedge1.set_value(Status(StatusCode::kDeadlineExceeded, "hedge deadline")); + + EXPECT_THAT(pending.get(), + StatusIs(StatusCode::kUnavailable, HasSubstr("primary"))); +} + +TEST_F(HedgedOpenStreamTest, CallerCancelCancelsAllAttemptsAndTimer) { + ExpectTimers({"Timer1", "Timer2"}); + + ResultFuture pending = RunHedgedOpen({std::chrono::milliseconds(100), 2}, + UnlimitedLimiter(), nullptr); + promise primary = PopStep("Primary"); + PopStep("Timer1").set_value(0); + promise hedge1 = PopStep("Hedge1"); + promise timer2 = PopStep("Timer2"); + + pending.cancel(); + EXPECT_EQ(cancelled_timers_.load(), 1); + EXPECT_EQ(cancelled_attempts_.load(), 2); + + timer2.set_value(CancelledError()); + primary.set_value(TransientError()); + hedge1.set_value(TransientError()); + + EXPECT_THAT(pending.get(), StatusIs(StatusCode::kCancelled)); +} + +TEST_F(HedgedOpenStreamTest, CallerCancelWithInlineAttemptCompletion) { + ExpectTimers({"Timer1"}); + promise> attempt_promise{null_promise_t{}}; + attempt_promise = promise>( + [&attempt_promise] { attempt_promise.set_value(CancelledError()); }); + OpenStreamFactory inline_cancel_factory = + [&attempt_promise](google::storage::v2::BidiReadObjectRequest const&) { + return attempt_promise.get_future(); + }; + + ResultFuture pending = HedgedOpenStream( + CompletionQueue(mock_cq_), std::move(inline_cancel_factory), + MakeInitialRequest(), + storage::LimitedErrorCountAsyncRetryPolicy(0).clone(), + {std::chrono::milliseconds(100), 1}, UnlimitedLimiter(), nullptr, + google::cloud::internal::MakeImmutableOptions(Options{})); + promise timer1 = PopStep("Timer1"); + + pending.cancel(); + EXPECT_THAT(pending.get(), StatusIs(StatusCode::kCancelled)); + timer1.set_value(CancelledError()); +} + +TEST_F(HedgedOpenStreamTest, + LimiterDenialRetriesAtMinDelayAndRespectsLifetimeBudget) { + using ms = std::chrono::milliseconds; + auto limiter = std::make_shared( + 0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/2); + MetricsPtr metrics = MakeMockHedgeMetrics(/*expected_dispatched=*/2, + /*expected_won=*/2); + ExpectTimers( + {"Call1Timer1", "Call2Timer1", "Call1Timer2", "Call2RetryTimer"}); + + ResultFuture call1 = RunHedgedOpen({ms(1), 2}, limiter, metrics); + ResultFuture call2 = RunHedgedOpen({ms(1), 2}, limiter, metrics); + promise c1_primary = PopStep("Primary"); + promise c1_timer1 = PopStep("Call1Timer1"); + promise c2_primary = PopStep("Primary"); + promise c2_timer1 = PopStep("Call2Timer1"); + + // Call 1 acquires the single concurrency slot (total 1/2) and arms Timer 2. + c1_timer1.set_value(0); + promise c1_hedge = PopStep("Hedge1"); + promise c1_timer2 = PopStep("Call1Timer2"); + + // Call 2 is denied by `max_concurrent = 1` and re-arms at the 10ms floor. + c2_timer1.set_value(0); + promise c2_retry = PopStep("Call2RetryTimer"); + EXPECT_THAT(timer_delays_, ElementsAre(ms(1), ms(1), ms(1), ms(10))); + + // Finishing Call 1's hedge releases its concurrency slot. + c1_hedge.set_value(601); + ASSERT_TRUE(call1.get().ok()); + c1_timer2.set_value(CancelledError()); + + // Call 2's retry timer acquires the freed slot and spends total budget (2/2), + // so no further timer is armed on Call 2 or on a subsequent Call 3. + c2_retry.set_value(0); + PopStep("Hedge1").set_value(602); + ASSERT_TRUE(call2.get().ok()); + + ResultFuture call3 = RunHedgedOpen({ms(1), 2}, limiter, metrics); + PopStep("Primary").set_value(603); + ASSERT_TRUE(call3.get().ok()); + + c1_primary.set_value(CancelledError()); + c2_primary.set_value(CancelledError()); +} + +TEST_F(HedgedOpenStreamTest, ClampsNegativeParamsToZero) { + // Negative `max_hedges` clamps to 0 (no timers armed). + ExpectTimers({}); + ResultFuture zero_hedges = RunHedgedOpen({std::chrono::milliseconds(-50), -3}, + UnlimitedLimiter(), nullptr); + PopStep("Primary").set_value(42); + ASSERT_TRUE(zero_hedges.get().ok()); + + // Negative `delay` clamps to 0ms. + timer_delays_.clear(); + ExpectTimers({"Timer1"}); + ResultFuture zero_delay = RunHedgedOpen({std::chrono::milliseconds(-25), 1}, + UnlimitedLimiter(), nullptr); + promise primary = PopStep("Primary"); + promise timer1 = PopStep("Timer1"); + EXPECT_THAT(timer_delays_, ElementsAre(std::chrono::milliseconds(0))); + primary.set_value(43); + ASSERT_TRUE(zero_delay.get().ok()); + timer1.set_value(CancelledError()); +} + +TEST(HedgedOpenStreamConcurrencyTest, ConcurrentCompletionRace) { + for (int iter = 0; iter != 25; ++iter) { + std::mutex gate_mu; + std::condition_variable gate_cv; + int ready_workers = 0; + bool release_workers = false; + std::atomic cancelled_streams{0}; + std::atomic attempt_seq{0}; + std::vector workers; + workers.reserve(2); + + OpenStreamFactory factory = + [&](google::storage::v2::BidiReadObjectRequest const&) { + std::int64_t const gen = ++attempt_seq; + OpenStreamResult open_result = + MakeOpenResult(gen, &cancelled_streams); + auto p = std::make_shared>>(); + future> out = p->get_future(); + { + std::lock_guard lock(gate_mu); + workers.emplace_back( + [&, p = std::move(p), res = std::move(open_result)]() mutable { + { + std::unique_lock wlock(gate_mu); + ++ready_workers; + gate_cv.notify_all(); + gate_cv.wait(wlock, [&] { return release_workers; }); + } + p->set_value(std::move(res)); + }); + } + return out; + }; + + auto mock_cq = std::make_shared(); + EXPECT_CALL(*mock_cq, MakeRelativeTimer) + .WillOnce([](std::chrono::nanoseconds) { + return make_ready_future( + StatusOr( + std::chrono::system_clock::now())); + }); + + future> pending = HedgedOpenStream( + CompletionQueue(mock_cq), std::move(factory), MakeInitialRequest(), + storage::LimitedErrorCountAsyncRetryPolicy(0).clone(), + {std::chrono::milliseconds(0), 1}, + std::make_shared(0.0, 0.0, 0, 0), + nullptr, google::cloud::internal::MakeImmutableOptions(Options{})); + + { + std::unique_lock lock(gate_mu); + gate_cv.wait(lock, [&] { return ready_workers == 2; }); + release_workers = true; + } + gate_cv.notify_all(); + for (std::thread& w : workers) w.join(); + + StatusOr result = pending.get(); + ASSERT_TRUE(result.ok()); + EXPECT_THAT(result->first_response.metadata().generation(), + AnyOf(Eq(1), Eq(2))); + // Exactly the losing attempt's `OpenStream` is cancelled, never the winner. + EXPECT_EQ(cancelled_streams.load(), 1); + } +} + +} // namespace +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage_internal +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/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 diff --git a/google/cloud/storage/internal/hedge_limiter.h b/google/cloud/storage/internal/hedge_limiter.h new file mode 100644 index 0000000000000..78827ec3dcb06 --- /dev/null +++ b/google/cloud/storage/internal/hedge_limiter.h @@ -0,0 +1,174 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H +#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H + +#include "google/cloud/storage/version.h" +#include "google/cloud/internal/clock.h" +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace internal { + +/** + * Enforces connection-wide rate, concurrency, and lifetime limits on + * speculative hedged requests. + * + * Values `<= 0` disable the corresponding limit; `capacity` is clamped to at + * least `1.0` so fractional rate limits (`0.0 < rate_limit < 1.0`) can still + * issue hedges once refilled. + */ +class HedgeLimiter { + public: + using Clock = google::cloud::internal::SteadyClock; + + HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent, + std::int64_t max_total) + : HedgeLimiter(rate_limit, capacity, max_concurrent, max_total, + std::make_shared()) {} + + /// @p clock must not be null. Tests inject `testing_util::FakeSteadyClock`. + HedgeLimiter(double rate_limit, double capacity, std::int64_t max_concurrent, + std::int64_t max_total, std::shared_ptr clock) + : clock_(std::move(clock)), + rate_limit_(rate_limit), + tokens_capacity_((std::max)(1.0, capacity)), + tokens_((std::max)(1.0, capacity)), + last_refill_(clock_->Now()), + max_concurrent_hedges_(max_concurrent), + max_total_hedges_(max_total) {} + + ~HedgeLimiter() = default; + + HedgeLimiter(HedgeLimiter const&) = delete; + HedgeLimiter& operator=(HedgeLimiter const&) = delete; + HedgeLimiter(HedgeLimiter&&) = delete; + HedgeLimiter& operator=(HedgeLimiter&&) = delete; + + /** + * Reserves capacity for one hedged request. + * + * On success the caller *must* eventually call `ReleaseHedgeSlot()`. + */ + bool TryAcquireHedgeToken() { + // Once the lifetime budget is spent, deny with a single atomic load. + if (IsTotalBudgetSpent()) return false; + + // Gate 1: the ceiling on concurrently active hedges. When + // max_concurrent_hedges_ <= 0, concurrency limiting is disabled. + if (max_concurrent_hedges_ > 0) { + std::int64_t current = + active_concurrent_hedges_.load(std::memory_order_relaxed); + do { + if (current >= max_concurrent_hedges_) return false; + } while (!active_concurrent_hedges_.compare_exchange_weak( + current, current + 1, std::memory_order_relaxed)); + } + + // Gate 2: the rate limit on new hedges (token bucket). When + // rate_limit_ <= 0.0, rate limiting is disabled. + if (rate_limit_ > 0.0) { + std::lock_guard lock(limiter_mutex_); + Refill(); + if (tokens_ < 1.0) { + ReleaseHedgeSlot(); + return false; + } + tokens_ -= 1.0; + } + + // Gate 3: the lifetime budget. Checked last so the counter only moves for + // a hedge that is granted, which keeps `IsTotalBudgetSpent()` exact. If + // another thread took the last unit since the check above, return what the + // earlier gates reserved. When max_total_hedges_ <= 0, the lifetime limit + // is disabled. + if (max_total_hedges_ > 0) { + std::int64_t granted = + total_hedges_granted_.load(std::memory_order_relaxed); + do { + if (granted >= max_total_hedges_) { + ReleaseHedgeSlot(); + ReturnRateToken(); + return false; + } + } while (!total_hedges_granted_.compare_exchange_weak( + granted, granted + 1, std::memory_order_relaxed)); + } + + return true; + } + + /// Releases the concurrency slot. The lifetime budget is never returned. + void ReleaseHedgeSlot() { + if (max_concurrent_hedges_ > 0) { + active_concurrent_hedges_.fetch_sub(1, std::memory_order_relaxed); + } + } + + /// Returns true once the lifetime budget is spent. No hedge is granted after + /// that, so callers can skip racing altogether. + bool IsTotalBudgetSpent() const { + return max_total_hedges_ > 0 && + total_hedges_granted_.load(std::memory_order_relaxed) >= + max_total_hedges_; + } + + private: + void ReturnRateToken() { + if (rate_limit_ <= 0.0) return; + std::lock_guard lock(limiter_mutex_); + tokens_ = (std::min)(tokens_capacity_, tokens_ + 1.0); + } + + void Refill() { + Clock::time_point const now = clock_->Now(); + double const elapsed = + std::chrono::duration_cast>(now - + last_refill_) + .count(); + last_refill_ = now; + tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_); + } + + std::shared_ptr const clock_; + double const rate_limit_; + double const tokens_capacity_; + double tokens_; + Clock::time_point last_refill_; + std::mutex limiter_mutex_; + + std::int64_t const max_concurrent_hedges_; + std::atomic active_concurrent_hedges_{0}; + + std::int64_t const max_total_hedges_; + std::atomic total_hedges_granted_{0}; +}; + +} // namespace internal +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage +} // namespace cloud +} // namespace google + +#endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGE_LIMITER_H diff --git a/google/cloud/storage/internal/hedge_limiter_test.cc b/google/cloud/storage/internal/hedge_limiter_test.cc new file mode 100644 index 0000000000000..f987efcbfdaea --- /dev/null +++ b/google/cloud/storage/internal/hedge_limiter_test.cc @@ -0,0 +1,180 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#include "google/cloud/storage/internal/hedge_limiter.h" +#include "google/cloud/testing_util/fake_clock.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace google { +namespace cloud { +namespace storage { +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN +namespace internal { +namespace { + +using ::google::cloud::testing_util::FakeSteadyClock; +using ::testing::Eq; + +TEST(HedgeLimiterTest, MaxConcurrentHedgesLimit) { + HedgeLimiter limiter(0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/0); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + limiter.ReleaseHedgeSlot(); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, RateLimiter) { + // 5 tokens/second (one token per 200ms), burst capacity of 2 tokens. + auto clock = std::make_shared(); + HedgeLimiter limiter(5.0, 2.0, 0, 0, clock); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + // Half-token step margins avoid IEEE-754 boundary rounding sensitivity. + clock->AdvanceTime(std::chrono::milliseconds(100)); // +0.5 token + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + clock->AdvanceTime(std::chrono::milliseconds(200)); // +1.0 token => 1.5 + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + // Refill is clamped at burst capacity (2 tokens). + clock->AdvanceTime(std::chrono::seconds(10)); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, FractionalRateLimiter) { + // 0.5 tokens/second (one token per 2s); capacity 0.5 clamps to floor 1.0. + auto clock = std::make_shared(); + HedgeLimiter limiter(0.5, 0.5, 0, 0, clock); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + clock->AdvanceTime(std::chrono::seconds(1)); // +0.5 token + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + clock->AdvanceTime(std::chrono::seconds(2)); // +1.0 token => clamped to 1.0 + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, ZeroRateLimitDisablesRateLimiting) { + HedgeLimiter limiter(0.0, 0.0, 0, 0); + + for (int i = 0; i < 100; ++i) { + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + } +} + +TEST(HedgeLimiterTest, MaxTotalHedgesLimit) { + HedgeLimiter limiter(0.0, 0.0, 0, /*max_total=*/3); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.IsTotalBudgetSpent()); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.IsTotalBudgetSpent()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + + // Releasing a hedge frees its concurrency slot, never its lifetime budget. + limiter.ReleaseHedgeSlot(); + limiter.ReleaseHedgeSlot(); + limiter.ReleaseHedgeSlot(); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, ConcurrencyDenialDoesNotSpendTotalBudget) { + HedgeLimiter limiter(0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/2); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.IsTotalBudgetSpent()); + limiter.ReleaseHedgeSlot(); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + limiter.ReleaseHedgeSlot(); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); +} + +TEST(HedgeLimiterTest, RateLimitDenialDoesNotSpendTotalBudget) { + auto clock = std::make_shared(); + HedgeLimiter limiter(0.001, 1.0, 0, /*max_total=*/2, clock); + + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.TryAcquireHedgeToken()); + EXPECT_FALSE(limiter.IsTotalBudgetSpent()); + + clock->AdvanceTime(std::chrono::seconds(1500)); + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + EXPECT_TRUE(limiter.IsTotalBudgetSpent()); +} + +TEST(HedgeLimiterTest, ZeroMaxTotalDisablesLifetimeLimit) { + HedgeLimiter limiter(0.0, 0.0, 0, /*max_total=*/0); + + for (int i = 0; i < 100; ++i) { + EXPECT_TRUE(limiter.TryAcquireHedgeToken()); + } + EXPECT_FALSE(limiter.IsTotalBudgetSpent()); +} + +TEST(HedgeLimiterTest, MaxTotalHedgesUnderContention) { + std::int64_t const max_total = 100; + // A rate limit that never runs out, so threads racing for the last unit of + // budget also exercise returning the rate token. + HedgeLimiter limiter(1e9, 1e9, /*max_concurrent=*/4, max_total); + + std::atomic granted{0}; + std::vector threads; + threads.reserve(8); + for (int t = 0; t != 8; ++t) { + threads.emplace_back([&limiter, &granted] { + for (int i = 0; i != 1000; ++i) { + if (!limiter.TryAcquireHedgeToken()) continue; + ++granted; + limiter.ReleaseHedgeSlot(); + } + }); + } + for (std::thread& t : threads) t.join(); + + while (limiter.TryAcquireHedgeToken()) { + ++granted; + limiter.ReleaseHedgeSlot(); + } + EXPECT_THAT(granted.load(), Eq(max_total)); + EXPECT_TRUE(limiter.IsTotalBudgetSpent()); +} + +} // namespace +} // namespace internal +GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END +} // namespace storage +} // namespace cloud +} // namespace google diff --git a/google/cloud/storage/internal/hedging_thread_pool.h b/google/cloud/storage/internal/hedging_thread_pool.h index dffceb8eca0b7..f421611ab000b 100644 --- a/google/cloud/storage/internal/hedging_thread_pool.h +++ b/google/cloud/storage/internal/hedging_thread_pool.h @@ -15,11 +15,11 @@ #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGING_THREAD_POOL_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_STORAGE_INTERNAL_HEDGING_THREAD_POOL_H +#include "google/cloud/storage/internal/hedge_limiter.h" #include "google/cloud/storage/version.h" #include -#include -#include #include +#include #include #include #include @@ -137,13 +137,9 @@ class ThreadPool { /** * Coordinates and bounds speculative hedged requests across a storage client. * - * Hedged requests are gated by `TryAcquireHedgeToken()`, which enforces three - * limits: a maximum number of hedges over the life of the pool (when - * `max_total > 0`), a maximum number of concurrently active hedges (when - * `max_concurrent > 0`), and a maximum rate of new hedges per second via a - * token bucket (when `rate_limit > 0.0`). Setting `rate_limit <= 0.0` disables - * rate limiting (unlimited hedges per second). Task execution is dispatched - * onto a dedicated internal `ThreadPool`. + * Hedged requests are gated by `TryAcquireHedgeToken()` (delegated to + * `HedgeLimiter`), and task execution is dispatched onto a dedicated internal + * `ThreadPool`. */ class HedgingThreadPool { public: @@ -162,12 +158,7 @@ class HedgingThreadPool { */ HedgingThreadPool(std::size_t max_threads, double rate_limit, double capacity, std::int64_t max_concurrent, std::int64_t max_total) - : rate_limit_(rate_limit), - tokens_capacity_((std::max)(1.0, capacity)), - tokens_((std::max)(1.0, capacity)), - last_refill_(std::chrono::steady_clock::now()), - max_concurrent_hedges_(max_concurrent), - max_total_hedges_(max_total), + : limiter_(rate_limit, capacity, max_concurrent, max_total), pool_(max_threads) {} ~HedgingThreadPool() = default; @@ -191,103 +182,19 @@ class HedgingThreadPool { * * On success the caller *must* eventually call `ReleaseHedgeSlot()`. */ - bool TryAcquireHedgeToken() { - // Once the lifetime budget is spent, deny with a single atomic load. - if (IsTotalBudgetSpent()) return false; - - // Gate 1: the ceiling on concurrently active hedges. When - // max_concurrent_hedges_ <= 0, concurrency limiting is disabled. - if (max_concurrent_hedges_ > 0) { - std::int64_t current = - active_concurrent_hedges_.load(std::memory_order_relaxed); - do { - if (current >= max_concurrent_hedges_) return false; - } while (!active_concurrent_hedges_.compare_exchange_weak( - current, current + 1, std::memory_order_relaxed)); - } - - // Gate 2: the rate limit on new hedges (token bucket). When - // rate_limit_ <= 0.0, rate limiting is disabled. - if (rate_limit_ > 0.0) { - std::lock_guard lock(limiter_mutex_); - Refill(); - if (tokens_ < 1.0) { - ReleaseHedgeSlot(); - return false; - } - tokens_ -= 1.0; - } - - // Gate 3: the lifetime budget. Checked last so the counter only moves for - // a hedge that is granted, which keeps `IsTotalBudgetSpent()` exact. If - // another thread took the last unit since the check above, return what - // the earlier gates reserved. When max_total_hedges_ <= 0, the lifetime - // limit is disabled. - if (max_total_hedges_ > 0) { - std::int64_t granted = - total_hedges_granted_.load(std::memory_order_relaxed); - do { - if (granted >= max_total_hedges_) { - ReleaseHedgeSlot(); - ReturnRateToken(); - return false; - } - } while (!total_hedges_granted_.compare_exchange_weak( - granted, granted + 1, std::memory_order_relaxed)); - } - - return true; - } + bool TryAcquireHedgeToken() { return limiter_.TryAcquireHedgeToken(); } /// Releases the concurrency slot. The lifetime budget is never returned. - void ReleaseHedgeSlot() { - if (max_concurrent_hedges_ > 0) { - active_concurrent_hedges_.fetch_sub(1, std::memory_order_relaxed); - } - } + void ReleaseHedgeSlot() { limiter_.ReleaseHedgeSlot(); } /// Returns true once the lifetime budget is spent. No hedge is granted after /// that, so callers can skip racing altogether. - bool IsTotalBudgetSpent() const { - return max_total_hedges_ > 0 && - total_hedges_granted_.load(std::memory_order_relaxed) >= - max_total_hedges_; - } + bool IsTotalBudgetSpent() const { return limiter_.IsTotalBudgetSpent(); } std::size_t max_threads() const { return pool_.max_threads(); } private: - void ReturnRateToken() { - if (rate_limit_ <= 0.0) return; - std::lock_guard lock(limiter_mutex_); - tokens_ = (std::min)(tokens_capacity_, tokens_ + 1.0); - } - - void Refill() { - std::chrono::steady_clock::time_point const now = - std::chrono::steady_clock::now(); - double const elapsed = - std::chrono::duration_cast>(now - - last_refill_) - .count(); - last_refill_ = now; - tokens_ = (std::min)(tokens_capacity_, tokens_ + elapsed * rate_limit_); - } - - // Token bucket rate limiter. A rate_limit_ <= 0.0 disables rate limiting. - double rate_limit_; - double tokens_capacity_; - double tokens_; - std::chrono::steady_clock::time_point last_refill_; - std::mutex limiter_mutex_; - - // Concurrency limiter. A max_concurrent_hedges_ <= 0 disables limit. - std::int64_t const max_concurrent_hedges_; - std::atomic active_concurrent_hedges_{0}; - - // Lifetime limiter. A max_total_hedges_ <= 0 disables limit. - std::int64_t const max_total_hedges_; - std::atomic total_hedges_granted_{0}; + HedgeLimiter limiter_; // Declared last so the pool (and its worker threads) is destroyed and joined // first, before any other member variables are torn down. diff --git a/google/cloud/storage/internal/hedging_thread_pool_test.cc b/google/cloud/storage/internal/hedging_thread_pool_test.cc index 716183f4d06c5..f49ab725928d4 100644 --- a/google/cloud/storage/internal/hedging_thread_pool_test.cc +++ b/google/cloud/storage/internal/hedging_thread_pool_test.cc @@ -16,12 +16,9 @@ #include #include #include -#include #include -#include #include #include -#include #include namespace google { @@ -139,143 +136,18 @@ TEST(HedgingThreadPoolTest, EnqueueAndExecute) { f2.get(); } -TEST(HedgingThreadPoolTest, MaxConcurrentHedgesLimit) { - // Only one concurrent hedge allowed. - HedgingThreadPool pool(5, 0.0, 0.0, 1, 0); +TEST(HedgingThreadPoolTest, DelegatesToHedgeLimiter) { + HedgingThreadPool pool(2, 0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/1); - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - // Fails because one hedge is active. - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - - pool.ReleaseHedgeSlot(); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); -} - -TEST(HedgingThreadPoolTest, RateLimiter) { - // A rate limit of 5.0 tokens per second (one token per 200ms), and a burst - // capacity of 2 tokens. - HedgingThreadPool pool(5, 5.0, 2.0, 0, 0); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - // The burst capacity is exhausted. - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - - // The refill is time-based, there is no way to inject a fake clock. Wait - // longer than one token's refill period, with margin for slow machines. - std::this_thread::sleep_for(std::chrono::milliseconds(250)); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); -} - -TEST(HedgingThreadPoolTest, FractionalRateLimiter) { - // A rate limit of 0.5 tokens per second (one token per 2 seconds). - // The capacity is set to 0.5, which the pool must clamp to a floor of 1.0. - HedgingThreadPool pool(5, 0.5, 0.5, 0, 0); - - // Since capacity is clamped to 1.0, we must be able to acquire at least one - // token. - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - EXPECT_FALSE(pool.TryAcquireHedgeToken()); -} - -TEST(HedgingThreadPoolTest, ZeroRateLimitDisablesRateLimiting) { - // A rate limit of 0.0 disables rate limiting, allowing unlimited - // acquisitions. - HedgingThreadPool pool(5, 0.0, 0.0, 0, 0); - - for (int i = 0; i < 100; ++i) { - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - } -} - -TEST(HedgingThreadPoolTest, MaxTotalHedgesLimit) { - HedgingThreadPool pool(5, 0.0, 0.0, 0, /*max_total=*/3); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - EXPECT_TRUE(pool.TryAcquireHedgeToken()); EXPECT_FALSE(pool.IsTotalBudgetSpent()); EXPECT_TRUE(pool.TryAcquireHedgeToken()); EXPECT_TRUE(pool.IsTotalBudgetSpent()); EXPECT_FALSE(pool.TryAcquireHedgeToken()); - // Releasing a hedge frees its concurrency slot, but never returns the - // lifetime budget. - pool.ReleaseHedgeSlot(); - pool.ReleaseHedgeSlot(); - pool.ReleaseHedgeSlot(); - EXPECT_FALSE(pool.TryAcquireHedgeToken()); -} - -TEST(HedgingThreadPoolTest, ConcurrencyDenialDoesNotSpendTotalBudget) { - HedgingThreadPool pool(5, 0.0, 0.0, /*max_concurrent=*/1, /*max_total=*/2); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - // Denied by the concurrency limit, so this hedge is never sent. - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - EXPECT_FALSE(pool.IsTotalBudgetSpent()); - pool.ReleaseHedgeSlot(); - - // The denials above did not spend the budget, so one hedge is left. - EXPECT_TRUE(pool.TryAcquireHedgeToken()); pool.ReleaseHedgeSlot(); EXPECT_FALSE(pool.TryAcquireHedgeToken()); } -TEST(HedgingThreadPoolTest, RateLimitDenialDoesNotSpendTotalBudget) { - // A burst capacity of one token, and a refill (one token per 1000 seconds) - // too slow to add a token while the test runs. - HedgingThreadPool pool(5, 0.001, 1.0, 0, /*max_total=*/2); - - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - // Denied by the rate limit, so this hedge is never sent. - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - EXPECT_FALSE(pool.TryAcquireHedgeToken()); - // Only the first hedge spent the budget. - EXPECT_FALSE(pool.IsTotalBudgetSpent()); -} - -TEST(HedgingThreadPoolTest, ZeroMaxTotalDisablesLifetimeLimit) { - HedgingThreadPool pool(5, 0.0, 0.0, 0, /*max_total=*/0); - - for (int i = 0; i < 100; ++i) { - EXPECT_TRUE(pool.TryAcquireHedgeToken()); - } - EXPECT_FALSE(pool.IsTotalBudgetSpent()); -} - -TEST(HedgingThreadPoolTest, MaxTotalHedgesUnderContention) { - std::int64_t const max_total = 100; - // A rate limit that never runs out, so threads racing for the last unit of - // budget also exercise returning the rate token. - HedgingThreadPool pool(1, 1e9, 1e9, /*max_concurrent=*/4, max_total); - - std::atomic granted{0}; - std::vector threads; - for (int t = 0; t != 8; ++t) { - threads.emplace_back([&pool, &granted] { - for (int i = 0; i != 1000; ++i) { - if (!pool.TryAcquireHedgeToken()) continue; - ++granted; - pool.ReleaseHedgeSlot(); - } - }); - } - for (auto& t : threads) t.join(); - - // Spend whatever budget the threads left, so the count below does not depend - // on how the threads were scheduled. If contention ever over-granted, or a - // hedge denied by an earlier gate spent budget, the total is off. - while (pool.TryAcquireHedgeToken()) { - ++granted; - pool.ReleaseHedgeSlot(); - } - EXPECT_THAT(granted.load(), Eq(max_total)); - EXPECT_TRUE(pool.IsTotalBudgetSpent()); -} - TEST(HedgingThreadPoolTest, SafeDestructionOnWorkerThread) { TestSafeDestructionOnWorkerThread( std::make_shared(1, 0.0, 0.0, 0, 0)); diff --git a/google/cloud/storage/options.h b/google/cloud/storage/options.h index ff179dc79eccc..0a85b954d7c77 100644 --- a/google/cloud/storage/options.h +++ b/google/cloud/storage/options.h @@ -35,21 +35,34 @@ 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 connection-wide `ReadHedgeRateLimitOption`, + * `MaxConcurrentHedgesOption`, and `MaxTotalHedgesOption`, which are read at + * client creation time only). Individual calls may opt out via + * `EnableReadHedgingOption(false)` or `MaxReadHedgesOption(0)`, or override + * `ReadHedgeDelayOption` and `MaxReadHedgesOption`. Any initial read ranges + * passed to `AsyncClient::Open()` (`storage::AsyncClient::InitialReadRanges`) + * 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: * `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 +97,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 +124,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 +137,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 +150,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 +173,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 +188,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 { diff --git a/google/cloud/storage/storage_client_grpc_unit_tests.bzl b/google/cloud/storage/storage_client_grpc_unit_tests.bzl index d3fbed0e8e840..207da05c56197 100644 --- a/google/cloud/storage/storage_client_grpc_unit_tests.bzl +++ b/google/cloud/storage/storage_client_grpc_unit_tests.bzl @@ -40,6 +40,7 @@ storage_client_grpc_unit_tests = [ "internal/async/connection_tracing_test.cc", "internal/async/default_options_test.cc", "internal/async/handle_redirect_error_test.cc", + "internal/async/hedged_open_stream_test.cc", "internal/async/insert_object_test.cc", "internal/async/multi_stream_manager_test.cc", "internal/async/object_descriptor_connection_tracing_test.cc", diff --git a/google/cloud/storage/storage_client_unit_tests.bzl b/google/cloud/storage/storage_client_unit_tests.bzl index e646a81293431..1ca32e963b028 100644 --- a/google/cloud/storage/storage_client_unit_tests.bzl +++ b/google/cloud/storage/storage_client_unit_tests.bzl @@ -67,6 +67,7 @@ storage_client_unit_tests = [ "internal/hash_function_impl_test.cc", "internal/hash_validator_test.cc", "internal/hash_values_test.cc", + "internal/hedge_limiter_test.cc", "internal/hedged_object_read_source_test.cc", "internal/hedged_read_metrics_test.cc", "internal/hedging_thread_pool_test.cc",