Skip to content

[Bug] workflow_streams: subscribe() raises RPCError when a publish signal lands during the continue-as-new workflow task #2170

Backlog

Description

@ptimizeroracle

What are you really trying to do?

keep a WorkflowStreamClient.subscribe() iterator alive across WorkflowStream.continue_as_new() while other clients keep publishing to the same stream (token streaming, many small batches).

Describe the bug

if a publish signal reaches the server while the workflow task that emits continue-as-new is still running, the server fails that task with UNHANDLED_COMMAND. that part is normal, the task is retried and the rollover goes through.

but a poll update that was delivered to the worker in that same task gets aborted by the server with FAILED_PRECONDITION + WorkflowNotReadyFailure:

temporalio.service.RPCError: Unable to perform workflow execution update due to unexpected workflow task failure.

subscribe() catches the RPCError from start_update, describes the run, sees RUNNING and re-raises. so the subscriber dies while the stream is healthy.

expected: the poll was never accepted and it is read-only, so subscribe() resends it, like it already does for StreamDraining. the subscribe() docstring says it "Automatically follows continue-as-new chains".

which subscribers die depends only on timing. in my runs the other subscribers on the same workflow, with a poll that was not delivered in the failed task, kept going and got every item.

How did you hit this issue?

not in production. i was stress testing a stream on the local dev server: continue-as-new every second, concurrent WorkflowStreamClient publishers, and a check that every subscriber sees every item.

  • 4 publishers at batch_interval=10ms, 4 subscribers, 8 rollovers per run: 6 of 20 subscribers died over 5 runs
  • 1 publisher at batch_interval=100ms, 3 subscribers, 40 rollovers: 0 died, 1 UNHANDLED_COMMAND

so it needs publish load at rollover time. i did not measure a real cluster, where workflow tasks take longer.

Minimal Reproduction

the script makes the race deterministic: build_args holds the continue-as-new task open until one publish is flushed. the workflow is sandboxed=False only for that hold.

import asyncio
import threading
import uuid
from dataclasses import dataclass

import temporalio
from temporalio import workflow
from temporalio.api.enums.v1 import WorkflowTaskFailedCause
from temporalio.contrib.workflow_streams import (
    WorkflowStream,
    WorkflowStreamClient,
    WorkflowStreamState,
)
from temporalio.testing import WorkflowEnvironment
from temporalio.worker import Worker

at_continue_as_new = threading.Event()
publish_sent = threading.Event()


@dataclass
class Input:
    stream_state: WorkflowStreamState | None = None


@workflow.defn(sandboxed=False)
class Rolling:
    @workflow.init
    def __init__(self, input: Input) -> None:
        self.stream = WorkflowStream(input.stream_state)

    @workflow.run
    async def run(self, input: Input) -> None:
        # roll over in the workflow task that delivers the first poll
        await workflow.wait_condition(lambda: not workflow.all_handlers_finished())
        await self.stream.continue_as_new(self.build_args)

    def build_args(self, state: WorkflowStreamState) -> list[Input]:
        # hold the first continue-as-new task open until a publish signal is sent,
        # the same thing a publisher flushing during the rollover does
        if not at_continue_as_new.is_set():
            at_continue_as_new.set()
            publish_sent.wait(1)
        return [Input(stream_state=state)]


async def main() -> None:
    print("temporalio", temporalio.__version__)
    async with await WorkflowEnvironment.start_local() as env:
        client = env.client
        async with Worker(client, task_queue="tq", workflows=[Rolling]):
            handle = await client.start_workflow(
                Rolling.run, Input(), id=f"wf-{uuid.uuid4()}", task_queue="tq"
            )
            stream = WorkflowStreamClient.create(client, handle.id)

            async def first_item() -> str:
                async for item in stream.subscribe(["events"], result_type=str):
                    return item.data
                raise AssertionError("stream ended")

            subscriber = asyncio.create_task(first_item())
            assert await asyncio.to_thread(at_continue_as_new.wait, 10)
            stream.topic("events", type=str).publish("hello")
            await stream.flush()
            publish_sent.set()
            try:
                print("subscriber got:", await asyncio.wait_for(subscriber, 20))
            except Exception as err:
                print("subscriber raised:", repr(err))
            first_run = client.get_workflow_handle(
                handle.id, run_id=handle.result_run_id
            )
            async for event in first_run.fetch_history_events():
                if event.HasField("workflow_task_failed_event_attributes"):
                    cause = event.workflow_task_failed_event_attributes.cause
                    print("workflow task failed:", WorkflowTaskFailedCause.Name(cause))
            desc = await handle.describe()
            print("workflow:", desc.status.name, "| offset:", await stream.get_offset())
            await client.get_workflow_handle(handle.id).terminate()


asyncio.run(main())

output on 1.37.0:

temporalio 1.37.0
subscriber raised: RPCError('Unable to perform workflow execution update due to unexpected workflow task failure.')
workflow task failed: WORKFLOW_TASK_FAILED_CAUSE_UNHANDLED_COMMAND
workflow: RUNNING | offset: 1

Environment/Versions

  • OS and processor: macOS arm64 (Darwin 27.0.0), python 3.12.13
  • Temporal Version: temporalio 1.37.0 from pypi. temporalio/contrib/workflow_streams is the same on main at ce8cd48, and the script fails the same way with main's python sources
  • server: dev server from WorkflowEnvironment.start_local() (Temporal CLI 1.10.1, server 1.32.2). also fails on the dev server the repo tests start (server 1.33.0)
  • no docker, no kubernetes, not tested on temporal cloud

Additional context

  • server side this looks intended: service/history/workflow/update/abort_reason.go maps (workflow task failed, update in state Sent) to workflowTaskFailErr, and docs/architecture/workflow-update.md says updates the workflow has already seen are aborted with a non-retryable error
  • test_workflow_streams_unconfirmed_closure_and_query_errors[running] pins "run is RUNNING + rpc error = raise" for a generic NOT_FOUND. i think WorkflowNotReadyFailure needs its own branch because the stream's own continue-as-new helper produces it
  • a worker that fails the task itself (exception raised in workflow code) did not trigger it in my test, that subscriber still got its item. it needs a task that fails at completion
  • i have a small patch: one retry branch in _client.py and one test that fails on main and passes with it. i can open a pr
  • the go, typescript, java and dotnet stream clients share the protocol. i did not check them

(ai-assisted, checked by me)

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions