From bfe90fb8e320481def125d71f77c25fd80787f41 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 1 Dec 2026 10:13:05 -0700 Subject: [PATCH 1/4] Use UTC for the default times of ActivityEnvironment `datetime.fromtimestamp(0)` reads the local time zone, so on a host west of UTC the default times of `ActivityEnvironment` fall before 1970. SDK Core and the client both refuse a Stream append whose Producer has an attempt time before 1970. --- temporalio/testing/_activity.py | 2 +- tests/testing/test_activity.py | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/temporalio/testing/_activity.py b/temporalio/testing/_activity.py index 6f0a9ab5d5..63fb08c588 100644 --- a/temporalio/testing/_activity.py +++ b/temporalio/testing/_activity.py @@ -67,7 +67,7 @@ def default_info() -> temporalio.activity.Info: Returns a new default Info instance that can be modified using :py:func:`dataclasses.replace` before assigning to the info attribute. """ - utc_zero = datetime.fromtimestamp(0).replace(tzinfo=timezone.utc) + utc_zero = datetime.fromtimestamp(0, tz=timezone.utc) return temporalio.activity.Info( activity_id="test", activity_type="unknown", diff --git a/tests/testing/test_activity.py b/tests/testing/test_activity.py index 71ba7f5907..d7941d05a0 100644 --- a/tests/testing/test_activity.py +++ b/tests/testing/test_activity.py @@ -2,6 +2,7 @@ import threading import time from contextvars import copy_context +from datetime import datetime, timezone from unittest.mock import Mock import pytest @@ -38,6 +39,10 @@ async def via_create_task(): return "done" env = ActivityEnvironment() + epoch = datetime(1970, 1, 1, tzinfo=timezone.utc) + assert env.info.scheduled_time == epoch + assert env.info.current_attempt_scheduled_time == epoch + assert env.info.started_time == epoch # Set heartbeat handler to add to list heartbeats = [] env.on_heartbeat = lambda *args: heartbeats.append(args[0]) From 92c87f5440ec9180db7e1161669fe3228afacdf1 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 1 Dec 2026 10:13:05 -0700 Subject: [PATCH 2/4] Add the StreamStore contract, StreamConfig and StreamError A Store is the service that keeps the Records of a Stream. The contract says what client, Activity and Workflow calls need from a Store, and `StreamConfig` registers the Stores of a client and its Workers. --- temporalio/client/__init__.py | 8 + temporalio/client/_stream_store.py | 265 +++++++++++++++++++++++++++++ temporalio/exceptions.py | 44 +++++ 3 files changed, 317 insertions(+) create mode 100644 temporalio/client/_stream_store.py diff --git a/temporalio/client/__init__.py b/temporalio/client/__init__.py index 2eef41a39d..75e32e5e2c 100644 --- a/temporalio/client/__init__.py +++ b/temporalio/client/__init__.py @@ -185,6 +185,11 @@ ScheduleUpdate, ScheduleUpdateInput, ) +from ._stream_store import ( + StreamConfig, + StreamSelectContext, + StreamStore, +) from ._worker_versioning import ( BuildIdOp, BuildIdOpAddNewCompatible, @@ -350,6 +355,9 @@ "TaskReachabilityType", "CloudOperationsClient", "Plugin", + "StreamConfig", + "StreamSelectContext", + "StreamStore", "Callback", "_ClientImpl", "_apply_headers", diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py new file mode 100644 index 0000000000..ddba2554f8 --- /dev/null +++ b/temporalio/client/_stream_store.py @@ -0,0 +1,265 @@ +"""Stream Stores and the Stream config of a client.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Callable, Sequence +from dataclasses import dataclass, field + +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) + + +class StreamStore(ABC): + """Base class for a Store that keeps Stream Records. + + Methods use request and response messages from + :py:mod:`temporalio.api.streamservice.v1`. Requests contain a Stream id. + The SDK routes each ``StreamRef`` to its registered Store and sets the Store + name on refs returned by create. Stores don't read or set ``StreamRef.store``. + + Workflow execution and replay depend on these contracts. + + Retention: + + * Retention starts at create and restarts after an append that writes a batch. + Retries and reads don't extend it. The Store sets the retention period. + * An expired Stream has no Records and rejects calls with ``EXPIRED``. + * Streams have no stored end. Applications use their own terminal Record. + + Records and offsets: + + * Keep each body as received. The payload codec has already encoded it. + * Write each append batch atomically, with contiguous Records in request order. + * Record offsets are nonempty and sort bytewise in Record order. + * After a response returns an offset, no later write can insert a Record at + or below it. This also applies to concurrent writes. + * Keep Records unchanged until the Stream expires. + + Producers and attempts: + + * A Producer identifies a Workflow run, Activity, Local Activity or client. + Its kind and ids determine its identity. + * An attempt identifies a Producer's execution attempt, such as a Workflow + Task or Activity attempt. Every Record retains its Producer and attempt. + * Fencing is optional. A Store that fences rejects an earlier attempt once + a later attempt of that Producer has written to the Stream. + + Reject calls with :py:class:`temporalio.exceptions.StreamError` and its reason. + These docs omit the ``STREAM_ERROR_REASON_`` prefix from reason names. + Other exceptions become ``STORE_UNAVAILABLE`` errors. Workflow append and + read refusals record messages of at most 4 KiB in History. All Stream marker + data in an activation must fit within 1 MiB. Keep messages short to avoid + failing the Workflow Task with ``StreamMarkerTooLarge``. + + Calls can run concurrently on the event loop. Cancellation can follow a + timeout, eviction or Worker shutdown. A cancelled call may have taken effect. + The Store must remain usable, and overlapping retries must not duplicate a + batch. + + SDK Core validates and retries Workflow appends and reads during outages. + Other calls make one attempt. For those calls, the SDK checks each request + with the rules of SDK Core and the append limits from :py:class:`StreamConfig`, + but it doesn't check the answer. Stores must perform any other checks they + require. + + .. warning:: + This API is experimental and subject to change. + """ + + @abstractmethod + def name(self) -> str: + """Return the Store name registered in :py:class:`StreamConfig`. + + The name must remain stable. Separate instances of one Store class can + use different names. + """ + raise NotImplementedError + + @abstractmethod + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + """Create a Stream, or reuse it if the conflict policy permits. + + Retries use the same ``request_id``. An empty id never identifies a retry. + The response contains only ``created``. + + For an existing Stream, check these conditions in order. + + 1. An expired Stream fails with ``EXPIRED``. + 2. A matching create ``request_id`` returns ``created=True``. + 3. ``USE_EXISTING`` returns ``created=False``. ``FAIL`` or an unset policy + fails with ``ALREADY_EXISTS``. + + Only a new Stream starts retention. Reusing a Stream doesn't extend it. + """ + raise NotImplementedError + + @abstractmethod + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + """Append one batch from one Producer. + + Retries of one append use the same ``request_id``. + Retain recent request ids for each Producer, including at least its last + batch. Matching Producer, attempt and ``request_id`` identify a resend. + An empty request id never identifies a resend. + + Check these conditions in order. + + 1. Missing or expired Streams fail with ``NOT_FOUND`` or ``EXPIRED``. + 2. A resend returns the original offsets without comparing or writing + Records. + 3. If fencing is enabled, an attempt older than the latest writer attempt + fails with ``FENCED``. + + Return the first and last Record offsets. Only a new batch extends + retention. A resend doesn't extend it. + """ + raise NotImplementedError + + @abstractmethod + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """Read one page after ``after_offset``, in Stream order. + + * Apply ``max_records`` and ``max_bytes``. Zero uses the Store's default. + Include the first Record even if it exceeds ``max_bytes``. + * The next read starts after the last returned Record. An empty page + leaves ``after_offset`` unchanged. + * If no Records are available, wait until one arrives or ``wait`` expires. + An unset wait returns immediately. The SDK converts zero to an unset + wait. Returning empty pages before a requested wait expires can cause + callers to poll repeatedly. + * Accept any offset returned by a response. Reject ``after_offset`` with + ``OFFSET_TOO_HIGH`` only if it exceeds the end of the Stream. + """ + raise NotImplementedError + + @abstractmethod + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """Return the newest Record's offset, or empty bytes for an empty Stream.""" + raise NotImplementedError + + +@dataclass(frozen=True) +class StreamSelectContext: + """Context passed to :py:attr:`StreamConfig.store_selector` calls. + + .. warning:: + This API is experimental and subject to change. + """ + + id: str + """The id of the Stream of the call.""" + + namespace: str | None = None + """The namespace of the client or Worker that makes the call.""" + + +@dataclass(frozen=True) +class StreamConfig: + """Stream Stores shared by a client and its Workers. + + Appends that exceed :py:attr:`max_record_bytes`, :py:attr:`max_batch_bytes` + or :py:attr:`max_batch_records` fail with ``STREAM_ERROR_REASON_TOO_LARGE`` + before reaching the Store. ``rpc_metadata`` has no effect on Store calls. + + Streams have no close. Retention starts at create and restarts after each + append that writes a batch. Applications use their own terminal Record. + + In client, Activity and Workflow code, ``read`` and ``read_pages`` continue + after empty pages. ``read_pages`` yields those pages. Callers must stop the + iterator, for example with ``break`` or a timeout. An unset ``wait`` makes the + first request immediate. Later requests wait up to one minute. An explicit + wait applies to every request. Zero disables waiting, so an idle Stream can + cause repeated empty reads. ``read_page`` has no default wait. After a page, + the ``read`` iterator's ``next_request`` includes the next request's wait. + + A positive ``rpc_timeout`` caps client and Activity waits below the timeout, + leaving time for the Store to answer. An Activity that heartbeats between + Records needs a wait below its heartbeat timeout, or a separate heartbeat task. + + .. warning:: + This API is experimental and subject to change. + """ + + stores: Sequence[StreamStore] + """Stores available for Stream calls. At least one Store must be provided, + and each Store must have a unique :py:meth:`StreamStore.name` that isn't + empty. + """ + + store_selector: Callable[[StreamSelectContext], StreamStore] | None = None + """Select the Store for a call whose ``StreamRef`` has no Store name. + + Return an instance from :py:attr:`stores`. A selector is required with + multiple Stores. Without one, the sole Store handles these calls. + """ + + max_record_bytes: int = 1536 * 1024 + """Maximum stored Record size for an append or a live Workflow read. + + Includes its Producer. Defaults to 1.5 MiB and must be at least one. + """ + + max_batch_bytes: int = 4 * 1024 * 1024 + """Maximum size in bytes of the Records of one append, each in its stored + size. Defaults to 4 MiB. Must be greater than or equal to one. + """ + + max_batch_records: int = 1000 + """Maximum number of Records of one append. Defaults to 1000. Must be + greater than or equal to one. + """ + + _by_name: dict[str, StreamStore] = field( + init=False, repr=False, compare=False, default_factory=dict + ) + """Snapshot Store names so later name changes can't change routing.""" + + def __post_init__(self) -> None: + """Validate the Stores and the limits. + + Raises :exc:`ValueError` if no Store is provided, if a limit is less + than one, if more than one Store is registered without a + :py:attr:`store_selector`, if a Store has an empty name, or if any two + Stores have the same name. + """ + if not self.stores: + raise ValueError("StreamConfig.stores must contain at least one Store.") + for limit in ("max_record_bytes", "max_batch_bytes", "max_batch_records"): + if getattr(self, limit) < 1: + raise ValueError( + f"StreamConfig.{limit} must be greater than or equal to one." + ) + if len(self.stores) > 1 and self.store_selector is None: + raise ValueError( + "StreamConfig.store_selector must be specified if multiple Stores " + "are registered." + ) + by_name: dict[str, StreamStore] = {} + for store in self.stores: + name = store.name() + if not name: + raise ValueError( + "StreamConfig.stores contains a Store with an empty name." + ) + if name in by_name: + raise ValueError( + f"StreamConfig.stores contains multiple Stores with name '{name}'. " + "Each Store must have a unique name." + ) + by_name[name] = store + object.__setattr__(self, "_by_name", by_name) diff --git a/temporalio/exceptions.py b/temporalio/exceptions.py index 03a623c21e..5bec57528c 100644 --- a/temporalio/exceptions.py +++ b/temporalio/exceptions.py @@ -1,6 +1,7 @@ """Common Temporal exceptions.""" import asyncio +import functools from collections.abc import Sequence from datetime import timedelta from enum import IntEnum @@ -8,6 +9,7 @@ import temporalio.api.enums.v1 import temporalio.api.failure.v1 +import temporalio.api.stream.v1 class TemporalError(Exception): @@ -474,6 +476,48 @@ def operation_token(self) -> str: return self._operation_token +class StreamError(ApplicationError): + """Error raised when a Stream call fails. + + Client, Activity and Workflow code all get this class for a failed Stream + call, with no other error around it, and :py:attr:`reason` says why the call + failed. A call that fails with ``STREAM_ERROR_REASON_STORE_UNAVAILABLE`` may + succeed on another try, so it's the only reason that isn't ``non_retryable``. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + message: str, + *, + reason: temporalio.api.enums.v1.StreamErrorReason.ValueType, + ) -> None: + """Initialize a Stream error.""" + reasons = temporalio.api.enums.v1.StreamErrorReason + super().__init__( + message, + temporalio.api.stream.v1.StreamErrorDetails(reason=reason), + # The form of the type in a failure that Core builds + type="stream_" + + reasons.Name(reason).removeprefix("STREAM_ERROR_REASON_").lower(), + non_retryable=reason != reasons.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) + self._reason = reason + + @property + def reason(self) -> temporalio.api.enums.v1.StreamErrorReason.ValueType: + """Why the Stream call failed.""" + return self._reason + + def __reduce__(self) -> Any: + """Return the parts that ``copy`` and ``pickle`` build the error from.""" + # The default calls the class with `args` alone, which has no reason. + _, *rest = tuple(super().__reduce__()) + return functools.partial(type(self), reason=self._reason), *rest + + def is_cancelled_exception(exception: BaseException) -> bool: """Check whether the given exception is considered a cancellation exception according to Temporal. From bdf94308a360665c3a249e497844240a84e4e7d9 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 1 Dec 2026 10:13:05 -0700 Subject: [PATCH 3/4] Add MemoryStreamStore Tests and local runs need a Store with no other service. The memory Store keeps its Streams in plain Python data and applies the rules of `StreamStore` in their order, so it also shows what a Store does. --- temporalio/testing/__init__.py | 2 + temporalio/testing/_stream_store.py | 294 ++++++++++++++++++++ tests/helpers/streams.py | 62 +++++ tests/testing/test_stream_store.py | 403 ++++++++++++++++++++++++++++ 4 files changed, 761 insertions(+) create mode 100644 temporalio/testing/_stream_store.py create mode 100644 tests/helpers/streams.py create mode 100644 tests/testing/test_stream_store.py diff --git a/temporalio/testing/__init__.py b/temporalio/testing/__init__.py index 0cd652d86b..5574a0a39b 100644 --- a/temporalio/testing/__init__.py +++ b/temporalio/testing/__init__.py @@ -1,11 +1,13 @@ """Test framework for workflows and activities.""" from ._activity import ActivityEnvironment +from ._stream_store import MemoryStreamStore from ._timeskipping import TimeSkipper, TimeSkippingConfig from ._workflow import WorkflowEnvironment __all__ = [ "ActivityEnvironment", + "MemoryStreamStore", "TimeSkipper", "WorkflowEnvironment", "TimeSkippingConfig", diff --git a/temporalio/testing/_stream_store.py b/temporalio/testing/_stream_store.py new file mode 100644 index 0000000000..d82619e013 --- /dev/null +++ b/temporalio/testing/_stream_store.py @@ -0,0 +1,294 @@ +"""Stream Store that keeps its Streams in memory.""" + +from __future__ import annotations + +import asyncio +import bisect +import collections +from dataclasses import dataclass, field +from datetime import timedelta + +import google.protobuf.message + +from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.stream.v1 import ( + ActivityAttempt, + LocalActivityAttempt, + Producer, + StreamRecord, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.client._stream_store import StreamStore +from temporalio.exceptions import StreamError + +_Attempt = tuple[int, ...] + + +@dataclass +class _Batch: + attempt: _Attempt + request_id: str + response: AppendRecordsResponse + + +@dataclass +class _Writer: + """What a Stream keeps of one of its Producers.""" + + window: collections.deque[_Batch] + """The last batches that the Producer wrote, oldest first.""" + + newest: _Attempt = () + """The latest attempt of the Producer that wrote.""" + + +@dataclass +class _Stream: + request_id: str + """The request id of the create that made the Stream.""" + + expires_at: float + """The time of the event loop at which the Stream expires.""" + + records: list[StreamRecord] = field(default_factory=list) + writers: dict[bytes, _Writer] = field(default_factory=dict) + changed: asyncio.Event = field(default_factory=asyncio.Event) + """Set at the next append that writes, which then puts a new event here.""" + + @property + def last_offset(self) -> bytes: + return self.records[-1].offset if self.records else b"" + + +class MemoryStreamStore(StreamStore): + """Stream Store that keeps its Streams in the memory of this process. + + It's for tests and local runs, and it shows what a Store does. A client and a + Worker see the same Streams only through the same instance, in one event loop. + + The Store has no limit of a batch, since the limits are those of the + :py:class:`temporalio.client.StreamConfig` of the caller. A read with no + ``max_records`` or no ``max_bytes`` has no limit of that kind. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + *, + name: str = "memory", + retention: timedelta | None = None, + resend_window: int | None = None, + fence: bool = False, + ) -> None: + """Create a memory Store. + + Args: + name: The name of the Store in a + :py:class:`temporalio.client.StreamConfig`. + retention: How long after its create, or after its last append that + wrote a batch, a Stream expires. Defaults to 7 days. A resend and + a create of a Stream that exists don't start it again. + resend_window: The number of recent batches of each Producer of a + Stream whose request ids the Store remembers, so that it writes + a resend of one of them only once. Defaults to 16, and must be + at least 1, since a Store remembers the last batch of a Producer. + fence: Whether the Store fences. If true, an append of an attempt + fails with ``STREAM_ERROR_REASON_FENCED`` once a later attempt of + its Producer has written to the Stream. + """ + if resend_window is not None and resend_window < 1: + raise ValueError("resend_window must be greater than zero.") + self._name = name + self._retention = timedelta(days=7) if retention is None else retention + self._resend_window = 16 if resend_window is None else resend_window + self._fence = fence + self._streams: dict[str, _Stream] = {} + + def name(self) -> str: + """See base class.""" + return self._name + + async def create_stream( + self, request: CreateStreamRequest, *, request_id: str + ) -> CreateStreamResponse: + """See base class.""" + stream_id = request.stream_id + if stream_id not in self._streams: + self._streams[stream_id] = _Stream(request_id, self._expiry()) + return CreateStreamResponse(created=True) + stream = self._stream(stream_id) + # An empty request id identifies no create, so it never matches. + if request_id and request_id == stream.request_id: + return CreateStreamResponse(created=True) + use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + if request.id_conflict_policy == use_existing: + return CreateStreamResponse(created=False) + raise StreamError( + f"The Stream '{stream_id}' already exists", + reason=StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, + ) + + async def append_records( + self, request: AppendRecordsRequest, *, request_id: str + ) -> AppendRecordsResponse: + """See base class.""" + stream = self._stream(request.stream_id) + key, attempt = _producer_key(request.producer), _attempt(request.producer) + writer = stream.writers.get(key) + if writer is None: + writer = _Writer(collections.deque(maxlen=self._resend_window)) + if request_id: + for batch in writer.window: + if (batch.attempt, batch.request_id) == (attempt, request_id): + return batch.response + if self._fence and attempt < writer.newest: + raise _fenced(request.stream_id) + first = len(stream.records) + 1 + stream.records.extend( + StreamRecord( + producer=request.producer, + body=record.body, + offset=(first + at).to_bytes(8, "big"), + ) + for at, record in enumerate(request.records) + ) + response = AppendRecordsResponse( + first_offset=first.to_bytes(8, "big"), last_offset=stream.last_offset + ) + writer.newest = attempt + writer.window.append(_Batch(attempt, request_id, response)) + stream.writers[key] = writer + stream.expires_at = self._expiry() + self._notify(stream) + return response + + async def read_records(self, request: ReadRecordsRequest) -> ReadRecordsResponse: + """See base class.""" + stream = self._stream(request.stream_id) + if request.after_offset > stream.last_offset: + raise StreamError( + f"The after_offset of the read is past the newest offset of the " + f"Stream '{request.stream_id}'", + reason=StreamErrorReason.STREAM_ERROR_REASON_OFFSET_TOO_HIGH, + ) + start = bisect.bisect_right( + stream.records, request.after_offset, key=lambda record: record.offset + ) + wait = request.wait.ToTimedelta().total_seconds() + until = self._now() + wait + while start == len(stream.records) and self._now() < until: + try: + async with asyncio.timeout_at(min(until, stream.expires_at)): + await stream.changed.wait() + except TimeoutError: + pass + self._stream(request.stream_id) + page: list[StreamRecord] = [] + page_bytes = 0 + for record in stream.records[start:]: + if request.max_records and len(page) == request.max_records: + break + page_bytes += record.ByteSize() + # The first Record is always in the page, so a read makes progress. + if request.max_bytes and page and page_bytes > request.max_bytes: + break + page.append(record) + return ReadRecordsResponse(records=page) + + async def describe_stream( + self, request: DescribeStreamRequest + ) -> DescribeStreamResponse: + """See base class.""" + stream = self._stream(request.stream_id) + return DescribeStreamResponse(last_offset=stream.last_offset) + + def _stream(self, stream_id: str) -> _Stream: + stream = self._streams.get(stream_id) + if stream is None: + raise StreamError( + f"The Stream '{stream_id}' doesn't exist", + reason=StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND, + ) + if self._now() >= stream.expires_at: + raise StreamError( + f"The Stream '{stream_id}' expired", + reason=StreamErrorReason.STREAM_ERROR_REASON_EXPIRED, + ) + return stream + + def _now(self) -> float: + return asyncio.get_running_loop().time() + + def _expiry(self) -> float: + return self._now() + self._retention.total_seconds() + + def _notify(self, stream: _Stream) -> None: + stream.changed.set() + stream.changed = asyncio.Event() + + +def _fenced(stream_id: str) -> StreamError: + return StreamError( + f"A later attempt of the Producer has written to the Stream '{stream_id}'", + reason=StreamErrorReason.STREAM_ERROR_REASON_FENCED, + ) + + +def _kind(producer: Producer) -> google.protobuf.message.Message: + name = producer.WhichOneof("kind") + assert name, "The SDK refuses a Producer with no kind before a Store gets it" + return getattr(producer, name) + + +def _producer_key(producer: Producer) -> bytes: + """Return what identifies a Producer, which is its kind with the ids of that + kind and without its attempt. + """ + key = Producer() + key.CopyFrom(producer) + kind = _kind(key) + if "attempt" in kind.DESCRIPTOR.fields_by_name: + kind.ClearField("attempt") + return key.SerializeToString(deterministic=True) + + +def _attempt(producer: Producer) -> _Attempt: + """Return a value that orders the attempts of one Producer, as the attempt key + of SDK Core does. + + Two attempts compare by the Workflow Task first (its started event id, its + attempt number, its started time), and then by the Activity attempt (its + scheduled time, its attempt number). A field that the kind of the Producer + doesn't have, or that is negative, is zero. So every write of a client has + the same attempt. + """ + attempt = getattr(_kind(producer), "attempt", None) + task, scheduled, number = WorkflowTaskAttempt(), ActivityAttempt(), 0 + if isinstance(attempt, WorkflowTaskAttempt): + task = attempt + elif isinstance(attempt, LocalActivityAttempt): + task, number = attempt.task, attempt.attempt + elif isinstance(attempt, ActivityAttempt): + scheduled, number = attempt, attempt.attempt + fields = ( + task.started_event_id, + task.attempt, + task.started_time.seconds, + task.started_time.nanos, + scheduled.attempt_scheduled_time.seconds, + scheduled.attempt_scheduled_time.nanos, + number, + ) + return tuple(max(0, value) for value in fields) diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py new file mode 100644 index 0000000000..10e43a2b66 --- /dev/null +++ b/tests/helpers/streams.py @@ -0,0 +1,62 @@ +"""Helpers for the tests of Streams.""" + +import asyncio +import selectors +from collections.abc import Coroutine, Iterator +from contextlib import contextmanager +from typing import Any, TypeVar + +_T = TypeVar("_T") + + +@contextmanager +def failure_note(note: str) -> Iterator[None]: + """Add ``note`` to a failure in the block, such as the seed of a generated case.""" + try: + yield + except BaseException as err: + err.add_note(note) + raise + + +class _JumpingSelector(selectors.DefaultSelector): + """Selector that moves the clock of its loop past a wait and doesn't wait.""" + + def __init__(self, loop: "VirtualClockLoop") -> None: + super().__init__() + self._loop = loop + + def select( + self, timeout: float | None = None + ) -> list[tuple[selectors.SelectorKey, int]]: + # With no timer, only another thread can wake the loop, so this waits for it. + if timeout is None: + return super().select(None) + events = super().select(0) + if not events: + self._loop.now += max(timeout, 0) + return events + + +class VirtualClockLoop(asyncio.SelectorEventLoop): + """Event loop whose clock jumps to its next timer when no task can run. + + A test on it must not wait for another thread while a timer is pending, since + the clock then jumps past the wait. + """ + + def __init__(self) -> None: + self.now = 0.0 + super().__init__(_JumpingSelector(self)) + # asyncio runs a timer that is due within the resolution of the real clock, which is + # about 16 ms on Windows. This clock is exact, so its timers run when they are due. + self._clock_resolution = 1e-9 + + def time(self) -> float: + return self.now + + +def run_with_virtual_clock(main: Coroutine[Any, Any, _T]) -> _T: + """Run ``main`` on a new :py:class:`VirtualClockLoop` and return its result.""" + with asyncio.Runner(loop_factory=VirtualClockLoop) as runner: + return runner.run(main) diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py new file mode 100644 index 0000000000..9e827ddf3d --- /dev/null +++ b/tests/testing/test_stream_store.py @@ -0,0 +1,403 @@ +"""Tests of the memory Stream Store.""" + +import asyncio +import random +from collections.abc import Awaitable +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any + +import pytest +from google.protobuf.duration_pb2 import Duration +from google.protobuf.message import Message +from google.protobuf.timestamp_pb2 import Timestamp + +from temporalio.api.common.v1 import Payload +from temporalio.api.enums.v1 import ( + StreamErrorReason, + StreamIdConflictPolicy, +) +from temporalio.api.stream.v1 import ( + ActivityAttempt, + AppendRecord, + LocalActivityAttempt, + Producer, + StreamRecord, + WorkflowTaskAttempt, +) +from temporalio.api.streamservice.v1 import ( + AppendRecordsRequest, + AppendRecordsResponse, + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + DescribeStreamResponse, + ReadRecordsRequest, + ReadRecordsResponse, +) +from temporalio.exceptions import StreamError +from temporalio.testing import MemoryStreamStore +from tests.helpers.streams import failure_note, run_with_virtual_clock + +_NOT_FOUND = StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND +_EXPIRED = StreamErrorReason.STREAM_ERROR_REASON_EXPIRED +_FENCED = StreamErrorReason.STREAM_ERROR_REASON_FENCED + +# Attempts of each attempt message, earliest first. Where a later attempt wins by one field, +# its fields after that one are lower, so a comparison in another order of the fields differs. +_TASKS = [ + WorkflowTaskAttempt(started_event_id=3, attempt=2), + WorkflowTaskAttempt( + started_event_id=3, attempt=2, started_time=Timestamp(seconds=9) + ), + WorkflowTaskAttempt( + started_event_id=3, attempt=3, started_time=Timestamp(seconds=1) + ), + WorkflowTaskAttempt(started_event_id=5, attempt=1), +] +_ATTEMPTS: dict[type[Message], list[Any]] = { + WorkflowTaskAttempt: _TASKS, + LocalActivityAttempt: [ + LocalActivityAttempt(task=_TASKS[0], attempt=2), + LocalActivityAttempt(task=_TASKS[0], attempt=3), + LocalActivityAttempt(task=_TASKS[1], attempt=1), + LocalActivityAttempt(task=_TASKS[3], attempt=1), + ], + ActivityAttempt: [ + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=7), attempt=2 + ), + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=7), attempt=3 + ), + ActivityAttempt( + attempt_scheduled_time=Timestamp(seconds=4, nanos=8), attempt=1 + ), + ActivityAttempt(attempt_scheduled_time=Timestamp(seconds=5), attempt=1), + ], +} + + +@dataclass(frozen=True) +class _Writer: + """A generated Producer, with what a Store tells Producers and attempts apart by.""" + + producer: Producer + ids: tuple[str | int, ...] + """The kind and each id of the Producer.""" + rank: int + """The place of the attempt among the attempts of the Producer.""" + + +def _writer(rng: random.Random, same: _Writer | None = None) -> _Writer: + """Return a new Producer, or the Producer of ``same``, with an attempt.""" + producer = Producer() + if same: + producer.CopyFrom(same.producer) + name = ( + str(same.ids[0]) + if same + else rng.choice(list(Producer.DESCRIPTOR.fields_by_name)) + ) + kind = getattr(producer, name) + kind.SetInParent() + ids: list[str | int] = [name] + for id_field in kind.DESCRIPTOR.fields: + # A number id, such as the scheduled event id of an Activity, can be zero. + values = {id_field.TYPE_STRING: "aab", id_field.TYPE_INT64: [0, 0, 5]} + if id_field.type in values: + if not same: + setattr(kind, id_field.name, rng.choice(values[id_field.type])) + ids.append(getattr(kind, id_field.name)) + rank = 0 + if attempt := kind.DESCRIPTOR.fields_by_name.get("attempt"): + attempts = _ATTEMPTS[type(getattr(kind, attempt.name))] + rank = rng.randrange(len(attempts)) + getattr(kind, attempt.name).CopyFrom(attempts[rank]) + return _Writer(producer, tuple(ids), rank) + + +@dataclass +class _ModelBatch: + writer: _Writer + request_id: str + response: AppendRecordsResponse + + +@dataclass +class _ModelStream: + request_id: str + records: list[StreamRecord] = field(default_factory=list) + batches: list[_ModelBatch] = field(default_factory=list) + + def fenced(self, writer: _Writer) -> bool: + return any( + batch.writer.ids == writer.ids and batch.writer.rank > writer.rank + for batch in self.batches + ) + + +@dataclass +class _Model: + """What a Store with the rules of ``StreamStore`` answers, from all that it wrote.""" + + resend_window: int + fence: bool + streams: dict[str, _ModelStream] = field(default_factory=dict) + + def create(self, request: CreateStreamRequest, request_id: str) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + self.streams[request.stream_id] = _ModelStream(request_id) + return CreateStreamResponse(created=True) + if request_id and request_id == stream.request_id: + return CreateStreamResponse(created=True) + use_existing = StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + if request.id_conflict_policy == use_existing: + return CreateStreamResponse() + return StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS + + def append( + self, request: AppendRecordsRequest, writer: _Writer, request_id: str + ) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + return _NOT_FOUND + own = [batch for batch in stream.batches if batch.writer.ids == writer.ids] + for batch in own[len(own) - min(len(own), self.resend_window) :]: + if request_id and (batch.writer.rank, batch.request_id) == ( + writer.rank, + request_id, + ): + return batch.response + if self.fence and stream.fenced(writer): + return _FENCED + response = AppendRecordsResponse() + for record in request.records: + offset = (len(stream.records) + 1).to_bytes(8, "big") + response.first_offset = response.first_offset or offset + response.last_offset = offset + stream.records.append( + StreamRecord(producer=request.producer, body=record.body, offset=offset) + ) + stream.batches.append(_ModelBatch(writer, request_id, response)) + return response + + def read(self, request: ReadRecordsRequest) -> Any: + stream = self.streams.get(request.stream_id) + if stream is None: + return _NOT_FOUND + start = int.from_bytes(request.after_offset, "big") + if start > len(stream.records): + return StreamErrorReason.STREAM_ERROR_REASON_OFFSET_TOO_HIGH + records = stream.records[start:][: request.max_records or None] + return ReadRecordsResponse(records=records) + + +_OPERATIONS = ["create", "append", "again", "read"] +_WEIGHTS = [3, 10, 6, 4] + + +async def _answer(call: Awaitable[Message]) -> Any: + """Return the response of a Store call, or the reason of its refusal.""" + try: + return await call + except StreamError as err: + return err.reason + + +async def test_workflow_attempt_fencing_is_scoped_to_each_task() -> None: + store = MemoryStreamStore(fence=True) + await store.create_stream(CreateStreamRequest(stream_id="s"), request_id="") + + async def append(task_id: int, started: int, attempt: int) -> AppendRecordsResponse: + request = AppendRecordsRequest( + stream_id="s", records=[AppendRecord(body=Payload())] + ) + producer = request.producer.workflow + producer.namespace, producer.workflow_id, producer.run_id = "ns", "wf", "run" + producer.workflow_task_id = task_id + producer.attempt.started_event_id = started + producer.attempt.attempt = attempt + return await store.append_records(request, request_id="") + + await append(0, 11, 2) + await append(11, 19, 1) + # A delayed write from the first task still competes only with its own attempts. + await append(0, 11, 2) + assert await _answer(append(0, 3, 1)) == _FENCED + + +async def test_the_memory_store_keeps_the_rules_of_the_redis_store() -> None: + for seed in range(150): + with failure_note(f"seed {seed}"): + await _store_script(random.Random(seed)) + + +async def _store_script(rng: random.Random) -> None: + model = _Model(resend_window=rng.randrange(1, 4), fence=rng.random() < 0.5) + store = MemoryStreamStore(resend_window=model.resend_window, fence=model.fence) + appends: list[tuple[AppendRecordsRequest, _Writer, str]] = [] + writers: list[_Writer] = [] + for step in range(50): + stream_id = rng.choice("xy") + # Most writes come from another attempt of a Producer that the script already has. + writer = _writer( + rng, rng.choice(writers) if rng.random() < 0.7 * bool(writers) else None + ) + writers.append(writer) + request: Message + match rng.choices(_OPERATIONS, _WEIGHTS)[0]: + case "create": + request = CreateStreamRequest( + stream_id=stream_id, + id_conflict_policy=rng.choice( + list(StreamIdConflictPolicy.values()) + ), + ) + request_id = rng.choice(["", "r1", "r2"]) + expected = model.create(request, request_id) + answer = await _answer( + store.create_stream(request, request_id=request_id) + ) + case "append" | "again" as op: + request = AppendRecordsRequest( + stream_id=stream_id, producer=writer.producer + ) + request_id = rng.choice(["", "r1", "r2", "r3"]) + if op == "again" and appends: + # A late or a repeated try has the Producer, the attempt and the + # request id of an earlier append, and it may have other Records. + earlier, writer, request_id = rng.choice(appends) + request.CopyFrom(earlier) + del request.records[:] + # The SDK refuses a batch with no Record before a Store gets it. + for _ in range(rng.randrange(1, 3)): + body = Payload(data=bytes([rng.randrange(256)])) + request.records.append(AppendRecord(body=body)) + appends.append((request, writer, request_id)) + expected = model.append(request, writer, request_id) + answer = await _answer( + store.append_records(request, request_id=request_id) + ) + case _: + request = ReadRecordsRequest( + stream_id=stream_id, + after_offset=rng.choice( + [b"", *(i.to_bytes(8, "big") for i in range(1, 9))] + ), + max_records=rng.randrange(4), + ) + expected = model.read(request) + answer = await _answer(store.read_records(request)) + assert answer == expected, f"step {step}: {request}" + + +def _streams(retention: int = 1) -> MemoryStreamStore: + return MemoryStreamStore(retention=timedelta(seconds=retention), resend_window=1) + + +_S = "s" + + +def _client_append() -> AppendRecordsRequest: + request = AppendRecordsRequest(stream_id=_S, records=[AppendRecord()]) + request.producer.client.SetInParent() + return request + + +def test_a_stream_expires_after_its_retention_from_its_create_or_last_write() -> None: + async def script(rng: random.Random) -> None: + loop = asyncio.get_running_loop() + retention = rng.randrange(1, 50) + streams = _streams(retention) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="c") + expires_at = loop.time() + retention + # The window of the client Producer has its last batch, so an append with the + # request id of that batch is a resend, which writes nothing. + last_batch: str | None = None + for step in range(12): + await asyncio.sleep(rng.randrange(40)) + expired = loop.time() >= expires_at + match rng.choice(["append", "append", "read", "describe", "create"]): + case "append": + request_id = rng.choice(["", "r"]) + append = streams.append_records( + _client_append(), request_id=request_id + ) + answer = await _answer(append) + expected: Any = AppendRecordsResponse + resend = bool(request_id) and request_id == last_batch + if not expired and not resend: + expires_at, last_batch = loop.time() + retention, request_id + case "read": + read = ReadRecordsRequest(stream_id=_S) + answer = await _answer(streams.read_records(read)) + expected = ReadRecordsResponse + case "describe": + describe = DescribeStreamRequest(stream_id=_S) + answer = await _answer(streams.describe_stream(describe)) + expected = DescribeStreamResponse + case _: + use_existing = ( + StreamIdConflictPolicy.STREAM_ID_CONFLICT_POLICY_USE_EXISTING + ) + create = CreateStreamRequest( + stream_id=_S, id_conflict_policy=use_existing + ) + answer = await _answer( + streams.create_stream(create, request_id=rng.choice("cd")) + ) + expected = CreateStreamResponse + if expired: + expected = _EXPIRED + assert answer == expected or type(answer) is expected, ( + f"step {step}: {answer} at {loop.time()}" + ) + + for seed in range(200): + with failure_note(f"seed {seed}"): + run_with_virtual_clock(script(random.Random(seed))) + + +@pytest.mark.parametrize( + "wait,write_in,answered_at,outcome", + [ + (5, 3, 3, "record"), + (5, 7, 5, "empty"), + (5, None, 5, "empty"), + (20, None, 10, "expired"), + (10, None, 10, "expired"), + ], +) +def test_a_read_waits_for_a_write_its_timeout_or_expiry( + wait: int, write_in: int | None, answered_at: int, outcome: str +) -> None: + async def script() -> None: + loop = asyncio.get_running_loop() + streams = _streams(retention=10) + await streams.create_stream(CreateStreamRequest(stream_id=_S), request_id="") + first = await streams.append_records(_client_append(), request_id="") + request = ReadRecordsRequest( + stream_id=_S, after_offset=first.last_offset, wait=Duration(seconds=wait) + ) + + async def read() -> tuple[float, Any]: + response = await _answer(streams.read_records(request)) + return loop.time(), response + + reader = asyncio.create_task(read()) + if write_in is not None: + await asyncio.sleep(write_in) + await streams.append_records(_client_append(), request_id="") + ended, page = await reader + assert ended == answered_at + if outcome == "expired": + assert page == _EXPIRED + elif outcome == "empty": + assert page == ReadRecordsResponse() + else: + [record] = page.records + assert record.offset > first.last_offset + + run_with_virtual_clock(script()) From bf635e670f8d10dbfa9ce5bc71937cd8db5dc2a8 Mon Sep 17 00:00:00 2001 From: Moe Dashti Date: Tue, 1 Dec 2026 10:13:05 -0700 Subject: [PATCH 4/4] Add BufferedAppender, current_producer and as_producer An Activity that appends each model token pays one Store call for each token. The appender batches them with one write in flight, and stops at the first failed batch so that a reader sees no gap. `current_producer` and `as_producer` let resumed Activity work write as its first Producer. --- temporalio/contrib/streams/README.md | 66 ++++++++ temporalio/contrib/streams/__init__.py | 15 ++ temporalio/contrib/streams/_appender.py | 194 ++++++++++++++++++++++++ temporalio/contrib/streams/_producer.py | 57 +++++++ tests/contrib/streams/__init__.py | 0 tests/contrib/streams/test_appender.py | 154 +++++++++++++++++++ tests/nexus/test_streams.py | 154 +++++++++++++++++++ 7 files changed, 640 insertions(+) create mode 100644 temporalio/contrib/streams/README.md create mode 100644 temporalio/contrib/streams/__init__.py create mode 100644 temporalio/contrib/streams/_appender.py create mode 100644 temporalio/contrib/streams/_producer.py create mode 100644 tests/contrib/streams/__init__.py create mode 100644 tests/contrib/streams/test_appender.py create mode 100644 tests/nexus/test_streams.py diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md new file mode 100644 index 0000000000..3fa5a5ccf0 --- /dev/null +++ b/temporalio/contrib/streams/README.md @@ -0,0 +1,66 @@ +# Stream helpers + +> This package is experimental. Its API can change. + +`temporalio.contrib.streams` supports the SDK's Stream API. Configure Stores with +`stream_config=StreamConfig(stores=[...])`. Use `create_stream` or `get_stream` +on the client or `temporalio.workflow` to get a `Stream`. + +`temporalio.contrib.workflow_streams` is a separate API that stores events in +Workflow state. + +## `BufferedAppender` + +Use `BufferedAppender` in client or Activity code to combine frequent appends. + +```python +from temporalio.contrib.streams import BufferedAppender + +async with BufferedAppender(stream) as tokens: + async for token in model_tokens(): + tokens.append(token) +``` + +`append` returns immediately. When no write is active, the appender starts one on +the next turn of the event loop with the buffered Records. Records that arrive +during a write form the next batch. Writes are sequential. + +`async with` flushes before exit. Without it, call `await tokens.flush()` before +the Activity ends. Otherwise the last write can run after the Activity ends, even +after a write of a later attempt, and nobody gets its error. + +The buffer has no size limit. Await `flush()` periodically if the producer is +faster than the Store. Set the appender's `max_batch_records` to stay within the +client's batch count limit. The client's byte limits still apply. + +A failed batch stops later writes. Later `append` and `flush` calls raise that +error, or `RuntimeError` if the write was cancelled. `unwritten` counts Records +in the failed batch and the remaining buffer. The Store may have accepted the +failed batch if only its response was lost. + +Workflow code batches values in one Stream `append` call. + +## Store a Producer + +`current_producer()` returns the running Activity attempt's Producer. Use +`as_producer` to restore it from heartbeat details. Pass the restored value as +`append(..., producer=...)` when resumed work must retain that Producer. + +## Read a Stream + +Pass `body_type=` or a typed ref such as `StreamRef[str](id=...)` to `get_stream`. +A ref without a body type raises `TypeError` when read. A Stream from +`create_stream` without a body type accepts any body. + +A Stream has no close. Stop at the application's terminal Record or cancel the +iterator. `read` and `read_pages` continue after empty pages. `read_pages` yields +those pages. `read_page` returns one page and has no default wait. + +With no `wait`, an iterator requests its first page immediately. Later requests +wait up to one minute. An explicit `wait` applies to every page. Zero disables +waiting, so an idle Stream produces repeated empty pages. Client iterators yield +to the event loop between them so cancellation can run. + +A positive `rpc_timeout` caps client and Activity waits below the timeout. An +Activity that heartbeats between Records needs a shorter `wait` than its +heartbeat timeout, or a separate heartbeat task. diff --git a/temporalio/contrib/streams/__init__.py b/temporalio/contrib/streams/__init__.py new file mode 100644 index 0000000000..fd05faea41 --- /dev/null +++ b/temporalio/contrib/streams/__init__.py @@ -0,0 +1,15 @@ +"""Helpers on top of the Streams API. + +:py:class:`BufferedAppender` batches the appends of one Stream, in client and +Activity code. :py:func:`current_producer` gives the Producer that a write of +the running Activity sends by default, and :py:func:`as_producer` gives back a +Producer that code stored. + +.. warning:: + This package is experimental and may change in future versions. +""" + +from temporalio.contrib.streams._appender import BufferedAppender +from temporalio.contrib.streams._producer import as_producer, current_producer + +__all__ = ["BufferedAppender", "as_producer", "current_producer"] diff --git a/temporalio/contrib/streams/_appender.py b/temporalio/contrib/streams/_appender.py new file mode 100644 index 0000000000..6141216a29 --- /dev/null +++ b/temporalio/contrib/streams/_appender.py @@ -0,0 +1,194 @@ +"""A helper that batches the appends of one Stream. + +.. warning:: + This module is experimental and subject to change. +""" + +from __future__ import annotations + +import asyncio +from types import TracebackType +from typing import Generic, TypeVar + +from typing_extensions import Self + +import temporalio.nexus.system.stream_service.client +import temporalio.workflow + +BodyT = TypeVar("BodyT") + + +class BufferedAppender(Generic[BodyT]): + """A buffer that writes the appends of one Stream in batches. + + Use it in code that appends often, such as an Activity that streams model + tokens. :py:meth:`append` returns immediately and does no I/O. While no write + runs, the appender starts one on the next turn of the event loop, with the + Records that are buffered by then. Records that arrive during a write go into + the next batch. One write runs at a time, and the Records keep their order. + + Use it in ``async with``, or await :py:meth:`flush` before the code that + appends ends. Otherwise the last Records are written after that code ends, + and nobody gets the error of that write. For an Activity that has ended, + that write can come after a write of the next attempt. + + ``await flush()`` is the backpressure point. The buffer has no bound, so code + that appends faster than the Store takes Records must await it from time to + time. + + After a batch fails, the appender writes nothing more, so a reader sees no + gap. Each later :py:meth:`append` and :py:meth:`flush` raises the error of + that batch, or :exc:`RuntimeError` if the write was cancelled. + + The appender is for client and Activity code. Workflow code passes its + Records to one ``append`` call of its Stream. + + .. warning:: + This API is experimental and subject to change. + """ + + def __init__( + self, + stream: temporalio.nexus.system.stream_service.client.Stream[BodyT], + *, + max_batch_records: int | None = None, + ) -> None: + """Create an appender. It starts no write before the first append. + + Args: + stream: The Stream to append to, from a client or from the client of + an Activity. + max_batch_records: The maximum number of Records of one batch. A + buffer with this many Records is written immediately. ``None`` + means no maximum of the appender, and a batch over a limit of + the client's ``StreamConfig`` then fails. + + Raises: + RuntimeError: The appender is created in Workflow code. + ValueError: ``max_batch_records`` is below 1. + """ + if temporalio.workflow.in_workflow(): + raise RuntimeError( + "BufferedAppender is for client and Activity code. In Workflow code, " + "pass the Records to one append call." + ) + if max_batch_records is not None and max_batch_records < 1: + raise ValueError("max_batch_records must be 1 or more") + self._stream = stream + self._max_batch_records = max_batch_records + self._buffer: list[BodyT] = [] + self._scheduled: asyncio.Handle | None = None + self._writing: asyncio.Task[None] | None = None + self._appended = 0 + # Failed batches also settle buffered Records, so flush cannot wait forever. + self._settled = 0 + self._error: Exception | None = None + self._last_offset: bytes | None = None + self._unwritten = 0 + + def append(self, *records: BodyT) -> None: + """Add one Record for each value to the buffer, and return immediately. + + Raises: + temporalio.exceptions.StreamError: A batch failed, so the appender + takes no more Records. + RuntimeError: The write of a batch was cancelled. + """ + if self._error: + raise self._error + self._buffer.extend(records) + self._appended += len(records) + self._schedule() + + async def flush(self) -> bytes | None: + """Write every Record that was appended before the call. + + Returns: + The offset of the last written Record, or ``None`` if the appender + has written nothing. + + Raises: + temporalio.exceptions.StreamError: A batch failed. + RuntimeError: The write of a batch was cancelled before the call. + """ + target = self._appended + while self._settled < target: + if not self._writing: + self._start() + assert self._writing + # A write is one batch at the Store, so a cancel of the caller doesn't stop it. + await asyncio.shield(self._writing) + if self._error: + raise self._error + return self._last_offset + + @property + def unwritten(self) -> int: + """Number of Records of the failed batch and of the buffer behind it. + + The appender wrote none of the buffer. The Store may still have taken the + failed batch, if only its answer was lost. + """ + return self._unwritten + + async def __aenter__(self) -> Self: + """Use the appender in ``async with``.""" + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + """Write the buffered Records. An error of the block wins over a write error.""" + try: + await self.flush() + except asyncio.CancelledError: + if exc is None or self._error is None: + raise + except Exception: + if exc is None: + raise + + def _schedule(self) -> None: + if self._writing or not self._buffer: + return + if self._max_batch_records and len(self._buffer) >= self._max_batch_records: + self._start() + elif not self._scheduled: + # The Records that the caller appends before it yields join this batch. + self._scheduled = asyncio.get_running_loop().call_soon(self._start) + + def _start(self) -> None: + if self._scheduled: + self._scheduled.cancel() + self._scheduled = None + batch = self._buffer[: self._max_batch_records] + del self._buffer[: self._max_batch_records] + self._writing = asyncio.get_running_loop().create_task(self._write(batch)) + + async def _write(self, batch: list[BodyT]) -> None: + try: + # An eager task factory must let append return before the Store call starts. + await asyncio.sleep(0) + response = await self._stream.append(*batch) + self._last_offset = response.last_offset + except BaseException as err: + # Later batches must not create a gap after this failed batch. + self._unwritten = len(batch) + len(self._buffer) + self._settled += len(self._buffer) + self._buffer.clear() + if isinstance(err, Exception): + self._error = err + else: + # Nobody cancelled a later caller, so it gets no `CancelledError`. + self._error = RuntimeError( + "The write of a batch was cancelled, so the appender takes no " + "more Records." + ) + raise + finally: + self._settled += len(batch) + self._writing = None + self._schedule() diff --git a/temporalio/contrib/streams/_producer.py b/temporalio/contrib/streams/_producer.py new file mode 100644 index 0000000000..70ef0d242b --- /dev/null +++ b/temporalio/contrib/streams/_producer.py @@ -0,0 +1,57 @@ +"""The Producer of a Stream write. + +.. warning:: + This module is experimental and subject to change. +""" + +from __future__ import annotations + +import temporalio.activity +import temporalio.api.stream.v1 +import temporalio.converter +from temporalio.nexus.system import _support +from temporalio.nexus.system.stream_service import Producer + + +def current_producer() -> Producer: + """Return the Producer of the running attempt of an Activity. + + An append of that attempt sends it by default. Code that stores + it, such as in heartbeat details, gets it back from :py:func:`as_producer`. + + The Producer of an Activity of a Workflow has the Activity id and the id of + its ``ActivityTaskScheduled`` event. So a later Activity of the run that uses + the same Activity id is a separate Producer. A Local Activity's Producer + uses the Workflow Task id and Activity id from its original schedule. + Its retries keep both ids, including when a timer delays the retry. + + Raises: + RuntimeError: The caller is outside an Activity or its Local Activity + scheduling metadata is unavailable. + + .. warning:: + This API is experimental and subject to change. + """ + return _support.activity_producer(temporalio.activity.info()) + + +def as_producer(value: object) -> Producer: + """Return the Producer that code stored, such as in heartbeat details. + + The default data converter gives a stored Producer back as its proto + message, since such a value has no type hint. + + Raises: + TypeError: ``value`` is neither a Producer nor its proto message. + + .. warning:: + This API is experimental and subject to change. + """ + if isinstance(value, Producer): + return value + if not isinstance(value, temporalio.api.stream.v1.Producer): + raise TypeError(f"Expected a Producer, got {type(value).__name__}") + converter = temporalio.converter.DataConverter.default + return _support.model_from_proto( + value, Producer, converter.payload_converter, converter.failure_converter + ) diff --git a/tests/contrib/streams/__init__.py b/tests/contrib/streams/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/contrib/streams/test_appender.py b/tests/contrib/streams/test_appender.py new file mode 100644 index 0000000000..1b0d5052bb --- /dev/null +++ b/tests/contrib/streams/test_appender.py @@ -0,0 +1,154 @@ +"""Tests of the buffered appender, with no server.""" + +import asyncio +from typing import Any +from unittest.mock import AsyncMock, Mock, call + +import pytest + +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.contrib.streams import BufferedAppender +from temporalio.exceptions import StreamError +from temporalio.nexus.system.stream_service import AppendRecordsResponse +from tests.helpers.streams import run_with_virtual_clock + + +class _FakeStream: + """Stream whose append takes time on the clock of the loop, and whose batch + number ``fails_at`` fails, or has its write cancelled. + """ + + def __init__( + self, write_time: float, fails_at: int | None = None, cancelled: bool = False + ) -> None: + self._write_time = write_time + self._fails_at = fails_at + self._cancelled = cancelled + self.written: list[int] = [] + self.batches: list[tuple[float, float, tuple[int, ...]]] = [] + """The start time, the end time and the Records of each batch.""" + + async def append(self, *records: int) -> AppendRecordsResponse: + loop = asyncio.get_running_loop() + started = loop.time() + try: + await asyncio.sleep(self._write_time) + if len(self.batches) == self._fails_at: + if self._cancelled: + raise asyncio.CancelledError() + raise StreamError( + "The Store is down", + reason=StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE, + ) + self.written.extend(records) + offset = len(self.written).to_bytes(8, "big") + return AppendRecordsResponse(first_offset=offset, last_offset=offset) + finally: + self.batches.append((started, loop.time(), records)) + + +def test_records_that_arrive_during_a_write_form_the_next_batch() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + appender = BufferedAppender[int](stream) + appender.append(1) + appender.append(2) + await asyncio.sleep(1) + appender.append(3) + appender.append(4) + await asyncio.sleep(5) + assert stream.batches == [(0, 2, (1, 2)), (2, 4, (3, 4))] + + run_with_virtual_clock(script()) + + +def test_a_flush_takes_over_the_scheduled_write() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + appender = BufferedAppender[int](stream) + appender.append(1) + assert await appender.flush() == (1).to_bytes(8, "big") + await asyncio.sleep(5) + assert stream.batches == [(0, 2, (1,))] + + run_with_virtual_clock(script()) + + +def test_full_batches_wait_for_the_previous_write() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + appender = BufferedAppender[int](stream, max_batch_records=2) + assert await appender.flush() is None + appender.append(1, 2) + await asyncio.sleep(1) + appender.append(3, 4, 5) + await asyncio.sleep(6) + assert stream.batches == [(0, 2, (1, 2)), (2, 4, (3, 4)), (4, 6, (5,))] + assert await appender.flush() == (5).to_bytes(8, "big") + + run_with_virtual_clock(script()) + + +def test_cancelling_a_flush_preserves_the_write_and_buffer() -> None: + async def script() -> None: + stream: Any = _FakeStream(2) + async with BufferedAppender[int](stream) as appender: + appender.append(1) + flushing = asyncio.create_task(appender.flush()) + await asyncio.sleep(1) + appender.append(2) + flushing.cancel() + with pytest.raises(asyncio.CancelledError): + await flushing + assert stream.batches == [(0, 2, (1,)), (2, 4, (2,))] + + run_with_virtual_clock(script()) + + +@pytest.mark.parametrize("cancelled", [False, True]) +async def test_a_failed_batch_stops_later_writes(cancelled: bool) -> None: + stream: Any = _FakeStream(0, fails_at=1, cancelled=cancelled) + appender = BufferedAppender[int](stream, max_batch_records=2) + appender.append(1, 2, 3, 4, 5) + with pytest.raises(asyncio.CancelledError if cancelled else StreamError): + await appender.flush() + assert stream.written == [1, 2] + assert appender.unwritten == 3 + later = RuntimeError if cancelled else StreamError + with pytest.raises(later) as raised: + appender.append(6) + with pytest.raises(later) as again: + await appender.flush() + assert raised.value is again.value + + +async def test_append_defers_immediate_writes_with_an_eager_task_factory() -> None: + eager = getattr(asyncio, "eager_task_factory", None) + if eager is None: + pytest.skip("Eager task factories require Python 3.12") + loop = asyncio.get_running_loop() + previous = loop.get_task_factory() + stream = Mock() + stream.append = AsyncMock(return_value=AppendRecordsResponse(last_offset=b"last")) + try: + loop.set_task_factory(eager) + appender = BufferedAppender[int](stream, max_batch_records=1) + appender.append(1) + appender.append(2) + stream.append.assert_not_awaited() + assert await appender.flush() == b"last" + assert stream.append.await_args_list == [call(1), call(2)] + finally: + loop.set_task_factory(previous) + + +@pytest.mark.parametrize("cancelled", [False, True]) +def test_async_with_keeps_the_error_of_its_block(cancelled: bool) -> None: + async def block() -> None: + stream: Any = _FakeStream(0.0, fails_at=0, cancelled=cancelled) + async with BufferedAppender[int](stream) as appender: + appender.append(1) + raise KeyError("The block failed") + + with pytest.raises(KeyError): + run_with_virtual_clock(block()) diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py new file mode 100644 index 0000000000..5ce7229e59 --- /dev/null +++ b/tests/nexus/test_streams.py @@ -0,0 +1,154 @@ +"""Tests of the client path of Streams, with no server.""" + +import dataclasses +from datetime import datetime, timezone +from types import SimpleNamespace +from typing import Any, cast +from unittest.mock import patch + +import pytest +from google.protobuf.timestamp_pb2 import Timestamp + +import temporalio.converter +from temporalio.activity import WorkflowTaskAttempt +from temporalio.api.stream.v1 import ( + Producer, +) +from temporalio.contrib.streams import as_producer, current_producer +from temporalio.nexus.system import _support +from temporalio.testing import ActivityEnvironment + + +def _producer_proto(producer: Any) -> Producer: + converter = temporalio.converter.DataConverter.default + message = _support.model_to_proto( + producer, converter.payload_converter, converter.failure_converter + ) + assert isinstance(message, Producer) + return message + + +@dataclasses.dataclass(frozen=True) +class _WriterInfo: + kind: str + namespace: str + workflow_id: str + run_id: str + activity_id: str + attempt: int + time: datetime + event_id: int + + +def _default_producer(writer: _WriterInfo) -> Any: + """Return the default Producer of a write of ``writer``.""" + if writer.kind == "workflow": + info = SimpleNamespace( + namespace=writer.namespace, + workflow_id=writer.workflow_id, + run_id=writer.run_id, + ) + with patch("temporalio.workflow.info", lambda: info): + return _support.workflow_producer() + in_workflow = writer.kind != "standalone_activity" + activity = ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, + namespace=writer.namespace, + activity_id=writer.activity_id, + attempt=writer.attempt, + current_attempt_scheduled_time=writer.time, + is_local=writer.kind == "local_activity", + workflow_id=writer.workflow_id if in_workflow else None, + workflow_run_id=writer.run_id if in_workflow else None, + activity_run_id=None if in_workflow else writer.run_id, + workflow_task=WorkflowTaskAttempt( + writer.event_id + 3, writer.attempt + 1, writer.time + ) + if writer.kind == "local_activity" + else None, + _local_activity_origin=(writer.event_id, "original") + if writer.kind == "local_activity" + else None, + _scheduled_event_id=writer.event_id + if writer.kind == "workflow_activity" + else 0, + ) + producer = activity.run(current_producer) + # The default of a write in an Activity is that Producer, and it reads no client. + assert activity.run(_support.default_producer, cast(Any, None)) == producer + return producer + + +def _expected_producer(writer: _WriterInfo) -> Producer: + """Return the whole Producer of ``writer``, built field by field.""" + time = Timestamp() + time.FromDatetime(writer.time) + producer = Producer() + kind = getattr(producer, writer.kind) + kind.namespace, kind.run_id = writer.namespace, writer.run_id + if writer.kind != "standalone_activity": + kind.workflow_id = writer.workflow_id + if writer.kind == "workflow": + return producer + kind.activity_id = writer.activity_id + kind.attempt.attempt = writer.attempt + if writer.kind == "local_activity": + kind.workflow_task_id, kind.activity_id = writer.event_id, "original" + task = kind.attempt.task + task.started_event_id, task.attempt = writer.event_id + 3, writer.attempt + 1 + task.started_time.CopyFrom(time) + else: + kind.attempt.attempt_scheduled_time.CopyFrom(time) + if writer.kind == "workflow_activity": + kind.scheduled_event_id = writer.event_id + return producer + + +@pytest.mark.parametrize( + ("kind", "event_id"), + [ + ("workflow", 7), + ("local_activity", 0), + ("local_activity", 9), + ("workflow_activity", 0), + ("workflow_activity", 17), + ("standalone_activity", 0), + ], +) +def test_a_writer_keeps_its_identity_and_attempt(kind: str, event_id: int) -> None: + writer = _WriterInfo( + kind=kind, + namespace="ns:/é", + workflow_id="workflow", + run_id="run", + activity_id="activity", + attempt=3, + time=datetime(2026, 1, 1, tzinfo=timezone.utc), + event_id=event_id, + ) + producer = _default_producer(writer) + assert _producer_proto(producer) == _expected_producer(writer) + converter = temporalio.converter.PayloadConverter.default + # Heartbeat details can be decoded without a type hint. + [stored] = converter.from_payloads(converter.to_payloads([producer])) + assert as_producer(stored) == producer + assert as_producer(producer) is producer + + +def test_a_local_activity_requires_its_origin_to_identify_a_stream_producer() -> None: + activity = ActivityEnvironment() + activity.info = dataclasses.replace( + activity.info, is_local=True, workflow_task=WorkflowTaskAttempt(17, 2, None) + ) + with pytest.raises(RuntimeError, match="no scheduling origin"): + activity.run(current_producer) + + +def test_a_workflow_producer_preserves_the_task_id_and_attempt() -> None: + proto = Producer() + task = proto.workflow + task.namespace, task.workflow_id, task.run_id = "ns", "workflow", "run" + task.workflow_task_id = 11 + task.attempt.started_event_id, task.attempt.attempt = 37, 2 + assert _producer_proto(as_producer(proto)) == proto