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

未关闭
#2,170 0 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

维护者通常 1 天内回复

@feiiiiii5 已经在做这个了。

开始于 2026年11月29日。

  • #2172 来自 @feiiiiii5 —— 未关闭

评估

难度
3/5
预计耗时
1-2 天
新手友好度
52/100
Issue 类型
缺陷
描述清晰度
描述清楚
活跃度
活跃
技术栈
python

调研方向

Start in temporalio/contrib/workflow_streams/_client.py, where subscribe() handles errors from start_update, and read the existing stream retry logic. Reproduce the rollover race with the issue’s script and add a regression test for the poll aborted with WorkflowNotReadyFailure; done means the subscriber retries the unaccepted poll and receives the published item. The reporter says they have a patch and test, so coordinate before starting.

由索引模型根据 Issue 内容生成。

描述

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)

主要语言
Python
星标
1.3k
派生
305
平均合并
3 天 23 小时
30 天内合并 PR
44

环境准备

  • 没有 Dockerfile 或 Docker Compose 文件
  • 没有 Pull Request 模板
  • 阅读贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

temporalio/sdk-python 的其他 Issue

查看 temporalio/sdk-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。