Skip to content

fix(storage): make OpenStream and OpenObject cancellation-safe - #16613

Open
ajayky-os wants to merge 1 commit into
googleapis:mainfrom
ajayky-os:fix/storage-bidi-open-cancel
Open

ajayky-os wants to merge 1 commit into
googleapis:mainfrom
ajayky-os:fix/storage-bidi-open-cancel

Conversation

@ajayky-os

@ajayky-os ajayky-os commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Note

Async Open() Hedging Series (Prerequisite fix — Ready for Independent Merge):
Can be reviewed and merged directly into main (7 files, +584 / -69), in parallel with #16715:

  1. fix(storage): make OpenStream and OpenObject cancellation-safe #16613 (this PR — fix, Ready): fix(storage): make OpenStream and OpenObject cancellation-safe (independent root on main)
  2. refactor(storage): extract HedgeLimiter from HedgingThreadPool #16715 (refactor, Ready): refactor(storage): extract HedgeLimiter from HedgingThreadPool (independent root on main)
  3. impl(storage): add HedgedOpenStream coordinator for async Open #16716 (impl, Draft — stacked on refactor(storage): extract HedgeLimiter from HedgingThreadPool #16715): impl(storage): add HedgedOpenStream coordinator for async Open
  4. feat(storage): add speculative open hedging to AsyncClient::Open #16612 (feat, 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::Open

Summary

Makes storage_internal::OpenStream and storage_internal::OpenObject safe to cancel mid-handshake using a single-mutex operation counter in OpenStream and wires future::cancel() on OpenObject::Call() so cancelled BidiReadObject opens abort cleanly and resolve only after Finish() completes.

Motivation

OpenStream and OpenObject previously had two cancellation hazards when an Open() handshake (Start() -> initial Write() -> first Read()) was cancelled before completing:

  1. OpenStream mid-Start() / concurrent cancellation & lifecycle races:
    • OpenStream tracked pending_read_ and pending_write_, but not Start(). Calling OpenStream::Cancel() while rpc_->Start() was still in flight immediately invoked Finish(), violating gRPC's requirement not to call Finish() while Start() is pending.
    • OpenStream::Cancel() was not idempotent, Start() / Write() / Read() checked cancel_ before setting their pending flags (leaving a check-then-set window where a concurrent Cancel() could call Finish() concurrently with a newly launched gRPC operation), and MaybeFinish() discarded its Finish() future so OpenObject::DoFinish() could not await Finish() completion.
    • If Finish() ran before an in-progress Cancel() completed on AsyncStreamingReadWriteRpcAuth, Auth::Finish() marked cancelled = true first and caused Auth::Cancel() to skip TryCancel() on an open stream.
  2. OpenObject promise cancellation & commit race:
    • OpenObject::Call() created a promise<StatusOr<OpenStreamResult>> without a cancellation callback, so calling .cancel() on the returned future did not cancel the underlying OpenStream.
    • When future::cancel() raced with OnRead() committing the opened stream to the caller (or with OnFinish() draining a failing handshake), an uncoordinated cancel could tear down a stream already handed off to ObjectDescriptorImpl or misreport OK / kUnavailable / kInternal instead of kCancelled (causing outer AsyncRetryLoop callers to retry a cancelled open).

Changes

  • google/cloud/storage/internal/async/open_stream.{h,cc}:
    • Replaces the 4 separate std::atomic<bool> flags (cancel_, pending_read_, pending_write_, finish_issued_) with a single std::mutex mu_ and int pending_ops_ counter (BeginOp() / EndOp()) covering Start(), Write(), Read(), and Cancel() itself, with zero rpc_->* calls made while holding mu_, and pins self = shared_from_this() across Cancel().
    • Preserves immediate, zero-extra-allocation rpc_->Finish() when Finish() is called with pending_ops_ == 0 (finish_promise_{null_promise_t{}}), while deferring rpc_->Finish() whenever pending_ops_ > 0 (either on Finish() or via Cancel()) until rpc_->Cancel() and all in-flight operations drain (pending_ops_ == 0), handing that pending finish_ future to the first Finish() caller.
    • Moves the captured std::shared_ptr<OpenStream> (self = std::move(s)) out of .then() continuations and calls EndOp() before f.get() so streams never leak via retained upstream future_shared_state continuations, while masking post-cancel completions (Start/Write -> false, Read -> std::nullopt).
  • google/cloud/storage/internal/async/open_object.{h,cc}:
    • Leaves CreateRpc(), OnStart(), OnWrite(), and DoFinish() unchanged from main, initializes promise_{null_promise_t{}} to avoid a throwaway shared-state allocation in the constructor, and wires promise_ cancellation to OpenObject::OnCancel().
    • Uses a 3-state atomic transition (kOpening -> kCommitted | kCancelled) with std::move(rpc_) on commit so late cancellations never tear down an already-committed stream, calls idempotent rpc_->Cancel() before DoFinish() if OnRead() loses the commit race to OnCancel(), and checks state_ == State::kCancelled before !status.ok() in OnFinish() to unconditionally return StatusCode::kCancelled.
  • Unit Tests:
    • open_stream_test.cc: Verifies InSequence Cancel-before-Finish ordering in CancelBlocksAllRequest, DuplicateFinish (!Finish().valid()), CancelDuringStartDefersFinishAndHandsOffFutureOnce, CancelDuringReadDropsResponseAndReleasesRetainedPromise (including weak_ptr release with a retained upstream promise), FinishDefersUntilInFlightOpCompletes, FinishDeferredThenCancelDoesNotOverwritePromise, CancelResolvingStartInlineDefersFinishUntilCancelReturns, CancelPinsSelfWhenInlineContinuationDropsLastRef, and CancelDuringWriteReturnsFalseAndDefersFinish.
    • open_object_test.cc: Adds parameterized OpenObjectCancelPhaseTest.CancelsCleanlyAtHandshakePhase (kStart, kWrite, kRead, kFinish — verifying Cancel/Finish ordering, post-Finish readiness, and kCancelled precedence over kUnavailable) and multi-threaded OpenImpl.ConcurrentCancelAndReadCompletion (including Cancel-before-Finish assertions inside Finish()).
    • object_descriptor_impl_test.cc: Updates IgnoresCallbacksFromStaleStreams so Finish[1] defers until Write[1] drains (matching gRPC's Finish() contract) while still exercising the stale OnWrite() callback guard after stream2 is active.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

codecov Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.54128% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.80%. Comparing base (088ccec) to head (e6721ba).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
google/cloud/storage/internal/async/open_object.cc 87.50% 2 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

{
std::lock_guard<std::mutex> lk(mu_);
if (finish_issued_) return std::move(finish_);
finish_issued_ = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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([] {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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()?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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())?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in e6721ba — added CancelDuringWriteReturnsFalseAndDefersFinish in open_stream_test.cc, resolving Write() to true after Cancel() and asserting EXPECT_FALSE(write.get()).

@ajayky-os
ajayky-os force-pushed the fix/storage-bidi-open-cancel branch from ac48a20 to e6721ba Compare December 1, 2026 06:20

This branch was successfully deployed

1 active (outdated) deployment
false — 184911fd Deployed Nov 2, 2026 by ajayky-os via Save PR ref #12770
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

api: storage Issues related to the Cloud Storage API.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants