Skip to content

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

Merged
ajayky-os merged 1 commit into
googleapis:mainfrom
ajayky-os:fix/storage-bidi-open-cancel
Dec 3, 2026
Merged

ajayky-os merged 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.54338% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.93%. Comparing base (79985ca) to head (b97753d).

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.91%   92.93%   +0.01%     
==========================================
  Files        2282     2282              
  Lines      232266   232655     +389     
==========================================
+ Hits       215820   216210     +390     
+ Misses      16446    16445       -1     

☔ 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.

@ajayky-os
ajayky-os force-pushed the fix/storage-bidi-open-cancel branch 2 times, most recently from e6721ba to 065dd69 Compare December 2, 2026 06:44
@ajayky-os
ajayky-os force-pushed the fix/storage-bidi-open-cancel branch from 065dd69 to 95cdd8f Compare December 3, 2026 08:54
@ajayky-os
ajayky-os force-pushed the fix/storage-bidi-open-cancel branch from 95cdd8f to b97753d Compare December 3, 2026 09:21
@ajayky-os
ajayky-os merged commit 261271c into googleapis:main Dec 3, 2026
68 checks passed
@ajayky-os
ajayky-os deleted the fix/storage-bidi-open-cancel branch December 3, 2026 11:08
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