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
1 change: 1 addition & 0 deletions changelog/fixed/humming-pelican-retry.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fixed `WorkflowStreamClient.subscribe()` retrying an unaccepted poll aborted by a failed continue-as-new workflow task instead of ending the subscription.
20 changes: 19 additions & 1 deletion temporalio/contrib/workflow_streams/_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
74 changes: 74 additions & 0 deletions tests/contrib/workflow_streams/test_closed_streams.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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(
Expand Down