From 3caed62abd890f2f520bbdeaf86a37ac887422c4 Mon Sep 17 00:00:00 2001 From: Gauri Kalra Date: Thu, 3 Dec 2026 05:37:00 +0000 Subject: [PATCH 1/3] fix(storage): complete active ranges when ObjectDescriptorImpl is cancelled --- .../cloud/storage/async/object_descriptor.h | 11 + .../storage/internal/async/connection_impl.cc | 8 +- .../async/connection_impl_open_test.cc | 86 +++ .../internal/async/multi_stream_manager.h | 19 + .../async/multi_stream_manager_test.cc | 59 ++ .../internal/async/object_descriptor_impl.cc | 43 +- .../internal/async/object_descriptor_impl.h | 17 +- .../async/object_descriptor_impl_test.cc | 625 +++++++++++++++++- .../storage/internal/async/read_range_test.cc | 12 + 9 files changed, 831 insertions(+), 49 deletions(-) diff --git a/google/cloud/storage/async/object_descriptor.h b/google/cloud/storage/async/object_descriptor.h index 91ba48abfd01d..a7ab9d42c0734 100644 --- a/google/cloud/storage/async/object_descriptor.h +++ b/google/cloud/storage/async/object_descriptor.h @@ -35,6 +35,17 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN * * Applications use an `ObjectDescriptor` to perform multiple reads on the same * Google Cloud Storage object. + * + * Destroying an `ObjectDescriptor` cancels any unfinished reads started from + * it. Each affected `AsyncReader` returns any data received before + * cancellation, followed by `StatusCode::kCancelled`. To receive all data, keep + * the `ObjectDescriptor` alive until every `AsyncReader` started from it + * returns its final status. + * + * Cancelled reads complete on the client's completion queue, like any other + * read. If that queue has already been shut down (for example, via + * `CompletionQueue::Shutdown()` or because the owning `AsyncClient` was + * destroyed), they complete on the thread that destroys the descriptor. */ class ObjectDescriptor { public: diff --git a/google/cloud/storage/internal/async/connection_impl.cc b/google/cloud/storage/internal/async/connection_impl.cc index 40b536c920906..ea510ec2fe576 100644 --- a/google/cloud/storage/internal/async/connection_impl.cc +++ b/google/cloud/storage/internal/async/connection_impl.cc @@ -344,7 +344,8 @@ AsyncConnectionImpl::Open(OpenParams p) { auto pending = factory(std::move(initial_request)); using ReturnType = std::shared_ptr; - return pending.then([rp = std::move(resume_policy), fa = std::move(factory), + return pending.then([cq = cq_, rp = std::move(resume_policy), + fa = std::move(factory), qfa = std::move(clean_resume_factory), rs = std::move(p.read_spec), options = std::move(p.options), refresh = refresh_]( @@ -367,8 +368,9 @@ AsyncConnectionImpl::Open(OpenParams p) { }); }; auto impl = std::make_shared( - std::move(rp), std::move(fa), std::move(qfa), std::move(rs), - std::move(result->stream), std::move(options), std::move(transport_ok)); + std::move(cq), std::move(rp), std::move(fa), std::move(qfa), + std::move(rs), std::move(result->stream), std::move(options), + std::move(transport_ok)); impl->Start(std::move(result->first_response)); return ReturnType(impl); }); 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..87a0ade7de7a0 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,9 @@ #include "absl/strings/match.h" #include #include +#include #include +#include #include #include #include @@ -73,6 +75,7 @@ using ::testing::NotNull; using ::testing::Optional; using ::testing::Pair; using ::testing::SizeIs; +using ::testing::VariantWith; using BidiReadStream = google::cloud::AsyncStreamingReadWriteRpc< google::storage::v2::BidiReadObjectRequest, @@ -908,6 +911,89 @@ TEST(AsyncConnectionImplTest, OpenWithReadRanges) { next.first.set_value(true); } +/// @test Verify that `AsyncConnectionImpl::Open()` passes its completion queue +/// to the `ObjectDescriptorImpl` it creates, so destroying the descriptor +/// schedules cancellation of active range reads on that queue. +TEST(AsyncConnectionImplTest, OpenPassesCompletionQueueToDescriptor) { + AsyncSequencer sequencer; + auto mock = std::make_shared(); + EXPECT_CALL(*mock, AsyncBidiReadObject) + .WillOnce([&sequencer](CompletionQueue const&, + std::shared_ptr const&, + google::cloud::internal::ImmutableOptions const&) { + auto stream = std::make_unique>(); + ON_CALL(*stream, Start).WillByDefault(InvokeWithoutArgs([] { + return make_ready_future(true); + })); + ON_CALL(*stream, Write).WillByDefault([](auto const&, auto) { + return make_ready_future(true); + }); + ON_CALL(*stream, Read) + .WillByDefault(InvokeWithoutArgs([&sequencer, + read_count = 0]() mutable { + using Response = google::storage::v2::BidiReadObjectResponse; + // The first read satisfies Open(); the second stays parked + // until the descriptor is destroyed. + if (read_count++ == 0) { + return make_ready_future(std::optional(Response{})); + } + return sequencer.PushBack("Read").then( + [](auto) { return std::optional(); }); + })); + ON_CALL(*stream, Finish).WillByDefault(InvokeWithoutArgs([] { + return make_ready_future(Status{}); + })); + return std::unique_ptr(std::move(stream)); + }); + + auto mock_cq = std::make_shared(); + promise> timer_promise; + bool timer_started = false; + EXPECT_CALL(*mock_cq, MakeRelativeTimer(std::chrono::nanoseconds(0))) + .WillOnce([&timer_started, &timer_promise] { + timer_started = true; + return timer_promise.get_future(); + }); + + auto connection = std::make_shared( + CompletionQueue(mock_cq), std::shared_ptr(), mock, + TestOptions( + Options{}.set(false))); + + google::storage::v2::BidiReadObjectSpec request; + request.set_bucket("test-only-invalid"); + request.set_object("test-object"); + StatusOr> opened = + connection->Open({std::move(request), connection->options()}).get(); + ASSERT_THAT(opened, IsOkAndHolds(NotNull())); + std::shared_ptr descriptor = + *std::move(opened); + + std::unique_ptr reader = + descriptor->Read({/*start=*/0, /*length=*/1024}); + future pending_read = + reader->Read(); + ASSERT_FALSE(pending_read.is_ready()); + ASSERT_FALSE(timer_started); + + descriptor.reset(); + EXPECT_TRUE(timer_started); + // Cancellation waits for the connection's completion queue timer rather than + // running inline on the destroying thread. + EXPECT_FALSE(pending_read.is_ready()); + + timer_promise.set_value(std::chrono::system_clock::now()); + ASSERT_TRUE(pending_read.is_ready()); + EXPECT_THAT(pending_read.get(), + VariantWith(StatusIs(StatusCode::kCancelled))); + + // Release the parked read so the stream winds down before mocks are + // destroyed. + std::pair, std::string> next = sequencer.PopFrontWithName(); + EXPECT_EQ(next.second, "Read"); + next.first.set_value(false); +} + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal diff --git a/google/cloud/storage/internal/async/multi_stream_manager.h b/google/cloud/storage/internal/async/multi_stream_manager.h index 876f228d5ada3..770783455f14a 100644 --- a/google/cloud/storage/internal/async/multi_stream_manager.h +++ b/google/cloud/storage/internal/async/multi_stream_manager.h @@ -23,6 +23,8 @@ #include #include #include +#include +#include namespace google { namespace cloud { @@ -139,6 +141,23 @@ class MultiStreamManager { } } + // Detaches and returns all active ranges across all streams without + // notifying them. + // + // Unlike `RemoveStreamAndNotifyRanges()`, this leaves the streams in place + // and defers range notifications so the caller can invoke them after + // releasing its mutex. + std::vector> TakeActiveRanges() { + std::vector> ranges; + for (Stream& stream : streams_) { + for (auto& [id, range] : stream.active_ranges) { + ranges.push_back(std::move(range)); + } + stream.active_ranges.clear(); + } + return ranges; + } + void MoveActiveRanges(StreamIterator from, StreamIterator to) { to->active_ranges = std::move(from->active_ranges); } diff --git a/google/cloud/storage/internal/async/multi_stream_manager_test.cc b/google/cloud/storage/internal/async/multi_stream_manager_test.cc index d3dd69c9ef3da..c7983cd9e95a9 100644 --- a/google/cloud/storage/internal/async/multi_stream_manager_test.cc +++ b/google/cloud/storage/internal/async/multi_stream_manager_test.cc @@ -16,6 +16,7 @@ #include #include #include +#include namespace google { namespace cloud { @@ -173,6 +174,64 @@ TEST(MultiStreamManagerTest, CancelAllInvokesCancel) { EXPECT_EQ(s2->cancelled, 1); } +/// @test Verify `TakeActiveRanges()` returns the active ranges from all +/// streams. +TEST(MultiStreamManagerTest, TakeActiveRangesReturnsRangesOfAllStreams) { + Manager mgr = MultiStreamManagerTest::MakeManager(); + auto r1 = std::make_shared(); + auto r2 = std::make_shared(); + auto r3 = std::make_shared(); + mgr.GetFirstStream()->active_ranges.emplace(11, r1); + auto second = mgr.AddStream(std::make_shared()); + second->active_ranges.emplace(22, r2); + second->active_ranges.emplace(33, r3); + + std::vector> const ranges = mgr.TakeActiveRanges(); + + EXPECT_THAT(ranges, ::testing::UnorderedElementsAre(r1, r2, r3)); +} + +/// @test Verify `TakeActiveRanges()` detaches active ranges without notifying +/// them and leaves all streams in place. +TEST(MultiStreamManagerTest, + TakeActiveRangesDetachesWithoutNotifyingAndKeepsStreams) { + Manager mgr = MultiStreamManagerTest::MakeManager(); + auto r1 = std::make_shared(); + auto r2 = std::make_shared(); + auto first = mgr.GetFirstStream(); + first->active_ranges.emplace(11, r1); + auto second = mgr.AddStream(std::make_shared()); + second->active_ranges.emplace(22, r2); + + (void)mgr.TakeActiveRanges(); + + EXPECT_EQ(mgr.Size(), 2U); + EXPECT_THAT(first->active_ranges, ::testing::IsEmpty()); + EXPECT_THAT(second->active_ranges, ::testing::IsEmpty()); + EXPECT_EQ(r1->finished, 0); + EXPECT_EQ(r2->finished, 0); + EXPECT_THAT(mgr.TakeActiveRanges(), ::testing::IsEmpty()); +} + +/// @test Verify `TakeActiveRanges()` returns an empty vector when no stream +/// has active ranges. +TEST(MultiStreamManagerTest, TakeActiveRangesReturnsEmptyWithoutRanges) { + Manager mgr = MultiStreamManagerTest::MakeManager(); + mgr.AddStream(std::make_shared()); + + EXPECT_THAT(mgr.TakeActiveRanges(), ::testing::IsEmpty()); +} + +/// @test Verify `TakeActiveRanges()` returns an empty vector when no streams +/// remain. +TEST(MultiStreamManagerTest, TakeActiveRangesReturnsEmptyWhenNoStreamsRemain) { + Manager mgr = MultiStreamManagerTest::MakeManager(); + mgr.RemoveStreamAndNotifyRanges(mgr.GetFirstStream(), Status{}); + ASSERT_TRUE(mgr.Empty()); + + EXPECT_THAT(mgr.TakeActiveRanges(), ::testing::IsEmpty()); +} + TEST(MultiStreamManagerTest, ReuseIdleStreamToFrontMovesElement) { auto mgr = MultiStreamManagerTest::MakeManager(); // Capture the factory-created stream pointer (initial element) diff --git a/google/cloud/storage/internal/async/object_descriptor_impl.cc b/google/cloud/storage/internal/async/object_descriptor_impl.cc index 536ee22cb1b1a..947eb566e5944 100644 --- a/google/cloud/storage/internal/async/object_descriptor_impl.cc +++ b/google/cloud/storage/internal/async/object_descriptor_impl.cc @@ -30,13 +30,16 @@ #include "google/cloud/storage/internal/retry_logging.h" #include "google/cloud/storage/options.h" #include "google/cloud/grpc_error_delegate.h" +#include "google/cloud/internal/make_status.h" #include "google/cloud/internal/opentelemetry.h" #include "google/rpc/status.pb.h" #include +#include #include #include #include #include +#include namespace google { namespace cloud { @@ -69,7 +72,7 @@ std::string_view CacheStatusToString(InitialReadRangesCacheStatus status) { } // namespace ObjectDescriptorImpl::ObjectDescriptorImpl( - std::unique_ptr resume_policy, + CompletionQueue cq, std::unique_ptr resume_policy, OpenStreamFactory make_stream, google::storage::v2::BidiReadObjectSpec read_object_spec, std::shared_ptr stream, Options options, @@ -77,18 +80,19 @@ ObjectDescriptorImpl::ObjectDescriptorImpl( // An empty clean-resume factory means "use `make_stream` for those // re-opens too", i.e. every re-open behaves the same way, including // whether it reports its retries. - : ObjectDescriptorImpl(std::move(resume_policy), std::move(make_stream), - OpenStreamFactory{}, std::move(read_object_spec), - std::move(stream), std::move(options), - std::move(transport_ok)) {} + : ObjectDescriptorImpl(std::move(cq), std::move(resume_policy), + std::move(make_stream), OpenStreamFactory{}, + std::move(read_object_spec), std::move(stream), + std::move(options), std::move(transport_ok)) {} ObjectDescriptorImpl::ObjectDescriptorImpl( - std::unique_ptr resume_policy, + CompletionQueue cq, std::unique_ptr resume_policy, OpenStreamFactory make_stream, OpenStreamFactory make_clean_resume_stream, google::storage::v2::BidiReadObjectSpec read_object_spec, std::shared_ptr stream, Options options, std::function transport_ok) - : resume_policy_prototype_(std::move(resume_policy)), + : cq_(std::move(cq)), + resume_policy_prototype_(std::move(resume_policy)), make_stream_(std::move(make_stream)), make_clean_resume_stream_(std::move(make_clean_resume_stream)), read_object_spec_(std::move(read_object_spec)), @@ -169,8 +173,31 @@ void ObjectDescriptorImpl::Cancel() { std::unique_lock lk(mu_); if (cancelled_) return; cancelled_ = true; - if (stream_manager_) stream_manager_->CancelAll(); + std::vector> active_ranges; + if (stream_manager_) { + stream_manager_->CancelAll(); + active_ranges = stream_manager_->TakeActiveRanges(); + } if (pending_stream_.valid()) pending_stream_.cancel(); + lk.unlock(); + if (active_ranges.empty()) return; + // Stream callbacks become no-ops once `cancelled_` is set or this object is + // destroyed, so `Cancel()` must complete all detached ranges or readers will + // wait forever. + // + // Schedule via a zero-delay timer (ignoring its status) rather than + // `RunAsync()`: unlike `RunAsync()`, a timer still runs its continuation + // inline when the completion queue is already shut down. + Status status = internal::CancelledError( + "the ObjectDescriptor was destroyed before the read completed", + GCP_ERROR_INFO()); + cq_.MakeRelativeTimer(std::chrono::nanoseconds(0)) + .then([ranges = std::move(active_ranges), + status = std::move(status)](auto) { + for (std::shared_ptr const& range : ranges) { + range->OnFinish(status); + } + }); } std::optional ObjectDescriptorImpl::metadata() diff --git a/google/cloud/storage/internal/async/object_descriptor_impl.h b/google/cloud/storage/internal/async/object_descriptor_impl.h index d18c47c661d0c..41262f42fece1 100644 --- a/google/cloud/storage/internal/async/object_descriptor_impl.h +++ b/google/cloud/storage/internal/async/object_descriptor_impl.h @@ -22,6 +22,7 @@ #include "google/cloud/storage/internal/async/open_stream.h" #include "google/cloud/storage/internal/async/read_range.h" #include "google/cloud/storage/options.h" +#include "google/cloud/completion_queue.h" #include "google/cloud/status.h" #include "google/cloud/version.h" #include "google/storage/v2/storage.pb.h" @@ -69,7 +70,10 @@ class ObjectDescriptorImpl : public storage::ObjectDescriptorConnection, public std::enable_shared_from_this { public: - ObjectDescriptorImpl(std::unique_ptr resume_policy, + /// @p cq schedules cancellation notifications for active ranges; see + /// `Cancel()`. + ObjectDescriptorImpl(CompletionQueue cq, + std::unique_ptr resume_policy, OpenStreamFactory make_stream, google::storage::v2::BidiReadObjectSpec read_object_spec, std::shared_ptr stream, Options options = {}, @@ -92,7 +96,8 @@ class ObjectDescriptorImpl * @p make_clean_resume_stream may be empty, in which case @p make_stream is * used for those re-opens as well. */ - ObjectDescriptorImpl(std::unique_ptr resume_policy, + ObjectDescriptorImpl(CompletionQueue cq, + std::unique_ptr resume_policy, OpenStreamFactory make_stream, OpenStreamFactory make_clean_resume_stream, google::storage::v2::BidiReadObjectSpec read_object_spec, @@ -105,6 +110,12 @@ class ObjectDescriptorImpl void Start(google::storage::v2::BidiReadObjectResponse first_response); // Cancel the underlying RPC and stop the resume loop. + // + // Any unfinished ranges complete with `StatusCode::kCancelled`. Notifications + // are scheduled on the completion queue rather than invoked inline because + // callers may destroy the descriptor while holding locks needed by their + // continuations. Only when the completion queue is already shut down are + // ranges notified before this function returns. void Cancel(); Options options() const override { return options_; } @@ -185,6 +196,8 @@ class ObjectDescriptorImpl std::unique_ptr CreateHashValidator( bool is_full_read, std::unique_lock const&) const; + // Schedules cancellation notifications for active ranges in `Cancel()`. + CompletionQueue cq_; std::unique_ptr resume_policy_prototype_; OpenStreamFactory make_stream_; // Used only to re-open a stream that ended cleanly. See the constructor. diff --git a/google/cloud/storage/internal/async/object_descriptor_impl_test.cc b/google/cloud/storage/internal/async/object_descriptor_impl_test.cc index d58e680697341..6d31edc015b35 100644 --- a/google/cloud/storage/internal/async/object_descriptor_impl_test.cc +++ b/google/cloud/storage/internal/async/object_descriptor_impl_test.cc @@ -20,13 +20,17 @@ #include "google/cloud/internal/disable_deprecation_warnings.inc" #include "google/cloud/mocks/mock_async_streaming_read_write_rpc.h" #include "google/cloud/storage/async/options.h" +#include "google/cloud/storage/async/reader.h" #include "google/cloud/storage/async/resume_policy.h" #include "google/cloud/storage/internal/async/default_options.h" #include "google/cloud/storage/options.h" #include "google/cloud/storage/testing/canonical_errors.h" #include "google/cloud/storage/testing/mock_resume_policy.h" #include "google/cloud/storage/testing/mock_storage_stub.h" +#include "google/cloud/completion_queue.h" +#include "google/cloud/internal/background_threads_impl.h" #include "google/cloud/testing_util/async_sequencer.h" +#include "google/cloud/testing_util/fake_completion_queue_impl.h" #include "google/cloud/testing_util/is_proto_equal.h" #include "google/cloud/testing_util/scoped_log.h" #include "google/cloud/testing_util/status_matchers.h" @@ -36,8 +40,17 @@ #include #include #include +#include +#include +#include +#include +#include +#include +#include #include #include +#include +#include #include namespace google { @@ -50,6 +63,7 @@ using ::google::cloud::storage::testing::MockResumePolicy; 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::FakeCompletionQueueImpl; using ::google::cloud::testing_util::IsOk; using ::google::cloud::testing_util::IsProtoEqual; using ::google::cloud::testing_util::ScopedLog; @@ -89,6 +103,12 @@ auto constexpr kMetadataText = R"pb( auto NoResume() { return storage::LimitedErrorCountResumePolicy(0)(); } +// Returns a completion queue that never executes scheduled work, for tests +// that do not inspect range-cancellation notifications. +CompletionQueue IdleCompletionQueue() { + return CompletionQueue(std::make_shared()); +} + // The `[gcs-retry]` records, in order. Everything else the library logs is // noise for these tests. std::vector RetryRecords(ScopedLog& log) { @@ -108,7 +128,7 @@ auto MakeTested( Options options; options.set(true); return std::make_shared( - std::move(resume_policy), std::move(make_stream), + IdleCompletionQueue(), std::move(resume_policy), std::move(make_stream), std::move(read_object_spec), std::move(stream), std::move(options), std::move(transport_ok)); } @@ -252,8 +272,8 @@ TEST(ObjectDescriptorImpl, CleanResumeUsesTheSilentFactory) { // Keep `MakeSubsequentStream()` out of the way. options.set(false); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), clean_factory.AsStdFunction(), - google::storage::v2::BidiReadObjectSpec{}, + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), + clean_factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options, std::function{}); tested->Start(Response{}); @@ -300,8 +320,9 @@ TEST(ObjectDescriptorImpl, FailedResumeUsesTheReportingFactory) { Options options; options.set(false); auto tested = std::make_shared( - storage::LimitedErrorCountResumePolicy(1)(), factory.AsStdFunction(), - clean_factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, + IdleCompletionQueue(), storage::LimitedErrorCountResumePolicy(1)(), + factory.AsStdFunction(), clean_factory.AsStdFunction(), + google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options, std::function{}); tested->Start(Response{}); @@ -350,8 +371,8 @@ TEST(ObjectDescriptorImpl, NoRetryLogForPermanentStreamFailure) { Options options; options.set(false); auto tested = std::make_shared( - storage::LimitedErrorCountResumePolicy(1)(), factory.AsStdFunction(), - google::storage::v2::BidiReadObjectSpec{}, + IdleCompletionQueue(), storage::LimitedErrorCountResumePolicy(1)(), + factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options, std::function{}); tested->Start(Response{}); @@ -419,8 +440,9 @@ TEST(ObjectDescriptorImpl, ResumeAttemptCountsConsecutiveFailures) { Options options; options.set(false); auto tested = std::make_shared( - storage::LimitedErrorCountResumePolicy(3)(), factory.AsStdFunction(), - factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, + IdleCompletionQueue(), storage::LimitedErrorCountResumePolicy(3)(), + factory.AsStdFunction(), factory.AsStdFunction(), + google::storage::v2::BidiReadObjectSpec{}, std::make_shared(make_failing_stream("s1")), options, std::function{}); tested->Start(Response{}); @@ -2109,7 +2131,7 @@ TEST(ObjectDescriptorImpl, MultiStreamOptimizationDisabled) { options.set(false); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -2172,7 +2194,7 @@ TEST(ObjectDescriptorImpl, IsOpenFalseOnTransportFailure) { MockFactory factory; auto transport_ok = [] { return false; }; auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), Options{}, std::move(transport_ok)); @@ -2188,7 +2210,7 @@ TEST(ObjectDescriptorImpl, IsOpenTrueOnTransportSuccess) { MockFactory factory; auto transport_ok = [] { return true; }; auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), Options{}, std::move(transport_ok)); @@ -2266,7 +2288,7 @@ TEST(ObjectDescriptorImpl, FullReadChecksumValidationSuccess) { options.set(true); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -2374,7 +2396,7 @@ TEST(ObjectDescriptorImpl, FullReadChecksumValidationMismatchCrc32c) { options.set(true); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -2483,7 +2505,7 @@ TEST(ObjectDescriptorImpl, FullReadChecksumValidationMismatchMd5) { options.set(true); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -2591,7 +2613,7 @@ TEST(ObjectDescriptorImpl, PartialReadChecksumValidationBypassed) { options.set(true); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -2703,7 +2725,7 @@ TEST(ObjectDescriptorImpl, options.set(true); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -2814,7 +2836,7 @@ TEST(ObjectDescriptorImpl, options.set(true); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -2903,7 +2925,7 @@ TEST(ObjectDescriptorImpl, PrewarmedCacheHit) { options.set({{0, 15}}); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -3002,7 +3024,7 @@ TEST(ObjectDescriptorImpl, PrewarmedCacheMiss) { options.set({{0, 15}}); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -3107,7 +3129,7 @@ TEST(ObjectDescriptorImpl, PrewarmedPacingEviction) { options.set(5); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -3186,7 +3208,7 @@ TEST(ObjectDescriptorImpl, InitialReadRangesExactRangeCacheHit) { options.set({{0, 1024}}); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -3284,7 +3306,7 @@ TEST(ObjectDescriptorImpl, InitialReadRangesSubRangeCacheMiss) { options.set({{0, 1024}}); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -3389,7 +3411,7 @@ TEST(ObjectDescriptorImpl, PreWarmBufferLimitEvictionTombstone) { options.set(5); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -3453,7 +3475,7 @@ TEST(ObjectDescriptorImpl, DuplicateInitialRangesDeduplication) { options.set({{0, 1024}, {0, 1024}}); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream)), options); @@ -3804,8 +3826,8 @@ TEST(ObjectDescriptorImpl, UserCancelStopsStreamWithoutResume) { Options options; options.set(false); auto tested = std::make_shared( - storage::LimitedErrorCountResumePolicy(2)(), factory.AsStdFunction(), - google::storage::v2::BidiReadObjectSpec{}, + IdleCompletionQueue(), storage::LimitedErrorCountResumePolicy(2)(), + factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream1)), options); Response start_resp; @@ -3899,8 +3921,8 @@ TEST(ObjectDescriptorImpl, ConcurrentReadPreservedAcrossMultipleResumeRetries) { }); auto tested = std::make_shared( - storage::LimitedErrorCountResumePolicy(3)(), factory.AsStdFunction(), - google::storage::v2::BidiReadObjectSpec{}, + IdleCompletionQueue(), storage::LimitedErrorCountResumePolicy(3)(), + factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream1)), Options{}.set(false)); @@ -4091,7 +4113,7 @@ TEST(ObjectDescriptorImpl, ResumePolicyObservesCancelledStatus) { Options options; options.set(false); auto tested = std::make_shared( - std::move(prototype), factory.AsStdFunction(), + IdleCompletionQueue(), std::move(prototype), factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream1)), options); @@ -4178,8 +4200,8 @@ TEST(ObjectDescriptorImpl, ResumeBudgetIsNotResetByASuccessfulReconnect) { options.set(false); // A budget of exactly one resume for the lifetime of this descriptor. auto tested = std::make_shared( - storage::LimitedErrorCountResumePolicy(1)(), factory.AsStdFunction(), - google::storage::v2::BidiReadObjectSpec{}, + IdleCompletionQueue(), storage::LimitedErrorCountResumePolicy(1)(), + factory.AsStdFunction(), google::storage::v2::BidiReadObjectSpec{}, std::make_shared(std::move(stream1)), options); tested->Start(Response{}); @@ -4277,8 +4299,9 @@ TEST(ObjectDescriptorImpl, ConcurrentReadAndMetadataUpdate) { spec.set_object("test-object-with-long-non-sso-allocated-name"); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), std::move(spec), - std::make_shared(std::move(stream)), options); + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), + std::move(spec), std::make_shared(std::move(stream)), + options); tested->Start(MakeMetadataUpdateResponse(0)); @@ -4388,8 +4411,9 @@ TEST(ObjectDescriptorImpl, ConcurrentMultiStreamReadAndStreamSize) { spec.set_object("test-object-with-long-non-sso-allocated-name"); auto tested = std::make_shared( - NoResume(), factory.AsStdFunction(), std::move(spec), - std::make_shared(std::move(initial_stream)), options); + IdleCompletionQueue(), NoResume(), factory.AsStdFunction(), + std::move(spec), std::make_shared(std::move(initial_stream)), + options); tested->Start(MakeMetadataUpdateResponse(0)); @@ -4439,6 +4463,535 @@ TEST(ObjectDescriptorImpl, ConcurrentMultiStreamReadAndStreamSize) { while (!sequencer.empty()) sequencer.PopFront().set_value(false); } +/// How a test triggers cancellation of an `ObjectDescriptorImpl`. +enum class CancelTrigger { + // Drop the last reference, which is the only path reachable from the public + // API. + kDestroy, + // Call `Cancel()` directly while keeping the impl alive. + kCancel, +}; + +std::ostream& operator<<(std::ostream& os, CancelTrigger trigger) { + switch (trigger) { + case CancelTrigger::kDestroy: + return os << "Destroy"; + case CancelTrigger::kCancel: + return os << "Cancel"; + } + return os << "Unknown"; +} + +/// Parameter case for `ObjectDescriptorImplCancelRangeTest`: the range state +/// before cancellation and the data/status the reader must observe afterward. +struct RangeAtCancel { + std::string name; + // Text-proto response delivered by the stream before cancellation; empty if + // no response is delivered. + std::string initial_response_text; + bool has_pending_read; + std::vector expected_data; + StatusCode expected_status; +}; + +std::ostream& operator<<(std::ostream& os, RangeAtCancel const& range) { + return os << range.name; +} + +// The `Cancel()` tests start their first read with `Read({0, 100})`, which +// assigns `read_id: 1`. This text proto delivers a partial chunk for it. +constexpr std::string_view kPartialRangeResponse = R"pb( + object_data_ranges { + read_range { read_id: 1 read_offset: 0 } + checksummed_data { content: "0123456789" } + } +)pb"; + +// The same chunk marked as the final message (`range_end: true`) for +// `read_id: 1`. +constexpr std::string_view kCompleteRangeResponse = R"pb( + object_data_ranges { + range_end: true + read_range { read_id: 1 read_offset: 0 } + checksummed_data { content: "0123456789" } + } +)pb"; + +using ReadResponse = storage::AsyncReaderConnection::ReadResponse; + +// Returns the value of a future the test expects to be satisfied. Calling +// `get()` on one that is not would block the test forever. +ReadResponse GetNow(future pending) { + if (pending.valid() && pending.is_ready()) return pending.get(); + ADD_FAILURE() << "the Read() has not completed"; + return Status(StatusCode::kUnknown, "the Read() has not completed"); +} + +ReadResponse ReadNow(storage::AsyncReaderConnection& reader) { + return GetNow(reader.Read()); +} + +MATCHER_P(IsData, contents, + "is a payload with contents " + ::testing::PrintToString(contents)) { + return ::testing::ExplainMatchResult( + VariantWith(ResultOf( + "contents", + [](storage::ReadPayload const& payload) { + return payload.contents(); + }, + ElementsAre(std::string_view{contents}))), + arg, result_listener); +} + +MATCHER(IsCancelled, "is a kCancelled status") { + return ::testing::ExplainMatchResult( + VariantWith(StatusIs(StatusCode::kCancelled)), arg, + result_listener); +} + +// Wraps an `AsyncReaderConnection` and records when it is destroyed. +class DestructionObserver : public storage::AsyncReaderConnection { + public: + DestructionObserver(std::unique_ptr impl, + bool& destroyed) + : impl_(std::move(impl)), destroyed_(destroyed) {} + ~DestructionObserver() override { destroyed_ = true; } + + void Cancel() override { impl_->Cancel(); } + future Read() override { return impl_->Read(); } + RpcMetadata GetRequestMetadata() override { + return impl_->GetRequestMetadata(); + } + + private: + std::unique_ptr impl_; + bool& destroyed_; +}; + +/** + * Runs an `ObjectDescriptorImpl` over mock streams to test `Cancel()`. + * + * `Cancel()` schedules active-range notifications on the completion queue. Most + * tests supply a `FakeCompletionQueueImpl` so they can assert reader state both + * before and after the queued notification runs. + */ +class ObjectDescriptorImplCancelTest : public ::testing::Test { + protected: + void TearDown() override { + // Complete any parked stream reads as gRPC does for a cancelled RPC, so + // `OpenStream` proceeds to `Finish()`. + while (!sequencer_.empty()) sequencer_.PopFront().set_value(false); + } + + static Options SingleStreamOptions() { + return Options{}.set(false); + } + + // Returns a mock stream whose `Read()` calls park in `sequencer_` as + // "Read[]" and that expects one `Cancel()` and one `Finish()`. + std::unique_ptr MakeStream(int stream_id, + Status const& finish_status) { + auto stream = std::make_unique(); + EXPECT_CALL(*stream, Write) + .WillRepeatedly([this, stream_id](Request const&, grpc::WriteOptions) { + write_stream_ids_.push_back(stream_id); + return make_ready_future(true); + }); + EXPECT_CALL(*stream, Read).WillRepeatedly([this, stream_id] { + return sequencer_.PushBack("Read[" + std::to_string(stream_id) + "]") + .then([this](future f) -> std::optional { + if (!f.get()) return std::nullopt; + return std::exchange(next_response_, std::nullopt); + }); + }); + EXPECT_CALL(*stream, Finish).WillOnce([finish_status] { + return make_ready_future(finish_status); + }); + EXPECT_CALL(*stream, Cancel).WillOnce([this] { ++stream_cancel_count_; }); + return stream; + } + + std::unique_ptr MakeStream(int stream_id) { + return MakeStream(stream_id, Status(StatusCode::kCancelled, "cancelled")); + } + + void StartDescriptor(CompletionQueue cq, + std::unique_ptr resume_policy, + std::unique_ptr stream, Options options) { + tested_ = std::make_shared( + std::move(cq), std::move(resume_policy), factory_.AsStdFunction(), + google::storage::v2::BidiReadObjectSpec{}, + std::make_shared(std::move(stream)), std::move(options), + std::function{}); + tested_->Start(Response{}); + } + + // Starts a single-stream descriptor that does not resume. + void StartDescriptor() { + StartDescriptor(CompletionQueue(cq_), NoResume(), MakeStream(1), + SingleStreamOptions()); + } + + // Pops the oldest parked stream `Read()` and checks that its label matches + // @p expected_name. + promise PopStreamRead(std::string const& expected_name) { + std::pair, std::string> next = sequencer_.PopFrontWithName(); + EXPECT_EQ(next.second, expected_name); + return std::move(next.first); + } + + // Completes @p stream_read with the parsed text proto @p response_text. + void DeliverResponse(promise stream_read, + std::string const& response_text) { + next_response_.emplace(); + ASSERT_TRUE(TextFormat::ParseFromString(response_text, &*next_response_)); + stream_read.set_value(true); + } + + void TriggerCancel(CancelTrigger trigger) { + switch (trigger) { + case CancelTrigger::kDestroy: + tested_.reset(); + break; + case CancelTrigger::kCancel: + tested_->Cancel(); + break; + } + } + + void RunCompletionQueue() { cq_->SimulateCompletion(/*ok=*/true); } + + AsyncSequencer sequencer_; + MockFactory factory_; + std::shared_ptr cq_ = + std::make_shared(); + std::optional next_response_; + std::vector write_stream_ids_; + int stream_cancel_count_ = 0; + std::shared_ptr tested_; +}; + +class ObjectDescriptorImplCancelRangeTest + : public ObjectDescriptorImplCancelTest, + public ::testing::WithParamInterface< + std::tuple> {}; + +/// @test Verify what a reader returns after its descriptor is cancelled, across +/// both cancellation triggers and every pre-cancel range state. +TEST_P(ObjectDescriptorImplCancelRangeTest, ReaderReturnsDataThenStatus) { + CancelTrigger const trigger = std::get<0>(GetParam()); + RangeAtCancel const& range_case = std::get<1>(GetParam()); + + StartDescriptor(); + std::unique_ptr reader = + tested_->Read({0, 100}); + if (!range_case.initial_response_text.empty()) { + DeliverResponse(PopStreamRead("Read[1]"), range_case.initial_response_text); + } + future pending_read; + if (range_case.has_pending_read) pending_read = reader->Read(); + + TriggerCancel(trigger); + // `Cancel()` only queues the notification, so a pending read's continuation + // does not run on the cancelling thread. + if (range_case.has_pending_read) { + EXPECT_FALSE(pending_read.is_ready()); + } + RunCompletionQueue(); + + for (std::string const& expected_chunk : range_case.expected_data) { + EXPECT_THAT(ReadNow(*reader), IsData(expected_chunk)); + } + ReadResponse const final_response = range_case.has_pending_read + ? GetNow(std::move(pending_read)) + : ReadNow(*reader); + EXPECT_THAT(final_response, + VariantWith(StatusIs(range_case.expected_status))); +} + +INSTANTIATE_TEST_SUITE_P( + ObjectDescriptorImpl, ObjectDescriptorImplCancelRangeTest, + ::testing::Combine( + ::testing::Values(CancelTrigger::kDestroy, CancelTrigger::kCancel), + ::testing::Values(RangeAtCancel{"ReadPending", + "", + /*has_pending_read=*/true, + {}, + StatusCode::kCancelled}, + RangeAtCancel{"NoReadYet", + "", + /*has_pending_read=*/false, + {}, + StatusCode::kCancelled}, + RangeAtCancel{"DataBuffered", + std::string{kPartialRangeResponse}, + /*has_pending_read=*/false, + {"0123456789"}, + StatusCode::kCancelled}, + // A range that already finished before cancellation + // keeps its OK status. + RangeAtCancel{"RangeComplete", + std::string{kCompleteRangeResponse}, + /*has_pending_read=*/false, + {"0123456789"}, + StatusCode::kOk})), + [](::testing::TestParamInfo< + ObjectDescriptorImplCancelRangeTest::ParamType> const& info) { + std::ostringstream os; + os << std::get<0>(info.param) << std::get<1>(info.param); + return std::move(os).str(); + }); + +/// @test Verify `Cancel()` does not schedule completion-queue work when no +/// active range needs notification. +TEST_F(ObjectDescriptorImplCancelTest, DoesNotQueueWorkWhenNoRangesActive) { + StartDescriptor(); + tested_.reset(); + EXPECT_TRUE(cq_->empty()); +} + +/// @test Verify `Cancel()` completes ranges attached to a reconnecting stream, +/// both those written before the failure and those queued for the new stream. +TEST_F(ObjectDescriptorImplCancelTest, CompletesRangesOfReconnectingStream) { + EXPECT_CALL(factory_, Call).WillOnce([this](Request const&) { + return sequencer_.PushBack("Reconnect").then([](future) { + return StatusOr(PermanentError()); + }); + }); + StartDescriptor(CompletionQueue(cq_), + storage::LimitedErrorCountResumePolicy(1)(), + MakeStream(1, TransientError()), SingleStreamOptions()); + + std::unique_ptr sent_reader = + tested_->Read({0, 100}); + // Fail the stream so the descriptor enters the reconnecting state. + PopStreamRead("Read[1]").set_value(false); + std::unique_ptr waiting_reader = + tested_->Read({200, 100}); + // Only the first range was written; the second waits for the new stream. + EXPECT_THAT(write_stream_ids_, ElementsAre(1)); + future sent_read = sent_reader->Read(); + future waiting_read = waiting_reader->Read(); + + tested_.reset(); + RunCompletionQueue(); + + EXPECT_THAT(GetNow(std::move(sent_read)), IsCancelled()); + EXPECT_THAT(GetNow(std::move(waiting_read)), IsCancelled()); +} + +/// @test Verify `Cancel()` completes active ranges across all managed streams. +TEST_F(ObjectDescriptorImplCancelTest, CompletesRangesOfAllStreams) { + EXPECT_CALL(factory_, Call) + .WillOnce([this](Request const&) { + return make_ready_future(make_status_or(OpenStreamResult{ + std::make_shared(MakeStream(2)), Response{}})); + }) + .WillRepeatedly([](Request const&) { + return make_ready_future(StatusOr(PermanentError())); + }); + StartDescriptor( + CompletionQueue(cq_), NoResume(), MakeStream(1), + Options{}.set(true)); + + std::unique_ptr first_reader = + tested_->Read({0, 100}); + // Stream 1 is busy, so `MakeSubsequentStream()` activates stream 2. + tested_->MakeSubsequentStream(); + std::unique_ptr second_reader = + tested_->Read({200, 100}); + EXPECT_THAT(write_stream_ids_, ElementsAre(1, 2)); + future first_read = first_reader->Read(); + future second_read = second_reader->Read(); + + tested_.reset(); + EXPECT_EQ(stream_cancel_count_, 2); + RunCompletionQueue(); + + EXPECT_THAT(GetNow(std::move(first_read)), IsCancelled()); + EXPECT_THAT(GetNow(std::move(second_read)), IsCancelled()); +} + +/// @test Verify `Cancel()` completes a claimed pre-warmed range and tears down +/// cleanly when an unclaimed pre-warmed range is also present. +TEST_F(ObjectDescriptorImplCancelTest, CompletesPrewarmedRanges) { + StartDescriptor( + CompletionQueue(cq_), NoResume(), MakeStream(1), + SingleStreamOptions().set({{0, 100}, {200, 50}})); + + // Claims the first pre-warmed range while leaving the second unclaimed. + std::unique_ptr reader = + tested_->Read({0, 100}); + EXPECT_THAT(write_stream_ids_, IsEmpty()); + future pending_read = reader->Read(); + + tested_.reset(); + EXPECT_FALSE(pending_read.is_ready()); + RunCompletionQueue(); + + EXPECT_THAT(GetNow(std::move(pending_read)), IsCancelled()); +} + +/// @test Verify an abandoned `AsyncReader` is released once descriptor +/// cancellation completes its underlying range. +TEST_F(ObjectDescriptorImplCancelTest, ReleasesAbandonedReader) { + StartDescriptor(); + bool reader_destroyed = false; + { + storage::AsyncReader abandoned_reader(std::make_unique( + tested_->Read({0, 100}), reader_destroyed)); + } + // `~AsyncReader()` keeps the connection alive in its background drain loop + // until the range finishes. + EXPECT_FALSE(reader_destroyed); + + tested_.reset(); + RunCompletionQueue(); + + EXPECT_TRUE(reader_destroyed); +} + +/// @test Verify active ranges complete when the last reference to the +/// descriptor is released by a stream callback. +TEST_F(ObjectDescriptorImplCancelTest, + CompletesRangesWhenDestroyedByStreamCallback) { + StartDescriptor(); + std::unique_ptr first_reader = + tested_->Read({0, 100}); + std::unique_ptr second_reader = + tested_->Read({200, 100}); + // Drop the test's reference inside the stream callback so the callback's own + // `shared_ptr` becomes the last reference and destroys the descriptor on + // return. + future first_read = + first_reader->Read().then([this](future f) { + tested_.reset(); + return f.get(); + }); + future second_read = second_reader->Read(); + + DeliverResponse(PopStreamRead("Read[1]"), std::string{kPartialRangeResponse}); + EXPECT_EQ(stream_cancel_count_, 1); + EXPECT_THAT(GetNow(std::move(first_read)), IsData("0123456789")); + EXPECT_FALSE(second_read.is_ready()); + RunCompletionQueue(); + + EXPECT_THAT(GetNow(std::move(second_read)), IsCancelled()); + EXPECT_THAT(ReadNow(*first_reader), IsCancelled()); +} + +/// @test Verify a cancellation continuation for one reader can safely read from +/// another reader of the same descriptor. +TEST_F(ObjectDescriptorImplCancelTest, CallbackCanReadFromAnotherReader) { + StartDescriptor(); + // Declared before `first_reader` so they outlive its continuation. + future second_read_from_callback; + std::unique_ptr second_reader = + tested_->Read({200, 100}); + std::unique_ptr first_reader = + tested_->Read({0, 100}); + // Ranges are notified in arbitrary order, so `second_reader` may already be + // cancelled or still awaiting notification when this continuation runs. + future first_read = first_reader->Read().then( + [&second_reader, &second_read_from_callback](future f) { + second_read_from_callback = second_reader->Read(); + return f.get(); + }); + + tested_.reset(); + RunCompletionQueue(); + + EXPECT_THAT(GetNow(std::move(first_read)), IsCancelled()); + EXPECT_THAT(GetNow(std::move(second_read_from_callback)), IsCancelled()); +} + +/// @test Verify `Cancel()` releases the descriptor mutex before triggering +/// range notifications. +TEST_F(ObjectDescriptorImplCancelTest, NotifiesWithoutHoldingMutex) { + StartDescriptor(); + // Declared before `reader` so it outlives the continuation. + bool is_open_during_callback = true; + std::unique_ptr reader = + tested_->Read({0, 100}); + // A shut-down completion queue completes timers inline inside `Cancel()`. + // Calling `IsOpen()` from the continuation would deadlock if `mu_` were still + // held. + cq_->Shutdown(); + future pending_read = reader->Read().then( + [this, &is_open_during_callback](future f) { + is_open_during_callback = tested_->IsOpen(); + return f.get(); + }); + + tested_->Cancel(); + + EXPECT_FALSE(is_open_during_callback); + EXPECT_THAT(GetNow(std::move(pending_read)), IsCancelled()); +} + +/// @test Verify cancellation notifications run on a completion-queue thread +/// rather than on the thread that destroys the descriptor. +TEST_F(ObjectDescriptorImplCancelTest, NotifiesInCompletionQueueThread) { + internal::AutomaticallyCreatedBackgroundThreads background_threads; + StartDescriptor(background_threads.cq(), NoResume(), MakeStream(1), + SingleStreamOptions()); + std::unique_ptr reader = + tested_->Read({0, 100}); + future notification_thread_id = + reader->Read().then([](future f) { + EXPECT_THAT(f.get(), IsCancelled()); + return std::this_thread::get_id(); + }); + + tested_.reset(); + + // Bound the wait so the test fails instead of hanging if nothing notifies the + // reader. + ASSERT_EQ(notification_thread_id.wait_for(std::chrono::seconds(60)), + std::future_status::ready); + EXPECT_NE(notification_thread_id.get(), std::this_thread::get_id()); +} + +/// @test Verify active ranges still complete inline on the destroying thread +/// when the completion queue has already been shut down. +TEST_F(ObjectDescriptorImplCancelTest, NotifiesAfterCompletionQueueShutdown) { + internal::AutomaticallyCreatedBackgroundThreads background_threads; + StartDescriptor(background_threads.cq(), NoResume(), MakeStream(1), + SingleStreamOptions()); + std::unique_ptr reader = + tested_->Read({0, 100}); + future pending_read = reader->Read(); + background_threads.Shutdown(); + + tested_.reset(); + + EXPECT_THAT(GetNow(std::move(pending_read)), IsCancelled()); +} + +/// @test Verify a second `Cancel()` neither cancels streams nor queues +/// notifications again, and late stream data delivered after `Cancel()` is +/// ignored. +TEST_F(ObjectDescriptorImplCancelTest, IgnoresSecondCancelAndLateData) { + StartDescriptor(); + std::unique_ptr reader = + tested_->Read({0, 100}); + future pending_read = reader->Read(); + + tested_->Cancel(); + tested_->Cancel(); + EXPECT_EQ(stream_cancel_count_, 1); + + // Deliver data after `Cancel()` but before the completion queue runs. + // Because `TakeActiveRanges()` already detached the range, `OnRead()` skips + // the chunk and the reader only sees `kCancelled`. + DeliverResponse(PopStreamRead("Read[1]"), std::string{kPartialRangeResponse}); + EXPECT_FALSE(pending_read.is_ready()); + + RunCompletionQueue(); + EXPECT_TRUE(cq_->empty()); + EXPECT_THAT(GetNow(std::move(pending_read)), IsCancelled()); +} + } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage_internal diff --git a/google/cloud/storage/internal/async/read_range_test.cc b/google/cloud/storage/internal/async/read_range_test.cc index 8dcbb8093696d..fa59e10e05c0d 100644 --- a/google/cloud/storage/internal/async/read_range_test.cc +++ b/google/cloud/storage/internal/async/read_range_test.cc @@ -143,6 +143,18 @@ TEST(ReadRange, Error) { VariantWith(StatusIs(PermanentError().code()))); } +/// @test Verify `ReadRange::OnFinish()` keeps the first terminal status, so a +/// range that already finished before descriptor cancellation is not +/// overwritten with `StatusCode::kCancelled`. +TEST(ReadRange, FinishKeepsFirstStatus) { + ReadRange actual(10000, 40); + actual.OnFinish(PermanentError()); + actual.OnFinish(Status(StatusCode::kCancelled, "cancelled")); + + EXPECT_THAT(actual.Read().get(), + VariantWith(StatusIs(PermanentError().code()))); +} + TEST(ReadRange, Queue) { ReadRange actual(10000, 40); From d7f362a121e476c3a2a8e2a1ad10413b82a9c99a Mon Sep 17 00:00:00 2001 From: Gauri Kalra Date: Thu, 3 Dec 2026 10:20:58 +0000 Subject: [PATCH 2/3] style(storage): format Open() lambda and clarify Cancel() comment --- .../storage/internal/async/connection_impl.cc | 60 +++++++++---------- .../internal/async/object_descriptor_impl.h | 11 ++-- 2 files changed, 36 insertions(+), 35 deletions(-) diff --git a/google/cloud/storage/internal/async/connection_impl.cc b/google/cloud/storage/internal/async/connection_impl.cc index ea510ec2fe576..fe43ead6c3d27 100644 --- a/google/cloud/storage/internal/async/connection_impl.cc +++ b/google/cloud/storage/internal/async/connection_impl.cc @@ -344,36 +344,36 @@ AsyncConnectionImpl::Open(OpenParams p) { auto pending = factory(std::move(initial_request)); using ReturnType = std::shared_ptr; - return pending.then([cq = cq_, rp = std::move(resume_policy), - fa = std::move(factory), - qfa = std::move(clean_resume_factory), - rs = std::move(p.read_spec), - options = std::move(p.options), refresh = refresh_]( - auto f) mutable -> StatusOr { - auto result = f.get(); - if (!result) return std::move(result).status(); - - // The descriptor remains open if at least one gRPC channel is in a - // functional state. We consider READY, IDLE, and CONNECTING to be - // functional. TRANSIENT_FAILURE and SHUTDOWN are not included because - // they indicate a definitive loss of connectivity or terminal closure. - auto transport_ok = [refresh] { - if (!refresh) return true; - auto const& channels = refresh->channels(); - return std::any_of( - channels.begin(), channels.end(), [](auto const& channel) { - auto state = channel->GetState(false); - return state == GRPC_CHANNEL_READY || state == GRPC_CHANNEL_IDLE || - state == GRPC_CHANNEL_CONNECTING; - }); - }; - auto impl = std::make_shared( - std::move(cq), std::move(rp), std::move(fa), std::move(qfa), - std::move(rs), std::move(result->stream), std::move(options), - std::move(transport_ok)); - impl->Start(std::move(result->first_response)); - return ReturnType(impl); - }); + return pending.then( + [cq = cq_, rp = std::move(resume_policy), fa = std::move(factory), + qfa = std::move(clean_resume_factory), rs = std::move(p.read_spec), + options = std::move(p.options), + refresh = refresh_](auto f) mutable -> StatusOr { + auto result = f.get(); + if (!result) return std::move(result).status(); + + // The descriptor remains open if at least one gRPC channel is in a + // functional state. We consider READY, IDLE, and CONNECTING to be + // functional. TRANSIENT_FAILURE and SHUTDOWN are not included because + // they indicate a definitive loss of connectivity or terminal closure. + auto transport_ok = [refresh] { + if (!refresh) return true; + auto const& channels = refresh->channels(); + return std::any_of(channels.begin(), channels.end(), + [](auto const& channel) { + auto state = channel->GetState(false); + return state == GRPC_CHANNEL_READY || + state == GRPC_CHANNEL_IDLE || + state == GRPC_CHANNEL_CONNECTING; + }); + }; + auto impl = std::make_shared( + std::move(cq), std::move(rp), std::move(fa), std::move(qfa), + std::move(rs), std::move(result->stream), std::move(options), + std::move(transport_ok)); + impl->Start(std::move(result->first_response)); + return ReturnType(impl); + }); } future>> diff --git a/google/cloud/storage/internal/async/object_descriptor_impl.h b/google/cloud/storage/internal/async/object_descriptor_impl.h index 41262f42fece1..c3d3459c9c095 100644 --- a/google/cloud/storage/internal/async/object_descriptor_impl.h +++ b/google/cloud/storage/internal/async/object_descriptor_impl.h @@ -111,11 +111,12 @@ class ObjectDescriptorImpl // Cancel the underlying RPC and stop the resume loop. // - // Any unfinished ranges complete with `StatusCode::kCancelled`. Notifications - // are scheduled on the completion queue rather than invoked inline because - // callers may destroy the descriptor while holding locks needed by their - // continuations. Only when the completion queue is already shut down are - // ranges notified before this function returns. + // Any unfinished ranges active when `Cancel()` runs complete with + // `StatusCode::kCancelled`. Notifications are scheduled on the completion + // queue rather than invoked inline because callers may destroy the descriptor + // while holding locks needed by their continuations. Only when the completion + // queue is already shut down are ranges notified before this function + // returns. void Cancel(); Options options() const override { return options_; } From 4a1a8143851343001735c9084798e5f66b4fbee2 Mon Sep 17 00:00:00 2001 From: Gauri Kalra Date: Thu, 3 Dec 2026 11:16:50 +0000 Subject: [PATCH 3/3] docs(storage): limit ObjectDescriptor shutdown example to CompletionQueue::Shutdown() --- google/cloud/storage/async/object_descriptor.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/google/cloud/storage/async/object_descriptor.h b/google/cloud/storage/async/object_descriptor.h index a7ab9d42c0734..bc613d0083389 100644 --- a/google/cloud/storage/async/object_descriptor.h +++ b/google/cloud/storage/async/object_descriptor.h @@ -44,8 +44,8 @@ GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN * * Cancelled reads complete on the client's completion queue, like any other * read. If that queue has already been shut down (for example, via - * `CompletionQueue::Shutdown()` or because the owning `AsyncClient` was - * destroyed), they complete on the thread that destroys the descriptor. + * `CompletionQueue::Shutdown()`), they complete on the thread that destroys + * the descriptor. */ class ObjectDescriptor { public: