Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 56 additions & 6 deletions dapr/ext/workflow/_durabletask/aio/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,12 @@ def __init__(
self._channel: grpc.aio.Channel | None = None
self._stub: stubs.TaskHubSidecarServiceStub | None = None
self._logger = shared.get_logger('client', log_handler, log_formatter)
self._is_closed = False

@property
def is_closed(self) -> bool:
"""Returns True if the client has been closed."""
return self._is_closed

def _get_stub(self) -> stubs.TaskHubSidecarServiceStub:
"""Lazily create the channel and stub on first use.
Expand All @@ -99,9 +105,15 @@ def _get_stub(self) -> stubs.TaskHubSidecarServiceStub:
return self._stub

async def aclose(self):
"""Close the underlying gRPC channel."""
self._is_closed = True
if self._channel is not None:
await self._channel.close()

async def close(self):
"""Alias for aclose()."""
await self.aclose()

async def __aenter__(self):
return self

Expand Down Expand Up @@ -247,11 +259,12 @@ async def _call(grpc_timeout):

# Transient gRPC codes that indicate the workflow runtime is temporarily
# unable to locate the workflow actor — typically immediately after a Dapr
# sidecar restart (e.g. recovery from chaos). The placement service has the
# actor registration, but local daprd hasn't received the dissemination yet.
# Without retry, every poll fails permanently with FAILED_PRECONDITION even
# though the workflow runtime state is intact.
# sidecar restart (e.g. recovery from chaos), or when daprd cancels in-flight
# wait calls on runtime restart/reload (dapr/dapr#10566, dapr/python-sdk#1246).
# Without retry, every poll fails permanently with FAILED_PRECONDITION/CANCELLED
# even though the workflow runtime state is intact.
_TRANSIENT_RPC_CODES = (
grpc.StatusCode.CANCELLED,
grpc.StatusCode.FAILED_PRECONDITION,
grpc.StatusCode.UNAVAILABLE,
)
Expand All @@ -260,10 +273,11 @@ async def _call(grpc_timeout):
# unbounded (timeout=0) callers so a down sidecar surfaces the original
# error instead of retrying forever.
_MAX_TRANSIENT_RETRY_SECONDS = 30.0
_MAX_CONSECUTIVE_TRANSIENT_RESETS = 3

async def _call_with_transient_retry(self, instance_id, timeout, call_fn):
"""Async mirror of TaskHubGrpcClient._call_with_transient_retry.
Retries FAILED_PRECONDITION/UNAVAILABLE with capped exponential
Retries FAILED_PRECONDITION/UNAVAILABLE/CANCELLED with capped exponential
backoff while clamping sleep and per-call gRPC timeout to the
remaining budget. The first call uses the caller's timeout unchanged
(``None`` when unbounded) so callers observe identical behavior on a
Expand All @@ -276,7 +290,9 @@ async def _call_with_transient_retry(self, instance_id, timeout, call_fn):
grpc_timeout = None if unbounded else timeout
backoff = 0.5
transient_deadline = None # unbounded mode only; anchored on first transient
consecutive_resets = 0
while True:
call_start = time.monotonic()
try:
return await call_fn(grpc_timeout)
except grpc.RpcError as rpc_error:
Expand All @@ -285,12 +301,46 @@ async def _call_with_transient_retry(self, instance_id, timeout, call_fn):
raise _TransientTimeout()
if TaskHubGrpcClient._is_deadline_cancellation(code, deadline):
raise _TransientTimeout()
details = (
rpc_error.details()
if hasattr(rpc_error, 'details') and callable(rpc_error.details)
else str(rpc_error)
) or ''
if self._is_closed or (
code == grpc.StatusCode.CANCELLED and 'channel closed' in details.lower()
):
raise
if code not in self._TRANSIENT_RPC_CODES:
raise

now = time.monotonic()

call_duration = now - call_start

# In unbounded mode the user budget can't end the loop, so cap
# continuous transient retries and re-raise the original error
# (matching pre-retry behavior) once the grace window elapses.
# If a re-issued wait was healthy and in-flight (held by daprd)
# before being cancelled by a new restart, restart the grace
# window and reset backoff rather than anchoring on the first error,
# up to _MAX_CONSECUTIVE_TRANSIENT_RESETS times to avoid infinite retry loops.
if unbounded:
if code == grpc.StatusCode.CANCELLED and call_duration >= 1.0:
if consecutive_resets < self._MAX_CONSECUTIVE_TRANSIENT_RESETS:
consecutive_resets += 1
transient_deadline = None
backoff = 0.5
self._logger.warning(
f"In-flight wait for instance '{instance_id}' was cancelled by server after "
f'{call_duration:.1f}s; resetting transient retry grace window '
f'({consecutive_resets}/{self._MAX_CONSECUTIVE_TRANSIENT_RESETS}).'
)
else:
self._logger.warning(
f"In-flight wait for instance '{instance_id}' reached maximum "
f'consecutive grace window resets ({self._MAX_CONSECUTIVE_TRANSIENT_RESETS}); '
f'transient retry window will not be extended further.'
)

if transient_deadline is None:
transient_deadline = now + self._MAX_TRANSIENT_RETRY_SECONDS
elif now >= transient_deadline:
Expand Down
55 changes: 49 additions & 6 deletions dapr/ext/workflow/_durabletask/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,6 +278,12 @@ def __init__(
self._channel = channel
self._stub = stubs.TaskHubSidecarServiceStub(channel)
self._logger = shared.get_logger('client', log_handler, log_formatter)
self._is_closed = False

@property
def is_closed(self) -> bool:
"""Returns True if the client has been closed."""
return self._is_closed

def __enter__(self):
return self
Expand All @@ -291,6 +297,7 @@ def __exit__(self, exc_type, exc, tb):

def close(self) -> None:
"""Close the underlying gRPC channel."""
self._is_closed = True
try:
# grpc.Channel.close() is idempotent
self._channel.close()
Expand Down Expand Up @@ -436,11 +443,12 @@ def _call(grpc_timeout):

# Transient gRPC codes that indicate the workflow runtime is temporarily
# unable to locate the workflow actor — typically immediately after a Dapr
# sidecar restart (e.g. recovery from chaos). The placement service has the
# actor registration, but local daprd hasn't received the dissemination yet.
# Without retry, every poll fails permanently with FAILED_PRECONDITION even
# though the workflow runtime state is intact.
# sidecar restart (e.g. recovery from chaos), or when daprd cancels in-flight
# wait calls on runtime restart/reload (dapr/dapr#10566, dapr/python-sdk#1246).
# Without retry, every poll fails permanently with FAILED_PRECONDITION/CANCELLED
# even though the workflow runtime state is intact.
_TRANSIENT_RPC_CODES = (
grpc.StatusCode.CANCELLED,
grpc.StatusCode.FAILED_PRECONDITION,
grpc.StatusCode.UNAVAILABLE,
)
Expand All @@ -452,6 +460,7 @@ def _call(grpc_timeout):
# a slow-but-healthy workflow never enters this path (it just blocks in
# the long-poll), so its indefinite wait is preserved.
_MAX_TRANSIENT_RETRY_SECONDS = 30.0
_MAX_CONSECUTIVE_TRANSIENT_RESETS = 3

@staticmethod
def _is_deadline_cancellation(code, deadline: Optional[float]) -> bool:
Expand All @@ -460,8 +469,9 @@ def _is_deadline_cancellation(code, deadline: Optional[float]) -> bool:
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.
TimeoutError either way. When the deadline has not expired, server-sent
cancellations are treated as transient errors and retried until the budget
elapses or the client is closed locally.
"""
if code != grpc.StatusCode.CANCELLED or deadline is None:
return False
Expand All @@ -487,7 +497,9 @@ def _call_with_transient_retry(self, instance_id, timeout, call_fn):
grpc_timeout = None if unbounded else timeout
backoff = 0.5
transient_deadline = None # unbounded mode only; anchored on first transient
consecutive_resets = 0
while True:
call_start = time.monotonic()
try:
return call_fn(grpc_timeout)
except grpc.RpcError as rpc_error:
Expand All @@ -496,15 +508,46 @@ def _call_with_transient_retry(self, instance_id, timeout, call_fn):
raise _TransientTimeout()
if self._is_deadline_cancellation(code, deadline):
raise _TransientTimeout()
details = (
rpc_error.details()
if hasattr(rpc_error, 'details') and callable(rpc_error.details)
else str(rpc_error)
) or ''
if self._is_closed or (
code == grpc.StatusCode.CANCELLED and 'channel closed' in details.lower()
):
raise
if code not in self._TRANSIENT_RPC_CODES:
raise

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

# In unbounded mode the user budget can't end the loop, so cap
# continuous transient retries and re-raise the original error
# (matching pre-retry behavior) once the grace window elapses.
# If a re-issued wait was healthy and in-flight (held by daprd)
# before being cancelled by a new restart, restart the grace
# window and reset backoff rather than anchoring on the first error,
# up to _MAX_CONSECUTIVE_TRANSIENT_RESETS times to avoid infinite retry loops.
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.

if consecutive_resets < self._MAX_CONSECUTIVE_TRANSIENT_RESETS:
consecutive_resets += 1
transient_deadline = None
backoff = 0.5
self._logger.warning(
f"In-flight wait for instance '{instance_id}' was cancelled by server after "
f'{call_duration:.1f}s; resetting transient retry grace window '
f'({consecutive_resets}/{self._MAX_CONSECUTIVE_TRANSIENT_RESETS}).'
)
else:
self._logger.warning(
f"In-flight wait for instance '{instance_id}' reached maximum "
f'consecutive grace window resets ({self._MAX_CONSECUTIVE_TRANSIENT_RESETS}); '
f'transient retry window will not be extended further.'
)

if transient_deadline is None:
transient_deadline = now + self._MAX_TRANSIENT_RETRY_SECONDS
elif now >= transient_deadline:
Expand Down
20 changes: 20 additions & 0 deletions dapr/ext/workflow/aio/dapr_workflow_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -793,3 +793,23 @@ async def rerun_workflow_from_event_with_result(
app_id=app_id,
)
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.

"""Returns True if the client has been closed."""
return self.__obj.is_closed

async def aclose(self):
"""Closes the gRPC connection used by the client."""
await self.__obj.aclose()

async def close(self):
"""Closes the gRPC connection used by the client."""
await self.aclose()

async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc_val, exc_tb):
await self.aclose()
return False
12 changes: 12 additions & 0 deletions dapr/ext/workflow/dapr_workflow_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,18 @@ def rerun_workflow_from_event_with_result(
)
return WorkflowRerunResult(new_instance_id=res.newInstanceID, staged=res.staged)

@property
def is_closed(self) -> bool:
"""Returns True if the client has been closed."""
return self.__obj.is_closed

def close(self):
"""Closes the gRPC connection used by the client."""
return self.__obj.close()

def __enter__(self):
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
return False
Loading