From 8c9c86f6f3f9fd9064035179a6bf5d3bb41f9f3e Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Sun, 22 Nov 2026 21:00:59 -0700 Subject: [PATCH 1/8] Add a sample of Streams on the Redis Stream Store An agent's events in Redis outlive its Workflow, and a reader can leave and resume at its offset. The test isn't collected and mypy skips the sample until the two packages have a release, so CI stays green on the released temporalio. --- README.md | 1 + pyproject.toml | 5 ++ streams_redis/README.md | 81 ++++++++++++++++++++++ streams_redis/__init__.py | 0 streams_redis/activities/__init__.py | 0 streams_redis/activities/model_activity.py | 23 ++++++ streams_redis/run_agent.py | 64 +++++++++++++++++ streams_redis/run_worker.py | 25 +++++++ streams_redis/shared.py | 24 +++++++ streams_redis/workflows/__init__.py | 0 streams_redis/workflows/agent_workflow.py | 41 +++++++++++ tests/streams_redis/__init__.py | 0 tests/streams_redis/agent_workflow_test.py | 31 +++++++++ tests/streams_redis/conftest.py | 66 ++++++++++++++++++ 14 files changed, 361 insertions(+) create mode 100644 streams_redis/README.md create mode 100644 streams_redis/__init__.py create mode 100644 streams_redis/activities/__init__.py create mode 100644 streams_redis/activities/model_activity.py create mode 100644 streams_redis/run_agent.py create mode 100644 streams_redis/run_worker.py create mode 100644 streams_redis/shared.py create mode 100644 streams_redis/workflows/__init__.py create mode 100644 streams_redis/workflows/agent_workflow.py create mode 100644 tests/streams_redis/__init__.py create mode 100644 tests/streams_redis/agent_workflow_test.py create mode 100644 tests/streams_redis/conftest.py diff --git a/README.md b/README.md index 020237770..e0a5acc1a 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,7 @@ without wrapping them in a workflow. * [sentry](sentry) - Report errors to Sentry. * [sleep_for_days](sleep_for_days) - A workflow that runs forever, sending an email every 30 days. * [strands_plugin](strands_plugin) - Run Strands Agents as durable Temporal workflows (model calls, tools, MCP, HITL). +* [streams_redis](streams_redis) - Stream the events of an agent through Redis, and resume a reader from its offset. **Experimental** * [trio_async](trio_async) - Use asyncio Temporal in Trio-based environments. * [updatable_timer](updatable_timer) - A timer that can be updated while sleeping. * [worker_multiprocessing](worker_multiprocessing) - Leverage Python multiprocessing to parallelize workflow tasks and other CPU bound operations by running multiple workers. diff --git a/pyproject.toml b/pyproject.toml index 571d8efca..8e97580f9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -162,3 +162,8 @@ ignore_errors = true [[tool.mypy.overrides]] module = "opentelemetry.*" ignore_errors = true + +# The released temporalio that CI installs has no Streams API yet. +[[tool.mypy.overrides]] +module = ["streams_redis.*", "tests.streams_redis.*"] +ignore_errors = true diff --git a/streams_redis/README.md b/streams_redis/README.md new file mode 100644 index 000000000..956ad6326 --- /dev/null +++ b/streams_redis/README.md @@ -0,0 +1,81 @@ +# Streams on Redis + +> **Experimental.** This sample uses the Streams API of the Temporal Python SDK and the +> Redis Stream Store of `temporal-community/sdk-streams`. Neither has a release yet, and +> both APIs may change. + +A Stream is an append-only log of events in a Stream Store, here Redis. Workflow code, +Activities and clients append to it, and a reader goes on from the offset of the last event +that it read. `temporalio.contrib.workflow_streams` (see +[workflow_streams](../workflow_streams)) keeps its events in the Workflow and needs no +Store. A Stream keeps them in Redis. A client reads them from there, and they stay +readable for 7 days after the close by default. + +The sample has one scenario: + +* `workflows/agent_workflow.py` - an agent-like Workflow. It creates a Stream with the id + of the Workflow, writes a status event, runs the model Activity, writes another status + event, and closes the Stream in `finally`. +* `activities/model_activity.py` - an Activity that stands in for a model. It appends each + token of its answer to the Stream with `BufferedAppender`. +* `run_agent.py` - starts the Workflow, gets the `StreamRef` from an Update, and prints the + events as they come. After four events it disconnects. A new client then reads on from + the offset of the last event that it printed, and stops at the close of the Stream. + +## Install + +The two packages build from source, with Rust and `protoc`. From the root of this repo: + +```bash +uv sync +uv pip install "temporalio @ git+https://github.com/temporalio/sdk-python@moe/streams-api" +git clone --branch moe/retention-from-close https://github.com/temporal-community/sdk-streams ../sdk-streams +(cd ../sdk-streams && SDK_RUST_REF=moe/streams-crate-types scripts/patch-sdk-rust.sh) +uv pip install ../sdk-streams/python +``` + +The Store's native module needs the crate `temporalio-streams`, which isn't on crates.io +yet. `patch-sdk-rust.sh` points the build at the branch of `temporalio/sdk-rust` that has it. + +## Run it + +Start Redis and a Temporal dev server: + +```bash +redis-server +temporal server start-dev +``` + +Start the Worker, and then the agent in another terminal: + +```bash +uv run --no-sync streams_redis/run_worker.py +uv run --no-sync streams_redis/run_agent.py +``` + +`--no-sync` keeps uv from putting the released `temporalio` back. Set `REDIS_URL` for a +Redis other than `redis://localhost:6379`. + +The agent prints each event with its offset, which is opaque bytes: + +``` +000001a2068b96180000000000000000 status Thinking about: Why keep the events of an agent in Redis? +000001a2068b96880000000000000000 token Redis +000001a2068b97210000000000000000 token keeps +000001a2068b97b90000000000000000 token the +-- The reader disconnects, and the agent goes on. +000001a2068b98510000000000000000 token events, +... +000001a2068b9edd0000000000000000 token rest. +000001a2068b9f120000000000000000 status Done +-- The Stream is closed. The Workflow returned: Redis keeps the events, so a reader can leave and come back for the rest. +``` + +## Test + +The test starts its own `redis-server`, from the `PATH`. It isn't collected when the two +packages aren't installed, as in the CI of this repo. + +```bash +uv run --no-sync pytest tests/streams_redis +``` diff --git a/streams_redis/__init__.py b/streams_redis/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/streams_redis/activities/__init__.py b/streams_redis/activities/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/streams_redis/activities/model_activity.py b/streams_redis/activities/model_activity.py new file mode 100644 index 000000000..7b48b6d8b --- /dev/null +++ b/streams_redis/activities/model_activity.py @@ -0,0 +1,23 @@ +from __future__ import annotations + +import asyncio + +from temporalio import activity +from temporalio.contrib.streams import BufferedAppender +from temporalio.nexus.system.stream_service import StreamRef + +from streams_redis.shared import AgentEvent + +ANSWER = "Redis keeps the events, so a reader can leave and come back for the rest." + + +@activity.defn +async def stream_answer(stream_ref: StreamRef[AgentEvent]) -> str: + """Stand in for a model that streams the tokens of its answer.""" + stream = activity.client().get_stream(stream_ref) + # The appender writes in the background, so the model never waits for Redis. + async with BufferedAppender(stream) as tokens: + for word in ANSWER.split(): + tokens.append(AgentEvent("token", word)) + await asyncio.sleep(0.15) + return ANSWER diff --git a/streams_redis/run_agent.py b/streams_redis/run_agent.py new file mode 100644 index 000000000..793642484 --- /dev/null +++ b/streams_redis/run_agent.py @@ -0,0 +1,64 @@ +"""Start the agent, print its events as they come, disconnect, and resume.""" + +from __future__ import annotations + +import asyncio +import uuid +from collections.abc import Awaitable, Callable +from datetime import timedelta + +from temporalio.client import Client +from temporalio.nexus.system.stream_service import StreamRef + +from streams_redis.shared import TASK_QUEUE, AgentEvent, connect +from streams_redis.workflows.agent_workflow import AgentWorkflow + +QUESTION = "Why keep the events of an agent in Redis?" + + +async def follow( + client: Client, + stream_ref: StreamRef[AgentEvent], + after: bytes | None, + stop_after: int | None = None, +) -> tuple[list[AgentEvent], bytes | None]: + """Print the events after an offset, up to ``stop_after`` of them or to the close. + + Return the events, with the offset of the last one. + """ + events: list[AgentEvent] = [] + # With a wait, a read ends only at the close of the Stream. + records = client.get_stream(stream_ref).read( + from_offset=after, wait=timedelta(seconds=10) + ) + async for record in records: + print(f"{record.offset.hex()} {record.body.kind:<6} {record.body.text}") + events.append(record.body) + after = record.offset + if len(events) == stop_after: + break + return events, after + + +async def run(connect: Callable[[], Awaitable[Client]]) -> list[AgentEvent]: + client = await connect() + handle = await client.start_workflow( + AgentWorkflow.run, + QUESTION, + id=f"agent-{uuid.uuid4()}", + task_queue=TASK_QUEUE, + ) + stream_ref = await handle.execute_update(AgentWorkflow.stream_ref) + first, offset = await follow(client, stream_ref, after=None, stop_after=4) + print("-- The reader disconnects, and the agent goes on.") + await asyncio.sleep(1) + + # A new client needs only the ref and the offset, so it misses no event and + # repeats none. + rest, _ = await follow(await connect(), stream_ref, after=offset) + print(f"-- The Stream is closed. The Workflow returned: {await handle.result()}") + return first + rest + + +if __name__ == "__main__": + asyncio.run(run(connect)) diff --git a/streams_redis/run_worker.py b/streams_redis/run_worker.py new file mode 100644 index 000000000..607aa2c42 --- /dev/null +++ b/streams_redis/run_worker.py @@ -0,0 +1,25 @@ +from __future__ import annotations + +import asyncio +import logging + +from temporalio.worker import Worker + +from streams_redis.activities.model_activity import stream_answer +from streams_redis.shared import TASK_QUEUE, connect +from streams_redis.workflows.agent_workflow import AgentWorkflow + + +async def main() -> None: + logging.basicConfig(level=logging.INFO) + worker = Worker( + await connect(), + task_queue=TASK_QUEUE, + workflows=[AgentWorkflow], + activities=[stream_answer], + ) + await worker.run() + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/streams_redis/shared.py b/streams_redis/shared.py new file mode 100644 index 000000000..fc4819a87 --- /dev/null +++ b/streams_redis/shared.py @@ -0,0 +1,24 @@ +from __future__ import annotations + +import os +from dataclasses import dataclass + +from temporalio.client import Client, StreamConfig +from temporalio.envconfig import ClientConfig +from temporalio_streams_redis import RedisStreamStore + +TASK_QUEUE = "streams-redis-task-queue" + + +@dataclass +class AgentEvent: + kind: str + text: str + + +async def connect() -> Client: + """Connect a client whose Stream calls, and those of its Workers, go to Redis.""" + config = ClientConfig.load_client_connect_config() + config.setdefault("target_host", "localhost:7233") + store = RedisStreamStore(os.environ.get("REDIS_URL", "redis://localhost:6379")) + return await Client.connect(**config, stream_config=StreamConfig(stores=[store])) diff --git a/streams_redis/workflows/__init__.py b/streams_redis/workflows/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/streams_redis/workflows/agent_workflow.py b/streams_redis/workflows/agent_workflow.py new file mode 100644 index 000000000..b513a6095 --- /dev/null +++ b/streams_redis/workflows/agent_workflow.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from datetime import timedelta + +from temporalio import workflow +from temporalio.nexus.system.stream_service import StreamRef + +with workflow.unsafe.imports_passed_through(): + from streams_redis.activities.model_activity import stream_answer + from streams_redis.shared import AgentEvent + + +@workflow.defn +class AgentWorkflow: + def __init__(self) -> None: + self._stream_ref: StreamRef[AgentEvent] | None = None + + @workflow.update + async def stream_ref(self) -> StreamRef[AgentEvent]: + # A read of a Stream that doesn't exist yet fails, so a reader waits here. + await workflow.wait_condition(lambda: self._stream_ref is not None) + assert self._stream_ref + return self._stream_ref + + @workflow.run + async def run(self, question: str) -> str: + stream = await workflow.create_stream( + id=workflow.info().workflow_id, body_type=AgentEvent + ) + self._stream_ref = stream.ref + try: + await stream.append(AgentEvent("status", f"Thinking about: {question}")) + answer = await workflow.execute_activity( + stream_answer, + stream.ref, + start_to_close_timeout=timedelta(minutes=1), + ) + await stream.append(AgentEvent("status", "Done")) + return answer + finally: + await stream.close() diff --git a/tests/streams_redis/__init__.py b/tests/streams_redis/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/tests/streams_redis/agent_workflow_test.py b/tests/streams_redis/agent_workflow_test.py new file mode 100644 index 000000000..5e6a77f7f --- /dev/null +++ b/tests/streams_redis/agent_workflow_test.py @@ -0,0 +1,31 @@ +from temporalio.client import Client, StreamConfig +from temporalio.worker import Worker +from temporalio_streams_redis import RedisStreamStore + +from streams_redis.activities.model_activity import ANSWER, stream_answer +from streams_redis.run_agent import QUESTION, run +from streams_redis.shared import TASK_QUEUE, AgentEvent +from streams_redis.workflows.agent_workflow import AgentWorkflow + + +async def test_a_reader_resumes_at_its_offset(client: Client, redis_url: str): + config = client.config() + config["stream_config"] = StreamConfig(stores=[RedisStreamStore(redis_url)]) + + async def connect() -> Client: + return Client(**config) + + async with Worker( + await connect(), + task_queue=TASK_QUEUE, + workflows=[AgentWorkflow], + activities=[stream_answer], + ): + events = await run(connect) + + # The reader got each event once and in order, across its disconnect, to the close. + assert events == [ + AgentEvent("status", f"Thinking about: {QUESTION}"), + *(AgentEvent("token", word) for word in ANSWER.split()), + AgentEvent("status", "Done"), + ] diff --git a/tests/streams_redis/conftest.py b/tests/streams_redis/conftest.py new file mode 100644 index 000000000..4b3c0e757 --- /dev/null +++ b/tests/streams_redis/conftest.py @@ -0,0 +1,66 @@ +"""Collection guard and Redis server for the tests of the Streams sample on Redis. + +The Streams API of `temporalio` and the `temporalio-streams-redis` package have no +release yet, so the environment of this repo has neither. The test module imports +both, and `collect_ignore_glob` skips it before that import fails, as +`tests/microsoft_agent_framework_plugin/conftest.py` does for its plugin. +""" + +import shutil +import socket +import subprocess +import tempfile +import time +from collections.abc import Iterator + +import pytest + +collect_ignore_glob: list[str] = [] + +try: + import temporalio_streams_redis # noqa: F401 + from temporalio.client import StreamConfig # noqa: F401 +except ImportError: + collect_ignore_glob = ["*_test.py"] + + +def pytest_report_header(config) -> str | None: + if collect_ignore_glob: + return ( + "streams_redis: the Streams API or temporalio-streams-redis isn't " + "installed, so its tests are NOT collected " + "(see tests/streams_redis/conftest.py)" + ) + return None + + +@pytest.fixture(scope="session") +def redis_url() -> Iterator[str]: + """Start a `redis-server` on a free port.""" + binary = shutil.which("redis-server") + if binary is None: + pytest.skip("redis-server isn't on the PATH") + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + port = sock.getsockname()[1] + directory = tempfile.mkdtemp(prefix="streams-redis-") + process = subprocess.Popen( + [binary, "--bind", "127.0.0.1", "--port", str(port)] + + ["--save", "", "--appendonly", "no", "--dir", directory], + stdout=subprocess.DEVNULL, + ) + try: + deadline = time.monotonic() + 20 + while True: + try: + socket.create_connection(("127.0.0.1", port), timeout=1).close() + break + except OSError: + assert process.poll() is None, "redis-server didn't start" + assert time.monotonic() < deadline, "redis-server didn't start" + time.sleep(0.05) + yield f"redis://127.0.0.1:{port}" + finally: + process.kill() + process.wait() + shutil.rmtree(directory, ignore_errors=True) From a68cf7eecd08cc5c49047d5a17b4fe297ad5a6ce Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Wed, 25 Nov 2026 20:28:27 -0700 Subject: [PATCH 2/8] Stop each reader at the last event of the Stream A Stream has no close in the current Streams API. The Workflow writes the status event Done in finally, and each reader breaks at it. --- streams_redis/README.md | 13 ++++++++----- streams_redis/run_agent.py | 16 ++++++---------- streams_redis/shared.py | 3 +++ streams_redis/workflows/agent_workflow.py | 9 ++++----- tests/streams_redis/agent_workflow_test.py | 2 +- 5 files changed, 22 insertions(+), 21 deletions(-) diff --git a/streams_redis/README.md b/streams_redis/README.md index 956ad6326..7aa3cd5dc 100644 --- a/streams_redis/README.md +++ b/streams_redis/README.md @@ -9,18 +9,21 @@ Activities and clients append to it, and a reader goes on from the offset of the that it read. `temporalio.contrib.workflow_streams` (see [workflow_streams](../workflow_streams)) keeps its events in the Workflow and needs no Store. A Stream keeps them in Redis. A client reads them from there, and they stay -readable for 7 days after the close by default. +readable after the Workflow ends. A Stream has no close. It expires when its Retention +(7 days by default) passes with no append. The sample has one scenario: * `workflows/agent_workflow.py` - an agent-like Workflow. It creates a Stream with the id - of the Workflow, writes a status event, runs the model Activity, writes another status - event, and closes the Stream in `finally`. + of the Workflow, writes a status event, and runs the model Activity. In `finally` it + writes the status event `Done`, which tells a reader to stop. * `activities/model_activity.py` - an Activity that stands in for a model. It appends each token of its answer to the Stream with `BufferedAppender`. * `run_agent.py` - starts the Workflow, gets the `StreamRef` from an Update, and prints the events as they come. After four events it disconnects. A new client then reads on from - the offset of the last event that it printed, and stops at the close of the Stream. + the offset of the last event that it printed, and stops at `Done`. A read never ends + by itself, so each reader breaks out of its loop. A terminated Workflow writes no + `Done`, so its reader waits until you stop it. ## Install @@ -68,7 +71,7 @@ The agent prints each event with its offset, which is opaque bytes: ... 000001a2068b9edd0000000000000000 token rest. 000001a2068b9f120000000000000000 status Done --- The Stream is closed. The Workflow returned: Redis keeps the events, so a reader can leave and come back for the rest. +-- The Workflow returned: Redis keeps the events, so a reader can leave and come back for the rest. ``` ## Test diff --git a/streams_redis/run_agent.py b/streams_redis/run_agent.py index 793642484..9034da770 100644 --- a/streams_redis/run_agent.py +++ b/streams_redis/run_agent.py @@ -5,12 +5,11 @@ import asyncio import uuid from collections.abc import Awaitable, Callable -from datetime import timedelta from temporalio.client import Client from temporalio.nexus.system.stream_service import StreamRef -from streams_redis.shared import TASK_QUEUE, AgentEvent, connect +from streams_redis.shared import LAST_EVENT, TASK_QUEUE, AgentEvent, connect from streams_redis.workflows.agent_workflow import AgentWorkflow QUESTION = "Why keep the events of an agent in Redis?" @@ -22,20 +21,17 @@ async def follow( after: bytes | None, stop_after: int | None = None, ) -> tuple[list[AgentEvent], bytes | None]: - """Print the events after an offset, up to ``stop_after`` of them or to the close. + """Print the events after an offset, to ``LAST_EVENT`` or ``stop_after`` of them. Return the events, with the offset of the last one. """ events: list[AgentEvent] = [] - # With a wait, a read ends only at the close of the Stream. - records = client.get_stream(stream_ref).read( - from_offset=after, wait=timedelta(seconds=10) - ) - async for record in records: + # The read waits for new events and never ends by itself, so the loop breaks. + async for record in client.get_stream(stream_ref).read(from_offset=after): print(f"{record.offset.hex()} {record.body.kind:<6} {record.body.text}") events.append(record.body) after = record.offset - if len(events) == stop_after: + if record.body == LAST_EVENT or len(events) == stop_after: break return events, after @@ -56,7 +52,7 @@ async def run(connect: Callable[[], Awaitable[Client]]) -> list[AgentEvent]: # A new client needs only the ref and the offset, so it misses no event and # repeats none. rest, _ = await follow(await connect(), stream_ref, after=offset) - print(f"-- The Stream is closed. The Workflow returned: {await handle.result()}") + print(f"-- The Workflow returned: {await handle.result()}") return first + rest diff --git a/streams_redis/shared.py b/streams_redis/shared.py index fc4819a87..f32eba4d6 100644 --- a/streams_redis/shared.py +++ b/streams_redis/shared.py @@ -16,6 +16,9 @@ class AgentEvent: text: str +LAST_EVENT = AgentEvent("status", "Done") + + async def connect() -> Client: """Connect a client whose Stream calls, and those of its Workers, go to Redis.""" config = ClientConfig.load_client_connect_config() diff --git a/streams_redis/workflows/agent_workflow.py b/streams_redis/workflows/agent_workflow.py index b513a6095..3b0b05592 100644 --- a/streams_redis/workflows/agent_workflow.py +++ b/streams_redis/workflows/agent_workflow.py @@ -7,7 +7,7 @@ with workflow.unsafe.imports_passed_through(): from streams_redis.activities.model_activity import stream_answer - from streams_redis.shared import AgentEvent + from streams_redis.shared import LAST_EVENT, AgentEvent @workflow.defn @@ -30,12 +30,11 @@ async def run(self, question: str) -> str: self._stream_ref = stream.ref try: await stream.append(AgentEvent("status", f"Thinking about: {question}")) - answer = await workflow.execute_activity( + return await workflow.execute_activity( stream_answer, stream.ref, start_to_close_timeout=timedelta(minutes=1), ) - await stream.append(AgentEvent("status", "Done")) - return answer finally: - await stream.close() + # A Stream has no close, so a reader stops when it sees this event. + await stream.append(LAST_EVENT) diff --git a/tests/streams_redis/agent_workflow_test.py b/tests/streams_redis/agent_workflow_test.py index 5e6a77f7f..ac168273e 100644 --- a/tests/streams_redis/agent_workflow_test.py +++ b/tests/streams_redis/agent_workflow_test.py @@ -23,7 +23,7 @@ async def connect() -> Client: ): events = await run(connect) - # The reader got each event once and in order, across its disconnect, to the close. + # The reader got each event once and in order, across its disconnect, to Done. assert events == [ AgentEvent("status", f"Thinking about: {QUESTION}"), *(AgentEvent("token", word) for word in ANSWER.split()), From df7a46be01a642af0716f97b470e20ef739a4beb Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 26 Nov 2026 22:13:44 -0700 Subject: [PATCH 3/8] Observe the Workflow result when the first reader reaches Done --- streams_redis/run_agent.py | 16 +++++++++------- tests/streams_redis/agent_workflow_test.py | 21 ++++++++++++++++++++- 2 files changed, 29 insertions(+), 8 deletions(-) diff --git a/streams_redis/run_agent.py b/streams_redis/run_agent.py index 9034da770..77f25d065 100644 --- a/streams_redis/run_agent.py +++ b/streams_redis/run_agent.py @@ -46,14 +46,16 @@ async def run(connect: Callable[[], Awaitable[Client]]) -> list[AgentEvent]: ) stream_ref = await handle.execute_update(AgentWorkflow.stream_ref) first, offset = await follow(client, stream_ref, after=None, stop_after=4) - print("-- The reader disconnects, and the agent goes on.") - await asyncio.sleep(1) - - # A new client needs only the ref and the offset, so it misses no event and - # repeats none. - rest, _ = await follow(await connect(), stream_ref, after=offset) + if LAST_EVENT not in first: + print("-- The reader disconnects, and the agent goes on.") + await asyncio.sleep(1) + + # A new client needs only the ref and the offset, so it misses no event and + # repeats none. + rest, _ = await follow(await connect(), stream_ref, after=offset) + first.extend(rest) print(f"-- The Workflow returned: {await handle.result()}") - return first + rest + return first if __name__ == "__main__": diff --git a/tests/streams_redis/agent_workflow_test.py b/tests/streams_redis/agent_workflow_test.py index ac168273e..d29c6a8b0 100644 --- a/tests/streams_redis/agent_workflow_test.py +++ b/tests/streams_redis/agent_workflow_test.py @@ -1,10 +1,14 @@ +from unittest.mock import AsyncMock + +import pytest from temporalio.client import Client, StreamConfig from temporalio.worker import Worker from temporalio_streams_redis import RedisStreamStore +from streams_redis import run_agent from streams_redis.activities.model_activity import ANSWER, stream_answer from streams_redis.run_agent import QUESTION, run -from streams_redis.shared import TASK_QUEUE, AgentEvent +from streams_redis.shared import LAST_EVENT, TASK_QUEUE, AgentEvent from streams_redis.workflows.agent_workflow import AgentWorkflow @@ -29,3 +33,18 @@ async def connect() -> Client: *(AgentEvent("token", word) for word in ANSWER.split()), AgentEvent("status", "Done"), ] + + +async def test_an_early_terminal_event_observes_the_workflow_result(monkeypatch): + handle = AsyncMock() + handle.result.side_effect = RuntimeError("Workflow cancelled") + connect = AsyncMock() + connect.return_value.start_workflow.return_value = handle + follow = AsyncMock(return_value=([LAST_EVENT], b"last")) + monkeypatch.setattr(run_agent, "follow", follow) + + with pytest.raises(RuntimeError, match="Workflow cancelled"): + await run(connect) + connect.assert_awaited_once() + follow.assert_awaited_once() + handle.result.assert_awaited_once() From 325b7efcdd40d1dcbc02f6fe121702ccd18ee676 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Thu, 26 Nov 2026 22:19:37 -0700 Subject: [PATCH 4/8] Exercise terminal cancellation against a Worker and Redis --- tests/streams_redis/agent_workflow_test.py | 45 ++++++++++++++-------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/tests/streams_redis/agent_workflow_test.py b/tests/streams_redis/agent_workflow_test.py index d29c6a8b0..bf6c908bd 100644 --- a/tests/streams_redis/agent_workflow_test.py +++ b/tests/streams_redis/agent_workflow_test.py @@ -1,7 +1,6 @@ -from unittest.mock import AsyncMock - import pytest -from temporalio.client import Client, StreamConfig +from temporalio.client import Client, StreamConfig, WorkflowFailureError +from temporalio.exceptions import CancelledError from temporalio.worker import Worker from temporalio_streams_redis import RedisStreamStore @@ -35,16 +34,32 @@ async def connect() -> Client: ] -async def test_an_early_terminal_event_observes_the_workflow_result(monkeypatch): - handle = AsyncMock() - handle.result.side_effect = RuntimeError("Workflow cancelled") - connect = AsyncMock() - connect.return_value.start_workflow.return_value = handle - follow = AsyncMock(return_value=([LAST_EVENT], b"last")) - monkeypatch.setattr(run_agent, "follow", follow) +async def test_an_early_terminal_event_observes_the_workflow_result( + client: Client, redis_url: str, monkeypatch +): + config = client.config() + config["stream_config"] = StreamConfig(stores=[RedisStreamStore(redis_url)]) + client = Client(**config) + follow = run_agent.follow + events = [] + + async def cancel_then_follow(client, stream_ref, **kwargs): + await client.get_workflow_handle(stream_ref.id).cancel() + page, offset = await follow(client, stream_ref, **kwargs) + events.extend(page) + return page, offset + + monkeypatch.setattr(run_agent, "follow", cancel_then_follow) + + async def connect() -> Client: + assert not events, "the reader reconnected after Done" + return client + + # Keep the Activity queued so cancellation reaches the Workflow before four events. + async with Worker(client, task_queue=TASK_QUEUE, workflows=[AgentWorkflow]): + with pytest.raises(WorkflowFailureError) as failure: + await run(connect) - with pytest.raises(RuntimeError, match="Workflow cancelled"): - await run(connect) - connect.assert_awaited_once() - follow.assert_awaited_once() - handle.result.assert_awaited_once() + assert isinstance(failure.value.cause, CancelledError) + assert 0 < len(events) < 4 + assert events[-1] == LAST_EVENT From 234df882df3f2fd33007d591a894c11f86465438 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 27 Nov 2026 02:15:51 -0700 Subject: [PATCH 5/8] Stop Stream readers when the Workflow fails --- streams_redis/README.md | 84 +++++++++------------- streams_redis/activities/model_activity.py | 4 +- streams_redis/run_agent.py | 53 +++++++++----- streams_redis/shared.py | 2 +- streams_redis/workflows/agent_workflow.py | 10 ++- tests/streams_redis/agent_workflow_test.py | 36 +++++++++- tests/streams_redis/conftest.py | 8 +-- 7 files changed, 112 insertions(+), 85 deletions(-) diff --git a/streams_redis/README.md b/streams_redis/README.md index 7aa3cd5dc..b5568b3fb 100644 --- a/streams_redis/README.md +++ b/streams_redis/README.md @@ -1,33 +1,22 @@ # Streams on Redis -> **Experimental.** This sample uses the Streams API of the Temporal Python SDK and the -> Redis Stream Store of `temporal-community/sdk-streams`. Neither has a release yet, and -> both APIs may change. - -A Stream is an append-only log of events in a Stream Store, here Redis. Workflow code, -Activities and clients append to it, and a reader goes on from the offset of the last event -that it read. `temporalio.contrib.workflow_streams` (see -[workflow_streams](../workflow_streams)) keeps its events in the Workflow and needs no -Store. A Stream keeps them in Redis. A client reads them from there, and they stay -readable after the Workflow ends. A Stream has no close. It expires when its Retention -(7 days by default) passes with no append. - -The sample has one scenario: - -* `workflows/agent_workflow.py` - an agent-like Workflow. It creates a Stream with the id - of the Workflow, writes a status event, and runs the model Activity. In `finally` it - writes the status event `Done`, which tells a reader to stop. -* `activities/model_activity.py` - an Activity that stands in for a model. It appends each - token of its answer to the Stream with `BufferedAppender`. -* `run_agent.py` - starts the Workflow, gets the `StreamRef` from an Update, and prints the - events as they come. After four events it disconnects. A new client then reads on from - the offset of the last event that it printed, and stops at `Done`. A read never ends - by itself, so each reader breaks out of its loop. A terminated Workflow writes no - `Done`, so its reader waits until you stop it. +> **Experimental.** The Streams SDK and Redis Store are unreleased. Their APIs can change. + +This sample reads agent events from Redis after a client disconnects. +The reader saves the last consumed offset and resumes without repeating or skipping events. + +The Workflow creates a Stream and returns its `StreamRef` through an Update. +The Activity uses `BufferedAppender` to write fixed model tokens without an external model service. +A `Done` event stops the reader. The Workflow result reports success or failure. +The client also observes that result because termination can prevent the final event. + +Streams have no close operation. Each new batch restarts retention, which defaults to seven days. +Reads and resends do not extend retention. Events remain readable after the Workflow ends. +The [Workflow Streams sample](../workflow_streams) keeps events in the Workflow and needs no Store. ## Install -The two packages build from source, with Rust and `protoc`. From the root of this repo: +Install Rust and `protoc`. Run these commands from the repository root. ```bash uv sync @@ -37,48 +26,39 @@ git clone --branch moe/retention-from-close https://github.com/temporal-communit uv pip install ../sdk-streams/python ``` -The Store's native module needs the crate `temporalio-streams`, which isn't on crates.io -yet. `patch-sdk-rust.sh` points the build at the branch of `temporalio/sdk-rust` that has it. +The patch script selects the unreleased `temporalio-streams` Rust crate. +Use `--no-sync` below to keep `uv` from replacing these packages with released versions. -## Run it +## Run -Start Redis and a Temporal dev server: +Start Redis and Temporal in separate terminals. ```bash -redis-server -temporal server start-dev +redis-server --port 26379 ``` -Start the Worker, and then the agent in another terminal: - ```bash -uv run --no-sync streams_redis/run_worker.py -uv run --no-sync streams_redis/run_agent.py +temporal server start-dev ``` -`--no-sync` keeps uv from putting the released `temporalio` back. Set `REDIS_URL` for a -Redis other than `redis://localhost:6379`. - -The agent prints each event with its offset, which is opaque bytes: +Start the Worker and client in separate terminals. +```bash +REDIS_URL=redis://localhost:26379 uv run --no-sync streams_redis/run_worker.py ``` -000001a2068b96180000000000000000 status Thinking about: Why keep the events of an agent in Redis? -000001a2068b96880000000000000000 token Redis -000001a2068b97210000000000000000 token keeps -000001a2068b97b90000000000000000 token the --- The reader disconnects, and the agent goes on. -000001a2068b98510000000000000000 token events, -... -000001a2068b9edd0000000000000000 token rest. -000001a2068b9f120000000000000000 status Done --- The Workflow returned: Redis keeps the events, so a reader can leave and come back for the rest. + +```bash +REDIS_URL=redis://localhost:26379 uv run --no-sync streams_redis/run_agent.py ``` +The client prints each event and its offset. It reconnects after four events and reads through `Done`. +A Workflow failure ends the reader and raises the Workflow error. + ## Test -The test starts its own `redis-server`, from the `PATH`. It isn't collected when the two -packages aren't installed, as in the CI of this repo. +The tests start a local Temporal server and a private `redis-server` from `PATH`. +Collection skips these tests when either unreleased package is absent. ```bash -uv run --no-sync pytest tests/streams_redis +uv run --no-sync pytest tests/streams_redis --deselect=tests/test_envconfig.py::test_load_profiles_no_config_file ``` diff --git a/streams_redis/activities/model_activity.py b/streams_redis/activities/model_activity.py index 7b48b6d8b..bad124960 100644 --- a/streams_redis/activities/model_activity.py +++ b/streams_redis/activities/model_activity.py @@ -13,9 +13,9 @@ @activity.defn async def stream_answer(stream_ref: StreamRef[AgentEvent]) -> str: - """Stand in for a model that streams the tokens of its answer.""" + """Use fixed tokens so the sample needs no model service.""" stream = activity.client().get_stream(stream_ref) - # The appender writes in the background, so the model never waits for Redis. + # Background writes let token generation continue between flushes. async with BufferedAppender(stream) as tokens: for word in ANSWER.split(): tokens.append(AgentEvent("token", word)) diff --git a/streams_redis/run_agent.py b/streams_redis/run_agent.py index 77f25d065..b7f025f37 100644 --- a/streams_redis/run_agent.py +++ b/streams_redis/run_agent.py @@ -1,4 +1,4 @@ -"""Start the agent, print its events as they come, disconnect, and resume.""" +"""Resume Stream reads after a client disconnect.""" from __future__ import annotations @@ -6,7 +6,7 @@ import uuid from collections.abc import Awaitable, Callable -from temporalio.client import Client +from temporalio.client import Client, WorkflowHandle from temporalio.nexus.system.stream_service import StreamRef from streams_redis.shared import LAST_EVENT, TASK_QUEUE, AgentEvent, connect @@ -21,12 +21,8 @@ async def follow( after: bytes | None, stop_after: int | None = None, ) -> tuple[list[AgentEvent], bytes | None]: - """Print the events after an offset, to ``LAST_EVENT`` or ``stop_after`` of them. - - Return the events, with the offset of the last one. - """ + """Stop at an application event because Streams have no close operation.""" events: list[AgentEvent] = [] - # The read waits for new events and never ends by itself, so the loop breaks. async for record in client.get_stream(stream_ref).read(from_offset=after): print(f"{record.offset.hex()} {record.body.kind:<6} {record.body.text}") events.append(record.body) @@ -36,27 +32,48 @@ async def follow( return events, after -async def run(connect: Callable[[], Awaitable[Client]]) -> list[AgentEvent]: - client = await connect() - handle = await client.start_workflow( - AgentWorkflow.run, - QUESTION, - id=f"agent-{uuid.uuid4()}", - task_queue=TASK_QUEUE, - ) +async def read_and_resume( + client: Client, + handle: WorkflowHandle, + connect: Callable[[], Awaitable[Client]], +) -> list[AgentEvent]: stream_ref = await handle.execute_update(AgentWorkflow.stream_ref) first, offset = await follow(client, stream_ref, after=None, stop_after=4) if LAST_EVENT not in first: print("-- The reader disconnects, and the agent goes on.") await asyncio.sleep(1) - # A new client needs only the ref and the offset, so it misses no event and - # repeats none. + # The last consumed offset prevents gaps and repeats after reconnect. rest, _ = await follow(await connect(), stream_ref, after=offset) first.extend(rest) - print(f"-- The Workflow returned: {await handle.result()}") return first +async def run(connect: Callable[[], Awaitable[Client]]) -> list[AgentEvent]: + client = await connect() + handle = await client.start_workflow( + AgentWorkflow.run, + QUESTION, + id=f"agent-{uuid.uuid4()}", + task_queue=TASK_QUEUE, + ) + result_task = asyncio.create_task(handle.result()) + reader_task = asyncio.create_task(read_and_resume(client, handle, connect)) + try: + # Termination skips the Workflow's final event, so also observe its result. + done, _ = await asyncio.wait( + (reader_task, result_task), return_when=asyncio.FIRST_COMPLETED + ) + if result_task in done: + await result_task + events = await reader_task + print(f"-- The Workflow returned: {await result_task}") + return events + finally: + for task in (reader_task, result_task): + task.cancel() + await asyncio.gather(reader_task, result_task, return_exceptions=True) + + if __name__ == "__main__": asyncio.run(run(connect)) diff --git a/streams_redis/shared.py b/streams_redis/shared.py index f32eba4d6..581e52752 100644 --- a/streams_redis/shared.py +++ b/streams_redis/shared.py @@ -20,7 +20,7 @@ class AgentEvent: async def connect() -> Client: - """Connect a client whose Stream calls, and those of its Workers, go to Redis.""" + """Share one Store configuration between the client and its Workers.""" config = ClientConfig.load_client_connect_config() config.setdefault("target_host", "localhost:7233") store = RedisStreamStore(os.environ.get("REDIS_URL", "redis://localhost:6379")) diff --git a/streams_redis/workflows/agent_workflow.py b/streams_redis/workflows/agent_workflow.py index 3b0b05592..2627f8bed 100644 --- a/streams_redis/workflows/agent_workflow.py +++ b/streams_redis/workflows/agent_workflow.py @@ -1,5 +1,6 @@ from __future__ import annotations +import asyncio from datetime import timedelta from temporalio import workflow @@ -30,11 +31,14 @@ async def run(self, question: str) -> str: self._stream_ref = stream.ref try: await stream.append(AgentEvent("status", f"Thinking about: {question}")) - return await workflow.execute_activity( + result = await workflow.execute_activity( stream_answer, stream.ref, start_to_close_timeout=timedelta(minutes=1), ) - finally: - # A Stream has no close, so a reader stops when it sees this event. + except (Exception, asyncio.CancelledError): + # Coroutine cleanup cannot await a Store call, so exclude GeneratorExit. await stream.append(LAST_EVENT) + raise + await stream.append(LAST_EVENT) + return result diff --git a/tests/streams_redis/agent_workflow_test.py b/tests/streams_redis/agent_workflow_test.py index bf6c908bd..b7d15dbd7 100644 --- a/tests/streams_redis/agent_workflow_test.py +++ b/tests/streams_redis/agent_workflow_test.py @@ -1,6 +1,8 @@ +import asyncio + import pytest from temporalio.client import Client, StreamConfig, WorkflowFailureError -from temporalio.exceptions import CancelledError +from temporalio.exceptions import CancelledError, TerminatedError from temporalio.worker import Worker from temporalio_streams_redis import RedisStreamStore @@ -26,7 +28,6 @@ async def connect() -> Client: ): events = await run(connect) - # The reader got each event once and in order, across its disconnect, to Done. assert events == [ AgentEvent("status", f"Thinking about: {QUESTION}"), *(AgentEvent("token", word) for word in ANSWER.split()), @@ -63,3 +64,34 @@ async def connect() -> Client: assert isinstance(failure.value.cause, CancelledError) assert 0 < len(events) < 4 assert events[-1] == LAST_EVENT + + +async def test_a_terminated_workflow_stops_its_reader( + client: Client, redis_url: str, monkeypatch +): + config = client.config() + config["stream_config"] = StreamConfig(stores=[RedisStreamStore(redis_url)]) + client = Client(**config) + follow = run_agent.follow + reader_closed = asyncio.Event() + + async def terminate_then_follow(client, stream_ref, **kwargs): + await client.get_workflow_handle(stream_ref.id).terminate() + try: + return await follow(client, stream_ref, **kwargs) + finally: + reader_closed.set() + + monkeypatch.setattr(run_agent, "follow", terminate_then_follow) + + async def connect() -> Client: + return client + + # A queued Activity keeps the Workflow open without writing its final event. + async with Worker(client, task_queue=TASK_QUEUE, workflows=[AgentWorkflow]): + async with asyncio.timeout(15): + with pytest.raises(WorkflowFailureError) as failure: + await run(connect) + + assert isinstance(failure.value.cause, TerminatedError) + assert reader_closed.is_set() diff --git a/tests/streams_redis/conftest.py b/tests/streams_redis/conftest.py index 4b3c0e757..b612db389 100644 --- a/tests/streams_redis/conftest.py +++ b/tests/streams_redis/conftest.py @@ -1,10 +1,4 @@ -"""Collection guard and Redis server for the tests of the Streams sample on Redis. - -The Streams API of `temporalio` and the `temporalio-streams-redis` package have no -release yet, so the environment of this repo has neither. The test module imports -both, and `collect_ignore_glob` skips it before that import fails, as -`tests/microsoft_agent_framework_plugin/conftest.py` does for its plugin. -""" +"""Skip collection until the unreleased Streams packages are installed.""" import shutil import socket From 048356319adc5f79bde948cd4d53333935e2f795 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Fri, 27 Nov 2026 02:19:33 -0700 Subject: [PATCH 6/8] Keep terminal-event coverage independent of result delivery --- streams_redis/README.md | 2 +- tests/streams_redis/agent_workflow_test.py | 12 +++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/streams_redis/README.md b/streams_redis/README.md index b5568b3fb..200f514bf 100644 --- a/streams_redis/README.md +++ b/streams_redis/README.md @@ -60,5 +60,5 @@ The tests start a local Temporal server and a private `redis-server` from `PATH` Collection skips these tests when either unreleased package is absent. ```bash -uv run --no-sync pytest tests/streams_redis --deselect=tests/test_envconfig.py::test_load_profiles_no_config_file +uv run --no-sync pytest tests/streams_redis ``` diff --git a/tests/streams_redis/agent_workflow_test.py b/tests/streams_redis/agent_workflow_test.py index b7d15dbd7..249ce5858 100644 --- a/tests/streams_redis/agent_workflow_test.py +++ b/tests/streams_redis/agent_workflow_test.py @@ -1,7 +1,7 @@ import asyncio import pytest -from temporalio.client import Client, StreamConfig, WorkflowFailureError +from temporalio.client import Client, StreamConfig, WorkflowFailureError, WorkflowHandle from temporalio.exceptions import CancelledError, TerminatedError from temporalio.worker import Worker from temporalio_streams_redis import RedisStreamStore @@ -43,11 +43,21 @@ async def test_an_early_terminal_event_observes_the_workflow_result( client = Client(**config) follow = run_agent.follow events = [] + read_done = asyncio.Event() + result = WorkflowHandle.result + + async def result_after_read(self, *args, **kwargs): + # Force the final-event path instead of racing Workflow result delivery. + await read_done.wait() + return await result(self, *args, **kwargs) + + monkeypatch.setattr(WorkflowHandle, "result", result_after_read) async def cancel_then_follow(client, stream_ref, **kwargs): await client.get_workflow_handle(stream_ref.id).cancel() page, offset = await follow(client, stream_ref, **kwargs) events.extend(page) + read_done.set() return page, offset monkeypatch.setattr(run_agent, "follow", cancel_then_follow) From f25d2921dcd5b397f9c4e5768757fd96a1418f18 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Sat, 28 Nov 2026 04:25:52 -0700 Subject: [PATCH 7/8] Preserve Stream startup and cancellation order --- README.md | 3 +- streams_redis/README.md | 18 +- streams_redis/activities/model_activity.py | 1 + streams_redis/run_agent.py | 23 +- streams_redis/workflows/agent_workflow.py | 8 + tests/streams_redis/agent_workflow_test.py | 98 +++++- tests/streams_redis/cancellation_history.json | 328 ++++++++++++++++++ tests/streams_redis/conftest.py | 9 +- 8 files changed, 465 insertions(+), 23 deletions(-) create mode 100644 tests/streams_redis/cancellation_history.json diff --git a/README.md b/README.md index 59bc55d36..7b37efdae 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,8 @@ without wrapping them in a workflow. * [sentry](sentry) - Report errors to Sentry. * [sleep_for_days](sleep_for_days) - A workflow that runs forever, sending an email every 30 days. * [strands_plugin](strands_plugin) - Run Strands Agents as durable Temporal workflows (model calls, tools, MCP, HITL). -* [streams_redis](streams_redis) - Stream the events of an agent through Redis, and resume a reader from its offset. **Experimental** +* [streams_redis](streams_redis) - Read agent events from Redis and resume from an offset. + **Experimental** * [trio_async](trio_async) - Use asyncio Temporal in Trio-based environments. * [updatable_timer](updatable_timer) - A timer that can be updated while sleeping. * [worker_multiprocessing](worker_multiprocessing) - Leverage Python multiprocessing to parallelize workflow tasks and other CPU bound operations by running multiple workers. diff --git a/streams_redis/README.md b/streams_redis/README.md index 200f514bf..c5d4b0ebe 100644 --- a/streams_redis/README.md +++ b/streams_redis/README.md @@ -3,25 +3,27 @@ > **Experimental.** The Streams SDK and Redis Store are unreleased. Their APIs can change. This sample reads agent events from Redis after a client disconnects. -The reader saves the last consumed offset and resumes without repeating or skipping events. +The reader resumes after its last consumed offset. -The Workflow creates a Stream and returns its `StreamRef` through an Update. +Update-with-Start starts the Workflow and requests its `StreamRef` in one call. The Activity uses `BufferedAppender` to write fixed model tokens without an external model service. A `Done` event stops the reader. The Workflow result reports success or failure. -The client also observes that result because termination can prevent the final event. +On cancellation, the Workflow waits for its Activity to stop before writing `Done`. +The client also observes the result because termination can prevent that final event. Streams have no close operation. Each new batch restarts retention, which defaults to seven days. -Reads and resends do not extend retention. Events remain readable after the Workflow ends. +Reads and resends do not extend retention. Events remain readable until retention expires. The [Workflow Streams sample](../workflow_streams) keeps events in the Workflow and needs no Store. ## Install -Install Rust and `protoc`. Run these commands from the repository root. +Install Redis 7.0 or later, Rust and `protoc`. Run these commands from the repository root. ```bash uv sync uv pip install "temporalio @ git+https://github.com/temporalio/sdk-python@moe/streams-api" -git clone --branch moe/retention-from-close https://github.com/temporal-community/sdk-streams ../sdk-streams +git clone --branch moe/retention-from-close \ + https://github.com/temporal-community/sdk-streams ../sdk-streams (cd ../sdk-streams && SDK_RUST_REF=moe/streams-crate-types scripts/patch-sdk-rust.sh) uv pip install ../sdk-streams/python ``` @@ -51,7 +53,9 @@ REDIS_URL=redis://localhost:26379 uv run --no-sync streams_redis/run_worker.py REDIS_URL=redis://localhost:26379 uv run --no-sync streams_redis/run_agent.py ``` -The client prints each event and its offset. It reconnects after four events and reads through `Done`. +The client prints each event and its offset. +After four events, it reconnects and reads through `Done`. +Activity retries can append repeated tokens at new offsets. A Workflow failure ends the reader and raises the Workflow error. ## Test diff --git a/streams_redis/activities/model_activity.py b/streams_redis/activities/model_activity.py index bad124960..90fc67f53 100644 --- a/streams_redis/activities/model_activity.py +++ b/streams_redis/activities/model_activity.py @@ -18,6 +18,7 @@ async def stream_answer(stream_ref: StreamRef[AgentEvent]) -> str: # Background writes let token generation continue between flushes. async with BufferedAppender(stream) as tokens: for word in ANSWER.split(): + activity.heartbeat() tokens.append(AgentEvent("token", word)) await asyncio.sleep(0.15) return ANSWER diff --git a/streams_redis/run_agent.py b/streams_redis/run_agent.py index b7f025f37..6a26944ac 100644 --- a/streams_redis/run_agent.py +++ b/streams_redis/run_agent.py @@ -6,7 +6,13 @@ import uuid from collections.abc import Awaitable, Callable -from temporalio.client import Client, WorkflowHandle +from temporalio.client import ( + Client, + WithStartWorkflowOperation, + WorkflowUpdateHandle, + WorkflowUpdateStage, +) +from temporalio.common import WorkflowIDConflictPolicy from temporalio.nexus.system.stream_service import StreamRef from streams_redis.shared import LAST_EVENT, TASK_QUEUE, AgentEvent, connect @@ -34,10 +40,10 @@ async def follow( async def read_and_resume( client: Client, - handle: WorkflowHandle, + ref_update: WorkflowUpdateHandle[StreamRef[AgentEvent]], connect: Callable[[], Awaitable[Client]], ) -> list[AgentEvent]: - stream_ref = await handle.execute_update(AgentWorkflow.stream_ref) + stream_ref = await ref_update.result() first, offset = await follow(client, stream_ref, after=None, stop_after=4) if LAST_EVENT not in first: print("-- The reader disconnects, and the agent goes on.") @@ -51,14 +57,21 @@ async def read_and_resume( async def run(connect: Callable[[], Awaitable[Client]]) -> list[AgentEvent]: client = await connect() - handle = await client.start_workflow( + start = WithStartWorkflowOperation( AgentWorkflow.run, QUESTION, id=f"agent-{uuid.uuid4()}", + id_conflict_policy=WorkflowIDConflictPolicy.FAIL, task_queue=TASK_QUEUE, ) + ref_update = await client.start_update_with_start_workflow( + AgentWorkflow.stream_ref, + start_workflow_operation=start, + wait_for_stage=WorkflowUpdateStage.ACCEPTED, + ) + handle = await start.workflow_handle() result_task = asyncio.create_task(handle.result()) - reader_task = asyncio.create_task(read_and_resume(client, handle, connect)) + reader_task = asyncio.create_task(read_and_resume(client, ref_update, connect)) try: # Termination skips the Workflow's final event, so also observe its result. done, _ = await asyncio.wait( diff --git a/streams_redis/workflows/agent_workflow.py b/streams_redis/workflows/agent_workflow.py index 2627f8bed..1ac69f1c3 100644 --- a/streams_redis/workflows/agent_workflow.py +++ b/streams_redis/workflows/agent_workflow.py @@ -31,10 +31,18 @@ async def run(self, question: str) -> str: self._stream_ref = stream.ref try: await stream.append(AgentEvent("status", f"Thinking about: {question}")) + # Cancellation must preserve the recorded Workflow command order. + wait_for_writer = workflow.patched("wait-for-stream-writer-cancellation") result = await workflow.execute_activity( stream_answer, stream.ref, start_to_close_timeout=timedelta(minutes=1), + heartbeat_timeout=timedelta(seconds=1) if wait_for_writer else None, + cancellation_type=( + workflow.ActivityCancellationType.WAIT_CANCELLATION_COMPLETED + if wait_for_writer + else workflow.ActivityCancellationType.TRY_CANCEL + ), ) except (Exception, asyncio.CancelledError): # Coroutine cleanup cannot await a Store call, so exclude GeneratorExit. diff --git a/tests/streams_redis/agent_workflow_test.py b/tests/streams_redis/agent_workflow_test.py index 249ce5858..6589df7e8 100644 --- a/tests/streams_redis/agent_workflow_test.py +++ b/tests/streams_redis/agent_workflow_test.py @@ -1,9 +1,21 @@ import asyncio +import json +import uuid +from pathlib import Path import pytest -from temporalio.client import Client, StreamConfig, WorkflowFailureError, WorkflowHandle +from temporalio import activity +from temporalio.client import ( + Client, + StreamConfig, + WorkflowFailureError, + WorkflowHandle, + WorkflowHistory, +) from temporalio.exceptions import CancelledError, TerminatedError -from temporalio.worker import Worker +from temporalio.nexus.system.stream_service import StreamRef +from temporalio.testing import MemoryStreamStore +from temporalio.worker import Replayer, Worker from temporalio_streams_redis import RedisStreamStore from streams_redis import run_agent @@ -13,20 +25,41 @@ from streams_redis.workflows.agent_workflow import AgentWorkflow -async def test_a_reader_resumes_at_its_offset(client: Client, redis_url: str): +@pytest.mark.parametrize("after_completion", [False, True], ids=["live", "completed"]) +async def test_a_reader_resumes_at_its_offset( + client: Client, redis_url: str, monkeypatch, after_completion: bool +): config = client.config() config["stream_config"] = StreamConfig(stores=[RedisStreamStore(redis_url)]) async def connect() -> Client: return Client(**config) + if after_completion: + completed = asyncio.Event() + result = WorkflowHandle.result + read = run_agent.read_and_resume + + async def observe_completion(self, *args, **kwargs): + answer = await result(self, *args, **kwargs) + completed.set() + return answer + + async def delayed_read(*args, **kwargs): + await completed.wait() + return await read(*args, **kwargs) + + monkeypatch.setattr(WorkflowHandle, "result", observe_completion) + monkeypatch.setattr(run_agent, "read_and_resume", delayed_read) + async with Worker( await connect(), task_queue=TASK_QUEUE, workflows=[AgentWorkflow], activities=[stream_answer], ): - events = await run(connect) + async with asyncio.timeout(15): + events = await run(connect) assert events == [ AgentEvent("status", f"Thinking about: {QUESTION}"), @@ -68,14 +101,67 @@ async def connect() -> Client: # Keep the Activity queued so cancellation reaches the Workflow before four events. async with Worker(client, task_queue=TASK_QUEUE, workflows=[AgentWorkflow]): - with pytest.raises(WorkflowFailureError) as failure: - await run(connect) + async with asyncio.timeout(15): + with pytest.raises(WorkflowFailureError) as failure: + await run(connect) assert isinstance(failure.value.cause, CancelledError) assert 0 < len(events) < 4 assert events[-1] == LAST_EVENT +async def test_cancellation_after_a_token_leaves_done_last( + client: Client, redis_url: str +): + config = client.config() + config["stream_config"] = StreamConfig(stores=[RedisStreamStore(redis_url)]) + client = Client(**config) + stopped = asyncio.Event() + + @activity.defn(name="stream_answer") + async def tracked_answer(stream_ref: StreamRef[AgentEvent]) -> str: + try: + return await stream_answer(stream_ref) + finally: + stopped.set() + + async with Worker( + client, + task_queue=TASK_QUEUE, + workflows=[AgentWorkflow], + activities=[tracked_answer], + ): + async with asyncio.timeout(15): + handle = await client.start_workflow( + AgentWorkflow.run, QUESTION, id=str(uuid.uuid4()), task_queue=TASK_QUEUE + ) + stream = client.get_stream( + await handle.execute_update(AgentWorkflow.stream_ref) + ) + async for record in stream.read(): + if record.body.kind == "token": + break + await handle.cancel() + with pytest.raises(WorkflowFailureError) as failure: + await handle.result() + await stopped.wait() + page = await stream.read_page() + + assert isinstance(failure.value.cause, CancelledError) + assert page.records[-1].body == LAST_EVENT + + +async def test_replay_cancellation_before_activity_acknowledgement(): + history = json.loads( + Path(__file__).with_name("cancellation_history.json").read_text() + ) + started = history["events"][0]["workflowExecutionStartedEventAttributes"] + await Replayer( + workflows=[AgentWorkflow], + stream_config=StreamConfig(stores=[MemoryStreamStore(name="redis")]), + ).replay_workflow(WorkflowHistory.from_json(started["workflowId"], history)) + + async def test_a_terminated_workflow_stops_its_reader( client: Client, redis_url: str, monkeypatch ): diff --git a/tests/streams_redis/cancellation_history.json b/tests/streams_redis/cancellation_history.json new file mode 100644 index 000000000..a665f8720 --- /dev/null +++ b/tests/streams_redis/cancellation_history.json @@ -0,0 +1,328 @@ +{ + "events": [ + { + "eventId": "1", + "eventTime": "2026-11-28T11:18:02.004910Z", + "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_STARTED", + "taskId": "1048587", + "workflowExecutionStartedEventAttributes": { + "workflowType": { + "name": "AgentWorkflow" + }, + "taskQueue": { + "name": "streams-redis-task-queue", + "kind": "TASK_QUEUE_KIND_NORMAL" + }, + "input": { + "payloads": [ + { + "metadata": { + "encoding": "anNvbi9wbGFpbg==" + }, + "data": "IldoeSBrZWVwIHRoZSBldmVudHMgb2YgYW4gYWdlbnQgaW4gUmVkaXM/Ig==" + } + ] + }, + "workflowTaskTimeout": "10s", + "originalExecutionRunId": "01a221e0-5e14-7de2-9d5c-6b7d4dd5acfc", + "identity": "sample-worker", + "firstExecutionRunId": "01a221e0-5e14-7de2-9d5c-6b7d4dd5acfc", + "attempt": 1, + "firstWorkflowTaskBackoff": "0s", + "workflowId": "2bfae822-3339-470a-9943-3beece7b8452", + "priority": {} + } + }, + { + "eventId": "2", + "eventTime": "2026-11-28T11:18:02.004956Z", + "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED", + "taskId": "1048588", + "workflowTaskScheduledEventAttributes": { + "taskQueue": { + "name": "streams-redis-task-queue", + "kind": "TASK_QUEUE_KIND_NORMAL" + }, + "startToCloseTimeout": "10s", + "attempt": 1 + } + }, + { + "eventId": "3", + "eventTime": "2026-11-28T11:18:02.008955Z", + "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED", + "taskId": "1048593", + "workflowTaskStartedEventAttributes": { + "scheduledEventId": "2", + "identity": "sample-worker", + "requestId": "f254bf33-2c99-4a7a-bcdc-9317f00183f0", + "historySizeBytes": "367", + "workerVersion": { + "buildId": "5b94a49d2377cf8050182eb77fc9caa4" + } + } + }, + { + "eventId": "4", + "eventTime": "2026-11-28T11:18:02.018935Z", + "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED", + "taskId": "1048598", + "workflowTaskCompletedEventAttributes": { + "scheduledEventId": "2", + "startedEventId": "3", + "identity": "sample-worker", + "workerVersion": { + "buildId": "5b94a49d2377cf8050182eb77fc9caa4" + }, + "sdkMetadata": { + "coreUsedFlags": [ + 1, + 2, + 3, + 4, + 5 + ], + "sdkName": "temporal-python", + "sdkVersion": "1.37.0" + }, + "meteringMetadata": {} + } + }, + { + "eventId": "5", + "eventTime": "2026-11-28T11:18:02.019058Z", + "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_UPDATE_ACCEPTED", + "taskId": "1048599", + "workflowExecutionUpdateAcceptedEventAttributes": { + "protocolInstanceId": "8fd01153-73fe-4afa-942c-ca59f9a3077a", + "acceptedRequestMessageId": "8fd01153-73fe-4afa-942c-ca59f9a3077a/request", + "acceptedRequestSequencingEventId": "2", + "acceptedRequest": { + "meta": { + "updateId": "8fd01153-73fe-4afa-942c-ca59f9a3077a", + "identity": "sample-worker" + }, + "input": { + "name": "stream_ref" + } + } + } + }, + { + "eventId": "6", + "eventTime": "2026-11-28T11:18:02.019149Z", + "eventType": "EVENT_TYPE_MARKER_RECORDED", + "taskId": "1048600", + "markerRecordedEventAttributes": { + "markerName": "core_local_activity", + "details": { + "data": { + "payloads": [ + { + "metadata": { + "encoding": "anNvbi9wbGFpbg==" + }, + "data": "eyJzZXEiOjEsImF0dGVtcHQiOjEsImFjdGl2aXR5X2lkIjoiMSIsImFjdGl2aXR5X3R5cGUiOiJfX3RlbXBvcmFsX3N0cmVhbV9zdG9yZV9jYWxsIiwiY29tcGxldGVfdGltZSI6eyJzZWNvbmRzIjoxNzk1ODY0NjgyLCJuYW5vcyI6MTA2ODY0NTh9LCJiYWNrb2ZmIjpudWxsLCJvcmlnaW5hbF9zY2hlZHVsZV90aW1lIjp7InNlY29uZHMiOjE3OTU4NjQ2ODIsIm5hbm9zIjoxMjk2MjAwMH0sImFjdGl2YXRpb25faW5kZXgiOjF9" + } + ] + }, + "result": { + "payloads": [ + { + "metadata": { + "encoding": "YmluYXJ5L3BsYWlu" + }, + "data": "Ci0KJDJiZmFlODIyLTMzMzktNDcwYS05OTQzLTNiZWVjZTdiODQ1MhIFcmVkaXMQAQ==" + } + ] + } + }, + "workflowTaskCompletedEventId": "4" + } + }, + { + "eventId": "7", + "eventTime": "2026-11-28T11:18:02.019182Z", + "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_UPDATE_COMPLETED", + "taskId": "1048601", + "workflowExecutionUpdateCompletedEventAttributes": { + "meta": { + "updateId": "8fd01153-73fe-4afa-942c-ca59f9a3077a", + "identity": "sample-worker" + }, + "outcome": { + "success": { + "payloads": [ + { + "metadata": { + "encoding": "anNvbi9wcm90b2J1Zg==", + "messageType": "dGVtcG9yYWwuYXBpLnNkay52MS5TdHJlYW1SZWY=" + }, + "data": "eyJpZCI6IjJiZmFlODIyLTMzMzktNDcwYS05OTQzLTNiZWVjZTdiODQ1MiIsInN0b3JlIjoicmVkaXMifQ==" + } + ] + } + }, + "acceptedEventId": "5" + } + }, + { + "eventId": "8", + "eventTime": "2026-11-28T11:18:02.019206Z", + "eventType": "EVENT_TYPE_MARKER_RECORDED", + "taskId": "1048602", + "markerRecordedEventAttributes": { + "markerName": "core_stream_append", + "details": { + "data": { + "payloads": [ + { + "metadata": { + "encoding": "anNvbi9wbGFpbg==" + }, + "data": "eyJhcHBlbmRzIjpbeyJzZXEiOjEsInN0cmVhbV9pZCI6IjJiZmFlODIyLTMzMzktNDcwYS05OTQzLTNiZWVjZTdiODQ1MiIsInN0b3JlIjoicmVkaXMiLCJhY3RpdmF0aW9uX2luZGV4IjoyLCJyZXN1bHQiOnsiYXBwZW5kZWQiOnsiZmlyc3Rfb2Zmc2V0IjoiMDAwMDAxYTIyMWUwNWUyMDAwMDAwMDAwMDAwMDAwMDAiLCJsYXN0X29mZnNldCI6IjAwMDAwMWEyMjFlMDVlMjAwMDAwMDAwMDAwMDAwMDAwIn19fV19" + } + ] + } + }, + "workflowTaskCompletedEventId": "4" + } + }, + { + "eventId": "9", + "eventTime": "2026-11-28T11:18:02.019230Z", + "eventType": "EVENT_TYPE_ACTIVITY_TASK_SCHEDULED", + "taskId": "1048603", + "activityTaskScheduledEventAttributes": { + "activityId": "2", + "activityType": { + "name": "stream_answer" + }, + "taskQueue": { + "name": "streams-redis-task-queue", + "kind": "TASK_QUEUE_KIND_NORMAL" + }, + "header": {}, + "input": { + "payloads": [ + { + "metadata": { + "encoding": "anNvbi9wcm90b2J1Zg==", + "messageType": "dGVtcG9yYWwuYXBpLnNkay52MS5TdHJlYW1SZWY=" + }, + "data": "eyJpZCI6IjJiZmFlODIyLTMzMzktNDcwYS05OTQzLTNiZWVjZTdiODQ1MiIsInN0b3JlIjoicmVkaXMifQ==" + } + ] + }, + "scheduleToCloseTimeout": "0s", + "scheduleToStartTimeout": "0s", + "startToCloseTimeout": "60s", + "heartbeatTimeout": "0s", + "workflowTaskCompletedEventId": "4", + "retryPolicy": { + "initialInterval": "1s", + "backoffCoefficient": 2.0, + "maximumInterval": "100s" + }, + "useWorkflowBuildId": true, + "priority": {} + } + }, + { + "eventId": "10", + "eventTime": "2026-11-28T11:18:02.125277Z", + "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_CANCEL_REQUESTED", + "taskId": "1048607", + "workflowExecutionCancelRequestedEventAttributes": { + "identity": "sample-worker" + } + }, + { + "eventId": "11", + "eventTime": "2026-11-28T11:18:02.125296Z", + "eventType": "EVENT_TYPE_WORKFLOW_TASK_SCHEDULED", + "taskId": "1048608", + "workflowTaskScheduledEventAttributes": { + "taskQueue": { + "name": "sample-worker-297933a497f84930bf9d91bc7cb1f863", + "kind": "TASK_QUEUE_KIND_STICKY", + "normalName": "streams-redis-task-queue" + }, + "startToCloseTimeout": "10s", + "attempt": 1 + } + }, + { + "eventId": "12", + "eventTime": "2026-11-28T11:18:02.126030Z", + "eventType": "EVENT_TYPE_WORKFLOW_TASK_STARTED", + "taskId": "1048612", + "workflowTaskStartedEventAttributes": { + "scheduledEventId": "11", + "identity": "sample-worker", + "requestId": "df57f94a-d66d-494f-8fe6-cba7bfc6dafc", + "historySizeBytes": "2268", + "workerVersion": { + "buildId": "5b94a49d2377cf8050182eb77fc9caa4" + } + } + }, + { + "eventId": "13", + "eventTime": "2026-11-28T11:18:02.130128Z", + "eventType": "EVENT_TYPE_WORKFLOW_TASK_COMPLETED", + "taskId": "1048616", + "workflowTaskCompletedEventAttributes": { + "scheduledEventId": "11", + "startedEventId": "12", + "identity": "sample-worker", + "workerVersion": { + "buildId": "5b94a49d2377cf8050182eb77fc9caa4" + }, + "sdkMetadata": {}, + "meteringMetadata": {} + } + }, + { + "eventId": "14", + "eventTime": "2026-11-28T11:18:02.130151Z", + "eventType": "EVENT_TYPE_ACTIVITY_TASK_CANCEL_REQUESTED", + "taskId": "1048617", + "activityTaskCancelRequestedEventAttributes": { + "scheduledEventId": "9", + "workflowTaskCompletedEventId": "13" + } + }, + { + "eventId": "15", + "eventTime": "2026-11-28T11:18:02.130187Z", + "eventType": "EVENT_TYPE_MARKER_RECORDED", + "taskId": "1048618", + "markerRecordedEventAttributes": { + "markerName": "core_stream_append", + "details": { + "data": { + "payloads": [ + { + "metadata": { + "encoding": "anNvbi9wbGFpbg==" + }, + "data": "eyJhcHBlbmRzIjpbeyJzZXEiOjIsInN0cmVhbV9pZCI6IjJiZmFlODIyLTMzMzktNDcwYS05OTQzLTNiZWVjZTdiODQ1MiIsInN0b3JlIjoicmVkaXMiLCJhY3RpdmF0aW9uX2luZGV4IjoyLCJyZXN1bHQiOnsiYXBwZW5kZWQiOnsiZmlyc3Rfb2Zmc2V0IjoiMDAwMDAxYTIyMWUwNWU5MDAwMDAwMDAwMDAwMDAwMDAiLCJsYXN0X29mZnNldCI6IjAwMDAwMWEyMjFlMDVlOTAwMDAwMDAwMDAwMDAwMDAwIn19fV19" + } + ] + } + }, + "workflowTaskCompletedEventId": "13" + } + }, + { + "eventId": "16", + "eventTime": "2026-11-28T11:18:02.130193Z", + "eventType": "EVENT_TYPE_WORKFLOW_EXECUTION_CANCELED", + "taskId": "1048619", + "workflowExecutionCanceledEventAttributes": { + "workflowTaskCompletedEventId": "13" + } + } + ] +} diff --git a/tests/streams_redis/conftest.py b/tests/streams_redis/conftest.py index b612db389..269a1f42b 100644 --- a/tests/streams_redis/conftest.py +++ b/tests/streams_redis/conftest.py @@ -1,5 +1,6 @@ """Skip collection until the unreleased Streams packages are installed.""" +import importlib.util import shutil import socket import subprocess @@ -8,13 +9,13 @@ from collections.abc import Iterator import pytest +import temporalio.client collect_ignore_glob: list[str] = [] -try: - import temporalio_streams_redis # noqa: F401 - from temporalio.client import StreamConfig # noqa: F401 -except ImportError: +if importlib.util.find_spec("temporalio_streams_redis") is None or not hasattr( + temporalio.client, "StreamConfig" +): collect_ignore_glob = ["*_test.py"] From abf17901aeffe6edb6dd005c20c9821d73052aa8 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Sat, 28 Nov 2026 15:56:47 -0700 Subject: [PATCH 8/8] Use the exclusive Stream cursor name --- streams_redis/run_agent.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/streams_redis/run_agent.py b/streams_redis/run_agent.py index 6a26944ac..a3a6aea3e 100644 --- a/streams_redis/run_agent.py +++ b/streams_redis/run_agent.py @@ -29,7 +29,7 @@ async def follow( ) -> tuple[list[AgentEvent], bytes | None]: """Stop at an application event because Streams have no close operation.""" events: list[AgentEvent] = [] - async for record in client.get_stream(stream_ref).read(from_offset=after): + async for record in client.get_stream(stream_ref).read(after_offset=after): print(f"{record.offset.hex()} {record.body.kind:<6} {record.body.text}") events.append(record.body) after = record.offset