Skip to content

fix(workflow_streams): retry aborted unaccepted polls - #2172

Open
feiiiiii5 wants to merge 1 commit into
temporalio:mainfrom
feiiiiii5:fix/2170-continue-as-new-poll
Open

feiiiiii5 wants to merge 1 commit into
temporalio:mainfrom
feiiiiii5:fix/2170-continue-as-new-poll

Conversation

@feiiiiii5

Copy link
Copy Markdown

What was changed

WorkflowStreamClient.subscribe() now retries a poll aborted before acceptance with FAILED_PRECONDITION and a WorkflowNotReadyFailure detail. That is the error the server produces when a publish lands in the workflow task that emits continue-as-new. The retry is limited to the unaccepted case: accepted-run errors, generic RPC errors, cancellation, and terminal handling are unchanged.

The public docstring now states that unaccepted polls aborted with WorkflowNotReadyFailure are retried. A changelog/fixed/ fragment is included. The fix uses only local per-attempt state; it adds no cache, client, connection, loop, timer, or retained global state.

Why?

Issue #2170 reports that a healthy token-stream subscriber dies because subscribe() describes the run, sees RUNNING, and re-raises the aborted poll error. The method already retries unaccepted polls for StreamDraining and promises to follow continue-as-new chains. A stress reproduction lost 6 of 20 subscribers at rollover under publish load.

Checklist

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

  2. How was this tested:

    • Base ce8cd48149423e005302ae0b4ea5f5488d90a4f3 + new tests: 1 failed, 1 passed. The retry test failed with the reported RPCError.
    • This branch: focused tests 2 passed; broader closed-stream unit subset 24 passed.
    • ruff check --select I and ruff format --check pass on both changed Python files; git diff --check passes.
    • Full uv dev install timed out downloading the unrelated cibuildwheel package, so tests ran with the local Python 3.11 environment and the installed native bridge shim. Integration tests requiring a Temporal dev server were not run.
    • Local Ruff 0.16.6 reports three pre-existing findings in untouched lines; this repo pins Ruff <0.16.
  3. Any docs updates needed?

    • Updated the subscribe() docstring and added a changelog/fixed/ fragment. No docs.temporal.io update is needed.

🤖 Generated with Claude Code

Unaccepted polls aborted with WorkflowNotReadyFailure during continue-as-new are retried instead of ending the subscription.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
@feiiiiii5
feiiiiii5 requested review from a team as code owners November 29, 2026 04:20
@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@chatgpt-codex-connector

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-29T04:20:59.816136Z
We couldn’t complete this review. Comment @codex review to try again.
569e9ae PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Copy link
Copy Markdown

I ran the deterministic loopback reproduction from #2170 against main ce8cd48 and this PR at 569e9ae on macOS arm64 with Python 3.13 and Temporal CLI 1.10.1 (Server 1.32.2). The official Python SDK 1.37.0 wheel and the main client both lost the subscriber with the reported RPCError. This PR and a separate restore of the same commit both delivered hello. All four runs recorded the server's UNHANDLED_COMMAND workflow-task failure, and the workflow remained RUNNING at offset 1, so the successful runs still exercised the reported collision.

Replayed with Codex assistance.

@feiiiiii5

Copy link
Copy Markdown
Author

Thanks for running the deterministic loopback reproduction on both main and this PR — great to see the PR delivers the expected greeting where the official SDK loses the subscriber, and that the collision path was still exercised. Appreciate the independent verification.

@ptimizeroracle ptimizeroracle left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i filed #2170 and had a patch with the same branch, so no need for mine. i did not run the pr branch: i applied gh pr diff 2172 onto main at ce8cd48, python 3.12, bridge from the 1.37.0 wheel.

the tests here are mocks and you say the dev server ones were not run, so i ran this one on the dev server: a publish signal lands while the continue-as-new task is open. on main it fails with the RPCError from the issue, with the diff it passes (n=3). all 90 tests in tests/contrib/workflow_streams pass with it, and the accepted case test fails (timeout) if i drop the polled_run_id is None check.

the retry has no limit, same as the StreamDraining one. fine for me, a maintainer may want a cap.

here is the dev server test if you want to add it, it applies on ce8cd48:

test diff
diff --git a/tests/contrib/workflow_streams/test_workflow_streams.py b/tests/contrib/workflow_streams/test_workflow_streams.py
index a61db95..12956c8 100644
--- a/tests/contrib/workflow_streams/test_workflow_streams.py
+++ b/tests/contrib/workflow_streams/test_workflow_streams.py
@@ -3,6 +3,7 @@
 from __future__ import annotations
 
 import asyncio
+import threading
 import uuid
 from asyncio import timeout as _async_timeout
 from collections.abc import Sequence
@@ -47,7 +48,11 @@ from temporalio.nexus import WorkflowRunOperationContext, workflow_run_operation
 from temporalio.service import RPCError, RPCStatusCode
 from temporalio.testing import WorkflowEnvironment
 from temporalio.worker import Worker
-from tests.helpers import assert_eq_eventually, new_worker
+from tests.helpers import (
+    assert_eq_eventually,
+    assert_task_fail_eventually,
+    new_worker,
+)
 from tests.helpers.nexus import make_nexus_endpoint_name
 
 
@@ -2289,6 +2294,74 @@ async def test_subscribe_retries_while_draining(client: Client) -> None:
             await new_handle.signal(DrainingGateWorkflow.close)
 
 
+continue_as_new_reached = threading.Event()
+publish_signal_sent = threading.Event()
+
+
+@workflow.defn(sandboxed=False)
+class ContinueAsNewRacesPublishWorkflow:
+    """Continues-as-new in the workflow task that delivers the first poll, and
+    holds that task open until the test has sent a publish signal."""
+
+    @workflow.init
+    def __init__(self, input: CANWorkflowInputTyped) -> None:
+        self.stream = WorkflowStream(prior_state=input.stream_state)
+        self._closed = False
+
+    @workflow.signal
+    def close(self) -> None:
+        self._closed = True
+
+    @workflow.run
+    async def run(self, _input: CANWorkflowInputTyped) -> None:
+        del _input
+        await workflow.wait_condition(
+            lambda: self._closed or not workflow.all_handlers_finished()
+        )
+        if not self._closed:
+            await self.stream.continue_as_new(self._build_args)
+
+    def _build_args(self, state: WorkflowStreamState) -> list[CANWorkflowInputTyped]:
+        if not continue_as_new_reached.is_set():
+            continue_as_new_reached.set()
+            publish_signal_sent.wait(1)
+        return [CANWorkflowInputTyped(stream_state=state)]
+
+
+@pytest.mark.asyncio
+async def test_subscribe_survives_continue_as_new_racing_publish(
+    client: Client,
+) -> None:
+    """A publish signal that lands during the continue-as-new workflow task makes
+    the server fail that task and abort the poll it delivered. The poll was
+    never accepted, so the subscription must resend it instead of raising."""
+    continue_as_new_reached.clear()
+    publish_signal_sent.clear()
+    async with new_worker(client, ContinueAsNewRacesPublishWorkflow) as worker:
+        handle = await client.start_workflow(
+            ContinueAsNewRacesPublishWorkflow.run,
+            CANWorkflowInputTyped(),
+            id=f"workflow-stream-can-races-publish-{uuid.uuid4()}",
+            task_queue=worker.task_queue,
+        )
+        first_run = client.get_workflow_handle(handle.id, run_id=handle.result_run_id)
+
+        collect = asyncio.create_task(
+            collect_items(client, handle, None, 0, 1, result_type=str)
+        )
+        assert await asyncio.to_thread(continue_as_new_reached.wait, 10)
+        stream = WorkflowStreamClient.create(client, handle.id)
+        stream.topic("events", type=str).publish("item-0")
+        await stream.flush()
+        publish_signal_sent.set()
+
+        assert [i.data for i in await collect] == ["item-0"]
+        await assert_task_fail_eventually(first_run)
+
+        await handle.signal(ContinueAsNewRacesPublishWorkflow.close)
+        await handle.result()
+
+
 # ---------------------------------------------------------------------------
 # Cross-workflow workflow stream (Scenario 1)
 # ---------------------------------------------------------------------------

(ai-assisted, checked by me)

@feiiiiii5

Copy link
Copy Markdown
Author

@ptimizeroracle Thanks for running the dev-server test — good to see the fix holds against a real publish signal racing a continue-as-new task, and that dropping the polled_run_id is None check makes the accepted case fail. I'll leave the dev-server test out of this PR since I can't run it here and your independent verification already covers it; happy to add it if a maintainer prefers. The unlimited retry matches the existing StreamDraining behavior — noted for maintainers. Appreciate the thorough check.

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

4 participants