diff --git a/dapr/ext/workflow/_durabletask/aio/client.py b/dapr/ext/workflow/_durabletask/aio/client.py index 77f5eb82d..9d1c3e973 100644 --- a/dapr/ext/workflow/_durabletask/aio/client.py +++ b/dapr/ext/workflow/_durabletask/aio/client.py @@ -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. @@ -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 @@ -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, ) @@ -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 @@ -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: @@ -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: diff --git a/dapr/ext/workflow/_durabletask/client.py b/dapr/ext/workflow/_durabletask/client.py index fbe1c87fa..75668e932 100644 --- a/dapr/ext/workflow/_durabletask/client.py +++ b/dapr/ext/workflow/_durabletask/client.py @@ -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 @@ -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() @@ -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, ) @@ -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: @@ -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 @@ -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: @@ -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: + 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: diff --git a/dapr/ext/workflow/aio/dapr_workflow_client.py b/dapr/ext/workflow/aio/dapr_workflow_client.py index a01db930b..75ddf590a 100644 --- a/dapr/ext/workflow/aio/dapr_workflow_client.py +++ b/dapr/ext/workflow/aio/dapr_workflow_client.py @@ -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: + """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 diff --git a/dapr/ext/workflow/dapr_workflow_client.py b/dapr/ext/workflow/dapr_workflow_client.py index ab88fc776..565e20498 100644 --- a/dapr/ext/workflow/dapr_workflow_client.py +++ b/dapr/ext/workflow/dapr_workflow_client.py @@ -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 diff --git a/tests/ext/workflow/durabletask/test_client_async.py b/tests/ext/workflow/durabletask/test_client_async.py index b23c69af6..f769ebd15 100644 --- a/tests/ext/workflow/durabletask/test_client_async.py +++ b/tests/ext/workflow/durabletask/test_client_async.py @@ -10,7 +10,8 @@ # limitations under the License. import asyncio -from unittest.mock import Mock, patch +from typing import Optional +from unittest.mock import AsyncMock, Mock, patch import grpc import pytest @@ -20,6 +21,7 @@ DefaultClientInterceptorImpl, ) from dapr.ext.workflow._durabletask.aio.internal.shared import get_grpc_aio_channel +from dapr.ext.workflow._durabletask.client import OrchestrationStatus from dapr.ext.workflow._durabletask.internal.shared import get_default_host_address HOST_ADDRESS = 'localhost:50051' @@ -27,10 +29,10 @@ INTERCEPTORS_AIO = [DefaultClientInterceptorImpl(METADATA)] -def _make_async_rpc_error(code: grpc.StatusCode) -> grpc.RpcError: +def _make_async_rpc_error(code: grpc.StatusCode, details: Optional[str] = None) -> grpc.RpcError: err = grpc.RpcError() err.code = lambda: code # type: ignore[method-assign] - err.details = lambda: f'simulated {code.name}' # type: ignore[method-assign] + err.details = lambda: details if details is not None else f'simulated {code.name}' # type: ignore[method-assign] return err @@ -245,16 +247,276 @@ async def cancel_after_budget_spent(*args, **kwargs): await client.wait_for_orchestration_completion('test-instance', timeout=0.01) -async def test_cancelled_within_deadline_still_propagates(): - """A CANCELLED with budget remaining is a real cancellation, not a timeout.""" +async def test_cancelled_within_deadline_retries_then_succeeds(monkeypatch): + """A server-sent CANCELLED with deadline budget remaining is retried.""" + instance_id = 'test-instance' - async def cancel_immediately(*args, **kwargs): + from dapr.ext.workflow._durabletask.internal.protos import ( + ORCHESTRATION_STATUS_COMPLETED, + GetInstanceResponse, + WorkflowState, + ) + + response = GetInstanceResponse() + response.exists = True + state = WorkflowState() + state.instanceId = instance_id + state.workflowStatus = ORCHESTRATION_STATUS_COMPLETED + response.workflowState.CopyFrom(state) + + sleeps = [] + + async def fake_sleep(s): + sleeps.append(s) + + monkeypatch.setattr('asyncio.sleep', fake_sleep) + + calls = {'n': 0} + + async def fake_call(*args, **kwargs): + calls['n'] += 1 + if calls['n'] == 1: + raise _make_async_rpc_error(grpc.StatusCode.CANCELLED) + return response + + client = AsyncTaskHubGrpcClient() + client._stub = Mock() + client._stub.WaitForInstanceCompletion = fake_call + + res = await client.wait_for_orchestration_completion(instance_id, timeout=300) + assert res is not None + assert res.runtime_status == OrchestrationStatus.COMPLETED + assert calls['n'] == 2 + assert len(sleeps) == 1 and sleeps[0] > 0 + + +async def test_cancelled_unbounded_wait_retries_then_succeeds(monkeypatch): + """With timeout=0 (unbounded), async wait retries server-sent CANCELLED.""" + instance_id = 'test-instance' + + from dapr.ext.workflow._durabletask.internal.protos import ( + ORCHESTRATION_STATUS_COMPLETED, + GetInstanceResponse, + WorkflowState, + ) + + response = GetInstanceResponse() + response.exists = True + state = WorkflowState() + state.instanceId = instance_id + state.workflowStatus = ORCHESTRATION_STATUS_COMPLETED + response.workflowState.CopyFrom(state) + + sleeps = [] + + async def fake_sleep(s): + sleeps.append(s) + + monkeypatch.setattr('asyncio.sleep', fake_sleep) + + calls = {'n': 0} + + async def fake_call(*args, **kwargs): + calls['n'] += 1 + if calls['n'] == 1: + raise _make_async_rpc_error(grpc.StatusCode.CANCELLED) + return response + + client = AsyncTaskHubGrpcClient() + client._stub = Mock() + client._stub.WaitForInstanceCompletion = fake_call + + res = await client.wait_for_orchestration_completion(instance_id, timeout=0) + assert res is not None + assert res.runtime_status == OrchestrationStatus.COMPLETED + assert calls['n'] == 2 + assert len(sleeps) == 1 and sleeps[0] > 0 + + +async def test_unbounded_wait_retries_across_multiple_sidecar_restarts(monkeypatch): + """Async unbounded wait survives multiple sidecar restarts separated by long waits.""" + instance_id = 'test-instance' + + from dapr.ext.workflow._durabletask.internal.protos import ( + ORCHESTRATION_STATUS_COMPLETED, + GetInstanceResponse, + WorkflowState, + ) + + response = GetInstanceResponse() + response.exists = True + state = WorkflowState() + state.instanceId = instance_id + state.workflowStatus = ORCHESTRATION_STATUS_COMPLETED + response.workflowState.CopyFrom(state) + + fake_time = [0.0] + + def fake_monotonic(): + return fake_time[0] + + async def fake_sleep(s): + pass + + monkeypatch.setattr('dapr.ext.workflow._durabletask.aio.client.time.monotonic', fake_monotonic) + monkeypatch.setattr('asyncio.sleep', fake_sleep) + + calls = {'n': 0} + + async def fake_call(*args, **kwargs): + calls['n'] += 1 + if calls['n'] == 1: + fake_time[0] += 10.0 + raise _make_async_rpc_error(grpc.StatusCode.CANCELLED) + if calls['n'] == 2: + fake_time[0] += 60.0 + raise _make_async_rpc_error(grpc.StatusCode.CANCELLED) + fake_time[0] += 5.0 + return response + + client = AsyncTaskHubGrpcClient() + client._stub = Mock() + client._stub.WaitForInstanceCompletion = fake_call + + res = await client.wait_for_orchestration_completion(instance_id, timeout=0) + assert res is not None + assert res.runtime_status == OrchestrationStatus.COMPLETED + assert calls['n'] == 3 + + +async def test_unbounded_wait_async_caps_consecutive_in_flight_cancellations(monkeypatch): + """When every async wait attempt is CANCELLED after >= 1s, the client caps consecutive + window resets (_MAX_CONSECUTIVE_TRANSIENT_RESETS) and eventually propagates + the CANCELLED RpcError rather than looping forever.""" + instance_id = 'test-instance' + + fake_time = [0.0] + + def fake_monotonic(): + return fake_time[0] + + async def fake_sleep(s): + pass + + monkeypatch.setattr('dapr.ext.workflow._durabletask.aio.client.time.monotonic', fake_monotonic) + monkeypatch.setattr('asyncio.sleep', fake_sleep) + + calls = {'n': 0} + + async def fake_call(*args, **kwargs): + calls['n'] += 1 + fake_time[0] += 5.0 # >= 1.0s in-flight before server cancellation raise _make_async_rpc_error(grpc.StatusCode.CANCELLED) client = AsyncTaskHubGrpcClient() client._stub = Mock() - client._stub.WaitForInstanceCompletion = cancel_immediately + client._stub.WaitForInstanceCompletion = fake_call with pytest.raises(grpc.RpcError) as exc_info: - await client.wait_for_orchestration_completion('test-instance', timeout=300) - assert not isinstance(exc_info.value, TimeoutError) + await client.wait_for_orchestration_completion(instance_id, timeout=0) + + assert exc_info.value.code() == grpc.StatusCode.CANCELLED + assert calls['n'] > AsyncTaskHubGrpcClient._MAX_CONSECUTIVE_TRANSIENT_RESETS + + +async def test_async_client_aclose_sets_is_closed(): + """Closing the async client marks is_closed as True.""" + client = AsyncTaskHubGrpcClient() + mock_channel = AsyncMock() + client._channel = mock_channel + assert not client.is_closed + await client.aclose() + assert client.is_closed + mock_channel.close.assert_awaited_once() + + +async def test_async_cancelled_when_client_closed_reraises_immediately(monkeypatch): + """When the async client is closed locally, CANCELLED is not retried and raises immediately.""" + instance_id = 'test-instance' + sleeps = [] + + async def fake_sleep(s): + sleeps.append(s) + + monkeypatch.setattr('asyncio.sleep', fake_sleep) + + client = AsyncTaskHubGrpcClient() + mock_channel = AsyncMock() + client._channel = mock_channel + await client.aclose() + + calls = {'n': 0} + + async def fake_call(*args, **kwargs): + calls['n'] += 1 + raise _make_async_rpc_error(grpc.StatusCode.CANCELLED) + + client._stub = Mock() + client._stub.WaitForInstanceCompletion = fake_call + + with pytest.raises(grpc.RpcError): + await client.wait_for_orchestration_completion(instance_id, timeout=0) + + assert calls['n'] == 1 + assert len(sleeps) == 0 + + +async def test_async_cancelled_with_channel_closed_details_reraises_immediately(monkeypatch): + """When CANCELLED details indicate channel closure, async wait re-raises immediately.""" + instance_id = 'test-instance' + sleeps = [] + + async def fake_sleep(s): + sleeps.append(s) + + monkeypatch.setattr('asyncio.sleep', fake_sleep) + + client = AsyncTaskHubGrpcClient() + calls = {'n': 0} + + async def fake_call(*args, **kwargs): + calls['n'] += 1 + raise _make_async_rpc_error(grpc.StatusCode.CANCELLED, details='Channel closed!') + + client._stub = Mock() + client._stub.WaitForInstanceCompletion = fake_call + + with pytest.raises(grpc.RpcError): + await client.wait_for_orchestration_completion(instance_id, timeout=0) + + assert calls['n'] == 1 + assert len(sleeps) == 0 + + +async def test_async_in_flight_cancellation_on_client_aclose_repro(monkeypatch): + """Repro from CasperGN: async WaitForInstanceCompletion in flight is aborted when + aclose() is invoked. Must re-raise grpc.RpcError immediately without attempting to retry. + """ + instance_id = 'test-instance' + sleeps = [] + + async def fake_sleep(s): + sleeps.append(s) + + monkeypatch.setattr('asyncio.sleep', fake_sleep) + + client = AsyncTaskHubGrpcClient() + client._channel = AsyncMock() + + calls = {'n': 0} + + async def fake_wait(*args, **kwargs): + calls['n'] += 1 + await client.aclose() + raise _make_async_rpc_error(grpc.StatusCode.CANCELLED, details='Channel closed!') + + client._stub = Mock() + client._stub.WaitForInstanceCompletion = fake_wait + + with pytest.raises(grpc.RpcError) as exc_info: + await client.wait_for_orchestration_completion(instance_id, timeout=0) + + assert isinstance(exc_info.value, grpc.RpcError) + assert not isinstance(exc_info.value, ValueError) + assert calls['n'] == 1 + assert len(sleeps) == 0 diff --git a/tests/ext/workflow/durabletask/test_orchestration_wait.py b/tests/ext/workflow/durabletask/test_orchestration_wait.py index 2a2ab3560..ab89a7c4d 100644 --- a/tests/ext/workflow/durabletask/test_orchestration_wait.py +++ b/tests/ext/workflow/durabletask/test_orchestration_wait.py @@ -1,10 +1,11 @@ import time +from typing import Optional from unittest.mock import Mock import grpc import pytest -from dapr.ext.workflow._durabletask.client import TaskHubGrpcClient +from dapr.ext.workflow._durabletask.client import OrchestrationStatus, TaskHubGrpcClient @pytest.mark.parametrize('timeout', [None, 0, 5]) @@ -71,15 +72,20 @@ def test_wait_for_orchestration_completion_timeout(timeout): assert kwargs.get('timeout') == timeout -def _make_rpc_error(code: grpc.StatusCode) -> grpc.RpcError: +def _make_rpc_error(code: grpc.StatusCode, details: Optional[str] = None) -> grpc.RpcError: err = grpc.RpcError() err.code = lambda: code # type: ignore[method-assign] - err.details = lambda: f'simulated {code.name}' # type: ignore[method-assign] + err.details = lambda: details if details is not None else f'simulated {code.name}' # type: ignore[method-assign] return err @pytest.mark.parametrize( - 'transient_code', [grpc.StatusCode.FAILED_PRECONDITION, grpc.StatusCode.UNAVAILABLE] + 'transient_code', + [ + grpc.StatusCode.CANCELLED, + grpc.StatusCode.FAILED_PRECONDITION, + grpc.StatusCode.UNAVAILABLE, + ], ) def test_wait_for_orchestration_start_retries_transient_then_succeeds(transient_code, monkeypatch): """Transient gRPC error on the first call → backoff → next call succeeds.""" @@ -210,23 +216,277 @@ def cancel_after_budget_spent(*args, **kwargs): c.wait_for_orchestration_completion('test-instance', timeout=0.01) -def test_cancelled_within_deadline_still_propagates(): - """A CANCELLED with budget remaining is a real cancellation, not a timeout.""" +def test_cancelled_within_deadline_retries_then_succeeds(monkeypatch): + """A server-sent CANCELLED with deadline budget remaining is retried.""" + instance_id = 'test-instance' + + from dapr.ext.workflow._durabletask.internal.protos import ( + ORCHESTRATION_STATUS_COMPLETED, + GetInstanceResponse, + WorkflowState, + ) + + response = GetInstanceResponse() + response.exists = True + state = WorkflowState() + state.instanceId = instance_id + state.workflowStatus = ORCHESTRATION_STATUS_COMPLETED + response.workflowState.CopyFrom(state) + + sleeps = [] + monkeypatch.setattr( + 'dapr.ext.workflow._durabletask.client.time.sleep', lambda s: sleeps.append(s) + ) + + calls = {'n': 0} + + def fake_call(*args, **kwargs): + calls['n'] += 1 + if calls['n'] == 1: + raise _make_rpc_error(grpc.StatusCode.CANCELLED) + return response + + c = TaskHubGrpcClient() + c._stub = Mock() + c._stub.WaitForInstanceCompletion.side_effect = fake_call + + res = c.wait_for_orchestration_completion(instance_id, timeout=300) + assert res is not None + assert res.runtime_status == OrchestrationStatus.COMPLETED + assert calls['n'] == 2 + assert len(sleeps) == 1 and sleeps[0] > 0 + + +def test_cancelled_unbounded_wait_retries_then_succeeds(monkeypatch): + """With timeout=0 (unbounded), server-sent CANCELLED is retried with backoff.""" + instance_id = 'test-instance' + + from dapr.ext.workflow._durabletask.internal.protos import ( + ORCHESTRATION_STATUS_COMPLETED, + GetInstanceResponse, + WorkflowState, + ) + + response = GetInstanceResponse() + response.exists = True + state = WorkflowState() + state.instanceId = instance_id + state.workflowStatus = ORCHESTRATION_STATUS_COMPLETED + response.workflowState.CopyFrom(state) + + sleeps = [] + monkeypatch.setattr( + 'dapr.ext.workflow._durabletask.client.time.sleep', lambda s: sleeps.append(s) + ) + + calls = {'n': 0} + + def fake_call(*args, **kwargs): + calls['n'] += 1 + if calls['n'] == 1: + raise _make_rpc_error(grpc.StatusCode.CANCELLED) + return response + + c = TaskHubGrpcClient() + c._stub = Mock() + c._stub.WaitForInstanceCompletion.side_effect = fake_call + + res = c.wait_for_orchestration_completion(instance_id, timeout=0) + assert res is not None + assert res.runtime_status == OrchestrationStatus.COMPLETED + assert calls['n'] == 2 + assert len(sleeps) == 1 and sleeps[0] > 0 + + +def test_cancelled_unbounded_wait_persistent_gives_up_with_rpc_error(monkeypatch): + """With timeout=0 (unbounded), persistent CANCELLED errors are retried only + for the grace window, then the original RpcError propagates — NOT a hang and + NOT a TimeoutError.""" + instance_id = 'test-instance' + + fake_time = [0.0] + + def fake_monotonic(): + fake_time[0] += 20.0 + return fake_time[0] + + monkeypatch.setattr('dapr.ext.workflow._durabletask.client.time.monotonic', fake_monotonic) + monkeypatch.setattr('dapr.ext.workflow._durabletask.client.time.sleep', lambda s: None) + c = TaskHubGrpcClient() c._stub = Mock() c._stub.WaitForInstanceCompletion.side_effect = _make_rpc_error(grpc.StatusCode.CANCELLED) with pytest.raises(grpc.RpcError) as exc_info: - c.wait_for_orchestration_completion('test-instance', timeout=300) + c.wait_for_orchestration_completion(instance_id, timeout=0) assert not isinstance(exc_info.value, TimeoutError) + assert c._stub.WaitForInstanceCompletion.call_count >= 2 + +def test_unbounded_wait_retries_across_multiple_sidecar_restarts(monkeypatch): + """An unbounded wait survives multiple sidecar restarts separated by long waits. + + Restarting the 30s transient window on each healthy re-issue prevents + restarts separated by normal wait times from failing the orchestrator wait. + """ + instance_id = 'test-instance' + + from dapr.ext.workflow._durabletask.internal.protos import ( + ORCHESTRATION_STATUS_COMPLETED, + GetInstanceResponse, + WorkflowState, + ) + + response = GetInstanceResponse() + response.exists = True + state = WorkflowState() + state.instanceId = instance_id + state.workflowStatus = ORCHESTRATION_STATUS_COMPLETED + response.workflowState.CopyFrom(state) + + fake_time = [0.0] + + def fake_monotonic(): + return fake_time[0] + + monkeypatch.setattr('dapr.ext.workflow._durabletask.client.time.monotonic', fake_monotonic) + monkeypatch.setattr('dapr.ext.workflow._durabletask.client.time.sleep', lambda s: None) + + calls = {'n': 0} + + def fake_call(*args, **kwargs): + calls['n'] += 1 + if calls['n'] == 1: + fake_time[0] += 10.0 # waited 10s before first restart + raise _make_rpc_error(grpc.StatusCode.CANCELLED) + if calls['n'] == 2: + fake_time[0] += 60.0 # in-flight wait for 60s before second restart + raise _make_rpc_error(grpc.StatusCode.CANCELLED) + fake_time[0] += 5.0 + return response + + c = TaskHubGrpcClient() + c._stub = Mock() + c._stub.WaitForInstanceCompletion.side_effect = fake_call + + res = c.wait_for_orchestration_completion(instance_id, timeout=0) + assert res is not None + assert res.runtime_status == OrchestrationStatus.COMPLETED + assert calls['n'] == 3 + + +def test_unbounded_wait_caps_consecutive_in_flight_cancellations(monkeypatch): + """When every wait attempt is CANCELLED after >= 1s, the client caps consecutive + window resets (_MAX_CONSECUTIVE_TRANSIENT_RESETS) and eventually propagates + the CANCELLED RpcError rather than looping forever.""" + instance_id = 'test-instance' + + fake_time = [0.0] + + def fake_monotonic(): + return fake_time[0] + + monkeypatch.setattr('dapr.ext.workflow._durabletask.client.time.monotonic', fake_monotonic) + monkeypatch.setattr('dapr.ext.workflow._durabletask.client.time.sleep', lambda s: None) + + calls = {'n': 0} + + def fake_call(*args, **kwargs): + calls['n'] += 1 + fake_time[0] += 5.0 # >= 1.0s in-flight before server cancellation + raise _make_rpc_error(grpc.StatusCode.CANCELLED) + + c = TaskHubGrpcClient() + c._stub = Mock() + c._stub.WaitForInstanceCompletion.side_effect = fake_call + + with pytest.raises(grpc.RpcError) as exc_info: + c.wait_for_orchestration_completion(instance_id, timeout=0) + + assert exc_info.value.code() == grpc.StatusCode.CANCELLED + # Must have attempted beyond the max reset limit before exhausting the 30s window + assert calls['n'] > TaskHubGrpcClient._MAX_CONSECUTIVE_TRANSIENT_RESETS + + +def test_client_close_sets_is_closed(): + """Closing the client marks is_closed as True.""" + c = TaskHubGrpcClient() + c._channel = Mock() + assert not c.is_closed + c.close() + assert c.is_closed + + +def test_cancelled_when_client_closed_reraises_immediately_without_retry(monkeypatch): + """When the client is closed locally, CANCELLED is not retried and raises immediately.""" + instance_id = 'test-instance' + sleeps = [] + monkeypatch.setattr( + 'dapr.ext.workflow._durabletask.client.time.sleep', lambda s: sleeps.append(s) + ) -def test_cancelled_unbounded_wait_still_propagates(): - """With no caller deadline there is nothing to attribute a CANCELLED to.""" c = TaskHubGrpcClient() + c._channel = Mock() + c.close() c._stub = Mock() c._stub.WaitForInstanceCompletion.side_effect = _make_rpc_error(grpc.StatusCode.CANCELLED) + with pytest.raises(grpc.RpcError): + c.wait_for_orchestration_completion(instance_id, timeout=0) + + assert c._stub.WaitForInstanceCompletion.call_count == 1 + assert len(sleeps) == 0 + + +def test_cancelled_with_channel_closed_details_reraises_immediately(monkeypatch): + """When CANCELLED details indicate channel closure, it is raised immediately without retry.""" + instance_id = 'test-instance' + sleeps = [] + monkeypatch.setattr( + 'dapr.ext.workflow._durabletask.client.time.sleep', lambda s: sleeps.append(s) + ) + + c = TaskHubGrpcClient() + c._stub = Mock() + c._stub.WaitForInstanceCompletion.side_effect = _make_rpc_error( + grpc.StatusCode.CANCELLED, details='Channel closed!' + ) + + with pytest.raises(grpc.RpcError): + c.wait_for_orchestration_completion(instance_id, timeout=0) + + assert c._stub.WaitForInstanceCompletion.call_count == 1 + assert len(sleeps) == 0 + + +def test_in_flight_cancellation_on_client_close_repro(monkeypatch): + """Repro from CasperGN: WaitForInstanceCompletion in flight is aborted when the client + is closed locally. Must re-raise grpc.RpcError immediately without attempting to invoke + a new RPC on the closed channel (which would raise ValueError: Cannot invoke RPC on closed channel!). + """ + instance_id = 'test-instance' + sleeps = [] + monkeypatch.setattr( + 'dapr.ext.workflow._durabletask.client.time.sleep', lambda s: sleeps.append(s) + ) + + c = TaskHubGrpcClient() + c._channel = Mock() + + def fake_wait(*args, **kwargs): + # Client is closed while wait is in-flight + c.close() + # gRPC raises CANCELLED on channel closure + raise _make_rpc_error(grpc.StatusCode.CANCELLED, details='Channel closed!') + + c._stub = Mock() + c._stub.WaitForInstanceCompletion.side_effect = fake_wait + with pytest.raises(grpc.RpcError) as exc_info: - c.wait_for_orchestration_completion('test-instance', timeout=0) - assert not isinstance(exc_info.value, TimeoutError) + c.wait_for_orchestration_completion(instance_id, timeout=0) + + # Must be grpc.RpcError, NOT ValueError("Cannot invoke RPC on closed channel!") + assert isinstance(exc_info.value, grpc.RpcError) + assert not isinstance(exc_info.value, ValueError) + assert c._stub.WaitForInstanceCompletion.call_count == 1 + assert len(sleeps) == 0 diff --git a/tests/ext/workflow/test_workflow_client.py b/tests/ext/workflow/test_workflow_client.py index 00d1d09f6..a5028c043 100644 --- a/tests/ext/workflow/test_workflow_client.py +++ b/tests/ext/workflow/test_workflow_client.py @@ -446,3 +446,19 @@ def test_cross_app_kwargs_default_to_none(self): wfClient = DaprWorkflowClient() wfClient.terminate_workflow(instance_id=mock_instance_id) assert fake_client.last_app_id is None + + +class WorkflowClientLifecycleTest(unittest.TestCase): + def test_sync_with_context_manager_closes_client(self): + wf_client = DaprWorkflowClient() + self.assertFalse(wf_client.is_closed) + with wf_client as client: + self.assertIs(client, wf_client) + self.assertFalse(client.is_closed) + self.assertTrue(wf_client.is_closed) + + def test_close_method(self): + wf_client = DaprWorkflowClient() + self.assertFalse(wf_client.is_closed) + wf_client.close() + self.assertTrue(wf_client.is_closed) diff --git a/tests/ext/workflow/test_workflow_client_aio.py b/tests/ext/workflow/test_workflow_client_aio.py index c3fed6d4e..bd1c28a5d 100644 --- a/tests/ext/workflow/test_workflow_client_aio.py +++ b/tests/ext/workflow/test_workflow_client_aio.py @@ -446,3 +446,24 @@ async def test_cross_app_kwargs_default_to_none(self): wfClient = DaprWorkflowClient() await wfClient.terminate_workflow(instance_id=mock_instance_id) assert fake_client.last_app_id is None + + +class WorkflowClientAioLifecycleTest(unittest.IsolatedAsyncioTestCase): + async def test_async_with_context_manager_closes_client(self): + wf_client = DaprWorkflowClient() + self.assertFalse(wf_client.is_closed) + async with wf_client as client: + self.assertIs(client, wf_client) + self.assertFalse(client.is_closed) + self.assertTrue(wf_client.is_closed) + + async def test_aclose_and_close_methods(self): + wf_client = DaprWorkflowClient() + self.assertFalse(wf_client.is_closed) + await wf_client.aclose() + self.assertTrue(wf_client.is_closed) + + wf_client2 = DaprWorkflowClient() + self.assertFalse(wf_client2.is_closed) + await wf_client2.close() + self.assertTrue(wf_client2.is_closed)