Repository navigation
Conversation
There was a problem hiding this comment.
Code Review
This pull request introduces robust cancellation handling and state tracking in OpenObject and OpenStream to ensure safe, concurrent teardown of bidirectional streaming RPCs, supported by comprehensive new unit tests. The review feedback recommends aligning with the repository style guide by avoiding auto where it obscures domain or return types—specifically for std::shared_ptr<OpenObject> and future<StatusOr<OpenStreamResult>>—and suggests removing a redundant return statement from a void function for consistency.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #16613 +/- ##
==========================================
+ Coverage 92.76% 92.80% +0.03%
==========================================
Files 2273 2273
Lines 227827 228215 +388
==========================================
+ Hits 211355 211787 +432
+ Misses 16472 16428 -44 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
184911f to
bb6e5de
Compare
bb6e5de to
ac48a20
Compare
| { | ||
| std::lock_guard<std::mutex> lk(mu_); | ||
| if (finish_issued_) return std::move(finish_); | ||
| finish_issued_ = true; |
There was a problem hiding this comment.
When finish_issued_ transitions to true here, OpenStream::Finish() calls rpc_->Finish() right away even if pending_ops_ > 0. That can still happen on uncancelled mid-stream errors in ObjectDescriptorImpl::OnRead or OnWrite when a sibling Write() or Read() is still in flight, which violates the AsyncStreamingReadWriteRpc::Finish() contract. Since pending_ops_ and finish_deferred_ are already here, could we also defer rpc_->Finish() when pending_ops_ > 0 (keeping the immediate fast path when pending_ops_ == 0)?
There was a problem hiding this comment.
Done in e6721ba — OpenStream::Finish() now defers rpc_->Finish() via finish_deferred_ / finish_promise_ whenever pending_ops_ > 0 (leaving finish_ empty so subsequent Finish() calls still return {} and keeping the immediate fast path when pending_ops_ == 0). Added FinishDefersUntilInFlightOpCompletes and FinishDeferredThenCancelDoesNotOverwritePromise in open_stream_test.cc, and updated ObjectDescriptorImpl.IgnoresCallbacksFromStaleStreams (which previously expected Finish[1] while Write[1] was still in flight) to drain Write[1] before Finish[1] resumes stream 2.
| std::lock_guard<std::mutex> lk(mu_); | ||
| if (cancel_) return; | ||
| cancel_ = true; | ||
| ++pending_ops_; |
There was a problem hiding this comment.
All current tests in open_stream_test.cc resolve the in-flight operation after Cancel() returns, so removing this ++pending_ops_ guard would not fail any test even though an operation completing inline inside rpc_->Cancel() could trigger rpc_->Finish() before AsyncStreamingReadWriteRpcAuth::Cancel() finishes. Could we add a unit test where the Cancel mock resolves a pending Start() inline and verifies Finish() is not called until Cancel() returns?
There was a problem hiding this comment.
Done in e6721ba — added CancelResolvingStartInlineDefersFinishUntilCancelReturns in open_stream_test.cc, where the Cancel mock resolves pending Start() inline and asserts Finish() is not called until Cancel() returns.
| ON_CALL(*stream, Cancel).WillByDefault([&cancel_calls] { | ||
| ++cancel_calls; | ||
| }); | ||
| ON_CALL(*stream, Finish).WillByDefault([] { |
There was a problem hiding this comment.
This Finish handler does not verify that Cancel already ran. Could we capture &cancel_calls here and assert EXPECT_EQ(cancel_calls.load(), 1) inside Finish so any race that invokes Finish() before Cancel() is caught?
There was a problem hiding this comment.
Done in e6721ba — captured &cancel_calls (and &finish_calls) in the Finish handler of ConcurrentCancelAndReadCompletion to assert EXPECT_EQ(cancel_calls.load(), 1) inside Finish() and verify finish_calls matches each branch.
| } | ||
| rpc_->Cancel(); | ||
| MaybeFinish(); | ||
| EndOp(); |
There was a problem hiding this comment.
EndOp() runs on this after rpc_->Cancel() returns without Cancel() holding its own shared_from_this(). If rpc_->Cancel() ever synchronously triggered a continuation that dropped the caller's last external shared_ptr<OpenStream>, EndOp() would run on a destroyed object. Could we pin std::shared_ptr<OpenStream> self = shared_from_this(); before rpc_->Cancel() to match Start(), Write(), Read(), and Finish()?
There was a problem hiding this comment.
Done in e6721ba — pinned std::shared_ptr<OpenStream> self = shared_from_this(); at the start of OpenStream::Cancel() before acquiring mu_, and added CancelPinsSelfWhenInlineContinuationDropsLastRef in open_stream_test.cc.
| std::shared_ptr<OpenStream> self = std::move(s); | ||
| bool const cancelled = self->EndOp(); | ||
| bool const ok = f.get(); | ||
| return !cancelled && ok; |
There was a problem hiding this comment.
Mutating return !cancelled && ok; here to return ok; currently passes every test (CleanShutdown returns false from the Write mock and does not check write.get(), and CancelPhase::kWrite still ends in kCancelled via OpenStream::Read()'s BeginOp() guard). Could we add a case in open_stream_test.cc where Write() resolves to true after Cancel() and assert EXPECT_FALSE(write.get())?
There was a problem hiding this comment.
Done in e6721ba — added CancelDuringWriteReturnsFalseAndDefersFinish in open_stream_test.cc, resolving Write() to true after Cancel() and asserting EXPECT_FALSE(write.get()).
ac48a20 to
e6721ba
Compare
Note
Async
Open()Hedging Series (Prerequisitefix— Ready for Independent Merge):Can be reviewed and merged directly into
main(7 files, +584 / -69), in parallel with #16715:fix, Ready):fix(storage): make OpenStream and OpenObject cancellation-safe(independent root onmain)refactor, Ready):refactor(storage): extract HedgeLimiter from HedgingThreadPool(independent root onmain)impl, Draft — stacked on refactor(storage): extract HedgeLimiter from HedgingThreadPool #16715):impl(storage): add HedgedOpenStream coordinator for async Openfeat, Draft — stacked on fix(storage): make OpenStream and OpenObject cancellation-safe #16613 + impl(storage): add HedgedOpenStream coordinator for async Open #16716):feat(storage): add speculative open hedging to AsyncClient::OpenSummary
Makes
storage_internal::OpenStreamandstorage_internal::OpenObjectsafe to cancel mid-handshake using a single-mutex operation counter inOpenStreamand wiresfuture::cancel()onOpenObject::Call()so cancelledBidiReadObjectopens abort cleanly and resolve only afterFinish()completes.Motivation
OpenStreamandOpenObjectpreviously had two cancellation hazards when anOpen()handshake (Start()-> initialWrite()-> firstRead()) was cancelled before completing:OpenStreammid-Start()/ concurrent cancellation & lifecycle races:OpenStreamtrackedpending_read_andpending_write_, but notStart(). CallingOpenStream::Cancel()whilerpc_->Start()was still in flight immediately invokedFinish(), violating gRPC's requirement not to callFinish()whileStart()is pending.OpenStream::Cancel()was not idempotent,Start()/Write()/Read()checkedcancel_before setting their pending flags (leaving a check-then-set window where a concurrentCancel()could callFinish()concurrently with a newly launched gRPC operation), andMaybeFinish()discarded itsFinish()future soOpenObject::DoFinish()could not awaitFinish()completion.Finish()ran before an in-progressCancel()completed onAsyncStreamingReadWriteRpcAuth,Auth::Finish()markedcancelled = truefirst and causedAuth::Cancel()to skipTryCancel()on an open stream.OpenObjectpromise cancellation & commit race:OpenObject::Call()created apromise<StatusOr<OpenStreamResult>>without a cancellation callback, so calling.cancel()on the returnedfuturedid not cancel the underlyingOpenStream.future::cancel()raced withOnRead()committing the opened stream to the caller (or withOnFinish()draining a failing handshake), an uncoordinated cancel could tear down a stream already handed off toObjectDescriptorImplor misreportOK/kUnavailable/kInternalinstead ofkCancelled(causing outerAsyncRetryLoopcallers to retry a cancelled open).Changes
google/cloud/storage/internal/async/open_stream.{h,cc}:std::atomic<bool>flags (cancel_,pending_read_,pending_write_,finish_issued_) with a singlestd::mutex mu_andint pending_ops_counter (BeginOp()/EndOp()) coveringStart(),Write(),Read(), andCancel()itself, with zerorpc_->*calls made while holdingmu_, and pinsself = shared_from_this()acrossCancel().rpc_->Finish()whenFinish()is called withpending_ops_ == 0(finish_promise_{null_promise_t{}}), while deferringrpc_->Finish()wheneverpending_ops_ > 0(either onFinish()or viaCancel()) untilrpc_->Cancel()and all in-flight operations drain (pending_ops_ == 0), handing that pendingfinish_future to the firstFinish()caller.std::shared_ptr<OpenStream>(self = std::move(s)) out of.then()continuations and callsEndOp()beforef.get()so streams never leak via retained upstreamfuture_shared_statecontinuations, while masking post-cancel completions (Start/Write->false,Read->std::nullopt).google/cloud/storage/internal/async/open_object.{h,cc}:CreateRpc(),OnStart(),OnWrite(), andDoFinish()unchanged frommain, initializespromise_{null_promise_t{}}to avoid a throwaway shared-state allocation in the constructor, and wirespromise_cancellation toOpenObject::OnCancel().kOpening -> kCommitted | kCancelled) withstd::move(rpc_)on commit so late cancellations never tear down an already-committed stream, calls idempotentrpc_->Cancel()beforeDoFinish()ifOnRead()loses the commit race toOnCancel(), and checksstate_ == State::kCancelledbefore!status.ok()inOnFinish()to unconditionally returnStatusCode::kCancelled.open_stream_test.cc: VerifiesInSequenceCancel-before-Finishordering inCancelBlocksAllRequest,DuplicateFinish(!Finish().valid()),CancelDuringStartDefersFinishAndHandsOffFutureOnce,CancelDuringReadDropsResponseAndReleasesRetainedPromise(includingweak_ptrrelease with a retained upstreampromise),FinishDefersUntilInFlightOpCompletes,FinishDeferredThenCancelDoesNotOverwritePromise,CancelResolvingStartInlineDefersFinishUntilCancelReturns,CancelPinsSelfWhenInlineContinuationDropsLastRef, andCancelDuringWriteReturnsFalseAndDefersFinish.open_object_test.cc: Adds parameterizedOpenObjectCancelPhaseTest.CancelsCleanlyAtHandshakePhase(kStart,kWrite,kRead,kFinish— verifyingCancel/Finishordering, post-Finishreadiness, andkCancelledprecedence overkUnavailable) and multi-threadedOpenImpl.ConcurrentCancelAndReadCompletion(includingCancel-before-Finishassertions insideFinish()).object_descriptor_impl_test.cc: UpdatesIgnoresCallbacksFromStaleStreamssoFinish[1]defers untilWrite[1]drains (matching gRPC'sFinish()contract) while still exercising the staleOnWrite()callback guard afterstream2is active.