Skip to content

fix(workflow): retry server-sent CANCELLED during orchestration waits (closes #1246) - #1370

Open
NaniToka wants to merge 4 commits into
dapr:mainfrom
NaniToka:fix/workflow-retry-server-cancelled-wait-1246
Open

NaniToka wants to merge 4 commits into
dapr:mainfrom
NaniToka:fix/workflow-retry-server-cancelled-wait-1246

Conversation

@NaniToka

@NaniToka NaniToka commented Nov 14, 2026 •

Copy link
Copy Markdown

Description

Implements the proposal in #1246 by @CasperGN: re-issue WaitForInstanceCompletion and WaitForInstanceStart (sync and async) when the server ends the wait call with grpc.StatusCode.CANCELLED and the caller's timeout has not expired.

Problem

When daprd shuts down or restarts mid-wait (e.g. rollouts, pod restarts, runtime reload), the actors router cancels all in-flight calls it tracks (dapr/dapr#10566). Previously, this caused wait_for_orchestration_completion and wait_for_orchestration_start to abort and raise grpc.RpcError(StatusCode.CANCELLED) immediately, even though the workflow is intact and running on durable storage.

Solution

  1. Add CANCELLED to _TRANSIENT_RPC_CODES:
    • Added grpc.StatusCode.CANCELLED to _TRANSIENT_RPC_CODES in both TaskHubGrpcClient (dapr/ext/workflow/_durabletask/client.py) and AsyncTaskHubGrpcClient (dapr/ext/workflow/_durabletask/aio/client.py).
    • Callers' timeout deadlines remain strictly enforced: _is_deadline_cancellation() maps deadline expiration to _TransientTimeout (TimeoutError), ensuring that caller-specified deadlines are never exceeded.
  2. Refresh Transient Grace Window on In-Flight Wait Cancellations (Capped):
    • In unbounded wait mode (timeout=0), when a healthy wait was in-flight and held by daprd before being cancelled by a restart, transient_deadline and backoff are refreshed, capped at _MAX_CONSECUTIVE_TRANSIENT_RESETS = 3 to prevent infinite loops from persistent proxy idle timeouts or sidecar crash loops.
    • Immediate/consecutive errors (e.g. from an unavailable sidecar or proxy reset) continue to count down the 30s grace window before propagating the original error.
    • If the client is closed locally while a wait is in-flight, CANCELLED is re-raised immediately without retrying or invoking calls on the closed channel.
  3. Public API Additions (for Release Notes):
    • Added is_closed property to both sync and async DaprWorkflowClient (and underlying TaskHubGrpcClient / AsyncTaskHubGrpcClient) to inspect channel closure status.
    • Added close(), aclose(), and async context manager (async with) support to dapr.ext.workflow.aio.DaprWorkflowClient.
    • Added context manager (with) support to dapr.ext.workflow.DaprWorkflowClient.
  4. Tests:
    • Flipped the tests from Add stateful-history delta delivery to the workflow worker #1112 (test_cancelled_within_deadline_still_propagates, test_cancelled_unbounded_wait_still_propagates in sync and async) to verify that CANCELLED is absorbed, retried with backoff, and succeeds when the subsequent wait call returns the workflow state.
    • Added tests verifying that multiple restarts separated by long waits succeed without exhausting the transient window.
    • Added tests verifying that persistent cancellations give up with grpc.RpcError once the grace window or consecutive reset cap elapses.
    • Added tests verifying client closure marks is_closed and avoids re-invoking on closed channels.
    • Added tests for is_closed, close(), aclose(), and context manager lifecycles across sync and async public DaprWorkflowClients.

Issue reference

Please reference the issue this PR will close: Closes #1246

Checklist

  • Code compiles correctly
  • Created/updated tests
  • Extended the documentation

…closes dapr#1246)

When daprd shuts down or restarts mid-wait (rollouts, pod restarts, runtime reload),
the actors router cancels in-flight calls, causing WaitForInstanceCompletion and
WaitForInstanceStart to receive grpc.StatusCode.CANCELLED ('context canceled').
Previously, this caused waits to abort and raise RpcError even though the
workflow instance was still running on persistent state.

- Add grpc.StatusCode.CANCELLED to _TRANSIENT_RPC_CODES in sync and async clients.
  Callers' timeout deadlines continue to be strictly enforced via _is_deadline_cancellation(),
  which converts deadline expiration into TimeoutError.
- In unbounded wait mode (timeout=0), refresh the 30s transient grace window and reset
  exponential backoff whenever a healthy in-flight wait was held by daprd before being cancelled,
  ensuring that long-running workflows survive multiple sidecar restarts.
- Update tests from dapr#1112 that previously asserted immediate failure on CANCELLED to verify
  that server-sent CANCELLED is retried with backoff and succeeds on subsequent re-issue.
- Add unit tests verifying multiple sidecar restarts across long waits in both sync and async clients.

Fixes dapr#1246

Signed-off-by: NaniToka <tokananiy@gmail.com>
@CasperGN

Copy link
Copy Markdown
Contributor

Claude review · not a review sign-off.

  1. Adding CANCELLED to _TRANSIENT_RPC_CODES also retries a cancellation the client caused itself. Closing the client while an unbounded wait_for_orchestration_completion is in flight used to raise grpc.RpcError (CANCELLED, "Channel closed!") straight away. At this head the loop retries on the closed channel and raises ValueError('Cannot invoke RPC on closed channel!') about 0.5s later, so callers that catch grpc.RpcError on shutdown miss it. Consider re-raising CANCELLED once the client has been closed locally. Repro: an in-process server whose WaitForInstanceCompletion sleeps, timeout=0, and the channel closed after 1.5s. The async client has the same list.
    _TRANSIENT_RPC_CODES = (
    grpc.StatusCode.CANCELLED,
    grpc.StatusCode.FAILED_PRECONDITION,
    grpc.StatusCode.UNAVAILABLE,
    )

Minor

  1. The _is_deadline_cancellation docstring still says a genuine cancellation keeps "propagating as-is". With CANCELLED now transient, it is retried instead.
    def _is_deadline_cancellation(code, deadline: Optional[float]) -> bool:
    """Reports whether a CANCELLED status is really the caller's deadline expiring.
    As a bounded wait times out, the sidecar can reset the stream (RST_STREAM
    CANCEL) marginally before gRPC raises DEADLINE_EXCEEDED locally, so the same
    expiry surfaces as CANCELLED. Callers asked for a timeout and must see
    TimeoutError either way. Requiring the budget to be spent keeps a genuine
    cancellation, or a reset with time still on the clock, propagating as-is.
    """
    if code != grpc.StatusCode.CANCELLED or deadline is None:
    return False
    return time.monotonic() >= deadline

Reviewed at bcddae9.
Disagree, or want to talk it through? Reply /human and Casper will pick it up.

@NaniToka

Copy link
Copy Markdown
Author

Thanks for the thorough review and catch @CasperGN!

You're completely right — when the client or underlying channel is closed locally during an in-flight wait, retrying on the terminated channel caused gRPC to raise ValueError('Cannot invoke RPC on closed channel!') ~0.5s later, masking the expected grpc.RpcError(StatusCode.CANCELLED) on shutdown.

Pushed a fix in 8260cf1:

  1. Local closure check: Added _is_closed tracking (set in close() / aclose(), exposed via property) and details check for 'channel closed' in _call_with_transient_retry. If the client has been closed locally, StatusCode.CANCELLED is immediately re-raised without backoff or attempting to re-invoke on the closed channel.
  2. Async parity: Mirrored the identical _is_closed guard and aclose() lifecycle in AsyncTaskHubGrpcClient.
  3. Docstring update: Updated _is_deadline_cancellation to clearly state that server-sent cancellations are treated as transient and retried until deadline expiry or local client closure.
  4. Regression tests: Added tests for both sync and async clients verifying that local client closure and channel-closed details re-raise grpc.RpcError immediately on the first attempt without sleeping, retrying, or raising ValueError.

@CasperGN CasperGN left a comment

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.

Thanks @NaniToka for picking up #1246 and for your interest in the project! 🙌 Retrying a server-sent CANCELLED only while the caller still has time left, and still turning a cancellation at the deadline into TimeoutError, is what the issue asked for. Stopping right away once the client is closed locally is a nice touch, and the in-flight close tests cover it well 🧪. I left a few comments inline, please take a look.

A few more notes:

  • Only the DCO check is reported on this head commit so far, so the build and test workflows still need to run before this can merge.
  • The PR also adds public API that the description doesn't mention: is_closed on both DaprWorkflowClients, plus aclose(), close() and async with support on the async one. Could you list these in the description so they show up in the release notes?

Drafted with AI assistance and reviewed by me.

# before being cancelled by a new restart, restart the grace
# window and reset backoff rather than anchoring on the first error.
if unbounded:
if code == grpc.StatusCode.CANCELLED and call_duration >= 1.0:

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.

With an unbounded wait, any CANCELLED that took at least 1s clears transient_deadline, so nothing caps how many times we retry. If something between the client and daprd always cancels after a second or more (a proxy idle timeout, an interceptor, a daprd stuck in a restart loop), wait_for_orchestration_completion(timeout=0) keeps retrying forever, logging only warnings. Before this change, the 30s window always ended in an error. What do you think about capping the number of resets in a row (or the total time spent retrying), or at least logging at a higher level when the window resets? A test where every attempt is CANCELLED after more than 1s would pin down whichever behaviour we choose. The same applies to the async client at aio/client.py line 324.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Really sharp catch on the unbounded wait loop when a proxy or restart cycle keeps cancelling.

I went with capping consecutive in-flight resets: added _MAX_CONSECUTIVE_TRANSIENT_RESETS = 3 to both sync and async clients. If cancellations keep arriving after >=1s, the 30s grace window is refreshed up to 3 times (with a warning log showing the count). Once the cap is reached, the window no longer extends, allowing persistent failure modes to surface the real RpcError instead of spinning forever.

Added regression tests in test_orchestration_wait.py and test_client_async.py verifying that continuous in-flight cancellations eventually propagate.

return WorkflowRerunResult(new_instance_id=res.newInstanceID, staged=res.staged)

@property
def is_closed(self) -> bool:

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 adds is_closed, aclose(), close() and __aenter__/__aexit__ to the public async DaprWorkflowClient (and is_closed to the sync one), but the new tests only cover the _durabletask clients. Could you add a small test that async with DaprWorkflowClient(...) closes the inner client and that is_closed reflects it? These will be public API once released, so a test keeps them from regressing.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Definitely — added tests covering is_closed, close(), aclose(), and context managers (with and async with) across test_workflow_client.py and test_workflow_client_aio.py.

I also added __enter__ / __exit__ to the sync DaprWorkflowClient so both sync and async clients share the same context manager ergonomics.

raise

now = time.monotonic()
call_duration = time.perf_counter() - call_start

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.

nit: call_duration uses time.perf_counter(), while every other timing in this loop uses time.monotonic(). Using time.monotonic() for call_start as well would keep one clock here and mean tests only need to patch one function. The same goes for the async client.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good spot! Switched call_start to time.monotonic() and compute call_duration = now - call_start directly. Much cleaner to stick to a single clock, and it let us drop the extra perf_counter mock from the test suite as well.

…add public client tests

- Cap consecutive transient grace window resets in unbounded wait mode
  (_MAX_CONSECUTIVE_TRANSIENT_RESETS = 3) for both sync and async clients,
  preventing persistent proxy/sidecar cancellation loops from retrying indefinitely.
- Log warning with reset counter and warning on reset cap exhaustion.
- Use time.monotonic() consistently for call_start and call_duration in both
  sync and async retry loops, eliminating time.perf_counter().
- Add context manager (__enter__/__exit__) to sync DaprWorkflowClient.
- Add unit tests for public DaprWorkflowClient lifecycle (is_closed, close,
  aclose, and context managers in sync and async).
- Add regression tests verifying consecutive in-flight cancellations are capped
  and eventually propagate grpc.RpcError(StatusCode.CANCELLED).

Signed-off-by: NaniToka <tokananiy@gmail.com>
@NaniToka

Copy link
Copy Markdown
Author

Thanks for the thorough follow-up review, @CasperGN!

Pushed commit fa01cd3 addressing all 3 items:

  • Capping in-flight resets: You were completely right about the unbounded wait risk with proxy timeouts or restart loops. I added _MAX_CONSECUTIVE_TRANSIENT_RESETS = 3 (with warning logs tracking reset count) in both sync and async clients. Once the cap is hit, it stops refreshing the grace window so the error surfaces. Added tests pinning this behavior down.
  • Clock unification: Switched call_start to time.monotonic() and removed the secondary perf_counter patches in the test suite.
  • Public client tests & parity: Added lifecycle tests for is_closed, close(), aclose(), and context manager support (with / async with) on both sync and async DaprWorkflowClients. Also added __enter__/__exit__ to the sync client so both have identical context manager ergonomics.
  • Release notes: Updated the PR description with the new public APIs (is_closed, close(), aclose(), and context managers).

Whenever you get a chance, could you trigger the CI test workflow on this commit? Thanks again for helping steer the design!

@CasperGN CasperGN left a comment

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.

Round 3 of 3: follow-up on the changes since 8260cf1.

Every earlier blocker is resolved and the new changes add none.

Nits, not blocking:

  • F1: Grace-window refresh only applies to CANCELLED, so a later restart that surfaces as UNAVAILABLE/FAILED_PRECONDITION after a long healthy wait is raised immediately against the stale transient_deadline (dapr/ext/workflow/_durabletask/client.py)
  • F2: Mixes perf_counter with monotonic and hardcodes the 1.0s healthy-wait threshold in both clients (dapr/ext/workflow/_durabletask/client.py)

Drafted with AI assistance and reviewed by me.

@NaniToka

Copy link
Copy Markdown
Author

Thanks so much for the thorough review and guidance throughout this, @CasperGN! Really appreciate your help in steering the design. Made a note of the non-blocking nits on the grace window and threshold constants for follow-up improvements down the road. Whenever you have a moment to trigger the CI run, it should be all set to go! 🙌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[WORKFLOW SDK FEATURE REQUEST] Retry WaitForInstanceCompletion/Start on a server-sent CANCELLED

2 participants