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

Stacked PR (1 of 2): Standalone cancellation-safety prerequisite for #16612 (feat(storage): add speculative open hedging to AsyncClient::Open). Can be reviewed and merged independently (6 files, +375 / -55).

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_.
    • Preserves immediate, zero-extra-allocation rpc_->Finish() when Finish() is called on an uncancelled stream (finish_promise_{null_promise_t{}}), while deferring rpc_->Finish() on cancelled streams 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, and CancelDuringReadDropsResponseAndReleasesRetainedPromise (including weak_ptr release with a retained upstream promise).
    • 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.

@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.28058% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.79%. Comparing base (088ccec) to head (ac48a20).
⚠️ Report is 1 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.79%   +0.02%     
==========================================
  Files        2273     2273              
  Lines      227827   228066     +239     
==========================================
+ Hits       211355   211623     +268     
+ Misses      16472    16443      -29     

☔ 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 from 184911f to bb6e5de Compare November 25, 2026 08:52
@ajayky-os
ajayky-os marked this pull request as ready for review November 25, 2026 12:13
@ajayky-os
ajayky-os requested review from a team as code owners November 25, 2026 12:13
@ajayky-os
ajayky-os force-pushed the fix/storage-bidi-open-cancel branch from bb6e5de to ac48a20 Compare November 26, 2026 06:47

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.

1 participant