diff --git a/README.md b/README.md index 5577a324..7b37efda 100644 --- a/README.md +++ b/README.md @@ -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. diff --git a/pyproject.toml b/pyproject.toml index 0d117d04..b02511a5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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 diff --git a/streams_redis/README.md b/streams_redis/README.md new file mode 100644 index 00000000..c5d4b0eb --- /dev/null +++ b/streams_redis/README.md @@ -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 +``` diff --git a/streams_redis/__init__.py b/streams_redis/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/streams_redis/activities/__init__.py b/streams_redis/activities/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/streams_redis/activities/model_activity.py b/streams_redis/activities/model_activity.py new file mode 100644 index 00000000..90fc67f5 --- /dev/null +++ b/streams_redis/activities/model_activity.py @@ -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 diff --git a/streams_redis/run_agent.py b/streams_redis/run_agent.py new file mode 100644 index 00000000..a3a6aea3 --- /dev/null +++ b/streams_redis/run_agent.py @@ -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)) diff --git a/streams_redis/run_worker.py b/streams_redis/run_worker.py new file mode 100644 index 00000000..607aa2c4 --- /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 00000000..581e5275 --- /dev/null +++ b/streams_redis/shared.py @@ -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])) diff --git a/streams_redis/workflows/__init__.py b/streams_redis/workflows/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/streams_redis/workflows/agent_workflow.py b/streams_redis/workflows/agent_workflow.py new file mode 100644 index 00000000..1ac69f1c --- /dev/null +++ b/streams_redis/workflows/agent_workflow.py @@ -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 diff --git a/tests/streams_redis/__init__.py b/tests/streams_redis/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/tests/streams_redis/agent_workflow_test.py b/tests/streams_redis/agent_workflow_test.py new file mode 100644 index 00000000..6589df7e --- /dev/null +++ b/tests/streams_redis/agent_workflow_test.py @@ -0,0 +1,193 @@ +import asyncio +import json +import uuid +from pathlib import Path + +import pytest +from temporalio import activity +from temporalio.client import ( + Client, + StreamConfig, + WorkflowFailureError, + WorkflowHandle, + WorkflowHistory, +) +from temporalio.exceptions import CancelledError, TerminatedError +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 +from streams_redis.activities.model_activity import ANSWER, stream_answer +from streams_redis.run_agent import QUESTION, run +from streams_redis.shared import LAST_EVENT, TASK_QUEUE, AgentEvent +from streams_redis.workflows.agent_workflow import AgentWorkflow + + +@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], + ): + async with asyncio.timeout(15): + events = await run(connect) + + assert events == [ + AgentEvent("status", f"Thinking about: {QUESTION}"), + *(AgentEvent("token", word) for word in ANSWER.split()), + AgentEvent("status", "Done"), + ] + + +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 = [] + 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) + + 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]): + 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 +): + 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/cancellation_history.json b/tests/streams_redis/cancellation_history.json new file mode 100644 index 00000000..a665f872 --- /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 new file mode 100644 index 00000000..269a1f42 --- /dev/null +++ b/tests/streams_redis/conftest.py @@ -0,0 +1,61 @@ +"""Skip collection until the unreleased Streams packages are installed.""" + +import importlib.util +import shutil +import socket +import subprocess +import tempfile +import time +from collections.abc import Iterator + +import pytest +import temporalio.client + +collect_ignore_glob: list[str] = [] + +if importlib.util.find_spec("temporalio_streams_redis") is None or not hasattr( + temporalio.client, "StreamConfig" +): + 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)