diff --git a/temporalio/bridge/Cargo.toml b/temporalio/bridge/Cargo.toml index 10ffc2208..1d6bad33c 100644 --- a/temporalio/bridge/Cargo.toml +++ b/temporalio/bridge/Cargo.toml @@ -72,6 +72,8 @@ temporalio-sdk-core = { version = "0.12.0", path = "./sdk-core/crates/sdk-core", "ephemeral-server", "envconfig", "prometheus", + # Replay must retain the result groups of Stream create and describe Local Activities. + "disable_workflow_task_chunking", ] } temporalio-streams = { version = "0.1.0", path = "./sdk-core/crates/streams" } tokio = "1.26" diff --git a/temporalio/bridge/src/lib.rs b/temporalio/bridge/src/lib.rs index 867da998e..63fae3d88 100644 --- a/temporalio/bridge/src/lib.rs +++ b/temporalio/bridge/src/lib.rs @@ -6,6 +6,7 @@ mod client_rpc_generated; mod envconfig; mod metric; mod runtime; +mod streams; mod testing; mod worker; diff --git a/temporalio/bridge/src/streams.rs b/temporalio/bridge/src/streams.rs new file mode 100644 index 000000000..7c6663e00 --- /dev/null +++ b/temporalio/bridge/src/streams.rs @@ -0,0 +1,221 @@ +use futures::future::BoxFuture; +use prost::Message; +use pyo3::exceptions::asyncio::CancelledError; +use pyo3::exceptions::PyValueError; +use pyo3::prelude::*; +use pyo3::sync::PyOnceLock; +use pyo3::types::{PyBytes, PyType}; +use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError}; +use temporalio_sdk_core::StreamRuntimes; +use temporalio_streams::proto::{ + AppendRecordsRequest, AppendRecordsResponse, CreateStreamRequest, CreateStreamResponse, + DescribeStreamRequest, DescribeStreamResponse, ReadRecordsRequest, ReadRecordsResponse, +}; +use temporalio_streams::record::StoreLimits; +use temporalio_streams::{ + AppendError, CreateError, DescribeError, ReadError, StreamError, StreamRuntime, StreamStore, + WireReason, +}; + +struct PythonStore { + caller: Py, + event_loop_task_locals: Arc>, +} + +enum CallState { + Pending, + Running(Py), + Dropped, + Done, +} + +// Release this lock before acquiring the GIL to avoid a deadlock with `OnTask`. +fn lock(state: &Mutex) -> MutexGuard<'_, CallState> { + state.lock().unwrap_or_else(PoisonError::into_inner) +} + +#[pyclass] +struct OnTask { + state: Arc>, +} + +#[pymethods] +impl OnTask { + fn __call__(&self, task: Py) -> PyResult<()> { + let mut state = lock(&self.state); + if matches!(*state, CallState::Dropped) { + drop(state); + return Err(CancelledError::new_err(())); + } + *state = CallState::Running(task); + Ok(()) + } +} + +// Dropping a Core future must also stop its Python Store task. +struct CallGuard<'a> { + state: Arc>, + task_locals: &'a pyo3_async_runtimes::TaskLocals, +} + +impl Drop for CallGuard<'_> { + fn drop(&mut self) { + let state = std::mem::replace(&mut *lock(&self.state), CallState::Dropped); + if let CallState::Running(task) = state { + // `asyncio` requires cross-thread cancellation to run through its event loop. + let _ = Python::try_attach(|py| { + let cancel = task.getattr(py, "cancel")?; + let event_loop = self.task_locals.event_loop(py); + event_loop.call_method1("call_soon_threadsafe", (cancel,))?; + PyResult::Ok(()) + }); + } + } +} + +impl PythonStore { + async fn call( + &self, + operation: &'static str, + request: Request, + request_id: Option, + ) -> Result> + where + Request: Message, + Response: Message + Default, + R: WireReason, + { + let Some(task_locals) = self.event_loop_task_locals.get() else { + return Err(StreamError::store_unavailable( + "The Worker hasn't set the event loop of its Stream Stores yet", + )); + }; + let state = Arc::new(Mutex::new(CallState::Pending)); + let _guard = CallGuard { + state: state.clone(), + task_locals, + }; + let called = Python::try_attach(|py| { + let on_task = OnTask { + state: state.clone(), + }; + let request = PyBytes::new(py, &request.encode_to_vec()); + let arguments = (operation, request, request_id, on_task); + let coroutine = (self.caller.bind(py)).call_method1("call", arguments)?; + pyo3_async_runtimes::into_future_with_locals(task_locals, coroutine) + }); + let answer = match called { + Some(Ok(answer)) => answer.await, + Some(Err(err)) => Err(err), + None => return Err(interpreter_gone(operation)), + }; + let done = Python::try_attach(|py| { + let _task = std::mem::replace(&mut *lock(&state), CallState::Done); + match answer { + Ok(response) => (response.bind(py).cast::().ok()) + .and_then(|bytes| Response::decode(bytes.as_bytes()).ok()) + .ok_or_else(|| { + StreamError::store_corrupt(format!( + "The Store didn't answer the {operation} call with its encoded \ + response message" + )) + }), + Err(err) => Err(store_error(py, err)), + } + }); + done.unwrap_or_else(|| Err(interpreter_gone(operation))) + } +} + +fn interpreter_gone(operation: &str) -> StreamError { + StreamError::store_unavailable(format!( + "The Python interpreter is shutting down, so the Store can't take the {operation} call" + )) +} + +// Only Store refusals retain their reason. Other exceptions can be retried. +fn store_error(py: Python<'_>, err: PyErr) -> StreamError { + let refusal = || -> PyResult> { + let value = err.value(py); + if !value.is_instance(stream_error_type(py)?)? { + return Ok(None); + } + let reason = value.getattr("reason")?.extract()?; + Ok(Some((reason, value.getattr("message")?.extract()?))) + }; + match refusal() { + Ok(Some((reason, message))) => StreamError::from_wire(reason, message), + _ => StreamError::store_unavailable(err.to_string()), + } +} + +fn stream_error_type(py: Python<'_>) -> PyResult<&Bound<'_, PyType>> { + static STREAM_ERROR: PyOnceLock> = PyOnceLock::new(); + STREAM_ERROR.import(py, "temporalio.exceptions", "StreamError") +} + +impl StreamStore for PythonStore { + fn create_stream( + &self, + request: CreateStreamRequest, + request_id: String, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("CreateStream", request, Some(request_id))) + } + + fn append_records( + &self, + request: AppendRecordsRequest, + request_id: String, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("AppendRecords", request, Some(request_id))) + } + + fn read_records( + &self, + request: ReadRecordsRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("ReadRecords", request, None)) + } + + fn describe_stream( + &self, + request: DescribeStreamRequest, + ) -> BoxFuture<'_, Result> { + Box::pin(self.call("DescribeStream", request, None)) + } +} + +fn store_limits( + (max_record_bytes, max_batch_bytes, max_batch_records): (usize, usize, usize), +) -> PyResult { + StoreLimits::default() + .with_max_record_bytes(max_record_bytes) + .and_then(|limits| limits.with_max_batch_bytes(max_batch_bytes)) + .and_then(|limits| limits.with_max_batch_records(max_batch_records)) + .map_err(|err| PyValueError::new_err(err.message)) +} + +#[derive(FromPyObject)] +pub(crate) struct WorkerStreams { + limits: Option<(usize, usize, usize)>, + stores: Vec<(String, Py)>, +} + +impl WorkerStreams { + pub(crate) fn into_runtimes( + self, + task_locals: &Arc>, + ) -> PyResult { + let limits = (self.limits.map(store_limits).transpose()?).unwrap_or_default(); + let runtimes = self.stores.into_iter().map(|(name, caller)| { + let store = PythonStore { + caller, + event_loop_task_locals: task_locals.clone(), + }; + let runtime = StreamRuntime::new(Arc::new(store), limits); + (name, Arc::new(runtime)) + }); + Ok(StreamRuntimes::new(runtimes)) + } +} diff --git a/temporalio/bridge/src/worker.rs b/temporalio/bridge/src/worker.rs index 46b6c00de..4c8de98da 100644 --- a/temporalio/bridge/src/worker.rs +++ b/temporalio/bridge/src/worker.rs @@ -27,6 +27,7 @@ use tracing::error; use crate::client; use crate::runtime; +use crate::streams::WorkerStreams; pyo3::create_exception!(temporal_sdk_bridge, PollShutdownError, PyException); @@ -65,6 +66,7 @@ pub struct WorkerConfig { plugins: Vec<(String, String)>, storage_drivers: HashSet, disable_payload_error_limit: bool, + streams: WorkerStreams, } #[derive(FromPyObject)] @@ -720,6 +722,7 @@ fn convert_worker_config( conf: WorkerConfig, task_locals: Arc>, ) -> PyResult { + let stream_runtimes = conf.streams.into_runtimes(&task_locals)?; let converted_tuner = convert_tuner_holder(conf.tuner, task_locals)?; let converted_versioning_strategy = convert_versioning_strategy(conf.versioning_strategy); temporalio_sdk_core::WorkerConfig::builder() @@ -781,6 +784,7 @@ fn convert_worker_config( .collect::>(), ) .disable_payload_error_limit(conf.disable_payload_error_limit) + .stream_runtimes(stream_runtimes) .build() .map_err(|err| PyValueError::new_err(format!("Invalid worker config: {err}"))) } diff --git a/temporalio/bridge/streams.py b/temporalio/bridge/streams.py new file mode 100644 index 000000000..d9d3aa5bb --- /dev/null +++ b/temporalio/bridge/streams.py @@ -0,0 +1,41 @@ +"""Stream Store calls through SDK Core. (unstable) + +Nothing in this module should be considered stable. The API may change. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Any, Protocol + + +class StoreCaller(Protocol): + """What SDK Core calls to reach a Stream Store that is a Python object.""" + + async def call( + self, + operation: str, + request: bytes, + request_id: str | None, + on_task: Callable[[asyncio.Task[Any]], None], + ) -> bytes: + """Call the Store for a Stream operation with its encoded request, and + return its encoded response. + + ``request_id`` is that of a create or an append, and ``None`` for the + other operations. + """ + ... + + +@dataclass +class WorkerStreams: + """Python representation of the Rust struct for the Stream Stores of a worker.""" + + limits: tuple[int, int, int] | None + """The ``max_record_bytes``, the ``max_batch_bytes`` and the ``max_batch_records`` + of the Stream config, or ``None`` with no Stream config.""" + stores: Sequence[tuple[str, StoreCaller]] + """The caller of each Stream Store that Workflow code can use, by Store name.""" diff --git a/temporalio/bridge/worker.py b/temporalio/bridge/worker.py index fd4d2aae3..811fa0dfe 100644 --- a/temporalio/bridge/worker.py +++ b/temporalio/bridge/worker.py @@ -18,6 +18,7 @@ import temporalio.bridge.proto.workflow_activation import temporalio.bridge.proto.workflow_completion import temporalio.bridge.runtime +import temporalio.bridge.streams import temporalio.bridge.temporal_sdk_bridge import temporalio.converter import temporalio.converter._extstore @@ -63,6 +64,7 @@ class WorkerConfig: plugins: Sequence[tuple[str, str]] storage_drivers: set[str] disable_payload_error_limit: bool + streams: temporalio.bridge.streams.WorkerStreams @dataclass diff --git a/temporalio/client/_stream_store.py b/temporalio/client/_stream_store.py index 12a40d146..ed68bfb00 100644 --- a/temporalio/client/_stream_store.py +++ b/temporalio/client/_stream_store.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import logging from abc import ABC, abstractmethod from collections.abc import Callable, Sequence from dataclasses import dataclass, field @@ -37,10 +38,13 @@ ReadRecordsResponse, ) from temporalio.converter import PayloadCodec +from temporalio.converter._payload_converter import _get_transfer_type_converter from temporalio.exceptions import StreamError from temporalio.nexus.system.stream_service import StreamService from temporalio.types import ReturnType +logger = logging.getLogger(__name__) + _definition = nexusrpc.get_service_definition(StreamService) assert _definition _STREAM_SERVICE: nexusrpc.ServiceDefinition = _definition @@ -223,6 +227,18 @@ class StreamConfig: 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. + Workflow calls: + + * The SDK selects a Store before each call, including replay. SDK Core handles + append and read. Create and describe use SDK Local Activities, which pass + through Worker interceptors. + * Appends are at-least-once. A Workflow Task retry can write its batch again. + * Store outages fail the Workflow Task. Workflow code gets no outage error. + * A missing Store fails the Workflow Task even if Workflow code catches the + error. A call not awaited before Workflow completion may not run. + * Workers read the limits at startup. A replacement client must have the same + limits and Store names. + .. warning:: This API is experimental and subject to change. """ @@ -238,6 +254,15 @@ class StreamConfig: Return an instance from :py:attr:`stores`. A selector is required with multiple Stores. Without one, the sole Store handles these calls. + + Workflow calls invoke the selector before each command, including creates, + describes and replay. The selector must return the same Store for the same + call, must not block or perform I/O, and must be safe across threads. Core + receives the selected Store name with each command. + + Replayed appends and reads fail with nondeterminism if their selected Store + differs from History. Create and describe use their recorded results. A + created Stream's ref includes its Store name, so later calls skip selection. """ max_record_bytes: int = 1536 * 1024 @@ -348,6 +373,15 @@ def _store_operation(name: str) -> tuple[str, _Message, _Message]: return _STORE_OPERATIONS[name] +def _sdk_request_type( # pyright: ignore[reportUnusedFunction] + name: str, +) -> _Message: + operation = _STREAM_SERVICE.operation_definitions[name] + converter = _get_transfer_type_converter(operation.input_type) + assert converter and converter.transfer_type + return converter.transfer_type + + def _store_request( request: google.protobuf.message.Message, ) -> google.protobuf.message.Message: @@ -726,3 +760,41 @@ async def _call_stream_store( # pyright: ignore[reportUnusedFunction] response, result_type, *converters ) return handle + + +class _StoreCaller: # pyright: ignore[reportUnusedClass] + """Keep Store calls on the Python event loop so Core can cancel them.""" + + def __init__(self, store: Callable[[], StreamStore]) -> None: + """Resolve the Store at each call so client replacement takes effect.""" + self._store = store + + async def call( + self, + operation: str, + request: bytes, + request_id: str | None, + on_task: Callable[[asyncio.Task[Any]], None], + ) -> bytes: + """Register the Python task before any Store work can start. + + ``on_task`` raises :py:class:`asyncio.CancelledError` if Core already + dropped the call. + """ + task = asyncio.current_task() + assert task + on_task(task) + _, request_type, _ = _store_operation(operation) + try: + response = await _call_method( + self._store(), operation, request_type.FromString(request), request_id + ) + except StreamError as err: + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + if err.reason == unavailable and err.__cause__: + # Core keeps only the text of the error, so the traceback is logged here. + logger.warning( + "Stream Store failed the %s call", operation, exc_info=err.__cause__ + ) + raise + return response.SerializeToString() diff --git a/temporalio/contrib/streams/README.md b/temporalio/contrib/streams/README.md index 3fa5a5ccf..ad1fdc76b 100644 --- a/temporalio/contrib/streams/README.md +++ b/temporalio/contrib/streams/README.md @@ -46,6 +46,11 @@ Workflow code batches values in one Stream `append` call. `as_producer` to restore it from heartbeat details. Pass the restored value as `append(..., producer=...)` when resumed work must retain that Producer. +A `WorkflowProducer` includes `workflow_task_id` so readers can distinguish +retries from separate Workflow Tasks. Core sets it to the started event ID of the +last completed Workflow Task, or zero for the first task. Each retry has its own +`attempt`. + ## Read a Stream Pass `body_type=` or a typed ref such as `StreamRef[str](id=...)` to `get_stream`. diff --git a/temporalio/worker/_interceptor.py b/temporalio/worker/_interceptor.py index 09d49884d..f164103a0 100644 --- a/temporalio/worker/_interceptor.py +++ b/temporalio/worker/_interceptor.py @@ -21,6 +21,9 @@ import temporalio.nexus import temporalio.nexus._util import temporalio.workflow +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _SystemNexusWorkflowOutboundInterceptorBase as _StreamOutboundInterceptorBase, +) from temporalio.nexus.system.workflow_service._system_nexus_interceptor import ( _SystemNexusWorkflowOutboundInterceptorBase, ) @@ -455,7 +458,9 @@ async def handle_update_handler(self, input: HandleUpdateInput) -> Any: return await self.next.handle_update_handler(input) -class WorkflowOutboundInterceptor(_SystemNexusWorkflowOutboundInterceptorBase): +class WorkflowOutboundInterceptor( + _SystemNexusWorkflowOutboundInterceptorBase, _StreamOutboundInterceptorBase +): """Outbound interceptor to wrap calls made from within workflows. This should be extended by any workflow outbound interceptors. @@ -472,9 +477,7 @@ def __init__(self, next: WorkflowOutboundInterceptor) -> None: """ self.next = next - def _next_system_nexus_interceptor( - self, - ) -> _SystemNexusWorkflowOutboundInterceptorBase: + def _next_system_nexus_interceptor(self) -> WorkflowOutboundInterceptor: return self.next def continue_as_new(self, input: ContinueAsNewInput) -> NoReturn: diff --git a/temporalio/worker/_replayer.py b/temporalio/worker/_replayer.py index 1542b3e0f..7e1dcc08a 100644 --- a/temporalio/worker/_replayer.py +++ b/temporalio/worker/_replayer.py @@ -32,6 +32,7 @@ UnsandboxedWorkflowRunner, WorkflowRunner, ) +from ._workflow_streams import _bridge_streams from .workflow_sandbox import SandboxedWorkflowRunner logger = logging.getLogger(__name__) @@ -58,6 +59,7 @@ def __init__( runtime: temporalio.runtime.Runtime | None = None, disable_safe_workflow_eviction: bool = False, header_codec_behavior: HeaderCodecBehavior = HeaderCodecBehavior.NO_CODEC, + stream_config: temporalio.client.StreamConfig | None = None, ) -> None: """Create a replayer to replay workflows from history. @@ -70,6 +72,13 @@ def __init__( will default to a new thread pool executor with no max_workers set that will be shared across all replay calls and never explicitly shut down. Users are encouraged to provide their own if needing more control. + + ``stream_config`` must preserve the Worker's Store names and selector + choices because replay selects the Store of each call again. Append, + create and describe use recorded results without calling the Store. + A :py:class:`temporalio.testing.MemoryStreamStore` with the same name can + serve those operations during replay. Reads fetch Records from the Store + again and fail if the recorded Records are unavailable or changed. """ self._config = ReplayerConfig( workflows=list(workflows), @@ -88,6 +97,7 @@ def __init__( runtime=runtime, disable_safe_workflow_eviction=disable_safe_workflow_eviction, header_codec_behavior=header_codec_behavior, + stream_config=stream_config, ) self._initial_config = self._config.copy() self._default_workflow_logic_flags = set(_DEFAULT_ENABLED_WORKFLOW_LOGIC_FLAGS) @@ -253,6 +263,7 @@ def on_eviction_hook( self._config.get("data_converter") or temporalio.converter.DataConverter.default ) + stream_config = self._config.get("stream_config") workflow_worker = _WorkflowWorker( bridge_worker=lambda: bridge_worker, namespace=self._config.get("namespace", "ReplayNamespace"), @@ -281,6 +292,7 @@ def on_eviction_hook( ), should_enforce_versioning_behavior=False, assert_local_activity_valid=lambda a: None, + stream_config=lambda: stream_config, encode_headers=self._config.get( "header_codec_behavior", HeaderCodecBehavior.NO_CODEC ) @@ -358,6 +370,7 @@ def on_eviction_hook( (plugin.name(), plugin.version()) for plugin in self.plugins ], storage_drivers=storage_driver_types, + streams=_bridge_streams(lambda: stream_config), ), ) bridge_worker_scope = bridge_worker @@ -437,6 +450,7 @@ class ReplayerConfig(TypedDict, total=False): runtime: temporalio.runtime.Runtime | None disable_safe_workflow_eviction: bool header_codec_behavior: HeaderCodecBehavior + stream_config: temporalio.client.StreamConfig | None @dataclass(frozen=True) diff --git a/temporalio/worker/_worker.py b/temporalio/worker/_worker.py index cf8125d81..bbe056abc 100644 --- a/temporalio/worker/_worker.py +++ b/temporalio/worker/_worker.py @@ -45,6 +45,7 @@ UnsandboxedWorkflowRunner, WorkflowRunner, ) +from ._workflow_streams import _bridge_streams, _check_stream_swap, _stream_store_call from .workflow_sandbox import SandboxedWorkflowRunner logger = logging.getLogger(__name__) @@ -498,7 +499,9 @@ def _init_from_config(self, client: temporalio.client.Client, config: WorkerConf or bridge_client.config.runtime or temporalio.runtime.Runtime.default() ) - activities = config.get("activities") + activities = list(config.get("activities") or []) + if client_config["stream_config"] and config.get("workflows"): + activities.append(_stream_store_call) if activities: _warn_if_activity_executor_max_workers_is_inconsistent(config) self._activity_worker = _ActivityWorker( @@ -575,6 +578,7 @@ def check_activity(activity: str): disable_safe_eviction=config["disable_safe_workflow_eviction"], # type: ignore[reportTypedDictNotRequiredAccess] should_enforce_versioning_behavior=should_enforce_versioning_behavior, assert_local_activity_valid=check_activity, + stream_config=lambda: self.client._config["stream_config"], encode_headers=client_config["header_codec_behavior"] != HeaderCodecBehavior.NO_CODEC, max_workflow_task_external_storage_concurrency=max_workflow_task_external_storage_concurrency, @@ -667,7 +671,7 @@ def check_activity(activity: str): enable_workflows=self._workflow_worker is not None, enable_local_activities=self._activity_worker is not None and self._workflow_worker is not None, - enable_remote_activities=self._activity_worker is not None + enable_remote_activities=bool(config.get("activities")) and not config.get("no_remote_activities"), enable_nexus=self._nexus_worker is not None, ), @@ -716,6 +720,9 @@ def check_activity(activity: str): disable_payload_error_limit=config.get( "disable_payload_error_limit", False ), + streams=_bridge_streams( + lambda: self.client._config["stream_config"], + ), ), ) @@ -758,6 +765,9 @@ def client(self, value: temporalio.client.Client) -> None: raise ValueError( "New client is not on the same runtime as the existing client" ) + _check_stream_swap( + self.client._config["stream_config"], value._config["stream_config"] + ) assert bridge_client._bridge_client self._bridge_worker.replace_client(bridge_client._bridge_client) self._config["client"] = value diff --git a/temporalio/worker/_workflow.py b/temporalio/worker/_workflow.py index b0f18b7b8..2c1922f29 100644 --- a/temporalio/worker/_workflow.py +++ b/temporalio/worker/_workflow.py @@ -27,6 +27,7 @@ import temporalio.exceptions import temporalio.workflow from temporalio.bridge.worker import PollShutdownError +from temporalio.client._stream_store import StreamConfig from temporalio.converter import StorageDriverStoreContext, StorageDriverWorkflowInfo from temporalio.worker.workflow_sandbox._runner import SandboxedWorkflowRunner @@ -136,6 +137,7 @@ def __init__( encode_headers: bool, max_workflow_task_external_storage_concurrency: int, default_workflow_logic_flags: frozenset[_WorkflowLogicFlag] | None = None, + stream_config: Callable[[], StreamConfig | None] = lambda: None, ) -> None: # Debug mode is enabled if specified or if the TEMPORAL_DEBUG env var is truthy debug_mode = debug_mode or bool(os.environ.get("TEMPORAL_DEBUG")) @@ -192,6 +194,7 @@ def __init__( **_WorkflowExternFunctions( # type: ignore __temporal_get_metric_meter=lambda: metric_meter, __temporal_assert_local_activity_valid=assert_local_activity_valid, + __temporal_stream_config=stream_config, ) ) diff --git a/temporalio/worker/_workflow_instance.py b/temporalio/worker/_workflow_instance.py index 06621aa21..6a7396cfe 100644 --- a/temporalio/worker/_workflow_instance.py +++ b/temporalio/worker/_workflow_instance.py @@ -58,7 +58,14 @@ import temporalio.exceptions import temporalio.nexus.system import temporalio.workflow +from temporalio.client._stream_store import _STREAM_SERVICE, StreamConfig from temporalio.converter import StorageDriverStoreContext, StorageDriverWorkflowInfo +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _start_system_nexus_operation as _start_stream_nexus_operation, +) +from temporalio.nexus.system.stream_service.workflow._system_nexus_interceptor import ( + _SystemNexusWorkflowOutboundInterceptorTerminal as _StreamOutboundInterceptorTerminal, +) from temporalio.nexus.system.workflow_service._system_nexus_interceptor import ( _start_system_nexus_operation, _SystemNexusWorkflowOutboundInterceptorTerminal, @@ -92,6 +99,7 @@ WorkflowInboundInterceptor, WorkflowOutboundInterceptor, ) +from ._workflow_streams import _WorkflowStreams logger = logging.getLogger(__name__) @@ -352,6 +360,7 @@ def __init__(self, det: WorkflowInstanceDetails) -> None: self._pending_nexus_operations: dict[int, _NexusOperationHandle] = {} self._pending_external_signals: dict[int, tuple[asyncio.Future, str]] = {} self._pending_external_cancels: dict[int, tuple[asyncio.Future, str]] = {} + self._streams = _WorkflowStreams(self) # Keyed by type self._curr_seqs: dict[str, int] = {} # TODO(cretz): Any concerns about not sharing this? Maybe the types I @@ -497,6 +506,7 @@ def _activate( self._finished_nexus_update_ids.clear() self._current_activation_error: Exception | None = None + self._streams.task_error = None self._deployment_version_for_current_task = ( act.deployment_version_for_current_task ) @@ -575,10 +585,13 @@ def _activate( check_conditions=index == 1 or index == 2, jobs=act.jobs ) except Exception as err: + # Store outages must remain retryable even when Workflow failure types include them. + if self._streams.task_error: + activation_err = self._streams.task_error # We want some errors during activation, like those that can happen # during payload conversion, to be able to fail the workflow not the # task - if self.workflow_is_failure_exception(err): + elif self.workflow_is_failure_exception(err): try: self._set_workflow_failure(err) except Exception as inner_err: @@ -695,6 +708,8 @@ def _apply( self._apply_resolve_signal_external_workflow( job.resolve_signal_external_workflow ) + elif job.HasField("resolve_stream_append"): + self._streams.resolve_append(job.resolve_stream_append) elif job.HasField("signal_workflow"): self._apply_signal_workflow(job.signal_workflow) elif job.HasField("initialize_workflow"): @@ -1848,7 +1863,12 @@ async def workflow_start_nexus_operation( event_groups: Sequence[temporalio.workflow.EventGroup] | None = None, ) -> temporalio.workflow.NexusOperationHandle[OutputT]: if temporalio.nexus.system.is_system_endpoint(endpoint): - return await _start_system_nexus_operation( + start = ( + _start_stream_nexus_operation + if service == _STREAM_SERVICE.name + else _start_system_nexus_operation + ) + return await start( self._outbound, StartNexusOperationInput( endpoint=temporalio.nexus.system.TEMPORAL_SYSTEM_ENDPOINT, @@ -3388,7 +3408,9 @@ async def handle_update_handler(self, input: HandleUpdateInput) -> Any: class _WorkflowOutboundImpl( - _SystemNexusWorkflowOutboundInterceptorTerminal, WorkflowOutboundInterceptor + _SystemNexusWorkflowOutboundInterceptorTerminal, + _StreamOutboundInterceptorTerminal, + WorkflowOutboundInterceptor, ): def __init__(self, instance: _WorkflowInstanceImpl) -> None: # type: ignore # We are intentionally not calling the base class's __init__ here @@ -3430,7 +3452,9 @@ async def start_nexus_operation( async def _schedule_system_nexus_operation( self, input: StartNexusOperationInput[Any, OutputT] - ) -> _NexusOperationHandle[OutputT]: + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: + if input.service == _STREAM_SERVICE.name: + return self._instance._streams.start(input) return await self._instance._outbound_start_nexus_operation(input) def start_local_activity( @@ -4063,6 +4087,7 @@ def _encode_search_attributes( class _WorkflowExternFunctions(TypedDict): __temporal_get_metric_meter: Callable[[], temporalio.common.MetricMeter] __temporal_assert_local_activity_valid: Callable[[str], None] + __temporal_stream_config: Callable[[], StreamConfig | None] class _ReplaySafeMetricMeter(temporalio.common.MetricMeter): diff --git a/temporalio/worker/_workflow_streams.py b/temporalio/worker/_workflow_streams.py new file mode 100644 index 000000000..ed596f42a --- /dev/null +++ b/temporalio/worker/_workflow_streams.py @@ -0,0 +1,343 @@ +"""Stream calls of Workflow code.""" + +from __future__ import annotations + +import asyncio +import functools +from collections.abc import Callable, Generator +from typing import TYPE_CHECKING, Any, cast + +import google.protobuf.json_format +import google.protobuf.message +from nexusrpc import OutputT + +import temporalio.activity +import temporalio.api.failure.v1 +import temporalio.api.sdk.v1 as sdk +import temporalio.api.stream.v1 +import temporalio.api.streamservice.v1 as proto +import temporalio.bridge.proto.workflow_activation +import temporalio.bridge.streams +import temporalio.common +import temporalio.exceptions +import temporalio.nexus.system._support +import temporalio.workflow +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.client._stream_store import ( + StreamConfig, + StreamStore, + _call_store, + _request_ref, + _sdk_request_type, + _StoreCaller, +) +from temporalio.exceptions import StreamError + +from ._interceptor import StartLocalActivityInput, StartNexusOperationInput + +if TYPE_CHECKING: + from ._workflow_instance import _WorkflowInstanceImpl + +_STORE_CALL_ACTIVITY = "__temporal_stream_store_call" + + +class _WorkflowStreams: # pyright: ignore[reportUnusedClass] + """Use Local Activities for create and describe because Core has no commands + for those operations. + """ + + def __init__(self, instance: _WorkflowInstanceImpl) -> None: + self._instance = instance + self._appends: dict[int, asyncio.Future[Any]] = {} + self.task_error: Exception | None = None + + def start( + self, input: StartNexusOperationInput[Any, OutputT] + ) -> temporalio.workflow.NexusOperationHandle[OutputT]: + """Schedule before returning so command order matches call order. + + Cancellation stops the caller's wait. Core still completes appends and + reads, so their later results must be discarded. + """ + instance = self._instance + instance._assert_not_read_only("start a Stream call") + operation = input.operation_name + converters = ( + instance._context_free_payload_converter, + instance._context_free_failure_converter, + ) + model = input.input + result_type: Any = input.output_type + request = temporalio.nexus.system._support.model_to_proto(model, *converters) + store = self._store(_request_ref(request)).name() + result = _start_call(self, store, operation, request) + + async def call() -> OutputT: + # `asyncio.wait` ends at a cancel of this task. `await result` would pass the + # cancel on and wait for the cancelled Local Activity. + await asyncio.wait([result]) + return temporalio.nexus.system._support.model_from_proto( + self._response(operation, request, result), + result_type, + *converters, + ) + + def stop(_: asyncio.Task[OutputT]) -> None: + if result.done(): + return + result.cancel() + + task = instance.create_task(call(), name=f"stream: {operation}") + # A callback also runs for a task that is cancelled before its first step. + task.add_done_callback(stop) + return _StreamCall(task) + + def _store(self, ref: sdk.StreamRef) -> StreamStore: + config = self._stream_config() + if config is None: + raise self._fail_task( + ValueError( + "Worker or Replayer has no stream_config, which every " + "Stream call requires, also in a replay." + ) + ) + try: + return config._store_for(ref, self._instance._info.namespace) + except Exception as err: + raise self._fail_task(err) + + def resolve_append( + self, job: temporalio.bridge.proto.workflow_activation.ResolveStreamAppend + ) -> None: + future = self._appends.pop(job.seq, None) + if future is None: + raise RuntimeError(f"Failed finding Stream append for sequence {job.seq}") + # Core completes writes even after their caller is cancelled. + if future.done(): + return + if job.HasField("failed"): + future.set_exception(self._error(job.failed)) + else: + future.set_result(job.appended) + + def _error(self, failure: temporalio.api.failure.v1.Failure) -> BaseException: + instance = self._instance + return _stream_error_from_failure(failure) or ( + instance._context_free_failure_converter.from_failure( + failure, instance._context_free_payload_converter + ) + ) + + def _schedule_store_call( + self, + store: str, + operation: str, + request: google.protobuf.message.Message, + request_id: str | None, + ) -> asyncio.Future[Any]: + instance = self._instance + activity = instance._outbound.start_local_activity( + StartLocalActivityInput( + activity=_STORE_CALL_ACTIVITY, + args=(operation, store, request.SerializeToString(), request_id), + activity_id=None, + # A call that hangs ends before the heartbeat of the Workflow Task, and an + # outage fails the task immediately, so neither writes into History. + schedule_to_close_timeout=instance._info.task_timeout / 2, + schedule_to_start_timeout=None, + start_to_close_timeout=None, + retry_policy=temporalio.common.RetryPolicy(maximum_attempts=1), + local_retry_threshold=None, + cancellation_type=temporalio.workflow.ActivityCancellationType.TRY_CANCEL, + headers={}, + summary=None, + arg_types=None, + ret_type=None, + ) + ) + # Nothing awaits the Activity once its call is cancelled. + activity.add_done_callback(lambda done: done.cancelled() or done.exception()) + return activity + + def _response( + self, + operation: str, + request: google.protobuf.message.Message, + result: asyncio.Future[Any], + ) -> google.protobuf.message.Message: + if isinstance(request, sdk.AppendRecordsRequest): + appended = result.result() + return proto.AppendRecordsResponse( + first_offset=appended.first_offset, last_offset=appended.last_offset + ) + try: + answer = result.result() + except temporalio.exceptions.FailureError as err: + # A refusal of the Store comes as the failure of the attempt. A timeout comes + # inside an Activity failure, which has no Stream details. + error = _stream_error_from_failure(err.failure) if err.failure else None + if ( + error is None + or error.reason + == StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + ): + # Workflow code could catch an error of this call, so the task fails and + # nothing goes into History, as for an outage during an append. + outage = RuntimeError(f"Stream Store call {operation} failed") + outage.__cause__ = err + raise self._fail_task(outage) + raise error from err + # Replay must retain the Store recorded by create. + if isinstance(request, sdk.CreateStreamRequest): + return sdk.CreateStreamResponse.FromString(answer) + return proto.DescribeStreamResponse.FromString(answer) + + def _fail_task(self, error: Exception) -> Exception: + """Prevent caught errors from recording an unserved call as successful.""" + self.task_error = self._instance._current_activation_error = error + return error + + def _stream_config(self) -> StreamConfig | None: + functions = self._instance._extern_functions + return cast( + Callable[[], StreamConfig | None], functions["__temporal_stream_config"] + )() + + +def _start_call( + streams: _WorkflowStreams, + store: str, + operation: str, + request: google.protobuf.message.Message, +) -> asyncio.Future[Any]: + """Use the selected Store in commands so replay can detect routing changes.""" + instance = streams._instance + stream = sdk.StreamRef(id=_request_ref(request).id, store=store) + if isinstance(request, sdk.AppendRecordsRequest): + seq = instance._next_seq("stream_append") + append = instance._add_command().append_to_stream + append.seq = seq + append.stream.CopyFrom(stream) + append.bodies.extend(record.body for record in request.records) + result = streams._appends[seq] = instance.create_future() + return result + # Runs in a chain must retry the same create. + request_id = None + if isinstance(request, sdk.CreateStreamRequest): + request_id = instance._info.first_execution_run_id + return streams._schedule_store_call(store, operation, request, request_id) + + +class _StreamCall(temporalio.workflow.NexusOperationHandle[OutputT]): + """Cancel the caller's wait without waiting for the Store call to finish.""" + + def __init__(self, task: asyncio.Task[OutputT]) -> None: + self._task = task + + @property + def operation_token(self) -> str | None: + return None + + def __await__(self) -> Generator[Any, Any, OutputT]: + return self._task.__await__() + + def cancel(self) -> bool: + return self._task.cancel() + + +@temporalio.activity.defn(name=_STORE_CALL_ACTIVITY) +async def _stream_store_call( # pyright: ignore[reportUnusedFunction] + operation: str, store: str, request: bytes, request_id: str | None +) -> bytes: + """Record the selected Store in create results so replay keeps the same ref.""" + info = temporalio.activity.info() + if not info.is_local or operation not in ("CreateStream", "DescribeStream"): + raise temporalio.exceptions.ApplicationError( + f"{_STORE_CALL_ACTIVITY} is an Activity of the SDK, which only runs " + "a create or a describe of a Stream as a Local Activity", + non_retryable=True, + ) + client = temporalio.activity.client() + stream_config = client._config["stream_config"] + if stream_config is None: + raise ValueError("Client of this Worker has no stream_config.") + stream_request = _sdk_request_type(operation).FromString(request) + response = await _call_store( + stream_config._store(store), + stream_config._limits(), + client.data_converter.payload_codec, + operation, + stream_request, + request_id, + ) + return response.SerializeToString() + + +def _stream_error_from_failure( + failure: temporalio.api.failure.v1.Failure, +) -> StreamError | None: + """Accept Core's binary details and the default converter's JSON details.""" + details = temporalio.api.stream.v1.StreamErrorDetails() + for payload in failure.application_failure_info.details.payloads: + if payload.metadata.get("messageType") != details.DESCRIPTOR.full_name.encode(): + continue + # Core writes the details as binary, and the default converter as JSON. + if payload.metadata.get("encoding") == b"json/protobuf": + try: + google.protobuf.json_format.Parse(payload.data, details) + except google.protobuf.json_format.ParseError: + # The JSON has a reason by a name that this SDK doesn't know. + pass + else: + details.ParseFromString(payload.data) + reason = details.reason + if reason not in StreamErrorReason.values(): + reason = StreamErrorReason.STREAM_ERROR_REASON_UNSPECIFIED + error = StreamError(failure.message, reason=reason) + error._failure = failure + return error + return None + + +def _for_core( + stream_config: StreamConfig | None, +) -> tuple[set[str], tuple[int, int, int] | None]: + if stream_config is None: + return set(), None + return set(stream_config._by_name), stream_config._limits() + + +def _bridge_streams( # pyright: ignore[reportUnusedFunction] + stream_config: Callable[[], StreamConfig | None], +) -> temporalio.bridge.streams.WorkerStreams: + """Resolve Store instances at call time so client replacement takes effect.""" + + def store(name: str) -> StreamStore: + current = stream_config() + assert current + return current._store(name) + + names, limits = _for_core(stream_config()) + return temporalio.bridge.streams.WorkerStreams( + limits=limits, + # Client swaps must affect later Store calls. + stores=[ + (name, _StoreCaller(functools.partial(store, name))) + for name in sorted(names) + ], + ) + + +def _check_stream_swap( # pyright: ignore[reportUnusedFunction] + existing: StreamConfig | None, new: StreamConfig | None +) -> None: + names, limits = _for_core(existing) + new_names, new_limits = _for_core(new) + if new_names != names: + raise ValueError( + "New client does not have the Stream Stores of the existing client" + ) + if new_limits != limits: + raise ValueError( + "New client does not have the Stream limits of the existing client" + ) diff --git a/tests/helpers/streams.py b/tests/helpers/streams.py index f8c78cdb1..674ee63c3 100644 --- a/tests/helpers/streams.py +++ b/tests/helpers/streams.py @@ -3,13 +3,19 @@ import asyncio import collections import selectors -from collections.abc import Awaitable, Callable, Coroutine, Iterator, Sequence +import uuid +from collections.abc import Awaitable, Callable, Coroutine, Iterator, Mapping, Sequence from contextlib import contextmanager +from dataclasses import dataclass, field +from datetime import timedelta from typing import Any, TypeVar from google.protobuf.message import Message -from temporalio.api.common.v1 import Payload +from temporalio.api.common.v1 import Payload, Payloads +from temporalio.api.enums.v1 import StreamErrorReason +from temporalio.api.failure.v1 import ApplicationFailureInfo, Failure +from temporalio.api.stream.v1 import StreamErrorDetails from temporalio.api.streamservice.v1 import ( AppendRecordsRequest, AppendRecordsResponse, @@ -25,6 +31,9 @@ StreamConfig, StreamSelectContext, StreamStore, + WorkflowFailureError, + WorkflowHandle, + WorkflowHistory, ) from temporalio.converter import ( DataConverter, @@ -33,6 +42,8 @@ WithSerializationContext, ) from temporalio.testing import MemoryStreamStore +from temporalio.worker import Replayer, Worker +from tests.helpers import new_worker _T = TypeVar("_T") @@ -99,6 +110,15 @@ def failure_note(note: str) -> Iterator[None]: raise +def raises(error: BaseException) -> Fault: + """Return a fault that fails a call, and doesn't call the memory Store.""" + + async def fault(_call: Callable[[], Awaitable[Any]]) -> Any: + raise error + + return fault + + def answers(response: Message) -> Fault: """Return a fault that answers a call with ``response``, with no Store call.""" @@ -194,6 +214,32 @@ async def call() -> Any: return await call() +def core_failure(reason: int, message: str = "The Store refused the call") -> Failure: + """Return the failure of a Stream job as SDK Core builds it, also for a reason + number that this SDK doesn't know. + """ + unavailable = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE + details = StreamErrorDetails(reason=reason) # type: ignore[arg-type] + return Failure( + message=message, + application_failure_info=ApplicationFailureInfo( + type="stream_token", + non_retryable=reason != unavailable, + details=Payloads( + payloads=[ + Payload( + metadata={ + "encoding": b"binary/protobuf", + "messageType": details.DESCRIPTOR.full_name.encode(), + }, + data=details.SerializeToString(), + ) + ] + ), + ), + ) + + def stream_client( client: Client, *stores: StreamStore, @@ -213,6 +259,72 @@ def stream_client( return Client(**config) +@dataclass +class RunOptions: + """What :py:func:`run` runs, and on which Worker.""" + + workflow: Any + """The Workflow class.""" + + args: Sequence[Any] = () + activities: Sequence[Callable[..., Any]] = () + cached: bool = True + """If false, the Worker caches no run, so each Workflow Task replays its run.""" + + replay: bool = False + """Whether a ``Replayer`` with the Stream config of the client replays the History.""" + + task_timeout: timedelta | None = None + worker: Mapping[str, Any] = field(default_factory=dict) + """More options of the Worker.""" + + during: Callable[[WorkflowHandle[Any, Any], Worker], Awaitable[None]] | None = None + """Called once the Workflow has started, while its Worker runs.""" + + +@dataclass +class Run: + """What a Workflow of :py:func:`run` did.""" + + result: Any + """The result of the Workflow, or the error that it failed with.""" + + history: WorkflowHistory + + +async def run(client: Client, options: RunOptions) -> Run: + """Run a Workflow to its end on a new Worker.""" + async with new_worker( + client, + options.workflow, + activities=options.activities, + max_cached_workflows=1000 if options.cached else 0, + **options.worker, + ) as worker: + handle = await client.start_workflow( + options.workflow.run, + args=options.args, + id=f"wf-{uuid.uuid4()}", + task_queue=worker.task_queue, + task_timeout=options.task_timeout, + ) + if options.during: + await options.during(handle, worker) + result: Any + try: + result = await handle.result() + except WorkflowFailureError as err: + result = err + history = await handle.fetch_history() + if options.replay: + await Replayer( + workflows=[options.workflow], + data_converter=client.data_converter, + stream_config=client._config["stream_config"], + ).replay_workflow(history) + return Run(result, history) + + class _JumpingSelector(selectors.DefaultSelector): """Selector that moves the clock of its loop past a wait and doesn't wait.""" diff --git a/tests/nexus/test_streams.py b/tests/nexus/test_streams.py index 210228ac5..fd0f6fd38 100644 --- a/tests/nexus/test_streams.py +++ b/tests/nexus/test_streams.py @@ -1,7 +1,9 @@ """Tests of the client path of Streams, with no server.""" import asyncio +import copy import dataclasses +import pickle import random from collections.abc import Awaitable, Callable from datetime import datetime, timedelta, timezone @@ -22,10 +24,12 @@ from temporalio.activity import WorkflowTaskAttempt from temporalio.api.common.v1 import Payload from temporalio.api.enums.v1 import StreamErrorReason, StreamIdConflictPolicy +from temporalio.api.failure.v1 import Failure from temporalio.api.stream.v1 import ( AppendRecord, ClientProducer, Producer, + StreamErrorDetails, ) from temporalio.client import ( Client, @@ -40,7 +44,7 @@ _store_request, # pyright: ignore[reportPrivateUsage] ) from temporalio.contrib.streams import as_producer, current_producer -from temporalio.exceptions import StreamError +from temporalio.exceptions import ApplicationError, StreamError from temporalio.nexus.system import _support from temporalio.nexus.system.stream_service import ( ReadRecordsRequest, @@ -56,11 +60,13 @@ from temporalio.service import ServiceClient from temporalio.testing import ActivityEnvironment, MemoryStreamStore from temporalio.types import ReturnType +from temporalio.worker._workflow_streams import _stream_error_from_failure from tests.helpers.streams import ( ContextCodec, FaultStore, Hold, answers, + core_failure, failure_note, loses_answer, run_with_virtual_clock, @@ -950,6 +956,53 @@ def test_the_append_check_measures_each_record_in_its_stored_size() -> None: ) +async def test_a_stream_error_keeps_its_reason_on_every_path() -> None: + converter = temporalio.converter.DataConverter.default + for number in [*StreamErrorReason.values(), 99]: + known = number in StreamErrorReason.values() + reason = StreamErrorReason.ValueType(number if known else 0) + token = ( + "stream_" + + StreamErrorReason.Name(reason) + .removeprefix("STREAM_ERROR_REASON_") + .lower() + ) + message = f"The call failed with {number}" + expected = (reason, token, message, reason != _UNAVAILABLE) + details = StreamErrorDetails(reason=number) # type: ignore[arg-type] + + # Through an Activity, which gives its error to the default failure converter. + raised: ApplicationError = ( + StreamError(message, reason=reason) + if known + else ApplicationError(message, details, type=token, non_retryable=True) + ) + failure = Failure() + converter.failure_converter.to_failure( + raised, converter.payload_converter, failure + ) + # From Core, which builds the failure of a Stream job itself. + from_core = core_failure(number, message) + for form in (failure, from_core): + error = _stream_error_from_failure(form) + assert error is not None, number + # A copy of the error, also one from another process, is the same error. + for same in (error, copy.copy(error), pickle.loads(pickle.dumps(error))): + assert ( + same.reason, + same.type, + same.message, + same.non_retryable, + ) == expected, number + if not known: + # A newer Worker can record a reason by a name that this SDK doesn't have. + named = failure.application_failure_info.details.payloads[0] + named.data = b'{"reason": "STREAM_ERROR_REASON_ADDED_LATER"}' + later = _stream_error_from_failure(failure) + assert later and (later.reason, later.message) == (reason, message) + assert _stream_error_from_failure(Failure(message="other")) is None + + class _FakeReads(temporalio.client.OutboundInterceptor): def __init__(self, next: temporalio.client.OutboundInterceptor) -> None: super().__init__(next) diff --git a/tests/nexus/test_streams_with_worker.py b/tests/nexus/test_streams_with_worker.py index aef7d4661..ddf34ba31 100644 --- a/tests/nexus/test_streams_with_worker.py +++ b/tests/nexus/test_streams_with_worker.py @@ -1,32 +1,140 @@ """Tests of Streams with a Worker on the test server.""" import asyncio +from collections.abc import Sequence from datetime import timedelta from typing import Any import pytest from temporalio import activity, workflow -from temporalio.api.enums.v1 import EventType -from temporalio.client import Client +from temporalio.api.enums.v1 import EventType, TaskQueueType +from temporalio.api.streamservice.v1 import ( + CreateStreamRequest, + ReadRecordsRequest, +) +from temporalio.api.taskqueue.v1 import TaskQueue +from temporalio.api.workflowservice.v1 import DescribeTaskQueueRequest +from temporalio.client import Client, StreamConfig from temporalio.common import RetryPolicy from temporalio.contrib.streams import current_producer -from temporalio.exceptions import ApplicationError +from temporalio.exceptions import ApplicationError, StreamError from temporalio.nexus.system.stream_service import ( ProducerKindLocalActivity, + ProducerKindWorkflow, + StreamIdConflictPolicy, StreamRef, ) from temporalio.worker import ( + ActivityInboundInterceptor, + Interceptor, Replayer, + Worker, ) -from tests.helpers import new_worker +from tests.helpers import assert_eventually, new_worker from tests.helpers.streams import ( FaultStore, Hold, + RunOptions, + failure_note, + loses_answer, + raises, + run, stream_client, ) +async def _answers( + api: Any, calls: Sequence[Sequence[Any]], store: str | None = None +) -> list[Any]: + """Make each generated Stream call in turn and return what each one gave. + + ``api`` is a client or the ``temporalio.workflow`` module, which both have + ``create_stream`` and ``get_stream``. ``store`` is the Store name of each ref. + """ + streams: dict[str, Any] = {} + answers: list[Any] = [] + for operation, stream_id, *args in calls: + stream = streams.get(stream_id) or api.get_stream( + StreamRef[int](id=stream_id, store=store) + ) + try: + if operation == "create": + policy = StreamIdConflictPolicy(args[0]) if args and args[0] else None + stream = await api.create_stream( + id=stream_id, store=store, id_conflict_policy=policy, body_type=int + ) + streams[stream_id] = stream + answers.append([stream.ref.store, stream.created]) + elif operation == "append": + appended = await stream.append(*args[0]) + answers.append( + [appended.first_offset.hex(), appended.last_offset.hex()] + ) + elif operation == "read": + page = await stream.read_page() + bodies = [record.body for record in page.records] + last = page.records[-1].offset if page.records else b"" + answers.append([bodies, last.hex()]) + else: + described = await stream.describe() + answers.append([(described.last_offset or b"").hex()]) + except StreamError as err: + answers.append(["error", err.reason, err.message]) + return answers + + +@activity.defn +async def _calls_activity(calls: list[list[Any]]) -> list[Any]: + return await _answers(activity.client(), calls) + + +@workflow.defn +class _CallsWorkflow: + @workflow.run + async def run(self, calls: list[list[Any]], in_activity: bool = False) -> list[Any]: + if in_activity: + return await workflow.execute_activity( + _calls_activity, calls, start_to_close_timeout=timedelta(seconds=10) + ) + return await _answers(workflow, calls) + + +@activity.defn +async def _append_one(stream_id: str) -> None: + await activity.client().get_stream(StreamRef[int](id=stream_id)).append(1) + + +@workflow.defn +class _OneActivityIdWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + for _ in range(2): + await workflow.execute_activity( + _append_one, + stream_id, + activity_id="one id", + start_to_close_timeout=timedelta(seconds=10), + ) + + +async def test_two_activities_with_one_id_write_as_two_producers( + client: Client, +) -> None: + store = FaultStore() + client = stream_client(client, store) + await client.create_stream(id="one id", body_type=int) + options = RunOptions(_OneActivityIdWorkflow, ["one id"], activities=[_append_one]) + ran = await run(client, options) + # The Producer of each Activity has the id of the Activity's scheduled event. + scheduled = _events(ran.history, EventType.EVENT_TYPE_ACTIVITY_TASK_SCHEDULED) + page = await store.memory.read_records(ReadRecordsRequest(stream_id="one id")) + producers = [record.producer.workflow_activity for record in page.records] + assert [(p.activity_id, p.scheduled_event_id) for p in producers] == [ + ("one id", event.event_id) for event in scheduled + ] + + @activity.defn async def _write_local_attempt(stream_id: str, retry: bool) -> str: info = activity.info() @@ -132,5 +240,251 @@ async def test_local_activity_producers_survive_timer_retries_and_worker_restart ] +@workflow.defn +class _WorkflowTaskProducerWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + stream = workflow.get_stream(StreamRef[int](id=stream_id)) + await stream.append(1) + await asyncio.sleep(0.1) + await stream.append(2) + await workflow.create_stream(id="after append", body_type=int) + + +async def test_workflow_task_retries_write_as_one_producer(client: Client) -> None: + store = FaultStore() + client = stream_client(client, store) + stream = await client.create_stream(id="task producers", body_type=int) + # Fail the second task after it writes, so its retry writes to the same Stream. + store.faults["create_stream"].append(raises(ConnectionError("down"))) + ran = await run( + client, RunOptions(_WorkflowTaskProducerWorkflow, [stream.ref.id], replay=True) + ) + assert ran.result is None + [first, second] = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_COMPLETED) + [failed] = _events(ran.history, EventType.EVENT_TYPE_WORKFLOW_TASK_FAILED) + first_start = first.workflow_task_completed_event_attributes.started_event_id + page = await stream.read_page() + assert [record.body for record in page.records] == [1, 2, 2] + ids = [] + for record in page.records: + assert record.producer and isinstance( + record.producer.kind, ProducerKindWorkflow + ) + producer = record.producer.kind.value + assert producer.attempt + ids.append((producer.workflow_task_id, producer.attempt.started_event_id)) + assert ids == [ + (0, first_start), + (first_start, failed.workflow_task_failed_event_attributes.started_event_id), + (first_start, second.workflow_task_completed_event_attributes.started_event_id), + ] + + def _events(history: Any, event_type: EventType.ValueType) -> list[Any]: return [event for event in history.events if event.event_type == event_type] + + +class _ActivityTypes(Interceptor): + """Logs the type of each Activity that its Worker runs.""" + + def __init__(self) -> None: + super().__init__() + self.types: list[str] = [] + + def intercept_activity( + self, next: ActivityInboundInterceptor + ) -> ActivityInboundInterceptor: + self.types.append(activity.info().activity_type) + return next + + +async def test_a_worker_with_only_workflows_creates_a_stream(client: Client) -> None: + client = stream_client(client, FaultStore()) + interceptor = _ActivityTypes() + pollers: list[Any] = [] + + async def activity_pollers(handle: Any, worker: Worker) -> None: + await handle.result() + described = await client.workflow_service.describe_task_queue( + DescribeTaskQueueRequest( + namespace=client.namespace, + task_queue=TaskQueue(name=worker.task_queue), + task_queue_type=TaskQueueType.TASK_QUEUE_TYPE_ACTIVITY, + ) + ) + pollers.extend(described.pollers) + + options = RunOptions( + _CallsWorkflow, + [[["create", "alone"], ["describe", "alone"]]], + worker={"interceptors": [interceptor]}, + during=activity_pollers, + ) + ran = await run(client, options) + assert ran.result == [["memory", True], [""]] + assert interceptor.types == ["__temporal_stream_store_call"] * 2 + assert not pollers + + +@activity.defn +async def _append_to(stream_id: str) -> None: + stream = activity.client().get_stream(StreamRef[int](id=stream_id)) + await stream.append(3) + + +@workflow.defn +class _SwapWorkflow: + def __init__(self) -> None: + self._swapped = False + + @workflow.signal + def swapped(self) -> None: + self._swapped = True + + @workflow.run + async def run(self, own: str, shared: str) -> str | None: + created = await workflow.create_stream(id=own, body_type=int) + await workflow.wait_condition(lambda: self._swapped) + await created.append(1) + stream = workflow.get_stream(StreamRef[int](id=shared)) + await stream.append(2) + await workflow.execute_activity( + _append_to, shared, start_to_close_timeout=timedelta(seconds=10) + ) + return created.ref.store + + +def _calls(store: FaultStore) -> list[tuple[str, str]]: + """Return the request type and the Stream id of each call of a Store.""" + return [(type(r).__name__, r.stream_id) for r in store.requests] + + +# On a server with worker commands, a lone Worker polls in a loop after a new client. Marked as +# `test_workflow_replace_worker_client` and `test_nexus_client_updates_when_worker_client_changes`. +@pytest.mark.requires_local_server +async def test_a_worker_uses_the_stream_config_of_its_new_client( + client: Client, +) -> None: + for cached in (True, False): + with failure_note(f"cached {cached}"): + first, second = FaultStore("first"), FaultStore("second") + # The new client has other Store objects, with the Streams of the first ones. + new_first, new_second = FaultStore("first"), FaultStore("second") + new_first.memory = first.memory + selects: list[tuple[str, str | None]] = [] + + def pick_first(context: Any) -> FaultStore: + selects.append((context.id, context.namespace)) + return first + + before = stream_client(client, first, second, store_selector=pick_first) + after = stream_client( + client, new_first, new_second, store_selector=lambda _: new_second + ) + await after.create_stream(id="shared", body_type=int) + + async def swap(handle: Any, worker: Worker) -> None: + async def created() -> None: + assert first.requests + + await assert_eventually(created) + # A client with other Store names or other limits is refused. + for other in ( + stream_client(client, FaultStore("third")), + stream_client( + client, + first, + second, + store_selector=pick_first, + max_batch_records=1, + ), + ): + with pytest.raises(ValueError): + worker.client = other + worker.client = after + await handle.signal(_SwapWorkflow.swapped) + + options = RunOptions( + _SwapWorkflow, + ["own", "shared"], + activities=[_append_to], + cached=cached, + during=swap, + ) + # The created Stream stays on its Store. A ref with no Store name goes to the + # Store that the new selector picks, in Workflow code as in an Activity. + assert (await run(before, options)).result == "first" + assert _calls(first) == [("CreateStreamRequest", "own")] + # After the swap, Core calls the Store objects of the new client. + assert _calls(new_first) == [("AppendRecordsRequest", "own")] + assert _calls(new_second) == [ + ("CreateStreamRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ("AppendRecordsRequest", "shared"), + ] + assert not second.requests + # The selector of the Workflow's create got the Stream id and the namespace of + # the Worker. + assert selects == [("own", client.namespace)] + + +@workflow.defn +class _AppendOnceWorkflow: + @workflow.run + async def run(self, stream_id: str) -> None: + await workflow.get_stream(StreamRef[int](id=stream_id)).append(1) + + +async def test_a_replay_fails_when_the_selector_picks_another_store( + client: Client, +) -> None: + first, second = FaultStore("first"), FaultStore("second") + for store in (first, second): + await stream_client(client, store).create_stream(id="picked", body_type=int) + options = RunOptions(_AppendOnceWorkflow, ["picked"]) + ran = await run( + stream_client(client, first, second, store_selector=lambda _: first), options + ) + assert ran.result is None + for picked in (first, second): + with failure_note(f"replay picks {picked.name()}"): + + def select(_: Any) -> FaultStore: + return picked + + config = StreamConfig([first, second], store_selector=select) + replay = Replayer(workflows=[_AppendOnceWorkflow], stream_config=config) + if picked is first: + await replay.replay_workflow(ran.history) + continue + # SDK Core compares the Store of a replayed append with History. + with pytest.raises(workflow.NondeterminismError, match="Store `first`"): + await replay.replay_workflow(ran.history) + + +@workflow.defn +class _ChainWorkflow: + @workflow.run + async def run(self, stream_id: str, runs: int) -> bool | None: + stream = await workflow.create_stream(id=stream_id) + if runs > 1: + workflow.continue_as_new(args=[stream_id, runs - 1]) + return stream.created + + +async def test_a_create_in_a_later_run_of_the_chain_is_the_same_create( + client: Client, +) -> None: + store = FaultStore() + # The Store loses the answer of the first create of each run, so the Workflow Task + # fails after its create ran, and its next attempt makes the create again. + faults = [loses_answer(), lambda call: call(), loses_answer()] + store.faults["create_stream"].extend(faults) + ran = await run( + stream_client(client, store), RunOptions(_ChainWorkflow, ["chain", 2]) + ) + # Each run makes its create twice, and the Store takes all four for one create. + assert ran.result is True + creates = [i for r, i in store.calls if isinstance(r, CreateStreamRequest)] + assert len(creates) == 4 and len(set(creates)) == 1 diff --git a/tests/testing/test_stream_store.py b/tests/testing/test_stream_store.py index 9e827ddf3..c32ece184 100644 --- a/tests/testing/test_stream_store.py +++ b/tests/testing/test_stream_store.py @@ -35,6 +35,7 @@ ReadRecordsRequest, ReadRecordsResponse, ) +from temporalio.client._stream_store import _StoreCaller from temporalio.exceptions import StreamError from temporalio.testing import MemoryStreamStore from tests.helpers.streams import failure_note, run_with_virtual_clock @@ -401,3 +402,19 @@ async def read() -> tuple[float, Any]: assert record.offset > first.last_offset run_with_virtual_clock(script()) + + +async def test_a_dropped_store_call_never_reaches_the_store() -> None: + asked: list[str] = [] + + def store() -> MemoryStreamStore: + asked.append("store") + return MemoryStreamStore() + + def on_task(_task: asyncio.Task[Any]) -> None: + raise asyncio.CancelledError + + request = DescribeStreamRequest(stream_id=_S).SerializeToString() + with pytest.raises(asyncio.CancelledError): + await _StoreCaller(store).call("DescribeStream", request, None, on_task) + assert not asked diff --git a/tests/worker/test_workflow_streams.py b/tests/worker/test_workflow_streams.py new file mode 100644 index 000000000..d1acd976d --- /dev/null +++ b/tests/worker/test_workflow_streams.py @@ -0,0 +1,606 @@ +"""Tests of the Stream calls of one Workflow instance, with no server.""" + +import asyncio +import dataclasses +from collections.abc import Sequence +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from typing import Any + +import pytest +from google.protobuf.message import Message + +import temporalio.api.common.v1 +import temporalio.bridge.worker +import temporalio.common +import temporalio.converter +import temporalio.worker +from temporalio import workflow +from temporalio.api.common.v1 import ActivityType +from temporalio.api.enums.v1 import RetryState, StreamErrorReason, TimeoutType +from temporalio.api.failure.v1 import ( + ActivityFailureInfo, + ApplicationFailureInfo, + Failure, + TimeoutFailureInfo, +) +from temporalio.api.sdk.v1 import ( + CreateStreamRequest, + CreateStreamResponse, + DescribeStreamRequest, + StreamRef, +) +from temporalio.api.sdk.v1.external_storage_pb2 import ExternalStorageReference +from temporalio.api.streamservice.v1 import DescribeStreamResponse +from temporalio.bridge.proto.activity_result import ( + ActivityResolution, +) +from temporalio.bridge.proto.activity_result import Success as ActivitySuccess +from temporalio.bridge.proto.workflow_activation import ( + InitializeWorkflow, + RemoveFromCache, + ResolveActivity, + ResolveStreamAppend, + StreamAppended, + WorkflowActivation, + WorkflowActivationJob, +) +from temporalio.bridge.proto.workflow_commands import ( + AppendToStream, + CompleteWorkflowExecution, + RequestCancelLocalActivity, + WorkflowCommand, +) +from temporalio.bridge.proto.workflow_completion import ( + Success, + WorkflowActivationCompletion, +) +from temporalio.client import StreamConfig, StreamSelectContext, StreamStore +from temporalio.converter import ( + ExternalStorage, + WorkflowSerializationContext, +) +from temporalio.exceptions import ApplicationError, StreamError +from temporalio.nexus.system.stream_service import StreamRef as ModelRef +from temporalio.nexus.system.stream_service.models import ( + CreateStreamResult, + StreamIdConflictPolicy, +) +from temporalio.testing import MemoryStreamStore +from temporalio.worker._workflow import _CommandAwareDataConverter +from temporalio.worker._workflow_instance import ( + _WorkflowInstanceImpl, +) +from tests.helpers.streams import ( + CodecCall, + ContextCodec, + core_failure, + wrapped, +) +from tests.test_extstore import InMemoryTestDriver + + +@workflow.defn +class _StreamWorkflow: + @workflow.run + async def run(self) -> None: + pass + + +def _new_instance( + workflow_class: type, + stream_config: StreamConfig | None = None, + interceptor_classes: Sequence[ + type[temporalio.worker.WorkflowInboundInterceptor] + ] = (), + failure_exception_types: Sequence[type[BaseException]] = (), +) -> _WorkflowInstanceImpl: + defn = workflow._Definition.must_from_class(workflow_class) + start_time = datetime(2026, 1, 1, tzinfo=timezone.utc) + instance = temporalio.worker.UnsandboxedWorkflowRunner().create_instance( + temporalio.worker.WorkflowInstanceDetails( + payload_converter_factory=temporalio.converter.DefaultPayloadConverter, + failure_converter_class=temporalio.converter.DefaultFailureConverter, + interceptor_classes=interceptor_classes, + defn=defn, + info=workflow.Info( + attempt=1, + continued_run_id=None, + cron_schedule=None, + execution_timeout=None, + first_execution_run_id="first-run", + headers={}, + namespace="ns", + original_execution_run_id="run", + parent=None, + root=None, + priority=temporalio.common.Priority(), + raw_memo={}, + retry_policy=None, + run_id="run", + run_timeout=None, + search_attributes={}, + start_time=start_time, + task_queue="tq", + task_timeout=timedelta(seconds=10), + typed_search_attributes=temporalio.common.TypedSearchAttributes.empty, + workflow_id="wf", + workflow_start_time=start_time, + workflow_type=defn.name or "", + ), + randomness_seed=1, + extern_functions={"__temporal_stream_config": lambda: stream_config}, + disable_eager_activity_execution=False, + worker_level_failure_exception_types=failure_exception_types, + patch_activation_callback=None, + last_completion_result=temporalio.api.common.v1.Payloads(), + last_failure=None, + ) + ) + assert isinstance(instance, _WorkflowInstanceImpl) + return instance + + +async def _activate( + instance: _WorkflowInstanceImpl, + *jobs: WorkflowActivationJob, + replaying: bool = False, + flags: Sequence[int] = (), +) -> WorkflowActivationCompletion: + # A Worker runs an activation in another thread too, so that the tasks of the + # Workflow don't run inside the task of the caller. + activation = WorkflowActivation( + run_id="run", jobs=jobs, is_replaying=replaying, available_internal_flags=flags + ) + return await asyncio.to_thread(instance.activate, activation) + + +async def test_stream_payloads_take_the_codec_with_no_context_and_no_storage() -> None: + calls: list[CodecCall] = [] + driver = InMemoryTestDriver() + converter = dataclasses.replace( + temporalio.converter.DataConverter.default, + payload_codec=ContextCodec(calls), + external_storage=ExternalStorage(drivers=[driver], payload_size_threshold=0), + ) + context = WorkflowSerializationContext(namespace="ns", workflow_id="wf") + command_aware = _CommandAwareDataConverter.create( + instance=_new_instance(_StreamWorkflow), + context_free_dc=converter, + workflow_context_dc=converter.with_context(context), + workflow_context=context, + ) + to_payload = temporalio.converter.PayloadConverter.default.to_payload + reference = to_payload(ExternalStorageReference(driver_name=driver.name())) + bodies = [to_payload("plain"), reference] + result = to_payload("result") + + completion = WorkflowActivationCompletion( + successful=Success( + commands=[ + WorkflowCommand( + append_to_stream=AppendToStream( + seq=1, stream=StreamRef(id="s", store="memory"), bodies=bodies + ) + ), + WorkflowCommand( + complete_workflow_execution=CompleteWorkflowExecution(result=result) + ), + ] + ) + ) + await temporalio.bridge.worker.encode_completion( + completion, command_aware, encode_headers=True, storage_concurrency_limit=1 + ) + append, complete = completion.successful.commands + assert list(append.append_to_stream.bodies) == [wrapped(body) for body in bodies] + stored = complete.complete_workflow_execution.result + assert stored.metadata["messageType"] == reference.metadata["messageType"] + assert driver._store_calls == 1 + assert calls == [("encode", None, 1)] * 2 + [("encode", context, 1)] + + failure = Failure( + message="A later attempt has written to the Stream", + application_failure_info=ApplicationFailureInfo( + type="stream_fenced", + details=temporalio.api.common.v1.Payloads(payloads=[wrapped(result)]), + ), + ) + activation = WorkflowActivation( + jobs=[ + WorkflowActivationJob( + resolve_stream_append=ResolveStreamAppend(seq=1, failed=failure) + ), + WorkflowActivationJob( + resolve_activity=ResolveActivity( + seq=1, + result=ActivityResolution(completed=ActivitySuccess(result=stored)), + ) + ), + ] + ) + calls.clear() + await temporalio.bridge.worker.decode_activation( + activation, command_aware, decode_headers=True, storage_concurrency_limit=1 + ) + appended, activity = activation.jobs + assert appended.resolve_stream_append.failed == failure + assert activity.resolve_activity.result.completed.result == result + assert driver._retrieve_calls == 1 + assert calls == [("decode", context, 1)] + + +_REFUSALS = [ + StreamErrorReason.STREAM_ERROR_REASON_NOT_FOUND, + StreamErrorReason.STREAM_ERROR_REASON_ALREADY_EXISTS, + StreamErrorReason.STREAM_ERROR_REASON_EXPIRED, + StreamErrorReason.STREAM_ERROR_REASON_FENCED, +] +_UNAVAILABLE = StreamErrorReason.STREAM_ERROR_REASON_STORE_UNAVAILABLE +_STORE_CALL = "__temporal_stream_store_call" + + +@dataclass +class _Call: + operation: str + stream: str + store: str | None = None + bodies: Sequence[int] = () + cancel: bool = False + refusal: StreamErrorReason.ValueType | None = None + timeout: bool = False + unserved: bool = False + outcome: Any = None + + +class _Script: + phases: list[list[_Call]] = [] + late_cancels = False + intercepted: list[tuple[str, Any]] = [] + local_activities: list[str] = [] + + +@workflow.defn +class _ScriptWorkflow: + @workflow.run + async def run(self) -> None: + streams: dict[str, Any] = {} + for phase in _Script.phases: + tasks = [asyncio.ensure_future(self._call(streams, call)) for call in phase] + # Each task makes its call in its first step, and the task of the call runs + # one step later. + await asyncio.sleep(0) + if _Script.late_cancels: + await asyncio.sleep(0) + for call, task in zip(phase, tasks): + if call.cancel: + task.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + async def _call(self, streams: dict[str, Any], call: _Call) -> None: + try: + if call.operation == "create": + stream = await workflow.create_stream( + id=call.stream, store=call.store, body_type=int + ) + streams[call.stream] = stream + call.outcome = (stream.ref.store, stream.created) + return + stream = streams.get(call.stream) or workflow.get_stream( + ModelRef[int](id=call.stream, store=call.store) + ) + if call.operation == "append": + appended = await stream.append(*call.bodies) + call.outcome = (appended.first_offset, appended.last_offset) + else: + described = await stream.describe() + call.outcome = described.last_offset + except StreamError as err: + call.outcome = err.reason + except asyncio.CancelledError: + call.outcome = "cancelled" + raise + + +class _RecordingInbound(temporalio.worker.WorkflowInboundInterceptor): + def init(self, outbound: temporalio.worker.WorkflowOutboundInterceptor) -> None: + super().init(_RecordingOutbound(outbound)) + + +class _RecordingOutbound(temporalio.worker.WorkflowOutboundInterceptor): + def start_local_activity( + self, input: temporalio.worker.StartLocalActivityInput + ) -> workflow.ActivityHandle[Any]: + _Script.local_activities.append(input.activity) + return super().start_local_activity(input) + + async def start_create_stream(self, request: Any, output_type: Any = None) -> Any: + _Script.intercepted.append(("create", request)) + return await super().start_create_stream(request, output_type) + + async def start_append_records(self, request: Any) -> Any: + _Script.intercepted.append(("append", request)) + return await super().start_append_records(request) + + async def start_describe_stream(self, request: Any) -> Any: + _Script.intercepted.append(("describe", request)) + return await super().start_describe_stream(request) + + +def _resolve_call( + call: _Call, seq: int, *, created: bool = True +) -> WorkflowActivationJob: + converter = temporalio.converter.DefaultPayloadConverter() + job = WorkflowActivationJob() + if call.operation == "append": + job.resolve_stream_append.seq = seq + if call.refusal is not None: + job.resolve_stream_append.failed.CopyFrom(core_failure(call.refusal)) + else: + job.resolve_stream_append.appended.CopyFrom( + StreamAppended( + first_offset=b"first%d" % seq, last_offset=b"last%d" % seq + ) + ) + return job + + job.resolve_activity.seq = seq + job.resolve_activity.is_local = True + result = job.resolve_activity.result + if call.cancel: + result.cancelled.failure.canceled_failure_info.SetInParent() + elif call.refusal is not None: + result.failed.failure.CopyFrom(core_failure(call.refusal)) + elif call.unserved: + result.failed.failure.CopyFrom( + Failure( + message="No Stream Store", + application_failure_info=ApplicationFailureInfo(type="ValueError"), + ) + ) + elif call.timeout: + result.failed.failure.CopyFrom( + Failure( + message="Local Activity timed out", + cause=Failure( + timeout_failure_info=TimeoutFailureInfo( + timeout_type=TimeoutType.TIMEOUT_TYPE_SCHEDULE_TO_CLOSE + ) + ), + activity_failure_info=ActivityFailureInfo( + activity_type=ActivityType(name=_STORE_CALL), + retry_state=RetryState.RETRY_STATE_CANCEL_REQUESTED, + ), + ) + ) + else: + answer: Message = ( + CreateStreamResponse( + ref=StreamRef(id=call.stream, store="b"), created=created + ) + if call.operation == "create" + else DescribeStreamResponse(last_offset=b"last%d" % seq) + ) + result.completed.result.CopyFrom( + converter.to_payload(answer.SerializeToString()) + ) + return job + + +@workflow.defn +class _ReuseStreamWorkflow: + @workflow.run + async def run(self) -> bool | None: + stream = await workflow.create_stream( + id="s", + store="b", + id_conflict_policy=StreamIdConflictPolicy.StreamIdConflictPolicyUseExisting, + ) + return stream.created + + +@pytest.mark.parametrize("intercepted", [False, True]) +async def test_create_reports_an_existing_stream_as_not_created( + intercepted: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + async def existing(_self: Any, request: Any, _output_type: Any = None) -> Any: + answer = asyncio.get_running_loop().create_future() + answer.set_result(CreateStreamResult(ref=request.stream_ref, created=False)) + return answer + + if intercepted: + monkeypatch.setattr(_RecordingOutbound, "start_create_stream", existing) + for replaying in (False, True): + instance = _new_instance( + _ReuseStreamWorkflow, + StreamConfig([MemoryStreamStore(name="b")]), + [_RecordingInbound], + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + replaying=replaying, + ) + if not intercepted: + [schedule] = completion.successful.commands + completion = await _activate( + instance, + _resolve_call( + _Call("create", "s"), + schedule.schedule_local_activity.seq, + created=False, + ), + replaying=replaying, + ) + [command] = completion.successful.commands + assert command.HasField("complete_workflow_execution") + payload = command.complete_workflow_execution.result + assert ( + temporalio.converter.PayloadConverter.default.from_payload(payload) is False + ) + + +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize("late_cancels", [False, True]) +async def test_stream_calls_keep_their_results_when_jobs_arrive_in_reverse_order( + replaying: bool, late_cancels: bool +) -> None: + a, b = MemoryStreamStore(name="a"), MemoryStreamStore(name="b") + selects: list[StreamSelectContext] = [] + + def selector(context: StreamSelectContext) -> StreamStore: + selects.append(context) + return a + + phases = [ + [ + _Call("create", "created"), + _Call("append", "appended", "a", [1, 2]), + _Call("describe", "described", "a"), + ], + [ + _Call("append", "created", bodies=[3]), + _Call("create", "cancelled", cancel=True), + _Call("append", "cancelled-append", "a", [4], cancel=True), + _Call("describe", "refused", "a", refusal=_REFUSALS[0]), + ], + ] + _Script.phases, _Script.intercepted, _Script.local_activities = phases, [], [] + _Script.late_cancels = late_cancels + instance = _new_instance( + _ScriptWorkflow, + StreamConfig([a, b], store_selector=selector), + [_RecordingInbound], + ) + converter = temporalio.converter.DefaultPayloadConverter() + jobs = [WorkflowActivationJob(initialize_workflow=InitializeWorkflow())] + seqs = {"append": 0, "activity": 0} + for phase in phases: + completion = await _activate(instance, *jobs, replaying=replaying) + commands = completion.successful.commands + jobs = [] + cancelled: list[int] = [] + for call, command in zip(phase, commands[: len(phase)], strict=True): + kind = "append" if call.operation == "append" else "activity" + seqs[kind] += 1 + seq = seqs[kind] + if kind == "append": + assert command.append_to_stream.seq == seq + assert command.append_to_stream.stream == StreamRef( + id=call.stream, store="b" if call.stream == "created" else "a" + ) + assert converter.from_payloads(command.append_to_stream.bodies) == list( + call.bodies + ) + else: + activity = command.schedule_local_activity + assert activity.seq == seq and activity.activity_type == _STORE_CALL + operation, store, raw, request_id = converter.from_payloads( + activity.arguments + ) + assert operation == ( + "CreateStream" if call.operation == "create" else "DescribeStream" + ) + assert store == "a" + assert request_id == ( + "first-run" if call.operation == "create" else None + ) + if call.operation == "create": + assert CreateStreamRequest.FromString(raw).stream_ref == StreamRef( + id=call.stream + ) + else: + assert DescribeStreamRequest.FromString(raw).ref == StreamRef( + id=call.stream, store="a" + ) + if call.cancel: + cancelled.append(seq) + jobs.append(_resolve_call(call, seq)) + assert list(commands[len(phase) :]) == [ + WorkflowCommand( + request_cancel_local_activity=RequestCancelLocalActivity(seq=seq) + ) + for seq in cancelled + ] + jobs.reverse() + completion = await _activate(instance, *jobs, replaying=replaying) + [command] = completion.successful.commands + assert command.HasField("complete_workflow_execution") + calls = [call for phase in phases for call in phase] + assert [call.outcome for call in calls] == [ + ("b", True), + (b"first1", b"last1"), + b"last2", + (b"first2", b"last2"), + "cancelled", + "cancelled", + _REFUSALS[0], + ] + assert not instance._streams._appends + assert selects == [ + StreamSelectContext(id=id, namespace="ns") for id in ("created", "cancelled") + ] + assert [operation for operation, _ in _Script.intercepted] == [ + call.operation for call in calls + ] + assert _Script.local_activities == [_STORE_CALL] * 4 + for operation, request in _Script.intercepted: + if operation == "create": + assert request.stream_ref.store is None + assert ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).HasField("successful") + + +@pytest.mark.parametrize("replaying", [False, True]) +@pytest.mark.parametrize( + ("operation", "failure"), + [ + (op, failure) + for op in ("create", "describe") + for failure in ("outage", "timeout", "unserved") + ] + + [(op, "selector") for op in ("create", "append", "describe")], +) +async def test_store_failures_fail_the_task_even_when_workflow_errors_are_enabled( + operation: str, failure: str, replaying: bool +) -> None: + store = MemoryStreamStore(name="a") + + def selector(_context: StreamSelectContext) -> StreamStore: + if failure == "selector": + raise ApplicationError("The selector has no Store for this Stream") + return store + + call = _Call( + operation, + "s", + bodies=[1], + refusal=_UNAVAILABLE if failure == "outage" else None, + timeout=failure == "timeout", + unserved=failure == "unserved", + ) + _Script.phases, _Script.late_cancels = [[call]], False + instance = _new_instance( + _ScriptWorkflow, + StreamConfig([store], store_selector=selector), + failure_exception_types=[Exception], + ) + completion = await _activate( + instance, + WorkflowActivationJob(initialize_workflow=InitializeWorkflow()), + replaying=replaying, + ) + if failure != "selector": + assert len(completion.successful.commands) == 1 + completion = await _activate( + instance, _resolve_call(call, 1), replaying=replaying + ) + assert completion.HasField("failed") + assert ( + await _activate( + instance, WorkflowActivationJob(remove_from_cache=RemoveFromCache()) + ) + ).HasField("successful")