Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +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) - 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.
Expand Down
5 changes: 5 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -161,3 +161,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
68 changes: 68 additions & 0 deletions streams_redis/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
# Streams on Redis

> **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 resumes after its last consumed offset.

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.
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 until retention expires.
The [Workflow Streams sample](../workflow_streams) keeps events in the Workflow and needs no Store.

## Install

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
(cd ../sdk-streams && SDK_RUST_REF=moe/streams-crate-types scripts/patch-sdk-rust.sh)
uv pip install ../sdk-streams/python
```

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

Start Redis and Temporal in separate terminals.

```bash
redis-server --port 26379
```

```bash
temporal server start-dev
```

Start the Worker and client in separate terminals.

```bash
REDIS_URL=redis://localhost:26379 uv run --no-sync streams_redis/run_worker.py
```

```bash
REDIS_URL=redis://localhost:26379 uv run --no-sync streams_redis/run_agent.py
```

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

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
```
Empty file added streams_redis/__init__.py
Empty file.
Empty file.
24 changes: 24 additions & 0 deletions streams_redis/activities/model_activity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
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:
"""Use fixed tokens so the sample needs no model service."""
stream = activity.client().get_stream(stream_ref)
# 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
92 changes: 92 additions & 0 deletions streams_redis/run_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
"""Resume Stream reads after a client disconnect."""

from __future__ import annotations

import asyncio
import uuid
from collections.abc import Awaitable, Callable

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
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]:
"""Stop at an application event because Streams have no close operation."""
events: list[AgentEvent] = []
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
if record.body == LAST_EVENT or len(events) == stop_after:
break
return events, after


async def read_and_resume(
client: Client,
ref_update: WorkflowUpdateHandle[StreamRef[AgentEvent]],
connect: Callable[[], Awaitable[Client]],
) -> list[AgentEvent]:
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.")
await asyncio.sleep(1)

# The last consumed offset prevents gaps and repeats after reconnect.
rest, _ = await follow(await connect(), stream_ref, after=offset)
first.extend(rest)
return first


async def run(connect: Callable[[], Awaitable[Client]]) -> list[AgentEvent]:
client = await connect()
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, ref_update, 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))
25 changes: 25 additions & 0 deletions streams_redis/run_worker.py
Original file line number Diff line number Diff line change
@@ -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())
27 changes: 27 additions & 0 deletions streams_redis/shared.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
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


LAST_EVENT = AgentEvent("status", "Done")


async def connect() -> Client:
"""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"))
return await Client.connect(**config, stream_config=StreamConfig(stores=[store]))
Empty file.
52 changes: 52 additions & 0 deletions streams_redis/workflows/agent_workflow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from __future__ import annotations

import asyncio
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 LAST_EVENT, 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}"))
# 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.
await stream.append(LAST_EVENT)
raise
await stream.append(LAST_EVENT)
return result
Empty file.
Loading
Loading