diff --git a/changelog/fixed/humming-pelican-retry.md b/changelog/fixed/humming-pelican-retry.md new file mode 100644 index 0000000000..6a5884584e --- /dev/null +++ b/changelog/fixed/humming-pelican-retry.md @@ -0,0 +1 @@ +Fixed `WorkflowStreamClient.subscribe()` retrying an unaccepted poll aborted by a failed continue-as-new workflow task instead of ending the subscription. diff --git a/temporalio/contrib/workflow_streams/_client.py b/temporalio/contrib/workflow_streams/_client.py index 791151e6bc..524c18dc55 100644 --- a/temporalio/contrib/workflow_streams/_client.py +++ b/temporalio/contrib/workflow_streams/_client.py @@ -29,6 +29,7 @@ from temporalio import activity from temporalio.api.common.v1 import Payload +from temporalio.api.errordetails.v1 import WorkflowNotReadyFailure from temporalio.client import ( Client, WorkflowExecutionDescription, @@ -87,6 +88,13 @@ def _is_retryable_rpc_error(error: RPCError) -> bool: ) +def _is_workflow_not_ready_error(error: RPCError) -> bool: + if error.status != RPCStatusCode.FAILED_PRECONDITION: + return False + details = error.grpc_status.details + return bool(details) and details[0].Is(WorkflowNotReadyFailure.DESCRIPTOR) + + class WorkflowStreamClient: """Client for publishing to and subscribing from a workflow stream. @@ -525,7 +533,8 @@ async def subscribe( """Async iterator that polls for new items. Automatically follows continue-as-new chains when the client - was created via :py:meth:`create`. After the workflow completes, + was created via :py:meth:`create`. Unaccepted polls aborted with + ``WorkflowNotReadyFailure`` are retried. After the workflow completes, fails, is canceled, terminated, or times out, queries deliver its remaining retained items before the iterator finishes. These reads require retained history and an available worker with the poll query @@ -613,6 +622,15 @@ async def subscribe( continue if isinstance(err.__cause__, asyncio.CancelledError): raise err.__cause__ + if ( + polled_run_id is None + and isinstance(err, RPCError) + and _is_workflow_not_ready_error(err) + ): + cooldown_secs = poll_cooldown.total_seconds() + if cooldown_secs > 0: + await asyncio.sleep(cooldown_secs) + continue try: desc = await self._describe_polled_run( poll_handle, polled_run_id diff --git a/tests/contrib/workflow_streams/test_closed_streams.py b/tests/contrib/workflow_streams/test_closed_streams.py index d032bc2e12..94b5ed82d9 100644 --- a/tests/contrib/workflow_streams/test_closed_streams.py +++ b/tests/contrib/workflow_streams/test_closed_streams.py @@ -12,8 +12,11 @@ from unittest.mock import AsyncMock, MagicMock, patch import pytest +from google.protobuf.any_pb2 import Any as ProtoAny from temporalio import workflow +from temporalio.api.common.v1 import GrpcStatus +from temporalio.api.errordetails.v1 import WorkflowNotReadyFailure from temporalio.client import ( Client, WorkflowExecutionStatus, @@ -71,6 +74,18 @@ def mock_stream( return WorkflowStreamClient(poll, client=client), client, poll, read +def workflow_not_ready_error() -> RPCError: + error = RPCError( + "Unable to perform workflow execution update due to unexpected workflow task failure.", + RPCStatusCode.FAILED_PRECONDITION, + b"", + ) + detail = ProtoAny() + detail.Pack(WorkflowNotReadyFailure()) + error._grpc_status = GrpcStatus(details=[detail]) + return error + + @pytest.mark.parametrize("status", TERMINAL_STATUSES) async def test_workflow_streams_terminal_pages(status: WorkflowExecutionStatus) -> None: stream, client, poll, read = mock_stream(status) @@ -182,6 +197,65 @@ async def test_workflow_streams_unconfirmed_closure_and_query_errors( assert err.value is expected +async def test_workflow_streams_retries_unaccepted_workflow_not_ready_poll() -> None: + stream, _, poll, read = mock_stream(WorkflowExecutionStatus.RUNNING) + poll.start_update.side_effect = [ + workflow_not_ready_error(), + SimpleNamespace( + workflow_run_id="running-run", + result=AsyncMock( + return_value=PollResult( + [_WorkflowStreamWireItem("events", WIRE_ABC, 0)], 1 + ) + ), + ), + RPCError("closed", RPCStatusCode.NOT_FOUND, b""), + ] + + async def describe() -> SimpleNamespace: + if poll.start_update.await_count == 1: + return SimpleNamespace( + status=WorkflowExecutionStatus.RUNNING, run_id="running-run" + ) + return SimpleNamespace( + status=WorkflowExecutionStatus.COMPLETED, run_id="closed-run" + ) + + poll.describe.side_effect = describe + items = [ + item + async for item in stream.subscribe( + "events", result_type=bytes, poll_cooldown=timedelta(0) + ) + ] + assert [(item.offset, item.data) for item in items] == [(0, b"abc")] + assert [call.args for call in poll.start_update.await_args_list] == [ + (POLL, PollInput(["events"], 0)), + (POLL, PollInput(["events"], 0)), + (POLL, PollInput(["events"], 1)), + ] + poll.describe.assert_awaited_once() + read.query.assert_awaited_once_with( + POLL, PollInput(["events"], 1), result_type=PollResult + ) + + +async def test_workflow_streams_does_not_retry_accepted_workflow_not_ready_poll() -> ( + None +): + stream, _, poll, read = mock_stream(WorkflowExecutionStatus.RUNNING) + expected = workflow_not_ready_error() + poll.start_update.side_effect = None + poll.start_update.return_value = SimpleNamespace( + workflow_run_id="accepted-run", result=AsyncMock(side_effect=expected) + ) + with pytest.raises(RPCError) as err: + _ = [item async for item in stream.subscribe()] + assert err.value is expected + assert poll.start_update.await_count == 1 + read.query.assert_not_awaited() + + @pytest.mark.parametrize("accepted", [False, True]) @pytest.mark.parametrize("failure", ["rpc", "update", "timeout"]) async def test_workflow_streams_describe_failure_preserves_poll_error(